@tradecanvas/core 1.41.0 → 1.42.0

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/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./gpuContexts-BN9YuYEa.cjs`);let t=require(`@tradecanvas/commons`);var n=class{canvas;ctx;dpr=1;constructor(e,t){this.canvas=document.createElement(`canvas`),this.canvas.style.position=`absolute`,this.canvas.style.top=`0`,this.canvas.style.left=`0`,this.canvas.style.zIndex=String(t),this.canvas.style.pointerEvents=`none`,this.ctx=this.canvas.getContext(`2d`),e.appendChild(this.canvas)}resize(e,t){this.dpr=t;let n=Math.round(e.width*t),r=Math.round(e.height*t);(this.canvas.width!==n||this.canvas.height!==r)&&(this.canvas.width=n,this.canvas.height=r),this.canvas.style.width=`${e.width}px`,this.canvas.style.height=`${e.height}px`,this.ctx.setTransform(t,0,0,t,0,0)}clear(){this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.setTransform(this.dpr,0,0,this.dpr,0,0)}getSize(){return{width:this.canvas.width/this.dpr,height:this.canvas.height/this.dpr}}destroy(){this.canvas.width=0,this.canvas.height=0,this.canvas.remove()}},r=class{scene=null;top=null;back=null;gpuCanvas=null;size=null;dpr=1;constructor(e){this.container=e}createLayers(){this.destroy(),this.scene=new n(this.container,0),this.top=new n(this.container,1)}getLayer(e){return(e===t.LayerType.Hover?this.top:this.scene)??void 0}backLayer(){return this.gpuCanvas?(this.back||(this.back=new n(this.container,0),this.container.insertBefore(this.back.canvas,this.gpuCanvas),this.size&&this.back.resize(this.size,this.dpr)),this.back):null}getDpr(){return this.dpr}dropBackLayer(){this.back?.destroy(),this.back=null}attachGpu(e){this.detachGpu(),e.style.position=`absolute`,e.style.top=`0`,e.style.left=`0`,e.style.zIndex=`0`,e.style.pointerEvents=`none`,this.container.insertBefore(e,this.scene?.canvas??null),this.gpuCanvas=e,this.size&&this.sizeGpu(this.size,this.dpr)}detachGpu(){this.dropBackLayer(),this.gpuCanvas&&(this.gpuCanvas.width=0,this.gpuCanvas.height=0,this.gpuCanvas.remove()),this.gpuCanvas=null}resize(e,t){this.size=e,this.dpr=t,this.scene?.resize(e,t),this.top?.resize(e,t),this.back?.resize(e,t),this.sizeGpu(e,t)}destroy(){this.detachGpu(),this.scene?.destroy(),this.top?.destroy(),this.scene=null,this.top=null}sizeGpu(e,t){let n=this.gpuCanvas;if(!n)return;let r=Math.round(e.width*t),i=Math.round(e.height*t);(n.width!==r||n.height!==i)&&(n.width=r,n.height=i),n.style.width=`${e.width}px`,n.style.height=`${e.height}px`}},i=class{animFrameId=0;running=!1;paused=!1;dirtyLayers=new Set;swapLayers=new Set;callback=null;setCallback(e){this.callback=e}markDirty(e){this.dirtyLayers.add(e),this.running&&!this.paused&&!this.animFrameId&&this.scheduleFrame()}markAllDirty(){this.dirtyLayers.add(t.LayerType.Background),this.dirtyLayers.add(t.LayerType.Main),this.dirtyLayers.add(t.LayerType.Overlay),this.dirtyLayers.add(t.LayerType.UI),this.dirtyLayers.add(t.LayerType.Hover),this.running&&!this.paused&&!this.animFrameId&&this.scheduleFrame()}start(){this.running=!0,this.markAllDirty()}pause(){this.paused=!0,this.animFrameId&&=(cancelAnimationFrame(this.animFrameId),0)}resume(){this.paused&&(this.paused=!1,this.running&&this.dirtyLayers.size>0&&!this.animFrameId&&this.scheduleFrame())}isPaused(){return this.paused}stop(){this.running=!1,this.animFrameId&&=(cancelAnimationFrame(this.animFrameId),0)}scheduleFrame(){this.animFrameId=requestAnimationFrame(()=>{if(this.animFrameId=0,!(!this.running||!this.callback)&&this.dirtyLayers.size>0){let e=this.dirtyLayers;this.dirtyLayers=this.swapLayers,this.callback(e),e.clear(),this.swapLayers=e}})}},a=2;function o(e=2){let t=typeof window<`u`&&window.devicePixelRatio||1;return e>0?Math.min(t,e):t}var s=class{observer=null;callback=null;currentDpr=1;resizeScheduled=!1;cachedSize;stopWatchingRatio=null;constructor(e,t=2){this.container=e,this.maxPixelRatio=t,this.currentDpr=o(t),this.cachedSize={width:e.clientWidth,height:e.clientHeight}}getDpr(){return this.currentDpr}getMaxPixelRatio(){return this.maxPixelRatio}setMaxPixelRatio(e){this.maxPixelRatio=e,this.update(!0)}getContainerSize(){return this.cachedSize}readContainerSize(){let e=this.container.clientWidth,t=this.container.clientHeight;return(e!==this.cachedSize.width||t!==this.cachedSize.height)&&(this.cachedSize={width:e,height:t}),this.cachedSize}onResize(e){this.callback=e,this.observer=new ResizeObserver(()=>{this.resizeScheduled||(this.resizeScheduled=!0,requestAnimationFrame(()=>{this.resizeScheduled=!1,this.update(!1)}))}),this.observer.observe(this.container),this.watchRatio()}update(e){let t=o(this.maxPixelRatio),n=this.container.clientWidth,r=this.container.clientHeight,i=t!==this.currentDpr||n!==this.cachedSize.width||r!==this.cachedSize.height;this.currentDpr=t,this.cachedSize={width:n,height:r},(i||e)&&this.callback?.(this.cachedSize,t)}watchRatio(){if(this.stopWatchingRatio?.(),this.stopWatchingRatio=null,typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(resolution: ${window.devicePixelRatio||1}dppx)`);if(!e||typeof e.addEventListener!=`function`)return;let t=()=>{this.update(!1),this.watchRatio()};e.addEventListener(`change`,t),this.stopWatchingRatio=()=>e.removeEventListener(`change`,t)}destroy(){this.observer?.disconnect(),this.observer=null,this.stopWatchingRatio?.(),this.stopWatchingRatio=null,this.callback=null}};function c(e,n,r,i){let a=n.scaleMode??(n.logScale?`logarithmic`:`regular`);return(a===`percentage`||a===`indexedTo100`)&&n.scaleBaseline?(0,t.formatPriceScaleLabel)(e,a,n.scaleBaseline,r,i):n.formatPrice?n.formatPrice(e):(0,t.formatPriceScaleLabel)(e,`regular`,void 0,r,i)}function l(e,t,n){return n!==null&&n>0?Math.max(1,Math.ceil(e/n-1e-9))*n:t===null?e:Math.max(e,10**-t)}var u=1e-9;function d(e,t){for(let n=0;n<t;n++){let t=10**n;if(e.every(e=>Math.abs(e*t-Math.round(e*t))<=u*Math.max(1,Math.abs(e*t))))return n}return t}function f(e,t,n){return Math.floor(t/n+1e-9)-Math.ceil(e/n-1e-9)+1}function p(e,t){if(!t||!(t>0)||e>=1)return e;let n=t;for(;n<e;)n*=2;return n}var m=24,h=200;function g(e){return Math.max(2,Math.min(m,Math.round(e/56)+1))}function _(e){if(!(e>0))return 0;let t=10**Math.floor(Math.log10(e)+1e-9),n=e/t;return(n<2?1:n<5?2:5)*t}function v(e){let t=10**Math.floor(Math.log10(e)+1e-9),n=e/t;return(n<1.5?2:n<3.5?5:10)*t}function y(e,n,r){let i=(0,t.computeTickStep)(e,n,g(r));if(!(i>0)||!(r>0))return i;let a=n-e;for(let e=0;e<8&&i/a*r<30;e++)i=v(i);return i}function b(e,t,n){if(!(n>0)||!(t>=e))return[];let r=[],i=Math.ceil(e/n-1e-9);if(!Number.isFinite(i)||Math.abs(i)>=2**53-1)return[];for(let e=i;e*n<=t+n*1e-9&&e-i<h;e++){let t=e*n;r.push(Math.abs(t)<n*1e-9?0:t)}return r}var x=12,S=14,C=class{locale=`en-US`;reservedPrice=null;precision=null;tick=null;rows=[];setPricePrecision(e){this.precision=e!==null&&Number.isInteger(e)&&e>=0?e:null}setPriceTick(e){this.tick=e!==null&&Number.isFinite(e)&&e>0?e:null}scale(e){let{min:n,max:r}=e.priceRange,i=y(n,r,e.chartRect.height),a=(0,t.autoPricePrecision)(n,r);if(e.priceUnit)return{step:p(i,e.priceUnit),precision:this.precision??a};let o=l(i,this.precision,this.tick);return f(n,r,o)<2?{step:i,precision:Math.max(this.precision??0,a)}:{step:o,precision:this.precision??a}}ticks(e){let{min:t,max:n}=e.priceRange;if(!(n-t>0))return[];let r=e.scaleMode??(e.logScale?`logarithmic`:`regular`),i=e.scaleBaseline;return(r===`percentage`||r===`indexedTo100`)&&i?this.rebasedTicks(e,r,i):r===`logarithmic`&&t>0?this.logTicks(e):b(t,n,this.scale(e).step)}rebasedTicks(e,t,n){let{min:r,max:i}=e.priceRange,a=t===`percentage`?100:0,o=e=>e/n*100-a,s=e=>(e+a)/100*n,c=Math.min(o(r),o(i)),l=Math.max(o(r),o(i));return b(c,l,y(c,l,e.chartRect.height)).map(s).sort((e,t)=>e-t)}logTicks(t){let{min:n,max:r}=t.priceRange,i=Math.log(r/n)/t.chartRect.height,a=e.E(t),o=Math.exp(-i*56),s=[],c=l(_(r*(1-o)),this.precision,this.tick),u=Math.floor(r/c+1e-9)*c,d=null;for(let e=0;e<200&&u>=n&&u>0;e++){let e=a(u);(d===null||Math.abs(e-d)>=30)&&(s.push(u),d=e);let t=u*o;if(c=l(_(Math.min(u-t,t)),this.precision,this.tick),!(c>0))break;let n=Math.round(t/c)*c;n>=u&&(n-=c),u=n}return s.length===0?b(n,r,this.scale(t).step):s.reverse()}labelText(e,t){return c(e,t,this.scale(t).precision,this.locale)}setReservedPriceProvider(e){this.reservedPrice=e}setLocale(e){this.locale=e}labelRows(){return this.rows}render(t,n,r,i=`right`,a=[]){let{chartRect:o,priceRange:s}=n,l=i===`left`,u=l?o.x:o.x+o.width;if(s.max-s.min<=0)return;let f=e.E(n);t.strokeStyle=r.style?.axis.price.line??r.axisLine,t.lineWidth=1,t.globalAlpha=.65,t.beginPath(),t.moveTo(u+.5,o.y),t.lineTo(u+.5,o.y+o.height),t.stroke(),t.globalAlpha=1;let{precision:p}=this.scale(n),m=this.ticks(n),h=n.scaleMode??(n.logScale?`logarithmic`:`regular`),g=h===`regular`||h===`logarithmic`?d(m,p):p,_=`500 ${r.font.sizeSmall}px ${r.font.family}`,v=[],y=l?null:this.reservedPrice?.()??null,b=y===null?null:e.T(y,n);for(let e of m){let t=f(e);b!==null&&Math.abs(t-b)<x||a.some(e=>Math.abs(t-e)<S)||v.push({y:t,text:c(e,n,g,this.locale)})}t.font=_,t.textBaseline=`middle`,t.textAlign=l?`right`:`left`,t.strokeStyle=r.style?.axis.price.line??r.axisLine,t.globalAlpha=.45,t.beginPath();let C=l?-1:1;for(let{y:e}of v)t.moveTo(u+C,e+.5),t.lineTo(u+4*C,e+.5);t.stroke(),t.globalAlpha=1,t.fillStyle=r.style?.axis.price.text??r.axisLabel;for(let{y:e,text:n}of v)t.fillText(n,u+8*C,e);l||(this.rows=v.map(e=>e.y))}};function w(e,t,n,r,i,a){let o=a.shape?.tagRadius,s=typeof o==`number`&&Number.isFinite(o)?Math.max(0,Math.min(o,i/2,r/2)):0;if(!(s>0)){e.fillRect(t,n,r,i);return}e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+r-s,n),e.arcTo(t+r,n,t+r,n+s,s),e.lineTo(t+r,n+i-s),e.arcTo(t+r,n+i,t+r-s,n+i,s),e.lineTo(t+s,n+i),e.arcTo(t,n+i,t,n+i-s,s),e.lineTo(t,n+s),e.arcTo(t,n,t+s,n,s),e.closePath(),e.fill()}function T(e){let t=Math.abs(e);return t>=1e3?1:t>=1?2:t>=.01?4:6}var E=16;function D(e,t,n,r=16){let i=r/2,a=e.map(e=>Math.min(Math.max(e,t+i),n-i));for(let e=1;e<a.length;e++)a[e]=Math.max(a[e],a[e-1]+r);a.length>0&&(a[a.length-1]=Math.min(a[a.length-1],n-i));for(let e=a.length-2;e>=0;e--)a[e]=Math.min(a[e],a[e+1]-r);if(a.length>0&&a[0]<t+i){a[0]=t+i;for(let e=1;e<a.length;e++)a[e]=Math.max(a[e],a[e-1]+r)}return a}function O(e){let t=k(e);if(!t)return`#ffffff`;let[n,r,i]=t;return(.299*n+.587*r+.114*i)/255>.62?`#10131a`:`#ffffff`}function k(e){let t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim());if(t){let e=t[1].length===3?t[1].replace(/./g,e=>e+e):t[1];return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]}let n=/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(e.trim());return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function A(e,t,n=[],r=16){let i=r/2,a=n.filter(e=>e.y+e.half>t.top&&e.y-e.half<t.bottom).sort((e,t)=>e.y-t.y),o=e.filter(e=>e.y>=t.top&&e.y<=t.bottom).sort((e,t)=>e.y-t.y),s=[],c=0,l=t.top;for(let e=0;e<=a.length;e++){e>0&&(l=Math.max(l,a[e-1].y+a[e-1].half));let n=l,u=e===a.length?t.bottom:a[e].y-a[e].half,d=e===a.length?1/0:a[e].y,f=c;for(;c<o.length&&o[c].y<d;)c++;let p=o.slice(f,c);if(p.length===0||u-n<r)continue;let m=D(p.map(e=>e.y),n,u,r);p.forEach((e,t)=>{m[t]-i>=n-.5&&m[t]+i<=u+.5&&s.push({...e,y:m[t]})})}return s}function ee(e,t,n,r,i){if(t.length!==0){e.save(),e.font=`bold ${i.font.sizeSmall}px ${i.font.family}`,e.textBaseline=`middle`,e.textAlign=`left`;for(let a of t){let t=Math.min(e.measureText(a.text).width+10,r-2);e.fillStyle=a.color,w(e,n+1,Math.round(a.y-8),t,16,i),e.fillStyle=O(a.color),e.fillText(a.text,n+5,Math.round(a.y))}e.restore()}}function te(e,t,n,r,i,a){ee(e,A(t,i),n,r,a)}function ne(e){return{plot:e,plotText:null,panes:new Map}}function re(e,t,n,r){let i=e.region(t),a=0;for(;a<n.length&&i.step(n[a]);)a++;let o=new Map;for(let t of r){let n=e.region(t.rect).step(t.background),r=e.region(t.inner),i=0;if(n)for(;i<t.steps.length&&r.step(t.steps[i]);)i++;o.set(t.id,{background:n,text:r,rest:t.steps.slice(i)})}return{plot:n.slice(a),plotText:i,panes:o}}var ie=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,s=r.barWidth,c=s+r.barSpacing,l=-r.offset+r.chartRect.x+s/2,{min:u,max:d}=r.priceRange;if(d-u===0)return;if(e.f(r)){e.p(t,n,r,i.candleUp,i.candleDown);return}let f=e.E(r);e.v(t,r=>{let{body:u,wick:d}=e.h(s,r.ratio),p=(u-d)/2,m=new Path2D,h=new Path2D,g=new Path2D,_=new Path2D;for(let e=a;e<=o&&e<n.length;e++){let t=n[e],i=t.close>=t.open,a=r.left(e*c+l,d),o=r.y(f(t.high)),s=r.y(f(t.low));(i?m:h).rect(a,Math.min(o,s),d,Math.max(Math.abs(s-o),1));let v=r.y(f(t.open)),y=r.y(f(t.close));(i?g:_).rect(a-p,Math.min(v,y),u,Math.max(Math.abs(y-v),d))}t.fillStyle=i.candleUpWick,t.fill(m),t.fillStyle=i.candleDownWick,t.fill(h),t.fillStyle=i.candleUp,t.fill(g),t.fillStyle=i.candleDown,t.fill(_)})}};function ae(e){if(e.style)return e.style.crosshair;let t=()=>({visible:!0,color:e.crosshair,style:`solid`,width:1});return{horizontal:t(),vertical:t(),labelBackground:e.text,labelText:e.background}}var oe=16,se=class{visible=!0;timeframeMs=0;setVisible(e){this.visible=e}isVisible(){return this.visible}setTimeframeMs(e){this.timeframeMs=e}isShown(e){return this.remaining(e)>0}render(e,t,n,r,i=null){let a=this.remaining(r);if(i===null||a<=0)return;let o=i.y+i.height;e.fillStyle=i.color,w(e,i.x,o,i.width,16,n),e.font=`${n.font.sizeSmall}px ${n.font.family}`,e.textBaseline=`middle`,e.textAlign=`left`,e.fillStyle=O(i.color),e.fillText(this.formatRemaining(a),i.x+5,o+16/2)}remaining(e){if(!this.visible||!(this.timeframeMs>0)||e.length===0)return 0;let n=e[e.length-1].time*(0,t.barTimeUnit)(e)+this.timeframeMs-Date.now();return n>0?n:0}formatRemaining(e){let t=Math.ceil(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}:${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`:`${r}:${String(i).padStart(2,`0`)}`}},ce=20,le=8;function ue(e,t,n){if(!e)return null;let r=e.region(t,{text:!1});return n.every(e=>r.step(e))?e:null}function de(e){return e<1?Math.ceil(-Math.log10(e))+1:+(e<10)}var fe=class{layerManager;renderLoop;dprManager;renderCtx=null;sceneLayer;topLayer;gpu=null;lostGpu=null;onGpuLost=null;onGpuRestored=null;onContainerResize=null;constructor(e,t){this.layerManager=new r(e),this.renderLoop=new i,this.dprManager=new s(e,t),this.layerManager.createLayers(),this.cacheLayerRefs(),this.renderLoop.setCallback(e=>this.render(e)),this.dprManager.onResize((e,t)=>{this.layerManager.resize(e,t),this.renderLoop.markAllDirty(),this.onContainerResize?.(e)});let n=this.dprManager.getContainerSize(),a=this.dprManager.getDpr();this.layerManager.resize(n,a)}cacheLayerRefs(){this.sceneLayer=this.layerManager.getLayer(t.LayerType.Main),this.topLayer=this.layerManager.getLayer(t.LayerType.Hover)}setRenderContext(e){this.renderCtx=e}attachGpu(e){this.detachGpu(),this.placeGpu(e),e.onLost(()=>{this.gpu===e&&(this.gpu=null,this.lostGpu=e,this.layerManager.detachGpu(),this.renderLoop.markAllDirty(),this.onGpuLost?.())}),e.onRestored?.(()=>{this.lostGpu===e&&(this.lostGpu=null,this.placeGpu(e),this.onGpuRestored?.())})}placeGpu(e){this.gpu=e,this.layerManager.attachGpu(e.canvas),this.renderLoop.markAllDirty()}detachGpu(){let e=this.gpu??this.lostGpu;e&&(this.gpu=null,this.lostGpu=null,this.layerManager.detachGpu(),e.destroy(),this.renderLoop.markAllDirty())}renderNow(){this.render(new Set([t.LayerType.Main,t.LayerType.Hover]))}getGpu(){return this.gpu}start(){this.renderLoop.start()}stop(){this.renderLoop.stop()}requestRender(e){e===void 0?this.renderLoop.markAllDirty():this.renderLoop.markDirty(e)}render(e){let n=this.renderCtx;if(!n)return;let{chartRect:r}=n.viewport;if(r.width<=0||r.height<=0)return;let i=!1;for(let n of e)if(n!==t.LayerType.Hover){i=!0;break}i&&this.sceneLayer&&this.renderScene(this.sceneLayer,n),this.topLayer&&this.renderTop(this.topLayer,n)}renderScene(e,n){let{viewport:r,theme:i,data:a}=n;e.clear();let o=e.ctx,s=this.gpu,c=!!s&&n.chartRenderer instanceof ie,l=n.chartRenderer?[e=>n.chartRenderer.render(e,a,r,i)]:[],u=[...c?[]:l,...n.compareRenderer?[e=>n.compareRenderer.render(e,a,r,i)]:[],...n.indicatorEngine?.overlayDraws(r,n.leftViewport??void 0)??[]],d=this.paneSteps(n),f={series:!1,volume:!1,background:!1},p=ne(u);s?({drawn:f,plan:p}=this.renderGpu(s,n,o,u,d),c&&!f.series&&(p={...p,plot:[...l,...p.plot]})):this.renderBackground(o,n),o.save(),o.beginPath(),o.rect(r.chartRect.x,r.chartRect.y,r.chartRect.width,r.chartRect.height),o.clip(),s||n.depthHeatmap?.render(o,r,i),f.volume||n.volumeRenderer?.render(o,a,r,i),s||(n.volumeProfile?.render(o,a,r,i),n.marketProfile?.render(o,a,r,i)),p.plotText?.drawText(o);for(let e of p.plot)e(o);n.sessionBreaks?.renderLabels(o,r,i,a),n.periodLevels?.render(o,a,r,i),n.pivotMarkers?.render(o,a,r,i),n.renderOverlayPlugins?.(o,`main`),o.restore(),this.renderPanels(o,n,d,p),n.priceLimits&&this.renderPriceLimits(o,r,i,n.priceLimits),n.tradeZoneManager?.render(o,r,i),n.drawingRenderer?.render(o,r,i),n.tradingRenderer?.render(o,r,i),n.signalMarkerManager?.render(o,r,i),n.alertManager?.render(o,r,i),n.priceLines?.render(o,r,i,a);let m=this.fixedAxisTags(n),h=n.indicatorValueLabels===!1?[]:this.overlayValueTags(n,m);n.priceAxis?.render(o,r,i,`right`,[...m.map(e=>e.y),...h.map(e=>e.y)]),ee(o,h,r.chartRect.x+r.chartRect.width,r.priceAxisWidth??t.PRICE_AXIS_WIDTH,i),n.leftViewport&&(n.leftPriceAxis?.render(o,n.leftViewport,i,`left`),n.indicatorValueLabels!==!1&&this.renderLeftValueLabels(o,n,n.leftViewport)),n.tradingRenderer?.renderAxisBadges(o,r,i),n.priceLines?.renderAxisTags(o,r,i,a),n.currentPriceLine?.render(o,r,i),n.timeAxis?.render(o,r,i,a,n.timeAxisY),this.renderPanelAxes(o,n)}renderGpu(t,n,r,i,a){let{viewport:o,theme:s,data:c}=n,l=this.layerManager.getDpr(),u=this.underSteps(n),d=!!(n.marketProfile?.isVisible()&&n.marketProfile.drawsText()),f=u.length>0&&!d?ue(t.recorder?.(l,r)??null,o.chartRect,u):null,p=u.length>0&&!f,m=t.recorder?.(l,r)??null,h=m?re(m,o.chartRect,i,a):ne(i),g=!!(n.volumeProfile?.isVisible()||n.marketProfile?.isVisible()),_=!!n.gridRenderer?.isVisible()&&!e.s(s),v=n.watermark?.isVisible()||p||_?null:{grid:n.gridRenderer?.isVisible()??!1,marks:n.gridRenderer?.isVisible()?pe(n):void 0,rects:[...n.sessionShading?.rects(c,o,s)??[],...n.sessionBreaks?.lineRects(o,s,c)??[]]},y=n.volumeRenderer?.isVisible()&&!g?{heightRatio:n.volumeRenderer.getHeightRatio()}:null,b=t.render({data:c,viewport:o,theme:s,dpr:l,candles:n.chartRenderer instanceof ie,volume:y,background:v,under:f,recorded:m}),x=b.recorded?h:ne(i),S={drawn:{...b,volume:b.volume||g},plan:x},C=v!==null&&!!b.background,w=f!==null&&b.under?[]:u;return C&&w.length===0?(this.layerManager.dropBackLayer(),S):(this.renderBackCanvas(n,w,!C),S)}underSteps(e){let{viewport:t,theme:n,data:r}=e,i=[];return e.depthHeatmap?.isVisible()&&i.push(r=>e.depthHeatmap.render(r,t,n)),(e.volumeProfile?.isVisible()||e.marketProfile?.isVisible())&&(e.volumeRenderer?.isVisible()&&i.push(i=>e.volumeRenderer.render(i,r,t,n)),e.volumeProfile?.isVisible()&&i.push(i=>e.volumeProfile.render(i,r,t,n)),e.marketProfile?.isVisible()&&i.push(i=>e.marketProfile.render(i,r,t,n))),i}renderBackCanvas(e,t,n){let r=this.layerManager.backLayer();r&&(r.clear(),n&&this.renderBackground(r.ctx,e),t.length>0&&this.inPlot(r.ctx,e.viewport,()=>t.forEach(e=>e(r.ctx))))}renderBackground(e,t){let{viewport:n,theme:r,data:i}=t;t.gridRenderer?.isVisible()&&t.gridRenderer.render(e,n,r,pe(t)),t.sessionShading?.render(e,i,n,r),t.sessionBreaks?.renderLines(e,n,r,i),t.watermark?.render(e,n,r)}inPlot(e,t,n){e.save(),e.beginPath(),e.rect(t.chartRect.x,t.chartRect.y,t.chartRect.width,t.chartRect.height),e.clip(),n(),e.restore()}renderTop(e,t){let{viewport:n,theme:r,data:i}=t;e.clear();let a=e.ctx;t.measureOverlay?.render(a,n,r),t.selectionBoxOverlay?.render(a,n,r),t.crosshairHandler?.render(a,n,r),t.renderOverlayPlugins?.(a,`overlay`),this.renderPanelCrosshair(a,t),t.barCountdown?.render(a,n,r,i,t.currentPriceLine?.getTag()??null),t.crosshairHandler?.renderAxisLabels(a,n,r,i,t.timeAxisY,t.priceAxis?.labelRows(),t.timeAxis?.labelColumns()),t.priceAxisAddButton?.render(a,n,r,t.crosshairHandler?.getPosition()??null),t.chartLegend?.render(a,n,r,i),t.renderOverlayPlugins?.(a,`ui`),this.renderPanelHoverValues(a,t)}paneSteps(e){let{theme:t,panels:n}=e,r=e.indicatorEngine;if(!r||n.length===0)return[];let i=[];for(let e of n){let{rect:n,viewport:a}=e;if(n.width<=0||n.height<=0)continue;let o=e.members?.length?[e.instanceId,...e.members]:[e.instanceId],s=[];for(let e of o){let n=r.isShown(e)?r.getLevels(e):[];n.length>0&&s.push(e=>this.renderLevels(e,n,a,t))}for(let e of o)s.push(t=>r.renderPanel(t,e,a));i.push({id:e.instanceId,rect:n,inner:{x:n.x,y:n.y+ce,width:n.width,height:n.height-ce},background:r=>{r.fillStyle=e.style?.background??t.style?.panes.background??t.background,r.fillRect(n.x,n.y,n.width,n.height)},steps:s})}return i}renderPanels(e,t,n,r){let{theme:i}=t,a=t.indicatorEngine;if(!a||n.length===0)return;let o=`10px ${i.font.family}`,s=this.panelDescriptors(a),c=new Map(t.panels.map(e=>[e.instanceId,e.style]));for(let a of n){let{rect:n,inner:l}=a,u=r.panes.get(a.id),d=c.get(a.id);e.save(),e.beginPath(),e.rect(n.x,n.y,n.width,n.height),e.clip(),u?.background||a.background(e),e.fillStyle=d?.separator??i.style?.panes.separator??i.axisLine,e.fillRect(n.x,n.y,n.width,3),e.fillStyle=i.style?.panes.title??i.textSecondary,e.font=o,e.textBaseline=`top`,e.textAlign=`left`;let f=s.get(a.id);f&&t.paneTitles!==!1&&e.fillText(f.descriptor.name,n.x+6,n.y+6),e.save(),e.beginPath(),e.rect(l.x,l.y,l.width,l.height),e.clip(),u?.text?.drawText(e);for(let t of u?u.rest:a.steps)t(e);e.restore(),e.restore()}}fixedAxisTags(t){let{viewport:n,data:r}=t,{chartRect:i}=n,a=[],o=t.currentPriceLine?.isVisible()&&t.theme.style?.lastPrice.visible!==!1?t.currentPriceLine.getPrice():null;if(o!=null){let s=e.T(o,n);a.push({y:s,half:10}),s>=i.y&&s<=i.y+i.height&&t.barCountdown?.isShown(r)&&a.push({y:s+10+16/2,half:16/2})}for(let i of t.priceLines?.levels(r,n)??[])a.push({y:e.T(i.price,n),half:8});for(let e of t.tradingRenderer?.axisTagYs(n)??[])a.push({y:e,half:9});return a.filter(e=>e.y>=i.y&&e.y<=i.y+i.height)}overlayValueTags(n,r){let i=n.indicatorEngine?.getLatestOverlayValues();if(!i?.length)return[];let{viewport:a}=n,{chartRect:o}=a,s=n.formatPrice??(e=>(0,t.formatPrice)(e,2,n.numberLocale??`en-US`));return A(i.map(t=>({y:e.T(t.value,a),text:s(t.value),color:t.color})),{top:o.y,bottom:o.y+o.height},r)}renderLeftValueLabels(n,r,i){let a=r.indicatorEngine?.getLatestOverlayValues(`left`);if(!a?.length)return;let{chartRect:o}=i,s=r.leftAxisWidth??t.PRICE_AXIS_WIDTH,c=(0,t.autoPricePrecision)(i.priceRange.min,i.priceRange.max),l=r.numberLocale??`en-US`;te(n,a.map(n=>({y:e.T(n.value,i),text:(0,t.formatPrice)(n.value,c,l),color:n.color})),o.x-s,s,{top:o.y,bottom:o.y+o.height},r.theme)}renderLevels(t,n,r,i){if(n.length===0)return;let{chartRect:a}=r;t.save(),t.strokeStyle=i.axisLabel,t.globalAlpha=.45,t.lineWidth=1,t.setLineDash([4,4]),t.beginPath();for(let i of n){let n=Math.round(e.T(i,r))+.5;t.moveTo(a.x,n),t.lineTo(a.x+a.width,n)}t.stroke(),t.restore()}renderPanelAxes(n,r){let{theme:i}=r,a=r.numberLocale??`en-US`,o=`${i.font.sizeSmall}px ${i.font.family}`;for(let s of r.panels){let l=s.viewport,u=s.rect,{min:d,max:f}=l.priceRange;if(f-d<=0||u.height<=0||l.chartRect.height<le)continue;let p=u.x+u.width,m=l.chartRect,h=i.style?.axis.price.line??i.axisLine,g=i.style?.axis.price.text??i.axisLabel;n.strokeStyle=h,n.lineWidth=1,n.beginPath(),n.moveTo(p+.5,u.y),n.lineTo(p+.5,u.y+u.height),n.stroke();let _=y(d,f,m.height),v=de(_);n.font=o,n.textBaseline=`middle`,n.textAlign=`left`;for(let t of b(d,f,_)){let r=e.T(t,l);r<m.y||r>m.y+m.height||(n.strokeStyle=h,n.beginPath(),n.moveTo(p,Math.round(r)+.5),n.lineTo(p+4,Math.round(r)+.5),n.stroke(),n.fillStyle=g,n.fillText(c(t,l,v,a),p+6,r))}let x=r.indicatorValueLabels===!1?null:[s.instanceId,...s.members??[]].flatMap(e=>r.indicatorEngine?.getLatestValues(e)??[]);x?.length&&te(n,x.map(n=>({y:e.T(n.value,l),text:l.scaleMode===`percentage`&&l.scaleBaseline?c(n.value,l,2,a):(0,t.formatPrice)(n.value,T(n.value),a),color:n.color})),p,r.viewport.priceAxisWidth??t.PRICE_AXIS_WIDTH,{top:m.y,bottom:m.y+m.height},i)}}renderPanelCrosshair(n,r){let i=r.crosshairHandler?.getPosition();if(!i||r.panels.length===0)return;let{theme:a}=r;for(let o of r.panels){let s=o.rect;if(i.x<s.x||i.x>s.x+s.width||i.y<s.y||i.y>s.y+s.height)continue;let c=o.viewport;if(c.chartRect.height<le)continue;let l=e.A(i.x,c),u=e.b(Math.max(0,Math.min((r.data?.length??1)-1,Math.round(l))),c),d=ae(a);if(n.save(),n.beginPath(),n.rect(s.x,s.y,s.width,s.height),n.clip(),d.vertical.visible){n.setLineDash((0,t.lineDash)(d.vertical.style,[4,4],d.vertical.width)),n.strokeStyle=d.vertical.color;let r=e.g(n,u,d.vertical.width);n.lineWidth=r.width,n.beginPath(),n.moveTo(r.x,s.y),n.lineTo(r.x,s.y+s.height),n.stroke()}if(d.horizontal.visible){n.setLineDash((0,t.lineDash)(d.horizontal.style,[4,4],d.horizontal.width)),n.strokeStyle=d.horizontal.color;let r=e._(n,i.y,d.horizontal.width);n.lineWidth=r.width,n.beginPath(),n.moveTo(s.x,r.y),n.lineTo(s.x+s.width,r.y),n.stroke()}n.setLineDash([]),n.restore();break}}renderPanelHoverValues(n,r){let i=r.crosshairHandler?.getPosition(),a=r.indicatorEngine;if(!i||r.panels.length===0)return;let{theme:o,viewport:s,data:l}=r,u=r.numberLocale??`en-US`,d=`${o.font.sizeSmall}px ${o.font.family}`,f=a?this.panelDescriptors(a):null;for(let p of r.panels){let m=p.viewport,h=p.rect,{min:g,max:_}=m.priceRange;if(_-g<=0||h.height<=0||m.chartRect.height<le)continue;let v=h.x+h.width,b=de(y(g,_,m.chartRect.height));if(i.x>=h.x&&i.x<=h.x+h.width&&i.y>=h.y&&i.y<=h.y+h.height){let r=c(e.M(i.y,m),m,b,u);n.font=`bold ${o.font.sizeSmall}px ${o.font.family}`;let a=n.measureText(r).width,l=Math.min(a+10,(s.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2),d=ae(o);n.fillStyle=d.labelBackground,w(n,v+1,i.y-9,l,18,o),n.fillStyle=d.labelText,n.textBaseline=`middle`,n.textAlign=`left`,n.fillText(r,v+5,i.y)}if(!a||r.paneTitles===!1||!a.isShown(p.instanceId))continue;let x=Math.max(0,Math.min((l?.length??1)-1,Math.round(e.A(i.x,m)))),S=a.getOutput(p.instanceId),C=S?.series&&x<S.series.length?S.series[x]:null;if(!C)continue;let T=f?.get(p.instanceId),E=T?.descriptor.plots,D=[];if(E)for(let e of E){let t=C[e.key];t!==void 0&&Number.isFinite(t)&&D.push(`${e.title} ${c(t,m,b,u)}`)}else for(let e in C){let t=C[e];t!==void 0&&D.push(`${e}: ${t.toFixed(b)}`)}if(D.length===0)continue;n.font=d;let O=T?n.measureText(T.descriptor.name).width+14:10;n.fillStyle=o.textSecondary,n.textBaseline=`top`,n.textAlign=`left`,n.fillText(D.join(` `),h.x+O,h.y+6)}}panelDescriptors(e){let t=new Map;for(let n of e.getPanelIndicators())t.set(n.instanceId,n);return t}renderPriceLimits(n,r,i,a){let{chartRect:o}=r,s=[{price:a.ceiling,color:a.colors?.ceiling??`#FF00FF`,label:`CE`},{price:a.floor,color:a.colors?.floor??`#00FFFF`,label:`FL`},{price:a.reference,color:a.colors?.reference??`#FFD700`,label:`REF`}],c=`bold 9px ${i.font.family}`,l=`10px ${i.font.family}`;for(let{price:a,color:u,label:d}of s){let s=e.T(a,r);if(s<o.y||s>o.y+o.height)continue;n.setLineDash([8,4]),n.strokeStyle=u,n.lineWidth=1,n.beginPath(),n.moveTo(o.x,Math.round(s)+.5),n.lineTo(o.x+o.width,Math.round(s)+.5),n.stroke(),n.setLineDash([]),n.font=c,n.fillStyle=u,n.textBaseline=`bottom`,n.textAlign=`left`,n.fillText(`${d} ${r.formatPrice?.(a)??a.toFixed(2)}`,o.x+4,s-2);let f=o.x+o.width+1;n.fillStyle=u,w(n,f,s-7,(r.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,14,i),n.fillStyle=`#000`,n.font=l,n.textBaseline=`middle`,n.textAlign=`left`,n.fillText(r.formatPrice?.(a)??a.toFixed(2),f+4,s)}}destroy(){this.renderLoop.stop(),this.detachGpu(),this.dprManager.destroy(),this.layerManager.destroy()}};function pe(e){return{prices:e.priceAxis?.ticks(e.viewport),slots:e.timeAxis?.marks(e.viewport,e.data).map(e=>e.index)}}async function me(t){let n=e.n();if(!n)return{gpu:null,reason:`limit`};let r;try{r=await Promise.resolve().then(()=>require(`./WebGLSeriesRenderer-DaTDdW4O.cjs`))}catch(e){return n(),console.warn(`TradeCanvas: the WebGL renderer failed to load, drawing with Canvas 2D.`,e),{gpu:null,reason:`unsupported`}}let i=r.WebGLSeriesRenderer.create({failIfMajorPerformanceCaveat:t===`auto`,release:n});return i?{gpu:i}:(n(),{gpu:null,reason:`unsupported`})}async function he(e){return(await me(e)).gpu}var ge=.25,_e=.02,ve=t.PHI**-5,ye=.2,be=class{state;priceAxisWidth=t.PRICE_AXIS_WIDTH;stateCache=null;dataLength=0;margins={top:ve,bottom:ve};minBarWidth;maxBarWidth;rightMarginBars;freePan=!0;minVisibleBars=3;minBarUnit=ge;constructor(e,n,r=2,i=30,a=5){this.minBarWidth=r,this.maxBarWidth=i,this.rightMarginBars=a;let o=this.computeChartRect(e,n);this.state={visibleRange:{from:0,to:0},priceRange:{min:0,max:1},barWidth:t.DEFAULT_BAR_WIDTH,barSpacing:t.DEFAULT_BAR_SPACING,offset:0,chartRect:o}}getState(){return this.stateCache||={visibleRange:{...this.state.visibleRange},priceRange:{...this.state.priceRange},barWidth:this.state.barWidth,barSpacing:this.state.barSpacing,offset:this.state.offset,chartRect:{...this.state.chartRect},logScale:this.state.logScale,scaleMode:this.state.scaleMode,scaleBaseline:this.state.scaleBaseline,invertScale:this.state.invertScale,priceAxisWidth:this.state.priceAxisWidth,formatPrice:this.state.formatPrice,numberLocale:this.state.numberLocale,priceUnit:this.state.priceUnit},this.stateCache}invalidate(){this.stateCache=null}setLogScale(e){this.setScaleMode(e?`logarithmic`:`regular`)}isLogScale(){return(this.state.scaleMode??(this.state.logScale?`logarithmic`:`regular`))===`logarithmic`}setScaleMode(e){this.state.scaleMode=e,this.state.logScale=e===`logarithmic`,this.invalidate()}getScaleMode(){return this.state.scaleMode??(this.state.logScale?`logarithmic`:`regular`)}setInvertScale(e){this.state.invertScale=e,this.invalidate()}isInvertScale(){return this.state.invertScale===!0}setNumberLocale(e){this.state.numberLocale=e,this.invalidate()}setPriceFormat(e,t=null){this.state.formatPrice=e??void 0,this.state.priceUnit=t??void 0,this.invalidate()}setScaleBaseline(e){this.state.scaleBaseline=e,this.invalidate()}setRightMargin(e){this.rightMarginBars=e}getRightMargin(){return this.rightMarginBars}setPanLimits(e){e.freePan!==void 0&&(this.freePan=e.freePan),e.minVisibleBars!==void 0&&(this.minVisibleBars=Math.max(1,Math.floor(e.minVisibleBars))),this.clampOffset(),this.updateVisibleRange()}endOffset(){let e=this.state.barWidth+this.state.barSpacing;return this.dataLength*e-this.state.chartRect.width+this.rightMarginBars*e}setPriceAxisWidth(e){this.priceAxisWidth!==e&&(this.priceAxisWidth=e,this.state.priceAxisWidth=e,this.invalidate())}computeChartRect(e,n){return{x:0,y:0,width:Math.max(0,e-this.priceAxisWidth),height:Math.max(0,n-t.TIME_AXIS_HEIGHT)}}resize(e,t){this.state.chartRect=this.computeChartRect(e,t),this.invalidate(),this.clampUnit(),this.clampOffset()}setChartRect(e){this.state.chartRect={x:e.x,y:e.y,width:Math.max(0,e.width),height:Math.max(0,e.height)},this.invalidate(),this.clampUnit(),this.clampOffset(),this.updateVisibleRange()}floorUnit(){return this.minBarWidth+t.DEFAULT_BAR_SPACING}minUnit(){let e=this.floorUnit(),t=this.state.chartRect.width,n=this.dataLength+this.rightMarginBars;return t<=0||n<=0?e:Math.max(this.minBarUnit,Math.min(e,t/n))}setMinBarUnit(e){this.minBarUnit=Number.isFinite(e)?Math.max(_e,Math.min(e,this.floorUnit())):ge,this.clampUnit(),this.clampOffset(),this.updateVisibleRange(),this.invalidate()}getMinBarUnit(){return this.minBarUnit}maxUnit(){return this.maxBarWidth+t.DEFAULT_BAR_SPACING}applyUnit(e){let n=this.floorUnit();if(e>=n)this.state.barWidth=e-t.DEFAULT_BAR_SPACING,this.state.barSpacing=t.DEFAULT_BAR_SPACING;else{let t=this.minBarWidth/n;this.state.barWidth=e*t,this.state.barSpacing=e-this.state.barWidth}this.invalidate()}clampUnit(){let e=this.state.barWidth+this.state.barSpacing,n=(0,t.clamp)(e,this.minUnit(),this.maxUnit());n===e||e<=0||(this.state.offset=this.state.offset/e*n,this.applyUnit(n))}updateData(e,n){let r=this.dataLength===0;if(this.dataLength=e.length,this.dataLength!==0&&(this.clampUnit(),r&&(this.state.offset=this.endOffset()),this.clampOffset(),this.updateVisibleRange(),n)){let{min:n,max:r}=(0,t.computePriceRange)(e,this.state.visibleRange.from,Math.min(this.state.visibleRange.to,this.dataLength-1),0);this.fitToPrices(n,r)}}setScaleMargins(e){let t=e=>Number.isFinite(e)&&e>=0;!t(e.top)||!t(e.bottom)||1-e.top-e.bottom<ye||(this.margins={top:e.top,bottom:e.bottom})}getScaleMargins(){return{...this.margins}}fitToPrices(e,n){this.state.priceRange=(0,t.fitPriceRange)(e,n,this.margins,this.isLogScale()),this.invalidate()}prependBars(e){e===0||!Number.isFinite(e)||(this.dataLength+=e,this.state.offset+=e*(this.state.barWidth+this.state.barSpacing),this.invalidate(),this.updateVisibleRange())}setPriceRange(e,t){this.state.priceRange={min:e,max:t},this.invalidate()}scalePriceRange(e){if(!Number.isFinite(e)||e<=0)return;let{min:t,max:n}=this.state.priceRange,r=(t+n)/2,i=(n-t)/2,a=Math.max(i*e,1e-9);this.state.priceRange={min:r-a,max:r+a},this.invalidate()}scrollBy(e){this.state.offset+=e,this.invalidate(),this.clampOffset(),this.updateVisibleRange()}panPriceRange(e){let t=this.state.chartRect.height;if(t<=0||e===0)return;let{min:n,max:r}=this.state.priceRange,i=(this.state.invertScale?-e:e)/t;if(this.isLogScale()&&n>0&&r>0){let e=Math.log(n),t=Math.log(r),a=(t-e)*i;this.state.priceRange={min:Math.exp(e-a),max:Math.exp(t-a)},this.invalidate();return}let a=(r-n)*i;this.state.priceRange={min:n-a,max:r-a},this.invalidate()}isAtEnd(){let e=this.state.barWidth+this.state.barSpacing;return Math.abs(this.state.offset-this.endOffset())<=e*2}scrollToEnd(){this.state.offset=this.endOffset(),this.invalidate(),this.updateVisibleRange()}zoom(e,n){let r=this.state.barWidth+this.state.barSpacing,i=this.state.barWidth*(1+e),a=(0,t.clamp)(r>=this.floorUnit()&&i>=this.minBarWidth?i+t.DEFAULT_BAR_SPACING:r*(1+e),this.minUnit(),this.maxUnit());if(a===r)return;let o=this.isAtEnd(),s=(this.state.offset+n)/r;this.applyUnit(a),this.state.offset=o?this.endOffset():s*a-n,this.invalidate(),this.clampOffset(),this.updateVisibleRange()}zoomToBarRange(e,n){let r=this.state.chartRect.width;if(r<=0||!Number.isFinite(e)||!Number.isFinite(n)||n<e)return;let i=(0,t.clamp)(r/(n-e+1),this.minUnit(),this.maxUnit());this.applyUnit(i),this.state.offset=(e+n+1)/2*i-r/2,this.invalidate(),this.clampOffset(),this.updateVisibleRange()}clampOffset(){if(this.state.chartRect.width<=0)return;let e=this.state.barWidth+this.state.barSpacing,n=this.state.chartRect.width,r=this.endOffset(),i,a;if(this.freePan&&this.dataLength>0){let t=Math.min(this.minVisibleBars,this.dataLength);i=t*e-n,a=(this.dataLength-t)*e,i=Math.min(i,r),a=Math.max(a,r)}else if(r>0)i=-(n*.5),a=r;else{let e=n*.5;i=r-e,a=r+e}this.state.offset=(0,t.clamp)(this.state.offset,i,a),this.invalidate()}updateVisibleRange(){let e=this.state.barWidth+this.state.barSpacing;if(e<=0||this.state.chartRect.width<=0)return;let t=Math.floor(this.state.offset/e),n=Math.ceil(this.state.chartRect.width/e)+1,r=Math.min(t+n,this.dataLength-1);this.state.visibleRange={from:Math.max(0,t),to:Math.max(0,r)},this.invalidate()}};function xe(e,n){return(0,t.sliceVisibleData)(e,n.visibleRange.from,n.visibleRange.to)}var Se=[`1D`,`5D`,`1M`,`3M`,`6M`,`YTD`,`1Y`,`5Y`,`All`],Ce=864e5,we=6e4,Te={"1M":1,"3M":3,"6M":6,"1Y":12,"5Y":60};function Ee(e,t){let n=new Date(e),r=n.getUTCFullYear(),i=n.getUTCMonth()+t,a=new Date(Date.UTC(r,i+1,0)).getUTCDate();return Date.UTC(r,i,Math.min(n.getUTCDate(),a),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds())}function De(e,n,r=0){if(e===`All`)return null;if(e===`1D`)return n-Ce;if(e===`5D`)return n-5*Ce;let i=n+(0,t.offsetAt)(r,n)*we;return e===`YTD`?(0,t.wallToUtc)(Date.UTC(new Date(i).getUTCFullYear(),0,1),r):(0,t.wallToUtc)(Ee(i,-(Te[e]??0)),r)}function Oe(e,t,n){if(t>=e){let t=Array(Math.max(0,e));for(let n=0;n<e;n++)t[n]=n;return t}if(t<=2)return e>=2?[0,e-1]:e===1?[0]:[];let r=[0],i=(e-2)/(t-2),a=0;for(let o=0;o<t-2;o++){let t=Math.floor((o+1)*i)+1,s=Math.floor((o+2)*i)+1;s>e&&(s=e);let c=0,l=0,u=0;for(let e=t;e<s;e++)c+=e,l+=n(e),u++;if(u>0)c/=u,l/=u;else{let r=Math.min(t,e-1);c=r,l=n(r)}let d=Math.floor(o*i)+1,f=Math.floor((o+1)*i)+1,p=n(a),m=-1,h=d;for(let e=d;e<f;e++){let t=Math.abs((a-c)*(n(e)-p)-(a-e)*(l-p));t>m&&(m=t,h=e)}r.push(h),a=h}return r.push(e-1),r}var ke=64;function Ae(e,t,n,r,i){let a=Math.max(0,e),o=Math.min(t,n-1);if(o<a)return[];let s=o-a+1,c=Math.max(ke,Math.ceil(r*2));if(s<=c){let e=Array(s);for(let t=0;t<s;t++)e[t]=a+t;return e}let l=Oe(s,c,e=>i(a+e));for(let e=0;e<l.length;e++)l[e]+=a;return l}var je=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange;if(a>o||n.length===0)return;let s=r.barWidth+r.barSpacing,c=-r.offset+r.chartRect.x+r.barWidth/2,{min:l,max:u}=r.priceRange;if(u-l===0)return;let d=e.E(r);t.beginPath(),t.strokeStyle=i.lineColor,t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`round`;let f=Ae(a,o,n.length,r.chartRect.width,e=>n[e].close),p=!1;for(let e of f){let r=e*s+c,i=d(n[e].close);p?t.lineTo(r,i):(t.moveTo(r,i),p=!0)}t.stroke()}},Me=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange;if(a>o||n.length===0)return;let s=r.barWidth+r.barSpacing,c=-r.offset+r.chartRect.x+r.barWidth/2,{min:l,max:u}=r.priceRange;if(u-l===0)return;let d=e.E(r),f=d(l),p=Ae(a,o,n.length,r.chartRect.width,e=>n[e].close);if(p.length===0)return;let m=p[0],h=m*s+c,g=d(n[m].close),_=t.createLinearGradient(0,d(u),0,f);_.addColorStop(0,i.areaTopColor),_.addColorStop(1,i.areaBottomColor),t.beginPath(),t.moveTo(h,f),t.lineTo(h,g);let v=h;for(let e=1;e<p.length;e++){let r=p[e];v=r*s+c,t.lineTo(v,d(n[r].close))}t.lineTo(v,f),t.closePath(),t.fillStyle=_,t.fill(),t.beginPath(),t.strokeStyle=i.lineColor,t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`round`,t.moveTo(h,g);for(let e=1;e<p.length;e++){let r=p[e];t.lineTo(r*s+c,d(n[r].close))}t.stroke()}},Ne=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,s=r.barWidth,c=s+r.barSpacing,l=-r.offset+r.chartRect.x+s/2,{min:u,max:d}=r.priceRange;if(d-u===0)return;if(e.f(r)){e.p(t,n,r,i.candleUp,i.candleDown);return}let f=e.E(r);e.v(t,r=>{let{body:u,wick:d}=e.h(s,r.ratio),p=Math.max((u-d)/2,d),m=new Path2D,h=new Path2D;for(let e=a;e<=o&&e<n.length;e++){let t=n[e],i=t.close>=t.open?m:h,a=r.left(e*c+l,d),o=r.y(f(t.high)),s=r.y(f(t.low));i.rect(a,Math.min(o,s),d,Math.max(Math.abs(s-o),d)),i.rect(a-p,r.y(f(t.open))-Math.floor(d/2),p,d),i.rect(a+d,r.y(f(t.close))-Math.floor(d/2),p,d)}t.fillStyle=i.candleUp,t.fill(m),t.fillStyle=i.candleDown,t.fill(h)})}},Pe=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,s=r.barWidth,c=s+r.barSpacing,l=-r.offset+r.chartRect.x+s/2,{min:u,max:d}=r.priceRange;if(d-u===0)return;if(e.f(r)){e.p(t,n,r,i.candleUp,i.candleDown);return}let f=e.E(r);e.v(t,r=>{let{body:u,wick:d}=e.h(s,r.ratio),p=(u-d)/2,m={up:new Path2D,down:new Path2D},h={up:new Path2D,down:new Path2D},g={up:new Path2D,down:new Path2D};for(let e=a;e<=o&&e<n.length;e++){let t=n[e],i=e===0||t.close>=n[e-1].close?`up`:`down`,a=r.left(e*c+l,d),o=a-p,s=r.y(f(t.high)),_=r.y(f(t.low)),v=r.y(f(t.open)),y=r.y(f(t.close)),b=Math.min(v,y),x=Math.max(Math.abs(y-v),d);t.close>=t.open?(b>s&&m[i].rect(a,s,d,b-s),_>b+x&&m[i].rect(a,b+x,d,_-b-x),g[i].rect(o+d/2,b+d/2,Math.max(u-d,0),Math.max(x-d,0))):(m[i].rect(a,Math.min(s,_),d,Math.max(Math.abs(_-s),1)),h[i].rect(o,b,u,x))}for(let e of[`up`,`down`]){let n=e===`up`?i.candleUp:i.candleDown;t.fillStyle=n,t.fill(m[e]),t.fill(h[e]),t.strokeStyle=n,t.lineWidth=d,t.stroke(g[e])}})}},Fe=32/255,Ie=class{baselinePrice=null;setBaseline(e){this.baselinePrice=e}render(t,n,r,i){let{from:a,to:o}=r.visibleRange;if(a>o||n.length===0)return;let s=r.barWidth,c=s/2,l=s+r.barSpacing,u=-r.offset+r.chartRect.x+c,{min:d,max:f}=r.priceRange;if(f-d===0)return;let p=e=>e*l+u,m=e.E(r),h=m(this.baselinePrice??this.computeBaseline(n,a,o)),{chartRect:g}=r,_=[],v=[];for(let e=a;e<=o&&e<n.length;e++)_.push(p(e)),v.push(m(n[e].close));if(_.length<2)return;let y=_.length-1;t.save();let b=m(f),x=m(d),S=new Path2D;S.rect(g.x,Math.min(h,b),g.width,Math.abs(b-h)),t.clip(S);let C=new Path2D;C.moveTo(_[0],h);for(let e=0;e<=y;e++)C.lineTo(_[e],v[e]);C.lineTo(_[y],h),C.closePath(),t.globalAlpha*=Fe,t.fillStyle=i.candleUp,t.fill(C),t.restore(),t.save();let w=new Path2D;w.rect(g.x,Math.min(h,x),g.width,Math.abs(x-h)),t.clip(w);let T=new Path2D;T.moveTo(_[0],h);for(let e=0;e<=y;e++)T.lineTo(_[e],v[e]);T.lineTo(_[y],h),T.closePath(),t.globalAlpha*=Fe,t.fillStyle=i.candleDown,t.fill(T),t.restore();let E=new Path2D,D=new Path2D,O=null;for(let e=1;e<=y;e++){let t=r.invertScale?v[e]>=h:v[e]<=h,n=t?E:D;t!==O&&n.moveTo(_[e-1],v[e-1]),O=t,n.lineTo(_[e],v[e])}t.save(),t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`round`,t.strokeStyle=i.candleUp,t.stroke(E),t.strokeStyle=i.candleDown,t.stroke(D),t.restore(),t.setLineDash([6,4]),t.strokeStyle=i.textSecondary,t.lineWidth=1;let k=new Path2D;k.moveTo(g.x,h),k.lineTo(g.x+g.width,h),t.stroke(k),t.setLineDash([])}computeBaseline(e,t,n){let r=0,i=0;for(let a=t;a<=n&&a<e.length;a++)r+=e[a].close,i++;return i>0?r/i:0}},Le=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,s=r.barWidth,c=s/2,l=s+r.barSpacing,u=-r.offset+r.chartRect.x+c,{min:d,max:f}=r.priceRange;if(f-d===0)return;let p=e=>e*l+u,m=e.E(r),h=new Path2D,g=new Path2D,_=new Path2D,v=new Path2D;for(let e=a;e<=o&&e<n.length;e++){let t=n[e],r=p(e),i=t.close>=t.open,a=m(Math.max(t.open,t.close)),o=m(Math.min(t.open,t.close)),l=Math.min(a,o),u=Math.max(Math.abs(o-a),1),d=r-c;i?(h.rect(d,l,s,u),_.rect(d,l,s,u)):(g.rect(d,l,s,u),v.rect(d,l,s,u))}t.fillStyle=i.candleUp,t.fill(h),t.fillStyle=i.candleDown,t.fill(g),t.lineWidth=1,t.strokeStyle=i.candleUp,t.stroke(_),t.strokeStyle=i.candleDown,t.stroke(v)}},Re=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,s=r.barWidth,c=s/2,l=s+r.barSpacing,u=-r.offset+r.chartRect.x+c,{min:d,max:f}=r.priceRange;if(f-d===0)return;let p=e=>e*l+u,m=e.E(r),h=new Path2D,g=new Path2D;for(let e=a;e<=o&&e<n.length;e++){let t=n[e],r=p(e),i=t.close>=t.open,a=m(t.high),s=m(t.low),c=i?s:a,l=i?h:g;l.moveTo(r,i?a:s),l.lineTo(r,c),e<o&&e+1<n.length&&l.lineTo(p(e+1),c)}t.save(),t.lineJoin=`round`,t.strokeStyle=i.candleUp,t.lineWidth=3,t.stroke(h),t.strokeStyle=i.candleDown,t.lineWidth=1,t.stroke(g),t.restore()}},ze=class{boxSize=1;setBoxSize(e){this.boxSize=e}render(t,n,r,i){let{from:a,to:o}=r.visibleRange,s=r.barWidth,c=s/2,l=s+r.barSpacing,u=-r.offset+r.chartRect.x+c,{min:d,max:f}=r.priceRange,p=f-d;if(p===0||!(this.boxSize>0))return;let m=r.chartRect.height/p,h=e=>e*l+u,g=e.E(r),_=Math.abs(this.boxSize*m),v=Math.min(c*.8,_*.8)*.5,y=new Path2D,b=new Path2D,x=new Path2D;for(let e=a;e<=o&&e<n.length;e++){let t=n[e],r=h(e),i=t.close>=t.open,a=t.high,o=t.low,s=Math.max(1,Math.round((a-o)/this.boxSize)),c=Math.max(0,Math.floor((d-o)/this.boxSize)-1),l=Math.min(s-1,Math.ceil((f-o)/this.boxSize)),u=Math.max(1,Math.ceil(1/_));for(let e=c;e<=l;e+=u){let t=g(o+(e+.5)*this.boxSize);i?(y.moveTo(r-v,t-v),y.lineTo(r+v,t+v),b.moveTo(r+v,t-v),b.lineTo(r-v,t+v)):(x.moveTo(r+v,t),x.arc(r,t,v,0,Math.PI*2))}}t.lineWidth=1.5,t.strokeStyle=i.candleUp,t.stroke(y),t.stroke(b),t.strokeStyle=i.candleDown,t.stroke(x)}},Be=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,{min:s,max:c}=r.priceRange;if(c-s===0||a>o||n.length===0)return;if(e.f(r)){e.p(t,n,r,i.candleUp,i.candleDown);return}let l=r.barWidth+r.barSpacing,u=-r.offset+r.chartRect.x+r.barWidth/2,d=r.barWidth,f=0;for(let e=a;e<=o&&e<n.length;e++)n[e].volume>f&&(f=n[e].volume);f===0&&(f=1);let p=e=>e*l+u,m=e.E(r);e.v(t,r=>{let{wick:s}=e.h(d,r.ratio),c=new Path2D,l=new Path2D,u=new Path2D,h=new Path2D;for(let t=a;t<=o&&t<n.length;t++){let i=n[t],a=i.close>=i.open,o=r.left(p(t),s),g=r.y(m(i.high)),_=r.y(m(i.low));(a?c:l).rect(o,Math.min(g,_),s,Math.max(Math.abs(_-g),1));let{body:v}=e.h(d*Math.max(.2,i.volume/f),r.ratio),y=r.y(m(i.open)),b=r.y(m(i.close));(a?u:h).rect(o-(v-s)/2,Math.min(y,b),v,Math.max(Math.abs(b-y),s))}t.fillStyle=i.candleUpWick,t.fill(c),t.fillStyle=i.candleDownWick,t.fill(l),t.fillStyle=i.candleUp,t.fill(u),t.fillStyle=i.candleDown,t.fill(h)})}},Ve=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,{min:s,max:c}=r.priceRange;if(c-s===0||a>o||n.length===0)return;let l=r.barWidth+r.barSpacing,u=-r.offset+r.chartRect.x+r.barWidth/2,d=r.barWidth,f=0;for(let e=a;e<=o&&e<n.length;e++)n[e].volume>f&&(f=n[e].volume);f===0&&(f=1);let p=new Path2D,m=new Path2D,h=new Path2D,g=new Path2D,_=e=>e*l+u,v=e.E(r);for(let e=a;e<=o&&e<n.length;e++){let t=n[e],r=e>0?n[e-1]:t,i=_(e),a=v(t.high),o=v(t.low),s=t.close>=r.close,c=d*Math.max(.15,t.volume/f),l=c/2,u=Math.min(a,o),y=Math.max(Math.abs(o-a),1),b=s?p:m,x=s?h:g;b.rect(i-l,u,c,y),x.rect(i-l,u,c,y)}t.fillStyle=He(i.candleUp,.55),t.fill(p),t.fillStyle=He(i.candleDown,.55),t.fill(m),t.lineWidth=1,t.strokeStyle=i.candleUpWick,t.stroke(h),t.strokeStyle=i.candleDownWick,t.stroke(g)}};function He(e,t){if(e.startsWith(`#`)){let n=Math.round(Math.max(0,Math.min(1,t))*255).toString(16).padStart(2,`0`);if(e.length===7)return`${e}${n}`;if(e.length===9)return`${e.slice(0,7)}${n}`}return e}var Ue=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange;if(a>o||n.length===0)return;let{min:s,max:c}=r.priceRange;if(c-s===0)return;let l=r.barWidth+r.barSpacing,u=-r.offset+r.chartRect.x+r.barWidth/2,d=e=>e*l+u,f=e.E(r),p=[],m=[];for(let e=a;e<=o&&e<n.length;e++){let t=d(e);p.push({x:t,y:f(n[e].high)}),m.push({x:t,y:f(n[e].low)})}if(p.length===0)return;let h=t.createLinearGradient(0,f(c),0,f(s));h.addColorStop(0,i.areaTopColor),h.addColorStop(1,i.areaBottomColor),t.beginPath(),t.moveTo(p[0].x,p[0].y);for(let e=1;e<p.length;e++)t.lineTo(p[e].x,p[e].y);for(let e=m.length-1;e>=0;e--)t.lineTo(m[e].x,m[e].y);t.closePath(),t.fillStyle=h,t.fill(),t.beginPath(),t.strokeStyle=i.lineColor,t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`round`;for(let e=a;e<=o&&e<n.length;e++){let r=d(e),i=f(n[e].close);e===a?t.moveTo(r,i):t.lineTo(r,i)}t.stroke()}},We=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange;if(a>o||n.length===0)return;let{min:s,max:c}=r.priceRange;if(c-s===0)return;let l=r.barWidth+r.barSpacing,u=-r.offset+r.chartRect.x+r.barWidth/2,d=e=>e*l+u,f=e.E(r);t.beginPath(),t.strokeStyle=i.lineColor,t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`miter`;let p=0;for(let e=a;e<=o&&e<n.length;e++){let r=d(e),i=f(n[e].close);e===a?t.moveTo(r,i):(t.lineTo(r,p),t.lineTo(r,i)),p=i}t.stroke()}},Ge=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange;if(a>o||n.length===0)return;let{min:s,max:c}=r.priceRange;if(c-s===0)return;let l=r.barWidth+r.barSpacing,u=-r.offset+r.chartRect.x+r.barWidth/2,d=e=>e*l+u,f=e.E(r);t.beginPath(),t.strokeStyle=i.lineColor,t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`round`;let p=[];for(let e=a;e<=o&&e<n.length;e++){let r=d(e),i=f(n[e].close);p.push({x:r,y:i}),e===a?t.moveTo(r,i):t.lineTo(r,i)}t.stroke();let m=Math.max(2,Math.min(4,r.barWidth*.3));if(l<m*2)return;let h=new Path2D;for(let{x:e,y:t}of p)h.moveTo(e+m,t),h.arc(e,t,m,0,Math.PI*2);t.fillStyle=i.lineColor,t.fill(h),t.strokeStyle=i.background,t.lineWidth=1,t.stroke(h)}},Ke=28,qe=3,Je=class{priceText=null;setPriceText(e){this.priceText=e}render(n,r,i,a){let{from:o,to:s}=i.visibleRange,{min:c,max:l}=i.priceRange;if(l===c)return;if(e.f(i)){e.p(n,r,i,a.candleUp,a.candleDown);return}let u=i.barWidth+i.barSpacing,d=-i.offset+i.chartRect.x+i.barWidth/2,f=e.E(i),p=Math.max(1,Math.round(i.barWidth*.6)),m=i.barWidth>=Ke,h=(0,t.autoPricePrecision)(c,l),g=e=>i.formatPrice?.(e)??this.priceText?.(e)??(0,t.formatPrice)(e,h);m&&(n.font=`${a.font.sizeSmall}px ${a.font.family}`,n.textAlign=`center`);for(let e=Math.max(0,o);e<=s&&e<r.length;e++){let t=r[e],i=e*u+d,o=Math.min(f(t.high),f(t.low)),s=Math.max(f(t.high),f(t.low));if(n.fillStyle=t.close>=t.open?a.candleUp:a.candleDown,n.fillRect(Math.round(i-p/2),o,p,Math.max(1,s-o)),!m)continue;let c=f(t.high)<=f(t.low);n.textBaseline=`bottom`,n.fillText(g(c?t.high:t.low),i,o-qe),n.textBaseline=`top`,n.fillText(g(c?t.low:t.high),i,s+qe)}}},Ye=t.PHI**-4.5,Xe=class{visible=!0;heightRatio=Ye;setVisible(e){this.visible=e}isVisible(){return this.visible}setHeightRatio(e){this.heightRatio=Math.max(.05,Math.min(.5,e))}getHeightRatio(){return this.heightRatio}render(n,r,i,a){if(!this.visible||r.length===0)return;let{from:o,to:s}=i.visibleRange,{chartRect:c}=i,l=i.barWidth,u=l+i.barSpacing,d=-i.offset+c.x+l/2,f=0;for(let e=o;e<=s&&e<r.length;e++)r[e].volume>f&&(f=r[e].volume);if(f===0)return;let p=c.y+c.height,m=c.height*this.heightRatio/f;e.v(n,c=>{let f=new Path2D,h=new Path2D,g=c.y(p),_=(e,t,n,r)=>{let i=c.y(p-r*m);g-i>=1&&e.rect(t,i,n,g-i)};if(e.f(i))e.d(r,o,s,e=>e*u+d,e=>{let t=c.x(e.x);_(e.close>=e.open?f:h,t,Math.max(1,c.x(e.x+1)-t),e.volume)});else{let{body:t,wick:n}=e.h(l,c.ratio),i=(t-n)/2;for(let e=o;e<=s&&e<r.length;e++){let a=r[e];_(a.close>=a.open?f:h,c.left(e*u+d,n)-i,t,a.volume)}}let v=(0,t.resolveVolumeColors)(a);n.fillStyle=v.up,n.fill(f),n.fillStyle=v.down,n.fill(h)})}},Ze=class{visible=!1;buckets=48;widthRatio=.18;opacity=.32;highlightPoC=!0;setVisible(e){this.visible=e}isVisible(){return this.visible}setBuckets(e){this.buckets=Math.max(8,Math.min(200,Math.floor(e)))}setWidthRatio(e){this.widthRatio=Math.max(.05,Math.min(.5,e))}setOpacity(e){this.opacity=Math.max(.05,Math.min(1,e))}setHighlightPoC(e){this.highlightPoC=e}render(t,n,r,i){if(!this.visible||n.length===0)return;let{from:a,to:o}=r.visibleRange,{chartRect:s,priceRange:c}=r,l=c.max-c.min;if(l<=0)return;let u=new Float64Array(this.buckets),d=new Float64Array(this.buckets),f=new Float64Array(this.buckets);for(let e=a;e<=o&&e<n.length;e++){let t=n[e];if(t.volume<=0)continue;let r=Math.max(t.low,c.min),i=Math.min(t.high,c.max);if(i<=r)continue;let a=(r-c.min)/l,o=(i-c.min)/l,s=Math.max(0,Math.floor(a*this.buckets)),p=Math.min(this.buckets-1,Math.floor(o*this.buckets)),m=Math.max(1,p-s+1),h=t.volume/m,g=t.close>=t.open;for(let e=s;e<=p;e++)u[e]+=h,g?d[e]+=h:f[e]+=h}let p=0,m=-1;for(let e=0;e<u.length;e++)u[e]>p&&(p=u[e],m=e);if(p===0)return;let h=s.width*this.widthRatio,g=s.x+s.width,_=e.E(r),v=1/p;t.save(),t.globalAlpha=this.opacity;for(let n=0;n<this.buckets;n++){let a=u[n];if(a===0)continue;let o=e.w(n,this.buckets,r,_),c=a*v*h,l=d[n]*v*h,p=f[n]*v*h;l>0&&(t.fillStyle=i.candleUp,t.fillRect(g-l,o.top+.5,l,o.height-1)),p>0&&(t.fillStyle=i.candleDown,t.fillRect(g-c,o.top+.5,p,o.height-1)),this.highlightPoC&&n===m&&(t.globalAlpha=1,t.strokeStyle=i.crosshair,t.lineWidth=1,t.setLineDash([3,2]),t.beginPath(),t.moveTo(s.x,o.mid+.5),t.lineTo(g-c-2,o.mid+.5),t.stroke(),t.setLineDash([]),t.globalAlpha=this.opacity)}t.restore()}};function Qe(e,t){return e<0?0:e>t?t:e}function $e(e,t,n,r={}){let i=Math.max(4,Math.min(500,Math.floor(r.buckets??48))),a=n-t;if(a<=0||e.length===0)return null;let o=a/i,s=new Float64Array(i);for(let r of e){let e=Math.min(r.low,r.high),a=Math.max(r.low,r.high);if(a<t||e>n)continue;let c=Qe(Math.floor((e-t)/o),i-1),l=Qe(Math.floor((a-t)/o),i-1);for(let e=c;e<=l;e++)s[e]+=1}let c=0,l=0,u=0;for(let e=0;e<i;e++)u+=s[e],s[e]>l&&(l=s[e],c=e);if(u===0)return null;let d=u*(r.valueAreaPct??.7),f=c,p=c,m=s[c];for(;m<d&&(f>0||p<i-1);){let e=f>0?s[f-1]:-1;(p<i-1?s[p+1]:-1)>=e?(p+=1,m+=s[p]):(--f,m+=s[f])}let h=[];for(let e=0;e<i;e++){let n=t+e*o;h.push({low:n,high:n+o,mid:n+o/2,count:s[e]})}return{buckets:h,pocIndex:c,maxCount:l,totalCount:u,valueAreaLow:t+f*o,valueAreaHigh:t+(p+1)*o}}function et(e){let t=(e%52+52)%52;return t<26?String.fromCharCode(65+t):String.fromCharCode(97+t-26)}function tt(e,t,n,r=48){let i=Math.max(4,Math.min(500,Math.floor(r))),a=n-t,o=Array.from({length:i},()=>[]);if(a<=0)return o;let s=a/i;return e.forEach((e,r)=>{let a=Math.min(e.low,e.high),c=Math.max(e.low,e.high);if(c<t||a>n)return;let l=Math.max(0,Math.min(i-1,Math.floor((a-t)/s))),u=Math.max(0,Math.min(i-1,Math.floor((c-t)/s)));for(let e=l;e<=u;e++)o[e].push(r)}),o}function nt(e,n,r,i={}){if(e.length===0||r-n<=0)return[];let a=[],o=0,s=(0,t.timeframeBucketStart)(e[0].time,`1d`),c=(t,o,s)=>{let c=$e(e.slice(t,o+1),n,r,i);c&&a.push({startIndex:t,endIndex:o,startTime:s,profile:c})};for(let n=1;n<e.length;n++){let r=(0,t.timeframeBucketStart)(e[n].time,`1d`);r!==s&&(c(o,n-1,s),o=n,s=r)}return c(o,e.length-1,s),a}var rt=class{visible=!1;buckets=48;widthRatio=.18;opacity=.32;valueAreaPct=.7;highlightPoC=!0;showStats=!0;splitBySession=!1;letters=!1;lastStats=null;setVisible(e){this.visible=e,e||(this.lastStats=null)}isVisible(){return this.visible}setBuckets(e){this.buckets=Math.max(8,Math.min(200,Math.floor(e)))}setWidthRatio(e){this.widthRatio=Math.max(.05,Math.min(.5,e))}setOpacity(e){this.opacity=Math.max(.05,Math.min(1,e))}setValueAreaPct(e){this.valueAreaPct=Math.max(.3,Math.min(.95,e))}setHighlightPoC(e){this.highlightPoC=e}setShowStats(e){this.showStats=e}setSplitBySession(e){this.splitBySession=e}isSplitBySession(){return this.splitBySession}setLetters(e){this.letters=e}drawsText(){return this.splitBySession?this.letters:this.showStats}getStats(){return this.lastStats}render(t,n,r,i){if(!this.visible||n.length===0)return;let{from:a,to:o}=r.visibleRange,{chartRect:s,priceRange:c}=r,l=Math.max(0,a),u=Math.min(o,n.length-1);if(u<l)return;let d=n.slice(l,u+1);if(this.splitBySession){this.lastStats=null,this.renderSplit(t,d,l,r,i);return}let f=$e(d,c.min,c.max,{buckets:this.buckets,valueAreaPct:this.valueAreaPct});if(!f){this.lastStats=null;return}let p=f.buckets[f.pocIndex].mid;this.lastStats={poc:p,vah:f.valueAreaHigh,val:f.valueAreaLow,valueAreaPct:this.valueAreaPct};let m=f.buckets.length,h=s.width*this.widthRatio,g=s.x,_=e.E(r),v=1/f.maxCount;t.save();for(let n=0;n<m;n++){let a=f.buckets[n];if(a.count===0)continue;let o=e.w(n,m,r,_),s=a.count*v*h,c=a.mid>=f.valueAreaLow&&a.mid<=f.valueAreaHigh;t.globalAlpha=c?Math.min(1,this.opacity+.18):this.opacity,t.fillStyle=c?i.candleUp:i.textSecondary,t.fillRect(g,o.top+.5,s,o.height-1)}t.globalAlpha=.6,t.strokeStyle=i.candleUp,t.lineWidth=1,t.setLineDash([1,3]);for(let e of[f.valueAreaHigh,f.valueAreaLow]){let n=_(e);t.beginPath(),t.moveTo(g,Math.round(n)+.5),t.lineTo(s.x+s.width,Math.round(n)+.5),t.stroke()}if(t.setLineDash([]),this.highlightPoC){let e=_(p);t.globalAlpha=1,t.strokeStyle=i.crosshair,t.lineWidth=1,t.setLineDash([3,2]),t.beginPath(),t.moveTo(g,Math.round(e)+.5),t.lineTo(s.x+s.width,Math.round(e)+.5),t.stroke(),t.setLineDash([])}this.showStats&&this.drawStats(t,s.x+6,s.y+6,p,f.valueAreaHigh,f.valueAreaLow,i),t.restore()}renderSplit(t,n,r,i,a){let{chartRect:o,priceRange:s}=i,c=nt(n,s.min,s.max,{buckets:this.buckets,valueAreaPct:this.valueAreaPct});if(c.length===0)return;let l=e.E(i),u=i.barWidth/2;t.save();for(let d of c){let c=d.profile,f=c.buckets.length,p=o.height/f,m=e.b(r+d.startIndex,i)-u,h=e.b(r+d.endIndex,i)+u,g=Math.max(2,h-m),_=1/c.maxCount,v=this.letters&&p>=7,y=v?tt(n.slice(d.startIndex,d.endIndex+1),s.min,s.max,this.buckets):null;if(v&&y){t.font=`${Math.min(11,Math.floor(p))}px ui-monospace, monospace`,t.textBaseline=`middle`,t.textAlign=`left`;let n=Math.max(1,Math.floor(g/6));for(let r=0;r<f;r++){let o=y[r];if(o.length===0)continue;let s=e.w(r,f,i,l).mid,u=c.buckets[r].mid>=c.valueAreaLow&&c.buckets[r].mid<=c.valueAreaHigh;t.globalAlpha=u?.95:.6,t.fillStyle=u?a.candleUp:a.textSecondary;let d=Math.min(o.length,n);for(let e=0;e<d;e++)t.fillText(et(o[e]),m+e*6,s)}}else for(let n=0;n<f;n++){let r=c.buckets[n];if(r.count===0)continue;let o=e.w(n,f,i,l),s=r.count*_*g,u=r.mid>=c.valueAreaLow&&r.mid<=c.valueAreaHigh;t.globalAlpha=u?Math.min(1,this.opacity+.18):this.opacity,t.fillStyle=u?a.candleUp:a.textSecondary,t.fillRect(m,o.top+.5,s,o.height-1)}if(this.highlightPoC){let e=l(c.buckets[c.pocIndex].mid);t.globalAlpha=1,t.strokeStyle=a.crosshair,t.lineWidth=1,t.setLineDash([3,2]),t.beginPath(),t.moveTo(m,Math.round(e)+.5),t.lineTo(Math.min(h,o.x+o.width),Math.round(e)+.5),t.stroke(),t.setLineDash([])}}t.restore()}drawStats(e,t,n,r,i,a,o){let s=it(r),c=[[`POC`,r.toFixed(s),o.text],[`VAH`,i.toFixed(s),o.candleUp],[`VAL`,a.toFixed(s),o.candleUp]];e.globalAlpha=1,e.font=`600 10px ${o.font.family}`,e.textBaseline=`middle`;let l=0;for(let[,t]of c)l=Math.max(l,e.measureText(t).width);let u=38+l,d=6+c.length*14;e.fillStyle=o.background,e.globalAlpha=.82,at(e,t,n,u,d,4),e.fill(),e.globalAlpha=1,c.forEach(([r,i,a],s)=>{let c=n+6/2+14/2+s*14;e.fillStyle=a,e.textAlign=`left`,e.fillText(r,t+6,c),e.fillStyle=o.text,e.textAlign=`right`,e.fillText(i,t+u-6,c)}),e.textAlign=`left`}};function it(e){let t=Math.abs(e);return t>=1e3?2:t>=1?4:6}function at(e,t,n,r,i,a){e.beginPath(),e.moveTo(t+a,n),e.arcTo(t+r,n,t+r,n+i,a),e.arcTo(t+r,n+i,t,n+i,a),e.arcTo(t,n+i,t,n,a),e.arcTo(t,n,t+r,n,a),e.closePath()}function ot(e,n){let r=n===`day`?`1d`:`1w`,i=[];for(let n of e){let e=(0,t.timeframeBucketStart)(n.time,r),a=i[i.length-1];a&&a.key===e?(a.high=Math.max(a.high,n.high),a.low=Math.min(a.low,n.low),a.close=n.close):i.push({key:e,open:n.open,high:n.high,low:n.low,close:n.close})}return i}function st(e,t=`day`){let n=ot(e,t);if(n.length<2)return[];let r=n[n.length-2],i=n[n.length-1],a=t===`day`?`D`:`W`;return[{id:`p${a}h`,label:`P${a}H`,price:r.high},{id:`p${a}c`,label:`P${a}C`,price:r.close},{id:`p${a}l`,label:`P${a}L`,price:r.low},{id:`open`,label:t===`day`?`Day Open`:`Week Open`,price:i.open}]}var ct=class{visible=!1;period=`day`;setVisible(e){this.visible=e}isVisible(){return this.visible}setPeriod(e){this.period=e}getPeriod(){return this.period}render(t,n,r,i){if(!this.visible||n.length===0)return;let a=st(n,this.period);if(a.length===0)return;let{chartRect:o}=r,s=o.y,c=o.y+o.height;t.save(),t.font=`600 10px ${i.font.family}`,t.textBaseline=`middle`;for(let n of a){let a=e.T(n.price,r);if(a<s||a>c)continue;let l=lt(n,i);t.strokeStyle=l,t.globalAlpha=.7,t.lineWidth=1,t.setLineDash([5,4]),t.beginPath(),t.moveTo(o.x,Math.round(a)+.5),t.lineTo(o.x+o.width,Math.round(a)+.5),t.stroke(),t.setLineDash([]),t.globalAlpha=1;let u=n.label,d=t.measureText(u).width,f=o.x+o.width-d-10;t.fillStyle=i.background,t.globalAlpha=.85,w(t,f-4,a-7,d+8,14,i),t.globalAlpha=1,t.fillStyle=l,t.textAlign=`left`,t.fillText(u,f,a+.5)}t.restore()}};function lt(e,t){return e.id.endsWith(`h`)?t.candleUp:e.id.endsWith(`l`)?t.candleDown:t.textSecondary}function ut(e){let t,n;return e.map(e=>{let r;return e.type===`high`?(r=t===void 0||e.price>t?`HH`:`LH`,t=e.price):(r=n===void 0||e.price<n?`LL`:`HL`,n=e.price),{...e,label:r}})}function dt(e,t=5,n=5){let r=Math.max(1,Math.floor(t)),i=Math.max(1,Math.floor(n)),a=[];for(let t=r;t<e.length-i;t++){let n=e[t].high,o=e[t].low,s=!0,c=!0;for(let a=t-r;a<=t+i&&!(a!==t&&(e[a].high>=n&&(s=!1),e[a].low<=o&&(c=!1),!s&&!c));a++);s?a.push({index:t,price:n,type:`high`}):c&&a.push({index:t,price:o,type:`low`})}return a}var ft=class{visible=!1;left=5;right=5;showLabels=!1;structureLabels=!1;setVisible(e){this.visible=e}isVisible(){return this.visible}setStrength(e,t){this.left=Math.max(1,Math.floor(e)),this.right=Math.max(1,Math.floor(t))}setShowLabels(e){this.showLabels=e}setStructureLabels(e){this.structureLabels=e}render(t,n,r,i){if(!this.visible||n.length===0)return;let a=dt(n,this.left,this.right);if(a.length===0)return;let o=this.structureLabels?ut(a):a,{from:s,to:c}=r.visibleRange;t.save(),t.font=`10px ${i.font.family}`,t.textAlign=`center`;for(let n of o){if(n.index<s-1||n.index>c+1)continue;let a=e.b(n.index,r),o=e.T(n.price,r),l=n.type===`high`,u=l?i.candleDown:i.candleUp,d=l!==(r.invertScale===!0),f=d?o-8:o+8;t.fillStyle=u,t.beginPath(),d?(t.moveTo(a-5,f-5),t.lineTo(a+5,f-5),t.lineTo(a,f)):(t.moveTo(a-5,f+5),t.lineTo(a+5,f+5),t.lineTo(a,f)),t.closePath(),t.fill();let p=this.structureLabels&&`label`in n?String(n.label):this.showLabels?r.formatPrice?.(n.price)??pt(n.price):null;p&&(t.textBaseline=d?`bottom`:`top`,t.fillText(p,a,d?f-5-1:f+5+1))}t.restore()}};function pt(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var mt=class{buffer=[];constructor(e=240){this.capacity=e,this.capacity=Math.max(1,Math.floor(e))}push(e,t){let n={time:e,bids:t.bids.map(e=>({...e})),asks:t.asks.map(e=>({...e}))},r=this.indexAfter(e);if(r>0&&this.buffer[r-1].time===e){this.buffer[r-1]=n;return}this.buffer.splice(r,0,n),this.buffer.length>this.capacity&&(this.buffer=this.buffer.slice(this.buffer.length-this.capacity))}indexAfter(e){let t=this.buffer;if(t.length===0||t[t.length-1].time<=e)return t.length;let n=0,r=t.length;for(;n<r;){let i=n+r>>1;t[i].time<=e?n=i+1:r=i}return n}snapshots(){return this.buffer}maxVolume(){let e=0;for(let t of this.buffer){for(let n of t.bids)n.volume>e&&(e=n.volume);for(let n of t.asks)n.volume>e&&(e=n.volume)}return e}setCapacity(e){this.capacity=Math.max(1,Math.floor(e)),this.buffer.length>this.capacity&&(this.buffer=this.buffer.slice(this.buffer.length-this.capacity))}clear(){this.buffer=[]}get size(){return this.buffer.length}},ht=class{buffer=new mt(240);visible=!1;opacity=.7;setVisible(e){this.visible=e}isVisible(){return this.visible}setOpacity(e){this.opacity=Math.max(.1,Math.min(1,e))}setCapacity(e){this.buffer.setCapacity(e)}push(e,t){this.buffer.push(e,t)}clear(){this.buffer.clear()}render(t,n,r){if(!this.visible)return;let i=this.buffer.snapshots();if(i.length===0)return;let a=this.buffer.maxVolume();if(a<=0)return;let o=1/a,{chartRect:s}=n,c=Math.max(2,n.barWidth+n.barSpacing),l=s.x,u=s.x+s.width,d=s.y,f=s.y+s.height;t.save();for(let a of i){let i=e.O(a.time,n);if(i<l-c||i>u+c)continue;let s=i-c/2;this.drawSide(t,a.bids,r.candleUp,s,c,n,o,d,f),this.drawSide(t,a.asks,r.candleDown,s,c,n,o,d,f)}t.restore()}drawSide(t,n,r,i,a,o,s,c,l){if(n.length===0)return;let u=gt(n,o);t.fillStyle=r;for(let r of n){let n=e.T(r.price,o);n<c-u||n>l+u||(t.globalAlpha=Math.min(1,Math.sqrt(r.volume*s))*this.opacity,t.fillRect(i,n-u/2,a,u))}t.globalAlpha=1}};function gt(t,n){if(t.length<2)return 3;let r=t.map(e=>e.price).sort((e,t)=>e-t),i=[];for(let e=1;e<r.length;e++){let t=r[e]-r[e-1];t>0&&i.push(t)}if(i.length===0)return 3;i.sort((e,t)=>e-t);let a=i[Math.floor(i.length/2)],o=Math.abs(e.T(r[0],n)-e.T(r[0]+a,n));return Math.max(2,Math.min(o,12))}var _t=class{series=new Map;set(e,n){if(!n||n.length===0){this.series.delete(e);return}let r=[...n].sort((e,t)=>e.time-t.time),i=(0,t.barTimeUnit)(r),a=r.map(e=>e.time*i),o=a[a.length-1],s=a.length>1?o-a[a.length-2]:0;this.series.set(e,{bars:r,times:a,end:o+s})}has(e){return this.series.has(e)}get(e){return this.series.get(e)?.bars}symbols(){return[...this.series.keys()]}closeAt(e,n,r){let i=this.series.get(e);if(!i)return;let a=(0,t.normalizeBarTime)(n,r),{times:o,bars:s}=i;if(a<o[0])return;let c=o.length-1;if(a>o[c]&&(i.end<=o[c]||a>=i.end))return;let l=0,u=c;for(;l<u;){let e=l+u+1>>1;o[e]<=a?l=e:u=e-1}return s[l].close}},vt=class{symbols=new Map;mode=`percent`;store=new _t;aligned=new Map;setMode(e){this.mode=e}getMode(){return this.mode}addSymbol(e){this.symbols.set(e.id,e),this.store.set(e.id,e.data),this.aligned.delete(e.id)}removeSymbol(e){this.symbols.delete(e),this.store.set(e,null),this.aligned.delete(e)}setSymbolData(e,t){let n=this.symbols.get(e);n&&(n.data=t,this.store.set(e,t),this.aligned.delete(e))}setSymbolVisible(e,t){let n=this.symbols.get(e);n&&(n.visible=t)}getSymbols(){return Array.from(this.symbols.values())}clear(){for(let e of this.symbols.keys())this.store.set(e,null);this.symbols.clear(),this.aligned.clear()}getPriceRange(e,t){let n=1/0,r=-1/0;for(let i of this.symbols.values()){if(!i.visible||i.data.length===0)continue;let a=this.line(i,e,t);if(a)for(let e=a.from;e<=a.to;e++){let t=a.priceAt(e);t!==null&&(t<n&&(n=t),t>r&&(r=t))}}return n<=r?{min:n,max:r}:null}render(e,t,n,r){if(this.symbols.size===0||t.length===0)return;let{chartRect:i}=n;e.save(),e.beginPath(),e.rect(i.x,i.y,i.width,i.height),e.clip();for(let r of this.symbols.values())!r.visible||r.data.length===0||this.renderSymbol(e,r,t,n);e.restore()}closesOn(e,n){let r=n.length>0?n[n.length-1].time:NaN,i=this.aligned.get(e.id);if(i&&i.main===n&&i.data===e.data&&i.length===n.length&&i.lastTime===r)return i.closes;let a=new Float64Array(n.length),o=(0,t.barTimeUnit)(n);for(let t=0;t<n.length;t++)a[t]=this.store.closeAt(e.id,n[t].time,o)??NaN;return this.aligned.set(e.id,{main:n,data:e.data,length:n.length,lastTime:r,closes:a}),a}line(e,t,n){let r=this.closesOn(e,t),i=Math.max(0,n.visibleRange.from),a=Math.min(t.length-1,n.visibleRange.to),o=-1;for(let e=i;e<=a;e++)if(Number.isFinite(r[e])&&r[e]!==0&&t[e].close!==0){o=e;break}if(o<0)return null;let s=t[o].close,c=r[o],l=this.mode===`percent`;return{from:o,to:a,priceAt:e=>{let t=r[e];return Number.isFinite(t)?l?t/c*s:t:null}}}renderSymbol(t,n,r,i){let a=this.line(n,r,i);if(!a)return;t.strokeStyle=n.color,t.lineWidth=n.lineWidth??1.5,t.lineJoin=`round`,t.beginPath();let o=0,s=null;for(let n=a.from;n<=a.to;n++){let r=a.priceAt(n);if(r===null)continue;let c=e.b(n,i),l=e.T(r,i);o===0?t.moveTo(c,l):t.lineTo(c,l),(o===2||o===0&&s===null)&&(s={x:c+4,y:l-4}),o++}t.stroke(),s&&(t.fillStyle=n.color,t.font=`bold 10px sans-serif`,t.textBaseline=`bottom`,t.textAlign=`left`,t.fillText(n.label,s.x,s.y))}};function yt(e){if(e.length===0)return[];let t=[],n=e[0].open,r=(e[0].open+e[0].high+e[0].low+e[0].close)/4;for(let i=0;i<e.length;i++){let a=e[i],o=(a.open+a.high+a.low+a.close)/4,s=i===0?a.open:(n+r)/2,c=Math.max(a.high,s,o),l=Math.min(a.low,s,o);t.push({time:a.time,open:s,high:c,low:l,close:o,volume:a.volume}),n=s,r=o}return t}function bt(e,t){if(e.length===0)return[];let n=t.brickSize;t.useATR&&e.length>2&&(n=xt(e,t.atrPeriod??14)),n>0||(n=Math.abs(e[e.length-1].close)/100||1);let r=[],i=Math.round(e[0].close/n)*n,a=e[0].time;for(let t=1;t<e.length;t++){let o=e[t].close-i,s=Math.floor(Math.abs(o)/n);if(s>=1){let c=o>0?1:-1;for(let o=0;o<s;o++){let o=i;i+=c*n,r.push({time:a++,open:o,high:Math.max(o,i),low:Math.min(o,i),close:i,volume:e[t].volume/s})}}}return r}function xt(e,t){let n=e.length-1,r=Math.max(1,n-t),i=0;for(let t=r;t<n;t++)i+=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-e[t-1].close),Math.abs(e[t].low-e[t-1].close));let a=n>r?i/(n-r):0;if(!(a>0))return 0;let o=10**(Math.floor(Math.log10(a))-1);return Math.round(a/o)*o}function St(e,t=3){if(e.length===0)return[];let n=[],r=0;n.push({time:r++,open:e[0].open,high:Math.max(e[0].open,e[0].close),low:Math.min(e[0].open,e[0].close),close:e[0].close,volume:e[0].volume});for(let i=1;i<e.length;i++){let a=e[i].close,o=n[n.length-1],s=o.close>=o.open,c=Math.min(t,n.length),l=-1/0,u=1/0;for(let e=n.length-c;e<n.length;e++)l=Math.max(l,n[e].high),u=Math.min(u,n[e].low);s&&a>o.close?n.push({time:r++,open:o.close,high:a,low:o.close,close:a,volume:e[i].volume}):!s&&a<o.close||s&&a<u?n.push({time:r++,open:o.close,high:o.close,low:a,close:a,volume:e[i].volume}):!s&&a>l&&n.push({time:r++,open:o.close,high:a,low:o.close,close:a,volume:e[i].volume})}return n}function Ct(e,t=4,n=`percent`){if(e.length<2)return e.slice();let r=[],i=e[1].close>=e[0].close?1:-1,a=e[0].close,o=e[0].close,s=e[0].close,c=0;for(let l=1;l<e.length;l++){let u=e[l].close,d=n===`price`?t:t/100*s;i===1?(u>a&&(a=u),a-u>=d&&(r.push({time:c++,open:s,high:a,low:s,close:a,volume:e[l].volume}),i=-1,s=a,o=u,a=u)):(u<o&&(o=u),u-o>=d&&(r.push({time:c++,open:s,high:s,low:o,close:o,volume:e[l].volume}),i=1,s=o,a=u,o=u))}return i===1?r.push({time:c,open:s,high:a,low:s,close:a,volume:0}):r.push({time:c,open:s,high:s,low:o,close:o,volume:0}),r}function wt(e,t,n=3){if(e.length===0||t<=0)return[];let r=[],i=0,a=0,o=0,s=0,c=Math.round(e[0].close/t)*t;a=c,o=c,i=1;for(let c=1;c<e.length;c++){let l=e[c].close,u=Math.round(l/t)*t;i===1?u>a?a=u:a-u>=t*n&&(r.push({time:s++,open:o,high:a,low:o,close:a,volume:e[c].volume}),i=-1,o=u,a-=t):u<o?o=u:u-o>=t*n&&(r.push({time:s++,open:a,high:a,low:o,close:o,volume:e[c].volume}),i=1,a=u,o+=t)}return r.push({time:s,open:i===1?o:a,high:a,low:o,close:i===1?a:o,volume:0}),r}function Tt(e,t){if(e.length===0||t.rangeSize<=0)return[];let n=[],r=e[0].time,i=e[0].open,a=i,o=i,s=0,c=(e,c)=>{for(e>a&&(a=e),e<o&&(o=e),s+=c;a-o>=t.rangeSize;){let c=e>=i,l=c?i+t.rangeSize:i-t.rangeSize;n.push({time:r++,open:i,high:c?l:i,low:c?i:l,close:l,volume:s}),i=l,a=l,o=l,s=0}};for(let t of e){let e=t.close>=t.open?[t.low,t.high,t.close]:[t.high,t.low,t.close],n=t.volume/e.length;for(let t of e)c(t,n)}return n}function j(e){return e.barWidth+e.barSpacing<1}function Et(e,t,n){return e>1.5*(Math.abs(n-t)+1)}var M=class{started=!1;lastX=NaN;lastY=NaN;col=NaN;lo=0;hi=0;width;constructor(e,t,n,r,i=[]){this.ctx=e,this.dense=r,this.dash=i,this.width=Number.isFinite(n)&&n>0?n:1,e.beginPath(),r?e.fillStyle=t:(e.strokeStyle=t,e.lineWidth=this.width,e.lineJoin=`round`)}add(e,t){!Number.isFinite(e)||!Number.isFinite(t)||(this.dense?this.addDense(e,t):this.started?this.ctx.lineTo(e,t):this.ctx.moveTo(e,t),this.started=!0,this.lastX=e,this.lastY=t)}gap(){this.flush(),this.started=!1,this.lastY=NaN}segment(e,t,n,r){(!this.started||e!==this.lastX||t!==this.lastY)&&(this.gap(),this.add(e,t)),this.add(n,r)}finish(){this.flush(),this.dense?this.ctx.fill():this.dash.length>0?(this.ctx.setLineDash([...this.dash]),this.ctx.stroke(),this.ctx.setLineDash([])):this.ctx.stroke()}addDense(e,t){let n=Math.floor(e);n!==this.col&&(this.flush(),this.col=n,this.lo=this.hi=Number.isNaN(this.lastY)?t:this.lastY),t<this.lo&&(this.lo=t),t>this.hi&&(this.hi=t)}flush(){if(Number.isNaN(this.col))return;let e=this.width/2,t=Math.max(1,this.width);this.ctx.rect(this.col+.5-t/2,this.lo-e,t,this.hi-this.lo+2*e),this.col=NaN}};function Dt(e,t,n,r,i,a=t.length){e.beginPath(),e.fillStyle=i;let o=NaN,s=0,c=0,l=NaN,u=NaN,d=()=>{Number.isNaN(o)||e.rect(o,s,1,c-s)};for(let e=0;e<a;e++){let i=Math.floor(t[e]),a=Math.min(n[e],r[e]),f=Math.max(n[e],r[e]);i!==o&&(d(),o=i,s=Number.isNaN(l)?a:Math.min(a,l),c=Number.isNaN(u)?f:Math.max(f,u)),a<s&&(s=a),f>c&&(c=f),l=a,u=f}d(),e.fill()}var Ot=.1;function kt(e){return e.plots?e.plots.map(e=>e.key):null}function At(e,t){return e.tone?e.tone===`sign`?(t[e.key]??0)>=0:t[e.tone.field]===1:!0}function jt(e,t){return t.plots?.[e.key]?.visible!==!1}var Mt=[6,4];function N(e,n,r){let i=e.plots?.[n];return{visible:i?.visible!==!1,dash:(0,t.lineDash)(i?.lineStyle??`solid`,Mt,r)}}function Nt(e,t,n){let r=t.colors[e.color]??t.colors[0];return!e.tone||e.downColor===void 0||!n||At(e,n)?r:t.colors[e.downColor]??r}function Pt(e,t,n,r){let{lo:i,hi:a}=It(e,t,n,r.keys),o=r.scale,s=o?.min,c=o?.max;if(i===1/0){if(s===void 0&&c===void 0)return null;i=s??0,a=c??i+1}else{let e=a-i||Math.abs(a)||1;i-=e*Ot,a+=e*Ot}for(let e of r.levels??[])e<i&&(i=e),e>a&&(a=e);return(r.zero||o?.zero)&&(i>0&&(i=0),a<0&&(a=0)),s!==void 0&&(i=s),c!==void 0&&(a=c),a>i||(a=i+1),{min:i,max:a}}function Ft(e,t,n,r){let{lo:i,hi:a}=It(e,t,n,r.keys),o=e=>e!==void 0&&e>0,s=o(r.scale?.min)?r.scale?.min:void 0,c=o(r.scale?.max)?r.scale?.max:void 0;if(i===1/0){if(s===void 0||c===void 0)return null;i=s,a=c}else{if(!(i>0))return!1;let e=Math.exp((Math.log(a/i)||Math.LN2/4)*Ot);i/=e,a*=e}for(let e of r.levels??[])e>0&&(e<i&&(i=e),e>a&&(a=e));return s!==void 0&&(i=s),c!==void 0&&(a=c),a>i?{min:i,max:a}:null}function It(e,t,n,r){let i=1/0,a=-1/0,o=e=>{e===void 0||!Number.isFinite(e)||(e<i&&(i=e),e>a&&(a=e))},s=e=>{if(e){if(r){for(let t=0;t<r.length;t++)o(e[r[t]]);return}for(let t in e)o(e[t])}},c=e?.series;if(c){let e=Math.min(n,c.length-1);for(let n=Math.max(0,t);n<=e;n++)s(c[n])}else if(e){let r=0;for(let i of e.values.values()){if(r>n)break;r>=t&&s(i),r++}}return{lo:i,hi:a}}function Lt(e){return!!e?.some(e=>e.kind===`histogram`)}function Rt(n,r,i,a,o){let s=r.series;if(!s)return;let c=Math.max(0,i.visibleRange.from),l=Math.min(i.visibleRange.to,s.length-1);if(l<c)return;let u=e.E(i);for(let e=0;e<o.length;e++){let r=o[e];if(!jt(r,a))continue;let d=a.lineWidths[e]??a.lineWidths[0]??1.5,f=(0,t.lineDash)(a.plots?.[r.key]?.lineStyle??`solid`,Mt,d),p=r.kind??`line`,m=r.tone&&r.downColor!==void 0?[!0,!1]:[null];for(let e of m){let t=a.colors[r.color]??a.colors[0],o=e===!1?a.colors[r.downColor]??t:t,m=t=>e===null||At(r,t)===e;p===`histogram`?Ht(n,s,r.key,c,l,i,u,o,m):p===`dots`?Vt(n,s,r.key,c,l,i,u,o,m):Bt(n,s,r.key,c,l,i,u,o,d,p===`step`,e===null?null:m,f)}}}function zt(e,t){let n=e?.[t];return n!==void 0&&Number.isFinite(n)?n:void 0}function Bt(t,n,r,i,a,o,s,c,l,u,d,f=[]){let p=new M(t,c,l,j(o),f),m=0,h=0,g=!1;for(let t=i;t<=a;t++){let i=n[t],a=zt(i,r);if(a===void 0){g=!1,p.gap();continue}let c=e.b(t,o),l=s(a);d?g&&d(i)&&(u?(p.segment(m,h,c,h),p.add(c,l)):p.segment(m,h,c,l)):(g&&u&&p.add(c,h),p.add(c,l)),m=c,h=l,g=!0}p.finish()}function Vt(t,n,r,i,a,o,s,c,l){let u=Math.max(1.5,o.barWidth*.15),d=j(o),f=NaN;t.beginPath(),t.fillStyle=c;for(let c=i;c<=a;c++){let i=n[c],a=zt(i,r);if(a===void 0||!l(i))continue;let p=e.b(c,o);if(d){let e=Math.floor(p);if(e===f)continue;f=e}let m=s(a);t.moveTo(p+u,m),t.arc(p,m,u,0,Math.PI*2)}t.fill()}function Ht(t,n,r,i,a,o,s,c,l){let u=s(0);if(t.beginPath(),t.fillStyle=c,j(o)){let c=NaN,d=0,f=()=>{if(Number.isNaN(c))return;let e=s(d);t.rect(c,Math.min(e,u),1,Math.max(1,Math.abs(e-u)))};for(let t=i;t<=a;t++){let i=n[t],a=zt(i,r);if(a===void 0||!l(i))continue;let s=Math.floor(e.b(t,o));s===c?Math.abs(a)>Math.abs(d)&&(d=a):(f(),c=s,d=a)}f(),t.fill();return}let d=Math.max(1,o.barWidth);for(let c=i;c<=a;c++){let i=n[c],a=zt(i,r);if(a===void 0||!l(i))continue;let f=e.b(c,o),p=s(a);t.rect(f-d/2,Math.min(p,u),d,Math.max(1,Math.abs(p-u)))}t.fill()}var P=class{canResume(e,t,n){let r=t.series;if(!r||n<=0||n>r.length||r.length>e.length)return!1;for(let i=n;i<r.length;i++)if(r[i]&&!t.values.has(e[i].time))return!1;return!0}writePoint(e,t,n,r){e.series[n]=r,r?e.values.set(t[n].time,r):e.values.delete(t[n].time)}render(e,t,n,r){this.descriptor.plots&&Rt(e,t,n,r,this.descriptor.plots)}drawLine(e,t,n,r,i){if(t.length<2||i?.visible===!1)return;let a=new M(e,n,r,Et(t.length,t[0].x,t[t.length-1].x),i?.dash);for(let e of t)a.add(e.x,e.y);a.finish()}drawBand(e,t,n,r){if(!(t.length<2||n.length<2)){if(t.length===n.length&&Et(t.length,t[0].x,t[t.length-1].x)){Dt(e,t.map(e=>e.x),t.map(e=>e.y),n.map(e=>e.y),r);return}e.beginPath(),e.moveTo(t[0].x,t[0].y);for(let n=1;n<t.length;n++)e.lineTo(t[n].x,t[n].y);for(let t=n.length-1;t>=0;t--)e.lineTo(n[t].x,n[t].y);e.closePath(),e.fillStyle=r,e.fill()}}drawHistogram(e,t,n){let r=n/2;for(let i of t){e.fillStyle=i.color;let t=Math.min(i.y,i.baseY),a=Math.abs(i.y-i.baseY);e.fillRect(i.x-r,t,n,Math.max(a,1))}}valuesToPoints(t,n,r,i){let a=[],{from:o,to:s}=i.visibleRange;for(let c=o;c<=s&&c<r.length;c++){let o=t.values.get(r[c].time);o&&o[n]!==void 0&&a.push({x:e.b(c,i),y:e.T(o[n],i)})}return a}};function Ut(e){let t=e.inputs;if(!t)return null;for(let e in t)if(t[e]?.source)return e;return null}function Wt(e,n){let r=Ut(e);if(!r)return{kind:`bars`};let i=n[r],a=(0,t.parseIndicatorSource)(i);return a?{kind:`line`,...a}:(0,t.isPriceSource)(i)&&i!==`close`?{kind:`price`,source:i}:{kind:`bars`}}function Gt(e,n,r=null,i=0){let a=r&&i>0&&i<=r.length?r:[],o=a===r?i:0;a.length=e.length;for(let r=o;r<e.length;r++){let i=e[r];a[r]={...i,close:(0,t.sourcePrice)(i,n)}}return a}function Kt(e,t,n){if(!t)return null;let r=-1;for(let i=0;i<e.length&&i<t.length;i++){let e=t[i]?.[n];if(e!==void 0&&Number.isFinite(e)){r=i;break}}if(r<0)return null;let i=Array(e.length-r),a=t[r][n];for(let o=r;o<e.length;o++){let s=t[o]?.[n];s!==void 0&&Number.isFinite(s)&&(a=s);let c=e[o];i[o-r]={time:c.time,open:a,high:a,low:a,close:a,volume:c.volume}}return{bars:i,start:r}}function qt(e,t,n){if(t===0||!e.series)return e;let r=Array(n).fill(null);for(let i=0;i<e.series.length&&t+i<n;i++)r[t+i]=e.series[i];return{...e,series:r}}function Jt(e){return{values:new Map,series:Array(e).fill(null)}}var Yt=[`ticks`,`seconds`,`minutes`,`hours`,`days`,`weeks`,`months`],Xt={ticks:1e6,seconds:59,minutes:59,hours:24,days:366,weeks:52,months:12},Zt={s:`seconds`,m:`minutes`,h:`hours`,d:`days`,w:`weeks`,M:`months`};function Qt(e){let n=(0,t.tickBarCount)(e);if(n!==null)return{unit:`ticks`,count:n};let r=(0,t.parseTimeframe)(e);return r?{unit:Zt[r.unit],count:r.count}:null}function $t(e,t){if(!e||!t)return!0;let n=Qt(t);if(!n)return!0;let r=e[n.unit];return r===void 0?!0:r===!1?!1:n.count>=r[0]&&(n.count<=r[1]||r[1]>=Xt[n.unit])}function en(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=e,n={};for(let e of Yt){let r=t[e];if(r===!1){n[e]=!1;continue}if(!Array.isArray(r)||r.length!==2||!r.every(e=>typeof e==`number`&&Number.isFinite(e)))continue;let i=Xt[e],[a,o]=r.map(e=>Math.min(i,Math.max(1,Math.round(e)))).sort((e,t)=>e-t);(a>1||o<i)&&(n[e]=[a,o])}return Object.keys(n).length>0?n:null}function tn(e){return[...t.TC_SERIES_COLORS.slice(e),...t.TC_SERIES_COLORS.slice(0,e)]}function nn(e){let n=t.TC_SERIES_COLORS.length;if(e.length!==n)return!1;let r=t.TC_SERIES_COLORS.indexOf(e[0]);return r>=0&&e.every((e,i)=>e===t.TC_SERIES_COLORS[(r+i)%n])}function rn(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t}]))}function an(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t===!1?!1:[t[0],t[1]]]))}var on=1,sn=class{registry=new Map;instances=new Map;styleDefaults=new Map;order=null;pending=null;timeframe=null;register(e){this.registry.set(e.descriptor.id,e)}getAvailableIndicators(){return Array.from(this.registry.values()).map(e=>e.descriptor)}addIndicator(e,t={},n,r={}){let i=this.registry.get(e);if(!i)throw Error(`Unknown indicator: ${e}`);let a=this.claimInstanceId(e,r.instanceId),o={id:e,instanceId:a,params:{...i.descriptor.defaultConfig,...t},visible:!0};r.pane&&this.canHost(r.pane)&&(o.pane=r.pane),r.scale===`left`&&i.descriptor.placement===`overlay`&&!o.pane&&(o.scale=`left`);let s=this.styleDefaults.get(e),c={...s?.plots,...o.style?.plots},l={colors:o.style?.colors??s?.colors?.slice()??tn(this.freeColor(e,i.descriptor.placement,o.pane??null)),lineWidths:o.style?.lineWidths??s?.lineWidths?.slice()??[1.5],opacity:o.style?.opacity??s?.opacity??1,...Object.keys(c).length>0?{plots:rn(c)}:{}};this.flush();let u={plugin:i,config:o,output:null,style:l,changedFrom:0,offInterval:!1};return this.instances.set(a,u),this.order=null,n&&this.compute(u,n),a}removeIndicator(e){this.instances.delete(e),this.order=null}updateIndicator(e,t,n){this.flush();let r=this.instances.get(e);if(!r)return;let i=Ut(r.plugin.descriptor);if(i&&i in t&&this.readsFromItself(e,{...r.config.params,...t})){let{[i]:e,...n}=t;t=n}if(Object.assign(r.config.params,t),delete r.sourceBars,delete r.lineInput,this.order=null,!n)return;let a=new Set([e,...this.getDependents(e)]);for(let e of this.ordered())a.has(e.config.instanceId)&&this.compute(e,n)}recalculateAll(e){this.pending=null;for(let t of this.ordered())this.compute(t,e)}deferRecalculateFrom(e,t){let n=this.pending;if(n&&n.data===e){n.from=Math.min(n.from,t);return}this.flush(),this.pending={data:e,from:t}}flush(){let e=this.pending;if(e){this.pending=null;for(let t of this.ordered())this.compute(t,e.data,e.from)}}recalculateFrom(e,t){this.deferRecalculateFrom(e,t),this.flush()}compute(e,t,n){let{plugin:r,config:i}=e,a=Wt(r.descriptor,i.params);if(a.kind===`line`){this.computeFromLine(e,t,a.instanceId,a.key,n);return}delete e.lineInput;let o=t;a.kind===`price`?(e.sourceBars=Gt(t,a.source,e.sourceBars??null,n??0),o=e.sourceBars):delete e.sourceBars;let s=e.output,c=null;n!==void 0&&n>0&&s&&r.update&&(c=r.update(o,i,s,n)),e.changedFrom=c?Math.max(0,n-(r.revisesBefore?.(i)??0)):0,e.output=c??r.calculate(o,i)}computeFromLine(e,t,n,r,i){let{plugin:a,config:o}=e,s=this.instances.get(n),c=s?.output?.series,l=e.lineInput,u=i===void 0?void 0:Math.min(i,s?.changedFrom??0);if(u!==void 0&&c&&a.update&&l&&l.raw.series&&l.aligned.series&&l.sourceId===n&&l.key===r&&l.start<u&&u<=l.start+l.bars.length){let{start:n,bars:i}=l;i.length=t.length-n;let s=i[u-1-n].close;for(let e=u;e<t.length;e++){let a=c[e]?.[r];a!==void 0&&Number.isFinite(a)&&(s=a),i[e-n]={time:t[e].time,open:s,high:s,low:s,close:s,volume:t[e].volume}}let d=a.update(i,o,l.raw,u-n);if(d?.series){let r=Math.max(n,u-(a.revisesBefore?.(o)??0));if(l.raw=d,n===0)l.aligned=d;else{let e=l.aligned.series;e.length=t.length;for(let i=r;i<t.length;i++)e[i]=d.series[i-n]??null;l.aligned.values=d.values,l.aligned.meta=d.meta}e.output=l.aligned,e.changedFrom=r;return}}e.changedFrom=0;let d=Kt(t,c,r);if(!d){delete e.lineInput,e.output=Jt(t.length);return}let f=a.calculate(d.bars,o),p=qt(f,d.start,t.length);e.lineInput={sourceId:n,key:r,start:d.start,bars:d.bars,raw:f,aligned:p},e.output=p}ordered(){if(this.order)return this.order;let e=[],t=new Map,n=r=>{let i=r.config.instanceId;if(t.get(i))return;t.set(i,`visiting`);let a=Wt(r.plugin.descriptor,r.config.params),o=a.kind===`line`?this.instances.get(a.instanceId):void 0;o&&n(o),t.set(i,`done`),e.push(r)};for(let e of this.instances.values())n(e);return this.order=e,e}readsFromItself(e,t){let n=this.instances.get(e);if(!n)return!1;let r=Wt(n.plugin.descriptor,t),i=new Set;for(;r.kind===`line`;){if(r.instanceId===e)return!0;if(i.has(r.instanceId))return!1;i.add(r.instanceId);let t=this.instances.get(r.instanceId);if(!t)return!1;r=Wt(t.plugin.descriptor,t.config.params)}return!1}canHost(e){let t=this.instances.get(e);return!!t&&t.plugin.descriptor.placement===`panel`&&!t.config.pane}getDependents(e){let t=[],n=new Set([e]),r=[e];for(;r.length;){let e=r.shift();for(let i of this.instances.values()){let a=Wt(i.plugin.descriptor,i.config.params),o=i.config.instanceId;a.kind===`line`&&a.instanceId===e&&!n.has(o)&&(n.add(o),t.push(o),r.push(o))}}return t}claimInstanceId(e,t){if(t&&!this.instances.has(t)){let e=Number(/_(\d+)$/.exec(t)?.[1]);return Number.isSafeInteger(e)&&e>=on&&(on=e+1),t}let n=`tc_${e}_${on++}`;for(;this.instances.has(n);)n=`tc_${e}_${on++}`;return n}getPaneMembers(e){let t=[];for(let n of this.instances.values())n.config.pane===e&&t.push(n.config.instanceId);return t}setPane(e,t){let n=this.instances.get(e);if(!n||t===e||t!==null&&!this.canHost(t))return!1;if(t===null?delete n.config.pane:(n.config.pane=t,delete n.config.scale),nn(n.style.colors)){let t=n.plugin.descriptor.placement,r=n.config.pane??null;this.colorsInPane(t,r,e).has(n.style.colors[0])&&(n.style.colors=tn(this.freeColor(n.config.id,t,r,e)))}return!0}colorsInPane(e,t,n){let r=new Set;for(let i of this.instances.values())i.config.instanceId!==n&&(t===null?e===`overlay`&&i.plugin.descriptor.placement===`overlay`&&!i.config.pane:i.config.instanceId===t||i.config.pane===t)&&r.add(i.style.colors[0]);return r}freeColor(e,n,r,i){let a=this.colorsInPane(n,r,i);for(let t of this.instances.values())t.config.id===e&&t.config.instanceId!==i&&a.add(t.style.colors[0]);let o=t.TC_SERIES_COLORS.findIndex(e=>!a.has(e));return o>=0?o:a.size%t.TC_SERIES_COLORS.length}getOutput(e){return this.flush(),this.instances.get(e)?.output??null}renderOverlays(e,t,n){for(let r of this.overlayDraws(t,n))r(e)}overlayDraws(e,t){this.flush();let n=[];for(let r of this.instances.values()){let i=r.output;if(!i||!cn(r)||r.plugin.descriptor.placement!==`overlay`||r.config.pane)continue;let a=r.config.scale===`left`?t??e:e;n.push(e=>r.plugin.render(e,i,a,r.style))}return n}hasLeftScaleOverlays(){for(let e of this.instances.values())if(e.config.scale===`left`&&cn(e))return!0;return!1}setScale(e,t){let n=this.instances.get(e);return!n||n.plugin.descriptor.placement!==`overlay`||n.config.pane?!1:(t===`left`?n.config.scale=`left`:delete n.config.scale,!0)}renderPanel(e,t,n){this.flush();let r=this.instances.get(t);!r?.output||!cn(r)||r.plugin.render(e,r.output,n,r.style)}getLatestValues(e){this.flush();let t=this.instances.get(e);return t?un(t):[]}getLatestOverlayValues(e=`right`){this.flush();let t=[];for(let n of this.instances.values())n.plugin.descriptor.placement!==`overlay`||n.config.pane||n.config.scale===`left`==(e===`left`)&&t.push(...un(n));return t}getIndicatorConfig(e){return this.instances.get(e)?.config??null}setVisible(e,t){let n=this.instances.get(e);return n?(n.config.visible=t,t):null}isVisible(e){return this.instances.get(e)?.config.visible??!1}isShown(e){let t=this.instances.get(e);return t?cn(t):!1}setTimeframe(e){this.timeframe=e;let t=!1;for(let e of this.instances.values())t=this.placeOnInterval(e)||t;return t}setIntervals(e,t){let n=this.instances.get(e);if(!n)return!1;let r=t?en(t):null;return r?n.config.intervals=r:delete n.config.intervals,this.placeOnInterval(n),!0}getIntervals(e){let t=this.instances.get(e)?.config.intervals;return t?an(t):null}placeOnInterval(e){let t=!$t(e.config.intervals,this.timeframe);return t===e.offInterval?!1:(e.offInterval=t,!0)}getLevels(e){let t=this.instances.get(e);return t?[...t.config.levels??t.plugin.descriptor.levels??[]]:[]}setLevels(e,t){let n=this.instances.get(e);return n?(t===null?delete n.config.levels:n.config.levels=t.filter(e=>Number.isFinite(e)),!0):!1}getPaneValueRange(e,t,n,r=!1){this.flush();let i=null;for(let a of[e,...this.getPaneMembers(e)]){let e=this.instances.get(a);if(!e||!cn(e))continue;let o=e.plugin.descriptor,s={keys:ln(e),scale:o.scale,levels:e.config.levels??o.levels,zero:Lt(o.plots)},c=r?Ft(e.output,t,n,s):Pt(e.output,t,n,s);if(c===!1)return null;c&&(i=i?{min:Math.min(i.min,c.min),max:Math.max(i.max,c.max)}:c)}return i}getIndicatorDescriptor(e){return this.instances.get(e)?.plugin.descriptor??null}getActiveIndicators(){let e=[];for(let[t,n]of this.instances)e.push({instanceId:t,id:n.config.id,params:{...n.config.params},descriptor:n.plugin.descriptor,visible:n.config.visible??!0,shown:cn(n),...n.config.intervals?{intervals:an(n.config.intervals)}:{},...n.config.pane?{pane:n.config.pane}:{}});return e}getIndicatorStyle(e){let t=this.instances.get(e)?.style;return t?{colors:[...t.colors],lineWidths:[...t.lineWidths],opacity:t.opacity,...t.plots?{plots:rn(t.plots)}:{}}:null}updateIndicatorStyle(e,t){let n=this.instances.get(e);if(!n)return;let{plots:r,...i}=t;if(Object.assign(n.style,i),r){let e=rn(n.style.plots??{});for(let[t,n]of Object.entries(r))e[t]={...e[t],...n};n.style.plots=e}}setPlotStyles(e,t){let n=this.instances.get(e);n&&(t&&Object.keys(t).length>0?n.style.plots=rn(t):delete n.style.plots)}setStyleDefaults(e,t){t?this.styleDefaults.set(e,{...t,...t.plots?{plots:rn(t.plots)}:{}}):this.styleDefaults.delete(e)}getOverlayPriceRange(e,t,n=`right`){this.flush();let r=1/0,i=-1/0;for(let a of this.instances.values()){if(!a.output||!cn(a)||a.plugin.descriptor.placement!==`overlay`||a.config.pane||a.config.scale===`left`!=(n===`left`))continue;let o=a.output.series;if(!o)continue;let s=ln(a),c=Math.min(t,o.length-1);for(let t=Math.max(0,e);t<=c;t++){let e=o[t];if(e){if(s){for(let t=0;t<s.length;t++){let n=e[s[t]];n!==void 0&&isFinite(n)&&(n<r&&(r=n),n>i&&(i=n))}continue}for(let t in e){let n=e[t];n!==void 0&&isFinite(n)&&(n<r&&(r=n),n>i&&(i=n))}}}}return r===1/0?null:{min:r,max:i}}getPanelIndicators(){let e=[];for(let[t,n]of this.instances)n.plugin.descriptor.placement===`panel`&&e.push({instanceId:t,descriptor:n.plugin.descriptor});return e}};function cn(e){return e.config.visible!==!1&&!e.offInterval}function ln(e){let t=kt(e.plugin.descriptor),n=e.style.plots;return t&&n?t.filter(e=>n[e]?.visible!==!1):t}function un(e){let t=e.output?.series,n=e.plugin.descriptor.plots;if(!t||!n||!cn(e))return[];let r=t[t.length-1];if(!r)return[];let i=[];for(let t of n){if(!jt(t,e.style))continue;let n=r[t.key];n!==void 0&&Number.isFinite(n)&&i.push({value:n,color:Nt(t,e.style,r)})}return i}var F=class extends Map{keyBuf=[];valBuf=[];folded=!1;constructor(){super()}set(e,t){if(this.folded)return super.set(e,t);let n=this.keyBuf,r=n.length;if(r===0||e>n[r-1])return n.push(e),this.valBuf.push(t),this;let i=this.indexOf(e);return i>=0?(this.valBuf[i]=t,this):(this.fold(),super.set(e,t))}get(e){if(this.folded)return super.get(e);let t=this.indexOf(e);return t>=0?this.valBuf[t]:void 0}has(e){return this.folded?super.has(e):this.indexOf(e)>=0}delete(e){if(this.folded)return super.delete(e);let t=this.indexOf(e);return t<0?!1:(this.keyBuf.splice(t,1),this.valBuf.splice(t,1),!0)}clear(){super.clear(),this.keyBuf=[],this.valBuf=[],this.folded=!1}get size(){return this.folded?super.size:this.keyBuf.length}forEach(e,t){this.fold(),super.forEach(e,t)}entries(){return this.fold(),super.entries()}keys(){return this.fold(),super.keys()}values(){return this.fold(),super.values()}[Symbol.iterator](){return this.fold(),super[Symbol.iterator]()}indexOf(e){let t=this.keyBuf,n=0,r=t.length-1;for(;n<=r;){let i=n+r>>1,a=t[i];if(a===e)return i;a<e?n=i+1:r=i-1}return-1}fold(){if(this.folded)return;this.folded=!0;let e=this.keyBuf,t=this.valBuf;for(let n=0;n<e.length;n++)super.set(e[n],t[n]);this.keyBuf=[],this.valBuf=[]}};function I(e,t,n){let r=e.params[t];if(typeof r==`number`&&Number.isFinite(r))return r;if(typeof r==`string`){let e=Number(r);if(Number.isFinite(e))return e}return n}function L(e,t,n,r=1){let i=I(e,t,n);return Math.max(r,Math.floor(i))}var dn=class extends P{descriptor={id:`sma`,name:`Simple Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`SMA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`SMA`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null),a=0;for(let t=0;t<e.length;t++)if(a+=e[t].close,t>=n&&(a-=e[t-n].close),t>=n-1){let o={value:a/n};r.set(e[t].time,o),i[t]=o}return{values:r,series:i}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=L(t,`period`,20,1);for(let t=r;t<e.length;t++){if(t<i-1){this.writePoint(n,e,t,null);continue}let r=0;for(let n=t-i+1;n<=t;n++)r+=e[n].close;this.writePoint(n,e,t,{value:r/i})}return n}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},fn=class extends P{descriptor={id:`ema`,name:`Exponential Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`EMA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`EMA`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=2/(n+1),i=new F,a=Array(e.length).fill(null),o=0;for(let t=0;t<e.length;t++){if(t<n-1){o+=e[t].close;continue}o=t===n-1?(o+e[t].close)/n:(e[t].close-o)*r+o;let s={value:o};i.set(e[t].time,s),a[t]=s}return{values:i,series:a}}update(e,t,n,r){let i=L(t,`period`,20,1);if(r<i||!this.canResume(e,n,r))return null;let a=n.series[r-1]?.value;if(a===void 0)return null;let o=2/(i+1);for(let t=r;t<e.length;t++)a=(e[t].close-a)*o+a,this.writePoint(n,e,t,{value:a});return n}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},pn=class extends P{descriptor={id:`bb`,name:`Bollinger Bands`,placement:`overlay`,defaultConfig:{period:20,stdDev:2,source:`close`},shortName:`BB`,inputs:{source:{source:!0}},plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=I(t,`stdDev`,2),i=new F,a=Array(e.length).fill(null),o=0,s=0;for(let t=0;t<e.length;t++){let c=e[t].close;if(o+=c,s+=c*c,t>=n){let r=e[t-n].close;o-=r,s-=r*r}if(t>=n-1){let c=o/n,l=s/n-c*c,u=Math.sqrt(Math.max(0,l)),d={middle:c,upper:c+r*u,lower:c-r*u};i.set(e[t].time,d),a[t]=d}}return{values:i,series:a}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=L(t,`period`,20,1),a=I(t,`stdDev`,2);for(let t=r;t<e.length;t++){if(t<i-1){this.writePoint(n,e,t,null);continue}let r=0,o=0;for(let n=t-i+1;n<=t;n++){let t=e[n].close;r+=t,o+=t*t}let s=r/i,c=Math.sqrt(Math.max(0,o/i-s*s));this.writePoint(n,e,t,{middle:s,upper:s+a*c,lower:s-a*c})}return n}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=0,u=c-s+1,d=new Float64Array(u),f=new Float64Array(u),p=new Float64Array(u),m=new Float64Array(u);for(let t=s;t<=c&&t<o.length;t++){let n=o[t];!n||n.upper===void 0||(d[l]=e.b(t,i),f[l]=e.T(n.upper,i),p[l]=e.T(n.middle,i),m[l]=e.T(n.lower,i),l++)}if(l<2)return;let h=j(i),g=d.subarray(0,l);if(h)Dt(n,g,f,m,(0,t.withAlpha)(a.colors[0],.1),l);else{n.beginPath(),n.moveTo(d[0],f[0]);for(let e=1;e<l;e++)n.lineTo(d[e],f[e]);for(let e=l-1;e>=0;e--)n.lineTo(d[e],m[e]);n.closePath(),n.fillStyle=(0,t.withAlpha)(a.colors[0],.1),n.fill()}let _=(e,t,r)=>{let i=N(a,r,a.lineWidths[0]);if(!i.visible)return;let o=new M(n,t,a.lineWidths[0],h,i.dash);for(let t=0;t<l;t++)o.add(g[t],e[t]);o.finish()};_(f,a.colors[0],`upper`),_(p,a.colors[1]??a.colors[0],`middle`),_(m,a.colors[0],`lower`)}},mn=class extends P{descriptor={id:`vwap`,name:`Volume Weighted Average Price`,placement:`overlay`,defaultConfig:{},shortName:`VWAP`,plots:[{key:`value`,title:`VWAP`,color:0}]};calculate(e,t){let n=new F,r=Array(e.length).fill(null),i=0,a=0;for(let t=0;t<e.length;t++){let o=(e[t].high+e[t].low+e[t].close)/3;if(i+=e[t].volume,a+=o*e[t].volume,i>0){let o={value:a/i};n.set(e[t].time,o),r[t]=o}}return{values:n,series:r}}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},hn=class extends P{descriptor={id:`ichimoku`,name:`Ichimoku Cloud`,placement:`overlay`,defaultConfig:{tenkan:9,kijun:26,senkou:52,displacement:26},shortName:`Ichimoku`,plots:[{key:`tenkan`,title:`Conversion`,color:0},{key:`kijun`,title:`Base`,color:1},{key:`senkouA`,title:`Lead A`,color:2},{key:`senkouB`,title:`Lead B`,color:3}]};calculate(e,t){let n=L(t,`tenkan`,9,1),r=L(t,`kijun`,26,1),i=L(t,`senkou`,52,1),a=new F,o=Array(e.length).fill(null),s=t=>{let n=new Float64Array(e.length),r=new Float64Array(e.length);for(let i=0;i<e.length;i++){let a=-1/0,o=1/0,s=Math.max(0,i-t+1);for(let t=s;t<=i;t++)e[t].high>a&&(a=e[t].high),e[t].low<o&&(o=e[t].low);n[i]=a,r[i]=o}return{highs:n,lows:r}},c=s(n),l=s(r),u=s(i);for(let t=0;t<e.length;t++){let s={};t>=n-1&&(s.tenkan=(c.highs[t]+c.lows[t])/2),t>=r-1&&(s.kijun=(l.highs[t]+l.lows[t])/2),s.tenkan!==void 0&&s.kijun!==void 0&&(s.senkouA=(s.tenkan+s.kijun)/2),t>=i-1&&(s.senkouB=(u.highs[t]+u.lows[t])/2),t>=r-1&&(s.chikou=e[t].close),(s.tenkan!==void 0||s.kijun!==void 0||s.senkouA!==void 0||s.senkouB!==void 0)&&(a.set(e[t].time,s),o[t]=s)}return{values:a,series:o}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=c-s+1,u=new Float64Array(l),d=new Float64Array(l),f=0,p=new Float64Array(l),m=new Float64Array(l),h=0,g=new Float64Array(l),_=new Float64Array(l),v=0,y=new Float64Array(l),b=new Float64Array(l),x=0;for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n)continue;let r=e.b(t,i);n.tenkan!==void 0&&(u[f]=r,d[f]=e.T(n.tenkan,i),f++),n.kijun!==void 0&&(p[h]=r,m[h]=e.T(n.kijun,i),h++),n.senkouA!==void 0&&(g[v]=r,_[v]=e.T(n.senkouA,i),v++),n.senkouB!==void 0&&(y[x]=r,b[x]=e.T(n.senkouB,i),x++)}if(v>1&&x>1){let e=Math.min(v,x);n.beginPath(),n.moveTo(g[0],_[0]);for(let t=1;t<e;t++)n.lineTo(g[t],_[t]);for(let t=e-1;t>=0;t--)n.lineTo(y[t],b[t]);n.closePath(),n.fillStyle=(0,t.withAlpha)(a.colors[2]??`#1fa874`,.15),n.fill()}let S=(e,t,r,i,o,s)=>{let c=N(a,e,s);if(!(i<2||!c.visible)){n.beginPath(),n.strokeStyle=o,n.lineWidth=s,n.lineJoin=`round`,n.setLineDash(c.dash),n.moveTo(t[0],r[0]);for(let e=1;e<i;e++)n.lineTo(t[e],r[e]);n.stroke(),n.setLineDash([])}};S(`tenkan`,u,d,f,a.colors[0],a.lineWidths[0]),S(`kijun`,p,m,h,a.colors[1]??`#f2a93b`,a.lineWidths[0]),S(`senkouA`,g,_,v,a.colors[2]??`#1fa874`,1),S(`senkouB`,y,b,x,a.colors[3]??`#e8505b`,1)}},gn=class extends P{descriptor={id:`psar`,name:`Parabolic SAR`,placement:`overlay`,defaultConfig:{step:.02,max:.2},shortName:`SAR`,plots:[{key:`value`,title:`SAR`,color:0,kind:`dots`,tone:{field:`trend`},downColor:1}]};calculate(e,t){let n=I(t,`step`,.02),r=I(t,`max`,.2),i=new F,a=Array(e.length).fill(null);if(e.length<2)return{values:i,series:a};let o=e[1].close>e[0].close,s=n,c=o?e[0].high:e[0].low,l=o?e[0].low:e[0].high,u={value:l,trend:o?1:-1};i.set(e[0].time,u),a[0]=u;for(let t=1;t<e.length;t++){let u=l;l=u+s*(c-u),o?(l=Math.min(l,e[t-1].low),t>=2&&(l=Math.min(l,e[t-2].low)),e[t].low<l?(o=!1,l=c,c=e[t].low,s=n):e[t].high>c&&(c=e[t].high,s=Math.min(s+n,r))):(l=Math.max(l,e[t-1].high),t>=2&&(l=Math.max(l,e[t-2].high)),e[t].high>l?(o=!0,l=c,c=e[t].high,s=n):e[t].low<c&&(c=e[t].low,s=Math.min(s+n,r)));let d={value:l,trend:o?1:-1};i.set(e[t].time,d),a[t]=d}return{values:i,series:a}}render(t,n,r,i){let a=n.series;if(!a||i.plots?.value?.visible===!1)return;let{from:o,to:s}=r.visibleRange,c=Math.max(1.5,r.barWidth*.15);for(let n=o;n<=s&&n<a.length;n++){let o=a[n];if(!o||o.value===void 0)continue;let s=e.b(n,r),l=e.T(o.value,r);t.beginPath(),t.arc(s,l,c,0,Math.PI*2),t.fillStyle=o.trend===1?i.colors[0]:i.colors[1]??`#e8505b`,t.fill()}}},_n=class extends P{descriptor={id:`supertrend`,name:`Supertrend`,placement:`overlay`,defaultConfig:{period:10,multiplier:3},shortName:`Supertrend`,plots:[{key:`value`,title:`Supertrend`,color:0,tone:{field:`trend`},downColor:1}]};calculate(e,t){let n=L(t,`period`,10,1),r=I(t,`multiplier`,3),i=new F,a=Array(e.length).fill(null);if(e.length<n)return{values:i,series:a};let o=[e[0].high-e[0].low];for(let t=1;t<e.length;t++)o.push(Math.max(e[t].high-e[t].low,Math.abs(e[t].high-e[t-1].close),Math.abs(e[t].low-e[t-1].close)));let s=0;for(let e=0;e<n;e++)s+=o[e];s/=n;let c=0,l=0,u=0,d=0,f=0,p=0,m=1;for(let t=n-1;t<e.length;t++){t>n-1&&(s=(s*(n-1)+o[t])/n);let h=(e[t].high+e[t].low)/2,g=h+r*s,_=h-r*s;c=g<u||e[t-1].close>u?g:u,l=_>d||e[t-1].close<d?_:d,f=p===u?e[t].close<=c?c:l:e[t].close>=l?l:c,m=f===l?1:-1;let v={value:f,trend:m};i.set(e[t].time,v),a[t]=v,u=c,d=l,p=f}return{values:i,series:a}}render(t,n,r,i){let a=n.series;if(!a||i.plots?.value?.visible===!1)return;let{from:o,to:s}=r.visibleRange,c=i.colors[0],l=i.colors[1]??`#e8505b`,u=j(r),d=i.lineWidths[0]+.5;for(let[n,i]of[[c,1],[l,-1]]){let c=new M(t,n,d,u),l=0,f=0,p=!1;for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let o=e.b(t,r),s=e.T(n.value,r);p&&(n.trend??1)===i&&c.segment(l,f,o,s),l=o,f=s,p=!0}c.finish()}}},vn=class extends P{descriptor={id:`keltner`,name:`Keltner Channel`,placement:`overlay`,defaultConfig:{emaPeriod:20,atrPeriod:10,multiplier:1.5},shortName:`KC`,plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=L(t,`emaPeriod`,20,1),r=L(t,`atrPeriod`,10,1),i=I(t,`multiplier`,1.5),a=new F;if(e.length<Math.max(n,r))return{values:a};let o=2/(n+1),s=e[0].close,c=[s];for(let t=1;t<e.length;t++)s=(e[t].close-s)*o+s,c.push(s);let l=[e[0].high-e[0].low];for(let t=1;t<e.length;t++)l.push(Math.max(e[t].high-e[t].low,Math.abs(e[t].high-e[t-1].close),Math.abs(e[t].low-e[t-1].close)));let u=0;for(let e=0;e<r;e++)u+=l[e];u/=r;let d=Array(e.length).fill(null),f=Math.max(n,r)-1;for(let t=f;t<e.length;t++){t>f&&(u=(u*(r-1)+l[t])/r);let n={middle:c[t],upper:c[t]+i*u,lower:c[t]-i*u};a.set(e[t].time,n),d[t]=n}return{values:a,series:d}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=[],u=[],d=[];for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n)continue;let r=e.b(t,i);n.upper!==void 0&&l.push({x:r,y:e.T(n.upper,i)}),n.middle!==void 0&&u.push({x:r,y:e.T(n.middle,i)}),n.lower!==void 0&&d.push({x:r,y:e.T(n.lower,i)})}this.drawBand(n,l,d,(0,t.withAlpha)(a.colors[0],.08)),this.drawLine(n,l,a.colors[0],a.lineWidths[0],N(a,`upper`,a.lineWidths[0])),this.drawLine(n,u,a.colors[1]??a.colors[0],a.lineWidths[0],N(a,`middle`,a.lineWidths[0])),this.drawLine(n,d,a.colors[0],a.lineWidths[0],N(a,`lower`,a.lineWidths[0]))}},yn=class extends P{descriptor={id:`donchian`,name:`Donchian Channel`,placement:`overlay`,defaultConfig:{period:20},shortName:`DC`,plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null);for(let t=n-1;t<e.length;t++){let a=-1/0,o=1/0;for(let r=t-n+1;r<=t;r++)e[r].high>a&&(a=e[r].high),e[r].low<o&&(o=e[r].low);let s={upper:a,middle:(a+o)/2,lower:o};r.set(e[t].time,s),i[t]=s}return{values:r,series:i}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=[],u=[],d=[];for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n)continue;let r=e.b(t,i);n.upper!==void 0&&l.push({x:r,y:e.T(n.upper,i)}),n.middle!==void 0&&u.push({x:r,y:e.T(n.middle,i)}),n.lower!==void 0&&d.push({x:r,y:e.T(n.lower,i)})}this.drawBand(n,l,d,(0,t.withAlpha)(a.colors[0],.08)),this.drawLine(n,l,a.colors[0],a.lineWidths[0],N(a,`upper`,a.lineWidths[0])),this.drawLine(n,u,a.colors[1]??`#7d8696`,1,N(a,`middle`,1)),this.drawLine(n,d,a.colors[0],a.lineWidths[0],N(a,`lower`,a.lineWidths[0]))}},bn=[`s3`,`s2`,`s1`,`pp`,`r1`,`r2`,`r3`],xn=[`traditional`,`fibonacci`,`woodie`,`classic`,`camarilla`,`dm`],Sn=class extends P{descriptor={id:`pivots`,name:`Pivot Points`,placement:`overlay`,defaultConfig:{lookback:24,type:`traditional`},shortName:`Pivots`,inputs:{lookback:{min:1},type:{options:xn}},plots:[{key:`r3`,title:`R3`,color:1},{key:`r2`,title:`R2`,color:1},{key:`r1`,title:`R1`,color:1},{key:`pp`,title:`P`,color:0},{key:`s1`,title:`S1`,color:2},{key:`s2`,title:`S2`,color:2},{key:`s3`,title:`S3`,color:2}]};calculate(e,t){let n=L(t,`lookback`,24,1),r=xn.includes(t.params.type)?t.params.type:`traditional`,i=new F,a=Array(e.length).fill(null);if(e.length<=n)return{values:i,series:a};for(let t=n;t<e.length;t++){let o=-1/0,s=1/0;for(let r=t-n;r<t;r++)e[r].high>o&&(o=e[r].high),e[r].low<s&&(s=e[r].low);let c=Cn(r,e[t-n].open,o,s,e[t-1].close);i.set(e[t].time,c),a[t]=c}return{values:i,series:a}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=a.colors[0],u=a.colors[1]??`#e8505b`,d=a.colors[2]??`#1fa874`,f=a.lineWidths[0],p=e=>e===`pp`?l:e.startsWith(`r`)?u:d;for(let r of bn){let l=a.plots?.[r];if(l?.visible===!1)continue;n.beginPath(),n.strokeStyle=p(r),n.lineWidth=r===`pp`?f:Math.max(1,f-1),n.setLineDash((0,t.lineDash)(l?.lineStyle??(r===`pp`?`solid`:`dashed`),[4,3],n.lineWidth));let u=!1;for(let t=s;t<=c&&t<o.length;t++){let a=o[t]?.[r];if(a===void 0)continue;let s=e.b(t,i),c=e.T(a,i);u?n.lineTo(s,c):(n.moveTo(s,c),u=!0)}n.stroke(),n.setLineDash([])}}};function Cn(e,t,n,r,i){let a=n-r;if(e===`dm`){let e=i<t?n+2*r+i:i>t?2*n+r+i:n+r+2*i;return{pp:e/4,r1:e/2-r,s1:e/2-n}}if(e===`camarilla`){let e=a*1.1;return{pp:(n+r+i)/3,r1:i+e/12,s1:i-e/12,r2:i+e/6,s2:i-e/6,r3:i+e/4,s3:i-e/4}}let o=e===`woodie`?(n+r+2*i)/4:(n+r+i)/3;if(e===`fibonacci`)return{pp:o,r1:o+.382*a,s1:o-.382*a,r2:o+.618*a,s2:o-.618*a,r3:o+a,s3:o-a};let s=2*o-r,c=2*o-n;return e===`classic`?{pp:o,r1:s,s1:c,r2:o+a,s2:o-a,r3:o+2*a,s3:o-2*a}:{pp:o,r1:s,s1:c,r2:o+a,s2:o-a,r3:n+2*(o-r),s3:r-2*(n-o)}}var wn=class extends P{descriptor={id:`avwap`,name:`Anchored VWAP`,placement:`overlay`,defaultConfig:{anchorTime:0},shortName:`AVWAP`,plots:[{key:`value`,title:`AVWAP`,color:0}]};calculate(e,t){let n=I(t,`anchorTime`,0),r=new F,i=Array(e.length).fill(null),a=0;if(n>0&&(a=e.findIndex(e=>e.time>=n),a<0))return{values:r,series:i};let o=0,s=0;for(let t=a;t<e.length;t++){let n=(e[t].high+e[t].low+e[t].close)/3;if(o+=e[t].volume,s+=n*e[t].volume,o>0){let n={value:s/o};r.set(e[t].time,n),i[t]=n}}return{values:r,series:i}}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},Tn=class extends P{descriptor={id:`zigzag`,name:`ZigZag`,placement:`overlay`,defaultConfig:{deviation:5},shortName:`ZigZag`,plots:[{key:`pivot`,title:`Pivot`,color:0}]};calculate(e,t){let n=Math.max(.01,I(t,`deviation`,5))/100,r=new F,i=Array(e.length).fill(null);if(e.length<2)return{values:r,series:i,meta:{pivots:[]}};let a=[],o=null,s=0,c=e[0].close;for(let t=1;t<e.length;t++){let r=e[t].high,i=e[t].low;if(o===null){r>=c*(1+n)?(a.push({idx:s,price:c,type:`low`}),o=`up`,s=t,c=r):i<=c*(1-n)&&(a.push({idx:s,price:c,type:`high`}),o=`down`,s=t,c=i);continue}o===`up`?r>c?(s=t,c=r):i<=c*(1-n)&&(a.push({idx:s,price:c,type:`high`}),o=`down`,s=t,c=i):i<c?(s=t,c=i):r>=c*(1+n)&&(a.push({idx:s,price:c,type:`low`}),o=`up`,s=t,c=r)}a.push({idx:s,price:c,type:o===`up`?`high`:`low`});for(let t of a){let n={pivot:t.price};r.set(e[t.idx].time,n),i[t.idx]=n}return{values:r,series:i,meta:{pivots:a}}}render(t,n,r,i){if(i.plots?.pivot?.visible===!1)return;let a=n.meta?.pivots;if(!(!a||a.length<2)){t.beginPath(),t.strokeStyle=i.colors[0],t.lineWidth=i.lineWidths[0],t.lineJoin=`round`;for(let n=0;n<a.length;n++){let i=a[n],o=e.b(i.idx,r),s=e.T(i.price,r);n===0?t.moveTo(o,s):t.lineTo(o,s)}t.stroke()}}},En=class extends P{descriptor={id:`lrc`,name:`Linear Regression Channel`,placement:`overlay`,defaultConfig:{period:100,stdDev:2,source:`close`},shortName:`LRC`,inputs:{source:{source:!0}},plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=L(t,`period`,100,2),r=I(t,`stdDev`,2),i=new F,a=Array(e.length).fill(null);if(e.length<n)return{values:i,series:a};for(let t=n-1;t<e.length;t++){let o=t-n+1,s=0,c=0,l=0,u=0;for(let t=0;t<n;t++){let n=t,r=e[o+t].close;s+=n,c+=r,l+=n*r,u+=n*n}let d=n*u-s*s;if(d===0)continue;let f=(n*l-s*c)/d,p=(c-f*s)/n,m=0;for(let t=0;t<n;t++){let n=f*t+p,r=e[o+t].close-n;m+=r*r}let h=Math.sqrt(m/n),g=f*(n-1)+p,_={middle:g,upper:g+r*h,lower:g-r*h,slope:f};i.set(e[t].time,_),a[t]=_}return{values:i,series:a}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=[],u=[],d=[];for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n)continue;let r=e.b(t,i);n.middle!==void 0&&u.push({x:r,y:e.T(n.middle,i)}),n.upper!==void 0&&l.push({x:r,y:e.T(n.upper,i)}),n.lower!==void 0&&d.push({x:r,y:e.T(n.lower,i)})}this.drawBand(n,l,d,(0,t.withAlpha)(a.colors[0],.08)),this.drawLine(n,l,a.colors[0],a.lineWidths[0],N(a,`upper`,a.lineWidths[0])),this.drawLine(n,u,a.colors[1]??a.colors[0],a.lineWidths[0],N(a,`middle`,a.lineWidths[0])),this.drawLine(n,d,a.colors[0],a.lineWidths[0],N(a,`lower`,a.lineWidths[0]))}},Dn=class extends P{descriptor={id:`hma`,name:`Hull Moving Average`,placement:`overlay`,defaultConfig:{period:21,source:`close`},shortName:`HMA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`HMA`,color:0}]};calculate(e,t){let n=L(t,`period`,21,2),r=new F,i=Array(e.length).fill(null);if(e.length<n)return{values:r,series:i};let a=e.map(e=>e.close),o=Math.max(2,Math.floor(n/2)),s=Math.max(2,Math.floor(Math.sqrt(n))),c=On(a,n),l=On(a,o),u=kn(a.map((e,t)=>c[t]===null||l[t]===null?null:2*l[t]-c[t]),s);for(let t=0;t<e.length;t++){if(u[t]===null)continue;let n={value:u[t]};r.set(e[t].time,n),i[t]=n}return{values:r,series:i}}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}};function On(e,t){let n=Array(e.length).fill(null);if(e.length<t)return n;let r=t*(t+1)/2;for(let i=t-1;i<e.length;i++){let a=0;for(let n=0;n<t;n++)a+=e[i-n]*(t-n);n[i]=a/r}return n}function kn(e,t){let n=Array(e.length).fill(null),r=t*(t+1)/2;for(let i=t-1;i<e.length;i++){let a=0,o=!0;for(let n=0;n<t;n++){let r=e[i-n];if(r===null){o=!1;break}a+=r*(t-n)}o&&(n[i]=a/r)}return n}var An=class extends P{descriptor={id:`mtfma`,name:`MTF Moving Average`,placement:`overlay`,defaultConfig:{period:50,timeframe:`1d`,source:`close`},shortName:`MTF MA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`MA`,color:0}]};calculate(e,n){let r=L(n,`period`,50,1),i=String(n.params.timeframe??`1d`),a=new F,o=Array(e.length).fill(null);if(e.length===0)return{values:a,series:o};let s=[],c=(0,t.timeframeBucketStart)(e[0].time,i),l=e[0].close,u=null,d=()=>{if(s.length<r)return;let e=0;for(let t=s.length-r;t<s.length;t++)e+=s[t];u=e/r};for(let n=0;n<e.length;n++){let r=(0,t.timeframeBucketStart)(e[n].time,i);if(r!==c&&(s.push(l),d(),c=r),l=e[n].close,u!==null){let t={value:u};a.set(e[n].time,t),o[n]=t}}return{values:a,series:o}}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},jn=class extends P{descriptor={id:`svwap`,name:`Session VWAP`,placement:`overlay`,defaultConfig:{bands:1},shortName:`SVWAP`,plots:[{key:`value`,title:`VWAP`,color:0},{key:`u1`,title:`+1σ`,color:1},{key:`l1`,title:`−1σ`,color:1},{key:`u2`,title:`+2σ`,color:1},{key:`l2`,title:`−2σ`,color:1},{key:`u3`,title:`+3σ`,color:1},{key:`l3`,title:`−3σ`,color:1}]};calculate(e,n){let r=Math.min(3,L(n,`bands`,1,0)),i=new F,a=Array(e.length).fill(null);if(e.length===0)return{values:i,series:a};let o=(0,t.timeframeBucketStart)(e[0].time,`1d`),s=0,c=0,l=0;for(let n=0;n<e.length;n++){let u=e[n],d=(0,t.timeframeBucketStart)(u.time,`1d`);d!==o&&(s=0,c=0,l=0,o=d);let f=(u.high+u.low+u.close)/3;if(s+=f*u.volume,c+=f*f*u.volume,l+=u.volume,l>0){let e=s/l,t={value:e,session:o};if(r>0){let n=Math.max(0,c/l-e*e),i=Math.sqrt(n);for(let n=1;n<=r;n++)t[`u${n}`]=e+n*i,t[`l${n}`]=e-n*i}i.set(u.time,t),a[n]=t}}return{values:i,series:a}}render(e,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange;e.globalAlpha=.55,e.lineWidth=1,e.strokeStyle=i.colors[1]??i.colors[0];let c=n=>{let c=i.plots?.[n];c?.visible!==!1&&(e.setLineDash(c?.lineStyle?(0,t.lineDash)(c.lineStyle,[4,3],1):[4,3]),this.strokeBandSeries(e,a,r,o,s,e=>e[n]))};for(let e=1;e<=3;e++)c(`u${e}`),c(`l${e}`);e.setLineDash([]),e.globalAlpha=1;let l=i.plots?.value;l?.visible!==!1&&(e.strokeStyle=i.colors[0],e.lineWidth=i.lineWidths[0],e.lineJoin=`round`,e.setLineDash((0,t.lineDash)(l?.lineStyle??`solid`,[6,4],i.lineWidths[0])),this.strokeBandSeries(e,a,r,o,s,e=>e.value),e.setLineDash([]))}strokeBandSeries(t,n,r,i,a,o){let s=new M(t,String(t.strokeStyle),t.lineWidth,j(r)),c;for(let t=i;t<=a&&t<n.length;t++){let i=n[t],a=i?o(i):void 0;if(i===null||a===void 0){s.gap();continue}let l=e.b(t,r),u=e.T(a,r);i.session!==c&&s.gap(),s.add(l,u),c=i.session}s.finish()}},Mn=class extends P{descriptor={id:`chandelier`,name:`Chandelier Exit`,placement:`overlay`,defaultConfig:{period:22,multiplier:3},shortName:`CE`,plots:[{key:`long`,title:`Long`,color:0},{key:`short`,title:`Short`,color:1}]};calculate(e,t){let n=L(t,`period`,22,1),r=I(t,`multiplier`,3),i=new F,a=Array(e.length).fill(null),o=e.length;if(o<=n)return{values:i,series:a};let s=Array(o).fill(0);for(let t=1;t<o;t++){let n=e[t-1].close;s[t]=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-n),Math.abs(e[t].low-n))}let c=0;for(let e=1;e<=n;e++)c+=s[e];c/=n;for(let t=n;t<o;t++){t>n&&(c=(c*(n-1)+s[t])/n);let o=-1/0,l=1/0;for(let r=t-n+1;r<=t;r++)e[r].high>o&&(o=e[r].high),e[r].low<l&&(l=e[r].low);let u={long:o-r*c,short:l+r*c};i.set(e[t].time,u),a[t]=u}return{values:i,series:a}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=(r,l)=>{let u=a.plots?.[r];if(u?.visible===!1)return;n.beginPath(),n.strokeStyle=l,n.lineWidth=a.lineWidths[0],n.lineJoin=`round`,n.setLineDash(u?.lineStyle?(0,t.lineDash)(u.lineStyle,[5,3],a.lineWidths[0]):[5,3]);let d=!1;for(let t=s;t<=c&&t<o.length;t++){let a=o[t];if(!a||a[r]===void 0){d=!1;continue}let s=e.b(t,i),c=e.T(a[r],i);d?n.lineTo(s,c):(n.moveTo(s,c),d=!0)}n.stroke(),n.setLineDash([])};l(`long`,a.colors[0]??`#1fa874`),l(`short`,a.colors[1]??`#e8505b`)}},Nn=class extends P{descriptor={id:`alligator`,name:`Alligator`,placement:`overlay`,defaultConfig:{jaw:13,teeth:8,lips:5,jawShift:8,teethShift:5,lipsShift:3},shortName:`Alligator`,plots:[{key:`jaw`,title:`Jaw`,color:0},{key:`teeth`,title:`Teeth`,color:1},{key:`lips`,title:`Lips`,color:2}]};calculate(e,t){let n=L(t,`jaw`,13,1),r=L(t,`teeth`,8,1),i=L(t,`lips`,5,1),a=L(t,`jawShift`,8,0),o=L(t,`teethShift`,5,0),s=L(t,`lipsShift`,3,0),c=new F,l=e.length,u=Array(l).fill(null);if(l===0)return{values:c,series:u};let d=e.map(e=>(e.high+e.low)/2),f=Pn(d,n),p=Pn(d,r),m=Pn(d,i),h=Array(l).fill(void 0),g=Array(l).fill(void 0),_=Array(l).fill(void 0);for(let e=0;e<l;e++)f[e]!==void 0&&e+a<l&&(h[e+a]=f[e]),p[e]!==void 0&&e+o<l&&(g[e+o]=p[e]),m[e]!==void 0&&e+s<l&&(_[e+s]=m[e]);for(let t=0;t<l;t++){if(h[t]===void 0&&g[t]===void 0&&_[t]===void 0)continue;let n={};h[t]!==void 0&&(n.jaw=h[t]),g[t]!==void 0&&(n.teeth=g[t]),_[t]!==void 0&&(n.lips=_[t]),c.set(e[t].time,n),u[t]=n}return{values:c,series:u}}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=(n,c)=>{let l=N(i,n,i.lineWidths[0]);if(!l.visible)return;let u=new M(t,c,i.lineWidths[0],j(r),l.dash);for(let t=o;t<=s&&t<a.length;t++){let i=a[t];if(!i||i[n]===void 0){u.gap();continue}let o=e.b(t,r),s=e.T(i[n],r);u.add(o,s)}u.finish()};c(`jaw`,i.colors[0]??`#4c8dff`),c(`teeth`,i.colors[1]??`#e8505b`),c(`lips`,i.colors[2]??`#1fa874`)}};function Pn(e,t){let n=e.length,r=Array(n).fill(void 0);if(n<t)return r;let i=0;for(let n=0;n<t;n++)i+=e[n];let a=i/t;r[t-1]=a;for(let i=t;i<n;i++)a=(a*(t-1)+e[i])/t,r[i]=a;return r}var Fn=class extends P{descriptor={id:`vwma`,name:`Volume Weighted Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`VWMA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`VWMA`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null),a=0,o=0;for(let t=0;t<e.length;t++){let s=e[t].close*e[t].volume;if(a+=s,o+=e[t].volume,t>=n){let r=e[t-n];a-=r.close*r.volume,o-=r.volume}if(t>=n-1&&o>0){let n={value:a/o};r.set(e[t].time,n),i[t]=n}}return{values:r,series:i}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=L(t,`period`,20,1);for(let t=r;t<e.length;t++){if(t<i-1){this.writePoint(n,e,t,null);continue}let r=0,a=0;for(let n=t-i+1;n<=t;n++)r+=e[n].close*e[n].volume,a+=e[n].volume;this.writePoint(n,e,t,a>0?{value:r/a}:null)}return n}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},In=class extends P{descriptor={id:`wma`,name:`Weighted Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`WMA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`WMA`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null),a=n*(n+1)/2,o=0,s=0;for(let t=0;t<e.length;t++){let c=e[t].close;if(s+=c*n-o,o+=c,t>=n&&(o-=e[t-n].close),t>=n-1){let n={value:s/a};r.set(e[t].time,n),i[t]=n}}return{values:r,series:i}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=L(t,`period`,20,1),a=i*(i+1)/2;for(let t=r;t<e.length;t++){if(t<i-1){this.writePoint(n,e,t,null);continue}let r=0,o=t-i+1;for(let t=0;t<i;t++)r+=e[o+t].close*(t+1);this.writePoint(n,e,t,{value:r/a})}return n}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},Ln=class extends P{descriptor={id:`envelope`,name:`Moving Average Envelope`,placement:`overlay`,defaultConfig:{period:20,percent:2.5,source:`close`},shortName:`Env`,inputs:{source:{source:!0}},plots:[{key:`upper`,title:`Upper`,color:0},{key:`basis`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=I(t,`percent`,2.5)/100,i=new F,a=Array(e.length).fill(null),o=0;for(let t=0;t<e.length;t++)if(o+=e[t].close,t>=n&&(o-=e[t-n].close),t>=n-1){let s=o/n,c={basis:s,upper:s*(1+r),lower:s*(1-r)};i.set(e[t].time,c),a[t]=c}return{values:i,series:a}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=L(t,`period`,20,1),a=I(t,`percent`,2.5)/100;for(let t=r;t<e.length;t++){if(t<i-1){this.writePoint(n,e,t,null);continue}let r=0;for(let n=t-i+1;n<=t;n++)r+=e[n].close;let o=r/i;this.writePoint(n,e,t,{basis:o,upper:o*(1+a),lower:o*(1-a)})}return n}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=[],u=[],d=[];for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n||n.upper===void 0)continue;let r=e.b(t,i);l.push({x:r,y:e.T(n.upper,i)}),u.push({x:r,y:e.T(n.lower,i)}),d.push({x:r,y:e.T(n.basis,i)})}this.drawBand(n,l,u,(0,t.withAlpha)(a.colors[0],.08)),this.drawLine(n,l,a.colors[0],a.lineWidths[0],N(a,`upper`,a.lineWidths[0])),this.drawLine(n,u,a.colors[0],a.lineWidths[0],N(a,`lower`,a.lineWidths[0])),this.drawLine(n,d,a.colors[1]??a.colors[0],a.lineWidths[0],N(a,`basis`,a.lineWidths[0]))}};function Rn(e,t){let n=2/(t+1),r=Array(e.length).fill(null),i=0,a=0;for(let o=0;o<e.length;o++){if(o<t-1){a+=e[o];continue}i=o===t-1?(a+e[o])/t:(e[o]-i)*n+i,r[o]=i}return r}function zn(e,t,n){let r=Array(n).fill(null);for(let n=0;n<e.length;n++)e[n]!==null&&(r[t[n]]=e[n]);return r}function Bn(e){let t=[],n=[];for(let r=0;r<e.length;r++)e[r]!==null&&(t.push(e[r]),n.push(r));return{values:t,indices:n}}var Vn=class extends P{descriptor={id:`tema`,name:`Triple EMA`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`TEMA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`TEMA`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null),a=Rn(e.map(e=>e.close),n),o=Bn(a),s=zn(Rn(o.values,n),o.indices,e.length),c=Bn(s),l=zn(Rn(c.values,n),c.indices,e.length);for(let t=0;t<e.length;t++){let n=a[t],o=s[t],c=l[t];if(n===null||o===null||c===null)continue;let u={value:3*n-3*o+c};r.set(e[t].time,u),i[t]=u}return{values:r,series:i}}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},Hn=class extends P{descriptor={id:`ao`,name:`Awesome Oscillator`,placement:`panel`,defaultConfig:{fast:5,slow:34},shortName:`AO`,plots:[{key:`value`,title:`AO`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}]};calculate(e,t){let n=L(t,`fast`,5,1),r=L(t,`slow`,34,1),i=new F,a=Array(e.length).fill(null);if(e.length<r)return{values:i,series:a};let o=Array(e.length);for(let t=0;t<e.length;t++)o[t]=(e[t].high+e[t].low)/2;let s=0,c=0,l;for(let t=0;t<e.length;t++)if(c+=o[t],t>=r&&(c-=o[t-r]),s+=o[t],t>=n&&(s-=o[t-n]),t>=r-1){let o=s/n-c/r,u={value:o,up:+(l===void 0||o>=l)};i.set(e[t].time,u),a[t]=u,l=o}return{values:i,series:a}}},Un=class extends P{descriptor={id:`chaikinOsc`,name:`Chaikin Oscillator`,placement:`panel`,defaultConfig:{fast:3,slow:10},shortName:`Chaikin Osc`,plots:[{key:`value`,title:`Chaikin`,color:0,kind:`histogram`,tone:`sign`,downColor:1}]};calculate(e,t){let n=L(t,`fast`,3,1),r=L(t,`slow`,10,1),i=new F,a=Array(e.length).fill(null);if(e.length<r)return{values:i,series:a};let o=2/(n+1),s=2/(r+1),c=0,l=0,u=0;for(let t=0;t<e.length;t++){let{high:n,low:d,close:f,volume:p}=e[t],m=n-d,h=m===0?0:(f-d-(n-f))/m;if(c+=h*p,t===0?(l=c,u=c):(l=(c-l)*o+l,u=(c-u)*s+u),t>=r-1){let n={value:l-u,adl:c};i.set(e[t].time,n),a[t]=n}}return{values:i,series:a}}},Wn=class extends P{descriptor={id:`rsi`,name:`Relative Strength Index`,placement:`panel`,defaultConfig:{period:14,source:`close`},shortName:`RSI`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`RSI`,color:0}],scale:{min:0,max:100},levels:[30,70]};smoothing=new WeakMap;calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null),a={values:r,series:i};if(e.length<n+1)return a;let o=[],s=[],c=0,l=0;for(let t=1;t<=n;t++){let n=e[t].close-e[t-1].close;n>0?c+=n:l-=n}c/=n,l/=n,o[n]=c,s[n]=l;let u={value:l===0?100:100-100/(1+c/l)};r.set(e[n].time,u),i[n]=u;for(let t=n+1;t<e.length;t++){let a=e[t].close-e[t-1].close,u=a>0?a:0,d=a<0?-a:0;c=(c*(n-1)+u)/n,l=(l*(n-1)+d)/n,o[t]=c,s[t]=l;let f={value:l===0?100:100-100/(1+c/l)};r.set(e[t].time,f),i[t]=f}return this.smoothing.set(a,{gain:o,loss:s}),a}update(e,t,n,r){let i=L(t,`period`,14,1),a=this.smoothing.get(n);if(!a||r<=i||!this.canResume(e,n,r))return null;let o=a.gain[r-1],s=a.loss[r-1];if(o===void 0||s===void 0)return null;for(let t=r;t<e.length;t++){let r=e[t].close-e[t-1].close,c=r>0?r:0,l=r<0?-r:0;o=(o*(i-1)+c)/i,s=(s*(i-1)+l)/i,a.gain[t]=o,a.loss[t]=s;let u=s===0?100:100-100/(1+o/s);this.writePoint(n,e,t,{value:u})}return n}},Gn=class extends P{descriptor={id:`macd`,name:`MACD`,placement:`panel`,defaultConfig:{fast:12,slow:26,signal:9,source:`close`},shortName:`MACD`,inputs:{source:{source:!0}},plots:[{key:`histogram`,title:`Histogram`,color:2,kind:`histogram`,tone:`sign`,downColor:3},{key:`macd`,title:`MACD`,color:0},{key:`signal`,title:`Signal`,color:1}]};emas=new WeakMap;calculate(e,t){let n=L(t,`fast`,12,1),r=L(t,`slow`,26,1),i=L(t,`signal`,9,1),a=new F,o=Array(e.length).fill(null),s={values:a,series:o};if(e.length<r)return s;let c=2/(n+1),l=2/(r+1),u=2/(i+1),d=Array(e.length),f=Array(e.length),p=e[0].close,m=e[0].close,h=0,g=!1;for(let t=0;t<e.length;t++){let n=e[t].close;if(t===0?(p=n,m=n):(p=(n-p)*c+p,m=(n-m)*l+m),d[t]=p,f[t]=m,t>=r-1){let n=p-m;g?h=(n-h)*u+h:(h=n,g=!0);let r=n-h,i={macd:n,signal:h,histogram:r};a.set(e[t].time,i),o[t]=i}}return this.emas.set(s,{fast:d,slow:f}),s}update(e,t,n,r){let i=L(t,`fast`,12,1),a=L(t,`slow`,26,1),o=L(t,`signal`,9,1),s=this.emas.get(n);if(!s||r<a||!this.canResume(e,n,r))return null;let c=s.fast[r-1],l=s.slow[r-1],u=n.series[r-1]?.signal;if(c===void 0||l===void 0||u===void 0)return null;let d=2/(i+1),f=2/(a+1),p=2/(o+1);for(let t=r;t<e.length;t++){let r=e[t].close;c=(r-c)*d+c,l=(r-l)*f+l,s.fast[t]=c,s.slow[t]=l;let i=c-l;u=(i-u)*p+u,this.writePoint(n,e,t,{macd:i,signal:u,histogram:i-u})}return n}},Kn=class extends P{descriptor={id:`stochastic`,name:`Stochastic Oscillator`,placement:`panel`,defaultConfig:{kPeriod:14,dPeriod:3,smooth:3},shortName:`Stoch`,plots:[{key:`k`,title:`%K`,color:0},{key:`d`,title:`%D`,color:1}],scale:{min:0,max:100},levels:[20,80]};calculate(e,t){let n=L(t,`kPeriod`,14,1),r=L(t,`dPeriod`,3,1),i=L(t,`smooth`,3,1),a=new F,o=Array(e.length).fill(null);if(e.length<n)return{values:a,series:o};let s=[];for(let t=0;t<e.length;t++){if(t<n-1){s.push(0);continue}let r=-1/0,i=1/0;for(let a=t-n+1;a<=t;a++)e[a].high>r&&(r=e[a].high),e[a].low<i&&(i=e[a].low);s.push(r===i?50:(e[t].close-i)/(r-i)*100)}let c=[];for(let e=0;e<s.length;e++){if(e<n-1+i-1){c.push(0);continue}let t=0;for(let n=e-i+1;n<=e;n++)t+=s[n];c.push(t/i)}let l=n-1+i-1;for(let t=l;t<c.length;t++){let n={k:c[t]};if(t>=l+r-1){let e=0;for(let n=t-r+1;n<=t;n++)e+=c[n];n.d=e/r}a.set(e[t].time,n),o[t]=n}return{values:a,series:o}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=L(t,`kPeriod`,14,1),a=L(t,`dPeriod`,3,1),o=L(t,`smooth`,3,1),s=i-1+o-1,c=t=>{let n=-1/0,r=1/0;for(let a=t-i+1;a<=t;a++)e[a].high>n&&(n=e[a].high),e[a].low<r&&(r=e[a].low);return n===r?50:(e[t].close-r)/(n-r)*100},l=e=>{let t=0;for(let n=e-o+1;n<=e;n++)t+=c(n);return t/o};for(let t=r;t<e.length;t++){if(t<s||e.length<i){this.writePoint(n,e,t,null);continue}let r={k:l(t)};if(t>=s+a-1){let e=0;for(let n=t-a+1;n<=t;n++)e+=l(n);r.d=e/a}this.writePoint(n,e,t,r)}return n}},qn=class extends P{descriptor={id:`atr`,name:`Average True Range`,placement:`panel`,defaultConfig:{period:14},shortName:`ATR`,plots:[{key:`value`,title:`ATR`,color:0}]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null);if(e.length<Math.max(2,n))return{values:r,series:i};let a=[e[0].high-e[0].low];for(let t=1;t<e.length;t++){let n=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-e[t-1].close),Math.abs(e[t].low-e[t-1].close));a.push(n)}let o=0;for(let e=0;e<n;e++)o+=a[e];o/=n;let s={value:o};r.set(e[n-1].time,s),i[n-1]=s;for(let t=n;t<e.length;t++){o=(o*(n-1)+a[t])/n;let s={value:o};r.set(e[t].time,s),i[t]=s}return{values:r,series:i}}update(e,t,n,r){let i=L(t,`period`,14,1);if(r<i||!this.canResume(e,n,r))return null;let a=n.series[r-1]?.value;if(a===void 0)return null;for(let t=r;t<e.length;t++){let r=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-e[t-1].close),Math.abs(e[t].low-e[t-1].close));a=(a*(i-1)+r)/i,this.writePoint(n,e,t,{value:a})}return n}},Jn=class extends P{descriptor={id:`adx`,name:`Average Directional Index`,placement:`panel`,defaultConfig:{period:14},shortName:`ADX`,plots:[{key:`adx`,title:`ADX`,color:0},{key:`plusDI`,title:`+DI`,color:1},{key:`minusDI`,title:`−DI`,color:2}],scale:{min:0}};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null);if(e.length<n*2)return{values:r,series:i};let a=[],o=[],s=[];for(let t=1;t<e.length;t++){let n=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-e[t-1].close),Math.abs(e[t].low-e[t-1].close));a.push(n);let r=e[t].high-e[t-1].high,i=e[t-1].low-e[t].low;o.push(r>i&&r>0?r:0),s.push(i>r&&i>0?i:0)}let c=0,l=0,u=0;for(let e=0;e<n;e++)c+=a[e],l+=o[e],u+=s[e];let d=[];for(let t=n;t<a.length;t++){t>n&&(c=c-c/n+a[t],l=l-l/n+o[t],u=u-u/n+s[t]);let f=c===0?0:l/c*100,p=c===0?0:u/c*100,m=f+p,h=m===0?0:Math.abs(f-p)/m*100;d.push(h);let g=t+1,_={plusDI:f,minusDI:p,dx:h};r.set(e[g].time,_),i[g]=_}if(d.length>=n){let t=0;for(let e=0;e<n;e++)t+=d[e];t/=n;let a=n*2;if(a<e.length){let n=r.get(e[a].time);n&&(n.adx=t),i[a]&&(i[a].adx=t)}for(let a=n;a<d.length;a++){t=(t*(n-1)+d[a])/n;let o=a+n+1;if(o<e.length){let n=r.get(e[o].time);n&&(n.adx=t),i[o]&&(i[o].adx=t)}}}return{values:r,series:i}}},Yn=class extends P{descriptor={id:`obv`,name:`On Balance Volume`,placement:`panel`,defaultConfig:{},shortName:`OBV`,plots:[{key:`value`,title:`OBV`,color:0}]};calculate(e,t){let n=new F,r=Array(e.length).fill(null);if(e.length===0)return{values:n,series:r};let i=0,a={value:i};n.set(e[0].time,a),r[0]=a;for(let t=1;t<e.length;t++){e[t].close>e[t-1].close?i+=e[t].volume:e[t].close<e[t-1].close&&(i-=e[t].volume);let a={value:i};n.set(e[t].time,a),r[t]=a}return{values:n,series:r}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=n.series[r-1]?.value;if(i===void 0)return null;for(let t=r;t<e.length;t++)e[t].close>e[t-1].close?i+=e[t].volume:e[t].close<e[t-1].close&&(i-=e[t].volume),this.writePoint(n,e,t,{value:i});return n}},Xn=class extends P{descriptor={id:`williamsR`,name:`Williams %R`,placement:`panel`,defaultConfig:{period:14},shortName:`%R`,plots:[{key:`value`,title:`%R`,color:0}],scale:{min:-100,max:0},levels:[-80,-20]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null);for(let t=n-1;t<e.length;t++){let a=-1/0,o=1/0;for(let r=t-n+1;r<=t;r++)e[r].high>a&&(a=e[r].high),e[r].low<o&&(o=e[r].low);let s={value:a===o?-50:(a-e[t].close)/(a-o)*-100};r.set(e[t].time,s),i[t]=s}return{values:r,series:i}}},Zn=class extends P{descriptor={id:`cci`,name:`Commodity Channel Index`,placement:`panel`,defaultConfig:{period:20},shortName:`CCI`,plots:[{key:`value`,title:`CCI`,color:0}],levels:[-100,0,100]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null);for(let t=n-1;t<e.length;t++){let a=0;for(let r=t-n+1;r<=t;r++)a+=(e[r].high+e[r].low+e[r].close)/3;let o=a/n,s=0;for(let r=t-n+1;r<=t;r++){let t=(e[r].high+e[r].low+e[r].close)/3;s+=Math.abs(t-o)}let c=s/n,l=(e[t].high+e[t].low+e[t].close)/3,u={value:c===0?0:(l-o)/(.015*c)};r.set(e[t].time,u),i[t]=u}return{values:r,series:i}}},Qn=class extends P{descriptor={id:`mfi`,name:`Money Flow Index`,placement:`panel`,defaultConfig:{period:14},shortName:`MFI`,plots:[{key:`value`,title:`MFI`,color:0}],scale:{min:0,max:100},levels:[20,80]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null);if(e.length<n+1)return{values:r,series:i};let a=e.map(e=>(e.high+e.low+e.close)/3),o=a.map((t,n)=>t*e[n].volume);for(let t=n;t<e.length;t++){let s=0,c=0;for(let e=t-n+1;e<=t;e++)a[e]>a[e-1]?s+=o[e]:a[e]<a[e-1]&&(c+=o[e]);let l={value:c===0?100:100-100/(1+s/c)};r.set(e[t].time,l),i[t]=l}return{values:r,series:i}}},$n=class extends P{descriptor={id:`aroon`,name:`Aroon`,placement:`panel`,defaultConfig:{period:25},shortName:`Aroon`,plots:[{key:`up`,title:`Up`,color:0},{key:`down`,title:`Down`,color:1}],scale:{min:0,max:100}};calculate(e,t){let n=L(t,`period`,25,1),r=new F,i=Array(e.length).fill(null);for(let t=n;t<e.length;t++){let a=0,o=0,s=-1/0,c=1/0;for(let r=0;r<=n;r++){let i=t-n+r;e[i].high>s&&(s=e[i].high,a=r),e[i].low<c&&(c=e[i].low,o=r)}let l={up:a/n*100,down:o/n*100};r.set(e[t].time,l),i[t]=l}return{values:r,series:i}}},er=class extends P{descriptor={id:`roc`,name:`Rate of Change`,placement:`panel`,defaultConfig:{period:12,source:`close`},shortName:`ROC`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`ROC`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`period`,12,1),r=new F,i=Array(e.length).fill(null);for(let t=n;t<e.length;t++){let a=e[t-n].close,o={value:a===0?0:(e[t].close-a)/a*100};r.set(e[t].time,o),i[t]=o}return{values:r,series:i}}},tr=class extends P{descriptor={id:`tsi`,name:`True Strength Index`,placement:`panel`,defaultConfig:{longPeriod:25,shortPeriod:13,signalPeriod:7,source:`close`},shortName:`TSI`,inputs:{source:{source:!0}},plots:[{key:`tsi`,title:`TSI`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};emaSmooth(e,t){let n=2/(t+1),r=[e[0]];for(let t=1;t<e.length;t++)r.push((e[t]-r[t-1])*n+r[t-1]);return r}calculate(e,t){let n=L(t,`longPeriod`,25,1),r=L(t,`shortPeriod`,13,1),i=L(t,`signalPeriod`,7,1),a=new F,o=Array(e.length).fill(null);if(e.length<2)return{values:a,series:o};let s=[],c=[];for(let t=1;t<e.length;t++){let n=e[t].close-e[t-1].close;s.push(n),c.push(Math.abs(n))}let l=this.emaSmooth(this.emaSmooth(s,n),r),u=this.emaSmooth(this.emaSmooth(c,n),r),d=[];for(let e=0;e<l.length;e++)d.push(u[e]===0?0:l[e]/u[e]*100);let f=this.emaSmooth(d,i);for(let t=0;t<d.length;t++){let n=t+1;if(n<e.length){let r={tsi:d[t],signal:f[t]};a.set(e[n].time,r),o[n]=r}}return{values:a,series:o}}},nr=class extends P{descriptor={id:`cmf`,name:`Chaikin Money Flow`,placement:`panel`,defaultConfig:{period:20},shortName:`CMF`,plots:[{key:`value`,title:`CMF`,color:0,kind:`histogram`,tone:`sign`,downColor:1}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null);for(let t=n-1;t<e.length;t++){let a=0,o=0;for(let r=t-n+1;r<=t;r++){let t=e[r].high-e[r].low,n=t===0?0:(e[r].close-e[r].low-(e[r].high-e[r].close))/t;a+=n*e[r].volume,o+=e[r].volume}let s={value:o===0?0:a/o};r.set(e[t].time,s),i[t]=s}return{values:r,series:i}}},rr=class extends P{descriptor={id:`voldelta`,name:`Volume Delta`,placement:`panel`,defaultConfig:{mode:0},shortName:`Vol Δ`,plots:[{key:`value`,title:`Delta`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}]};calculate(e,t){let n=I(t,`mode`,0)>=1,r=new F,i=Array(e.length).fill(null),a=0;for(let t=0;t<e.length;t++){let o=e[t],s=o.close>=o.open,c=s?o.volume:-o.volume;a+=c;let l={value:n?a:c,up:+!!s};r.set(o.time,l),i[t]=l}return{values:r,series:i}}},ir=class extends P{descriptor={id:`vortex`,name:`Vortex Indicator`,placement:`panel`,defaultConfig:{period:14},shortName:`VI`,plots:[{key:`viPlus`,title:`VI+`,color:0},{key:`viMinus`,title:`VI−`,color:1}],levels:[1]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null);if(e.length<=n)return{values:r,series:i};let a=Array(e.length).fill(0),o=Array(e.length).fill(0),s=Array(e.length).fill(0);for(let t=1;t<e.length;t++){a[t]=Math.abs(e[t].high-e[t-1].low),o[t]=Math.abs(e[t].low-e[t-1].high);let n=e[t].high,r=e[t].low,i=e[t-1].close;s[t]=Math.max(n-r,Math.abs(n-i),Math.abs(r-i))}let c=0,l=0,u=0;for(let t=1;t<e.length;t++)if(c+=a[t],l+=o[t],u+=s[t],t>n&&(c-=a[t-n],l-=o[t-n],u-=s[t-n]),t>=n&&u>0){let n={viPlus:c/u,viMinus:l/u};r.set(e[t].time,n),i[t]=n}return{values:r,series:i}}},ar=class extends P{descriptor={id:`chop`,name:`Choppiness Index`,placement:`panel`,defaultConfig:{period:14},shortName:`CHOP`,plots:[{key:`value`,title:`CHOP`,color:0}],scale:{min:0,max:100},levels:[38.2,61.8]};calculate(e,t){let n=L(t,`period`,14,2),r=new F,i=Array(e.length).fill(null);if(e.length<=n)return{values:r,series:i};let a=Array(e.length).fill(0);for(let t=1;t<e.length;t++){let n=e[t].high,r=e[t].low,i=e[t-1].close;a[t]=Math.max(n-r,Math.abs(n-i),Math.abs(r-i))}let o=Math.log10(n),s=0;for(let t=1;t<e.length;t++)if(s+=a[t],t>n&&(s-=a[t-n]),t>=n){let a=-1/0,c=1/0;for(let r=t-n+1;r<=t;r++)e[r].high>a&&(a=e[r].high),e[r].low<c&&(c=e[r].low);let l=a-c;if(l>0&&s>0){let n={value:Math.max(0,Math.min(100,100*Math.log10(s/l)/o))};r.set(e[t].time,n),i[t]=n}}return{values:r,series:i}}},or=class extends P{descriptor={id:`uo`,name:`Ultimate Oscillator`,placement:`panel`,defaultConfig:{fast:7,mid:14,slow:28},shortName:`UO`,plots:[{key:`value`,title:`UO`,color:0}],scale:{min:0,max:100},levels:[30,70]};calculate(e,t){let n=L(t,`fast`,7,1),r=L(t,`mid`,14,1),i=L(t,`slow`,28,1),a=new F,o=Array(e.length).fill(null);if(e.length<=i)return{values:a,series:o};let s=Array(e.length).fill(0),c=Array(e.length).fill(0);for(let t=1;t<e.length;t++){let n=e[t-1].close,r=Math.min(e[t].low,n),i=Math.max(e[t].high,n);s[t]=e[t].close-r,c[t]=i-r}let l=(e,t,n)=>{let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i];return r};for(let t=i;t<e.length;t++){let u=sr(l(s,t,n),l(c,t,n)),d=sr(l(s,t,r),l(c,t,r)),f=sr(l(s,t,i),l(c,t,i)),p={value:100*(4*u+2*d+f)/7};a.set(e[t].time,p),o[t]=p}return{values:a,series:o}}};function sr(e,t){return t===0?0:e/t}var cr=class extends P{descriptor={id:`fi`,name:`Force Index`,placement:`panel`,defaultConfig:{period:13},shortName:`EFI`,plots:[{key:`value`,title:`EFI`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`period`,13,1),r=new F,i=Array(e.length).fill(null);if(e.length<2)return{values:r,series:i};let a=2/(n+1),o;for(let t=1;t<e.length;t++){let s=(e[t].close-e[t-1].close)*e[t].volume;if(o=o===void 0?s:s*a+o*(1-a),t>=n){let n={value:o};r.set(e[t].time,n),i[t]=n}}return{values:r,series:i}}},lr=class extends P{descriptor={id:`crsi`,name:`Connors RSI`,placement:`panel`,defaultConfig:{rsiPeriod:3,streakPeriod:2,rankPeriod:100,source:`close`},shortName:`CRSI`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`CRSI`,color:0}],scale:{min:0,max:100},levels:[10,90]};calculate(e,t){let n=L(t,`rsiPeriod`,3,1),r=L(t,`streakPeriod`,2,1),i=L(t,`rankPeriod`,100,1),a=new F,o=Array(e.length).fill(null),s=e.length;if(s<2)return{values:a,series:o};let c=e.map(e=>e.close),l=ur(c,n),u=Array(s).fill(0);for(let e=1;e<s;e++)c[e]>c[e-1]?u[e]=u[e-1]>0?u[e-1]+1:1:c[e]<c[e-1]?u[e]=u[e-1]<0?u[e-1]-1:-1:u[e]=0;let d=ur(u,r),f=Array(s).fill(0);for(let e=1;e<s;e++)f[e]=c[e-1]===0?0:(c[e]-c[e-1])/c[e-1]*100;for(let t=0;t<s;t++){if(t<i+1)continue;let n=l[t],r=d[t];if(n===void 0||r===void 0)continue;let s=0;for(let e=t-i;e<t;e++)f[e]<f[t]&&s++;let c=s/i*100,u={value:(n+r+c)/3};a.set(e[t].time,u),o[t]=u}return{values:a,series:o}}};function ur(e,t){let n=e.length,r=Array(n).fill(void 0);if(n<=t)return r;let i=0,a=0;for(let n=1;n<=t;n++){let t=e[n]-e[n-1];t>=0?i+=t:a-=t}i/=t,a/=t,r[t]=a===0?100:100-100/(1+i/a);for(let o=t+1;o<n;o++){let n=e[o]-e[o-1],s=n>0?n:0,c=n<0?-n:0;i=(i*(t-1)+s)/t,a=(a*(t-1)+c)/t,r[o]=a===0?100:100-100/(1+i/a)}return r}var dr=class extends P{descriptor={id:`coppock`,name:`Coppock Curve`,placement:`panel`,defaultConfig:{longRoc:14,shortRoc:11,wma:10,source:`close`},shortName:`Coppock`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`Coppock`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`longRoc`,14,1),r=L(t,`shortRoc`,11,1),i=L(t,`wma`,10,1),a=new F,o=Array(e.length).fill(null),s=e.length,c=Math.max(n,r);if(s<=c+i)return{values:a,series:o};let l=e.map(e=>e.close),u=(e,t)=>l[e-t]===0?0:(l[e]-l[e-t])/l[e-t]*100,d=Array(s).fill(void 0);for(let e=c;e<s;e++)d[e]=u(e,n)+u(e,r);let f=i*(i+1)/2;for(let t=c+i-1;t<s;t++){let n=0,r=!0;for(let e=0;e<i;e++){let a=d[t-e];if(a===void 0){r=!1;break}n+=a*(i-e)}if(!r)continue;let s={value:n/f};a.set(e[t].time,s),o[t]=s}return{values:a,series:o}}},fr=class extends P{descriptor={id:`kst`,name:`Know Sure Thing`,placement:`panel`,defaultConfig:{roc1:10,roc2:15,roc3:20,roc4:30,sma1:10,sma2:10,sma3:10,sma4:15,signal:9,source:`close`},shortName:`KST`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`KST`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`roc1`,10,1),r=L(t,`roc2`,15,1),i=L(t,`roc3`,20,1),a=L(t,`roc4`,30,1),o=L(t,`sma1`,10,1),s=L(t,`sma2`,10,1),c=L(t,`sma3`,10,1),l=L(t,`sma4`,15,1),u=L(t,`signal`,9,1),d=new F,f=Array(e.length).fill(null),p=e.length;if(p<2)return{values:d,series:f};let m=e.map(e=>e.close),h=mr(pr(m,n),o),g=mr(pr(m,r),s),_=mr(pr(m,i),c),v=mr(pr(m,a),l),y=Array(p).fill(void 0);for(let e=0;e<p;e++)h[e]===void 0||g[e]===void 0||_[e]===void 0||v[e]===void 0||(y[e]=h[e]*1+g[e]*2+_[e]*3+v[e]*4);let b=mr(y,u);for(let t=0;t<p;t++){if(y[t]===void 0)continue;let n={value:y[t]};b[t]!==void 0&&(n.signal=b[t]),d.set(e[t].time,n),f[t]=n}return{values:d,series:f}}};function pr(e,t){let n=Array(e.length).fill(void 0);for(let r=t;r<e.length;r++)n[r]=e[r-t]===0?0:(e[r]-e[r-t])/e[r-t]*100;return n}function mr(e,t){let n=Array(e.length).fill(void 0);for(let r=t-1;r<e.length;r++){let i=0,a=!0;for(let n=r-t+1;n<=r;n++){let t=e[n];if(t===void 0){a=!1;break}i+=t}a&&(n[r]=i/t)}return n}var hr=class extends P{descriptor={id:`elderray`,name:`Elder Ray`,placement:`panel`,defaultConfig:{period:13},shortName:`Elder Ray`,plots:[{key:`bull`,title:`Bull`,color:0,kind:`histogram`},{key:`bear`,title:`Bear`,color:1,kind:`histogram`}]};calculate(e,t){let n=L(t,`period`,13,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a===0)return{values:r,series:i};let o=2/(n+1),s;for(let t=0;t<a;t++)if(s=s===void 0?e[t].close:e[t].close*o+s*(1-o),t>=n-1){let n={bull:e[t].high-s,bear:e[t].low-s};r.set(e[t].time,n),i[t]=n}return{values:r,series:i}}render(t,n,r,i){let a=n.series;if(!a)return;let o=Math.max(0,r.visibleRange.from),s=Math.min(r.visibleRange.to,a.length-1),c=e.E(r),l=c(0),u=Math.max(1,r.barWidth/2),d=[[`bull`,i.colors[0],-u],[`bear`,i.colors[1]??i.colors[0],0]];for(let[n,f,p]of d)if(i.plots?.[n]?.visible!==!1){t.beginPath(),t.fillStyle=f;for(let i=o;i<=s;i++){let o=a[i]?.[n];if(o===void 0||!Number.isFinite(o))continue;let s=c(o);t.rect(e.b(i,r)+p,Math.min(s,l),u,Math.max(1,Math.abs(s-l)))}t.fill()}}},gr=class extends P{descriptor={id:`stc`,name:`Schaff Trend Cycle`,placement:`panel`,defaultConfig:{fast:23,slow:50,cycle:10,source:`close`},shortName:`STC`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`STC`,color:0}],scale:{min:0,max:100},levels:[25,75]};calculate(e,t){let n=L(t,`fast`,23,1),r=L(t,`slow`,50,1),i=L(t,`cycle`,10,1),a=new F,o=Array(e.length).fill(null),s=e.length;if(s===0)return{values:a,series:o};let c=e.map(e=>e.close),l=2/(n+1),u=2/(r+1),d=c[0],f=c[0],p=Array(s);for(let e=0;e<s;e++)d=e===0?c[0]:c[e]*l+d*(1-l),f=e===0?c[0]:c[e]*u+f*(1-u),p[e]=d-f;let m=_r(_r(p,i),i);for(let t=0;t<s;t++){let n=m[t];if(n===void 0)continue;let r={value:Math.max(0,Math.min(100,n))};a.set(e[t].time,r),o[t]=r}return{values:a,series:o}}};function _r(e,t){let n=e.length,r=Array(n).fill(void 0),i;for(let a=0;a<n;a++){if(a<t-1)continue;let n=1/0,o=-1/0,s=!0;for(let r=a-t+1;r<=a;r++){let t=e[r];if(t===void 0){s=!1;break}t<n&&(n=t),t>o&&(o=t)}if(!s||e[a]===void 0)continue;let c=o-n>0?(e[a]-n)/(o-n)*100:50;i=i===void 0?c:i+.5*(c-i),r[a]=i}return r}var vr=class extends P{descriptor={id:`kvo`,name:`Klinger Oscillator`,placement:`panel`,defaultConfig:{fast:34,slow:55,signal:13},shortName:`KVO`,plots:[{key:`value`,title:`KVO`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`fast`,34,1),r=L(t,`slow`,55,1),i=L(t,`signal`,13,1),a=new F,o=Array(e.length).fill(null),s=e.length;if(s<2)return{values:a,series:o};let c=2/(n+1),l=2/(r+1),u=2/(i+1),d,f=1,p=0,m=0,h,g,_;for(let t=0;t<s;t++){let n=e[t],i=n.high+n.low+n.close,s=d===void 0||i>d?1:-1,v=n.high-n.low;m=d===void 0?v:s===f?m+v:p+v;let y=m===0?0:n.volume*Math.abs(2*(v/m-1))*s*100;h=h===void 0?y:y*c+h*(1-c),g=g===void 0?y:y*l+g*(1-l);let b=h-g;if(_=_===void 0?b:b*u+_*(1-u),d=i,f=s,p=v,t>=r){let e={value:b,signal:_};a.set(n.time,e),o[t]=e}}return{values:a,series:o}}},yr=class extends P{descriptor={id:`fisher`,name:`Fisher Transform`,placement:`panel`,defaultConfig:{period:9},shortName:`Fisher`,plots:[{key:`value`,title:`Fisher`,color:0},{key:`trigger`,title:`Trigger`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`period`,9,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<n)return{values:r,series:i};let o=e.map(e=>(e.high+e.low)/2),s=0,c=0;for(let t=n-1;t<a;t++){let a=-1/0,l=1/0;for(let e=t-n+1;e<=t;e++)o[e]>a&&(a=o[e]),o[e]<l&&(l=o[e]);s=.33*(a-l>0?2*(o[t]-l)/(a-l)-1:0)+.67*s,s=Math.max(-.999,Math.min(.999,s));let u=c;c=.5*Math.log((1+s)/(1-s))+.5*c;let d={value:c,trigger:u};r.set(e[t].time,d),i[t]=d}return{values:r,series:i}}},br=class extends P{descriptor={id:`dpo`,name:`Detrended Price Oscillator`,placement:`panel`,defaultConfig:{period:20,source:`close`},shortName:`DPO`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`DPO`,color:0,kind:`histogram`,tone:`sign`,downColor:1}]};calculate(e,t){let n=L(t,`period`,20,2),r=Math.floor(n/2)+1,i=new F,a=Array(e.length).fill(null),o=e.length;if(o<n)return{values:i,series:a};let s=0;for(let t=0;t<o;t++)if(s+=e[t].close,t>=n&&(s-=e[t-n].close),t>=n-1&&t-r>=0){let o=s/n,c={value:e[t-r].close-o};i.set(e[t].time,c),a[t]=c}return{values:i,series:a}}},xr=class extends P{descriptor={id:`bop`,name:`Balance of Power`,placement:`panel`,defaultConfig:{smooth:14},shortName:`BOP`,plots:[{key:`value`,title:`BOP`,color:0}],scale:{min:-1,max:1},levels:[0]};calculate(e,t){let n=L(t,`smooth`,14,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a===0)return{values:r,series:i};let o=Array(a);for(let t=0;t<a;t++){let n=e[t].high-e[t].low;o[t]=n>0?(e[t].close-e[t].open)/n:0}let s=0;for(let t=0;t<a;t++)if(s+=o[t],t>=n&&(s-=o[t-n]),t>=n-1){let a={value:s/n};r.set(e[t].time,a),i[t]=a}return{values:r,series:i}}},Sr=class extends P{descriptor={id:`massindex`,name:`Mass Index`,placement:`panel`,defaultConfig:{ema:9,sum:25},shortName:`Mass`,plots:[{key:`value`,title:`Mass`,color:0}],levels:[26.5,27]};calculate(e,t){let n=L(t,`ema`,9,1),r=L(t,`sum`,25,1),i=new F,a=Array(e.length).fill(null),o=e.length;if(o<r)return{values:i,series:a};let s=2/(n+1),c,l,u=Array(o).fill(0);for(let t=0;t<o;t++){let n=e[t].high-e[t].low;c=c===void 0?n:n*s+c*(1-s),l=l===void 0?c:c*s+l*(1-s),u[t]=l===0?1:c/l}let d=0;for(let t=0;t<o;t++)if(d+=u[t],t>=r&&(d-=u[t-r]),t>=n+r){let n={value:d};i.set(e[t].time,n),a[t]=n}return{values:i,series:a}}},Cr=class extends P{descriptor={id:`cmo`,name:`Chande Momentum`,placement:`panel`,defaultConfig:{period:9,source:`close`},shortName:`CMO`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`CMO`,color:0}],scale:{min:-100,max:100},levels:[-50,0,50]};calculate(e,t){let n=L(t,`period`,9,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<=n)return{values:r,series:i};let o=Array(a).fill(0),s=Array(a).fill(0);for(let t=1;t<a;t++){let n=e[t].close-e[t-1].close;o[t]=n>0?n:0,s[t]=n<0?-n:0}let c=0,l=0;for(let t=1;t<a;t++)if(c+=o[t],l+=s[t],t>n&&(c-=o[t-n],l-=s[t-n]),t>=n){let n=c+l,a={value:n>0?100*(c-l)/n:0};r.set(e[t].time,a),i[t]=a}return{values:r,series:i}}},wr=class extends P{descriptor={id:`trix`,name:`TRIX`,placement:`panel`,defaultConfig:{period:15,signal:9,source:`close`},shortName:`TRIX`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`TRIX`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`period`,15,1),r=L(t,`signal`,9,1),i=new F,a=Array(e.length).fill(null),o=e.length;if(o<2)return{values:i,series:a};let s=Tr(Tr(Tr(e.map(e=>e.close),n),n),n),c=Array(o).fill(0);for(let e=1;e<o;e++)c[e]=s[e-1]===0?0:(s[e]-s[e-1])/s[e-1]*100;let l=Tr(c,r),u=3*n;for(let t=u;t<o;t++){let n={value:c[t],signal:l[t]};i.set(e[t].time,n),a[t]=n}return{values:i,series:a}}};function Tr(e,t){let n=2/(t+1),r=Array(e.length).fill(0),i=e[0]??0;r[0]=i;for(let t=1;t<e.length;t++)i=e[t]*n+i*(1-n),r[t]=i;return r}var Er=class extends P{descriptor={id:`emv`,name:`Ease of Movement`,placement:`panel`,defaultConfig:{period:14},shortName:`EOM`,plots:[{key:`value`,title:`EOM`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<2)return{values:r,series:i};let o=Array(a).fill(0);for(let t=1;t<a;t++){let n=(e[t].high+e[t].low)/2,r=(e[t-1].high+e[t-1].low)/2,i=e[t].high-e[t].low,a=e[t].volume;o[t]=a>0?(n-r)*i/a:0}let s=0;for(let t=1;t<a;t++)if(s+=o[t],t>n&&(s-=o[t-n]),t>=n){let a={value:s/n};r.set(e[t].time,a),i[t]=a}return{values:r,series:i}}},Dr=class extends P{descriptor={id:`pvt`,name:`Price Volume Trend`,placement:`panel`,defaultConfig:{},shortName:`PVT`,plots:[{key:`value`,title:`PVT`,color:0}]};calculate(e,t){let n=new F,r=Array(e.length).fill(null),i=e.length;if(i===0)return{values:n,series:r};let a=0;n.set(e[0].time,{value:0}),r[0]={value:0};for(let t=1;t<i;t++){let i=e[t-1].close;i!==0&&(a+=e[t].volume*(e[t].close-i)/i);let o={value:a};n.set(e[t].time,o),r[t]=o}return{values:n,series:r}}},Or=class extends P{descriptor={id:`wad`,name:`Williams A/D`,placement:`panel`,defaultConfig:{},shortName:`WAD`,plots:[{key:`value`,title:`WAD`,color:0}]};calculate(e,t){let n=new F,r=Array(e.length).fill(null),i=e.length;if(i===0)return{values:n,series:r};let a=0;n.set(e[0].time,{value:0}),r[0]={value:0};for(let t=1;t<i;t++){let i=e[t-1].close,o=e[t].close;o>i?a+=o-Math.min(e[t].low,i):o<i&&(a+=o-Math.max(e[t].high,i));let s={value:a};n.set(e[t].time,s),r[t]=s}return{values:n,series:r}}},kr=class extends P{descriptor={id:`chaikinvol`,name:`Chaikin Volatility`,placement:`panel`,defaultConfig:{ema:10,roc:10},shortName:`CV`,plots:[{key:`value`,title:`CV`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`ema`,10,1),r=L(t,`roc`,10,1),i=new F,a=Array(e.length).fill(null),o=e.length;if(o<=r)return{values:i,series:a};let s=2/(n+1),c=Array(o),l=e[0].high-e[0].low;c[0]=l;for(let t=1;t<o;t++)l=(e[t].high-e[t].low)*s+l*(1-s),c[t]=l;for(let t=n+r;t<o;t++){let n=c[t-r],o={value:n===0?0:(c[t]-n)/n*100};i.set(e[t].time,o),a[t]=o}return{values:i,series:a}}},Ar=class extends P{descriptor={id:`rvi`,name:`Relative Vigor Index`,placement:`panel`,defaultConfig:{period:10},shortName:`RVGI`,plots:[{key:`value`,title:`RVGI`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`period`,10,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<n+3)return{values:r,series:i};let o=Array(a).fill(0),s=Array(a).fill(0);for(let t=0;t<a;t++)o[t]=e[t].close-e[t].open,s[t]=e[t].high-e[t].low;let c=(e,t)=>(e[t]+2*e[t-1]+2*e[t-2]+e[t-3])/6,l=Array(a).fill(void 0),u=Array(a).fill(void 0);for(let e=3;e<a;e++)l[e]=c(o,e),u[e]=c(s,e);let d=Array(a).fill(void 0);for(let e=3+n-1;e<a;e++){let t=0,r=0;for(let i=e-n+1;i<=e;i++)t+=l[i],r+=u[i];d[e]=r===0?0:t/r}for(let t=0;t<a;t++){if(d[t]===void 0)continue;let n={value:d[t]};t>=3&&d[t-3]!==void 0&&(n.signal=(d[t]+2*d[t-1]+2*d[t-2]+d[t-3])/6),r.set(e[t].time,n),i[t]=n}return{values:r,series:i}}},jr=class extends P{descriptor={id:`stochrsi`,name:`Stochastic RSI`,placement:`panel`,defaultConfig:{rsiPeriod:14,stochPeriod:14,k:3,d:3,source:`close`},shortName:`Stoch RSI`,inputs:{source:{source:!0}},plots:[{key:`k`,title:`%K`,color:0},{key:`d`,title:`%D`,color:1}],scale:{min:0,max:100},levels:[20,80]};calculate(e,t){let n=L(t,`rsiPeriod`,14,1),r=L(t,`stochPeriod`,14,1),i=L(t,`k`,3,1),a=L(t,`d`,3,1),o=new F,s=Array(e.length).fill(null),c=e.length;if(c<=n+r)return{values:o,series:s};let l=Mr(e.map(e=>e.close),n),u=Array(c).fill(void 0);for(let e=0;e<c;e++){if(l[e]===void 0)continue;let t=1/0,n=-1/0,i=!0;for(let a=e-r+1;a<=e;a++){if(a<0||l[a]===void 0){i=!1;break}l[a]<t&&(t=l[a]),l[a]>n&&(n=l[a])}i&&(u[e]=n-t>0?(l[e]-t)/(n-t)*100:0)}let d=Nr(u,i),f=Nr(d,a);for(let t=0;t<c;t++){if(d[t]===void 0)continue;let n={k:d[t]};f[t]!==void 0&&(n.d=f[t]),o.set(e[t].time,n),s[t]=n}return{values:o,series:s}}};function Mr(e,t){let n=e.length,r=Array(n).fill(void 0);if(n<=t)return r;let i=0,a=0;for(let n=1;n<=t;n++){let t=e[n]-e[n-1];t>=0?i+=t:a-=t}i/=t,a/=t,r[t]=a===0?100:100-100/(1+i/a);for(let o=t+1;o<n;o++){let n=e[o]-e[o-1];i=(i*(t-1)+(n>0?n:0))/t,a=(a*(t-1)+(n<0?-n:0))/t,r[o]=a===0?100:100-100/(1+i/a)}return r}function Nr(e,t){let n=Array(e.length).fill(void 0);for(let r=t-1;r<e.length;r++){let i=0,a=!0;for(let n=r-t+1;n<=r;n++){if(e[n]===void 0){a=!1;break}i+=e[n]}a&&(n[r]=i/t)}return n}var Pr=class extends P{descriptor={id:`ppo`,name:`Percentage Price Oscillator`,placement:`panel`,defaultConfig:{fast:12,slow:26,signal:9,source:`close`},shortName:`PPO`,inputs:{source:{source:!0}},plots:[{key:`hist`,title:`Histogram`,color:2,kind:`histogram`,tone:`sign`,downColor:3},{key:`value`,title:`PPO`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`fast`,12,1),r=L(t,`slow`,26,1),i=L(t,`signal`,9,1),a=new F,o=Array(e.length).fill(null),s=e.length;if(s<=r)return{values:a,series:o};let c=e.map(e=>e.close),l=Fr(c,n),u=Fr(c,r),d=Array(s).fill(void 0);for(let e=0;e<s;e++)l[e]===void 0||u[e]===void 0||u[e]===0||(d[e]=(l[e]-u[e])/u[e]*100);let f=Fr(d,i);for(let t=0;t<s;t++){if(d[t]===void 0)continue;let n={value:d[t]};f[t]!==void 0&&(n.signal=f[t],n.hist=d[t]-f[t]),a.set(e[t].time,n),o[t]=n}return{values:a,series:o}}};function Fr(e,t){let n=e.length,r=Array(n).fill(void 0),i=2/(t+1),a,o=0,s=0;for(let c=0;c<n;c++){let n=e[c];n!==void 0&&(a===void 0?(o+=n,s++,s===t&&(a=o/t,r[c]=a)):(a=n*i+a*(1-i),r[c]=a))}return r}var Ir=class extends P{descriptor={id:`ac`,name:`Accelerator Oscillator`,placement:`panel`,defaultConfig:{},shortName:`AC`,plots:[{key:`value`,title:`AC`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}]};calculate(e){let t=new F,n=Array(e.length).fill(null),r=e.length;if(r<38)return{values:t,series:n};let i=e.map(e=>(e.high+e.low)/2),a=Array(r).fill(void 0);for(let e=33;e<r;e++)a[e]=Lr(i,e,5)-Lr(i,e,34);let o;for(let i=37;i<r;i++){let r=0;for(let e=i-4;e<=i;e++)r+=a[e];let s=a[i]-r/5,c=o===void 0?s>=0:s>=o;o=s;let l={value:s,up:+!!c};t.set(e[i].time,l),n[i]=l}return{values:t,series:n}}};function Lr(e,t,n){let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i];return r/n}var Rr=class extends P{descriptor={id:`rmi`,name:`Relative Momentum Index`,placement:`panel`,defaultConfig:{period:20,momentum:5,source:`close`},shortName:`RMI`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`RMI`,color:0}],scale:{min:0,max:100},levels:[30,70]};calculate(e,t){let n=L(t,`period`,20,1),r=L(t,`momentum`,5,1),i=new F,a=Array(e.length).fill(null),o=e.length;if(o<=n+r)return{values:i,series:a};let s=e.map(e=>e.close),c=Array(o).fill(0),l=Array(o).fill(0);for(let e=r;e<o;e++){let t=s[e]-s[e-r];c[e]=t>0?t:0,l[e]=t<0?-t:0}let u=0,d=0,f=r+n;for(let e=r+1;e<=f;e++)u+=c[e],d+=l[e];u/=n,d/=n;let p=t=>{let n={value:d===0?100:100-100/(1+u/d)};i.set(e[t].time,n),a[t]=n};p(f);for(let e=f+1;e<o;e++)u=(u*(n-1)+c[e])/n,d=(d*(n-1)+l[e])/n,p(e);return{values:i,series:a}}},zr=class extends P{descriptor={id:`disparity`,name:`Disparity Index`,placement:`panel`,defaultConfig:{period:14,source:`close`},shortName:`DI`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`DI`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<n)return{values:r,series:i};let o=0;for(let t=0;t<a;t++)if(o+=e[t].close,t>=n&&(o-=e[t-n].close),t>=n-1){let a=o/n,s={value:a===0?0:(e[t].close-a)/a*100};r.set(e[t].time,s),i[t]=s}return{values:r,series:i}}},Br=class extends P{descriptor={id:`qstick`,name:`Qstick`,placement:`panel`,defaultConfig:{period:8},shortName:`Qstick`,plots:[{key:`value`,title:`Qstick`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`period`,8,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<n)return{values:r,series:i};let o=0;for(let t=0;t<a;t++){let a=e[t].close-e[t].open;if(o+=a,t>=n&&(o-=e[t-n].close-e[t-n].open),t>=n-1){let a={value:o/n};r.set(e[t].time,a),i[t]=a}}return{values:r,series:i}}},Vr=class extends P{descriptor={id:`pgo`,name:`Pretty Good Oscillator`,placement:`panel`,defaultConfig:{period:14},shortName:`PGO`,plots:[{key:`value`,title:`PGO`,color:0}],levels:[-3,0,3]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<=n)return{values:r,series:i};let o=Array(a).fill(0);for(let t=0;t<a;t++){if(t===0){o[t]=e[t].high-e[t].low;continue}let n=e[t-1].close;o[t]=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-n),Math.abs(e[t].low-n))}let s=Array(a).fill(void 0),c=0;for(let e=1;e<=n;e++)c+=o[e];s[n]=c/n;for(let e=n+1;e<a;e++)s[e]=(s[e-1]*(n-1)+o[e])/n;let l=0;for(let t=0;t<a;t++)if(l+=e[t].close,t>=n&&(l-=e[t-n].close),t>=n&&s[t]!==void 0&&s[t]>0){let a=l/n,o={value:(e[t].close-a)/s[t]};r.set(e[t].time,o),i[t]=o}return{values:r,series:i}}},Hr=class extends P{descriptor={id:`stddev`,name:`Standard Deviation`,placement:`panel`,defaultConfig:{period:20,source:`close`},shortName:`StdDev`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`StdDev`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null);for(let t=n-1;t<e.length;t++){let a=0;for(let r=t-n+1;r<=t;r++)a+=e[r].close;let o=a/n,s=0;for(let r=t-n+1;r<=t;r++){let t=e[r].close-o;s+=t*t}let c={value:Math.sqrt(s/n)};r.set(e[t].time,c),i[t]=c}return{values:r,series:i}}},Ur=class extends P{descriptor={id:`volumeProfile`,name:`Volume Profile`,placement:`overlay`,defaultConfig:{rows:24},shortName:`VP`,plots:[]};calculate(e,t){let n=L(t,`rows`,24,1),r=new F,i=Array(e.length).fill(null);if(e.length===0)return{values:r,series:i};let a=1/0,o=-1/0;for(let t of e)t.low<a&&(a=t.low),t.high>o&&(o=t.high);let s=(o-a||1)/n,c=Array(n).fill(0);for(let t of e){let e=(t.high+t.low+t.close)/3,r=Math.min(n-1,Math.floor((e-a)/s));c[r]+=t.volume}for(let e=0;e<n;e++){let t=a+(e+.5)*s;r.set(e,{price:t,volume:c[e],rowIndex:e})}return{values:r,series:i,meta:{minPrice:a,maxPrice:o,rows:n,rowHeight:s,bins:c,maxVolume:Math.max(...c)}}}render(t,n,r,i){let{chartRect:a}=r,o=n.meta;if(!o||o.maxVolume===0)return;let{minPrice:s,rows:c,rowHeight:l,bins:u,maxVolume:d}=o,f=a.width*.3,p=e.E(r);for(let e=0;e<c;e++){let n=p(s+e*l),r=p(s+(e+1)*l),o=u[e]/d*f;t.fillStyle=u[e]>d*.7?i.colors[1]??`rgba(242, 169, 59, 0.5)`:i.colors[0]??`rgba(76, 141, 255, 0.3)`,t.fillRect(a.x,Math.min(n,r),o,Math.max(Math.abs(n-r)-1,1))}}},Wr=class extends P{descriptor={id:`ad`,name:`Accumulation/Distribution`,placement:`panel`,defaultConfig:{},shortName:`A/D`,plots:[{key:`value`,title:`A/D`,color:0}]};calculate(e,t){let n=new F,r=Array(e.length).fill(null);if(e.length===0)return{values:n,series:r};let i=0;for(let t=0;t<e.length;t++){let a=e[t].high-e[t].low,o=a===0?0:(e[t].close-e[t].low-(e[t].high-e[t].close))/a;i+=o*e[t].volume;let s={value:i};n.set(e[t].time,s),r[t]=s}return{values:n,series:r}}},Gr=class extends P{descriptor={id:`vroc`,name:`Volume Rate of Change`,placement:`panel`,defaultConfig:{period:14},shortName:`VROC`,plots:[{key:`value`,title:`VROC`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null);for(let t=n;t<e.length;t++){let a=e[t-n].volume,o={value:a===0?0:(e[t].volume-a)/a*100};r.set(e[t].time,o),i[t]=o}return{values:r,series:i}}};function R(e,t){let n=new F;for(let r=0;r<t.length;r++){let i=t[r];i&&n.set(e[r].time,i)}return{values:n,series:t}}function z(e){return e.map(e=>e.close)}function Kr(e,t){let n=Array(e.length).fill(void 0),r=0,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(o===void 0){r=0,i=0;continue}r+=o,i++,i>t&&(r-=e[a-t]),i>=t&&(n[a]=r/t)}return n}function qr(e,t,n){let r=Array(e.length).fill(void 0),i=0,a=0,o;for(let s=0;s<e.length;s++){let c=e[s];if(c!==void 0){if(o===void 0){i+=c,a++,a===t&&(r[s]=o=i/t);continue}o+=n*(c-o),r[s]=o}}return r}function B(e,t){return qr(e,t,2/(t+1))}function Jr(e,t){let n=Array(e.length).fill(void 0),r=t*(t+1)/2;for(let i=t-1;i<e.length;i++){let a=0,o=!0;for(let n=0;n<t;n++){let r=e[i-t+1+n];if(r===void 0){o=!1;break}a+=r*(n+1)}o&&(n[i]=a/r)}return n}function Yr(e,t){return qr(e,t,1/t)}function Xr(e,t){let n=Array(e.length).fill(void 0);for(let r=t-1;r<e.length;r++){let i=0,a=0,o=!0;for(let n=r-t+1;n<=r;n++){let t=e[n];if(t===void 0){o=!1;break}i+=t,a+=t*t}if(!o)continue;let s=i/t;n[r]=Math.sqrt(Math.max(0,a/t-s*s))}return n}function Zr(e){return e.map((t,n)=>{if(n===0)return t.high-t.low;let r=e[n-1].close;return Math.max(t.high-t.low,Math.abs(t.high-r),Math.abs(t.low-r))})}function Qr(e,t,n){if(t<n-1)return;let r=-1/0;for(let i=t-n+1;i<=t;i++){let t=e[i];if(t===void 0)return;t>r&&(r=t)}return r}function $r(e,t,n){if(t<n-1)return;let r=1/0;for(let i=t-n+1;i<=t;i++){let t=e[i];if(t===void 0)return;t<r&&(r=t)}return r}function ei(e,t=`value`){return e.map(e=>e!==void 0&&Number.isFinite(e)?{[t]:e}:null)}function ti(e,t,n){if(t<n-1||t>=e.length)return;let r=0,i=0;for(let a=t-n+1;a<=t;a++){let t=e[a].close;r+=t,i+=t*t}let a=r/n;return{mean:a,sd:Math.sqrt(Math.max(0,i/n-a*a))}}function ni(e,t,n){if(t<n-1)return;let r=-1/0;for(let i=t-n+1;i<=t;i++)e[i].high>r&&(r=e[i].high);return r}function ri(e,t,n){if(t<n-1)return;let r=1/0;for(let i=t-n+1;i<=t;i++)e[i].low<r&&(r=e[i].low);return r}function ii(e,t,n){if(t<n-1)return;let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i].close;return r/n}function ai(e,t,n){if(n<2||t<n-1)return;let r=n,i=(r-1)/2,a=0;for(let n=0;n<r;n++)a+=e[t-r+1+n].close;a/=r;let o=0,s=0,c=0;for(let n=0;n<r;n++){let l=n-i,u=e[t-r+1+n].close-a;o+=l*u,s+=l*l,c+=u*u}let l=o/s,u=a-l*i,d=0;for(let n=0;n<r;n++){let i=e[t-r+1+n].close-(u+l*n);d+=i*i}return{slope:l,end:u+l*(r-1),stdErr:r>2?Math.sqrt(d/(r-2)):0,r:c===0?0:o/Math.sqrt(s*c)}}var oi=class extends P{descriptor={id:`dema`,name:`Double Exponential Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`DEMA`,inputs:{period:{min:1},source:{source:!0}},plots:[{key:`value`,title:`DEMA`,color:0}]};emas=new WeakMap;calculate(e,t){let n=L(t,`period`,20,1),r=B(z(e),n),i=B(r,n),a=R(e,ei(r.map((e,t)=>e!==void 0&&i[t]!==void 0?2*e-i[t]:void 0)));return this.emas.set(a,{e1:r,e2:i}),a}update(e,t,n,r){let i=this.emas.get(n);if(!i||!this.canResume(e,n,r))return null;let a=i.e1[r-1],o=i.e2[r-1];if(a===void 0||o===void 0)return null;let s=2/(L(t,`period`,20,1)+1);for(let t=r;t<e.length;t++)a+=s*(e[t].close-a),o+=s*(a-o),i.e1[t]=a,i.e2[t]=o,this.writePoint(n,e,t,{value:2*a-o});return n}},si=class extends P{descriptor={id:`smma`,name:`Smoothed Moving Average`,placement:`overlay`,defaultConfig:{period:14,source:`close`},shortName:`SMMA`,inputs:{period:{min:1},source:{source:!0}},plots:[{key:`value`,title:`SMMA`,color:0}]};calculate(e,t){return R(e,ei(Yr(z(e),L(t,`period`,14,1))))}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=n.series[r-1]?.value;if(i===void 0)return null;let a=L(t,`period`,14,1);for(let t=r;t<e.length;t++)i+=(e[t].close-i)/a,this.writePoint(n,e,t,{value:i});return n}},V=class extends P{times=new WeakMap;lookback(e){return 0}revisesBefore(e){return this.lookback(this.read(e))}calculate(e,t){let n=this.read(t),r=Array(e.length);for(let t=0;t<e.length;t++)r[t]=this.pointAt(e,t,n);let i=R(e,r);return this.times.set(i,e.map(e=>e.time)),i}update(e,t,n,r){let i=this.times.get(n);if(!i||!this.canResume(e,n,r))return null;for(let t=r;t<i.length&&t<e.length;t++)if(i[t]!==e[t].time)return null;let a=this.read(t);for(let t=Math.max(0,r-this.lookback(a));t<e.length;t++)this.writePoint(n,e,t,this.pointAt(e,t,a));i.length=e.length;for(let t=r;t<e.length;t++)i[t]=e[t].time;return n}},ci=class extends V{descriptor={id:`alma`,name:`Arnaud Legoux Moving Average`,placement:`overlay`,defaultConfig:{period:9,offset:.85,sigma:6,source:`close`},shortName:`ALMA`,inputs:{period:{min:1,max:5e3},offset:{min:0,max:1,step:.05},sigma:{min:.5,step:.5},source:{source:!0}},plots:[{key:`value`,title:`ALMA`,color:0}]};read(e){let t=Math.min(5e3,L(e,`period`,9,1)),n=Math.min(1,Math.max(0,I(e,`offset`,.85))),r=Math.max(.5,I(e,`sigma`,6)),i=n*(t-1),a=t/r,o=Array.from({length:t},(e,t)=>Math.exp(-((t-i)**2)/(2*a*a)));return{period:t,weights:o,norm:o.reduce((e,t)=>e+t,0)}}pointAt(e,t,{period:n,weights:r,norm:i}){if(t<n-1)return null;let a=0;for(let i=0;i<n;i++)a+=r[i]*e[t-n+1+i].close;return{value:a/i}}},li=class extends P{descriptor={id:`kama`,name:`Kaufman Adaptive Moving Average`,placement:`overlay`,defaultConfig:{period:10,fast:2,slow:30,source:`close`},shortName:`KAMA`,inputs:{period:{min:1},fast:{min:1},slow:{min:1},source:{source:!0}},plots:[{key:`value`,title:`KAMA`,color:0}]};calculate(e,t){let n=R(e,Array(e.length).fill(null)),r=L(t,`period`,10,1);return e.length<=r||this.extend(e,t,n,r,e[r-1].close),n}update(e,t,n,r){if(r<=L(t,`period`,10,1)||!this.canResume(e,n,r))return null;let i=n.series[r-1]?.value;return i===void 0?null:(this.extend(e,t,n,r,i),n)}extend(e,t,n,r,i){let a=L(t,`period`,10,1),o=2/(L(t,`fast`,2,1)+1),s=2/(L(t,`slow`,30,1)+1);for(let t=r;t<e.length;t++){let r=0;for(let n=t-a+1;n<=t;n++)r+=Math.abs(e[n].close-e[n-1].close);let c=Math.abs(e[t].close-e[t-a].close),l=((r>0?c/r:0)*(o-s)+s)**2;i+=l*(e[t].close-i),this.writePoint(n,e,t,{value:i})}}},ui=class extends V{descriptor={id:`lsma`,name:`Least Squares Moving Average`,placement:`overlay`,defaultConfig:{period:25,offset:0,source:`close`},shortName:`LSMA`,inputs:{period:{min:2,max:5e3},offset:{step:1},source:{source:!0}},plots:[{key:`value`,title:`LSMA`,color:0}]};read(e){let t=Math.min(5e3,L(e,`period`,25,2)),n=Math.round(L(e,`offset`,0,-1e3)),r=t*(t-1)/2;return{period:t,offset:n,sx:r,denom:t*((t-1)*t*(2*t-1)/6)-r*r}}pointAt(e,t,{period:n,offset:r,sx:i,denom:a}){if(t<n-1)return null;let o=0,s=0;for(let r=0;r<n;r++){let i=e[t-n+1+r].close;o+=i,s+=r*i}let c=(n*s-i*o)/a;return{value:(o-c*i)/n+c*(n-1-r)}}},di=class extends P{descriptor={id:`mcginley`,name:`McGinley Dynamic`,placement:`overlay`,defaultConfig:{period:14,source:`close`},shortName:`McGinley`,inputs:{period:{min:1},source:{source:!0}},plots:[{key:`value`,title:`McGinley`,color:0}]};calculate(e,t){let n=L(t,`period`,14,1),r=B(z(e),n),i=Array(e.length).fill(void 0),a;for(let t=0;t<e.length;t++)a=a===void 0?r[t]:fi(a,e[t].close,n),i[t]=a;return R(e,ei(i))}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=n.series[r-1]?.value;if(i===void 0)return null;let a=L(t,`period`,14,1);for(let t=r;t<e.length;t++)i=fi(i,e[t].close,a),this.writePoint(n,e,t,{value:i});return n}};function fi(e,t,n){return e>0&&t>0?e+(t-e)/(n*(t/e)**4):t}function pi(e){return e.params.type===`ema`?[`ema`,`ema`]:e.params.type===`sma-ema`?[`sma`,`ema`]:[`sma`,`sma`]}var mi=class extends P{descriptor={id:`macross`,name:`MA Cross`,placement:`overlay`,defaultConfig:{fast:9,slow:21,type:`sma`,source:`close`},shortName:`MA Cross`,inputs:{fast:{min:1},slow:{min:1},type:{options:[`sma`,`ema`,`sma-ema`]},source:{source:!0}},plots:[{key:`fast`,title:`Fast`,color:0},{key:`slow`,title:`Slow`,color:1}]};calculate(e,t){let[n,r]=pi(t),i=z(e),a=(t,n)=>t===`ema`?B(i,n):e.map((t,r)=>ii(e,r,n)),o=a(n,L(t,`fast`,9,1)),s=a(r,L(t,`slow`,21,1));return R(e,o.map((e,t)=>hi(e,s[t])))}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let[i,a]=pi(t),o=L(t,`fast`,9,1),s=L(t,`slow`,21,1),c=n.series[r-1]?.fast,l=n.series[r-1]?.slow;if(i===`ema`&&c===void 0||a===`ema`&&l===void 0)return null;for(let t=r;t<e.length;t++){let r=e[t].close;c=i===`ema`?c+2/(o+1)*(r-c):ii(e,t,o),l=a===`ema`?l+2/(s+1)*(r-l):ii(e,t,s),this.writePoint(n,e,t,hi(c,l))}return n}};function hi(e,t){return e===void 0&&t===void 0?null:{...e===void 0?{}:{fast:e},...t===void 0?{}:{slow:t}}}var gi=class extends V{descriptor={id:`fractals`,name:`Williams Fractals`,placement:`overlay`,defaultConfig:{period:2},shortName:`Fractals`,inputs:{period:{min:1,max:10}},plots:[{key:`up`,title:`Up`,color:0,kind:`dots`},{key:`down`,title:`Down`,color:1,kind:`dots`}]};read(e){return L(e,`period`,2,1)}lookback(e){return e}pointAt(e,t,n){if(t<n||t>e.length-n-1)return null;let r=!0,i=!0;for(let a=t-n;a<=t+n&&(r||i);a++)a!==t&&(e[a].high>=e[t].high&&(r=!1),e[a].low<=e[t].low&&(i=!1));return!r&&!i?null:{...r?{up:e[t].high}:{},...i?{down:e[t].low}:{}}}},_i=class extends P{descriptor={id:`cks`,name:`Chande Kroll Stop`,placement:`overlay`,defaultConfig:{p:10,x:1,q:9},shortName:`CKS`,inputs:{p:{label:`ATR length`,min:1},x:{label:`ATR multiplier`,min:0,step:.1},q:{label:`Stop length`,min:1}},plots:[{key:`long`,title:`Stop Long`,color:0},{key:`short`,title:`Stop Short`,color:1}]};states=new WeakMap;calculate(e,t){let n=L(t,`p`,10,1),r=I(t,`x`,1),i=L(t,`q`,9,1),a={atr:Yr(Zr(e),n),firstHigh:[],firstLow:[]};for(let t=0;t<e.length;t++)vi(e,a,t,n,r);let o=R(e,e.map((e,t)=>yi(a,t,i)));return this.states.set(o,a),o}update(e,t,n,r){let i=this.states.get(n);if(!i||!this.canResume(e,n,r))return null;let a=i.atr[r-1];if(a===void 0)return null;let o=L(t,`p`,10,1),s=I(t,`x`,1),c=L(t,`q`,9,1);for(let t=r;t<e.length;t++){let r=e[t-1].close,l=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-r),Math.abs(e[t].low-r));a+=(l-a)/o,i.atr[t]=a,vi(e,i,t,o,s),this.writePoint(n,e,t,yi(i,t,c))}return n}};function vi(e,t,n,r,i){let a=t.atr[n],o=ni(e,n,r),s=ri(e,n,r);t.firstHigh[n]=o!==void 0&&a!==void 0?o-i*a:void 0,t.firstLow[n]=s!==void 0&&a!==void 0?s+i*a:void 0}function yi(e,t,n){let r=Qr(e.firstHigh,t,n),i=$r(e.firstLow,t,n);return r!==void 0&&i!==void 0?{long:i,short:r}:null}var bi=class extends V{descriptor={id:`bbpb`,name:`Bollinger Bands %B`,placement:`panel`,defaultConfig:{period:20,stdDev:2,source:`close`},shortName:`%B`,inputs:{period:{min:2},stdDev:{min:.1,step:.1},source:{source:!0}},plots:[{key:`value`,title:`%B`,color:0}],levels:[0,.5,1]};read(e){return{period:L(e,`period`,20,2),k:I(e,`stdDev`,2)}}pointAt(e,t,{period:n,k:r}){let i=ti(e,t,n);return!i||i.sd===0?null:{value:(e[t].close-(i.mean-r*i.sd))/(2*r*i.sd)}}},xi=class extends V{descriptor={id:`bbw`,name:`Bollinger BandWidth`,placement:`panel`,defaultConfig:{period:20,stdDev:2,source:`close`},shortName:`BBW`,inputs:{period:{min:2},stdDev:{min:.1,step:.1},source:{source:!0}},plots:[{key:`value`,title:`BBW`,color:0}]};read(e){return{period:L(e,`period`,20,2),k:I(e,`stdDev`,2)}}pointAt(e,t,{period:n,k:r}){let i=ti(e,t,n);return!i||i.mean===0?null:{value:2*r*i.sd/i.mean}}},Si=class extends V{descriptor={id:`mom`,name:`Momentum`,placement:`panel`,defaultConfig:{period:10,source:`close`},shortName:`MOM`,inputs:{period:{min:1},source:{source:!0}},plots:[{key:`value`,title:`MOM`,color:0}],levels:[0]};read(e){return L(e,`period`,10,1)}pointAt(e,t,n){return t>=n?{value:e[t].close-e[t-n].close}:null}},Ci=class extends V{descriptor={id:`hv`,name:`Historical Volatility`,placement:`panel`,defaultConfig:{period:10,annual:365,source:`close`},shortName:`HV`,inputs:{period:{min:2},annual:{label:`Bars per year`,min:1},source:{source:!0}},plots:[{key:`value`,title:`HV`,color:0}],scale:{min:0}};read(e){return{period:L(e,`period`,10,2),annual:Math.max(1,I(e,`annual`,365))}}pointAt(e,t,{period:n,annual:r}){if(t<n)return null;let i=0,a=0;for(let r=t-n+1;r<=t;r++){let t=e[r-1].close,n=e[r].close;if(!(t>0&&n>0))return null;let o=Math.log(n/t);i+=o,a+=o*o}let o=i/n;return{value:100*Math.sqrt(Math.max(0,a/n-o*o))*Math.sqrt(r)}}},wi=class extends P{descriptor={id:`vo`,name:`Volume Oscillator`,placement:`panel`,defaultConfig:{short:5,long:10},shortName:`Vol Osc`,inputs:{short:{min:1},long:{min:1}},plots:[{key:`value`,title:`Vol Osc`,color:0}],levels:[0]};emas=new WeakMap;calculate(e,t){let n=e.map(e=>e.volume),r=B(n,L(t,`short`,5,1)),i=B(n,L(t,`long`,10,1)),a=R(e,ei(r.map((e,t)=>Ti(e,i[t]))));return this.emas.set(a,{fast:r,slow:i}),a}update(e,t,n,r){let i=this.emas.get(n);if(!i||!this.canResume(e,n,r))return null;let a=i.fast[r-1],o=i.slow[r-1];if(a===void 0||o===void 0)return null;let s=2/(L(t,`short`,5,1)+1),c=2/(L(t,`long`,10,1)+1);for(let t=r;t<e.length;t++){a+=s*(e[t].volume-a),o+=c*(e[t].volume-o),i.fast[t]=a,i.slow[t]=o;let r=Ti(a,o);this.writePoint(n,e,t,r===void 0?null:{value:r})}return n}};function Ti(e,t){return e===void 0||t===void 0||t===0?void 0:100*(e-t)/t}var Ei=class extends P{descriptor={id:`ulcer`,name:`Ulcer Index`,placement:`panel`,defaultConfig:{period:14,source:`close`},shortName:`Ulcer`,inputs:{period:{min:1},source:{source:!0}},plots:[{key:`value`,title:`Ulcer`,color:0}],scale:{min:0}};drawdowns=new WeakMap;calculate(e,t){let n=L(t,`period`,14,1),r=e.map((t,r)=>Di(e,r,n)),i=R(e,e.map((e,t)=>Oi(r,t,n)));return this.drawdowns.set(i,r),i}update(e,t,n,r){let i=this.drawdowns.get(n);if(!i||!this.canResume(e,n,r))return null;let a=L(t,`period`,14,1);for(let t=r;t<e.length;t++)i[t]=Di(e,t,a);i.length=e.length;for(let t=r;t<e.length;t++)this.writePoint(n,e,t,Oi(i,t,a));return n}};function Di(e,t,n){if(t<n-1)return;let r=-1/0;for(let i=t-n+1;i<=t;i++)e[i].close>r&&(r=e[i].close);return r===0?void 0:100*(e[t].close-r)/r}function Oi(e,t,n){if(t<n-1)return null;let r=0;for(let i=t-n+1;i<=t;i++){let t=e[i];if(t===void 0)return null;r+=t*t}return{value:Math.sqrt(r/n)}}var ki=class extends P{descriptor={id:`smi`,name:`Stochastic Momentum Index`,placement:`panel`,defaultConfig:{period:10,smooth:3,signal:3},shortName:`SMI`,inputs:{period:{min:1},smooth:{min:1},signal:{min:1}},plots:[{key:`smi`,title:`SMI`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[40,-40]};calculate(e,t){let n=L(t,`period`,10,1),r=L(t,`smooth`,3,1),i=L(t,`signal`,3,1),a=Array(e.length).fill(void 0),o=Array(e.length).fill(void 0);for(let t=n-1;t<e.length;t++){let r=ni(e,t,n),i=ri(e,t,n);r===void 0||i===void 0||(a[t]=e[t].close-(r+i)/2,o[t]=r-i)}let s=B(B(a,r),r),c=B(B(o,r),r),l=s.map((e,t)=>{let n=c[t]===void 0?void 0:c[t]/2;if(!(e===void 0||n===void 0))return n===0?0:Math.max(-100,Math.min(100,100*e/n))}),u=B(l,i);return R(e,l.map((e,t)=>{if(e===void 0)return null;let n={smi:e};return u[t]!==void 0&&(n.signal=u[t]),n}))}},Ai=class extends P{descriptor={id:`rvix`,name:`Relative Volatility Index`,placement:`panel`,defaultConfig:{period:10,smooth:14},shortName:`RVI (vol)`,inputs:{period:{min:2},smooth:{min:1}},plots:[{key:`value`,title:`RVI`,color:0}],levels:[80,50,20],scale:{min:0,max:100}};calculate(e,t){let n=L(t,`period`,10,2),r=L(t,`smooth`,14,1),i=Xr(z(e),n),a=i.map((t,n)=>t===void 0||n===0?void 0:e[n].close>e[n-1].close?t:0),o=i.map((t,n)=>t===void 0||n===0?void 0:e[n].close<e[n-1].close?t:0),s=B(a,r),c=B(o,r);return R(e,ei(s.map((e,t)=>{let n=c[t];if(!(e===void 0||n===void 0))return e+n===0?50:100*e/(e+n)})))}},ji=class extends V{descriptor={id:`trendstrength`,name:`Trend Strength Index`,placement:`panel`,defaultConfig:{period:14},shortName:`TSI (trend)`,inputs:{period:{min:2}},plots:[{key:`value`,title:`Trend`,color:0}],levels:[0],scale:{min:-1,max:1}};read(e){return L(e,`period`,14,2)}pointAt(e,t,n){let r=ai(e,t,n);return r?{value:r.r}:null}},Mi=class extends V{descriptor={id:`lrslope`,name:`Linear Regression Slope`,placement:`panel`,defaultConfig:{period:14},shortName:`LR Slope`,inputs:{period:{min:2}},plots:[{key:`value`,title:`Slope`,color:0}],levels:[0]};read(e){return L(e,`period`,14,2)}pointAt(e,t,n){let r=ai(e,t,n);return r?{value:r.slope}:null}},Ni=class extends V{descriptor={id:`stderror`,name:`Standard Error`,placement:`panel`,defaultConfig:{period:14},shortName:`StdErr`,inputs:{period:{min:3}},plots:[{key:`value`,title:`StdErr`,color:0}],scale:{min:0}};read(e){return L(e,`period`,14,3)}pointAt(e,t,n){let r=ai(e,t,n);return r?{value:r.stdErr}:null}},Pi=class extends V{descriptor={id:`adr`,name:`Average Day Range`,placement:`panel`,defaultConfig:{period:14},shortName:`ADR`,inputs:{period:{min:1}},plots:[{key:`value`,title:`ADR`,color:0}],scale:{min:0}};read(e){return L(e,`period`,14,1)}pointAt(e,t,n){if(t<n-1)return null;let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i].high-e[i].low;return{value:r/n}}},Fi=class extends V{descriptor={id:`netvolume`,name:`Net Volume`,placement:`panel`,defaultConfig:{},shortName:`Net Vol`,plots:[{key:`value`,title:`Net`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}],levels:[0]};read(e){return null}pointAt(e,t){if(t===0)return null;let n=e[t].close-e[t-1].close,r=e[t].volume??0;return{value:n>0?r:n<0?-r:0,up:+(n>=0)}}lookback(){return 1}},Ii=class extends P{descriptor={id:`seb`,name:`Standard Error Bands`,placement:`overlay`,defaultConfig:{period:21,mult:2,smooth:3},shortName:`SEB`,inputs:{period:{min:3},mult:{min:0,step:.1},smooth:{min:1}},plots:[{key:`upper`,title:`Upper`,color:1},{key:`middle`,title:`Middle`,color:0},{key:`lower`,title:`Lower`,color:1}]};calculate(e,t){let n=L(t,`period`,21,3),r=I(t,`mult`,2),i=L(t,`smooth`,3,1),a=Array(e.length).fill(void 0),o=Array(e.length).fill(void 0),s=Array(e.length).fill(void 0);for(let t=0;t<e.length;t++){let i=ai(e,t,n);i&&(a[t]=i.end,o[t]=i.end+r*i.stdErr,s[t]=i.end-r*i.stdErr)}let c=Kr(a,i),l=Kr(o,i),u=Kr(s,i);return R(e,c.map((e,t)=>e===void 0||l[t]===void 0||u[t]===void 0?null:{middle:e,upper:l[t],lower:u[t]}))}},Li=[3,5,8,10,12,15],Ri=[30,35,40,45,50,60],zi=class extends P{descriptor={id:`gmma`,name:`Guppy Multiple Moving Average`,placement:`overlay`,defaultConfig:{},shortName:`GMMA`,plots:[...Li.map(e=>({key:`s${e}`,title:`EMA ${e}`,color:0})),...Ri.map(e=>({key:`l${e}`,title:`EMA ${e}`,color:1}))]};calculate(e,t){let n=z(e),r=[...Li.map(e=>[`s${e}`,B(n,e)]),...Ri.map(e=>[`l${e}`,B(n,e)])];return R(e,e.map((e,t)=>{let n={},i=!1;for(let[e,a]of r)a[t]!==void 0&&(n[e]=a[t],i=!0);return i?n:null}))}},Bi=class extends P{descriptor={id:`maribbon`,name:`Moving Average Ribbon`,placement:`overlay`,defaultConfig:{ma1:20,ma2:50,ma3:100,ma4:200,exponential:0},shortName:`MA Ribbon`,inputs:{ma1:{min:1},ma2:{min:1},ma3:{min:1},ma4:{min:1},exponential:{min:0,max:1}},plots:[{key:`ma1`,title:`MA 1`,color:0},{key:`ma2`,title:`MA 2`,color:1},{key:`ma3`,title:`MA 3`,color:2},{key:`ma4`,title:`MA 4`,color:3}]};calculate(e,t){let n=I(t,`exponential`,0)>=1?B:Kr,r=z(e),i=[`ma1`,`ma2`,`ma3`,`ma4`],a=[20,50,100,200],o=i.map((e,i)=>[e,n(r,L(t,e,a[i],1))]);return R(e,e.map((e,t)=>{let n={},r=!1;for(let[e,i]of o)i[t]!==void 0&&(n[e]=i[t],r=!0);return r?n:null}))}},Vi=class extends V{read(e){return null}pointAt(e,t){return{value:this.price(e[t])}}},Hi=class extends Vi{descriptor={id:`avgprice`,name:`Average Price`,placement:`overlay`,defaultConfig:{},shortName:`OHLC4`,plots:[{key:`value`,title:`Average`,color:0}]};price(e){return(e.open+e.high+e.low+e.close)/4}},Ui=class extends Vi{descriptor={id:`medprice`,name:`Median Price`,placement:`overlay`,defaultConfig:{},shortName:`HL2`,plots:[{key:`value`,title:`Median`,color:0}]};price(e){return(e.high+e.low)/2}},Wi=class extends Vi{descriptor={id:`typprice`,name:`Typical Price`,placement:`overlay`,defaultConfig:{},shortName:`HLC3`,plots:[{key:`value`,title:`Typical`,color:0}]};price(e){return(e.high+e.low+e.close)/3}},Gi=class extends Vi{descriptor={id:`wclose`,name:`Weighted Close`,placement:`overlay`,defaultConfig:{},shortName:`HLCC4`,plots:[{key:`value`,title:`Weighted`,color:0}]};price(e){return(e.high+e.low+2*e.close)/4}},Ki=class extends V{descriptor={id:`psy`,name:`Psychological Line`,placement:`panel`,defaultConfig:{period:10},shortName:`PSY`,plots:[{key:`value`,title:`PSY`,color:0}],scale:{min:0,max:100},levels:[25,75]};read(e){return L(e,`period`,10,1)}pointAt(e,t,n){if(t<n)return null;let r=0;for(let i=t-n+1;i<=t;i++)e[i].close>e[i-1].close&&r++;return{value:r/n*100}}},qi=class extends V{descriptor={id:`newpsy`,name:`New Psychological Line`,placement:`panel`,defaultConfig:{period:10},shortName:`New PSY`,plots:[{key:`value`,title:`New PSY`,color:0}],scale:{min:-100,max:100},levels:[-50,0,50]};read(e){return L(e,`period`,10,1)}pointAt(e,t,n){if(t<n)return null;let r=0,i=0,a=0,o=0;for(let s=t-n+1;s<=t;s++){let t=e[s].close-e[s-1].close;t>0?(r++,a+=t):t<0&&(i++,o-=t)}let s=a+o;return{value:s===0?0:(r*a-i*o)/(s*n)*100}}},Ji=class extends V{descriptor={id:`vr`,name:`Volume Ratio`,placement:`panel`,defaultConfig:{period:20},shortName:`VR`,plots:[{key:`value`,title:`VR`,color:0}],levels:[70,150,450]};read(e){return L(e,`period`,20,1)}pointAt(e,t,n){if(t<n)return null;let r=0,i=0,a=0;for(let o=t-n+1;o<=t;o++){let t=e[o].close-e[o-1].close;t>0?r+=e[o].volume:t<0?i+=e[o].volume:a+=e[o].volume}let o=i+a/2;return o>0?{value:(r+a/2)/o*100}:null}},Yi=class extends V{descriptor={id:`abratio`,name:`AB Ratio`,placement:`panel`,defaultConfig:{period:26},shortName:`AB Ratio`,plots:[{key:`a`,title:`A`,color:0},{key:`b`,title:`B`,color:1}],levels:[100]};read(e){return L(e,`period`,26,1)}pointAt(e,t,n){if(t<n)return null;let r=0,i=0,a=0,o=0;for(let s=t-n+1;s<=t;s++){let{open:t,high:n,low:c}=e[s],l=e[s-1].close;r+=n-t,i+=t-c,a+=Math.max(0,n-l),o+=Math.max(0,l-c)}let s={};return i>0&&(s.a=r/i*100),o>0&&(s.b=a/o*100),s.a!==void 0||s.b!==void 0?s:null}},Xi=class extends P{descriptor={id:`sonar`,name:`Sonar`,placement:`panel`,defaultConfig:{period:20,lookback:9,signal:9},shortName:`Sonar`,plots:[{key:`sonar`,title:`Sonar`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`period`,20,1),r=L(t,`lookback`,9,1),i=L(t,`signal`,9,1),a=B(z(e),n),o=a.map((e,t)=>e!==void 0&&t>=r&&a[t-r]!==void 0?e-a[t-r]:void 0),s=B(o,i);return R(e,o.map((e,t)=>e===void 0?null:s[t]===void 0?{sonar:e}:{sonar:e,signal:s[t]}))}},Zi=class extends V{descriptor={id:`sigma`,name:`Sigma`,placement:`panel`,defaultConfig:{period:20},shortName:`Sigma`,plots:[{key:`value`,title:`Sigma`,color:0}],levels:[-2,0,2]};read(e){return L(e,`period`,20,2)}pointAt(e,t,n){let r=ti(e,t,n);return r?{value:r.sd<=Math.abs(r.mean)*1e-9?0:(e[t].close-r.mean)/r.sd}:null}},Qi=class extends V{descriptor={id:`vhf`,name:`Vertical Horizontal Filter`,placement:`panel`,defaultConfig:{period:28},shortName:`VHF`,plots:[{key:`value`,title:`VHF`,color:0}]};read(e){return L(e,`period`,28,1)}pointAt(e,t,n){if(t<n)return null;let r=e[t-n].close,i=r,a=0;for(let o=t-n+1;o<=t;o++){let t=e[o].close;t>r&&(r=t),t<i&&(i=t),a+=Math.abs(t-e[o-1].close)}return a>0?{value:(r-i)/a}:null}},$i=class extends V{descriptor={id:`rsquared`,name:`R-Squared`,placement:`panel`,defaultConfig:{period:14},shortName:`R²`,plots:[{key:`value`,title:`R²`,color:0}],scale:{min:0,max:1}};read(e){return L(e,`period`,14,2)}pointAt(e,t,n){let r=ai(e,t,n);return r?{value:r.r*r.r}:null}};function ea(e,t){let n=e[t];if(t===0)return n.high-n.low;let r=e[t-1].close;return Math.max(n.high-n.low,Math.abs(n.high-r),Math.abs(n.low-r))}var ta=class extends V{descriptor={id:`rwi`,name:`Random Walk Index`,placement:`panel`,defaultConfig:{period:14},shortName:`RWI`,plots:[{key:`high`,title:`RWI High`,color:0},{key:`low`,title:`RWI Low`,color:1}],levels:[1]};read(e){return L(e,`period`,14,2)}pointAt(e,t,n){if(t<n)return null;let r=0,i=0,a=ea(e,t);for(let o=1;o<=n;o++){if(o>1){let n=a/o*Math.sqrt(o);n>0&&(r=Math.max(r,(e[t].high-e[t-o].low)/n),i=Math.max(i,(e[t-o].high-e[t].low)/n))}a+=ea(e,t-o)}return{high:r,low:i}}},na=1e3,ra=class extends P{calculate(e,t){let n=Array(e.length).fill(void 0),r=na;for(let t=0;t<e.length;t++){if(t>0){let n=e[t-1].close;n!==0&&this.counts(e[t].volume,e[t-1].volume)&&(r*=e[t].close/n)}n[t]=r}let i=B(n,L(t,`signal`,255,1));return R(e,n.map((e,t)=>i[t]===void 0?{value:e}:{value:e,signal:i[t]}))}},ia=class extends ra{descriptor={id:`nvi`,name:`Negative Volume Index`,placement:`panel`,defaultConfig:{signal:255},shortName:`NVI`,plots:[{key:`value`,title:`NVI`,color:0},{key:`signal`,title:`Signal`,color:1}]};counts(e,t){return e<t}},aa=class extends ra{descriptor={id:`pvi`,name:`Positive Volume Index`,placement:`panel`,defaultConfig:{signal:255},shortName:`PVI`,plots:[{key:`value`,title:`PVI`,color:0},{key:`signal`,title:`Signal`,color:1}]};counts(e,t){return e>t}},oa=class extends V{descriptor={id:`tr`,name:`True Range`,placement:`panel`,defaultConfig:{},shortName:`TR`,plots:[{key:`value`,title:`TR`,color:0}]};read(e){return null}pointAt(e,t){let n=e[t];if(t===0)return{value:n.high-n.low};let r=e[t-1].close;return{value:Math.max(n.high-n.low,Math.abs(n.high-r),Math.abs(n.low-r))}}},sa=class extends V{descriptor={id:`iii`,name:`Intraday Intensity`,placement:`panel`,defaultConfig:{period:21},shortName:`III`,plots:[{key:`value`,title:`III %`,color:0,kind:`histogram`,tone:`sign`,downColor:1}],scale:{zero:!0},levels:[0]};read(e){return L(e,`period`,21,1)}pointAt(e,t,n){if(t<n-1)return null;let r=0,i=0;for(let a=t-n+1;a<=t;a++){let t=e[a];i+=t.volume,t.high>t.low&&(r+=t.volume*(2*t.close-t.high-t.low)/(t.high-t.low))}return i>0?{value:Math.max(-100,Math.min(100,r/i*100))}:{value:0}}},ca=class extends V{descriptor={id:`volpct`,name:`Volume vs Average`,placement:`panel`,defaultConfig:{period:20},shortName:`Vol %`,plots:[{key:`value`,title:`Vol %`,color:0,kind:`histogram`,tone:`sign`,downColor:1}],scale:{zero:!0},levels:[0]};read(e){return L(e,`period`,20,1)}pointAt(e,t,n){if(t<n-1)return null;let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i].volume;let i=r/n,a=(e[t].volume-i)/i*100;return i>0&&Number.isFinite(a)?{value:a}:null}},la=class extends V{descriptor={id:`volchange`,name:`Volume Change`,placement:`panel`,defaultConfig:{},shortName:`Vol Δ`,plots:[{key:`value`,title:`Volume`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}],scale:{zero:!0}};read(e){return null}pointAt(e,t){let{volume:n}=e[t];return Number.isFinite(n)?{value:n,up:+(t===0||n>=e[t-1].volume)}:null}},ua=class extends V{descriptor={id:`tradevalue`,name:`Trade Value`,placement:`panel`,defaultConfig:{},shortName:`Value`,plots:[{key:`value`,title:`Value`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}],scale:{zero:!0}};read(e){return null}pointAt(e,t){let n=e[t],r=n.close*n.volume;return Number.isFinite(r)?{value:r,up:+(n.close>=n.open)}:null}},da=class extends P{descriptor={id:`binarywave`,name:`Binary Wave`,placement:`panel`,defaultConfig:{ma:20,fast:12,slow:26,signal:9,roc:12,stoch:14},shortName:`Binary Wave`,plots:[{key:`value`,title:`Wave`,color:0,kind:`step`}],scale:{min:-4,max:4},levels:[0]};calculate(e,t){let n=z(e),r=Kr(n,L(t,`ma`,20,1)),i=B(n,L(t,`fast`,12,1)),a=B(n,L(t,`slow`,26,1)),o=i.map((e,t)=>e!==void 0&&a[t]!==void 0?e-a[t]:void 0),s=B(o,L(t,`signal`,9,1)),c=L(t,`roc`,12,1),l=L(t,`stoch`,14,1),u=e=>e?1:-1;return R(e,ei(e.map((t,i)=>{let a=ni(e,i,l),d=ri(e,i,l);if(r[i]===void 0||o[i]===void 0||s[i]===void 0||i<c||a===void 0||d===void 0)return;let f=a>d?(t.close-d)/(a-d)*100:50;return u(t.close>r[i])+u(o[i]>s[i])+u(t.close>n[i-c])+u(f>50)})))}},fa=class extends P{descriptor={id:`sroc`,name:`Smoothed Rate of Change`,placement:`panel`,defaultConfig:{ema:13,roc:21},shortName:`S-ROC`,plots:[{key:`value`,title:`S-ROC`,color:0}],levels:[0]};calculate(e,t){let n=B(z(e),L(t,`ema`,13,1)),r=L(t,`roc`,21,1);return R(e,ei(n.map((e,t)=>{let i=t>=r?n[t-r]:void 0;return e!==void 0&&i!==void 0&&i!==0?(e-i)/Math.abs(i)*100:void 0})))}},pa=class extends V{descriptor={id:`tsf`,name:`Time Series Forecast`,placement:`overlay`,defaultConfig:{period:14},shortName:`TSF`,plots:[{key:`value`,title:`TSF`,color:0}]};read(e){return L(e,`period`,14,2)}pointAt(e,t,n){let r=ai(e,t,n);return r?{value:r.end+r.slope}:null}},ma=class extends V{descriptor={id:`demark`,name:`DeMark Projected Range`,placement:`overlay`,defaultConfig:{},shortName:`DeMark`,plots:[{key:`high`,title:`Projected high`,color:0,kind:`step`},{key:`low`,title:`Projected low`,color:1,kind:`step`}]};read(e){return null}pointAt(e,t){if(t===0)return null;let{open:n,high:r,low:i,close:a}=e[t-1],o=a>n?2*r+i+a:a<n?r+2*i+a:r+i+2*a;return{high:o/2-i,low:o/2-r}}},ha=class extends P{descriptor={id:`rainbow`,name:`Moving Average Rainbow`,placement:`overlay`,defaultConfig:{first:10,step:10,count:10,exponential:0},shortName:`Rainbow`,inputs:{first:{min:1},step:{min:1},count:{min:1,max:20},exponential:{min:0,max:1}},plots:Array.from({length:20},(e,n)=>({key:`ma${n+1}`,title:`MA ${n+1}`,color:n%t.TC_SERIES_COLORS.length}))};calculate(e,t){let n=L(t,`first`,10,1),r=L(t,`step`,10,1),i=Math.min(20,L(t,`count`,10,1)),a=L(t,`exponential`,0,0)>=1?B:Kr,o=z(e),s=Array.from({length:i},(e,t)=>[`ma${t+1}`,a(o,n+t*r)]);return R(e,e.map((e,t)=>{let n={},r=!1;for(let[e,i]of s)i[t]!==void 0&&(n[e]=i[t],r=!0);return r?n:null}))}},ga=.05,_a=class{bodies=new Map;ranges=new Map;trends=new Map;constructor(e,t){this.data=e,this.period=t}open(e){return this.data[e].open}high(e){return this.data[e].high}low(e){return this.data[e].low}close(e){return this.data[e].close}body(e){return Math.abs(this.data[e].close-this.data[e].open)}range(e){return this.data[e].high-this.data[e].low}bodyTop(e){return Math.max(this.data[e].open,this.data[e].close)}bodyBottom(e){return Math.min(this.data[e].open,this.data[e].close)}mid(e){return(this.data[e].open+this.data[e].close)/2}upper(e){return this.data[e].high-this.bodyTop(e)}lower(e){return this.bodyBottom(e)-this.data[e].low}white(e){return this.data[e].close>this.data[e].open}black(e){return this.data[e].close<this.data[e].open}avgBody(e){let t=this.bodies.get(e);return t===void 0&&(t=this.averageBefore(e,e=>this.body(e)),this.bodies.set(e,t)),t}avgRange(e){let t=this.ranges.get(e);return t===void 0&&(t=this.averageBefore(e,e=>this.range(e)),this.ranges.set(e,t)),t}averageBefore(e,t){let n=Math.max(0,e-this.period);if(e<=n)return t(e);let r=0;for(let i=n;i<e;i++)r+=t(i);return r/(e-n)}bodyScale(e){return Math.max(this.avgBody(e),this.avgRange(e)*.25)}long(e,t=e){let n=this.bodyScale(t);return n>0&&this.body(e)>n}short(e,t=e){return this.body(e)<this.bodyScale(t)*.5}doji(e){return this.range(e)>0&&this.body(e)<=this.range(e)*.1}marubozu(e,t=e){return this.long(e,t)&&this.upper(e)<=this.range(e)*.05&&this.lower(e)<=this.range(e)*.05}same(e,t,n){return Math.abs(e-t)<=this.avgRange(n)*ga}bodyGapUp(e,t){return this.bodyBottom(t)>this.bodyTop(e)}bodyGapDown(e,t){return this.bodyTop(t)<this.bodyBottom(e)}bodyInside(e,t){return this.bodyTop(t)<=this.bodyTop(e)&&this.bodyBottom(t)>=this.bodyBottom(e)&&this.body(t)<this.body(e)}trendBefore(e){let t=this.trends.get(e);return t===void 0&&(t=this.readTrend(e),this.trends.set(e,t)),t}readTrend(e){let t=e-1;if(t<this.period-1)return null;let n=0;for(let e=t-this.period+1;e<=t;e++)n+=this.close(e);let r=n/this.period,i=this.close(t),a=this.close(t-this.period+1);return i>r&&i>a?`up`:i<r&&i<a?`down`:null}};function H(e,t,n,r,i,a,o,s){return{info:Object.freeze({id:e,name:t,short:n,direction:r,kind:i,bars:a}),trend:o,test:s}}function va(e,t){let n=e.range(t);return n>0&&n>=e.avgRange(t)*.5&&e.body(t)<=n*.35&&e.lower(t)>=2*Math.max(e.body(t),n*.05)&&e.upper(t)<=n*.1}function ya(e,t){let n=e.range(t);return n>0&&n>=e.avgRange(t)*.5&&e.body(t)<=n*.35&&e.upper(t)>=2*Math.max(e.body(t),n*.05)&&e.lower(t)<=n*.1}var ba=[H(`doji`,`Doji`,`Doji`,`neutral`,`indecision`,1,null,(e,t)=>e.doji(t)),H(`longLeggedDoji`,`Long-Legged Doji`,`LL Doji`,`neutral`,`indecision`,1,null,(e,t)=>e.doji(t)&&e.upper(t)>=e.range(t)*.3&&e.lower(t)>=e.range(t)*.3&&e.range(t)>e.avgRange(t)),H(`dragonflyDoji`,`Dragonfly Doji`,`Dragonfly`,`bullish`,`reversal`,1,`down`,(e,t)=>e.doji(t)&&e.upper(t)<=e.range(t)*.1&&e.lower(t)>=e.range(t)*.6),H(`gravestoneDoji`,`Gravestone Doji`,`Gravestone`,`bearish`,`reversal`,1,`up`,(e,t)=>e.doji(t)&&e.lower(t)<=e.range(t)*.1&&e.upper(t)>=e.range(t)*.6),H(`hammer`,`Hammer`,`Hammer`,`bullish`,`reversal`,1,`down`,va),H(`hangingMan`,`Hanging Man`,`Hanging`,`bearish`,`reversal`,1,`up`,va),H(`invertedHammer`,`Inverted Hammer`,`Inv Hammer`,`bullish`,`reversal`,1,`down`,ya),H(`shootingStar`,`Shooting Star`,`Shooting`,`bearish`,`reversal`,1,`up`,ya),H(`spinningTop`,`Spinning Top`,`Spinning`,`neutral`,`indecision`,1,null,(e,t)=>!e.doji(t)&&e.body(t)<=e.range(t)*.3&&e.upper(t)>e.body(t)&&e.lower(t)>e.body(t)),H(`bullishMarubozu`,`Bullish Marubozu`,`Marubozu`,`bullish`,`continuation`,1,null,(e,t)=>e.white(t)&&e.marubozu(t)),H(`bearishMarubozu`,`Bearish Marubozu`,`Marubozu`,`bearish`,`continuation`,1,null,(e,t)=>e.black(t)&&e.marubozu(t)),H(`bullishBeltHold`,`Bullish Belt Hold`,`Belt Hold`,`bullish`,`reversal`,1,`down`,(e,t)=>e.white(t)&&e.long(t)&&e.lower(t)<=e.range(t)*.05&&e.upper(t)>e.range(t)*.05),H(`bearishBeltHold`,`Bearish Belt Hold`,`Belt Hold`,`bearish`,`reversal`,1,`up`,(e,t)=>e.black(t)&&e.long(t)&&e.upper(t)<=e.range(t)*.05&&e.lower(t)>e.range(t)*.05)],xa=[H(`bullishEngulfing`,`Bullish Engulfing`,`Engulf`,`bullish`,`reversal`,2,`down`,(e,t)=>{let n=t-1;return e.black(n)&&e.white(t)&&e.open(t)<=e.close(n)&&e.close(t)>=e.open(n)&&e.body(t)>e.body(n)}),H(`bearishEngulfing`,`Bearish Engulfing`,`Engulf`,`bearish`,`reversal`,2,`up`,(e,t)=>{let n=t-1;return e.white(n)&&e.black(t)&&e.open(t)>=e.close(n)&&e.close(t)<=e.open(n)&&e.body(t)>e.body(n)}),H(`bullishHarami`,`Bullish Harami`,`Harami`,`bullish`,`reversal`,2,`down`,(e,t)=>e.black(t-1)&&e.long(t-1,t-1)&&!e.doji(t)&&e.bodyInside(t-1,t)&&e.body(t)<e.body(t-1)*.6),H(`bearishHarami`,`Bearish Harami`,`Harami`,`bearish`,`reversal`,2,`up`,(e,t)=>e.white(t-1)&&e.long(t-1,t-1)&&!e.doji(t)&&e.bodyInside(t-1,t)&&e.body(t)<e.body(t-1)*.6),H(`bullishHaramiCross`,`Bullish Harami Cross`,`Harami +`,`bullish`,`reversal`,2,`down`,(e,t)=>e.black(t-1)&&e.long(t-1,t-1)&&e.doji(t)&&e.bodyInside(t-1,t)),H(`bearishHaramiCross`,`Bearish Harami Cross`,`Harami +`,`bearish`,`reversal`,2,`up`,(e,t)=>e.white(t-1)&&e.long(t-1,t-1)&&e.doji(t)&&e.bodyInside(t-1,t)),H(`piercingLine`,`Piercing Line`,`Piercing`,`bullish`,`reversal`,2,`down`,(e,t)=>{let n=t-1;return e.black(n)&&e.long(n,n)&&e.white(t)&&e.open(t)<e.low(n)&&e.close(t)>e.mid(n)&&e.close(t)<e.open(n)}),H(`darkCloudCover`,`Dark Cloud Cover`,`Dark Cloud`,`bearish`,`reversal`,2,`up`,(e,t)=>{let n=t-1;return e.white(n)&&e.long(n,n)&&e.black(t)&&e.open(t)>e.high(n)&&e.close(t)<e.mid(n)&&e.close(t)>e.open(n)}),H(`tweezerBottom`,`Tweezer Bottom`,`Tweezer`,`bullish`,`reversal`,2,`down`,(e,t)=>e.black(t-1)&&e.white(t)&&e.same(e.low(t-1),e.low(t),t-1)),H(`tweezerTop`,`Tweezer Top`,`Tweezer`,`bearish`,`reversal`,2,`up`,(e,t)=>e.white(t-1)&&e.black(t)&&e.same(e.high(t-1),e.high(t),t-1)),H(`bullishKicking`,`Bullish Kicking`,`Kicking`,`bullish`,`reversal`,2,null,(e,t)=>e.black(t-1)&&e.marubozu(t-1,t-1)&&e.white(t)&&e.marubozu(t,t-1)&&e.low(t)>e.high(t-1)),H(`bearishKicking`,`Bearish Kicking`,`Kicking`,`bearish`,`reversal`,2,null,(e,t)=>e.white(t-1)&&e.marubozu(t-1,t-1)&&e.black(t)&&e.marubozu(t,t-1)&&e.high(t)<e.low(t-1)),H(`bullishCounterattack`,`Bullish Counterattack`,`Counter`,`bullish`,`reversal`,2,`down`,(e,t)=>e.black(t-1)&&e.long(t-1,t-1)&&e.white(t)&&e.long(t,t-1)&&e.same(e.close(t),e.close(t-1),t-1)),H(`bearishCounterattack`,`Bearish Counterattack`,`Counter`,`bearish`,`reversal`,2,`up`,(e,t)=>e.white(t-1)&&e.long(t-1,t-1)&&e.black(t)&&e.long(t,t-1)&&e.same(e.close(t),e.close(t-1),t-1)),H(`matchingLow`,`Matching Low`,`Match Low`,`bullish`,`reversal`,2,`down`,(e,t)=>e.black(t-1)&&e.long(t-1,t-1)&&e.black(t)&&e.same(e.close(t),e.close(t-1),t-1)),H(`homingPigeon`,`Homing Pigeon`,`Pigeon`,`bullish`,`reversal`,2,`down`,(e,t)=>e.black(t-1)&&e.long(t-1,t-1)&&e.black(t)&&e.short(t,t-1)&&e.bodyInside(t-1,t)),H(`onNeck`,`On Neck`,`On Neck`,`bearish`,`continuation`,2,`down`,(e,t)=>{let n=t-1;return e.black(n)&&e.long(n,n)&&e.white(t)&&e.open(t)<e.low(n)&&e.same(e.close(t),e.low(n),n)&&e.close(t)<e.close(n)}),H(`inNeck`,`In Neck`,`In Neck`,`bearish`,`continuation`,2,`down`,(e,t)=>{let n=t-1;return e.black(n)&&e.long(n,n)&&e.white(t)&&e.open(t)<e.low(n)&&e.close(t)>e.close(n)&&e.close(t)<=e.close(n)+e.body(n)*.1}),H(`thrusting`,`Thrusting`,`Thrusting`,`bearish`,`continuation`,2,`down`,(e,t)=>{let n=t-1;return e.black(n)&&e.long(n,n)&&e.white(t)&&e.open(t)<e.low(n)&&e.close(t)>e.close(n)+e.body(n)*.1&&e.close(t)<e.mid(n)}),H(`bullishSeparatingLines`,`Bullish Separating Lines`,`Separating`,`bullish`,`continuation`,2,`up`,(e,t)=>e.black(t-1)&&e.white(t)&&e.long(t,t-1)&&e.lower(t)<=e.range(t)*.05&&e.same(e.open(t),e.open(t-1),t-1)),H(`bearishSeparatingLines`,`Bearish Separating Lines`,`Separating`,`bearish`,`continuation`,2,`down`,(e,t)=>e.white(t-1)&&e.black(t)&&e.long(t,t-1)&&e.upper(t)<=e.range(t)*.05&&e.same(e.open(t),e.open(t-1),t-1))];function Sa(e,t){for(let n=t;n<t+3;n++)if(!e.white(n)||e.short(n,t)||e.upper(n)>e.body(n)*.25||n>t&&(e.close(n)<=e.close(n-1)||e.open(n)<e.open(n-1)||e.open(n)>e.close(n-1)))return!1;return!0}function Ca(e,t){for(let n=t;n<t+3;n++)if(!e.black(n)||e.short(n,t)||e.lower(n)>e.body(n)*.25||n>t&&(e.close(n)>=e.close(n-1)||e.open(n)>e.open(n-1)||e.open(n)<e.close(n-1)))return!1;return!0}function wa(e,t,n,r){for(let i=t+1;i<=n;i++)if(r?e.close(i)>=e.close(i-1):e.close(i)<=e.close(i-1))return!1;return!0}function Ta(e,t,n,r,i){for(let a=n;a<=r;a++)if((i?!e.black(a):!e.white(a))||e.long(a,t)||e.high(a)>e.high(t)||e.low(a)<e.low(t))return!1;return!0}var Ea=[H(`morningStar`,`Morning Star`,`M. Star`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.long(n,n)&&e.short(r,n)&&!e.doji(r)&&e.bodyGapDown(n,r)&&e.white(t)&&e.close(t)>e.mid(n)}),H(`eveningStar`,`Evening Star`,`E. Star`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.short(r,n)&&!e.doji(r)&&e.bodyGapUp(n,r)&&e.black(t)&&e.close(t)<e.mid(n)}),H(`morningDojiStar`,`Morning Doji Star`,`M. Doji`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.long(n,n)&&e.doji(r)&&e.bodyGapDown(n,r)&&e.white(t)&&e.close(t)>e.mid(n)}),H(`eveningDojiStar`,`Evening Doji Star`,`E. Doji`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.doji(r)&&e.bodyGapUp(n,r)&&e.black(t)&&e.close(t)<e.mid(n)}),H(`bullishAbandonedBaby`,`Bullish Abandoned Baby`,`Abandoned`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.long(n,n)&&e.doji(r)&&e.high(r)<e.low(n)&&e.white(t)&&!e.short(t,n)&&e.low(t)>e.high(r)}),H(`bearishAbandonedBaby`,`Bearish Abandoned Baby`,`Abandoned`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.doji(r)&&e.low(r)>e.high(n)&&e.black(t)&&!e.short(t,n)&&e.high(t)<e.low(r)}),H(`threeWhiteSoldiers`,`Three White Soldiers`,`3 Soldiers`,`bullish`,`reversal`,3,null,(e,t)=>Sa(e,t-2)),H(`threeBlackCrows`,`Three Black Crows`,`3 Crows`,`bearish`,`reversal`,3,null,(e,t)=>Ca(e,t-2)),H(`threeInsideUp`,`Three Inside Up`,`3 Inside`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.long(n,n)&&e.white(r)&&e.bodyInside(n,r)&&e.white(t)&&e.close(t)>e.open(n)}),H(`threeInsideDown`,`Three Inside Down`,`3 Inside`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.black(r)&&e.bodyInside(n,r)&&e.black(t)&&e.close(t)<e.open(n)}),H(`threeOutsideUp`,`Three Outside Up`,`3 Outside`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.white(r)&&e.open(r)<=e.close(n)&&e.close(r)>=e.open(n)&&e.body(r)>e.body(n)&&e.white(t)&&e.close(t)>e.close(r)}),H(`threeOutsideDown`,`Three Outside Down`,`3 Outside`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.black(r)&&e.open(r)>=e.close(n)&&e.close(r)<=e.open(n)&&e.body(r)>e.body(n)&&e.black(t)&&e.close(t)<e.close(r)}),H(`upsideGapTwoCrows`,`Upside Gap Two Crows`,`2 Crows Gap`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.black(r)&&e.short(r,n)&&e.bodyGapUp(n,r)&&e.black(t)&&e.open(t)>e.open(r)&&e.close(t)<e.close(r)&&e.close(t)>e.close(n)}),H(`twoCrows`,`Two Crows`,`2 Crows`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.black(r)&&e.bodyGapUp(n,r)&&e.black(t)&&e.open(t)<e.open(r)&&e.open(t)>e.close(r)&&e.close(t)<e.close(n)&&e.close(t)>e.open(n)}),H(`bullishTriStar`,`Bullish Tri-Star`,`Tri-Star`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.doji(n)&&e.doji(r)&&e.doji(t)&&e.bodyGapDown(n,r)&&e.bodyGapUp(r,t)}),H(`bearishTriStar`,`Bearish Tri-Star`,`Tri-Star`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.doji(n)&&e.doji(r)&&e.doji(t)&&e.bodyGapUp(n,r)&&e.bodyGapDown(r,t)}),H(`upsideTasukiGap`,`Upside Tasuki Gap`,`Tasuki`,`bullish`,`continuation`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.white(r)&&e.low(r)>e.high(n)&&e.black(t)&&e.open(t)<e.close(r)&&e.open(t)>e.open(r)&&e.close(t)<e.low(r)&&e.close(t)>e.high(n)}),H(`downsideTasukiGap`,`Downside Tasuki Gap`,`Tasuki`,`bearish`,`continuation`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.black(r)&&e.high(r)<e.low(n)&&e.white(t)&&e.open(t)>e.close(r)&&e.open(t)<e.open(r)&&e.close(t)>e.high(r)&&e.close(t)<e.low(n)}),H(`stickSandwich`,`Stick Sandwich`,`Sandwich`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.white(r)&&e.low(r)>e.close(n)&&e.black(t)&&e.same(e.close(t),e.close(n),n)}),H(`advanceBlock`,`Advance Block`,`Adv Block`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.white(r)&&e.white(t)&&e.close(r)>e.close(n)&&e.close(t)>e.close(r)&&e.open(r)>e.open(n)&&e.open(r)<=e.close(n)&&e.open(t)>e.open(r)&&e.open(t)<=e.close(r)&&e.body(t)<e.body(r)&&e.body(r)<e.body(n)&&e.upper(t)>e.upper(n)}),H(`identicalThreeCrows`,`Identical Three Crows`,`Ident Crows`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.black(r)&&e.black(t)&&e.close(r)<e.close(n)&&e.close(t)<e.close(r)&&e.same(e.open(r),e.close(n),n)&&e.same(e.open(t),e.close(r),n)&&e.lower(n)<=e.body(n)*.25&&e.lower(r)<=e.body(r)*.25&&e.lower(t)<=e.body(t)*.25})],Da=[H(`bullishThreeLineStrike`,`Bullish Three-Line Strike`,`Strike`,`bullish`,`continuation`,4,`up`,(e,t)=>{let n=t-3;return e.white(n)&&e.white(n+1)&&e.white(n+2)&&wa(e,n,n+2,!1)&&e.open(n+1)>=e.open(n)&&e.open(n+1)<=e.close(n)&&e.open(n+2)>=e.open(n+1)&&e.open(n+2)<=e.close(n+1)&&e.black(t)&&e.open(t)>e.close(n+2)&&e.close(t)<e.open(n)}),H(`bearishThreeLineStrike`,`Bearish Three-Line Strike`,`Strike`,`bearish`,`continuation`,4,`down`,(e,t)=>{let n=t-3;return e.black(n)&&e.black(n+1)&&e.black(n+2)&&wa(e,n,n+2,!0)&&e.open(n+1)<=e.open(n)&&e.open(n+1)>=e.close(n)&&e.open(n+2)<=e.open(n+1)&&e.open(n+2)>=e.close(n+1)&&e.white(t)&&e.open(t)<e.close(n+2)&&e.close(t)>e.open(n)}),H(`risingThreeMethods`,`Rising Three Methods`,`Rising 3`,`bullish`,`continuation`,5,`up`,(e,t)=>{let n=t-4;return e.white(n)&&e.long(n,n)&&Ta(e,n,n+1,n+3,!0)&&wa(e,n+1,n+3,!0)&&e.white(t)&&e.long(t,n)&&e.open(t)>e.close(t-1)&&e.close(t)>e.close(n)}),H(`fallingThreeMethods`,`Falling Three Methods`,`Falling 3`,`bearish`,`continuation`,5,`down`,(e,t)=>{let n=t-4;return e.black(n)&&e.long(n,n)&&Ta(e,n,n+1,n+3,!1)&&wa(e,n+1,n+3,!1)&&e.black(t)&&e.long(t,n)&&e.open(t)<e.close(t-1)&&e.close(t)<e.close(n)}),H(`matHold`,`Mat Hold`,`Mat Hold`,`bullish`,`continuation`,5,`up`,(e,t)=>{let n=t-4;if(!(e.white(n)&&e.long(n,n)&&e.black(n+1)&&e.short(n+1,n)&&e.bodyGapUp(n,n+1)))return!1;for(let t=n+1;t<=n+3;t++)if(e.long(t,n)||e.bodyBottom(t)<e.mid(n))return!1;let r=Math.max(e.high(n+1),e.high(n+2),e.high(n+3));return e.close(n+3)<e.close(n+1)&&e.white(t)&&e.open(t)>e.close(t-1)&&e.close(t)>r}),H(`bullishBreakaway`,`Bullish Breakaway`,`Breakaway`,`bullish`,`reversal`,5,`down`,(e,t)=>{let n=t-4;return e.black(n)&&e.long(n,n)&&e.black(n+1)&&e.bodyGapDown(n,n+1)&&e.close(n+2)<e.close(n+1)&&e.close(n+3)<e.close(n+2)&&e.black(n+3)&&e.white(t)&&e.close(t)>e.open(n+1)&&e.close(t)<e.close(n)}),H(`bearishBreakaway`,`Bearish Breakaway`,`Breakaway`,`bearish`,`reversal`,5,`up`,(e,t)=>{let n=t-4;return e.white(n)&&e.long(n,n)&&e.white(n+1)&&e.bodyGapUp(n,n+1)&&e.close(n+2)>e.close(n+1)&&e.close(n+3)>e.close(n+2)&&e.white(n+3)&&e.black(t)&&e.close(t)<e.open(n+1)&&e.close(t)>e.close(n)}),H(`concealingBabySwallow`,`Concealing Baby Swallow`,`Swallow`,`bullish`,`reversal`,4,`down`,(e,t)=>{let n=t-3;return e.black(n)&&e.marubozu(n,n)&&e.black(n+1)&&e.marubozu(n+1,n)&&e.black(n+2)&&e.open(n+2)<e.close(n+1)&&e.high(n+2)>e.close(n+1)&&e.black(t)&&e.open(t)>e.high(n+2)&&e.close(t)<e.low(n+2)}),H(`ladderBottom`,`Ladder Bottom`,`Ladder`,`bullish`,`reversal`,5,`down`,(e,t)=>{let n=t-4;for(let t=n;t<=n+3;t++)if(!e.black(t))return!1;for(let t=n+1;t<=n+2;t++)if(e.open(t)>=e.open(t-1)||e.close(t)>=e.close(t-1))return!1;return e.upper(n+3)>e.body(n+3)&&e.white(t)&&e.open(t)>e.open(n+3)&&e.close(t)>e.high(n+3)})],Oa=[...ba,...xa,...Ea,...Da],ka=Oa.map(e=>e.info);function Aa(e){let t=e.trendPeriod;return t!==void 0&&Number.isFinite(t)?Math.max(2,Math.floor(t)):10}function ja(e){if(!e.patterns)return Oa;let t=new Set(e.patterns);return Oa.filter(e=>t.has(e.info.id))}function Ma(e,t,n){let r=[];for(let i of n){let n=t-i.info.bars+1;n<0||i.trend&&e.trendBefore(n)!==i.trend||i.test(e,t)&&r.push(i)}return r}function Na(e,t={}){let n=new _a(e,Aa(t)),r=ja(t),i=[],a=t.from!==void 0&&Number.isFinite(t.from)?Math.max(0,Math.floor(t.from)):0;for(let t=a;t<e.length;t++)for(let a of Ma(n,t,r))i.push({index:t,time:e[t].time,pattern:a.info});return i}function Pa(e={}){return ja(e)}var Fa=6,Ia=4,La=12,Ra=class extends V{descriptor={id:`candlepatterns`,name:`Candlestick Patterns`,placement:`overlay`,defaultConfig:{trendPeriod:10,reversal:1,continuation:1,indecision:0},shortName:`Patterns`,inputs:{trendPeriod:{min:2},reversal:{min:0,max:1},continuation:{min:0,max:1},indecision:{min:0,max:1}},plots:[{key:`bull`,title:`Bullish`,color:3,kind:`dots`},{key:`bear`,title:`Bearish`,color:4,kind:`dots`},{key:`neutral`,title:`Indecision`,color:1,kind:`dots`}]};read(e){let t=new Set;return L(e,`reversal`,1,0)>=1&&t.add(`reversal`),L(e,`continuation`,1,0)>=1&&t.add(`continuation`),L(e,`indecision`,0,0)>=1&&t.add(`indecision`),{trendPeriod:L(e,`trendPeriod`,10,2),defs:Pa().filter(e=>t.has(e.info.kind))}}pointAt(e,t,{trendPeriod:n,defs:r}){let i=Ma(new _a(e,n),t,r);if(i.length===0)return null;let a=i[0];for(let e of i)e.info.bars>=a.info.bars&&(a=e);let o=e[t],s={code:ka.indexOf(a.info),count:i.length};return a.info.direction===`bullish`?s.bull=o.low:a.info.direction===`bearish`?s.bear=o.high:s.neutral=o.high,s}render(t,n,r,i){let a=n.series;if(!a)return;let o=Math.max(0,Math.floor(r.visibleRange.from)),s=Math.min(a.length-1,Math.ceil(r.visibleRange.to)),c=r.barWidth+r.barSpacing>=La,{chartRect:l}=r,u=l.y+10,d=l.y+l.height-10,f=e=>i.plots?.[e]?.visible!==!1;t.save(),t.globalAlpha=i.opacity,t.font=`10px sans-serif`,t.textAlign=`center`;let p=-1/0,m=-1/0;for(let n=o;n<=s;n++){let o=a[n];if(!o)continue;let s=e.b(n,r),l=ka[o.code??-1]?.short??``;if(o.bull!==void 0&&f(`bull`)){let n=e.T(o.bull,r)+Ia;t.fillStyle=i.colors[3]??i.colors[0],za(t,s,n,`up`),c&&l&&(m=Ba(t,l,s,Math.min(d,n+Fa+2),`top`,m))}else if(o.bear!==void 0&&f(`bear`)){let n=e.T(o.bear,r)-Ia;t.fillStyle=i.colors[4]??i.colors[0],za(t,s,n,`down`),c&&l&&(p=Ba(t,l,s,Math.max(u,n-Fa-2),`bottom`,p))}else if(o.neutral!==void 0&&f(`neutral`)){let n=e.T(o.neutral,r)-Ia-Fa/2;t.fillStyle=i.colors[1]??i.colors[0],t.beginPath(),t.arc(s,n,Fa/2-1,0,Math.PI*2),t.fill(),c&&l&&(p=Ba(t,l,s,Math.max(u,n-Fa/2-2),`bottom`,p))}}t.restore()}};function za(e,t,n,r){let i=Fa/2;e.beginPath(),r===`up`?(e.moveTo(t,n),e.lineTo(t-i,n+Fa),e.lineTo(t+i,n+Fa)):(e.moveTo(t,n),e.lineTo(t-i,n-Fa),e.lineTo(t+i,n-Fa)),e.closePath(),e.fill()}function Ba(e,t,n,r,i,a){let o=e.measureText(t).width/2;return n-o<a+2?a:(e.textBaseline=i,e.fillText(t,n,r),n+o)}var Va=500,Ha=class extends P{descriptor={id:`machannel`,name:`Moving Average Channel`,placement:`overlay`,defaultConfig:{upperLength:20,lowerLength:20,upperOffset:0,lowerOffset:0},shortName:`MA Channel`,inputs:{upperLength:{min:1},lowerLength:{min:1},upperOffset:{min:-Va,max:Va},lowerOffset:{min:-Va,max:Va}},plots:[{key:`upper`,title:`Upper`,color:0},{key:`lower`,title:`Lower`,color:1}]};calculate(e,t){let n=Wa(Kr(e.map(e=>e.high),L(t,`upperLength`,20,1)),Ua(t,`upperOffset`)),r=Wa(Kr(e.map(e=>e.low),L(t,`lowerLength`,20,1)),Ua(t,`lowerOffset`));return R(e,n.map((e,t)=>{let n=r[t];return e===void 0&&n===void 0?null:{...e===void 0?{}:{upper:e},...n===void 0?{}:{lower:n}}}))}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=[],u=[],d=[],f=[];for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n)continue;let r=e.b(t,i),a=n.upper===void 0?null:{x:r,y:e.T(n.upper,i)},s=n.lower===void 0?null:{x:r,y:e.T(n.lower,i)};a&&l.push(a),s&&u.push(s),a&&s&&(d.push(a),f.push(s))}this.drawBand(n,d,f,(0,t.withAlpha)(a.colors[0],.08)),this.drawLine(n,l,a.colors[0],a.lineWidths[0],N(a,`upper`,a.lineWidths[0])),this.drawLine(n,u,a.colors[1]??a.colors[0],a.lineWidths[1]??a.lineWidths[0],N(a,`lower`,a.lineWidths[1]??a.lineWidths[0]))}};function Ua(e,t){let n=Number(e.params[t]??0);return Number.isFinite(n)?Math.max(-Va,Math.min(Va,Math.round(n))):0}function Wa(e,t){return e.map((n,r)=>e[r-t])}var Ga=500,Ka=class extends V{descriptor={id:`hamming`,name:`Moving Average Hamming`,placement:`overlay`,defaultConfig:{period:10,source:`close`},shortName:`HMA (Hamming)`,inputs:{period:{min:2,max:Ga},source:{source:!0}},plots:[{key:`value`,title:`MA`,color:0}]};read(e){let t=Math.min(Ga,L(e,`period`,10,2)),n=Array.from({length:t},(e,n)=>.54-.46*Math.cos(2*Math.PI*n/(t-1)));return{weights:n,total:n.reduce((e,t)=>e+t,0)}}pointAt(e,t,{weights:n,total:r}){let i=t-n.length+1;if(i<0)return null;let a=0;for(let t=0;t<n.length;t++)a+=n[t]*e[i+t].close;return{value:a/r}}},qa=[`sma`,`ema`,`wma`];function Ja(e,t,n){return e===`ema`?B(t,n):e===`wma`?Jr(t,n):Kr(t,n)}var Ya=class extends P{calculate(e,t){let n=qa.includes(t.params.type)?t.params.type:`sma`,r=z(e),i=this.lengths.map(([e,i])=>Ja(n,r,L(t,e,i,1)));return R(e,e.map((e,t)=>{let n={};return i.forEach((e,r)=>{let i=e[t];i!==void 0&&(n[`ma${r+1}`]=i)}),Object.keys(n).length>0?n:null}))}},Xa=class extends Ya{lengths=[[`first`,20],[`second`,50]];descriptor={id:`madouble`,name:`Moving Average Double`,placement:`overlay`,defaultConfig:{first:20,second:50,type:`sma`,source:`close`},shortName:`MA x2`,inputs:{first:{min:1},second:{min:1},type:{options:qa},source:{source:!0}},plots:[{key:`ma1`,title:`MA 1`,color:0},{key:`ma2`,title:`MA 2`,color:1}]}},Za=class extends Ya{lengths=[[`first`,10],[`second`,20],[`third`,50]];descriptor={id:`matriple`,name:`Moving Average Triple`,placement:`overlay`,defaultConfig:{first:10,second:20,third:50,type:`sma`,source:`close`},shortName:`MA x3`,inputs:{first:{min:1},second:{min:1},third:{min:1},type:{options:qa},source:{source:!0}},plots:[{key:`ma1`,title:`MA 1`,color:0},{key:`ma2`,title:`MA 2`,color:1},{key:`ma3`,title:`MA 3`,color:2}]}},Qa=class extends P{descriptor={id:`volindex`,name:`Volatility Index`,placement:`overlay`,defaultConfig:{period:7,mult:3},shortName:`VI`,inputs:{period:{min:1},mult:{label:`ATR multiple`,min:.1,step:.1}},plots:[{key:`sar`,title:`Stop`,color:0,kind:`dots`,tone:{field:`long`},downColor:1}]};calculate(e,t){let n=L(t,`period`,7,1),r=Math.max(.1,I(t,`mult`,3)),i=Yr(Zr(e),n),a=Array(e.length).fill(null),o=null,s=0;for(let t=0;t<e.length;t++){let n=i[t];if(n===void 0)continue;let c=e[t].close,l=n*r;o===null?(o=c>=e[0].close,s=c):o?(s=Math.max(s,c),c<s-l&&(o=!1,s=c)):(s=Math.min(s,c),c>s+l&&(o=!0,s=c)),a[t]={sar:o?s-l:s+l,long:+!!o}}return R(e,a)}},$a=class extends P{descriptor={id:`asi`,name:`Accumulative Swing Index`,placement:`panel`,defaultConfig:{limit:10},shortName:`ASI`,inputs:{limit:{label:`Limit move`,min:1e-4,step:.1}},plots:[{key:`value`,title:`ASI`,color:0}],scale:{zero:!0}};calculate(e,t){let n=Math.max(1e-9,I(t,`limit`,10)),r=Array(e.length).fill(null),i=0;for(let t=1;t<e.length;t++)i+=eo(e[t-1],e[t],n),r[t]={value:i};return R(e,r)}};function eo(e,t,n){let r=Math.abs(t.high-e.close),i=Math.abs(t.low-e.close),a=t.high-t.low,o=Math.abs(e.close-e.open),s;return s=r>=i&&r>=a?r-.5*i+.25*o:i>=r&&i>=a?i-.5*r+.25*o:a+.25*o,s===0?0:50*(t.close-e.close+.5*(t.close-t.open)+.25*(e.close-e.open))/s*(Math.max(r,i)/n)}var to=class extends V{descriptor={id:`advdecline`,name:`Advance/Decline`,placement:`panel`,defaultConfig:{length:10},shortName:`A/D Ratio`,inputs:{length:{min:1}},plots:[{key:`value`,title:`Ratio`,color:0}],scale:{min:0}};read(e){return{length:L(e,`length`,10,1)}}pointAt(e,t,{length:n}){if(t<n-1)return null;let r=0,i=0;for(let a=t-n+1;a<=t;a++)e[a].close>e[a].open?r++:e[a].close<e[a].open&&i++;return{value:i===0?r:r/i}}},no=class extends V{descriptor={id:`majority`,name:`Majority Rule`,placement:`panel`,defaultConfig:{period:14},shortName:`Majority`,inputs:{period:{min:1}},plots:[{key:`value`,title:`Majority`,color:0}],scale:{min:0,max:100},levels:[50]};read(e){return{period:L(e,`period`,14,1)}}pointAt(e,t,{period:n}){if(t<n)return null;let r=0;for(let i=t-n+1;i<=t;i++)e[i].close>e[i-1].close&&r++;return{value:100*r/n}}},ro=34,io=30,ao=class extends P{descriptor={id:`chopzone`,name:`Chop Zone`,placement:`panel`,defaultConfig:{},shortName:`Chop Zone`,plots:[{key:`angle`,title:`Angle`,color:0,kind:`histogram`}],scale:{zero:!0}};calculate(e,t){let n=B(z(e),ro),r=Array(e.length).fill(null);for(let t=1;t<e.length;t++){let i=n[t],a=n[t-1],o=ni(e,t,io),s=ri(e,t,io);if(i===void 0||a===void 0||o===void 0||s===void 0||o===s)continue;let c=e[t],l=(c.high+c.low+c.close)/3;if(!(l>0&&s>0))continue;let u=(i-a)/l*(25/(o-s)*s);r[t]={angle:Math.atan(u)*180/Math.PI}}return R(e,r)}render(t,n,r,i){if(i.plots?.angle?.visible===!1)return;let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=e.T(0,r),l=[];for(let t=o;t<=s&&t<a.length;t++){let n=a[t]?.angle;n!==void 0&&l.push({x:e.b(t,r),y:e.T(n,r),baseY:c,color:oo(n)})}this.drawHistogram(t,l,Math.max(1,r.barWidth))}};function oo(e){return e>=5?`#26C6DA`:e>=3.57?`#43A047`:e>=2.14?`#A5D6A7`:e>=.71?`#009688`:e<=-5?`#D50000`:e<=-3.57?`#E91E63`:e<=-2.14?`#FF6D00`:e<=-.71?`#FFB74D`:`#FDD835`}var so=class extends P{descriptor={id:`smiergodic`,name:`SMI Ergodic`,placement:`panel`,defaultConfig:{short:5,long:20,signal:5,source:`close`},shortName:`SMIIO`,inputs:{short:{min:1},long:{min:1},signal:{min:1},source:{source:!0}},plots:[{key:`oscillator`,title:`Oscillator`,color:2,kind:`histogram`,tone:`sign`,downColor:3},{key:`indicator`,title:`Indicator`,color:0},{key:`signal`,title:`Signal`,color:1}],scale:{zero:!0}};calculate(e,t){let n=L(t,`short`,5,1),r=L(t,`long`,20,1),i=e.map((t,n)=>n===0?void 0:t.close-e[n-1].close),a=B(B(i,r),n),o=B(B(i.map(e=>e===void 0?void 0:Math.abs(e)),r),n),s=a.map((e,t)=>e===void 0||!o[t]?void 0:e/o[t]),c=B(s,L(t,`signal`,5,1));return R(e,s.map((e,t)=>{if(e===void 0)return null;let n=c[t];return n===void 0?{indicator:e}:{indicator:e,signal:n,oscillator:e-n}}))}},co=class extends P{descriptor={id:`po`,name:`Price Oscillator`,placement:`panel`,defaultConfig:{short:10,long:21,source:`close`},shortName:`PO`,inputs:{short:{min:1},long:{min:1},source:{source:!0}},plots:[{key:`value`,title:`PO`,color:0}],scale:{zero:!0}};calculate(e,t){let n=z(e),r=Kr(n,L(t,`short`,10,1)),i=Kr(n,L(t,`long`,21,1));return R(e,ei(r.map((e,t)=>e===void 0||i[t]===void 0?void 0:e-i[t])))}},lo=e=>({period:L(e,`period`,10,1),annual:Math.max(1,I(e,`annual`,365))}),uo={period:{min:1},annual:{label:`Bars per year`,min:1}},fo=class extends V{descriptor={id:`volohlc`,name:`Volatility O-H-L-C`,placement:`panel`,defaultConfig:{period:10,annual:365},shortName:`Vol OHLC`,inputs:uo,plots:[{key:`value`,title:`Volatility`,color:0}],scale:{min:0}};read(e){return lo(e)}pointAt(e,t,{period:n,annual:r}){if(t<n-1)return null;let i=0;for(let r=t-n+1;r<=t;r++){let{open:t,high:n,low:a,close:o}=e[r];if(!(t>0&&n>0&&a>0&&o>0))return null;i+=.5*Math.log(n/a)**2-(2*Math.LN2-1)*Math.log(o/t)**2}return{value:100*Math.sqrt(Math.max(0,i/n*r))}}},po=class extends V{descriptor={id:`volzt`,name:`Volatility Zero Trend Close-to-Close`,placement:`panel`,defaultConfig:{period:10,annual:365},shortName:`Vol ZT`,inputs:uo,plots:[{key:`value`,title:`Volatility`,color:0}],scale:{min:0}};read(e){return lo(e)}pointAt(e,t,{period:n,annual:r}){if(t<n)return null;let i=0;for(let r=t-n+1;r<=t;r++){let t=e[r-1].close,n=e[r].close;if(!(t>0&&n>0))return null;i+=Math.log(n/t)**2}return{value:100*Math.sqrt(i/n*r)}}};function mo(e){e.register(new dn),e.register(new fn),e.register(new pn),e.register(new mn),e.register(new hn),e.register(new gn),e.register(new _n),e.register(new vn),e.register(new yn),e.register(new Sn),e.register(new wn),e.register(new Tn),e.register(new En),e.register(new Dn),e.register(new An),e.register(new jn),e.register(new Mn),e.register(new Nn),e.register(new Fn),e.register(new In),e.register(new Ln),e.register(new Vn),e.register(new Wn),e.register(new Gn),e.register(new Kn),e.register(new qn),e.register(new Jn),e.register(new Yn),e.register(new Xn),e.register(new Zn),e.register(new Qn),e.register(new $n),e.register(new er),e.register(new tr),e.register(new nr),e.register(new Hr),e.register(new Ur),e.register(new Wr),e.register(new Gr),e.register(new Hn),e.register(new Un),e.register(new rr),e.register(new ir),e.register(new ar),e.register(new or),e.register(new cr),e.register(new lr),e.register(new dr),e.register(new fr),e.register(new hr),e.register(new gr),e.register(new vr),e.register(new yr),e.register(new br),e.register(new xr),e.register(new Sr),e.register(new Cr),e.register(new wr),e.register(new Er),e.register(new Dr),e.register(new Or),e.register(new kr),e.register(new Ar),e.register(new jr),e.register(new Pr),e.register(new Ir),e.register(new Rr),e.register(new zr),e.register(new Br),e.register(new Vr),e.register(new oi),e.register(new si),e.register(new ci),e.register(new li),e.register(new ui),e.register(new di),e.register(new mi),e.register(new gi),e.register(new _i),e.register(new bi),e.register(new xi),e.register(new Si),e.register(new Ci),e.register(new wi),e.register(new Ei),e.register(new ki),e.register(new Ai),e.register(new ji),e.register(new Mi),e.register(new Ni),e.register(new Pi),e.register(new Fi),e.register(new Ii),e.register(new zi),e.register(new Bi),e.register(new Hi),e.register(new Ui),e.register(new Wi),e.register(new Ha),e.register(new Ka),e.register(new Xa),e.register(new Za),e.register(new Qa),e.register(new $a),e.register(new to),e.register(new no),e.register(new ao),e.register(new so),e.register(new co),e.register(new fo),e.register(new po),e.register(new Ki),e.register(new qi),e.register(new Ji),e.register(new Yi),e.register(new Xi),e.register(new Zi),e.register(new Qi),e.register(new $i),e.register(new ta),e.register(new ia),e.register(new aa),e.register(new oa),e.register(new sa),e.register(new ca),e.register(new la),e.register(new ua),e.register(new da),e.register(new fa),e.register(new pa),e.register(new Gi),e.register(new ma),e.register(new ha),e.register(new Ra)}var ho=[`movingAverages`,`trend`,`oscillators`,`volatility`,`volume`,`bands`,`patterns`,`other`],go=new Map(Object.entries({movingAverages:[`sma`,`ema`,`wma`,`vwma`,`hma`,`tema`,`dema`,`smma`,`alma`,`kama`,`lsma`,`mcginley`,`mtfma`,`macross`,`gmma`,`maribbon`,`hamming`,`madouble`,`matriple`,`rainbow`,`alligator`,`tsf`],trend:[`ichimoku`,`psar`,`supertrend`,`chandelier`,`cks`,`volindex`,`adx`,`aroon`,`vortex`,`chop`,`chopzone`,`vhf`,`trendstrength`,`lrslope`,`rsquared`,`rwi`,`majority`,`asi`],oscillators:`rsi.macd.stochastic.williamsR.cci.roc.tsi.ao.uo.crsi.coppock.kst.elderray.stc.fisher.dpo.bop.cmo.trix.rvi.stochrsi.ppo.ac.rmi.disparity.qstick.pgo.bbpb.mom.smi.smiergodic.po.psy.newpsy.sonar.binarywave.sroc.abratio.advdecline`.split(`.`),volatility:[`atr`,`stddev`,`chaikinvol`,`bbw`,`hv`,`ulcer`,`rvix`,`stderror`,`adr`,`volohlc`,`volzt`,`sigma`,`tr`,`massindex`],volume:[`vwap`,`avwap`,`svwap`,`volumeProfile`,`obv`,`mfi`,`cmf`,`ad`,`vroc`,`chaikinOsc`,`voldelta`,`fi`,`kvo`,`emv`,`pvt`,`wad`,`vo`,`netvolume`,`vr`,`nvi`,`pvi`,`iii`,`volpct`,`volchange`,`tradevalue`],bands:[`bb`,`keltner`,`donchian`,`envelope`,`lrc`,`seb`,`machannel`],patterns:[`pivots`,`zigzag`,`fractals`,`candlepatterns`,`demark`,`avgprice`,`medprice`,`typprice`,`wclose`]}).flatMap(([e,t])=>t.map(t=>[t,e])));function _o(e){return e.category??go.get(e.id)??`other`}function vo(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.requestId==`number`?t.type===`result`||t.type===`pong`||t.type===`error`:!1}var yo=class{worker;fallbackPlugins;timeoutMs;nextRequestId=1;pending=new Map;messageHandler;constructor(e,t={}){this.worker=e,this.fallbackPlugins=t.fallbackPlugins??new Map,this.timeoutMs=t.timeoutMs??3e4,this.messageHandler=e=>this.handleMessage(e),this.worker&&(this.worker.addEventListener(`message`,this.messageHandler),this.worker.addEventListener(`error`,this.messageHandler))}hasWorker(){return this.worker!==null}registerFallbackPlugin(e){this.fallbackPlugins.set(e.descriptor.id,e)}async calculate(e,t,n){if(!this.worker){let r=this.fallbackPlugins.get(e);if(!r)throw Error(`Unknown indicator: ${e}`);return r.calculate(n,t)}let r=this.nextRequestId++,i={type:`calculate`,requestId:r,indicatorId:e,config:t,data:n};return new Promise((t,n)=>{let a={resolve:t,reject:n,timer:null};this.timeoutMs>0&&(a.timer=setTimeout(()=>{this.pending.delete(r),n(Error(`Indicator worker timeout (${this.timeoutMs}ms): ${e}`))},this.timeoutMs)),this.pending.set(r,a),this.worker.postMessage(i)})}ping(){if(!this.worker)return Promise.resolve();let e=this.nextRequestId++;return new Promise((t,n)=>{let r={resolve:()=>t(),reject:n,timer:this.timeoutMs>0?setTimeout(()=>{this.pending.delete(e),n(Error(`Indicator worker ping timeout`))},this.timeoutMs):null};this.pending.set(e,r),this.worker.postMessage({type:`ping`,requestId:e})})}terminate(){this.worker&&=(this.worker.removeEventListener(`message`,this.messageHandler),this.worker.removeEventListener(`error`,this.messageHandler),this.worker.terminate(),null);for(let e of this.pending.values())e.timer&&clearTimeout(e.timer),e.reject(Error(`Indicator worker terminated`));this.pending.clear()}handleMessage(e){let t=e.data;if(t!==void 0){if(!vo(t))return;this.dispatchResponse(t);return}let n=e.message??`Indicator worker error`;for(let[e,t]of this.pending)t.timer&&clearTimeout(t.timer),t.reject(Error(n)),this.pending.delete(e)}dispatchResponse(e){let t=this.pending.get(e.requestId);if(t){if(this.pending.delete(e.requestId),t.timer&&clearTimeout(t.timer),e.type===`error`){t.reject(Error(e.message));return}if(e.type===`pong`){t.resolve(void 0);return}t.resolve(e.output)}}},bo=new Set([`compareSymbol`,`spread`,`correlation`,`correlationlog`]),xo=e=>typeof e.params.symbol==`string`?e.params.symbol.trim():``,So=class extends V{descriptor={id:`compareSymbol`,name:`Compare Symbol`,placement:`overlay`,defaultConfig:{symbol:``},shortName:`Compare`,plots:[{key:`value`,title:`Close`,color:0}]};constructor(e){super(),this.store=e}read(e){return{symbol:xo(e)}}pointAt(e,n,{symbol:r}){if(!r)return null;let i=this.store.closeAt(r,e[n].time,(0,t.barTimeUnit)(e));return i===void 0?null:{value:i}}},Co=class extends V{descriptor={id:`spread`,name:`Spread / Ratio`,placement:`panel`,defaultConfig:{symbol:``,mode:`spread`},shortName:`Spread`,plots:[{key:`value`,title:`Spread`,color:0}],inputs:{mode:{options:[`spread`,`ratio`]}}};constructor(e){super(),this.store=e}read(e){return{symbol:xo(e),ratio:e.params.mode===`ratio`}}pointAt(e,n,{symbol:r,ratio:i}){if(!r)return null;let a=this.store.closeAt(r,e[n].time,(0,t.barTimeUnit)(e));return a===void 0?null:i?a===0?null:{value:e[n].close/a}:{value:e[n].close-a}}},wo=e=>{let t=Math.round(Number(e.params.length??20));return{symbol:xo(e),length:Number.isFinite(t)?Math.max(2,t):20}};function To(e,t){if(e.every(t=>t===e[0])||t.every(e=>e===t[0]))return null;let n=e.length,r=0,i=0;for(let a=0;a<n;a++)r+=e[a],i+=t[a];r/=n,i/=n;let a=0,o=0,s=0;for(let c=0;c<n;c++){let n=e[c]-r,l=t[c]-i;a+=n*l,o+=n*n,s+=l*l}return o>0&&s>0?Math.max(-1,Math.min(1,a/Math.sqrt(o*s))):null}var Eo={placement:`panel`,defaultConfig:{symbol:``,length:20},inputs:{length:{min:2}},plots:[{key:`value`,title:`Correlation`,color:0}],scale:{min:-1,max:1},levels:[0]},Do=class extends V{descriptor={...Eo,id:`correlation`,name:`Correlation Coefficient`,shortName:`Correlation`};constructor(e){super(),this.store=e}read(e){return wo(e)}pointAt(e,n,{symbol:r,length:i}){if(!r||n<i-1)return null;let a=[],o=[];for(let s=n-i+1;s<=n;s++){let n=this.store.closeAt(r,e[s].time,(0,t.barTimeUnit)(e));if(n===void 0)return null;a.push(e[s].close),o.push(n)}let s=To(a,o);return s===null?null:{value:s}}},Oo=class extends V{descriptor={...Eo,id:`correlationlog`,name:`Correlation Log`,shortName:`Correlation Log`};constructor(e){super(),this.store=e}read(e){return wo(e)}pointAt(e,n,{symbol:r,length:i}){if(!r||n<i)return null;let a=[],o=[],s=this.store.closeAt(r,e[n-i].time,(0,t.barTimeUnit)(e));for(let c=n-i+1;c<=n;c++){let n=this.store.closeAt(r,e[c].time,(0,t.barTimeUnit)(e)),i=e[c-1].close,l=e[c].close;if(n===void 0||s===void 0||!(i>0&&l>0&&n>0&&s>0))return null;a.push(Math.log(l/i)),o.push(Math.log(n/s)),s=n}let c=To(a,o);return c===null?null:{value:c}}},U={year:100,quarter:91,month:90,dayOfFive:81,day:80,hour12:73,hour6:72,hour3:71,hour:70,minute30:63,minute15:62,minute5:61,minute:60,within:50},ko=[...new Set(Object.values(U))].sort((e,t)=>t-e);function Ao(e){return e>=U.year?`year`:e>=U.month?`month`:e>=U.day?`day`:`time`}function jo(e,t){if(!e)return 0;if(t.year!==e.year)return U.year;if(t.month!==e.month)return t.month%3==1?U.quarter:U.month;if(t.day!==e.day)return t.day%5==0?U.dayOfFive:U.day;if(t.hours!==e.hours){let e=t.hours;return e%12==0?U.hour12:e%6==0?U.hour6:e%3==0?U.hour3:U.hour}if(t.minutes!==e.minutes){let e=t.minutes;return e%30==0?U.minute30:e%15==0?U.minute15:e%5==0?U.minute5:U.minute}return U.within}var Mo=256,No=1.25;function Po(e){return e>1?Math.ceil(No**Math.ceil(Math.log(e)/Math.log(No)-1e-9)):1}var Fo=class{weights=new Uint8Array;times=[];weighed=null;chosen=new Int32Array;chosenFor=null;marks(e,t){let n=e.length;if(n===0)return[];let r=Po(t.gapBars),i=t.timesPastData?Math.max(n-1,Math.ceil(t.to)):n-1,a=i<=n-1?n:Math.ceil((i+1-n)/Mo)*Mo+n;this.weigh(e,t.tz,a),this.choose(r,a);let o=Math.max(0,Math.floor(t.from)),s=Math.min(i,Math.ceil(t.to)),c=this.chosen,l=0,u=c.length;for(;l<u;){let e=l+u>>1;c[e]<o?l=e+1:u=e}let d=[];for(let e=l;e<c.length&&c[e]<=s;e++){let t=c[e];d.push({index:t,time:this.times[t],weight:this.weights[t]})}return d}weigh(n,r,i){let a=n.length,o=(0,t.barTimeUnit)(n),s=this.weighed,c=0;if(s&&s.tz===r&&s.unit===o){let e=Math.min(s.bars,a),t=this.times;for(;c<e&&n[c].time*o===t[c];)c++;c<e&&(c=0)}if(s&&c===a&&s.bars===a&&s.extent===i)return;let l=new Uint8Array(i),u=Array(i);if(c>0){l.set(this.weights.subarray(0,c));for(let e=0;e<c;e++)u[e]=this.times[e]}let d=c>0?(0,t.timeParts)(u[c-1],r):null;for(let s=c;s<i;s++){let i=(s<a?n[s].time:e.y(s,n))*o,c=(0,t.timeParts)(i,r);l[s]=jo(d,c),u[s]=i,d=c}this.weights=l,this.times=u,this.weighed={bars:a,tz:r,extent:i,unit:o}}choose(e,t){let n=this.chosenFor;if(n&&n.gapBars===e&&n.extent===t&&n.weights===this.weights)return;let r=this.weights,i=new Uint8Array(t),a=[];for(let n of ko)for(let o=0;o<t;o++){if(r[o]!==n||i[o])continue;a.push(o);let s=Math.max(0,o-e+1),c=Math.min(t-1,o+e-1);for(let e=s;e<=c;e++)i[e]=1}this.chosen=Int32Array.from(a).sort(),this.chosenFor={gapBars:e,extent:t,weights:r}}},Io=e=>e<10?`0`+e:``+e,Lo=8,Ro=new Map;function zo(e){let t=Ro.get(e);if(!t){let n;try{n=new Intl.DateTimeFormat(e,{month:`short`,timeZone:`UTC`})}catch{n=new Intl.DateTimeFormat(`en-US`,{month:`short`,timeZone:`UTC`})}t=Array.from({length:12},(e,t)=>n.format(Date.UTC(2e3,t,15))),Ro.set(e,t)}return t}var Bo=class{tz=null;timeFormatter=null;timesPastData=!0;locale=`en-US`;columns=[];marker=new Fo;setLocale(e){this.locale=e}setTimezoneOffset(e){this.tz=e}setTimeFormatter(e){this.timeFormatter=e}setTimesPastData(e){this.timesPastData=e}getTimesPastData(){return this.timesPastData}marks(e,t){let n=e.barWidth+e.barSpacing;return!(n>0)||t.length===0?[]:this.marker.marks(t,{from:Math.floor(e.offset/n),to:Math.ceil((e.offset+e.chartRect.width)/n),gapBars:80/n,tz:this.tz,timesPastData:this.timesPastData})}label(e,n){if(this.timeFormatter)return this.timeFormatter(e.time,{kind:n,timeZone:this.tz});let r=(0,t.timeParts)(e.time,this.tz);if(n===`year`)return String(r.year);if(n===`month`)return zo(this.locale)[r.month-1];if(n===`day`)return String(r.day);let i=`${Io(r.hours)}:${Io(r.minutes)}`;return e.weight===U.within?`${i}:${Io(new Date(e.time).getUTCSeconds())}`:i}labelColumns(){return this.columns}render(n,r,i,a,o){let{chartRect:s}=r,c=o??s.y+s.height;n.strokeStyle=i.style?.axis.time.line??i.axisLine,n.lineWidth=1,n.globalAlpha=.65,n.beginPath(),n.moveTo(s.x,c+.5),n.lineTo(s.x+s.width,c+.5),n.stroke(),n.globalAlpha=1;let l=r.barWidth+r.barSpacing,u=-r.offset+s.x+r.barWidth/2,d=Math.ceil((r.offset+s.width)/l),f=(0,t.barTimeUnit)(a),p=a.length>0?e.y(Math.min(d,a.length-1),a):Date.now(),m=(0,t.tzLabel)(this.tz,p*f),h=`500 ${i.font.sizeSmall-1}px ${i.font.family}`,g=s.x+s.width-4;n.font=h;let _=g-n.measureText(m).width-8,v=`500 ${i.font.sizeSmall}px ${i.font.family}`,y=`600 ${i.font.sizeSmall}px ${i.font.family}`;n.textBaseline=`top`,n.textAlign=`center`,n.fillStyle=i.style?.axis.time.text??i.axisLabel;let b=[],x=this.marks(r,a).sort((e,t)=>t.weight-e.weight||e.index-t.index);for(let e of x){let t=e.index*l+u,r=Ao(e.weight),i=this.label(e,r);n.font=r===`year`?y:v;let a=n.measureText(i).width/2;t+a>_||b.some(e=>t-a<e.right+Lo&&t+a+Lo>e.left)||(b.push({left:t-a,right:t+a}),n.fillText(i,t,c+7))}this.columns=b,n.font=h,n.textAlign=`right`,n.textBaseline=`top`,n.globalAlpha=.75,n.fillStyle=i.textSecondary,n.fillText(m,g,c+7),n.globalAlpha=1}},Vo={line:16,handle:22,alert:16,order:16,button:8,divider:12},Ho=300,Uo=24,Wo=class{last=null;tap(e,t=Date.now()){let n=this.last;return n&&t-n.at<=300&&Math.hypot(e.x-n.pos.x,e.y-n.pos.y)<=24?(this.last=null,!0):(this.last={pos:e,at:t},!1)}reset(){this.last=null}},Go=new Set,Ko=null,qo=4,Jo=8,Yo=500,Xo=800,Zo={ctrl:!1,shift:!1,alt:!1};function Qo(){let e=typeof document<`u`?document.activeElement:null;return e instanceof Element&&e.closest(`[aria-modal="true"], [role="dialog"], [role="menu"]`)!==null}var $o=class{panHandler=null;zoomHandler=null;crosshairHandler=null;axisDragHandler=null;alertDragHandler=null;axisViewportGetter=null;onAxisDoubleClick=null;onDrawingDoubleClick=null;onDrawingContextMenu=null;zoomArea=!1;onChartContextMenu=null;priceAxisAdd=null;axisStrips=null;savedTouchAction=``;measureHandlers=null;measuring=!1;boxSelectHandlers=null;boxSelecting=!1;onAltClick=null;onEscape=null;onConfirm=null;onClick=null;markerAt=null;onMarkerHover=null;markerClickable=()=>!0;markerPos={x:0,y:0};hoveredMarker=null;downPos=null;downMoved=!1;pressForClick=!1;drawingManager=null;tradingManager=null;paneResizeHandler=null;viewportGetter=null;onOverlayDirty=null;boundHandlers=[];lastTouchDist=0;lastTouchMid={x:0,y:0};touchActive=!1;touchStartPos={x:0,y:0};longPressTimer=null;longPressed=!1;touchFallthrough=!1;touchDecided=!1;touchYielded=!1;taps=new Wo;pageScroll=!1;touchStartPrevented=!1;lastTouchAt=-1/0;pressPlacedPoint=!1;cachedRect=null;constructor(e){this.element=e}setOverlayDirtyCallback(e){this.onOverlayDirty=e}setPanHandler(e){this.panHandler=e,this.refreshTouchAction()}setZoomHandler(e){this.zoomHandler=e,this.refreshTouchAction()}setCrosshairHandler(e){this.crosshairHandler=e}setAltClickHandler(e){this.onAltClick=e}setEscapeHandler(e){this.onEscape=e}setConfirmHandler(e){this.onConfirm=e}setSignalMarkerHitTest(e,t,n=()=>!0){this.markerAt=e,this.onMarkerHover=t,this.markerClickable=n,e||(this.hoveredMarker=null)}leaveMarker(){this.hoveredMarker!==null&&(this.hoveredMarker=null,this.onMarkerHover?.(null,this.markerPos))}setClickHandler(e){this.onClick=e}setBoxSelectHandlers(e){this.boxSelectHandlers=e}setMeasureHandlers(e){this.measureHandlers=e}setAxisDragHandler(e,t,n){this.axisDragHandler=e,this.axisViewportGetter=t,this.onAxisDoubleClick=n??null}setDrawingManager(e,t){this.drawingManager=e,this.viewportGetter=t}setChartContextMenu(e){this.onChartContextMenu=e}setPriceAxisAddButton(e,t){this.priceAxisAdd={button:e,onClick:t}}setZoomAreaMode(e){this.zoomArea=e}setDrawingContextMenu(e){this.onDrawingContextMenu=e}setDrawingDoubleClick(e){this.onDrawingDoubleClick=e}setAlertDragHandler(e){this.alertDragHandler=e}setTradingManager(e,t){this.tradingManager=e,this.viewportGetter=t}setAxisStrips(e){this.axisStrips=e}setPaneResizeHandler(e){this.paneResizeHandler=e}setPageScroll(e){this.pageScroll=e,this.refreshTouchAction()}refreshTouchAction(){Go.has(this.element)&&this.element.style.setProperty(`touch-action`,this.touchAction())}pageTakes(){let e=!this.panHandler,t=this.pageScroll||!this.panHandler;return{x:e,y:t,zoom:!this.zoomHandler,any:e||t}}touchAction(){let e=this.pageTakes();if(e.x&&e.y&&e.zoom)return`manipulation`;let t=[e.x&&`pan-x`,e.y&&`pan-y`,e.zoom&&`pinch-zoom`].filter(Boolean);return t.length>0?t.join(` `):`none`}attach(){let e=()=>this.viewportGetter?.()??null;Go.add(this.element),this.savedTouchAction=this.element.style.getPropertyValue(`touch-action`),this.element.style.setProperty(`touch-action`,this.touchAction());let t=e=>{let t=this.axisStrips?.()??null,n=t?.plot??this.axisViewportGetter?.()?.chartRect;if(!n)return null;let r=this.axisDragHandler!==null;if(e.y>(t?.timeAxisTop??n.y+n.height))return r?`time`:null;let i=e.y>=n.y&&e.y<=n.y+n.height;if(e.x>n.x+n.width)return i?r?`price`:null:`inert`;let a=t?.left;return a&&a.width>0&&e.x<n.x&&e.x>=n.x-a.width?i&&a.scales&&r?`price`:`inert`:null},n=e=>{let t=this.axisStrips?.()??null,n=t?.plot??this.axisViewportGetter?.()?.chartRect;if(!n)return`plot`;if(e.y>(t?.timeAxisTop??n.y+n.height))return`timeAxis`;let r=e.y>=n.y&&e.y<=n.y+n.height,i=t?.left,a=!!i&&i.width>0&&e.x<n.x&&e.x>=n.x-i.width;return e.x>n.x+n.width||a?r?`priceAxis`:`pane`:r?`plot`:`pane`},r=e=>{let t=(this.viewportGetter?.()??this.axisViewportGetter?.())?.chartRect;return t?{x:Math.max(t.x,Math.min(t.x+t.width,e.x)),y:Math.max(t.y,Math.min(t.y+t.height,e.y))}:e},i=()=>this.zoomArea?`zoom-in`:this.crosshairHandler&&this.crosshairHandler.getMode()!==`hidden`?`crosshair`:``,a=e=>{this.element.style.cursor!==e&&(this.element.style.cursor=e)},o=n=>{let r=t(n);if(r===`price`)return`ns-resize`;if(r===`time`)return`ew-resize`;if(r===`inert`)return`default`;let a=this.paneResizeHandler?.cursorAt(n);if(a)return a;if(this.alertDragHandler?.isOverAlert(n))return`ns-resize`;let o=e();return this.tradingManager?.isOverButton(n)?`pointer`:o&&this.tradingManager?.isOverDraggableLine(n,o)?`ns-resize`:this.zoomArea?`zoom-in`:(o?this.drawingManager?.hoverCursorAt(n,o):null)||(o&&this.priceAxisAdd?.button.hit(n,o)?`pointer`:i())},s=!1,c=``,l=e=>{if(!(e.buttons&1)){b(e);return}g(e)},u=()=>{s||(s=!0,this.leaveMarker(),c=document.documentElement.style.userSelect,document.documentElement.style.userSelect=`none`,document.addEventListener(`mousemove`,l))},d=()=>{s&&(s=!1,document.documentElement.style.userSelect=c,document.removeEventListener(`mousemove`,l))},f=e=>e===this.element||e instanceof HTMLCanvasElement,p=(n,r,o)=>{this.panHandler?.cancelMomentum();let s=e(),c=o===`mouse`,l=c?void 0:Vo;this.pressPlacedPoint=!1,this.downPos=n,this.downMoved=!1,this.pressForClick=!1;let u=t(n);if(u===`inert`)return`inert`;if(u&&this.axisDragHandler)return this.axisDragHandler.begin(u,n),`taken`;if(this.paneResizeHandler?.tryBegin(n,l?.divider))return`taken`;let d=!!this.drawingManager?.getActiveTool()||!!this.tradingManager?.isBracketActive()||!!this.tradingManager?.isOrderDraftActive();return this.boxSelectHandlers&&(this.zoomArea||r.ctrl&&!d)?(this.boxSelecting=!0,this.boxSelectHandlers.begin(n),c&&a(i()),this.onOverlayDirty?.(!0),`taken`):r.shift&&this.measureHandlers?(this.measuring=!0,this.measureHandlers.begin(n),this.onOverlayDirty?.(!0),`taken`):r.alt&&this.onAltClick?(this.onAltClick(n),`taken`):this.priceAxisAdd&&s&&!d&&this.priceAxisAdd.button.hit(n,s)&&!this.alertDragHandler?.isOverAlert(n)&&!this.tradingManager?.isOverButton(n)&&!this.tradingManager?.isOverDraggableLine(n,s)&&!this.drawingManager?.hoverCursorAt(n,s)?(this.priceAxisAdd.onClick(n),`menu`):this.tradingManager&&s&&this.tradingManager.onPointerDown(n,s,l)?(c&&a(this.tradingManager.isOverButton(n)?`pointer`:`ns-resize`),`taken`):this.drawingManager&&s&&this.drawingManager.onPointerDown(n,s,l)?(c&&this.drawingManager.isDragging()&&a(`grabbing`),this.pressPlacedPoint=!!this.drawingManager.getActiveTool(),d||this.drawingManager.isEraser()?`taken`:`drawing`):this.alertDragHandler?.tryBegin(n,l?.alert)?(this.onOverlayDirty?.(),`taken`):(this.pressForClick=!0,this.panHandler&&(this.panHandler.onPointerDown(n),c&&a(`grabbing`)),`pan`)},m=e=>{if(Ko=this.element,e.button!==0||!f(e.target))return;u(),this.invalidateRect();let t={ctrl:e.ctrlKey||e.metaKey,shift:e.shiftKey,alt:e.altKey};p(this.getMousePos(e),t,`mouse`)===`menu`&&e.preventDefault()},h=e=>{if(!s){if(!f(e.target)){this.leaveMarker();return}g(e)}},g=e=>{let t=this.getMousePos(e);if(!s){let e=this.markerAt?.(t)??null;e!==this.hoveredMarker&&(this.hoveredMarker=e,this.onMarkerHover?.(e,t)),e&&(this.markerPos=t),a(e&&this.markerClickable()?`pointer`:o(t))}_(t,`mouse`,s)},_=(t,n,i,a=t)=>{let o=e();if(this.downPos&&!this.downMoved){let e=n===`mouse`?qo:Jo;Math.hypot(t.x-this.downPos.x,t.y-this.downPos.y)>e&&(this.downMoved=!0)}if(this.axisDragHandler?.isActive()){this.axisDragHandler.move(t),n===`touch`&&this.onOverlayDirty?.();return}if(this.paneResizeHandler?.isActive()){this.paneResizeHandler.move(t),n===`touch`&&this.onOverlayDirty?.();return}if(this.alertDragHandler?.isActive()){this.alertDragHandler.move(r(t)),this.onOverlayDirty?.();return}if(this.measuring&&this.measureHandlers){this.measureHandlers.move(t),this.onOverlayDirty?.(!0);return}if(this.boxSelecting&&this.boxSelectHandlers){this.boxSelectHandlers.move(t),this.onOverlayDirty?.(!0);return}if(this.tradingManager&&o&&this.tradingManager.onPointerMove(i?r(t):t,o)){this.crosshairHandler?.onPointerMove(t),this.onOverlayDirty?.();return}if(this.drawingManager&&o&&this.drawingManager.onPointerMove(t,o)){this.crosshairHandler?.onPointerMove(t),this.onOverlayDirty?.();return}this.panHandler?.onPointerMove(a),this.crosshairHandler?.onPointerMove(t),this.onOverlayDirty?.(!i)},v=(t,n,r=!1)=>{let i=this.downPos,a=this.downMoved&&i!==null,o=this.pressPlacedPoint,s=this.pressForClick&&!this.downMoved&&i!==null&&!r;if(this.pressForClick=!1,this.pressPlacedPoint=!1,this.downPos=null,this.downMoved=!1,this.boxSelecting&&this.boxSelectHandlers)return this.boxSelecting=!1,r?this.boxSelectHandlers.cancel():this.boxSelectHandlers.end(),this.onOverlayDirty?.(!0),!1;if(this.axisDragHandler?.isActive())return this.axisDragHandler.end(),!1;if(this.paneResizeHandler?.isActive())return this.paneResizeHandler.end(),!1;if(this.alertDragHandler?.isActive())return this.alertDragHandler.end(),this.onOverlayDirty?.(),!1;if(this.measuring&&this.measureHandlers)return this.measuring=!1,this.measureHandlers.end(),this.onOverlayDirty?.(!0),!1;if(r?this.tradingManager?.cancelPointer():this.tradingManager?.onPointerUp(t??void 0))return!1;let c=e();return r&&o&&this.drawingManager?.takeBackPoint(),n===`touch`&&a&&!r&&t&&c&&this.drawingManager?.placeAt(t,c),this.drawingManager?.onPointerUp()?!1:(this.panHandler?.onPointerUp(),r&&this.panHandler?.cancelMomentum(),s&&this.onClick&&this.onClick(i),s)},y=(n,r)=>{let i=t(n);if(i){i!==`inert`&&this.onAxisDoubleClick?.(i);return}let a=e();if(!a||this.drawingManager?.justFinished())return;let o=this.drawingManager?.drawingAt(n,a,r);o&&this.onDrawingDoubleClick?.(o)},b=e=>{if(e.button!==0&&e.type===`mouseup`||!s)return;d();let t=this.getMousePos(e);a(o(t)),v(t,`mouse`)},x=e=>{y(this.getMousePos(e))},S=()=>{if(this.leaveMarker(),s){this.crosshairHandler?.onPointerLeave(),this.onOverlayDirty?.(!0);return}a(``),this.panHandler?.onPointerUp(),this.drawingManager?.onPointerUp(),this.tradingManager?.onPointerUp(),this.alertDragHandler?.end(),this.paneResizeHandler?.end(),this.crosshairHandler?.onPointerLeave(),this.pressForClick=!1,this.downPos=null,this.onOverlayDirty?.()},C=e=>{if(!this.zoomHandler||this.pageScroll&&!e.ctrlKey)return;e.preventDefault();let t=this.getMousePos(e);this.zoomHandler.onWheel(e.deltaY,t)},w=e=>{if(!Qo()){if(e.key===`Escape`&&this.boxSelecting&&this.boxSelectHandlers&&(this.boxSelecting=!1,this.boxSelectHandlers.cancel(),this.onOverlayDirty?.(!0)),e.key===`Escape`&&this.onEscape&&this.onEscape(),e.key===`Enter`&&this.onConfirm&&this.onConfirm()){e.preventDefault();return}e.key!==`Escape`&&!this.ownsShortcuts()||this.drawingManager?.onKeyDown(e.key,e.ctrlKey||e.metaKey,e.shiftKey)&&e.preventDefault()}},T=t=>{if(this.touchActive||Date.now()-this.lastTouchAt<Xo){t.preventDefault();return}let r=e();if(!r)return;let i=this.getMousePos(t),a=r.chartRect,o=i.x>=a.x&&i.x<=a.x+a.width&&i.y>=a.y&&i.y<=a.y+a.height,s=this.onDrawingContextMenu&&o&&!this.drawingManager?.getActiveTool()?this.drawingManager?.drawingAt(i,r):null;if(s){t.preventDefault(),this.onDrawingContextMenu?.(s,i);return}if(this.tradingManager?.onContextMenu(i,r)){t.preventDefault();return}this.onChartContextMenu?.(n(i),i)&&t.preventDefault()},E=e=>{if(Ko=this.element,!(!this.touchActive&&!f(e.target))){if(this.lastTouchAt=Date.now(),this.invalidateRect(),e.touches.length===1){let t=this.getTouchPos(e.touches[0]);this.touchStartPos=t,this.longPressed=!1,this.touchYielded=!1,this.touchDecided=!1;let n=p(t,Zo,`touch`);if(this.touchActive=!0,this.touchFallthrough=n===`pan`||n===`inert`,this.touchStartPrevented=!(this.touchFallthrough&&this.pageTakes().any),this.touchStartPrevented&&e.preventDefault(),n===`drawing`){D(t);return}if(n!==`pan`)return;this.onAltClick&&(this.clearLongPress(),this.longPressTimer=setTimeout(()=>{this.longPressTimer=null,this.longPressed=!0,this.pressForClick=!1,this.onAltClick?.(t),this.panHandler?.onPointerUp(),this.panHandler?.cancelMomentum(),this.onOverlayDirty?.(!0)},Yo)),this.crosshairHandler?.onPointerMove(t),this.onOverlayDirty?.(!0)}else if(e.touches.length===2){if(this.clearLongPress(),this.touchActive&&!this.touchYielded&&this.lastTouchDist===0&&v(null,`touch`,!0),!this.zoomHandler&&!this.panHandler){this.touchActive=!1;return}e.cancelable&&e.preventDefault(),this.lastTouchDist=this.getTouchDistance(e.touches[0],e.touches[1]),this.lastTouchMid=this.getTouchMidpoint(e.touches[0],e.touches[1]),this.touchActive=!0,this.touchYielded=!1}}},D=t=>{this.onDrawingContextMenu&&(this.clearLongPress(),this.longPressTimer=setTimeout(()=>{this.longPressTimer=null;let n=e(),r=n?this.drawingManager?.drawingAt(t,n,Vo.line):null;r&&(v(null,`touch`,!0),this.longPressed=!0,this.touchYielded=!0,this.crosshairHandler?.onPointerLeave(),this.onDrawingContextMenu?.(r,t),this.onOverlayDirty?.())},Yo))},O=e=>{if(this.touchDecided)return!1;let t=e.x-this.touchStartPos.x,n=e.y-this.touchStartPos.y;if(Math.hypot(t,n)<=Jo)return!1;this.touchDecided=!0;let r=this.pageTakes();return Math.abs(n)>=Math.abs(t)?r.y:r.x},k=e=>{if(!(!this.touchActive||this.touchYielded)){if(e.touches.length===1){let t=this.getTouchPos(e.touches[0]);if(this.lastTouchDist>0){e.cancelable&&e.preventDefault(),this.panHandler?.onPointerMove(this.pageScroll?{x:t.x,y:this.touchStartPos.y}:t),this.onOverlayDirty?.();return}if(this.longPressTimer&&Math.hypot(t.x-this.touchStartPos.x,t.y-this.touchStartPos.y)>Jo&&this.clearLongPress(),this.touchFallthrough&&this.pageTakes().any){if(!this.touchDecided&&Math.hypot(t.x-this.touchStartPos.x,t.y-this.touchStartPos.y)<=Jo)return;if(O(t)){this.touchYielded=!0,v(null,`touch`,!0),this.crosshairHandler?.onPointerLeave(),this.onOverlayDirty?.(!0);return}}e.cancelable&&e.preventDefault(),_(t,`touch`,!0,this.pageScroll?{x:t.x,y:this.touchStartPos.y}:t)}else if(e.touches.length===2){e.cancelable&&e.preventDefault();let t=this.getTouchDistance(e.touches[0],e.touches[1]),n=this.getTouchMidpoint(e.touches[0],e.touches[1]);this.lastTouchDist>0&&t>0&&this.zoomHandler?.onPinch(t/this.lastTouchDist,n);let r=this.lastTouchMid.x-n.x;Math.abs(r)>1&&(this.panHandler?.onPointerDown(this.lastTouchMid),this.panHandler?.onPointerMove({x:n.x,y:this.lastTouchMid.y})),this.lastTouchDist=t,this.lastTouchMid=n,this.onOverlayDirty?.()}}},A=e=>{if(this.clearLongPress(),this.touchActive)if(this.lastTouchAt=Date.now(),e.touches.length===0){let t=e.changedTouches?.[0],n=t?this.getTouchPos(t):null,r=this.lastTouchDist>0,i=!r&&!this.longPressed&&!this.touchYielded&&this.downPos!==null&&!this.downMoved;this.touchYielded||(r?this.panHandler?.onPointerUp():v(n,`touch`),!this.touchStartPrevented&&e.cancelable&&e.preventDefault()),i&&n&&this.taps.tap(n)?y(n,Vo.line):i||this.taps.reset(),this.crosshairHandler?.onPointerLeave(),this.touchActive=!1,this.touchYielded=!1,this.lastTouchDist=0,this.onOverlayDirty?.()}else if(e.touches.length===1&&!this.touchYielded){let t=this.getTouchPos(e.touches[0]);this.touchStartPos=t,this.panHandler?.onPointerDown(t)}else e.touches.length===2&&this.lastTouchDist>0&&(this.lastTouchDist=this.getTouchDistance(e.touches[0],e.touches[1]),this.lastTouchMid=this.getTouchMidpoint(e.touches[0],e.touches[1]))},ee=()=>{this.clearLongPress(),this.touchActive&&(this.lastTouchAt=Date.now(),this.touchYielded||(this.lastTouchDist>0?(this.panHandler?.onPointerUp(),this.panHandler?.cancelMomentum()):v(null,`touch`,!0)),this.taps.reset(),this.crosshairHandler?.onPointerLeave(),this.touchActive=!1,this.touchYielded=!1,this.lastTouchDist=0,this.onOverlayDirty?.())},te=()=>this.invalidateRect(),ne=()=>this.invalidateRect(),re=()=>this.invalidateRect(),ie=e=>{let t=e.target instanceof Node&&this.element.contains(e.target)&&f(e.target);(s||t)&&e.preventDefault()};this.element.addEventListener(`mousedown`,m),this.element.addEventListener(`mousemove`,h),document.addEventListener(`dragstart`,ie,!0),document.addEventListener(`mouseup`,b),this.element.addEventListener(`mouseleave`,S),this.element.addEventListener(`dblclick`,x),this.element.addEventListener(`wheel`,C,{passive:!1}),this.element.addEventListener(`contextmenu`,T),this.element.addEventListener(`touchstart`,E,{passive:!1}),this.element.addEventListener(`touchmove`,k,{passive:!1}),this.element.addEventListener(`touchend`,A),this.element.addEventListener(`touchcancel`,ee),document.addEventListener(`keydown`,w),window.addEventListener(`resize`,te),document.addEventListener(`scroll`,ne,{capture:!0,passive:!0}),this.element.addEventListener(`mouseenter`,re),this.boundHandlers.push(d,()=>this.element.removeEventListener(`mousedown`,m),()=>document.removeEventListener(`dragstart`,ie,!0),()=>this.element.removeEventListener(`mousemove`,h),()=>document.removeEventListener(`mouseup`,b),()=>this.element.removeEventListener(`mouseleave`,S),()=>this.element.removeEventListener(`dblclick`,x),()=>this.element.removeEventListener(`wheel`,C),()=>this.element.removeEventListener(`contextmenu`,T),()=>this.element.removeEventListener(`touchstart`,E),()=>this.element.removeEventListener(`touchmove`,k),()=>this.element.removeEventListener(`touchend`,A),()=>this.element.removeEventListener(`touchcancel`,ee),()=>document.removeEventListener(`keydown`,w),()=>window.removeEventListener(`resize`,te),()=>document.removeEventListener(`scroll`,ne,{capture:!0}),()=>this.element.removeEventListener(`mouseenter`,re))}detach(){Go.delete(this.element),this.savedTouchAction?this.element.style.setProperty(`touch-action`,this.savedTouchAction):this.element.style.removeProperty(`touch-action`),Ko===this.element&&(Ko=null);for(let e of this.boundHandlers)e();this.boundHandlers=[],this.cachedRect=null,this.clearLongPress()}clearLongPress(){this.longPressTimer&&=(clearTimeout(this.longPressTimer),null)}invalidateRect(){this.cachedRect=null}getRect(){return this.cachedRect||=this.element.getBoundingClientRect(),this.cachedRect}ownsShortcuts(){let e=document.activeElement;if(e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.tagName===`SELECT`||e.isContentEditable))return!1;for(let t of Go)if(e&&t.contains(e))return t===this.element;return Ko===null||Ko===this.element}getMousePos(e){let t=this.getRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}getTouchPos(e){let t=this.getRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}getTouchDistance(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)}getTouchMidpoint(e,t){let n=this.getRect();return{x:(e.clientX+t.clientX)/2-n.left,y:(e.clientY+t.clientY)/2-n.top}}},es=16,ts=3,ns=class{enabled=!1;setEnabled(e){this.enabled=e}isEnabled(){return this.enabled}hit(e,t){if(!this.enabled)return!1;let{x:n,y:r,width:i,height:a}=t.chartRect,o=n+i-es-ts;return e.x>=o&&e.x<=n+i&&e.y>=r&&e.y<=r+a}render(e,t,n,r){if(!this.enabled||!r)return;let{x:i,y:a,width:o,height:s}=t.chartRect;if(r.y<a||r.y>a+s||r.x<i||r.x>i+o)return;let c=i+o-ts-es/2,l=es/2;e.fillStyle=n.background,e.strokeStyle=n.axisLabelBackground,e.lineWidth=1,e.beginPath(),e.arc(c,r.y,l-.5,0,Math.PI*2),e.fill(),e.stroke(),e.strokeStyle=n.text,e.lineWidth=1.5,e.beginPath(),e.moveTo(c-l*.45,r.y),e.lineTo(c+l*.45,r.y),e.moveTo(c,r.y-l*.45),e.lineTo(c,r.y+l*.45),e.stroke()}},rs=100,is=50,as=.1,os=60,ss=16;function cs(){return typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches}var ls=class{dragging=!1;lastX=0;lastY=0;samples=[];momentumId=0;callback;onStart;friction=.92;constructor(e,t){this.callback=e,this.onStart=t}isDragging(){return this.dragging}onPointerDown(e){this.dragging=!0,this.lastX=e.x,this.lastY=e.y,this.samples=[{t:Date.now(),x:e.x,y:e.y}],this.stopMomentum(),this.onStart?.()}onPointerMove(e){if(!this.dragging)return;let t=this.lastX-e.x,n=this.lastY-e.y;this.lastX=e.x,this.lastY=e.y;let r=Date.now();for(this.samples.push({t:r,x:e.x,y:e.y});this.samples.length>2&&r-this.samples[1].t>rs;)this.samples.shift();(t||n)&&this.callback(t,n)}onPointerUp(){if(!this.dragging)return;this.dragging=!1;let e=this.releaseVelocity(Date.now());this.samples=[],!cs()&&e&&Math.hypot(e.x,e.y)>as&&this.startMomentum(e.x,e.y)}cancelMomentum(){this.stopMomentum()}releaseVelocity(e){let t=this.samples[this.samples.length-1];if(!t||e-t.t>is)return null;let n=this.samples.find(e=>t.t-e.t<=rs)??this.samples[0],r=t.t-n.t;return r<=0?null:{x:(n.x-t.x)/r,y:(n.y-t.y)/r}}startMomentum(e,t){this.stopMomentum();let n=e*ss,r=t*ss,i=Math.hypot(n,r);i>os&&(n*=os/i,r*=os/i);let a=null,o=e=>{let t=a===null?1:Math.min(4,Math.max(0,(e-a)/ss));a=e;let i=this.friction**t;if(n*=i,r*=i,Math.hypot(n,r)<.5){this.momentumId=0;return}this.callback(n*t,r*t),this.momentumId=requestAnimationFrame(o)};this.momentumId=requestAnimationFrame(o)}stopMomentum(){this.momentumId&&=(cancelAnimationFrame(this.momentumId),0)}},us=class{callback;sensitivity;pendingDelta=0;pendingScale=1;pendingCenterX=0;rafId=0;constructor(e,t=.001){this.callback=e,this.sensitivity=t}onWheel(e,t){this.pendingDelta+=-e*this.sensitivity,this.pendingCenterX=t.x,this.schedule()}onPinch(e,t){!(e>0)||!Number.isFinite(e)||(this.pendingScale*=e,this.pendingCenterX=t.x,this.schedule())}schedule(){this.rafId||=requestAnimationFrame(()=>{this.rafId=0;let e=(1+this.pendingDelta)*this.pendingScale-1,t=this.pendingCenterX;this.pendingDelta=0,this.pendingScale=1,this.callback(e,t)})}dispose(){this.rafId&&=(cancelAnimationFrame(this.rafId),0)}},ds=class{dragging=!1;axis=null;startPos={x:0,y:0};lastPos={x:0,y:0};moved=!1;threshold=3;sensitivity=.005;constructor(e,t){this.onPriceScale=e,this.onTimeScale=t}begin(e,t){this.dragging=!0,this.axis=e,this.startPos=t,this.lastPos=t,this.moved=!1}move(e){if(!this.dragging||!this.axis)return!1;let t=e.x-this.startPos.x,n=e.y-this.startPos.y;if(!this.moved&&Math.hypot(t,n)<this.threshold)return!1;if(this.moved=!0,this.axis===`price`){let t=e.y-this.lastPos.y,n=Math.exp(t*this.sensitivity);this.onPriceScale(n)}else{let t=e.x-this.lastPos.x,n=Math.exp(t*this.sensitivity);this.onTimeScale(n)}return this.lastPos=e,!0}end(){let e=this.dragging&&this.moved;return this.dragging=!1,this.axis=null,this.moved=!1,e}isActive(){return this.dragging}},fs=class{draggingId=null;constructor(e,t){this.alerts=e,this.viewportGetter=t}isOverAlert(e){let t=this.viewportGetter();return t?this.alerts.getAlertAtPoint(e,t)!==null:!1}tryBegin(e,t){let n=this.viewportGetter();if(!n)return!1;let r=this.alerts.getAlertAtPoint(e,n,t);return r?(this.draggingId=r.id,!0):!1}move(t){if(this.draggingId===null)return;let n=this.viewportGetter();n&&this.alerts.updateAlertPrice(this.draggingId,e.M(t.y,n))}end(){this.draggingId=null}isActive(){return this.draggingId!==null}},ps=class{state=null;layoutGetter=null;onResize=null;constructor(e=4){this.tolerance=e}configure(e,t){this.layoutGetter=e,this.onResize=t}hitTest(e,t,n=this.tolerance){for(let r of t.dividers)if(ms(e,r.rect,n)){let e=t.panels.find(e=>e.config.id===r.panelId);if(e)return{panelId:r.panelId,orientation:r.orientation,position:e.config.position,size:r.orientation===`horizontal`?e.rect.height:e.rect.width}}return null}cursorAt(e){let t=this.layoutGetter?.();if(!t)return null;let n=this.hitTest(e,t);return n?n.orientation===`horizontal`?`ns-resize`:`ew-resize`:null}tryBegin(e,t){let n=this.layoutGetter?.();if(!n)return!1;let r=this.hitTest(e,n,Math.max(t??0,this.tolerance));return r?(this.state={panelId:r.panelId,position:r.position,startSize:r.size,startPos:e},!0):!1}move(e){let t=this.computeSize(e);t&&this.onResize?.(t.panelId,t.size)}computeSize(e){let t=this.state;if(!t)return null;let n=0;switch(t.position){case`bottom`:n=t.startPos.y-e.y;break;case`top`:n=e.y-t.startPos.y;break;case`left`:n=e.x-t.startPos.x;break;case`right`:n=t.startPos.x-e.x;break}return{panelId:t.panelId,size:t.startSize+n}}end(){this.state=null}isActive(){return this.state!==null}};function ms(e,t,n){return e.x>=t.x-n&&e.x<=t.x+t.width+n&&e.y>=t.y-n&&e.y<=t.y+t.height+n}var hs=class{position=null;callback=null;data=[];source=null;tz=null;timeFormatter=null;timesPastData=!0;setTimesPastData(e){this.timesPastData=e}getTimesPastData(){return this.timesPastData}setTimeFormatter(e){this.timeFormatter=e}setTimezoneOffset(e){this.tz=e}magnetMode=!0;mode=`magnet`;pricePrecision=null;locale=`en-US`;syncedSlot=null;pendingBarIndex=null;pendingPoint=null;callbackScheduled=!1;lastCallbackBarIndex=-1;reportTop=null;reportBottom=null;setCallback(e){this.callback=e}setData(e){this.data=e}setDataSource(e){this.source=e}series(){return this.source?.()??this.data}setMagnetMode(e){this.magnetMode=e,this.mode=e?`magnet`:`normal`}setMode(e){this.mode=e,this.magnetMode=e===`magnet`}getMode(){return this.mode}setPricePrecision(e){this.pricePrecision=e}setLocale(e){this.locale=e}getPosition(){return this.position}setSyncedSlot(e){this.syncedSlot=e!==null&&Number.isFinite(e)?e:null}getSyncedSlot(){return this.syncedSlot}setReportBounds(e){this.reportTop=e?.top??null,this.reportBottom=e?.bottom??null}onPointerMove(e){this.position=e}onPointerLeave(){this.position=null,this.pendingBarIndex=null,this.pendingPoint=null,this.lastCallbackBarIndex=-1,this.flushCallback(null,null)}render(n,r,i){if(this.mode===`hidden`)return;if(!this.position){this.syncedSlot!==null&&this.renderSynced(n,r,i,this.syncedSlot);return}let{chartRect:a}=r,{x:o,y:s}=this.position;if(o<a.x||o>a.x+a.width)return;let c=a.y+a.height;if(s<Math.min(this.reportTop??a.y,a.y)||s>Math.max(this.reportBottom??c,c))return;let l=s>=a.y&&s<=c,u=e.A(o,r),d=this.series().length,f=Math.max(0,Math.min(d-1,u)),p=u>=0&&u<d;if(this.magnetMode&&(o=e.b(u,r)),f!==this.lastCallbackBarIndex&&(this.pendingBarIndex=f,this.pendingPoint={x:o,y:s},this.lastCallbackBarIndex=f,this.scheduleCallback()),!l)return;let m=ae(i);this.magnetMode&&p&&_s(n,o,r,m.vertical.color),vs(n,o,a,m.vertical);let h=m.horizontal;if(h.visible){n.setLineDash((0,t.lineDash)(h.style,gs,h.width)),n.strokeStyle=h.color;let r=e._(n,s,h.width);n.lineWidth=r.width,n.beginPath(),n.moveTo(a.x,r.y),n.lineTo(a.x+a.width,r.y),n.stroke()}n.setLineDash([])}renderAxisLabels(n,r,i,a,o,s=[],l=[]){if(this.mode===`hidden`)return;if(!this.position){this.syncedSlot!==null&&this.renderSyncedTimeLabel(n,r,i,a,this.syncedSlot,o,l);return}let{chartRect:u}=r,{x:d,y:f}=this.position;if(d<u.x||d>u.x+u.width||f<u.y||f>u.y+u.height)return;let p=e.A(d,r);this.magnetMode&&(d=e.b(p,r));let m=`600 ${i.font.sizeSmall}px ${i.font.family}`,h=c(e.M(f,r),r,this.pricePrecision??(0,t.autoPricePrecision)(r.priceRange.min,r.priceRange.max),this.locale),g=u.x+u.width;Ss(n,s,f,g,r.priceAxisWidth??t.PRICE_AXIS_WIDTH,i),Cs(n,{text:h,anchorX:g,anchorY:f,orientation:`right`,bg:ae(i).labelBackground,fg:ae(i).labelText,theme:i,font:m}),this.drawTimePill(n,r,i,a,p,d,o,l)}renderSynced(t,n,r,i){let a=e.b(i,n),{chartRect:o}=n;if(a<o.x||a>o.x+o.width)return;let s=ae(r);this.magnetMode&&i>=0&&i<this.series().length&&_s(t,a,n,s.vertical.color),vs(t,a,o,s.vertical)}renderSyncedTimeLabel(t,n,r,i,a,o,s=[]){let c=e.b(a,n),{chartRect:l}=n;c<l.x||c>l.x+l.width||this.drawTimePill(t,n,r,i,a,c,o,s)}drawTimePill(n,r,i,a,o,s,c,l=[]){if(a.length===0||!this.timesPastData&&(o<0||o>=a.length))return;let u=e.y(o,a),d=this.timeFormatter?this.timeFormatter(u*(0,t.barTimeUnit)(a),{kind:`crosshair`,timeZone:this.tz}):ws(u*(0,t.barTimeUnit)(a),this.tz,(0,t.barsAreDaily)(a)),f=`600 ${i.font.sizeSmall}px ${i.font.family}`,p=c??r.chartRect.y+r.chartRect.height;n.font=f;let m=Math.ceil(n.measureText(d).width)/2+bs;xs(n,l,s-m,s+m,p,i),Cs(n,{text:d,anchorX:s,anchorY:p,orientation:`bottom`,bg:ae(i).labelBackground,fg:ae(i).labelText,theme:i,font:f})}scheduleCallback(){this.callbackScheduled||(this.callbackScheduled=!0,queueMicrotask(()=>{this.callbackScheduled=!1,this.flushCallback(this.pendingBarIndex,this.pendingPoint)}))}flushCallback(e,t){this.callback?.(e,t)}},gs=[4,4];function _s(e,t,n,r){let i=n.barWidth+n.barSpacing;e.fillStyle=r,e.globalAlpha=.08,e.fillRect(t-i/2,n.chartRect.y,i,n.chartRect.height),e.globalAlpha=1}function vs(n,r,i,a){if(!a.visible)return;n.setLineDash((0,t.lineDash)(a.style,gs,a.width)),n.strokeStyle=a.color;let o=e.g(n,r,a.width);n.lineWidth=o.width,n.beginPath(),n.moveTo(o.x,i.y),n.lineTo(o.x,i.y+i.height),n.stroke(),n.setLineDash([])}var ys=20,bs=8;function xs(e,t,n,r,i,a){let o=t.filter(e=>e.right>n-2&&e.left<r+2);if(o.length!==0){e.save(),e.fillStyle=a.background;for(let t of o)e.fillRect(t.left-2,i+1,t.right-t.left+4,a.font.sizeSmall+12);e.restore()}}function Ss(e,t,n,r,i,a){let o=Math.ceil(a.font.sizeSmall/2)+1,s=t.filter(e=>Math.abs(e-n)<ys/2+o);if(s.length!==0){e.save(),e.fillStyle=a.background;for(let t of s)e.fillRect(r+1,t-o,i-1,o*2);e.restore()}}function Cs(e,t){e.save(),e.font=t.font;let n=bs,r=Math.ceil(e.measureText(t.text).width)+n*2,i=ys;if(e.fillStyle=t.bg,e.textBaseline=`middle`,t.orientation===`right`){let a=t.anchorX+5;w(e,a,t.anchorY-i/2,r,i,t.theme),e.beginPath(),e.moveTo(t.anchorX,t.anchorY),e.lineTo(a+2,t.anchorY-5),e.lineTo(a+2,t.anchorY+5),e.closePath(),e.fill(),e.fillStyle=t.fg,e.textAlign=`left`,e.fillText(t.text,a+n,t.anchorY)}else{let n=t.anchorX-r/2,a=t.anchorY+5;w(e,n,a,r,i,t.theme),e.beginPath(),e.moveTo(t.anchorX,t.anchorY),e.lineTo(t.anchorX-5,a+1),e.lineTo(t.anchorX+5,a+1),e.closePath(),e.fill(),e.fillStyle=t.fg,e.textAlign=`center`,e.fillText(t.text,t.anchorX,a+i/2)}e.restore()}function ws(e,n,r){let i=(0,t.timeParts)(e,n),{year:a,month:o,day:s,hours:c,minutes:l}=i;return r??(0,t.isDateOnly)(i)?`${o}/${s}/${a}`:`${o}/${s} ${c<10?`0`+c:c}:${l<10?`0`+l:l}`}var Ts=class{callbacks;enabled=!0;constructor(e){this.callbacks=e}setEnabled(e){this.enabled=e}handleKey(e){if(!this.enabled)return!1;let t=e.shiftKey?10:1;switch(e.key){case`ArrowLeft`:return this.callbacks.scrollBars(-t),!0;case`ArrowRight`:return this.callbacks.scrollBars(t),!0;case`ArrowUp`:case`+`:case`=`:return this.callbacks.zoom(.1),!0;case`ArrowDown`:case`-`:return this.callbacks.zoom(-.1),!0;case`Home`:return this.callbacks.goToStart(),!0;case`End`:return this.callbacks.goToEnd(),!0;case` `:return this.callbacks.fitContent(),!0;default:return!1}}},Es=16,Ds=80,Os=864e5,ks={month:`short`,day:`numeric`},As={month:`short`,day:`numeric`,year:`numeric`};function js(e,n,r,i){return(0,t.zonedDateFormatter)(r,i?As:ks,n)(e)}var Ms=e=>e<10?`0${e}`:`${e}`;function Ns(e,n,r,i=`en-US`,a){let o=(0,t.normalizeBarTime)(e,a),s=(0,t.timeParts)(o,n);if(r!==void 0&&r>0?r>=Os:(0,t.isDateOnly)(s))return js(o,n,i,!0);let c=js(o,n,i,!1),l=`${Ms(s.hours)}:${Ms(s.minutes)}`;return r!==void 0&&r>0&&r<6e4?`${c} · ${l}:${Ms(new Date(o).getUTCSeconds())}`:`${c} · ${l}`}function Ps(e,n){return Number.isFinite(e)?e>=1e9?`${(0,t.formatPrice)(e/1e9,2,n)}B`:e>=1e6?`${(0,t.formatPrice)(e/1e6,2,n)}M`:e>=1e3?`${(0,t.formatPrice)(e/1e3,1,n)}K`:(0,t.formatPrice)(e,e%1==0?0:2,n):`—`}var Fs=class{el=null;visible=!1;appliedTheme=null;locale=`en-US`;pricePrecision=null;tz=null;priceFormatter=null;timeFormatter=null;dirEl;timeEl;changeEl;valueEls;labelEls=[];dividerEl;width=176;height=112;create(e){if(this.el)return;let t=document.createElement(`div`);t.setAttribute(`aria-hidden`,`true`),Object.assign(t.style,{position:`absolute`,left:`0`,top:`0`,display:`none`,minWidth:`168px`,padding:`8px 10px 9px`,borderRadius:`var(--tcw-tooltip-radius, 8px)`,fontSize:`11.5px`,lineHeight:`1.45`,fontVariantNumeric:`tabular-nums`,pointerEvents:`none`,zIndex:`100`,whiteSpace:`nowrap`,willChange:`transform`,contain:`layout paint`,backdropFilter:`blur(10px)`});let n=Is({display:`flex`,alignItems:`center`,gap:`7px`,marginBottom:`6px`});this.dirEl=Is({width:`3px`,height:`12px`,borderRadius:`2px`,flex:`none`}),this.timeEl=Is({flex:`1`,fontSize:`11px`,letterSpacing:`0.01em`}),this.changeEl=Is({padding:`1px 6px`,borderRadius:`999px`,fontSize:`10.5px`,fontWeight:`600`}),n.append(this.dirEl,this.timeEl,this.changeEl);let r=Is({display:`grid`,gridTemplateColumns:`auto 1fr auto 1fr`,columnGap:`8px`,rowGap:`1px`,alignItems:`baseline`}),i=e=>{let t=Is({fontSize:`10px`,letterSpacing:`0.04em`});t.textContent=e,this.labelEls.push(t);let n=Is({textAlign:`right`,fontWeight:`500`});return r.append(t,n),n},a=i(`O`),o=i(`H`),s=i(`L`),c=i(`C`);this.dividerEl=Is({height:`1px`,margin:`6px 0 5px`});let l=Is({display:`flex`,justifyContent:`space-between`,gap:`12px`}),u=Is({fontSize:`10px`,letterSpacing:`0.04em`});u.textContent=`VOL`,this.labelEls.push(u);let d=Is({fontWeight:`500`});l.append(u,d),this.valueEls={open:a,high:o,low:s,close:c,volume:d},t.append(n,r,this.dividerEl,l),e.appendChild(t),this.el=t}setLocale(e){this.locale=e}setPricePrecision(e){this.pricePrecision=e}setTimezoneOffset(e){this.tz=e}setPriceFormatter(e){this.priceFormatter=e}setTimeFormatter(e){this.timeFormatter=e}show(e,n,r,i,a={}){let o=this.el;if(!o)return;this.appliedTheme!==r&&this.applyTheme(r);let s=this.pricePrecision??(a.priceRange?(0,t.autoPricePrecision)(a.priceRange.min,a.priceRange.max):(0,t.autoPricePrecision)(n.low,n.high)),c=e=>this.priceFormatter?.(e)??(0,t.formatPrice)(e,s,this.locale),l=a.prevClose??n.open,u=n.close-l,d=l===0?0:u/l*100,f=u>=0,p=f?r.candleUp:r.candleDown,m=f?`+`:`−`;this.timeEl.textContent=this.timeFormatter?this.timeFormatter((0,t.normalizeBarTime)(n.time,a.timeUnit),{kind:`crosshair`,timeZone:this.tz}):Ns(n.time,this.tz,a.barStepMs,this.locale,a.timeUnit),this.changeEl.textContent=`${m}${(0,t.formatPrice)(Math.abs(d),2,this.locale)}%`,this.changeEl.style.color=p,this.changeEl.style.background=zs(p,.14),this.dirEl.style.background=n.close>=n.open?r.candleUp:r.candleDown,this.valueEls.open.textContent=c(n.open),this.valueEls.high.textContent=c(n.high),this.valueEls.low.textContent=c(n.low),this.valueEls.close.textContent=c(n.close),this.valueEls.close.style.color=n.close>=n.open?r.candleUp:r.candleDown,this.valueEls.volume.textContent=Ps(n.volume,this.locale),this.visible||=(o.style.display=`block`,!0),this.width=o.offsetWidth||this.width,this.height=o.offsetHeight||this.height;let h=a.plot??{x:0,y:0,width:i.width-Ds,height:i.height},g=h.x+h.width,_=h.y+h.height,v=e.x+Es,y=e.y-this.height/2;v+this.width>g-4&&(v=e.x-this.width-Es),v<h.x+4&&(v=h.x+4),y+this.height>_-4&&(y=_-this.height-4),y<h.y+4&&(y=h.y+4),o.style.transform=`translate(${Math.round(v)}px, ${Math.round(y)}px)`}hide(){this.el&&this.visible&&(this.el.style.display=`none`,this.visible=!1)}isVisible(){return this.visible}destroy(){this.el?.remove(),this.el=null,this.visible=!1,this.appliedTheme=null,this.labelEls=[]}applyTheme(e){let t=this.el,n=Ls(e.background);t.style.background=zs(e.background,n?.9:.94),t.style.border=`1px solid ${e.axisLine}`,t.style.boxShadow=n?`0 12px 32px -8px rgba(0, 0, 0, 0.6), 0 2px 6px rgba(0, 0, 0, 0.35)`:`0 12px 32px -10px rgba(15, 19, 26, 0.22), 0 2px 6px rgba(15, 19, 26, 0.08)`,t.style.color=e.text,t.style.fontFamily=e.font.family,this.timeEl.style.color=e.textSecondary;for(let t of this.labelEls)t.style.color=e.textSecondary;this.dividerEl.style.background=e.axisLine,this.appliedTheme=e}};function Is(e){let t=document.createElement(`div`);return Object.assign(t.style,e),t}function Ls(e){let t=Rs(e);return t?(.299*t[0]+.587*t[1]+.114*t[2])/255<.5:!0}function Rs(e){if(e.startsWith(`#`)){let t=e.slice(1),n=t.length===3?t.split(``).map(e=>e+e).join(``):t.slice(0,6);return[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)]}let t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function zs(e,t){let n=Rs(e);return n?`rgba(${n[0]}, ${n[1]}, ${n[2]}, ${t})`:`color-mix(in srgb, ${e} ${Math.round(t*100)}%, transparent)`}var Bs=class{el=null;deltaEl=null;timeEl=null;ohlcEl=null;pinnedBar=null;pinnedIndex=-1;tz=null;priceFormatter=null;setTimezone(e){this.tz=e}setPriceFormatter(e){this.priceFormatter=e}fmt(e){return Vs(this.priceFormatter?this.priceFormatter(e):e.toFixed(2))}create(e){if(this.el)return;this.el=document.createElement(`div`),Object.assign(this.el.style,{position:`absolute`,display:`none`,padding:`6px 10px`,borderRadius:`var(--tcw-tooltip-radius, 4px)`,fontSize:`11px`,fontFamily:`-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif`,lineHeight:`1.5`,pointerEvents:`auto`,cursor:`pointer`,zIndex:`99`,whiteSpace:`nowrap`,willChange:`transform`}),this.timeEl=document.createElement(`div`),this.ohlcEl=document.createElement(`div`),this.deltaEl=document.createElement(`div`),this.deltaEl.style.marginTop=`4px`,this.deltaEl.style.paddingTop=`4px`,this.deltaEl.style.borderTop=`1px solid currentColor`,this.deltaEl.style.opacity=`0.85`,this.deltaEl.style.fontVariantNumeric=`tabular-nums`,this.el.appendChild(this.timeEl),this.el.appendChild(this.ohlcEl),this.el.appendChild(this.deltaEl);let n=document.createElement(`div`);n.innerHTML=`${(0,t.iconSvg)(t.UI_ICONS.pin,10)}<span>pinned</span>`,n.style.display=`flex`,n.style.alignItems=`center`,n.style.gap=`3px`,n.style.fontSize=`9px`,n.style.opacity=`0.6`,n.style.marginBottom=`2px`,n.style.letterSpacing=`0.04em`,n.style.textTransform=`uppercase`,this.el.insertBefore(n,this.timeEl),e.appendChild(this.el)}pin(e,n,r,i){if(!this.el||!this.timeEl||!this.ohlcEl)return;this.pinnedBar=e,this.pinnedIndex=n;let a=e.close>=e.open?r.candleUp:r.candleDown,o=(0,t.timeParts)((0,t.normalizeBarTime)(e.time,i),this.tz);this.timeEl.textContent=`${o.month}/${o.day} ${Hs(o.hours)}:${Hs(o.minutes)}`,this.timeEl.style.color=r.textSecondary;let s=[];for(let[t,n]of[[`O `,e.open],[` H `,e.high],[` L `,e.low],[` C `,e.close]]){let e=document.createElement(`span`);e.style.opacity=`.6`,e.textContent=t;let r=document.createElement(`span`);r.style.color=a,r.textContent=this.fmt(n),s.push(e,r)}this.ohlcEl.replaceChildren(...s);let c=Us(r.background);this.el.style.background=Ws(r.background,c?.96:.97),this.el.style.border=`1px solid ${a}`,this.el.style.boxShadow=c?`0 4px 12px rgba(0,0,0,0.55)`:`0 4px 12px rgba(0,0,0,0.18)`,this.el.style.color=r.text,this.el.style.backdropFilter=`blur(8px)`,this.el.style.display=`block`}unpin(){this.pinnedBar=null,this.pinnedIndex=-1,this.el&&(this.el.style.display=`none`)}isPinned(){return this.pinnedBar!==null}getPinnedIndex(){return this.pinnedIndex}reposition(t,n,r,i){if(!this.el||!this.pinnedBar)return;let a=e.b(this.pinnedIndex,t),o=e.T(this.pinnedBar.close,t),s=t.chartRect,c=a>=s.x-4&&a<=s.x+s.width+4;this.el.style.opacity=c?`1`:`0.35`;let l=Math.max(s.x,Math.min(s.x+s.width-180,a+8)),u=Math.max(s.y,Math.min(s.y+s.height-90,o-64));if(this.el.style.transform=`translate(${Math.round(l)}px, ${Math.round(u)}px)`,this.el.style.left=`0`,this.el.style.top=`0`,this.deltaEl)if(n&&r!==null&&r!==this.pinnedIndex){let e=n.close-this.pinnedBar.close,t=this.pinnedBar.close===0?0:e/this.pinnedBar.close*100,a=e>0?`+`:e<0?`−`:``,o=r-this.pinnedIndex,s=e>=0?i.candleUp:i.candleDown;this.deltaEl.style.color=s,this.deltaEl.innerHTML=`Δ ${a}${this.fmt(Math.abs(e))} <span style="opacity:.7">(${a}${Math.abs(t).toFixed(2)}%)</span> · ${o>0?`+`:``}${o} bars`,this.deltaEl.style.display=`block`}else this.deltaEl.style.display=`none`}destroy(){this.el?.remove(),this.el=null,this.deltaEl=null,this.timeEl=null,this.ohlcEl=null,this.pinnedBar=null,this.pinnedIndex=-1}};function Vs(e){return e.replace(/[&<>"']/g,e=>`&#${e.charCodeAt(0)};`)}function Hs(e){return e<10?`0`+e:``+e}function Us(e){if(e.startsWith(`#`)){let t=e.slice(1),n=t.length===3?t.split(``).map(e=>e+e).join(``):t.slice(0,6),r=parseInt(n.slice(0,2),16),i=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);return(.299*r+.587*i+.114*a)/255<.5}return!0}function Ws(e,t){if(e.startsWith(`#`)){let n=e.slice(1),r=n.length===3?n.split(``).map(e=>e+e).join(``):n.slice(0,6);return`rgba(${parseInt(r.slice(0,2),16)}, ${parseInt(r.slice(2,4),16)}, ${parseInt(r.slice(4,6),16)}, ${t})`}return e}var Gs=class{listeners=new Map;tauriBridge=null;on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}hasListeners(e){return(this.listeners.get(e)?.size??0)>0}emit(e,t){let n={type:e,timestamp:Date.now(),payload:t},r=this.listeners.get(e);if(r)for(let e of r)e(n);if(this.tauriBridge?.enabled&&window.__TAURI__){let t=this.tauriBridge.eventPrefix??`tc-chart`;window.__TAURI__.event.emit(`${t}:${e}`,n).catch(()=>{})}}enableTauriBridge(e){this.tauriBridge=e}disableTauriBridge(){this.tauriBridge=null}destroy(){this.listeners.clear(),this.tauriBridge=null}},Ks=`#FFFFFF`;function qs(e){for(let t in e)if(e[t]!==null)return!0;return!1}function Js(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];i!==null&&(n[t[r]]=i)}return n}function Ys(e,t){let n=t.style?.trading;return!n||!qs(n)?e:{...e,orderColors:{...e.orderColors,...Js({buy:n.buy,sell:n.sell},{buy:`buy`,sell:`sell`})},positionColors:{...e.positionColors,...Js({profit:n.profit,loss:n.loss,entry:n.entry},{profit:`profit`,loss:`loss`,entry:`entry`})}}}function Xs(e,t){let n=t.style?.markers;return!n||!qs(n)?e:{...e,...Js(n,{long:`longColor`,short:`shortColor`,neutral:`neutralColor`})}}function Zs(e,t){let n=t.style?.tradeZones;return!n||!qs(n)?e:{...e,...Js(n,{profit:`profitColor`,loss:`lossColor`,active:`activeColor`})}}function Qs(e){return e?.style?.drawings.handle??Ks}var $s=`rgba(12, 16, 22, 0.85)`,ec=$s,tc=t.DEFAULT_FONT_FAMILY,nc=Qs(null);function rc(e){ec=e?.background??$s,tc=e?.font?.family||t.DEFAULT_FONT_FAMILY,nc=Qs(e)}function ic(){return nc}function ac(){return tc}function W(e,t){return`${t?`${t} `:``}${e}px ${tc}`}function G(e,t,n,r){e.save(),e.lineJoin=`round`,e.lineWidth=3,e.strokeStyle=ec,e.globalAlpha*=.85,e.setLineDash([]),e.strokeText(t,n,r),e.restore(),e.fillText(t,n,r)}function oc(e,t){return Math.ceil(e.measureText(t).width)+12}function sc(e,t,n,r,i,a=`#ffffff`){let o=oc(e,t),s=Math.round(r-18/2);return e.fillStyle=i,e.beginPath(),typeof e.roundRect==`function`?e.roundRect(n,s,o,18,4):e.rect(n,s,o,18),e.fill(),e.fillStyle=a,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(t,n+6,s+18/2+.5),o}var cc=14,lc=6,uc=4,dc=`rgba(19, 23, 34, 0.85)`,fc=`#FFFFFF`,pc=6e4,mc=60*pc,hc=24*mc;function gc(e){let t=Math.abs(e);return t>=10||t===0?2:t>=1?4:Math.min(10,Math.ceil(-Math.log10(t))+3)}function _c(e,t=e,n){return n?.formatPrice?n.formatPrice(e):e.toFixed(gc(t))}function vc(e,t,n){let r=t-e,i=e===0?0:r/e*100,a=r>=0?`+`:``;return`${a}${_c(r,e,n)} (${a}${i.toFixed(2)}%)`}function yc(e){let t=Math.abs(e);if(t<mc)return`${Math.round(t/pc)}m`;if(t<hc){let e=Math.floor(t/mc),n=Math.round((t-e*mc)/pc);return n>0?`${e}h ${n}m`:`${e}h`}let n=Math.floor(t/hc),r=Math.round((t-n*hc)/mc);if(n>=7){let e=Math.floor(n/7),t=n-e*7;return t>0?`${e}w ${t}d`:`${e}w`}return r>0?`${n}d ${r}h`:`${n}d`}function bc(e){return!!e.data&&e.data.length>0}function xc(t,n,r,i){let a=e.D(t.anchors[n].time,i),o=e.D(t.anchors[r].time,i);return Math.round(Math.abs(o-a))}function Sc(e,t,n,r){return bc(r)?yc(e.anchors[n].time-e.anchors[t].time):null}function Cc(e,t,n,r,i=`center`,a=!0){e.font=W(11);let o=0;for(let n of t)o=Math.max(o,e.measureText(n).width);let s=o+lc*2,c=t.length*cc+uc*2,l=i===`left`?n:i===`right`?n-s:n-s/2,u=a?r-c:r;e.fillStyle=dc,e.fillRect(l,u,s,c),e.fillStyle=fc,e.textAlign=`left`,e.textBaseline=`top`;for(let n=0;n<t.length;n++)e.fillText(t[n],l+lc,u+uc+n*cc);return{x:l,y:u,width:s,height:c}}function wc(e,t,n){let r=Math.abs(e.anchors[t[1]].price-e.anchors[t[0]].price),i=Math.abs(e.anchors[n[1]].price-e.anchors[n[0]].price);return i===0?`—`:(r/i).toFixed(3)}var Tc={at:e=>e,value:e=>e,price:e=>e};function Ec(t){if(!t)return Tc;let{min:n,max:r}=t.priceRange,i=t.logScale===!0&&n>0&&r>0;return{at:n=>e.D(n,t),value:i?e=>Math.log(Math.max(e,2**-52)):e=>e,price:i?Math.exp:e=>e}}function Dc(e,t,n){let r=n.x-t.x,i=n.y-t.y,a=r*r+i*i;if(a===0)return Math.hypot(e.x-t.x,e.y-t.y);let o=Math.max(0,Math.min(1,((e.x-t.x)*r+(e.y-t.y)*i)/a));return Math.hypot(e.x-(t.x+o*r),e.y-(t.y+o*i))}function Oc(e,t,n,r=!1){for(let r=0;r<t.length-1;r++)if(Dc(e,t[r],t[r+1])<=n)return!0;return r&&t.length>2&&Dc(e,t[t.length-1],t[0])<=n}function kc(e,t){switch(e.kind){case`boolean`:return typeof t==`boolean`;case`number`:return typeof t==`number`&&Number.isFinite(t);case`levels`:return Array.isArray(t);default:return typeof t==`string`}}var K=class{hitTestAnchor(e,t,n,r){for(let i=0;i<t.anchors.length;i++){let a=this.anchorToPixel(t.anchors[i],n);if(Math.hypot(e.x-a.x,e.y-a.y)<=r)return i}return-1}option(e,t){let n=this.descriptor.options?.[t],r=e.options?.[t];return n?r!==void 0&&kc(n,r)?r:n.default:r}optionsOf(e){return t=>this.option(e,t)}visibleLevels(e,t=`levels`){return this.option(e,t).filter(e=>e.visible&&Number.isFinite(e.value))}extendLine(e,t,n,r,i){let a=t.x-e.x,o=t.y-e.y,s=Math.hypot(a,o);if(s===0||!r&&!i)return[e,t];let c=Math.hypot(n.chartRect.width,n.chartRect.height)*2,l=a/s*c,u=o/s*c;return[r?{x:e.x-l,y:e.y-u}:e,i?{x:t.x+l,y:t.y+u}:t]}linePriceAt(e,t,n,r,i,a=Tc){let o=this.lineValueAt(e,t,n,r,i,a);return o===null?null:a.price(o)}lineValueAt(e,t,n,r,i,a){let o=a.at(e.time),s=a.at(t.time);if(o===s)return null;let c=(a.at(n)-o)/(s-o);if(!Number.isFinite(c)||c<0&&!r||c>1&&!i)return null;let l=a.value(e.price);return l+(a.value(t.price)-l)*c}anchorToPixel(t,n){return{x:e.O(t.time,n),y:e.T(t.price,n)}}pixelToAnchor(t,n){return{time:e.j(t.x,n),price:e.M(t.y,n)}}applyLineStyle(e,t){switch(e.strokeStyle=t.color,e.lineWidth=t.lineWidth,e.lineCap=`butt`,e.lineJoin=`round`,t.lineStyle){case`dashed`:e.setLineDash([6,4]);break;case`dotted`:e.setLineDash([2,2]);break;default:e.setLineDash([]);break}}strokeHorizontal(t,n,r,i){let a=e._(t,i,Number(t.lineWidth)||1);t.lineWidth=a.width,t.beginPath(),t.moveTo(n,a.y),t.lineTo(r,a.y),t.stroke()}strokeVertical(t,n,r,i){let a=e.g(t,n,Number(t.lineWidth)||1);t.lineWidth=a.width,t.beginPath(),t.moveTo(a.x,r),t.lineTo(a.x,i),t.stroke()}resetLineStyle(e){e.setLineDash([]),e.lineCap=`butt`,e.lineJoin=`miter`}renderAnchorHandles(e,t,n){e.fillStyle=ic(),e.strokeStyle=t.style.color,e.lineWidth=1;for(let r of t.anchors){let t=this.anchorToPixel(r,n);e.fillRect(t.x-4,t.y-4,8,8),e.strokeRect(t.x-4,t.y-4,8,8)}}distanceToLine(e,t,n){return Dc(e,t,n)}distanceToInfiniteLine(e,t,n){let r=n.x-t.x,i=n.y-t.y,a=Math.hypot(r,i);return a===0?Math.hypot(e.x-t.x,e.y-t.y):Math.abs(r*(t.y-e.y)-i*(t.x-e.x))/a}};function Ac(e){let t={};for(let[n,r]of Object.entries(e))t[n]=Array.isArray(r)?r.map(e=>({...e})):r;return t}function q(e){return{...e,anchors:e.anchors.map(e=>({...e})),style:{...e.style},options:e.options?Ac(e.options):void 0,intervals:e.intervals?an(e.intervals):void 0,group:e.group?{...e.group}:void 0,meta:e.meta?{...e.meta}:void 0}}function jc(e,t){return JSON.stringify(e??{})===JSON.stringify(t??{})}function Mc(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n].time!==t[n].time||e[n].price!==t[n].price)return!1;return!0}var Nc=1,Pc=1,Fc=/^tc_drawing_(\d+)$/,Ic=/^tc_group_(\d+)$/;function Lc(){return`tc_drawing_${Nc++}`}function Rc(){let e=Pc++;return{id:`tc_group_${e}`,number:e}}function zc(e){for(let t of e){let e=Fc.exec(t.id);e&&(Nc=Math.max(Nc,Number(e[1])+1));let n=t.group?Ic.exec(t.group.id):null;n&&(Pc=Math.max(Pc,Number(n[1])+1))}}function Bc(e,t){let n=new Map(e.map(e=>[e.id,e])),r=new Set(t);return[...t.map(e=>n.get(e)).filter(e=>e!==void 0),...e.filter(e=>!r.has(e.id))]}function Vc(e,t,n){let r=t-1;switch(n){case`front`:return r;case`back`:return 0;case`forward`:return Math.min(r,e+1);case`backward`:return Math.max(0,e-1)}}function Hc(e,t){return e.map(e=>e.id===t.id?structuredClone(t):e)}function Uc(e,t){switch(t.type){case`drawingBatch`:return[...t.actions??[]].reverse().reduce(Uc,[...e]);case`drawingCreate`:return t.after?e.filter(e=>e.id!==t.after.id):[...e];case`drawingRemove`:{if(!t.before)return[...e];let n=[...e];return n.splice(Math.min(t.index??n.length,n.length),0,structuredClone(t.before)),n}case`drawingOrder`:return t.order?Bc(e,t.order.before):[...e];case`drawingModify`:return t.before?Hc(e,t.before):[...e];default:return[...e]}}function Wc(e,t){switch(t.type){case`drawingBatch`:return(t.actions??[]).reduce(Wc,[...e]);case`drawingCreate`:return t.after?[...e,structuredClone(t.after)]:[...e];case`drawingRemove`:return t.before?e.filter(e=>e.id!==t.before.id):[...e];case`drawingOrder`:return t.order?Bc(e,t.order.after):[...e];case`drawingModify`:return t.after?Hc(e,t.after):[...e];default:return[...e]}}var Gc={"]":[`forward`,`front`],"}":[`front`,`front`],"[":[`backward`,`back`],"{":[`back`,`back`]};function Kc(e,t,n){if(e===`Escape`)return`escape`;if(e===`Enter`&&!t)return`finish`;if(e===`Delete`||e===`Backspace`)return`delete`;if(!t)return null;let r=n??(e.length===1&&e!==e.toLowerCase()),i=Gc[e];if(i)return i[+!!r];switch(e.toLowerCase()){case`c`:return`copy`;case`v`:return`paste`;case`d`:return`duplicate`;case`g`:return r?`ungroup`:`group`;case`z`:return r?`redo`:`undo`;case`y`:return`redo`;default:return null}}var qc=2,Jc=6;function Yc(e){return e.descriptor.creation??`clicks`}var Xc=class{drawing=null;plugin=null;preview=null;lastPos=null;dragging=!1;step=qc;get current(){return this.drawing}reset(){this.drawing=null,this.plugin=null,this.preview=null,this.lastPos=null,this.dragging=!1,this.step=qc}press(e,t,n,r,i){if(this.dragging)return`continue`;let a=Yc(e);if(!this.drawing)return this.plugin=e,this.drawing={...t(),anchors:[n]},this.preview=null,this.lastPos=r,a===`freehand`?(this.dragging=!0,`continue`):a===`clicks`&&e.descriptor.requiredAnchors<=1?`done`:`continue`;let o=this.drawing.anchors[this.drawing.anchors.length-1],s=i?i(o):this.lastPos;if(a===`path`&&s&&Math.hypot(r.x-s.x,r.y-s.y)<=Jc)return this.finish();this.commit(n,r);let c=a===`path`?e.descriptor.maxAnchors??100:e.descriptor.requiredAnchors;return this.drawing.anchors.length>=c?`done`:`continue`}move(e,t){if(!this.drawing||!this.plugin)return!1;if(this.dragging){let n=this.lastPos;return n&&Math.hypot(t.x-n.x,t.y-n.y)<this.step?!0:(this.drawing.anchors.length>=2e3&&(this.drawing.anchors=this.drawing.anchors.filter((e,t)=>t%2==0),this.step*=2),this.commit(e,t),!0)}return Yc(this.plugin)===`path`||this.drawing.anchors.length<this.plugin.descriptor.requiredAnchors?(this.preview=e,!0):!1}release(){return this.dragging?(this.dragging=!1,this.hasEnough()?`done`:`cancel`):null}undoPoint(){return!this.drawing||this.dragging||this.drawing.anchors.length<=1?(this.reset(),!1):(this.drawing.anchors.pop(),this.preview=null,this.lastPos=null,!0)}finish(){return!this.plugin||Yc(this.plugin)!==`path`||!this.hasEnough()?`continue`:(this.preview=null,`done`)}previewState(){return this.drawing?this.preview?{...this.drawing,anchors:[...this.drawing.anchors,this.preview]}:this.drawing:null}take(){let e=this.drawing;return this.reset(),e}hasEnough(){return!!this.drawing&&!!this.plugin&&this.drawing.anchors.length>=Math.max(2,this.plugin.descriptor.requiredAnchors)}commit(e,t){this.drawing.anchors.push(e),this.preview=null,this.lastPos=t}},Zc=30;function Qc(t,n,r,i,a){if(r===`none`||i.length===0)return{time:t,price:n};let o=!!(a?.data&&a.data.length>0),s=Math.round(o?e.k(t,i):t);if(s<0||s>i.length-1)return{time:t,price:n};let c=i[s],l=o?c.time:s,u=c.open;for(let e of[c.high,c.low,c.close])Math.abs(n-e)<Math.abs(n-u)&&(u=e);return r===`magnet`&&a&&Math.abs(e.T(n,a)-e.T(u,a))>Zc?{time:l,price:n}:{time:l,price:u}}var $c=class{primaryId=null;others=new Set;listener=null;setListener(e){this.listener=e}change(e){let t=this.ids().join(`\0`),n=e();return this.listener&&this.ids().join(`\0`)!==t&&this.listener(this.ids()),n}get primary(){return this.primaryId}has(e){return e===this.primaryId||this.others.has(e)}ids(){return this.primaryId?[this.primaryId,...this.others]:[]}clear(){this.change(()=>{this.primaryId=null,this.others.clear()})}add(e){this.change(()=>{this.primaryId?e!==this.primaryId&&this.others.add(e):this.primaryId=e})}only(e,t=[]){this.change(()=>{this.primaryId=e,this.others.clear();for(let n of t)n!==e&&this.others.add(n)})}focus(e){e===this.primaryId||!this.others.has(e)||this.change(()=>{this.primaryId&&this.others.add(this.primaryId),this.others.delete(e),this.primaryId=e})}remove(e){return this.change(()=>this.removeNow(e))}removeNow(e){let t=!1;for(let n of e)this.others.delete(n)&&(t=!0),n===this.primaryId&&(this.primaryId=null,t=!0);if(!this.primaryId){let e=this.others.values().next();e.done||(this.primaryId=e.value,this.others.delete(e.value))}return t}},el=3,tl=class{start=null;handle=-1;grabbed=[];constructor(e){this.find=e}isActive(){return this.start!==null}beginMove(e,t){this.start=e,this.handle=-1,this.grabbed=t.map(e=>({id:e.id,anchors:e.anchors.map(e=>({...e})),before:q(e)}))}beginResize(e,t,n){this.start=e,this.handle=n,this.grabbed=[{id:t.id,anchors:t.anchors.map(e=>({...e})),before:q(t)}]}move(e,t,n){return!this.start||this.grabbed.length===0?!1:this.handle>=0?this.reshape(e,t,n):this.translate(e,t)}end(){let e=this.grabbed.flatMap(({id:e,before:t})=>{let n=this.find(e);return n?[{before:t,drawing:n}]:[]});return this.start=null,this.handle=-1,this.grabbed=[],e}translate(t,n){let r=this.start,i=t.x-r.x,a=t.y-r.y;if(Math.hypot(i,a)<el&&this.unmoved())return!0;let o=n.barWidth+n.barSpacing,s=o>0?Math.round(i/o):0,c=n.data,l=t=>{let r=e.D(t,n)+s;return c&&c.length>0?e.y(r,c):r};for(let{id:t,anchors:r}of this.grabbed){let i=this.find(t);!i||i.locked||(i.anchors=r.map(t=>({time:s===0?t.time:l(t.time),price:a===0?t.price:e.M(e.T(t.price,n)+a,n)})))}return!0}unmoved(){return this.grabbed.every(({id:e,anchors:t})=>{let n=this.find(e)?.anchors;return!n||n.every((e,n)=>e.time===t[n]?.time&&e.price===t[n]?.price)})}reshape(n,r,i){let a=this.find(this.grabbed[0].id);if(!a)return!1;let o={time:e.j(n.x,r),price:e.M(n.y,r)};if(i?.moveHandle){let e=i.moveHandle(q(a),this.handle,o);a.anchors=e.anchors,a.options=e.options&&Object.keys(e.options).length>0?(0,t.sanitizeDrawingOptions)(i.descriptor.options,e.options):void 0}else this.handle<a.anchors.length&&(a.anchors[this.handle]=o);return!0}},nl={drawings:[],pastes:0},rl=1e7,il={line:8,handle:8},al=class{registry=new Map;drawings=[];state=`idle`;activeTool=null;activeStyle={color:`#4c8dff`,lineWidth:1,lineStyle:`solid`,fillColor:`rgba(76, 141, 255, 0.1)`,fillOpacity:.1,fontSize:12};creator=new Xc;finishedAt=-1/0;creationPressAt=-1/0;eraser=!1;selection=new $c;drag=new tl(e=>this.drawings.find(t=>t.id===e));eventCallback=null;requestRender=null;undoRedo=null;magnetMode=`none`;dataGetter=null;displayDataGetter=null;stayInDrawingMode=!1;toolAllowed=()=>!0;toolDefaults=new Map;edits=new Map;batch=null;timeframe=null;register(e){this.registry.set(e.descriptor.type,e),this.dataGetter&&e.setDataGetter?.(this.dataGetter)}setEventCallback(e){this.eventCallback=e}setRequestRender(e){this.requestRender=e}setUndoRedoManager(e){this.undoRedo=e}setMagnetMode(e){this.magnetMode=e}getMagnetMode(){return this.magnetMode}setDataGetter(e){this.dataGetter=e;for(let t of this.registry.values())t.setDataGetter?.(e)}setDisplayDataGetter(e){this.displayDataGetter=e}snapToOHLC(e,t,n){let r=this.magnetMode===`none`?[]:this.displayDataGetter?.()??this.dataGetter?.()??[];return Qc(e,t,this.magnetMode,r,n)}undo(){if(!this.undoRedo)return!1;let e=this.undoRedo.undo();return e?(this.applyUndoAction(e),!0):!1}redo(){if(!this.undoRedo)return!1;let e=this.undoRedo.redo();return e?(this.applyRedoAction(e),!0):!1}foreignHistory=null;setForeignHistory(e){this.foreignHistory=e}applyUndoAction(e){if(e.type===`indicators`||e.type===`custom`){this.foreignHistory?.(e,`undo`);return}this.applyHistory(Uc(this.drawings,e))}applyRedoAction(e){if(e.type===`indicators`||e.type===`custom`){this.foreignHistory?.(e,`redo`);return}this.applyHistory(Wc(this.drawings,e))}applyHistory(e){let t=new Map(this.drawings.map((e,t)=>[e.id,{d:e,index:t}]));this.drawings=e,this.settleAfterHistory();let n=new Set(e.map(e=>e.id));for(let e of t.keys())n.has(e)||(this.edits.delete(e),this.eventCallback?.(`drawingRemove`,{id:e}));e.forEach((e,n)=>{let r=t.get(e.id);r?(r.d!==e||r.index!==n)&&this.eventCallback?.(`drawingUpdate`,{id:e.id}):this.eventCallback?.(`drawingCreate`,{id:e.id,type:e.type,drawing:e})})}settleAfterHistory(){this.selection.clear(),this.creator.reset(),this.state=this.activeTool?`creating`:`idle`,this.requestRender?.()}record(e){this.batch?this.batch.push(e):this.undoRedo?.push(e)}batchUndo(e){if(this.batch){e();return}let t=[];this.batch=t;try{e()}finally{this.batch=null}t.length===1?this.undoRedo?.push(t[0]):t.length>1&&this.undoRedo?.push({type:`drawingBatch`,before:null,after:null,actions:t})}deselect(e){this.selection.remove(e)&&!this.selection.primary&&this.state===`selected`&&(this.state=`idle`)}addToSelection(e){this.selection.add(e),this.state=`selected`}groupMates(e){let t=e.group?.id;return t?this.drawings.filter(n=>n.group?.id===t&&n.id!==e.id&&this.shown(n)).map(e=>e.id):[]}select(e){if(this.state===`creating`)return!1;let t=this.drawings.find(t=>t.id===e);return!t||!this.shown(t)?!1:(this.selection.has(e)||this.selection.only(e,this.groupMates(t)),this.state=`selected`,this.requestRender?.(),!0)}setSelectionListener(e){this.selection.setListener(e)}getSelectedDrawingIds(){return this.selection.ids()}selectInRect(t,n){if(this.state===`creating`)return 0;this.selection.clear(),this.state=`idle`;let r=Math.min(t.x0,t.x1),i=Math.max(t.x0,t.x1),a=Math.min(t.y0,t.y1),o=Math.max(t.y0,t.y1);for(let t of this.drawings)this.shown(t)&&t.anchors.some(t=>{let s=e.O(t.time,n),c=e.T(t.price,n);return s>=r&&s<=i&&c>=a&&c<=o})&&this.addToSelection(t.id);return this.requestRender?.(),this.getSelectedDrawingIds().length}toggleSelectionAt(e,t){if(this.state===`creating`)return!1;for(let n=this.drawings.length-1;n>=0;n--){let r=this.drawings[n];if(this.shown(r)&&this.registry.get(r.type)?.hitTest(e,r,t,8))return this.selection.has(r.id)?this.deselect([r.id]):this.addToSelection(r.id),this.requestRender?.(),!0}return!1}beginMove(e,t){this.state=`moving`;let n=this.getSelectedDrawingIds().filter(e=>e!==t.id).map(e=>this.drawings.find(t=>t.id===e)).filter(e=>e!==void 0&&!e.locked);this.drag.beginMove(e,[t,...n])}setFlags(e,t){this.batchUndo(()=>{for(let n of e){if((t.visible===void 0||n.visible===t.visible)&&(t.locked===void 0||n.locked===t.locked))continue;let e=q(n);Object.assign(n,t),this.record({type:`drawingModify`,before:e,after:q(n)})}}),t.visible===!1&&this.deselect(e.map(e=>e.id)),this.requestRender?.()}lockAllDrawings(){this.setFlags(this.drawings,{locked:!0})}unlockAllDrawings(){this.setFlags(this.drawings,{locked:!1})}hideAllDrawings(){this.setFlags(this.drawings,{visible:!1})}showAllDrawings(){this.setFlags(this.drawings,{visible:!0})}setTimeframe(e){e!==this.timeframe&&(this.timeframe=e,this.deselect(this.drawings.filter(e=>!this.shown(e)).map(e=>e.id)),this.requestRender?.())}isShown(e){let t=this.drawings.find(t=>t.id===e);return t!==void 0&&this.shown(t)}shown(e){return e.visible&&$t(e.intervals,this.timeframe)}setDrawingVisible(e,t){let n=this.drawings.find(t=>t.id===e);return n?(this.setFlags([n],{visible:t}),t):null}setDrawingsVisible(e,t){let n=new Set(e);this.setFlags(this.drawings.filter(e=>n.has(e.id)),{visible:t})}setDrawingsLocked(e,t){let n=new Set(e);this.setFlags(this.drawings.filter(e=>n.has(e.id)),{locked:t})}setDrawingLocked(e,t){let n=this.drawings.find(t=>t.id===e);return n?(this.setFlags([n],{locked:t}),t):null}setActiveTool(e){e&&this.setEraser(!1);let t=e!==this.activeTool;this.activeTool=e,this.state=e?`creating`:`idle`,this.creator.reset(),t&&this.eventCallback?.(`drawingToolChange`,{tool:e})}setStayInDrawingMode(e){this.stayInDrawingMode=e}isStayInDrawingMode(){return this.stayInDrawingMode}setToolFilter(e){this.toolAllowed=e}copySelection(){let e=this.getSelectedDrawingIds().map(e=>this.drawings.find(t=>t.id===e)).filter(e=>e!==void 0);return e.length===0?0:(nl.drawings=e.map(e=>structuredClone(e)),nl.pastes=0,e.length)}canPaste(){return this.state!==`creating`&&nl.drawings.some(e=>this.canPasteType(e.type))}canPasteType(e){return this.registry.has(e)&&this.toolAllowed(e)}paste(){if(nl.drawings.length===0||this.state===`creating`)return[];let e=nl.drawings.every(e=>this.drawings.some(t=>t.id===e.id));nl.pastes+=1;let t=e?this.computeBarOffsetTime(3*nl.pastes):0,n=[];if(this.batchUndo(()=>{for(let e of nl.drawings)this.canPasteType(e.type)&&n.push(this.addDrawing({type:e.type,anchors:e.anchors.map(e=>({...e,time:e.time+t})),style:{...e.style},options:e.options?Ac(e.options):void 0,intervals:e.intervals,meta:e.meta?structuredClone(e.meta):void 0}))}),n.length===0)return n;this.selection.clear(),this.state=`idle`;for(let e of n)this.isShown(e)&&this.addToSelection(e);return this.requestRender?.(),n}getActiveTool(){return this.activeTool}setStyle(e){Object.assign(this.activeStyle,e)}getActiveStyle(){return{...this.activeStyle}}setSelectedDrawingStyle(e,t){let n=t?[t]:this.getSelectedDrawingIds(),r=!1;return this.batchUndo(()=>{for(let t of n){let n=this.drawings.find(e=>e.id===t);if(!n||n.locked)continue;let i=q(n);n.style={...n.style,...e},this.record({type:`drawingModify`,before:i,after:q(n)}),r=!0}}),r&&this.requestRender?.(),r}onPointerDown(e,t,n=il){return this.eraser?this.erase(e,t,n.line):this.state===`creating`&&this.activeTool?this.handleCreationClick(e,t):this.state===`idle`||this.state===`selected`?this.handleSelectionClick(e,t,n):!1}placeAt(e,t){let n=this.state===`creating`?this.creator.current:null;return!n||n.anchors.length!==1||this.registry.get(n.type)?.descriptor.creation===`freehand`?!1:this.handleCreationClick(e,t)}takeBackPoint(){return this.state!==`creating`||!this.creator.current?!1:(this.creator.undoPoint(),this.requestRender?.(),!0)}onPointerMove(e,t){let n=this.state===`creating`?this.creator.current:null;if(n&&this.creator.move(this.creationAnchor(n.type,e,t),e))return this.requestRender?.(),!0;if((this.state===`moving`||this.state===`resizing`)&&this.drag.isActive()){let n=this.drawings.find(e=>e.id===this.selection.primary);return this.drag.move(e,t,n&&this.registry.get(n.type))?(this.requestRender?.(),!0):!1}return!1}onPointerUp(){let e=this.state===`creating`?this.creator.release():null;if(e)return this.afterCreationStep(e),!0;if(this.state===`moving`||this.state===`resizing`){let e=this.drag.end();return this.batchUndo(()=>{for(let{before:t,drawing:n}of e)Mc(n.anchors,t.anchors)&&jc(n.options,t.options)||this.record({type:`drawingModify`,before:t,after:q(n)})}),this.state=`selected`,!0}return!1}onKeyDown(e,t=!1,n){let r=Kc(e,t,n);if(!r)return!1;let i=this.state===`selected`?this.selection.primary:null;switch(r){case`copy`:return i!==null&&this.copySelection()>0;case`paste`:return this.paste().length>0;case`duplicate`:return i!==null&&this.duplicateDrawing(i)!==null;case`group`:return i!==null&&this.groupDrawings(this.getSelectedDrawingIds())!==null;case`ungroup`:return this.ungroupSelection();case`front`:case`forward`:case`backward`:case`back`:return i!==null&&this.moveDrawing(i,r);case`undo`:return this.state===`creating`&&this.creator.current?(this.creator.undoPoint(),this.requestRender?.(),!0):this.undo();case`redo`:return this.redo();case`escape`:return this.escape();case`delete`:return i!==null&&this.removeDrawings(this.getSelectedDrawingIds())>0;case`finish`:{if(this.state!==`creating`||!this.creator.current)return!1;let e=this.creator.finish();return e===`done`?(this.afterCreationStep(e),!0):!1}}}escape(){return this.eraser?(this.setEraser(!1),!0):this.state===`creating`?(this.setActiveTool(null),this.requestRender?.(),!0):this.state===`selected`?(this.selection.clear(),this.state=`idle`,this.requestRender?.(),!0):!1}ungroupSelection(){let e=new Set;for(let t of this.getSelectedDrawingIds()){let n=this.drawings.find(e=>e.id===t)?.group;n&&e.add(n.id)}for(let t of e)this.ungroup(t);return e.size>0}getDrawings(){return this.drawings}setDrawings(e){zc(e),this.drawings=this.upgradeLegacyAnchors(e).map(e=>{if(!e.options&&e.intervals===void 0)return e;let n=(0,t.sanitizeDrawingOptions)(this.optionDefs(e.type),e.options);return{...e,options:Object.keys(n).length>0?n:void 0,intervals:en(e.intervals)??void 0}});let n=new Map(this.drawings.map(e=>[e.id,e]));this.deselect(this.getSelectedDrawingIds().filter(e=>{let t=n.get(e);return!t||!this.shown(t)}));let r=new Set(n.keys());for(let e of[...this.edits.keys()])r.has(e)||this.edits.delete(e);this.requestRender?.()}moveDrawing(e,t){let n=this.drawings.findIndex(t=>t.id===e);if(n<0)return!1;let r=Vc(n,this.drawings.length,t);if(r===n)return!1;let i=this.drawings.map(e=>e.id),a=[...this.drawings],[o]=a.splice(n,1);return a.splice(r,0,o),this.drawings=a,this.record({type:`drawingOrder`,before:null,after:null,order:{before:i,after:a.map(e=>e.id)}}),this.eventCallback?.(`drawingUpdate`,{id:e}),this.requestRender?.(),!0}getGroups(){let e=new Map;for(let t of this.drawings){if(!t.group)continue;let n=e.get(t.group.id)??{id:t.group.id,name:t.group.name,ids:[]};n.ids.push(t.id),e.set(t.group.id,n)}return[...e.values()]}updateGroup(e,t){let n=this.drawings.filter(t=>t.group?.id===e);return n.length===0?!1:(this.batchUndo(()=>{for(let e of n){let n=q(e);t(e),this.record({type:`drawingModify`,before:n,after:q(e)}),this.eventCallback?.(`drawingUpdate`,{id:e.id})}}),this.requestRender?.(),!0)}groupDrawings(e,t){let n=new Set(e),r=this.drawings.filter(e=>n.has(e.id));if(r.length<2)return null;let{id:i,number:a}=Rc(),o={id:i,name:ol(t)||`Group ${a}`};return this.batchUndo(()=>{for(let e of r){let t=q(e);e.group={...o},this.record({type:`drawingModify`,before:t,after:q(e)}),this.eventCallback?.(`drawingUpdate`,{id:e.id})}}),this.requestRender?.(),o.id}ungroup(e){return this.updateGroup(e,e=>{delete e.group})}renameGroup(e,t){let n=ol(t);return n.length>0&&this.updateGroup(e,t=>{t.group={id:e,name:n}})}setGroupVisible(e,t){let n=this.updateGroup(e,e=>{e.visible=t});return n&&!t&&this.deselect(this.drawings.filter(t=>t.group?.id===e).map(e=>e.id)),n}setGroupLocked(e,t){return this.updateGroup(e,e=>{e.locked=t})}priceAt(e,t,n){let r=this.drawings.find(t=>t.id===e);if(!r)return null;let i=this.registry.get(r.type)?.priceAt?.(r,t,n)??null;return i&&i.every(Number.isFinite)?i:null}hasPriceLevels(e){let t=this.drawings.find(t=>t.id===e);return!!t&&typeof this.registry.get(t.type)?.priceAt==`function`}getDescriptor(e){return this.registry.get(e)?.descriptor??null}getOptionDefs(e){return this.optionDefs(e)??{}}optionDefs(e){return this.registry.get(e)?.descriptor.options}initialOptions(e,n){let r=this.optionDefs(e),i={...Ac(this.toolDefaults.get(e)??{}),...(0,t.sanitizeDrawingOptions)(r,n)};return Object.keys(i).length>0?i:void 0}setToolDefaults(e,n){let r=n?(0,t.sanitizeDrawingOptions)(this.optionDefs(e),n):{};Object.keys(r).length>0?this.toolDefaults.set(e,r):this.toolDefaults.delete(e)}getToolDefaults(e){return Ac(this.toolDefaults.get(e)??{})}getDrawingOptions(e){let n=this.drawings.find(t=>t.id===e);return n?(0,t.resolveDrawingOptions)(this.optionDefs(n.type),n.options):{}}setDrawingOptions(e,t){return this.updateDrawing(e,{options:t})}updateDrawing(e,n){let r=this.drawings.find(t=>t.id===e);if(!r||n.anchors&&!(n.anchors.length===r.anchors.length&&n.anchors.every(e=>Number.isFinite(e.time)&&Number.isFinite(e.price))))return!1;let i=this.edits.has(e)?null:q(r);if(n.anchors&&(r.anchors=n.anchors.map(e=>({time:e.time,price:e.price}))),n.style&&(r.style={...r.style,...n.style}),n.options){let e={...r.options,...(0,t.sanitizeDrawingOptions)(this.optionDefs(r.type),n.options)};r.options=Object.keys(e).length>0?e:void 0}return n.intervals!==void 0&&(r.intervals=en(n.intervals)??void 0,!this.edits.has(e)&&!this.shown(r)&&this.deselect([e])),i&&this.record({type:`drawingModify`,before:i,after:q(r)}),this.eventCallback?.(`drawingUpdate`,{id:e}),this.requestRender?.(),!0}beginEdit(e){let t=this.drawings.find(t=>t.id===e);return t?(this.edits.has(e)||this.edits.set(e,q(t)),!0):!1}endEdit(e,{cancel:t=!1}={}){let n=this.edits.get(e);if(!n)return;this.edits.delete(e);let r=this.drawings.findIndex(t=>t.id===e);r<0||(t?(this.drawings[r]=n,this.requestRender?.()):JSON.stringify(n)!==JSON.stringify(this.drawings[r])&&this.record({type:`drawingModify`,before:n,after:q(this.drawings[r])}),this.shown(this.drawings[r])||this.deselect([e]),this.eventCallback?.(`drawingUpdate`,{id:e}))}addDrawing(e){e.id&&zc([{id:e.id}]);let t=e.id??Lc(),n={id:t,type:e.type,anchors:e.anchors.map(e=>({...e})),style:{...this.activeStyle,...e.style},visible:e.visible??!0,locked:e.locked??!1,options:this.initialOptions(e.type,e.options),intervals:en(e.intervals)??void 0,meta:e.meta};return this.drawings=[...this.drawings,n],this.record({type:`drawingCreate`,before:null,after:q(n)}),this.eventCallback?.(`drawingCreate`,{id:t,type:n.type,drawing:n}),this.requestRender?.(),t}upgradeLegacyAnchors(e){let t=this.dataGetter?.();if(!t||t.length===0)return e;let n=rl;return t[t.length-1].time<n?e:e.map(e=>({...e,anchors:e.anchors.map(e=>{if(!Number.isFinite(e.time)||e.time<0||e.time>=n)return e;let r=Math.max(0,Math.min(t.length-1,Math.round(e.time)));return{...e,time:t[r].time}})}))}removeDrawing(e){let t=this.drawings.findIndex(t=>t.id===e),n=this.drawings[t];this.drawings=this.drawings.filter(t=>t.id!==e),n&&this.record({type:`drawingRemove`,before:structuredClone(n),after:null,index:t}),this.deselect([e]),this.edits.delete(e),this.eventCallback?.(`drawingRemove`,{id:e}),this.requestRender?.()}removeDrawings(e){let t=[...new Set(e)].filter(e=>{let t=this.drawings.find(t=>t.id===e);return t!==void 0&&!t.locked});return t.length===0?0:(this.batchUndo(()=>{for(let e of t)this.removeDrawing(e)}),t.length)}duplicateDrawing(e){let t=this.drawings.find(t=>t.id===e);if(!t)return null;let n=structuredClone(t);n.id=Lc();let r=this.computeBarOffsetTime(3);return n.anchors=n.anchors.map(e=>({...e,time:e.time+r})),n.locked=!1,this.drawings.push(n),this.record({type:`drawingCreate`,before:null,after:structuredClone(n)}),this.selection.only(n.id),this.state=`selected`,this.eventCallback?.(`drawingCreate`,{id:n.id,type:n.type,drawing:n}),this.requestRender?.(),n.id}clearDrawings(){this.drawings=[],this.selection.clear(),this.state=`idle`,this.requestRender?.()}getSelectedDrawingId(){return this.selection.primary}render(e,t){e.save(),e.beginPath(),e.rect(t.chartRect.x,t.chartRect.y,t.chartRect.width,t.chartRect.height),e.clip();for(let n of this.drawings){if(!this.shown(n))continue;let r=this.registry.get(n.type);if(!r)continue;let i=this.selection.has(n.id);r.render(e,n,t,i)}let n=this.creator.previewState();n&&this.registry.get(n.type)?.render(e,n,t,!1),e.restore()}computeBarOffsetTime(e){let t=this.dataGetter?.();if(!t||t.length<2)return e;let n=Math.max(0,t.length-20),r=[];for(let e=n+1;e<t.length;e++)r.push(t[e].time-t[e-1].time);return r.length===0?e:(r.sort((e,t)=>e-t),e*r[Math.floor(r.length/2)])}creationAnchor(t,n,r){let i=e.j(n.x,r),a=e.M(n.y,r);return this.registry.get(t)?.descriptor.creation===`freehand`?{time:i,price:a}:this.snapToOHLC(i,a,r)}handleCreationClick(t,n){let r=this.activeTool,i=r?this.registry.get(r):void 0;if(!r||!i)return!1;let a=()=>({id:Lc(),type:r,anchors:[],style:{...this.activeStyle},visible:!0,locked:!1,options:this.initialOptions(r)});return this.creationPressAt=Date.now(),this.afterCreationStep(this.creator.press(i,a,this.creationAnchor(r,t,n),t,t=>({x:e.O(t.time,n),y:e.T(t.price,n)}))),!0}afterCreationStep(e){e===`done`?this.finalizeCreation():e===`cancel`&&this.creator.reset(),this.requestRender?.()}setEraser(e){e!==this.eraser&&(this.eraser=e,e&&(this.setActiveTool(null),this.selection.clear(),this.state=`idle`),this.eventCallback?.(`toolModeChange`,{eraser:e}),this.requestRender?.())}isEraser(){return this.eraser}erase(e,t,n){let r=this.erasableAt(e,t,n);return r?(this.removeDrawing(r),!0):!1}erasableAt(e,t,n=il.line){for(let r=this.drawings.length-1;r>=0;r--){let i=this.drawings[r];if(!(!this.shown(i)||i.locked)&&this.registry.get(i.type)?.hitTest(e,i,t,n))return i.id}return null}justFinished(e=500){return Date.now()-this.creationPressAt<e&&this.finishedAt>=this.creationPressAt}finalizeCreation(){let e=this.creator.take();if(e){if(this.finishedAt=Date.now(),this.drawings.push(e),this.selection.only(e.id),this.record({type:`drawingCreate`,before:null,after:structuredClone(e)}),this.eventCallback?.(`drawingCreate`,{id:e.id,type:e.type,drawing:e}),this.stayInDrawingMode&&this.activeTool){this.selection.clear(),this.state=`creating`;return}this.activeTool=null,this.state=`selected`,this.eventCallback?.(`drawingToolChange`,{tool:null})}}isDragging(){return this.state===`moving`||this.state===`resizing`}drawingAt(e,t,n=il.line){for(let r=this.drawings.length-1;r>=0;r--){let i=this.drawings[r];if(this.shown(i)&&this.registry.get(i.type)?.hitTest(e,i,t,n))return i.id}return null}hoverCursorAt(e,t){if(this.eraser)return this.erasableAt(e,t)?`pointer`:null;if(this.activeTool||this.state===`creating`)return null;let n=il.line;if(this.selection.primary){let r=this.drawings.find(e=>e.id===this.selection.primary),i=r&&this.shown(r)&&!r.locked?this.registry.get(r.type):void 0;if(r&&i&&i.hitTestAnchor(e,r,t,n)>=0)return`move`}for(let r=this.drawings.length-1;r>=0;r--){let i=this.drawings[r];if(!(!this.shown(i)||i.locked)&&this.registry.get(i.type)?.hitTest(e,i,t,n))return`pointer`}return null}handleSelectionClick(e,t,n){let r=n.line;if(this.selection.primary){let i=this.drawings.find(e=>e.id===this.selection.primary);if(i&&this.shown(i)&&!i.locked){let a=this.registry.get(i.type);if(a){let o=a.hitTestAnchor(e,i,t,n.handle);if(o>=0)return this.state=`resizing`,this.drag.beginResize(e,i,o),!0;if(a.hitTest(e,i,t,r))return this.beginMove(e,i),!0}}}for(let n=this.drawings.length-1;n>=0;n--){let i=this.drawings[n];if(!this.shown(i))continue;let a=this.registry.get(i.type);if(a&&a.hitTest(e,i,t,r))return this.selection.has(i.id)?this.selection.focus(i.id):this.selection.only(i.id,this.groupMates(i)),this.requestRender?.(),i.locked?(this.state=`selected`,!1):(this.beginMove(e,i),!0)}return this.selection.primary&&(this.selection.clear(),this.state=`idle`,this.requestRender?.()),!1}};function ol(e){return(e??``).trim().slice(0,80)}var sl=class{constructor(e){this.manager=e}render(e,t,n){rc(n??null),this.manager.render(e,t)}};function cl(e,t,n){let r=Math.max(0,t),i=Math.min(e.length-1,n);if(i<=r)return null;let a=r,o=r;for(let t=r;t<=i;t++)e[t].high>e[a].high&&(a=t),e[t].low<e[o].low&&(o=t);if(a===o)return null;let s={time:e[a].time,price:e[a].high},c={time:e[o].time,price:e[o].low};return a<o?[s,c]:[c,s]}var ll={0:`#7d8696`,.236:`#e8505b`,.25:`#e8505b`,.382:`#c98316`,.5:`#1fa874`,.618:`#1398a8`,.75:`#1398a8`,.786:`#4c8dff`,1:`#7d8696`,1.272:`#a57cff`,1.414:`#e25592`,1.618:`#4c8dff`,2:`#a57cff`,2.618:`#e8505b`,3.618:`#a57cff`,4.236:`#e25592`};function ul(e,t=[]){return dl(e,t).map(e=>{let t=ll[e.value];return t?{...e,color:t}:e})}function dl(e,t=[]){return[...e.map(e=>({value:e,visible:!0})),...t.map(e=>({value:e,visible:!1}))].sort((e,t)=>e.value-t.value)}function fl(e=!1,t=!1){return{extendLeft:{kind:`boolean`,label:`Extend left`,default:e},extendRight:{kind:`boolean`,label:`Extend right`,default:t}}}var pl={showLevels:{kind:`boolean`,label:`Show levels`,default:!0},showPrices:{kind:`boolean`,label:`Show prices`,default:!0},labelPosition:{kind:`choice`,label:`Labels`,default:`left`,choices:[{value:`left`,label:`Left`},{value:`right`,label:`Right`}]}},ml=28,hl=48;function gl(e,t){return Math.atan2(e.y-t.y,t.x-e.x)*180/Math.PI}var _l=class extends K{descriptor={type:`trendAngle`,name:`Trend Angle`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=gl(i,a),s=a.x>=i.x?1:-1;this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),this.resetLineStyle(e),e.strokeStyle=t.style.color,e.lineWidth=1,e.setLineDash([3,3]),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x+s*hl,i.y),e.stroke(),e.setLineDash([]);let c=Math.atan2(a.y-i.y,a.x-i.x),l=s>0?0:Math.PI;s<0&&c<0&&(c+=2*Math.PI),e.beginPath(),e.arc(i.x,i.y,ml,Math.min(l,c),Math.max(l,c)),e.stroke(),e.font=W(11),e.fillStyle=t.style.color,e.textAlign=s>0?`left`:`right`,e.textBaseline=`middle`,G(e,`${o.toFixed(1)}°`,i.x+s*(ml+6),i.y+(o>=0?-8:8)),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);return this.distanceToLine(e,i,a)<=r}},vl=12,yl=3.5,bl=8,xl=[{value:`normal`,label:`Normal`},{value:`arrow`,label:`Arrow`}],Sl={leftEnd:{kind:`choice`,label:`Left end`,default:`normal`,choices:xl},rightEnd:{kind:`choice`,label:`Right end`,default:`normal`,choices:xl}},Cl={showMiddlePoint:{kind:`boolean`,label:`Show middle point`,default:!1},showPriceRange:{kind:`boolean`,label:`Show price range`,default:!1},showBarsRange:{kind:`boolean`,label:`Show bars range`,default:!1},showDateRange:{kind:`boolean`,label:`Show date and time range`,default:!1},showAngle:{kind:`boolean`,label:`Show angle`,default:!1},alwaysShowStats:{kind:`boolean`,label:`Always show stats`,default:!1},statsPosition:{kind:`choice`,label:`Stats position`,default:`right`,choices:[{value:`left`,label:`Left`},{value:`center`,label:`Center`},{value:`right`,label:`Right`}]}};function wl(e,t,n,r){let i=Math.atan2(n.y-t.y,n.x-t.x);e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-vl*Math.cos(i-Math.PI/6),n.y-vl*Math.sin(i-Math.PI/6)),e.lineTo(n.x-vl*Math.cos(i+Math.PI/6),n.y-vl*Math.sin(i+Math.PI/6)),e.closePath(),e.fillStyle=r,e.fill()}function Tl(e,t,n,r){let[i,a]=t;i.x===a.x&&i.y===a.y||(r(`leftEnd`)===`arrow`&&wl(e,a,i,n),r(`rightEnd`)===`arrow`&&wl(e,i,a,n))}function El(e,t,n,r,i){let a=[];i(`showPriceRange`)&&a.push(vc(e.anchors[0].price,e.anchors[1].price,t)),i(`showBarsRange`)&&a.push(`${xc(e,0,1,t)} bars`);let o=i(`showDateRange`)?Sc(e,0,1,t):null;return o&&a.push(o),i(`showAngle`)&&a.push(`${gl(n,r).toFixed(1)}°`),a}function Dl(e,t,n,[r,i],a,o){let s={x:(r.x+i.x)/2,y:(r.y+i.y)/2};if(o(`showMiddlePoint`)&&(e.beginPath(),e.arc(s.x,s.y,yl,0,Math.PI*2),e.fillStyle=ic(),e.fill(),e.strokeStyle=t.style.color,e.lineWidth=1,e.stroke()),!a&&!o(`alwaysShowStats`))return;let c=El(t,n,r,i,o);if(c.length===0)return;let[l,u]=r.x<=i.x?[r,i]:[i,r],d=o(`statsPosition`);if(d===`center`){Cc(e,c,s.x,s.y-bl,`center`,!0);return}let[f,p]=d===`left`?[l,u]:[u,l],m=f.y<=p.y;Cc(e,c,d===`left`?f.x-bl:f.x+bl,f.y+(m?-bl:bl),d===`left`?`right`:`left`,m)}var Ol=class extends K{descriptor={type:`trendLine`,name:`Trend Line`,requiredAnchors:2,options:{...fl(),...Sl,...Cl}};segment(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t);return this.extendLine(n,r,t,this.option(e,`extendLeft`),this.option(e,`extendRight`))}render(e,t,n,r){if(t.anchors.length<2)return;let[i,a]=this.segment(t,n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),this.resetLineStyle(e);let o=this.optionsOf(t);Tl(e,[i,a],t.style.color,o),Dl(e,t,n,[this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n)],r,o),r&&this.renderAnchorHandles(e,t,n)}priceAt(e,t,n){if(e.anchors.length<2)return null;let r=this.linePriceAt(e.anchors[0],e.anchors[1],t,this.option(e,`extendLeft`),this.option(e,`extendRight`),Ec(n));return r===null?null:[r]}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let[i,a]=this.segment(t,n);return this.distanceToLine(e,i,a)<=r}},kl=class extends K{descriptor={type:`horizontalLine`,name:`Horizontal Line`,requiredAnchors:1};priceAt(e){return e.anchors.length<1?null:[e.anchors[0].price]}render(t,n,r,i){if(n.anchors.length<1)return;let a=e.T(n.anchors[0].price,r),{chartRect:o}=r;this.applyLineStyle(t,n.style),this.strokeHorizontal(t,o.x,o.x+o.width,a),this.resetLineStyle(t),t.fillStyle=n.style.color,t.font=W(11),t.textBaseline=`bottom`,G(t,_c(n.anchors[0].price,n.anchors[0].price,r),o.x+4,a-3),i&&this.renderAnchorHandles(t,n,r)}hitTest(t,n,r,i){if(n.anchors.length<1)return!1;let a=e.T(n.anchors[0].price,r);return Math.abs(t.y-a)<=i&&t.x>=r.chartRect.x&&t.x<=r.chartRect.x+r.chartRect.width}},Al=class extends K{descriptor={type:`horizontalRay`,name:`Horizontal Ray`,requiredAnchors:1};priceAt(e,t){return e.anchors.length<1||t<e.anchors[0].time?null:[e.anchors[0].price]}render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=i.y,{chartRect:o}=n;this.applyLineStyle(e,t.style),this.strokeHorizontal(e,i.x,o.x+o.width,a),this.resetLineStyle(e),e.fillStyle=t.style.color,e.font=W(11),e.textBaseline=`bottom`,G(e,_c(t.anchors[0].price,t.anchors[0].price,n),i.x+4,a-3),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n);return Math.abs(e.y-i.y)<=r&&e.x>=i.x-r&&e.x<=n.chartRect.x+n.chartRect.width}},jl=class extends K{descriptor={type:`verticalLine`,name:`Vertical Line`,requiredAnchors:1};render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),{chartRect:a}=n;this.applyLineStyle(e,t.style),this.strokeVertical(e,i.x,a.y,a.y+a.height),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n),{chartRect:a}=n;return Math.abs(e.x-i.x)<=r&&e.y>=a.y&&e.y<=a.y+a.height}},Ml=class extends K{descriptor={type:`ray`,name:`Ray`,requiredAnchors:2,options:Cl};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),{chartRect:o}=n,s=a.x-i.x,c=a.y-i.y,l=Math.hypot(s,c);if(l===0)return;let u=Math.hypot(o.width,o.height)*2,d=i.x+s/l*u,f=i.y+c/l*u;this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(d,f),e.stroke(),this.resetLineStyle(e),Dl(e,t,n,[i,a],r,this.optionsOf(t)),r&&this.renderAnchorHandles(e,t,n)}priceAt(e,t,n){if(e.anchors.length<2)return null;let r=this.linePriceAt(e.anchors[0],e.anchors[1],t,!1,!0,Ec(n));return r===null?null:[r]}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=a.x-i.x,s=a.y-i.y;return((e.x-i.x)*o+(e.y-i.y)*s)/(o*o+s*s)<0?!1:this.distanceToInfiniteLine(e,i,a)<=r}},Nl=class extends K{descriptor={type:`extendedLine`,name:`Extended Line`,requiredAnchors:2,options:Cl};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),{chartRect:o}=n,s=a.x-i.x,c=a.y-i.y,l=Math.hypot(s,c);if(l===0)return;let u=Math.hypot(o.width,o.height)*2,d=i.x-s/l*u,f=i.y-c/l*u,p=i.x+s/l*u,m=i.y+c/l*u;this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(d,f),e.lineTo(p,m),e.stroke(),this.resetLineStyle(e),Dl(e,t,n,[i,a],r,this.optionsOf(t)),r&&this.renderAnchorHandles(e,t,n)}priceAt(e,t,n){if(e.anchors.length<2)return null;let r=this.linePriceAt(e.anchors[0],e.anchors[1],t,!0,!0,Ec(n));return r===null?null:[r]}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);return this.distanceToInfiniteLine(e,i,a)<=r}},Pl=class extends K{descriptor={type:`parallelChannel`,name:`Parallel Channel`,requiredAnchors:3,fill:!0,options:{...fl(),middleLine:{kind:`boolean`,label:`Middle line`,default:!1}}};lines(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i=this.option(e,`extendLeft`),a=this.option(e,`extendRight`),o=this.extendLine(n,r,t,i,a);if(e.anchors.length<3)return{base:o,parallel:null,middle:null,corners:null};let s=this.anchorToPixel(e.anchors[2],t),c=r.x-n.x,l=r.y-n.y,u=Math.hypot(c,l)||1,d=-l/u,f=c/u,p=(s.x-n.x)*d+(s.y-n.y)*f,m=(e,t)=>({x:e.x+d*p*t,y:e.y+f*p*t}),h=m(n,1),g=m(r,1);return{base:o,parallel:this.extendLine(h,g,t,i,a),middle:this.option(e,`middleLine`)?this.extendLine(m(n,.5),m(r,.5),t,i,a):null,corners:[n,r,g,h]}}render(e,t,n,r){if(t.anchors.length<2)return;let{base:i,parallel:a,middle:o,corners:s}=this.lines(t,n);this.applyLineStyle(e,t.style);for(let t of[i,a])t&&(e.beginPath(),e.moveTo(t[0].x,t[0].y),e.lineTo(t[1].x,t[1].y),e.stroke());if(o&&(e.setLineDash([4,4]),e.beginPath(),e.moveTo(o[0].x,o[0].y),e.lineTo(o[1].x,o[1].y),e.stroke()),s&&t.style.fillColor){e.fillStyle=t.style.fillColor,e.beginPath(),e.moveTo(s[0].x,s[0].y);for(let t of s.slice(1))e.lineTo(t.x,t.y);e.closePath(),e.fill()}this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}priceAt(e,t,n){if(e.anchors.length<3)return null;let[r,i,a]=e.anchors,o=Ec(n),s=this.lineValueAt(r,i,t,this.option(e,`extendLeft`),this.option(e,`extendRight`),o),c=this.lineValueAt(r,i,a.time,!0,!0,o);if(s===null||c===null)return null;let l=o.value(a.price)-c,u=[s,s+l];return this.option(e,`middleLine`)&&u.push(s+l/2),u.map(o.price)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let{base:i,parallel:a,middle:o}=this.lines(t,n);return[i,a,o].some(t=>t!==null&&this.distanceToLine(e,t[0],t[1])<=r)}},Fl=class extends K{descriptor={type:`regressionChannel`,name:`Regression Channel`,requiredAnchors:2,fill:!0};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke();let o=a.x-i.x,s=a.y-i.y,c=Math.hypot(o,s);if(c===0){this.resetLineStyle(e);return}let l=Math.max(10,Math.min(c*.2,100)),u=-s/c*l,d=o/c*l;e.setLineDash([4,4]),e.beginPath(),e.moveTo(i.x+u,i.y+d),e.lineTo(a.x+u,a.y+d),e.stroke(),e.beginPath(),e.moveTo(i.x-u,i.y-d),e.lineTo(a.x-u,a.y-d),e.stroke(),t.style.fillColor&&(e.fillStyle=t.style.fillColor,e.beginPath(),e.moveTo(i.x+u,i.y+d),e.lineTo(a.x+u,a.y+d),e.lineTo(a.x-u,a.y-d),e.lineTo(i.x-u,i.y-d),e.closePath(),e.fill()),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.hypot(a.x-i.x,a.y-i.y),s=Math.max(10,Math.min(o*.2,100));return this.distanceToLine(e,i,a)<=r+s}};function Il(e,t,n,r,i=e=>e.toFixed(2)){let a=`${(e*100).toFixed(1)}%`,o=i(t);return n&&r?`${a} (${o})`:n?a:r?o:``}function Ll(t,n,r,i,a,o){let s=a.x1-a.x0;if(a.background&&i.length>1){let o=[...i].sort((e,t)=>e.level.value-t.level.value);for(let i=0;i<o.length-1;i++){let c=e.T(o[i].price,r),l=e.T(o[i+1].price,r),u=o[i+1].level.color,d=u??n.style.fillColor;d&&(t.fillStyle=d,t.globalAlpha=u?.07:.05+i*.02,t.fillRect(a.x0,Math.min(c,l),s,Math.abs(l-c)))}t.globalAlpha=1}t.font=W(11),t.textBaseline=`bottom`,t.textAlign=a.labelPosition===`right`?`right`:`left`;let c=a.labelPosition===`right`?a.x1-4:a.x0+4;for(let{level:s,price:l}of i){let i=e.T(l,r),u=s.color??n.style.color;o(u),t.globalAlpha=s.value===0||s.value===1?1:.8;let d=e._(t,i,Number(t.lineWidth)||1);t.lineWidth=d.width,t.beginPath(),t.moveTo(a.x0,d.y),t.lineTo(a.x1,d.y),t.stroke();let f=Il(s.value,l,a.showLevels,a.showPrices,e=>_c(e,e,r));f&&(t.globalAlpha=1,t.fillStyle=u,G(t,f,c,i-3))}t.globalAlpha=1}function Rl(t,n,r,i,a,o){return t.x<i-o||t.x>a+o?!1:r.some(({price:r})=>Math.abs(t.y-e.T(r,n))<=o)}var zl=ul([0,.236,.382,.5,.618,.786,1],[1.272,1.414,1.618,2.618,3.618,4.236]),Bl=class extends K{descriptor={type:`fibRetracement`,name:`Fibonacci Retracement`,requiredAnchors:2,fill:!0,options:{levels:{kind:`levels`,label:`Levels`,default:zl},...fl(!0,!0),reverse:{kind:`boolean`,label:`Reverse`,default:!1},...pl,background:{kind:`boolean`,label:`Background`,default:!0}}};levels(e){let t=this.option(e,`reverse`),n=e.anchors[+!!t].price,r=e.anchors[+!t].price;return this.visibleLevels(e).map(e=>({level:e,price:n+(r-n)*e.value}))}span(e,t){let{chartRect:n}=t,r=this.anchorToPixel(e.anchors[0],t).x,i=this.anchorToPixel(e.anchors[1],t).x;return[this.option(e,`extendLeft`)?n.x:Math.min(r,i),this.option(e,`extendRight`)?n.x+n.width:Math.max(r,i)]}render(e,t,n,r){if(t.anchors.length<2)return;let[i,a]=this.span(t,n);Ll(e,t,n,this.levels(t),{x0:i,x1:a,showLevels:this.option(t,`showLevels`),showPrices:this.option(t,`showPrices`),labelPosition:this.option(t,`labelPosition`),background:this.option(t,`background`)},n=>this.applyLineStyle(e,{...t.style,color:n})),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let[i,a]=this.span(t,n);return Rl(e,n,this.levels(t),i,a,r)}},Vl=ul([0,.618,1,1.618,2,2.618,3.618,4.236],[.382,.5,.786,1.272,1.414]),Hl=class extends K{descriptor={type:`fibExtension`,name:`Fibonacci Extension`,requiredAnchors:3,fill:!0,options:{levels:{kind:`levels`,label:`Levels`,default:Vl},...fl(!0,!0),...pl,background:{kind:`boolean`,label:`Background`,default:!1}}};levels(e){let t=e.anchors[1].price-e.anchors[0].price,n=e.anchors[2].price;return this.visibleLevels(e).map(e=>({level:e,price:n+t*e.value}))}span(e,t){let{chartRect:n}=t,r=e.anchors.map(e=>this.anchorToPixel(e,t).x);return[this.option(e,`extendLeft`)?n.x:Math.min(...r),this.option(e,`extendRight`)?n.x+n.width:Math.max(...r)]}render(e,t,n,r){if(t.anchors.length<3){if(t.anchors.length===2){let r=this.anchorToPixel(t.anchors[0],n),i=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(i.x,i.y),e.stroke(),this.resetLineStyle(e)}return}let[i,a]=this.span(t,n);Ll(e,t,n,this.levels(t),{x0:i,x1:a,showLevels:this.option(t,`showLevels`),showPrices:this.option(t,`showPrices`),labelPosition:this.option(t,`labelPosition`),background:this.option(t,`background`)},n=>this.applyLineStyle(e,{...t.style,color:n})),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<3)return!1;let[i,a]=this.span(t,n);return Rl(e,n,this.levels(t),i,a,r)}},Ul=class extends K{descriptor={type:`rectangle`,name:`Rectangle`,requiredAnchors:2,fill:!0};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x),s=Math.min(i.y,a.y),c=Math.abs(a.x-i.x),l=Math.abs(a.y-i.y);t.style.fillColor&&(e.fillStyle=t.style.fillColor,e.fillRect(o,s,c,l)),this.applyLineStyle(e,t.style),e.strokeRect(o,s,c,l),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x)-r,s=Math.min(i.y,a.y)-r,c=Math.max(i.x,a.x)+r,l=Math.max(i.y,a.y)+r;if(e.x<o||e.x>c||e.y<s||e.y>l)return!1;let u=Math.min(i.x,a.x)+r,d=Math.min(i.y,a.y)+r,f=Math.max(i.x,a.x)-r,p=Math.max(i.y,a.y)-r;return!(e.x>u&&e.x<f&&e.y>d&&e.y<p)||!!t.style.fillColor}},Wl=class extends K{descriptor={type:`ellipse`,name:`Ellipse`,requiredAnchors:2,fill:!0};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=(i.x+a.x)/2,s=(i.y+a.y)/2,c=Math.abs(a.x-i.x)/2,l=Math.abs(a.y-i.y)/2;e.beginPath(),e.ellipse(o,s,Math.max(c,1),Math.max(l,1),0,0,Math.PI*2),t.style.fillColor&&(e.fillStyle=t.style.fillColor,e.fill()),this.applyLineStyle(e,t.style),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=(i.x+a.x)/2,s=(i.y+a.y)/2,c=Math.max(Math.abs(a.x-i.x)/2,1),l=Math.max(Math.abs(a.y-i.y)/2,1),u=(e.x-o)/c,d=(e.y-s)/l,f=Math.sqrt(u*u+d*d),p=r/Math.max(Math.min(c,l),4);return t.style.fillColor?f<=1+p:Math.abs(f-1)<=p}},Gl=class extends K{descriptor={type:`triangle`,name:`Triangle`,requiredAnchors:3,fill:!0};render(e,t,n,r){if(t.anchors.length<3){if(t.anchors.length===2){let r=this.anchorToPixel(t.anchors[0],n),i=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(i.x,i.y),e.stroke(),this.resetLineStyle(e)}return}let i=t.anchors.map(e=>this.anchorToPixel(e,n));e.beginPath(),e.moveTo(i[0].x,i[0].y),e.lineTo(i[1].x,i[1].y),e.lineTo(i[2].x,i[2].y),e.closePath(),t.style.fillColor&&(e.fillStyle=t.style.fillColor,e.fill()),this.applyLineStyle(e,t.style),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<3)return!1;let i=t.anchors.map(e=>this.anchorToPixel(e,n));for(let t=0;t<3;t++){let n=(t+1)%3;if(this.distanceToLine(e,i[t],i[n])<=r)return!0}return!1}},Kl=class extends K{descriptor={type:`pitchfork`,name:`Andrews' Pitchfork`,requiredAnchors:3};origin(e,t){return e}render(e,t,n,r){if(t.anchors.length<3){if(t.anchors.length===2){let r=this.anchorToPixel(t.anchors[0],n),i=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(i.x,i.y),e.stroke(),this.resetLineStyle(e)}return}let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=this.anchorToPixel(t.anchors[2],n),s=this.origin(i,a),c={x:(a.x+o.x)/2,y:(a.y+o.y)/2};(s.x!==i.x||s.y!==i.y)&&(e.strokeStyle=t.style.color,e.lineWidth=1,e.setLineDash([3,3]),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(s.x,s.y),e.stroke(),e.setLineDash([]));let l=c.x-s.x,u=c.y-s.y,d=Math.hypot(l,u)||1,f=Math.hypot(n.chartRect.width,n.chartRect.height),p=s.x+l/d*f,m=s.y+u/d*f;this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(p,m),e.stroke(),e.beginPath(),e.moveTo(a.x,a.y),e.lineTo(a.x+l/d*f,a.y+u/d*f),e.stroke(),e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(o.x+l/d*f,o.y+u/d*f),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<3)return!1;let i=this.anchorToPixel(t.anchors[1],n),a=this.anchorToPixel(t.anchors[2],n),o=this.origin(this.anchorToPixel(t.anchors[0],n),i),s={x:(i.x+a.x)/2,y:(i.y+a.y)/2};if(this.distanceToInfiniteLine(e,o,s)<=r)return!0;let c=s.x-o.x,l=s.y-o.y,u={x:i.x+c,y:i.y+l},d={x:a.x+c,y:a.y+l};return this.distanceToInfiniteLine(e,i,u)<=r||this.distanceToInfiniteLine(e,a,d)<=r}},ql=class extends Kl{descriptor={type:`schiffPitchfork`,name:`Schiff Pitchfork`,requiredAnchors:3};origin(e,t){return{x:e.x,y:(e.y+t.y)/2}}},Jl=class extends Kl{descriptor={type:`modifiedSchiffPitchfork`,name:`Modified Schiff Pitchfork`,requiredAnchors:3};origin(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}},Yl=[`0`,`i`,`ii`,`iii`,`iv`,`v`];function Xl(e,t){let n=/^[0-9]$/.test(e);switch(t){case`primary`:return n?e===`0`?`⓪`:String.fromCodePoint(9312+Number(e)-1):/^[A-Z]$/.test(e)?String.fromCodePoint(9398+e.charCodeAt(0)-65):e;case`intermediate`:return`(${e})`;case`minute`:return n?Yl[Number(e)]??e:e.toLowerCase();default:return e}}var Zl={degree:{kind:`choice`,label:`Degree`,default:`minor`,choices:[{value:`primary`,label:`Primary`},{value:`intermediate`,label:`Intermediate`},{value:`minor`,label:`Minor`},{value:`minute`,label:`Minute`}]}},Ql=class extends K{render(e,t,n,r){if(t.anchors.length<2)return;let i=t.anchors.map(e=>this.anchorToPixel(e,n));this.applyLineStyle(e,t.style),e.beginPath(),i.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.stroke(),this.resetLineStyle(e);let a=this.option(t,`degree`);e.font=W(12,`bold`),e.fillStyle=t.style.color,e.textAlign=`center`;for(let t=0;t<i.length&&t<this.labels.length;t++){let n=i[t-1]??i[t+1],r=i[t+1]??i[t-1],o=i[t].y<=Math.min(n.y,r.y);e.textBaseline=o?`bottom`:`top`,G(e,Xl(this.labels[t],a),i[t].x,i[t].y+(o?-6:6))}r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:Oc(e,t.anchors.map(e=>this.anchorToPixel(e,n)),r)}},$l=class extends Ql{descriptor={type:`elliottWave`,name:`Elliott Wave`,requiredAnchors:8,options:Zl};labels=[`1`,`2`,`3`,`4`,`5`,`A`,`B`,`C`]},eu=class extends Ql{descriptor={type:`elliottImpulse`,name:`Elliott Impulse Wave`,requiredAnchors:6,options:Zl};labels=[`0`,`1`,`2`,`3`,`4`,`5`]},tu=class extends Ql{descriptor={type:`elliottCorrection`,name:`Elliott Correction Wave`,requiredAnchors:4,options:Zl};labels=[`0`,`A`,`B`,`C`]},nu=class extends Ql{descriptor={type:`elliottTriangle`,name:`Elliott Triangle Wave`,requiredAnchors:6,options:Zl};labels=[`0`,`A`,`B`,`C`,`D`,`E`]},ru=class extends Ql{descriptor={type:`elliottDoubleCombo`,name:`Elliott Double Combo Wave`,requiredAnchors:4,options:Zl};labels=[`0`,`W`,`X`,`Y`]},iu=class extends Ql{descriptor={type:`elliottTripleCombo`,name:`Elliott Triple Combo Wave`,requiredAnchors:6,options:Zl};labels=[`0`,`W`,`X`,`Y`,`X`,`Z`]},au=class extends K{descriptor={type:`priceRange`,name:`Price Range`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x),s=Math.abs(a.x-i.x),c=Math.min(i.y,a.y),l=Math.abs(a.y-i.y),u=t.anchors[1].price>t.anchors[0].price;e.fillStyle=u?`rgba(31, 168, 116, 0.15)`:`rgba(232, 80, 91, 0.15)`,e.fillRect(o,c,s,l),this.applyLineStyle(e,t.style),e.strokeRect(o,c,s,l),this.resetLineStyle(e);let d=vc(t.anchors[0].price,t.anchors[1].price,n);e.font=W(12),e.fillStyle=u?`#1fa874`:`#e8505b`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(d,o+s/2,c+l/2),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x),s=Math.max(i.x,a.x),c=Math.min(i.y,a.y),l=Math.max(i.y,a.y);return e.x>=o-r&&e.x<=s+r&&e.y>=c-r&&e.y<=l+r}},ou=class extends K{descriptor={type:`dateRange`,name:`Date Range`,requiredAnchors:2};render(t,n,r,i){if(n.anchors.length<2)return;let a=this.anchorToPixel(n.anchors[0],r),o=this.anchorToPixel(n.anchors[1],r),{chartRect:s}=r,c=Math.min(a.x,o.x),l=Math.max(a.x,o.x);t.fillStyle=`rgba(76, 141, 255, 0.08)`,t.fillRect(c,s.y,l-c,s.height),this.applyLineStyle(t,n.style),t.beginPath(),t.moveTo(c,s.y),t.lineTo(c,s.y+s.height),t.stroke(),t.beginPath(),t.moveTo(l,s.y),t.lineTo(l,s.y+s.height),t.stroke(),this.resetLineStyle(t);let u=e.D(n.anchors[0].time,r),d=e.D(n.anchors[1].time,r),f=Math.max(0,Math.round(Math.abs(d-u)));t.font=W(12),t.fillStyle=n.style.color,t.textAlign=`center`,t.textBaseline=`top`,t.fillText(`${f} bars`,(c+l)/2,s.y+4),i&&this.renderAnchorHandles(t,n,r)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),{chartRect:o}=n,s=Math.min(i.x,a.x),c=Math.max(i.x,a.x);return e.x>=s-r&&e.x<=c+r&&e.y>=o.y&&e.y<=o.y+o.height}},su=class extends K{descriptor={type:`measure`,name:`Measure`,requiredAnchors:2};render(t,n,r,i){if(n.anchors.length<2)return;let a=this.anchorToPixel(n.anchors[0],r),o=this.anchorToPixel(n.anchors[1],r);this.applyLineStyle(t,n.style),t.setLineDash([4,4]),t.beginPath(),t.moveTo(a.x,a.y),t.lineTo(o.x,o.y),t.stroke(),this.resetLineStyle(t);let s=e.D(n.anchors[0].time,r),c=e.D(n.anchors[1].time,r),l=Math.max(0,Math.round(Math.abs(c-s))),u=[`Price: ${vc(n.anchors[0].price,n.anchors[1].price,r)}`,`Bars: ${l}`],d=(a.x+o.x)/2,f=(a.y+o.y)/2;t.font=W(11),t.textAlign=`center`,t.textBaseline=`bottom`;let p=Math.max(...u.map(e=>t.measureText(e).width));t.fillStyle=`rgba(0, 0, 0, 0.7)`,t.fillRect(d-p/2-6,f-u.length*14-4,p+12,u.length*14+8),t.fillStyle=`#FFFFFF`;for(let e=0;e<u.length;e++)t.fillText(u[e],d,f-(u.length-1-e)*14);i&&this.renderAnchorHandles(t,n,r)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);return this.distanceToLine(e,i,a)<=r}};function cu(e,t=`Text`){if(typeof e.style.text==`string`&&e.style.text.length>0)return e.style.text;let n=e.meta?.text;return typeof n==`string`&&n.length>0?n:t}var lu=class extends K{descriptor={type:`text`,name:`Text`,requiredAnchors:1,text:!0};render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=cu(t),o=t.style.fontSize||14;if(e.font=`${o}px ${ac()}`,e.fillStyle=t.style.color,e.textAlign=`left`,e.textBaseline=`top`,r){let n=e.measureText(a);e.strokeStyle=t.style.color,e.lineWidth=1,e.setLineDash([3,3]),e.strokeRect(i.x-2,i.y-2,n.width+4,o+4),e.setLineDash([])}e.fillText(a,i.x,i.y),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=t.style.fontSize||14;return e.x>=i.x-r&&e.x<=i.x+80+r&&e.y>=i.y-r&&e.y<=i.y+a+r}},uu=class extends K{descriptor={type:`arrow`,name:`Arrow`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),wl(e,i,a,t.style.color),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);return this.distanceToLine(e,i,a)<=r}},du=[{label:`8x1`,ratio:8},{label:`4x1`,ratio:4},{label:`3x1`,ratio:3},{label:`2x1`,ratio:2},{label:`1x1`,ratio:1},{label:`1x2`,ratio:.5},{label:`1x3`,ratio:1/3},{label:`1x4`,ratio:.25},{label:`1x8`,ratio:.125}],fu=class extends K{descriptor={type:`gannFan`,name:`Gann Fan`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=a.x-i.x,s=a.y-i.y;if(Math.abs(o)<1)return;let c=s/o,l=o>0?1:-1,{chartRect:u}=n,d=l>0?u.x+u.width:u.x;this.applyLineStyle(e,t.style);for(let{label:n,ratio:r}of du){let a=c*r,o=d,s=i.y+a*(o-i.x);e.globalAlpha=r===1?1:.5,e.lineWidth=r===1?t.style.lineWidth:Math.max(.5,t.style.lineWidth*.7),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(o,s),e.stroke();let f=o-l*4,p=s;p>u.y&&p<u.y+u.height&&(e.globalAlpha=.7,e.fillStyle=t.style.color,e.font=W(9),e.textAlign=l>0?`right`:`left`,e.textBaseline=`bottom`,G(e,n,f,p-2))}e.globalAlpha=1,this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=a.x-i.x,s=a.y-i.y;if(Math.abs(o)<1)return!1;let c=s/o,l=o>0?1:-1,{chartRect:u}=n,d=l>0?u.x+u.width:u.x;for(let{ratio:t}of du){let n=c*t,a=d,o=i.y+n*(a-i.x);if(this.distanceToLine(e,i,{x:a,y:o})<=r)return!0}return!1}},pu=[0,.25,.333,.5,.667,.75,1],mu=class extends K{descriptor={type:`gannBox`,name:`Gann Box`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x),s=Math.max(i.x,a.x),c=Math.min(i.y,a.y),l=Math.max(i.y,a.y),u=s-o,d=l-c;if(!(u<2||d<2)){this.applyLineStyle(e,t.style),e.strokeRect(o,c,u,d),e.save(),e.globalAlpha=.35;for(let t of pu){if(t===0||t===1)continue;let n=c+d*t;e.beginPath(),e.moveTo(o,n),e.lineTo(s,n),e.stroke()}for(let t of pu){if(t===0||t===1)continue;let n=o+u*t;e.beginPath(),e.moveTo(n,c),e.lineTo(n,l),e.stroke()}e.globalAlpha=.5,e.setLineDash([4,3]),e.beginPath(),e.moveTo(o,c),e.lineTo(s,l),e.stroke(),e.beginPath(),e.moveTo(s,c),e.lineTo(o,l),e.stroke(),e.restore(),this.resetLineStyle(e),e.fillStyle=t.style.color,e.font=W(8),e.globalAlpha=.6,e.textBaseline=`bottom`,e.textAlign=`right`;for(let t of pu){if(t===0||t===1)continue;let n=c+d*t;e.fillText(`${(t*100).toFixed(0)}%`,o-3,n)}e.globalAlpha=1,r&&this.renderAnchorHandles(e,t,n)}}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x),s=Math.max(i.x,a.x),c=Math.min(i.y,a.y),l=Math.max(i.y,a.y);return Math.abs(e.x-o)<=r&&e.y>=c-r&&e.y<=l+r||Math.abs(e.x-s)<=r&&e.y>=c-r&&e.y<=l+r||Math.abs(e.y-c)<=r&&e.x>=o-r&&e.x<=s+r||Math.abs(e.y-l)<=r&&e.x>=o-r&&e.x<=s+r||this.distanceToLine(e,{x:o,y:c},{x:s,y:l})<=r||this.distanceToLine(e,{x:s,y:c},{x:o,y:l})<=r}},hu=class extends K{descriptor={type:`anchoredVWAP`,name:`Anchored VWAP`,requiredAnchors:1};dataGetter=null;showBands=!0;setDataGetter(e){this.dataGetter=e}setShowBands(e){this.showBands=e}render(t,n,r,i){if(n.anchors.length<1||!this.dataGetter)return;let a=this.dataGetter(),o=Math.max(0,Math.round(e.D(n.anchors[0].time,r)));if(o>=a.length)return;let{vwap:s,upper1:c,lower1:l,upper2:u,lower2:d}=this.computeVWAP(a,o),{chartRect:f}=r,p=r.barWidth+r.barSpacing;if(this.applyLineStyle(t,n.style),t.lineWidth=n.style.lineWidth+.5,this.drawLine(t,s,o,r,f,p),this.showBands&&s.length>1&&(t.globalAlpha=.4,t.lineWidth=Math.max(.5,n.style.lineWidth*.6),t.setLineDash([4,3]),this.drawLine(t,c,o,r,f,p),this.drawLine(t,l,o,r,f,p),t.globalAlpha=.25,this.drawLine(t,u,o,r,f,p),this.drawLine(t,d,o,r,f,p),t.globalAlpha=1),this.resetLineStyle(t),s.length>0){let i=s[s.length-1],a=e.b(o+s.length-1,r),c=e.T(i,r);a>=f.x&&a<=f.x+f.width&&(t.fillStyle=n.style.color,t.font=W(9,`bold`),t.textAlign=`left`,t.textBaseline=`middle`,t.fillText(`AVWAP ${_c(i,i,r)}`,a+6,c))}i&&this.renderAnchorHandles(t,n,r)}drawLine(t,n,r,i,a,o){t.beginPath();let s=!1;for(let c=0;c<n.length;c++){let l=e.b(r+c,i);if(l<a.x-o)continue;if(l>a.x+a.width+o)break;let u=e.T(n[c],i);s?t.lineTo(l,u):(t.moveTo(l,u),s=!0)}t.stroke()}vwapCache=null;computeVWAP(e,t){let n=e[e.length-1],r=this.vwapCache;if(r&&r.data===e&&r.length===e.length&&r.startIdx===t&&r.lastClose===n?.close&&r.lastVolume===(n?.volume??0))return r.result;let i=this.computeVWAPUncached(e,t);return this.vwapCache={data:e,length:e.length,startIdx:t,lastClose:n?.close,lastVolume:n?.volume??0,result:i},i}computeVWAPUncached(e,t){let n=e.length-t,r=Array(n),i=Array(n),a=Array(n),o=Array(n),s=Array(n),c=0,l=0,u=0;for(let d=0;d<n;d++){let n=e[t+d],f=(n.high+n.low+n.close)/3,p=n.volume??1;c+=f*p,l+=p,u+=f*f*p;let m=l>0?c/l:f;r[d]=m;let h=l>0?u/l-m*m:0,g=Math.sqrt(Math.max(0,h));i[d]=m+g,a[d]=m-g,o[d]=m+2*g,s[d]=m-2*g}return{vwap:r,upper1:i,lower1:a,upper2:o,lower2:s}}hitTest(t,n,r,i){if(n.anchors.length<1||!this.dataGetter)return!1;let a=this.dataGetter(),o=Math.max(0,Math.round(e.D(n.anchors[0].time,r)));if(o>=a.length)return!1;let{vwap:s}=this.computeVWAP(a,o);for(let n=1;n<s.length;n++){let a=e.b(o+n-1,r),c=e.T(s[n-1],r),l=e.b(o+n,r),u=e.T(s[n],r);if(this.distanceToLine(t,{x:a,y:c},{x:l,y:u})<=i)return!0}return!1}},gu=class extends K{descriptor={type:`volumeProfileRange`,name:`Volume Profile (Range)`,requiredAnchors:2,fill:!0};dataGetter=null;numBins=40;setDataGetter(e){this.dataGetter=e}render(t,n,r,i){if(n.anchors.length<2||!this.dataGetter)return;let a=this.dataGetter(),o=Math.round(e.D(n.anchors[0].time,r)),s=Math.round(e.D(n.anchors[1].time,r)),c=Math.max(0,Math.min(o,s)),l=Math.min(a.length-1,Math.max(o,s));if(c>=a.length||l<0||c>l)return;let u=1/0,d=-1/0;for(let e=c;e<=l;e++)a[e].low<u&&(u=a[e].low),a[e].high>d&&(d=a[e].high);if(u>=d)return;let f=(d-u)/this.numBins,p=new Float64Array(this.numBins),m=0;for(let e=c;e<=l;e++){let t=a[e],n=t.volume??1,r=Math.max(0,Math.floor((t.low-u)/f)),i=Math.min(this.numBins-1,Math.floor((t.high-u)/f)),o=n/(i-r+1);for(let e=r;e<=i;e++)p[e]+=o,p[e]>m&&(m=p[e])}if(m===0)return;let h=0;for(let e=1;e<this.numBins;e++)p[e]>p[h]&&(h=e);let g=e.b(l,r)+r.barWidth,_=n.style.color,v=n.style.fillColor??`#f2a93b`;t.save();for(let n=0;n<this.numBins;n++){let i=p[n]/m*100,a=u+(n+1)*f,o=u+n*f,s=e.T(a,r),c=e.T(o,r),l=Math.abs(c-s);t.globalAlpha=.35,t.fillStyle=n===h?v:_,t.fillRect(g,Math.min(s,c),i,Math.max(1,l-.5))}let y=u+(h+.5)*f,b=e.T(y,r);t.globalAlpha=.7,t.strokeStyle=v,t.lineWidth=1,t.setLineDash([4,3]),t.beginPath();let x=e.b(c,r)-r.barWidth/2;t.moveTo(x,b),t.lineTo(g+100,b),t.stroke(),t.fillStyle=v,t.font=W(9),t.textAlign=`left`,t.textBaseline=`bottom`,t.globalAlpha=.8,t.fillText(`POC ${_c(y,y,r)}`,g+100+4,b-2),t.restore(),i&&this.renderAnchorHandles(t,n,r)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x)-r,s=Math.max(i.x,a.x)+100+r,c=Math.min(i.y,a.y)-r,l=Math.max(i.y,a.y)+r;return e.x>=o&&e.x<=s&&e.y>=c&&e.y<=l}},_u=[1,2,3,5,8,13,21,34,55],vu=class extends K{descriptor={type:`fibTimeZones`,name:`Fibonacci Time Zones`,requiredAnchors:2,options:{levels:{kind:`levels`,label:`Levels`,default:dl(_u,[0,89,144])}}};render(t,n,r,i){if(n.anchors.length<2)return;let a=n.anchors[0],o=n.anchors[1].time-a.time;if(o===0)return;let{chartRect:s}=r;t.font=W(11),t.textBaseline=`top`,t.textAlign=`center`;for(let{value:i,color:c}of this.visibleLevels(n)){this.applyLineStyle(t,{...n.style,color:c??n.style.color});let l=e.O(a.time+o*i,r);l<s.x||l>s.x+s.width||(t.globalAlpha=i===1?1:.55,t.beginPath(),t.moveTo(l,s.y),t.lineTo(l,s.y+s.height),t.stroke(),t.fillStyle=c??n.style.color,G(t,String(i),l,s.y+2))}t.globalAlpha=1,this.resetLineStyle(t),i&&this.renderAnchorHandles(t,n,r)}hitTest(t,n,r,i){if(n.anchors.length<2)return!1;let a=n.anchors[0],o=n.anchors[1].time-a.time;if(o===0)return!1;let{chartRect:s}=r;if(t.y<s.y||t.y>s.y+s.height)return!1;for(let{value:s}of this.visibleLevels(n)){let n=e.O(a.time+o*s,r);if(Math.abs(t.x-n)<=i)return!0}return!1}},yu=40,bu=2,xu=.1,Su=100,Cu=0x38d7ea4c68000,wu=class extends K{descriptor={type:`riskReward`,name:`Long/Short Position`,requiredAnchors:2,options:{rewardRatio:{kind:`number`,label:`Reward:risk`,default:2,min:xu,max:Su,step:.1},accountSize:{kind:`number`,label:`Account size`,default:1e3,min:0,max:Cu},riskMode:{kind:`choice`,label:`Risk as`,default:`percent`,choices:[{value:`percent`,label:`Percent of account`},{value:`amount`,label:`Amount`}]},risk:{kind:`number`,label:`Risk`,default:1,min:0,max:Cu},qtyDecimals:{kind:`number`,label:`Quantity decimals`,default:2,min:0,max:8,step:1},showLabels:{kind:`boolean`,label:`Show labels`,default:!0}}};geometry(e){let t=e.anchors[0].price,n=e.anchors[1].price,r=this.option(e,`rewardRatio`),i=Math.abs(t-n),a=n<t,o=a?t+i*r:t-i*r,s=this.option(e,`risk`),c=this.option(e,`riskMode`)===`amount`?s:this.option(e,`accountSize`)*s/100,l=i>0?c/i:0;return{entry:t,stop:n,target:o,ratio:r,isLong:a,qty:l,riskAmount:c,rewardAmount:l*i*r}}span(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t);return{x:Math.min(n.x,r.x),width:Math.max(Math.abs(r.x-n.x),yu),stopX:r.x}}handles(e,t){let{target:n}=this.geometry(e),r=this.anchorToPixel(e.anchors[0],t),i=this.anchorToPixel(e.anchors[1],t),a=this.anchorToPixel({time:e.anchors[1].time,price:n},t).y;return[r,i,{x:i.x,y:a}]}render(e,n,r,i){if(n.anchors.length<2)return;let a=this.geometry(n),{x:o,width:s}=this.span(n,r),[c,l,u]=this.handles(n,r);e.fillStyle=`rgba(232, 80, 91, 0.18)`,e.fillRect(o,Math.min(c.y,l.y),s,Math.abs(l.y-c.y)),e.fillStyle=`rgba(31, 168, 116, 0.18)`,e.fillRect(o,Math.min(c.y,u.y),s,Math.abs(u.y-c.y)),e.strokeStyle=n.style.color,e.lineWidth=1,e.setLineDash([]),e.beginPath(),e.moveTo(o,c.y),e.lineTo(o+s,c.y),e.stroke();let{chartRect:d}=r,f=d.x,p=d.x+d.width;if(this.option(n,`showLabels`)&&o+s>=f&&o<=p){let i=(0,t.autoPricePrecision)(Math.min(a.stop,a.target),Math.max(a.stop,a.target)),s=this.option(n,`qtyDecimals`),m=e=>(a.entry===0?0:(e-a.entry)/a.entry*100).toFixed(2),h=Number(a.ratio.toFixed(2));e.font=W(11);let g=e=>r.formatPrice?.(e)??e.toFixed(i),_=e=>`${e>=a.entry?`+`:`−`}${Math.abs(Number(m(e))).toFixed(2)}%`,v=e=>{let t=e<c.y,n=e+(t?-1:1)*11,r=t?Math.min(n,c.y-20):Math.max(n,c.y+20);return Math.min(Math.max(r,d.y+9),d.y+d.height-9)},y=(t,n,r)=>{sc(e,t,Math.max(f+4,Math.min(o+4,p-4-oc(e,t))),n,r)};y(`${a.isLong?`Long`:`Short`} · Qty ${a.qty.toFixed(s)} · R:R ${h}`,c.y,n.style.color),Math.abs(l.y-c.y)>=1&&(y(`Target ${g(a.target)} (${_(a.target)}) · ${a.rewardAmount.toFixed(2)}`,v(u.y),`#1fa874`),y(`Stop ${g(a.stop)} (${_(a.stop)}) · ${a.riskAmount.toFixed(2)}`,v(l.y),`#e8505b`))}i&&this.renderHandles(e,n,r)}renderHandles(e,t,n){e.fillStyle=`#FFFFFF`,e.strokeStyle=t.style.color,e.lineWidth=1;for(let r of this.handles(t,n))e.fillRect(r.x-4,r.y-4,8,8),e.strokeRect(r.x-4,r.y-4,8,8)}hitTestAnchor(e,t,n,r){return t.anchors.length<2?super.hitTestAnchor(e,t,n,r):this.handles(t,n).findIndex(t=>Math.hypot(e.x-t.x,e.y-t.y)<=r)}moveHandle(e,t,n){if(t!==bu){let r=e.anchors.map((e,r)=>r===t?{...n}:{...e});return{...e,anchors:r}}let{entry:r,isLong:i}=this.geometry(e),a=Math.abs(r-e.anchors[1].price),o=i?n.price-r:r-n.price,s=a>0?Math.min(Su,Math.max(xu,o/a)):xu;return{...e,options:{...e.options,rewardRatio:Math.round(s*100)/100}}}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let{x:i,width:a}=this.span(t,n),o=this.handles(t,n).map(e=>e.y);return e.x>=i-r&&e.x<=i+a+r&&e.y>=Math.min(...o)-r&&e.y<=Math.max(...o)+r}},Tu=class extends K{descriptor={type:`crossLine`,name:`Cross Line`,requiredAnchors:1};render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),{chartRect:a}=n;this.applyLineStyle(e,t.style);let o=e.lineWidth;this.strokeHorizontal(e,a.x,a.x+a.width,i.y),e.lineWidth=o,this.strokeVertical(e,i.x,a.y,a.y+a.height),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n);return Math.abs(e.y-i.y)<=r||Math.abs(e.x-i.x)<=r}};function Eu(e,t,n){let r=Sc(e,0,1,t),i=xc(e,0,1,t);return[vc(e.anchors[0].price,e.anchors[1].price,t),r?`${i} bars, ${r}`:`${i} bars`,`${n.toFixed(1)}°`]}var Du=class extends K{descriptor={type:`infoLine`,name:`Info Line`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),this.resetLineStyle(e);let o=Eu(t,n,gl(i,a)),s=a.y<=i.y;Cc(e,o,a.x+(a.x>=i.x?8:-8),a.y+(s?-6:6),a.x>=i.x?`left`:`right`,s),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);return this.distanceToLine(e,i,a)<=r}},Ou=[0,.236,.382,.5,.618,.786,1,1.618];function ku(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=r*r+i*i;if(a===0)return{x:n.x-e.x,y:n.y-e.y};let o=((n.x-e.x)*r+(n.y-e.y)*i)/a;return{x:n.x-(e.x+o*r),y:n.y-(e.y+o*i)}}function Au(e,t,n,r){let i=ku(e,t,n);return[{x:e.x+i.x*r,y:e.y+i.y*r},{x:t.x+i.x*r,y:t.y+i.y*r}]}var ju=class extends K{descriptor={type:`fibChannel`,name:`Fibonacci Channel`,requiredAnchors:3,options:{levels:{kind:`levels`,label:`Levels`,default:ul(Ou,[2.618,3.618,4.236])}}};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);if(t.anchors.length<3){this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),this.resetLineStyle(e);return}let o=this.anchorToPixel(t.anchors[2],n);e.font=W(11),e.textAlign=`right`,e.textBaseline=`middle`;for(let{value:n,color:r}of this.visibleLevels(t)){let[s,c]=Au(i,a,o,n);this.applyLineStyle(e,{...t.style,color:r??t.style.color}),e.globalAlpha=n===0||n===1?1:.6,e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(c.x,c.y),e.stroke(),e.fillStyle=r??t.style.color;let l=s.x<=c.x?s:c;G(e,String(n),l.x-4,l.y)}e.globalAlpha=1,this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<3)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=this.anchorToPixel(t.anchors[2],n);for(let{value:n}of this.visibleLevels(t)){let[t,s]=Au(i,a,o,n);if(this.distanceToLine(e,t,s)<=r)return!0}return!1}},Mu=[.25,.382,.5,.618,.75];function Nu(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=Math.hypot(r,i);if(a===0)return null;let o=(n.chartRect.width+n.chartRect.height)*2;return{x:e.x+r/a*o,y:e.y+i/a*o}}function Pu(e,t,n=Mu){let r=[{level:1,kind:`diagonal`,point:t}];for(let i of n)r.push({level:i,kind:`price`,point:{x:t.x,y:e.y+(t.y-e.y)*i}}),r.push({level:i,kind:`time`,point:{x:e.x+(t.x-e.x)*i,y:t.y}});return r}var Fu=class extends K{descriptor={type:`fibSpeedResistanceFan`,name:`Fib Speed Resistance Fan`,requiredAnchors:2,options:{levels:{kind:`levels`,label:`Levels`,default:ul(Mu,[.236,.786])}}};targets(e,t,n){return Pu(t,n,this.visibleLevels(e).map(e=>e.value))}render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);e.strokeStyle=t.style.color,e.lineWidth=1,e.globalAlpha=.25,e.strokeRect(Math.min(i.x,a.x),Math.min(i.y,a.y),Math.abs(a.x-i.x),Math.abs(a.y-i.y)),e.globalAlpha=1,e.font=W(11),e.textBaseline=`middle`;for(let r of this.targets(t,i,a)){let o=Nu(i,r.point,n);o&&(this.applyLineStyle(e,t.style),e.globalAlpha=r.kind===`diagonal`?1:.65,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(o.x,o.y),e.stroke(),r.kind===`price`&&(e.fillStyle=t.style.color,e.textAlign=a.x>=i.x?`left`:`right`,G(e,String(r.level),r.point.x+(a.x>=i.x?4:-4),r.point.y)))}e.globalAlpha=1,this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);for(let o of this.targets(t,i,a)){let t=Nu(i,o.point,n);if(t&&this.distanceToLine(e,i,t)<=r)return!0}return!1}},Iu=class extends K{ratioLinks=[];triangles=[];render(e,t,n,r){if(t.anchors.length<2)return;let i=t.anchors.map(e=>this.anchorToPixel(e,n));t.anchors.length>=this.descriptor.requiredAnchors&&this.renderTriangles(e,t,i),this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i[0].x,i[0].y);for(let t=1;t<i.length;t++)e.lineTo(i[t].x,i[t].y);e.stroke(),this.resetLineStyle(e),this.renderRatioLinks(e,t,i),this.renderPointLabels(e,t,i),this.renderExtras(e,t,i,n),r&&this.renderAnchorHandles(e,t,n)}renderExtras(e,t,n,r){}renderTriangles(e,t,n){e.fillStyle=t.style.fillColor??t.style.color,e.globalAlpha=t.style.fillColor?1:.12;for(let[t,r,i]of this.triangles)e.beginPath(),e.moveTo(n[t].x,n[t].y),e.lineTo(n[r].x,n[r].y),e.lineTo(n[i].x,n[i].y),e.closePath(),e.fill();e.globalAlpha=1}renderRatioLinks(e,t,n){e.font=W(11),e.textAlign=`center`,e.textBaseline=`middle`;for(let r of this.ratioLinks){if(Math.max(r.from,r.to,...r.num,...r.den)>=n.length)continue;let i=n[r.from],a=n[r.to];e.strokeStyle=t.style.color,e.lineWidth=1,e.globalAlpha=.7,e.setLineDash([4,4]),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),e.setLineDash([]),e.globalAlpha=1,e.fillStyle=t.style.color,G(e,wc(t,r.num,r.den),(i.x+a.x)/2,(i.y+a.y)/2)}}renderPointLabels(e,t,n){e.font=W(12,`bold`),e.fillStyle=t.style.color,e.textAlign=`center`;for(let t=0;t<n.length&&t<this.pointLabels.length;t++){let r=n[t-1]??n[t+1],i=n[t+1]??n[t-1],a=!r||!i?!0:n[t].y<=Math.min(r.y,i.y);e.textBaseline=a?`bottom`:`top`,G(e,this.pointLabels[t],n[t].x,n[t].y+(a?-6:6))}}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=t.anchors.map(e=>this.anchorToPixel(e,n));for(let t=0;t<i.length-1;t++)if(this.distanceToLine(e,i[t],i[t+1])<=r)return!0;return!1}},Lu=class extends Iu{descriptor={type:`xabcdPattern`,name:`XABCD Pattern`,requiredAnchors:5,fill:!0};pointLabels=[`X`,`A`,`B`,`C`,`D`];ratioLinks=[{from:0,to:2,num:[1,2],den:[0,1]},{from:1,to:3,num:[2,3],den:[1,2]},{from:2,to:4,num:[3,4],den:[2,3]},{from:0,to:4,num:[1,4],den:[0,1]}];triangles=[[0,1,2],[2,3,4]]},Ru=class extends Iu{descriptor={type:`abcdPattern`,name:`ABCD Pattern`,requiredAnchors:4,fill:!0};pointLabels=[`A`,`B`,`C`,`D`];ratioLinks=[{from:0,to:2,num:[1,2],den:[0,1]},{from:1,to:3,num:[2,3],den:[1,2]}]},zu=class extends Iu{descriptor={type:`headAndShoulders`,name:`Head and Shoulders`,requiredAnchors:7,fill:!0};pointLabels=[``,`Left Shoulder`,``,`Head`,``,`Right Shoulder`,``];triangles=[[0,1,2],[2,3,4],[4,5,6]];renderExtras(e,t,n){if(n.length<5)return;let r=n[2],i=n[4],a=n[0],o=n[n.length-1],s=i.x===r.x?0:(i.y-r.y)/(i.x-r.x),c=e=>r.y+s*(e-r.x);e.strokeStyle=t.style.color,e.lineWidth=Math.max(1,t.style.lineWidth),e.setLineDash([6,4]),e.beginPath(),e.moveTo(a.x,c(a.x)),e.lineTo(o.x,c(o.x)),e.stroke(),e.setLineDash([])}},Bu=class extends Iu{descriptor={type:`threeDrives`,name:`Three Drives Pattern`,requiredAnchors:6};pointLabels=[``,`1`,`A`,`2`,`B`,`3`];ratioLinks=[{from:1,to:3,num:[2,3],den:[1,2]},{from:3,to:5,num:[4,5],den:[3,4]}]},Vu=class extends Iu{descriptor={type:`cypherPattern`,name:`Cypher Pattern`,requiredAnchors:5,fill:!0};pointLabels=[`X`,`A`,`B`,`C`,`D`];ratioLinks=[{from:0,to:2,num:[1,2],den:[0,1]},{from:0,to:3,num:[2,3],den:[0,1]},{from:0,to:4,num:[3,4],den:[0,3]}];triangles=[[0,1,2],[2,3,4]]},Hu=class extends K{descriptor={type:`circle`,name:`Circle`,requiredAnchors:2,fill:!0};geometry(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t);return{c:n,r:Math.hypot(r.x-n.x,r.y-n.y)}}render(e,t,n,r){if(t.anchors.length<2)return;let{c:i,r:a}=this.geometry(t,n);e.beginPath(),e.arc(i.x,i.y,a,0,Math.PI*2),t.style.fillColor&&(e.fillStyle=t.style.fillColor,e.fill()),this.applyLineStyle(e,t.style),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let{c:i,r:a}=this.geometry(t,n),o=Math.hypot(e.x-i.x,e.y-i.y);return t.style.fillColor?o<=a+r:Math.abs(o-a)<=r}},Uu=`rgba(76, 141, 255, 0.12)`,Wu=`rgba(232, 80, 91, 0.12)`;function Gu(t,n){let r=n.data;if(!r||r.length===0)return null;let i=Math.round(e.D(t.anchors[0].time,n)),a=Math.round(e.D(t.anchors[1].time,n)),o=Math.max(0,Math.min(i,a)),s=Math.min(r.length-1,Math.max(i,a)),c=0;for(let e=o;e<=s;e++)c+=r[e].volume??0;return c}function Ku(e){return e>=1e9?`${(e/1e9).toFixed(2)}B`:e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(2)}K`:e.toFixed(0)}function qu(e,t){let n=Sc(e,0,1,t),r=xc(e,0,1,t),i=[vc(e.anchors[0].price,e.anchors[1].price,t),n?`${r} bars, ${n}`:`${r} bars`],a=Gu(e,t);return a!==null&&i.push(`Vol ${Ku(a)}`),i}var Ju=class extends K{descriptor={type:`dateAndPriceRange`,name:`Date and Price Range`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x),s=Math.min(i.y,a.y),c=Math.abs(a.x-i.x),l=Math.abs(a.y-i.y),u=t.anchors[1].price>=t.anchors[0].price;e.fillStyle=u?Uu:Wu,e.fillRect(o,s,c,l),this.applyLineStyle(e,t.style);let d=o+c/2,f=s+l/2;e.beginPath(),e.moveTo(d,i.y),e.lineTo(d,a.y),e.moveTo(i.x,f),e.lineTo(a.x,f),e.stroke(),this.resetLineStyle(e),Cc(e,qu(t,n),d,u?s-6:s+l+6,`center`,u),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);return e.x>=Math.min(i.x,a.x)-r&&e.x<=Math.max(i.x,a.x)+r&&e.y>=Math.min(i.y,a.y)-r&&e.y<=Math.max(i.y,a.y)+r}},Yu=400,Xu=2;function Zu(e,t,n){let r=Math.abs(t.x-e.x);if(r<Xu)return[e.x];let i=n.chartRect.x+n.chartRect.width,a=[],o=Math.min(e.x,t.x);for(let e=o;e<=i&&a.length<Yu;e+=r)a.push(e);return a}var Qu=class extends K{descriptor={type:`cyclicLines`,name:`Cyclic Lines`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),{chartRect:o}=n;this.applyLineStyle(e,t.style),e.beginPath();for(let t of Zu(i,a,n))t<o.x||(e.moveTo(t,o.y),e.lineTo(t,o.y+o.height));e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:Zu(this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n),n).some(t=>Math.abs(e.x-t)<=r)}},$u=14,ed=18,td=6,nd=20,rd=class extends K{descriptor={type:`priceLabel`,name:`Price Label`,requiredAnchors:1,text:!0};text(e,t){return e.style.text||_c(e.anchors[0].price,e.anchors[0].price,t)}box(e,t,n,r){let i=t.style.fontSize??12,a=this.text(t,r),o=e?e.measureText(a).width:a.length*i*.6;return{x:n.x+$u,y:n.y-ed-nd/2,w:o+td*2,h:nd}}render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n);e.font=`${t.style.fontSize??12}px ${ac()}`;let a=this.box(e,t,i,n);e.strokeStyle=t.style.color,e.lineWidth=1,e.setLineDash([]),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y+a.h),e.stroke(),e.fillStyle=t.style.color,e.fillRect(a.x,a.y,a.w,a.h),e.fillStyle=`#FFFFFF`,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(this.text(t,n),a.x+td,a.y+a.h/2),e.beginPath(),e.arc(i.x,i.y,3,0,Math.PI*2),e.fillStyle=t.style.color,e.fill(),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n);if(Math.hypot(e.x-i.x,e.y-i.y)<=r)return!0;let a=this.box(null,t,i,n);return e.x>=a.x-r&&e.x<=a.x+a.w+r&&e.y>=a.y-r&&e.y<=a.y+a.h+r}},id=8,ad=6,od=1.3,sd=12;function cd(e){return`${e}px ${ac()}`}function ld(e,t,n){let r=[];for(let i of t.split(`
2
- `)){let t=``;for(let a of i.split(/\s+/).filter(Boolean)){let i=t?`${t} ${a}`:a;if(e(i)<=n){t=i;continue}t&&r.push(t),t=e(a)<=n?a:ud(e,a,n)}if(r.push(t),r.length>=sd)break}return r.length>sd&&(r.length=sd),r}function ud(e,t,n){if(e(t)<=n)return t;let r=1,i=t.length-1;for(;r<i;){let a=Math.ceil((r+i)/2);e(`${t.slice(0,a)}…`)<=n?r=a:i=a-1}return`${t.slice(0,r)}…`}var dd=200,fd=new Map;function pd(e,t,n,r){let i=`${r}|${n}|${t}`,a=fd.get(i);if(a)return a;fd.size>=dd&&fd.clear();let o=ld(e,t,n);return fd.set(i,o),o}function md(e,t,n,r,i){return{x:n,y:r,width:Math.max(0,...t.map(e))+id*2,height:t.length*i*od+ad*2}}function hd(e,t,n,r,i){e.font=cd(i.fontSize);let a=t=>e.measureText(t).width,o=pd(a,t,i.maxWidth,i.fontSize),s=md(a,o,n,r,i.fontSize);return i.fill&&(e.fillStyle=i.fill,e.fillRect(s.x,s.y,s.width,s.height)),i.stroke&&(e.strokeStyle=i.stroke,e.lineWidth=1,e.strokeRect(s.x+.5,s.y+.5,s.width-1,s.height-1)),e.fillStyle=i.color,e.textAlign=`left`,e.textBaseline=`top`,o.forEach((t,a)=>e.fillText(t,n+id,r+ad+a*i.fontSize*od)),s}function gd(e,t,n=0){return e.x>=t.x-n&&e.x<=t.x+t.width+n&&e.y>=t.y-n&&e.y<=t.y+t.height+n}var _d=1e3,vd=class{boxes=new Map;set(e,t){this.boxes.size>=_d&&!this.boxes.has(e)&&this.boxes.clear(),this.boxes.set(e,t)}get(e){return this.boxes.get(e)}},yd=240,bd=13;function xd(e){return e.style.fontSize||bd}function Sd(e){return{fontSize:xd(e),color:e.style.color,fill:e.style.fillColor??`rgba(76, 141, 255, 0.1)`,stroke:e.style.color,maxWidth:yd}}function Cd(e,t,n,r){let i=xd(e),a=Math.max(...t.split(`
3
- `).map(e=>e.length));return{x:n,y:r,width:Math.min(yd,a*i*.6)+16,height:i*1.3+12}}var wd=7,Td=16,Ed=class extends K{descriptor={type:`note`,name:`Note`,requiredAnchors:1,text:!0,fill:!0,options:{showText:{kind:`boolean`,label:`Show text`,default:!0}}};boxes=new vd;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n);if(this.renderPin(e,t,i),this.option(t,`showText`)){let n=hd(e,cu(t,`Note`),i.x+wd+6,i.y-Td-wd,Sd(t));this.boxes.set(t.id,n)}r&&this.renderAnchorHandles(e,t,n)}renderPin(e,t,n){let r=n.y-Td;e.fillStyle=t.style.color,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-wd*.7,r+wd*.5),e.arc(n.x,r,wd,Math.PI*.8,Math.PI*.2),e.closePath(),e.fill(),e.fillStyle=`#ffffff`,e.beginPath(),e.arc(n.x,r,wd*.4,0,Math.PI*2),e.fill()}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n);return gd(e,{x:i.x-wd,y:i.y-Td-wd,width:wd*2,height:Td+wd},r)?!0:this.option(t,`showText`)?gd(e,this.boxes.get(t.id)??Cd(t,cu(t,`Note`),i.x+wd+6,i.y-Td-wd),r):!1}},Dd=class extends K{descriptor={type:`callout`,name:`Callout`,requiredAnchors:2,text:!0,fill:!0};boxes=new vd;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n);if(e.fillStyle=t.style.color,e.beginPath(),e.arc(i.x,i.y,3,0,Math.PI*2),e.fill(),t.anchors.length<2)return;let a=this.anchorToPixel(t.anchors[1],n),o=hd(e,cu(t,`Callout`),a.x,a.y,Sd(t));this.boxes.set(t.id,o);let s=Od(o,i);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(i.x,i.y),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=this.boxes.get(t.id)??Cd(t,cu(t,`Callout`),a.x,a.y);return gd(e,o,r)||this.distanceToLine(e,Od(o,i),i)<=r}};function Od(e,t){let n=e.x+e.width/2,r=e.y+e.height/2,i=t.x-n,a=t.y-r;return Math.abs(i)*e.height>Math.abs(a)*e.width?{x:i>0?e.x+e.width:e.x,y:r}:{x:n,y:a>0?e.y+e.height:e.y}}var kd=24,Ad=18,jd=10,Md=class extends K{descriptor={type:`flag`,name:`Flag Mark`,requiredAnchors:1};render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=i.y-kd;e.strokeStyle=t.style.color,e.lineWidth=1.5,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x,a),e.stroke(),e.fillStyle=t.style.color,e.beginPath(),e.moveTo(i.x,a),e.lineTo(i.x+Ad,a),e.lineTo(i.x+Ad-5,a+jd/2),e.lineTo(i.x+Ad,a+jd),e.lineTo(i.x,a+jd),e.closePath(),e.fill(),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n);return gd(e,{x:i.x,y:i.y-kd,width:Ad,height:kd},r)}},Nd={up:{x:0,y:-1},down:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0}};function Pd(e,t,n){let r=n*.5,i=n*.4,a=n*.17,o=(n,r)=>({x:e.x-t.x*n-t.y*r,y:e.y-t.y*n+t.x*r});return[o(0,0),o(r,i),o(r,a),o(n,a),o(n,-a),o(r,-a),o(r,-i)]}var Fd=class extends K{descriptor={type:`arrowMark`,name:`Arrow Mark`,requiredAnchors:1,text:!0,options:{direction:{kind:`choice`,label:`Direction`,default:`up`,choices:[{value:`up`,label:`Up`},{value:`down`,label:`Down`},{value:`left`,label:`Left`},{value:`right`,label:`Right`}]},size:{kind:`number`,label:`Size`,default:22,min:10,max:80,step:2}}};outline(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=Nd[this.option(e,`direction`)]??Nd.up,i=this.option(e,`size`);return{points:Pd(n,r,i),dir:r,tail:{x:n.x-r.x*i,y:n.y-r.y*i}}}render(e,t,n,r){if(t.anchors.length<1)return;let{points:i,dir:a,tail:o}=this.outline(t,n);e.fillStyle=t.style.color,e.beginPath(),i.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.closePath(),e.fill();let s=t.style.text;s&&(e.font=`${t.style.fontSize||12}px ${ac()}`,e.textAlign=a.x===0?`center`:a.x>0?`right`:`left`,e.textBaseline=a.y===0?`middle`:a.y<0?`top`:`bottom`,e.fillText(s,o.x-a.x*4,o.y-a.y*4)),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let{points:i}=this.outline(t,n),a=i.map(e=>e.x),o=i.map(e=>e.y);return gd(e,{x:Math.min(...a),y:Math.min(...o),width:Math.max(...a)-Math.min(...a),height:Math.max(...o)-Math.min(...o)},r)}},Id=[`star`,`heart`,`check`,`cross`,`circle`,`triangleUp`,`triangleDown`,`bolt`];function Ld(e,t,n,r){let i=r/2;switch(e.beginPath(),t){case`star`:for(let t=0;t<10;t++){let r=-Math.PI/2+t*Math.PI/5,a=t%2==0?i:i*.42,o=n.x+Math.cos(r)*a,s=n.y+Math.sin(r)*a;t===0?e.moveTo(o,s):e.lineTo(o,s)}return e.closePath(),!1;case`heart`:return e.moveTo(n.x,n.y+i*.85),e.bezierCurveTo(n.x-i*1.3,n.y-i*.1,n.x-i*.6,n.y-i*1.1,n.x,n.y-i*.35),e.bezierCurveTo(n.x+i*.6,n.y-i*1.1,n.x+i*1.3,n.y-i*.1,n.x,n.y+i*.85),e.closePath(),!1;case`check`:return e.moveTo(n.x-i*.8,n.y),e.lineTo(n.x-i*.2,n.y+i*.6),e.lineTo(n.x+i*.85,n.y-i*.65),!0;case`cross`:return e.moveTo(n.x-i*.7,n.y-i*.7),e.lineTo(n.x+i*.7,n.y+i*.7),e.moveTo(n.x+i*.7,n.y-i*.7),e.lineTo(n.x-i*.7,n.y+i*.7),!0;case`circle`:return e.arc(n.x,n.y,i*.8,0,Math.PI*2),!1;case`triangleUp`:return e.moveTo(n.x,n.y-i*.85),e.lineTo(n.x+i*.9,n.y+i*.7),e.lineTo(n.x-i*.9,n.y+i*.7),e.closePath(),!1;case`triangleDown`:return e.moveTo(n.x,n.y+i*.85),e.lineTo(n.x+i*.9,n.y-i*.7),e.lineTo(n.x-i*.9,n.y-i*.7),e.closePath(),!1;case`bolt`:return e.moveTo(n.x+i*.15,n.y-i),e.lineTo(n.x-i*.6,n.y+i*.1),e.lineTo(n.x-i*.05,n.y+i*.1),e.lineTo(n.x-i*.15,n.y+i),e.lineTo(n.x+i*.6,n.y-i*.1),e.lineTo(n.x+i*.05,n.y-i*.1),e.closePath(),!1}}var Rd=class extends K{descriptor={type:`icon`,name:`Icon`,requiredAnchors:1,options:{glyph:{kind:`choice`,label:`Icon`,default:`star`,choices:[{value:`star`,label:`Star`},{value:`heart`,label:`Heart`},{value:`check`,label:`Check`},{value:`cross`,label:`Cross`},{value:`circle`,label:`Circle`},{value:`triangleUp`,label:`Triangle up`},{value:`triangleDown`,label:`Triangle down`},{value:`bolt`,label:`Bolt`}]},size:{kind:`number`,label:`Size`,default:22,min:10,max:80,step:2}}};render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.option(t,`size`),o=this.option(t,`glyph`);Ld(e,Id.includes(o)?o:`star`,i,a)?(e.strokeStyle=t.style.color,e.lineWidth=Math.max(2,a/8),e.lineCap=`round`,e.lineJoin=`round`,e.stroke(),e.lineCap=`butt`,e.lineJoin=`miter`):(e.fillStyle=t.style.color,e.fill()),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.option(t,`size`)/2;return Math.abs(e.x-i.x)<=a+r&&Math.abs(e.y-i.y)<=a+r}},zd=48,Bd=10;function Vd(e,t){if(e.beginPath(),e.moveTo(t[0].x,t[0].y),t.length===2)e.lineTo(t[1].x,t[1].y);else{for(let n=1;n<t.length-1;n++){let r=(t[n].x+t[n+1].x)/2,i=(t[n].y+t[n+1].y)/2;e.quadraticCurveTo(t[n].x,t[n].y,r,i)}let n=t[t.length-1];e.lineTo(n.x,n.y)}e.stroke()}function Hd(e,t,n=!1){e.beginPath(),t.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),n&&e.closePath()}function Ud(e,t,n,r=Bd){let i=Math.atan2(n.y-t.y,n.x-t.x);e.beginPath(),e.moveTo(n.x-r*Math.cos(i-Math.PI/6),n.y-r*Math.sin(i-Math.PI/6)),e.lineTo(n.x,n.y),e.lineTo(n.x-r*Math.cos(i+Math.PI/6),n.y-r*Math.sin(i+Math.PI/6)),e.stroke()}function Wd(e,t){let n=!1;for(let r=0,i=t.length-1;r<t.length;i=r++){let a=t[r],o=t[i];a.y>e.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(n=!n)}return n}var Gd=new WeakMap;function Kd(e){let t=Gd.get(e);if(!t){t={t0:1/0,t1:-1/0,p0:1/0,p1:-1/0};for(let n of e)n.time<t.t0&&(t.t0=n.time),n.time>t.t1&&(t.t1=n.time),n.price<t.p0&&(t.p0=n.price),n.price>t.p1&&(t.p1=n.price);Gd.set(e,t)}return t}var qd=class extends K{descriptor={type:`brush`,name:`Brush`,requiredAnchors:2,creation:`freehand`};stroke(e){return{width:e.style.lineWidth,alpha:1}}render(e,t,n,r){if(t.anchors.length<2)return;let i=t.anchors.map(e=>this.anchorToPixel(e,n)),{width:a,alpha:o}=this.stroke(t);this.applyLineStyle(e,t.style),e.lineWidth=a,e.lineCap=`round`,e.lineJoin=`round`,e.globalAlpha=o,Vd(e,i),e.globalAlpha=1,e.lineCap=`butt`,e.lineJoin=`miter`,this.resetLineStyle(e),r&&this.renderBounds(e,t,n)}renderBounds(e,t,n){let r=this.screenBox(t,n),i=this.stroke(t).width/2+3;e.strokeStyle=t.style.color,e.lineWidth=1,e.setLineDash([3,3]),e.strokeRect(r.x0-i,r.y0-i,r.x1-r.x0+i*2,r.y1-r.y0+i*2),e.setLineDash([])}screenBox(t,n){let{t0:r,t1:i,p0:a,p1:o}=Kd(t.anchors),s=e.T(a,n),c=e.T(o,n);return{x0:e.O(r,n),x1:e.O(i,n),y0:Math.min(s,c),y1:Math.max(s,c)}}hitTestAnchor(){return-1}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=r+this.stroke(t).width/2,a=this.screenBox(t,n);return e.x<a.x0-i||e.x>a.x1+i||e.y<a.y0-i||e.y>a.y1+i?!1:Oc(e,t.anchors.map(e=>this.anchorToPixel(e,n)),i)}},Jd=class extends qd{descriptor={type:`highlighter`,name:`Highlighter`,requiredAnchors:2,creation:`freehand`};stroke(e){return{width:Math.max(10,e.style.lineWidth*8),alpha:.3}}},Yd=class extends K{descriptor={type:`path`,name:`Path`,requiredAnchors:2,creation:`path`,options:{arrowEnd:{kind:`boolean`,label:`Arrow at the end`,default:!0}}};render(e,t,n,r){if(t.anchors.length<2)return;let i=t.anchors.map(e=>this.anchorToPixel(e,n));this.applyLineStyle(e,t.style),e.lineJoin=`round`,Hd(e,i),e.stroke(),this.resetLineStyle(e),this.option(t,`arrowEnd`)&&Ud(e,i[i.length-2],i[i.length-1]),e.lineJoin=`miter`,r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:Oc(e,t.anchors.map(e=>this.anchorToPixel(e,n)),r)}},Xd=class extends K{descriptor={type:`polyline`,name:`Polyline`,requiredAnchors:3,creation:`path`,fill:!0};render(e,t,n,r){if(t.anchors.length<2)return;let i=t.anchors.map(e=>this.anchorToPixel(e,n)),a=i.length>=3;Hd(e,i,a),a&&(e.fillStyle=t.style.fillColor??`rgba(76, 141, 255, 0.1)`,e.fill()),this.applyLineStyle(e,t.style),e.lineJoin=`round`,e.stroke(),e.lineJoin=`miter`,this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=t.anchors.map(e=>this.anchorToPixel(e,n));return Oc(e,i,r,!0)||i.length>=3&&Wd(e,i)}};function Zd(e,t,n,r=zd){let i={x:2*t.x-(e.x+n.x)/2,y:2*t.y-(e.y+n.y)/2},a=[];for(let t=0;t<=r;t++){let o=t/r,s=1-o;a.push({x:s*s*e.x+2*s*o*i.x+o*o*n.x,y:s*s*e.y+2*s*o*i.y+o*o*n.y})}return a}function Qd(e,t,n,r=zd){let i=2*(e.x*(t.y-n.y)+t.x*(n.y-e.y)+n.x*(e.y-t.y));if(Math.abs(i)<1e-9)return[e,n];let a=e.x*e.x+e.y*e.y,o=t.x*t.x+t.y*t.y,s=n.x*n.x+n.y*n.y,c=(a*(t.y-n.y)+o*(n.y-e.y)+s*(e.y-t.y))/i,l=(a*(n.x-t.x)+o*(e.x-n.x)+s*(t.x-e.x))/i,u=Math.hypot(e.x-c,e.y-l),d=Math.atan2(e.y-l,e.x-c),f=Math.atan2(t.y-l,t.x-c),p=Math.atan2(n.y-l,n.x-c),m=(e,t)=>((t-e)%(2*Math.PI)+2*Math.PI)%(2*Math.PI),h=m(d,p),g=m(d,f)<=h?h:h-2*Math.PI,_=[];for(let e=0;e<=r;e++){let t=d+g*e/r;_.push({x:c+u*Math.cos(t),y:l+u*Math.sin(t)})}return _}var $d=class extends K{descriptor={type:`curve`,name:`Curve`,requiredAnchors:3};shape(e,t,n){return Zd(e,t,n)}points(e,t){let n=e.anchors.map(e=>this.anchorToPixel(e,t));return n.length<3?n:this.shape(n[0],n[2],n[1])}render(e,t,n,r){t.anchors.length<2||(this.applyLineStyle(e,t.style),Hd(e,this.points(t,n)),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n))}hitTest(e,t,n,r){return t.anchors.length<2?!1:Oc(e,this.points(t,n),r)}},ef=class extends $d{descriptor={type:`arc`,name:`Arc`,requiredAnchors:3};shape(e,t,n){return Qd(e,t,n)}},tf=(1+Math.sqrt(5))/2,nf=64,rf=34,af=12;function of(e,t=[]){return{levels:{kind:`levels`,label:`Levels`,default:ul(e,t)},showLevels:{kind:`boolean`,label:`Show levels`,default:!0}}}var sf=[.236,.382,.5,.618,.786,1];function cf(e){return String(Number(e.toFixed(3)))}function lf(e,t,n,r,i,a=nf){let o=[];for(let s=0;s<=a;s++){let c=r+i*s/a;o.push({x:e.x+t*Math.cos(c),y:e.y+n*Math.sin(c)})}return o}function uf(e,t){e.beginPath(),t.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.stroke()}var df=class extends K{guides(e){return e.length>=2?[[e[0],e[1]]]:[]}pixels(e,t){return e.anchors.map(e=>this.anchorToPixel(e,t))}render(e,t,n,r){if(t.anchors.length<2)return;let i=this.pixels(t,n);this.applyLineStyle(e,t.style),e.globalAlpha=.6,e.setLineDash([4,4]);for(let[t,n]of this.guides(i))uf(e,[t,n]);e.globalAlpha=1,this.applyLineStyle(e,t.style);let a=this.option(t,`showLevels`);e.font=W(11),e.textAlign=`left`,e.textBaseline=`bottom`;let o=this.shapes(i,this.visibleLevels(t),n,t);for(let n of o)e.strokeStyle=n.level.color??t.style.color,uf(e,n.points);a&&this.renderLabels(e,t,o),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}renderLabels(e,t,n){let r=[];for(let{level:i,label:a}of[...n].reverse())r.some(e=>Math.abs(e.x-a.x)<rf&&Math.abs(e.y-a.y)<af)||(r.push(a),e.fillStyle=i.color??t.style.color,G(e,cf(i.value),a.x+3,a.y-2))}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.pixels(t,n);return this.guides(i).some(([t,n])=>Dc(e,t,n)<=r)?!0:this.shapes(i,this.visibleLevels(t),n,t).some(t=>Oc(e,t.points,r))}},ff=class extends df{descriptor={type:`fibCircles`,name:`Fib Circles`,requiredAnchors:2,options:of([...sf,1.618,2.618],[3.618,4.236])};shapes(e,t){let[n,r]=e,i=Math.hypot(r.x-n.x,r.y-n.y);return t.map(e=>{let t=i*e.value;return{level:e,points:lf(n,t,t,0,Math.PI*2),label:{x:n.x+t,y:n.y}}})}},pf=class extends df{descriptor={type:`fibArcs`,name:`Fib Speed Resistance Arcs`,requiredAnchors:2,options:{...of(sf),fullCircles:{kind:`boolean`,label:`Full circles`,default:!1}}};shapes(e,t,n,r){let[i,a]=e,o=Math.hypot(a.x-i.x,a.y-i.y),s=Math.atan2(a.y-i.y,a.x-i.x),c=this.option(r,`fullCircles`);return t.map(e=>{let t=o*e.value;return{level:e,points:c?lf(i,t,t,0,Math.PI*2):lf(i,t,t,s-Math.PI/2,Math.PI),label:{x:i.x+t*Math.cos(s),y:i.y+t*Math.sin(s)}}})}},mf=class extends df{descriptor={type:`fibWedge`,name:`Fib Wedge`,requiredAnchors:3,options:of(sf)};guides(e){return e.slice(1).map(t=>[e[0],t])}shapes(e,t){if(e.length<3)return[];let[n,r,i]=e,a=Math.hypot(r.x-n.x,r.y-n.y),o=Math.atan2(r.y-n.y,r.x-n.x),s=Math.atan2(i.y-n.y,i.x-n.x)-o;return s>Math.PI&&(s-=2*Math.PI),s<-Math.PI&&(s+=2*Math.PI),t.map(e=>{let t=a*e.value;return{level:e,points:lf(n,t,t,o,s,32),label:{x:n.x+t*Math.cos(o),y:n.y+t*Math.sin(o)}}})}},hf=class extends df{descriptor={type:`pitchfan`,name:`Pitchfan`,requiredAnchors:3,options:of([0,.25,.382,.5,.618,.75,1])};guides(e){return e.length>=3?[[e[1],e[2]]]:[[e[0],e[1]]]}shapes(e,t,n){if(e.length<3)return[];let[r,i,a]=e,o=Math.hypot(n.chartRect.width,n.chartRect.height)*2;return t.map(e=>{let t={x:i.x+(a.x-i.x)*e.value,y:i.y+(a.y-i.y)*e.value},n=Math.hypot(t.x-r.x,t.y-r.y)||1;return{level:e,points:[r,{x:r.x+(t.x-r.x)/n*o,y:r.y+(t.y-r.y)/n*o}],label:t}})}},gf=class extends K{descriptor={type:`fibSpiral`,name:`Fib Spiral`,requiredAnchors:2,options:{clockwise:{kind:`boolean`,label:`Clockwise`,default:!1}}};points(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i=Math.hypot(r.x-n.x,r.y-n.y);if(i===0)return[];let a=Math.atan2(r.y-n.y,r.x-n.x),o=this.option(e,`clockwise`)?1:-1,s=Math.hypot(t.chartRect.width,t.chartRect.height)*1.5,c=Math.PI/2,l=Math.log(s/i)/Math.log(tf),u=Math.log(i/2)/Math.log(tf),d=-Math.max(0,u)*c,f=Math.max(1,l)*c,p=[],m=Math.min(720,Math.ceil((f-d)/c*24));for(let e=0;e<=m;e++){let t=d+(f-d)*e/m,r=i*tf**+(t/c);p.push({x:n.x+r*Math.cos(a+o*t),y:n.y+r*Math.sin(a+o*t)})}return p}render(e,t,n,r){t.anchors.length<2||(this.applyLineStyle(e,t.style),uf(e,this.points(t,n)),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n))}hitTest(e,t,n,r){return t.anchors.length<2?!1:Oc(e,this.points(t,n),r)}},_f=class extends K{descriptor={type:`gannSquare`,name:`Gann Square`,requiredAnchors:2,options:{...of([.25,.382,.5,.618,.75]),arcs:{kind:`boolean`,label:`Arcs`,default:!0}}};lines(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i=r.x-n.x,a=r.y-n.y,o=[[n,{x:r.x,y:n.y}],[{x:r.x,y:n.y},r],[r,{x:n.x,y:r.y}],[{x:n.x,y:r.y},n],[n,r],[{x:r.x,y:n.y},{x:n.x,y:r.y}]],s=this.visibleLevels(e);for(let{value:e}of s)o.push([{x:n.x+i*e,y:n.y},{x:n.x+i*e,y:r.y}]),o.push([{x:n.x,y:n.y+a*e},{x:r.x,y:n.y+a*e}]);return{grid:o,arcs:this.option(e,`arcs`)?[...s.map(e=>e.value),1].map(e=>{let t=Math.atan2(0,Math.sign(i)||1),r=(Math.sign(i)||1)*(Math.sign(a)||1)*(Math.PI/2);return lf(n,Math.abs(i)*e,Math.abs(a)*e,t,r,24)}):[]}}render(e,t,n,r){if(t.anchors.length<2)return;let{grid:i,arcs:a}=this.lines(t,n);this.applyLineStyle(e,t.style),i.forEach(([t,n],r)=>{e.globalAlpha=r<6?1:.55,uf(e,[t,n])}),e.globalAlpha=.8;for(let t of a)uf(e,t);e.globalAlpha=1,this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let{grid:i}=this.lines(t,n);return i.slice(0,6).some(([t,n])=>Dc(e,t,n)<=r)}},vf=400,yf=32,bf=3,xf=class extends K{descriptor={type:`timeCycles`,name:`Time Cycles`,requiredAnchors:2,fill:!0};visibleCycles(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t).x-n.x,i=Math.abs(r)/2;if(i<1)return{y:n.y,r:i,centres:[]};let a=t.chartRect.x,o=a+t.chartRect.width,s=Math.max(0,Math.floor(((r>0?a:o)-n.x)/r)-1),c=[];for(let e=s;c.length<vf;e++){let t=n.x+r*(e+.5);if(t-i>o||t+i<a){if(c.length>0||(r>0?t-i>o:t+i<a))break;continue}c.push(t)}return{y:n.y,r:i,centres:c}}cycles(e,t){let{y:n,r,centres:i}=this.visibleCycles(e,t);return i.map(e=>{let t=[];for(let i=0;i<=yf;i++){let a=Math.PI+Math.PI*i/yf;t.push({x:e+r*Math.cos(a),y:n+r*Math.sin(a)})}return t})}render(e,t,n,r){if(t.anchors.length<2)return;let i=this.cycles(t,n);e.fillStyle=t.style.fillColor??`rgba(76, 141, 255, 0.1)`,this.applyLineStyle(e,t.style);for(let t of i)e.beginPath(),t.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.fill(),e.stroke();this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let{y:i,r:a,centres:o}=this.visibleCycles(t,n);return e.y>i+r?!1:o.some(t=>Math.abs(Math.hypot(e.x-t,e.y-i)-a)<=r)}},Sf=class extends K{descriptor={type:`sineLine`,name:`Sine Line`,requiredAnchors:2};points(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i=r.x-n.x;if(Math.abs(i)<1)return[n,r];let a=(n.y+r.y)/2,o=(n.y-r.y)/2,{x:s,width:c}=t.chartRect,l=[];for(let e=s;e<=s+c;e+=bf)l.push({x:e,y:a+o*Math.cos(Math.PI*(e-n.x)/i)});return l}render(e,t,n,r){t.anchors.length<2||(this.applyLineStyle(e,t.style),e.beginPath(),this.points(t,n).forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n))}hitTest(e,t,n,r){return t.anchors.length<2?!1:Oc(e,this.points(t,n),r)}},Cf=`#26a69a`,wf=`#ef5350`,Tf=500;function Ef(t,n,r){let i=r.price>=n.price,a=t.length>0?Math.max(0,Math.floor(e.k(n.time,t))+1):0;for(let e=a;e<t.length;e++){let a=t[e];if(!(a.time<=n.time)){if(a.time>r.time)return`missed`;if(i?a.high>=r.price:a.low<=r.price)return`reached`}}return`pending`}var Df=class extends K{descriptor={type:`forecast`,name:`Forecast`,requiredAnchors:2};bars=()=>[];setDataGetter(e){this.bars=e}render(e,t,n,r){if(t.anchors.length<2)return;let[i,a]=t.anchors,o=this.anchorToPixel(i,n),s=this.anchorToPixel(a,n),c=Ef(this.bars(),i,a),l=c===`reached`?Cf:c===`missed`?wf:t.style.color;this.applyLineStyle(e,{...t.style,color:l}),e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(s.x,s.y),e.stroke(),Ud(e,o,s),this.resetLineStyle(e),e.strokeStyle=l,e.beginPath(),e.arc(s.x,s.y,5,0,Math.PI*2),e.stroke();let u=Sc(t,0,1,n);Cc(e,[vc(i.price,a.price,n),`${_c(a.price,i.price,n)} · ${xc(t,0,1,n)} bars${u?`, ${u}`:``}`,c===`reached`?`Target reached`:c===`missed`?`Target missed`:`Pending`],s.x,s.y+(s.y<o.y?-10:10),`center`,s.y<o.y),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:Dc(e,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n))<=r}},Of=class extends K{descriptor={type:`projection`,name:`Projection`,requiredAnchors:3,fill:!0};target(t,n){let[r,i,a]=t.anchors,o=e.D(i.time,n)-e.D(r.time,n);return{x:e.b(e.D(a.time,n)+o,n),y:e.T(a.price+(i.price-r.price),n)}}render(e,t,n,r){if(t.anchors.length<2)return;let i=t.anchors.map(e=>this.anchorToPixel(e,n));if(this.applyLineStyle(e,t.style),e.setLineDash([5,4]),e.beginPath(),e.moveTo(i[0].x,i[0].y),e.lineTo(i[1].x,i[1].y),e.stroke(),t.anchors.length>=3){let r=i[2],a=this.target(t,n);e.fillStyle=t.style.fillColor??`rgba(76, 141, 255, 0.1)`,e.fillRect(Math.min(r.x,a.x),Math.min(r.y,a.y),Math.abs(a.x-r.x),Math.abs(a.y-r.y)),this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(a.x,a.y),e.stroke(),Ud(e,r,a);let[o,s,c]=t.anchors,l=c.price+(s.price-o.price);Cc(e,[_c(l,c.price,n),vc(c.price,l,n)],a.x,a.y+(a.y<r.y?-8:8),`center`,a.y<r.y)}this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=t.anchors.map(e=>this.anchorToPixel(e,n));return Dc(e,i[0],i[1])<=r?!0:i.length>=3&&Dc(e,i[2],this.target(t,n))<=r}},kf=class extends K{descriptor={type:`barsPattern`,name:`Bars Pattern`,requiredAnchors:3,options:{mode:{kind:`choice`,label:`Show as`,default:`bars`,choices:[{value:`bars`,label:`Bars`},{value:`line`,label:`Line`},{value:`highLow`,label:`High-low`}]},mirrored:{kind:`boolean`,label:`Mirrored`,default:!1},flipped:{kind:`boolean`,label:`Flipped`,default:!1}}};bars=()=>[];setDataGetter(e){this.bars=e}copied(t){let n=this.bars();if(n.length===0)return[];let[r,i,a]=t.anchors,o=Math.max(0,Math.round(e.k(Math.min(r.time,i.time),n))),s=Math.min(n.length-1,Math.round(e.k(Math.max(r.time,i.time),n)));if(s<o)return[];let c=n.slice(o,Math.min(s+1,o+Tf));if(c.length===0)return[];let l=this.option(t,`flipped`),u=this.option(t,`mirrored`)?[...c].reverse():c,d=u[0].open,f=e=>a.price+(l?d-e:e-d);return u.map(e=>{let t=f(e.high),n=f(e.low);return{...e,open:f(e.open),close:f(e.close),high:Math.max(t,n),low:Math.min(t,n)}})}box(t,n,r){if(r.length===0)return null;let i=e.D(t.anchors[2].time,n),a=e.b(i,n)-n.barWidth/2,o=e.b(i+r.length-1,n)+n.barWidth/2,s=-1/0,c=1/0;for(let e of r)e.high>s&&(s=e.high),e.low<c&&(c=e.low);let l=e.T(s,n),u=e.T(c,n);return{x:a,y:Math.min(l,u),width:o-a,height:Math.abs(u-l)}}render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.setLineDash([4,4]),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),this.resetLineStyle(e),t.anchors.length>=3&&this.renderCopy(e,t,n),r&&this.renderAnchorHandles(e,t,n)}renderCopy(t,n,r){let i=this.copied(n);if(i.length===0)return;let a=e.D(n.anchors[2].time,r),o=this.option(n,`mode`);if(t.strokeStyle=n.style.color,t.fillStyle=n.style.color,t.lineWidth=1,t.globalAlpha=.7,o===`line`)t.beginPath(),i.forEach((n,i)=>{let o=e.b(a+i,r),s=e.T(n.close,r);i===0?t.moveTo(o,s):t.lineTo(o,s)}),t.stroke();else{let n=Math.max(1,r.barWidth/2);i.forEach((i,s)=>{let c=e.b(a+s,r);if(t.beginPath(),t.moveTo(c,e.T(i.high,r)),t.lineTo(c,e.T(i.low,r)),t.stroke(),o===`highLow`)return;let l=e.T(Math.max(i.open,i.close),r),u=Math.max(1,e.T(Math.min(i.open,i.close),r)-l);i.close>=i.open?t.strokeRect(c-n,l,n*2,u):t.fillRect(c-n,l,n*2,u)})}t.globalAlpha=1}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;if(Dc(e,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n))<=r)return!0;let i=t.anchors.length>=3?this.box(t,n,this.copied(t)):null;return i!==null&&gd(e,i,r)}};function Af(e){e.register(new Ol),e.register(new kl),e.register(new Al),e.register(new jl),e.register(new Ml),e.register(new Nl),e.register(new Pl),e.register(new Fl),e.register(new Bl),e.register(new Hl),e.register(new Ul),e.register(new Wl),e.register(new Gl),e.register(new Kl),e.register(new $l),e.register(new au),e.register(new ou),e.register(new su),e.register(new lu),e.register(new uu),e.register(new fu),e.register(new mu),e.register(new hu),e.register(new gu),e.register(new vu),e.register(new wu),e.register(new Tu),e.register(new _l),e.register(new Du),e.register(new ju),e.register(new Fu),e.register(new ql),e.register(new Jl),e.register(new Lu),e.register(new Ru),e.register(new zu),e.register(new Hu),e.register(new Ju),e.register(new Qu),e.register(new rd),e.register(new Ed),e.register(new Dd),e.register(new Md),e.register(new Fd),e.register(new Rd),e.register(new qd),e.register(new Jd),e.register(new Yd),e.register(new Xd),e.register(new $d),e.register(new ef),e.register(new ff),e.register(new gf),e.register(new pf),e.register(new mf),e.register(new hf),e.register(new _f),e.register(new eu),e.register(new tu),e.register(new nu),e.register(new ru),e.register(new iu),e.register(new Bu),e.register(new Vu),e.register(new xf),e.register(new Sf),e.register(new Df),e.register(new Of),e.register(new kf)}function jf(e,t){let{chartRect:n}=t;return e>=n.y&&e<=n.y+n.height}var Mf=2;function Nf(e,t){return e.type===t.type?e.type===`cancelOrder`?e.orderId===t.orderId:e.type===`removeStop`?e.positionId===t.positionId&&e.which===t.which:e.positionId===t.positionId:!1}function Pf(e,t,n=Mf){for(let r=e.length-1;r>=0;r--){let i=e[r];if(t.x>=i.x-n&&t.x<=i.x+i.size+n&&t.y>=i.y-n&&t.y<=i.y+i.size+n)return i}return null}function Ff(e,t,n,r,i){e.fillStyle=i,e.fillRect(t,n,r,r);let a=r*.3;e.strokeStyle=`#FFFFFF`,e.lineWidth=1.5,e.beginPath(),e.moveTo(t+a,n+a),e.lineTo(t+r-a,n+r-a),e.moveTo(t+r-a,n+a),e.lineTo(t+a,n+r-a),e.stroke()}function If(e,t,n,r,i){e.fillStyle=i,e.fillRect(t,n,r,r);let a=n+r*.25,o=n+r*.75,s=t+r*.35,c=t+r*.65,l=r*.14;e.strokeStyle=`#FFFFFF`,e.lineWidth=1.5,e.beginPath(),e.moveTo(s,o),e.lineTo(s,a),e.moveTo(s-l,a+l),e.lineTo(s,a),e.lineTo(s+l,a+l),e.moveTo(c,a),e.lineTo(c,o),e.moveTo(c-l,o-l),e.lineTo(c,o),e.lineTo(c+l,o-l),e.stroke()}var Lf=16,Rf=class{render(t,n,r,i,a,o,s=[]){let c=a.orderColors?.buy??`#1fa874`,l=a.orderColors?.sell??`#e8505b`,{chartRect:u}=r,d=a.lineButtons?.cancel!==!1;for(let a of n){let n=o?.orderId===a.id&&o.sourceType===`order`,f=e.T(n?o.currentPrice:a.price,r);if(f<u.y||f>u.y+u.height)continue;let p=a.side===`buy`?c:l;t.setLineDash([6,4]),t.strokeStyle=p,t.lineWidth=1,t.beginPath(),t.moveTo(u.x,Math.round(f)+.5),t.lineTo(u.x+u.width,Math.round(f)+.5),t.stroke(),t.setLineDash([]);let m=`${a.label??a.type.toUpperCase()} ${a.quantity}`;t.font=`bold 10px ${i.font.family}`;let h=t.measureText(m).width+8;t.fillStyle=p,w(t,u.x+4,f-8,h,16,i),t.fillStyle=`#FFFFFF`,t.textBaseline=`middle`,t.textAlign=`left`,t.fillText(m,u.x+8,f);let g=u.x+4+h+6;if(t.fillStyle=p,t.beginPath(),a.side===`buy`?(t.moveTo(g,f+4),t.lineTo(g+5,f-2),t.lineTo(g+10,f+4)):(t.moveTo(g,f-4),t.lineTo(g+5,f+2),t.lineTo(g+10,f-4)),t.fill(),d&&!n){let e=g+16;Ff(t,e,f-Lf/2,Lf,p),s.push({x:e,y:f-Lf/2,size:Lf,action:{type:`cancelOrder`,orderId:a.id}})}if(n){let n=e.T(o.startPrice,r);t.setLineDash([2,4]),t.strokeStyle=p,t.globalAlpha=.3,t.beginPath(),t.moveTo(u.x,Math.round(n)+.5),t.lineTo(u.x+u.width,Math.round(n)+.5),t.stroke(),t.globalAlpha=1,t.setLineDash([])}}}renderAxisBadges(n,r,i,a,o,s){let c=o.orderColors?.buy??`#1fa874`,l=o.orderColors?.sell??`#e8505b`,{chartRect:u}=i,d=u.x+u.width+1;for(let f of r){let r=s?.orderId===f.id&&s.sourceType===`order`?s.currentPrice:f.price,p=e.T(r,i);if(p<u.y||p>u.y+u.height)continue;let m=f.side===`buy`?c:l,h=(0,t.priceTagText)(r,i,o.pricePrecision);n.font=`11px ${a.font.family}`;let g=n.measureText(h).width+10;n.fillStyle=m,w(n,d,p-9,Math.min(g,(i.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2),18,a),n.fillStyle=`#FFFFFF`,n.textAlign=`left`,n.textBaseline=`middle`,n.fillText(h,d+5,p)}}hitTest(t,n,r,i){for(let a of n){if(a.draggable===!1)continue;let n=e.T(a.price,r);if(Math.abs(t-n)<=i)return a}return null}};function zf(e,t,n,r,i){let a=Math.min(Math.max(e.closedQuantity??0,0),e.quantity),o=e.quantity-a,s=e.side===`buy`?1:-1,c=(t-e.entryPrice)*o*s,l=e.entryPrice===0?0:(t-e.entryPrice)/e.entryPrice*100*s;return{side:e.side,quantity:e.quantity,closedQuantity:a,openQuantity:o,entryPrice:e.entryPrice,currentPrice:t,pnl:c,pnlPct:l,precision:n,formatPrice:r,locale:i}}var Bf=/\{(side|qty|closedQty|openQty|entry|price|pnl|pnlPct|pnlSign)\}/g;function Vf(e,n){return e.replace(Bf,(e,r)=>{switch(r){case`side`:return n.side.toUpperCase();case`qty`:return String(n.quantity);case`closedQty`:return String(n.closedQuantity);case`openQty`:return String(n.openQuantity);case`entry`:return n.formatPrice?.(n.entryPrice)??(0,t.formatPrice)(n.entryPrice,n.precision,n.locale);case`price`:return n.formatPrice?.(n.currentPrice)??(0,t.formatPrice)(n.currentPrice,n.precision,n.locale);case`pnl`:return(0,t.formatPrice)(n.pnl,n.precision,n.locale);case`pnlPct`:return`${n.pnlPct.toFixed(2)}%`;case`pnlSign`:return n.pnl>=0?`+`:``;default:return``}})}function Hf(e,t){return typeof e==`function`?e(t):Vf(e??`{side} {qty} | P&L: {pnlSign}{pnl}`,t)}function Uf(e,t,n){if(!t||t.length===0)return n;let r=[...t].sort((e,t)=>e.pnl-t.pnl),i;for(let t of r)if(e>=t.pnl)i=t.color;else break;return i??n}var Wf=20,Gf=16;function Kf(e,t,n){let{chartRect:r}=n;return e-t/2>=r.y&&e+t/2<=r.y+r.height}var qf=class{render(n,r,i,a,o,s,c=[]){let{chartRect:l}=a,u=s.positionColors?.profit??`#1fa874`,d=s.positionColors?.loss??`#e8505b`,f=s.positionColors?.entry??`#4c8dff`,p=s.pricePrecision??2,m=s.lineButtons??{};for(let h of r){let r=e.T(h.entryPrice,a);if(n.strokeStyle=f,n.lineWidth=1.5,n.setLineDash([]),n.beginPath(),n.moveTo(l.x,Math.round(r)+.5),n.lineTo(l.x+l.width,Math.round(r)+.5),n.stroke(),i!==null){let g=e.T(i,a),_=zf(h,i,p,e=>(0,t.priceTagText)(e,a,s.pricePrecision),a.numberLocale),v=_.pnl,y=v>=0?u:d,b=Uf(v,s.pnlThresholds,y);n.fillStyle=b,n.globalAlpha=.08;let x=Math.min(r,g),S=Math.abs(g-r);if(n.fillRect(l.x,x,l.width,S),n.globalAlpha=1,_.closedQuantity>0&&h.quantity>0){let e=_.closedQuantity/h.quantity;n.fillStyle=f,n.globalAlpha=.25,n.fillRect(l.x,x,Math.max(2,l.width*e*.04)+2,S),n.globalAlpha=1}let C=Hf(s.positionLabel,_);n.font=`bold 11px ${o.font.family}`;let T=n.measureText(C).width+12,E=l.x+8;n.fillStyle=b,n.globalAlpha=.9,w(n,E,r-10,T,20,o),n.globalAlpha=1,n.fillStyle=`#FFFFFF`,n.textBaseline=`middle`,n.textAlign=`left`,n.fillText(C,E+6,r),Kf(r,Wf,a)&&this.renderButtons(n,h.id,E+T+2,r,b,m,c)}else Kf(r,Wf,a)&&this.renderButtons(n,h.id,l.x+8,r,f,m,c);let g=h.stopLoss===void 0?NaN:e.T(h.stopLoss,a);jf(g,a)&&(n.setLineDash([4,4]),n.strokeStyle=d,n.lineWidth=1,n.beginPath(),n.moveTo(l.x,Math.round(g)+.5),n.lineTo(l.x+l.width,Math.round(g)+.5),n.stroke(),n.font=`bold 10px ${o.font.family}`,n.fillStyle=d,w(n,l.x+4,g-8,24,16,o),n.fillStyle=`#FFFFFF`,n.textAlign=`left`,n.textBaseline=`middle`,n.fillText(`SL`,l.x+8,g),m.removeStops!==!1&&Kf(g,Gf,a)&&this.renderStopButton(n,h.id,`stopLoss`,l.x+30,g,d,c));let _=h.takeProfit===void 0?NaN:e.T(h.takeProfit,a);jf(_,a)&&(n.setLineDash([4,4]),n.strokeStyle=u,n.lineWidth=1,n.beginPath(),n.moveTo(l.x,Math.round(_)+.5),n.lineTo(l.x+l.width,Math.round(_)+.5),n.stroke(),n.font=`bold 10px ${o.font.family}`,n.fillStyle=u,w(n,l.x+4,_-8,24,16,o),n.fillStyle=`#FFFFFF`,n.textAlign=`left`,n.textBaseline=`middle`,n.fillText(`TP`,l.x+8,_),m.removeStops!==!1&&Kf(_,Gf,a)&&this.renderStopButton(n,h.id,`takeProfit`,l.x+30,_,u,c)),n.setLineDash([])}}renderButtons(e,t,n,r,i,a,o){let s=r-Wf/2,c=n;e.globalAlpha=.9,a.reverse!==!1&&(If(e,c,s,Wf,i),o.push({x:c,y:s,size:Wf,action:{type:`reversePosition`,positionId:t}}),c+=Wf+2),a.close!==!1&&(Ff(e,c,s,Wf,i),o.push({x:c,y:s,size:Wf,action:{type:`closePosition`,positionId:t}})),e.globalAlpha=1}renderStopButton(e,t,n,r,i,a,o){let s=i-Gf/2;Ff(e,r,s,Gf,a),o.push({x:r,y:s,size:Gf,action:{type:`removeStop`,positionId:t,which:n}})}renderAxisBadges(n,r,i,a,o){let{chartRect:s}=i,c=o.positionColors?.entry??`#4c8dff`,l=s.x+s.width+1;for(let s of r){let r=e.T(s.entryPrice,i);jf(r,i)&&(n.fillStyle=c,w(n,l,r-9,(i.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,18,a),n.fillStyle=`#FFFFFF`,n.font=`11px ${a.font.family}`,n.textAlign=`left`,n.textBaseline=`middle`,n.fillText((0,t.priceTagText)(s.entryPrice,i,o.pricePrecision),l+5,r))}}},Jf=class{render(t,n,r,i){if(!i.depthOverlay?.enabled)return;let{chartRect:a}=r,o=i.depthOverlay.bidColor??`rgba(31, 168, 116,0.15)`,s=i.depthOverlay.askColor??`rgba(232, 80, 91,0.15)`,c=i.depthOverlay.maxWidth??100,l=0,u=[],d=0;for(let e of n.bids)d+=e.volume,u.push({price:e.price,cumVol:d}),d>l&&(l=d);let f=[];d=0;for(let e of n.asks)d+=e.volume,f.push({price:e.price,cumVol:d}),d>l&&(l=d);if(l===0)return;let p=Math.max(1,n.bids.length>1?Math.abs(e.T(n.bids[0].price,r)-e.T(n.bids[1].price,r)):4),m=a.x+a.width;t.fillStyle=o;for(let{price:n,cumVol:i}of u){let o=e.T(n,r);if(o<a.y||o>a.y+a.height)continue;let s=i/l*c;t.fillRect(m-s,o-p/2,s,p)}t.fillStyle=s;for(let{price:n,cumVol:i}of f){let o=e.T(n,r);if(o<a.y||o>a.y+a.height)continue;let s=i/l*c;t.fillRect(m-s,o-p/2,s,p)}}},Yf=class{dragState=null;startY=0;dragging=!1;constructor(e=3){this.dragThreshold=e}onPointerDown(t,n,r,i,a){for(let r of n){if(r.draggable===!1)continue;let n=e.T(r.price,i);if(jf(n,i)&&Math.abs(t.y-n)<=a)return this.dragState={orderId:r.id,sourceType:`order`,startPrice:r.price,currentPrice:r.price},this.startY=t.y,this.dragging=!1,!0}for(let n of r){if(n.stopLoss!==void 0){let r=e.T(n.stopLoss,i);if(jf(r,i)&&Math.abs(t.y-r)<=a)return this.dragState={orderId:n.id,sourceType:`stopLoss`,startPrice:n.stopLoss,currentPrice:n.stopLoss},this.startY=t.y,this.dragging=!1,!0}if(n.takeProfit!==void 0){let r=e.T(n.takeProfit,i);if(jf(r,i)&&Math.abs(t.y-r)<=a)return this.dragState={orderId:n.id,sourceType:`takeProfit`,startPrice:n.takeProfit,currentPrice:n.takeProfit},this.startY=t.y,this.dragging=!1,!0}}return!1}onPointerMove(t,n){if(!this.dragState)return!1;if(!this.dragging){if(Math.abs(t.y-this.startY)<this.dragThreshold)return!0;this.dragging=!0}return this.dragState.currentPrice=e.M(t.y,n),!0}onPointerUp(){if(!this.dragState)return null;let e=this.dragState;return this.dragState=null,this.dragging?(this.dragging=!1,{sourceType:e.sourceType,id:e.orderId,newPrice:e.currentPrice,previousPrice:e.startPrice}):null}cancel(){return this.dragState?(this.dragState=null,this.dragging=!1,!0):!1}getDragState(){return this.dragState}isActive(){return this.dragState!==null}},Xf=class{menuElement=null;removeHandler=null;onItemSelect=null;show(e,t,n,r,i){if(this.hide(),!r.contextMenu?.enabled)return;let a=r.pricePrecision??2,o=i?.(t)??t.toFixed(a),s=document.createElement(`div`);s.style.cssText=`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./gpuContexts-BN9YuYEa.cjs`);let t=require(`@tradecanvas/commons`);var n=class{canvas;ctx;dpr=1;constructor(e,t){this.canvas=document.createElement(`canvas`),this.canvas.style.position=`absolute`,this.canvas.style.top=`0`,this.canvas.style.left=`0`,this.canvas.style.zIndex=String(t),this.canvas.style.pointerEvents=`none`,this.ctx=this.canvas.getContext(`2d`),e.appendChild(this.canvas)}resize(e,t){this.dpr=t;let n=Math.round(e.width*t),r=Math.round(e.height*t);(this.canvas.width!==n||this.canvas.height!==r)&&(this.canvas.width=n,this.canvas.height=r),this.canvas.style.width=`${e.width}px`,this.canvas.style.height=`${e.height}px`,this.ctx.setTransform(t,0,0,t,0,0)}clear(){this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.setTransform(this.dpr,0,0,this.dpr,0,0)}getSize(){return{width:this.canvas.width/this.dpr,height:this.canvas.height/this.dpr}}destroy(){this.canvas.width=0,this.canvas.height=0,this.canvas.remove()}},r=class{scene=null;top=null;back=null;gpuCanvas=null;size=null;dpr=1;constructor(e){this.container=e}createLayers(){this.destroy(),this.scene=new n(this.container,0),this.top=new n(this.container,1)}getLayer(e){return(e===t.LayerType.Hover?this.top:this.scene)??void 0}backLayer(){return this.gpuCanvas?(this.back||(this.back=new n(this.container,0),this.container.insertBefore(this.back.canvas,this.gpuCanvas),this.size&&this.back.resize(this.size,this.dpr)),this.back):null}getDpr(){return this.dpr}dropBackLayer(){this.back?.destroy(),this.back=null}attachGpu(e){this.detachGpu(),e.style.position=`absolute`,e.style.top=`0`,e.style.left=`0`,e.style.zIndex=`0`,e.style.pointerEvents=`none`,this.container.insertBefore(e,this.scene?.canvas??null),this.gpuCanvas=e,this.size&&this.sizeGpu(this.size,this.dpr)}detachGpu(){this.dropBackLayer(),this.gpuCanvas&&(this.gpuCanvas.width=0,this.gpuCanvas.height=0,this.gpuCanvas.remove()),this.gpuCanvas=null}resize(e,t){this.size=e,this.dpr=t,this.scene?.resize(e,t),this.top?.resize(e,t),this.back?.resize(e,t),this.sizeGpu(e,t)}destroy(){this.detachGpu(),this.scene?.destroy(),this.top?.destroy(),this.scene=null,this.top=null}sizeGpu(e,t){let n=this.gpuCanvas;if(!n)return;let r=Math.round(e.width*t),i=Math.round(e.height*t);(n.width!==r||n.height!==i)&&(n.width=r,n.height=i),n.style.width=`${e.width}px`,n.style.height=`${e.height}px`}},i=class{animFrameId=0;running=!1;paused=!1;dirtyLayers=new Set;swapLayers=new Set;callback=null;setCallback(e){this.callback=e}markDirty(e){this.dirtyLayers.add(e),this.running&&!this.paused&&!this.animFrameId&&this.scheduleFrame()}markAllDirty(){this.dirtyLayers.add(t.LayerType.Background),this.dirtyLayers.add(t.LayerType.Main),this.dirtyLayers.add(t.LayerType.Overlay),this.dirtyLayers.add(t.LayerType.UI),this.dirtyLayers.add(t.LayerType.Hover),this.running&&!this.paused&&!this.animFrameId&&this.scheduleFrame()}start(){this.running=!0,this.markAllDirty()}pause(){this.paused=!0,this.animFrameId&&=(cancelAnimationFrame(this.animFrameId),0)}resume(){this.paused&&(this.paused=!1,this.running&&this.dirtyLayers.size>0&&!this.animFrameId&&this.scheduleFrame())}isPaused(){return this.paused}stop(){this.running=!1,this.animFrameId&&=(cancelAnimationFrame(this.animFrameId),0)}scheduleFrame(){this.animFrameId=requestAnimationFrame(()=>{if(this.animFrameId=0,!(!this.running||!this.callback)&&this.dirtyLayers.size>0){let e=this.dirtyLayers;this.dirtyLayers=this.swapLayers,this.callback(e),e.clear(),this.swapLayers=e}})}},a=2;function o(e=2){let t=typeof window<`u`&&window.devicePixelRatio||1;return e>0?Math.min(t,e):t}var s=class{observer=null;callback=null;currentDpr=1;resizeScheduled=!1;cachedSize;stopWatchingRatio=null;constructor(e,t=2){this.container=e,this.maxPixelRatio=t,this.currentDpr=o(t),this.cachedSize={width:e.clientWidth,height:e.clientHeight}}getDpr(){return this.currentDpr}getMaxPixelRatio(){return this.maxPixelRatio}setMaxPixelRatio(e){this.maxPixelRatio=e,this.update(!0)}getContainerSize(){return this.cachedSize}readContainerSize(){let e=this.container.clientWidth,t=this.container.clientHeight;return(e!==this.cachedSize.width||t!==this.cachedSize.height)&&(this.cachedSize={width:e,height:t}),this.cachedSize}onResize(e){this.callback=e,this.observer=new ResizeObserver(()=>{this.resizeScheduled||(this.resizeScheduled=!0,requestAnimationFrame(()=>{this.resizeScheduled=!1,this.update(!1)}))}),this.observer.observe(this.container),this.watchRatio()}update(e){let t=o(this.maxPixelRatio),n=this.container.clientWidth,r=this.container.clientHeight,i=t!==this.currentDpr||n!==this.cachedSize.width||r!==this.cachedSize.height;this.currentDpr=t,this.cachedSize={width:n,height:r},(i||e)&&this.callback?.(this.cachedSize,t)}watchRatio(){if(this.stopWatchingRatio?.(),this.stopWatchingRatio=null,typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(resolution: ${window.devicePixelRatio||1}dppx)`);if(!e||typeof e.addEventListener!=`function`)return;let t=()=>{this.update(!1),this.watchRatio()};e.addEventListener(`change`,t),this.stopWatchingRatio=()=>e.removeEventListener(`change`,t)}destroy(){this.observer?.disconnect(),this.observer=null,this.stopWatchingRatio?.(),this.stopWatchingRatio=null,this.callback=null}};function c(e,n,r,i){let a=n.scaleMode??(n.logScale?`logarithmic`:`regular`);return(a===`percentage`||a===`indexedTo100`)&&n.scaleBaseline?(0,t.formatPriceScaleLabel)(e,a,n.scaleBaseline,r,i):n.formatPrice?n.formatPrice(e):(0,t.formatPriceScaleLabel)(e,`regular`,void 0,r,i)}function l(e,t,n){return n!==null&&n>0?Math.max(1,Math.ceil(e/n-1e-9))*n:t===null?e:Math.max(e,10**-t)}var u=1e-9;function d(e,t){for(let n=0;n<t;n++){let t=10**n;if(e.every(e=>Math.abs(e*t-Math.round(e*t))<=u*Math.max(1,Math.abs(e*t))))return n}return t}function f(e,t,n){return Math.floor(t/n+1e-9)-Math.ceil(e/n-1e-9)+1}function p(e,t){if(!t||!(t>0)||e>=1)return e;let n=t;for(;n<e;)n*=2;return n}var m=24,h=200;function g(e){return Math.max(2,Math.min(m,Math.round(e/56)+1))}function _(e){if(!(e>0))return 0;let t=10**Math.floor(Math.log10(e)+1e-9),n=e/t;return(n<2?1:n<5?2:5)*t}function v(e){let t=10**Math.floor(Math.log10(e)+1e-9),n=e/t;return(n<1.5?2:n<3.5?5:10)*t}function y(e,n,r){let i=(0,t.computeTickStep)(e,n,g(r));if(!(i>0)||!(r>0))return i;let a=n-e;for(let e=0;e<8&&i/a*r<30;e++)i=v(i);return i}function b(e,t,n){if(!(n>0)||!(t>=e))return[];let r=[],i=Math.ceil(e/n-1e-9);if(!Number.isFinite(i)||Math.abs(i)>=2**53-1)return[];for(let e=i;e*n<=t+n*1e-9&&e-i<h;e++){let t=e*n;r.push(Math.abs(t)<n*1e-9?0:t)}return r}var x=12,S=14,C=class{locale=`en-US`;reservedPrice=null;precision=null;tick=null;rows=[];setPricePrecision(e){this.precision=e!==null&&Number.isInteger(e)&&e>=0?e:null}setPriceTick(e){this.tick=e!==null&&Number.isFinite(e)&&e>0?e:null}scale(e){let{min:n,max:r}=e.priceRange,i=y(n,r,e.chartRect.height),a=(0,t.autoPricePrecision)(n,r);if(e.priceUnit)return{step:p(i,e.priceUnit),precision:this.precision??a};let o=l(i,this.precision,this.tick);return f(n,r,o)<2?{step:i,precision:Math.max(this.precision??0,a)}:{step:o,precision:this.precision??a}}ticks(e){let{min:t,max:n}=e.priceRange;if(!(n-t>0))return[];let r=e.scaleMode??(e.logScale?`logarithmic`:`regular`),i=e.scaleBaseline;return(r===`percentage`||r===`indexedTo100`)&&i?this.rebasedTicks(e,r,i):r===`logarithmic`&&t>0?this.logTicks(e):b(t,n,this.scale(e).step)}rebasedTicks(e,t,n){let{min:r,max:i}=e.priceRange,a=t===`percentage`?100:0,o=e=>e/n*100-a,s=e=>(e+a)/100*n,c=Math.min(o(r),o(i)),l=Math.max(o(r),o(i));return b(c,l,y(c,l,e.chartRect.height)).map(s).sort((e,t)=>e-t)}logTicks(t){let{min:n,max:r}=t.priceRange,i=Math.log(r/n)/t.chartRect.height,a=e.E(t),o=Math.exp(-i*56),s=[],c=l(_(r*(1-o)),this.precision,this.tick),u=Math.floor(r/c+1e-9)*c,d=null;for(let e=0;e<200&&u>=n&&u>0;e++){let e=a(u);(d===null||Math.abs(e-d)>=30)&&(s.push(u),d=e);let t=u*o;if(c=l(_(Math.min(u-t,t)),this.precision,this.tick),!(c>0))break;let n=Math.round(t/c)*c;n>=u&&(n-=c),u=n}return s.length===0?b(n,r,this.scale(t).step):s.reverse()}labelText(e,t){return c(e,t,this.scale(t).precision,this.locale)}setReservedPriceProvider(e){this.reservedPrice=e}setLocale(e){this.locale=e}labelRows(){return this.rows}render(t,n,r,i=`right`,a=[]){let{chartRect:o,priceRange:s}=n,l=i===`left`,u=l?o.x:o.x+o.width;if(s.max-s.min<=0)return;let f=e.E(n);t.strokeStyle=r.style?.axis.price.line??r.axisLine,t.lineWidth=1,t.globalAlpha=.65,t.beginPath(),t.moveTo(u+.5,o.y),t.lineTo(u+.5,o.y+o.height),t.stroke(),t.globalAlpha=1;let{precision:p}=this.scale(n),m=this.ticks(n),h=n.scaleMode??(n.logScale?`logarithmic`:`regular`),g=h===`regular`||h===`logarithmic`?d(m,p):p,_=`500 ${r.font.sizeSmall}px ${r.font.family}`,v=[],y=l?null:this.reservedPrice?.()??null,b=y===null?null:e.T(y,n);for(let e of m){let t=f(e);b!==null&&Math.abs(t-b)<x||a.some(e=>Math.abs(t-e)<S)||v.push({y:t,text:c(e,n,g,this.locale)})}t.font=_,t.textBaseline=`middle`,t.textAlign=l?`right`:`left`,t.strokeStyle=r.style?.axis.price.line??r.axisLine,t.globalAlpha=.45,t.beginPath();let C=l?-1:1;for(let{y:e}of v)t.moveTo(u+C,e+.5),t.lineTo(u+4*C,e+.5);t.stroke(),t.globalAlpha=1,t.fillStyle=r.style?.axis.price.text??r.axisLabel;for(let{y:e,text:n}of v)t.fillText(n,u+8*C,e);l||(this.rows=v.map(e=>e.y))}};function w(e,t,n){let r=e.shape?.tagRadius;return typeof r==`number`&&Number.isFinite(r)?Math.max(0,Math.min(r,n/2,t/2)):0}function T(e,t,n,r,i,a){let o=w(a,r,i);if(e.beginPath(),!(o>0)){e.rect(t,n,r,i);return}e.moveTo(t+o,n),e.lineTo(t+r-o,n),e.arcTo(t+r,n,t+r,n+o,o),e.lineTo(t+r,n+i-o),e.arcTo(t+r,n+i,t+r-o,n+i,o),e.lineTo(t+o,n+i),e.arcTo(t,n+i,t,n+i-o,o),e.lineTo(t,n+o),e.arcTo(t,n,t+o,n,o),e.closePath()}function E(e,t,n,r,i,a){if(!(w(a,r,i)>0)){e.fillRect(t,n,r,i);return}T(e,t,n,r,i,a),e.fill()}function D(e){let t=Math.abs(e);return t>=1e3?1:t>=1?2:t>=.01?4:6}var O=16;function k(e,t,n,r=16){let i=r/2,a=e.map(e=>Math.min(Math.max(e,t+i),n-i));for(let e=1;e<a.length;e++)a[e]=Math.max(a[e],a[e-1]+r);a.length>0&&(a[a.length-1]=Math.min(a[a.length-1],n-i));for(let e=a.length-2;e>=0;e--)a[e]=Math.min(a[e],a[e+1]-r);if(a.length>0&&a[0]<t+i){a[0]=t+i;for(let e=1;e<a.length;e++)a[e]=Math.max(a[e],a[e-1]+r)}return a}function A(e){let t=ee(e);if(!t)return`#ffffff`;let[n,r,i]=t;return(.299*n+.587*r+.114*i)/255>.62?`#10131a`:`#ffffff`}function ee(e){let t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim());if(t){let e=t[1].length===3?t[1].replace(/./g,e=>e+e):t[1];return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]}let n=/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(e.trim());return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function te(e,t,n=[],r=16){let i=r/2,a=n.filter(e=>e.y+e.half>t.top&&e.y-e.half<t.bottom).sort((e,t)=>e.y-t.y),o=e.filter(e=>e.y>=t.top&&e.y<=t.bottom).sort((e,t)=>e.y-t.y),s=[],c=0,l=t.top;for(let e=0;e<=a.length;e++){e>0&&(l=Math.max(l,a[e-1].y+a[e-1].half));let n=l,u=e===a.length?t.bottom:a[e].y-a[e].half,d=e===a.length?1/0:a[e].y,f=c;for(;c<o.length&&o[c].y<d;)c++;let p=o.slice(f,c);if(p.length===0||u-n<r)continue;let m=k(p.map(e=>e.y),n,u,r);p.forEach((e,t)=>{m[t]-i>=n-.5&&m[t]+i<=u+.5&&s.push({...e,y:m[t]})})}return s}function ne(e,t,n,r,i){if(t.length!==0){e.save(),e.font=`bold ${i.font.sizeSmall}px ${i.font.family}`,e.textBaseline=`middle`,e.textAlign=`left`;for(let a of t){let t=Math.min(e.measureText(a.text).width+10,r-2);e.fillStyle=a.color,E(e,n+1,Math.round(a.y-8),t,16,i),e.fillStyle=A(a.color),e.fillText(a.text,n+5,Math.round(a.y))}e.restore()}}function re(e,t,n,r,i,a){ne(e,te(t,i),n,r,a)}function ie(e){return{plot:e,plotText:null,panes:new Map}}function ae(e,t,n,r){let i=e.region(t),a=0;for(;a<n.length&&i.step(n[a]);)a++;let o=new Map;for(let t of r){let n=e.region(t.rect).step(t.background),r=e.region(t.inner),i=0;if(n)for(;i<t.steps.length&&r.step(t.steps[i]);)i++;o.set(t.id,{background:n,text:r,rest:t.steps.slice(i)})}return{plot:n.slice(a),plotText:i,panes:o}}var oe=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,s=r.barWidth,c=s+r.barSpacing,l=-r.offset+r.chartRect.x+s/2,{min:u,max:d}=r.priceRange;if(d-u===0)return;if(e.f(r)){e.p(t,n,r,i.candleUp,i.candleDown);return}let f=e.E(r);e.v(t,r=>{let{body:u,wick:d}=e.h(s,r.ratio),p=(u-d)/2,m=new Path2D,h=new Path2D,g=new Path2D,_=new Path2D;for(let e=a;e<=o&&e<n.length;e++){let t=n[e],i=t.close>=t.open,a=r.left(e*c+l,d),o=r.y(f(t.high)),s=r.y(f(t.low));(i?m:h).rect(a,Math.min(o,s),d,Math.max(Math.abs(s-o),1));let v=r.y(f(t.open)),y=r.y(f(t.close));(i?g:_).rect(a-p,Math.min(v,y),u,Math.max(Math.abs(y-v),d))}t.fillStyle=i.candleUpWick,t.fill(m),t.fillStyle=i.candleDownWick,t.fill(h),t.fillStyle=i.candleUp,t.fill(g),t.fillStyle=i.candleDown,t.fill(_)})}};function se(e){if(e.style)return e.style.crosshair;let t=()=>({visible:!0,color:e.crosshair,style:`solid`,width:1});return{horizontal:t(),vertical:t(),labelBackground:e.text,labelText:e.background}}var ce=16,le=class{visible=!0;timeframeMs=0;setVisible(e){this.visible=e}isVisible(){return this.visible}setTimeframeMs(e){this.timeframeMs=e}isShown(e){return this.remaining(e)>0}render(e,t,n,r,i=null){let a=this.remaining(r);if(i===null||a<=0)return;let o=i.y+i.height;e.fillStyle=i.color,E(e,i.x,o,i.width,16,n),e.font=`${n.font.sizeSmall}px ${n.font.family}`,e.textBaseline=`middle`,e.textAlign=`left`,e.fillStyle=A(i.color),e.fillText(this.formatRemaining(a),i.x+5,o+16/2)}remaining(e){if(!this.visible||!(this.timeframeMs>0)||e.length===0)return 0;let n=e[e.length-1].time*(0,t.barTimeUnit)(e)+this.timeframeMs-Date.now();return n>0?n:0}formatRemaining(e){let t=Math.ceil(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}:${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`:`${r}:${String(i).padStart(2,`0`)}`}},ue=20,de=8;function fe(e,t,n){if(!e)return null;let r=e.region(t,{text:!1});return n.every(e=>r.step(e))?e:null}function pe(e){return e<1?Math.ceil(-Math.log10(e))+1:+(e<10)}var me=class{layerManager;renderLoop;dprManager;renderCtx=null;sceneLayer;topLayer;gpu=null;lostGpu=null;onGpuLost=null;onGpuRestored=null;onContainerResize=null;constructor(e,t){this.layerManager=new r(e),this.renderLoop=new i,this.dprManager=new s(e,t),this.layerManager.createLayers(),this.cacheLayerRefs(),this.renderLoop.setCallback(e=>this.render(e)),this.dprManager.onResize((e,t)=>{this.layerManager.resize(e,t),this.renderLoop.markAllDirty(),this.onContainerResize?.(e)});let n=this.dprManager.getContainerSize(),a=this.dprManager.getDpr();this.layerManager.resize(n,a)}cacheLayerRefs(){this.sceneLayer=this.layerManager.getLayer(t.LayerType.Main),this.topLayer=this.layerManager.getLayer(t.LayerType.Hover)}setRenderContext(e){this.renderCtx=e}attachGpu(e){this.detachGpu(),this.placeGpu(e),e.onLost(()=>{this.gpu===e&&(this.gpu=null,this.lostGpu=e,this.layerManager.detachGpu(),this.renderLoop.markAllDirty(),this.onGpuLost?.())}),e.onRestored?.(()=>{this.lostGpu===e&&(this.lostGpu=null,this.placeGpu(e),this.onGpuRestored?.())})}placeGpu(e){this.gpu=e,this.layerManager.attachGpu(e.canvas),this.renderLoop.markAllDirty()}detachGpu(){let e=this.gpu??this.lostGpu;e&&(this.gpu=null,this.lostGpu=null,this.layerManager.detachGpu(),e.destroy(),this.renderLoop.markAllDirty())}renderNow(){this.render(new Set([t.LayerType.Main,t.LayerType.Hover]))}getGpu(){return this.gpu}start(){this.renderLoop.start()}stop(){this.renderLoop.stop()}requestRender(e){e===void 0?this.renderLoop.markAllDirty():this.renderLoop.markDirty(e)}render(e){let n=this.renderCtx;if(!n)return;let{chartRect:r}=n.viewport;if(r.width<=0||r.height<=0)return;let i=!1;for(let n of e)if(n!==t.LayerType.Hover){i=!0;break}i&&this.sceneLayer&&this.renderScene(this.sceneLayer,n),this.topLayer&&this.renderTop(this.topLayer,n)}renderScene(e,n){let{viewport:r,theme:i,data:a}=n;e.clear();let o=e.ctx,s=this.gpu,c=!!s&&n.chartRenderer instanceof oe,l=n.chartRenderer?[e=>n.chartRenderer.render(e,a,r,i)]:[],u=[...c?[]:l,...n.compareRenderer?[e=>n.compareRenderer.render(e,a,r,i)]:[],...n.indicatorEngine?.overlayDraws(r,n.leftViewport??void 0)??[]],d=this.paneSteps(n),f={series:!1,volume:!1,background:!1},p=ie(u);s?({drawn:f,plan:p}=this.renderGpu(s,n,o,u,d),c&&!f.series&&(p={...p,plot:[...l,...p.plot]})):this.renderBackground(o,n),o.save(),o.beginPath(),o.rect(r.chartRect.x,r.chartRect.y,r.chartRect.width,r.chartRect.height),o.clip(),s||n.depthHeatmap?.render(o,r,i),f.volume||n.volumeRenderer?.render(o,a,r,i),s||(n.volumeProfile?.render(o,a,r,i),n.marketProfile?.render(o,a,r,i)),p.plotText?.drawText(o);for(let e of p.plot)e(o);n.sessionBreaks?.renderLabels(o,r,i,a),n.periodLevels?.render(o,a,r,i),n.pivotMarkers?.render(o,a,r,i),n.renderOverlayPlugins?.(o,`main`),o.restore(),this.renderPanels(o,n,d,p),n.priceLimits&&this.renderPriceLimits(o,r,i,n.priceLimits),n.tradeZoneManager?.render(o,r,i),n.drawingRenderer?.render(o,r,i),n.tradingRenderer?.render(o,r,i),n.signalMarkerManager?.render(o,r,i),n.alertManager?.render(o,r,i),n.priceLines?.render(o,r,i,a);let m=this.fixedAxisTags(n),h=n.indicatorValueLabels===!1?[]:this.overlayValueTags(n,m);n.priceAxis?.render(o,r,i,`right`,[...m.map(e=>e.y),...h.map(e=>e.y)]),ne(o,h,r.chartRect.x+r.chartRect.width,r.priceAxisWidth??t.PRICE_AXIS_WIDTH,i),n.leftViewport&&(n.leftPriceAxis?.render(o,n.leftViewport,i,`left`),n.indicatorValueLabels!==!1&&this.renderLeftValueLabels(o,n,n.leftViewport)),n.tradingRenderer?.renderAxisBadges(o,r,i),n.priceLines?.renderAxisTags(o,r,i,a),n.currentPriceLine?.render(o,r,i),n.timeAxis?.render(o,r,i,a,n.timeAxisY),this.renderPanelAxes(o,n)}renderGpu(t,n,r,i,a){let{viewport:o,theme:s,data:c}=n,l=this.layerManager.getDpr(),u=this.underSteps(n),d=!!(n.marketProfile?.isVisible()&&n.marketProfile.drawsText()),f=u.length>0&&!d?fe(t.recorder?.(l,r)??null,o.chartRect,u):null,p=u.length>0&&!f,m=t.recorder?.(l,r)??null,h=m?ae(m,o.chartRect,i,a):ie(i),g=!!(n.volumeProfile?.isVisible()||n.marketProfile?.isVisible()),_=!!n.gridRenderer?.isVisible()&&!e.s(s),v=n.watermark?.isVisible()||p||_?null:{grid:n.gridRenderer?.isVisible()??!1,marks:n.gridRenderer?.isVisible()?he(n):void 0,rects:[...n.sessionShading?.rects(c,o,s)??[],...n.sessionBreaks?.lineRects(o,s,c)??[]]},y=n.volumeRenderer?.isVisible()&&!g?{heightRatio:n.volumeRenderer.getHeightRatio()}:null,b=t.render({data:c,viewport:o,theme:s,dpr:l,candles:n.chartRenderer instanceof oe,volume:y,background:v,under:f,recorded:m}),x=b.recorded?h:ie(i),S={drawn:{...b,volume:b.volume||g},plan:x},C=v!==null&&!!b.background,w=f!==null&&b.under?[]:u;return C&&w.length===0?(this.layerManager.dropBackLayer(),S):(this.renderBackCanvas(n,w,!C),S)}underSteps(e){let{viewport:t,theme:n,data:r}=e,i=[];return e.depthHeatmap?.isVisible()&&i.push(r=>e.depthHeatmap.render(r,t,n)),(e.volumeProfile?.isVisible()||e.marketProfile?.isVisible())&&(e.volumeRenderer?.isVisible()&&i.push(i=>e.volumeRenderer.render(i,r,t,n)),e.volumeProfile?.isVisible()&&i.push(i=>e.volumeProfile.render(i,r,t,n)),e.marketProfile?.isVisible()&&i.push(i=>e.marketProfile.render(i,r,t,n))),i}renderBackCanvas(e,t,n){let r=this.layerManager.backLayer();r&&(r.clear(),n&&this.renderBackground(r.ctx,e),t.length>0&&this.inPlot(r.ctx,e.viewport,()=>t.forEach(e=>e(r.ctx))))}renderBackground(e,t){let{viewport:n,theme:r,data:i}=t;t.gridRenderer?.isVisible()&&t.gridRenderer.render(e,n,r,he(t)),t.sessionShading?.render(e,i,n,r),t.sessionBreaks?.renderLines(e,n,r,i),t.watermark?.render(e,n,r)}inPlot(e,t,n){e.save(),e.beginPath(),e.rect(t.chartRect.x,t.chartRect.y,t.chartRect.width,t.chartRect.height),e.clip(),n(),e.restore()}renderTop(e,t){let{viewport:n,theme:r,data:i}=t;e.clear();let a=e.ctx;t.measureOverlay?.render(a,n,r),t.selectionBoxOverlay?.render(a,n,r),t.crosshairHandler?.render(a,n,r),t.renderOverlayPlugins?.(a,`overlay`),this.renderPanelCrosshair(a,t),t.barCountdown?.render(a,n,r,i,t.currentPriceLine?.getTag()??null),t.crosshairHandler?.renderAxisLabels(a,n,r,i,t.timeAxisY,t.priceAxis?.labelRows(),t.timeAxis?.labelColumns()),t.priceAxisAddButton?.render(a,n,r,t.crosshairHandler?.getPosition()??null),t.chartLegend?.render(a,n,r,i),t.renderOverlayPlugins?.(a,`ui`),this.renderPanelHoverValues(a,t)}paneSteps(e){let{theme:t,panels:n}=e,r=e.indicatorEngine;if(!r||n.length===0)return[];let i=[];for(let e of n){let{rect:n,viewport:a}=e;if(n.width<=0||n.height<=0)continue;let o=e.members?.length?[e.instanceId,...e.members]:[e.instanceId],s=[];for(let e of o){let n=r.isShown(e)?r.getLevels(e):[];n.length>0&&s.push(e=>this.renderLevels(e,n,a,t))}for(let e of o)s.push(t=>r.renderPanel(t,e,a));i.push({id:e.instanceId,rect:n,inner:{x:n.x,y:n.y+ue,width:n.width,height:n.height-ue},background:r=>{r.fillStyle=e.style?.background??t.style?.panes.background??t.background,r.fillRect(n.x,n.y,n.width,n.height)},steps:s})}return i}renderPanels(e,t,n,r){let{theme:i}=t,a=t.indicatorEngine;if(!a||n.length===0)return;let o=`10px ${i.font.family}`,s=this.panelDescriptors(a),c=new Map(t.panels.map(e=>[e.instanceId,e.style]));for(let a of n){let{rect:n,inner:l}=a,u=r.panes.get(a.id),d=c.get(a.id);e.save(),e.beginPath(),e.rect(n.x,n.y,n.width,n.height),e.clip(),u?.background||a.background(e),e.fillStyle=d?.separator??i.style?.panes.separator??i.axisLine,e.fillRect(n.x,n.y,n.width,3),e.fillStyle=i.style?.panes.title??i.textSecondary,e.font=o,e.textBaseline=`top`,e.textAlign=`left`;let f=s.get(a.id);f&&t.paneTitles!==!1&&e.fillText(f.descriptor.name,n.x+6,n.y+6),e.save(),e.beginPath(),e.rect(l.x,l.y,l.width,l.height),e.clip(),u?.text?.drawText(e);for(let t of u?u.rest:a.steps)t(e);e.restore(),e.restore()}}fixedAxisTags(t){let{viewport:n,data:r}=t,{chartRect:i}=n,a=[],o=t.currentPriceLine?.isVisible()&&t.theme.style?.lastPrice.visible!==!1?t.currentPriceLine.getPrice():null;if(o!=null){let s=e.T(o,n);a.push({y:s,half:10}),s>=i.y&&s<=i.y+i.height&&t.barCountdown?.isShown(r)&&a.push({y:s+10+16/2,half:16/2})}for(let i of t.priceLines?.levels(r,n)??[])a.push({y:e.T(i.price,n),half:8});for(let e of t.tradingRenderer?.axisTagYs(n,t.theme)??[])a.push({y:e,half:16/2});return a.filter(e=>e.y>=i.y&&e.y<=i.y+i.height)}overlayValueTags(n,r){let i=n.indicatorEngine?.getLatestOverlayValues();if(!i?.length)return[];let{viewport:a}=n,{chartRect:o}=a,s=n.formatPrice??(e=>(0,t.formatPrice)(e,2,n.numberLocale??`en-US`));return te(i.map(t=>({y:e.T(t.value,a),text:s(t.value),color:t.color})),{top:o.y,bottom:o.y+o.height},r)}renderLeftValueLabels(n,r,i){let a=r.indicatorEngine?.getLatestOverlayValues(`left`);if(!a?.length)return;let{chartRect:o}=i,s=r.leftAxisWidth??t.PRICE_AXIS_WIDTH,c=(0,t.autoPricePrecision)(i.priceRange.min,i.priceRange.max),l=r.numberLocale??`en-US`;re(n,a.map(n=>({y:e.T(n.value,i),text:(0,t.formatPrice)(n.value,c,l),color:n.color})),o.x-s,s,{top:o.y,bottom:o.y+o.height},r.theme)}renderLevels(t,n,r,i){if(n.length===0)return;let{chartRect:a}=r;t.save(),t.strokeStyle=i.axisLabel,t.globalAlpha=.45,t.lineWidth=1,t.setLineDash([4,4]),t.beginPath();for(let i of n){let n=Math.round(e.T(i,r))+.5;t.moveTo(a.x,n),t.lineTo(a.x+a.width,n)}t.stroke(),t.restore()}renderPanelAxes(n,r){let{theme:i}=r,a=r.numberLocale??`en-US`,o=`${i.font.sizeSmall}px ${i.font.family}`;for(let s of r.panels){let l=s.viewport,u=s.rect,{min:d,max:f}=l.priceRange;if(f-d<=0||u.height<=0||l.chartRect.height<de)continue;let p=u.x+u.width,m=l.chartRect,h=i.style?.axis.price.line??i.axisLine,g=i.style?.axis.price.text??i.axisLabel;n.strokeStyle=h,n.lineWidth=1,n.beginPath(),n.moveTo(p+.5,u.y),n.lineTo(p+.5,u.y+u.height),n.stroke();let _=y(d,f,m.height),v=pe(_);n.font=o,n.textBaseline=`middle`,n.textAlign=`left`;for(let t of b(d,f,_)){let r=e.T(t,l);r<m.y||r>m.y+m.height||(n.strokeStyle=h,n.beginPath(),n.moveTo(p,Math.round(r)+.5),n.lineTo(p+4,Math.round(r)+.5),n.stroke(),n.fillStyle=g,n.fillText(c(t,l,v,a),p+6,r))}let x=r.indicatorValueLabels===!1?null:[s.instanceId,...s.members??[]].flatMap(e=>r.indicatorEngine?.getLatestValues(e)??[]);x?.length&&re(n,x.map(n=>({y:e.T(n.value,l),text:l.scaleMode===`percentage`&&l.scaleBaseline?c(n.value,l,2,a):(0,t.formatPrice)(n.value,D(n.value),a),color:n.color})),p,r.viewport.priceAxisWidth??t.PRICE_AXIS_WIDTH,{top:m.y,bottom:m.y+m.height},i)}}renderPanelCrosshair(n,r){let i=r.crosshairHandler?.getPosition();if(!i||r.panels.length===0)return;let{theme:a}=r;for(let o of r.panels){let s=o.rect;if(i.x<s.x||i.x>s.x+s.width||i.y<s.y||i.y>s.y+s.height)continue;let c=o.viewport;if(c.chartRect.height<de)continue;let l=e.A(i.x,c),u=e.b(Math.max(0,Math.min((r.data?.length??1)-1,Math.round(l))),c),d=se(a);if(n.save(),n.beginPath(),n.rect(s.x,s.y,s.width,s.height),n.clip(),d.vertical.visible){n.setLineDash((0,t.lineDash)(d.vertical.style,[4,4],d.vertical.width)),n.strokeStyle=d.vertical.color;let r=e.g(n,u,d.vertical.width);n.lineWidth=r.width,n.beginPath(),n.moveTo(r.x,s.y),n.lineTo(r.x,s.y+s.height),n.stroke()}if(d.horizontal.visible){n.setLineDash((0,t.lineDash)(d.horizontal.style,[4,4],d.horizontal.width)),n.strokeStyle=d.horizontal.color;let r=e._(n,i.y,d.horizontal.width);n.lineWidth=r.width,n.beginPath(),n.moveTo(s.x,r.y),n.lineTo(s.x+s.width,r.y),n.stroke()}n.setLineDash([]),n.restore();break}}renderPanelHoverValues(n,r){let i=r.crosshairHandler?.getPosition(),a=r.indicatorEngine;if(!i||r.panels.length===0)return;let{theme:o,viewport:s,data:l}=r,u=r.numberLocale??`en-US`,d=`${o.font.sizeSmall}px ${o.font.family}`,f=a?this.panelDescriptors(a):null;for(let p of r.panels){let m=p.viewport,h=p.rect,{min:g,max:_}=m.priceRange;if(_-g<=0||h.height<=0||m.chartRect.height<de)continue;let v=h.x+h.width,b=pe(y(g,_,m.chartRect.height));if(i.x>=h.x&&i.x<=h.x+h.width&&i.y>=h.y&&i.y<=h.y+h.height){let r=c(e.M(i.y,m),m,b,u);n.font=`bold ${o.font.sizeSmall}px ${o.font.family}`;let a=n.measureText(r).width,l=Math.min(a+10,(s.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2),d=se(o);n.fillStyle=d.labelBackground,E(n,v+1,i.y-9,l,18,o),n.fillStyle=d.labelText,n.textBaseline=`middle`,n.textAlign=`left`,n.fillText(r,v+5,i.y)}if(!a||r.paneTitles===!1||!a.isShown(p.instanceId))continue;let x=Math.max(0,Math.min((l?.length??1)-1,Math.round(e.A(i.x,m)))),S=a.getOutput(p.instanceId),C=S?.series&&x<S.series.length?S.series[x]:null;if(!C)continue;let w=f?.get(p.instanceId),T=w?.descriptor.plots,D=[];if(T)for(let e of T){let t=C[e.key];t!==void 0&&Number.isFinite(t)&&D.push(`${e.title} ${c(t,m,b,u)}`)}else for(let e in C){let t=C[e];t!==void 0&&D.push(`${e}: ${t.toFixed(b)}`)}if(D.length===0)continue;n.font=d;let O=w?n.measureText(w.descriptor.name).width+14:10;n.fillStyle=o.textSecondary,n.textBaseline=`top`,n.textAlign=`left`,n.fillText(D.join(` `),h.x+O,h.y+6)}}panelDescriptors(e){let t=new Map;for(let n of e.getPanelIndicators())t.set(n.instanceId,n);return t}renderPriceLimits(n,r,i,a){let{chartRect:o}=r,s=[{price:a.ceiling,color:a.colors?.ceiling??`#FF00FF`,label:`CE`},{price:a.floor,color:a.colors?.floor??`#00FFFF`,label:`FL`},{price:a.reference,color:a.colors?.reference??`#FFD700`,label:`REF`}],c=`bold 9px ${i.font.family}`,l=`10px ${i.font.family}`;for(let{price:a,color:u,label:d}of s){let s=e.T(a,r);if(s<o.y||s>o.y+o.height)continue;n.setLineDash([8,4]),n.strokeStyle=u,n.lineWidth=1,n.beginPath(),n.moveTo(o.x,Math.round(s)+.5),n.lineTo(o.x+o.width,Math.round(s)+.5),n.stroke(),n.setLineDash([]),n.font=c,n.fillStyle=u,n.textBaseline=`bottom`,n.textAlign=`left`,n.fillText(`${d} ${r.formatPrice?.(a)??a.toFixed(2)}`,o.x+4,s-2);let f=o.x+o.width+1;n.fillStyle=u,E(n,f,s-7,(r.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,14,i),n.fillStyle=`#000`,n.font=l,n.textBaseline=`middle`,n.textAlign=`left`,n.fillText(r.formatPrice?.(a)??a.toFixed(2),f+4,s)}}destroy(){this.renderLoop.stop(),this.detachGpu(),this.dprManager.destroy(),this.layerManager.destroy()}};function he(e){return{prices:e.priceAxis?.ticks(e.viewport),slots:e.timeAxis?.marks(e.viewport,e.data).map(e=>e.index)}}async function ge(t){let n=e.n();if(!n)return{gpu:null,reason:`limit`};let r;try{r=await Promise.resolve().then(()=>require(`./WebGLSeriesRenderer-DaTDdW4O.cjs`))}catch(e){return n(),console.warn(`TradeCanvas: the WebGL renderer failed to load, drawing with Canvas 2D.`,e),{gpu:null,reason:`unsupported`}}let i=r.WebGLSeriesRenderer.create({failIfMajorPerformanceCaveat:t===`auto`,release:n});return i?{gpu:i}:(n(),{gpu:null,reason:`unsupported`})}async function _e(e){return(await ge(e)).gpu}var ve=.25,ye=.02,be=t.PHI**-5,xe=.2,Se=class{state;priceAxisWidth=t.PRICE_AXIS_WIDTH;stateCache=null;dataLength=0;margins={top:be,bottom:be};minBarWidth;maxBarWidth;rightMarginBars;freePan=!0;minVisibleBars=3;minBarUnit=ve;constructor(e,n,r=2,i=30,a=5){this.minBarWidth=r,this.maxBarWidth=i,this.rightMarginBars=a;let o=this.computeChartRect(e,n);this.state={visibleRange:{from:0,to:0},priceRange:{min:0,max:1},barWidth:t.DEFAULT_BAR_WIDTH,barSpacing:t.DEFAULT_BAR_SPACING,offset:0,chartRect:o}}getState(){return this.stateCache||={visibleRange:{...this.state.visibleRange},priceRange:{...this.state.priceRange},barWidth:this.state.barWidth,barSpacing:this.state.barSpacing,offset:this.state.offset,chartRect:{...this.state.chartRect},logScale:this.state.logScale,scaleMode:this.state.scaleMode,scaleBaseline:this.state.scaleBaseline,invertScale:this.state.invertScale,priceAxisWidth:this.state.priceAxisWidth,formatPrice:this.state.formatPrice,numberLocale:this.state.numberLocale,priceUnit:this.state.priceUnit},this.stateCache}invalidate(){this.stateCache=null}setLogScale(e){this.setScaleMode(e?`logarithmic`:`regular`)}isLogScale(){return(this.state.scaleMode??(this.state.logScale?`logarithmic`:`regular`))===`logarithmic`}setScaleMode(e){this.state.scaleMode=e,this.state.logScale=e===`logarithmic`,this.invalidate()}getScaleMode(){return this.state.scaleMode??(this.state.logScale?`logarithmic`:`regular`)}setInvertScale(e){this.state.invertScale=e,this.invalidate()}isInvertScale(){return this.state.invertScale===!0}setNumberLocale(e){this.state.numberLocale=e,this.invalidate()}setPriceFormat(e,t=null){this.state.formatPrice=e??void 0,this.state.priceUnit=t??void 0,this.invalidate()}setScaleBaseline(e){this.state.scaleBaseline=e,this.invalidate()}setRightMargin(e){this.rightMarginBars=e}getRightMargin(){return this.rightMarginBars}setPanLimits(e){e.freePan!==void 0&&(this.freePan=e.freePan),e.minVisibleBars!==void 0&&(this.minVisibleBars=Math.max(1,Math.floor(e.minVisibleBars))),this.clampOffset(),this.updateVisibleRange()}endOffset(){let e=this.state.barWidth+this.state.barSpacing;return this.dataLength*e-this.state.chartRect.width+this.rightMarginBars*e}setPriceAxisWidth(e){this.priceAxisWidth!==e&&(this.priceAxisWidth=e,this.state.priceAxisWidth=e,this.invalidate())}computeChartRect(e,n){return{x:0,y:0,width:Math.max(0,e-this.priceAxisWidth),height:Math.max(0,n-t.TIME_AXIS_HEIGHT)}}resize(e,t){this.state.chartRect=this.computeChartRect(e,t),this.invalidate(),this.clampUnit(),this.clampOffset()}setChartRect(e){this.state.chartRect={x:e.x,y:e.y,width:Math.max(0,e.width),height:Math.max(0,e.height)},this.invalidate(),this.clampUnit(),this.clampOffset(),this.updateVisibleRange()}floorUnit(){return this.minBarWidth+t.DEFAULT_BAR_SPACING}minUnit(){let e=this.floorUnit(),t=this.state.chartRect.width,n=this.dataLength+this.rightMarginBars;return t<=0||n<=0?e:Math.max(this.minBarUnit,Math.min(e,t/n))}setMinBarUnit(e){this.minBarUnit=Number.isFinite(e)?Math.max(ye,Math.min(e,this.floorUnit())):ve,this.clampUnit(),this.clampOffset(),this.updateVisibleRange(),this.invalidate()}getMinBarUnit(){return this.minBarUnit}maxUnit(){return this.maxBarWidth+t.DEFAULT_BAR_SPACING}applyUnit(e){let n=this.floorUnit();if(e>=n)this.state.barWidth=e-t.DEFAULT_BAR_SPACING,this.state.barSpacing=t.DEFAULT_BAR_SPACING;else{let t=this.minBarWidth/n;this.state.barWidth=e*t,this.state.barSpacing=e-this.state.barWidth}this.invalidate()}clampUnit(){let e=this.state.barWidth+this.state.barSpacing,n=(0,t.clamp)(e,this.minUnit(),this.maxUnit());n===e||e<=0||(this.state.offset=this.state.offset/e*n,this.applyUnit(n))}updateData(e,n){let r=this.dataLength===0;if(this.dataLength=e.length,this.dataLength!==0&&(this.clampUnit(),r&&(this.state.offset=this.endOffset()),this.clampOffset(),this.updateVisibleRange(),n)){let{min:n,max:r}=(0,t.computePriceRange)(e,this.state.visibleRange.from,Math.min(this.state.visibleRange.to,this.dataLength-1),0);this.fitToPrices(n,r)}}setScaleMargins(e){let t=e=>Number.isFinite(e)&&e>=0;!t(e.top)||!t(e.bottom)||1-e.top-e.bottom<xe||(this.margins={top:e.top,bottom:e.bottom})}getScaleMargins(){return{...this.margins}}fitToPrices(e,n){this.state.priceRange=(0,t.fitPriceRange)(e,n,this.margins,this.isLogScale()),this.invalidate()}prependBars(e){e===0||!Number.isFinite(e)||(this.dataLength+=e,this.state.offset+=e*(this.state.barWidth+this.state.barSpacing),this.invalidate(),this.updateVisibleRange())}setPriceRange(e,t){this.state.priceRange={min:e,max:t},this.invalidate()}scalePriceRange(e){if(!Number.isFinite(e)||e<=0)return;let{min:t,max:n}=this.state.priceRange,r=(t+n)/2,i=(n-t)/2,a=Math.max(i*e,1e-9);this.state.priceRange={min:r-a,max:r+a},this.invalidate()}scrollBy(e){this.state.offset+=e,this.invalidate(),this.clampOffset(),this.updateVisibleRange()}panPriceRange(e){let t=this.state.chartRect.height;if(t<=0||e===0)return;let{min:n,max:r}=this.state.priceRange,i=(this.state.invertScale?-e:e)/t;if(this.isLogScale()&&n>0&&r>0){let e=Math.log(n),t=Math.log(r),a=(t-e)*i;this.state.priceRange={min:Math.exp(e-a),max:Math.exp(t-a)},this.invalidate();return}let a=(r-n)*i;this.state.priceRange={min:n-a,max:r-a},this.invalidate()}isAtEnd(){let e=this.state.barWidth+this.state.barSpacing;return Math.abs(this.state.offset-this.endOffset())<=e*2}scrollToEnd(){this.state.offset=this.endOffset(),this.invalidate(),this.updateVisibleRange()}zoom(e,n){let r=this.state.barWidth+this.state.barSpacing,i=this.state.barWidth*(1+e),a=(0,t.clamp)(r>=this.floorUnit()&&i>=this.minBarWidth?i+t.DEFAULT_BAR_SPACING:r*(1+e),this.minUnit(),this.maxUnit());if(a===r)return;let o=this.isAtEnd(),s=(this.state.offset+n)/r;this.applyUnit(a),this.state.offset=o?this.endOffset():s*a-n,this.invalidate(),this.clampOffset(),this.updateVisibleRange()}zoomToBarRange(e,n){let r=this.state.chartRect.width;if(r<=0||!Number.isFinite(e)||!Number.isFinite(n)||n<e)return;let i=(0,t.clamp)(r/(n-e+1),this.minUnit(),this.maxUnit());this.applyUnit(i),this.state.offset=(e+n+1)/2*i-r/2,this.invalidate(),this.clampOffset(),this.updateVisibleRange()}clampOffset(){if(this.state.chartRect.width<=0)return;let e=this.state.barWidth+this.state.barSpacing,n=this.state.chartRect.width,r=this.endOffset(),i,a;if(this.freePan&&this.dataLength>0){let t=Math.min(this.minVisibleBars,this.dataLength);i=t*e-n,a=(this.dataLength-t)*e,i=Math.min(i,r),a=Math.max(a,r)}else if(r>0)i=-(n*.5),a=r;else{let e=n*.5;i=r-e,a=r+e}this.state.offset=(0,t.clamp)(this.state.offset,i,a),this.invalidate()}updateVisibleRange(){let e=this.state.barWidth+this.state.barSpacing;if(e<=0||this.state.chartRect.width<=0)return;let t=Math.floor(this.state.offset/e),n=Math.ceil(this.state.chartRect.width/e)+1,r=Math.min(t+n,this.dataLength-1);this.state.visibleRange={from:Math.max(0,t),to:Math.max(0,r)},this.invalidate()}};function Ce(e,n){return(0,t.sliceVisibleData)(e,n.visibleRange.from,n.visibleRange.to)}var we=[`1D`,`5D`,`1M`,`3M`,`6M`,`YTD`,`1Y`,`5Y`,`All`],Te=864e5,Ee=6e4,De={"1M":1,"3M":3,"6M":6,"1Y":12,"5Y":60};function Oe(e,t){let n=new Date(e),r=n.getUTCFullYear(),i=n.getUTCMonth()+t,a=new Date(Date.UTC(r,i+1,0)).getUTCDate();return Date.UTC(r,i,Math.min(n.getUTCDate(),a),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds())}function ke(e,n,r=0){if(e===`All`)return null;if(e===`1D`)return n-Te;if(e===`5D`)return n-5*Te;let i=n+(0,t.offsetAt)(r,n)*Ee;return e===`YTD`?(0,t.wallToUtc)(Date.UTC(new Date(i).getUTCFullYear(),0,1),r):(0,t.wallToUtc)(Oe(i,-(De[e]??0)),r)}function Ae(e,t,n){if(t>=e){let t=Array(Math.max(0,e));for(let n=0;n<e;n++)t[n]=n;return t}if(t<=2)return e>=2?[0,e-1]:e===1?[0]:[];let r=[0],i=(e-2)/(t-2),a=0;for(let o=0;o<t-2;o++){let t=Math.floor((o+1)*i)+1,s=Math.floor((o+2)*i)+1;s>e&&(s=e);let c=0,l=0,u=0;for(let e=t;e<s;e++)c+=e,l+=n(e),u++;if(u>0)c/=u,l/=u;else{let r=Math.min(t,e-1);c=r,l=n(r)}let d=Math.floor(o*i)+1,f=Math.floor((o+1)*i)+1,p=n(a),m=-1,h=d;for(let e=d;e<f;e++){let t=Math.abs((a-c)*(n(e)-p)-(a-e)*(l-p));t>m&&(m=t,h=e)}r.push(h),a=h}return r.push(e-1),r}var je=64;function Me(e,t,n,r,i){let a=Math.max(0,e),o=Math.min(t,n-1);if(o<a)return[];let s=o-a+1,c=Math.max(je,Math.ceil(r*2));if(s<=c){let e=Array(s);for(let t=0;t<s;t++)e[t]=a+t;return e}let l=Ae(s,c,e=>i(a+e));for(let e=0;e<l.length;e++)l[e]+=a;return l}var Ne=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange;if(a>o||n.length===0)return;let s=r.barWidth+r.barSpacing,c=-r.offset+r.chartRect.x+r.barWidth/2,{min:l,max:u}=r.priceRange;if(u-l===0)return;let d=e.E(r);t.beginPath(),t.strokeStyle=i.lineColor,t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`round`;let f=Me(a,o,n.length,r.chartRect.width,e=>n[e].close),p=!1;for(let e of f){let r=e*s+c,i=d(n[e].close);p?t.lineTo(r,i):(t.moveTo(r,i),p=!0)}t.stroke()}},Pe=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange;if(a>o||n.length===0)return;let s=r.barWidth+r.barSpacing,c=-r.offset+r.chartRect.x+r.barWidth/2,{min:l,max:u}=r.priceRange;if(u-l===0)return;let d=e.E(r),f=d(l),p=Me(a,o,n.length,r.chartRect.width,e=>n[e].close);if(p.length===0)return;let m=p[0],h=m*s+c,g=d(n[m].close),_=t.createLinearGradient(0,d(u),0,f);_.addColorStop(0,i.areaTopColor),_.addColorStop(1,i.areaBottomColor),t.beginPath(),t.moveTo(h,f),t.lineTo(h,g);let v=h;for(let e=1;e<p.length;e++){let r=p[e];v=r*s+c,t.lineTo(v,d(n[r].close))}t.lineTo(v,f),t.closePath(),t.fillStyle=_,t.fill(),t.beginPath(),t.strokeStyle=i.lineColor,t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`round`,t.moveTo(h,g);for(let e=1;e<p.length;e++){let r=p[e];t.lineTo(r*s+c,d(n[r].close))}t.stroke()}},Fe=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,s=r.barWidth,c=s+r.barSpacing,l=-r.offset+r.chartRect.x+s/2,{min:u,max:d}=r.priceRange;if(d-u===0)return;if(e.f(r)){e.p(t,n,r,i.candleUp,i.candleDown);return}let f=e.E(r);e.v(t,r=>{let{body:u,wick:d}=e.h(s,r.ratio),p=Math.max((u-d)/2,d),m=new Path2D,h=new Path2D;for(let e=a;e<=o&&e<n.length;e++){let t=n[e],i=t.close>=t.open?m:h,a=r.left(e*c+l,d),o=r.y(f(t.high)),s=r.y(f(t.low));i.rect(a,Math.min(o,s),d,Math.max(Math.abs(s-o),d)),i.rect(a-p,r.y(f(t.open))-Math.floor(d/2),p,d),i.rect(a+d,r.y(f(t.close))-Math.floor(d/2),p,d)}t.fillStyle=i.candleUp,t.fill(m),t.fillStyle=i.candleDown,t.fill(h)})}},Ie=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,s=r.barWidth,c=s+r.barSpacing,l=-r.offset+r.chartRect.x+s/2,{min:u,max:d}=r.priceRange;if(d-u===0)return;if(e.f(r)){e.p(t,n,r,i.candleUp,i.candleDown);return}let f=e.E(r);e.v(t,r=>{let{body:u,wick:d}=e.h(s,r.ratio),p=(u-d)/2,m={up:new Path2D,down:new Path2D},h={up:new Path2D,down:new Path2D},g={up:new Path2D,down:new Path2D};for(let e=a;e<=o&&e<n.length;e++){let t=n[e],i=e===0||t.close>=n[e-1].close?`up`:`down`,a=r.left(e*c+l,d),o=a-p,s=r.y(f(t.high)),_=r.y(f(t.low)),v=r.y(f(t.open)),y=r.y(f(t.close)),b=Math.min(v,y),x=Math.max(Math.abs(y-v),d);t.close>=t.open?(b>s&&m[i].rect(a,s,d,b-s),_>b+x&&m[i].rect(a,b+x,d,_-b-x),g[i].rect(o+d/2,b+d/2,Math.max(u-d,0),Math.max(x-d,0))):(m[i].rect(a,Math.min(s,_),d,Math.max(Math.abs(_-s),1)),h[i].rect(o,b,u,x))}for(let e of[`up`,`down`]){let n=e===`up`?i.candleUp:i.candleDown;t.fillStyle=n,t.fill(m[e]),t.fill(h[e]),t.strokeStyle=n,t.lineWidth=d,t.stroke(g[e])}})}},Le=32/255,Re=class{baselinePrice=null;setBaseline(e){this.baselinePrice=e}render(t,n,r,i){let{from:a,to:o}=r.visibleRange;if(a>o||n.length===0)return;let s=r.barWidth,c=s/2,l=s+r.barSpacing,u=-r.offset+r.chartRect.x+c,{min:d,max:f}=r.priceRange;if(f-d===0)return;let p=e=>e*l+u,m=e.E(r),h=m(this.baselinePrice??this.computeBaseline(n,a,o)),{chartRect:g}=r,_=[],v=[];for(let e=a;e<=o&&e<n.length;e++)_.push(p(e)),v.push(m(n[e].close));if(_.length<2)return;let y=_.length-1;t.save();let b=m(f),x=m(d),S=new Path2D;S.rect(g.x,Math.min(h,b),g.width,Math.abs(b-h)),t.clip(S);let C=new Path2D;C.moveTo(_[0],h);for(let e=0;e<=y;e++)C.lineTo(_[e],v[e]);C.lineTo(_[y],h),C.closePath(),t.globalAlpha*=Le,t.fillStyle=i.candleUp,t.fill(C),t.restore(),t.save();let w=new Path2D;w.rect(g.x,Math.min(h,x),g.width,Math.abs(x-h)),t.clip(w);let T=new Path2D;T.moveTo(_[0],h);for(let e=0;e<=y;e++)T.lineTo(_[e],v[e]);T.lineTo(_[y],h),T.closePath(),t.globalAlpha*=Le,t.fillStyle=i.candleDown,t.fill(T),t.restore();let E=new Path2D,D=new Path2D,O=null;for(let e=1;e<=y;e++){let t=r.invertScale?v[e]>=h:v[e]<=h,n=t?E:D;t!==O&&n.moveTo(_[e-1],v[e-1]),O=t,n.lineTo(_[e],v[e])}t.save(),t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`round`,t.strokeStyle=i.candleUp,t.stroke(E),t.strokeStyle=i.candleDown,t.stroke(D),t.restore(),t.setLineDash([6,4]),t.strokeStyle=i.textSecondary,t.lineWidth=1;let k=new Path2D;k.moveTo(g.x,h),k.lineTo(g.x+g.width,h),t.stroke(k),t.setLineDash([])}computeBaseline(e,t,n){let r=0,i=0;for(let a=t;a<=n&&a<e.length;a++)r+=e[a].close,i++;return i>0?r/i:0}},ze=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,s=r.barWidth,c=s/2,l=s+r.barSpacing,u=-r.offset+r.chartRect.x+c,{min:d,max:f}=r.priceRange;if(f-d===0)return;let p=e=>e*l+u,m=e.E(r),h=new Path2D,g=new Path2D,_=new Path2D,v=new Path2D;for(let e=a;e<=o&&e<n.length;e++){let t=n[e],r=p(e),i=t.close>=t.open,a=m(Math.max(t.open,t.close)),o=m(Math.min(t.open,t.close)),l=Math.min(a,o),u=Math.max(Math.abs(o-a),1),d=r-c;i?(h.rect(d,l,s,u),_.rect(d,l,s,u)):(g.rect(d,l,s,u),v.rect(d,l,s,u))}t.fillStyle=i.candleUp,t.fill(h),t.fillStyle=i.candleDown,t.fill(g),t.lineWidth=1,t.strokeStyle=i.candleUp,t.stroke(_),t.strokeStyle=i.candleDown,t.stroke(v)}},Be=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,s=r.barWidth,c=s/2,l=s+r.barSpacing,u=-r.offset+r.chartRect.x+c,{min:d,max:f}=r.priceRange;if(f-d===0)return;let p=e=>e*l+u,m=e.E(r),h=new Path2D,g=new Path2D;for(let e=a;e<=o&&e<n.length;e++){let t=n[e],r=p(e),i=t.close>=t.open,a=m(t.high),s=m(t.low),c=i?s:a,l=i?h:g;l.moveTo(r,i?a:s),l.lineTo(r,c),e<o&&e+1<n.length&&l.lineTo(p(e+1),c)}t.save(),t.lineJoin=`round`,t.strokeStyle=i.candleUp,t.lineWidth=3,t.stroke(h),t.strokeStyle=i.candleDown,t.lineWidth=1,t.stroke(g),t.restore()}},Ve=class{boxSize=1;setBoxSize(e){this.boxSize=e}render(t,n,r,i){let{from:a,to:o}=r.visibleRange,s=r.barWidth,c=s/2,l=s+r.barSpacing,u=-r.offset+r.chartRect.x+c,{min:d,max:f}=r.priceRange,p=f-d;if(p===0||!(this.boxSize>0))return;let m=r.chartRect.height/p,h=e=>e*l+u,g=e.E(r),_=Math.abs(this.boxSize*m),v=Math.min(c*.8,_*.8)*.5,y=new Path2D,b=new Path2D,x=new Path2D;for(let e=a;e<=o&&e<n.length;e++){let t=n[e],r=h(e),i=t.close>=t.open,a=t.high,o=t.low,s=Math.max(1,Math.round((a-o)/this.boxSize)),c=Math.max(0,Math.floor((d-o)/this.boxSize)-1),l=Math.min(s-1,Math.ceil((f-o)/this.boxSize)),u=Math.max(1,Math.ceil(1/_));for(let e=c;e<=l;e+=u){let t=g(o+(e+.5)*this.boxSize);i?(y.moveTo(r-v,t-v),y.lineTo(r+v,t+v),b.moveTo(r+v,t-v),b.lineTo(r-v,t+v)):(x.moveTo(r+v,t),x.arc(r,t,v,0,Math.PI*2))}}t.lineWidth=1.5,t.strokeStyle=i.candleUp,t.stroke(y),t.stroke(b),t.strokeStyle=i.candleDown,t.stroke(x)}},He=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,{min:s,max:c}=r.priceRange;if(c-s===0||a>o||n.length===0)return;if(e.f(r)){e.p(t,n,r,i.candleUp,i.candleDown);return}let l=r.barWidth+r.barSpacing,u=-r.offset+r.chartRect.x+r.barWidth/2,d=r.barWidth,f=0;for(let e=a;e<=o&&e<n.length;e++)n[e].volume>f&&(f=n[e].volume);f===0&&(f=1);let p=e=>e*l+u,m=e.E(r);e.v(t,r=>{let{wick:s}=e.h(d,r.ratio),c=new Path2D,l=new Path2D,u=new Path2D,h=new Path2D;for(let t=a;t<=o&&t<n.length;t++){let i=n[t],a=i.close>=i.open,o=r.left(p(t),s),g=r.y(m(i.high)),_=r.y(m(i.low));(a?c:l).rect(o,Math.min(g,_),s,Math.max(Math.abs(_-g),1));let{body:v}=e.h(d*Math.max(.2,i.volume/f),r.ratio),y=r.y(m(i.open)),b=r.y(m(i.close));(a?u:h).rect(o-(v-s)/2,Math.min(y,b),v,Math.max(Math.abs(b-y),s))}t.fillStyle=i.candleUpWick,t.fill(c),t.fillStyle=i.candleDownWick,t.fill(l),t.fillStyle=i.candleUp,t.fill(u),t.fillStyle=i.candleDown,t.fill(h)})}},Ue=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange,{min:s,max:c}=r.priceRange;if(c-s===0||a>o||n.length===0)return;let l=r.barWidth+r.barSpacing,u=-r.offset+r.chartRect.x+r.barWidth/2,d=r.barWidth,f=0;for(let e=a;e<=o&&e<n.length;e++)n[e].volume>f&&(f=n[e].volume);f===0&&(f=1);let p=new Path2D,m=new Path2D,h=new Path2D,g=new Path2D,_=e=>e*l+u,v=e.E(r);for(let e=a;e<=o&&e<n.length;e++){let t=n[e],r=e>0?n[e-1]:t,i=_(e),a=v(t.high),o=v(t.low),s=t.close>=r.close,c=d*Math.max(.15,t.volume/f),l=c/2,u=Math.min(a,o),y=Math.max(Math.abs(o-a),1),b=s?p:m,x=s?h:g;b.rect(i-l,u,c,y),x.rect(i-l,u,c,y)}t.fillStyle=We(i.candleUp,.55),t.fill(p),t.fillStyle=We(i.candleDown,.55),t.fill(m),t.lineWidth=1,t.strokeStyle=i.candleUpWick,t.stroke(h),t.strokeStyle=i.candleDownWick,t.stroke(g)}};function We(e,t){if(e.startsWith(`#`)){let n=Math.round(Math.max(0,Math.min(1,t))*255).toString(16).padStart(2,`0`);if(e.length===7)return`${e}${n}`;if(e.length===9)return`${e.slice(0,7)}${n}`}return e}var Ge=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange;if(a>o||n.length===0)return;let{min:s,max:c}=r.priceRange;if(c-s===0)return;let l=r.barWidth+r.barSpacing,u=-r.offset+r.chartRect.x+r.barWidth/2,d=e=>e*l+u,f=e.E(r),p=[],m=[];for(let e=a;e<=o&&e<n.length;e++){let t=d(e);p.push({x:t,y:f(n[e].high)}),m.push({x:t,y:f(n[e].low)})}if(p.length===0)return;let h=t.createLinearGradient(0,f(c),0,f(s));h.addColorStop(0,i.areaTopColor),h.addColorStop(1,i.areaBottomColor),t.beginPath(),t.moveTo(p[0].x,p[0].y);for(let e=1;e<p.length;e++)t.lineTo(p[e].x,p[e].y);for(let e=m.length-1;e>=0;e--)t.lineTo(m[e].x,m[e].y);t.closePath(),t.fillStyle=h,t.fill(),t.beginPath(),t.strokeStyle=i.lineColor,t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`round`;for(let e=a;e<=o&&e<n.length;e++){let r=d(e),i=f(n[e].close);e===a?t.moveTo(r,i):t.lineTo(r,i)}t.stroke()}},Ke=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange;if(a>o||n.length===0)return;let{min:s,max:c}=r.priceRange;if(c-s===0)return;let l=r.barWidth+r.barSpacing,u=-r.offset+r.chartRect.x+r.barWidth/2,d=e=>e*l+u,f=e.E(r);t.beginPath(),t.strokeStyle=i.lineColor,t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`miter`;let p=0;for(let e=a;e<=o&&e<n.length;e++){let r=d(e),i=f(n[e].close);e===a?t.moveTo(r,i):(t.lineTo(r,p),t.lineTo(r,i)),p=i}t.stroke()}},qe=class{render(t,n,r,i){let{from:a,to:o}=r.visibleRange;if(a>o||n.length===0)return;let{min:s,max:c}=r.priceRange;if(c-s===0)return;let l=r.barWidth+r.barSpacing,u=-r.offset+r.chartRect.x+r.barWidth/2,d=e=>e*l+u,f=e.E(r);t.beginPath(),t.strokeStyle=i.lineColor,t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`round`;let p=[];for(let e=a;e<=o&&e<n.length;e++){let r=d(e),i=f(n[e].close);p.push({x:r,y:i}),e===a?t.moveTo(r,i):t.lineTo(r,i)}t.stroke();let m=Math.max(2,Math.min(4,r.barWidth*.3));if(l<m*2)return;let h=new Path2D;for(let{x:e,y:t}of p)h.moveTo(e+m,t),h.arc(e,t,m,0,Math.PI*2);t.fillStyle=i.lineColor,t.fill(h),t.strokeStyle=i.background,t.lineWidth=1,t.stroke(h)}},Je=28,Ye=3,Xe=class{priceText=null;setPriceText(e){this.priceText=e}render(n,r,i,a){let{from:o,to:s}=i.visibleRange,{min:c,max:l}=i.priceRange;if(l===c)return;if(e.f(i)){e.p(n,r,i,a.candleUp,a.candleDown);return}let u=i.barWidth+i.barSpacing,d=-i.offset+i.chartRect.x+i.barWidth/2,f=e.E(i),p=Math.max(1,Math.round(i.barWidth*.6)),m=i.barWidth>=Je,h=(0,t.autoPricePrecision)(c,l),g=e=>i.formatPrice?.(e)??this.priceText?.(e)??(0,t.formatPrice)(e,h);m&&(n.font=`${a.font.sizeSmall}px ${a.font.family}`,n.textAlign=`center`);for(let e=Math.max(0,o);e<=s&&e<r.length;e++){let t=r[e],i=e*u+d,o=Math.min(f(t.high),f(t.low)),s=Math.max(f(t.high),f(t.low));if(n.fillStyle=t.close>=t.open?a.candleUp:a.candleDown,n.fillRect(Math.round(i-p/2),o,p,Math.max(1,s-o)),!m)continue;let c=f(t.high)<=f(t.low);n.textBaseline=`bottom`,n.fillText(g(c?t.high:t.low),i,o-Ye),n.textBaseline=`top`,n.fillText(g(c?t.low:t.high),i,s+Ye)}}},Ze=t.PHI**-4.5,Qe=class{visible=!0;heightRatio=Ze;setVisible(e){this.visible=e}isVisible(){return this.visible}setHeightRatio(e){this.heightRatio=Math.max(.05,Math.min(.5,e))}getHeightRatio(){return this.heightRatio}render(n,r,i,a){if(!this.visible||r.length===0)return;let{from:o,to:s}=i.visibleRange,{chartRect:c}=i,l=i.barWidth,u=l+i.barSpacing,d=-i.offset+c.x+l/2,f=0;for(let e=o;e<=s&&e<r.length;e++)r[e].volume>f&&(f=r[e].volume);if(f===0)return;let p=c.y+c.height,m=c.height*this.heightRatio/f;e.v(n,c=>{let f=new Path2D,h=new Path2D,g=c.y(p),_=(e,t,n,r)=>{let i=c.y(p-r*m);g-i>=1&&e.rect(t,i,n,g-i)};if(e.f(i))e.d(r,o,s,e=>e*u+d,e=>{let t=c.x(e.x);_(e.close>=e.open?f:h,t,Math.max(1,c.x(e.x+1)-t),e.volume)});else{let{body:t,wick:n}=e.h(l,c.ratio),i=(t-n)/2;for(let e=o;e<=s&&e<r.length;e++){let a=r[e];_(a.close>=a.open?f:h,c.left(e*u+d,n)-i,t,a.volume)}}let v=(0,t.resolveVolumeColors)(a);n.fillStyle=v.up,n.fill(f),n.fillStyle=v.down,n.fill(h)})}},$e=class{visible=!1;buckets=48;widthRatio=.18;opacity=.32;highlightPoC=!0;setVisible(e){this.visible=e}isVisible(){return this.visible}setBuckets(e){this.buckets=Math.max(8,Math.min(200,Math.floor(e)))}setWidthRatio(e){this.widthRatio=Math.max(.05,Math.min(.5,e))}setOpacity(e){this.opacity=Math.max(.05,Math.min(1,e))}setHighlightPoC(e){this.highlightPoC=e}render(t,n,r,i){if(!this.visible||n.length===0)return;let{from:a,to:o}=r.visibleRange,{chartRect:s,priceRange:c}=r,l=c.max-c.min;if(l<=0)return;let u=new Float64Array(this.buckets),d=new Float64Array(this.buckets),f=new Float64Array(this.buckets);for(let e=a;e<=o&&e<n.length;e++){let t=n[e];if(t.volume<=0)continue;let r=Math.max(t.low,c.min),i=Math.min(t.high,c.max);if(i<=r)continue;let a=(r-c.min)/l,o=(i-c.min)/l,s=Math.max(0,Math.floor(a*this.buckets)),p=Math.min(this.buckets-1,Math.floor(o*this.buckets)),m=Math.max(1,p-s+1),h=t.volume/m,g=t.close>=t.open;for(let e=s;e<=p;e++)u[e]+=h,g?d[e]+=h:f[e]+=h}let p=0,m=-1;for(let e=0;e<u.length;e++)u[e]>p&&(p=u[e],m=e);if(p===0)return;let h=s.width*this.widthRatio,g=s.x+s.width,_=e.E(r),v=1/p;t.save(),t.globalAlpha=this.opacity;for(let n=0;n<this.buckets;n++){let a=u[n];if(a===0)continue;let o=e.w(n,this.buckets,r,_),c=a*v*h,l=d[n]*v*h,p=f[n]*v*h;l>0&&(t.fillStyle=i.candleUp,t.fillRect(g-l,o.top+.5,l,o.height-1)),p>0&&(t.fillStyle=i.candleDown,t.fillRect(g-c,o.top+.5,p,o.height-1)),this.highlightPoC&&n===m&&(t.globalAlpha=1,t.strokeStyle=i.crosshair,t.lineWidth=1,t.setLineDash([3,2]),t.beginPath(),t.moveTo(s.x,o.mid+.5),t.lineTo(g-c-2,o.mid+.5),t.stroke(),t.setLineDash([]),t.globalAlpha=this.opacity)}t.restore()}};function et(e,t){return e<0?0:e>t?t:e}function tt(e,t,n,r={}){let i=Math.max(4,Math.min(500,Math.floor(r.buckets??48))),a=n-t;if(a<=0||e.length===0)return null;let o=a/i,s=new Float64Array(i);for(let r of e){let e=Math.min(r.low,r.high),a=Math.max(r.low,r.high);if(a<t||e>n)continue;let c=et(Math.floor((e-t)/o),i-1),l=et(Math.floor((a-t)/o),i-1);for(let e=c;e<=l;e++)s[e]+=1}let c=0,l=0,u=0;for(let e=0;e<i;e++)u+=s[e],s[e]>l&&(l=s[e],c=e);if(u===0)return null;let d=u*(r.valueAreaPct??.7),f=c,p=c,m=s[c];for(;m<d&&(f>0||p<i-1);){let e=f>0?s[f-1]:-1;(p<i-1?s[p+1]:-1)>=e?(p+=1,m+=s[p]):(--f,m+=s[f])}let h=[];for(let e=0;e<i;e++){let n=t+e*o;h.push({low:n,high:n+o,mid:n+o/2,count:s[e]})}return{buckets:h,pocIndex:c,maxCount:l,totalCount:u,valueAreaLow:t+f*o,valueAreaHigh:t+(p+1)*o}}function nt(e){let t=(e%52+52)%52;return t<26?String.fromCharCode(65+t):String.fromCharCode(97+t-26)}function rt(e,t,n,r=48){let i=Math.max(4,Math.min(500,Math.floor(r))),a=n-t,o=Array.from({length:i},()=>[]);if(a<=0)return o;let s=a/i;return e.forEach((e,r)=>{let a=Math.min(e.low,e.high),c=Math.max(e.low,e.high);if(c<t||a>n)return;let l=Math.max(0,Math.min(i-1,Math.floor((a-t)/s))),u=Math.max(0,Math.min(i-1,Math.floor((c-t)/s)));for(let e=l;e<=u;e++)o[e].push(r)}),o}function it(e,n,r,i={}){if(e.length===0||r-n<=0)return[];let a=[],o=0,s=(0,t.timeframeBucketStart)(e[0].time,`1d`),c=(t,o,s)=>{let c=tt(e.slice(t,o+1),n,r,i);c&&a.push({startIndex:t,endIndex:o,startTime:s,profile:c})};for(let n=1;n<e.length;n++){let r=(0,t.timeframeBucketStart)(e[n].time,`1d`);r!==s&&(c(o,n-1,s),o=n,s=r)}return c(o,e.length-1,s),a}var at=class{visible=!1;buckets=48;widthRatio=.18;opacity=.32;valueAreaPct=.7;highlightPoC=!0;showStats=!0;splitBySession=!1;letters=!1;lastStats=null;setVisible(e){this.visible=e,e||(this.lastStats=null)}isVisible(){return this.visible}setBuckets(e){this.buckets=Math.max(8,Math.min(200,Math.floor(e)))}setWidthRatio(e){this.widthRatio=Math.max(.05,Math.min(.5,e))}setOpacity(e){this.opacity=Math.max(.05,Math.min(1,e))}setValueAreaPct(e){this.valueAreaPct=Math.max(.3,Math.min(.95,e))}setHighlightPoC(e){this.highlightPoC=e}setShowStats(e){this.showStats=e}setSplitBySession(e){this.splitBySession=e}isSplitBySession(){return this.splitBySession}setLetters(e){this.letters=e}drawsText(){return this.splitBySession?this.letters:this.showStats}getStats(){return this.lastStats}render(t,n,r,i){if(!this.visible||n.length===0)return;let{from:a,to:o}=r.visibleRange,{chartRect:s,priceRange:c}=r,l=Math.max(0,a),u=Math.min(o,n.length-1);if(u<l)return;let d=n.slice(l,u+1);if(this.splitBySession){this.lastStats=null,this.renderSplit(t,d,l,r,i);return}let f=tt(d,c.min,c.max,{buckets:this.buckets,valueAreaPct:this.valueAreaPct});if(!f){this.lastStats=null;return}let p=f.buckets[f.pocIndex].mid;this.lastStats={poc:p,vah:f.valueAreaHigh,val:f.valueAreaLow,valueAreaPct:this.valueAreaPct};let m=f.buckets.length,h=s.width*this.widthRatio,g=s.x,_=e.E(r),v=1/f.maxCount;t.save();for(let n=0;n<m;n++){let a=f.buckets[n];if(a.count===0)continue;let o=e.w(n,m,r,_),s=a.count*v*h,c=a.mid>=f.valueAreaLow&&a.mid<=f.valueAreaHigh;t.globalAlpha=c?Math.min(1,this.opacity+.18):this.opacity,t.fillStyle=c?i.candleUp:i.textSecondary,t.fillRect(g,o.top+.5,s,o.height-1)}t.globalAlpha=.6,t.strokeStyle=i.candleUp,t.lineWidth=1,t.setLineDash([1,3]);for(let e of[f.valueAreaHigh,f.valueAreaLow]){let n=_(e);t.beginPath(),t.moveTo(g,Math.round(n)+.5),t.lineTo(s.x+s.width,Math.round(n)+.5),t.stroke()}if(t.setLineDash([]),this.highlightPoC){let e=_(p);t.globalAlpha=1,t.strokeStyle=i.crosshair,t.lineWidth=1,t.setLineDash([3,2]),t.beginPath(),t.moveTo(g,Math.round(e)+.5),t.lineTo(s.x+s.width,Math.round(e)+.5),t.stroke(),t.setLineDash([])}this.showStats&&this.drawStats(t,s.x+6,s.y+6,p,f.valueAreaHigh,f.valueAreaLow,i),t.restore()}renderSplit(t,n,r,i,a){let{chartRect:o,priceRange:s}=i,c=it(n,s.min,s.max,{buckets:this.buckets,valueAreaPct:this.valueAreaPct});if(c.length===0)return;let l=e.E(i),u=i.barWidth/2;t.save();for(let d of c){let c=d.profile,f=c.buckets.length,p=o.height/f,m=e.b(r+d.startIndex,i)-u,h=e.b(r+d.endIndex,i)+u,g=Math.max(2,h-m),_=1/c.maxCount,v=this.letters&&p>=7,y=v?rt(n.slice(d.startIndex,d.endIndex+1),s.min,s.max,this.buckets):null;if(v&&y){t.font=`${Math.min(11,Math.floor(p))}px ui-monospace, monospace`,t.textBaseline=`middle`,t.textAlign=`left`;let n=Math.max(1,Math.floor(g/6));for(let r=0;r<f;r++){let o=y[r];if(o.length===0)continue;let s=e.w(r,f,i,l).mid,u=c.buckets[r].mid>=c.valueAreaLow&&c.buckets[r].mid<=c.valueAreaHigh;t.globalAlpha=u?.95:.6,t.fillStyle=u?a.candleUp:a.textSecondary;let d=Math.min(o.length,n);for(let e=0;e<d;e++)t.fillText(nt(o[e]),m+e*6,s)}}else for(let n=0;n<f;n++){let r=c.buckets[n];if(r.count===0)continue;let o=e.w(n,f,i,l),s=r.count*_*g,u=r.mid>=c.valueAreaLow&&r.mid<=c.valueAreaHigh;t.globalAlpha=u?Math.min(1,this.opacity+.18):this.opacity,t.fillStyle=u?a.candleUp:a.textSecondary,t.fillRect(m,o.top+.5,s,o.height-1)}if(this.highlightPoC){let e=l(c.buckets[c.pocIndex].mid);t.globalAlpha=1,t.strokeStyle=a.crosshair,t.lineWidth=1,t.setLineDash([3,2]),t.beginPath(),t.moveTo(m,Math.round(e)+.5),t.lineTo(Math.min(h,o.x+o.width),Math.round(e)+.5),t.stroke(),t.setLineDash([])}}t.restore()}drawStats(e,t,n,r,i,a,o){let s=ot(r),c=[[`POC`,r.toFixed(s),o.text],[`VAH`,i.toFixed(s),o.candleUp],[`VAL`,a.toFixed(s),o.candleUp]];e.globalAlpha=1,e.font=`600 10px ${o.font.family}`,e.textBaseline=`middle`;let l=0;for(let[,t]of c)l=Math.max(l,e.measureText(t).width);let u=38+l,d=6+c.length*14;e.fillStyle=o.background,e.globalAlpha=.82,st(e,t,n,u,d,4),e.fill(),e.globalAlpha=1,c.forEach(([r,i,a],s)=>{let c=n+6/2+14/2+s*14;e.fillStyle=a,e.textAlign=`left`,e.fillText(r,t+6,c),e.fillStyle=o.text,e.textAlign=`right`,e.fillText(i,t+u-6,c)}),e.textAlign=`left`}};function ot(e){let t=Math.abs(e);return t>=1e3?2:t>=1?4:6}function st(e,t,n,r,i,a){e.beginPath(),e.moveTo(t+a,n),e.arcTo(t+r,n,t+r,n+i,a),e.arcTo(t+r,n+i,t,n+i,a),e.arcTo(t,n+i,t,n,a),e.arcTo(t,n,t+r,n,a),e.closePath()}function ct(e,n){let r=n===`day`?`1d`:`1w`,i=[];for(let n of e){let e=(0,t.timeframeBucketStart)(n.time,r),a=i[i.length-1];a&&a.key===e?(a.high=Math.max(a.high,n.high),a.low=Math.min(a.low,n.low),a.close=n.close):i.push({key:e,open:n.open,high:n.high,low:n.low,close:n.close})}return i}function lt(e,t=`day`){let n=ct(e,t);if(n.length<2)return[];let r=n[n.length-2],i=n[n.length-1],a=t===`day`?`D`:`W`;return[{id:`p${a}h`,label:`P${a}H`,price:r.high},{id:`p${a}c`,label:`P${a}C`,price:r.close},{id:`p${a}l`,label:`P${a}L`,price:r.low},{id:`open`,label:t===`day`?`Day Open`:`Week Open`,price:i.open}]}var ut=class{visible=!1;period=`day`;setVisible(e){this.visible=e}isVisible(){return this.visible}setPeriod(e){this.period=e}getPeriod(){return this.period}render(t,n,r,i){if(!this.visible||n.length===0)return;let a=lt(n,this.period);if(a.length===0)return;let{chartRect:o}=r,s=o.y,c=o.y+o.height;t.save(),t.font=`600 10px ${i.font.family}`,t.textBaseline=`middle`;for(let n of a){let a=e.T(n.price,r);if(a<s||a>c)continue;let l=dt(n,i);t.strokeStyle=l,t.globalAlpha=.7,t.lineWidth=1,t.setLineDash([5,4]),t.beginPath(),t.moveTo(o.x,Math.round(a)+.5),t.lineTo(o.x+o.width,Math.round(a)+.5),t.stroke(),t.setLineDash([]),t.globalAlpha=1;let u=n.label,d=t.measureText(u).width,f=o.x+o.width-d-10;t.fillStyle=i.background,t.globalAlpha=.85,E(t,f-4,a-7,d+8,14,i),t.globalAlpha=1,t.fillStyle=l,t.textAlign=`left`,t.fillText(u,f,a+.5)}t.restore()}};function dt(e,t){return e.id.endsWith(`h`)?t.candleUp:e.id.endsWith(`l`)?t.candleDown:t.textSecondary}function ft(e){let t,n;return e.map(e=>{let r;return e.type===`high`?(r=t===void 0||e.price>t?`HH`:`LH`,t=e.price):(r=n===void 0||e.price<n?`LL`:`HL`,n=e.price),{...e,label:r}})}function pt(e,t=5,n=5){let r=Math.max(1,Math.floor(t)),i=Math.max(1,Math.floor(n)),a=[];for(let t=r;t<e.length-i;t++){let n=e[t].high,o=e[t].low,s=!0,c=!0;for(let a=t-r;a<=t+i&&!(a!==t&&(e[a].high>=n&&(s=!1),e[a].low<=o&&(c=!1),!s&&!c));a++);s?a.push({index:t,price:n,type:`high`}):c&&a.push({index:t,price:o,type:`low`})}return a}var mt=class{visible=!1;left=5;right=5;showLabels=!1;structureLabels=!1;setVisible(e){this.visible=e}isVisible(){return this.visible}setStrength(e,t){this.left=Math.max(1,Math.floor(e)),this.right=Math.max(1,Math.floor(t))}setShowLabels(e){this.showLabels=e}setStructureLabels(e){this.structureLabels=e}render(t,n,r,i){if(!this.visible||n.length===0)return;let a=pt(n,this.left,this.right);if(a.length===0)return;let o=this.structureLabels?ft(a):a,{from:s,to:c}=r.visibleRange;t.save(),t.font=`10px ${i.font.family}`,t.textAlign=`center`;for(let n of o){if(n.index<s-1||n.index>c+1)continue;let a=e.b(n.index,r),o=e.T(n.price,r),l=n.type===`high`,u=l?i.candleDown:i.candleUp,d=l!==(r.invertScale===!0),f=d?o-8:o+8;t.fillStyle=u,t.beginPath(),d?(t.moveTo(a-5,f-5),t.lineTo(a+5,f-5),t.lineTo(a,f)):(t.moveTo(a-5,f+5),t.lineTo(a+5,f+5),t.lineTo(a,f)),t.closePath(),t.fill();let p=this.structureLabels&&`label`in n?String(n.label):this.showLabels?r.formatPrice?.(n.price)??ht(n.price):null;p&&(t.textBaseline=d?`bottom`:`top`,t.fillText(p,a,d?f-5-1:f+5+1))}t.restore()}};function ht(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var gt=class{buffer=[];constructor(e=240){this.capacity=e,this.capacity=Math.max(1,Math.floor(e))}push(e,t){let n={time:e,bids:t.bids.map(e=>({...e})),asks:t.asks.map(e=>({...e}))},r=this.indexAfter(e);if(r>0&&this.buffer[r-1].time===e){this.buffer[r-1]=n;return}this.buffer.splice(r,0,n),this.buffer.length>this.capacity&&(this.buffer=this.buffer.slice(this.buffer.length-this.capacity))}indexAfter(e){let t=this.buffer;if(t.length===0||t[t.length-1].time<=e)return t.length;let n=0,r=t.length;for(;n<r;){let i=n+r>>1;t[i].time<=e?n=i+1:r=i}return n}snapshots(){return this.buffer}maxVolume(){let e=0;for(let t of this.buffer){for(let n of t.bids)n.volume>e&&(e=n.volume);for(let n of t.asks)n.volume>e&&(e=n.volume)}return e}setCapacity(e){this.capacity=Math.max(1,Math.floor(e)),this.buffer.length>this.capacity&&(this.buffer=this.buffer.slice(this.buffer.length-this.capacity))}clear(){this.buffer=[]}get size(){return this.buffer.length}},_t=class{buffer=new gt(240);visible=!1;opacity=.7;setVisible(e){this.visible=e}isVisible(){return this.visible}setOpacity(e){this.opacity=Math.max(.1,Math.min(1,e))}setCapacity(e){this.buffer.setCapacity(e)}push(e,t){this.buffer.push(e,t)}clear(){this.buffer.clear()}render(t,n,r){if(!this.visible)return;let i=this.buffer.snapshots();if(i.length===0)return;let a=this.buffer.maxVolume();if(a<=0)return;let o=1/a,{chartRect:s}=n,c=Math.max(2,n.barWidth+n.barSpacing),l=s.x,u=s.x+s.width,d=s.y,f=s.y+s.height;t.save();for(let a of i){let i=e.O(a.time,n);if(i<l-c||i>u+c)continue;let s=i-c/2;this.drawSide(t,a.bids,r.candleUp,s,c,n,o,d,f),this.drawSide(t,a.asks,r.candleDown,s,c,n,o,d,f)}t.restore()}drawSide(t,n,r,i,a,o,s,c,l){if(n.length===0)return;let u=vt(n,o);t.fillStyle=r;for(let r of n){let n=e.T(r.price,o);n<c-u||n>l+u||(t.globalAlpha=Math.min(1,Math.sqrt(r.volume*s))*this.opacity,t.fillRect(i,n-u/2,a,u))}t.globalAlpha=1}};function vt(t,n){if(t.length<2)return 3;let r=t.map(e=>e.price).sort((e,t)=>e-t),i=[];for(let e=1;e<r.length;e++){let t=r[e]-r[e-1];t>0&&i.push(t)}if(i.length===0)return 3;i.sort((e,t)=>e-t);let a=i[Math.floor(i.length/2)],o=Math.abs(e.T(r[0],n)-e.T(r[0]+a,n));return Math.max(2,Math.min(o,12))}var yt=class{series=new Map;set(e,n){if(!n||n.length===0){this.series.delete(e);return}let r=[...n].sort((e,t)=>e.time-t.time),i=(0,t.barTimeUnit)(r),a=r.map(e=>e.time*i),o=a[a.length-1],s=a.length>1?o-a[a.length-2]:0;this.series.set(e,{bars:r,times:a,end:o+s})}has(e){return this.series.has(e)}get(e){return this.series.get(e)?.bars}symbols(){return[...this.series.keys()]}closeAt(e,n,r){let i=this.series.get(e);if(!i)return;let a=(0,t.normalizeBarTime)(n,r),{times:o,bars:s}=i;if(a<o[0])return;let c=o.length-1;if(a>o[c]&&(i.end<=o[c]||a>=i.end))return;let l=0,u=c;for(;l<u;){let e=l+u+1>>1;o[e]<=a?l=e:u=e-1}return s[l].close}},bt=class{symbols=new Map;mode=`percent`;store=new yt;aligned=new Map;setMode(e){this.mode=e}getMode(){return this.mode}addSymbol(e){this.symbols.set(e.id,e),this.store.set(e.id,e.data),this.aligned.delete(e.id)}removeSymbol(e){this.symbols.delete(e),this.store.set(e,null),this.aligned.delete(e)}setSymbolData(e,t){let n=this.symbols.get(e);n&&(n.data=t,this.store.set(e,t),this.aligned.delete(e))}setSymbolVisible(e,t){let n=this.symbols.get(e);n&&(n.visible=t)}getSymbols(){return Array.from(this.symbols.values())}clear(){for(let e of this.symbols.keys())this.store.set(e,null);this.symbols.clear(),this.aligned.clear()}getPriceRange(e,t){let n=1/0,r=-1/0;for(let i of this.symbols.values()){if(!i.visible||i.data.length===0)continue;let a=this.line(i,e,t);if(a)for(let e=a.from;e<=a.to;e++){let t=a.priceAt(e);t!==null&&(t<n&&(n=t),t>r&&(r=t))}}return n<=r?{min:n,max:r}:null}render(e,t,n,r){if(this.symbols.size===0||t.length===0)return;let{chartRect:i}=n;e.save(),e.beginPath(),e.rect(i.x,i.y,i.width,i.height),e.clip();for(let r of this.symbols.values())!r.visible||r.data.length===0||this.renderSymbol(e,r,t,n);e.restore()}closesOn(e,n){let r=n.length>0?n[n.length-1].time:NaN,i=this.aligned.get(e.id);if(i&&i.main===n&&i.data===e.data&&i.length===n.length&&i.lastTime===r)return i.closes;let a=new Float64Array(n.length),o=(0,t.barTimeUnit)(n);for(let t=0;t<n.length;t++)a[t]=this.store.closeAt(e.id,n[t].time,o)??NaN;return this.aligned.set(e.id,{main:n,data:e.data,length:n.length,lastTime:r,closes:a}),a}line(e,t,n){let r=this.closesOn(e,t),i=Math.max(0,n.visibleRange.from),a=Math.min(t.length-1,n.visibleRange.to),o=-1;for(let e=i;e<=a;e++)if(Number.isFinite(r[e])&&r[e]!==0&&t[e].close!==0){o=e;break}if(o<0)return null;let s=t[o].close,c=r[o],l=this.mode===`percent`;return{from:o,to:a,priceAt:e=>{let t=r[e];return Number.isFinite(t)?l?t/c*s:t:null}}}renderSymbol(t,n,r,i){let a=this.line(n,r,i);if(!a)return;t.strokeStyle=n.color,t.lineWidth=n.lineWidth??1.5,t.lineJoin=`round`,t.beginPath();let o=0,s=null;for(let n=a.from;n<=a.to;n++){let r=a.priceAt(n);if(r===null)continue;let c=e.b(n,i),l=e.T(r,i);o===0?t.moveTo(c,l):t.lineTo(c,l),(o===2||o===0&&s===null)&&(s={x:c+4,y:l-4}),o++}t.stroke(),s&&(t.fillStyle=n.color,t.font=`bold 10px sans-serif`,t.textBaseline=`bottom`,t.textAlign=`left`,t.fillText(n.label,s.x,s.y))}};function xt(e){if(e.length===0)return[];let t=[],n=e[0].open,r=(e[0].open+e[0].high+e[0].low+e[0].close)/4;for(let i=0;i<e.length;i++){let a=e[i],o=(a.open+a.high+a.low+a.close)/4,s=i===0?a.open:(n+r)/2,c=Math.max(a.high,s,o),l=Math.min(a.low,s,o);t.push({time:a.time,open:s,high:c,low:l,close:o,volume:a.volume}),n=s,r=o}return t}function St(e,t){if(e.length===0)return[];let n=t.brickSize;t.useATR&&e.length>2&&(n=Ct(e,t.atrPeriod??14)),n>0||(n=Math.abs(e[e.length-1].close)/100||1);let r=[],i=Math.round(e[0].close/n)*n,a=e[0].time;for(let t=1;t<e.length;t++){let o=e[t].close-i,s=Math.floor(Math.abs(o)/n);if(s>=1){let c=o>0?1:-1;for(let o=0;o<s;o++){let o=i;i+=c*n,r.push({time:a++,open:o,high:Math.max(o,i),low:Math.min(o,i),close:i,volume:e[t].volume/s})}}}return r}function Ct(e,t){let n=e.length-1,r=Math.max(1,n-t),i=0;for(let t=r;t<n;t++)i+=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-e[t-1].close),Math.abs(e[t].low-e[t-1].close));let a=n>r?i/(n-r):0;if(!(a>0))return 0;let o=10**(Math.floor(Math.log10(a))-1);return Math.round(a/o)*o}function wt(e,t=3){if(e.length===0)return[];let n=[],r=0;n.push({time:r++,open:e[0].open,high:Math.max(e[0].open,e[0].close),low:Math.min(e[0].open,e[0].close),close:e[0].close,volume:e[0].volume});for(let i=1;i<e.length;i++){let a=e[i].close,o=n[n.length-1],s=o.close>=o.open,c=Math.min(t,n.length),l=-1/0,u=1/0;for(let e=n.length-c;e<n.length;e++)l=Math.max(l,n[e].high),u=Math.min(u,n[e].low);s&&a>o.close?n.push({time:r++,open:o.close,high:a,low:o.close,close:a,volume:e[i].volume}):!s&&a<o.close||s&&a<u?n.push({time:r++,open:o.close,high:o.close,low:a,close:a,volume:e[i].volume}):!s&&a>l&&n.push({time:r++,open:o.close,high:a,low:o.close,close:a,volume:e[i].volume})}return n}function Tt(e,t=4,n=`percent`){if(e.length<2)return e.slice();let r=[],i=e[1].close>=e[0].close?1:-1,a=e[0].close,o=e[0].close,s=e[0].close,c=0;for(let l=1;l<e.length;l++){let u=e[l].close,d=n===`price`?t:t/100*s;i===1?(u>a&&(a=u),a-u>=d&&(r.push({time:c++,open:s,high:a,low:s,close:a,volume:e[l].volume}),i=-1,s=a,o=u,a=u)):(u<o&&(o=u),u-o>=d&&(r.push({time:c++,open:s,high:s,low:o,close:o,volume:e[l].volume}),i=1,s=o,a=u,o=u))}return i===1?r.push({time:c,open:s,high:a,low:s,close:a,volume:0}):r.push({time:c,open:s,high:s,low:o,close:o,volume:0}),r}function Et(e,t,n=3){if(e.length===0||t<=0)return[];let r=[],i=0,a=0,o=0,s=0,c=Math.round(e[0].close/t)*t;a=c,o=c,i=1;for(let c=1;c<e.length;c++){let l=e[c].close,u=Math.round(l/t)*t;i===1?u>a?a=u:a-u>=t*n&&(r.push({time:s++,open:o,high:a,low:o,close:a,volume:e[c].volume}),i=-1,o=u,a-=t):u<o?o=u:u-o>=t*n&&(r.push({time:s++,open:a,high:a,low:o,close:o,volume:e[c].volume}),i=1,a=u,o+=t)}return r.push({time:s,open:i===1?o:a,high:a,low:o,close:i===1?a:o,volume:0}),r}function Dt(e,t){if(e.length===0||t.rangeSize<=0)return[];let n=[],r=e[0].time,i=e[0].open,a=i,o=i,s=0,c=(e,c)=>{for(e>a&&(a=e),e<o&&(o=e),s+=c;a-o>=t.rangeSize;){let c=e>=i,l=c?i+t.rangeSize:i-t.rangeSize;n.push({time:r++,open:i,high:c?l:i,low:c?i:l,close:l,volume:s}),i=l,a=l,o=l,s=0}};for(let t of e){let e=t.close>=t.open?[t.low,t.high,t.close]:[t.high,t.low,t.close],n=t.volume/e.length;for(let t of e)c(t,n)}return n}function j(e){return e.barWidth+e.barSpacing<1}function Ot(e,t,n){return e>1.5*(Math.abs(n-t)+1)}var M=class{started=!1;lastX=NaN;lastY=NaN;col=NaN;lo=0;hi=0;width;constructor(e,t,n,r,i=[]){this.ctx=e,this.dense=r,this.dash=i,this.width=Number.isFinite(n)&&n>0?n:1,e.beginPath(),r?e.fillStyle=t:(e.strokeStyle=t,e.lineWidth=this.width,e.lineJoin=`round`)}add(e,t){!Number.isFinite(e)||!Number.isFinite(t)||(this.dense?this.addDense(e,t):this.started?this.ctx.lineTo(e,t):this.ctx.moveTo(e,t),this.started=!0,this.lastX=e,this.lastY=t)}gap(){this.flush(),this.started=!1,this.lastY=NaN}segment(e,t,n,r){(!this.started||e!==this.lastX||t!==this.lastY)&&(this.gap(),this.add(e,t)),this.add(n,r)}finish(){this.flush(),this.dense?this.ctx.fill():this.dash.length>0?(this.ctx.setLineDash([...this.dash]),this.ctx.stroke(),this.ctx.setLineDash([])):this.ctx.stroke()}addDense(e,t){let n=Math.floor(e);n!==this.col&&(this.flush(),this.col=n,this.lo=this.hi=Number.isNaN(this.lastY)?t:this.lastY),t<this.lo&&(this.lo=t),t>this.hi&&(this.hi=t)}flush(){if(Number.isNaN(this.col))return;let e=this.width/2,t=Math.max(1,this.width);this.ctx.rect(this.col+.5-t/2,this.lo-e,t,this.hi-this.lo+2*e),this.col=NaN}};function kt(e,t,n,r,i,a=t.length){e.beginPath(),e.fillStyle=i;let o=NaN,s=0,c=0,l=NaN,u=NaN,d=()=>{Number.isNaN(o)||e.rect(o,s,1,c-s)};for(let e=0;e<a;e++){let i=Math.floor(t[e]),a=Math.min(n[e],r[e]),f=Math.max(n[e],r[e]);i!==o&&(d(),o=i,s=Number.isNaN(l)?a:Math.min(a,l),c=Number.isNaN(u)?f:Math.max(f,u)),a<s&&(s=a),f>c&&(c=f),l=a,u=f}d(),e.fill()}var At=.1;function jt(e){return e.plots?e.plots.map(e=>e.key):null}function Mt(e,t){return e.tone?e.tone===`sign`?(t[e.key]??0)>=0:t[e.tone.field]===1:!0}function Nt(e,t){return t.plots?.[e.key]?.visible!==!1}var Pt=[6,4];function N(e,n,r){let i=e.plots?.[n];return{visible:i?.visible!==!1,dash:(0,t.lineDash)(i?.lineStyle??`solid`,Pt,r)}}function Ft(e,t,n){let r=t.colors[e.color]??t.colors[0];return!e.tone||e.downColor===void 0||!n||Mt(e,n)?r:t.colors[e.downColor]??r}function It(e,t,n,r){let{lo:i,hi:a}=Rt(e,t,n,r.keys),o=r.scale,s=o?.min,c=o?.max;if(i===1/0){if(s===void 0&&c===void 0)return null;i=s??0,a=c??i+1}else{let e=a-i||Math.abs(a)||1;i-=e*At,a+=e*At}for(let e of r.levels??[])e<i&&(i=e),e>a&&(a=e);return(r.zero||o?.zero)&&(i>0&&(i=0),a<0&&(a=0)),s!==void 0&&(i=s),c!==void 0&&(a=c),a>i||(a=i+1),{min:i,max:a}}function Lt(e,t,n,r){let{lo:i,hi:a}=Rt(e,t,n,r.keys),o=e=>e!==void 0&&e>0,s=o(r.scale?.min)?r.scale?.min:void 0,c=o(r.scale?.max)?r.scale?.max:void 0;if(i===1/0){if(s===void 0||c===void 0)return null;i=s,a=c}else{if(!(i>0))return!1;let e=Math.exp((Math.log(a/i)||Math.LN2/4)*At);i/=e,a*=e}for(let e of r.levels??[])e>0&&(e<i&&(i=e),e>a&&(a=e));return s!==void 0&&(i=s),c!==void 0&&(a=c),a>i?{min:i,max:a}:null}function Rt(e,t,n,r){let i=1/0,a=-1/0,o=e=>{e===void 0||!Number.isFinite(e)||(e<i&&(i=e),e>a&&(a=e))},s=e=>{if(e){if(r){for(let t=0;t<r.length;t++)o(e[r[t]]);return}for(let t in e)o(e[t])}},c=e?.series;if(c){let e=Math.min(n,c.length-1);for(let n=Math.max(0,t);n<=e;n++)s(c[n])}else if(e){let r=0;for(let i of e.values.values()){if(r>n)break;r>=t&&s(i),r++}}return{lo:i,hi:a}}function zt(e){return!!e?.some(e=>e.kind===`histogram`)}function Bt(n,r,i,a,o){let s=r.series;if(!s)return;let c=Math.max(0,i.visibleRange.from),l=Math.min(i.visibleRange.to,s.length-1);if(l<c)return;let u=e.E(i);for(let e=0;e<o.length;e++){let r=o[e];if(!Nt(r,a))continue;let d=a.lineWidths[e]??a.lineWidths[0]??1.5,f=(0,t.lineDash)(a.plots?.[r.key]?.lineStyle??`solid`,Pt,d),p=r.kind??`line`,m=r.tone&&r.downColor!==void 0?[!0,!1]:[null];for(let e of m){let t=a.colors[r.color]??a.colors[0],o=e===!1?a.colors[r.downColor]??t:t,m=t=>e===null||Mt(r,t)===e;p===`histogram`?Wt(n,s,r.key,c,l,i,u,o,m):p===`dots`?Ut(n,s,r.key,c,l,i,u,o,m):Ht(n,s,r.key,c,l,i,u,o,d,p===`step`,e===null?null:m,f)}}}function Vt(e,t){let n=e?.[t];return n!==void 0&&Number.isFinite(n)?n:void 0}function Ht(t,n,r,i,a,o,s,c,l,u,d,f=[]){let p=new M(t,c,l,j(o),f),m=0,h=0,g=!1;for(let t=i;t<=a;t++){let i=n[t],a=Vt(i,r);if(a===void 0){g=!1,p.gap();continue}let c=e.b(t,o),l=s(a);d?g&&d(i)&&(u?(p.segment(m,h,c,h),p.add(c,l)):p.segment(m,h,c,l)):(g&&u&&p.add(c,h),p.add(c,l)),m=c,h=l,g=!0}p.finish()}function Ut(t,n,r,i,a,o,s,c,l){let u=Math.max(1.5,o.barWidth*.15),d=j(o),f=NaN;t.beginPath(),t.fillStyle=c;for(let c=i;c<=a;c++){let i=n[c],a=Vt(i,r);if(a===void 0||!l(i))continue;let p=e.b(c,o);if(d){let e=Math.floor(p);if(e===f)continue;f=e}let m=s(a);t.moveTo(p+u,m),t.arc(p,m,u,0,Math.PI*2)}t.fill()}function Wt(t,n,r,i,a,o,s,c,l){let u=s(0);if(t.beginPath(),t.fillStyle=c,j(o)){let c=NaN,d=0,f=()=>{if(Number.isNaN(c))return;let e=s(d);t.rect(c,Math.min(e,u),1,Math.max(1,Math.abs(e-u)))};for(let t=i;t<=a;t++){let i=n[t],a=Vt(i,r);if(a===void 0||!l(i))continue;let s=Math.floor(e.b(t,o));s===c?Math.abs(a)>Math.abs(d)&&(d=a):(f(),c=s,d=a)}f(),t.fill();return}let d=Math.max(1,o.barWidth);for(let c=i;c<=a;c++){let i=n[c],a=Vt(i,r);if(a===void 0||!l(i))continue;let f=e.b(c,o),p=s(a);t.rect(f-d/2,Math.min(p,u),d,Math.max(1,Math.abs(p-u)))}t.fill()}var P=class{canResume(e,t,n){let r=t.series;if(!r||n<=0||n>r.length||r.length>e.length)return!1;for(let i=n;i<r.length;i++)if(r[i]&&!t.values.has(e[i].time))return!1;return!0}writePoint(e,t,n,r){e.series[n]=r,r?e.values.set(t[n].time,r):e.values.delete(t[n].time)}render(e,t,n,r){this.descriptor.plots&&Bt(e,t,n,r,this.descriptor.plots)}drawLine(e,t,n,r,i){if(t.length<2||i?.visible===!1)return;let a=new M(e,n,r,Ot(t.length,t[0].x,t[t.length-1].x),i?.dash);for(let e of t)a.add(e.x,e.y);a.finish()}drawBand(e,t,n,r){if(!(t.length<2||n.length<2)){if(t.length===n.length&&Ot(t.length,t[0].x,t[t.length-1].x)){kt(e,t.map(e=>e.x),t.map(e=>e.y),n.map(e=>e.y),r);return}e.beginPath(),e.moveTo(t[0].x,t[0].y);for(let n=1;n<t.length;n++)e.lineTo(t[n].x,t[n].y);for(let t=n.length-1;t>=0;t--)e.lineTo(n[t].x,n[t].y);e.closePath(),e.fillStyle=r,e.fill()}}drawHistogram(e,t,n){let r=n/2;for(let i of t){e.fillStyle=i.color;let t=Math.min(i.y,i.baseY),a=Math.abs(i.y-i.baseY);e.fillRect(i.x-r,t,n,Math.max(a,1))}}valuesToPoints(t,n,r,i){let a=[],{from:o,to:s}=i.visibleRange;for(let c=o;c<=s&&c<r.length;c++){let o=t.values.get(r[c].time);o&&o[n]!==void 0&&a.push({x:e.b(c,i),y:e.T(o[n],i)})}return a}};function Gt(e){let t=e.inputs;if(!t)return null;for(let e in t)if(t[e]?.source)return e;return null}function Kt(e,n){let r=Gt(e);if(!r)return{kind:`bars`};let i=n[r],a=(0,t.parseIndicatorSource)(i);return a?{kind:`line`,...a}:(0,t.isPriceSource)(i)&&i!==`close`?{kind:`price`,source:i}:{kind:`bars`}}function qt(e,n,r=null,i=0){let a=r&&i>0&&i<=r.length?r:[],o=a===r?i:0;a.length=e.length;for(let r=o;r<e.length;r++){let i=e[r];a[r]={...i,close:(0,t.sourcePrice)(i,n)}}return a}function Jt(e,t,n){if(!t)return null;let r=-1;for(let i=0;i<e.length&&i<t.length;i++){let e=t[i]?.[n];if(e!==void 0&&Number.isFinite(e)){r=i;break}}if(r<0)return null;let i=Array(e.length-r),a=t[r][n];for(let o=r;o<e.length;o++){let s=t[o]?.[n];s!==void 0&&Number.isFinite(s)&&(a=s);let c=e[o];i[o-r]={time:c.time,open:a,high:a,low:a,close:a,volume:c.volume}}return{bars:i,start:r}}function Yt(e,t,n){if(t===0||!e.series)return e;let r=Array(n).fill(null);for(let i=0;i<e.series.length&&t+i<n;i++)r[t+i]=e.series[i];return{...e,series:r}}function Xt(e){return{values:new Map,series:Array(e).fill(null)}}var Zt=[`ticks`,`seconds`,`minutes`,`hours`,`days`,`weeks`,`months`],Qt={ticks:1e6,seconds:59,minutes:59,hours:24,days:366,weeks:52,months:12},$t={s:`seconds`,m:`minutes`,h:`hours`,d:`days`,w:`weeks`,M:`months`};function en(e){let n=(0,t.tickBarCount)(e);if(n!==null)return{unit:`ticks`,count:n};let r=(0,t.parseTimeframe)(e);return r?{unit:$t[r.unit],count:r.count}:null}function tn(e,t){if(!e||!t)return!0;let n=en(t);if(!n)return!0;let r=e[n.unit];return r===void 0?!0:r===!1?!1:n.count>=r[0]&&(n.count<=r[1]||r[1]>=Qt[n.unit])}function nn(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=e,n={};for(let e of Zt){let r=t[e];if(r===!1){n[e]=!1;continue}if(!Array.isArray(r)||r.length!==2||!r.every(e=>typeof e==`number`&&Number.isFinite(e)))continue;let i=Qt[e],[a,o]=r.map(e=>Math.min(i,Math.max(1,Math.round(e)))).sort((e,t)=>e-t);(a>1||o<i)&&(n[e]=[a,o])}return Object.keys(n).length>0?n:null}function rn(e){return[...t.TC_SERIES_COLORS.slice(e),...t.TC_SERIES_COLORS.slice(0,e)]}function an(e){let n=t.TC_SERIES_COLORS.length;if(e.length!==n)return!1;let r=t.TC_SERIES_COLORS.indexOf(e[0]);return r>=0&&e.every((e,i)=>e===t.TC_SERIES_COLORS[(r+i)%n])}function on(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t}]))}function sn(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t===!1?!1:[t[0],t[1]]]))}var cn=1,ln=class{registry=new Map;instances=new Map;styleDefaults=new Map;order=null;pending=null;timeframe=null;register(e){this.registry.set(e.descriptor.id,e)}getAvailableIndicators(){return Array.from(this.registry.values()).map(e=>e.descriptor)}addIndicator(e,t={},n,r={}){let i=this.registry.get(e);if(!i)throw Error(`Unknown indicator: ${e}`);let a=this.claimInstanceId(e,r.instanceId),o={id:e,instanceId:a,params:{...i.descriptor.defaultConfig,...t},visible:!0};r.pane&&this.canHost(r.pane)&&(o.pane=r.pane),r.scale===`left`&&i.descriptor.placement===`overlay`&&!o.pane&&(o.scale=`left`);let s=this.styleDefaults.get(e),c={...s?.plots,...o.style?.plots},l={colors:o.style?.colors??s?.colors?.slice()??rn(this.freeColor(e,i.descriptor.placement,o.pane??null)),lineWidths:o.style?.lineWidths??s?.lineWidths?.slice()??[1.5],opacity:o.style?.opacity??s?.opacity??1,...Object.keys(c).length>0?{plots:on(c)}:{}};this.flush();let u={plugin:i,config:o,output:null,style:l,changedFrom:0,offInterval:!1};return this.instances.set(a,u),this.order=null,n&&this.compute(u,n),a}removeIndicator(e){this.instances.delete(e),this.order=null}updateIndicator(e,t,n){this.flush();let r=this.instances.get(e);if(!r)return;let i=Gt(r.plugin.descriptor);if(i&&i in t&&this.readsFromItself(e,{...r.config.params,...t})){let{[i]:e,...n}=t;t=n}if(Object.assign(r.config.params,t),delete r.sourceBars,delete r.lineInput,this.order=null,!n)return;let a=new Set([e,...this.getDependents(e)]);for(let e of this.ordered())a.has(e.config.instanceId)&&this.compute(e,n)}recalculateAll(e){this.pending=null;for(let t of this.ordered())this.compute(t,e)}deferRecalculateFrom(e,t){let n=this.pending;if(n&&n.data===e){n.from=Math.min(n.from,t);return}this.flush(),this.pending={data:e,from:t}}flush(){let e=this.pending;if(e){this.pending=null;for(let t of this.ordered())this.compute(t,e.data,e.from)}}recalculateFrom(e,t){this.deferRecalculateFrom(e,t),this.flush()}compute(e,t,n){let{plugin:r,config:i}=e,a=Kt(r.descriptor,i.params);if(a.kind===`line`){this.computeFromLine(e,t,a.instanceId,a.key,n);return}delete e.lineInput;let o=t;a.kind===`price`?(e.sourceBars=qt(t,a.source,e.sourceBars??null,n??0),o=e.sourceBars):delete e.sourceBars;let s=e.output,c=null;n!==void 0&&n>0&&s&&r.update&&(c=r.update(o,i,s,n)),e.changedFrom=c?Math.max(0,n-(r.revisesBefore?.(i)??0)):0,e.output=c??r.calculate(o,i)}computeFromLine(e,t,n,r,i){let{plugin:a,config:o}=e,s=this.instances.get(n),c=s?.output?.series,l=e.lineInput,u=i===void 0?void 0:Math.min(i,s?.changedFrom??0);if(u!==void 0&&c&&a.update&&l&&l.raw.series&&l.aligned.series&&l.sourceId===n&&l.key===r&&l.start<u&&u<=l.start+l.bars.length){let{start:n,bars:i}=l;i.length=t.length-n;let s=i[u-1-n].close;for(let e=u;e<t.length;e++){let a=c[e]?.[r];a!==void 0&&Number.isFinite(a)&&(s=a),i[e-n]={time:t[e].time,open:s,high:s,low:s,close:s,volume:t[e].volume}}let d=a.update(i,o,l.raw,u-n);if(d?.series){let r=Math.max(n,u-(a.revisesBefore?.(o)??0));if(l.raw=d,n===0)l.aligned=d;else{let e=l.aligned.series;e.length=t.length;for(let i=r;i<t.length;i++)e[i]=d.series[i-n]??null;l.aligned.values=d.values,l.aligned.meta=d.meta}e.output=l.aligned,e.changedFrom=r;return}}e.changedFrom=0;let d=Jt(t,c,r);if(!d){delete e.lineInput,e.output=Xt(t.length);return}let f=a.calculate(d.bars,o),p=Yt(f,d.start,t.length);e.lineInput={sourceId:n,key:r,start:d.start,bars:d.bars,raw:f,aligned:p},e.output=p}ordered(){if(this.order)return this.order;let e=[],t=new Map,n=r=>{let i=r.config.instanceId;if(t.get(i))return;t.set(i,`visiting`);let a=Kt(r.plugin.descriptor,r.config.params),o=a.kind===`line`?this.instances.get(a.instanceId):void 0;o&&n(o),t.set(i,`done`),e.push(r)};for(let e of this.instances.values())n(e);return this.order=e,e}readsFromItself(e,t){let n=this.instances.get(e);if(!n)return!1;let r=Kt(n.plugin.descriptor,t),i=new Set;for(;r.kind===`line`;){if(r.instanceId===e)return!0;if(i.has(r.instanceId))return!1;i.add(r.instanceId);let t=this.instances.get(r.instanceId);if(!t)return!1;r=Kt(t.plugin.descriptor,t.config.params)}return!1}canHost(e){let t=this.instances.get(e);return!!t&&t.plugin.descriptor.placement===`panel`&&!t.config.pane}getDependents(e){let t=[],n=new Set([e]),r=[e];for(;r.length;){let e=r.shift();for(let i of this.instances.values()){let a=Kt(i.plugin.descriptor,i.config.params),o=i.config.instanceId;a.kind===`line`&&a.instanceId===e&&!n.has(o)&&(n.add(o),t.push(o),r.push(o))}}return t}claimInstanceId(e,t){if(t&&!this.instances.has(t)){let e=Number(/_(\d+)$/.exec(t)?.[1]);return Number.isSafeInteger(e)&&e>=cn&&(cn=e+1),t}let n=`tc_${e}_${cn++}`;for(;this.instances.has(n);)n=`tc_${e}_${cn++}`;return n}getPaneMembers(e){let t=[];for(let n of this.instances.values())n.config.pane===e&&t.push(n.config.instanceId);return t}setPane(e,t){let n=this.instances.get(e);if(!n||t===e||t!==null&&!this.canHost(t))return!1;if(t===null?delete n.config.pane:(n.config.pane=t,delete n.config.scale),an(n.style.colors)){let t=n.plugin.descriptor.placement,r=n.config.pane??null;this.colorsInPane(t,r,e).has(n.style.colors[0])&&(n.style.colors=rn(this.freeColor(n.config.id,t,r,e)))}return!0}colorsInPane(e,t,n){let r=new Set;for(let i of this.instances.values())i.config.instanceId!==n&&(t===null?e===`overlay`&&i.plugin.descriptor.placement===`overlay`&&!i.config.pane:i.config.instanceId===t||i.config.pane===t)&&r.add(i.style.colors[0]);return r}freeColor(e,n,r,i){let a=this.colorsInPane(n,r,i);for(let t of this.instances.values())t.config.id===e&&t.config.instanceId!==i&&a.add(t.style.colors[0]);let o=t.TC_SERIES_COLORS.findIndex(e=>!a.has(e));return o>=0?o:a.size%t.TC_SERIES_COLORS.length}getOutput(e){return this.flush(),this.instances.get(e)?.output??null}renderOverlays(e,t,n){for(let r of this.overlayDraws(t,n))r(e)}overlayDraws(e,t){this.flush();let n=[];for(let r of this.instances.values()){let i=r.output;if(!i||!un(r)||r.plugin.descriptor.placement!==`overlay`||r.config.pane)continue;let a=r.config.scale===`left`?t??e:e;n.push(e=>r.plugin.render(e,i,a,r.style))}return n}hasLeftScaleOverlays(){for(let e of this.instances.values())if(e.config.scale===`left`&&un(e))return!0;return!1}setScale(e,t){let n=this.instances.get(e);return!n||n.plugin.descriptor.placement!==`overlay`||n.config.pane?!1:(t===`left`?n.config.scale=`left`:delete n.config.scale,!0)}renderPanel(e,t,n){this.flush();let r=this.instances.get(t);!r?.output||!un(r)||r.plugin.render(e,r.output,n,r.style)}getLatestValues(e){this.flush();let t=this.instances.get(e);return t?fn(t):[]}getLatestOverlayValues(e=`right`){this.flush();let t=[];for(let n of this.instances.values())n.plugin.descriptor.placement!==`overlay`||n.config.pane||n.config.scale===`left`==(e===`left`)&&t.push(...fn(n));return t}getIndicatorConfig(e){return this.instances.get(e)?.config??null}setVisible(e,t){let n=this.instances.get(e);return n?(n.config.visible=t,t):null}isVisible(e){return this.instances.get(e)?.config.visible??!1}isShown(e){let t=this.instances.get(e);return t?un(t):!1}setTimeframe(e){this.timeframe=e;let t=!1;for(let e of this.instances.values())t=this.placeOnInterval(e)||t;return t}setIntervals(e,t){let n=this.instances.get(e);if(!n)return!1;let r=t?nn(t):null;return r?n.config.intervals=r:delete n.config.intervals,this.placeOnInterval(n),!0}getIntervals(e){let t=this.instances.get(e)?.config.intervals;return t?sn(t):null}placeOnInterval(e){let t=!tn(e.config.intervals,this.timeframe);return t===e.offInterval?!1:(e.offInterval=t,!0)}getLevels(e){let t=this.instances.get(e);return t?[...t.config.levels??t.plugin.descriptor.levels??[]]:[]}setLevels(e,t){let n=this.instances.get(e);return n?(t===null?delete n.config.levels:n.config.levels=t.filter(e=>Number.isFinite(e)),!0):!1}getPaneValueRange(e,t,n,r=!1){this.flush();let i=null;for(let a of[e,...this.getPaneMembers(e)]){let e=this.instances.get(a);if(!e||!un(e))continue;let o=e.plugin.descriptor,s={keys:dn(e),scale:o.scale,levels:e.config.levels??o.levels,zero:zt(o.plots)},c=r?Lt(e.output,t,n,s):It(e.output,t,n,s);if(c===!1)return null;c&&(i=i?{min:Math.min(i.min,c.min),max:Math.max(i.max,c.max)}:c)}return i}getIndicatorDescriptor(e){return this.instances.get(e)?.plugin.descriptor??null}getActiveIndicators(){let e=[];for(let[t,n]of this.instances)e.push({instanceId:t,id:n.config.id,params:{...n.config.params},descriptor:n.plugin.descriptor,visible:n.config.visible??!0,shown:un(n),...n.config.intervals?{intervals:sn(n.config.intervals)}:{},...n.config.pane?{pane:n.config.pane}:{}});return e}getIndicatorStyle(e){let t=this.instances.get(e)?.style;return t?{colors:[...t.colors],lineWidths:[...t.lineWidths],opacity:t.opacity,...t.plots?{plots:on(t.plots)}:{}}:null}updateIndicatorStyle(e,t){let n=this.instances.get(e);if(!n)return;let{plots:r,...i}=t;if(Object.assign(n.style,i),r){let e=on(n.style.plots??{});for(let[t,n]of Object.entries(r))e[t]={...e[t],...n};n.style.plots=e}}setPlotStyles(e,t){let n=this.instances.get(e);n&&(t&&Object.keys(t).length>0?n.style.plots=on(t):delete n.style.plots)}setStyleDefaults(e,t){t?this.styleDefaults.set(e,{...t,...t.plots?{plots:on(t.plots)}:{}}):this.styleDefaults.delete(e)}getOverlayPriceRange(e,t,n=`right`){this.flush();let r=1/0,i=-1/0;for(let a of this.instances.values()){if(!a.output||!un(a)||a.plugin.descriptor.placement!==`overlay`||a.config.pane||a.config.scale===`left`!=(n===`left`))continue;let o=a.output.series;if(!o)continue;let s=dn(a),c=Math.min(t,o.length-1);for(let t=Math.max(0,e);t<=c;t++){let e=o[t];if(e){if(s){for(let t=0;t<s.length;t++){let n=e[s[t]];n!==void 0&&isFinite(n)&&(n<r&&(r=n),n>i&&(i=n))}continue}for(let t in e){let n=e[t];n!==void 0&&isFinite(n)&&(n<r&&(r=n),n>i&&(i=n))}}}}return r===1/0?null:{min:r,max:i}}getPanelIndicators(){let e=[];for(let[t,n]of this.instances)n.plugin.descriptor.placement===`panel`&&e.push({instanceId:t,descriptor:n.plugin.descriptor});return e}};function un(e){return e.config.visible!==!1&&!e.offInterval}function dn(e){let t=jt(e.plugin.descriptor),n=e.style.plots;return t&&n?t.filter(e=>n[e]?.visible!==!1):t}function fn(e){let t=e.output?.series,n=e.plugin.descriptor.plots;if(!t||!n||!un(e))return[];let r=t[t.length-1];if(!r)return[];let i=[];for(let t of n){if(!Nt(t,e.style))continue;let n=r[t.key];n!==void 0&&Number.isFinite(n)&&i.push({value:n,color:Ft(t,e.style,r)})}return i}var F=class extends Map{keyBuf=[];valBuf=[];folded=!1;constructor(){super()}set(e,t){if(this.folded)return super.set(e,t);let n=this.keyBuf,r=n.length;if(r===0||e>n[r-1])return n.push(e),this.valBuf.push(t),this;let i=this.indexOf(e);return i>=0?(this.valBuf[i]=t,this):(this.fold(),super.set(e,t))}get(e){if(this.folded)return super.get(e);let t=this.indexOf(e);return t>=0?this.valBuf[t]:void 0}has(e){return this.folded?super.has(e):this.indexOf(e)>=0}delete(e){if(this.folded)return super.delete(e);let t=this.indexOf(e);return t<0?!1:(this.keyBuf.splice(t,1),this.valBuf.splice(t,1),!0)}clear(){super.clear(),this.keyBuf=[],this.valBuf=[],this.folded=!1}get size(){return this.folded?super.size:this.keyBuf.length}forEach(e,t){this.fold(),super.forEach(e,t)}entries(){return this.fold(),super.entries()}keys(){return this.fold(),super.keys()}values(){return this.fold(),super.values()}[Symbol.iterator](){return this.fold(),super[Symbol.iterator]()}indexOf(e){let t=this.keyBuf,n=0,r=t.length-1;for(;n<=r;){let i=n+r>>1,a=t[i];if(a===e)return i;a<e?n=i+1:r=i-1}return-1}fold(){if(this.folded)return;this.folded=!0;let e=this.keyBuf,t=this.valBuf;for(let n=0;n<e.length;n++)super.set(e[n],t[n]);this.keyBuf=[],this.valBuf=[]}};function I(e,t,n){let r=e.params[t];if(typeof r==`number`&&Number.isFinite(r))return r;if(typeof r==`string`){let e=Number(r);if(Number.isFinite(e))return e}return n}function L(e,t,n,r=1){let i=I(e,t,n);return Math.max(r,Math.floor(i))}var pn=class extends P{descriptor={id:`sma`,name:`Simple Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`SMA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`SMA`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null),a=0;for(let t=0;t<e.length;t++)if(a+=e[t].close,t>=n&&(a-=e[t-n].close),t>=n-1){let o={value:a/n};r.set(e[t].time,o),i[t]=o}return{values:r,series:i}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=L(t,`period`,20,1);for(let t=r;t<e.length;t++){if(t<i-1){this.writePoint(n,e,t,null);continue}let r=0;for(let n=t-i+1;n<=t;n++)r+=e[n].close;this.writePoint(n,e,t,{value:r/i})}return n}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},mn=class extends P{descriptor={id:`ema`,name:`Exponential Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`EMA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`EMA`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=2/(n+1),i=new F,a=Array(e.length).fill(null),o=0;for(let t=0;t<e.length;t++){if(t<n-1){o+=e[t].close;continue}o=t===n-1?(o+e[t].close)/n:(e[t].close-o)*r+o;let s={value:o};i.set(e[t].time,s),a[t]=s}return{values:i,series:a}}update(e,t,n,r){let i=L(t,`period`,20,1);if(r<i||!this.canResume(e,n,r))return null;let a=n.series[r-1]?.value;if(a===void 0)return null;let o=2/(i+1);for(let t=r;t<e.length;t++)a=(e[t].close-a)*o+a,this.writePoint(n,e,t,{value:a});return n}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},hn=class extends P{descriptor={id:`bb`,name:`Bollinger Bands`,placement:`overlay`,defaultConfig:{period:20,stdDev:2,source:`close`},shortName:`BB`,inputs:{source:{source:!0}},plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=I(t,`stdDev`,2),i=new F,a=Array(e.length).fill(null),o=0,s=0;for(let t=0;t<e.length;t++){let c=e[t].close;if(o+=c,s+=c*c,t>=n){let r=e[t-n].close;o-=r,s-=r*r}if(t>=n-1){let c=o/n,l=s/n-c*c,u=Math.sqrt(Math.max(0,l)),d={middle:c,upper:c+r*u,lower:c-r*u};i.set(e[t].time,d),a[t]=d}}return{values:i,series:a}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=L(t,`period`,20,1),a=I(t,`stdDev`,2);for(let t=r;t<e.length;t++){if(t<i-1){this.writePoint(n,e,t,null);continue}let r=0,o=0;for(let n=t-i+1;n<=t;n++){let t=e[n].close;r+=t,o+=t*t}let s=r/i,c=Math.sqrt(Math.max(0,o/i-s*s));this.writePoint(n,e,t,{middle:s,upper:s+a*c,lower:s-a*c})}return n}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=0,u=c-s+1,d=new Float64Array(u),f=new Float64Array(u),p=new Float64Array(u),m=new Float64Array(u);for(let t=s;t<=c&&t<o.length;t++){let n=o[t];!n||n.upper===void 0||(d[l]=e.b(t,i),f[l]=e.T(n.upper,i),p[l]=e.T(n.middle,i),m[l]=e.T(n.lower,i),l++)}if(l<2)return;let h=j(i),g=d.subarray(0,l);if(h)kt(n,g,f,m,(0,t.withAlpha)(a.colors[0],.1),l);else{n.beginPath(),n.moveTo(d[0],f[0]);for(let e=1;e<l;e++)n.lineTo(d[e],f[e]);for(let e=l-1;e>=0;e--)n.lineTo(d[e],m[e]);n.closePath(),n.fillStyle=(0,t.withAlpha)(a.colors[0],.1),n.fill()}let _=(e,t,r)=>{let i=N(a,r,a.lineWidths[0]);if(!i.visible)return;let o=new M(n,t,a.lineWidths[0],h,i.dash);for(let t=0;t<l;t++)o.add(g[t],e[t]);o.finish()};_(f,a.colors[0],`upper`),_(p,a.colors[1]??a.colors[0],`middle`),_(m,a.colors[0],`lower`)}},gn=class extends P{descriptor={id:`vwap`,name:`Volume Weighted Average Price`,placement:`overlay`,defaultConfig:{},shortName:`VWAP`,plots:[{key:`value`,title:`VWAP`,color:0}]};calculate(e,t){let n=new F,r=Array(e.length).fill(null),i=0,a=0;for(let t=0;t<e.length;t++){let o=(e[t].high+e[t].low+e[t].close)/3;if(i+=e[t].volume,a+=o*e[t].volume,i>0){let o={value:a/i};n.set(e[t].time,o),r[t]=o}}return{values:n,series:r}}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},_n=class extends P{descriptor={id:`ichimoku`,name:`Ichimoku Cloud`,placement:`overlay`,defaultConfig:{tenkan:9,kijun:26,senkou:52,displacement:26},shortName:`Ichimoku`,plots:[{key:`tenkan`,title:`Conversion`,color:0},{key:`kijun`,title:`Base`,color:1},{key:`senkouA`,title:`Lead A`,color:2},{key:`senkouB`,title:`Lead B`,color:3}]};calculate(e,t){let n=L(t,`tenkan`,9,1),r=L(t,`kijun`,26,1),i=L(t,`senkou`,52,1),a=new F,o=Array(e.length).fill(null),s=t=>{let n=new Float64Array(e.length),r=new Float64Array(e.length);for(let i=0;i<e.length;i++){let a=-1/0,o=1/0,s=Math.max(0,i-t+1);for(let t=s;t<=i;t++)e[t].high>a&&(a=e[t].high),e[t].low<o&&(o=e[t].low);n[i]=a,r[i]=o}return{highs:n,lows:r}},c=s(n),l=s(r),u=s(i);for(let t=0;t<e.length;t++){let s={};t>=n-1&&(s.tenkan=(c.highs[t]+c.lows[t])/2),t>=r-1&&(s.kijun=(l.highs[t]+l.lows[t])/2),s.tenkan!==void 0&&s.kijun!==void 0&&(s.senkouA=(s.tenkan+s.kijun)/2),t>=i-1&&(s.senkouB=(u.highs[t]+u.lows[t])/2),t>=r-1&&(s.chikou=e[t].close),(s.tenkan!==void 0||s.kijun!==void 0||s.senkouA!==void 0||s.senkouB!==void 0)&&(a.set(e[t].time,s),o[t]=s)}return{values:a,series:o}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=c-s+1,u=new Float64Array(l),d=new Float64Array(l),f=0,p=new Float64Array(l),m=new Float64Array(l),h=0,g=new Float64Array(l),_=new Float64Array(l),v=0,y=new Float64Array(l),b=new Float64Array(l),x=0;for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n)continue;let r=e.b(t,i);n.tenkan!==void 0&&(u[f]=r,d[f]=e.T(n.tenkan,i),f++),n.kijun!==void 0&&(p[h]=r,m[h]=e.T(n.kijun,i),h++),n.senkouA!==void 0&&(g[v]=r,_[v]=e.T(n.senkouA,i),v++),n.senkouB!==void 0&&(y[x]=r,b[x]=e.T(n.senkouB,i),x++)}if(v>1&&x>1){let e=Math.min(v,x);n.beginPath(),n.moveTo(g[0],_[0]);for(let t=1;t<e;t++)n.lineTo(g[t],_[t]);for(let t=e-1;t>=0;t--)n.lineTo(y[t],b[t]);n.closePath(),n.fillStyle=(0,t.withAlpha)(a.colors[2]??`#1fa874`,.15),n.fill()}let S=(e,t,r,i,o,s)=>{let c=N(a,e,s);if(!(i<2||!c.visible)){n.beginPath(),n.strokeStyle=o,n.lineWidth=s,n.lineJoin=`round`,n.setLineDash(c.dash),n.moveTo(t[0],r[0]);for(let e=1;e<i;e++)n.lineTo(t[e],r[e]);n.stroke(),n.setLineDash([])}};S(`tenkan`,u,d,f,a.colors[0],a.lineWidths[0]),S(`kijun`,p,m,h,a.colors[1]??`#f2a93b`,a.lineWidths[0]),S(`senkouA`,g,_,v,a.colors[2]??`#1fa874`,1),S(`senkouB`,y,b,x,a.colors[3]??`#e8505b`,1)}},vn=class extends P{descriptor={id:`psar`,name:`Parabolic SAR`,placement:`overlay`,defaultConfig:{step:.02,max:.2},shortName:`SAR`,plots:[{key:`value`,title:`SAR`,color:0,kind:`dots`,tone:{field:`trend`},downColor:1}]};calculate(e,t){let n=I(t,`step`,.02),r=I(t,`max`,.2),i=new F,a=Array(e.length).fill(null);if(e.length<2)return{values:i,series:a};let o=e[1].close>e[0].close,s=n,c=o?e[0].high:e[0].low,l=o?e[0].low:e[0].high,u={value:l,trend:o?1:-1};i.set(e[0].time,u),a[0]=u;for(let t=1;t<e.length;t++){let u=l;l=u+s*(c-u),o?(l=Math.min(l,e[t-1].low),t>=2&&(l=Math.min(l,e[t-2].low)),e[t].low<l?(o=!1,l=c,c=e[t].low,s=n):e[t].high>c&&(c=e[t].high,s=Math.min(s+n,r))):(l=Math.max(l,e[t-1].high),t>=2&&(l=Math.max(l,e[t-2].high)),e[t].high>l?(o=!0,l=c,c=e[t].high,s=n):e[t].low<c&&(c=e[t].low,s=Math.min(s+n,r)));let d={value:l,trend:o?1:-1};i.set(e[t].time,d),a[t]=d}return{values:i,series:a}}render(t,n,r,i){let a=n.series;if(!a||i.plots?.value?.visible===!1)return;let{from:o,to:s}=r.visibleRange,c=Math.max(1.5,r.barWidth*.15);for(let n=o;n<=s&&n<a.length;n++){let o=a[n];if(!o||o.value===void 0)continue;let s=e.b(n,r),l=e.T(o.value,r);t.beginPath(),t.arc(s,l,c,0,Math.PI*2),t.fillStyle=o.trend===1?i.colors[0]:i.colors[1]??`#e8505b`,t.fill()}}},yn=class extends P{descriptor={id:`supertrend`,name:`Supertrend`,placement:`overlay`,defaultConfig:{period:10,multiplier:3},shortName:`Supertrend`,plots:[{key:`value`,title:`Supertrend`,color:0,tone:{field:`trend`},downColor:1}]};calculate(e,t){let n=L(t,`period`,10,1),r=I(t,`multiplier`,3),i=new F,a=Array(e.length).fill(null);if(e.length<n)return{values:i,series:a};let o=[e[0].high-e[0].low];for(let t=1;t<e.length;t++)o.push(Math.max(e[t].high-e[t].low,Math.abs(e[t].high-e[t-1].close),Math.abs(e[t].low-e[t-1].close)));let s=0;for(let e=0;e<n;e++)s+=o[e];s/=n;let c=0,l=0,u=0,d=0,f=0,p=0,m=1;for(let t=n-1;t<e.length;t++){t>n-1&&(s=(s*(n-1)+o[t])/n);let h=(e[t].high+e[t].low)/2,g=h+r*s,_=h-r*s;c=g<u||e[t-1].close>u?g:u,l=_>d||e[t-1].close<d?_:d,f=p===u?e[t].close<=c?c:l:e[t].close>=l?l:c,m=f===l?1:-1;let v={value:f,trend:m};i.set(e[t].time,v),a[t]=v,u=c,d=l,p=f}return{values:i,series:a}}render(t,n,r,i){let a=n.series;if(!a||i.plots?.value?.visible===!1)return;let{from:o,to:s}=r.visibleRange,c=i.colors[0],l=i.colors[1]??`#e8505b`,u=j(r),d=i.lineWidths[0]+.5;for(let[n,i]of[[c,1],[l,-1]]){let c=new M(t,n,d,u),l=0,f=0,p=!1;for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let o=e.b(t,r),s=e.T(n.value,r);p&&(n.trend??1)===i&&c.segment(l,f,o,s),l=o,f=s,p=!0}c.finish()}}},bn=class extends P{descriptor={id:`keltner`,name:`Keltner Channel`,placement:`overlay`,defaultConfig:{emaPeriod:20,atrPeriod:10,multiplier:1.5},shortName:`KC`,plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=L(t,`emaPeriod`,20,1),r=L(t,`atrPeriod`,10,1),i=I(t,`multiplier`,1.5),a=new F;if(e.length<Math.max(n,r))return{values:a};let o=2/(n+1),s=e[0].close,c=[s];for(let t=1;t<e.length;t++)s=(e[t].close-s)*o+s,c.push(s);let l=[e[0].high-e[0].low];for(let t=1;t<e.length;t++)l.push(Math.max(e[t].high-e[t].low,Math.abs(e[t].high-e[t-1].close),Math.abs(e[t].low-e[t-1].close)));let u=0;for(let e=0;e<r;e++)u+=l[e];u/=r;let d=Array(e.length).fill(null),f=Math.max(n,r)-1;for(let t=f;t<e.length;t++){t>f&&(u=(u*(r-1)+l[t])/r);let n={middle:c[t],upper:c[t]+i*u,lower:c[t]-i*u};a.set(e[t].time,n),d[t]=n}return{values:a,series:d}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=[],u=[],d=[];for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n)continue;let r=e.b(t,i);n.upper!==void 0&&l.push({x:r,y:e.T(n.upper,i)}),n.middle!==void 0&&u.push({x:r,y:e.T(n.middle,i)}),n.lower!==void 0&&d.push({x:r,y:e.T(n.lower,i)})}this.drawBand(n,l,d,(0,t.withAlpha)(a.colors[0],.08)),this.drawLine(n,l,a.colors[0],a.lineWidths[0],N(a,`upper`,a.lineWidths[0])),this.drawLine(n,u,a.colors[1]??a.colors[0],a.lineWidths[0],N(a,`middle`,a.lineWidths[0])),this.drawLine(n,d,a.colors[0],a.lineWidths[0],N(a,`lower`,a.lineWidths[0]))}},xn=class extends P{descriptor={id:`donchian`,name:`Donchian Channel`,placement:`overlay`,defaultConfig:{period:20},shortName:`DC`,plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null);for(let t=n-1;t<e.length;t++){let a=-1/0,o=1/0;for(let r=t-n+1;r<=t;r++)e[r].high>a&&(a=e[r].high),e[r].low<o&&(o=e[r].low);let s={upper:a,middle:(a+o)/2,lower:o};r.set(e[t].time,s),i[t]=s}return{values:r,series:i}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=[],u=[],d=[];for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n)continue;let r=e.b(t,i);n.upper!==void 0&&l.push({x:r,y:e.T(n.upper,i)}),n.middle!==void 0&&u.push({x:r,y:e.T(n.middle,i)}),n.lower!==void 0&&d.push({x:r,y:e.T(n.lower,i)})}this.drawBand(n,l,d,(0,t.withAlpha)(a.colors[0],.08)),this.drawLine(n,l,a.colors[0],a.lineWidths[0],N(a,`upper`,a.lineWidths[0])),this.drawLine(n,u,a.colors[1]??`#7d8696`,1,N(a,`middle`,1)),this.drawLine(n,d,a.colors[0],a.lineWidths[0],N(a,`lower`,a.lineWidths[0]))}},Sn=[`s3`,`s2`,`s1`,`pp`,`r1`,`r2`,`r3`],Cn=[`traditional`,`fibonacci`,`woodie`,`classic`,`camarilla`,`dm`],wn=class extends P{descriptor={id:`pivots`,name:`Pivot Points`,placement:`overlay`,defaultConfig:{lookback:24,type:`traditional`},shortName:`Pivots`,inputs:{lookback:{min:1},type:{options:Cn}},plots:[{key:`r3`,title:`R3`,color:1},{key:`r2`,title:`R2`,color:1},{key:`r1`,title:`R1`,color:1},{key:`pp`,title:`P`,color:0},{key:`s1`,title:`S1`,color:2},{key:`s2`,title:`S2`,color:2},{key:`s3`,title:`S3`,color:2}]};calculate(e,t){let n=L(t,`lookback`,24,1),r=Cn.includes(t.params.type)?t.params.type:`traditional`,i=new F,a=Array(e.length).fill(null);if(e.length<=n)return{values:i,series:a};for(let t=n;t<e.length;t++){let o=-1/0,s=1/0;for(let r=t-n;r<t;r++)e[r].high>o&&(o=e[r].high),e[r].low<s&&(s=e[r].low);let c=Tn(r,e[t-n].open,o,s,e[t-1].close);i.set(e[t].time,c),a[t]=c}return{values:i,series:a}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=a.colors[0],u=a.colors[1]??`#e8505b`,d=a.colors[2]??`#1fa874`,f=a.lineWidths[0],p=e=>e===`pp`?l:e.startsWith(`r`)?u:d;for(let r of Sn){let l=a.plots?.[r];if(l?.visible===!1)continue;n.beginPath(),n.strokeStyle=p(r),n.lineWidth=r===`pp`?f:Math.max(1,f-1),n.setLineDash((0,t.lineDash)(l?.lineStyle??(r===`pp`?`solid`:`dashed`),[4,3],n.lineWidth));let u=!1;for(let t=s;t<=c&&t<o.length;t++){let a=o[t]?.[r];if(a===void 0)continue;let s=e.b(t,i),c=e.T(a,i);u?n.lineTo(s,c):(n.moveTo(s,c),u=!0)}n.stroke(),n.setLineDash([])}}};function Tn(e,t,n,r,i){let a=n-r;if(e===`dm`){let e=i<t?n+2*r+i:i>t?2*n+r+i:n+r+2*i;return{pp:e/4,r1:e/2-r,s1:e/2-n}}if(e===`camarilla`){let e=a*1.1;return{pp:(n+r+i)/3,r1:i+e/12,s1:i-e/12,r2:i+e/6,s2:i-e/6,r3:i+e/4,s3:i-e/4}}let o=e===`woodie`?(n+r+2*i)/4:(n+r+i)/3;if(e===`fibonacci`)return{pp:o,r1:o+.382*a,s1:o-.382*a,r2:o+.618*a,s2:o-.618*a,r3:o+a,s3:o-a};let s=2*o-r,c=2*o-n;return e===`classic`?{pp:o,r1:s,s1:c,r2:o+a,s2:o-a,r3:o+2*a,s3:o-2*a}:{pp:o,r1:s,s1:c,r2:o+a,s2:o-a,r3:n+2*(o-r),s3:r-2*(n-o)}}var En=class extends P{descriptor={id:`avwap`,name:`Anchored VWAP`,placement:`overlay`,defaultConfig:{anchorTime:0},shortName:`AVWAP`,plots:[{key:`value`,title:`AVWAP`,color:0}]};calculate(e,t){let n=I(t,`anchorTime`,0),r=new F,i=Array(e.length).fill(null),a=0;if(n>0&&(a=e.findIndex(e=>e.time>=n),a<0))return{values:r,series:i};let o=0,s=0;for(let t=a;t<e.length;t++){let n=(e[t].high+e[t].low+e[t].close)/3;if(o+=e[t].volume,s+=n*e[t].volume,o>0){let n={value:s/o};r.set(e[t].time,n),i[t]=n}}return{values:r,series:i}}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},Dn=class extends P{descriptor={id:`zigzag`,name:`ZigZag`,placement:`overlay`,defaultConfig:{deviation:5},shortName:`ZigZag`,plots:[{key:`pivot`,title:`Pivot`,color:0}]};calculate(e,t){let n=Math.max(.01,I(t,`deviation`,5))/100,r=new F,i=Array(e.length).fill(null);if(e.length<2)return{values:r,series:i,meta:{pivots:[]}};let a=[],o=null,s=0,c=e[0].close;for(let t=1;t<e.length;t++){let r=e[t].high,i=e[t].low;if(o===null){r>=c*(1+n)?(a.push({idx:s,price:c,type:`low`}),o=`up`,s=t,c=r):i<=c*(1-n)&&(a.push({idx:s,price:c,type:`high`}),o=`down`,s=t,c=i);continue}o===`up`?r>c?(s=t,c=r):i<=c*(1-n)&&(a.push({idx:s,price:c,type:`high`}),o=`down`,s=t,c=i):i<c?(s=t,c=i):r>=c*(1+n)&&(a.push({idx:s,price:c,type:`low`}),o=`up`,s=t,c=r)}a.push({idx:s,price:c,type:o===`up`?`high`:`low`});for(let t of a){let n={pivot:t.price};r.set(e[t.idx].time,n),i[t.idx]=n}return{values:r,series:i,meta:{pivots:a}}}render(t,n,r,i){if(i.plots?.pivot?.visible===!1)return;let a=n.meta?.pivots;if(!(!a||a.length<2)){t.beginPath(),t.strokeStyle=i.colors[0],t.lineWidth=i.lineWidths[0],t.lineJoin=`round`;for(let n=0;n<a.length;n++){let i=a[n],o=e.b(i.idx,r),s=e.T(i.price,r);n===0?t.moveTo(o,s):t.lineTo(o,s)}t.stroke()}}},On=class extends P{descriptor={id:`lrc`,name:`Linear Regression Channel`,placement:`overlay`,defaultConfig:{period:100,stdDev:2,source:`close`},shortName:`LRC`,inputs:{source:{source:!0}},plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=L(t,`period`,100,2),r=I(t,`stdDev`,2),i=new F,a=Array(e.length).fill(null);if(e.length<n)return{values:i,series:a};for(let t=n-1;t<e.length;t++){let o=t-n+1,s=0,c=0,l=0,u=0;for(let t=0;t<n;t++){let n=t,r=e[o+t].close;s+=n,c+=r,l+=n*r,u+=n*n}let d=n*u-s*s;if(d===0)continue;let f=(n*l-s*c)/d,p=(c-f*s)/n,m=0;for(let t=0;t<n;t++){let n=f*t+p,r=e[o+t].close-n;m+=r*r}let h=Math.sqrt(m/n),g=f*(n-1)+p,_={middle:g,upper:g+r*h,lower:g-r*h,slope:f};i.set(e[t].time,_),a[t]=_}return{values:i,series:a}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=[],u=[],d=[];for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n)continue;let r=e.b(t,i);n.middle!==void 0&&u.push({x:r,y:e.T(n.middle,i)}),n.upper!==void 0&&l.push({x:r,y:e.T(n.upper,i)}),n.lower!==void 0&&d.push({x:r,y:e.T(n.lower,i)})}this.drawBand(n,l,d,(0,t.withAlpha)(a.colors[0],.08)),this.drawLine(n,l,a.colors[0],a.lineWidths[0],N(a,`upper`,a.lineWidths[0])),this.drawLine(n,u,a.colors[1]??a.colors[0],a.lineWidths[0],N(a,`middle`,a.lineWidths[0])),this.drawLine(n,d,a.colors[0],a.lineWidths[0],N(a,`lower`,a.lineWidths[0]))}},kn=class extends P{descriptor={id:`hma`,name:`Hull Moving Average`,placement:`overlay`,defaultConfig:{period:21,source:`close`},shortName:`HMA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`HMA`,color:0}]};calculate(e,t){let n=L(t,`period`,21,2),r=new F,i=Array(e.length).fill(null);if(e.length<n)return{values:r,series:i};let a=e.map(e=>e.close),o=Math.max(2,Math.floor(n/2)),s=Math.max(2,Math.floor(Math.sqrt(n))),c=An(a,n),l=An(a,o),u=jn(a.map((e,t)=>c[t]===null||l[t]===null?null:2*l[t]-c[t]),s);for(let t=0;t<e.length;t++){if(u[t]===null)continue;let n={value:u[t]};r.set(e[t].time,n),i[t]=n}return{values:r,series:i}}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}};function An(e,t){let n=Array(e.length).fill(null);if(e.length<t)return n;let r=t*(t+1)/2;for(let i=t-1;i<e.length;i++){let a=0;for(let n=0;n<t;n++)a+=e[i-n]*(t-n);n[i]=a/r}return n}function jn(e,t){let n=Array(e.length).fill(null),r=t*(t+1)/2;for(let i=t-1;i<e.length;i++){let a=0,o=!0;for(let n=0;n<t;n++){let r=e[i-n];if(r===null){o=!1;break}a+=r*(t-n)}o&&(n[i]=a/r)}return n}var Mn=class extends P{descriptor={id:`mtfma`,name:`MTF Moving Average`,placement:`overlay`,defaultConfig:{period:50,timeframe:`1d`,source:`close`},shortName:`MTF MA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`MA`,color:0}]};calculate(e,n){let r=L(n,`period`,50,1),i=String(n.params.timeframe??`1d`),a=new F,o=Array(e.length).fill(null);if(e.length===0)return{values:a,series:o};let s=[],c=(0,t.timeframeBucketStart)(e[0].time,i),l=e[0].close,u=null,d=()=>{if(s.length<r)return;let e=0;for(let t=s.length-r;t<s.length;t++)e+=s[t];u=e/r};for(let n=0;n<e.length;n++){let r=(0,t.timeframeBucketStart)(e[n].time,i);if(r!==c&&(s.push(l),d(),c=r),l=e[n].close,u!==null){let t={value:u};a.set(e[n].time,t),o[n]=t}}return{values:a,series:o}}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},Nn=class extends P{descriptor={id:`svwap`,name:`Session VWAP`,placement:`overlay`,defaultConfig:{bands:1},shortName:`SVWAP`,plots:[{key:`value`,title:`VWAP`,color:0},{key:`u1`,title:`+1σ`,color:1},{key:`l1`,title:`−1σ`,color:1},{key:`u2`,title:`+2σ`,color:1},{key:`l2`,title:`−2σ`,color:1},{key:`u3`,title:`+3σ`,color:1},{key:`l3`,title:`−3σ`,color:1}]};calculate(e,n){let r=Math.min(3,L(n,`bands`,1,0)),i=new F,a=Array(e.length).fill(null);if(e.length===0)return{values:i,series:a};let o=(0,t.timeframeBucketStart)(e[0].time,`1d`),s=0,c=0,l=0;for(let n=0;n<e.length;n++){let u=e[n],d=(0,t.timeframeBucketStart)(u.time,`1d`);d!==o&&(s=0,c=0,l=0,o=d);let f=(u.high+u.low+u.close)/3;if(s+=f*u.volume,c+=f*f*u.volume,l+=u.volume,l>0){let e=s/l,t={value:e,session:o};if(r>0){let n=Math.max(0,c/l-e*e),i=Math.sqrt(n);for(let n=1;n<=r;n++)t[`u${n}`]=e+n*i,t[`l${n}`]=e-n*i}i.set(u.time,t),a[n]=t}}return{values:i,series:a}}render(e,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange;e.globalAlpha=.55,e.lineWidth=1,e.strokeStyle=i.colors[1]??i.colors[0];let c=n=>{let c=i.plots?.[n];c?.visible!==!1&&(e.setLineDash(c?.lineStyle?(0,t.lineDash)(c.lineStyle,[4,3],1):[4,3]),this.strokeBandSeries(e,a,r,o,s,e=>e[n]))};for(let e=1;e<=3;e++)c(`u${e}`),c(`l${e}`);e.setLineDash([]),e.globalAlpha=1;let l=i.plots?.value;l?.visible!==!1&&(e.strokeStyle=i.colors[0],e.lineWidth=i.lineWidths[0],e.lineJoin=`round`,e.setLineDash((0,t.lineDash)(l?.lineStyle??`solid`,[6,4],i.lineWidths[0])),this.strokeBandSeries(e,a,r,o,s,e=>e.value),e.setLineDash([]))}strokeBandSeries(t,n,r,i,a,o){let s=new M(t,String(t.strokeStyle),t.lineWidth,j(r)),c;for(let t=i;t<=a&&t<n.length;t++){let i=n[t],a=i?o(i):void 0;if(i===null||a===void 0){s.gap();continue}let l=e.b(t,r),u=e.T(a,r);i.session!==c&&s.gap(),s.add(l,u),c=i.session}s.finish()}},Pn=class extends P{descriptor={id:`chandelier`,name:`Chandelier Exit`,placement:`overlay`,defaultConfig:{period:22,multiplier:3},shortName:`CE`,plots:[{key:`long`,title:`Long`,color:0},{key:`short`,title:`Short`,color:1}]};calculate(e,t){let n=L(t,`period`,22,1),r=I(t,`multiplier`,3),i=new F,a=Array(e.length).fill(null),o=e.length;if(o<=n)return{values:i,series:a};let s=Array(o).fill(0);for(let t=1;t<o;t++){let n=e[t-1].close;s[t]=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-n),Math.abs(e[t].low-n))}let c=0;for(let e=1;e<=n;e++)c+=s[e];c/=n;for(let t=n;t<o;t++){t>n&&(c=(c*(n-1)+s[t])/n);let o=-1/0,l=1/0;for(let r=t-n+1;r<=t;r++)e[r].high>o&&(o=e[r].high),e[r].low<l&&(l=e[r].low);let u={long:o-r*c,short:l+r*c};i.set(e[t].time,u),a[t]=u}return{values:i,series:a}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=(r,l)=>{let u=a.plots?.[r];if(u?.visible===!1)return;n.beginPath(),n.strokeStyle=l,n.lineWidth=a.lineWidths[0],n.lineJoin=`round`,n.setLineDash(u?.lineStyle?(0,t.lineDash)(u.lineStyle,[5,3],a.lineWidths[0]):[5,3]);let d=!1;for(let t=s;t<=c&&t<o.length;t++){let a=o[t];if(!a||a[r]===void 0){d=!1;continue}let s=e.b(t,i),c=e.T(a[r],i);d?n.lineTo(s,c):(n.moveTo(s,c),d=!0)}n.stroke(),n.setLineDash([])};l(`long`,a.colors[0]??`#1fa874`),l(`short`,a.colors[1]??`#e8505b`)}},Fn=class extends P{descriptor={id:`alligator`,name:`Alligator`,placement:`overlay`,defaultConfig:{jaw:13,teeth:8,lips:5,jawShift:8,teethShift:5,lipsShift:3},shortName:`Alligator`,plots:[{key:`jaw`,title:`Jaw`,color:0},{key:`teeth`,title:`Teeth`,color:1},{key:`lips`,title:`Lips`,color:2}]};calculate(e,t){let n=L(t,`jaw`,13,1),r=L(t,`teeth`,8,1),i=L(t,`lips`,5,1),a=L(t,`jawShift`,8,0),o=L(t,`teethShift`,5,0),s=L(t,`lipsShift`,3,0),c=new F,l=e.length,u=Array(l).fill(null);if(l===0)return{values:c,series:u};let d=e.map(e=>(e.high+e.low)/2),f=In(d,n),p=In(d,r),m=In(d,i),h=Array(l).fill(void 0),g=Array(l).fill(void 0),_=Array(l).fill(void 0);for(let e=0;e<l;e++)f[e]!==void 0&&e+a<l&&(h[e+a]=f[e]),p[e]!==void 0&&e+o<l&&(g[e+o]=p[e]),m[e]!==void 0&&e+s<l&&(_[e+s]=m[e]);for(let t=0;t<l;t++){if(h[t]===void 0&&g[t]===void 0&&_[t]===void 0)continue;let n={};h[t]!==void 0&&(n.jaw=h[t]),g[t]!==void 0&&(n.teeth=g[t]),_[t]!==void 0&&(n.lips=_[t]),c.set(e[t].time,n),u[t]=n}return{values:c,series:u}}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=(n,c)=>{let l=N(i,n,i.lineWidths[0]);if(!l.visible)return;let u=new M(t,c,i.lineWidths[0],j(r),l.dash);for(let t=o;t<=s&&t<a.length;t++){let i=a[t];if(!i||i[n]===void 0){u.gap();continue}let o=e.b(t,r),s=e.T(i[n],r);u.add(o,s)}u.finish()};c(`jaw`,i.colors[0]??`#4c8dff`),c(`teeth`,i.colors[1]??`#e8505b`),c(`lips`,i.colors[2]??`#1fa874`)}};function In(e,t){let n=e.length,r=Array(n).fill(void 0);if(n<t)return r;let i=0;for(let n=0;n<t;n++)i+=e[n];let a=i/t;r[t-1]=a;for(let i=t;i<n;i++)a=(a*(t-1)+e[i])/t,r[i]=a;return r}var Ln=class extends P{descriptor={id:`vwma`,name:`Volume Weighted Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`VWMA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`VWMA`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null),a=0,o=0;for(let t=0;t<e.length;t++){let s=e[t].close*e[t].volume;if(a+=s,o+=e[t].volume,t>=n){let r=e[t-n];a-=r.close*r.volume,o-=r.volume}if(t>=n-1&&o>0){let n={value:a/o};r.set(e[t].time,n),i[t]=n}}return{values:r,series:i}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=L(t,`period`,20,1);for(let t=r;t<e.length;t++){if(t<i-1){this.writePoint(n,e,t,null);continue}let r=0,a=0;for(let n=t-i+1;n<=t;n++)r+=e[n].close*e[n].volume,a+=e[n].volume;this.writePoint(n,e,t,a>0?{value:r/a}:null)}return n}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},Rn=class extends P{descriptor={id:`wma`,name:`Weighted Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`WMA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`WMA`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null),a=n*(n+1)/2,o=0,s=0;for(let t=0;t<e.length;t++){let c=e[t].close;if(s+=c*n-o,o+=c,t>=n&&(o-=e[t-n].close),t>=n-1){let n={value:s/a};r.set(e[t].time,n),i[t]=n}}return{values:r,series:i}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=L(t,`period`,20,1),a=i*(i+1)/2;for(let t=r;t<e.length;t++){if(t<i-1){this.writePoint(n,e,t,null);continue}let r=0,o=t-i+1;for(let t=0;t<i;t++)r+=e[o+t].close*(t+1);this.writePoint(n,e,t,{value:r/a})}return n}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},zn=class extends P{descriptor={id:`envelope`,name:`Moving Average Envelope`,placement:`overlay`,defaultConfig:{period:20,percent:2.5,source:`close`},shortName:`Env`,inputs:{source:{source:!0}},plots:[{key:`upper`,title:`Upper`,color:0},{key:`basis`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=I(t,`percent`,2.5)/100,i=new F,a=Array(e.length).fill(null),o=0;for(let t=0;t<e.length;t++)if(o+=e[t].close,t>=n&&(o-=e[t-n].close),t>=n-1){let s=o/n,c={basis:s,upper:s*(1+r),lower:s*(1-r)};i.set(e[t].time,c),a[t]=c}return{values:i,series:a}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=L(t,`period`,20,1),a=I(t,`percent`,2.5)/100;for(let t=r;t<e.length;t++){if(t<i-1){this.writePoint(n,e,t,null);continue}let r=0;for(let n=t-i+1;n<=t;n++)r+=e[n].close;let o=r/i;this.writePoint(n,e,t,{basis:o,upper:o*(1+a),lower:o*(1-a)})}return n}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=[],u=[],d=[];for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n||n.upper===void 0)continue;let r=e.b(t,i);l.push({x:r,y:e.T(n.upper,i)}),u.push({x:r,y:e.T(n.lower,i)}),d.push({x:r,y:e.T(n.basis,i)})}this.drawBand(n,l,u,(0,t.withAlpha)(a.colors[0],.08)),this.drawLine(n,l,a.colors[0],a.lineWidths[0],N(a,`upper`,a.lineWidths[0])),this.drawLine(n,u,a.colors[0],a.lineWidths[0],N(a,`lower`,a.lineWidths[0])),this.drawLine(n,d,a.colors[1]??a.colors[0],a.lineWidths[0],N(a,`basis`,a.lineWidths[0]))}};function Bn(e,t){let n=2/(t+1),r=Array(e.length).fill(null),i=0,a=0;for(let o=0;o<e.length;o++){if(o<t-1){a+=e[o];continue}i=o===t-1?(a+e[o])/t:(e[o]-i)*n+i,r[o]=i}return r}function Vn(e,t,n){let r=Array(n).fill(null);for(let n=0;n<e.length;n++)e[n]!==null&&(r[t[n]]=e[n]);return r}function Hn(e){let t=[],n=[];for(let r=0;r<e.length;r++)e[r]!==null&&(t.push(e[r]),n.push(r));return{values:t,indices:n}}var Un=class extends P{descriptor={id:`tema`,name:`Triple EMA`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`TEMA`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`TEMA`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null),a=Bn(e.map(e=>e.close),n),o=Hn(a),s=Vn(Bn(o.values,n),o.indices,e.length),c=Hn(s),l=Vn(Bn(c.values,n),c.indices,e.length);for(let t=0;t<e.length;t++){let n=a[t],o=s[t],c=l[t];if(n===null||o===null||c===null)continue;let u={value:3*n-3*o+c};r.set(e[t].time,u),i[t]=u}return{values:r,series:i}}render(t,n,r,i){let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=N(i,`value`,i.lineWidths[0]);if(!c.visible)return;let l=new M(t,i.colors[0],i.lineWidths[0],j(r),c.dash);for(let t=o;t<=s&&t<a.length;t++){let n=a[t];if(!n||n.value===void 0)continue;let i=e.b(t,r),o=e.T(n.value,r);l.add(i,o)}l.finish()}},Wn=class extends P{descriptor={id:`ao`,name:`Awesome Oscillator`,placement:`panel`,defaultConfig:{fast:5,slow:34},shortName:`AO`,plots:[{key:`value`,title:`AO`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}]};calculate(e,t){let n=L(t,`fast`,5,1),r=L(t,`slow`,34,1),i=new F,a=Array(e.length).fill(null);if(e.length<r)return{values:i,series:a};let o=Array(e.length);for(let t=0;t<e.length;t++)o[t]=(e[t].high+e[t].low)/2;let s=0,c=0,l;for(let t=0;t<e.length;t++)if(c+=o[t],t>=r&&(c-=o[t-r]),s+=o[t],t>=n&&(s-=o[t-n]),t>=r-1){let o=s/n-c/r,u={value:o,up:+(l===void 0||o>=l)};i.set(e[t].time,u),a[t]=u,l=o}return{values:i,series:a}}},Gn=class extends P{descriptor={id:`chaikinOsc`,name:`Chaikin Oscillator`,placement:`panel`,defaultConfig:{fast:3,slow:10},shortName:`Chaikin Osc`,plots:[{key:`value`,title:`Chaikin`,color:0,kind:`histogram`,tone:`sign`,downColor:1}]};calculate(e,t){let n=L(t,`fast`,3,1),r=L(t,`slow`,10,1),i=new F,a=Array(e.length).fill(null);if(e.length<r)return{values:i,series:a};let o=2/(n+1),s=2/(r+1),c=0,l=0,u=0;for(let t=0;t<e.length;t++){let{high:n,low:d,close:f,volume:p}=e[t],m=n-d,h=m===0?0:(f-d-(n-f))/m;if(c+=h*p,t===0?(l=c,u=c):(l=(c-l)*o+l,u=(c-u)*s+u),t>=r-1){let n={value:l-u,adl:c};i.set(e[t].time,n),a[t]=n}}return{values:i,series:a}}},Kn=class extends P{descriptor={id:`rsi`,name:`Relative Strength Index`,placement:`panel`,defaultConfig:{period:14,source:`close`},shortName:`RSI`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`RSI`,color:0}],scale:{min:0,max:100},levels:[30,70]};smoothing=new WeakMap;calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null),a={values:r,series:i};if(e.length<n+1)return a;let o=[],s=[],c=0,l=0;for(let t=1;t<=n;t++){let n=e[t].close-e[t-1].close;n>0?c+=n:l-=n}c/=n,l/=n,o[n]=c,s[n]=l;let u={value:l===0?100:100-100/(1+c/l)};r.set(e[n].time,u),i[n]=u;for(let t=n+1;t<e.length;t++){let a=e[t].close-e[t-1].close,u=a>0?a:0,d=a<0?-a:0;c=(c*(n-1)+u)/n,l=(l*(n-1)+d)/n,o[t]=c,s[t]=l;let f={value:l===0?100:100-100/(1+c/l)};r.set(e[t].time,f),i[t]=f}return this.smoothing.set(a,{gain:o,loss:s}),a}update(e,t,n,r){let i=L(t,`period`,14,1),a=this.smoothing.get(n);if(!a||r<=i||!this.canResume(e,n,r))return null;let o=a.gain[r-1],s=a.loss[r-1];if(o===void 0||s===void 0)return null;for(let t=r;t<e.length;t++){let r=e[t].close-e[t-1].close,c=r>0?r:0,l=r<0?-r:0;o=(o*(i-1)+c)/i,s=(s*(i-1)+l)/i,a.gain[t]=o,a.loss[t]=s;let u=s===0?100:100-100/(1+o/s);this.writePoint(n,e,t,{value:u})}return n}},qn=class extends P{descriptor={id:`macd`,name:`MACD`,placement:`panel`,defaultConfig:{fast:12,slow:26,signal:9,source:`close`},shortName:`MACD`,inputs:{source:{source:!0}},plots:[{key:`histogram`,title:`Histogram`,color:2,kind:`histogram`,tone:`sign`,downColor:3},{key:`macd`,title:`MACD`,color:0},{key:`signal`,title:`Signal`,color:1}]};emas=new WeakMap;calculate(e,t){let n=L(t,`fast`,12,1),r=L(t,`slow`,26,1),i=L(t,`signal`,9,1),a=new F,o=Array(e.length).fill(null),s={values:a,series:o};if(e.length<r)return s;let c=2/(n+1),l=2/(r+1),u=2/(i+1),d=Array(e.length),f=Array(e.length),p=e[0].close,m=e[0].close,h=0,g=!1;for(let t=0;t<e.length;t++){let n=e[t].close;if(t===0?(p=n,m=n):(p=(n-p)*c+p,m=(n-m)*l+m),d[t]=p,f[t]=m,t>=r-1){let n=p-m;g?h=(n-h)*u+h:(h=n,g=!0);let r=n-h,i={macd:n,signal:h,histogram:r};a.set(e[t].time,i),o[t]=i}}return this.emas.set(s,{fast:d,slow:f}),s}update(e,t,n,r){let i=L(t,`fast`,12,1),a=L(t,`slow`,26,1),o=L(t,`signal`,9,1),s=this.emas.get(n);if(!s||r<a||!this.canResume(e,n,r))return null;let c=s.fast[r-1],l=s.slow[r-1],u=n.series[r-1]?.signal;if(c===void 0||l===void 0||u===void 0)return null;let d=2/(i+1),f=2/(a+1),p=2/(o+1);for(let t=r;t<e.length;t++){let r=e[t].close;c=(r-c)*d+c,l=(r-l)*f+l,s.fast[t]=c,s.slow[t]=l;let i=c-l;u=(i-u)*p+u,this.writePoint(n,e,t,{macd:i,signal:u,histogram:i-u})}return n}},Jn=class extends P{descriptor={id:`stochastic`,name:`Stochastic Oscillator`,placement:`panel`,defaultConfig:{kPeriod:14,dPeriod:3,smooth:3},shortName:`Stoch`,plots:[{key:`k`,title:`%K`,color:0},{key:`d`,title:`%D`,color:1}],scale:{min:0,max:100},levels:[20,80]};calculate(e,t){let n=L(t,`kPeriod`,14,1),r=L(t,`dPeriod`,3,1),i=L(t,`smooth`,3,1),a=new F,o=Array(e.length).fill(null);if(e.length<n)return{values:a,series:o};let s=[];for(let t=0;t<e.length;t++){if(t<n-1){s.push(0);continue}let r=-1/0,i=1/0;for(let a=t-n+1;a<=t;a++)e[a].high>r&&(r=e[a].high),e[a].low<i&&(i=e[a].low);s.push(r===i?50:(e[t].close-i)/(r-i)*100)}let c=[];for(let e=0;e<s.length;e++){if(e<n-1+i-1){c.push(0);continue}let t=0;for(let n=e-i+1;n<=e;n++)t+=s[n];c.push(t/i)}let l=n-1+i-1;for(let t=l;t<c.length;t++){let n={k:c[t]};if(t>=l+r-1){let e=0;for(let n=t-r+1;n<=t;n++)e+=c[n];n.d=e/r}a.set(e[t].time,n),o[t]=n}return{values:a,series:o}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=L(t,`kPeriod`,14,1),a=L(t,`dPeriod`,3,1),o=L(t,`smooth`,3,1),s=i-1+o-1,c=t=>{let n=-1/0,r=1/0;for(let a=t-i+1;a<=t;a++)e[a].high>n&&(n=e[a].high),e[a].low<r&&(r=e[a].low);return n===r?50:(e[t].close-r)/(n-r)*100},l=e=>{let t=0;for(let n=e-o+1;n<=e;n++)t+=c(n);return t/o};for(let t=r;t<e.length;t++){if(t<s||e.length<i){this.writePoint(n,e,t,null);continue}let r={k:l(t)};if(t>=s+a-1){let e=0;for(let n=t-a+1;n<=t;n++)e+=l(n);r.d=e/a}this.writePoint(n,e,t,r)}return n}},Yn=class extends P{descriptor={id:`atr`,name:`Average True Range`,placement:`panel`,defaultConfig:{period:14},shortName:`ATR`,plots:[{key:`value`,title:`ATR`,color:0}]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null);if(e.length<Math.max(2,n))return{values:r,series:i};let a=[e[0].high-e[0].low];for(let t=1;t<e.length;t++){let n=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-e[t-1].close),Math.abs(e[t].low-e[t-1].close));a.push(n)}let o=0;for(let e=0;e<n;e++)o+=a[e];o/=n;let s={value:o};r.set(e[n-1].time,s),i[n-1]=s;for(let t=n;t<e.length;t++){o=(o*(n-1)+a[t])/n;let s={value:o};r.set(e[t].time,s),i[t]=s}return{values:r,series:i}}update(e,t,n,r){let i=L(t,`period`,14,1);if(r<i||!this.canResume(e,n,r))return null;let a=n.series[r-1]?.value;if(a===void 0)return null;for(let t=r;t<e.length;t++){let r=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-e[t-1].close),Math.abs(e[t].low-e[t-1].close));a=(a*(i-1)+r)/i,this.writePoint(n,e,t,{value:a})}return n}},Xn=class extends P{descriptor={id:`adx`,name:`Average Directional Index`,placement:`panel`,defaultConfig:{period:14},shortName:`ADX`,plots:[{key:`adx`,title:`ADX`,color:0},{key:`plusDI`,title:`+DI`,color:1},{key:`minusDI`,title:`−DI`,color:2}],scale:{min:0}};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null);if(e.length<n*2)return{values:r,series:i};let a=[],o=[],s=[];for(let t=1;t<e.length;t++){let n=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-e[t-1].close),Math.abs(e[t].low-e[t-1].close));a.push(n);let r=e[t].high-e[t-1].high,i=e[t-1].low-e[t].low;o.push(r>i&&r>0?r:0),s.push(i>r&&i>0?i:0)}let c=0,l=0,u=0;for(let e=0;e<n;e++)c+=a[e],l+=o[e],u+=s[e];let d=[];for(let t=n;t<a.length;t++){t>n&&(c=c-c/n+a[t],l=l-l/n+o[t],u=u-u/n+s[t]);let f=c===0?0:l/c*100,p=c===0?0:u/c*100,m=f+p,h=m===0?0:Math.abs(f-p)/m*100;d.push(h);let g=t+1,_={plusDI:f,minusDI:p,dx:h};r.set(e[g].time,_),i[g]=_}if(d.length>=n){let t=0;for(let e=0;e<n;e++)t+=d[e];t/=n;let a=n*2;if(a<e.length){let n=r.get(e[a].time);n&&(n.adx=t),i[a]&&(i[a].adx=t)}for(let a=n;a<d.length;a++){t=(t*(n-1)+d[a])/n;let o=a+n+1;if(o<e.length){let n=r.get(e[o].time);n&&(n.adx=t),i[o]&&(i[o].adx=t)}}}return{values:r,series:i}}},Zn=class extends P{descriptor={id:`obv`,name:`On Balance Volume`,placement:`panel`,defaultConfig:{},shortName:`OBV`,plots:[{key:`value`,title:`OBV`,color:0}]};calculate(e,t){let n=new F,r=Array(e.length).fill(null);if(e.length===0)return{values:n,series:r};let i=0,a={value:i};n.set(e[0].time,a),r[0]=a;for(let t=1;t<e.length;t++){e[t].close>e[t-1].close?i+=e[t].volume:e[t].close<e[t-1].close&&(i-=e[t].volume);let a={value:i};n.set(e[t].time,a),r[t]=a}return{values:n,series:r}}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=n.series[r-1]?.value;if(i===void 0)return null;for(let t=r;t<e.length;t++)e[t].close>e[t-1].close?i+=e[t].volume:e[t].close<e[t-1].close&&(i-=e[t].volume),this.writePoint(n,e,t,{value:i});return n}},Qn=class extends P{descriptor={id:`williamsR`,name:`Williams %R`,placement:`panel`,defaultConfig:{period:14},shortName:`%R`,plots:[{key:`value`,title:`%R`,color:0}],scale:{min:-100,max:0},levels:[-80,-20]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null);for(let t=n-1;t<e.length;t++){let a=-1/0,o=1/0;for(let r=t-n+1;r<=t;r++)e[r].high>a&&(a=e[r].high),e[r].low<o&&(o=e[r].low);let s={value:a===o?-50:(a-e[t].close)/(a-o)*-100};r.set(e[t].time,s),i[t]=s}return{values:r,series:i}}},$n=class extends P{descriptor={id:`cci`,name:`Commodity Channel Index`,placement:`panel`,defaultConfig:{period:20},shortName:`CCI`,plots:[{key:`value`,title:`CCI`,color:0}],levels:[-100,0,100]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null);for(let t=n-1;t<e.length;t++){let a=0;for(let r=t-n+1;r<=t;r++)a+=(e[r].high+e[r].low+e[r].close)/3;let o=a/n,s=0;for(let r=t-n+1;r<=t;r++){let t=(e[r].high+e[r].low+e[r].close)/3;s+=Math.abs(t-o)}let c=s/n,l=(e[t].high+e[t].low+e[t].close)/3,u={value:c===0?0:(l-o)/(.015*c)};r.set(e[t].time,u),i[t]=u}return{values:r,series:i}}},er=class extends P{descriptor={id:`mfi`,name:`Money Flow Index`,placement:`panel`,defaultConfig:{period:14},shortName:`MFI`,plots:[{key:`value`,title:`MFI`,color:0}],scale:{min:0,max:100},levels:[20,80]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null);if(e.length<n+1)return{values:r,series:i};let a=e.map(e=>(e.high+e.low+e.close)/3),o=a.map((t,n)=>t*e[n].volume);for(let t=n;t<e.length;t++){let s=0,c=0;for(let e=t-n+1;e<=t;e++)a[e]>a[e-1]?s+=o[e]:a[e]<a[e-1]&&(c+=o[e]);let l={value:c===0?100:100-100/(1+s/c)};r.set(e[t].time,l),i[t]=l}return{values:r,series:i}}},tr=class extends P{descriptor={id:`aroon`,name:`Aroon`,placement:`panel`,defaultConfig:{period:25},shortName:`Aroon`,plots:[{key:`up`,title:`Up`,color:0},{key:`down`,title:`Down`,color:1}],scale:{min:0,max:100}};calculate(e,t){let n=L(t,`period`,25,1),r=new F,i=Array(e.length).fill(null);for(let t=n;t<e.length;t++){let a=0,o=0,s=-1/0,c=1/0;for(let r=0;r<=n;r++){let i=t-n+r;e[i].high>s&&(s=e[i].high,a=r),e[i].low<c&&(c=e[i].low,o=r)}let l={up:a/n*100,down:o/n*100};r.set(e[t].time,l),i[t]=l}return{values:r,series:i}}},nr=class extends P{descriptor={id:`roc`,name:`Rate of Change`,placement:`panel`,defaultConfig:{period:12,source:`close`},shortName:`ROC`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`ROC`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`period`,12,1),r=new F,i=Array(e.length).fill(null);for(let t=n;t<e.length;t++){let a=e[t-n].close,o={value:a===0?0:(e[t].close-a)/a*100};r.set(e[t].time,o),i[t]=o}return{values:r,series:i}}},rr=class extends P{descriptor={id:`tsi`,name:`True Strength Index`,placement:`panel`,defaultConfig:{longPeriod:25,shortPeriod:13,signalPeriod:7,source:`close`},shortName:`TSI`,inputs:{source:{source:!0}},plots:[{key:`tsi`,title:`TSI`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};emaSmooth(e,t){let n=2/(t+1),r=[e[0]];for(let t=1;t<e.length;t++)r.push((e[t]-r[t-1])*n+r[t-1]);return r}calculate(e,t){let n=L(t,`longPeriod`,25,1),r=L(t,`shortPeriod`,13,1),i=L(t,`signalPeriod`,7,1),a=new F,o=Array(e.length).fill(null);if(e.length<2)return{values:a,series:o};let s=[],c=[];for(let t=1;t<e.length;t++){let n=e[t].close-e[t-1].close;s.push(n),c.push(Math.abs(n))}let l=this.emaSmooth(this.emaSmooth(s,n),r),u=this.emaSmooth(this.emaSmooth(c,n),r),d=[];for(let e=0;e<l.length;e++)d.push(u[e]===0?0:l[e]/u[e]*100);let f=this.emaSmooth(d,i);for(let t=0;t<d.length;t++){let n=t+1;if(n<e.length){let r={tsi:d[t],signal:f[t]};a.set(e[n].time,r),o[n]=r}}return{values:a,series:o}}},ir=class extends P{descriptor={id:`cmf`,name:`Chaikin Money Flow`,placement:`panel`,defaultConfig:{period:20},shortName:`CMF`,plots:[{key:`value`,title:`CMF`,color:0,kind:`histogram`,tone:`sign`,downColor:1}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null);for(let t=n-1;t<e.length;t++){let a=0,o=0;for(let r=t-n+1;r<=t;r++){let t=e[r].high-e[r].low,n=t===0?0:(e[r].close-e[r].low-(e[r].high-e[r].close))/t;a+=n*e[r].volume,o+=e[r].volume}let s={value:o===0?0:a/o};r.set(e[t].time,s),i[t]=s}return{values:r,series:i}}},ar=class extends P{descriptor={id:`voldelta`,name:`Volume Delta`,placement:`panel`,defaultConfig:{mode:0},shortName:`Vol Δ`,plots:[{key:`value`,title:`Delta`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}]};calculate(e,t){let n=I(t,`mode`,0)>=1,r=new F,i=Array(e.length).fill(null),a=0;for(let t=0;t<e.length;t++){let o=e[t],s=o.close>=o.open,c=s?o.volume:-o.volume;a+=c;let l={value:n?a:c,up:+!!s};r.set(o.time,l),i[t]=l}return{values:r,series:i}}},or=class extends P{descriptor={id:`vortex`,name:`Vortex Indicator`,placement:`panel`,defaultConfig:{period:14},shortName:`VI`,plots:[{key:`viPlus`,title:`VI+`,color:0},{key:`viMinus`,title:`VI−`,color:1}],levels:[1]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null);if(e.length<=n)return{values:r,series:i};let a=Array(e.length).fill(0),o=Array(e.length).fill(0),s=Array(e.length).fill(0);for(let t=1;t<e.length;t++){a[t]=Math.abs(e[t].high-e[t-1].low),o[t]=Math.abs(e[t].low-e[t-1].high);let n=e[t].high,r=e[t].low,i=e[t-1].close;s[t]=Math.max(n-r,Math.abs(n-i),Math.abs(r-i))}let c=0,l=0,u=0;for(let t=1;t<e.length;t++)if(c+=a[t],l+=o[t],u+=s[t],t>n&&(c-=a[t-n],l-=o[t-n],u-=s[t-n]),t>=n&&u>0){let n={viPlus:c/u,viMinus:l/u};r.set(e[t].time,n),i[t]=n}return{values:r,series:i}}},sr=class extends P{descriptor={id:`chop`,name:`Choppiness Index`,placement:`panel`,defaultConfig:{period:14},shortName:`CHOP`,plots:[{key:`value`,title:`CHOP`,color:0}],scale:{min:0,max:100},levels:[38.2,61.8]};calculate(e,t){let n=L(t,`period`,14,2),r=new F,i=Array(e.length).fill(null);if(e.length<=n)return{values:r,series:i};let a=Array(e.length).fill(0);for(let t=1;t<e.length;t++){let n=e[t].high,r=e[t].low,i=e[t-1].close;a[t]=Math.max(n-r,Math.abs(n-i),Math.abs(r-i))}let o=Math.log10(n),s=0;for(let t=1;t<e.length;t++)if(s+=a[t],t>n&&(s-=a[t-n]),t>=n){let a=-1/0,c=1/0;for(let r=t-n+1;r<=t;r++)e[r].high>a&&(a=e[r].high),e[r].low<c&&(c=e[r].low);let l=a-c;if(l>0&&s>0){let n={value:Math.max(0,Math.min(100,100*Math.log10(s/l)/o))};r.set(e[t].time,n),i[t]=n}}return{values:r,series:i}}},cr=class extends P{descriptor={id:`uo`,name:`Ultimate Oscillator`,placement:`panel`,defaultConfig:{fast:7,mid:14,slow:28},shortName:`UO`,plots:[{key:`value`,title:`UO`,color:0}],scale:{min:0,max:100},levels:[30,70]};calculate(e,t){let n=L(t,`fast`,7,1),r=L(t,`mid`,14,1),i=L(t,`slow`,28,1),a=new F,o=Array(e.length).fill(null);if(e.length<=i)return{values:a,series:o};let s=Array(e.length).fill(0),c=Array(e.length).fill(0);for(let t=1;t<e.length;t++){let n=e[t-1].close,r=Math.min(e[t].low,n),i=Math.max(e[t].high,n);s[t]=e[t].close-r,c[t]=i-r}let l=(e,t,n)=>{let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i];return r};for(let t=i;t<e.length;t++){let u=lr(l(s,t,n),l(c,t,n)),d=lr(l(s,t,r),l(c,t,r)),f=lr(l(s,t,i),l(c,t,i)),p={value:100*(4*u+2*d+f)/7};a.set(e[t].time,p),o[t]=p}return{values:a,series:o}}};function lr(e,t){return t===0?0:e/t}var ur=class extends P{descriptor={id:`fi`,name:`Force Index`,placement:`panel`,defaultConfig:{period:13},shortName:`EFI`,plots:[{key:`value`,title:`EFI`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`period`,13,1),r=new F,i=Array(e.length).fill(null);if(e.length<2)return{values:r,series:i};let a=2/(n+1),o;for(let t=1;t<e.length;t++){let s=(e[t].close-e[t-1].close)*e[t].volume;if(o=o===void 0?s:s*a+o*(1-a),t>=n){let n={value:o};r.set(e[t].time,n),i[t]=n}}return{values:r,series:i}}},dr=class extends P{descriptor={id:`crsi`,name:`Connors RSI`,placement:`panel`,defaultConfig:{rsiPeriod:3,streakPeriod:2,rankPeriod:100,source:`close`},shortName:`CRSI`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`CRSI`,color:0}],scale:{min:0,max:100},levels:[10,90]};calculate(e,t){let n=L(t,`rsiPeriod`,3,1),r=L(t,`streakPeriod`,2,1),i=L(t,`rankPeriod`,100,1),a=new F,o=Array(e.length).fill(null),s=e.length;if(s<2)return{values:a,series:o};let c=e.map(e=>e.close),l=fr(c,n),u=Array(s).fill(0);for(let e=1;e<s;e++)c[e]>c[e-1]?u[e]=u[e-1]>0?u[e-1]+1:1:c[e]<c[e-1]?u[e]=u[e-1]<0?u[e-1]-1:-1:u[e]=0;let d=fr(u,r),f=Array(s).fill(0);for(let e=1;e<s;e++)f[e]=c[e-1]===0?0:(c[e]-c[e-1])/c[e-1]*100;for(let t=0;t<s;t++){if(t<i+1)continue;let n=l[t],r=d[t];if(n===void 0||r===void 0)continue;let s=0;for(let e=t-i;e<t;e++)f[e]<f[t]&&s++;let c=s/i*100,u={value:(n+r+c)/3};a.set(e[t].time,u),o[t]=u}return{values:a,series:o}}};function fr(e,t){let n=e.length,r=Array(n).fill(void 0);if(n<=t)return r;let i=0,a=0;for(let n=1;n<=t;n++){let t=e[n]-e[n-1];t>=0?i+=t:a-=t}i/=t,a/=t,r[t]=a===0?100:100-100/(1+i/a);for(let o=t+1;o<n;o++){let n=e[o]-e[o-1],s=n>0?n:0,c=n<0?-n:0;i=(i*(t-1)+s)/t,a=(a*(t-1)+c)/t,r[o]=a===0?100:100-100/(1+i/a)}return r}var pr=class extends P{descriptor={id:`coppock`,name:`Coppock Curve`,placement:`panel`,defaultConfig:{longRoc:14,shortRoc:11,wma:10,source:`close`},shortName:`Coppock`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`Coppock`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`longRoc`,14,1),r=L(t,`shortRoc`,11,1),i=L(t,`wma`,10,1),a=new F,o=Array(e.length).fill(null),s=e.length,c=Math.max(n,r);if(s<=c+i)return{values:a,series:o};let l=e.map(e=>e.close),u=(e,t)=>l[e-t]===0?0:(l[e]-l[e-t])/l[e-t]*100,d=Array(s).fill(void 0);for(let e=c;e<s;e++)d[e]=u(e,n)+u(e,r);let f=i*(i+1)/2;for(let t=c+i-1;t<s;t++){let n=0,r=!0;for(let e=0;e<i;e++){let a=d[t-e];if(a===void 0){r=!1;break}n+=a*(i-e)}if(!r)continue;let s={value:n/f};a.set(e[t].time,s),o[t]=s}return{values:a,series:o}}},mr=class extends P{descriptor={id:`kst`,name:`Know Sure Thing`,placement:`panel`,defaultConfig:{roc1:10,roc2:15,roc3:20,roc4:30,sma1:10,sma2:10,sma3:10,sma4:15,signal:9,source:`close`},shortName:`KST`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`KST`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`roc1`,10,1),r=L(t,`roc2`,15,1),i=L(t,`roc3`,20,1),a=L(t,`roc4`,30,1),o=L(t,`sma1`,10,1),s=L(t,`sma2`,10,1),c=L(t,`sma3`,10,1),l=L(t,`sma4`,15,1),u=L(t,`signal`,9,1),d=new F,f=Array(e.length).fill(null),p=e.length;if(p<2)return{values:d,series:f};let m=e.map(e=>e.close),h=gr(hr(m,n),o),g=gr(hr(m,r),s),_=gr(hr(m,i),c),v=gr(hr(m,a),l),y=Array(p).fill(void 0);for(let e=0;e<p;e++)h[e]===void 0||g[e]===void 0||_[e]===void 0||v[e]===void 0||(y[e]=h[e]*1+g[e]*2+_[e]*3+v[e]*4);let b=gr(y,u);for(let t=0;t<p;t++){if(y[t]===void 0)continue;let n={value:y[t]};b[t]!==void 0&&(n.signal=b[t]),d.set(e[t].time,n),f[t]=n}return{values:d,series:f}}};function hr(e,t){let n=Array(e.length).fill(void 0);for(let r=t;r<e.length;r++)n[r]=e[r-t]===0?0:(e[r]-e[r-t])/e[r-t]*100;return n}function gr(e,t){let n=Array(e.length).fill(void 0);for(let r=t-1;r<e.length;r++){let i=0,a=!0;for(let n=r-t+1;n<=r;n++){let t=e[n];if(t===void 0){a=!1;break}i+=t}a&&(n[r]=i/t)}return n}var _r=class extends P{descriptor={id:`elderray`,name:`Elder Ray`,placement:`panel`,defaultConfig:{period:13},shortName:`Elder Ray`,plots:[{key:`bull`,title:`Bull`,color:0,kind:`histogram`},{key:`bear`,title:`Bear`,color:1,kind:`histogram`}]};calculate(e,t){let n=L(t,`period`,13,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a===0)return{values:r,series:i};let o=2/(n+1),s;for(let t=0;t<a;t++)if(s=s===void 0?e[t].close:e[t].close*o+s*(1-o),t>=n-1){let n={bull:e[t].high-s,bear:e[t].low-s};r.set(e[t].time,n),i[t]=n}return{values:r,series:i}}render(t,n,r,i){let a=n.series;if(!a)return;let o=Math.max(0,r.visibleRange.from),s=Math.min(r.visibleRange.to,a.length-1),c=e.E(r),l=c(0),u=Math.max(1,r.barWidth/2),d=[[`bull`,i.colors[0],-u],[`bear`,i.colors[1]??i.colors[0],0]];for(let[n,f,p]of d)if(i.plots?.[n]?.visible!==!1){t.beginPath(),t.fillStyle=f;for(let i=o;i<=s;i++){let o=a[i]?.[n];if(o===void 0||!Number.isFinite(o))continue;let s=c(o);t.rect(e.b(i,r)+p,Math.min(s,l),u,Math.max(1,Math.abs(s-l)))}t.fill()}}},vr=class extends P{descriptor={id:`stc`,name:`Schaff Trend Cycle`,placement:`panel`,defaultConfig:{fast:23,slow:50,cycle:10,source:`close`},shortName:`STC`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`STC`,color:0}],scale:{min:0,max:100},levels:[25,75]};calculate(e,t){let n=L(t,`fast`,23,1),r=L(t,`slow`,50,1),i=L(t,`cycle`,10,1),a=new F,o=Array(e.length).fill(null),s=e.length;if(s===0)return{values:a,series:o};let c=e.map(e=>e.close),l=2/(n+1),u=2/(r+1),d=c[0],f=c[0],p=Array(s);for(let e=0;e<s;e++)d=e===0?c[0]:c[e]*l+d*(1-l),f=e===0?c[0]:c[e]*u+f*(1-u),p[e]=d-f;let m=yr(yr(p,i),i);for(let t=0;t<s;t++){let n=m[t];if(n===void 0)continue;let r={value:Math.max(0,Math.min(100,n))};a.set(e[t].time,r),o[t]=r}return{values:a,series:o}}};function yr(e,t){let n=e.length,r=Array(n).fill(void 0),i;for(let a=0;a<n;a++){if(a<t-1)continue;let n=1/0,o=-1/0,s=!0;for(let r=a-t+1;r<=a;r++){let t=e[r];if(t===void 0){s=!1;break}t<n&&(n=t),t>o&&(o=t)}if(!s||e[a]===void 0)continue;let c=o-n>0?(e[a]-n)/(o-n)*100:50;i=i===void 0?c:i+.5*(c-i),r[a]=i}return r}var br=class extends P{descriptor={id:`kvo`,name:`Klinger Oscillator`,placement:`panel`,defaultConfig:{fast:34,slow:55,signal:13},shortName:`KVO`,plots:[{key:`value`,title:`KVO`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`fast`,34,1),r=L(t,`slow`,55,1),i=L(t,`signal`,13,1),a=new F,o=Array(e.length).fill(null),s=e.length;if(s<2)return{values:a,series:o};let c=2/(n+1),l=2/(r+1),u=2/(i+1),d,f=1,p=0,m=0,h,g,_;for(let t=0;t<s;t++){let n=e[t],i=n.high+n.low+n.close,s=d===void 0||i>d?1:-1,v=n.high-n.low;m=d===void 0?v:s===f?m+v:p+v;let y=m===0?0:n.volume*Math.abs(2*(v/m-1))*s*100;h=h===void 0?y:y*c+h*(1-c),g=g===void 0?y:y*l+g*(1-l);let b=h-g;if(_=_===void 0?b:b*u+_*(1-u),d=i,f=s,p=v,t>=r){let e={value:b,signal:_};a.set(n.time,e),o[t]=e}}return{values:a,series:o}}},xr=class extends P{descriptor={id:`fisher`,name:`Fisher Transform`,placement:`panel`,defaultConfig:{period:9},shortName:`Fisher`,plots:[{key:`value`,title:`Fisher`,color:0},{key:`trigger`,title:`Trigger`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`period`,9,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<n)return{values:r,series:i};let o=e.map(e=>(e.high+e.low)/2),s=0,c=0;for(let t=n-1;t<a;t++){let a=-1/0,l=1/0;for(let e=t-n+1;e<=t;e++)o[e]>a&&(a=o[e]),o[e]<l&&(l=o[e]);s=.33*(a-l>0?2*(o[t]-l)/(a-l)-1:0)+.67*s,s=Math.max(-.999,Math.min(.999,s));let u=c;c=.5*Math.log((1+s)/(1-s))+.5*c;let d={value:c,trigger:u};r.set(e[t].time,d),i[t]=d}return{values:r,series:i}}},Sr=class extends P{descriptor={id:`dpo`,name:`Detrended Price Oscillator`,placement:`panel`,defaultConfig:{period:20,source:`close`},shortName:`DPO`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`DPO`,color:0,kind:`histogram`,tone:`sign`,downColor:1}]};calculate(e,t){let n=L(t,`period`,20,2),r=Math.floor(n/2)+1,i=new F,a=Array(e.length).fill(null),o=e.length;if(o<n)return{values:i,series:a};let s=0;for(let t=0;t<o;t++)if(s+=e[t].close,t>=n&&(s-=e[t-n].close),t>=n-1&&t-r>=0){let o=s/n,c={value:e[t-r].close-o};i.set(e[t].time,c),a[t]=c}return{values:i,series:a}}},Cr=class extends P{descriptor={id:`bop`,name:`Balance of Power`,placement:`panel`,defaultConfig:{smooth:14},shortName:`BOP`,plots:[{key:`value`,title:`BOP`,color:0}],scale:{min:-1,max:1},levels:[0]};calculate(e,t){let n=L(t,`smooth`,14,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a===0)return{values:r,series:i};let o=Array(a);for(let t=0;t<a;t++){let n=e[t].high-e[t].low;o[t]=n>0?(e[t].close-e[t].open)/n:0}let s=0;for(let t=0;t<a;t++)if(s+=o[t],t>=n&&(s-=o[t-n]),t>=n-1){let a={value:s/n};r.set(e[t].time,a),i[t]=a}return{values:r,series:i}}},wr=class extends P{descriptor={id:`massindex`,name:`Mass Index`,placement:`panel`,defaultConfig:{ema:9,sum:25},shortName:`Mass`,plots:[{key:`value`,title:`Mass`,color:0}],levels:[26.5,27]};calculate(e,t){let n=L(t,`ema`,9,1),r=L(t,`sum`,25,1),i=new F,a=Array(e.length).fill(null),o=e.length;if(o<r)return{values:i,series:a};let s=2/(n+1),c,l,u=Array(o).fill(0);for(let t=0;t<o;t++){let n=e[t].high-e[t].low;c=c===void 0?n:n*s+c*(1-s),l=l===void 0?c:c*s+l*(1-s),u[t]=l===0?1:c/l}let d=0;for(let t=0;t<o;t++)if(d+=u[t],t>=r&&(d-=u[t-r]),t>=n+r){let n={value:d};i.set(e[t].time,n),a[t]=n}return{values:i,series:a}}},Tr=class extends P{descriptor={id:`cmo`,name:`Chande Momentum`,placement:`panel`,defaultConfig:{period:9,source:`close`},shortName:`CMO`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`CMO`,color:0}],scale:{min:-100,max:100},levels:[-50,0,50]};calculate(e,t){let n=L(t,`period`,9,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<=n)return{values:r,series:i};let o=Array(a).fill(0),s=Array(a).fill(0);for(let t=1;t<a;t++){let n=e[t].close-e[t-1].close;o[t]=n>0?n:0,s[t]=n<0?-n:0}let c=0,l=0;for(let t=1;t<a;t++)if(c+=o[t],l+=s[t],t>n&&(c-=o[t-n],l-=s[t-n]),t>=n){let n=c+l,a={value:n>0?100*(c-l)/n:0};r.set(e[t].time,a),i[t]=a}return{values:r,series:i}}},Er=class extends P{descriptor={id:`trix`,name:`TRIX`,placement:`panel`,defaultConfig:{period:15,signal:9,source:`close`},shortName:`TRIX`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`TRIX`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`period`,15,1),r=L(t,`signal`,9,1),i=new F,a=Array(e.length).fill(null),o=e.length;if(o<2)return{values:i,series:a};let s=Dr(Dr(Dr(e.map(e=>e.close),n),n),n),c=Array(o).fill(0);for(let e=1;e<o;e++)c[e]=s[e-1]===0?0:(s[e]-s[e-1])/s[e-1]*100;let l=Dr(c,r),u=3*n;for(let t=u;t<o;t++){let n={value:c[t],signal:l[t]};i.set(e[t].time,n),a[t]=n}return{values:i,series:a}}};function Dr(e,t){let n=2/(t+1),r=Array(e.length).fill(0),i=e[0]??0;r[0]=i;for(let t=1;t<e.length;t++)i=e[t]*n+i*(1-n),r[t]=i;return r}var Or=class extends P{descriptor={id:`emv`,name:`Ease of Movement`,placement:`panel`,defaultConfig:{period:14},shortName:`EOM`,plots:[{key:`value`,title:`EOM`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<2)return{values:r,series:i};let o=Array(a).fill(0);for(let t=1;t<a;t++){let n=(e[t].high+e[t].low)/2,r=(e[t-1].high+e[t-1].low)/2,i=e[t].high-e[t].low,a=e[t].volume;o[t]=a>0?(n-r)*i/a:0}let s=0;for(let t=1;t<a;t++)if(s+=o[t],t>n&&(s-=o[t-n]),t>=n){let a={value:s/n};r.set(e[t].time,a),i[t]=a}return{values:r,series:i}}},kr=class extends P{descriptor={id:`pvt`,name:`Price Volume Trend`,placement:`panel`,defaultConfig:{},shortName:`PVT`,plots:[{key:`value`,title:`PVT`,color:0}]};calculate(e,t){let n=new F,r=Array(e.length).fill(null),i=e.length;if(i===0)return{values:n,series:r};let a=0;n.set(e[0].time,{value:0}),r[0]={value:0};for(let t=1;t<i;t++){let i=e[t-1].close;i!==0&&(a+=e[t].volume*(e[t].close-i)/i);let o={value:a};n.set(e[t].time,o),r[t]=o}return{values:n,series:r}}},Ar=class extends P{descriptor={id:`wad`,name:`Williams A/D`,placement:`panel`,defaultConfig:{},shortName:`WAD`,plots:[{key:`value`,title:`WAD`,color:0}]};calculate(e,t){let n=new F,r=Array(e.length).fill(null),i=e.length;if(i===0)return{values:n,series:r};let a=0;n.set(e[0].time,{value:0}),r[0]={value:0};for(let t=1;t<i;t++){let i=e[t-1].close,o=e[t].close;o>i?a+=o-Math.min(e[t].low,i):o<i&&(a+=o-Math.max(e[t].high,i));let s={value:a};n.set(e[t].time,s),r[t]=s}return{values:n,series:r}}},jr=class extends P{descriptor={id:`chaikinvol`,name:`Chaikin Volatility`,placement:`panel`,defaultConfig:{ema:10,roc:10},shortName:`CV`,plots:[{key:`value`,title:`CV`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`ema`,10,1),r=L(t,`roc`,10,1),i=new F,a=Array(e.length).fill(null),o=e.length;if(o<=r)return{values:i,series:a};let s=2/(n+1),c=Array(o),l=e[0].high-e[0].low;c[0]=l;for(let t=1;t<o;t++)l=(e[t].high-e[t].low)*s+l*(1-s),c[t]=l;for(let t=n+r;t<o;t++){let n=c[t-r],o={value:n===0?0:(c[t]-n)/n*100};i.set(e[t].time,o),a[t]=o}return{values:i,series:a}}},Mr=class extends P{descriptor={id:`rvi`,name:`Relative Vigor Index`,placement:`panel`,defaultConfig:{period:10},shortName:`RVGI`,plots:[{key:`value`,title:`RVGI`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`period`,10,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<n+3)return{values:r,series:i};let o=Array(a).fill(0),s=Array(a).fill(0);for(let t=0;t<a;t++)o[t]=e[t].close-e[t].open,s[t]=e[t].high-e[t].low;let c=(e,t)=>(e[t]+2*e[t-1]+2*e[t-2]+e[t-3])/6,l=Array(a).fill(void 0),u=Array(a).fill(void 0);for(let e=3;e<a;e++)l[e]=c(o,e),u[e]=c(s,e);let d=Array(a).fill(void 0);for(let e=3+n-1;e<a;e++){let t=0,r=0;for(let i=e-n+1;i<=e;i++)t+=l[i],r+=u[i];d[e]=r===0?0:t/r}for(let t=0;t<a;t++){if(d[t]===void 0)continue;let n={value:d[t]};t>=3&&d[t-3]!==void 0&&(n.signal=(d[t]+2*d[t-1]+2*d[t-2]+d[t-3])/6),r.set(e[t].time,n),i[t]=n}return{values:r,series:i}}},Nr=class extends P{descriptor={id:`stochrsi`,name:`Stochastic RSI`,placement:`panel`,defaultConfig:{rsiPeriod:14,stochPeriod:14,k:3,d:3,source:`close`},shortName:`Stoch RSI`,inputs:{source:{source:!0}},plots:[{key:`k`,title:`%K`,color:0},{key:`d`,title:`%D`,color:1}],scale:{min:0,max:100},levels:[20,80]};calculate(e,t){let n=L(t,`rsiPeriod`,14,1),r=L(t,`stochPeriod`,14,1),i=L(t,`k`,3,1),a=L(t,`d`,3,1),o=new F,s=Array(e.length).fill(null),c=e.length;if(c<=n+r)return{values:o,series:s};let l=Pr(e.map(e=>e.close),n),u=Array(c).fill(void 0);for(let e=0;e<c;e++){if(l[e]===void 0)continue;let t=1/0,n=-1/0,i=!0;for(let a=e-r+1;a<=e;a++){if(a<0||l[a]===void 0){i=!1;break}l[a]<t&&(t=l[a]),l[a]>n&&(n=l[a])}i&&(u[e]=n-t>0?(l[e]-t)/(n-t)*100:0)}let d=Fr(u,i),f=Fr(d,a);for(let t=0;t<c;t++){if(d[t]===void 0)continue;let n={k:d[t]};f[t]!==void 0&&(n.d=f[t]),o.set(e[t].time,n),s[t]=n}return{values:o,series:s}}};function Pr(e,t){let n=e.length,r=Array(n).fill(void 0);if(n<=t)return r;let i=0,a=0;for(let n=1;n<=t;n++){let t=e[n]-e[n-1];t>=0?i+=t:a-=t}i/=t,a/=t,r[t]=a===0?100:100-100/(1+i/a);for(let o=t+1;o<n;o++){let n=e[o]-e[o-1];i=(i*(t-1)+(n>0?n:0))/t,a=(a*(t-1)+(n<0?-n:0))/t,r[o]=a===0?100:100-100/(1+i/a)}return r}function Fr(e,t){let n=Array(e.length).fill(void 0);for(let r=t-1;r<e.length;r++){let i=0,a=!0;for(let n=r-t+1;n<=r;n++){if(e[n]===void 0){a=!1;break}i+=e[n]}a&&(n[r]=i/t)}return n}var Ir=class extends P{descriptor={id:`ppo`,name:`Percentage Price Oscillator`,placement:`panel`,defaultConfig:{fast:12,slow:26,signal:9,source:`close`},shortName:`PPO`,inputs:{source:{source:!0}},plots:[{key:`hist`,title:`Histogram`,color:2,kind:`histogram`,tone:`sign`,downColor:3},{key:`value`,title:`PPO`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`fast`,12,1),r=L(t,`slow`,26,1),i=L(t,`signal`,9,1),a=new F,o=Array(e.length).fill(null),s=e.length;if(s<=r)return{values:a,series:o};let c=e.map(e=>e.close),l=Lr(c,n),u=Lr(c,r),d=Array(s).fill(void 0);for(let e=0;e<s;e++)l[e]===void 0||u[e]===void 0||u[e]===0||(d[e]=(l[e]-u[e])/u[e]*100);let f=Lr(d,i);for(let t=0;t<s;t++){if(d[t]===void 0)continue;let n={value:d[t]};f[t]!==void 0&&(n.signal=f[t],n.hist=d[t]-f[t]),a.set(e[t].time,n),o[t]=n}return{values:a,series:o}}};function Lr(e,t){let n=e.length,r=Array(n).fill(void 0),i=2/(t+1),a,o=0,s=0;for(let c=0;c<n;c++){let n=e[c];n!==void 0&&(a===void 0?(o+=n,s++,s===t&&(a=o/t,r[c]=a)):(a=n*i+a*(1-i),r[c]=a))}return r}var Rr=class extends P{descriptor={id:`ac`,name:`Accelerator Oscillator`,placement:`panel`,defaultConfig:{},shortName:`AC`,plots:[{key:`value`,title:`AC`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}]};calculate(e){let t=new F,n=Array(e.length).fill(null),r=e.length;if(r<38)return{values:t,series:n};let i=e.map(e=>(e.high+e.low)/2),a=Array(r).fill(void 0);for(let e=33;e<r;e++)a[e]=zr(i,e,5)-zr(i,e,34);let o;for(let i=37;i<r;i++){let r=0;for(let e=i-4;e<=i;e++)r+=a[e];let s=a[i]-r/5,c=o===void 0?s>=0:s>=o;o=s;let l={value:s,up:+!!c};t.set(e[i].time,l),n[i]=l}return{values:t,series:n}}};function zr(e,t,n){let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i];return r/n}var Br=class extends P{descriptor={id:`rmi`,name:`Relative Momentum Index`,placement:`panel`,defaultConfig:{period:20,momentum:5,source:`close`},shortName:`RMI`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`RMI`,color:0}],scale:{min:0,max:100},levels:[30,70]};calculate(e,t){let n=L(t,`period`,20,1),r=L(t,`momentum`,5,1),i=new F,a=Array(e.length).fill(null),o=e.length;if(o<=n+r)return{values:i,series:a};let s=e.map(e=>e.close),c=Array(o).fill(0),l=Array(o).fill(0);for(let e=r;e<o;e++){let t=s[e]-s[e-r];c[e]=t>0?t:0,l[e]=t<0?-t:0}let u=0,d=0,f=r+n;for(let e=r+1;e<=f;e++)u+=c[e],d+=l[e];u/=n,d/=n;let p=t=>{let n={value:d===0?100:100-100/(1+u/d)};i.set(e[t].time,n),a[t]=n};p(f);for(let e=f+1;e<o;e++)u=(u*(n-1)+c[e])/n,d=(d*(n-1)+l[e])/n,p(e);return{values:i,series:a}}},Vr=class extends P{descriptor={id:`disparity`,name:`Disparity Index`,placement:`panel`,defaultConfig:{period:14,source:`close`},shortName:`DI`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`DI`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<n)return{values:r,series:i};let o=0;for(let t=0;t<a;t++)if(o+=e[t].close,t>=n&&(o-=e[t-n].close),t>=n-1){let a=o/n,s={value:a===0?0:(e[t].close-a)/a*100};r.set(e[t].time,s),i[t]=s}return{values:r,series:i}}},Hr=class extends P{descriptor={id:`qstick`,name:`Qstick`,placement:`panel`,defaultConfig:{period:8},shortName:`Qstick`,plots:[{key:`value`,title:`Qstick`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`period`,8,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<n)return{values:r,series:i};let o=0;for(let t=0;t<a;t++){let a=e[t].close-e[t].open;if(o+=a,t>=n&&(o-=e[t-n].close-e[t-n].open),t>=n-1){let a={value:o/n};r.set(e[t].time,a),i[t]=a}}return{values:r,series:i}}},Ur=class extends P{descriptor={id:`pgo`,name:`Pretty Good Oscillator`,placement:`panel`,defaultConfig:{period:14},shortName:`PGO`,plots:[{key:`value`,title:`PGO`,color:0}],levels:[-3,0,3]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null),a=e.length;if(a<=n)return{values:r,series:i};let o=Array(a).fill(0);for(let t=0;t<a;t++){if(t===0){o[t]=e[t].high-e[t].low;continue}let n=e[t-1].close;o[t]=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-n),Math.abs(e[t].low-n))}let s=Array(a).fill(void 0),c=0;for(let e=1;e<=n;e++)c+=o[e];s[n]=c/n;for(let e=n+1;e<a;e++)s[e]=(s[e-1]*(n-1)+o[e])/n;let l=0;for(let t=0;t<a;t++)if(l+=e[t].close,t>=n&&(l-=e[t-n].close),t>=n&&s[t]!==void 0&&s[t]>0){let a=l/n,o={value:(e[t].close-a)/s[t]};r.set(e[t].time,o),i[t]=o}return{values:r,series:i}}},Wr=class extends P{descriptor={id:`stddev`,name:`Standard Deviation`,placement:`panel`,defaultConfig:{period:20,source:`close`},shortName:`StdDev`,inputs:{source:{source:!0}},plots:[{key:`value`,title:`StdDev`,color:0}]};calculate(e,t){let n=L(t,`period`,20,1),r=new F,i=Array(e.length).fill(null);for(let t=n-1;t<e.length;t++){let a=0;for(let r=t-n+1;r<=t;r++)a+=e[r].close;let o=a/n,s=0;for(let r=t-n+1;r<=t;r++){let t=e[r].close-o;s+=t*t}let c={value:Math.sqrt(s/n)};r.set(e[t].time,c),i[t]=c}return{values:r,series:i}}},Gr=class extends P{descriptor={id:`volumeProfile`,name:`Volume Profile`,placement:`overlay`,defaultConfig:{rows:24},shortName:`VP`,plots:[]};calculate(e,t){let n=L(t,`rows`,24,1),r=new F,i=Array(e.length).fill(null);if(e.length===0)return{values:r,series:i};let a=1/0,o=-1/0;for(let t of e)t.low<a&&(a=t.low),t.high>o&&(o=t.high);let s=(o-a||1)/n,c=Array(n).fill(0);for(let t of e){let e=(t.high+t.low+t.close)/3,r=Math.min(n-1,Math.floor((e-a)/s));c[r]+=t.volume}for(let e=0;e<n;e++){let t=a+(e+.5)*s;r.set(e,{price:t,volume:c[e],rowIndex:e})}return{values:r,series:i,meta:{minPrice:a,maxPrice:o,rows:n,rowHeight:s,bins:c,maxVolume:Math.max(...c)}}}render(t,n,r,i){let{chartRect:a}=r,o=n.meta;if(!o||o.maxVolume===0)return;let{minPrice:s,rows:c,rowHeight:l,bins:u,maxVolume:d}=o,f=a.width*.3,p=e.E(r);for(let e=0;e<c;e++){let n=p(s+e*l),r=p(s+(e+1)*l),o=u[e]/d*f;t.fillStyle=u[e]>d*.7?i.colors[1]??`rgba(242, 169, 59, 0.5)`:i.colors[0]??`rgba(76, 141, 255, 0.3)`,t.fillRect(a.x,Math.min(n,r),o,Math.max(Math.abs(n-r)-1,1))}}},Kr=class extends P{descriptor={id:`ad`,name:`Accumulation/Distribution`,placement:`panel`,defaultConfig:{},shortName:`A/D`,plots:[{key:`value`,title:`A/D`,color:0}]};calculate(e,t){let n=new F,r=Array(e.length).fill(null);if(e.length===0)return{values:n,series:r};let i=0;for(let t=0;t<e.length;t++){let a=e[t].high-e[t].low,o=a===0?0:(e[t].close-e[t].low-(e[t].high-e[t].close))/a;i+=o*e[t].volume;let s={value:i};n.set(e[t].time,s),r[t]=s}return{values:n,series:r}}},qr=class extends P{descriptor={id:`vroc`,name:`Volume Rate of Change`,placement:`panel`,defaultConfig:{period:14},shortName:`VROC`,plots:[{key:`value`,title:`VROC`,color:0}],levels:[0]};calculate(e,t){let n=L(t,`period`,14,1),r=new F,i=Array(e.length).fill(null);for(let t=n;t<e.length;t++){let a=e[t-n].volume,o={value:a===0?0:(e[t].volume-a)/a*100};r.set(e[t].time,o),i[t]=o}return{values:r,series:i}}};function R(e,t){let n=new F;for(let r=0;r<t.length;r++){let i=t[r];i&&n.set(e[r].time,i)}return{values:n,series:t}}function z(e){return e.map(e=>e.close)}function Jr(e,t){let n=Array(e.length).fill(void 0),r=0,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(o===void 0){r=0,i=0;continue}r+=o,i++,i>t&&(r-=e[a-t]),i>=t&&(n[a]=r/t)}return n}function Yr(e,t,n){let r=Array(e.length).fill(void 0),i=0,a=0,o;for(let s=0;s<e.length;s++){let c=e[s];if(c!==void 0){if(o===void 0){i+=c,a++,a===t&&(r[s]=o=i/t);continue}o+=n*(c-o),r[s]=o}}return r}function B(e,t){return Yr(e,t,2/(t+1))}function Xr(e,t){let n=Array(e.length).fill(void 0),r=t*(t+1)/2;for(let i=t-1;i<e.length;i++){let a=0,o=!0;for(let n=0;n<t;n++){let r=e[i-t+1+n];if(r===void 0){o=!1;break}a+=r*(n+1)}o&&(n[i]=a/r)}return n}function Zr(e,t){return Yr(e,t,1/t)}function Qr(e,t){let n=Array(e.length).fill(void 0);for(let r=t-1;r<e.length;r++){let i=0,a=0,o=!0;for(let n=r-t+1;n<=r;n++){let t=e[n];if(t===void 0){o=!1;break}i+=t,a+=t*t}if(!o)continue;let s=i/t;n[r]=Math.sqrt(Math.max(0,a/t-s*s))}return n}function $r(e){return e.map((t,n)=>{if(n===0)return t.high-t.low;let r=e[n-1].close;return Math.max(t.high-t.low,Math.abs(t.high-r),Math.abs(t.low-r))})}function ei(e,t,n){if(t<n-1)return;let r=-1/0;for(let i=t-n+1;i<=t;i++){let t=e[i];if(t===void 0)return;t>r&&(r=t)}return r}function ti(e,t,n){if(t<n-1)return;let r=1/0;for(let i=t-n+1;i<=t;i++){let t=e[i];if(t===void 0)return;t<r&&(r=t)}return r}function ni(e,t=`value`){return e.map(e=>e!==void 0&&Number.isFinite(e)?{[t]:e}:null)}function ri(e,t,n){if(t<n-1||t>=e.length)return;let r=0,i=0;for(let a=t-n+1;a<=t;a++){let t=e[a].close;r+=t,i+=t*t}let a=r/n;return{mean:a,sd:Math.sqrt(Math.max(0,i/n-a*a))}}function ii(e,t,n){if(t<n-1)return;let r=-1/0;for(let i=t-n+1;i<=t;i++)e[i].high>r&&(r=e[i].high);return r}function ai(e,t,n){if(t<n-1)return;let r=1/0;for(let i=t-n+1;i<=t;i++)e[i].low<r&&(r=e[i].low);return r}function oi(e,t,n){if(t<n-1)return;let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i].close;return r/n}function si(e,t,n){if(n<2||t<n-1)return;let r=n,i=(r-1)/2,a=0;for(let n=0;n<r;n++)a+=e[t-r+1+n].close;a/=r;let o=0,s=0,c=0;for(let n=0;n<r;n++){let l=n-i,u=e[t-r+1+n].close-a;o+=l*u,s+=l*l,c+=u*u}let l=o/s,u=a-l*i,d=0;for(let n=0;n<r;n++){let i=e[t-r+1+n].close-(u+l*n);d+=i*i}return{slope:l,end:u+l*(r-1),stdErr:r>2?Math.sqrt(d/(r-2)):0,r:c===0?0:o/Math.sqrt(s*c)}}var ci=class extends P{descriptor={id:`dema`,name:`Double Exponential Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`DEMA`,inputs:{period:{min:1},source:{source:!0}},plots:[{key:`value`,title:`DEMA`,color:0}]};emas=new WeakMap;calculate(e,t){let n=L(t,`period`,20,1),r=B(z(e),n),i=B(r,n),a=R(e,ni(r.map((e,t)=>e!==void 0&&i[t]!==void 0?2*e-i[t]:void 0)));return this.emas.set(a,{e1:r,e2:i}),a}update(e,t,n,r){let i=this.emas.get(n);if(!i||!this.canResume(e,n,r))return null;let a=i.e1[r-1],o=i.e2[r-1];if(a===void 0||o===void 0)return null;let s=2/(L(t,`period`,20,1)+1);for(let t=r;t<e.length;t++)a+=s*(e[t].close-a),o+=s*(a-o),i.e1[t]=a,i.e2[t]=o,this.writePoint(n,e,t,{value:2*a-o});return n}},li=class extends P{descriptor={id:`smma`,name:`Smoothed Moving Average`,placement:`overlay`,defaultConfig:{period:14,source:`close`},shortName:`SMMA`,inputs:{period:{min:1},source:{source:!0}},plots:[{key:`value`,title:`SMMA`,color:0}]};calculate(e,t){return R(e,ni(Zr(z(e),L(t,`period`,14,1))))}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=n.series[r-1]?.value;if(i===void 0)return null;let a=L(t,`period`,14,1);for(let t=r;t<e.length;t++)i+=(e[t].close-i)/a,this.writePoint(n,e,t,{value:i});return n}},V=class extends P{times=new WeakMap;lookback(e){return 0}revisesBefore(e){return this.lookback(this.read(e))}calculate(e,t){let n=this.read(t),r=Array(e.length);for(let t=0;t<e.length;t++)r[t]=this.pointAt(e,t,n);let i=R(e,r);return this.times.set(i,e.map(e=>e.time)),i}update(e,t,n,r){let i=this.times.get(n);if(!i||!this.canResume(e,n,r))return null;for(let t=r;t<i.length&&t<e.length;t++)if(i[t]!==e[t].time)return null;let a=this.read(t);for(let t=Math.max(0,r-this.lookback(a));t<e.length;t++)this.writePoint(n,e,t,this.pointAt(e,t,a));i.length=e.length;for(let t=r;t<e.length;t++)i[t]=e[t].time;return n}},ui=class extends V{descriptor={id:`alma`,name:`Arnaud Legoux Moving Average`,placement:`overlay`,defaultConfig:{period:9,offset:.85,sigma:6,source:`close`},shortName:`ALMA`,inputs:{period:{min:1,max:5e3},offset:{min:0,max:1,step:.05},sigma:{min:.5,step:.5},source:{source:!0}},plots:[{key:`value`,title:`ALMA`,color:0}]};read(e){let t=Math.min(5e3,L(e,`period`,9,1)),n=Math.min(1,Math.max(0,I(e,`offset`,.85))),r=Math.max(.5,I(e,`sigma`,6)),i=n*(t-1),a=t/r,o=Array.from({length:t},(e,t)=>Math.exp(-((t-i)**2)/(2*a*a)));return{period:t,weights:o,norm:o.reduce((e,t)=>e+t,0)}}pointAt(e,t,{period:n,weights:r,norm:i}){if(t<n-1)return null;let a=0;for(let i=0;i<n;i++)a+=r[i]*e[t-n+1+i].close;return{value:a/i}}},di=class extends P{descriptor={id:`kama`,name:`Kaufman Adaptive Moving Average`,placement:`overlay`,defaultConfig:{period:10,fast:2,slow:30,source:`close`},shortName:`KAMA`,inputs:{period:{min:1},fast:{min:1},slow:{min:1},source:{source:!0}},plots:[{key:`value`,title:`KAMA`,color:0}]};calculate(e,t){let n=R(e,Array(e.length).fill(null)),r=L(t,`period`,10,1);return e.length<=r||this.extend(e,t,n,r,e[r-1].close),n}update(e,t,n,r){if(r<=L(t,`period`,10,1)||!this.canResume(e,n,r))return null;let i=n.series[r-1]?.value;return i===void 0?null:(this.extend(e,t,n,r,i),n)}extend(e,t,n,r,i){let a=L(t,`period`,10,1),o=2/(L(t,`fast`,2,1)+1),s=2/(L(t,`slow`,30,1)+1);for(let t=r;t<e.length;t++){let r=0;for(let n=t-a+1;n<=t;n++)r+=Math.abs(e[n].close-e[n-1].close);let c=Math.abs(e[t].close-e[t-a].close),l=((r>0?c/r:0)*(o-s)+s)**2;i+=l*(e[t].close-i),this.writePoint(n,e,t,{value:i})}}},fi=class extends V{descriptor={id:`lsma`,name:`Least Squares Moving Average`,placement:`overlay`,defaultConfig:{period:25,offset:0,source:`close`},shortName:`LSMA`,inputs:{period:{min:2,max:5e3},offset:{step:1},source:{source:!0}},plots:[{key:`value`,title:`LSMA`,color:0}]};read(e){let t=Math.min(5e3,L(e,`period`,25,2)),n=Math.round(L(e,`offset`,0,-1e3)),r=t*(t-1)/2;return{period:t,offset:n,sx:r,denom:t*((t-1)*t*(2*t-1)/6)-r*r}}pointAt(e,t,{period:n,offset:r,sx:i,denom:a}){if(t<n-1)return null;let o=0,s=0;for(let r=0;r<n;r++){let i=e[t-n+1+r].close;o+=i,s+=r*i}let c=(n*s-i*o)/a;return{value:(o-c*i)/n+c*(n-1-r)}}},pi=class extends P{descriptor={id:`mcginley`,name:`McGinley Dynamic`,placement:`overlay`,defaultConfig:{period:14,source:`close`},shortName:`McGinley`,inputs:{period:{min:1},source:{source:!0}},plots:[{key:`value`,title:`McGinley`,color:0}]};calculate(e,t){let n=L(t,`period`,14,1),r=B(z(e),n),i=Array(e.length).fill(void 0),a;for(let t=0;t<e.length;t++)a=a===void 0?r[t]:mi(a,e[t].close,n),i[t]=a;return R(e,ni(i))}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let i=n.series[r-1]?.value;if(i===void 0)return null;let a=L(t,`period`,14,1);for(let t=r;t<e.length;t++)i=mi(i,e[t].close,a),this.writePoint(n,e,t,{value:i});return n}};function mi(e,t,n){return e>0&&t>0?e+(t-e)/(n*(t/e)**4):t}function hi(e){return e.params.type===`ema`?[`ema`,`ema`]:e.params.type===`sma-ema`?[`sma`,`ema`]:[`sma`,`sma`]}var gi=class extends P{descriptor={id:`macross`,name:`MA Cross`,placement:`overlay`,defaultConfig:{fast:9,slow:21,type:`sma`,source:`close`},shortName:`MA Cross`,inputs:{fast:{min:1},slow:{min:1},type:{options:[`sma`,`ema`,`sma-ema`]},source:{source:!0}},plots:[{key:`fast`,title:`Fast`,color:0},{key:`slow`,title:`Slow`,color:1}]};calculate(e,t){let[n,r]=hi(t),i=z(e),a=(t,n)=>t===`ema`?B(i,n):e.map((t,r)=>oi(e,r,n)),o=a(n,L(t,`fast`,9,1)),s=a(r,L(t,`slow`,21,1));return R(e,o.map((e,t)=>_i(e,s[t])))}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let[i,a]=hi(t),o=L(t,`fast`,9,1),s=L(t,`slow`,21,1),c=n.series[r-1]?.fast,l=n.series[r-1]?.slow;if(i===`ema`&&c===void 0||a===`ema`&&l===void 0)return null;for(let t=r;t<e.length;t++){let r=e[t].close;c=i===`ema`?c+2/(o+1)*(r-c):oi(e,t,o),l=a===`ema`?l+2/(s+1)*(r-l):oi(e,t,s),this.writePoint(n,e,t,_i(c,l))}return n}};function _i(e,t){return e===void 0&&t===void 0?null:{...e===void 0?{}:{fast:e},...t===void 0?{}:{slow:t}}}var vi=class extends V{descriptor={id:`fractals`,name:`Williams Fractals`,placement:`overlay`,defaultConfig:{period:2},shortName:`Fractals`,inputs:{period:{min:1,max:10}},plots:[{key:`up`,title:`Up`,color:0,kind:`dots`},{key:`down`,title:`Down`,color:1,kind:`dots`}]};read(e){return L(e,`period`,2,1)}lookback(e){return e}pointAt(e,t,n){if(t<n||t>e.length-n-1)return null;let r=!0,i=!0;for(let a=t-n;a<=t+n&&(r||i);a++)a!==t&&(e[a].high>=e[t].high&&(r=!1),e[a].low<=e[t].low&&(i=!1));return!r&&!i?null:{...r?{up:e[t].high}:{},...i?{down:e[t].low}:{}}}},yi=class extends P{descriptor={id:`cks`,name:`Chande Kroll Stop`,placement:`overlay`,defaultConfig:{p:10,x:1,q:9},shortName:`CKS`,inputs:{p:{label:`ATR length`,min:1},x:{label:`ATR multiplier`,min:0,step:.1},q:{label:`Stop length`,min:1}},plots:[{key:`long`,title:`Stop Long`,color:0},{key:`short`,title:`Stop Short`,color:1}]};states=new WeakMap;calculate(e,t){let n=L(t,`p`,10,1),r=I(t,`x`,1),i=L(t,`q`,9,1),a={atr:Zr($r(e),n),firstHigh:[],firstLow:[]};for(let t=0;t<e.length;t++)bi(e,a,t,n,r);let o=R(e,e.map((e,t)=>xi(a,t,i)));return this.states.set(o,a),o}update(e,t,n,r){let i=this.states.get(n);if(!i||!this.canResume(e,n,r))return null;let a=i.atr[r-1];if(a===void 0)return null;let o=L(t,`p`,10,1),s=I(t,`x`,1),c=L(t,`q`,9,1);for(let t=r;t<e.length;t++){let r=e[t-1].close,l=Math.max(e[t].high-e[t].low,Math.abs(e[t].high-r),Math.abs(e[t].low-r));a+=(l-a)/o,i.atr[t]=a,bi(e,i,t,o,s),this.writePoint(n,e,t,xi(i,t,c))}return n}};function bi(e,t,n,r,i){let a=t.atr[n],o=ii(e,n,r),s=ai(e,n,r);t.firstHigh[n]=o!==void 0&&a!==void 0?o-i*a:void 0,t.firstLow[n]=s!==void 0&&a!==void 0?s+i*a:void 0}function xi(e,t,n){let r=ei(e.firstHigh,t,n),i=ti(e.firstLow,t,n);return r!==void 0&&i!==void 0?{long:i,short:r}:null}var Si=class extends V{descriptor={id:`bbpb`,name:`Bollinger Bands %B`,placement:`panel`,defaultConfig:{period:20,stdDev:2,source:`close`},shortName:`%B`,inputs:{period:{min:2},stdDev:{min:.1,step:.1},source:{source:!0}},plots:[{key:`value`,title:`%B`,color:0}],levels:[0,.5,1]};read(e){return{period:L(e,`period`,20,2),k:I(e,`stdDev`,2)}}pointAt(e,t,{period:n,k:r}){let i=ri(e,t,n);return!i||i.sd===0?null:{value:(e[t].close-(i.mean-r*i.sd))/(2*r*i.sd)}}},Ci=class extends V{descriptor={id:`bbw`,name:`Bollinger BandWidth`,placement:`panel`,defaultConfig:{period:20,stdDev:2,source:`close`},shortName:`BBW`,inputs:{period:{min:2},stdDev:{min:.1,step:.1},source:{source:!0}},plots:[{key:`value`,title:`BBW`,color:0}]};read(e){return{period:L(e,`period`,20,2),k:I(e,`stdDev`,2)}}pointAt(e,t,{period:n,k:r}){let i=ri(e,t,n);return!i||i.mean===0?null:{value:2*r*i.sd/i.mean}}},wi=class extends V{descriptor={id:`mom`,name:`Momentum`,placement:`panel`,defaultConfig:{period:10,source:`close`},shortName:`MOM`,inputs:{period:{min:1},source:{source:!0}},plots:[{key:`value`,title:`MOM`,color:0}],levels:[0]};read(e){return L(e,`period`,10,1)}pointAt(e,t,n){return t>=n?{value:e[t].close-e[t-n].close}:null}},Ti=class extends V{descriptor={id:`hv`,name:`Historical Volatility`,placement:`panel`,defaultConfig:{period:10,annual:365,source:`close`},shortName:`HV`,inputs:{period:{min:2},annual:{label:`Bars per year`,min:1},source:{source:!0}},plots:[{key:`value`,title:`HV`,color:0}],scale:{min:0}};read(e){return{period:L(e,`period`,10,2),annual:Math.max(1,I(e,`annual`,365))}}pointAt(e,t,{period:n,annual:r}){if(t<n)return null;let i=0,a=0;for(let r=t-n+1;r<=t;r++){let t=e[r-1].close,n=e[r].close;if(!(t>0&&n>0))return null;let o=Math.log(n/t);i+=o,a+=o*o}let o=i/n;return{value:100*Math.sqrt(Math.max(0,a/n-o*o))*Math.sqrt(r)}}},Ei=class extends P{descriptor={id:`vo`,name:`Volume Oscillator`,placement:`panel`,defaultConfig:{short:5,long:10},shortName:`Vol Osc`,inputs:{short:{min:1},long:{min:1}},plots:[{key:`value`,title:`Vol Osc`,color:0}],levels:[0]};emas=new WeakMap;calculate(e,t){let n=e.map(e=>e.volume),r=B(n,L(t,`short`,5,1)),i=B(n,L(t,`long`,10,1)),a=R(e,ni(r.map((e,t)=>Di(e,i[t]))));return this.emas.set(a,{fast:r,slow:i}),a}update(e,t,n,r){let i=this.emas.get(n);if(!i||!this.canResume(e,n,r))return null;let a=i.fast[r-1],o=i.slow[r-1];if(a===void 0||o===void 0)return null;let s=2/(L(t,`short`,5,1)+1),c=2/(L(t,`long`,10,1)+1);for(let t=r;t<e.length;t++){a+=s*(e[t].volume-a),o+=c*(e[t].volume-o),i.fast[t]=a,i.slow[t]=o;let r=Di(a,o);this.writePoint(n,e,t,r===void 0?null:{value:r})}return n}};function Di(e,t){return e===void 0||t===void 0||t===0?void 0:100*(e-t)/t}var Oi=class extends P{descriptor={id:`ulcer`,name:`Ulcer Index`,placement:`panel`,defaultConfig:{period:14,source:`close`},shortName:`Ulcer`,inputs:{period:{min:1},source:{source:!0}},plots:[{key:`value`,title:`Ulcer`,color:0}],scale:{min:0}};drawdowns=new WeakMap;calculate(e,t){let n=L(t,`period`,14,1),r=e.map((t,r)=>ki(e,r,n)),i=R(e,e.map((e,t)=>Ai(r,t,n)));return this.drawdowns.set(i,r),i}update(e,t,n,r){let i=this.drawdowns.get(n);if(!i||!this.canResume(e,n,r))return null;let a=L(t,`period`,14,1);for(let t=r;t<e.length;t++)i[t]=ki(e,t,a);i.length=e.length;for(let t=r;t<e.length;t++)this.writePoint(n,e,t,Ai(i,t,a));return n}};function ki(e,t,n){if(t<n-1)return;let r=-1/0;for(let i=t-n+1;i<=t;i++)e[i].close>r&&(r=e[i].close);return r===0?void 0:100*(e[t].close-r)/r}function Ai(e,t,n){if(t<n-1)return null;let r=0;for(let i=t-n+1;i<=t;i++){let t=e[i];if(t===void 0)return null;r+=t*t}return{value:Math.sqrt(r/n)}}var ji=class extends P{descriptor={id:`smi`,name:`Stochastic Momentum Index`,placement:`panel`,defaultConfig:{period:10,smooth:3,signal:3},shortName:`SMI`,inputs:{period:{min:1},smooth:{min:1},signal:{min:1}},plots:[{key:`smi`,title:`SMI`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[40,-40]};calculate(e,t){let n=L(t,`period`,10,1),r=L(t,`smooth`,3,1),i=L(t,`signal`,3,1),a=Array(e.length).fill(void 0),o=Array(e.length).fill(void 0);for(let t=n-1;t<e.length;t++){let r=ii(e,t,n),i=ai(e,t,n);r===void 0||i===void 0||(a[t]=e[t].close-(r+i)/2,o[t]=r-i)}let s=B(B(a,r),r),c=B(B(o,r),r),l=s.map((e,t)=>{let n=c[t]===void 0?void 0:c[t]/2;if(!(e===void 0||n===void 0))return n===0?0:Math.max(-100,Math.min(100,100*e/n))}),u=B(l,i);return R(e,l.map((e,t)=>{if(e===void 0)return null;let n={smi:e};return u[t]!==void 0&&(n.signal=u[t]),n}))}},Mi=class extends P{descriptor={id:`rvix`,name:`Relative Volatility Index`,placement:`panel`,defaultConfig:{period:10,smooth:14},shortName:`RVI (vol)`,inputs:{period:{min:2},smooth:{min:1}},plots:[{key:`value`,title:`RVI`,color:0}],levels:[80,50,20],scale:{min:0,max:100}};calculate(e,t){let n=L(t,`period`,10,2),r=L(t,`smooth`,14,1),i=Qr(z(e),n),a=i.map((t,n)=>t===void 0||n===0?void 0:e[n].close>e[n-1].close?t:0),o=i.map((t,n)=>t===void 0||n===0?void 0:e[n].close<e[n-1].close?t:0),s=B(a,r),c=B(o,r);return R(e,ni(s.map((e,t)=>{let n=c[t];if(!(e===void 0||n===void 0))return e+n===0?50:100*e/(e+n)})))}},Ni=class extends V{descriptor={id:`trendstrength`,name:`Trend Strength Index`,placement:`panel`,defaultConfig:{period:14},shortName:`TSI (trend)`,inputs:{period:{min:2}},plots:[{key:`value`,title:`Trend`,color:0}],levels:[0],scale:{min:-1,max:1}};read(e){return L(e,`period`,14,2)}pointAt(e,t,n){let r=si(e,t,n);return r?{value:r.r}:null}},Pi=class extends V{descriptor={id:`lrslope`,name:`Linear Regression Slope`,placement:`panel`,defaultConfig:{period:14},shortName:`LR Slope`,inputs:{period:{min:2}},plots:[{key:`value`,title:`Slope`,color:0}],levels:[0]};read(e){return L(e,`period`,14,2)}pointAt(e,t,n){let r=si(e,t,n);return r?{value:r.slope}:null}},Fi=class extends V{descriptor={id:`stderror`,name:`Standard Error`,placement:`panel`,defaultConfig:{period:14},shortName:`StdErr`,inputs:{period:{min:3}},plots:[{key:`value`,title:`StdErr`,color:0}],scale:{min:0}};read(e){return L(e,`period`,14,3)}pointAt(e,t,n){let r=si(e,t,n);return r?{value:r.stdErr}:null}},Ii=class extends V{descriptor={id:`adr`,name:`Average Day Range`,placement:`panel`,defaultConfig:{period:14},shortName:`ADR`,inputs:{period:{min:1}},plots:[{key:`value`,title:`ADR`,color:0}],scale:{min:0}};read(e){return L(e,`period`,14,1)}pointAt(e,t,n){if(t<n-1)return null;let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i].high-e[i].low;return{value:r/n}}},Li=class extends V{descriptor={id:`netvolume`,name:`Net Volume`,placement:`panel`,defaultConfig:{},shortName:`Net Vol`,plots:[{key:`value`,title:`Net`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}],levels:[0]};read(e){return null}pointAt(e,t){if(t===0)return null;let n=e[t].close-e[t-1].close,r=e[t].volume??0;return{value:n>0?r:n<0?-r:0,up:+(n>=0)}}lookback(){return 1}},Ri=class extends P{descriptor={id:`seb`,name:`Standard Error Bands`,placement:`overlay`,defaultConfig:{period:21,mult:2,smooth:3},shortName:`SEB`,inputs:{period:{min:3},mult:{min:0,step:.1},smooth:{min:1}},plots:[{key:`upper`,title:`Upper`,color:1},{key:`middle`,title:`Middle`,color:0},{key:`lower`,title:`Lower`,color:1}]};calculate(e,t){let n=L(t,`period`,21,3),r=I(t,`mult`,2),i=L(t,`smooth`,3,1),a=Array(e.length).fill(void 0),o=Array(e.length).fill(void 0),s=Array(e.length).fill(void 0);for(let t=0;t<e.length;t++){let i=si(e,t,n);i&&(a[t]=i.end,o[t]=i.end+r*i.stdErr,s[t]=i.end-r*i.stdErr)}let c=Jr(a,i),l=Jr(o,i),u=Jr(s,i);return R(e,c.map((e,t)=>e===void 0||l[t]===void 0||u[t]===void 0?null:{middle:e,upper:l[t],lower:u[t]}))}},zi=[3,5,8,10,12,15],Bi=[30,35,40,45,50,60],Vi=class extends P{descriptor={id:`gmma`,name:`Guppy Multiple Moving Average`,placement:`overlay`,defaultConfig:{},shortName:`GMMA`,plots:[...zi.map(e=>({key:`s${e}`,title:`EMA ${e}`,color:0})),...Bi.map(e=>({key:`l${e}`,title:`EMA ${e}`,color:1}))]};calculate(e,t){let n=z(e),r=[...zi.map(e=>[`s${e}`,B(n,e)]),...Bi.map(e=>[`l${e}`,B(n,e)])];return R(e,e.map((e,t)=>{let n={},i=!1;for(let[e,a]of r)a[t]!==void 0&&(n[e]=a[t],i=!0);return i?n:null}))}},Hi=class extends P{descriptor={id:`maribbon`,name:`Moving Average Ribbon`,placement:`overlay`,defaultConfig:{ma1:20,ma2:50,ma3:100,ma4:200,exponential:0},shortName:`MA Ribbon`,inputs:{ma1:{min:1},ma2:{min:1},ma3:{min:1},ma4:{min:1},exponential:{min:0,max:1}},plots:[{key:`ma1`,title:`MA 1`,color:0},{key:`ma2`,title:`MA 2`,color:1},{key:`ma3`,title:`MA 3`,color:2},{key:`ma4`,title:`MA 4`,color:3}]};calculate(e,t){let n=I(t,`exponential`,0)>=1?B:Jr,r=z(e),i=[`ma1`,`ma2`,`ma3`,`ma4`],a=[20,50,100,200],o=i.map((e,i)=>[e,n(r,L(t,e,a[i],1))]);return R(e,e.map((e,t)=>{let n={},r=!1;for(let[e,i]of o)i[t]!==void 0&&(n[e]=i[t],r=!0);return r?n:null}))}},Ui=class extends V{read(e){return null}pointAt(e,t){return{value:this.price(e[t])}}},Wi=class extends Ui{descriptor={id:`avgprice`,name:`Average Price`,placement:`overlay`,defaultConfig:{},shortName:`OHLC4`,plots:[{key:`value`,title:`Average`,color:0}]};price(e){return(e.open+e.high+e.low+e.close)/4}},Gi=class extends Ui{descriptor={id:`medprice`,name:`Median Price`,placement:`overlay`,defaultConfig:{},shortName:`HL2`,plots:[{key:`value`,title:`Median`,color:0}]};price(e){return(e.high+e.low)/2}},Ki=class extends Ui{descriptor={id:`typprice`,name:`Typical Price`,placement:`overlay`,defaultConfig:{},shortName:`HLC3`,plots:[{key:`value`,title:`Typical`,color:0}]};price(e){return(e.high+e.low+e.close)/3}},qi=class extends Ui{descriptor={id:`wclose`,name:`Weighted Close`,placement:`overlay`,defaultConfig:{},shortName:`HLCC4`,plots:[{key:`value`,title:`Weighted`,color:0}]};price(e){return(e.high+e.low+2*e.close)/4}},Ji=class extends V{descriptor={id:`psy`,name:`Psychological Line`,placement:`panel`,defaultConfig:{period:10},shortName:`PSY`,plots:[{key:`value`,title:`PSY`,color:0}],scale:{min:0,max:100},levels:[25,75]};read(e){return L(e,`period`,10,1)}pointAt(e,t,n){if(t<n)return null;let r=0;for(let i=t-n+1;i<=t;i++)e[i].close>e[i-1].close&&r++;return{value:r/n*100}}},Yi=class extends V{descriptor={id:`newpsy`,name:`New Psychological Line`,placement:`panel`,defaultConfig:{period:10},shortName:`New PSY`,plots:[{key:`value`,title:`New PSY`,color:0}],scale:{min:-100,max:100},levels:[-50,0,50]};read(e){return L(e,`period`,10,1)}pointAt(e,t,n){if(t<n)return null;let r=0,i=0,a=0,o=0;for(let s=t-n+1;s<=t;s++){let t=e[s].close-e[s-1].close;t>0?(r++,a+=t):t<0&&(i++,o-=t)}let s=a+o;return{value:s===0?0:(r*a-i*o)/(s*n)*100}}},Xi=class extends V{descriptor={id:`vr`,name:`Volume Ratio`,placement:`panel`,defaultConfig:{period:20},shortName:`VR`,plots:[{key:`value`,title:`VR`,color:0}],levels:[70,150,450]};read(e){return L(e,`period`,20,1)}pointAt(e,t,n){if(t<n)return null;let r=0,i=0,a=0;for(let o=t-n+1;o<=t;o++){let t=e[o].close-e[o-1].close;t>0?r+=e[o].volume:t<0?i+=e[o].volume:a+=e[o].volume}let o=i+a/2;return o>0?{value:(r+a/2)/o*100}:null}},Zi=class extends V{descriptor={id:`abratio`,name:`AB Ratio`,placement:`panel`,defaultConfig:{period:26},shortName:`AB Ratio`,plots:[{key:`a`,title:`A`,color:0},{key:`b`,title:`B`,color:1}],levels:[100]};read(e){return L(e,`period`,26,1)}pointAt(e,t,n){if(t<n)return null;let r=0,i=0,a=0,o=0;for(let s=t-n+1;s<=t;s++){let{open:t,high:n,low:c}=e[s],l=e[s-1].close;r+=n-t,i+=t-c,a+=Math.max(0,n-l),o+=Math.max(0,l-c)}let s={};return i>0&&(s.a=r/i*100),o>0&&(s.b=a/o*100),s.a!==void 0||s.b!==void 0?s:null}},Qi=class extends P{descriptor={id:`sonar`,name:`Sonar`,placement:`panel`,defaultConfig:{period:20,lookback:9,signal:9},shortName:`Sonar`,plots:[{key:`sonar`,title:`Sonar`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=L(t,`period`,20,1),r=L(t,`lookback`,9,1),i=L(t,`signal`,9,1),a=B(z(e),n),o=a.map((e,t)=>e!==void 0&&t>=r&&a[t-r]!==void 0?e-a[t-r]:void 0),s=B(o,i);return R(e,o.map((e,t)=>e===void 0?null:s[t]===void 0?{sonar:e}:{sonar:e,signal:s[t]}))}},$i=class extends V{descriptor={id:`sigma`,name:`Sigma`,placement:`panel`,defaultConfig:{period:20},shortName:`Sigma`,plots:[{key:`value`,title:`Sigma`,color:0}],levels:[-2,0,2]};read(e){return L(e,`period`,20,2)}pointAt(e,t,n){let r=ri(e,t,n);return r?{value:r.sd<=Math.abs(r.mean)*1e-9?0:(e[t].close-r.mean)/r.sd}:null}},ea=class extends V{descriptor={id:`vhf`,name:`Vertical Horizontal Filter`,placement:`panel`,defaultConfig:{period:28},shortName:`VHF`,plots:[{key:`value`,title:`VHF`,color:0}]};read(e){return L(e,`period`,28,1)}pointAt(e,t,n){if(t<n)return null;let r=e[t-n].close,i=r,a=0;for(let o=t-n+1;o<=t;o++){let t=e[o].close;t>r&&(r=t),t<i&&(i=t),a+=Math.abs(t-e[o-1].close)}return a>0?{value:(r-i)/a}:null}},ta=class extends V{descriptor={id:`rsquared`,name:`R-Squared`,placement:`panel`,defaultConfig:{period:14},shortName:`R²`,plots:[{key:`value`,title:`R²`,color:0}],scale:{min:0,max:1}};read(e){return L(e,`period`,14,2)}pointAt(e,t,n){let r=si(e,t,n);return r?{value:r.r*r.r}:null}};function na(e,t){let n=e[t];if(t===0)return n.high-n.low;let r=e[t-1].close;return Math.max(n.high-n.low,Math.abs(n.high-r),Math.abs(n.low-r))}var ra=class extends V{descriptor={id:`rwi`,name:`Random Walk Index`,placement:`panel`,defaultConfig:{period:14},shortName:`RWI`,plots:[{key:`high`,title:`RWI High`,color:0},{key:`low`,title:`RWI Low`,color:1}],levels:[1]};read(e){return L(e,`period`,14,2)}pointAt(e,t,n){if(t<n)return null;let r=0,i=0,a=na(e,t);for(let o=1;o<=n;o++){if(o>1){let n=a/o*Math.sqrt(o);n>0&&(r=Math.max(r,(e[t].high-e[t-o].low)/n),i=Math.max(i,(e[t-o].high-e[t].low)/n))}a+=na(e,t-o)}return{high:r,low:i}}},ia=1e3,aa=class extends P{calculate(e,t){let n=Array(e.length).fill(void 0),r=ia;for(let t=0;t<e.length;t++){if(t>0){let n=e[t-1].close;n!==0&&this.counts(e[t].volume,e[t-1].volume)&&(r*=e[t].close/n)}n[t]=r}let i=B(n,L(t,`signal`,255,1));return R(e,n.map((e,t)=>i[t]===void 0?{value:e}:{value:e,signal:i[t]}))}},oa=class extends aa{descriptor={id:`nvi`,name:`Negative Volume Index`,placement:`panel`,defaultConfig:{signal:255},shortName:`NVI`,plots:[{key:`value`,title:`NVI`,color:0},{key:`signal`,title:`Signal`,color:1}]};counts(e,t){return e<t}},sa=class extends aa{descriptor={id:`pvi`,name:`Positive Volume Index`,placement:`panel`,defaultConfig:{signal:255},shortName:`PVI`,plots:[{key:`value`,title:`PVI`,color:0},{key:`signal`,title:`Signal`,color:1}]};counts(e,t){return e>t}},ca=class extends V{descriptor={id:`tr`,name:`True Range`,placement:`panel`,defaultConfig:{},shortName:`TR`,plots:[{key:`value`,title:`TR`,color:0}]};read(e){return null}pointAt(e,t){let n=e[t];if(t===0)return{value:n.high-n.low};let r=e[t-1].close;return{value:Math.max(n.high-n.low,Math.abs(n.high-r),Math.abs(n.low-r))}}},la=class extends V{descriptor={id:`iii`,name:`Intraday Intensity`,placement:`panel`,defaultConfig:{period:21},shortName:`III`,plots:[{key:`value`,title:`III %`,color:0,kind:`histogram`,tone:`sign`,downColor:1}],scale:{zero:!0},levels:[0]};read(e){return L(e,`period`,21,1)}pointAt(e,t,n){if(t<n-1)return null;let r=0,i=0;for(let a=t-n+1;a<=t;a++){let t=e[a];i+=t.volume,t.high>t.low&&(r+=t.volume*(2*t.close-t.high-t.low)/(t.high-t.low))}return i>0?{value:Math.max(-100,Math.min(100,r/i*100))}:{value:0}}},ua=class extends V{descriptor={id:`volpct`,name:`Volume vs Average`,placement:`panel`,defaultConfig:{period:20},shortName:`Vol %`,plots:[{key:`value`,title:`Vol %`,color:0,kind:`histogram`,tone:`sign`,downColor:1}],scale:{zero:!0},levels:[0]};read(e){return L(e,`period`,20,1)}pointAt(e,t,n){if(t<n-1)return null;let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i].volume;let i=r/n,a=(e[t].volume-i)/i*100;return i>0&&Number.isFinite(a)?{value:a}:null}},da=class extends V{descriptor={id:`volchange`,name:`Volume Change`,placement:`panel`,defaultConfig:{},shortName:`Vol Δ`,plots:[{key:`value`,title:`Volume`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}],scale:{zero:!0}};read(e){return null}pointAt(e,t){let{volume:n}=e[t];return Number.isFinite(n)?{value:n,up:+(t===0||n>=e[t-1].volume)}:null}},fa=class extends V{descriptor={id:`tradevalue`,name:`Trade Value`,placement:`panel`,defaultConfig:{},shortName:`Value`,plots:[{key:`value`,title:`Value`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}],scale:{zero:!0}};read(e){return null}pointAt(e,t){let n=e[t],r=n.close*n.volume;return Number.isFinite(r)?{value:r,up:+(n.close>=n.open)}:null}},pa=class extends P{descriptor={id:`binarywave`,name:`Binary Wave`,placement:`panel`,defaultConfig:{ma:20,fast:12,slow:26,signal:9,roc:12,stoch:14},shortName:`Binary Wave`,plots:[{key:`value`,title:`Wave`,color:0,kind:`step`}],scale:{min:-4,max:4},levels:[0]};calculate(e,t){let n=z(e),r=Jr(n,L(t,`ma`,20,1)),i=B(n,L(t,`fast`,12,1)),a=B(n,L(t,`slow`,26,1)),o=i.map((e,t)=>e!==void 0&&a[t]!==void 0?e-a[t]:void 0),s=B(o,L(t,`signal`,9,1)),c=L(t,`roc`,12,1),l=L(t,`stoch`,14,1),u=e=>e?1:-1;return R(e,ni(e.map((t,i)=>{let a=ii(e,i,l),d=ai(e,i,l);if(r[i]===void 0||o[i]===void 0||s[i]===void 0||i<c||a===void 0||d===void 0)return;let f=a>d?(t.close-d)/(a-d)*100:50;return u(t.close>r[i])+u(o[i]>s[i])+u(t.close>n[i-c])+u(f>50)})))}},ma=class extends P{descriptor={id:`sroc`,name:`Smoothed Rate of Change`,placement:`panel`,defaultConfig:{ema:13,roc:21},shortName:`S-ROC`,plots:[{key:`value`,title:`S-ROC`,color:0}],levels:[0]};calculate(e,t){let n=B(z(e),L(t,`ema`,13,1)),r=L(t,`roc`,21,1);return R(e,ni(n.map((e,t)=>{let i=t>=r?n[t-r]:void 0;return e!==void 0&&i!==void 0&&i!==0?(e-i)/Math.abs(i)*100:void 0})))}},ha=class extends V{descriptor={id:`tsf`,name:`Time Series Forecast`,placement:`overlay`,defaultConfig:{period:14},shortName:`TSF`,plots:[{key:`value`,title:`TSF`,color:0}]};read(e){return L(e,`period`,14,2)}pointAt(e,t,n){let r=si(e,t,n);return r?{value:r.end+r.slope}:null}},ga=class extends V{descriptor={id:`demark`,name:`DeMark Projected Range`,placement:`overlay`,defaultConfig:{},shortName:`DeMark`,plots:[{key:`high`,title:`Projected high`,color:0,kind:`step`},{key:`low`,title:`Projected low`,color:1,kind:`step`}]};read(e){return null}pointAt(e,t){if(t===0)return null;let{open:n,high:r,low:i,close:a}=e[t-1],o=a>n?2*r+i+a:a<n?r+2*i+a:r+i+2*a;return{high:o/2-i,low:o/2-r}}},_a=class extends P{descriptor={id:`rainbow`,name:`Moving Average Rainbow`,placement:`overlay`,defaultConfig:{first:10,step:10,count:10,exponential:0},shortName:`Rainbow`,inputs:{first:{min:1},step:{min:1},count:{min:1,max:20},exponential:{min:0,max:1}},plots:Array.from({length:20},(e,n)=>({key:`ma${n+1}`,title:`MA ${n+1}`,color:n%t.TC_SERIES_COLORS.length}))};calculate(e,t){let n=L(t,`first`,10,1),r=L(t,`step`,10,1),i=Math.min(20,L(t,`count`,10,1)),a=L(t,`exponential`,0,0)>=1?B:Jr,o=z(e),s=Array.from({length:i},(e,t)=>[`ma${t+1}`,a(o,n+t*r)]);return R(e,e.map((e,t)=>{let n={},r=!1;for(let[e,i]of s)i[t]!==void 0&&(n[e]=i[t],r=!0);return r?n:null}))}},va=.05,ya=class{bodies=new Map;ranges=new Map;trends=new Map;constructor(e,t){this.data=e,this.period=t}open(e){return this.data[e].open}high(e){return this.data[e].high}low(e){return this.data[e].low}close(e){return this.data[e].close}body(e){return Math.abs(this.data[e].close-this.data[e].open)}range(e){return this.data[e].high-this.data[e].low}bodyTop(e){return Math.max(this.data[e].open,this.data[e].close)}bodyBottom(e){return Math.min(this.data[e].open,this.data[e].close)}mid(e){return(this.data[e].open+this.data[e].close)/2}upper(e){return this.data[e].high-this.bodyTop(e)}lower(e){return this.bodyBottom(e)-this.data[e].low}white(e){return this.data[e].close>this.data[e].open}black(e){return this.data[e].close<this.data[e].open}avgBody(e){let t=this.bodies.get(e);return t===void 0&&(t=this.averageBefore(e,e=>this.body(e)),this.bodies.set(e,t)),t}avgRange(e){let t=this.ranges.get(e);return t===void 0&&(t=this.averageBefore(e,e=>this.range(e)),this.ranges.set(e,t)),t}averageBefore(e,t){let n=Math.max(0,e-this.period);if(e<=n)return t(e);let r=0;for(let i=n;i<e;i++)r+=t(i);return r/(e-n)}bodyScale(e){return Math.max(this.avgBody(e),this.avgRange(e)*.25)}long(e,t=e){let n=this.bodyScale(t);return n>0&&this.body(e)>n}short(e,t=e){return this.body(e)<this.bodyScale(t)*.5}doji(e){return this.range(e)>0&&this.body(e)<=this.range(e)*.1}marubozu(e,t=e){return this.long(e,t)&&this.upper(e)<=this.range(e)*.05&&this.lower(e)<=this.range(e)*.05}same(e,t,n){return Math.abs(e-t)<=this.avgRange(n)*va}bodyGapUp(e,t){return this.bodyBottom(t)>this.bodyTop(e)}bodyGapDown(e,t){return this.bodyTop(t)<this.bodyBottom(e)}bodyInside(e,t){return this.bodyTop(t)<=this.bodyTop(e)&&this.bodyBottom(t)>=this.bodyBottom(e)&&this.body(t)<this.body(e)}trendBefore(e){let t=this.trends.get(e);return t===void 0&&(t=this.readTrend(e),this.trends.set(e,t)),t}readTrend(e){let t=e-1;if(t<this.period-1)return null;let n=0;for(let e=t-this.period+1;e<=t;e++)n+=this.close(e);let r=n/this.period,i=this.close(t),a=this.close(t-this.period+1);return i>r&&i>a?`up`:i<r&&i<a?`down`:null}};function H(e,t,n,r,i,a,o,s){return{info:Object.freeze({id:e,name:t,short:n,direction:r,kind:i,bars:a}),trend:o,test:s}}function ba(e,t){let n=e.range(t);return n>0&&n>=e.avgRange(t)*.5&&e.body(t)<=n*.35&&e.lower(t)>=2*Math.max(e.body(t),n*.05)&&e.upper(t)<=n*.1}function xa(e,t){let n=e.range(t);return n>0&&n>=e.avgRange(t)*.5&&e.body(t)<=n*.35&&e.upper(t)>=2*Math.max(e.body(t),n*.05)&&e.lower(t)<=n*.1}var Sa=[H(`doji`,`Doji`,`Doji`,`neutral`,`indecision`,1,null,(e,t)=>e.doji(t)),H(`longLeggedDoji`,`Long-Legged Doji`,`LL Doji`,`neutral`,`indecision`,1,null,(e,t)=>e.doji(t)&&e.upper(t)>=e.range(t)*.3&&e.lower(t)>=e.range(t)*.3&&e.range(t)>e.avgRange(t)),H(`dragonflyDoji`,`Dragonfly Doji`,`Dragonfly`,`bullish`,`reversal`,1,`down`,(e,t)=>e.doji(t)&&e.upper(t)<=e.range(t)*.1&&e.lower(t)>=e.range(t)*.6),H(`gravestoneDoji`,`Gravestone Doji`,`Gravestone`,`bearish`,`reversal`,1,`up`,(e,t)=>e.doji(t)&&e.lower(t)<=e.range(t)*.1&&e.upper(t)>=e.range(t)*.6),H(`hammer`,`Hammer`,`Hammer`,`bullish`,`reversal`,1,`down`,ba),H(`hangingMan`,`Hanging Man`,`Hanging`,`bearish`,`reversal`,1,`up`,ba),H(`invertedHammer`,`Inverted Hammer`,`Inv Hammer`,`bullish`,`reversal`,1,`down`,xa),H(`shootingStar`,`Shooting Star`,`Shooting`,`bearish`,`reversal`,1,`up`,xa),H(`spinningTop`,`Spinning Top`,`Spinning`,`neutral`,`indecision`,1,null,(e,t)=>!e.doji(t)&&e.body(t)<=e.range(t)*.3&&e.upper(t)>e.body(t)&&e.lower(t)>e.body(t)),H(`bullishMarubozu`,`Bullish Marubozu`,`Marubozu`,`bullish`,`continuation`,1,null,(e,t)=>e.white(t)&&e.marubozu(t)),H(`bearishMarubozu`,`Bearish Marubozu`,`Marubozu`,`bearish`,`continuation`,1,null,(e,t)=>e.black(t)&&e.marubozu(t)),H(`bullishBeltHold`,`Bullish Belt Hold`,`Belt Hold`,`bullish`,`reversal`,1,`down`,(e,t)=>e.white(t)&&e.long(t)&&e.lower(t)<=e.range(t)*.05&&e.upper(t)>e.range(t)*.05),H(`bearishBeltHold`,`Bearish Belt Hold`,`Belt Hold`,`bearish`,`reversal`,1,`up`,(e,t)=>e.black(t)&&e.long(t)&&e.upper(t)<=e.range(t)*.05&&e.lower(t)>e.range(t)*.05)],Ca=[H(`bullishEngulfing`,`Bullish Engulfing`,`Engulf`,`bullish`,`reversal`,2,`down`,(e,t)=>{let n=t-1;return e.black(n)&&e.white(t)&&e.open(t)<=e.close(n)&&e.close(t)>=e.open(n)&&e.body(t)>e.body(n)}),H(`bearishEngulfing`,`Bearish Engulfing`,`Engulf`,`bearish`,`reversal`,2,`up`,(e,t)=>{let n=t-1;return e.white(n)&&e.black(t)&&e.open(t)>=e.close(n)&&e.close(t)<=e.open(n)&&e.body(t)>e.body(n)}),H(`bullishHarami`,`Bullish Harami`,`Harami`,`bullish`,`reversal`,2,`down`,(e,t)=>e.black(t-1)&&e.long(t-1,t-1)&&!e.doji(t)&&e.bodyInside(t-1,t)&&e.body(t)<e.body(t-1)*.6),H(`bearishHarami`,`Bearish Harami`,`Harami`,`bearish`,`reversal`,2,`up`,(e,t)=>e.white(t-1)&&e.long(t-1,t-1)&&!e.doji(t)&&e.bodyInside(t-1,t)&&e.body(t)<e.body(t-1)*.6),H(`bullishHaramiCross`,`Bullish Harami Cross`,`Harami +`,`bullish`,`reversal`,2,`down`,(e,t)=>e.black(t-1)&&e.long(t-1,t-1)&&e.doji(t)&&e.bodyInside(t-1,t)),H(`bearishHaramiCross`,`Bearish Harami Cross`,`Harami +`,`bearish`,`reversal`,2,`up`,(e,t)=>e.white(t-1)&&e.long(t-1,t-1)&&e.doji(t)&&e.bodyInside(t-1,t)),H(`piercingLine`,`Piercing Line`,`Piercing`,`bullish`,`reversal`,2,`down`,(e,t)=>{let n=t-1;return e.black(n)&&e.long(n,n)&&e.white(t)&&e.open(t)<e.low(n)&&e.close(t)>e.mid(n)&&e.close(t)<e.open(n)}),H(`darkCloudCover`,`Dark Cloud Cover`,`Dark Cloud`,`bearish`,`reversal`,2,`up`,(e,t)=>{let n=t-1;return e.white(n)&&e.long(n,n)&&e.black(t)&&e.open(t)>e.high(n)&&e.close(t)<e.mid(n)&&e.close(t)>e.open(n)}),H(`tweezerBottom`,`Tweezer Bottom`,`Tweezer`,`bullish`,`reversal`,2,`down`,(e,t)=>e.black(t-1)&&e.white(t)&&e.same(e.low(t-1),e.low(t),t-1)),H(`tweezerTop`,`Tweezer Top`,`Tweezer`,`bearish`,`reversal`,2,`up`,(e,t)=>e.white(t-1)&&e.black(t)&&e.same(e.high(t-1),e.high(t),t-1)),H(`bullishKicking`,`Bullish Kicking`,`Kicking`,`bullish`,`reversal`,2,null,(e,t)=>e.black(t-1)&&e.marubozu(t-1,t-1)&&e.white(t)&&e.marubozu(t,t-1)&&e.low(t)>e.high(t-1)),H(`bearishKicking`,`Bearish Kicking`,`Kicking`,`bearish`,`reversal`,2,null,(e,t)=>e.white(t-1)&&e.marubozu(t-1,t-1)&&e.black(t)&&e.marubozu(t,t-1)&&e.high(t)<e.low(t-1)),H(`bullishCounterattack`,`Bullish Counterattack`,`Counter`,`bullish`,`reversal`,2,`down`,(e,t)=>e.black(t-1)&&e.long(t-1,t-1)&&e.white(t)&&e.long(t,t-1)&&e.same(e.close(t),e.close(t-1),t-1)),H(`bearishCounterattack`,`Bearish Counterattack`,`Counter`,`bearish`,`reversal`,2,`up`,(e,t)=>e.white(t-1)&&e.long(t-1,t-1)&&e.black(t)&&e.long(t,t-1)&&e.same(e.close(t),e.close(t-1),t-1)),H(`matchingLow`,`Matching Low`,`Match Low`,`bullish`,`reversal`,2,`down`,(e,t)=>e.black(t-1)&&e.long(t-1,t-1)&&e.black(t)&&e.same(e.close(t),e.close(t-1),t-1)),H(`homingPigeon`,`Homing Pigeon`,`Pigeon`,`bullish`,`reversal`,2,`down`,(e,t)=>e.black(t-1)&&e.long(t-1,t-1)&&e.black(t)&&e.short(t,t-1)&&e.bodyInside(t-1,t)),H(`onNeck`,`On Neck`,`On Neck`,`bearish`,`continuation`,2,`down`,(e,t)=>{let n=t-1;return e.black(n)&&e.long(n,n)&&e.white(t)&&e.open(t)<e.low(n)&&e.same(e.close(t),e.low(n),n)&&e.close(t)<e.close(n)}),H(`inNeck`,`In Neck`,`In Neck`,`bearish`,`continuation`,2,`down`,(e,t)=>{let n=t-1;return e.black(n)&&e.long(n,n)&&e.white(t)&&e.open(t)<e.low(n)&&e.close(t)>e.close(n)&&e.close(t)<=e.close(n)+e.body(n)*.1}),H(`thrusting`,`Thrusting`,`Thrusting`,`bearish`,`continuation`,2,`down`,(e,t)=>{let n=t-1;return e.black(n)&&e.long(n,n)&&e.white(t)&&e.open(t)<e.low(n)&&e.close(t)>e.close(n)+e.body(n)*.1&&e.close(t)<e.mid(n)}),H(`bullishSeparatingLines`,`Bullish Separating Lines`,`Separating`,`bullish`,`continuation`,2,`up`,(e,t)=>e.black(t-1)&&e.white(t)&&e.long(t,t-1)&&e.lower(t)<=e.range(t)*.05&&e.same(e.open(t),e.open(t-1),t-1)),H(`bearishSeparatingLines`,`Bearish Separating Lines`,`Separating`,`bearish`,`continuation`,2,`down`,(e,t)=>e.white(t-1)&&e.black(t)&&e.long(t,t-1)&&e.upper(t)<=e.range(t)*.05&&e.same(e.open(t),e.open(t-1),t-1))];function wa(e,t){for(let n=t;n<t+3;n++)if(!e.white(n)||e.short(n,t)||e.upper(n)>e.body(n)*.25||n>t&&(e.close(n)<=e.close(n-1)||e.open(n)<e.open(n-1)||e.open(n)>e.close(n-1)))return!1;return!0}function Ta(e,t){for(let n=t;n<t+3;n++)if(!e.black(n)||e.short(n,t)||e.lower(n)>e.body(n)*.25||n>t&&(e.close(n)>=e.close(n-1)||e.open(n)>e.open(n-1)||e.open(n)<e.close(n-1)))return!1;return!0}function Ea(e,t,n,r){for(let i=t+1;i<=n;i++)if(r?e.close(i)>=e.close(i-1):e.close(i)<=e.close(i-1))return!1;return!0}function Da(e,t,n,r,i){for(let a=n;a<=r;a++)if((i?!e.black(a):!e.white(a))||e.long(a,t)||e.high(a)>e.high(t)||e.low(a)<e.low(t))return!1;return!0}var Oa=[H(`morningStar`,`Morning Star`,`M. Star`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.long(n,n)&&e.short(r,n)&&!e.doji(r)&&e.bodyGapDown(n,r)&&e.white(t)&&e.close(t)>e.mid(n)}),H(`eveningStar`,`Evening Star`,`E. Star`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.short(r,n)&&!e.doji(r)&&e.bodyGapUp(n,r)&&e.black(t)&&e.close(t)<e.mid(n)}),H(`morningDojiStar`,`Morning Doji Star`,`M. Doji`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.long(n,n)&&e.doji(r)&&e.bodyGapDown(n,r)&&e.white(t)&&e.close(t)>e.mid(n)}),H(`eveningDojiStar`,`Evening Doji Star`,`E. Doji`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.doji(r)&&e.bodyGapUp(n,r)&&e.black(t)&&e.close(t)<e.mid(n)}),H(`bullishAbandonedBaby`,`Bullish Abandoned Baby`,`Abandoned`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.long(n,n)&&e.doji(r)&&e.high(r)<e.low(n)&&e.white(t)&&!e.short(t,n)&&e.low(t)>e.high(r)}),H(`bearishAbandonedBaby`,`Bearish Abandoned Baby`,`Abandoned`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.doji(r)&&e.low(r)>e.high(n)&&e.black(t)&&!e.short(t,n)&&e.high(t)<e.low(r)}),H(`threeWhiteSoldiers`,`Three White Soldiers`,`3 Soldiers`,`bullish`,`reversal`,3,null,(e,t)=>wa(e,t-2)),H(`threeBlackCrows`,`Three Black Crows`,`3 Crows`,`bearish`,`reversal`,3,null,(e,t)=>Ta(e,t-2)),H(`threeInsideUp`,`Three Inside Up`,`3 Inside`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.long(n,n)&&e.white(r)&&e.bodyInside(n,r)&&e.white(t)&&e.close(t)>e.open(n)}),H(`threeInsideDown`,`Three Inside Down`,`3 Inside`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.black(r)&&e.bodyInside(n,r)&&e.black(t)&&e.close(t)<e.open(n)}),H(`threeOutsideUp`,`Three Outside Up`,`3 Outside`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.white(r)&&e.open(r)<=e.close(n)&&e.close(r)>=e.open(n)&&e.body(r)>e.body(n)&&e.white(t)&&e.close(t)>e.close(r)}),H(`threeOutsideDown`,`Three Outside Down`,`3 Outside`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.black(r)&&e.open(r)>=e.close(n)&&e.close(r)<=e.open(n)&&e.body(r)>e.body(n)&&e.black(t)&&e.close(t)<e.close(r)}),H(`upsideGapTwoCrows`,`Upside Gap Two Crows`,`2 Crows Gap`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.black(r)&&e.short(r,n)&&e.bodyGapUp(n,r)&&e.black(t)&&e.open(t)>e.open(r)&&e.close(t)<e.close(r)&&e.close(t)>e.close(n)}),H(`twoCrows`,`Two Crows`,`2 Crows`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.black(r)&&e.bodyGapUp(n,r)&&e.black(t)&&e.open(t)<e.open(r)&&e.open(t)>e.close(r)&&e.close(t)<e.close(n)&&e.close(t)>e.open(n)}),H(`bullishTriStar`,`Bullish Tri-Star`,`Tri-Star`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.doji(n)&&e.doji(r)&&e.doji(t)&&e.bodyGapDown(n,r)&&e.bodyGapUp(r,t)}),H(`bearishTriStar`,`Bearish Tri-Star`,`Tri-Star`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.doji(n)&&e.doji(r)&&e.doji(t)&&e.bodyGapUp(n,r)&&e.bodyGapDown(r,t)}),H(`upsideTasukiGap`,`Upside Tasuki Gap`,`Tasuki`,`bullish`,`continuation`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.white(r)&&e.low(r)>e.high(n)&&e.black(t)&&e.open(t)<e.close(r)&&e.open(t)>e.open(r)&&e.close(t)<e.low(r)&&e.close(t)>e.high(n)}),H(`downsideTasukiGap`,`Downside Tasuki Gap`,`Tasuki`,`bearish`,`continuation`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.black(r)&&e.high(r)<e.low(n)&&e.white(t)&&e.open(t)>e.close(r)&&e.open(t)<e.open(r)&&e.close(t)>e.high(r)&&e.close(t)<e.low(n)}),H(`stickSandwich`,`Stick Sandwich`,`Sandwich`,`bullish`,`reversal`,3,`down`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.white(r)&&e.low(r)>e.close(n)&&e.black(t)&&e.same(e.close(t),e.close(n),n)}),H(`advanceBlock`,`Advance Block`,`Adv Block`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.white(n)&&e.long(n,n)&&e.white(r)&&e.white(t)&&e.close(r)>e.close(n)&&e.close(t)>e.close(r)&&e.open(r)>e.open(n)&&e.open(r)<=e.close(n)&&e.open(t)>e.open(r)&&e.open(t)<=e.close(r)&&e.body(t)<e.body(r)&&e.body(r)<e.body(n)&&e.upper(t)>e.upper(n)}),H(`identicalThreeCrows`,`Identical Three Crows`,`Ident Crows`,`bearish`,`reversal`,3,`up`,(e,t)=>{let n=t-2,r=t-1;return e.black(n)&&e.black(r)&&e.black(t)&&e.close(r)<e.close(n)&&e.close(t)<e.close(r)&&e.same(e.open(r),e.close(n),n)&&e.same(e.open(t),e.close(r),n)&&e.lower(n)<=e.body(n)*.25&&e.lower(r)<=e.body(r)*.25&&e.lower(t)<=e.body(t)*.25})],ka=[H(`bullishThreeLineStrike`,`Bullish Three-Line Strike`,`Strike`,`bullish`,`continuation`,4,`up`,(e,t)=>{let n=t-3;return e.white(n)&&e.white(n+1)&&e.white(n+2)&&Ea(e,n,n+2,!1)&&e.open(n+1)>=e.open(n)&&e.open(n+1)<=e.close(n)&&e.open(n+2)>=e.open(n+1)&&e.open(n+2)<=e.close(n+1)&&e.black(t)&&e.open(t)>e.close(n+2)&&e.close(t)<e.open(n)}),H(`bearishThreeLineStrike`,`Bearish Three-Line Strike`,`Strike`,`bearish`,`continuation`,4,`down`,(e,t)=>{let n=t-3;return e.black(n)&&e.black(n+1)&&e.black(n+2)&&Ea(e,n,n+2,!0)&&e.open(n+1)<=e.open(n)&&e.open(n+1)>=e.close(n)&&e.open(n+2)<=e.open(n+1)&&e.open(n+2)>=e.close(n+1)&&e.white(t)&&e.open(t)<e.close(n+2)&&e.close(t)>e.open(n)}),H(`risingThreeMethods`,`Rising Three Methods`,`Rising 3`,`bullish`,`continuation`,5,`up`,(e,t)=>{let n=t-4;return e.white(n)&&e.long(n,n)&&Da(e,n,n+1,n+3,!0)&&Ea(e,n+1,n+3,!0)&&e.white(t)&&e.long(t,n)&&e.open(t)>e.close(t-1)&&e.close(t)>e.close(n)}),H(`fallingThreeMethods`,`Falling Three Methods`,`Falling 3`,`bearish`,`continuation`,5,`down`,(e,t)=>{let n=t-4;return e.black(n)&&e.long(n,n)&&Da(e,n,n+1,n+3,!1)&&Ea(e,n+1,n+3,!1)&&e.black(t)&&e.long(t,n)&&e.open(t)<e.close(t-1)&&e.close(t)<e.close(n)}),H(`matHold`,`Mat Hold`,`Mat Hold`,`bullish`,`continuation`,5,`up`,(e,t)=>{let n=t-4;if(!(e.white(n)&&e.long(n,n)&&e.black(n+1)&&e.short(n+1,n)&&e.bodyGapUp(n,n+1)))return!1;for(let t=n+1;t<=n+3;t++)if(e.long(t,n)||e.bodyBottom(t)<e.mid(n))return!1;let r=Math.max(e.high(n+1),e.high(n+2),e.high(n+3));return e.close(n+3)<e.close(n+1)&&e.white(t)&&e.open(t)>e.close(t-1)&&e.close(t)>r}),H(`bullishBreakaway`,`Bullish Breakaway`,`Breakaway`,`bullish`,`reversal`,5,`down`,(e,t)=>{let n=t-4;return e.black(n)&&e.long(n,n)&&e.black(n+1)&&e.bodyGapDown(n,n+1)&&e.close(n+2)<e.close(n+1)&&e.close(n+3)<e.close(n+2)&&e.black(n+3)&&e.white(t)&&e.close(t)>e.open(n+1)&&e.close(t)<e.close(n)}),H(`bearishBreakaway`,`Bearish Breakaway`,`Breakaway`,`bearish`,`reversal`,5,`up`,(e,t)=>{let n=t-4;return e.white(n)&&e.long(n,n)&&e.white(n+1)&&e.bodyGapUp(n,n+1)&&e.close(n+2)>e.close(n+1)&&e.close(n+3)>e.close(n+2)&&e.white(n+3)&&e.black(t)&&e.close(t)<e.open(n+1)&&e.close(t)>e.close(n)}),H(`concealingBabySwallow`,`Concealing Baby Swallow`,`Swallow`,`bullish`,`reversal`,4,`down`,(e,t)=>{let n=t-3;return e.black(n)&&e.marubozu(n,n)&&e.black(n+1)&&e.marubozu(n+1,n)&&e.black(n+2)&&e.open(n+2)<e.close(n+1)&&e.high(n+2)>e.close(n+1)&&e.black(t)&&e.open(t)>e.high(n+2)&&e.close(t)<e.low(n+2)}),H(`ladderBottom`,`Ladder Bottom`,`Ladder`,`bullish`,`reversal`,5,`down`,(e,t)=>{let n=t-4;for(let t=n;t<=n+3;t++)if(!e.black(t))return!1;for(let t=n+1;t<=n+2;t++)if(e.open(t)>=e.open(t-1)||e.close(t)>=e.close(t-1))return!1;return e.upper(n+3)>e.body(n+3)&&e.white(t)&&e.open(t)>e.open(n+3)&&e.close(t)>e.high(n+3)})],Aa=[...Sa,...Ca,...Oa,...ka],ja=Aa.map(e=>e.info);function Ma(e){let t=e.trendPeriod;return t!==void 0&&Number.isFinite(t)?Math.max(2,Math.floor(t)):10}function Na(e){if(!e.patterns)return Aa;let t=new Set(e.patterns);return Aa.filter(e=>t.has(e.info.id))}function Pa(e,t,n){let r=[];for(let i of n){let n=t-i.info.bars+1;n<0||i.trend&&e.trendBefore(n)!==i.trend||i.test(e,t)&&r.push(i)}return r}function Fa(e,t={}){let n=new ya(e,Ma(t)),r=Na(t),i=[],a=t.from!==void 0&&Number.isFinite(t.from)?Math.max(0,Math.floor(t.from)):0;for(let t=a;t<e.length;t++)for(let a of Pa(n,t,r))i.push({index:t,time:e[t].time,pattern:a.info});return i}function Ia(e={}){return Na(e)}var La=6,Ra=4,za=12,Ba=class extends V{descriptor={id:`candlepatterns`,name:`Candlestick Patterns`,placement:`overlay`,defaultConfig:{trendPeriod:10,reversal:1,continuation:1,indecision:0},shortName:`Patterns`,inputs:{trendPeriod:{min:2},reversal:{min:0,max:1},continuation:{min:0,max:1},indecision:{min:0,max:1}},plots:[{key:`bull`,title:`Bullish`,color:3,kind:`dots`},{key:`bear`,title:`Bearish`,color:4,kind:`dots`},{key:`neutral`,title:`Indecision`,color:1,kind:`dots`}]};read(e){let t=new Set;return L(e,`reversal`,1,0)>=1&&t.add(`reversal`),L(e,`continuation`,1,0)>=1&&t.add(`continuation`),L(e,`indecision`,0,0)>=1&&t.add(`indecision`),{trendPeriod:L(e,`trendPeriod`,10,2),defs:Ia().filter(e=>t.has(e.info.kind))}}pointAt(e,t,{trendPeriod:n,defs:r}){let i=Pa(new ya(e,n),t,r);if(i.length===0)return null;let a=i[0];for(let e of i)e.info.bars>=a.info.bars&&(a=e);let o=e[t],s={code:ja.indexOf(a.info),count:i.length};return a.info.direction===`bullish`?s.bull=o.low:a.info.direction===`bearish`?s.bear=o.high:s.neutral=o.high,s}render(t,n,r,i){let a=n.series;if(!a)return;let o=Math.max(0,Math.floor(r.visibleRange.from)),s=Math.min(a.length-1,Math.ceil(r.visibleRange.to)),c=r.barWidth+r.barSpacing>=za,{chartRect:l}=r,u=l.y+10,d=l.y+l.height-10,f=e=>i.plots?.[e]?.visible!==!1;t.save(),t.globalAlpha=i.opacity,t.font=`10px sans-serif`,t.textAlign=`center`;let p=-1/0,m=-1/0;for(let n=o;n<=s;n++){let o=a[n];if(!o)continue;let s=e.b(n,r),l=ja[o.code??-1]?.short??``;if(o.bull!==void 0&&f(`bull`)){let n=e.T(o.bull,r)+Ra;t.fillStyle=i.colors[3]??i.colors[0],Va(t,s,n,`up`),c&&l&&(m=Ha(t,l,s,Math.min(d,n+La+2),`top`,m))}else if(o.bear!==void 0&&f(`bear`)){let n=e.T(o.bear,r)-Ra;t.fillStyle=i.colors[4]??i.colors[0],Va(t,s,n,`down`),c&&l&&(p=Ha(t,l,s,Math.max(u,n-La-2),`bottom`,p))}else if(o.neutral!==void 0&&f(`neutral`)){let n=e.T(o.neutral,r)-Ra-La/2;t.fillStyle=i.colors[1]??i.colors[0],t.beginPath(),t.arc(s,n,La/2-1,0,Math.PI*2),t.fill(),c&&l&&(p=Ha(t,l,s,Math.max(u,n-La/2-2),`bottom`,p))}}t.restore()}};function Va(e,t,n,r){let i=La/2;e.beginPath(),r===`up`?(e.moveTo(t,n),e.lineTo(t-i,n+La),e.lineTo(t+i,n+La)):(e.moveTo(t,n),e.lineTo(t-i,n-La),e.lineTo(t+i,n-La)),e.closePath(),e.fill()}function Ha(e,t,n,r,i,a){let o=e.measureText(t).width/2;return n-o<a+2?a:(e.textBaseline=i,e.fillText(t,n,r),n+o)}var Ua=500,Wa=class extends P{descriptor={id:`machannel`,name:`Moving Average Channel`,placement:`overlay`,defaultConfig:{upperLength:20,lowerLength:20,upperOffset:0,lowerOffset:0},shortName:`MA Channel`,inputs:{upperLength:{min:1},lowerLength:{min:1},upperOffset:{min:-Ua,max:Ua},lowerOffset:{min:-Ua,max:Ua}},plots:[{key:`upper`,title:`Upper`,color:0},{key:`lower`,title:`Lower`,color:1}]};calculate(e,t){let n=Ka(Jr(e.map(e=>e.high),L(t,`upperLength`,20,1)),Ga(t,`upperOffset`)),r=Ka(Jr(e.map(e=>e.low),L(t,`lowerLength`,20,1)),Ga(t,`lowerOffset`));return R(e,n.map((e,t)=>{let n=r[t];return e===void 0&&n===void 0?null:{...e===void 0?{}:{upper:e},...n===void 0?{}:{lower:n}}}))}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=[],u=[],d=[],f=[];for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n)continue;let r=e.b(t,i),a=n.upper===void 0?null:{x:r,y:e.T(n.upper,i)},s=n.lower===void 0?null:{x:r,y:e.T(n.lower,i)};a&&l.push(a),s&&u.push(s),a&&s&&(d.push(a),f.push(s))}this.drawBand(n,d,f,(0,t.withAlpha)(a.colors[0],.08)),this.drawLine(n,l,a.colors[0],a.lineWidths[0],N(a,`upper`,a.lineWidths[0])),this.drawLine(n,u,a.colors[1]??a.colors[0],a.lineWidths[1]??a.lineWidths[0],N(a,`lower`,a.lineWidths[1]??a.lineWidths[0]))}};function Ga(e,t){let n=Number(e.params[t]??0);return Number.isFinite(n)?Math.max(-Ua,Math.min(Ua,Math.round(n))):0}function Ka(e,t){return e.map((n,r)=>e[r-t])}var qa=500,Ja=class extends V{descriptor={id:`hamming`,name:`Moving Average Hamming`,placement:`overlay`,defaultConfig:{period:10,source:`close`},shortName:`HMA (Hamming)`,inputs:{period:{min:2,max:qa},source:{source:!0}},plots:[{key:`value`,title:`MA`,color:0}]};read(e){let t=Math.min(qa,L(e,`period`,10,2)),n=Array.from({length:t},(e,n)=>.54-.46*Math.cos(2*Math.PI*n/(t-1)));return{weights:n,total:n.reduce((e,t)=>e+t,0)}}pointAt(e,t,{weights:n,total:r}){let i=t-n.length+1;if(i<0)return null;let a=0;for(let t=0;t<n.length;t++)a+=n[t]*e[i+t].close;return{value:a/r}}},Ya=[`sma`,`ema`,`wma`];function Xa(e,t,n){return e===`ema`?B(t,n):e===`wma`?Xr(t,n):Jr(t,n)}var Za=class extends P{calculate(e,t){let n=Ya.includes(t.params.type)?t.params.type:`sma`,r=z(e),i=this.lengths.map(([e,i])=>Xa(n,r,L(t,e,i,1)));return R(e,e.map((e,t)=>{let n={};return i.forEach((e,r)=>{let i=e[t];i!==void 0&&(n[`ma${r+1}`]=i)}),Object.keys(n).length>0?n:null}))}},Qa=class extends Za{lengths=[[`first`,20],[`second`,50]];descriptor={id:`madouble`,name:`Moving Average Double`,placement:`overlay`,defaultConfig:{first:20,second:50,type:`sma`,source:`close`},shortName:`MA x2`,inputs:{first:{min:1},second:{min:1},type:{options:Ya},source:{source:!0}},plots:[{key:`ma1`,title:`MA 1`,color:0},{key:`ma2`,title:`MA 2`,color:1}]}},$a=class extends Za{lengths=[[`first`,10],[`second`,20],[`third`,50]];descriptor={id:`matriple`,name:`Moving Average Triple`,placement:`overlay`,defaultConfig:{first:10,second:20,third:50,type:`sma`,source:`close`},shortName:`MA x3`,inputs:{first:{min:1},second:{min:1},third:{min:1},type:{options:Ya},source:{source:!0}},plots:[{key:`ma1`,title:`MA 1`,color:0},{key:`ma2`,title:`MA 2`,color:1},{key:`ma3`,title:`MA 3`,color:2}]}},eo=class extends P{descriptor={id:`volindex`,name:`Volatility Index`,placement:`overlay`,defaultConfig:{period:7,mult:3},shortName:`VI`,inputs:{period:{min:1},mult:{label:`ATR multiple`,min:.1,step:.1}},plots:[{key:`sar`,title:`Stop`,color:0,kind:`dots`,tone:{field:`long`},downColor:1}]};calculate(e,t){let n=L(t,`period`,7,1),r=Math.max(.1,I(t,`mult`,3)),i=Zr($r(e),n),a=Array(e.length).fill(null),o=null,s=0;for(let t=0;t<e.length;t++){let n=i[t];if(n===void 0)continue;let c=e[t].close,l=n*r;o===null?(o=c>=e[0].close,s=c):o?(s=Math.max(s,c),c<s-l&&(o=!1,s=c)):(s=Math.min(s,c),c>s+l&&(o=!0,s=c)),a[t]={sar:o?s-l:s+l,long:+!!o}}return R(e,a)}},to=class extends P{descriptor={id:`asi`,name:`Accumulative Swing Index`,placement:`panel`,defaultConfig:{limit:10},shortName:`ASI`,inputs:{limit:{label:`Limit move`,min:1e-4,step:.1}},plots:[{key:`value`,title:`ASI`,color:0}],scale:{zero:!0}};calculate(e,t){let n=Math.max(1e-9,I(t,`limit`,10)),r=Array(e.length).fill(null),i=0;for(let t=1;t<e.length;t++)i+=no(e[t-1],e[t],n),r[t]={value:i};return R(e,r)}};function no(e,t,n){let r=Math.abs(t.high-e.close),i=Math.abs(t.low-e.close),a=t.high-t.low,o=Math.abs(e.close-e.open),s;return s=r>=i&&r>=a?r-.5*i+.25*o:i>=r&&i>=a?i-.5*r+.25*o:a+.25*o,s===0?0:50*(t.close-e.close+.5*(t.close-t.open)+.25*(e.close-e.open))/s*(Math.max(r,i)/n)}var ro=class extends V{descriptor={id:`advdecline`,name:`Advance/Decline`,placement:`panel`,defaultConfig:{length:10},shortName:`A/D Ratio`,inputs:{length:{min:1}},plots:[{key:`value`,title:`Ratio`,color:0}],scale:{min:0}};read(e){return{length:L(e,`length`,10,1)}}pointAt(e,t,{length:n}){if(t<n-1)return null;let r=0,i=0;for(let a=t-n+1;a<=t;a++)e[a].close>e[a].open?r++:e[a].close<e[a].open&&i++;return{value:i===0?r:r/i}}},io=class extends V{descriptor={id:`majority`,name:`Majority Rule`,placement:`panel`,defaultConfig:{period:14},shortName:`Majority`,inputs:{period:{min:1}},plots:[{key:`value`,title:`Majority`,color:0}],scale:{min:0,max:100},levels:[50]};read(e){return{period:L(e,`period`,14,1)}}pointAt(e,t,{period:n}){if(t<n)return null;let r=0;for(let i=t-n+1;i<=t;i++)e[i].close>e[i-1].close&&r++;return{value:100*r/n}}},ao=34,oo=30,so=class extends P{descriptor={id:`chopzone`,name:`Chop Zone`,placement:`panel`,defaultConfig:{},shortName:`Chop Zone`,plots:[{key:`angle`,title:`Angle`,color:0,kind:`histogram`}],scale:{zero:!0}};calculate(e,t){let n=B(z(e),ao),r=Array(e.length).fill(null);for(let t=1;t<e.length;t++){let i=n[t],a=n[t-1],o=ii(e,t,oo),s=ai(e,t,oo);if(i===void 0||a===void 0||o===void 0||s===void 0||o===s)continue;let c=e[t],l=(c.high+c.low+c.close)/3;if(!(l>0&&s>0))continue;let u=(i-a)/l*(25/(o-s)*s);r[t]={angle:Math.atan(u)*180/Math.PI}}return R(e,r)}render(t,n,r,i){if(i.plots?.angle?.visible===!1)return;let a=n.series;if(!a)return;let{from:o,to:s}=r.visibleRange,c=e.T(0,r),l=[];for(let t=o;t<=s&&t<a.length;t++){let n=a[t]?.angle;n!==void 0&&l.push({x:e.b(t,r),y:e.T(n,r),baseY:c,color:co(n)})}this.drawHistogram(t,l,Math.max(1,r.barWidth))}};function co(e){return e>=5?`#26C6DA`:e>=3.57?`#43A047`:e>=2.14?`#A5D6A7`:e>=.71?`#009688`:e<=-5?`#D50000`:e<=-3.57?`#E91E63`:e<=-2.14?`#FF6D00`:e<=-.71?`#FFB74D`:`#FDD835`}var lo=class extends P{descriptor={id:`smiergodic`,name:`SMI Ergodic`,placement:`panel`,defaultConfig:{short:5,long:20,signal:5,source:`close`},shortName:`SMIIO`,inputs:{short:{min:1},long:{min:1},signal:{min:1},source:{source:!0}},plots:[{key:`oscillator`,title:`Oscillator`,color:2,kind:`histogram`,tone:`sign`,downColor:3},{key:`indicator`,title:`Indicator`,color:0},{key:`signal`,title:`Signal`,color:1}],scale:{zero:!0}};calculate(e,t){let n=L(t,`short`,5,1),r=L(t,`long`,20,1),i=e.map((t,n)=>n===0?void 0:t.close-e[n-1].close),a=B(B(i,r),n),o=B(B(i.map(e=>e===void 0?void 0:Math.abs(e)),r),n),s=a.map((e,t)=>e===void 0||!o[t]?void 0:e/o[t]),c=B(s,L(t,`signal`,5,1));return R(e,s.map((e,t)=>{if(e===void 0)return null;let n=c[t];return n===void 0?{indicator:e}:{indicator:e,signal:n,oscillator:e-n}}))}},uo=class extends P{descriptor={id:`po`,name:`Price Oscillator`,placement:`panel`,defaultConfig:{short:10,long:21,source:`close`},shortName:`PO`,inputs:{short:{min:1},long:{min:1},source:{source:!0}},plots:[{key:`value`,title:`PO`,color:0}],scale:{zero:!0}};calculate(e,t){let n=z(e),r=Jr(n,L(t,`short`,10,1)),i=Jr(n,L(t,`long`,21,1));return R(e,ni(r.map((e,t)=>e===void 0||i[t]===void 0?void 0:e-i[t])))}},fo=e=>({period:L(e,`period`,10,1),annual:Math.max(1,I(e,`annual`,365))}),po={period:{min:1},annual:{label:`Bars per year`,min:1}},mo=class extends V{descriptor={id:`volohlc`,name:`Volatility O-H-L-C`,placement:`panel`,defaultConfig:{period:10,annual:365},shortName:`Vol OHLC`,inputs:po,plots:[{key:`value`,title:`Volatility`,color:0}],scale:{min:0}};read(e){return fo(e)}pointAt(e,t,{period:n,annual:r}){if(t<n-1)return null;let i=0;for(let r=t-n+1;r<=t;r++){let{open:t,high:n,low:a,close:o}=e[r];if(!(t>0&&n>0&&a>0&&o>0))return null;i+=.5*Math.log(n/a)**2-(2*Math.LN2-1)*Math.log(o/t)**2}return{value:100*Math.sqrt(Math.max(0,i/n*r))}}},ho=class extends V{descriptor={id:`volzt`,name:`Volatility Zero Trend Close-to-Close`,placement:`panel`,defaultConfig:{period:10,annual:365},shortName:`Vol ZT`,inputs:po,plots:[{key:`value`,title:`Volatility`,color:0}],scale:{min:0}};read(e){return fo(e)}pointAt(e,t,{period:n,annual:r}){if(t<n)return null;let i=0;for(let r=t-n+1;r<=t;r++){let t=e[r-1].close,n=e[r].close;if(!(t>0&&n>0))return null;i+=Math.log(n/t)**2}return{value:100*Math.sqrt(i/n*r)}}};function go(e){e.register(new pn),e.register(new mn),e.register(new hn),e.register(new gn),e.register(new _n),e.register(new vn),e.register(new yn),e.register(new bn),e.register(new xn),e.register(new wn),e.register(new En),e.register(new Dn),e.register(new On),e.register(new kn),e.register(new Mn),e.register(new Nn),e.register(new Pn),e.register(new Fn),e.register(new Ln),e.register(new Rn),e.register(new zn),e.register(new Un),e.register(new Kn),e.register(new qn),e.register(new Jn),e.register(new Yn),e.register(new Xn),e.register(new Zn),e.register(new Qn),e.register(new $n),e.register(new er),e.register(new tr),e.register(new nr),e.register(new rr),e.register(new ir),e.register(new Wr),e.register(new Gr),e.register(new Kr),e.register(new qr),e.register(new Wn),e.register(new Gn),e.register(new ar),e.register(new or),e.register(new sr),e.register(new cr),e.register(new ur),e.register(new dr),e.register(new pr),e.register(new mr),e.register(new _r),e.register(new vr),e.register(new br),e.register(new xr),e.register(new Sr),e.register(new Cr),e.register(new wr),e.register(new Tr),e.register(new Er),e.register(new Or),e.register(new kr),e.register(new Ar),e.register(new jr),e.register(new Mr),e.register(new Nr),e.register(new Ir),e.register(new Rr),e.register(new Br),e.register(new Vr),e.register(new Hr),e.register(new Ur),e.register(new ci),e.register(new li),e.register(new ui),e.register(new di),e.register(new fi),e.register(new pi),e.register(new gi),e.register(new vi),e.register(new yi),e.register(new Si),e.register(new Ci),e.register(new wi),e.register(new Ti),e.register(new Ei),e.register(new Oi),e.register(new ji),e.register(new Mi),e.register(new Ni),e.register(new Pi),e.register(new Fi),e.register(new Ii),e.register(new Li),e.register(new Ri),e.register(new Vi),e.register(new Hi),e.register(new Wi),e.register(new Gi),e.register(new Ki),e.register(new Wa),e.register(new Ja),e.register(new Qa),e.register(new $a),e.register(new eo),e.register(new to),e.register(new ro),e.register(new io),e.register(new so),e.register(new lo),e.register(new uo),e.register(new mo),e.register(new ho),e.register(new Ji),e.register(new Yi),e.register(new Xi),e.register(new Zi),e.register(new Qi),e.register(new $i),e.register(new ea),e.register(new ta),e.register(new ra),e.register(new oa),e.register(new sa),e.register(new ca),e.register(new la),e.register(new ua),e.register(new da),e.register(new fa),e.register(new pa),e.register(new ma),e.register(new ha),e.register(new qi),e.register(new ga),e.register(new _a),e.register(new Ba)}var _o=[`movingAverages`,`trend`,`oscillators`,`volatility`,`volume`,`bands`,`patterns`,`other`],vo=new Map(Object.entries({movingAverages:[`sma`,`ema`,`wma`,`vwma`,`hma`,`tema`,`dema`,`smma`,`alma`,`kama`,`lsma`,`mcginley`,`mtfma`,`macross`,`gmma`,`maribbon`,`hamming`,`madouble`,`matriple`,`rainbow`,`alligator`,`tsf`],trend:[`ichimoku`,`psar`,`supertrend`,`chandelier`,`cks`,`volindex`,`adx`,`aroon`,`vortex`,`chop`,`chopzone`,`vhf`,`trendstrength`,`lrslope`,`rsquared`,`rwi`,`majority`,`asi`],oscillators:`rsi.macd.stochastic.williamsR.cci.roc.tsi.ao.uo.crsi.coppock.kst.elderray.stc.fisher.dpo.bop.cmo.trix.rvi.stochrsi.ppo.ac.rmi.disparity.qstick.pgo.bbpb.mom.smi.smiergodic.po.psy.newpsy.sonar.binarywave.sroc.abratio.advdecline`.split(`.`),volatility:[`atr`,`stddev`,`chaikinvol`,`bbw`,`hv`,`ulcer`,`rvix`,`stderror`,`adr`,`volohlc`,`volzt`,`sigma`,`tr`,`massindex`],volume:[`vwap`,`avwap`,`svwap`,`volumeProfile`,`obv`,`mfi`,`cmf`,`ad`,`vroc`,`chaikinOsc`,`voldelta`,`fi`,`kvo`,`emv`,`pvt`,`wad`,`vo`,`netvolume`,`vr`,`nvi`,`pvi`,`iii`,`volpct`,`volchange`,`tradevalue`],bands:[`bb`,`keltner`,`donchian`,`envelope`,`lrc`,`seb`,`machannel`],patterns:[`pivots`,`zigzag`,`fractals`,`candlepatterns`,`demark`,`avgprice`,`medprice`,`typprice`,`wclose`]}).flatMap(([e,t])=>t.map(t=>[t,e])));function yo(e){return e.category??vo.get(e.id)??`other`}function bo(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.requestId==`number`?t.type===`result`||t.type===`pong`||t.type===`error`:!1}var xo=class{worker;fallbackPlugins;timeoutMs;nextRequestId=1;pending=new Map;messageHandler;constructor(e,t={}){this.worker=e,this.fallbackPlugins=t.fallbackPlugins??new Map,this.timeoutMs=t.timeoutMs??3e4,this.messageHandler=e=>this.handleMessage(e),this.worker&&(this.worker.addEventListener(`message`,this.messageHandler),this.worker.addEventListener(`error`,this.messageHandler))}hasWorker(){return this.worker!==null}registerFallbackPlugin(e){this.fallbackPlugins.set(e.descriptor.id,e)}async calculate(e,t,n){if(!this.worker){let r=this.fallbackPlugins.get(e);if(!r)throw Error(`Unknown indicator: ${e}`);return r.calculate(n,t)}let r=this.nextRequestId++,i={type:`calculate`,requestId:r,indicatorId:e,config:t,data:n};return new Promise((t,n)=>{let a={resolve:t,reject:n,timer:null};this.timeoutMs>0&&(a.timer=setTimeout(()=>{this.pending.delete(r),n(Error(`Indicator worker timeout (${this.timeoutMs}ms): ${e}`))},this.timeoutMs)),this.pending.set(r,a),this.worker.postMessage(i)})}ping(){if(!this.worker)return Promise.resolve();let e=this.nextRequestId++;return new Promise((t,n)=>{let r={resolve:()=>t(),reject:n,timer:this.timeoutMs>0?setTimeout(()=>{this.pending.delete(e),n(Error(`Indicator worker ping timeout`))},this.timeoutMs):null};this.pending.set(e,r),this.worker.postMessage({type:`ping`,requestId:e})})}terminate(){this.worker&&=(this.worker.removeEventListener(`message`,this.messageHandler),this.worker.removeEventListener(`error`,this.messageHandler),this.worker.terminate(),null);for(let e of this.pending.values())e.timer&&clearTimeout(e.timer),e.reject(Error(`Indicator worker terminated`));this.pending.clear()}handleMessage(e){let t=e.data;if(t!==void 0){if(!bo(t))return;this.dispatchResponse(t);return}let n=e.message??`Indicator worker error`;for(let[e,t]of this.pending)t.timer&&clearTimeout(t.timer),t.reject(Error(n)),this.pending.delete(e)}dispatchResponse(e){let t=this.pending.get(e.requestId);if(t){if(this.pending.delete(e.requestId),t.timer&&clearTimeout(t.timer),e.type===`error`){t.reject(Error(e.message));return}if(e.type===`pong`){t.resolve(void 0);return}t.resolve(e.output)}}},So=new Set([`compareSymbol`,`spread`,`correlation`,`correlationlog`]),Co=e=>typeof e.params.symbol==`string`?e.params.symbol.trim():``,wo=class extends V{descriptor={id:`compareSymbol`,name:`Compare Symbol`,placement:`overlay`,defaultConfig:{symbol:``},shortName:`Compare`,plots:[{key:`value`,title:`Close`,color:0}]};constructor(e){super(),this.store=e}read(e){return{symbol:Co(e)}}pointAt(e,n,{symbol:r}){if(!r)return null;let i=this.store.closeAt(r,e[n].time,(0,t.barTimeUnit)(e));return i===void 0?null:{value:i}}},To=class extends V{descriptor={id:`spread`,name:`Spread / Ratio`,placement:`panel`,defaultConfig:{symbol:``,mode:`spread`},shortName:`Spread`,plots:[{key:`value`,title:`Spread`,color:0}],inputs:{mode:{options:[`spread`,`ratio`]}}};constructor(e){super(),this.store=e}read(e){return{symbol:Co(e),ratio:e.params.mode===`ratio`}}pointAt(e,n,{symbol:r,ratio:i}){if(!r)return null;let a=this.store.closeAt(r,e[n].time,(0,t.barTimeUnit)(e));return a===void 0?null:i?a===0?null:{value:e[n].close/a}:{value:e[n].close-a}}},Eo=e=>{let t=Math.round(Number(e.params.length??20));return{symbol:Co(e),length:Number.isFinite(t)?Math.max(2,t):20}};function Do(e,t){if(e.every(t=>t===e[0])||t.every(e=>e===t[0]))return null;let n=e.length,r=0,i=0;for(let a=0;a<n;a++)r+=e[a],i+=t[a];r/=n,i/=n;let a=0,o=0,s=0;for(let c=0;c<n;c++){let n=e[c]-r,l=t[c]-i;a+=n*l,o+=n*n,s+=l*l}return o>0&&s>0?Math.max(-1,Math.min(1,a/Math.sqrt(o*s))):null}var Oo={placement:`panel`,defaultConfig:{symbol:``,length:20},inputs:{length:{min:2}},plots:[{key:`value`,title:`Correlation`,color:0}],scale:{min:-1,max:1},levels:[0]},ko=class extends V{descriptor={...Oo,id:`correlation`,name:`Correlation Coefficient`,shortName:`Correlation`};constructor(e){super(),this.store=e}read(e){return Eo(e)}pointAt(e,n,{symbol:r,length:i}){if(!r||n<i-1)return null;let a=[],o=[];for(let s=n-i+1;s<=n;s++){let n=this.store.closeAt(r,e[s].time,(0,t.barTimeUnit)(e));if(n===void 0)return null;a.push(e[s].close),o.push(n)}let s=Do(a,o);return s===null?null:{value:s}}},Ao=class extends V{descriptor={...Oo,id:`correlationlog`,name:`Correlation Log`,shortName:`Correlation Log`};constructor(e){super(),this.store=e}read(e){return Eo(e)}pointAt(e,n,{symbol:r,length:i}){if(!r||n<i)return null;let a=[],o=[],s=this.store.closeAt(r,e[n-i].time,(0,t.barTimeUnit)(e));for(let c=n-i+1;c<=n;c++){let n=this.store.closeAt(r,e[c].time,(0,t.barTimeUnit)(e)),i=e[c-1].close,l=e[c].close;if(n===void 0||s===void 0||!(i>0&&l>0&&n>0&&s>0))return null;a.push(Math.log(l/i)),o.push(Math.log(n/s)),s=n}let c=Do(a,o);return c===null?null:{value:c}}},U={year:100,quarter:91,month:90,dayOfFive:81,day:80,hour12:73,hour6:72,hour3:71,hour:70,minute30:63,minute15:62,minute5:61,minute:60,within:50},jo=[...new Set(Object.values(U))].sort((e,t)=>t-e);function Mo(e){return e>=U.year?`year`:e>=U.month?`month`:e>=U.day?`day`:`time`}function No(e,t){if(!e)return 0;if(t.year!==e.year)return U.year;if(t.month!==e.month)return t.month%3==1?U.quarter:U.month;if(t.day!==e.day)return t.day%5==0?U.dayOfFive:U.day;if(t.hours!==e.hours){let e=t.hours;return e%12==0?U.hour12:e%6==0?U.hour6:e%3==0?U.hour3:U.hour}if(t.minutes!==e.minutes){let e=t.minutes;return e%30==0?U.minute30:e%15==0?U.minute15:e%5==0?U.minute5:U.minute}return U.within}var Po=256,Fo=1.25;function Io(e){return e>1?Math.ceil(Fo**Math.ceil(Math.log(e)/Math.log(Fo)-1e-9)):1}var Lo=class{weights=new Uint8Array;times=[];weighed=null;chosen=new Int32Array;chosenFor=null;marks(e,t){let n=e.length;if(n===0)return[];let r=Io(t.gapBars),i=t.timesPastData?Math.max(n-1,Math.ceil(t.to)):n-1,a=i<=n-1?n:Math.ceil((i+1-n)/Po)*Po+n;this.weigh(e,t.tz,a),this.choose(r,a);let o=Math.max(0,Math.floor(t.from)),s=Math.min(i,Math.ceil(t.to)),c=this.chosen,l=0,u=c.length;for(;l<u;){let e=l+u>>1;c[e]<o?l=e+1:u=e}let d=[];for(let e=l;e<c.length&&c[e]<=s;e++){let t=c[e];d.push({index:t,time:this.times[t],weight:this.weights[t]})}return d}weigh(n,r,i){let a=n.length,o=(0,t.barTimeUnit)(n),s=this.weighed,c=0;if(s&&s.tz===r&&s.unit===o){let e=Math.min(s.bars,a),t=this.times;for(;c<e&&n[c].time*o===t[c];)c++;c<e&&(c=0)}if(s&&c===a&&s.bars===a&&s.extent===i)return;let l=new Uint8Array(i),u=Array(i);if(c>0){l.set(this.weights.subarray(0,c));for(let e=0;e<c;e++)u[e]=this.times[e]}let d=c>0?(0,t.timeParts)(u[c-1],r):null;for(let s=c;s<i;s++){let i=(s<a?n[s].time:e.y(s,n))*o,c=(0,t.timeParts)(i,r);l[s]=No(d,c),u[s]=i,d=c}this.weights=l,this.times=u,this.weighed={bars:a,tz:r,extent:i,unit:o}}choose(e,t){let n=this.chosenFor;if(n&&n.gapBars===e&&n.extent===t&&n.weights===this.weights)return;let r=this.weights,i=new Uint8Array(t),a=[];for(let n of jo)for(let o=0;o<t;o++){if(r[o]!==n||i[o])continue;a.push(o);let s=Math.max(0,o-e+1),c=Math.min(t-1,o+e-1);for(let e=s;e<=c;e++)i[e]=1}this.chosen=Int32Array.from(a).sort(),this.chosenFor={gapBars:e,extent:t,weights:r}}},Ro=e=>e<10?`0`+e:``+e,zo=8,Bo=new Map;function Vo(e){let t=Bo.get(e);if(!t){let n;try{n=new Intl.DateTimeFormat(e,{month:`short`,timeZone:`UTC`})}catch{n=new Intl.DateTimeFormat(`en-US`,{month:`short`,timeZone:`UTC`})}t=Array.from({length:12},(e,t)=>n.format(Date.UTC(2e3,t,15))),Bo.set(e,t)}return t}var Ho=class{tz=null;timeFormatter=null;timesPastData=!0;locale=`en-US`;columns=[];marker=new Lo;setLocale(e){this.locale=e}setTimezoneOffset(e){this.tz=e}setTimeFormatter(e){this.timeFormatter=e}setTimesPastData(e){this.timesPastData=e}getTimesPastData(){return this.timesPastData}marks(e,t){let n=e.barWidth+e.barSpacing;return!(n>0)||t.length===0?[]:this.marker.marks(t,{from:Math.floor(e.offset/n),to:Math.ceil((e.offset+e.chartRect.width)/n),gapBars:80/n,tz:this.tz,timesPastData:this.timesPastData})}label(e,n){if(this.timeFormatter)return this.timeFormatter(e.time,{kind:n,timeZone:this.tz});let r=(0,t.timeParts)(e.time,this.tz);if(n===`year`)return String(r.year);if(n===`month`)return Vo(this.locale)[r.month-1];if(n===`day`)return String(r.day);let i=`${Ro(r.hours)}:${Ro(r.minutes)}`;return e.weight===U.within?`${i}:${Ro(new Date(e.time).getUTCSeconds())}`:i}labelColumns(){return this.columns}render(n,r,i,a,o){let{chartRect:s}=r,c=o??s.y+s.height;n.strokeStyle=i.style?.axis.time.line??i.axisLine,n.lineWidth=1,n.globalAlpha=.65,n.beginPath(),n.moveTo(s.x,c+.5),n.lineTo(s.x+s.width,c+.5),n.stroke(),n.globalAlpha=1;let l=r.barWidth+r.barSpacing,u=-r.offset+s.x+r.barWidth/2,d=Math.ceil((r.offset+s.width)/l),f=(0,t.barTimeUnit)(a),p=a.length>0?e.y(Math.min(d,a.length-1),a):Date.now(),m=(0,t.tzLabel)(this.tz,p*f),h=`500 ${i.font.sizeSmall-1}px ${i.font.family}`,g=s.x+s.width-4;n.font=h;let _=g-n.measureText(m).width-8,v=`500 ${i.font.sizeSmall}px ${i.font.family}`,y=`600 ${i.font.sizeSmall}px ${i.font.family}`;n.textBaseline=`top`,n.textAlign=`center`,n.fillStyle=i.style?.axis.time.text??i.axisLabel;let b=[],x=this.marks(r,a).sort((e,t)=>t.weight-e.weight||e.index-t.index);for(let e of x){let t=e.index*l+u,r=Mo(e.weight),i=this.label(e,r);n.font=r===`year`?y:v;let a=n.measureText(i).width/2;t+a>_||b.some(e=>t-a<e.right+zo&&t+a+zo>e.left)||(b.push({left:t-a,right:t+a}),n.fillText(i,t,c+7))}this.columns=b,n.font=h,n.textAlign=`right`,n.textBaseline=`top`,n.globalAlpha=.75,n.fillStyle=i.textSecondary,n.fillText(m,g,c+7),n.globalAlpha=1}},Uo={line:16,handle:22,alert:16,order:16,button:8,divider:12},Wo=300,Go=24,Ko=class{last=null;tap(e,t=Date.now()){let n=this.last;return n&&t-n.at<=300&&Math.hypot(e.x-n.pos.x,e.y-n.pos.y)<=24?(this.last=null,!0):(this.last={pos:e,at:t},!1)}reset(){this.last=null}},qo=new Set,Jo=null,Yo=4,Xo=8,Zo=500,Qo=800,$o={ctrl:!1,shift:!1,alt:!1};function es(){let e=typeof document<`u`?document.activeElement:null;return e instanceof Element&&e.closest(`[aria-modal="true"], [role="dialog"], [role="menu"]`)!==null}var ts=class{panHandler=null;zoomHandler=null;crosshairHandler=null;axisDragHandler=null;alertDragHandler=null;axisViewportGetter=null;onAxisDoubleClick=null;onDrawingDoubleClick=null;onDrawingContextMenu=null;zoomArea=!1;onChartContextMenu=null;priceAxisAdd=null;axisStrips=null;savedTouchAction=``;measureHandlers=null;measuring=!1;boxSelectHandlers=null;boxSelecting=!1;onAltClick=null;onEscape=null;onConfirm=null;onClick=null;markerAt=null;onMarkerHover=null;markerClickable=()=>!0;markerPos={x:0,y:0};hoveredMarker=null;downPos=null;downMoved=!1;pressForClick=!1;drawingManager=null;tradingManager=null;paneResizeHandler=null;viewportGetter=null;onOverlayDirty=null;boundHandlers=[];lastTouchDist=0;lastTouchMid={x:0,y:0};touchActive=!1;touchStartPos={x:0,y:0};longPressTimer=null;longPressed=!1;touchFallthrough=!1;touchDecided=!1;touchYielded=!1;taps=new Ko;pageScroll=!1;touchStartPrevented=!1;lastTouchAt=-1/0;pressPlacedPoint=!1;cachedRect=null;constructor(e){this.element=e}setOverlayDirtyCallback(e){this.onOverlayDirty=e}setPanHandler(e){this.panHandler=e,this.refreshTouchAction()}setZoomHandler(e){this.zoomHandler=e,this.refreshTouchAction()}setCrosshairHandler(e){this.crosshairHandler=e}setAltClickHandler(e){this.onAltClick=e}setEscapeHandler(e){this.onEscape=e}setConfirmHandler(e){this.onConfirm=e}setSignalMarkerHitTest(e,t,n=()=>!0){this.markerAt=e,this.onMarkerHover=t,this.markerClickable=n,e||(this.hoveredMarker=null)}leaveMarker(){this.hoveredMarker!==null&&(this.hoveredMarker=null,this.onMarkerHover?.(null,this.markerPos))}setClickHandler(e){this.onClick=e}setBoxSelectHandlers(e){this.boxSelectHandlers=e}setMeasureHandlers(e){this.measureHandlers=e}setAxisDragHandler(e,t,n){this.axisDragHandler=e,this.axisViewportGetter=t,this.onAxisDoubleClick=n??null}setDrawingManager(e,t){this.drawingManager=e,this.viewportGetter=t}setChartContextMenu(e){this.onChartContextMenu=e}setPriceAxisAddButton(e,t){this.priceAxisAdd={button:e,onClick:t}}setZoomAreaMode(e){this.zoomArea=e}setDrawingContextMenu(e){this.onDrawingContextMenu=e}setDrawingDoubleClick(e){this.onDrawingDoubleClick=e}setAlertDragHandler(e){this.alertDragHandler=e}setTradingManager(e,t){this.tradingManager=e,this.viewportGetter=t}setAxisStrips(e){this.axisStrips=e}setPaneResizeHandler(e){this.paneResizeHandler=e}setPageScroll(e){this.pageScroll=e,this.refreshTouchAction()}refreshTouchAction(){qo.has(this.element)&&this.element.style.setProperty(`touch-action`,this.touchAction())}pageTakes(){let e=!this.panHandler,t=this.pageScroll||!this.panHandler;return{x:e,y:t,zoom:!this.zoomHandler,any:e||t}}touchAction(){let e=this.pageTakes();if(e.x&&e.y&&e.zoom)return`manipulation`;let t=[e.x&&`pan-x`,e.y&&`pan-y`,e.zoom&&`pinch-zoom`].filter(Boolean);return t.length>0?t.join(` `):`none`}attach(){let e=()=>this.viewportGetter?.()??null;qo.add(this.element),this.savedTouchAction=this.element.style.getPropertyValue(`touch-action`),this.element.style.setProperty(`touch-action`,this.touchAction());let t=e=>{let t=this.axisStrips?.()??null,n=t?.plot??this.axisViewportGetter?.()?.chartRect;if(!n)return null;let r=this.axisDragHandler!==null;if(e.y>(t?.timeAxisTop??n.y+n.height))return r?`time`:null;let i=e.y>=n.y&&e.y<=n.y+n.height;if(e.x>n.x+n.width)return i?r?`price`:null:`inert`;let a=t?.left;return a&&a.width>0&&e.x<n.x&&e.x>=n.x-a.width?i&&a.scales&&r?`price`:`inert`:null},n=e=>{let t=this.axisStrips?.()??null,n=t?.plot??this.axisViewportGetter?.()?.chartRect;if(!n)return`plot`;if(e.y>(t?.timeAxisTop??n.y+n.height))return`timeAxis`;let r=e.y>=n.y&&e.y<=n.y+n.height,i=t?.left,a=!!i&&i.width>0&&e.x<n.x&&e.x>=n.x-i.width;return e.x>n.x+n.width||a?r?`priceAxis`:`pane`:r?`plot`:`pane`},r=e=>{let t=(this.viewportGetter?.()??this.axisViewportGetter?.())?.chartRect;return t?{x:Math.max(t.x,Math.min(t.x+t.width,e.x)),y:Math.max(t.y,Math.min(t.y+t.height,e.y))}:e},i=()=>this.zoomArea?`zoom-in`:this.crosshairHandler&&this.crosshairHandler.getMode()!==`hidden`?`crosshair`:``,a=e=>{this.element.style.cursor!==e&&(this.element.style.cursor=e)},o=n=>{let r=t(n);if(r===`price`)return`ns-resize`;if(r===`time`)return`ew-resize`;if(r===`inert`)return`default`;let a=this.paneResizeHandler?.cursorAt(n);if(a)return a;if(this.alertDragHandler?.isOverAlert(n))return`ns-resize`;let o=e();return this.tradingManager?.isOverButton(n)?`pointer`:o&&this.tradingManager?.isOverDraggableLine(n,o)?`ns-resize`:this.zoomArea?`zoom-in`:(o?this.drawingManager?.hoverCursorAt(n,o):null)||(o&&this.priceAxisAdd?.button.hit(n,o)?`pointer`:i())},s=!1,c=``,l=e=>{if(!(e.buttons&1)){b(e);return}g(e)},u=()=>{s||(s=!0,this.leaveMarker(),c=document.documentElement.style.userSelect,document.documentElement.style.userSelect=`none`,document.addEventListener(`mousemove`,l))},d=()=>{s&&(s=!1,document.documentElement.style.userSelect=c,document.removeEventListener(`mousemove`,l))},f=e=>e===this.element||e instanceof HTMLCanvasElement,p=(n,r,o)=>{this.panHandler?.cancelMomentum();let s=e(),c=o===`mouse`,l=c?void 0:Uo;this.pressPlacedPoint=!1,this.downPos=n,this.downMoved=!1,this.pressForClick=!1;let u=t(n);if(u===`inert`)return`inert`;if(u&&this.axisDragHandler)return this.axisDragHandler.begin(u,n),`taken`;if(this.paneResizeHandler?.tryBegin(n,l?.divider))return`taken`;let d=!!this.drawingManager?.getActiveTool()||!!this.tradingManager?.isBracketActive()||!!this.tradingManager?.isOrderDraftActive();return this.boxSelectHandlers&&(this.zoomArea||r.ctrl&&!d)?(this.boxSelecting=!0,this.boxSelectHandlers.begin(n),c&&a(i()),this.onOverlayDirty?.(!0),`taken`):r.shift&&this.measureHandlers?(this.measuring=!0,this.measureHandlers.begin(n),this.onOverlayDirty?.(!0),`taken`):r.alt&&this.onAltClick?(this.onAltClick(n),`taken`):this.priceAxisAdd&&s&&!d&&this.priceAxisAdd.button.hit(n,s)&&!this.alertDragHandler?.isOverAlert(n)&&!this.tradingManager?.isOverButton(n)&&!this.tradingManager?.isOverDraggableLine(n,s)&&!this.drawingManager?.hoverCursorAt(n,s)?(this.priceAxisAdd.onClick(n),`menu`):this.tradingManager&&s&&this.tradingManager.onPointerDown(n,s,l)?(c&&a(this.tradingManager.isOverButton(n)?`pointer`:`ns-resize`),`taken`):this.drawingManager&&s&&this.drawingManager.onPointerDown(n,s,l)?(c&&this.drawingManager.isDragging()&&a(`grabbing`),this.pressPlacedPoint=!!this.drawingManager.getActiveTool(),d||this.drawingManager.isEraser()?`taken`:`drawing`):this.alertDragHandler?.tryBegin(n,l?.alert)?(this.onOverlayDirty?.(),`taken`):(this.pressForClick=!0,this.panHandler&&(this.panHandler.onPointerDown(n),c&&a(`grabbing`)),`pan`)},m=e=>{if(Jo=this.element,e.button!==0||!f(e.target))return;u(),this.invalidateRect();let t={ctrl:e.ctrlKey||e.metaKey,shift:e.shiftKey,alt:e.altKey};p(this.getMousePos(e),t,`mouse`)===`menu`&&e.preventDefault()},h=e=>{if(!s){if(!f(e.target)){this.leaveMarker();return}g(e)}},g=e=>{let t=this.getMousePos(e);if(!s){let e=this.markerAt?.(t)??null;e!==this.hoveredMarker&&(this.hoveredMarker=e,this.onMarkerHover?.(e,t)),e&&(this.markerPos=t),a(e&&this.markerClickable()?`pointer`:o(t))}_(t,`mouse`,s)},_=(t,n,i,a=t)=>{let o=e();if(this.downPos&&!this.downMoved){let e=n===`mouse`?Yo:Xo;Math.hypot(t.x-this.downPos.x,t.y-this.downPos.y)>e&&(this.downMoved=!0)}if(this.axisDragHandler?.isActive()){this.axisDragHandler.move(t),n===`touch`&&this.onOverlayDirty?.();return}if(this.paneResizeHandler?.isActive()){this.paneResizeHandler.move(t),n===`touch`&&this.onOverlayDirty?.();return}if(this.alertDragHandler?.isActive()){this.alertDragHandler.move(r(t)),this.onOverlayDirty?.();return}if(this.measuring&&this.measureHandlers){this.measureHandlers.move(t),this.onOverlayDirty?.(!0);return}if(this.boxSelecting&&this.boxSelectHandlers){this.boxSelectHandlers.move(t),this.onOverlayDirty?.(!0);return}if(this.tradingManager&&o&&this.tradingManager.onPointerMove(i?r(t):t,o)){this.crosshairHandler?.onPointerMove(t),this.onOverlayDirty?.();return}if(this.drawingManager&&o&&this.drawingManager.onPointerMove(t,o)){this.crosshairHandler?.onPointerMove(t),this.onOverlayDirty?.();return}this.panHandler?.onPointerMove(a),this.crosshairHandler?.onPointerMove(t),this.onOverlayDirty?.(!i)},v=(t,n,r=!1)=>{let i=this.downPos,a=this.downMoved&&i!==null,o=this.pressPlacedPoint,s=this.pressForClick&&!this.downMoved&&i!==null&&!r;if(this.pressForClick=!1,this.pressPlacedPoint=!1,this.downPos=null,this.downMoved=!1,this.boxSelecting&&this.boxSelectHandlers)return this.boxSelecting=!1,r?this.boxSelectHandlers.cancel():this.boxSelectHandlers.end(),this.onOverlayDirty?.(!0),!1;if(this.axisDragHandler?.isActive())return this.axisDragHandler.end(),!1;if(this.paneResizeHandler?.isActive())return this.paneResizeHandler.end(),!1;if(this.alertDragHandler?.isActive())return this.alertDragHandler.end(),this.onOverlayDirty?.(),!1;if(this.measuring&&this.measureHandlers)return this.measuring=!1,this.measureHandlers.end(),this.onOverlayDirty?.(!0),!1;if(r?this.tradingManager?.cancelPointer():this.tradingManager?.onPointerUp(t??void 0))return!1;let c=e();return r&&o&&this.drawingManager?.takeBackPoint(),n===`touch`&&a&&!r&&t&&c&&this.drawingManager?.placeAt(t,c),this.drawingManager?.onPointerUp()?!1:(this.panHandler?.onPointerUp(),r&&this.panHandler?.cancelMomentum(),s&&this.onClick&&this.onClick(i),s)},y=(n,r)=>{let i=t(n);if(i){i!==`inert`&&this.onAxisDoubleClick?.(i);return}let a=e();if(!a||this.drawingManager?.justFinished())return;let o=this.drawingManager?.drawingAt(n,a,r);o&&this.onDrawingDoubleClick?.(o)},b=e=>{if(e.button!==0&&e.type===`mouseup`||!s)return;d();let t=this.getMousePos(e);a(o(t)),v(t,`mouse`)},x=e=>{y(this.getMousePos(e))},S=()=>{if(this.leaveMarker(),s){this.crosshairHandler?.onPointerLeave(),this.onOverlayDirty?.(!0);return}a(``),this.panHandler?.onPointerUp(),this.drawingManager?.onPointerUp(),this.tradingManager?.onPointerUp(),this.alertDragHandler?.end(),this.paneResizeHandler?.end(),this.crosshairHandler?.onPointerLeave(),this.pressForClick=!1,this.downPos=null,this.onOverlayDirty?.()},C=e=>{if(!this.zoomHandler||this.pageScroll&&!e.ctrlKey)return;e.preventDefault();let t=this.getMousePos(e);this.zoomHandler.onWheel(e.deltaY,t)},w=e=>{if(!es()){if(e.key===`Escape`&&this.boxSelecting&&this.boxSelectHandlers&&(this.boxSelecting=!1,this.boxSelectHandlers.cancel(),this.onOverlayDirty?.(!0)),e.key===`Escape`&&this.onEscape&&this.onEscape(),e.key===`Enter`&&this.onConfirm&&this.onConfirm()){e.preventDefault();return}e.key!==`Escape`&&!this.ownsShortcuts()||this.drawingManager?.onKeyDown(e.key,e.ctrlKey||e.metaKey,e.shiftKey)&&e.preventDefault()}},T=t=>{if(this.touchActive||Date.now()-this.lastTouchAt<Qo){t.preventDefault();return}let r=e();if(!r)return;let i=this.getMousePos(t),a=r.chartRect,o=i.x>=a.x&&i.x<=a.x+a.width&&i.y>=a.y&&i.y<=a.y+a.height,s=this.onDrawingContextMenu&&o&&!this.drawingManager?.getActiveTool()?this.drawingManager?.drawingAt(i,r):null;if(s){t.preventDefault(),this.onDrawingContextMenu?.(s,i);return}if(this.tradingManager?.onContextMenu(i,r)){t.preventDefault();return}this.onChartContextMenu?.(n(i),i)&&t.preventDefault()},E=e=>{if(Jo=this.element,!(!this.touchActive&&!f(e.target))){if(this.lastTouchAt=Date.now(),this.invalidateRect(),e.touches.length===1){let t=this.getTouchPos(e.touches[0]);this.touchStartPos=t,this.longPressed=!1,this.touchYielded=!1,this.touchDecided=!1;let n=p(t,$o,`touch`);if(this.touchActive=!0,this.touchFallthrough=n===`pan`||n===`inert`,this.touchStartPrevented=!(this.touchFallthrough&&this.pageTakes().any),this.touchStartPrevented&&e.preventDefault(),n===`drawing`){D(t);return}if(n!==`pan`)return;this.onAltClick&&(this.clearLongPress(),this.longPressTimer=setTimeout(()=>{this.longPressTimer=null,this.longPressed=!0,this.pressForClick=!1,this.onAltClick?.(t),this.panHandler?.onPointerUp(),this.panHandler?.cancelMomentum(),this.onOverlayDirty?.(!0)},Zo)),this.crosshairHandler?.onPointerMove(t),this.onOverlayDirty?.(!0)}else if(e.touches.length===2){if(this.clearLongPress(),this.touchActive&&!this.touchYielded&&this.lastTouchDist===0&&v(null,`touch`,!0),!this.zoomHandler&&!this.panHandler){this.touchActive=!1;return}e.cancelable&&e.preventDefault(),this.lastTouchDist=this.getTouchDistance(e.touches[0],e.touches[1]),this.lastTouchMid=this.getTouchMidpoint(e.touches[0],e.touches[1]),this.touchActive=!0,this.touchYielded=!1}}},D=t=>{this.onDrawingContextMenu&&(this.clearLongPress(),this.longPressTimer=setTimeout(()=>{this.longPressTimer=null;let n=e(),r=n?this.drawingManager?.drawingAt(t,n,Uo.line):null;r&&(v(null,`touch`,!0),this.longPressed=!0,this.touchYielded=!0,this.crosshairHandler?.onPointerLeave(),this.onDrawingContextMenu?.(r,t),this.onOverlayDirty?.())},Zo))},O=e=>{if(this.touchDecided)return!1;let t=e.x-this.touchStartPos.x,n=e.y-this.touchStartPos.y;if(Math.hypot(t,n)<=Xo)return!1;this.touchDecided=!0;let r=this.pageTakes();return Math.abs(n)>=Math.abs(t)?r.y:r.x},k=e=>{if(!(!this.touchActive||this.touchYielded)){if(e.touches.length===1){let t=this.getTouchPos(e.touches[0]);if(this.lastTouchDist>0){e.cancelable&&e.preventDefault(),this.panHandler?.onPointerMove(this.pageScroll?{x:t.x,y:this.touchStartPos.y}:t),this.onOverlayDirty?.();return}if(this.longPressTimer&&Math.hypot(t.x-this.touchStartPos.x,t.y-this.touchStartPos.y)>Xo&&this.clearLongPress(),this.touchFallthrough&&this.pageTakes().any){if(!this.touchDecided&&Math.hypot(t.x-this.touchStartPos.x,t.y-this.touchStartPos.y)<=Xo)return;if(O(t)){this.touchYielded=!0,v(null,`touch`,!0),this.crosshairHandler?.onPointerLeave(),this.onOverlayDirty?.(!0);return}}e.cancelable&&e.preventDefault(),_(t,`touch`,!0,this.pageScroll?{x:t.x,y:this.touchStartPos.y}:t)}else if(e.touches.length===2){e.cancelable&&e.preventDefault();let t=this.getTouchDistance(e.touches[0],e.touches[1]),n=this.getTouchMidpoint(e.touches[0],e.touches[1]);this.lastTouchDist>0&&t>0&&this.zoomHandler?.onPinch(t/this.lastTouchDist,n);let r=this.lastTouchMid.x-n.x;Math.abs(r)>1&&(this.panHandler?.onPointerDown(this.lastTouchMid),this.panHandler?.onPointerMove({x:n.x,y:this.lastTouchMid.y})),this.lastTouchDist=t,this.lastTouchMid=n,this.onOverlayDirty?.()}}},A=e=>{if(this.clearLongPress(),this.touchActive)if(this.lastTouchAt=Date.now(),e.touches.length===0){let t=e.changedTouches?.[0],n=t?this.getTouchPos(t):null,r=this.lastTouchDist>0,i=!r&&!this.longPressed&&!this.touchYielded&&this.downPos!==null&&!this.downMoved;this.touchYielded||(r?this.panHandler?.onPointerUp():v(n,`touch`),!this.touchStartPrevented&&e.cancelable&&e.preventDefault()),i&&n&&this.taps.tap(n)?y(n,Uo.line):i||this.taps.reset(),this.crosshairHandler?.onPointerLeave(),this.touchActive=!1,this.touchYielded=!1,this.lastTouchDist=0,this.onOverlayDirty?.()}else if(e.touches.length===1&&!this.touchYielded){let t=this.getTouchPos(e.touches[0]);this.touchStartPos=t,this.panHandler?.onPointerDown(t)}else e.touches.length===2&&this.lastTouchDist>0&&(this.lastTouchDist=this.getTouchDistance(e.touches[0],e.touches[1]),this.lastTouchMid=this.getTouchMidpoint(e.touches[0],e.touches[1]))},ee=()=>{this.clearLongPress(),this.touchActive&&(this.lastTouchAt=Date.now(),this.touchYielded||(this.lastTouchDist>0?(this.panHandler?.onPointerUp(),this.panHandler?.cancelMomentum()):v(null,`touch`,!0)),this.taps.reset(),this.crosshairHandler?.onPointerLeave(),this.touchActive=!1,this.touchYielded=!1,this.lastTouchDist=0,this.onOverlayDirty?.())},te=()=>this.invalidateRect(),ne=()=>this.invalidateRect(),re=()=>this.invalidateRect(),ie=e=>{let t=e.target instanceof Node&&this.element.contains(e.target)&&f(e.target);(s||t)&&e.preventDefault()};this.element.addEventListener(`mousedown`,m),this.element.addEventListener(`mousemove`,h),document.addEventListener(`dragstart`,ie,!0),document.addEventListener(`mouseup`,b),this.element.addEventListener(`mouseleave`,S),this.element.addEventListener(`dblclick`,x),this.element.addEventListener(`wheel`,C,{passive:!1}),this.element.addEventListener(`contextmenu`,T),this.element.addEventListener(`touchstart`,E,{passive:!1}),this.element.addEventListener(`touchmove`,k,{passive:!1}),this.element.addEventListener(`touchend`,A),this.element.addEventListener(`touchcancel`,ee),document.addEventListener(`keydown`,w),window.addEventListener(`resize`,te),document.addEventListener(`scroll`,ne,{capture:!0,passive:!0}),this.element.addEventListener(`mouseenter`,re),this.boundHandlers.push(d,()=>this.element.removeEventListener(`mousedown`,m),()=>document.removeEventListener(`dragstart`,ie,!0),()=>this.element.removeEventListener(`mousemove`,h),()=>document.removeEventListener(`mouseup`,b),()=>this.element.removeEventListener(`mouseleave`,S),()=>this.element.removeEventListener(`dblclick`,x),()=>this.element.removeEventListener(`wheel`,C),()=>this.element.removeEventListener(`contextmenu`,T),()=>this.element.removeEventListener(`touchstart`,E),()=>this.element.removeEventListener(`touchmove`,k),()=>this.element.removeEventListener(`touchend`,A),()=>this.element.removeEventListener(`touchcancel`,ee),()=>document.removeEventListener(`keydown`,w),()=>window.removeEventListener(`resize`,te),()=>document.removeEventListener(`scroll`,ne,{capture:!0}),()=>this.element.removeEventListener(`mouseenter`,re))}detach(){qo.delete(this.element),this.savedTouchAction?this.element.style.setProperty(`touch-action`,this.savedTouchAction):this.element.style.removeProperty(`touch-action`),Jo===this.element&&(Jo=null);for(let e of this.boundHandlers)e();this.boundHandlers=[],this.cachedRect=null,this.clearLongPress()}clearLongPress(){this.longPressTimer&&=(clearTimeout(this.longPressTimer),null)}invalidateRect(){this.cachedRect=null}getRect(){return this.cachedRect||=this.element.getBoundingClientRect(),this.cachedRect}ownsShortcuts(){let e=document.activeElement;if(e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.tagName===`SELECT`||e.isContentEditable))return!1;for(let t of qo)if(e&&t.contains(e))return t===this.element;return Jo===null||Jo===this.element}getMousePos(e){let t=this.getRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}getTouchPos(e){let t=this.getRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}getTouchDistance(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)}getTouchMidpoint(e,t){let n=this.getRect();return{x:(e.clientX+t.clientX)/2-n.left,y:(e.clientY+t.clientY)/2-n.top}}},ns=16,rs=3,is=class{enabled=!1;setEnabled(e){this.enabled=e}isEnabled(){return this.enabled}hit(e,t){if(!this.enabled)return!1;let{x:n,y:r,width:i,height:a}=t.chartRect,o=n+i-ns-rs;return e.x>=o&&e.x<=n+i&&e.y>=r&&e.y<=r+a}render(e,t,n,r){if(!this.enabled||!r)return;let{x:i,y:a,width:o,height:s}=t.chartRect;if(r.y<a||r.y>a+s||r.x<i||r.x>i+o)return;let c=i+o-rs-ns/2,l=ns/2;e.fillStyle=n.background,e.strokeStyle=n.axisLabelBackground,e.lineWidth=1,e.beginPath(),e.arc(c,r.y,l-.5,0,Math.PI*2),e.fill(),e.stroke(),e.strokeStyle=n.text,e.lineWidth=1.5,e.beginPath(),e.moveTo(c-l*.45,r.y),e.lineTo(c+l*.45,r.y),e.moveTo(c,r.y-l*.45),e.lineTo(c,r.y+l*.45),e.stroke()}},as=100,os=50,ss=.1,cs=60,ls=16;function us(){return typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches}var ds=class{dragging=!1;lastX=0;lastY=0;samples=[];momentumId=0;callback;onStart;friction=.92;constructor(e,t){this.callback=e,this.onStart=t}isDragging(){return this.dragging}onPointerDown(e){this.dragging=!0,this.lastX=e.x,this.lastY=e.y,this.samples=[{t:Date.now(),x:e.x,y:e.y}],this.stopMomentum(),this.onStart?.()}onPointerMove(e){if(!this.dragging)return;let t=this.lastX-e.x,n=this.lastY-e.y;this.lastX=e.x,this.lastY=e.y;let r=Date.now();for(this.samples.push({t:r,x:e.x,y:e.y});this.samples.length>2&&r-this.samples[1].t>as;)this.samples.shift();(t||n)&&this.callback(t,n)}onPointerUp(){if(!this.dragging)return;this.dragging=!1;let e=this.releaseVelocity(Date.now());this.samples=[],!us()&&e&&Math.hypot(e.x,e.y)>ss&&this.startMomentum(e.x,e.y)}cancelMomentum(){this.stopMomentum()}releaseVelocity(e){let t=this.samples[this.samples.length-1];if(!t||e-t.t>os)return null;let n=this.samples.find(e=>t.t-e.t<=as)??this.samples[0],r=t.t-n.t;return r<=0?null:{x:(n.x-t.x)/r,y:(n.y-t.y)/r}}startMomentum(e,t){this.stopMomentum();let n=e*ls,r=t*ls,i=Math.hypot(n,r);i>cs&&(n*=cs/i,r*=cs/i);let a=null,o=e=>{let t=a===null?1:Math.min(4,Math.max(0,(e-a)/ls));a=e;let i=this.friction**t;if(n*=i,r*=i,Math.hypot(n,r)<.5){this.momentumId=0;return}this.callback(n*t,r*t),this.momentumId=requestAnimationFrame(o)};this.momentumId=requestAnimationFrame(o)}stopMomentum(){this.momentumId&&=(cancelAnimationFrame(this.momentumId),0)}},fs=class{callback;sensitivity;pendingDelta=0;pendingScale=1;pendingCenterX=0;rafId=0;constructor(e,t=.001){this.callback=e,this.sensitivity=t}onWheel(e,t){this.pendingDelta+=-e*this.sensitivity,this.pendingCenterX=t.x,this.schedule()}onPinch(e,t){!(e>0)||!Number.isFinite(e)||(this.pendingScale*=e,this.pendingCenterX=t.x,this.schedule())}schedule(){this.rafId||=requestAnimationFrame(()=>{this.rafId=0;let e=(1+this.pendingDelta)*this.pendingScale-1,t=this.pendingCenterX;this.pendingDelta=0,this.pendingScale=1,this.callback(e,t)})}dispose(){this.rafId&&=(cancelAnimationFrame(this.rafId),0)}},ps=class{dragging=!1;axis=null;startPos={x:0,y:0};lastPos={x:0,y:0};moved=!1;threshold=3;sensitivity=.005;constructor(e,t){this.onPriceScale=e,this.onTimeScale=t}begin(e,t){this.dragging=!0,this.axis=e,this.startPos=t,this.lastPos=t,this.moved=!1}move(e){if(!this.dragging||!this.axis)return!1;let t=e.x-this.startPos.x,n=e.y-this.startPos.y;if(!this.moved&&Math.hypot(t,n)<this.threshold)return!1;if(this.moved=!0,this.axis===`price`){let t=e.y-this.lastPos.y,n=Math.exp(t*this.sensitivity);this.onPriceScale(n)}else{let t=e.x-this.lastPos.x,n=Math.exp(t*this.sensitivity);this.onTimeScale(n)}return this.lastPos=e,!0}end(){let e=this.dragging&&this.moved;return this.dragging=!1,this.axis=null,this.moved=!1,e}isActive(){return this.dragging}},ms=class{draggingId=null;constructor(e,t){this.alerts=e,this.viewportGetter=t}isOverAlert(e){let t=this.viewportGetter();return t?this.alerts.getAlertAtPoint(e,t)!==null:!1}tryBegin(e,t){let n=this.viewportGetter();if(!n)return!1;let r=this.alerts.getAlertAtPoint(e,n,t);return r?(this.draggingId=r.id,!0):!1}move(t){if(this.draggingId===null)return;let n=this.viewportGetter();n&&this.alerts.updateAlertPrice(this.draggingId,e.M(t.y,n))}end(){this.draggingId=null}isActive(){return this.draggingId!==null}},hs=class{state=null;layoutGetter=null;onResize=null;constructor(e=4){this.tolerance=e}configure(e,t){this.layoutGetter=e,this.onResize=t}hitTest(e,t,n=this.tolerance){for(let r of t.dividers)if(gs(e,r.rect,n)){let e=t.panels.find(e=>e.config.id===r.panelId);if(e)return{panelId:r.panelId,orientation:r.orientation,position:e.config.position,size:r.orientation===`horizontal`?e.rect.height:e.rect.width}}return null}cursorAt(e){let t=this.layoutGetter?.();if(!t)return null;let n=this.hitTest(e,t);return n?n.orientation===`horizontal`?`ns-resize`:`ew-resize`:null}tryBegin(e,t){let n=this.layoutGetter?.();if(!n)return!1;let r=this.hitTest(e,n,Math.max(t??0,this.tolerance));return r?(this.state={panelId:r.panelId,position:r.position,startSize:r.size,startPos:e},!0):!1}move(e){let t=this.computeSize(e);t&&this.onResize?.(t.panelId,t.size)}computeSize(e){let t=this.state;if(!t)return null;let n=0;switch(t.position){case`bottom`:n=t.startPos.y-e.y;break;case`top`:n=e.y-t.startPos.y;break;case`left`:n=e.x-t.startPos.x;break;case`right`:n=t.startPos.x-e.x;break}return{panelId:t.panelId,size:t.startSize+n}}end(){this.state=null}isActive(){return this.state!==null}};function gs(e,t,n){return e.x>=t.x-n&&e.x<=t.x+t.width+n&&e.y>=t.y-n&&e.y<=t.y+t.height+n}var _s=class{position=null;callback=null;data=[];source=null;tz=null;timeFormatter=null;timesPastData=!0;setTimesPastData(e){this.timesPastData=e}getTimesPastData(){return this.timesPastData}setTimeFormatter(e){this.timeFormatter=e}setTimezoneOffset(e){this.tz=e}magnetMode=!0;mode=`magnet`;pricePrecision=null;locale=`en-US`;syncedSlot=null;pendingBarIndex=null;pendingPoint=null;callbackScheduled=!1;lastCallbackBarIndex=-1;reportTop=null;reportBottom=null;setCallback(e){this.callback=e}setData(e){this.data=e}setDataSource(e){this.source=e}series(){return this.source?.()??this.data}setMagnetMode(e){this.magnetMode=e,this.mode=e?`magnet`:`normal`}setMode(e){this.mode=e,this.magnetMode=e===`magnet`}getMode(){return this.mode}setPricePrecision(e){this.pricePrecision=e}setLocale(e){this.locale=e}getPosition(){return this.position}setSyncedSlot(e){this.syncedSlot=e!==null&&Number.isFinite(e)?e:null}getSyncedSlot(){return this.syncedSlot}setReportBounds(e){this.reportTop=e?.top??null,this.reportBottom=e?.bottom??null}onPointerMove(e){this.position=e}onPointerLeave(){this.position=null,this.pendingBarIndex=null,this.pendingPoint=null,this.lastCallbackBarIndex=-1,this.flushCallback(null,null)}render(n,r,i){if(this.mode===`hidden`)return;if(!this.position){this.syncedSlot!==null&&this.renderSynced(n,r,i,this.syncedSlot);return}let{chartRect:a}=r,{x:o,y:s}=this.position;if(o<a.x||o>a.x+a.width)return;let c=a.y+a.height;if(s<Math.min(this.reportTop??a.y,a.y)||s>Math.max(this.reportBottom??c,c))return;let l=s>=a.y&&s<=c,u=e.A(o,r),d=this.series().length,f=Math.max(0,Math.min(d-1,u)),p=u>=0&&u<d;if(this.magnetMode&&(o=e.b(u,r)),f!==this.lastCallbackBarIndex&&(this.pendingBarIndex=f,this.pendingPoint={x:o,y:s},this.lastCallbackBarIndex=f,this.scheduleCallback()),!l)return;let m=se(i);this.magnetMode&&p&&ys(n,o,r,m.vertical.color),bs(n,o,a,m.vertical);let h=m.horizontal;if(h.visible){n.setLineDash((0,t.lineDash)(h.style,vs,h.width)),n.strokeStyle=h.color;let r=e._(n,s,h.width);n.lineWidth=r.width,n.beginPath(),n.moveTo(a.x,r.y),n.lineTo(a.x+a.width,r.y),n.stroke()}n.setLineDash([])}renderAxisLabels(n,r,i,a,o,s=[],l=[]){if(this.mode===`hidden`)return;if(!this.position){this.syncedSlot!==null&&this.renderSyncedTimeLabel(n,r,i,a,this.syncedSlot,o,l);return}let{chartRect:u}=r,{x:d,y:f}=this.position;if(d<u.x||d>u.x+u.width||f<u.y||f>u.y+u.height)return;let p=e.A(d,r);this.magnetMode&&(d=e.b(p,r));let m=`600 ${i.font.sizeSmall}px ${i.font.family}`,h=c(e.M(f,r),r,this.pricePrecision??(0,t.autoPricePrecision)(r.priceRange.min,r.priceRange.max),this.locale),g=u.x+u.width;ws(n,s,f,g,r.priceAxisWidth??t.PRICE_AXIS_WIDTH,i),Ts(n,{text:h,anchorX:g,anchorY:f,orientation:`right`,bg:se(i).labelBackground,fg:se(i).labelText,theme:i,font:m}),this.drawTimePill(n,r,i,a,p,d,o,l)}renderSynced(t,n,r,i){let a=e.b(i,n),{chartRect:o}=n;if(a<o.x||a>o.x+o.width)return;let s=se(r);this.magnetMode&&i>=0&&i<this.series().length&&ys(t,a,n,s.vertical.color),bs(t,a,o,s.vertical)}renderSyncedTimeLabel(t,n,r,i,a,o,s=[]){let c=e.b(a,n),{chartRect:l}=n;c<l.x||c>l.x+l.width||this.drawTimePill(t,n,r,i,a,c,o,s)}drawTimePill(n,r,i,a,o,s,c,l=[]){if(a.length===0||!this.timesPastData&&(o<0||o>=a.length))return;let u=e.y(o,a),d=this.timeFormatter?this.timeFormatter(u*(0,t.barTimeUnit)(a),{kind:`crosshair`,timeZone:this.tz}):Es(u*(0,t.barTimeUnit)(a),this.tz,(0,t.barsAreDaily)(a)),f=`600 ${i.font.sizeSmall}px ${i.font.family}`,p=c??r.chartRect.y+r.chartRect.height;n.font=f;let m=Math.ceil(n.measureText(d).width)/2+Ss;Cs(n,l,s-m,s+m,p,i),Ts(n,{text:d,anchorX:s,anchorY:p,orientation:`bottom`,bg:se(i).labelBackground,fg:se(i).labelText,theme:i,font:f})}scheduleCallback(){this.callbackScheduled||(this.callbackScheduled=!0,queueMicrotask(()=>{this.callbackScheduled=!1,this.flushCallback(this.pendingBarIndex,this.pendingPoint)}))}flushCallback(e,t){this.callback?.(e,t)}},vs=[4,4];function ys(e,t,n,r){let i=n.barWidth+n.barSpacing;e.fillStyle=r,e.globalAlpha=.08,e.fillRect(t-i/2,n.chartRect.y,i,n.chartRect.height),e.globalAlpha=1}function bs(n,r,i,a){if(!a.visible)return;n.setLineDash((0,t.lineDash)(a.style,vs,a.width)),n.strokeStyle=a.color;let o=e.g(n,r,a.width);n.lineWidth=o.width,n.beginPath(),n.moveTo(o.x,i.y),n.lineTo(o.x,i.y+i.height),n.stroke(),n.setLineDash([])}var xs=20,Ss=8;function Cs(e,t,n,r,i,a){let o=t.filter(e=>e.right>n-2&&e.left<r+2);if(o.length!==0){e.save(),e.fillStyle=a.background;for(let t of o)e.fillRect(t.left-2,i+1,t.right-t.left+4,a.font.sizeSmall+12);e.restore()}}function ws(e,t,n,r,i,a){let o=Math.ceil(a.font.sizeSmall/2)+1,s=t.filter(e=>Math.abs(e-n)<xs/2+o);if(s.length!==0){e.save(),e.fillStyle=a.background;for(let t of s)e.fillRect(r+1,t-o,i-1,o*2);e.restore()}}function Ts(e,t){e.save(),e.font=t.font;let n=Ss,r=Math.ceil(e.measureText(t.text).width)+n*2,i=xs;if(e.fillStyle=t.bg,e.textBaseline=`middle`,t.orientation===`right`){let a=t.anchorX+5;E(e,a,t.anchorY-i/2,r,i,t.theme),e.beginPath(),e.moveTo(t.anchorX,t.anchorY),e.lineTo(a+2,t.anchorY-5),e.lineTo(a+2,t.anchorY+5),e.closePath(),e.fill(),e.fillStyle=t.fg,e.textAlign=`left`,e.fillText(t.text,a+n,t.anchorY)}else{let n=t.anchorX-r/2,a=t.anchorY+5;E(e,n,a,r,i,t.theme),e.beginPath(),e.moveTo(t.anchorX,t.anchorY),e.lineTo(t.anchorX-5,a+1),e.lineTo(t.anchorX+5,a+1),e.closePath(),e.fill(),e.fillStyle=t.fg,e.textAlign=`center`,e.fillText(t.text,t.anchorX,a+i/2)}e.restore()}function Es(e,n,r){let i=(0,t.timeParts)(e,n),{year:a,month:o,day:s,hours:c,minutes:l}=i;return r??(0,t.isDateOnly)(i)?`${o}/${s}/${a}`:`${o}/${s} ${c<10?`0`+c:c}:${l<10?`0`+l:l}`}var Ds=class{callbacks;enabled=!0;constructor(e){this.callbacks=e}setEnabled(e){this.enabled=e}handleKey(e){if(!this.enabled)return!1;let t=e.shiftKey?10:1;switch(e.key){case`ArrowLeft`:return this.callbacks.scrollBars(-t),!0;case`ArrowRight`:return this.callbacks.scrollBars(t),!0;case`ArrowUp`:case`+`:case`=`:return this.callbacks.zoom(.1),!0;case`ArrowDown`:case`-`:return this.callbacks.zoom(-.1),!0;case`Home`:return this.callbacks.goToStart(),!0;case`End`:return this.callbacks.goToEnd(),!0;case` `:return this.callbacks.fitContent(),!0;default:return!1}}},Os=16,ks=80,As=864e5,js={month:`short`,day:`numeric`},Ms={month:`short`,day:`numeric`,year:`numeric`};function Ns(e,n,r,i){return(0,t.zonedDateFormatter)(r,i?Ms:js,n)(e)}var Ps=e=>e<10?`0${e}`:`${e}`;function Fs(e,n,r,i=`en-US`,a){let o=(0,t.normalizeBarTime)(e,a),s=(0,t.timeParts)(o,n);if(r!==void 0&&r>0?r>=As:(0,t.isDateOnly)(s))return Ns(o,n,i,!0);let c=Ns(o,n,i,!1),l=`${Ps(s.hours)}:${Ps(s.minutes)}`;return r!==void 0&&r>0&&r<6e4?`${c} · ${l}:${Ps(new Date(o).getUTCSeconds())}`:`${c} · ${l}`}function Is(e,n){return Number.isFinite(e)?e>=1e9?`${(0,t.formatPrice)(e/1e9,2,n)}B`:e>=1e6?`${(0,t.formatPrice)(e/1e6,2,n)}M`:e>=1e3?`${(0,t.formatPrice)(e/1e3,1,n)}K`:(0,t.formatPrice)(e,e%1==0?0:2,n):`—`}var Ls=class{el=null;visible=!1;appliedTheme=null;locale=`en-US`;pricePrecision=null;tz=null;priceFormatter=null;timeFormatter=null;dirEl;timeEl;changeEl;valueEls;labelEls=[];dividerEl;width=176;height=112;create(e){if(this.el)return;let t=document.createElement(`div`);t.setAttribute(`aria-hidden`,`true`),Object.assign(t.style,{position:`absolute`,left:`0`,top:`0`,display:`none`,minWidth:`168px`,padding:`8px 10px 9px`,borderRadius:`var(--tcw-tooltip-radius, 8px)`,fontSize:`11.5px`,lineHeight:`1.45`,fontVariantNumeric:`tabular-nums`,pointerEvents:`none`,zIndex:`100`,whiteSpace:`nowrap`,willChange:`transform`,contain:`layout paint`,backdropFilter:`blur(10px)`});let n=Rs({display:`flex`,alignItems:`center`,gap:`7px`,marginBottom:`6px`});this.dirEl=Rs({width:`3px`,height:`12px`,borderRadius:`2px`,flex:`none`}),this.timeEl=Rs({flex:`1`,fontSize:`11px`,letterSpacing:`0.01em`}),this.changeEl=Rs({padding:`1px 6px`,borderRadius:`999px`,fontSize:`10.5px`,fontWeight:`600`}),n.append(this.dirEl,this.timeEl,this.changeEl);let r=Rs({display:`grid`,gridTemplateColumns:`auto 1fr auto 1fr`,columnGap:`8px`,rowGap:`1px`,alignItems:`baseline`}),i=e=>{let t=Rs({fontSize:`10px`,letterSpacing:`0.04em`});t.textContent=e,this.labelEls.push(t);let n=Rs({textAlign:`right`,fontWeight:`500`});return r.append(t,n),n},a=i(`O`),o=i(`H`),s=i(`L`),c=i(`C`);this.dividerEl=Rs({height:`1px`,margin:`6px 0 5px`});let l=Rs({display:`flex`,justifyContent:`space-between`,gap:`12px`}),u=Rs({fontSize:`10px`,letterSpacing:`0.04em`});u.textContent=`VOL`,this.labelEls.push(u);let d=Rs({fontWeight:`500`});l.append(u,d),this.valueEls={open:a,high:o,low:s,close:c,volume:d},t.append(n,r,this.dividerEl,l),e.appendChild(t),this.el=t}setLocale(e){this.locale=e}setPricePrecision(e){this.pricePrecision=e}setTimezoneOffset(e){this.tz=e}setPriceFormatter(e){this.priceFormatter=e}setTimeFormatter(e){this.timeFormatter=e}show(e,n,r,i,a={}){let o=this.el;if(!o)return;this.appliedTheme!==r&&this.applyTheme(r);let s=this.pricePrecision??(a.priceRange?(0,t.autoPricePrecision)(a.priceRange.min,a.priceRange.max):(0,t.autoPricePrecision)(n.low,n.high)),c=e=>this.priceFormatter?.(e)??(0,t.formatPrice)(e,s,this.locale),l=a.prevClose??n.open,u=n.close-l,d=l===0?0:u/l*100,f=u>=0,p=f?r.candleUp:r.candleDown,m=f?`+`:`−`;this.timeEl.textContent=this.timeFormatter?this.timeFormatter((0,t.normalizeBarTime)(n.time,a.timeUnit),{kind:`crosshair`,timeZone:this.tz}):Fs(n.time,this.tz,a.barStepMs,this.locale,a.timeUnit),this.changeEl.textContent=`${m}${(0,t.formatPrice)(Math.abs(d),2,this.locale)}%`,this.changeEl.style.color=p,this.changeEl.style.background=Vs(p,.14),this.dirEl.style.background=n.close>=n.open?r.candleUp:r.candleDown,this.valueEls.open.textContent=c(n.open),this.valueEls.high.textContent=c(n.high),this.valueEls.low.textContent=c(n.low),this.valueEls.close.textContent=c(n.close),this.valueEls.close.style.color=n.close>=n.open?r.candleUp:r.candleDown,this.valueEls.volume.textContent=Is(n.volume,this.locale),this.visible||=(o.style.display=`block`,!0),this.width=o.offsetWidth||this.width,this.height=o.offsetHeight||this.height;let h=a.plot??{x:0,y:0,width:i.width-ks,height:i.height},g=h.x+h.width,_=h.y+h.height,v=e.x+Os,y=e.y-this.height/2;v+this.width>g-4&&(v=e.x-this.width-Os),v<h.x+4&&(v=h.x+4),y+this.height>_-4&&(y=_-this.height-4),y<h.y+4&&(y=h.y+4),o.style.transform=`translate(${Math.round(v)}px, ${Math.round(y)}px)`}hide(){this.el&&this.visible&&(this.el.style.display=`none`,this.visible=!1)}isVisible(){return this.visible}destroy(){this.el?.remove(),this.el=null,this.visible=!1,this.appliedTheme=null,this.labelEls=[]}applyTheme(e){let t=this.el,n=zs(e.background);t.style.background=Vs(e.background,n?.9:.94),t.style.border=`1px solid ${e.axisLine}`,t.style.boxShadow=n?`0 12px 32px -8px rgba(0, 0, 0, 0.6), 0 2px 6px rgba(0, 0, 0, 0.35)`:`0 12px 32px -10px rgba(15, 19, 26, 0.22), 0 2px 6px rgba(15, 19, 26, 0.08)`,t.style.color=e.text,t.style.fontFamily=e.font.family,this.timeEl.style.color=e.textSecondary;for(let t of this.labelEls)t.style.color=e.textSecondary;this.dividerEl.style.background=e.axisLine,this.appliedTheme=e}};function Rs(e){let t=document.createElement(`div`);return Object.assign(t.style,e),t}function zs(e){let t=Bs(e);return t?(.299*t[0]+.587*t[1]+.114*t[2])/255<.5:!0}function Bs(e){if(e.startsWith(`#`)){let t=e.slice(1),n=t.length===3?t.split(``).map(e=>e+e).join(``):t.slice(0,6);return[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)]}let t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Vs(e,t){let n=Bs(e);return n?`rgba(${n[0]}, ${n[1]}, ${n[2]}, ${t})`:`color-mix(in srgb, ${e} ${Math.round(t*100)}%, transparent)`}var Hs=class{el=null;deltaEl=null;timeEl=null;ohlcEl=null;pinnedBar=null;pinnedIndex=-1;tz=null;priceFormatter=null;setTimezone(e){this.tz=e}setPriceFormatter(e){this.priceFormatter=e}fmt(e){return Us(this.priceFormatter?this.priceFormatter(e):e.toFixed(2))}create(e){if(this.el)return;this.el=document.createElement(`div`),Object.assign(this.el.style,{position:`absolute`,display:`none`,padding:`6px 10px`,borderRadius:`var(--tcw-tooltip-radius, 4px)`,fontSize:`11px`,fontFamily:`-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif`,lineHeight:`1.5`,pointerEvents:`auto`,cursor:`pointer`,zIndex:`99`,whiteSpace:`nowrap`,willChange:`transform`}),this.timeEl=document.createElement(`div`),this.ohlcEl=document.createElement(`div`),this.deltaEl=document.createElement(`div`),this.deltaEl.style.marginTop=`4px`,this.deltaEl.style.paddingTop=`4px`,this.deltaEl.style.borderTop=`1px solid currentColor`,this.deltaEl.style.opacity=`0.85`,this.deltaEl.style.fontVariantNumeric=`tabular-nums`,this.el.appendChild(this.timeEl),this.el.appendChild(this.ohlcEl),this.el.appendChild(this.deltaEl);let n=document.createElement(`div`);n.innerHTML=`${(0,t.iconSvg)(t.UI_ICONS.pin,10)}<span>pinned</span>`,n.style.display=`flex`,n.style.alignItems=`center`,n.style.gap=`3px`,n.style.fontSize=`9px`,n.style.opacity=`0.6`,n.style.marginBottom=`2px`,n.style.letterSpacing=`0.04em`,n.style.textTransform=`uppercase`,this.el.insertBefore(n,this.timeEl),e.appendChild(this.el)}pin(e,n,r,i){if(!this.el||!this.timeEl||!this.ohlcEl)return;this.pinnedBar=e,this.pinnedIndex=n;let a=e.close>=e.open?r.candleUp:r.candleDown,o=(0,t.timeParts)((0,t.normalizeBarTime)(e.time,i),this.tz);this.timeEl.textContent=`${o.month}/${o.day} ${Ws(o.hours)}:${Ws(o.minutes)}`,this.timeEl.style.color=r.textSecondary;let s=[];for(let[t,n]of[[`O `,e.open],[` H `,e.high],[` L `,e.low],[` C `,e.close]]){let e=document.createElement(`span`);e.style.opacity=`.6`,e.textContent=t;let r=document.createElement(`span`);r.style.color=a,r.textContent=this.fmt(n),s.push(e,r)}this.ohlcEl.replaceChildren(...s);let c=Gs(r.background);this.el.style.background=Ks(r.background,c?.96:.97),this.el.style.border=`1px solid ${a}`,this.el.style.boxShadow=c?`0 4px 12px rgba(0,0,0,0.55)`:`0 4px 12px rgba(0,0,0,0.18)`,this.el.style.color=r.text,this.el.style.backdropFilter=`blur(8px)`,this.el.style.display=`block`}unpin(){this.pinnedBar=null,this.pinnedIndex=-1,this.el&&(this.el.style.display=`none`)}isPinned(){return this.pinnedBar!==null}getPinnedIndex(){return this.pinnedIndex}reposition(t,n,r,i){if(!this.el||!this.pinnedBar)return;let a=e.b(this.pinnedIndex,t),o=e.T(this.pinnedBar.close,t),s=t.chartRect,c=a>=s.x-4&&a<=s.x+s.width+4;this.el.style.opacity=c?`1`:`0.35`;let l=Math.max(s.x,Math.min(s.x+s.width-180,a+8)),u=Math.max(s.y,Math.min(s.y+s.height-90,o-64));if(this.el.style.transform=`translate(${Math.round(l)}px, ${Math.round(u)}px)`,this.el.style.left=`0`,this.el.style.top=`0`,this.deltaEl)if(n&&r!==null&&r!==this.pinnedIndex){let e=n.close-this.pinnedBar.close,t=this.pinnedBar.close===0?0:e/this.pinnedBar.close*100,a=e>0?`+`:e<0?`−`:``,o=r-this.pinnedIndex,s=e>=0?i.candleUp:i.candleDown;this.deltaEl.style.color=s,this.deltaEl.innerHTML=`Δ ${a}${this.fmt(Math.abs(e))} <span style="opacity:.7">(${a}${Math.abs(t).toFixed(2)}%)</span> · ${o>0?`+`:``}${o} bars`,this.deltaEl.style.display=`block`}else this.deltaEl.style.display=`none`}destroy(){this.el?.remove(),this.el=null,this.deltaEl=null,this.timeEl=null,this.ohlcEl=null,this.pinnedBar=null,this.pinnedIndex=-1}};function Us(e){return e.replace(/[&<>"']/g,e=>`&#${e.charCodeAt(0)};`)}function Ws(e){return e<10?`0`+e:``+e}function Gs(e){if(e.startsWith(`#`)){let t=e.slice(1),n=t.length===3?t.split(``).map(e=>e+e).join(``):t.slice(0,6),r=parseInt(n.slice(0,2),16),i=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);return(.299*r+.587*i+.114*a)/255<.5}return!0}function Ks(e,t){if(e.startsWith(`#`)){let n=e.slice(1),r=n.length===3?n.split(``).map(e=>e+e).join(``):n.slice(0,6);return`rgba(${parseInt(r.slice(0,2),16)}, ${parseInt(r.slice(2,4),16)}, ${parseInt(r.slice(4,6),16)}, ${t})`}return e}var qs=class{listeners=new Map;tauriBridge=null;on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}hasListeners(e){return(this.listeners.get(e)?.size??0)>0}emit(e,t){let n={type:e,timestamp:Date.now(),payload:t},r=this.listeners.get(e);if(r)for(let e of r)e(n);if(this.tauriBridge?.enabled&&window.__TAURI__){let t=this.tauriBridge.eventPrefix??`tc-chart`;window.__TAURI__.event.emit(`${t}:${e}`,n).catch(()=>{})}}enableTauriBridge(e){this.tauriBridge=e}disableTauriBridge(){this.tauriBridge=null}destroy(){this.listeners.clear(),this.tauriBridge=null}},Js=`#FFFFFF`;function Ys(e){for(let t in e)if(e[t]!==null)return!0;return!1}function Xs(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];i!==null&&(n[t[r]]=i)}return n}function Zs(e,t){let n=t.style?.trading;return!n||!Ys(n)?e:{...e,orderColors:{...e.orderColors,...Xs({buy:n.buy,sell:n.sell},{buy:`buy`,sell:`sell`})},positionColors:{...e.positionColors,...Xs({profit:n.profit,loss:n.loss,entry:n.entry},{profit:`profit`,loss:`loss`,entry:`entry`})}}}function Qs(e,t){let n=t.style?.markers;return!n||!Ys(n)?e:{...e,...Xs(n,{long:`longColor`,short:`shortColor`,neutral:`neutralColor`})}}function $s(e,t){let n=t.style?.tradeZones;return!n||!Ys(n)?e:{...e,...Xs(n,{profit:`profitColor`,loss:`lossColor`,active:`activeColor`})}}function ec(e){return e?.style?.drawings.handle??Js}var tc=`rgba(12, 16, 22, 0.85)`,nc=tc,rc=t.DEFAULT_FONT_FAMILY,ic=ec(null);function ac(e){nc=e?.background??tc,rc=e?.font?.family||t.DEFAULT_FONT_FAMILY,ic=ec(e)}function oc(){return ic}function sc(){return rc}function W(e,t){return`${t?`${t} `:``}${e}px ${rc}`}function cc(e,t,n,r){e.save(),e.lineJoin=`round`,e.lineWidth=3,e.strokeStyle=nc,e.globalAlpha*=.85,e.setLineDash([]),e.strokeText(t,n,r),e.restore(),e.fillText(t,n,r)}function lc(e,t){return Math.ceil(e.measureText(t).width)+12}function uc(e,t,n,r,i,a=`#ffffff`){let o=lc(e,t),s=Math.round(r-18/2);return e.fillStyle=i,e.beginPath(),typeof e.roundRect==`function`?e.roundRect(n,s,o,18,4):e.rect(n,s,o,18),e.fill(),e.fillStyle=a,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(t,n+6,s+18/2+.5),o}var dc=14,fc=6,pc=4,mc=`rgba(19, 23, 34, 0.85)`,hc=`#FFFFFF`,gc=6e4,_c=60*gc,vc=24*_c;function yc(e){let t=Math.abs(e);return t>=10||t===0?2:t>=1?4:Math.min(10,Math.ceil(-Math.log10(t))+3)}function bc(e,t=e,n){return n?.formatPrice?n.formatPrice(e):e.toFixed(yc(t))}function xc(e,t,n){let r=t-e,i=e===0?0:r/e*100,a=r>=0?`+`:``;return`${a}${bc(r,e,n)} (${a}${i.toFixed(2)}%)`}function Sc(e){let t=Math.abs(e);if(t<_c)return`${Math.round(t/gc)}m`;if(t<vc){let e=Math.floor(t/_c),n=Math.round((t-e*_c)/gc);return n>0?`${e}h ${n}m`:`${e}h`}let n=Math.floor(t/vc),r=Math.round((t-n*vc)/_c);if(n>=7){let e=Math.floor(n/7),t=n-e*7;return t>0?`${e}w ${t}d`:`${e}w`}return r>0?`${n}d ${r}h`:`${n}d`}function Cc(e){return!!e.data&&e.data.length>0}function wc(t,n,r,i){let a=e.D(t.anchors[n].time,i),o=e.D(t.anchors[r].time,i);return Math.round(Math.abs(o-a))}function Tc(e,t,n,r){return Cc(r)?Sc(e.anchors[n].time-e.anchors[t].time):null}function Ec(e,t,n,r,i=`center`,a=!0){e.font=W(11);let o=0;for(let n of t)o=Math.max(o,e.measureText(n).width);let s=o+fc*2,c=t.length*dc+pc*2,l=i===`left`?n:i===`right`?n-s:n-s/2,u=a?r-c:r;e.fillStyle=mc,e.fillRect(l,u,s,c),e.fillStyle=hc,e.textAlign=`left`,e.textBaseline=`top`;for(let n=0;n<t.length;n++)e.fillText(t[n],l+fc,u+pc+n*dc);return{x:l,y:u,width:s,height:c}}function Dc(e,t,n){let r=Math.abs(e.anchors[t[1]].price-e.anchors[t[0]].price),i=Math.abs(e.anchors[n[1]].price-e.anchors[n[0]].price);return i===0?`—`:(r/i).toFixed(3)}var Oc={at:e=>e,value:e=>e,price:e=>e};function kc(t){if(!t)return Oc;let{min:n,max:r}=t.priceRange,i=t.logScale===!0&&n>0&&r>0;return{at:n=>e.D(n,t),value:i?e=>Math.log(Math.max(e,2**-52)):e=>e,price:i?Math.exp:e=>e}}function Ac(e,t,n){let r=n.x-t.x,i=n.y-t.y,a=r*r+i*i;if(a===0)return Math.hypot(e.x-t.x,e.y-t.y);let o=Math.max(0,Math.min(1,((e.x-t.x)*r+(e.y-t.y)*i)/a));return Math.hypot(e.x-(t.x+o*r),e.y-(t.y+o*i))}function jc(e,t,n,r=!1){for(let r=0;r<t.length-1;r++)if(Ac(e,t[r],t[r+1])<=n)return!0;return r&&t.length>2&&Ac(e,t[t.length-1],t[0])<=n}function Mc(e,t){switch(e.kind){case`boolean`:return typeof t==`boolean`;case`number`:return typeof t==`number`&&Number.isFinite(t);case`levels`:return Array.isArray(t);default:return typeof t==`string`}}var G=class{hitTestAnchor(e,t,n,r){for(let i=0;i<t.anchors.length;i++){let a=this.anchorToPixel(t.anchors[i],n);if(Math.hypot(e.x-a.x,e.y-a.y)<=r)return i}return-1}option(e,t){let n=this.descriptor.options?.[t],r=e.options?.[t];return n?r!==void 0&&Mc(n,r)?r:n.default:r}optionsOf(e){return t=>this.option(e,t)}visibleLevels(e,t=`levels`){return this.option(e,t).filter(e=>e.visible&&Number.isFinite(e.value))}extendLine(e,t,n,r,i){let a=t.x-e.x,o=t.y-e.y,s=Math.hypot(a,o);if(s===0||!r&&!i)return[e,t];let c=Math.hypot(n.chartRect.width,n.chartRect.height)*2,l=a/s*c,u=o/s*c;return[r?{x:e.x-l,y:e.y-u}:e,i?{x:t.x+l,y:t.y+u}:t]}linePriceAt(e,t,n,r,i,a=Oc){let o=this.lineValueAt(e,t,n,r,i,a);return o===null?null:a.price(o)}lineValueAt(e,t,n,r,i,a){let o=a.at(e.time),s=a.at(t.time);if(o===s)return null;let c=(a.at(n)-o)/(s-o);if(!Number.isFinite(c)||c<0&&!r||c>1&&!i)return null;let l=a.value(e.price);return l+(a.value(t.price)-l)*c}anchorToPixel(t,n){return{x:e.O(t.time,n),y:e.T(t.price,n)}}pixelToAnchor(t,n){return{time:e.j(t.x,n),price:e.M(t.y,n)}}applyLineStyle(e,t){switch(e.strokeStyle=t.color,e.lineWidth=t.lineWidth,e.lineCap=`butt`,e.lineJoin=`round`,t.lineStyle){case`dashed`:e.setLineDash([6,4]);break;case`dotted`:e.setLineDash([2,2]);break;default:e.setLineDash([]);break}}strokeHorizontal(t,n,r,i){let a=e._(t,i,Number(t.lineWidth)||1);t.lineWidth=a.width,t.beginPath(),t.moveTo(n,a.y),t.lineTo(r,a.y),t.stroke()}strokeVertical(t,n,r,i){let a=e.g(t,n,Number(t.lineWidth)||1);t.lineWidth=a.width,t.beginPath(),t.moveTo(a.x,r),t.lineTo(a.x,i),t.stroke()}resetLineStyle(e){e.setLineDash([]),e.lineCap=`butt`,e.lineJoin=`miter`}renderAnchorHandles(e,t,n){e.fillStyle=oc(),e.strokeStyle=t.style.color,e.lineWidth=1;for(let r of t.anchors){let t=this.anchorToPixel(r,n);e.fillRect(t.x-4,t.y-4,8,8),e.strokeRect(t.x-4,t.y-4,8,8)}}distanceToLine(e,t,n){return Ac(e,t,n)}distanceToInfiniteLine(e,t,n){let r=n.x-t.x,i=n.y-t.y,a=Math.hypot(r,i);return a===0?Math.hypot(e.x-t.x,e.y-t.y):Math.abs(r*(t.y-e.y)-i*(t.x-e.x))/a}};function Nc(e){let t={};for(let[n,r]of Object.entries(e))t[n]=Array.isArray(r)?r.map(e=>({...e})):r;return t}function K(e){return{...e,anchors:e.anchors.map(e=>({...e})),style:{...e.style},options:e.options?Nc(e.options):void 0,intervals:e.intervals?sn(e.intervals):void 0,group:e.group?{...e.group}:void 0,meta:e.meta?{...e.meta}:void 0}}function Pc(e,t){return JSON.stringify(e??{})===JSON.stringify(t??{})}function Fc(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n].time!==t[n].time||e[n].price!==t[n].price)return!1;return!0}var Ic=1,Lc=1,Rc=/^tc_drawing_(\d+)$/,zc=/^tc_group_(\d+)$/;function Bc(){return`tc_drawing_${Ic++}`}function Vc(){let e=Lc++;return{id:`tc_group_${e}`,number:e}}function Hc(e){for(let t of e){let e=Rc.exec(t.id);e&&(Ic=Math.max(Ic,Number(e[1])+1));let n=t.group?zc.exec(t.group.id):null;n&&(Lc=Math.max(Lc,Number(n[1])+1))}}function Uc(e,t){let n=new Map(e.map(e=>[e.id,e])),r=new Set(t);return[...t.map(e=>n.get(e)).filter(e=>e!==void 0),...e.filter(e=>!r.has(e.id))]}function Wc(e,t,n){let r=t-1;switch(n){case`front`:return r;case`back`:return 0;case`forward`:return Math.min(r,e+1);case`backward`:return Math.max(0,e-1)}}function Gc(e,t){return e.map(e=>e.id===t.id?structuredClone(t):e)}function Kc(e,t){switch(t.type){case`drawingBatch`:return[...t.actions??[]].reverse().reduce(Kc,[...e]);case`drawingCreate`:return t.after?e.filter(e=>e.id!==t.after.id):[...e];case`drawingRemove`:{if(!t.before)return[...e];let n=[...e];return n.splice(Math.min(t.index??n.length,n.length),0,structuredClone(t.before)),n}case`drawingOrder`:return t.order?Uc(e,t.order.before):[...e];case`drawingModify`:return t.before?Gc(e,t.before):[...e];default:return[...e]}}function qc(e,t){switch(t.type){case`drawingBatch`:return(t.actions??[]).reduce(qc,[...e]);case`drawingCreate`:return t.after?[...e,structuredClone(t.after)]:[...e];case`drawingRemove`:return t.before?e.filter(e=>e.id!==t.before.id):[...e];case`drawingOrder`:return t.order?Uc(e,t.order.after):[...e];case`drawingModify`:return t.after?Gc(e,t.after):[...e];default:return[...e]}}var Jc={"]":[`forward`,`front`],"}":[`front`,`front`],"[":[`backward`,`back`],"{":[`back`,`back`]};function Yc(e,t,n){if(e===`Escape`)return`escape`;if(e===`Enter`&&!t)return`finish`;if(e===`Delete`||e===`Backspace`)return`delete`;if(!t)return null;let r=n??(e.length===1&&e!==e.toLowerCase()),i=Jc[e];if(i)return i[+!!r];switch(e.toLowerCase()){case`c`:return`copy`;case`v`:return`paste`;case`d`:return`duplicate`;case`g`:return r?`ungroup`:`group`;case`z`:return r?`redo`:`undo`;case`y`:return`redo`;default:return null}}var Xc=2,Zc=6;function Qc(e){return e.descriptor.creation??`clicks`}var $c=class{drawing=null;plugin=null;preview=null;lastPos=null;dragging=!1;step=Xc;get current(){return this.drawing}reset(){this.drawing=null,this.plugin=null,this.preview=null,this.lastPos=null,this.dragging=!1,this.step=Xc}press(e,t,n,r,i){if(this.dragging)return`continue`;let a=Qc(e);if(!this.drawing)return this.plugin=e,this.drawing={...t(),anchors:[n]},this.preview=null,this.lastPos=r,a===`freehand`?(this.dragging=!0,`continue`):a===`clicks`&&e.descriptor.requiredAnchors<=1?`done`:`continue`;let o=this.drawing.anchors[this.drawing.anchors.length-1],s=i?i(o):this.lastPos;if(a===`path`&&s&&Math.hypot(r.x-s.x,r.y-s.y)<=Zc)return this.finish();this.commit(n,r);let c=a===`path`?e.descriptor.maxAnchors??100:e.descriptor.requiredAnchors;return this.drawing.anchors.length>=c?`done`:`continue`}move(e,t){if(!this.drawing||!this.plugin)return!1;if(this.dragging){let n=this.lastPos;return n&&Math.hypot(t.x-n.x,t.y-n.y)<this.step?!0:(this.drawing.anchors.length>=2e3&&(this.drawing.anchors=this.drawing.anchors.filter((e,t)=>t%2==0),this.step*=2),this.commit(e,t),!0)}return Qc(this.plugin)===`path`||this.drawing.anchors.length<this.plugin.descriptor.requiredAnchors?(this.preview=e,!0):!1}release(){return this.dragging?(this.dragging=!1,this.hasEnough()?`done`:`cancel`):null}undoPoint(){return!this.drawing||this.dragging||this.drawing.anchors.length<=1?(this.reset(),!1):(this.drawing.anchors.pop(),this.preview=null,this.lastPos=null,!0)}finish(){return!this.plugin||Qc(this.plugin)!==`path`||!this.hasEnough()?`continue`:(this.preview=null,`done`)}previewState(){return this.drawing?this.preview?{...this.drawing,anchors:[...this.drawing.anchors,this.preview]}:this.drawing:null}take(){let e=this.drawing;return this.reset(),e}hasEnough(){return!!this.drawing&&!!this.plugin&&this.drawing.anchors.length>=Math.max(2,this.plugin.descriptor.requiredAnchors)}commit(e,t){this.drawing.anchors.push(e),this.preview=null,this.lastPos=t}},el=30;function tl(t,n,r,i,a){if(r===`none`||i.length===0)return{time:t,price:n};let o=!!(a?.data&&a.data.length>0),s=Math.round(o?e.k(t,i):t);if(s<0||s>i.length-1)return{time:t,price:n};let c=i[s],l=o?c.time:s,u=c.open;for(let e of[c.high,c.low,c.close])Math.abs(n-e)<Math.abs(n-u)&&(u=e);return r===`magnet`&&a&&Math.abs(e.T(n,a)-e.T(u,a))>el?{time:l,price:n}:{time:l,price:u}}var nl=class{primaryId=null;others=new Set;listener=null;setListener(e){this.listener=e}change(e){let t=this.ids().join(`\0`),n=e();return this.listener&&this.ids().join(`\0`)!==t&&this.listener(this.ids()),n}get primary(){return this.primaryId}has(e){return e===this.primaryId||this.others.has(e)}ids(){return this.primaryId?[this.primaryId,...this.others]:[]}clear(){this.change(()=>{this.primaryId=null,this.others.clear()})}add(e){this.change(()=>{this.primaryId?e!==this.primaryId&&this.others.add(e):this.primaryId=e})}only(e,t=[]){this.change(()=>{this.primaryId=e,this.others.clear();for(let n of t)n!==e&&this.others.add(n)})}focus(e){e===this.primaryId||!this.others.has(e)||this.change(()=>{this.primaryId&&this.others.add(this.primaryId),this.others.delete(e),this.primaryId=e})}remove(e){return this.change(()=>this.removeNow(e))}removeNow(e){let t=!1;for(let n of e)this.others.delete(n)&&(t=!0),n===this.primaryId&&(this.primaryId=null,t=!0);if(!this.primaryId){let e=this.others.values().next();e.done||(this.primaryId=e.value,this.others.delete(e.value))}return t}},rl=3,il=class{start=null;handle=-1;grabbed=[];constructor(e){this.find=e}isActive(){return this.start!==null}beginMove(e,t){this.start=e,this.handle=-1,this.grabbed=t.map(e=>({id:e.id,anchors:e.anchors.map(e=>({...e})),before:K(e)}))}beginResize(e,t,n){this.start=e,this.handle=n,this.grabbed=[{id:t.id,anchors:t.anchors.map(e=>({...e})),before:K(t)}]}move(e,t,n){return!this.start||this.grabbed.length===0?!1:this.handle>=0?this.reshape(e,t,n):this.translate(e,t)}end(){let e=this.grabbed.flatMap(({id:e,before:t})=>{let n=this.find(e);return n?[{before:t,drawing:n}]:[]});return this.start=null,this.handle=-1,this.grabbed=[],e}translate(t,n){let r=this.start,i=t.x-r.x,a=t.y-r.y;if(Math.hypot(i,a)<rl&&this.unmoved())return!0;let o=n.barWidth+n.barSpacing,s=o>0?Math.round(i/o):0,c=n.data,l=t=>{let r=e.D(t,n)+s;return c&&c.length>0?e.y(r,c):r};for(let{id:t,anchors:r}of this.grabbed){let i=this.find(t);!i||i.locked||(i.anchors=r.map(t=>({time:s===0?t.time:l(t.time),price:a===0?t.price:e.M(e.T(t.price,n)+a,n)})))}return!0}unmoved(){return this.grabbed.every(({id:e,anchors:t})=>{let n=this.find(e)?.anchors;return!n||n.every((e,n)=>e.time===t[n]?.time&&e.price===t[n]?.price)})}reshape(n,r,i){let a=this.find(this.grabbed[0].id);if(!a)return!1;let o={time:e.j(n.x,r),price:e.M(n.y,r)};if(i?.moveHandle){let e=i.moveHandle(K(a),this.handle,o);a.anchors=e.anchors,a.options=e.options&&Object.keys(e.options).length>0?(0,t.sanitizeDrawingOptions)(i.descriptor.options,e.options):void 0}else this.handle<a.anchors.length&&(a.anchors[this.handle]=o);return!0}},al={drawings:[],pastes:0},ol=1e7,sl={line:8,handle:8},cl=class{registry=new Map;drawings=[];state=`idle`;activeTool=null;activeStyle={color:`#4c8dff`,lineWidth:1,lineStyle:`solid`,fillColor:`rgba(76, 141, 255, 0.1)`,fillOpacity:.1,fontSize:12};creator=new $c;finishedAt=-1/0;creationPressAt=-1/0;eraser=!1;selection=new nl;drag=new il(e=>this.drawings.find(t=>t.id===e));eventCallback=null;requestRender=null;undoRedo=null;magnetMode=`none`;dataGetter=null;displayDataGetter=null;stayInDrawingMode=!1;toolAllowed=()=>!0;toolDefaults=new Map;edits=new Map;batch=null;timeframe=null;register(e){this.registry.set(e.descriptor.type,e),this.dataGetter&&e.setDataGetter?.(this.dataGetter)}setEventCallback(e){this.eventCallback=e}setRequestRender(e){this.requestRender=e}setUndoRedoManager(e){this.undoRedo=e}setMagnetMode(e){this.magnetMode=e}getMagnetMode(){return this.magnetMode}setDataGetter(e){this.dataGetter=e;for(let t of this.registry.values())t.setDataGetter?.(e)}setDisplayDataGetter(e){this.displayDataGetter=e}snapToOHLC(e,t,n){let r=this.magnetMode===`none`?[]:this.displayDataGetter?.()??this.dataGetter?.()??[];return tl(e,t,this.magnetMode,r,n)}undo(){if(!this.undoRedo)return!1;let e=this.undoRedo.undo();return e?(this.applyUndoAction(e),!0):!1}redo(){if(!this.undoRedo)return!1;let e=this.undoRedo.redo();return e?(this.applyRedoAction(e),!0):!1}foreignHistory=null;setForeignHistory(e){this.foreignHistory=e}applyUndoAction(e){if(e.type===`indicators`||e.type===`custom`){this.foreignHistory?.(e,`undo`);return}this.applyHistory(Kc(this.drawings,e))}applyRedoAction(e){if(e.type===`indicators`||e.type===`custom`){this.foreignHistory?.(e,`redo`);return}this.applyHistory(qc(this.drawings,e))}applyHistory(e){let t=new Map(this.drawings.map((e,t)=>[e.id,{d:e,index:t}]));this.drawings=e,this.settleAfterHistory();let n=new Set(e.map(e=>e.id));for(let e of t.keys())n.has(e)||(this.edits.delete(e),this.eventCallback?.(`drawingRemove`,{id:e}));e.forEach((e,n)=>{let r=t.get(e.id);r?(r.d!==e||r.index!==n)&&this.eventCallback?.(`drawingUpdate`,{id:e.id}):this.eventCallback?.(`drawingCreate`,{id:e.id,type:e.type,drawing:e})})}settleAfterHistory(){this.selection.clear(),this.creator.reset(),this.state=this.activeTool?`creating`:`idle`,this.requestRender?.()}record(e){this.batch?this.batch.push(e):this.undoRedo?.push(e)}batchUndo(e){if(this.batch){e();return}let t=[];this.batch=t;try{e()}finally{this.batch=null}t.length===1?this.undoRedo?.push(t[0]):t.length>1&&this.undoRedo?.push({type:`drawingBatch`,before:null,after:null,actions:t})}deselect(e){this.selection.remove(e)&&!this.selection.primary&&this.state===`selected`&&(this.state=`idle`)}addToSelection(e){this.selection.add(e),this.state=`selected`}groupMates(e){let t=e.group?.id;return t?this.drawings.filter(n=>n.group?.id===t&&n.id!==e.id&&this.shown(n)).map(e=>e.id):[]}select(e){if(this.state===`creating`)return!1;let t=this.drawings.find(t=>t.id===e);return!t||!this.shown(t)?!1:(this.selection.has(e)||this.selection.only(e,this.groupMates(t)),this.state=`selected`,this.requestRender?.(),!0)}setSelectionListener(e){this.selection.setListener(e)}getSelectedDrawingIds(){return this.selection.ids()}selectInRect(t,n){if(this.state===`creating`)return 0;this.selection.clear(),this.state=`idle`;let r=Math.min(t.x0,t.x1),i=Math.max(t.x0,t.x1),a=Math.min(t.y0,t.y1),o=Math.max(t.y0,t.y1);for(let t of this.drawings)this.shown(t)&&t.anchors.some(t=>{let s=e.O(t.time,n),c=e.T(t.price,n);return s>=r&&s<=i&&c>=a&&c<=o})&&this.addToSelection(t.id);return this.requestRender?.(),this.getSelectedDrawingIds().length}toggleSelectionAt(e,t){if(this.state===`creating`)return!1;for(let n=this.drawings.length-1;n>=0;n--){let r=this.drawings[n];if(this.shown(r)&&this.registry.get(r.type)?.hitTest(e,r,t,8))return this.selection.has(r.id)?this.deselect([r.id]):this.addToSelection(r.id),this.requestRender?.(),!0}return!1}beginMove(e,t){this.state=`moving`;let n=this.getSelectedDrawingIds().filter(e=>e!==t.id).map(e=>this.drawings.find(t=>t.id===e)).filter(e=>e!==void 0&&!e.locked);this.drag.beginMove(e,[t,...n])}setFlags(e,t){this.batchUndo(()=>{for(let n of e){if((t.visible===void 0||n.visible===t.visible)&&(t.locked===void 0||n.locked===t.locked))continue;let e=K(n);Object.assign(n,t),this.record({type:`drawingModify`,before:e,after:K(n)})}}),t.visible===!1&&this.deselect(e.map(e=>e.id)),this.requestRender?.()}lockAllDrawings(){this.setFlags(this.drawings,{locked:!0})}unlockAllDrawings(){this.setFlags(this.drawings,{locked:!1})}hideAllDrawings(){this.setFlags(this.drawings,{visible:!1})}showAllDrawings(){this.setFlags(this.drawings,{visible:!0})}setTimeframe(e){e!==this.timeframe&&(this.timeframe=e,this.deselect(this.drawings.filter(e=>!this.shown(e)).map(e=>e.id)),this.requestRender?.())}isShown(e){let t=this.drawings.find(t=>t.id===e);return t!==void 0&&this.shown(t)}shown(e){return e.visible&&tn(e.intervals,this.timeframe)}setDrawingVisible(e,t){let n=this.drawings.find(t=>t.id===e);return n?(this.setFlags([n],{visible:t}),t):null}setDrawingsVisible(e,t){let n=new Set(e);this.setFlags(this.drawings.filter(e=>n.has(e.id)),{visible:t})}setDrawingsLocked(e,t){let n=new Set(e);this.setFlags(this.drawings.filter(e=>n.has(e.id)),{locked:t})}setDrawingLocked(e,t){let n=this.drawings.find(t=>t.id===e);return n?(this.setFlags([n],{locked:t}),t):null}setActiveTool(e){e&&this.setEraser(!1);let t=e!==this.activeTool;this.activeTool=e,this.state=e?`creating`:`idle`,this.creator.reset(),t&&this.eventCallback?.(`drawingToolChange`,{tool:e})}setStayInDrawingMode(e){this.stayInDrawingMode=e}isStayInDrawingMode(){return this.stayInDrawingMode}setToolFilter(e){this.toolAllowed=e}copySelection(){let e=this.getSelectedDrawingIds().map(e=>this.drawings.find(t=>t.id===e)).filter(e=>e!==void 0);return e.length===0?0:(al.drawings=e.map(e=>structuredClone(e)),al.pastes=0,e.length)}canPaste(){return this.state!==`creating`&&al.drawings.some(e=>this.canPasteType(e.type))}canPasteType(e){return this.registry.has(e)&&this.toolAllowed(e)}paste(){if(al.drawings.length===0||this.state===`creating`)return[];let e=al.drawings.every(e=>this.drawings.some(t=>t.id===e.id));al.pastes+=1;let t=e?this.computeBarOffsetTime(3*al.pastes):0,n=[];if(this.batchUndo(()=>{for(let e of al.drawings)this.canPasteType(e.type)&&n.push(this.addDrawing({type:e.type,anchors:e.anchors.map(e=>({...e,time:e.time+t})),style:{...e.style},options:e.options?Nc(e.options):void 0,intervals:e.intervals,meta:e.meta?structuredClone(e.meta):void 0}))}),n.length===0)return n;this.selection.clear(),this.state=`idle`;for(let e of n)this.isShown(e)&&this.addToSelection(e);return this.requestRender?.(),n}getActiveTool(){return this.activeTool}setStyle(e){Object.assign(this.activeStyle,e)}getActiveStyle(){return{...this.activeStyle}}setSelectedDrawingStyle(e,t){let n=t?[t]:this.getSelectedDrawingIds(),r=!1;return this.batchUndo(()=>{for(let t of n){let n=this.drawings.find(e=>e.id===t);if(!n||n.locked)continue;let i=K(n);n.style={...n.style,...e},this.record({type:`drawingModify`,before:i,after:K(n)}),r=!0}}),r&&this.requestRender?.(),r}onPointerDown(e,t,n=sl){return this.eraser?this.erase(e,t,n.line):this.state===`creating`&&this.activeTool?this.handleCreationClick(e,t):this.state===`idle`||this.state===`selected`?this.handleSelectionClick(e,t,n):!1}placeAt(e,t){let n=this.state===`creating`?this.creator.current:null;return!n||n.anchors.length!==1||this.registry.get(n.type)?.descriptor.creation===`freehand`?!1:this.handleCreationClick(e,t)}takeBackPoint(){return this.state!==`creating`||!this.creator.current?!1:(this.creator.undoPoint(),this.requestRender?.(),!0)}onPointerMove(e,t){let n=this.state===`creating`?this.creator.current:null;if(n&&this.creator.move(this.creationAnchor(n.type,e,t),e))return this.requestRender?.(),!0;if((this.state===`moving`||this.state===`resizing`)&&this.drag.isActive()){let n=this.drawings.find(e=>e.id===this.selection.primary);return this.drag.move(e,t,n&&this.registry.get(n.type))?(this.requestRender?.(),!0):!1}return!1}onPointerUp(){let e=this.state===`creating`?this.creator.release():null;if(e)return this.afterCreationStep(e),!0;if(this.state===`moving`||this.state===`resizing`){let e=this.drag.end();return this.batchUndo(()=>{for(let{before:t,drawing:n}of e)Fc(n.anchors,t.anchors)&&Pc(n.options,t.options)||this.record({type:`drawingModify`,before:t,after:K(n)})}),this.state=`selected`,!0}return!1}onKeyDown(e,t=!1,n){let r=Yc(e,t,n);if(!r)return!1;let i=this.state===`selected`?this.selection.primary:null;switch(r){case`copy`:return i!==null&&this.copySelection()>0;case`paste`:return this.paste().length>0;case`duplicate`:return i!==null&&this.duplicateDrawing(i)!==null;case`group`:return i!==null&&this.groupDrawings(this.getSelectedDrawingIds())!==null;case`ungroup`:return this.ungroupSelection();case`front`:case`forward`:case`backward`:case`back`:return i!==null&&this.moveDrawing(i,r);case`undo`:return this.state===`creating`&&this.creator.current?(this.creator.undoPoint(),this.requestRender?.(),!0):this.undo();case`redo`:return this.redo();case`escape`:return this.escape();case`delete`:return i!==null&&this.removeDrawings(this.getSelectedDrawingIds())>0;case`finish`:{if(this.state!==`creating`||!this.creator.current)return!1;let e=this.creator.finish();return e===`done`?(this.afterCreationStep(e),!0):!1}}}escape(){return this.eraser?(this.setEraser(!1),!0):this.state===`creating`?(this.setActiveTool(null),this.requestRender?.(),!0):this.state===`selected`?(this.selection.clear(),this.state=`idle`,this.requestRender?.(),!0):!1}ungroupSelection(){let e=new Set;for(let t of this.getSelectedDrawingIds()){let n=this.drawings.find(e=>e.id===t)?.group;n&&e.add(n.id)}for(let t of e)this.ungroup(t);return e.size>0}getDrawings(){return this.drawings}setDrawings(e){Hc(e),this.drawings=this.upgradeLegacyAnchors(e).map(e=>{if(!e.options&&e.intervals===void 0)return e;let n=(0,t.sanitizeDrawingOptions)(this.optionDefs(e.type),e.options);return{...e,options:Object.keys(n).length>0?n:void 0,intervals:nn(e.intervals)??void 0}});let n=new Map(this.drawings.map(e=>[e.id,e]));this.deselect(this.getSelectedDrawingIds().filter(e=>{let t=n.get(e);return!t||!this.shown(t)}));let r=new Set(n.keys());for(let e of[...this.edits.keys()])r.has(e)||this.edits.delete(e);this.requestRender?.()}moveDrawing(e,t){let n=this.drawings.findIndex(t=>t.id===e);if(n<0)return!1;let r=Wc(n,this.drawings.length,t);if(r===n)return!1;let i=this.drawings.map(e=>e.id),a=[...this.drawings],[o]=a.splice(n,1);return a.splice(r,0,o),this.drawings=a,this.record({type:`drawingOrder`,before:null,after:null,order:{before:i,after:a.map(e=>e.id)}}),this.eventCallback?.(`drawingUpdate`,{id:e}),this.requestRender?.(),!0}getGroups(){let e=new Map;for(let t of this.drawings){if(!t.group)continue;let n=e.get(t.group.id)??{id:t.group.id,name:t.group.name,ids:[]};n.ids.push(t.id),e.set(t.group.id,n)}return[...e.values()]}updateGroup(e,t){let n=this.drawings.filter(t=>t.group?.id===e);return n.length===0?!1:(this.batchUndo(()=>{for(let e of n){let n=K(e);t(e),this.record({type:`drawingModify`,before:n,after:K(e)}),this.eventCallback?.(`drawingUpdate`,{id:e.id})}}),this.requestRender?.(),!0)}groupDrawings(e,t){let n=new Set(e),r=this.drawings.filter(e=>n.has(e.id));if(r.length<2)return null;let{id:i,number:a}=Vc(),o={id:i,name:ll(t)||`Group ${a}`};return this.batchUndo(()=>{for(let e of r){let t=K(e);e.group={...o},this.record({type:`drawingModify`,before:t,after:K(e)}),this.eventCallback?.(`drawingUpdate`,{id:e.id})}}),this.requestRender?.(),o.id}ungroup(e){return this.updateGroup(e,e=>{delete e.group})}renameGroup(e,t){let n=ll(t);return n.length>0&&this.updateGroup(e,t=>{t.group={id:e,name:n}})}setGroupVisible(e,t){let n=this.updateGroup(e,e=>{e.visible=t});return n&&!t&&this.deselect(this.drawings.filter(t=>t.group?.id===e).map(e=>e.id)),n}setGroupLocked(e,t){return this.updateGroup(e,e=>{e.locked=t})}priceAt(e,t,n){let r=this.drawings.find(t=>t.id===e);if(!r)return null;let i=this.registry.get(r.type)?.priceAt?.(r,t,n)??null;return i&&i.every(Number.isFinite)?i:null}hasPriceLevels(e){let t=this.drawings.find(t=>t.id===e);return!!t&&typeof this.registry.get(t.type)?.priceAt==`function`}getDescriptor(e){return this.registry.get(e)?.descriptor??null}getOptionDefs(e){return this.optionDefs(e)??{}}optionDefs(e){return this.registry.get(e)?.descriptor.options}initialOptions(e,n){let r=this.optionDefs(e),i={...Nc(this.toolDefaults.get(e)??{}),...(0,t.sanitizeDrawingOptions)(r,n)};return Object.keys(i).length>0?i:void 0}setToolDefaults(e,n){let r=n?(0,t.sanitizeDrawingOptions)(this.optionDefs(e),n):{};Object.keys(r).length>0?this.toolDefaults.set(e,r):this.toolDefaults.delete(e)}getToolDefaults(e){return Nc(this.toolDefaults.get(e)??{})}getDrawingOptions(e){let n=this.drawings.find(t=>t.id===e);return n?(0,t.resolveDrawingOptions)(this.optionDefs(n.type),n.options):{}}setDrawingOptions(e,t){return this.updateDrawing(e,{options:t})}updateDrawing(e,n){let r=this.drawings.find(t=>t.id===e);if(!r||n.anchors&&!(n.anchors.length===r.anchors.length&&n.anchors.every(e=>Number.isFinite(e.time)&&Number.isFinite(e.price))))return!1;let i=this.edits.has(e)?null:K(r);if(n.anchors&&(r.anchors=n.anchors.map(e=>({time:e.time,price:e.price}))),n.style&&(r.style={...r.style,...n.style}),n.options){let e={...r.options,...(0,t.sanitizeDrawingOptions)(this.optionDefs(r.type),n.options)};r.options=Object.keys(e).length>0?e:void 0}return n.intervals!==void 0&&(r.intervals=nn(n.intervals)??void 0,!this.edits.has(e)&&!this.shown(r)&&this.deselect([e])),i&&this.record({type:`drawingModify`,before:i,after:K(r)}),this.eventCallback?.(`drawingUpdate`,{id:e}),this.requestRender?.(),!0}beginEdit(e){let t=this.drawings.find(t=>t.id===e);return t?(this.edits.has(e)||this.edits.set(e,K(t)),!0):!1}endEdit(e,{cancel:t=!1}={}){let n=this.edits.get(e);if(!n)return;this.edits.delete(e);let r=this.drawings.findIndex(t=>t.id===e);r<0||(t?(this.drawings[r]=n,this.requestRender?.()):JSON.stringify(n)!==JSON.stringify(this.drawings[r])&&this.record({type:`drawingModify`,before:n,after:K(this.drawings[r])}),this.shown(this.drawings[r])||this.deselect([e]),this.eventCallback?.(`drawingUpdate`,{id:e}))}addDrawing(e){e.id&&Hc([{id:e.id}]);let t=e.id??Bc(),n={id:t,type:e.type,anchors:e.anchors.map(e=>({...e})),style:{...this.activeStyle,...e.style},visible:e.visible??!0,locked:e.locked??!1,options:this.initialOptions(e.type,e.options),intervals:nn(e.intervals)??void 0,meta:e.meta};return this.drawings=[...this.drawings,n],this.record({type:`drawingCreate`,before:null,after:K(n)}),this.eventCallback?.(`drawingCreate`,{id:t,type:n.type,drawing:n}),this.requestRender?.(),t}upgradeLegacyAnchors(e){let t=this.dataGetter?.();if(!t||t.length===0)return e;let n=ol;return t[t.length-1].time<n?e:e.map(e=>({...e,anchors:e.anchors.map(e=>{if(!Number.isFinite(e.time)||e.time<0||e.time>=n)return e;let r=Math.max(0,Math.min(t.length-1,Math.round(e.time)));return{...e,time:t[r].time}})}))}removeDrawing(e){let t=this.drawings.findIndex(t=>t.id===e),n=this.drawings[t];this.drawings=this.drawings.filter(t=>t.id!==e),n&&this.record({type:`drawingRemove`,before:structuredClone(n),after:null,index:t}),this.deselect([e]),this.edits.delete(e),this.eventCallback?.(`drawingRemove`,{id:e}),this.requestRender?.()}removeDrawings(e){let t=[...new Set(e)].filter(e=>{let t=this.drawings.find(t=>t.id===e);return t!==void 0&&!t.locked});return t.length===0?0:(this.batchUndo(()=>{for(let e of t)this.removeDrawing(e)}),t.length)}duplicateDrawing(e){let t=this.drawings.find(t=>t.id===e);if(!t)return null;let n=structuredClone(t);n.id=Bc();let r=this.computeBarOffsetTime(3);return n.anchors=n.anchors.map(e=>({...e,time:e.time+r})),n.locked=!1,this.drawings.push(n),this.record({type:`drawingCreate`,before:null,after:structuredClone(n)}),this.selection.only(n.id),this.state=`selected`,this.eventCallback?.(`drawingCreate`,{id:n.id,type:n.type,drawing:n}),this.requestRender?.(),n.id}clearDrawings(){this.drawings=[],this.selection.clear(),this.state=`idle`,this.requestRender?.()}getSelectedDrawingId(){return this.selection.primary}render(e,t){e.save(),e.beginPath(),e.rect(t.chartRect.x,t.chartRect.y,t.chartRect.width,t.chartRect.height),e.clip();for(let n of this.drawings){if(!this.shown(n))continue;let r=this.registry.get(n.type);if(!r)continue;let i=this.selection.has(n.id);r.render(e,n,t,i)}let n=this.creator.previewState();n&&this.registry.get(n.type)?.render(e,n,t,!1),e.restore()}computeBarOffsetTime(e){let t=this.dataGetter?.();if(!t||t.length<2)return e;let n=Math.max(0,t.length-20),r=[];for(let e=n+1;e<t.length;e++)r.push(t[e].time-t[e-1].time);return r.length===0?e:(r.sort((e,t)=>e-t),e*r[Math.floor(r.length/2)])}creationAnchor(t,n,r){let i=e.j(n.x,r),a=e.M(n.y,r);return this.registry.get(t)?.descriptor.creation===`freehand`?{time:i,price:a}:this.snapToOHLC(i,a,r)}handleCreationClick(t,n){let r=this.activeTool,i=r?this.registry.get(r):void 0;if(!r||!i)return!1;let a=()=>({id:Bc(),type:r,anchors:[],style:{...this.activeStyle},visible:!0,locked:!1,options:this.initialOptions(r)});return this.creationPressAt=Date.now(),this.afterCreationStep(this.creator.press(i,a,this.creationAnchor(r,t,n),t,t=>({x:e.O(t.time,n),y:e.T(t.price,n)}))),!0}afterCreationStep(e){e===`done`?this.finalizeCreation():e===`cancel`&&this.creator.reset(),this.requestRender?.()}setEraser(e){e!==this.eraser&&(this.eraser=e,e&&(this.setActiveTool(null),this.selection.clear(),this.state=`idle`),this.eventCallback?.(`toolModeChange`,{eraser:e}),this.requestRender?.())}isEraser(){return this.eraser}erase(e,t,n){let r=this.erasableAt(e,t,n);return r?(this.removeDrawing(r),!0):!1}erasableAt(e,t,n=sl.line){for(let r=this.drawings.length-1;r>=0;r--){let i=this.drawings[r];if(!(!this.shown(i)||i.locked)&&this.registry.get(i.type)?.hitTest(e,i,t,n))return i.id}return null}justFinished(e=500){return Date.now()-this.creationPressAt<e&&this.finishedAt>=this.creationPressAt}finalizeCreation(){let e=this.creator.take();if(e){if(this.finishedAt=Date.now(),this.drawings.push(e),this.selection.only(e.id),this.record({type:`drawingCreate`,before:null,after:structuredClone(e)}),this.eventCallback?.(`drawingCreate`,{id:e.id,type:e.type,drawing:e}),this.stayInDrawingMode&&this.activeTool){this.selection.clear(),this.state=`creating`;return}this.activeTool=null,this.state=`selected`,this.eventCallback?.(`drawingToolChange`,{tool:null})}}isDragging(){return this.state===`moving`||this.state===`resizing`}drawingAt(e,t,n=sl.line){for(let r=this.drawings.length-1;r>=0;r--){let i=this.drawings[r];if(this.shown(i)&&this.registry.get(i.type)?.hitTest(e,i,t,n))return i.id}return null}hoverCursorAt(e,t){if(this.eraser)return this.erasableAt(e,t)?`pointer`:null;if(this.activeTool||this.state===`creating`)return null;let n=sl.line;if(this.selection.primary){let r=this.drawings.find(e=>e.id===this.selection.primary),i=r&&this.shown(r)&&!r.locked?this.registry.get(r.type):void 0;if(r&&i&&i.hitTestAnchor(e,r,t,n)>=0)return`move`}for(let r=this.drawings.length-1;r>=0;r--){let i=this.drawings[r];if(!(!this.shown(i)||i.locked)&&this.registry.get(i.type)?.hitTest(e,i,t,n))return`pointer`}return null}handleSelectionClick(e,t,n){let r=n.line;if(this.selection.primary){let i=this.drawings.find(e=>e.id===this.selection.primary);if(i&&this.shown(i)&&!i.locked){let a=this.registry.get(i.type);if(a){let o=a.hitTestAnchor(e,i,t,n.handle);if(o>=0)return this.state=`resizing`,this.drag.beginResize(e,i,o),!0;if(a.hitTest(e,i,t,r))return this.beginMove(e,i),!0}}}for(let n=this.drawings.length-1;n>=0;n--){let i=this.drawings[n];if(!this.shown(i))continue;let a=this.registry.get(i.type);if(a&&a.hitTest(e,i,t,r))return this.selection.has(i.id)?this.selection.focus(i.id):this.selection.only(i.id,this.groupMates(i)),this.requestRender?.(),i.locked?(this.state=`selected`,!1):(this.beginMove(e,i),!0)}return this.selection.primary&&(this.selection.clear(),this.state=`idle`,this.requestRender?.()),!1}};function ll(e){return(e??``).trim().slice(0,80)}var ul=class{constructor(e){this.manager=e}render(e,t,n){ac(n??null),this.manager.render(e,t)}};function dl(e,t,n){let r=Math.max(0,t),i=Math.min(e.length-1,n);if(i<=r)return null;let a=r,o=r;for(let t=r;t<=i;t++)e[t].high>e[a].high&&(a=t),e[t].low<e[o].low&&(o=t);if(a===o)return null;let s={time:e[a].time,price:e[a].high},c={time:e[o].time,price:e[o].low};return a<o?[s,c]:[c,s]}var fl={0:`#7d8696`,.236:`#e8505b`,.25:`#e8505b`,.382:`#c98316`,.5:`#1fa874`,.618:`#1398a8`,.75:`#1398a8`,.786:`#4c8dff`,1:`#7d8696`,1.272:`#a57cff`,1.414:`#e25592`,1.618:`#4c8dff`,2:`#a57cff`,2.618:`#e8505b`,3.618:`#a57cff`,4.236:`#e25592`};function pl(e,t=[]){return ml(e,t).map(e=>{let t=fl[e.value];return t?{...e,color:t}:e})}function ml(e,t=[]){return[...e.map(e=>({value:e,visible:!0})),...t.map(e=>({value:e,visible:!1}))].sort((e,t)=>e.value-t.value)}function hl(e=!1,t=!1){return{extendLeft:{kind:`boolean`,label:`Extend left`,default:e},extendRight:{kind:`boolean`,label:`Extend right`,default:t}}}var gl={showLevels:{kind:`boolean`,label:`Show levels`,default:!0},showPrices:{kind:`boolean`,label:`Show prices`,default:!0},labelPosition:{kind:`choice`,label:`Labels`,default:`left`,choices:[{value:`left`,label:`Left`},{value:`right`,label:`Right`}]}},_l=28,vl=48;function yl(e,t){return Math.atan2(e.y-t.y,t.x-e.x)*180/Math.PI}var bl=class extends G{descriptor={type:`trendAngle`,name:`Trend Angle`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=yl(i,a),s=a.x>=i.x?1:-1;this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),this.resetLineStyle(e),e.strokeStyle=t.style.color,e.lineWidth=1,e.setLineDash([3,3]),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x+s*vl,i.y),e.stroke(),e.setLineDash([]);let c=Math.atan2(a.y-i.y,a.x-i.x),l=s>0?0:Math.PI;s<0&&c<0&&(c+=2*Math.PI),e.beginPath(),e.arc(i.x,i.y,_l,Math.min(l,c),Math.max(l,c)),e.stroke(),e.font=W(11),e.fillStyle=t.style.color,e.textAlign=s>0?`left`:`right`,e.textBaseline=`middle`,cc(e,`${o.toFixed(1)}°`,i.x+s*(_l+6),i.y+(o>=0?-8:8)),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);return this.distanceToLine(e,i,a)<=r}},xl=12,Sl=3.5,Cl=8,wl=[{value:`normal`,label:`Normal`},{value:`arrow`,label:`Arrow`}],Tl={leftEnd:{kind:`choice`,label:`Left end`,default:`normal`,choices:wl},rightEnd:{kind:`choice`,label:`Right end`,default:`normal`,choices:wl}},El={showMiddlePoint:{kind:`boolean`,label:`Show middle point`,default:!1},showPriceRange:{kind:`boolean`,label:`Show price range`,default:!1},showBarsRange:{kind:`boolean`,label:`Show bars range`,default:!1},showDateRange:{kind:`boolean`,label:`Show date and time range`,default:!1},showAngle:{kind:`boolean`,label:`Show angle`,default:!1},alwaysShowStats:{kind:`boolean`,label:`Always show stats`,default:!1},statsPosition:{kind:`choice`,label:`Stats position`,default:`right`,choices:[{value:`left`,label:`Left`},{value:`center`,label:`Center`},{value:`right`,label:`Right`}]}};function Dl(e,t,n,r){let i=Math.atan2(n.y-t.y,n.x-t.x);e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-xl*Math.cos(i-Math.PI/6),n.y-xl*Math.sin(i-Math.PI/6)),e.lineTo(n.x-xl*Math.cos(i+Math.PI/6),n.y-xl*Math.sin(i+Math.PI/6)),e.closePath(),e.fillStyle=r,e.fill()}function Ol(e,t,n,r){let[i,a]=t;i.x===a.x&&i.y===a.y||(r(`leftEnd`)===`arrow`&&Dl(e,a,i,n),r(`rightEnd`)===`arrow`&&Dl(e,i,a,n))}function kl(e,t,n,r,i){let a=[];i(`showPriceRange`)&&a.push(xc(e.anchors[0].price,e.anchors[1].price,t)),i(`showBarsRange`)&&a.push(`${wc(e,0,1,t)} bars`);let o=i(`showDateRange`)?Tc(e,0,1,t):null;return o&&a.push(o),i(`showAngle`)&&a.push(`${yl(n,r).toFixed(1)}°`),a}function Al(e,t,n,[r,i],a,o){let s={x:(r.x+i.x)/2,y:(r.y+i.y)/2};if(o(`showMiddlePoint`)&&(e.beginPath(),e.arc(s.x,s.y,Sl,0,Math.PI*2),e.fillStyle=oc(),e.fill(),e.strokeStyle=t.style.color,e.lineWidth=1,e.stroke()),!a&&!o(`alwaysShowStats`))return;let c=kl(t,n,r,i,o);if(c.length===0)return;let[l,u]=r.x<=i.x?[r,i]:[i,r],d=o(`statsPosition`);if(d===`center`){Ec(e,c,s.x,s.y-Cl,`center`,!0);return}let[f,p]=d===`left`?[l,u]:[u,l],m=f.y<=p.y;Ec(e,c,d===`left`?f.x-Cl:f.x+Cl,f.y+(m?-Cl:Cl),d===`left`?`right`:`left`,m)}var jl=class extends G{descriptor={type:`trendLine`,name:`Trend Line`,requiredAnchors:2,options:{...hl(),...Tl,...El}};segment(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t);return this.extendLine(n,r,t,this.option(e,`extendLeft`),this.option(e,`extendRight`))}render(e,t,n,r){if(t.anchors.length<2)return;let[i,a]=this.segment(t,n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),this.resetLineStyle(e);let o=this.optionsOf(t);Ol(e,[i,a],t.style.color,o),Al(e,t,n,[this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n)],r,o),r&&this.renderAnchorHandles(e,t,n)}priceAt(e,t,n){if(e.anchors.length<2)return null;let r=this.linePriceAt(e.anchors[0],e.anchors[1],t,this.option(e,`extendLeft`),this.option(e,`extendRight`),kc(n));return r===null?null:[r]}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let[i,a]=this.segment(t,n);return this.distanceToLine(e,i,a)<=r}},Ml=class extends G{descriptor={type:`horizontalLine`,name:`Horizontal Line`,requiredAnchors:1};priceAt(e){return e.anchors.length<1?null:[e.anchors[0].price]}render(t,n,r,i){if(n.anchors.length<1)return;let a=e.T(n.anchors[0].price,r),{chartRect:o}=r;this.applyLineStyle(t,n.style),this.strokeHorizontal(t,o.x,o.x+o.width,a),this.resetLineStyle(t),t.fillStyle=n.style.color,t.font=W(11),t.textBaseline=`bottom`,cc(t,bc(n.anchors[0].price,n.anchors[0].price,r),o.x+4,a-3),i&&this.renderAnchorHandles(t,n,r)}hitTest(t,n,r,i){if(n.anchors.length<1)return!1;let a=e.T(n.anchors[0].price,r);return Math.abs(t.y-a)<=i&&t.x>=r.chartRect.x&&t.x<=r.chartRect.x+r.chartRect.width}},Nl=class extends G{descriptor={type:`horizontalRay`,name:`Horizontal Ray`,requiredAnchors:1};priceAt(e,t){return e.anchors.length<1||t<e.anchors[0].time?null:[e.anchors[0].price]}render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=i.y,{chartRect:o}=n;this.applyLineStyle(e,t.style),this.strokeHorizontal(e,i.x,o.x+o.width,a),this.resetLineStyle(e),e.fillStyle=t.style.color,e.font=W(11),e.textBaseline=`bottom`,cc(e,bc(t.anchors[0].price,t.anchors[0].price,n),i.x+4,a-3),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n);return Math.abs(e.y-i.y)<=r&&e.x>=i.x-r&&e.x<=n.chartRect.x+n.chartRect.width}},Pl=class extends G{descriptor={type:`verticalLine`,name:`Vertical Line`,requiredAnchors:1};render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),{chartRect:a}=n;this.applyLineStyle(e,t.style),this.strokeVertical(e,i.x,a.y,a.y+a.height),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n),{chartRect:a}=n;return Math.abs(e.x-i.x)<=r&&e.y>=a.y&&e.y<=a.y+a.height}},Fl=class extends G{descriptor={type:`ray`,name:`Ray`,requiredAnchors:2,options:El};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),{chartRect:o}=n,s=a.x-i.x,c=a.y-i.y,l=Math.hypot(s,c);if(l===0)return;let u=Math.hypot(o.width,o.height)*2,d=i.x+s/l*u,f=i.y+c/l*u;this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(d,f),e.stroke(),this.resetLineStyle(e),Al(e,t,n,[i,a],r,this.optionsOf(t)),r&&this.renderAnchorHandles(e,t,n)}priceAt(e,t,n){if(e.anchors.length<2)return null;let r=this.linePriceAt(e.anchors[0],e.anchors[1],t,!1,!0,kc(n));return r===null?null:[r]}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=a.x-i.x,s=a.y-i.y;return((e.x-i.x)*o+(e.y-i.y)*s)/(o*o+s*s)<0?!1:this.distanceToInfiniteLine(e,i,a)<=r}},Il=class extends G{descriptor={type:`extendedLine`,name:`Extended Line`,requiredAnchors:2,options:El};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),{chartRect:o}=n,s=a.x-i.x,c=a.y-i.y,l=Math.hypot(s,c);if(l===0)return;let u=Math.hypot(o.width,o.height)*2,d=i.x-s/l*u,f=i.y-c/l*u,p=i.x+s/l*u,m=i.y+c/l*u;this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(d,f),e.lineTo(p,m),e.stroke(),this.resetLineStyle(e),Al(e,t,n,[i,a],r,this.optionsOf(t)),r&&this.renderAnchorHandles(e,t,n)}priceAt(e,t,n){if(e.anchors.length<2)return null;let r=this.linePriceAt(e.anchors[0],e.anchors[1],t,!0,!0,kc(n));return r===null?null:[r]}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);return this.distanceToInfiniteLine(e,i,a)<=r}},Ll=class extends G{descriptor={type:`parallelChannel`,name:`Parallel Channel`,requiredAnchors:3,fill:!0,options:{...hl(),middleLine:{kind:`boolean`,label:`Middle line`,default:!1}}};lines(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i=this.option(e,`extendLeft`),a=this.option(e,`extendRight`),o=this.extendLine(n,r,t,i,a);if(e.anchors.length<3)return{base:o,parallel:null,middle:null,corners:null};let s=this.anchorToPixel(e.anchors[2],t),c=r.x-n.x,l=r.y-n.y,u=Math.hypot(c,l)||1,d=-l/u,f=c/u,p=(s.x-n.x)*d+(s.y-n.y)*f,m=(e,t)=>({x:e.x+d*p*t,y:e.y+f*p*t}),h=m(n,1),g=m(r,1);return{base:o,parallel:this.extendLine(h,g,t,i,a),middle:this.option(e,`middleLine`)?this.extendLine(m(n,.5),m(r,.5),t,i,a):null,corners:[n,r,g,h]}}render(e,t,n,r){if(t.anchors.length<2)return;let{base:i,parallel:a,middle:o,corners:s}=this.lines(t,n);this.applyLineStyle(e,t.style);for(let t of[i,a])t&&(e.beginPath(),e.moveTo(t[0].x,t[0].y),e.lineTo(t[1].x,t[1].y),e.stroke());if(o&&(e.setLineDash([4,4]),e.beginPath(),e.moveTo(o[0].x,o[0].y),e.lineTo(o[1].x,o[1].y),e.stroke()),s&&t.style.fillColor){e.fillStyle=t.style.fillColor,e.beginPath(),e.moveTo(s[0].x,s[0].y);for(let t of s.slice(1))e.lineTo(t.x,t.y);e.closePath(),e.fill()}this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}priceAt(e,t,n){if(e.anchors.length<3)return null;let[r,i,a]=e.anchors,o=kc(n),s=this.lineValueAt(r,i,t,this.option(e,`extendLeft`),this.option(e,`extendRight`),o),c=this.lineValueAt(r,i,a.time,!0,!0,o);if(s===null||c===null)return null;let l=o.value(a.price)-c,u=[s,s+l];return this.option(e,`middleLine`)&&u.push(s+l/2),u.map(o.price)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let{base:i,parallel:a,middle:o}=this.lines(t,n);return[i,a,o].some(t=>t!==null&&this.distanceToLine(e,t[0],t[1])<=r)}},Rl=class extends G{descriptor={type:`regressionChannel`,name:`Regression Channel`,requiredAnchors:2,fill:!0};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke();let o=a.x-i.x,s=a.y-i.y,c=Math.hypot(o,s);if(c===0){this.resetLineStyle(e);return}let l=Math.max(10,Math.min(c*.2,100)),u=-s/c*l,d=o/c*l;e.setLineDash([4,4]),e.beginPath(),e.moveTo(i.x+u,i.y+d),e.lineTo(a.x+u,a.y+d),e.stroke(),e.beginPath(),e.moveTo(i.x-u,i.y-d),e.lineTo(a.x-u,a.y-d),e.stroke(),t.style.fillColor&&(e.fillStyle=t.style.fillColor,e.beginPath(),e.moveTo(i.x+u,i.y+d),e.lineTo(a.x+u,a.y+d),e.lineTo(a.x-u,a.y-d),e.lineTo(i.x-u,i.y-d),e.closePath(),e.fill()),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.hypot(a.x-i.x,a.y-i.y),s=Math.max(10,Math.min(o*.2,100));return this.distanceToLine(e,i,a)<=r+s}};function zl(e,t,n,r,i=e=>e.toFixed(2)){let a=`${(e*100).toFixed(1)}%`,o=i(t);return n&&r?`${a} (${o})`:n?a:r?o:``}function Bl(t,n,r,i,a,o){let s=a.x1-a.x0;if(a.background&&i.length>1){let o=[...i].sort((e,t)=>e.level.value-t.level.value);for(let i=0;i<o.length-1;i++){let c=e.T(o[i].price,r),l=e.T(o[i+1].price,r),u=o[i+1].level.color,d=u??n.style.fillColor;d&&(t.fillStyle=d,t.globalAlpha=u?.07:.05+i*.02,t.fillRect(a.x0,Math.min(c,l),s,Math.abs(l-c)))}t.globalAlpha=1}t.font=W(11),t.textBaseline=`bottom`,t.textAlign=a.labelPosition===`right`?`right`:`left`;let c=a.labelPosition===`right`?a.x1-4:a.x0+4;for(let{level:s,price:l}of i){let i=e.T(l,r),u=s.color??n.style.color;o(u),t.globalAlpha=s.value===0||s.value===1?1:.8;let d=e._(t,i,Number(t.lineWidth)||1);t.lineWidth=d.width,t.beginPath(),t.moveTo(a.x0,d.y),t.lineTo(a.x1,d.y),t.stroke();let f=zl(s.value,l,a.showLevels,a.showPrices,e=>bc(e,e,r));f&&(t.globalAlpha=1,t.fillStyle=u,cc(t,f,c,i-3))}t.globalAlpha=1}function Vl(t,n,r,i,a,o){return t.x<i-o||t.x>a+o?!1:r.some(({price:r})=>Math.abs(t.y-e.T(r,n))<=o)}var Hl=pl([0,.236,.382,.5,.618,.786,1],[1.272,1.414,1.618,2.618,3.618,4.236]),Ul=class extends G{descriptor={type:`fibRetracement`,name:`Fibonacci Retracement`,requiredAnchors:2,fill:!0,options:{levels:{kind:`levels`,label:`Levels`,default:Hl},...hl(!0,!0),reverse:{kind:`boolean`,label:`Reverse`,default:!1},...gl,background:{kind:`boolean`,label:`Background`,default:!0}}};levels(e){let t=this.option(e,`reverse`),n=e.anchors[+!!t].price,r=e.anchors[+!t].price;return this.visibleLevels(e).map(e=>({level:e,price:n+(r-n)*e.value}))}span(e,t){let{chartRect:n}=t,r=this.anchorToPixel(e.anchors[0],t).x,i=this.anchorToPixel(e.anchors[1],t).x;return[this.option(e,`extendLeft`)?n.x:Math.min(r,i),this.option(e,`extendRight`)?n.x+n.width:Math.max(r,i)]}render(e,t,n,r){if(t.anchors.length<2)return;let[i,a]=this.span(t,n);Bl(e,t,n,this.levels(t),{x0:i,x1:a,showLevels:this.option(t,`showLevels`),showPrices:this.option(t,`showPrices`),labelPosition:this.option(t,`labelPosition`),background:this.option(t,`background`)},n=>this.applyLineStyle(e,{...t.style,color:n})),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let[i,a]=this.span(t,n);return Vl(e,n,this.levels(t),i,a,r)}},Wl=pl([0,.618,1,1.618,2,2.618,3.618,4.236],[.382,.5,.786,1.272,1.414]),Gl=class extends G{descriptor={type:`fibExtension`,name:`Fibonacci Extension`,requiredAnchors:3,fill:!0,options:{levels:{kind:`levels`,label:`Levels`,default:Wl},...hl(!0,!0),...gl,background:{kind:`boolean`,label:`Background`,default:!1}}};levels(e){let t=e.anchors[1].price-e.anchors[0].price,n=e.anchors[2].price;return this.visibleLevels(e).map(e=>({level:e,price:n+t*e.value}))}span(e,t){let{chartRect:n}=t,r=e.anchors.map(e=>this.anchorToPixel(e,t).x);return[this.option(e,`extendLeft`)?n.x:Math.min(...r),this.option(e,`extendRight`)?n.x+n.width:Math.max(...r)]}render(e,t,n,r){if(t.anchors.length<3){if(t.anchors.length===2){let r=this.anchorToPixel(t.anchors[0],n),i=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(i.x,i.y),e.stroke(),this.resetLineStyle(e)}return}let[i,a]=this.span(t,n);Bl(e,t,n,this.levels(t),{x0:i,x1:a,showLevels:this.option(t,`showLevels`),showPrices:this.option(t,`showPrices`),labelPosition:this.option(t,`labelPosition`),background:this.option(t,`background`)},n=>this.applyLineStyle(e,{...t.style,color:n})),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<3)return!1;let[i,a]=this.span(t,n);return Vl(e,n,this.levels(t),i,a,r)}},Kl=class extends G{descriptor={type:`rectangle`,name:`Rectangle`,requiredAnchors:2,fill:!0};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x),s=Math.min(i.y,a.y),c=Math.abs(a.x-i.x),l=Math.abs(a.y-i.y);t.style.fillColor&&(e.fillStyle=t.style.fillColor,e.fillRect(o,s,c,l)),this.applyLineStyle(e,t.style),e.strokeRect(o,s,c,l),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x)-r,s=Math.min(i.y,a.y)-r,c=Math.max(i.x,a.x)+r,l=Math.max(i.y,a.y)+r;if(e.x<o||e.x>c||e.y<s||e.y>l)return!1;let u=Math.min(i.x,a.x)+r,d=Math.min(i.y,a.y)+r,f=Math.max(i.x,a.x)-r,p=Math.max(i.y,a.y)-r;return!(e.x>u&&e.x<f&&e.y>d&&e.y<p)||!!t.style.fillColor}},ql=class extends G{descriptor={type:`ellipse`,name:`Ellipse`,requiredAnchors:2,fill:!0};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=(i.x+a.x)/2,s=(i.y+a.y)/2,c=Math.abs(a.x-i.x)/2,l=Math.abs(a.y-i.y)/2;e.beginPath(),e.ellipse(o,s,Math.max(c,1),Math.max(l,1),0,0,Math.PI*2),t.style.fillColor&&(e.fillStyle=t.style.fillColor,e.fill()),this.applyLineStyle(e,t.style),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=(i.x+a.x)/2,s=(i.y+a.y)/2,c=Math.max(Math.abs(a.x-i.x)/2,1),l=Math.max(Math.abs(a.y-i.y)/2,1),u=(e.x-o)/c,d=(e.y-s)/l,f=Math.sqrt(u*u+d*d),p=r/Math.max(Math.min(c,l),4);return t.style.fillColor?f<=1+p:Math.abs(f-1)<=p}},Jl=class extends G{descriptor={type:`triangle`,name:`Triangle`,requiredAnchors:3,fill:!0};render(e,t,n,r){if(t.anchors.length<3){if(t.anchors.length===2){let r=this.anchorToPixel(t.anchors[0],n),i=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(i.x,i.y),e.stroke(),this.resetLineStyle(e)}return}let i=t.anchors.map(e=>this.anchorToPixel(e,n));e.beginPath(),e.moveTo(i[0].x,i[0].y),e.lineTo(i[1].x,i[1].y),e.lineTo(i[2].x,i[2].y),e.closePath(),t.style.fillColor&&(e.fillStyle=t.style.fillColor,e.fill()),this.applyLineStyle(e,t.style),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<3)return!1;let i=t.anchors.map(e=>this.anchorToPixel(e,n));for(let t=0;t<3;t++){let n=(t+1)%3;if(this.distanceToLine(e,i[t],i[n])<=r)return!0}return!1}},Yl=class extends G{descriptor={type:`pitchfork`,name:`Andrews' Pitchfork`,requiredAnchors:3};origin(e,t){return e}render(e,t,n,r){if(t.anchors.length<3){if(t.anchors.length===2){let r=this.anchorToPixel(t.anchors[0],n),i=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(i.x,i.y),e.stroke(),this.resetLineStyle(e)}return}let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=this.anchorToPixel(t.anchors[2],n),s=this.origin(i,a),c={x:(a.x+o.x)/2,y:(a.y+o.y)/2};(s.x!==i.x||s.y!==i.y)&&(e.strokeStyle=t.style.color,e.lineWidth=1,e.setLineDash([3,3]),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(s.x,s.y),e.stroke(),e.setLineDash([]));let l=c.x-s.x,u=c.y-s.y,d=Math.hypot(l,u)||1,f=Math.hypot(n.chartRect.width,n.chartRect.height),p=s.x+l/d*f,m=s.y+u/d*f;this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(p,m),e.stroke(),e.beginPath(),e.moveTo(a.x,a.y),e.lineTo(a.x+l/d*f,a.y+u/d*f),e.stroke(),e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(o.x+l/d*f,o.y+u/d*f),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<3)return!1;let i=this.anchorToPixel(t.anchors[1],n),a=this.anchorToPixel(t.anchors[2],n),o=this.origin(this.anchorToPixel(t.anchors[0],n),i),s={x:(i.x+a.x)/2,y:(i.y+a.y)/2};if(this.distanceToInfiniteLine(e,o,s)<=r)return!0;let c=s.x-o.x,l=s.y-o.y,u={x:i.x+c,y:i.y+l},d={x:a.x+c,y:a.y+l};return this.distanceToInfiniteLine(e,i,u)<=r||this.distanceToInfiniteLine(e,a,d)<=r}},Xl=class extends Yl{descriptor={type:`schiffPitchfork`,name:`Schiff Pitchfork`,requiredAnchors:3};origin(e,t){return{x:e.x,y:(e.y+t.y)/2}}},Zl=class extends Yl{descriptor={type:`modifiedSchiffPitchfork`,name:`Modified Schiff Pitchfork`,requiredAnchors:3};origin(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}},Ql=[`0`,`i`,`ii`,`iii`,`iv`,`v`];function $l(e,t){let n=/^[0-9]$/.test(e);switch(t){case`primary`:return n?e===`0`?`⓪`:String.fromCodePoint(9312+Number(e)-1):/^[A-Z]$/.test(e)?String.fromCodePoint(9398+e.charCodeAt(0)-65):e;case`intermediate`:return`(${e})`;case`minute`:return n?Ql[Number(e)]??e:e.toLowerCase();default:return e}}var eu={degree:{kind:`choice`,label:`Degree`,default:`minor`,choices:[{value:`primary`,label:`Primary`},{value:`intermediate`,label:`Intermediate`},{value:`minor`,label:`Minor`},{value:`minute`,label:`Minute`}]}},tu=class extends G{render(e,t,n,r){if(t.anchors.length<2)return;let i=t.anchors.map(e=>this.anchorToPixel(e,n));this.applyLineStyle(e,t.style),e.beginPath(),i.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.stroke(),this.resetLineStyle(e);let a=this.option(t,`degree`);e.font=W(12,`bold`),e.fillStyle=t.style.color,e.textAlign=`center`;for(let t=0;t<i.length&&t<this.labels.length;t++){let n=i[t-1]??i[t+1],r=i[t+1]??i[t-1],o=i[t].y<=Math.min(n.y,r.y);e.textBaseline=o?`bottom`:`top`,cc(e,$l(this.labels[t],a),i[t].x,i[t].y+(o?-6:6))}r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:jc(e,t.anchors.map(e=>this.anchorToPixel(e,n)),r)}},nu=class extends tu{descriptor={type:`elliottWave`,name:`Elliott Wave`,requiredAnchors:8,options:eu};labels=[`1`,`2`,`3`,`4`,`5`,`A`,`B`,`C`]},ru=class extends tu{descriptor={type:`elliottImpulse`,name:`Elliott Impulse Wave`,requiredAnchors:6,options:eu};labels=[`0`,`1`,`2`,`3`,`4`,`5`]},iu=class extends tu{descriptor={type:`elliottCorrection`,name:`Elliott Correction Wave`,requiredAnchors:4,options:eu};labels=[`0`,`A`,`B`,`C`]},au=class extends tu{descriptor={type:`elliottTriangle`,name:`Elliott Triangle Wave`,requiredAnchors:6,options:eu};labels=[`0`,`A`,`B`,`C`,`D`,`E`]},ou=class extends tu{descriptor={type:`elliottDoubleCombo`,name:`Elliott Double Combo Wave`,requiredAnchors:4,options:eu};labels=[`0`,`W`,`X`,`Y`]},su=class extends tu{descriptor={type:`elliottTripleCombo`,name:`Elliott Triple Combo Wave`,requiredAnchors:6,options:eu};labels=[`0`,`W`,`X`,`Y`,`X`,`Z`]},cu=class extends G{descriptor={type:`priceRange`,name:`Price Range`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x),s=Math.abs(a.x-i.x),c=Math.min(i.y,a.y),l=Math.abs(a.y-i.y),u=t.anchors[1].price>t.anchors[0].price;e.fillStyle=u?`rgba(31, 168, 116, 0.15)`:`rgba(232, 80, 91, 0.15)`,e.fillRect(o,c,s,l),this.applyLineStyle(e,t.style),e.strokeRect(o,c,s,l),this.resetLineStyle(e);let d=xc(t.anchors[0].price,t.anchors[1].price,n);e.font=W(12),e.fillStyle=u?`#1fa874`:`#e8505b`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(d,o+s/2,c+l/2),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x),s=Math.max(i.x,a.x),c=Math.min(i.y,a.y),l=Math.max(i.y,a.y);return e.x>=o-r&&e.x<=s+r&&e.y>=c-r&&e.y<=l+r}},lu=class extends G{descriptor={type:`dateRange`,name:`Date Range`,requiredAnchors:2};render(t,n,r,i){if(n.anchors.length<2)return;let a=this.anchorToPixel(n.anchors[0],r),o=this.anchorToPixel(n.anchors[1],r),{chartRect:s}=r,c=Math.min(a.x,o.x),l=Math.max(a.x,o.x);t.fillStyle=`rgba(76, 141, 255, 0.08)`,t.fillRect(c,s.y,l-c,s.height),this.applyLineStyle(t,n.style),t.beginPath(),t.moveTo(c,s.y),t.lineTo(c,s.y+s.height),t.stroke(),t.beginPath(),t.moveTo(l,s.y),t.lineTo(l,s.y+s.height),t.stroke(),this.resetLineStyle(t);let u=e.D(n.anchors[0].time,r),d=e.D(n.anchors[1].time,r),f=Math.max(0,Math.round(Math.abs(d-u)));t.font=W(12),t.fillStyle=n.style.color,t.textAlign=`center`,t.textBaseline=`top`,t.fillText(`${f} bars`,(c+l)/2,s.y+4),i&&this.renderAnchorHandles(t,n,r)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),{chartRect:o}=n,s=Math.min(i.x,a.x),c=Math.max(i.x,a.x);return e.x>=s-r&&e.x<=c+r&&e.y>=o.y&&e.y<=o.y+o.height}},uu=class extends G{descriptor={type:`measure`,name:`Measure`,requiredAnchors:2};render(t,n,r,i){if(n.anchors.length<2)return;let a=this.anchorToPixel(n.anchors[0],r),o=this.anchorToPixel(n.anchors[1],r);this.applyLineStyle(t,n.style),t.setLineDash([4,4]),t.beginPath(),t.moveTo(a.x,a.y),t.lineTo(o.x,o.y),t.stroke(),this.resetLineStyle(t);let s=e.D(n.anchors[0].time,r),c=e.D(n.anchors[1].time,r),l=Math.max(0,Math.round(Math.abs(c-s))),u=[`Price: ${xc(n.anchors[0].price,n.anchors[1].price,r)}`,`Bars: ${l}`],d=(a.x+o.x)/2,f=(a.y+o.y)/2;t.font=W(11),t.textAlign=`center`,t.textBaseline=`bottom`;let p=Math.max(...u.map(e=>t.measureText(e).width));t.fillStyle=`rgba(0, 0, 0, 0.7)`,t.fillRect(d-p/2-6,f-u.length*14-4,p+12,u.length*14+8),t.fillStyle=`#FFFFFF`;for(let e=0;e<u.length;e++)t.fillText(u[e],d,f-(u.length-1-e)*14);i&&this.renderAnchorHandles(t,n,r)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);return this.distanceToLine(e,i,a)<=r}};function du(e,t=`Text`){if(typeof e.style.text==`string`&&e.style.text.length>0)return e.style.text;let n=e.meta?.text;return typeof n==`string`&&n.length>0?n:t}var fu=class extends G{descriptor={type:`text`,name:`Text`,requiredAnchors:1,text:!0};render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=du(t),o=t.style.fontSize||14;if(e.font=`${o}px ${sc()}`,e.fillStyle=t.style.color,e.textAlign=`left`,e.textBaseline=`top`,r){let n=e.measureText(a);e.strokeStyle=t.style.color,e.lineWidth=1,e.setLineDash([3,3]),e.strokeRect(i.x-2,i.y-2,n.width+4,o+4),e.setLineDash([])}e.fillText(a,i.x,i.y),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=t.style.fontSize||14;return e.x>=i.x-r&&e.x<=i.x+80+r&&e.y>=i.y-r&&e.y<=i.y+a+r}},pu=class extends G{descriptor={type:`arrow`,name:`Arrow`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),Dl(e,i,a,t.style.color),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);return this.distanceToLine(e,i,a)<=r}},mu=[{label:`8x1`,ratio:8},{label:`4x1`,ratio:4},{label:`3x1`,ratio:3},{label:`2x1`,ratio:2},{label:`1x1`,ratio:1},{label:`1x2`,ratio:.5},{label:`1x3`,ratio:1/3},{label:`1x4`,ratio:.25},{label:`1x8`,ratio:.125}],hu=class extends G{descriptor={type:`gannFan`,name:`Gann Fan`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=a.x-i.x,s=a.y-i.y;if(Math.abs(o)<1)return;let c=s/o,l=o>0?1:-1,{chartRect:u}=n,d=l>0?u.x+u.width:u.x;this.applyLineStyle(e,t.style);for(let{label:n,ratio:r}of mu){let a=c*r,o=d,s=i.y+a*(o-i.x);e.globalAlpha=r===1?1:.5,e.lineWidth=r===1?t.style.lineWidth:Math.max(.5,t.style.lineWidth*.7),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(o,s),e.stroke();let f=o-l*4,p=s;p>u.y&&p<u.y+u.height&&(e.globalAlpha=.7,e.fillStyle=t.style.color,e.font=W(9),e.textAlign=l>0?`right`:`left`,e.textBaseline=`bottom`,cc(e,n,f,p-2))}e.globalAlpha=1,this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=a.x-i.x,s=a.y-i.y;if(Math.abs(o)<1)return!1;let c=s/o,l=o>0?1:-1,{chartRect:u}=n,d=l>0?u.x+u.width:u.x;for(let{ratio:t}of mu){let n=c*t,a=d,o=i.y+n*(a-i.x);if(this.distanceToLine(e,i,{x:a,y:o})<=r)return!0}return!1}},gu=[0,.25,.333,.5,.667,.75,1],_u=class extends G{descriptor={type:`gannBox`,name:`Gann Box`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x),s=Math.max(i.x,a.x),c=Math.min(i.y,a.y),l=Math.max(i.y,a.y),u=s-o,d=l-c;if(!(u<2||d<2)){this.applyLineStyle(e,t.style),e.strokeRect(o,c,u,d),e.save(),e.globalAlpha=.35;for(let t of gu){if(t===0||t===1)continue;let n=c+d*t;e.beginPath(),e.moveTo(o,n),e.lineTo(s,n),e.stroke()}for(let t of gu){if(t===0||t===1)continue;let n=o+u*t;e.beginPath(),e.moveTo(n,c),e.lineTo(n,l),e.stroke()}e.globalAlpha=.5,e.setLineDash([4,3]),e.beginPath(),e.moveTo(o,c),e.lineTo(s,l),e.stroke(),e.beginPath(),e.moveTo(s,c),e.lineTo(o,l),e.stroke(),e.restore(),this.resetLineStyle(e),e.fillStyle=t.style.color,e.font=W(8),e.globalAlpha=.6,e.textBaseline=`bottom`,e.textAlign=`right`;for(let t of gu){if(t===0||t===1)continue;let n=c+d*t;e.fillText(`${(t*100).toFixed(0)}%`,o-3,n)}e.globalAlpha=1,r&&this.renderAnchorHandles(e,t,n)}}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x),s=Math.max(i.x,a.x),c=Math.min(i.y,a.y),l=Math.max(i.y,a.y);return Math.abs(e.x-o)<=r&&e.y>=c-r&&e.y<=l+r||Math.abs(e.x-s)<=r&&e.y>=c-r&&e.y<=l+r||Math.abs(e.y-c)<=r&&e.x>=o-r&&e.x<=s+r||Math.abs(e.y-l)<=r&&e.x>=o-r&&e.x<=s+r||this.distanceToLine(e,{x:o,y:c},{x:s,y:l})<=r||this.distanceToLine(e,{x:s,y:c},{x:o,y:l})<=r}},vu=class extends G{descriptor={type:`anchoredVWAP`,name:`Anchored VWAP`,requiredAnchors:1};dataGetter=null;showBands=!0;setDataGetter(e){this.dataGetter=e}setShowBands(e){this.showBands=e}render(t,n,r,i){if(n.anchors.length<1||!this.dataGetter)return;let a=this.dataGetter(),o=Math.max(0,Math.round(e.D(n.anchors[0].time,r)));if(o>=a.length)return;let{vwap:s,upper1:c,lower1:l,upper2:u,lower2:d}=this.computeVWAP(a,o),{chartRect:f}=r,p=r.barWidth+r.barSpacing;if(this.applyLineStyle(t,n.style),t.lineWidth=n.style.lineWidth+.5,this.drawLine(t,s,o,r,f,p),this.showBands&&s.length>1&&(t.globalAlpha=.4,t.lineWidth=Math.max(.5,n.style.lineWidth*.6),t.setLineDash([4,3]),this.drawLine(t,c,o,r,f,p),this.drawLine(t,l,o,r,f,p),t.globalAlpha=.25,this.drawLine(t,u,o,r,f,p),this.drawLine(t,d,o,r,f,p),t.globalAlpha=1),this.resetLineStyle(t),s.length>0){let i=s[s.length-1],a=e.b(o+s.length-1,r),c=e.T(i,r);a>=f.x&&a<=f.x+f.width&&(t.fillStyle=n.style.color,t.font=W(9,`bold`),t.textAlign=`left`,t.textBaseline=`middle`,t.fillText(`AVWAP ${bc(i,i,r)}`,a+6,c))}i&&this.renderAnchorHandles(t,n,r)}drawLine(t,n,r,i,a,o){t.beginPath();let s=!1;for(let c=0;c<n.length;c++){let l=e.b(r+c,i);if(l<a.x-o)continue;if(l>a.x+a.width+o)break;let u=e.T(n[c],i);s?t.lineTo(l,u):(t.moveTo(l,u),s=!0)}t.stroke()}vwapCache=null;computeVWAP(e,t){let n=e[e.length-1],r=this.vwapCache;if(r&&r.data===e&&r.length===e.length&&r.startIdx===t&&r.lastClose===n?.close&&r.lastVolume===(n?.volume??0))return r.result;let i=this.computeVWAPUncached(e,t);return this.vwapCache={data:e,length:e.length,startIdx:t,lastClose:n?.close,lastVolume:n?.volume??0,result:i},i}computeVWAPUncached(e,t){let n=e.length-t,r=Array(n),i=Array(n),a=Array(n),o=Array(n),s=Array(n),c=0,l=0,u=0;for(let d=0;d<n;d++){let n=e[t+d],f=(n.high+n.low+n.close)/3,p=n.volume??1;c+=f*p,l+=p,u+=f*f*p;let m=l>0?c/l:f;r[d]=m;let h=l>0?u/l-m*m:0,g=Math.sqrt(Math.max(0,h));i[d]=m+g,a[d]=m-g,o[d]=m+2*g,s[d]=m-2*g}return{vwap:r,upper1:i,lower1:a,upper2:o,lower2:s}}hitTest(t,n,r,i){if(n.anchors.length<1||!this.dataGetter)return!1;let a=this.dataGetter(),o=Math.max(0,Math.round(e.D(n.anchors[0].time,r)));if(o>=a.length)return!1;let{vwap:s}=this.computeVWAP(a,o);for(let n=1;n<s.length;n++){let a=e.b(o+n-1,r),c=e.T(s[n-1],r),l=e.b(o+n,r),u=e.T(s[n],r);if(this.distanceToLine(t,{x:a,y:c},{x:l,y:u})<=i)return!0}return!1}},yu=class extends G{descriptor={type:`volumeProfileRange`,name:`Volume Profile (Range)`,requiredAnchors:2,fill:!0};dataGetter=null;numBins=40;setDataGetter(e){this.dataGetter=e}render(t,n,r,i){if(n.anchors.length<2||!this.dataGetter)return;let a=this.dataGetter(),o=Math.round(e.D(n.anchors[0].time,r)),s=Math.round(e.D(n.anchors[1].time,r)),c=Math.max(0,Math.min(o,s)),l=Math.min(a.length-1,Math.max(o,s));if(c>=a.length||l<0||c>l)return;let u=1/0,d=-1/0;for(let e=c;e<=l;e++)a[e].low<u&&(u=a[e].low),a[e].high>d&&(d=a[e].high);if(u>=d)return;let f=(d-u)/this.numBins,p=new Float64Array(this.numBins),m=0;for(let e=c;e<=l;e++){let t=a[e],n=t.volume??1,r=Math.max(0,Math.floor((t.low-u)/f)),i=Math.min(this.numBins-1,Math.floor((t.high-u)/f)),o=n/(i-r+1);for(let e=r;e<=i;e++)p[e]+=o,p[e]>m&&(m=p[e])}if(m===0)return;let h=0;for(let e=1;e<this.numBins;e++)p[e]>p[h]&&(h=e);let g=e.b(l,r)+r.barWidth,_=n.style.color,v=n.style.fillColor??`#f2a93b`;t.save();for(let n=0;n<this.numBins;n++){let i=p[n]/m*100,a=u+(n+1)*f,o=u+n*f,s=e.T(a,r),c=e.T(o,r),l=Math.abs(c-s);t.globalAlpha=.35,t.fillStyle=n===h?v:_,t.fillRect(g,Math.min(s,c),i,Math.max(1,l-.5))}let y=u+(h+.5)*f,b=e.T(y,r);t.globalAlpha=.7,t.strokeStyle=v,t.lineWidth=1,t.setLineDash([4,3]),t.beginPath();let x=e.b(c,r)-r.barWidth/2;t.moveTo(x,b),t.lineTo(g+100,b),t.stroke(),t.fillStyle=v,t.font=W(9),t.textAlign=`left`,t.textBaseline=`bottom`,t.globalAlpha=.8,t.fillText(`POC ${bc(y,y,r)}`,g+100+4,b-2),t.restore(),i&&this.renderAnchorHandles(t,n,r)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x)-r,s=Math.max(i.x,a.x)+100+r,c=Math.min(i.y,a.y)-r,l=Math.max(i.y,a.y)+r;return e.x>=o&&e.x<=s&&e.y>=c&&e.y<=l}},bu=[1,2,3,5,8,13,21,34,55],xu=class extends G{descriptor={type:`fibTimeZones`,name:`Fibonacci Time Zones`,requiredAnchors:2,options:{levels:{kind:`levels`,label:`Levels`,default:ml(bu,[0,89,144])}}};render(t,n,r,i){if(n.anchors.length<2)return;let a=n.anchors[0],o=n.anchors[1].time-a.time;if(o===0)return;let{chartRect:s}=r;t.font=W(11),t.textBaseline=`top`,t.textAlign=`center`;for(let{value:i,color:c}of this.visibleLevels(n)){this.applyLineStyle(t,{...n.style,color:c??n.style.color});let l=e.O(a.time+o*i,r);l<s.x||l>s.x+s.width||(t.globalAlpha=i===1?1:.55,t.beginPath(),t.moveTo(l,s.y),t.lineTo(l,s.y+s.height),t.stroke(),t.fillStyle=c??n.style.color,cc(t,String(i),l,s.y+2))}t.globalAlpha=1,this.resetLineStyle(t),i&&this.renderAnchorHandles(t,n,r)}hitTest(t,n,r,i){if(n.anchors.length<2)return!1;let a=n.anchors[0],o=n.anchors[1].time-a.time;if(o===0)return!1;let{chartRect:s}=r;if(t.y<s.y||t.y>s.y+s.height)return!1;for(let{value:s}of this.visibleLevels(n)){let n=e.O(a.time+o*s,r);if(Math.abs(t.x-n)<=i)return!0}return!1}},Su=40,Cu=2,wu=.1,Tu=100,Eu=0x38d7ea4c68000,Du=class extends G{descriptor={type:`riskReward`,name:`Long/Short Position`,requiredAnchors:2,options:{rewardRatio:{kind:`number`,label:`Reward:risk`,default:2,min:wu,max:Tu,step:.1},accountSize:{kind:`number`,label:`Account size`,default:1e3,min:0,max:Eu},riskMode:{kind:`choice`,label:`Risk as`,default:`percent`,choices:[{value:`percent`,label:`Percent of account`},{value:`amount`,label:`Amount`}]},risk:{kind:`number`,label:`Risk`,default:1,min:0,max:Eu},qtyDecimals:{kind:`number`,label:`Quantity decimals`,default:2,min:0,max:8,step:1},showLabels:{kind:`boolean`,label:`Show labels`,default:!0}}};geometry(e){let t=e.anchors[0].price,n=e.anchors[1].price,r=this.option(e,`rewardRatio`),i=Math.abs(t-n),a=n<t,o=a?t+i*r:t-i*r,s=this.option(e,`risk`),c=this.option(e,`riskMode`)===`amount`?s:this.option(e,`accountSize`)*s/100,l=i>0?c/i:0;return{entry:t,stop:n,target:o,ratio:r,isLong:a,qty:l,riskAmount:c,rewardAmount:l*i*r}}span(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t);return{x:Math.min(n.x,r.x),width:Math.max(Math.abs(r.x-n.x),Su),stopX:r.x}}handles(e,t){let{target:n}=this.geometry(e),r=this.anchorToPixel(e.anchors[0],t),i=this.anchorToPixel(e.anchors[1],t),a=this.anchorToPixel({time:e.anchors[1].time,price:n},t).y;return[r,i,{x:i.x,y:a}]}render(e,n,r,i){if(n.anchors.length<2)return;let a=this.geometry(n),{x:o,width:s}=this.span(n,r),[c,l,u]=this.handles(n,r);e.fillStyle=`rgba(232, 80, 91, 0.18)`,e.fillRect(o,Math.min(c.y,l.y),s,Math.abs(l.y-c.y)),e.fillStyle=`rgba(31, 168, 116, 0.18)`,e.fillRect(o,Math.min(c.y,u.y),s,Math.abs(u.y-c.y)),e.strokeStyle=n.style.color,e.lineWidth=1,e.setLineDash([]),e.beginPath(),e.moveTo(o,c.y),e.lineTo(o+s,c.y),e.stroke();let{chartRect:d}=r,f=d.x,p=d.x+d.width;if(this.option(n,`showLabels`)&&o+s>=f&&o<=p){let i=(0,t.autoPricePrecision)(Math.min(a.stop,a.target),Math.max(a.stop,a.target)),s=this.option(n,`qtyDecimals`),m=e=>(a.entry===0?0:(e-a.entry)/a.entry*100).toFixed(2),h=Number(a.ratio.toFixed(2));e.font=W(11);let g=e=>r.formatPrice?.(e)??e.toFixed(i),_=e=>`${e>=a.entry?`+`:`−`}${Math.abs(Number(m(e))).toFixed(2)}%`,v=e=>{let t=e<c.y,n=e+(t?-1:1)*11,r=t?Math.min(n,c.y-20):Math.max(n,c.y+20);return Math.min(Math.max(r,d.y+9),d.y+d.height-9)},y=(t,n,r)=>{uc(e,t,Math.max(f+4,Math.min(o+4,p-4-lc(e,t))),n,r)};y(`${a.isLong?`Long`:`Short`} · Qty ${a.qty.toFixed(s)} · R:R ${h}`,c.y,n.style.color),Math.abs(l.y-c.y)>=1&&(y(`Target ${g(a.target)} (${_(a.target)}) · ${a.rewardAmount.toFixed(2)}`,v(u.y),`#1fa874`),y(`Stop ${g(a.stop)} (${_(a.stop)}) · ${a.riskAmount.toFixed(2)}`,v(l.y),`#e8505b`))}i&&this.renderHandles(e,n,r)}renderHandles(e,t,n){e.fillStyle=`#FFFFFF`,e.strokeStyle=t.style.color,e.lineWidth=1;for(let r of this.handles(t,n))e.fillRect(r.x-4,r.y-4,8,8),e.strokeRect(r.x-4,r.y-4,8,8)}hitTestAnchor(e,t,n,r){return t.anchors.length<2?super.hitTestAnchor(e,t,n,r):this.handles(t,n).findIndex(t=>Math.hypot(e.x-t.x,e.y-t.y)<=r)}moveHandle(e,t,n){if(t!==Cu){let r=e.anchors.map((e,r)=>r===t?{...n}:{...e});return{...e,anchors:r}}let{entry:r,isLong:i}=this.geometry(e),a=Math.abs(r-e.anchors[1].price),o=i?n.price-r:r-n.price,s=a>0?Math.min(Tu,Math.max(wu,o/a)):wu;return{...e,options:{...e.options,rewardRatio:Math.round(s*100)/100}}}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let{x:i,width:a}=this.span(t,n),o=this.handles(t,n).map(e=>e.y);return e.x>=i-r&&e.x<=i+a+r&&e.y>=Math.min(...o)-r&&e.y<=Math.max(...o)+r}},Ou=class extends G{descriptor={type:`crossLine`,name:`Cross Line`,requiredAnchors:1};render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),{chartRect:a}=n;this.applyLineStyle(e,t.style);let o=e.lineWidth;this.strokeHorizontal(e,a.x,a.x+a.width,i.y),e.lineWidth=o,this.strokeVertical(e,i.x,a.y,a.y+a.height),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n);return Math.abs(e.y-i.y)<=r||Math.abs(e.x-i.x)<=r}};function ku(e,t,n){let r=Tc(e,0,1,t),i=wc(e,0,1,t);return[xc(e.anchors[0].price,e.anchors[1].price,t),r?`${i} bars, ${r}`:`${i} bars`,`${n.toFixed(1)}°`]}var Au=class extends G{descriptor={type:`infoLine`,name:`Info Line`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),this.resetLineStyle(e);let o=ku(t,n,yl(i,a)),s=a.y<=i.y;Ec(e,o,a.x+(a.x>=i.x?8:-8),a.y+(s?-6:6),a.x>=i.x?`left`:`right`,s),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);return this.distanceToLine(e,i,a)<=r}},ju=[0,.236,.382,.5,.618,.786,1,1.618];function Mu(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=r*r+i*i;if(a===0)return{x:n.x-e.x,y:n.y-e.y};let o=((n.x-e.x)*r+(n.y-e.y)*i)/a;return{x:n.x-(e.x+o*r),y:n.y-(e.y+o*i)}}function Nu(e,t,n,r){let i=Mu(e,t,n);return[{x:e.x+i.x*r,y:e.y+i.y*r},{x:t.x+i.x*r,y:t.y+i.y*r}]}var Pu=class extends G{descriptor={type:`fibChannel`,name:`Fibonacci Channel`,requiredAnchors:3,options:{levels:{kind:`levels`,label:`Levels`,default:pl(ju,[2.618,3.618,4.236])}}};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);if(t.anchors.length<3){this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),this.resetLineStyle(e);return}let o=this.anchorToPixel(t.anchors[2],n);e.font=W(11),e.textAlign=`right`,e.textBaseline=`middle`;for(let{value:n,color:r}of this.visibleLevels(t)){let[s,c]=Nu(i,a,o,n);this.applyLineStyle(e,{...t.style,color:r??t.style.color}),e.globalAlpha=n===0||n===1?1:.6,e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(c.x,c.y),e.stroke(),e.fillStyle=r??t.style.color;let l=s.x<=c.x?s:c;cc(e,String(n),l.x-4,l.y)}e.globalAlpha=1,this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<3)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=this.anchorToPixel(t.anchors[2],n);for(let{value:n}of this.visibleLevels(t)){let[t,s]=Nu(i,a,o,n);if(this.distanceToLine(e,t,s)<=r)return!0}return!1}},Fu=[.25,.382,.5,.618,.75];function Iu(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=Math.hypot(r,i);if(a===0)return null;let o=(n.chartRect.width+n.chartRect.height)*2;return{x:e.x+r/a*o,y:e.y+i/a*o}}function Lu(e,t,n=Fu){let r=[{level:1,kind:`diagonal`,point:t}];for(let i of n)r.push({level:i,kind:`price`,point:{x:t.x,y:e.y+(t.y-e.y)*i}}),r.push({level:i,kind:`time`,point:{x:e.x+(t.x-e.x)*i,y:t.y}});return r}var Ru=class extends G{descriptor={type:`fibSpeedResistanceFan`,name:`Fib Speed Resistance Fan`,requiredAnchors:2,options:{levels:{kind:`levels`,label:`Levels`,default:pl(Fu,[.236,.786])}}};targets(e,t,n){return Lu(t,n,this.visibleLevels(e).map(e=>e.value))}render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);e.strokeStyle=t.style.color,e.lineWidth=1,e.globalAlpha=.25,e.strokeRect(Math.min(i.x,a.x),Math.min(i.y,a.y),Math.abs(a.x-i.x),Math.abs(a.y-i.y)),e.globalAlpha=1,e.font=W(11),e.textBaseline=`middle`;for(let r of this.targets(t,i,a)){let o=Iu(i,r.point,n);o&&(this.applyLineStyle(e,t.style),e.globalAlpha=r.kind===`diagonal`?1:.65,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(o.x,o.y),e.stroke(),r.kind===`price`&&(e.fillStyle=t.style.color,e.textAlign=a.x>=i.x?`left`:`right`,cc(e,String(r.level),r.point.x+(a.x>=i.x?4:-4),r.point.y)))}e.globalAlpha=1,this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);for(let o of this.targets(t,i,a)){let t=Iu(i,o.point,n);if(t&&this.distanceToLine(e,i,t)<=r)return!0}return!1}},zu=class extends G{ratioLinks=[];triangles=[];render(e,t,n,r){if(t.anchors.length<2)return;let i=t.anchors.map(e=>this.anchorToPixel(e,n));t.anchors.length>=this.descriptor.requiredAnchors&&this.renderTriangles(e,t,i),this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i[0].x,i[0].y);for(let t=1;t<i.length;t++)e.lineTo(i[t].x,i[t].y);e.stroke(),this.resetLineStyle(e),this.renderRatioLinks(e,t,i),this.renderPointLabels(e,t,i),this.renderExtras(e,t,i,n),r&&this.renderAnchorHandles(e,t,n)}renderExtras(e,t,n,r){}renderTriangles(e,t,n){e.fillStyle=t.style.fillColor??t.style.color,e.globalAlpha=t.style.fillColor?1:.12;for(let[t,r,i]of this.triangles)e.beginPath(),e.moveTo(n[t].x,n[t].y),e.lineTo(n[r].x,n[r].y),e.lineTo(n[i].x,n[i].y),e.closePath(),e.fill();e.globalAlpha=1}renderRatioLinks(e,t,n){e.font=W(11),e.textAlign=`center`,e.textBaseline=`middle`;for(let r of this.ratioLinks){if(Math.max(r.from,r.to,...r.num,...r.den)>=n.length)continue;let i=n[r.from],a=n[r.to];e.strokeStyle=t.style.color,e.lineWidth=1,e.globalAlpha=.7,e.setLineDash([4,4]),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),e.setLineDash([]),e.globalAlpha=1,e.fillStyle=t.style.color,cc(e,Dc(t,r.num,r.den),(i.x+a.x)/2,(i.y+a.y)/2)}}renderPointLabels(e,t,n){e.font=W(12,`bold`),e.fillStyle=t.style.color,e.textAlign=`center`;for(let t=0;t<n.length&&t<this.pointLabels.length;t++){let r=n[t-1]??n[t+1],i=n[t+1]??n[t-1],a=!r||!i?!0:n[t].y<=Math.min(r.y,i.y);e.textBaseline=a?`bottom`:`top`,cc(e,this.pointLabels[t],n[t].x,n[t].y+(a?-6:6))}}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=t.anchors.map(e=>this.anchorToPixel(e,n));for(let t=0;t<i.length-1;t++)if(this.distanceToLine(e,i[t],i[t+1])<=r)return!0;return!1}},Bu=class extends zu{descriptor={type:`xabcdPattern`,name:`XABCD Pattern`,requiredAnchors:5,fill:!0};pointLabels=[`X`,`A`,`B`,`C`,`D`];ratioLinks=[{from:0,to:2,num:[1,2],den:[0,1]},{from:1,to:3,num:[2,3],den:[1,2]},{from:2,to:4,num:[3,4],den:[2,3]},{from:0,to:4,num:[1,4],den:[0,1]}];triangles=[[0,1,2],[2,3,4]]},Vu=class extends zu{descriptor={type:`abcdPattern`,name:`ABCD Pattern`,requiredAnchors:4,fill:!0};pointLabels=[`A`,`B`,`C`,`D`];ratioLinks=[{from:0,to:2,num:[1,2],den:[0,1]},{from:1,to:3,num:[2,3],den:[1,2]}]},Hu=class extends zu{descriptor={type:`headAndShoulders`,name:`Head and Shoulders`,requiredAnchors:7,fill:!0};pointLabels=[``,`Left Shoulder`,``,`Head`,``,`Right Shoulder`,``];triangles=[[0,1,2],[2,3,4],[4,5,6]];renderExtras(e,t,n){if(n.length<5)return;let r=n[2],i=n[4],a=n[0],o=n[n.length-1],s=i.x===r.x?0:(i.y-r.y)/(i.x-r.x),c=e=>r.y+s*(e-r.x);e.strokeStyle=t.style.color,e.lineWidth=Math.max(1,t.style.lineWidth),e.setLineDash([6,4]),e.beginPath(),e.moveTo(a.x,c(a.x)),e.lineTo(o.x,c(o.x)),e.stroke(),e.setLineDash([])}},Uu=class extends zu{descriptor={type:`threeDrives`,name:`Three Drives Pattern`,requiredAnchors:6};pointLabels=[``,`1`,`A`,`2`,`B`,`3`];ratioLinks=[{from:1,to:3,num:[2,3],den:[1,2]},{from:3,to:5,num:[4,5],den:[3,4]}]},Wu=class extends zu{descriptor={type:`cypherPattern`,name:`Cypher Pattern`,requiredAnchors:5,fill:!0};pointLabels=[`X`,`A`,`B`,`C`,`D`];ratioLinks=[{from:0,to:2,num:[1,2],den:[0,1]},{from:0,to:3,num:[2,3],den:[0,1]},{from:0,to:4,num:[3,4],den:[0,3]}];triangles=[[0,1,2],[2,3,4]]},Gu=class extends G{descriptor={type:`circle`,name:`Circle`,requiredAnchors:2,fill:!0};geometry(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t);return{c:n,r:Math.hypot(r.x-n.x,r.y-n.y)}}render(e,t,n,r){if(t.anchors.length<2)return;let{c:i,r:a}=this.geometry(t,n);e.beginPath(),e.arc(i.x,i.y,a,0,Math.PI*2),t.style.fillColor&&(e.fillStyle=t.style.fillColor,e.fill()),this.applyLineStyle(e,t.style),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let{c:i,r:a}=this.geometry(t,n),o=Math.hypot(e.x-i.x,e.y-i.y);return t.style.fillColor?o<=a+r:Math.abs(o-a)<=r}},Ku=`rgba(76, 141, 255, 0.12)`,qu=`rgba(232, 80, 91, 0.12)`;function Ju(t,n){let r=n.data;if(!r||r.length===0)return null;let i=Math.round(e.D(t.anchors[0].time,n)),a=Math.round(e.D(t.anchors[1].time,n)),o=Math.max(0,Math.min(i,a)),s=Math.min(r.length-1,Math.max(i,a)),c=0;for(let e=o;e<=s;e++)c+=r[e].volume??0;return c}function Yu(e){return e>=1e9?`${(e/1e9).toFixed(2)}B`:e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(2)}K`:e.toFixed(0)}function Xu(e,t){let n=Tc(e,0,1,t),r=wc(e,0,1,t),i=[xc(e.anchors[0].price,e.anchors[1].price,t),n?`${r} bars, ${n}`:`${r} bars`],a=Ju(e,t);return a!==null&&i.push(`Vol ${Yu(a)}`),i}var Zu=class extends G{descriptor={type:`dateAndPriceRange`,name:`Date and Price Range`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Math.min(i.x,a.x),s=Math.min(i.y,a.y),c=Math.abs(a.x-i.x),l=Math.abs(a.y-i.y),u=t.anchors[1].price>=t.anchors[0].price;e.fillStyle=u?Ku:qu,e.fillRect(o,s,c,l),this.applyLineStyle(e,t.style);let d=o+c/2,f=s+l/2;e.beginPath(),e.moveTo(d,i.y),e.lineTo(d,a.y),e.moveTo(i.x,f),e.lineTo(a.x,f),e.stroke(),this.resetLineStyle(e),Ec(e,Xu(t,n),d,u?s-6:s+l+6,`center`,u),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);return e.x>=Math.min(i.x,a.x)-r&&e.x<=Math.max(i.x,a.x)+r&&e.y>=Math.min(i.y,a.y)-r&&e.y<=Math.max(i.y,a.y)+r}},Qu=400,$u=2;function ed(e,t,n){let r=Math.abs(t.x-e.x);if(r<$u)return[e.x];let i=n.chartRect.x+n.chartRect.width,a=[],o=Math.min(e.x,t.x);for(let e=o;e<=i&&a.length<Qu;e+=r)a.push(e);return a}var td=class extends G{descriptor={type:`cyclicLines`,name:`Cyclic Lines`,requiredAnchors:2};render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),{chartRect:o}=n;this.applyLineStyle(e,t.style),e.beginPath();for(let t of ed(i,a,n))t<o.x||(e.moveTo(t,o.y),e.lineTo(t,o.y+o.height));e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:ed(this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n),n).some(t=>Math.abs(e.x-t)<=r)}},nd=14,rd=18,id=6,ad=20,od=class extends G{descriptor={type:`priceLabel`,name:`Price Label`,requiredAnchors:1,text:!0};text(e,t){return e.style.text||bc(e.anchors[0].price,e.anchors[0].price,t)}box(e,t,n,r){let i=t.style.fontSize??12,a=this.text(t,r),o=e?e.measureText(a).width:a.length*i*.6;return{x:n.x+nd,y:n.y-rd-ad/2,w:o+id*2,h:ad}}render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n);e.font=`${t.style.fontSize??12}px ${sc()}`;let a=this.box(e,t,i,n);e.strokeStyle=t.style.color,e.lineWidth=1,e.setLineDash([]),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y+a.h),e.stroke(),e.fillStyle=t.style.color,e.fillRect(a.x,a.y,a.w,a.h),e.fillStyle=`#FFFFFF`,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(this.text(t,n),a.x+id,a.y+a.h/2),e.beginPath(),e.arc(i.x,i.y,3,0,Math.PI*2),e.fillStyle=t.style.color,e.fill(),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n);if(Math.hypot(e.x-i.x,e.y-i.y)<=r)return!0;let a=this.box(null,t,i,n);return e.x>=a.x-r&&e.x<=a.x+a.w+r&&e.y>=a.y-r&&e.y<=a.y+a.h+r}},sd=8,cd=6,ld=1.3,ud=12;function dd(e){return`${e}px ${sc()}`}function fd(e,t,n){let r=[];for(let i of t.split(`
2
+ `)){let t=``;for(let a of i.split(/\s+/).filter(Boolean)){let i=t?`${t} ${a}`:a;if(e(i)<=n){t=i;continue}t&&r.push(t),t=e(a)<=n?a:pd(e,a,n)}if(r.push(t),r.length>=ud)break}return r.length>ud&&(r.length=ud),r}function pd(e,t,n){if(e(t)<=n)return t;let r=1,i=t.length-1;for(;r<i;){let a=Math.ceil((r+i)/2);e(`${t.slice(0,a)}…`)<=n?r=a:i=a-1}return`${t.slice(0,r)}…`}var md=200,hd=new Map;function gd(e,t,n,r){let i=`${r}|${n}|${t}`,a=hd.get(i);if(a)return a;hd.size>=md&&hd.clear();let o=fd(e,t,n);return hd.set(i,o),o}function _d(e,t,n,r,i){return{x:n,y:r,width:Math.max(0,...t.map(e))+sd*2,height:t.length*i*ld+cd*2}}function vd(e,t,n,r,i){e.font=dd(i.fontSize);let a=t=>e.measureText(t).width,o=gd(a,t,i.maxWidth,i.fontSize),s=_d(a,o,n,r,i.fontSize);return i.fill&&(e.fillStyle=i.fill,e.fillRect(s.x,s.y,s.width,s.height)),i.stroke&&(e.strokeStyle=i.stroke,e.lineWidth=1,e.strokeRect(s.x+.5,s.y+.5,s.width-1,s.height-1)),e.fillStyle=i.color,e.textAlign=`left`,e.textBaseline=`top`,o.forEach((t,a)=>e.fillText(t,n+sd,r+cd+a*i.fontSize*ld)),s}function yd(e,t,n=0){return e.x>=t.x-n&&e.x<=t.x+t.width+n&&e.y>=t.y-n&&e.y<=t.y+t.height+n}var bd=1e3,xd=class{boxes=new Map;set(e,t){this.boxes.size>=bd&&!this.boxes.has(e)&&this.boxes.clear(),this.boxes.set(e,t)}get(e){return this.boxes.get(e)}},Sd=240,Cd=13;function wd(e){return e.style.fontSize||Cd}function Td(e){return{fontSize:wd(e),color:e.style.color,fill:e.style.fillColor??`rgba(76, 141, 255, 0.1)`,stroke:e.style.color,maxWidth:Sd}}function Ed(e,t,n,r){let i=wd(e),a=Math.max(...t.split(`
3
+ `).map(e=>e.length));return{x:n,y:r,width:Math.min(Sd,a*i*.6)+16,height:i*1.3+12}}var Dd=7,Od=16,kd=class extends G{descriptor={type:`note`,name:`Note`,requiredAnchors:1,text:!0,fill:!0,options:{showText:{kind:`boolean`,label:`Show text`,default:!0}}};boxes=new xd;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n);if(this.renderPin(e,t,i),this.option(t,`showText`)){let n=vd(e,du(t,`Note`),i.x+Dd+6,i.y-Od-Dd,Td(t));this.boxes.set(t.id,n)}r&&this.renderAnchorHandles(e,t,n)}renderPin(e,t,n){let r=n.y-Od;e.fillStyle=t.style.color,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-Dd*.7,r+Dd*.5),e.arc(n.x,r,Dd,Math.PI*.8,Math.PI*.2),e.closePath(),e.fill(),e.fillStyle=`#ffffff`,e.beginPath(),e.arc(n.x,r,Dd*.4,0,Math.PI*2),e.fill()}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n);return yd(e,{x:i.x-Dd,y:i.y-Od-Dd,width:Dd*2,height:Od+Dd},r)?!0:this.option(t,`showText`)?yd(e,this.boxes.get(t.id)??Ed(t,du(t,`Note`),i.x+Dd+6,i.y-Od-Dd),r):!1}},Ad=class extends G{descriptor={type:`callout`,name:`Callout`,requiredAnchors:2,text:!0,fill:!0};boxes=new xd;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n);if(e.fillStyle=t.style.color,e.beginPath(),e.arc(i.x,i.y,3,0,Math.PI*2),e.fill(),t.anchors.length<2)return;let a=this.anchorToPixel(t.anchors[1],n),o=vd(e,du(t,`Callout`),a.x,a.y,Td(t));this.boxes.set(t.id,o);let s=jd(o,i);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(i.x,i.y),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=this.boxes.get(t.id)??Ed(t,du(t,`Callout`),a.x,a.y);return yd(e,o,r)||this.distanceToLine(e,jd(o,i),i)<=r}};function jd(e,t){let n=e.x+e.width/2,r=e.y+e.height/2,i=t.x-n,a=t.y-r;return Math.abs(i)*e.height>Math.abs(a)*e.width?{x:i>0?e.x+e.width:e.x,y:r}:{x:n,y:a>0?e.y+e.height:e.y}}var Md=24,Nd=18,Pd=10,Fd=class extends G{descriptor={type:`flag`,name:`Flag Mark`,requiredAnchors:1};render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=i.y-Md;e.strokeStyle=t.style.color,e.lineWidth=1.5,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x,a),e.stroke(),e.fillStyle=t.style.color,e.beginPath(),e.moveTo(i.x,a),e.lineTo(i.x+Nd,a),e.lineTo(i.x+Nd-5,a+Pd/2),e.lineTo(i.x+Nd,a+Pd),e.lineTo(i.x,a+Pd),e.closePath(),e.fill(),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n);return yd(e,{x:i.x,y:i.y-Md,width:Nd,height:Md},r)}},Id={up:{x:0,y:-1},down:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0}};function Ld(e,t,n){let r=n*.5,i=n*.4,a=n*.17,o=(n,r)=>({x:e.x-t.x*n-t.y*r,y:e.y-t.y*n+t.x*r});return[o(0,0),o(r,i),o(r,a),o(n,a),o(n,-a),o(r,-a),o(r,-i)]}var Rd=class extends G{descriptor={type:`arrowMark`,name:`Arrow Mark`,requiredAnchors:1,text:!0,options:{direction:{kind:`choice`,label:`Direction`,default:`up`,choices:[{value:`up`,label:`Up`},{value:`down`,label:`Down`},{value:`left`,label:`Left`},{value:`right`,label:`Right`}]},size:{kind:`number`,label:`Size`,default:22,min:10,max:80,step:2}}};outline(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=Id[this.option(e,`direction`)]??Id.up,i=this.option(e,`size`);return{points:Ld(n,r,i),dir:r,tail:{x:n.x-r.x*i,y:n.y-r.y*i}}}render(e,t,n,r){if(t.anchors.length<1)return;let{points:i,dir:a,tail:o}=this.outline(t,n);e.fillStyle=t.style.color,e.beginPath(),i.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.closePath(),e.fill();let s=t.style.text;s&&(e.font=`${t.style.fontSize||12}px ${sc()}`,e.textAlign=a.x===0?`center`:a.x>0?`right`:`left`,e.textBaseline=a.y===0?`middle`:a.y<0?`top`:`bottom`,e.fillText(s,o.x-a.x*4,o.y-a.y*4)),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let{points:i}=this.outline(t,n),a=i.map(e=>e.x),o=i.map(e=>e.y);return yd(e,{x:Math.min(...a),y:Math.min(...o),width:Math.max(...a)-Math.min(...a),height:Math.max(...o)-Math.min(...o)},r)}},zd=[`star`,`heart`,`check`,`cross`,`circle`,`triangleUp`,`triangleDown`,`bolt`];function Bd(e,t,n,r){let i=r/2;switch(e.beginPath(),t){case`star`:for(let t=0;t<10;t++){let r=-Math.PI/2+t*Math.PI/5,a=t%2==0?i:i*.42,o=n.x+Math.cos(r)*a,s=n.y+Math.sin(r)*a;t===0?e.moveTo(o,s):e.lineTo(o,s)}return e.closePath(),!1;case`heart`:return e.moveTo(n.x,n.y+i*.85),e.bezierCurveTo(n.x-i*1.3,n.y-i*.1,n.x-i*.6,n.y-i*1.1,n.x,n.y-i*.35),e.bezierCurveTo(n.x+i*.6,n.y-i*1.1,n.x+i*1.3,n.y-i*.1,n.x,n.y+i*.85),e.closePath(),!1;case`check`:return e.moveTo(n.x-i*.8,n.y),e.lineTo(n.x-i*.2,n.y+i*.6),e.lineTo(n.x+i*.85,n.y-i*.65),!0;case`cross`:return e.moveTo(n.x-i*.7,n.y-i*.7),e.lineTo(n.x+i*.7,n.y+i*.7),e.moveTo(n.x+i*.7,n.y-i*.7),e.lineTo(n.x-i*.7,n.y+i*.7),!0;case`circle`:return e.arc(n.x,n.y,i*.8,0,Math.PI*2),!1;case`triangleUp`:return e.moveTo(n.x,n.y-i*.85),e.lineTo(n.x+i*.9,n.y+i*.7),e.lineTo(n.x-i*.9,n.y+i*.7),e.closePath(),!1;case`triangleDown`:return e.moveTo(n.x,n.y+i*.85),e.lineTo(n.x+i*.9,n.y-i*.7),e.lineTo(n.x-i*.9,n.y-i*.7),e.closePath(),!1;case`bolt`:return e.moveTo(n.x+i*.15,n.y-i),e.lineTo(n.x-i*.6,n.y+i*.1),e.lineTo(n.x-i*.05,n.y+i*.1),e.lineTo(n.x-i*.15,n.y+i),e.lineTo(n.x+i*.6,n.y-i*.1),e.lineTo(n.x+i*.05,n.y-i*.1),e.closePath(),!1}}var Vd=class extends G{descriptor={type:`icon`,name:`Icon`,requiredAnchors:1,options:{glyph:{kind:`choice`,label:`Icon`,default:`star`,choices:[{value:`star`,label:`Star`},{value:`heart`,label:`Heart`},{value:`check`,label:`Check`},{value:`cross`,label:`Cross`},{value:`circle`,label:`Circle`},{value:`triangleUp`,label:`Triangle up`},{value:`triangleDown`,label:`Triangle down`},{value:`bolt`,label:`Bolt`}]},size:{kind:`number`,label:`Size`,default:22,min:10,max:80,step:2}}};render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.option(t,`size`),o=this.option(t,`glyph`);Bd(e,zd.includes(o)?o:`star`,i,a)?(e.strokeStyle=t.style.color,e.lineWidth=Math.max(2,a/8),e.lineCap=`round`,e.lineJoin=`round`,e.stroke(),e.lineCap=`butt`,e.lineJoin=`miter`):(e.fillStyle=t.style.color,e.fill()),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n),a=this.option(t,`size`)/2;return Math.abs(e.x-i.x)<=a+r&&Math.abs(e.y-i.y)<=a+r}},Hd=48,Ud=10;function Wd(e,t){if(e.beginPath(),e.moveTo(t[0].x,t[0].y),t.length===2)e.lineTo(t[1].x,t[1].y);else{for(let n=1;n<t.length-1;n++){let r=(t[n].x+t[n+1].x)/2,i=(t[n].y+t[n+1].y)/2;e.quadraticCurveTo(t[n].x,t[n].y,r,i)}let n=t[t.length-1];e.lineTo(n.x,n.y)}e.stroke()}function Gd(e,t,n=!1){e.beginPath(),t.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),n&&e.closePath()}function Kd(e,t,n,r=Ud){let i=Math.atan2(n.y-t.y,n.x-t.x);e.beginPath(),e.moveTo(n.x-r*Math.cos(i-Math.PI/6),n.y-r*Math.sin(i-Math.PI/6)),e.lineTo(n.x,n.y),e.lineTo(n.x-r*Math.cos(i+Math.PI/6),n.y-r*Math.sin(i+Math.PI/6)),e.stroke()}function qd(e,t){let n=!1;for(let r=0,i=t.length-1;r<t.length;i=r++){let a=t[r],o=t[i];a.y>e.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(n=!n)}return n}var Jd=new WeakMap;function Yd(e){let t=Jd.get(e);if(!t){t={t0:1/0,t1:-1/0,p0:1/0,p1:-1/0};for(let n of e)n.time<t.t0&&(t.t0=n.time),n.time>t.t1&&(t.t1=n.time),n.price<t.p0&&(t.p0=n.price),n.price>t.p1&&(t.p1=n.price);Jd.set(e,t)}return t}var Xd=class extends G{descriptor={type:`brush`,name:`Brush`,requiredAnchors:2,creation:`freehand`};stroke(e){return{width:e.style.lineWidth,alpha:1}}render(e,t,n,r){if(t.anchors.length<2)return;let i=t.anchors.map(e=>this.anchorToPixel(e,n)),{width:a,alpha:o}=this.stroke(t);this.applyLineStyle(e,t.style),e.lineWidth=a,e.lineCap=`round`,e.lineJoin=`round`,e.globalAlpha=o,Wd(e,i),e.globalAlpha=1,e.lineCap=`butt`,e.lineJoin=`miter`,this.resetLineStyle(e),r&&this.renderBounds(e,t,n)}renderBounds(e,t,n){let r=this.screenBox(t,n),i=this.stroke(t).width/2+3;e.strokeStyle=t.style.color,e.lineWidth=1,e.setLineDash([3,3]),e.strokeRect(r.x0-i,r.y0-i,r.x1-r.x0+i*2,r.y1-r.y0+i*2),e.setLineDash([])}screenBox(t,n){let{t0:r,t1:i,p0:a,p1:o}=Yd(t.anchors),s=e.T(a,n),c=e.T(o,n);return{x0:e.O(r,n),x1:e.O(i,n),y0:Math.min(s,c),y1:Math.max(s,c)}}hitTestAnchor(){return-1}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=r+this.stroke(t).width/2,a=this.screenBox(t,n);return e.x<a.x0-i||e.x>a.x1+i||e.y<a.y0-i||e.y>a.y1+i?!1:jc(e,t.anchors.map(e=>this.anchorToPixel(e,n)),i)}},Zd=class extends Xd{descriptor={type:`highlighter`,name:`Highlighter`,requiredAnchors:2,creation:`freehand`};stroke(e){return{width:Math.max(10,e.style.lineWidth*8),alpha:.3}}},Qd=class extends G{descriptor={type:`path`,name:`Path`,requiredAnchors:2,creation:`path`,options:{arrowEnd:{kind:`boolean`,label:`Arrow at the end`,default:!0}}};render(e,t,n,r){if(t.anchors.length<2)return;let i=t.anchors.map(e=>this.anchorToPixel(e,n));this.applyLineStyle(e,t.style),e.lineJoin=`round`,Gd(e,i),e.stroke(),this.resetLineStyle(e),this.option(t,`arrowEnd`)&&Kd(e,i[i.length-2],i[i.length-1]),e.lineJoin=`miter`,r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:jc(e,t.anchors.map(e=>this.anchorToPixel(e,n)),r)}},$d=class extends G{descriptor={type:`polyline`,name:`Polyline`,requiredAnchors:3,creation:`path`,fill:!0};render(e,t,n,r){if(t.anchors.length<2)return;let i=t.anchors.map(e=>this.anchorToPixel(e,n)),a=i.length>=3;Gd(e,i,a),a&&(e.fillStyle=t.style.fillColor??`rgba(76, 141, 255, 0.1)`,e.fill()),this.applyLineStyle(e,t.style),e.lineJoin=`round`,e.stroke(),e.lineJoin=`miter`,this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=t.anchors.map(e=>this.anchorToPixel(e,n));return jc(e,i,r,!0)||i.length>=3&&qd(e,i)}};function ef(e,t,n,r=Hd){let i={x:2*t.x-(e.x+n.x)/2,y:2*t.y-(e.y+n.y)/2},a=[];for(let t=0;t<=r;t++){let o=t/r,s=1-o;a.push({x:s*s*e.x+2*s*o*i.x+o*o*n.x,y:s*s*e.y+2*s*o*i.y+o*o*n.y})}return a}function tf(e,t,n,r=Hd){let i=2*(e.x*(t.y-n.y)+t.x*(n.y-e.y)+n.x*(e.y-t.y));if(Math.abs(i)<1e-9)return[e,n];let a=e.x*e.x+e.y*e.y,o=t.x*t.x+t.y*t.y,s=n.x*n.x+n.y*n.y,c=(a*(t.y-n.y)+o*(n.y-e.y)+s*(e.y-t.y))/i,l=(a*(n.x-t.x)+o*(e.x-n.x)+s*(t.x-e.x))/i,u=Math.hypot(e.x-c,e.y-l),d=Math.atan2(e.y-l,e.x-c),f=Math.atan2(t.y-l,t.x-c),p=Math.atan2(n.y-l,n.x-c),m=(e,t)=>((t-e)%(2*Math.PI)+2*Math.PI)%(2*Math.PI),h=m(d,p),g=m(d,f)<=h?h:h-2*Math.PI,_=[];for(let e=0;e<=r;e++){let t=d+g*e/r;_.push({x:c+u*Math.cos(t),y:l+u*Math.sin(t)})}return _}var nf=class extends G{descriptor={type:`curve`,name:`Curve`,requiredAnchors:3};shape(e,t,n){return ef(e,t,n)}points(e,t){let n=e.anchors.map(e=>this.anchorToPixel(e,t));return n.length<3?n:this.shape(n[0],n[2],n[1])}render(e,t,n,r){t.anchors.length<2||(this.applyLineStyle(e,t.style),Gd(e,this.points(t,n)),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n))}hitTest(e,t,n,r){return t.anchors.length<2?!1:jc(e,this.points(t,n),r)}},rf=class extends nf{descriptor={type:`arc`,name:`Arc`,requiredAnchors:3};shape(e,t,n){return tf(e,t,n)}},af=(1+Math.sqrt(5))/2,of=64,sf=34,cf=12;function lf(e,t=[]){return{levels:{kind:`levels`,label:`Levels`,default:pl(e,t)},showLevels:{kind:`boolean`,label:`Show levels`,default:!0}}}var uf=[.236,.382,.5,.618,.786,1];function df(e){return String(Number(e.toFixed(3)))}function ff(e,t,n,r,i,a=of){let o=[];for(let s=0;s<=a;s++){let c=r+i*s/a;o.push({x:e.x+t*Math.cos(c),y:e.y+n*Math.sin(c)})}return o}function pf(e,t){e.beginPath(),t.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.stroke()}var mf=class extends G{guides(e){return e.length>=2?[[e[0],e[1]]]:[]}pixels(e,t){return e.anchors.map(e=>this.anchorToPixel(e,t))}render(e,t,n,r){if(t.anchors.length<2)return;let i=this.pixels(t,n);this.applyLineStyle(e,t.style),e.globalAlpha=.6,e.setLineDash([4,4]);for(let[t,n]of this.guides(i))pf(e,[t,n]);e.globalAlpha=1,this.applyLineStyle(e,t.style);let a=this.option(t,`showLevels`);e.font=W(11),e.textAlign=`left`,e.textBaseline=`bottom`;let o=this.shapes(i,this.visibleLevels(t),n,t);for(let n of o)e.strokeStyle=n.level.color??t.style.color,pf(e,n.points);a&&this.renderLabels(e,t,o),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}renderLabels(e,t,n){let r=[];for(let{level:i,label:a}of[...n].reverse())r.some(e=>Math.abs(e.x-a.x)<sf&&Math.abs(e.y-a.y)<cf)||(r.push(a),e.fillStyle=i.color??t.style.color,cc(e,df(i.value),a.x+3,a.y-2))}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.pixels(t,n);return this.guides(i).some(([t,n])=>Ac(e,t,n)<=r)?!0:this.shapes(i,this.visibleLevels(t),n,t).some(t=>jc(e,t.points,r))}},hf=class extends mf{descriptor={type:`fibCircles`,name:`Fib Circles`,requiredAnchors:2,options:lf([...uf,1.618,2.618],[3.618,4.236])};shapes(e,t){let[n,r]=e,i=Math.hypot(r.x-n.x,r.y-n.y);return t.map(e=>{let t=i*e.value;return{level:e,points:ff(n,t,t,0,Math.PI*2),label:{x:n.x+t,y:n.y}}})}},gf=class extends mf{descriptor={type:`fibArcs`,name:`Fib Speed Resistance Arcs`,requiredAnchors:2,options:{...lf(uf),fullCircles:{kind:`boolean`,label:`Full circles`,default:!1}}};shapes(e,t,n,r){let[i,a]=e,o=Math.hypot(a.x-i.x,a.y-i.y),s=Math.atan2(a.y-i.y,a.x-i.x),c=this.option(r,`fullCircles`);return t.map(e=>{let t=o*e.value;return{level:e,points:c?ff(i,t,t,0,Math.PI*2):ff(i,t,t,s-Math.PI/2,Math.PI),label:{x:i.x+t*Math.cos(s),y:i.y+t*Math.sin(s)}}})}},_f=class extends mf{descriptor={type:`fibWedge`,name:`Fib Wedge`,requiredAnchors:3,options:lf(uf)};guides(e){return e.slice(1).map(t=>[e[0],t])}shapes(e,t){if(e.length<3)return[];let[n,r,i]=e,a=Math.hypot(r.x-n.x,r.y-n.y),o=Math.atan2(r.y-n.y,r.x-n.x),s=Math.atan2(i.y-n.y,i.x-n.x)-o;return s>Math.PI&&(s-=2*Math.PI),s<-Math.PI&&(s+=2*Math.PI),t.map(e=>{let t=a*e.value;return{level:e,points:ff(n,t,t,o,s,32),label:{x:n.x+t*Math.cos(o),y:n.y+t*Math.sin(o)}}})}},vf=class extends mf{descriptor={type:`pitchfan`,name:`Pitchfan`,requiredAnchors:3,options:lf([0,.25,.382,.5,.618,.75,1])};guides(e){return e.length>=3?[[e[1],e[2]]]:[[e[0],e[1]]]}shapes(e,t,n){if(e.length<3)return[];let[r,i,a]=e,o=Math.hypot(n.chartRect.width,n.chartRect.height)*2;return t.map(e=>{let t={x:i.x+(a.x-i.x)*e.value,y:i.y+(a.y-i.y)*e.value},n=Math.hypot(t.x-r.x,t.y-r.y)||1;return{level:e,points:[r,{x:r.x+(t.x-r.x)/n*o,y:r.y+(t.y-r.y)/n*o}],label:t}})}},yf=class extends G{descriptor={type:`fibSpiral`,name:`Fib Spiral`,requiredAnchors:2,options:{clockwise:{kind:`boolean`,label:`Clockwise`,default:!1}}};points(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i=Math.hypot(r.x-n.x,r.y-n.y);if(i===0)return[];let a=Math.atan2(r.y-n.y,r.x-n.x),o=this.option(e,`clockwise`)?1:-1,s=Math.hypot(t.chartRect.width,t.chartRect.height)*1.5,c=Math.PI/2,l=Math.log(s/i)/Math.log(af),u=Math.log(i/2)/Math.log(af),d=-Math.max(0,u)*c,f=Math.max(1,l)*c,p=[],m=Math.min(720,Math.ceil((f-d)/c*24));for(let e=0;e<=m;e++){let t=d+(f-d)*e/m,r=i*af**+(t/c);p.push({x:n.x+r*Math.cos(a+o*t),y:n.y+r*Math.sin(a+o*t)})}return p}render(e,t,n,r){t.anchors.length<2||(this.applyLineStyle(e,t.style),pf(e,this.points(t,n)),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n))}hitTest(e,t,n,r){return t.anchors.length<2?!1:jc(e,this.points(t,n),r)}},bf=class extends G{descriptor={type:`gannSquare`,name:`Gann Square`,requiredAnchors:2,options:{...lf([.25,.382,.5,.618,.75]),arcs:{kind:`boolean`,label:`Arcs`,default:!0}}};lines(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i=r.x-n.x,a=r.y-n.y,o=[[n,{x:r.x,y:n.y}],[{x:r.x,y:n.y},r],[r,{x:n.x,y:r.y}],[{x:n.x,y:r.y},n],[n,r],[{x:r.x,y:n.y},{x:n.x,y:r.y}]],s=this.visibleLevels(e);for(let{value:e}of s)o.push([{x:n.x+i*e,y:n.y},{x:n.x+i*e,y:r.y}]),o.push([{x:n.x,y:n.y+a*e},{x:r.x,y:n.y+a*e}]);return{grid:o,arcs:this.option(e,`arcs`)?[...s.map(e=>e.value),1].map(e=>{let t=Math.atan2(0,Math.sign(i)||1),r=(Math.sign(i)||1)*(Math.sign(a)||1)*(Math.PI/2);return ff(n,Math.abs(i)*e,Math.abs(a)*e,t,r,24)}):[]}}render(e,t,n,r){if(t.anchors.length<2)return;let{grid:i,arcs:a}=this.lines(t,n);this.applyLineStyle(e,t.style),i.forEach(([t,n],r)=>{e.globalAlpha=r<6?1:.55,pf(e,[t,n])}),e.globalAlpha=.8;for(let t of a)pf(e,t);e.globalAlpha=1,this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let{grid:i}=this.lines(t,n);return i.slice(0,6).some(([t,n])=>Ac(e,t,n)<=r)}},xf=400,Sf=32,Cf=3,wf=class extends G{descriptor={type:`timeCycles`,name:`Time Cycles`,requiredAnchors:2,fill:!0};visibleCycles(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t).x-n.x,i=Math.abs(r)/2;if(i<1)return{y:n.y,r:i,centres:[]};let a=t.chartRect.x,o=a+t.chartRect.width,s=Math.max(0,Math.floor(((r>0?a:o)-n.x)/r)-1),c=[];for(let e=s;c.length<xf;e++){let t=n.x+r*(e+.5);if(t-i>o||t+i<a){if(c.length>0||(r>0?t-i>o:t+i<a))break;continue}c.push(t)}return{y:n.y,r:i,centres:c}}cycles(e,t){let{y:n,r,centres:i}=this.visibleCycles(e,t);return i.map(e=>{let t=[];for(let i=0;i<=Sf;i++){let a=Math.PI+Math.PI*i/Sf;t.push({x:e+r*Math.cos(a),y:n+r*Math.sin(a)})}return t})}render(e,t,n,r){if(t.anchors.length<2)return;let i=this.cycles(t,n);e.fillStyle=t.style.fillColor??`rgba(76, 141, 255, 0.1)`,this.applyLineStyle(e,t.style);for(let t of i)e.beginPath(),t.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.fill(),e.stroke();this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let{y:i,r:a,centres:o}=this.visibleCycles(t,n);return e.y>i+r?!1:o.some(t=>Math.abs(Math.hypot(e.x-t,e.y-i)-a)<=r)}},Tf=class extends G{descriptor={type:`sineLine`,name:`Sine Line`,requiredAnchors:2};points(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i=r.x-n.x;if(Math.abs(i)<1)return[n,r];let a=(n.y+r.y)/2,o=(n.y-r.y)/2,{x:s,width:c}=t.chartRect,l=[];for(let e=s;e<=s+c;e+=Cf)l.push({x:e,y:a+o*Math.cos(Math.PI*(e-n.x)/i)});return l}render(e,t,n,r){t.anchors.length<2||(this.applyLineStyle(e,t.style),e.beginPath(),this.points(t,n).forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n))}hitTest(e,t,n,r){return t.anchors.length<2?!1:jc(e,this.points(t,n),r)}},Ef=`#26a69a`,Df=`#ef5350`,Of=500;function kf(t,n,r){let i=r.price>=n.price,a=t.length>0?Math.max(0,Math.floor(e.k(n.time,t))+1):0;for(let e=a;e<t.length;e++){let a=t[e];if(!(a.time<=n.time)){if(a.time>r.time)return`missed`;if(i?a.high>=r.price:a.low<=r.price)return`reached`}}return`pending`}var Af=class extends G{descriptor={type:`forecast`,name:`Forecast`,requiredAnchors:2};bars=()=>[];setDataGetter(e){this.bars=e}render(e,t,n,r){if(t.anchors.length<2)return;let[i,a]=t.anchors,o=this.anchorToPixel(i,n),s=this.anchorToPixel(a,n),c=kf(this.bars(),i,a),l=c===`reached`?Ef:c===`missed`?Df:t.style.color;this.applyLineStyle(e,{...t.style,color:l}),e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(s.x,s.y),e.stroke(),Kd(e,o,s),this.resetLineStyle(e),e.strokeStyle=l,e.beginPath(),e.arc(s.x,s.y,5,0,Math.PI*2),e.stroke();let u=Tc(t,0,1,n);Ec(e,[xc(i.price,a.price,n),`${bc(a.price,i.price,n)} · ${wc(t,0,1,n)} bars${u?`, ${u}`:``}`,c===`reached`?`Target reached`:c===`missed`?`Target missed`:`Pending`],s.x,s.y+(s.y<o.y?-10:10),`center`,s.y<o.y),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:Ac(e,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n))<=r}},jf=class extends G{descriptor={type:`projection`,name:`Projection`,requiredAnchors:3,fill:!0};target(t,n){let[r,i,a]=t.anchors,o=e.D(i.time,n)-e.D(r.time,n);return{x:e.b(e.D(a.time,n)+o,n),y:e.T(a.price+(i.price-r.price),n)}}render(e,t,n,r){if(t.anchors.length<2)return;let i=t.anchors.map(e=>this.anchorToPixel(e,n));if(this.applyLineStyle(e,t.style),e.setLineDash([5,4]),e.beginPath(),e.moveTo(i[0].x,i[0].y),e.lineTo(i[1].x,i[1].y),e.stroke(),t.anchors.length>=3){let r=i[2],a=this.target(t,n);e.fillStyle=t.style.fillColor??`rgba(76, 141, 255, 0.1)`,e.fillRect(Math.min(r.x,a.x),Math.min(r.y,a.y),Math.abs(a.x-r.x),Math.abs(a.y-r.y)),this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(a.x,a.y),e.stroke(),Kd(e,r,a);let[o,s,c]=t.anchors,l=c.price+(s.price-o.price);Ec(e,[bc(l,c.price,n),xc(c.price,l,n)],a.x,a.y+(a.y<r.y?-8:8),`center`,a.y<r.y)}this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=t.anchors.map(e=>this.anchorToPixel(e,n));return Ac(e,i[0],i[1])<=r?!0:i.length>=3&&Ac(e,i[2],this.target(t,n))<=r}},Mf=class extends G{descriptor={type:`barsPattern`,name:`Bars Pattern`,requiredAnchors:3,options:{mode:{kind:`choice`,label:`Show as`,default:`bars`,choices:[{value:`bars`,label:`Bars`},{value:`line`,label:`Line`},{value:`highLow`,label:`High-low`}]},mirrored:{kind:`boolean`,label:`Mirrored`,default:!1},flipped:{kind:`boolean`,label:`Flipped`,default:!1}}};bars=()=>[];setDataGetter(e){this.bars=e}copied(t){let n=this.bars();if(n.length===0)return[];let[r,i,a]=t.anchors,o=Math.max(0,Math.round(e.k(Math.min(r.time,i.time),n))),s=Math.min(n.length-1,Math.round(e.k(Math.max(r.time,i.time),n)));if(s<o)return[];let c=n.slice(o,Math.min(s+1,o+Of));if(c.length===0)return[];let l=this.option(t,`flipped`),u=this.option(t,`mirrored`)?[...c].reverse():c,d=u[0].open,f=e=>a.price+(l?d-e:e-d);return u.map(e=>{let t=f(e.high),n=f(e.low);return{...e,open:f(e.open),close:f(e.close),high:Math.max(t,n),low:Math.min(t,n)}})}box(t,n,r){if(r.length===0)return null;let i=e.D(t.anchors[2].time,n),a=e.b(i,n)-n.barWidth/2,o=e.b(i+r.length-1,n)+n.barWidth/2,s=-1/0,c=1/0;for(let e of r)e.high>s&&(s=e.high),e.low<c&&(c=e.low);let l=e.T(s,n),u=e.T(c,n);return{x:a,y:Math.min(l,u),width:o-a,height:Math.abs(u-l)}}render(e,t,n,r){if(t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),e.setLineDash([4,4]),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),this.resetLineStyle(e),t.anchors.length>=3&&this.renderCopy(e,t,n),r&&this.renderAnchorHandles(e,t,n)}renderCopy(t,n,r){let i=this.copied(n);if(i.length===0)return;let a=e.D(n.anchors[2].time,r),o=this.option(n,`mode`);if(t.strokeStyle=n.style.color,t.fillStyle=n.style.color,t.lineWidth=1,t.globalAlpha=.7,o===`line`)t.beginPath(),i.forEach((n,i)=>{let o=e.b(a+i,r),s=e.T(n.close,r);i===0?t.moveTo(o,s):t.lineTo(o,s)}),t.stroke();else{let n=Math.max(1,r.barWidth/2);i.forEach((i,s)=>{let c=e.b(a+s,r);if(t.beginPath(),t.moveTo(c,e.T(i.high,r)),t.lineTo(c,e.T(i.low,r)),t.stroke(),o===`highLow`)return;let l=e.T(Math.max(i.open,i.close),r),u=Math.max(1,e.T(Math.min(i.open,i.close),r)-l);i.close>=i.open?t.strokeRect(c-n,l,n*2,u):t.fillRect(c-n,l,n*2,u)})}t.globalAlpha=1}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;if(Ac(e,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n))<=r)return!0;let i=t.anchors.length>=3?this.box(t,n,this.copied(t)):null;return i!==null&&yd(e,i,r)}};function Nf(e){e.register(new jl),e.register(new Ml),e.register(new Nl),e.register(new Pl),e.register(new Fl),e.register(new Il),e.register(new Ll),e.register(new Rl),e.register(new Ul),e.register(new Gl),e.register(new Kl),e.register(new ql),e.register(new Jl),e.register(new Yl),e.register(new nu),e.register(new cu),e.register(new lu),e.register(new uu),e.register(new fu),e.register(new pu),e.register(new hu),e.register(new _u),e.register(new vu),e.register(new yu),e.register(new xu),e.register(new Du),e.register(new Ou),e.register(new bl),e.register(new Au),e.register(new Pu),e.register(new Ru),e.register(new Xl),e.register(new Zl),e.register(new Bu),e.register(new Vu),e.register(new Hu),e.register(new Gu),e.register(new Zu),e.register(new td),e.register(new od),e.register(new kd),e.register(new Ad),e.register(new Fd),e.register(new Rd),e.register(new Vd),e.register(new Xd),e.register(new Zd),e.register(new Qd),e.register(new $d),e.register(new nf),e.register(new rf),e.register(new hf),e.register(new yf),e.register(new gf),e.register(new _f),e.register(new vf),e.register(new bf),e.register(new ru),e.register(new iu),e.register(new au),e.register(new ou),e.register(new su),e.register(new Uu),e.register(new Wu),e.register(new wf),e.register(new Tf),e.register(new Af),e.register(new jf),e.register(new Mf)}function q(e,t){let{chartRect:n}=t;return e>=n.y&&e<=n.y+n.height}function Pf(e,t){let{chartRect:n}=t;return Math.min(Math.max(e,n.y),n.y+n.height)}function Ff(e,t,n,r,i){let{chartRect:a}=t;e.setLineDash(i),e.strokeStyle=r,e.lineWidth=1,e.beginPath(),e.moveTo(a.x,Math.round(n)+.5),e.lineTo(a.x+a.width,Math.round(n)+.5),e.stroke(),e.setLineDash([])}function If(e,t,n,r,i){let a=Math.min(Math.max(e.closedQuantity??0,0),e.quantity),o=e.quantity-a,s=e.side===`buy`?1:-1,c=(t-e.entryPrice)*o*s,l=e.entryPrice===0?0:(t-e.entryPrice)/e.entryPrice*100*s;return{side:e.side,quantity:e.quantity,closedQuantity:a,openQuantity:o,entryPrice:e.entryPrice,currentPrice:t,pnl:c,pnlPct:l,precision:n,formatPrice:r,locale:i}}var Lf=/\{(side|qty|closedQty|openQty|entry|price|pnl|pnlPct|pnlSign)\}/g;function Rf(e,n){return e.replace(Lf,(e,r)=>{switch(r){case`side`:return n.side.toUpperCase();case`qty`:return String(n.quantity);case`closedQty`:return String(n.closedQuantity);case`openQty`:return String(n.openQuantity);case`entry`:return n.formatPrice?.(n.entryPrice)??(0,t.formatPrice)(n.entryPrice,n.precision,n.locale);case`price`:return n.formatPrice?.(n.currentPrice)??(0,t.formatPrice)(n.currentPrice,n.precision,n.locale);case`pnl`:return(0,t.formatPrice)(n.pnl,n.precision,n.locale);case`pnlPct`:return`${n.pnlPct.toFixed(2)}%`;case`pnlSign`:return n.pnl>=0?`+`:``;default:return``}})}function zf(e,n,r){let i=10**n,a=Math.round(e*i)/i||0;return`${a>0?`+`:``}${(0,t.formatPrice)(a,n,r)}`}function Bf(e,t,n,r){return(r-t)*n*(e===`buy`?1:-1)}function Vf(e,t){return typeof e==`function`?e(t):Rf(e??`{side} {qty} | P&L: {pnlSign}{pnl}`,t)}function Hf(e,t,n){if(!t||t.length===0)return n;let r=[...t].sort((e,t)=>e.pnl-t.pnl),i;for(let t of r)if(e>=t.pnl)i=t.color;else break;return i??n}var Uf=24,Wf=1.75,Gf=[2,2.5],Kf=new Map,qf=e=>{let t=Kf.get(e);return t||(t=new Path2D(e),Kf.set(e,t)),t};function Jf(e,n,r,i,a,o){if(!(typeof Path2D>`u`)){if(e.save(),e.translate(Math.round(r),Math.round(i)),e.scale(a/Uf,a/Uf),e.strokeStyle=o,e.fillStyle=o,e.lineWidth=Math.max(Wf,Uf/a),e.lineCap=`round`,e.lineJoin=`round`,e.setLineDash([]),n.soft){let r=e.globalAlpha;e.globalAlpha=r*t.ICON_SOFT_OPACITY,e.fill(qf(n.soft)),e.globalAlpha=r}for(let t of n.fills??[])e.fill(qf(t));n.d&&e.stroke(qf(n.d)),n.dash&&(e.setLineDash(Gf),e.stroke(qf(n.dash)),e.setLineDash([]));for(let[r,i,a=t.ICON_DOT_RADIUS]of n.dots??[])e.beginPath(),e.arc(r,i,a,0,Math.PI*2),e.fill();e.restore()}}var Yf=5,Xf=13,Zf=22;function Qf(e,t,n){for(let r=e.length-1;r>=0;r--){let i=e[r];if(t>=i.x&&t<=i.x+i.width&&n>=i.y&&n<=i.y+i.height)return i}return null}function $f(e,t){return`${e.kind===`stamp`?`600 `:``}${t.font.sizeSmall}px ${t.font.family}`}function ep(e,t,n){return t.kind===`button`?21:(e.font=$f(t,n),Math.ceil(e.measureText(t.text).width)+Yf*2)}function tp(e){return Math.round(e)-10}function np(e,t){let n=[];return e.map(({y:e,width:r})=>{let i=t.right-8-r;for(;;){let t=n.find(t=>Math.abs(t.y-e)<Zf&&i<t.x1&&i+r>t.x0);if(!t)break;i=t.x0-8-r}let a=i>=t.left;return i=Math.max(t.left,i),n.push({x0:i,x1:i+r,y:e}),{x:i,fits:a}})}function rp(e,t,n,r,i,a=[]){if(t.length===0)return;let{chartRect:o}=n,s=t.map(t=>t.cells.map(t=>ep(e,t,r))),c=s.map(e=>e.reduce((e,t)=>e+t,0)),l=np(t.map((e,t)=>({y:e.y,width:c[t]})),{left:o.x,right:o.x+o.width}),u=t.map((e,t)=>t).sort((e,t)=>Number(l[e].fits)-Number(l[t].fits));for(let n of u){let{x:u,fits:d}=l[n],f=tp(t[n].y);ip(e,t[n],u,f,s[n],c[n],r,d?i:[]);let p=t[n].grab;if(!d||!p)continue;let m=Math.max(f,o.y),h=Math.min(f+21,o.y+o.height);h>m&&a.push({x:u,y:m,width:c[n],height:h-m,lineY:t[n].y,grab:p})}}function ip(e,t,n,r,i,a,o,s){let c=r+21/2;e.save(),T(e,n,r,a,21,o),e.clip(),e.fillStyle=o.background,e.fillRect(n,r,a,21),e.textBaseline=`middle`,e.textAlign=`left`;let l=n;t.cells.forEach((n,a)=>{let u=i[a];e.fillStyle=t.color,n.kind===`stamp`?e.fillRect(l,r,u,21):a>0&&e.fillRect(l,r,1,21),n.kind===`button`?(Jf(e,n.icon,l+(u-Xf)/2,r+(21-Xf)/2,Xf,o.text),s.push({x:l,y:r,size:21,action:n.action})):(e.font=$f(n,o),e.fillStyle=n.kind===`stamp`?A(t.color):n.color??o.text,e.fillText(n.text,l+Yf,c)),l+=u}),T(e,n+.5,r+.5,a-1,20,o),e.strokeStyle=t.color,e.lineWidth=1,e.stroke(),e.restore()}function ap(e,t){let{chartRect:n}=t,r=n.y+n.height,i=[...e].sort((e,t)=>e.y-t.y),a=k(i.map(e=>e.y),n.y,r,16);return i.map((e,t)=>({...e,at:a[t]})).filter(e=>e.at+16/2<=r+.5)}function op(e,n,r,i,a,o){let{chartRect:s}=a,c=s.x+s.width+1;e.fillStyle=i,E(e,c,Math.round(n)-16/2,(a.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,16,o),e.fillStyle=A(i),e.font=`${o.font.sizeSmall}px ${o.font.family}`,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(r,c+5,Math.round(n))}var sp=[6,4],cp=[2,3],lp=[2,4],up=.3;function dp(e){if(e.label===`SL`||e.label===`TP`)return e.label;let t=e.label?e.label.toLowerCase():e.type===`stopLimit`?`stop limit`:e.type;return`${e.side===`buy`?`Buy`:`Sell`} ${t}`}function fp(e){return{buy:e.orderColors?.buy??`#1fa874`,sell:e.orderColors?.sell??`#e8505b`,profit:e.positionColors?.profit??`#1fa874`,loss:e.positionColors?.loss??`#e8505b`}}function pp(e,t){return t?.orderId===e.id&&t.sourceType===`order`}function mp(e,t){return pp(e,t)?t.currentPrice:e.price}var hp=class{render(e,t,n,r,i,a,o=[]){this.renderLines(e,t,n,i,a),rp(e,this.tags(t,n,i,a),n,r,o)}renderLines(t,n,r,i,a){let o=fp(i);for(let i of n){let n=e.T(mp(i,a),r),s=i.side===`buy`?o.buy:o.sell;q(n,r)&&Ff(t,r,n,s,sp),pp(i,a)&&(t.globalAlpha=up,Ff(t,r,e.T(a.startPrice,r),s,lp),t.globalAlpha=1);for(let[n,a]of[[i.stopLoss,o.loss],[i.takeProfit,o.profit]]){let i=n===void 0?NaN:e.T(n,r);q(i,r)&&Ff(t,r,i,a,cp)}}}tags(n,r,i,a){let o=fp(i),s=i.pricePrecision??2,c=[];for(let l of n){let n=mp(l,a),u=e.T(n,r);if(q(u,r)){let e=[{kind:`stamp`,text:String(l.quantity)},{kind:`text`,text:dp(l)}];i.lineButtons?.cancel!==!1&&!pp(l,a)&&e.push({kind:`button`,icon:t.UI_ICONS.x,action:{type:`cancelOrder`,orderId:l.id}});let n=l.draggable===!1?void 0:{kind:`order`,orderId:l.id};c.push({y:u,color:l.side===`buy`?o.buy:o.sell,cells:e,grab:n})}for(let t of[`stopLoss`,`takeProfit`]){let i=l[t],a=i===void 0?NaN:e.T(i,r);if(i===void 0||!q(a,r))continue;let u=Bf(l.side,n,l.quantity,i);c.push({y:a,color:t===`stopLoss`?o.loss:o.profit,cells:[{kind:`stamp`,text:t===`stopLoss`?`SL`:`TP`},{kind:`text`,text:zf(u,s,r.numberLocale),color:u>=0?o.profit:o.loss}]})}}return c}renderAxisBadges(e,t,n,r,i,a){for(let o of this.axisBadges(t,n,i,a))op(e,o.y,o.text,o.color,n,r)}axisBadges(n,r,i,a){let o=fp(i),s=[];for(let c of n){let n=mp(c,a),l=e.T(n,r);q(l,r)&&s.push({y:l,text:(0,t.priceTagText)(n,r,i.pricePrecision),color:c.side===`buy`?o.buy:o.sell})}return s}hitTest(t,n,r,i){for(let a of n){if(a.draggable===!1)continue;let n=e.T(a.price,r);if(Math.abs(t-n)<=i)return a}return null}},gp=[4,4],_p=[2,4],vp=.3,yp=.08,bp=.25,xp=.04,Sp=[`stopLoss`,`takeProfit`];function Cp(e){return{profit:e.positionColors?.profit??`#1fa874`,loss:e.positionColors?.loss??`#e8505b`,entry:e.positionColors?.entry??`#4c8dff`}}function wp(e,t){let{chartRect:n}=t;return e-21/2>=n.y&&e+21/2<=n.y+n.height}function Tp(e){return e.quantity-Math.min(Math.max(e.closedQuantity??0,0),e.quantity)}function Ep(e,t,n){return n?.orderId===e.id&&n.sourceType===t?n.currentPrice:e[t]}var Dp=class{render(e,t,n,r,i,a,o=[],s=null){this.renderLines(e,t,n,r,a,s),rp(e,this.tags(t,n,r,a,s),r,i,o)}renderLines(t,n,r,i,a,o=null){let s=Cp(a);for(let c of n){let n=e.T(c.entryPrice,i);Ff(t,i,n,s.entry,[]),r!==null&&this.renderBand(t,c,n,e.T(r,i),r,i,a);for(let n of Sp){let r=Ep(c,n,o),a=r===void 0?NaN:e.T(r,i),l=n===`stopLoss`?s.loss:s.profit;q(a,i)&&Ff(t,i,a,l,gp);let u=c[n];u!==void 0&&r!==u&&(t.globalAlpha=vp,Ff(t,i,e.T(u,i),l,_p),t.globalAlpha=1)}}}renderBand(e,t,n,r,i,a,o){let{chartRect:s}=a,c=Cp(o),l=If(t,i,o.pricePrecision??2),u=Math.min(n,r),d=Math.abs(r-n);e.fillStyle=Hf(l.pnl,o.pnlThresholds,l.pnl>=0?c.profit:c.loss),e.globalAlpha=yp,e.fillRect(s.x,u,s.width,d),l.closedQuantity>0&&t.quantity>0&&(e.fillStyle=c.entry,e.globalAlpha=bp,e.fillRect(s.x,u,Math.max(2,s.width*(l.closedQuantity/t.quantity)*xp)+2,d)),e.globalAlpha=1}tags(e,t,n,r,i=null){let a=[];for(let o of e){let e=this.entryTag(o,t,n,r);e&&a.push(e);for(let e of Sp){let t=this.stopTag(o,e,n,r,i);t&&a.push(t)}}return a}entryTag(n,r,i,a){let o=e.T(n.entryPrice,i);if(!q(o,i))return null;let s=Cp(a),c=n.side===`buy`?`Long`:`Short`,l=[{kind:`stamp`,text:String(Tp(n))}];if(r===null)l.push({kind:`text`,text:c});else{let e=a.pricePrecision??2,o=If(n,r,e,e=>(0,t.priceTagText)(e,i,a.pricePrecision),i.numberLocale);if(a.positionLabel!==void 0)l.push({kind:`text`,text:Vf(a.positionLabel,o)});else{let t=Hf(o.pnl,a.pnlThresholds,o.pnl>=0?s.profit:s.loss);l.push({kind:`text`,text:c},{kind:`text`,text:zf(o.pnl,e,i.numberLocale),color:t})}}let u=a.lineButtons??{};return wp(o,i)&&(u.reverse!==!1&&l.push({kind:`button`,icon:t.UI_ICONS.arrowUpDown,action:{type:`reversePosition`,positionId:n.id}}),u.close!==!1&&l.push({kind:`button`,icon:t.UI_ICONS.x,action:{type:`closePosition`,positionId:n.id}})),{y:o,color:s.entry,cells:l}}stopTag(n,r,i,a,o){let s=Ep(n,r,o),c=s===void 0?NaN:e.T(s,i);if(s===void 0||!q(c,i))return null;let l=Cp(a),u=Bf(n.side,n.entryPrice,Tp(n),s),d=[{kind:`stamp`,text:r===`stopLoss`?`SL`:`TP`},{kind:`text`,text:zf(u,a.pricePrecision??2,i.numberLocale),color:u>=0?l.profit:l.loss}],f=o?.orderId===n.id&&o.sourceType===r;return a.lineButtons?.removeStops!==!1&&wp(c,i)&&!f&&d.push({kind:`button`,icon:t.UI_ICONS.x,action:{type:`removeStop`,positionId:n.id,which:r}}),{y:c,color:r===`stopLoss`?l.loss:l.profit,cells:d,grab:{kind:`stop`,positionId:n.id,which:r}}}renderAxisBadges(e,t,n,r,i){for(let a of this.axisBadges(t,n,i))op(e,a.y,a.text,a.color,n,r)}axisBadges(n,r,i,a=null){let o=Cp(i),s=[];for(let c of n){let n=[[Ep(c,`stopLoss`,a),o.loss],[Ep(c,`takeProfit`,a),o.profit],[c.entryPrice,o.entry]];for(let[a,o]of n){if(a===void 0)continue;let n=e.T(a,r);q(n,r)&&s.push({y:n,text:(0,t.priceTagText)(a,r,i.pricePrecision),color:o})}}return s}},Op=class{render(t,n,r,i){if(!i.depthOverlay?.enabled)return;let{chartRect:a}=r,o=i.depthOverlay.bidColor??`rgba(31, 168, 116,0.15)`,s=i.depthOverlay.askColor??`rgba(232, 80, 91,0.15)`,c=i.depthOverlay.maxWidth??100,l=0,u=[],d=0;for(let e of n.bids)d+=e.volume,u.push({price:e.price,cumVol:d}),d>l&&(l=d);let f=[];d=0;for(let e of n.asks)d+=e.volume,f.push({price:e.price,cumVol:d}),d>l&&(l=d);if(l===0)return;let p=Math.max(1,n.bids.length>1?Math.abs(e.T(n.bids[0].price,r)-e.T(n.bids[1].price,r)):4),m=a.x+a.width;t.fillStyle=o;for(let{price:n,cumVol:i}of u){let o=e.T(n,r);if(o<a.y||o>a.y+a.height)continue;let s=i/l*c;t.fillRect(m-s,o-p/2,s,p)}t.fillStyle=s;for(let{price:n,cumVol:i}of f){let o=e.T(n,r);if(o<a.y||o>a.y+a.height)continue;let s=i/l*c;t.fillRect(m-s,o-p/2,s,p)}}},kp=[`stopLoss`,`takeProfit`],Ap=class{dragState=null;startY=0;dragging=!1;constructor(e=3){this.dragThreshold=e}onPointerDown(t,n,r,i,a){let o=n=>{let r=e.T(n,i);return q(r,i)&&Math.abs(t.y-r)<=a},s=n.find(e=>e.draggable!==!1&&o(e.price));if(s)return this.beginOrder(s,t.y);for(let e of r)for(let n of kp){let r=e[n];if(r!==void 0&&o(r))return this.beginStop(e,n,t.y)}return!1}beginOrder(e,t){return e.draggable===!1?!1:this.start({orderId:e.id,sourceType:`order`,startPrice:e.price,currentPrice:e.price},t)}beginStop(e,t,n){let r=e[t];return r===void 0?!1:this.start({orderId:e.id,sourceType:t,startPrice:r,currentPrice:r},n)}start(e,t){return this.dragState=e,this.startY=t,this.dragging=!1,!0}onPointerMove(t,n){if(!this.dragState)return!1;if(!this.dragging){if(Math.abs(t.y-this.startY)<this.dragThreshold)return!0;this.dragging=!0}return this.dragState.currentPrice=e.M(t.y,n),!0}onPointerUp(){if(!this.dragState)return null;let e=this.dragState;return this.dragState=null,this.dragging?(this.dragging=!1,{sourceType:e.sourceType,id:e.orderId,newPrice:e.currentPrice,previousPrice:e.startPrice}):null}cancel(){return this.dragState?(this.dragState=null,this.dragging=!1,!0):!1}getDragState(){return this.dragState}isActive(){return this.dragState!==null}},jp=class{menuElement=null;removeHandler=null;onItemSelect=null;show(e,t,n,r,i){if(this.hide(),!r.contextMenu?.enabled)return;let a=r.pricePrecision??2,o=i?.(t)??t.toFixed(a),s=document.createElement(`div`);s.style.cssText=`
4
4
  position: absolute;
5
5
  left: ${e.x}px;
6
6
  top: ${e.y}px;
@@ -18,6 +18,6 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
18
18
  cursor: pointer;
19
19
  color: ${n?`#1fa874`:`#e8505b`};
20
20
  transition: background 0.1s;
21
- `,t.addEventListener(`mouseenter`,()=>{t.style.background=`#1f2630`}),t.addEventListener(`mouseleave`,()=>{t.style.background=`transparent`}),t.addEventListener(`click`,()=>{this.onItemSelect?.(e.intent),this.hide()}),s.appendChild(t)}n.appendChild(s),this.menuElement=s;let l=e=>{(e instanceof KeyboardEvent&&e.key===`Escape`||e instanceof MouseEvent&&!s.contains(e.target))&&this.hide()};document.addEventListener(`mousedown`,l),document.addEventListener(`keydown`,l),this.removeHandler=()=>{document.removeEventListener(`mousedown`,l),document.removeEventListener(`keydown`,l)}}hide(){this.menuElement?.remove(),this.menuElement=null,this.removeHandler?.(),this.removeHandler=null}destroy(){this.hide(),this.onItemSelect=null}};function Zf(e,t,n={}){let r=Math.max(Math.abs(t)*(n.riskFraction??.01),1e-8),i=r*(n.riskReward??2);return e===`buy`?{side:e,entry:t,stopLoss:t-r,takeProfit:t+i}:{side:e,entry:t,stopLoss:t+r,takeProfit:t-i}}function Qf(e){let t=Math.abs(e.entry-e.stopLoss);return t===0?0:Math.abs(e.takeProfit-e.entry)/t}var $f=6,ep=class{draft=null;dragStart=null;dragging=null;defaults;constructor(e={}){this.defaults=e}start(e,t){this.draft=Zf(e,t,this.defaults),this.dragging=null}cancel(){this.draft=null,this.dragging=null}isActive(){return this.draft!==null}getDraft(){return this.draft?{...this.draft}:null}hitTest(t,n,r=$f){if(!this.draft)return null;let i=[`entry`,`sl`,`tp`],a=null,o=r;for(let r of i){let i=e.T(this.priceOf(r),n),s=Math.abs(i-t.y);s<=o&&(o=s,a=r)}return a}beginDrag(e,t,n){let r=this.hitTest(e,t,n);return r?(this.dragging=r,this.dragStart=this.draft,!0):!1}cancelDrag(){this.dragging&&this.dragStart&&(this.draft=this.dragStart),this.dragging=null,this.dragStart=null}drag(t,n){if(!this.draft||!this.dragging)return!1;let r=e.M(t.y,n);return this.draft=tp(this.draft,this.dragging,r),!0}endDrag(){this.dragging=null,this.dragStart=null}isDragging(){return this.dragging!==null}priceOf(e){let t=this.draft;return e===`entry`?t.entry:e===`sl`?t.stopLoss:t.takeProfit}render(n,r,i,a){let o=this.draft;if(!o)return;let{chartRect:s}=r,c=s.x,l=s.x+s.width,u=e.T(o.entry,r),d=e.T(o.stopLoss,r),f=e.T(o.takeProfit,r),p=i.style?.trading.profit??i.candleUp,m=i.style?.trading.loss??i.candleDown;n.save(),n.globalAlpha=.12,n.fillStyle=p,n.fillRect(c,Math.min(u,f),s.width,Math.abs(f-u)),n.fillStyle=m,n.fillRect(c,Math.min(u,d),s.width,Math.abs(d-u)),n.globalAlpha=1,np(n,c,l,u,i.text,[6,3]),np(n,c,l,f,p,[]),np(n,c,l,d,m,[]);let h=Qf(o),g=o.side===`buy`?`LONG`:`SHORT`,_=e=>(0,t.priceTagText)(e,r,a);rp(n,c+6,u,`${g} entry ${_(o.entry)}`,i.text,i),rp(n,c+6,f,`TP ${_(o.takeProfit)} · ${h.toFixed(2)}R`,p,i),rp(n,c+6,d,`SL ${_(o.stopLoss)}`,m,i);for(let[t,a]of[[o.entry,i.text],[o.takeProfit,p],[o.stopLoss,m]]){let i=e.T(t,r);n.fillStyle=a,n.beginPath(),n.arc(l-6,i,3.5,0,Math.PI*2),n.fill()}n.restore()}};function tp(e,t,n){let r=e.side===`buy`;if(t===`entry`){let t=n-e.entry;return{side:e.side,entry:n,stopLoss:e.stopLoss+t,takeProfit:e.takeProfit+t}}if(t===`sl`){let t=r?Math.min(n,e.entry):Math.max(n,e.entry);return{...e,stopLoss:t}}let i=r?Math.max(n,e.entry):Math.min(n,e.entry);return{...e,takeProfit:i}}function np(e,t,n,r,i,a){e.strokeStyle=i,e.lineWidth=1,e.setLineDash(a),e.beginPath(),e.moveTo(t,Math.round(r)+.5),e.lineTo(n,Math.round(r)+.5),e.stroke(),e.setLineDash([])}function rp(e,t,n,r,i,a){e.font=`600 10px system-ui, sans-serif`,e.textBaseline=`middle`,e.textAlign=`left`;let o=e.measureText(r).width;e.globalAlpha=.85,e.fillStyle=a.background,w(e,t-3,n-8,o+6,16,a),e.globalAlpha=1,e.fillStyle=i,e.fillText(r,t,n+.5)}function ip(e,t,n){return n==null?`limit`:e===`buy`?t<=n?`limit`:`stop`:t>=n?`limit`:`stop`}var ap=6,op=class{draft=null;dragStart=null;dragging=!1;start(e,t,n=1){this.draft={side:e,price:t,quantity:n},this.dragging=!1}cancel(){this.draft=null,this.dragging=!1}isActive(){return this.draft!==null}isDragging(){return this.dragging}getDraft(){return this.draft?{...this.draft}:null}setPrice(e){return this.draft?(this.draft={...this.draft,price:e},!0):!1}toIntent(e){return this.draft?{side:this.draft.side,type:ip(this.draft.side,this.draft.price,e),price:this.draft.price,quantity:this.draft.quantity}:null}hitTest(t,n,r=ap){return this.draft?Math.abs(e.T(this.draft.price,n)-t.y)<=r:!1}beginDrag(e,t,n){return this.hitTest(e,t,n)?(this.dragging=!0,this.dragStart=this.draft,!0):!1}cancelDrag(){this.dragging&&this.dragStart&&(this.draft=this.dragStart),this.dragging=!1,this.dragStart=null}drag(t,n){return!this.draft||!this.dragging?!1:this.setPrice(e.M(t.y,n))}endDrag(){this.dragging=!1,this.dragStart=null}render(n,r,i,a,o){let s=this.draft;if(!s)return;let{chartRect:c}=r,l=c.x,u=c.x+c.width,d=e.T(s.price,r),f=ip(s.side,s.price,a),p=s.side===`buy`?i.style?.trading.buy??i.candleUp:i.style?.trading.sell??i.candleDown;n.save(),sp(n,l,u,d,p,[6,3]);let m=s.side===`buy`?`BUY`:`SELL`;cp(n,l+6,d,`${m} ${f.toUpperCase()} ${(0,t.priceTagText)(s.price,r,o)}`,p,i),n.fillStyle=p,n.beginPath(),n.arc(u-6,d,3.5,0,Math.PI*2),n.fill(),n.restore()}};function sp(e,t,n,r,i,a){e.strokeStyle=i,e.lineWidth=1,e.setLineDash(a),e.beginPath(),e.moveTo(t,Math.round(r)+.5),e.lineTo(n,Math.round(r)+.5),e.stroke(),e.setLineDash([])}function cp(e,t,n,r,i,a){e.font=`600 10px system-ui, sans-serif`,e.textBaseline=`middle`,e.textAlign=`left`;let o=e.measureText(r).width;e.globalAlpha=.85,e.fillStyle=a.background,w(e,t-3,n-8,o+6,16,a),e.globalAlpha=1,e.fillStyle=i,e.fillText(r,t,n+.5)}var lp=5,up=7,dp=2;function fp(e,n){let r=n.data;return r&&r.length>0?e/(0,t.barTimeUnit)(r):e}function pp(t,n,r,i){if(n.length===0)return;let{chartRect:a}=r,o=i.orderColors?.buy??`#1fa874`,s=i.orderColors?.sell??`#e8505b`;t.lineWidth=1.5;for(let i of n){let n=e.O(fp(i.time,r),r),c=e.T(i.price,r);if(n<a.x||n>a.x+a.width||c<a.y||c>a.y+a.height)continue;let l=i.side===`buy`,u=l?c+dp:c-dp,d=l?u+up:u-up;t.beginPath(),t.moveTo(n,u),t.lineTo(n-lp,d),t.lineTo(n+lp,d),t.closePath();let f=l?o:s;!i.reason||i.reason===`order`?(t.fillStyle=f,t.fill()):(t.strokeStyle=f,t.stroke())}}var mp=1e3,hp=class{orders=[];positions=[];depthData=null;currentPrice=null;config;orderRenderer=new Rf;positionRenderer=new qf;depthOverlay=new Jf;dragHandler;contextMenu=new Xf;bracket=new ep;orderDraft=new op;buttons=[];fills=[];realisedPnl=0;requestRender=null;eventCallback=null;container=null;constructor(e){this.config={...t.DEFAULT_TRADING_CONFIG,...e},this.dragHandler=new Yf(this.config.dragThreshold),this.contextMenu.onItemSelect=e=>{this.eventCallback?.(`orderPlace`,e)}}setContainer(e){this.container=e}setRequestRender(e){this.requestRender=e}setEventCallback(e){this.eventCallback=e}setOrders(e){this.orders=e,this.requestRender?.()}setPositions(e){this.positions=e,this.requestRender?.()}getOrders(){return[...this.orders]}getPositions(){return[...this.positions]}getCurrentPrice(){return this.currentPrice}setDepthData(e){this.depthData=e,this.requestRender?.()}setCurrentPrice(e){this.currentPrice=e,this.requestRender?.()}setConfig(e){Object.assign(this.config,e),this.requestRender?.()}addFill(e){this.fills=[...this.fills.slice(-(mp-1)),e],this.realisedPnl+=e.pnl??0,this.requestRender?.()}setFills(e){this.fills=e.slice(-mp),this.realisedPnl=e.reduce((e,t)=>e+(t.pnl??0),0),this.requestRender?.()}getRealisedPnl(){return this.realisedPnl}getFills(){return[...this.fills]}armed=null;isOverButton(e){return this.config.enabled&&Pf(this.buttons,e)!==null}runButton(e){switch(e.type){case`cancelOrder`:this.eventCallback?.(`orderCancel`,{orderId:e.orderId});break;case`closePosition`:this.eventCallback?.(`positionClose`,{positionId:e.positionId});break;case`reversePosition`:this.eventCallback?.(`positionReverse`,{positionId:e.positionId});break;case`removeStop`:this.eventCallback?.(`positionModify`,{positionId:e.positionId,[e.which]:null});break}}startBracket(e,t){this.bracket.start(e,t),this.requestRender?.()}cancelBracket(){this.bracket.isActive()&&(this.bracket.cancel(),this.requestRender?.())}confirmBracket(){let e=this.bracket.getDraft();return e?(this.eventCallback?.(`bracketPlace`,{side:e.side,entry:e.entry,stopLoss:e.stopLoss,takeProfit:e.takeProfit,riskReward:Qf(e)}),this.bracket.cancel(),this.requestRender?.(),!0):!1}isBracketActive(){return this.bracket.isActive()}startOrderDraft(e,t){this.orderDraft.start(e,t),this.requestRender?.()}cancelOrderDraft(){this.orderDraft.isActive()&&(this.orderDraft.cancel(),this.requestRender?.())}confirmOrderDraft(){let e=this.orderDraft.toIntent(this.currentPrice);return e?(this.eventCallback?.(`orderPlace`,e),this.orderDraft.cancel(),this.requestRender?.(),!0):!1}isOrderDraftActive(){return this.orderDraft.isActive()}isOverDraggableLine(t,n,r=8){if(!this.config.enabled)return!1;let i=i=>{if(i===void 0)return!1;let a=e.T(i,n);return jf(a,n)&&Math.abs(t.y-a)<=r};for(let e of this.orders)if(e.draggable!==!1&&i(e.price))return!0;for(let e of this.positions)if(i(e.stopLoss)||i(e.takeProfit))return!0;return!1}onPointerDown(e,t,n){if(!this.config.enabled)return!1;if(this.bracket.isActive()&&this.bracket.beginDrag(e,t,n?.handle)||this.orderDraft.isActive()&&this.orderDraft.beginDrag(e,t,n?.handle))return this.requestRender?.(),!0;let r=Pf(this.buttons,e,n?.button);return r?(this.armed=r.action,!0):this.dragHandler.onPointerDown(e,this.orders,this.positions,t,n?.order??8)}onPointerMove(e,t){if(this.armed)return!0;if(this.bracket.isDragging()){let n=this.bracket.drag(e,t);return n&&this.requestRender?.(),n}if(this.orderDraft.isDragging()){let n=this.orderDraft.drag(e,t);return n&&this.requestRender?.(),n}if(!this.dragHandler.isActive())return!1;let n=this.dragHandler.onPointerMove(e,t);return n&&this.requestRender?.(),n}onPointerUp(e){if(this.armed){let t=this.armed;this.armed=null;let n=e?Pf(this.buttons,e):null;return n&&Nf(n.action,t)&&this.runButton(t),!0}if(this.bracket.isDragging())return this.bracket.endDrag(),this.requestRender?.(),!0;if(this.orderDraft.isDragging())return this.orderDraft.endDrag(),this.requestRender?.(),!0;let t=this.dragHandler.onPointerUp();return t?(t.sourceType===`order`?this.eventCallback?.(`orderModify`,{orderId:t.id,newPrice:t.newPrice,previousPrice:t.previousPrice}):this.eventCallback?.(`positionModify`,{positionId:t.id,[t.sourceType]:t.newPrice}),this.requestRender?.(),!0):!1}cancelPointer(){let e=!1;return this.armed&&(this.armed=null,e=!0),this.bracket.isDragging()&&(this.bracket.cancelDrag(),e=!0),this.orderDraft.isDragging()&&(this.orderDraft.cancelDrag(),e=!0),this.dragHandler.cancel()&&(e=!0),e&&this.requestRender?.(),e}onContextMenu(n,r){if(!this.config.enabled||!this.config.contextMenu?.enabled||!this.container)return!1;let i=e.M(n.y,r);return this.contextMenu.show(n,i,this.container,this.config,e=>(0,t.priceTagText)(e,r,this.config.pricePrecision)),!0}render(e,t,n){if(this.buttons=[],!this.config.enabled)return;let{chartRect:r}=t;e.save();try{e.beginPath(),e.rect(r.x,r.y,r.width,r.height),e.clip(),this.renderInPlot(e,t,n)}finally{e.restore()}}renderInPlot(e,t,n){let r=Ys(this.config,n);this.depthData&&this.depthOverlay.render(e,this.depthData,t,r),r.fillMarks!==!1&&pp(e,this.fills,t,r),this.positions.length>0&&this.positionRenderer.render(e,this.positions,this.currentPrice,t,n,r,this.buttons),this.orders.length>0&&this.orderRenderer.render(e,this.orders,t,n,r,this.dragHandler.getDragState(),this.buttons),this.bracket.isActive()&&this.bracket.render(e,t,n,this.config.pricePrecision),this.orderDraft.isActive()&&this.orderDraft.render(e,t,n,this.currentPrice,this.config.pricePrecision)}renderAxisBadges(e,t,n){if(!this.config.enabled)return;let r=Ys(this.config,n);this.positions.length>0&&this.positionRenderer.renderAxisBadges(e,this.positions,t,n,r),this.orders.length>0&&this.orderRenderer.renderAxisBadges(e,this.orders,t,n,r,this.dragHandler.getDragState())}axisTagYs(t){if(!this.config.enabled)return[];let n=this.dragHandler.getDragState(),r=this.positions.map(n=>e.T(n.entryPrice,t));for(let i of this.orders){let a=n?.orderId===i.id&&n.sourceType===`order`?n.currentPrice:i.price;r.push(e.T(a,t))}let{chartRect:i}=t;return r.filter(e=>e>=i.y&&e<=i.y+i.height)}destroy(){this.contextMenu.destroy()}},gp=class{constructor(e){this.manager=e}render(e,t,n){this.manager.render(e,t,n)}renderAxisBadges(e,t,n){this.manager.renderAxisBadges(e,t,n)}axisTagYs(e){return this.manager.axisTagYs(e)}},_p=class{name=`paper`;state=`disconnected`;listeners=new Map;orders=[];positions=[];markPrice;markTime;seq=0;constructor(e={}){this.markPrice=e.markPrice??0}connect(e){this.state=`connected`,this.emit(`connectionChange`,this.state),this.emit(`orders`,this.orders),this.emit(`positions`,this.positions)}disconnect(){this.state=`disconnected`,this.emit(`connectionChange`,this.state)}getConnectionState(){return this.state}setMarkPrice(e,t){this.markPrice=e,this.markTime=t!==void 0&&Number.isFinite(t)?t:void 0,this.checkPendingOrders(),this.checkStops()}fillTime(){return this.markTime??Date.now()}getOrders(){return[...this.orders]}getPositions(){return[...this.positions]}async placeOrder(e){let t={id:this.nextId(`ord`),side:e.side,type:e.type,price:e.price,stopPrice:e.stopPrice,quantity:e.quantity??1,label:e.type===`market`?void 0:yp(e.type),draggable:!0,stopLoss:e.stopLoss,takeProfit:e.takeProfit,timeInForce:e.timeInForce};return e.type===`market`?this.fill(t,this.markPrice||e.price):(this.orders=[...this.orders,t],this.emit(`orders`,this.orders)),t}async modifyOrder(e){this.orders=this.orders.map(t=>t.id===e.orderId?{...t,price:e.newPrice}:t),this.emit(`orders`,this.orders)}async cancelOrder(e){this.orders=this.orders.filter(t=>t.id!==e.orderId),this.emit(`orders`,this.orders)}async modifyPosition(e){let t=(e,t)=>e===void 0?t:e??void 0;this.positions=this.positions.map(n=>n.id===e.positionId?{...n,stopLoss:t(e.stopLoss,n.stopLoss),takeProfit:t(e.takeProfit,n.takeProfit)}:n),this.emit(`positions`,this.positions)}async closePosition(e){let t=this.positions.find(t=>t.id===e.positionId);t&&(this.close(t,this.markPrice||t.entryPrice,`close`),this.emit(`positions`,this.positions))}async reversePosition(e){let t=this.positions.find(t=>t.id===e.positionId);if(!t)return;let n=this.markPrice||t.entryPrice;this.close(t,n,`reverse`);let r=t.quantity-(t.closedQuantity??0),i={id:this.nextId(`ord`),side:vp(t.side),type:`market`,price:n,quantity:r};this.fill(i,n)}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear(),this.orders=[],this.positions=[]}fill(e,t){this.orders=this.orders.filter(t=>t.id!==e.id);let n={id:this.nextId(`pos`),side:e.side,entryPrice:t,quantity:e.quantity,stopLoss:e.stopLoss,takeProfit:e.takeProfit};this.positions=[...this.positions,n];let r={orderId:e.id,side:e.side,price:t,quantity:e.quantity,time:this.fillTime(),positionId:n.id,reason:`order`};this.emit(`fill`,r),this.emit(`orders`,this.orders),this.emit(`positions`,this.positions)}close(e,t,n){this.positions=this.positions.filter(t=>t.id!==e.id);let r=e.quantity-(e.closedQuantity??0),i=e.side===`buy`?1:-1;this.emit(`fill`,{orderId:this.nextId(`ord`),side:vp(e.side),price:t,quantity:r,time:this.fillTime(),positionId:e.id,reason:n,pnl:(t-e.entryPrice)*r*i})}checkPendingOrders(){let e=this.orders.filter(e=>this.isTriggered(e));for(let t of e)this.fill(t,t.type===`limit`?t.price:t.stopPrice??t.price)}isTriggered(e){if(e.type===`limit`)return e.side===`buy`?this.markPrice<=e.price:this.markPrice>=e.price;if(e.type===`stop`||e.type===`stopLimit`){let t=e.stopPrice??e.price;return e.side===`buy`?this.markPrice>=t:this.markPrice<=t}return!1}checkStops(){let e=!1;for(let t of[...this.positions]){let n=t.stopLoss!==void 0&&(t.side===`buy`?this.markPrice<=t.stopLoss:this.markPrice>=t.stopLoss),r=t.takeProfit!==void 0&&(t.side===`buy`?this.markPrice>=t.takeProfit:this.markPrice<=t.takeProfit);!n&&!r||(this.close(t,n?t.stopLoss:t.takeProfit,n?`stopLoss`:`takeProfit`),e=!0)}e&&this.emit(`positions`,this.positions)}nextId(e){return`${e}-${++this.seq}`}emit(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}};function vp(e){return e===`buy`?`sell`:`buy`}function yp(e){switch(e){case`stop`:return`STOP`;case`stopLimit`:return`STOP LIMIT`;default:return`LIMIT`}}var bp=class{listeners=new Map;on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>n.delete(t)}once(e,t){let n=this.on(e,e=>{n(),t(e)});return n}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){let n=this.listeners.get(e);if(n)for(let e of n)e(t)}removeAllListeners(){this.listeners.clear()}},xp=class extends bp{currentBar=null;timeframeMs;tickRing;ringHead=0;ringCount=0;ringCapacity;constructor(e,n=1e3){super(),this.timeframeMs=(0,t.timeframeToMs)(e),this.ringCapacity=n,this.tickRing=Array(n)}setTimeframe(e){this.timeframeMs=(0,t.timeframeToMs)(e),this.currentBar=null,this.ringHead=0,this.ringCount=0}processTick(e){let t=(this.ringHead+this.ringCount)%this.ringCapacity;this.tickRing[t]=e,this.ringCount<this.ringCapacity?this.ringCount++:this.ringHead=(this.ringHead+1)%this.ringCapacity;let n=this.alignToTimeframe(e.time);!this.currentBar||this.currentBar.time!==n?(this.currentBar&&(this.currentBar.closed=!0,this.emit(`barClose`,this.currentBar)),this.currentBar={time:n,open:e.price,high:e.price,low:e.price,close:e.price,volume:e.volume,closed:!1,tickCount:1}):(this.currentBar.high=Math.max(this.currentBar.high,e.price),this.currentBar.low=Math.min(this.currentBar.low,e.price),this.currentBar.close=e.price,this.currentBar.volume+=e.volume,this.currentBar.tickCount++),this.emit(`bar`,this.currentBar)}processBar(e,t){if(t&&this.currentBar&&this.currentBar.time===e.time)this.currentBar={...e,closed:!0,tickCount:this.currentBar.tickCount+1},this.emit(`barClose`,this.currentBar),this.currentBar=null;else if(!t)this.currentBar={...e,closed:!1,tickCount:(this.currentBar?.tickCount??0)+1},this.emit(`bar`,this.currentBar);else{let t={...e,closed:!0,tickCount:1};this.emit(`barClose`,t),this.currentBar=null}}getCurrentBar(){return this.currentBar?{...this.currentBar}:null}getTickBuffer(){let e=Array(this.ringCount);for(let t=0;t<this.ringCount;t++)e[t]=this.tickRing[(this.ringHead+t)%this.ringCapacity];return e}reset(){this.currentBar=null,this.ringHead=0,this.ringCount=0}alignToTimeframe(e){return this.timeframeMs>0?Math.floor(e/this.timeframeMs)*this.timeframeMs:e}},Sp=class extends bp{config;attempt=0;timer=null;active=!1;constructor(e){super(),this.config={...t.DEFAULT_RECONNECT,...e}}schedule(e){if(!this.config.enabled||!this.active)return;if(this.cancel(),this.attempt++,this.attempt>this.config.maxRetries){this.emit(`giveUp`,{attempts:this.attempt-1}),this.active=!1;return}let t=this.computeDelay();this.emit(`attempt`,{attempt:this.attempt,delay:t}),this.timer=setTimeout(()=>{this.timer=null,this.active&&e()},t)}onConnected(){this.attempt=0,this.cancel(),this.emit(`success`,void 0)}start(){this.active=!0}stop(){this.active=!1,this.cancel(),this.attempt=0}cancel(){this.timer&&=(clearTimeout(this.timer),null)}getAttempt(){return this.attempt}isActive(){return this.active}computeDelay(){let e=this.config.baseDelay,t=this.config.backoffMultiplier**(this.attempt-1),n=Math.min(e*t,this.config.maxDelay),r=n*.25*(Math.random()*2-1);return Math.max(0,Math.round(n+r))}},Cp=20,wp=class{price=null;previousClose=null;visible=!0;flashUntil=0;pricePrecision=null;locale=`en-US`;tag=null;setLocale(e){this.locale=e}setPrice(e,t){this.price!==null&&e!==this.price&&(this.flashUntil=Date.now()+300),this.previousClose=t??this.price??e,this.price=e}setVisible(e){this.visible=e}isVisible(){return this.visible}setPricePrecision(e){this.pricePrecision=e}getPrice(){return this.price}getTag(){return this.tag}render(n,r,i){this.tag=null;let a=i.style?.lastPrice;if(!this.visible||this.price===null||a?.visible===!1)return;let o=e.T(this.price,r),{chartRect:s}=r;if(o<s.y||o>s.y+s.height)return;let c=this.previousClose===null||this.price>=this.previousClose?a?.up??i.candleUp??`#1fa874`:a?.down??i.candleDown??`#e8505b`,l=Date.now()<this.flashUntil,u=a?.width??1;n.setLineDash((0,t.lineDash)(a?.style??`solid`,[4,3],u)),n.strokeStyle=c,n.lineWidth=u,n.globalAlpha=l?1:.7,n.beginPath(),n.moveTo(s.x,Math.round(o)+.5),n.lineTo(s.x+s.width,Math.round(o)+.5),n.stroke(),n.setLineDash([]),n.globalAlpha=1;let d=s.x+s.width+1,f=this.pricePrecision??(0,t.autoPricePrecision)(r.priceRange.min,r.priceRange.max),p=r.formatPrice?r.formatPrice(this.price):(0,t.formatPrice)(this.price,f,this.locale);n.font=`bold 11px ${i.font.family}`;let m=n.measureText(p).width,h=r.priceAxisWidth??t.PRICE_AXIS_WIDTH,g=Math.min(m+12,h-2);n.fillStyle=c,w(n,d,o-Cp/2,g,Cp,i),this.tag={x:d,y:o-Cp/2,width:g,height:Cp,color:c};let _=d-5;n.beginPath(),n.moveTo(_,o),n.lineTo(_+5,o-5),n.lineTo(_+5,o+5),n.closePath(),n.fill(),n.fillStyle=O(c),n.textBaseline=`middle`,n.textAlign=`left`,n.fillText(p,d+5,o)}},Tp=1e3,Ep=10,Dp=1440,Op=[`tick`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],kp=new WeakMap;function Ap(e){if(e instanceof Fp||!e.supportedTimeframes?.length)return e;let t=kp.get(e);return t||(t=new Fp(e,e.supportedTimeframes),kp.set(e,t)),t}function jp(e,n){if(n.includes(e))return e;let r=(0,t.pickBaseTimeframe)(e,n);return r&&Math.ceil((0,t.timeframeToMs)(e)/(0,t.timeframeToMs)(r))<=1440?r:null}function Mp(e,n){if((0,t.tickBarCount)(n)!==null)return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`;let r=e.supportedTimeframes;return!r?.length||jp(n,r)!==null}function Np(e,n){let r=(0,t.parseTimeframe)(n);if(r?.unit===`M`){let t=new Date(e);return Date.UTC(t.getUTCFullYear(),t.getUTCMonth()+r.count,1)}return e+(0,t.timeframeToMs)(n)}function Pp(e,t){let n=t[0],r={time:e,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume};for(let e=1;e<t.length;e++){let n=t[e];n.high>r.high&&(r.high=n.high),n.low<r.low&&(r.low=n.low),r.close=n.close,r.volume+=n.volume}return r}var Fp=class{name;fetchHistoryBefore;searchSymbols;resolveSymbol;subscribeQuotes;fetchNews;fetchTrades;subscribeTrades;listeners=new Map;unsubscribe=[];live=null;bucket=null;parts=new Map;tail=null;generation=0;constructor(e,t){this.inner=e,this.baseTimeframes=t,this.name=e.name,e.fetchHistoryBefore&&(this.fetchHistoryBefore=(e,t,n,r)=>this.historyBefore(e,t,n,r)),e.searchSymbols&&(this.searchSymbols=e.searchSymbols.bind(e)),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol.bind(e)),e.subscribeQuotes&&(this.subscribeQuotes=e.subscribeQuotes.bind(e)),e.fetchNews&&(this.fetchNews=e.fetchNews.bind(e)),e.fetchTrades&&(this.fetchTrades=e.fetchTrades.bind(e)),e.subscribeTrades&&(this.subscribeTrades=e.subscribeTrades.bind(e)),this.listen(`bar`,e=>this.onBar(e));for(let e of Op)this.listen(e,t=>this.emit(e,t.data))}baseFor(e){let t=jp(e,this.baseTimeframes);if(!t)throw RangeError(`${this.name} cannot serve the ${e} timeframe`);return t}connect(e){let t=this.baseFor(e.timeframe);this.generation++,this.resetBucket(),this.live=t===e.timeframe?null:{symbol:e.symbol,target:e.timeframe,base:t},this.live&&this.resumeFromHistory(this.live.symbol,this.live.target),this.inner.connect({...e,timeframe:t})}disconnect(){this.generation++,this.inner.disconnect(),this.resetBucket(),this.live=null}getConnectionState(){return this.inner.getConnectionState()}async fetchHistory(e,t,n=500){let r=this.baseFor(t);if(r===t)return this.inner.fetchHistory(e,t,n);let i=this.generation,a=this.baseBarsFor(t,r,n),o=await this.inner.fetchHistory(e,r,Math.min(a,Tp)),s=await this.extendBack(e,r,o,a,i);return this.rememberTail(e,t,s),this.toTarget(s,t,n)}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.generation++;for(let e of this.unsubscribe)e();this.unsubscribe.length=0,this.listeners.clear(),this.inner.dispose()}async historyBefore(e,t,n,r){let i=this.inner.fetchHistoryBefore.bind(this.inner),a=this.baseFor(t);if(a===t)return i(e,t,n,r);let o=this.generation,s=this.baseBarsFor(t,a,r),c=await i(e,a,n,Math.min(s,Tp)),l=await this.extendBack(e,a,c.filter(e=>e.time<n),s,o,1);return this.toTarget(l,t,r)}baseBarsFor(e,n,r){return(r+1)*Math.ceil((0,t.timeframeToMs)(e)/(0,t.timeframeToMs)(n))}async extendBack(e,t,n,r,i,a=1){let o=this.inner.fetchHistoryBefore?.bind(this.inner),s=n,c=a;for(;o&&s.length>0&&s.length<r&&c<10&&i===this.generation;){let n=s[0].time,i=await o(e,t,n,Math.min(r-s.length,Tp));c++;let a=i.filter(e=>e.time<n);if(a.length===0)break;s=a.concat(s)}return s}toTarget(e,n,r){if(e.length===0)return[];let i=(0,t.resampleBars)(e,n);return i.length>1&&i[0].time!==e[0].time&&i.shift(),i.length>r?i.slice(i.length-r):i}rememberTail(e,n,r){if(r.length===0)return;let i=(0,t.timeframeBucketStart)(r[r.length-1].time,n),a=r.length;for(;a>0&&(0,t.timeframeBucketStart)(r[a-1].time,n)===i;)a--;this.tail={symbol:e,target:n,bucket:i,bars:r.slice(a)}}resumeFromHistory(e,t){let n=this.tail;if(!(!n||n.symbol!==e||n.target!==t)){this.bucket=n.bucket;for(let e of n.bars)this.parts.set(e.time,e)}}onBar(e){let n=this.live;if(!n){this.emit(`bar`,e.data);return}let{bar:r,closed:i}=e.data,a=(0,t.timeframeBucketStart)(r.time,n.target);if(this.bucket!==null&&a<this.bucket)return;if(this.bucket!==null&&a>this.bucket){let e=this.composed();e&&this.emit(`bar`,{bar:e,closed:!0}),this.resetBucket()}this.bucket=a,this.parts.set(r.time,r);let o=this.composed();if(!o)return;let s=i&&(0,t.timeframeBucketStart)(Np(r.time,n.base),n.target)!==a;this.emit(`bar`,{bar:o,closed:s}),s&&(this.resetBucket(),this.bucket=(0,t.timeframeBucketStart)(Np(r.time,n.base),n.target))}composed(){if(this.bucket===null||this.parts.size===0)return null;let e=[...this.parts.values()].sort((e,t)=>e.time-t.time);return Pp(this.bucket,e)}resetBucket(){this.bucket=null,this.parts=new Map}listen(e,t){let n=e=>t(e);this.inner.on(e,n),this.unsubscribe.push(()=>this.inner.off(e,n))}emit(e,t){let n=this.listeners.get(e);if(!n)return;let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}},Ip=1e3,Lp=15e3,Rp=[`tick`,`bar`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],zp=class{bar=null;count=0;lastTime=-1/0;constructor(e){this.tradesPerBar=e}push(e){let t=[],n=!1;for(let r of e){if(this.bar)this.bar={...this.bar,high:Math.max(this.bar.high,r.price),low:Math.min(this.bar.low,r.price),close:r.price,volume:this.bar.volume+r.volume};else{let e=Math.max(r.time,this.lastTime+1);this.lastTime=e,this.bar={time:e,open:r.price,high:r.price,low:r.price,close:r.price,volume:r.volume},this.count=0}this.count++,n=!0,this.count>=this.tradesPerBar&&(t.push({bar:this.bar,closed:!0}),this.bar=null,n=!1)}return n&&this.bar&&t.push({bar:this.bar,closed:!1}),t}build(e){return this.bar=null,this.count=0,this.lastTime=-1/0,this.push(e).map(e=>e.bar)}},Bp=class{name;supportedTimeframes;searchSymbols;resolveSymbol;subscribeQuotes;fetchNews;fetchTrades;subscribeTrades;listeners=new Map;tick=null;stopTrades=null;keepAlive=null;tickMode=!1;state=`disconnected`;constructor(e){this.inner=e,this.name=e.name,this.supportedTimeframes=e.supportedTimeframes,e.searchSymbols&&(this.searchSymbols=e.searchSymbols.bind(e)),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol.bind(e)),e.subscribeQuotes&&(this.subscribeQuotes=e.subscribeQuotes.bind(e)),e.fetchNews&&(this.fetchNews=e.fetchNews.bind(e)),this.fetchTrades=e.fetchTrades.bind(e),this.subscribeTrades=e.subscribeTrades.bind(e);for(let t of Rp)e.on(t,e=>{this.tickMode||this.emit(t,e.data)})}async fetchHistory(e,n,r){let i=(0,t.tickBarCount)(n);if(i===null)return this.inner.fetchHistory(e,n,r);let a=(await this.inner.fetchTrades(e,Ip)).filter(Wp).sort((e,t)=>e.time-t.time),o=new zp(i),s=o.build(a);return this.tick={symbol:e,builder:o,after:a.length?a[a.length-1].time:-1/0},r!==void 0&&r>0?s.slice(-r):s}fetchHistoryBefore(e,n,r,i){return(0,t.tickBarCount)(n)!==null||!this.inner.fetchHistoryBefore?Promise.resolve([]):this.inner.fetchHistoryBefore(e,n,r,i)}connect(e){this.disconnect();let n=(0,t.tickBarCount)(e.timeframe);if(n===null){this.tickMode=!1,this.inner.connect(e);return}this.tickMode=!0;let r=this.tick?.symbol===e.symbol?this.tick:{symbol:e.symbol,builder:new zp(n),after:-1/0};this.tick=r,this.stopTrades=this.inner.subscribeTrades(e.symbol,e=>{let t=e.filter(e=>Wp(e)&&e.time>=r.after);for(let{bar:e,closed:n}of r.builder.push(t))this.emit(`bar`,{bar:e,closed:n}),this.emit(`tick`,{time:e.time,price:e.close,volume:e.volume})}),this.state=`connected`,this.emit(`connectionChange`,`connected`),this.keepAlive=setInterval(()=>this.emit(`connectionChange`,`connected`),Lp)}disconnect(){this.tickMode?(this.stopTrades?.(),this.stopTrades=null,this.keepAlive&&clearInterval(this.keepAlive),this.keepAlive=null,this.state=`disconnected`):this.inner.disconnect()}getConnectionState(){return this.tickMode?this.state:this.inner.getConnectionState()}dispose(){this.stopTrades?.(),this.stopTrades=null,this.keepAlive&&clearInterval(this.keepAlive),this.keepAlive=null,this.listeners.clear(),this.inner.dispose()}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){let n=this.listeners.get(e);if(!n)return;let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}},Vp=new WeakMap;function Hp(e){if(e instanceof Bp||!Up(e))return e;let t=Vp.get(e);return t||(t=new Bp(e),Vp.set(e,t)),t}function Up(e){return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`}function Wp(e){return Number.isFinite(e?.time)&&Number.isFinite(e?.price)&&Number.isFinite(e?.volume)}var Gp=2e4,Kp=class extends bp{config=null;adapter=null;aggregator=null;reconnector;priceLine=new wp;state=`disconnected`;lastPrice=null;previousClose=null;unsubscribers=[];heartbeatTimer=null;lastMessageTime=0;connectSeq=0;constructor(){super(),this.reconnector=new Sp,this.wireReconnector()}async connect(e){this.disconnect();let n=Hp(Ap(e.adapter));this.config={...t.DEFAULT_STREAM_CONFIG,...e,adapter:n},this.adapter=n,this.aggregator=new xp(e.timeframe),this.reconnector.removeAllListeners(),this.reconnector.stop(),this.reconnector=new Sp(e.reconnect??t.DEFAULT_RECONNECT),this.wireReconnector(),this.aggregator.on(`bar`,e=>{this.emit(`barUpdate`,e),this.updatePrice(e.close)}),this.aggregator.on(`barClose`,e=>{this.previousClose=e.close,this.emit(`barClose`,e)}),this.wireAdapter(),this.reconnector.start(),await this.doConnect()}disconnect(){this.connectSeq++,this.reconnector.stop(),this.stopHeartbeat();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.adapter&&=(this.adapter.disconnect(),null),this.aggregator?.reset(),this.aggregator?.removeAllListeners(),this.aggregator=null,this.config=null,this.lastPrice=null,this.previousClose=null,this.setState(`disconnected`)}async switchTo(e,t){!this.config||!this.adapter||(this.reconnector.stop(),this.adapter.disconnect(),this.reconnector.start(),this.aggregator?.reset(),this.aggregator?.setTimeframe(t),this.lastPrice=null,this.previousClose=null,this.config.symbol=e,this.config.timeframe=t,await this.doConnect())}getConnectionState(){return this.state}getConnectionInfo(){return{state:this.state,reconnectAttempt:this.reconnector.getAttempt(),lastMessageTime:this.lastMessageTime}}getLastPrice(){return this.lastPrice}async doConnect(){if(!this.config||!this.adapter)return;let e=++this.connectSeq,{symbol:t,timeframe:n}=this.config;this.setState(`connecting`);try{let r=await this.adapter.fetchHistory(t,n,this.config.historyLimit??500);if(e!==this.connectSeq||!this.adapter)return;r.length>0&&(this.previousClose=r[r.length-1].close,this.updatePrice(r[r.length-1].close)),this.emit(`snapshot`,r),this.adapter.connect({symbol:t,timeframe:n}),this.startHeartbeat()}catch(t){if(e!==this.connectSeq)return;let n=t instanceof Error?t.message:String(t);this.emit(`error`,{message:n,code:`CONNECT_FAILED`}),this.setState(`error`),this.reconnector.schedule(()=>this.doConnect())}}wireReconnector(){this.reconnector.on(`attempt`,({attempt:e,delay:t})=>{this.setState(`reconnecting`),this.emit(`connectionChange`,{state:`reconnecting`,reconnectAttempt:e,lastMessageTime:this.lastMessageTime})}),this.reconnector.on(`giveUp`,({attempts:e})=>{this.setState(`error`),this.emit(`error`,{message:`Reconnection failed after ${e} attempts`,code:`RECONNECT_EXHAUSTED`})})}wireAdapter(){if(!this.adapter)return;let e=this.adapter,t=e=>{let t=e.data;this.lastMessageTime=Date.now(),t===`connected`?(this.reconnector.onConnected(),this.setState(`connected`)):(t===`disconnected`||t===`error`)&&this.reconnector.schedule(()=>this.doConnect())};e.on(`connectionChange`,t),this.unsubscribers.push(()=>e.off(`connectionChange`,t));let n=e=>{this.lastMessageTime=Date.now();let t=e.data;this.emit(`tick`,t),(t.bid!==void 0||t.ask!==void 0)&&this.emit(`quote`,{bid:t.bid,ask:t.ask}),this.config?.aggregateTicks&&this.aggregator?this.aggregator.processTick(t):this.updatePrice(t.price)};e.on(`tick`,n),this.unsubscribers.push(()=>e.off(`tick`,n));let r=e=>{this.lastMessageTime=Date.now();let{bar:t,closed:n}=e.data;this.aggregator&&this.aggregator.processBar(t,n)};e.on(`bar`,r),this.unsubscribers.push(()=>e.off(`bar`,r));let i=e=>{this.emit(`error`,{message:e.data?.message??`Adapter error`})};e.on(`error`,i),this.unsubscribers.push(()=>e.off(`error`,i));let a=e=>{e?.data&&typeof e.data==`object`&&this.emit(`symbolInfo`,e.data)};try{e.on(`symbolInfo`,a),this.unsubscribers.push(()=>e.off(`symbolInfo`,a))}catch{}}updatePrice(e){e!==this.lastPrice&&(this.lastPrice=e,this.priceLine.setPrice(e,this.previousClose??void 0),this.emit(`priceChange`,{price:e,previousClose:this.previousClose}))}setState(e){this.state!==e&&(this.state=e,this.emit(`connectionChange`,{state:e,reconnectAttempt:this.reconnector.getAttempt(),lastMessageTime:this.lastMessageTime}))}wake(e){!this.adapter||!this.config||this.state===`connecting`||this.state===`disconnected`||this.state===`connected`&&e===`visible`&&Date.now()-this.lastMessageTime<=Gp||(this.reconnector.stop(),this.adapter.disconnect(),this.reconnector.start(),this.doConnect())}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{Date.now()-this.lastMessageTime>6e4&&this.state===`connected`&&(this.emit(`error`,{message:`Heartbeat timeout`,code:`HEARTBEAT_TIMEOUT`}),this.adapter?.disconnect(),this.reconnector.schedule(()=>this.doConnect()))},3e4)}stopHeartbeat(){this.heartbeatTimer&&=(clearInterval(this.heartbeatTimer),null)}dispose(){this.disconnect(),this.removeAllListeners()}},qp=class extends bp{data;speed;index;status=`idle`;timer=null;constructor(e){if(super(),e.data.length===0)throw Error(`ReplayController requires non-empty data`);this.data=e.data,this.speed=Math.max(.01,e.speed??1),this.index=Math.max(0,Math.min(e.startIndex??0,e.data.length)),e.autoStart&&this.start()}getStatus(){return this.status}getIndex(){return this.index}getTotal(){return this.data.length}getPrefix(){return this.data.slice(0,this.index)}start(){if(this.status!==`playing`){if(this.index>=this.data.length){this.transition(`finished`);return}this.transition(`playing`),this.scheduleNext()}}pause(){this.status===`playing`&&(this.clearTimer(),this.transition(`paused`))}resume(){this.status===`paused`&&this.start()}stop(){this.clearTimer(),this.index=0,this.transition(`idle`)}step(e=1){if(!(e<=0)){this.clearTimer();for(let t=0;t<e;t++)if(!this.emitNext())return;this.status!==`finished`&&this.transition(`paused`)}}seek(e){let t=Math.max(0,Math.min(e,this.data.length));this.clearTimer(),this.index=t;let n=t>=this.data.length?`finished`:`paused`;this.transition(n)}setSpeed(e){this.speed=Math.max(.01,e),this.status===`playing`&&(this.clearTimer(),this.scheduleNext())}destroy(){this.clearTimer(),this.removeAllListeners()}scheduleNext(){let e=1e3/this.speed;this.timer=setTimeout(()=>{this.timer=null,this.status===`playing`&&this.emitNext()&&this.scheduleNext()},e)}emitNext(){if(this.index>=this.data.length)return this.transition(`finished`),this.emit(`finished`,{total:this.data.length}),!1;let e=this.data[this.index],t=this.index;return this.index++,this.emit(`bar`,{bar:e,index:t,total:this.data.length}),this.index>=this.data.length?(this.transition(`finished`),this.emit(`finished`,{total:this.data.length}),!1):!0}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}transition(e){this.status!==e&&(this.status=e,this.emit(`stateChange`,{status:e,index:this.index,total:this.data.length}))}};function Jp(e){if(!Array.isArray(e)||e.length<6)return null;let t=e[0];if(typeof t!=`number`||!Number.isFinite(t))return null;let n=Xp(e[1]),r=Xp(e[2]),i=Xp(e[3]),a=Xp(e[4]),o=Xp(e[5]);return n===null||r===null||i===null||a===null||o===null?null:{time:t,open:n,high:r,low:i,close:a,volume:o}}function Yp(e){if(!Zp(e))return null;let t=e.t;if(typeof t!=`number`||!Number.isFinite(t))return null;let n=Xp(e.o),r=Xp(e.h),i=Xp(e.l),a=Xp(e.c),o=Xp(e.v);if(n===null||r===null||i===null||a===null||o===null)return null;let s=typeof e.x==`boolean`?e.x:!1;return{bar:{time:t,open:n,high:r,low:i,close:a,volume:o},closed:s}}function Xp(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=parseFloat(e);return Number.isFinite(t)?t:null}return null}function Zp(e){return typeof e==`object`&&!!e}function J(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:void 0}function Qp(e){let n=e&&typeof e==`object`&&`data`in e?e.data:e;if(!n||typeof n!=`object`)return null;let r=n;return r.e===`24hrMiniTicker`?(0,t.readQuote)({symbol:r.s,last:J(r.c),open:J(r.o),high:J(r.h),low:J(r.l),volume:J(r.v),time:J(r.E)}):null}function $p(e){if(!e||typeof e!=`object`)return null;let n=e;return(0,t.readQuote)({symbol:n.symbol,last:J(n.lastPrice),change:J(n.priceChange),changePercent:J(n.priceChangePercent),open:J(n.openPrice),high:J(n.highPrice),low:J(n.lowPrice),prevClose:J(n.prevClosePrice),volume:J(n.volume),bid:J(n.bidPrice),ask:J(n.askPrice),time:J(n.closeTime)})}function em(e){if(!e||typeof e!=`object`)return null;let t=e,n=J(t.T),r=J(t.p),i=J(t.q);return n!==void 0&&r!==void 0&&i!==void 0?{time:n,price:r,volume:i}:null}var tm={"1s":`1s`,"1m":`1m`,"3m":`3m`,"5m":`5m`,"15m":`15m`,"30m":`30m`,"1h":`1h`,"2h":`2h`,"4h":`4h`,"6h":`6h`,"8h":`8h`,"12h":`12h`,"1d":`1d`,"3d":`3d`,"1w":`1w`,"1M":`1M`},nm=1e3,rm=200,im=[`USDT`,`USDC`,`FDUSD`,`BTC`,`ETH`,`BNB`,`EUR`,`TRY`,`BRL`,`JPY`];function am(e){let t=e.currency?im.indexOf(e.currency):-1;return t<0?0:40-t*3}function om(e){if(typeof e.symbol!=`string`||e.status!==`TRADING`)return null;let n=typeof e.baseAsset==`string`?e.baseAsset:``,r=typeof e.quoteAsset==`string`?e.quoteAsset:``,i=Array.isArray(e.filters)?e.filters.find(e=>typeof e==`object`&&!!e&&e.filterType===`PRICE_FILTER`&&typeof e.tickSize==`string`):void 0,a={symbol:e.symbol,description:n&&r?`${n} / ${r}`:e.symbol,exchange:`Binance`,type:`crypto`};return i&&(a.pricePrecision=(0,t.stepDecimals)(i.tickSize),a.minTick=Number(i.tickSize)),a.timezone=`UTC`,r&&(a.currency=r),a}function sm(e){let t=e?.symbols;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=om(e);t&&n.push(t)}return n}var cm=class{name=`binance`;supportedTimeframes=Object.keys(tm);ws=null;state=`disconnected`;listeners=new Map;config=null;restBase;wsBase;symbolList=null;constructor(e){this.restBase=e?.restBase??`https://api.binance.com/api/v3`,this.wsBase=e?.wsBase??`wss://stream.binance.com:9443/ws`}connect(e){this.config=e,this.connectWs()}disconnect(){if(this.ws){let e=this.ws;e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null,e.close(),this.ws=null}this.setState(`disconnected`)}getConnectionState(){return this.state}fetchHistory(e,t,n=500){return this.fetchKlines(e,t,n,``)}async searchSymbols(e,n){return(0,t.rankSymbols)(await this.loadSymbols(),e,n?.limit??50,am)}async resolveSymbol(e){if(this.symbolList){let t=(await this.symbolList.catch(()=>null))?.find(t=>t.symbol===e);if(t)return t}let t=await fetch(`${this.restBase}/exchangeInfo?symbol=${encodeURIComponent(e)}`);return t.ok?sm(await t.json())[0]??null:null}loadSymbols(){return this.symbolList||(this.symbolList=(async()=>{let e=await fetch(`${this.restBase}/exchangeInfo`);if(!e.ok)throw Error(`Binance REST error: ${e.status}`);return sm(await e.json())})(),this.symbolList.catch(()=>{this.symbolList=null})),this.symbolList}subscribeQuotes(e,t){let n=[...new Set(e.map(e=>e.trim().toUpperCase()))].filter(e=>/^[A-Z0-9]{2,30}$/.test(e)).slice(0,rm);if(n.length===0)return()=>{};let r=!1,i=null,a=null,o=0,s=new Set,c=new AbortController;(async()=>{let e=await fetch(`${this.restBase}/ticker/24hr?symbols=${encodeURIComponent(JSON.stringify(n))}`,{signal:c.signal});if(e.ok)return e.json();let t=await fetch(`${this.restBase}/ticker/24hr`,{signal:c.signal});if(!t.ok)return[];let r=await t.json(),i=new Set(n);return Array.isArray(r)?r.filter(e=>i.has(e?.symbol)):[]})().then(e=>{if(r||!Array.isArray(e))return;let n=e.map($p).filter(e=>e!==null&&!s.has(e.symbol));n.length>0&&t(n)}).catch(()=>{});let l=this.wsBase.replace(/\/ws\/?$/,``),u=()=>{if(!r){try{i=new WebSocket(`${l}/stream?streams=${n.map(e=>`${e.toLowerCase()}@miniTicker`).join(`/`)}`)}catch{d();return}i.onopen=()=>{o=0},i.onmessage=e=>{let n;try{n=JSON.parse(typeof e.data==`string`?e.data:``)}catch{return}let i=Qp(n);!i||r||(s.add(i.symbol),t([i]))},i.onclose=()=>{i=null,d()}}},d=()=>{r||(a=setTimeout(u,Math.min(3e4,1e3*2**o++)))};return u(),()=>{r=!0,c.abort(),a&&clearTimeout(a),i&&=(i.onopen=null,i.onmessage=null,i.onclose=null,i.close(),null)}}async fetchTrades(e,t=1e3){let n=Math.max(1,Math.min(1e3,Math.floor(t))),r=await fetch(`${this.restBase}/aggTrades?symbol=${encodeURIComponent(e.toUpperCase())}&limit=${n}`);if(!r.ok)throw Error(`Binance aggTrades ${r.status}`);let i=await r.json();return Array.isArray(i)?i.map(em).filter(e=>e!==null):[]}subscribeTrades(e,t){let n=`${e.trim().toLowerCase()}@aggTrade`;if(!/^[a-z0-9]{2,30}@aggTrade$/.test(n))return()=>{};let r=!1,i=null,a=null,o=0,s=()=>{if(!r){try{i=new WebSocket(`${this.wsBase}/${n}`)}catch{c();return}i.onopen=()=>{o=0},i.onmessage=e=>{let n;try{n=JSON.parse(typeof e.data==`string`?e.data:``)}catch{return}let i=em(n);i&&!r&&t([i])},i.onclose=()=>{i=null,c()}}},c=()=>{r||(a=setTimeout(s,Math.min(3e4,1e3*2**o++)))};return s(),()=>{r=!0,a&&clearTimeout(a),i&&=(i.onopen=null,i.onmessage=null,i.onclose=null,i.close(),null)}}fetchHistoryBefore(e,t,n,r=500){return this.fetchKlines(e,t,Math.min(r,nm),`&endTime=${Math.floor(n)-1}`)}async fetchKlines(e,t,n,r){let i=tm[t]??`15m`,a=`${this.restBase}/klines?symbol=${e}&interval=${i}&limit=${n}${r}`,o=await fetch(a);if(!o.ok)throw Error(`Binance REST error: ${o.status}`);let s=await o.json();if(!Array.isArray(s))return[];let c=[];for(let e of s){let t=Jp(e);t&&c.push(t)}return c}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}connectWs(){if(!this.config)return;let e=`${this.config.symbol.toLowerCase()}@kline_${tm[this.config.timeframe]??`15m`}`,t=`${this.wsBase}/${e}`;this.setState(`connecting`);try{this.ws=new WebSocket(t)}catch{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket creation failed`}),this.emitEvent(`connectionChange`,`error`);return}this.ws.onopen=()=>{this.setState(`connected`),this.emitEvent(`connectionChange`,`connected`)},this.ws.onmessage=e=>{let t;try{t=JSON.parse(typeof e.data==`string`?e.data:``)}catch{return}typeof t==`object`&&t&&t.e===`kline`&&this.handleKline(t.k)},this.ws.onerror=()=>{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket error`})},this.ws.onclose=()=>{this.setState(`disconnected`),this.emitEvent(`connectionChange`,`disconnected`)}}handleKline(e){let t=Yp(e);if(!t)return;let{bar:n,closed:r}=t;this.emitEvent(`bar`,{bar:n,closed:r}),this.emitEvent(`tick`,{time:Date.now(),price:n.close,volume:n.volume})}setState(e){this.state=e}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}},lm=class{name=`mock`;state=`disconnected`;listeners=new Map;config=null;options;tickTimer=null;currentPrice;oldestOpen=new Map;constructor(e){this.options={basePrice:100,volatility:1.5,tickInterval:2e3,historySize:500,...e},this.currentPrice=this.options.basePrice}connect(e){this.config=e,this.state=`connected`,this.emitEvent(`connectionChange`,`connected`),this.startTicking()}disconnect(){this.stopTicking(),this.state=`disconnected`,this.emitEvent(`connectionChange`,`disconnected`)}getConnectionState(){return this.state}subscribeQuotes(e,t){let n=[...new Set(e)].map(e=>{let t=this.options.basePrice*(.5+um(e)%1e3/1e3);return{symbol:e,open:t,last:t,high:t,low:t,volume:0}});if(n.length===0)return()=>{};let r=this.options.volatility/100,i=()=>t(n.map(e=>({symbol:e.symbol,last:e.last,open:e.open,high:e.high,low:e.low,volume:e.volume,change:e.last-e.open,changePercent:(e.last-e.open)/e.open*100,time:Date.now()})));i();let a=setInterval(()=>{for(let e of n)e.last=Math.max(e.open*.01,e.last*(1+(Math.random()-.5)*r)),e.high=Math.max(e.high,e.last),e.low=Math.min(e.low,e.last),e.volume+=Math.random()*100;i()},this.options.tickInterval);return()=>clearInterval(a)}async fetchTrades(e,t=1e3){let n=Math.max(1,Math.min(1e3,Math.floor(t))),r=Date.now(),i=this.options.volatility/1e3,a=this.options.basePrice*(.5+um(e)%1e3/1e3),o=[];for(let e=n-1;e>=0;e--)a=Math.max(a*.5,a*(1+(Math.random()-.5)*i)),o.push({time:r-e*1e3,price:a,volume:Math.random()*5});return o}subscribeTrades(e,t){let n=this.options.volatility/1e3,r=this.options.basePrice*(.5+um(e)%1e3/1e3),i=setInterval(()=>{let e=[];for(let t=0;t<3;t++)r=Math.max(r*.5,r*(1+(Math.random()-.5)*n)),e.push({time:Date.now(),price:r,volume:Math.random()*5});t(e)},this.options.tickInterval);return()=>clearInterval(i)}async fetchHistory(e,t,n){let r=this.options.historyGenerator?this.options.historyGenerator(e,t,n??this.options.historySize):this.generateHistory(t,n??this.options.historySize);return r.length>0&&this.oldestOpen.set(e,r[0].open),r}async fetchHistoryBefore(e,n,r,i){let a=(0,t.timeframeToMs)(n),o=this.options.volatility/100,s=Array(Math.max(0,i)),c=this.oldestOpen.get(e)??this.options.basePrice;for(let e=0;e<i;e++){let t=c/(1+(Math.random()-.52)*o),n=Math.max(t,c)+Math.random()*c*o*.3,l=Math.max(0,Math.min(t,c)-Math.random()*c*o*.3),u=Math.floor(1e4+Math.random()*1e5);s[i-1-e]={time:r-(e+1)*a,open:t,high:n,low:l,close:c,volume:u},c=t}return this.oldestOpen.set(e,c),s}async searchSymbols(e,n){return(0,t.rankSymbols)(this.options.symbols??[],e,n?.limit??50)}async resolveSymbol(e){return this.options.symbols?.find(t=>t.symbol===e)??null}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}generateHistory(e,n){let r=[],i=Date.now(),a=(0,t.timeframeToMs)(e),o=this.options.basePrice,s=this.options.volatility/100;for(let e=n-1;e>=0;e--){let t=i-e*a,n=(Math.random()-.48)*o*s,c=o;o+=n;let l=Math.max(c,o)+Math.random()*o*s*.3,u=Math.min(c,o)-Math.random()*o*s*.3,d=Math.floor(1e4+Math.random()*1e5);r.push({time:t,open:c,high:l,low:u,close:o,volume:d})}return this.currentPrice=o,r}startTicking(){this.stopTicking();let e=this.options.tickInterval??2e3;this.tickTimer=setInterval(()=>{if(this.state!==`connected`||!this.config)return;let e=this.options.volatility/100,n=(Math.random()-.48)*this.currentPrice*e*.3;this.currentPrice+=n;let r=Date.now(),i=(0,t.timeframeToMs)(this.config.timeframe),a={time:Math.floor(r/i)*i,open:this.currentPrice-n,high:Math.max(this.currentPrice,this.currentPrice-n)+Math.abs(n)*.2,low:Math.min(this.currentPrice,this.currentPrice-n)-Math.abs(n)*.2,close:this.currentPrice,volume:Math.floor(100+Math.random()*5e3)};this.emitEvent(`bar`,{bar:a,closed:!1}),this.emitEvent(`tick`,{time:r,price:this.currentPrice,volume:a.volume})},e)}stopTicking(){this.tickTimer&&=(clearInterval(this.tickTimer),null)}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}};function um(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t}var dm=class{name;supportedTimeframes;ws=null;state=`disconnected`;config=null;listeners=new Map;opts;fetchHistoryBefore;searchSymbols;resolveSymbol;constructor(e){this.opts=e,this.name=e.name,this.supportedTimeframes=e.supportedTimeframes;let t=e.fetchHistoryBefore;t&&(this.fetchHistoryBefore=(e,n,r,i)=>t(e,n,r,i)),e.searchSymbols&&(this.searchSymbols=e.searchSymbols),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol)}connect(e){this.config=e,this.openSocket()}disconnect(){let e=this.config;if(this.ws){if(this.opts.unsubscribeMessage&&e)try{this.sendMessage(this.opts.unsubscribeMessage(e))}catch{}let t=this.ws;t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,t.close(),this.ws=null}this.setState(`disconnected`)}getConnectionState(){return this.state}fetchHistory(e,t,n){return this.opts.fetchHistory(e,t,n??this.opts.defaultHistoryLimit??500)}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}openSocket(){let e=this.config;if(!e)return;let t=this.opts.wsUrl(e);this.setState(`connecting`);let n;try{n=this.createSocket(t)}catch{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket creation failed`}),this.emitEvent(`connectionChange`,`error`);return}this.ws=n,n.onopen=()=>{if(this.setState(`connected`),this.emitEvent(`connectionChange`,`connected`),this.opts.subscribeMessage)try{this.sendMessage(this.opts.subscribeMessage(e))}catch{}},n.onmessage=t=>{let n=this.decode(t.data);if(n===void 0)return;let r;try{r=this.opts.parseMessage(n,e)}catch{return}r&&(r.bar&&this.emitEvent(`bar`,{bar:r.bar,closed:r.closed??!1}),r.tick?this.emitEvent(`tick`,r.tick):r.bar&&this.emitEvent(`tick`,{time:Date.now(),price:r.bar.close,volume:r.bar.volume}))},n.onerror=()=>{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket error`})},n.onclose=()=>{this.setState(`disconnected`),this.emitEvent(`connectionChange`,`disconnected`)}}sendMessage(e){e===void 0||!this.ws||this.ws.send(typeof e==`string`?e:JSON.stringify(e))}decode(e){if(this.opts.decode)try{return this.opts.decode(e)}catch{return}if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}createSocket(e){if(this.opts.socketFactory)return this.opts.socketFactory(e);let t=globalThis.WebSocket;if(!t)throw Error(`No WebSocket implementation available`);return new t(e)}setState(e){this.state=e}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}},fm=class{name;supportedTimeframes;state=`disconnected`;listeners=new Map;config=null;timer=null;lastBarTime=0;opts;fetchHistoryBefore;searchSymbols;resolveSymbol;constructor(e){this.opts=e,this.name=e.name,this.supportedTimeframes=e.supportedTimeframes;let t=e.fetchHistoryBefore;t&&(this.fetchHistoryBefore=(e,n,r,i)=>t(e,n,r,i)),e.searchSymbols&&(this.searchSymbols=e.searchSymbols),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol)}connect(e){this.config=e,this.lastBarTime=0,this.state=`connected`,this.emitEvent(`connectionChange`,`connected`),this.startPolling()}disconnect(){this.stopPolling(),this.state=`disconnected`,this.emitEvent(`connectionChange`,`disconnected`)}getConnectionState(){return this.state}fetchHistory(e,t,n){return this.opts.fetchBars(e,t,n??this.opts.defaultHistoryLimit??500)}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}async poll(){let e=this.config;if(!e||this.state!==`connected`)return;let t;try{t=await this.opts.fetchBars(e.symbol,e.timeframe,this.opts.pollLimit??2)}catch(e){this.emitEvent(`error`,{message:`Poll failed`,cause:e});return}if(t.length===0)return;let n=t[t.length-1];if(this.lastBarTime>0&&n.time>this.lastBarTime){let e=t.find(e=>e.time===this.lastBarTime);e&&this.emitEvent(`bar`,{bar:e,closed:!0})}this.emitEvent(`bar`,{bar:n,closed:!1}),this.emitEvent(`tick`,{time:Date.now(),price:n.close,volume:n.volume}),this.lastBarTime=n.time}startPolling(){this.stopPolling(),this.poll();let e=this.opts.setInterval??((e,t)=>setInterval(e,t));this.timer=e(()=>{this.poll()},this.opts.intervalMs??5e3)}stopPolling(){this.timer!==null&&((this.opts.clearInterval??(e=>clearInterval(e)))(this.timer),this.timer=null)}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}};function Y(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=parseFloat(e);return Number.isFinite(t)?t:null}return null}function pm(e){return typeof e==`object`&&!!e}var mm={"1m":60,"5m":300,"15m":900,"1h":3600,"6h":21600,"1d":86400};function hm(e){return mm[e]??3600}var gm=class extends fm{constructor(e={}){let t=e.restBase??`https://api.exchange.coinbase.com`;super({name:`coinbase`,supportedTimeframes:Object.keys(mm),intervalMs:e.intervalMs??5e3,pollLimit:2,fetchBars:(e,n)=>_m(t,e,n)})}};async function _m(e,t,n){let r=`${e}/products/${t}/candles?granularity=${hm(n)}`,i=await fetch(r);if(!i.ok)throw Error(`Coinbase REST error: ${i.status}`);return vm(await i.json())}function vm(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=ym(n);e&&t.push(e)}return t.sort((e,t)=>e.time-t.time),t}function ym(e){if(!Array.isArray(e)||e.length<6)return null;let t=Y(e[0]),n=Y(e[1]),r=Y(e[2]),i=Y(e[3]),a=Y(e[4]),o=Y(e[5]);return t===null||n===null||r===null||i===null||a===null||o===null?null:{time:t*1e3,open:i,high:r,low:n,close:a,volume:o}}var bm={"1m":`1`,"3m":`3`,"5m":`5`,"15m":`15`,"30m":`30`,"1h":`60`,"2h":`120`,"4h":`240`,"6h":`360`,"12h":`720`,"1d":`D`,"1w":`W`,"1M":`M`};function xm(e){return bm[e]??`1`}var Sm=class extends dm{constructor(e={}){let t=e.restBase??`https://api.bybit.com`,n=e.wsBase??`wss://stream.bybit.com/v5/public/spot`,r=e.category??`spot`;super({name:`bybit`,wsUrl:()=>n,subscribeMessage:e=>({op:`subscribe`,args:[`kline.${xm(e.timeframe)}.${e.symbol}`]}),unsubscribeMessage:e=>({op:`unsubscribe`,args:[`kline.${xm(e.timeframe)}.${e.symbol}`]}),supportedTimeframes:Object.keys(bm),parseMessage:Cm,fetchHistory:(e,n,i)=>wm(t,r,e,n,i),fetchHistoryBefore:(e,n,i,a)=>wm(t,r,e,n,a,Math.floor(i)-1)})}};function Cm(e){if(!pm(e)||typeof e.topic!=`string`||!e.topic.startsWith(`kline.`))return null;let t=e.data;if(!Array.isArray(t)||t.length===0)return null;let n=t[t.length-1];if(!pm(n))return null;let r=Y(n.start),i=Y(n.open),a=Y(n.high),o=Y(n.low),s=Y(n.close),c=Y(n.volume);if(r===null||i===null||a===null||o===null||s===null||c===null)return null;let l=typeof n.confirm==`boolean`?n.confirm:!1;return{bar:{time:r,open:i,high:a,low:o,close:s,volume:c},closed:l}}async function wm(e,t,n,r,i,a){let o=`${e}/v5/market/kline?category=${t}&symbol=${n}&interval=${xm(r)}&limit=${Math.min(Math.max(i,1),1e3)}${a===void 0?``:`&end=${a}`}`,s=await fetch(o);if(!s.ok)throw Error(`Bybit REST error: ${s.status}`);return Tm(await s.json())}function Tm(e){if(!pm(e)||!pm(e.result))return[];let t=e.result.list;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=Em(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function Em(e){if(!Array.isArray(e)||e.length<6)return null;let t=Y(e[0]),n=Y(e[1]),r=Y(e[2]),i=Y(e[3]),a=Y(e[4]),o=Y(e[5]);return t===null||n===null||r===null||i===null||a===null||o===null?null:{time:t,open:n,high:r,low:i,close:a,volume:o}}var Dm={"1m":1,"5m":5,"15m":15,"30m":30,"1h":60,"4h":240,"1d":1440,"1w":10080};function Om(e){return Dm[e]??1}var km=class extends dm{constructor(e={}){let t=e.restBase??`https://api.kraken.com`,n=e.wsBase??`wss://ws.kraken.com/v2`;super({name:`kraken`,wsUrl:()=>n,subscribeMessage:e=>({method:`subscribe`,params:{channel:`ohlc`,symbol:[e.symbol],interval:Om(e.timeframe)}}),unsubscribeMessage:e=>({method:`unsubscribe`,params:{channel:`ohlc`,symbol:[e.symbol],interval:Om(e.timeframe)}}),supportedTimeframes:Object.keys(Dm),parseMessage:Am,fetchHistory:(e,n)=>jm(t,e,n)})}};function Am(e){if(!pm(e)||e.channel!==`ohlc`)return null;let t=e.data;if(!Array.isArray(t)||t.length===0)return null;let n=t[t.length-1];if(!pm(n))return null;let r=Y(n.open),i=Y(n.high),a=Y(n.low),o=Y(n.close),s=Y(n.volume),c=typeof n.interval_begin==`string`?Date.parse(n.interval_begin):NaN;return r===null||i===null||a===null||o===null||s===null||!Number.isFinite(c)?null:{bar:{time:c,open:r,high:i,low:a,close:o,volume:s},closed:!1}}async function jm(e,t,n){let r=Om(n),i=t.replace(`/`,``),a=`${e}/0/public/OHLC?pair=${encodeURIComponent(i)}&interval=${r}`,o=await fetch(a);if(!o.ok)throw Error(`Kraken REST error: ${o.status}`);return Mm(await o.json())}function Mm(e){if(!pm(e)||!pm(e.result))return[];let t=null;for(let[n,r]of Object.entries(e.result))if(n!==`last`&&Array.isArray(r)){t=r;break}if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=Nm(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function Nm(e){if(!Array.isArray(e)||e.length<7)return null;let t=Y(e[0]),n=Y(e[1]),r=Y(e[2]),i=Y(e[3]),a=Y(e[4]),o=Y(e[6]);return t===null||n===null||r===null||i===null||a===null||o===null?null:{time:t*1e3,open:n,high:r,low:i,close:a,volume:o}}var Pm={visible:!0,showSymbol:!0,showOHLC:!0,showChange:!0,showVolume:!0,position:`top-left`,fontSize:12,fontFamily:null},Fm=class{config={...Pm};symbol=``;timeframe=``;hoverBar=null;hoverPrev=null;indicators=[];statusText=null;exchange=``;drawnHeight=null;locale=`en-US`;pricePrecision=null;setConfig(e){Object.assign(this.config,e),this.drawnHeight=null}setPricePrecision(e){this.pricePrecision=e}setLocale(e){this.locale=e}setSymbol(e){this.symbol=e,this.drawnHeight=null}setTimeframe(e){this.timeframe=e,this.drawnHeight=null}setChartType(e){}setHoverBar(e,t=null){this.hoverBar=e,this.hoverPrev=e?t:null}setIndicatorValues(e){this.indicators=e}setStatusText(e){this.statusText=e,this.drawnHeight=null}setExchange(e){this.exchange=e,this.drawnHeight=null}title(){return this.config.showSymbol?[this.symbol,this.timeframe,this.exchange].filter(Boolean).join(` · `):``}titleCells(e,t,n,r,i){let a=[],o=this.title();if(o){let i=`600 ${t}px ${n}`;e.font=i,a.push({label:``,labelWidth:0,value:o,width:e.measureText(o).width,color:r,font:i})}if(this.statusText){let r=`${t}px ${n}`;e.font=r,a.push({label:``,labelWidth:0,value:this.statusText,width:e.measureText(this.statusText).width,color:i,font:r})}return a}priceCells(e,n,r,i,a,o,s,c){let l=`${o}px ${s}`;e.font=l;let u=i.close>=i.open,d=this.pricePrecision??(0,t.autoPricePrecision)(n.priceRange.min,n.priceRange.max),f=e=>n.formatPrice?.(e)??(0,t.formatPrice)(e,d,this.locale),p=[{label:`O`,value:f(i.open),color:c},{label:`H`,value:f(i.high),color:c},{label:`L`,value:f(i.low),color:c},{label:`C`,value:f(i.close),color:u?r.candleUp:r.candleDown}];if(this.config.showChange){let e=i.close-a.close,n=a.close===0?0:e/a.close*100,o=e>=0?`+`:``,s=(0,t.formatPrice)(n,2,this.locale);p.push({label:``,value:`${o}${f(e)} (${o}${s}%)`,color:e>=0?r.candleUp:r.candleDown})}return p.map(t=>({...t,labelWidth:t.label?e.measureText(t.label+` `).width:0,width:Bm(e,t.value),font:l}))}getHeight(){if(!this.config.visible||this.config.position!==`top-left`)return 0;if(this.drawnHeight!==null)return this.drawnHeight;let e=this.config.fontSize,t=Im;return(this.config.showOHLC||this.title()||this.statusText)&&(t+=e+Rm),this.config.showVolume&&(t+=e+2),t}render(e,t,n,r){if(!this.config.visible||r.length===0)return;let i=this.hoverBar??r[r.length-1],a=this.hoverBar?this.hoverPrev??i:r.length>1?r[r.length-2]:i,{chartRect:o}=t,s=this.config.fontSize,c=this.config.fontFamily??n.font.family,l=n.style?.legend.text??n.text,u=n.style?.legend.label??n.textSecondary,d=this.config.position===`top-left`,f=d?o.x+Lm:o.x+o.width-Lm,p=o.y+Im;e.textAlign=d?`left`:`right`,e.textBaseline=`top`;let m=this.titleCells(e,s,c,l,u);if(this.config.showOHLC&&m.push(...this.priceCells(e,t,n,i,a,s,c,l)),m.length>0){e.font=`${s}px ${c}`;let t=e.measureText(` `).width;for(let n of zm(m,t,o.width-2*Lm)){let r=n.reduce((e,n)=>e+n.labelWidth+n.width+t,-t),i=d?f:f-r;e.textAlign=`left`;for(let r of n)e.font=r.font,r.label&&(e.fillStyle=u,e.fillText(r.label,i,p),i+=r.labelWidth),e.fillStyle=r.color,e.fillText(r.value,i,p),i+=r.width+t;p+=s+Rm}e.textAlign=d?`left`:`right`}if(this.config.showVolume){e.font=`${s}px ${c}`,e.fillStyle=u;let t=i.volume>=1e6?`${(i.volume/1e6).toFixed(2)}M`:i.volume>=1e3?`${(i.volume/1e3).toFixed(2)}K`:i.volume.toFixed(0);e.fillText(`Vol ${t}`,f,p),p+=s+2}if(this.drawnHeight=d?p-o.y:null,this.indicators.length>0){e.font=`${s}px ${c}`;let t=e.measureText(` `).width,n=this.indicators.map(t=>{let n=`${t.name} ${t.value}`;return{entry:n,color:t.color,width:Bm(e,n)}}),r=n.reduce((e,n)=>e+n.width+t,-t),i=d?f:f-r;e.textAlign=`left`;for(let{entry:r,color:a,width:o}of n)e.fillStyle=a,e.fillText(r,i,p),i+=o+t}}},Im=6,Lm=8,Rm=3;function zm(e,t,n){let r=[],i=[],a=0;for(let o of e){let e=o.labelWidth+o.width;i.length>0&&a+t+e>n&&(r.push(i),i=[],a=0),a+=(i.length>0?t:0)+e,i.push(o)}return i.length>0&&r.push(i),r}function Bm(e,t){let n=t.replace(/\d/g,`0`);return Math.max(e.measureText(t).width,e.measureText(n.replace(/[-−]/g,`+`)).width,e.measureText(n.replace(/\+/g,`-`)).width)}var Vm=class{static toDataURL(e,t){let n=e.querySelectorAll(`canvas`);if(n.length===0)return``;let r=n[0],i=r.width,a=r.height,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);t&&(s.fillStyle=t,s.fillRect(0,0,i,a));let c=Array.from(n).sort((e,t)=>(parseInt(e.style.zIndex)||0)-(parseInt(t.style.zIndex)||0));for(let e of c)s.drawImage(e,0,0);return o.toDataURL(`image/png`)}static async toBlob(e,t){let n=this.toDataURL(e,t);return n?(await fetch(n)).blob():null}static download(e,t=`chart.png`,n){let r=this.toDataURL(e,n);if(!r)return;let i=document.createElement(`a`);i.href=r,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i)}},Hm=class{config=null;setConfig(e){this.config=e}isVisible(){return!!this.config?.text}render(e,t,n){if(!this.config?.text)return;let{chartRect:r}=t,i=this.config.fontSize??48,a=n.style?.watermark.color??this.config.color??n.textSecondary;e.save(),e.globalAlpha=.07,e.font=`bold ${i}px ${n.font.family}`,e.fillStyle=a,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(this.config.text,r.x+r.width/2,r.y+r.height/2),e.restore()}},Um={solid:null,dashed:[6,4],dotted:[2,3]},Wm=6,Gm=8;function Km(e,t){let n=[...e].sort((e,t)=>t.rank-e.rank||e.px-t.px),r=[],i=[];for(let e of n){let n=0,a=r.length;for(;n<a;){let t=n+a>>1;r[t]<e.px?n=t+1:a=t}n>0&&e.px-r[n-1]<t||n<r.length&&r[n]-e.px<t||(r.splice(n,0,e.px),i.push(e))}return i.sort((e,t)=>e.px-t.px)}var qm=class{config={visible:!1};cachedBreaksTyped=[];cachedMedianStep=0;cacheValid=!1;lastDataLength=0;locale=`en-US`;tz=null;setConfig(e){Object.assign(this.config,e)}setLocale(e){this.locale=e}setTimezone(e){e!==this.tz&&(this.tz=e,this.invalidateCache())}isVisible(){return this.config.visible}setVisible(e){this.config.visible=e}computeBreaksTyped(e){if(e.length<2)return[];if(this.cacheValid&&e.length===this.lastDataLength)return this.cachedBreaksTyped;let n=[],r=(0,t.barTimeUnit)(e),i=(0,t.timeParts)(e[0].time*r,this.tz);for(let a=1;a<e.length;a++){let o=e[a].time*r,s=(0,t.timeParts)(o,this.tz);if(s.year!==i.year)n.push({idx:a,kind:`year`,time:o,year:s.year});else if(s.month!==i.month)n.push({idx:a,kind:`month`,time:o,year:s.year});else if(s.day!==i.day){let e=new Date(Date.UTC(s.year,s.month-1,s.day)).getUTCDay()===1;n.push({idx:a,kind:e?`week`:`day`,time:o,year:s.year})}i=s}return this.lastDataLength=e.length,this.cachedBreaksTyped=n,this.cachedMedianStep=Xm(e),this.cacheValid=!0,n}render(e,t,n,r){this.renderLines(e,t,n,r),this.renderLabels(e,t,n,r)}renderLines(e,t,n,r){let i=this.lineMarks(t,r,n);if(i.length===0)return;let{chartRect:a}=t,o=this.look(n),s=Um[o.style];e.save(),s&&e.setLineDash(s),e.strokeStyle=o.color;for(let t of i)e.globalAlpha=t.alpha,e.lineWidth=t.width,e.beginPath(),e.moveTo(t.px,a.y),e.lineTo(t.px,a.y+a.height),e.stroke();e.restore()}renderLabels(e,t,n,r){let i=this.lineMarks(t,r,n).filter(e=>e.label!==null);if(i.length===0)return;let{chartRect:a}=t;e.save(),e.font=`600 11px ${n.font.family}`,e.textBaseline=`top`,e.textAlign=`left`,e.fillStyle=n.textSecondary;let o=[],s=[...i].sort((e,t)=>t.rank-e.rank||e.px-t.px);for(let t of s){let n=t.px+4,r=n+e.measureText(t.label).width;o.some(e=>n<e.right+Gm&&r+Gm>e.left)||(o.push({left:n,right:r}),e.globalAlpha=Math.min(1,t.alpha+.35),e.fillText(t.label,n,a.y+4))}e.restore()}lineRects(e,t,n){let r=this.lineMarks(e,n,t);if(r.length===0)return[];let{color:i,style:a}=this.look(t),o=Um[a]??void 0,{y:s,height:c}=e.chartRect;return r.map(e=>({x:e.px-e.width/2,y:s,width:e.width,height:c,color:i,alpha:e.alpha,...o?{dash:o}:{}}))}look(e){let t=e.style?.sessionBreaks;return{color:t?.color??this.config.color??e.axisLine,style:t?.style??this.config.lineStyle??`dashed`,width:t?.width??this.config.lineWidth??1}}lineMarks(e,t,n){return Km(this.marks(e,t,n),Wm)}marks(n,r,i){if(!this.config.visible||r.length<2)return[];let a=this.computeBreaksTyped(r);if(a.length===0||this.cachedMedianStep>=1380*60*1e3)return[];let{chartRect:o}=n,s=this.look(i).width,c=[];for(let r of a){let i=e.b(r.idx,n)-(n.barWidth+n.barSpacing)/2;if(i<o.x-1||i>o.x+o.width+1)continue;let a=Math.round(i)+.5,l=.25,u=s,d=null,f=3;r.kind===`day`?(l=.22,f=0):r.kind===`week`?(l=.34,f=1,d=(0,t.zonedDateFormatter)(this.locale,Jm,this.tz)(r.time)):r.kind===`month`?(l=.5,f=2,u=s+.5,d=(0,t.zonedDateFormatter)(this.locale,Ym,this.tz)(r.time)):(l=.7,u=s+1,d=String(r.year)),c.push({px:a,width:u,alpha:l,label:d,rank:f})}return c}invalidateCache(){this.lastDataLength=0,this.cachedBreaksTyped=[],this.cachedMedianStep=0,this.cacheValid=!1}},Jm={month:`short`,day:`numeric`},Ym={month:`short`,year:`numeric`};function Xm(e){if(e.length<2)return 0;let n=Math.min(50,e.length-1),r=(0,t.barTimeUnit)(e),i=[];for(let t=1;t<=n;t++)i.push((e[t].time-e[t-1].time)*r);return i.sort((e,t)=>e-t),i[Math.floor(i.length/2)]}var Zm=864e5;function Qm(e,t){let n={...e,...t};return t.tzOffsetMinutes!==void 0&&t.timeZone===void 0&&delete n.timeZone,n.windows?n.windows=n.windows.map(e=>({...e})):delete n.windows,n}function $m(e,t){let n=((e+t*6e4)%Zm+Zm)%Zm;return Math.floor(n/6e4)}function eh(e,t,n){return t===n?!0:t<n?e>=t&&e<n:e>=t||e<n}function th(e,n){let r=$m(e,n.timeZone?(0,t.zoneOffsetMinutes)(n.timeZone,e):n.tzOffsetMinutes??0);return n.windows&&n.windows.length>0?n.windows.some(e=>eh(r,e.startMinute,e.endMinute)):eh(r,n.startMinute,n.endMinute)}var nh={startMinute:570,endMinute:960,tzOffsetMinutes:-300,timeZone:`America/New_York`},rh=class{visible=!1;config={...nh};setVisible(e){this.visible=e}isVisible(){return this.visible}setConfig(e){this.config=Qm(this.config,e)}replaceConfig(e){this.config=Qm(e,{})}getConfig(){return{...this.config,windows:this.config.windows?.map(e=>({...e}))}}render(e,t,n,r){let i=this.rects(t,n,r);if(i.length!==0){e.save(),e.fillStyle=i[0].color;for(let t of i)e.fillRect(t.x,t.y,t.width,t.height);e.restore()}}rects(t,n,r){if(!this.visible||t.length===0)return[];let{chartRect:i}=n,{from:a,to:o}=n.visibleRange,s=Math.max(0,a),c=Math.min(o,t.length-1);if(c<s)return[];let l=n.barWidth+n.barSpacing,u=r.name===`light`?`rgba(0,0,0,0.045)`:`rgba(0,0,0,0.28)`,d=[],f=-1,p=(t,r)=>{let a=e.b(t,n)-l/2,o=e.b(r,n)+l/2;d.push({x:a,y:i.y,width:o-a,height:i.height,color:u,alpha:1})};for(let e=s;e<=c;e++){let n=!th(t[e].time,this.config);n&&f===-1?f=e:!n&&f!==-1&&(p(f,e-1),f=-1)}return f!==-1&&p(f,c),d}},ih=[2,3],ah=16,oh=class{highLow=!1;quote=null;quoteShown=!0;priceText=null;setPriceText(e){this.priceText=e}setQuoteShown(e){this.quoteShown=e}setHighLow(e){this.highLow=e}isHighLowVisible(){return this.highLow}setBidAsk(e){this.quote=e?{...e}:null}getBidAsk(){return this.quote?{...this.quote}:null}levels(e,t){let n=[];if(this.highLow){let r=Math.max(0,t.visibleRange.from),i=Math.min(e.length-1,t.visibleRange.to),a=-1/0,o=1/0;for(let t=r;t<=i;t++)e[t].high>a&&(a=e[t].high),e[t].low<o&&(o=e[t].low);Number.isFinite(a)&&n.push({kind:`high`,price:a}),Number.isFinite(o)&&n.push({kind:`low`,price:o})}let{bid:r,ask:i}=(this.quoteShown?this.quote:null)??{};return r!==void 0&&Number.isFinite(r)&&n.push({kind:`bid`,price:r}),i!==void 0&&Number.isFinite(i)&&n.push({kind:`ask`,price:i}),n}render(t,n,r,i){let{chartRect:a}=n;t.save(),t.setLineDash(ih),t.lineWidth=1;for(let o of this.levels(i,n)){let i=Math.round(e.T(o.price,n))+.5;i<a.y||i>a.y+a.height||(t.strokeStyle=sh(o.kind,r),t.beginPath(),t.moveTo(a.x,i),t.lineTo(a.x+a.width,i),t.stroke())}t.restore()}renderAxisTags(n,r,i,a){let{chartRect:o}=r,s=o.x+o.width+1,c=(r.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,l=(0,t.autoPricePrecision)(r.priceRange.min,r.priceRange.max);n.save(),n.font=`${i.font.sizeSmall}px ${i.font.family}`,n.textBaseline=`middle`,n.textAlign=`left`;for(let u of this.levels(a,r)){let a=e.T(u.price,r);if(a<o.y||a>o.y+o.height)continue;n.fillStyle=sh(u.kind,i),w(n,s,a-ah/2,c,ah,i),n.fillStyle=i.background;let d=r.formatPrice?.(u.price)??this.priceText?.(u.price)??(0,t.formatPrice)(u.price,l);n.fillText(d,s+5,a)}n.restore()}};function sh(e,t){switch(e){case`bid`:return t.candleUp;case`ask`:return t.candleDown;default:return t.style?.highLow.color??t.textSecondary}}var ch=24,lh=1.75,uh=[2,2.5],dh=new Map,fh=e=>{let t=dh.get(e);return t||(t=new Path2D(e),dh.set(e,t)),t};function ph(e,n,r,i,a,o){if(!(typeof Path2D>`u`)){if(e.save(),e.translate(Math.round(r),Math.round(i)),e.scale(a/ch,a/ch),e.strokeStyle=o,e.fillStyle=o,e.lineWidth=Math.max(lh,ch/a),e.lineCap=`round`,e.lineJoin=`round`,e.setLineDash([]),n.soft){let r=e.globalAlpha;e.globalAlpha=r*t.ICON_SOFT_OPACITY,e.fill(fh(n.soft)),e.globalAlpha=r}for(let t of n.fills??[])e.fill(fh(t));n.d&&e.stroke(fh(n.d)),n.dash&&(e.setLineDash(uh),e.stroke(fh(n.dash)),e.setLineDash([]));for(let[r,i,a=t.ICON_DOT_RADIUS]of n.dots??[])e.beginPath(),e.arc(r,i,a,0,Math.PI*2),e.fill();e.restore()}}var mh=12,hh=3,gh=500,_h=2,vh=[`movesUp`,`movesDown`];function yh(e){return e.channel===`price`&&!e.drawingId&&!e.target&&!vh.includes(e.condition)}function bh(e,t,n,r){switch(r){case`crossingUp`:return e!==void 0&&e<n&&t>=n;case`crossingDown`:return e!==void 0&&e>n&&t<=n;case`crossing`:return e!==void 0&&(e<n&&t>=n||e>n&&t<=n);case`greaterThan`:return t>n;case`lessThan`:return t<n;default:return!1}}var xh=[`crossing`,`crossingUp`,`crossingDown`];function Sh(e,t,n){let r=e<0&&t>=0,i=e>0&&t<=0;return n===`crossingUp`?r:n===`crossingDown`?i:r||i}var Ch=1,wh=2**31-1,Th=class extends bp{alerts=[];lastValues=new Map;drawingSides=new Map;drawingLevels=null;requestRender=null;pricePrecision=null;barTime=null;expiryTimer=null;history=new Map;lastDiffs=new Map;setBarTime(e){this.barTime=e}setRequestRender(e){this.requestRender=e}setPricePrecision(e){this.pricePrecision=e}addAlert(e,t=`crossing`,n,r=!1,i=`price`,a,o={}){let s=Eh(t,i,o),c=`tc_alert_${Ch++}`,l={id:c,price:e,condition:t,message:n,triggered:!1,repeating:r,channel:i,label:a,...s};return this.alerts.push(l),s.expiresAt!==void 0&&this.scheduleExpiry(),this.emit(`added`,l),this.requestRender?.(),c}setDrawingLevels(e){this.drawingLevels=e}addDrawingAlert(e,t=`crossing`,n,r=!1,i){if(!xh.includes(t))throw RangeError(`An alert on a drawing takes a crossing condition, not "${t}"`);let a=`tc_alert_${Ch++}`,o={id:a,price:this.drawingLevels?.(e)?.[0]??NaN,condition:t,message:n,triggered:!1,repeating:r,channel:`price`,label:i,drawingId:e};return this.alerts.push(o),this.emit(`added`,o),a}removeDrawingAlerts(e){for(let t of this.alerts.filter(t=>t.drawingId===e))this.removeAlert(t.id)}takeDrawingAlerts(e){let t=this.alerts.filter(t=>t.drawingId===e);for(let e of t)this.removeAlert(e.id);return t.map(e=>({...e}))}restoreAlerts(e){for(let t of e){if(this.alerts.some(e=>e.id===t.id))continue;let e={...t};this.alerts.push(e),this.emit(`added`,e)}this.scheduleExpiry(),this.requestRender?.()}pruneDrawingAlerts(e){let t=this.alerts.filter(t=>t.drawingId!==void 0&&!e.has(t.drawingId));for(let e of t)this.removeAlert(e.id);return t.length}removeAlert(e){this.drawingSides.delete(e),this.lastDiffs.delete(e);let t=this.alerts.some(t=>t.id===e&&t.expiresAt!==void 0);this.alerts=this.alerts.filter(t=>t.id!==e),t&&this.scheduleExpiry(),this.emit(`removed`,e),this.requestRender?.()}getAlerts(){return[...this.alerts]}getAlertAtPoint(t,n,r=6){let{chartRect:i}=n;if(t.y<i.y||t.y>i.y+i.height)return null;let a=null,o=r;for(let r of this.alerts){if(!yh(r))continue;let i=Math.abs(e.T(r.price,n)-t.y);i<=o&&(o=i,a=r)}return a}updateAlertPrice(e,t){let n=this.alerts.find(t=>t.id===e);!n||!Number.isFinite(t)||(n.price=t,n.triggered=!1,n.expiresAt!==void 0&&this.scheduleExpiry(),this.emit(`updated`,{...n}),this.requestRender?.())}clearAlerts(){this.alerts=[],this.lastDiffs.clear(),this.drawingSides.clear(),this.scheduleExpiry(),this.requestRender?.()}checkPrice(e){this.checkChannel(`price`,e),this.checkDrawingAlerts(e)}checkDrawings(e){this.checkDrawingAlerts(e)}expire(){let e=Date.now(),t=this.alerts.filter(t=>!t.expired&&t.expiresAt!==void 0&&e>=t.expiresAt&&!(t.triggered&&!t.repeating));if(t.length!==0){for(let e of t)e.expired=!0;try{for(let e of t)this.emit(`expired`,{...e}),this.emit(`updated`,{...e})}finally{this.requestRender?.(),this.scheduleExpiry()}}}scheduleExpiry(){this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=null;let e=Math.min(...this.alerts.filter(e=>!e.expired&&e.expiresAt!==void 0&&!(e.triggered&&!e.repeating)).map(e=>e.expiresAt));if(!Number.isFinite(e))return;let t=Math.min(Math.max(0,e-Date.now()),wh);this.expiryTimer=setTimeout(()=>{this.expiryTimer=null,this.expire(),this.expiryTimer||this.scheduleExpiry()},t)}dispose(){this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=null}checkDrawingAlerts(e){if(!(!this.drawingLevels||!Number.isFinite(e)))for(let t of this.alerts){if(!t.drawingId||t.expired)continue;let n=this.drawingLevels(t.drawingId);if(!n||n.length===0){this.drawingSides.delete(t.id);continue}t.price=n[0];let r=n.map(t=>Math.sign(e-t)),i=this.drawingSides.get(t.id);this.drawingSides.set(t.id,r),!(!i||i.length!==r.length)&&(r.some((e,n)=>Sh(i[n],e,t.condition))?t.triggered||(t.triggered=!0,this.emit(`triggered`,{...t})):t.repeating&&(t.triggered=!1))}}checkChannel(e,t){this.checkChannels(new Map([[e,t]]))}checkChannels(e,t={}){let n=(e instanceof Map?[...e.entries()]:Object.entries(e)).filter(([,e])=>Number.isFinite(e));if(n.length===0)return;this.expire();let r=new Map,i=new Map;for(let[e,t]of n){r.set(e,this.lastValues.get(e));let n=this.recordBar(e,t);n&&i.set(e,n),this.lastValues.set(e,t)}for(let e of this.alerts){if(e.drawingId||e.expired)continue;let n=r.has(e.channel),a=e.target!==void 0&&r.has(e.target);if(!n&&!a||e.target!==void 0&&t.together&&!(n&&a))continue;let o;if(e.onBarClose){let t=i.get(e.channel)??(e.target?i.get(e.target):void 0);if(!t)continue;o=this.closedBarMet(e,t)}else if(e.target)o=this.targetMet(e);else if(vh.includes(e.condition)){if(!n)continue;o=this.moveMet(e,this.history.get(e.channel)??[])}else{let t=r.get(e.channel);if(!n||t===void 0)continue;o=bh(t,this.lastValues.get(e.channel),e.price,e.condition)}this.settle(e,o)}}settle(e,t){t?e.triggered||(e.triggered=!0,this.emit(`triggered`,{...e})):e.repeating&&(e.triggered=!1)}targetMet(e){let t=this.lastValues.get(e.channel),n=e.target?this.lastValues.get(e.target):void 0;if(t===void 0||n===void 0)return!1;let r=t-n,i=this.lastDiffs.get(e.id);return this.lastDiffs.set(e.id,r),e.price=n,bh(i,r,0,e.condition)}moveMet(e,t,n=t.length){let r=e.bars??1,i=t.slice(Math.max(0,n-r),n);if(i.length<2||e.percent===void 0)return!1;let a=i[i.length-1].value,o=i.map(e=>e.value);if(e.condition===`movesUp`){let t=Math.min(...o);return t!==0&&(a-t)/Math.abs(t)*100>=e.percent}let s=Math.max(...o);return s!==0&&(s-a)/Math.abs(s)*100>=e.percent}closedBarMet(e,t){let n=this.history.get(e.channel)??[],r=n.findIndex(e=>e.time===t.time);if(r<0)return!1;if(vh.includes(e.condition))return this.moveMet(e,n,r+1);let i=(e,t)=>{let r=this.history.get(e)??[],i=n[t]?.time;return i===void 0?void 0:r.find(e=>e.time===i)?.value},a=n[r].value,o=r>0?n[r-1].value:void 0,s=e.price;if(e.target){let t=i(e.target,r),n=r>0?i(e.target,r-1):void 0;if(t===void 0)return!1;a-=t,o=o!==void 0&&n!==void 0?o-n:void 0,s=0,e.price=t}return bh(o,a,s,e.condition)}recordBar(e,t){let n=this.barTime;if(n===null)return null;let r=this.history.get(e)??[],i=r[r.length-1];if(i&&n<i.time)return r=r.filter(e=>e.time<n),r.push({time:n,value:t}),this.history.set(e,r),null;if(i&&i.time===n)return r[r.length-1]={time:n,value:t},null;i=r[r.length-1],r.push({time:n,value:t});let a=Math.min(502,Math.max(3,...this.alerts.map(e=>(e.bars??1)+2)));return r.length>a&&r.splice(0,r.length-a),this.history.set(e,r),i?{channel:e,time:i.time}:null}clearLastValues(){this.lastValues.clear(),this.drawingSides.clear(),this.history.clear(),this.lastDiffs.clear()}saveToStorage(e){try{let t=this.alerts.map(e=>({id:e.id,price:e.price,condition:e.condition,message:e.message,triggered:e.triggered,repeating:e.repeating,channel:e.channel,label:e.label,drawingId:e.drawingId,target:e.target,percent:e.percent,bars:e.bars,onBarClose:e.onBarClose,expiresAt:e.expiresAt,expired:e.expired}));localStorage.setItem(e,JSON.stringify(t))}catch{}}loadFromStorage(e){try{let t=localStorage.getItem(e);if(!t)return;let n=JSON.parse(t);if(!Array.isArray(n))return;for(let e of n){if(typeof e.drawingId==`string`&&e.condition&&!e.triggered){xh.includes(e.condition)&&this.addDrawingAlert(e.drawingId,e.condition,e.message,e.repeating??!1,e.label);continue}if(!e.condition||e.triggered||e.expired)continue;let t=Dh(e),n=!t.target&&!vh.includes(e.condition),r=typeof e.price==`number`&&Number.isFinite(e.price)?e.price:NaN;if(!(n&&Number.isNaN(r)))try{this.addAlert(r,e.condition,e.message,e.repeating??!1,e.channel??`price`,e.label,t)}catch{}}}catch{}}render(n,r,i){let{chartRect:a}=r;for(let o of this.alerts){if(!yh(o))continue;let s=e.T(o.price,r);if(s<a.y||s>a.y+a.height)continue;let c=o.expired?`#8a93a3`:o.triggered?`#f2a93b`:`#4c8dff`;n.setLineDash([2,6]),n.strokeStyle=c,n.lineWidth=1,n.beginPath(),n.moveTo(a.x,Math.round(s)+.5),n.lineTo(a.x+a.width,Math.round(s)+.5),n.stroke(),n.setLineDash([]),n.font=`10px ${i.font.family}`,n.fillStyle=c,n.textBaseline=`bottom`,n.textAlign=`right`;let l=`${(0,t.priceTagText)(o.price,r,this.pricePrecision??void 0)}${o.message?` - ${o.message}`:``}`,u=a.x+a.width-4;n.fillText(l,u,s-2);let d=u-n.measureText(l).width-hh-mh;d>=a.x&&ph(n,t.UI_ICONS.bell,d,s-2-mh,mh,c)}}};function Eh(e,t,n){let r={},i=vh.includes(e);if(n.target!==void 0){if(i)throw RangeError(`An alert on a move takes no other line`);if(n.target===t)throw RangeError(`An alert can’t compare a line with itself`);r.target=n.target}if(i){let{percent:e,bars:t}=n;if(e===void 0||!Number.isFinite(e)||e<=0)throw RangeError(`An alert on a move needs a percent above 0`);if(t===void 0||!Number.isInteger(t)||t<2||t>500)throw RangeError(`An alert on a move needs 2 to 500 bars`);r.percent=e,r.bars=t}return n.onBarClose&&(r.onBarClose=!0),n.expiresAt!==void 0&&Number.isFinite(n.expiresAt)&&(r.expiresAt=n.expiresAt),r}function Dh(e){let t={};return typeof e.target==`string`&&e.target&&(t.target=e.target),typeof e.percent==`number`&&Number.isFinite(e.percent)&&(t.percent=e.percent),typeof e.bars==`number`&&Number.isInteger(e.bars)&&(t.bars=e.bars),e.onBarClose===!0&&(t.onBarClose=!0),typeof e.expiresAt==`number`&&Number.isFinite(e.expiresAt)&&(t.expiresAt=e.expiresAt),t}var Oh=16,kh=()=>typeof requestAnimationFrame==`function`&&!(typeof document<`u`&&document.hidden),Ah={now:()=>typeof performance<`u`?performance.now():Date.now(),frame:e=>kh()?{raf:requestAnimationFrame(e)}:{timeout:setTimeout(e,Oh)},cancel:e=>{let t=e;t.raf!==void 0&&cancelAnimationFrame(t.raf),t.timeout!==void 0&&clearTimeout(t.timeout)}},jh=class extends bp{data=[];cursor=-1;timer=null;frameHandle=null;run=0;state=`stopped`;config={speed:1,interval:500};paceMs=null;constructor(e=Ah){super(),this.clock=e}load(e){this.stop(),this.data=e,this.cursor=-1}play(e){if(this.data.length===0)return;if(e){let{startIndex:t,paused:n,duration:r,...i}=e;this.config={...this.config,...i};let a=t===void 0?null:this.clamp(t);if(n){this.clearTimer(),this.seekTo(a??Math.max(0,this.cursor)),this.setPace(r),this.setState(`paused`);return}a!==null&&(this.cursor=a-1),this.setPace(r)}if(this.isAtEnd()){this.clearTimer(),this.setState(`paused`);return}this.clearTimer();let t=this.paceMs??this.config.interval/this.config.speed;if(!(t>0)||!Number.isFinite(t)){this.setState(`paused`);return}this.setState(`playing`),t<Oh||this.paceMs!==null?this.runFrames(t):this.timer=setInterval(()=>this.advance(1),t)}pause(){this.clearTimer(),this.setState(`paused`)}resume(){this.state===`paused`&&this.play()}stop(){this.clearTimer(),this.cursor=-1,this.setState(`stopped`)}seekTo(e){this.data.length!==0&&(this.cursor=this.clamp(e),this.emit(`bar`,{bar:this.data[this.cursor],index:this.cursor,total:this.data.length}))}setSpeed(e){this.config={...this.config,speed:e},this.paceMs=null,this.state===`playing`&&this.play()}getState(){return this.state}isAtEnd(){return this.data.length>0&&this.cursor>=this.data.length-1}getProgress(){let e=this.data.length;return{current:Math.max(0,this.cursor),total:e,percent:e>0?(this.cursor+1)/e*100:0}}dispose(){this.stop(),this.removeAllListeners(),this.data=[]}setPace(e){this.paceMs=e!==void 0&&e>0&&Number.isFinite(e)?e/Math.max(1,this.data.length-1-this.cursor):null}runFrames(e){let t=this.run,n=this.clock.now(),r=0,i=()=>{if(t!==this.run||this.state!==`playing`)return;this.frameHandle=null;let a=this.clock.now();r+=Math.min(50,Math.max(0,a-n)),n=a;let o=Math.floor(r/e);try{o>0&&(r-=o*e,this.advance(o))}finally{t===this.run&&this.state===`playing`&&this.frameHandle===null&&(this.frameHandle=this.clock.frame(i))}};this.frameHandle=this.clock.frame(i)}advance(e){if(this.isAtEnd()){this.finish();return}this.cursor=Math.min(this.data.length-1,this.cursor+e),this.emit(`bar`,{bar:this.data[this.cursor],index:this.cursor,total:this.data.length}),this.isAtEnd()&&this.finish()}finish(){this.clearTimer(),this.setState(`paused`),this.emit(`complete`,void 0)}clamp(e){return Number.isFinite(e)?Math.max(0,Math.min(Math.floor(e),this.data.length-1)):0}clearTimer(){this.run++,this.timer&&=(clearInterval(this.timer),null),this.frameHandle!==null&&(this.clock.cancel(this.frameHandle),this.frameHandle=null)}setState(e){this.state!==e&&(this.state=e,this.emit(`stateChange`,e))}},Mh=64,Nh=3,Ph=3;function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fh(e){return Array.isArray(e)?e:[]}function Ih(e,t){return typeof e==`string`?e:t}function Lh(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function Rh(e){if(!X(e)||typeof e.id!=`string`||typeof e.type!=`string`||!Array.isArray(e.anchors)||e.anchors.length===0||e.anchors.length>zh||!X(e.style))return null;let n=[];for(let t of e.anchors){if(!X(t)||typeof t.time!=`number`||typeof t.price!=`number`||!Number.isFinite(t.time)||!Number.isFinite(t.price))return null;n.push({time:t.time,price:t.price})}let r=(0,t.sanitizeDrawingStyle)(e.style);return r.color===void 0||r.lineWidth===void 0?null:{id:e.id,type:e.type,anchors:n,style:{lineStyle:`solid`,...r,color:r.color,lineWidth:r.lineWidth},visible:typeof e.visible==`boolean`?e.visible:!0,locked:typeof e.locked==`boolean`?e.locked:!1,options:X(e.options)?e.options:void 0,intervals:en(e.intervals)??void 0,group:Hh(e.group),meta:X(e.meta)?e.meta:void 0}}var zh=5e3,Bh=64,Vh=80;function Hh(e){if(!(!X(e)||typeof e.id!=`string`||typeof e.name!=`string`)&&!(e.id===``||e.id.length>Bh))return{id:e.id,name:e.name.slice(0,Vh)}}function Uh(e){return!X(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.type!=`string`||typeof e.price!=`number`||typeof e.quantity!=`number`?null:e}function Wh(e){if(!X(e))return;let n={},r=Fh(e.colors).filter(e=>typeof e==`string`);r.length>0&&(n.colors=r);let i=Fh(e.lineWidths).filter(e=>typeof e==`number`&&Number.isFinite(e)&&e>0);i.length>0&&(n.lineWidths=i),typeof e.opacity==`number`&&Number.isFinite(e.opacity)&&(n.opacity=Math.min(1,Math.max(0,e.opacity)));let a=(0,t.readIndicatorPlotStyles)(e.plots);return a&&(n.plots=a),Object.keys(n).length>0?n:void 0}var Gh=[`crossingUp`,`crossingDown`,`crossing`,`greaterThan`,`lessThan`,`movesUp`,`movesDown`];function Kh(e){if(!X(e)||typeof e.id!=`string`)return null;let t=typeof e.drawingId==`string`?e.drawingId:void 0,n=typeof e.price==`number`&&Number.isFinite(e.price)?e.price:null,r=Gh.find(t=>t===e.condition)??`crossing`,i=Dh(e),a=i.target!==void 0||r===`movesUp`||r===`movesDown`;return n===null&&!t&&!a?null:{id:e.id,price:n??NaN,drawingId:t,condition:r,message:typeof e.message==`string`?e.message:void 0,triggered:e.triggered===!0,repeating:e.repeating===!0,channel:Ih(e.channel,`price`),label:typeof e.label==`string`?e.label:void 0,...i,...e.expired===!0?{expired:!0}:{}}}function qh(e){return!X(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.entryPrice!=`number`||typeof e.quantity!=`number`?null:e}var Jh=4e3;function Yh(e){if(!X(e))return;let n={},r=[];for(let[i,a]of Object.entries(e)){let e=(0,t.readChartStyleOverrides)(a);r.push(...e.rejected);let o=Object.fromEntries(Object.entries(e.overrides).filter(([,e])=>e!==null));Object.keys(o).length>0&&(n[i.slice(0,Mh)]=o)}return r.length>0&&console.warn(`Saved style overrides left out: ${[...new Set(r)].join(`, `)}`),n}function Xh(e){if(!X(e))return Zh();typeof e.version==`number`&&e.version>Ph&&console.warn(`Chart state from a newer version (${e.version}); loading what this version understands.`);let n=X(e.viewport)?e.viewport:{},r=[];for(let n of Fh(e.indicators))X(n)&&(typeof n.id!=`string`||typeof n.instanceId!=`string`||X(n.params)&&r.push({id:n.id,instanceId:n.instanceId,params:n.params,position:typeof n.position==`string`?n.position:void 0,style:Wh(n.style),visible:typeof n.visible==`boolean`?n.visible:void 0,levels:Array.isArray(n.levels)?n.levels.filter(e=>typeof e==`number`&&Number.isFinite(e)):void 0,pane:typeof n.pane==`string`?n.pane:void 0,scale:n.scale===`left`?`left`:void 0,intervals:en(n.intervals)??void 0,paneStyle:(0,t.readPaneStyle)(n.paneStyle)??void 0,paneSize:typeof n.paneSize==`number`&&Number.isFinite(n.paneSize)&&n.paneSize>0?Math.min(n.paneSize,Jh):void 0,paneOrder:typeof n.paneOrder==`number`&&Number.isInteger(n.paneOrder)&&n.paneOrder>=0?n.paneOrder:void 0,paneCollapsed:n.paneCollapsed===!0?!0:void 0,paneMaximized:n.paneMaximized===!0?!0:void 0,paneLog:n.paneLog===!0?!0:void 0,paneInvert:n.paneInvert===!0?!0:void 0,panePercent:n.panePercent===!0?!0:void 0}));let i=[];for(let t of Fh(e.drawings)){let e=Rh(t);e&&i.push(e)}let a=[];for(let t of Fh(e.orders)){let e=Uh(t);e&&a.push(e)}let o=[];for(let t of Fh(e.positions)){let e=qh(t);e&&o.push(e)}let s=[];for(let t of Fh(e.alerts)){let e=Kh(t);e&&s.push(e)}let c=Yh(e.overrides);return{version:typeof e.version==`number`&&Array.isArray(e.indicators)?e.version:1,timestamp:Lh(e.timestamp,Date.now()),symbol:typeof e.symbol==`string`?e.symbol:void 0,timeframe:typeof e.timeframe==`string`?e.timeframe:void 0,chartType:Ih(e.chartType,`candlestick`),...e.chartTypeOptions===void 0?{}:{chartTypeOptions:(0,t.readChartTypeOptions)(e.chartTypeOptions)},viewport:{barWidth:Lh(n.barWidth,8),barSpacing:Lh(n.barSpacing,2),offset:Lh(n.offset,0)},theme:typeof e.theme==`string`?e.theme:void 0,...c?{overrides:c}:{},locale:typeof e.locale==`string`?e.locale:void 0,indicators:r,drawings:i,orders:a,positions:o,alerts:s}}function Zh(){return{version:1,timestamp:Date.now(),chartType:`candlestick`,viewport:{barWidth:8,barSpacing:2,offset:0},indicators:[],drawings:[],orders:[],positions:[],alerts:[]}}var Qh=class{static capture(e,t){return{version:e.getIndicators?Ph:1,timestamp:Date.now(),chartType:t?.chartType??`candlestick`,...t?.chartTypeOptions&&Object.keys(t.chartTypeOptions).length>0?{chartTypeOptions:t.chartTypeOptions}:{},symbol:t?.symbol,timeframe:t?.timeframe,viewport:{barWidth:8,barSpacing:2,offset:0},theme:e.getTheme().name,...e.getOverrides&&Object.keys(e.getOverrides()).length>0?{overrides:e.getOverrides()}:{},indicators:e.getIndicators?.()??[],drawings:e.getDrawings(),orders:e.getOrders?.()??[],positions:e.getPositions?.()??[],alerts:e.getAlerts?.()??[]}}static serialize(e){return JSON.stringify(e)}static deserialize(e){return Xh(JSON.parse(e))}static saveToStorage(e,t){localStorage.setItem(e,this.serialize(t))}static loadFromStorage(e){let t=localStorage.getItem(e);return t?this.deserialize(t):null}static downloadFile(e,t=`tc-chart-state.json`){let n=new Blob([this.serialize(e)],{type:`application/json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}static loadFromFile(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.type=`file`,n.accept=`.json`,n.onchange=async()=>{let r=n.files?.[0];if(!r){t(Error(`No file selected`));return}let i=await r.text();e(this.deserialize(i))},n.click()})}},$h=class{undoStack=[];redoStack=[];maxHistory=50;onChange=null;setOnChange(e){this.onChange=e}push(e){this.undoStack.push(e),this.undoStack.length>this.maxHistory&&this.undoStack.shift(),this.redoStack.length=0,this.onChange?.()}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undo(){let e=this.undoStack.pop();return e?(this.redoStack.push(e),this.onChange?.(),e):null}redo(){let e=this.redoStack.pop();return e?(this.undoStack.push(e),this.onChange?.(),e):null}clear(){this.undoStack.length=0,this.redoStack.length=0,this.onChange?.()}last(){return this.undoStack[this.undoStack.length-1]??null}dropLast(){this.undoStack.pop()&&(this.redoStack.length=0,this.onChange?.())}replaceLast(e){if(this.undoStack.length===0){this.push(e);return}this.undoStack[this.undoStack.length-1]=e,this.redoStack.length=0,this.onChange?.()}getState(){return{canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoCount:this.undoStack.length,redoCount:this.redoStack.length}}},eg=[`Time`,`Open`,`High`,`Low`,`Close`,`Volume`];function tg(e,n){return new Date((0,t.normalizeBarTime)(e,n)).toISOString()}function ng(e){let t=/^[=+\-@\t\r]/.test(e)&&!/^-?\d/.test(e)?`'${e}`:e;return/[",\r\n]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}var rg=e=>e==null||!Number.isFinite(e)?``:String(e),ig=class{static toCSV(e,n=[]){let r=[...eg,...n.map(e=>ng(e.name))].join(`,`),i=(0,t.barTimeUnit)(e);return[r,...e.map((e,t)=>[tg(e.time,i),e.open,e.high,e.low,e.close,e.volume,...n.map(e=>rg(e.values[t]))].join(`,`))].join(`
22
- `)}static toJSON(e,n=[]){let r=(0,t.barTimeUnit)(e);return JSON.stringify(e.map((e,t)=>{let i={time:tg(e.time,r),open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume};for(let e of n){let n=e.values[t];i[e.name]=n==null||!Number.isFinite(n)?null:n}return i}),null,2)}static download(e,t,n){let r=new Blob([e],{type:n}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}};function ag(e,t,n=-1/0){return t===null?e:e.filter(e=>e.time>=n&&e.time<t)}function og(e,t,n=-1/0){return t===null?e:e.filter(e=>e.entryTime>=n&&e.entryTime<t).map(e=>{if(e.exitTime===void 0||e.exitTime<t)return e;let{exitTime:n,exitPrice:r,pnl:i,pnlPercent:a,...o}=e;return o})}var sg=1,cg=3,lg=class extends bp{markers=[];style={...t.DEFAULT_SIGNAL_STYLE};requestRender=null;dataGetter=null;revealUntil=null;revealFrom=-1/0;setRequestRender(e){this.requestRender=e}setDataGetter(e){this.dataGetter=e}setStyle(e){this.style={...this.style,...e},this.requestRender?.()}getStyle(){return{...this.style}}addMarker(e){let t=e.id??`tc_signal_${sg++}`,n={...e,id:t};return this.markers.push(n),this.emit(`added`,n),this.requestRender?.(),t}removeMarker(e){this.markers=this.markers.filter(t=>t.id!==e),this.emit(`removed`,e),this.requestRender?.()}getMarkers(){return[...this.markers]}clearMarkers(){this.markers=[],this.emit(`cleared`,void 0),this.requestRender?.()}setMarkers(e){this.markers=[...e],this.requestRender?.()}setRevealUntil(e,t=-1/0){e===this.revealUntil&&t===this.revealFrom||(this.revealUntil=e,this.revealFrom=t,this.requestRender?.())}shownMarkers(){return[...ag(this.markers,this.revealUntil,this.revealFrom)]}markerAt(t,n){let r=this.dataGetter?.();if(!r||r.length===0)return null;let{chartRect:i}=n;if(t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height)return null;let a=this.style.arrowSize??12,o=ag(this.markers,this.revealUntil,this.revealFrom);for(let i=o.length-1;i>=0;i--){let s=o[i],c=e.b(e.k(s.time,r),n),l=e.T(s.price,n),u=a*Math.max(.6,Math.min(1,s.confidence)),d=s.direction===`long`?l-u:(s.direction,l-u*.4),f=s.direction===`long`?l+u*.4:s.direction===`short`?l+u:l+u*.4;if(Math.abs(t.x-c)<=u*.6+cg&&t.y>=d-cg&&t.y<=f+cg)return s}return null}render(t,n,r){let i=this.dataGetter?.(),a=ag(this.markers,this.revealUntil,this.revealFrom);if(!i||i.length===0||a.length===0)return;let{chartRect:o}=n,s=Xs(this.style,r),c=s.arrowSize??12;t.save(),t.beginPath(),t.rect(o.x,o.y,o.width,o.height),t.clip();for(let l of a){let a=e.b(e.k(l.time,i),n),u=e.T(l.price,n);if(a<o.x-c||a>o.x+o.width+c||u<o.y-c||u>o.y+o.height+c)continue;let d=this.resolveColor(l,s),f=c*Math.max(.6,Math.min(1,l.confidence));if(this.renderArrow(t,a,u,l.direction,f,d),s.showLabel&&l.label){t.font=`10px ${r.font.family}`,t.fillStyle=d,t.textAlign=`center`,t.textBaseline=l.direction===`long`?`top`:`bottom`;let e=l.direction===`long`?u+f+3:u-f-3;t.fillText(l.label,a,e)}if(s.showConfidence&&l.confidence<1){t.font=`9px ${r.font.family}`,t.fillStyle=d,t.globalAlpha=.7,t.textAlign=`center`,t.textBaseline=l.direction===`long`?`top`:`bottom`;let e=l.direction===`long`?u+f+(l.label?14:3):u-f-(l.label?14:3);t.fillText(`${Math.round(l.confidence*100)}%`,a,e),t.globalAlpha=1}}t.restore()}resolveColor(e,t){if(e.color)return e.color;if(t.sourceColors?.[e.source])return t.sourceColors[e.source];switch(e.direction){case`long`:return t.longColor??`#1fa874`;case`short`:return t.shortColor??`#e8505b`;default:return t.neutralColor??`#9E9E9E`}}renderArrow(e,t,n,r,i,a){e.fillStyle=a,e.beginPath(),r===`long`?(e.moveTo(t,n-i),e.lineTo(t-i*.6,n),e.lineTo(t-i*.2,n),e.lineTo(t-i*.2,n+i*.4),e.lineTo(t+i*.2,n+i*.4),e.lineTo(t+i*.2,n),e.lineTo(t+i*.6,n)):r===`short`?(e.moveTo(t,n+i),e.lineTo(t-i*.6,n),e.lineTo(t-i*.2,n),e.lineTo(t-i*.2,n-i*.4),e.lineTo(t+i*.2,n-i*.4),e.lineTo(t+i*.2,n),e.lineTo(t+i*.6,n)):e.arc(t,n,i*.4,0,Math.PI*2),e.closePath(),e.fill()}},ug=12,dg=1,fg=class extends bp{zones=[];style={...t.DEFAULT_TRADE_ZONE_STYLE};requestRender=null;dataGetter=null;revealUntil=null;revealFrom=-1/0;pricePrecision=null;setRequestRender(e){this.requestRender=e}setDataGetter(e){this.dataGetter=e}setPricePrecision(e){this.pricePrecision=e}setStyle(e){this.style={...this.style,...e},this.requestRender?.()}getStyle(){return{...this.style}}addZone(e){let t=e.id??`tc_zone_${dg++}`,n={...e,id:t};return this.zones.push(n),this.emit(`added`,n),this.requestRender?.(),t}updateZone(e,t){let n=this.zones.findIndex(t=>t.id===e);n!==-1&&(this.zones[n]={...this.zones[n],...t},this.requestRender?.())}removeZone(e){this.zones=this.zones.filter(t=>t.id!==e),this.emit(`removed`,e),this.requestRender?.()}getZones(){return[...this.zones]}clearZones(){this.zones=[],this.emit(`cleared`,void 0),this.requestRender?.()}setZones(e){this.zones=[...e],this.requestRender?.()}setRevealUntil(e,t=-1/0){e===this.revealUntil&&t===this.revealFrom||(this.revealUntil=e,this.revealFrom=t,this.requestRender?.())}shownZones(){return[...og(this.zones,this.revealUntil,this.revealFrom)]}render(e,t,n){let r=this.dataGetter?.(),i=og(this.zones,this.revealUntil,this.revealFrom);if(!r||r.length===0||i.length===0)return;let{chartRect:a}=t,o=Zs(this.style,n);e.save(),e.beginPath(),e.rect(a.x,a.y,a.width,a.height),e.clip();for(let a of i)this.renderZone(e,a,r,t,n,o);e.restore()}renderZone(n,r,i,a,o,s){let{chartRect:c}=a,l=e.k(r.entryTime,i),u=r.exitTime==null?i.length-1:e.k(r.exitTime,i),d=e.b(l,a),f=e.b(u,a),p=Math.max(c.x,Math.min(d,f)),m=Math.min(c.x+c.width,Math.max(d,f));if(m-p<1)return;let h=e.T(r.entryPrice,a),g=r.exitPrice==null?e.T(r.entryPrice,a):e.T(r.exitPrice,a),_=Math.min(h,g),v=Math.max(Math.max(h,g)-_,2),y=r.exitTime==null,b=r.pnl==null?r.direction===`long`?(r.exitPrice??r.entryPrice)>=r.entryPrice:(r.exitPrice??r.entryPrice)<=r.entryPrice:r.pnl>=0,x=y?s.activeColor??`#4c8dff`:b?s.profitColor??`#1fa874`:s.lossColor??`#e8505b`;n.fillStyle=x,n.globalAlpha=s.fillOpacity??.12,n.fillRect(p,_,m-p,v),n.globalAlpha=1;let S=s.borderWidth??1;if(n.strokeStyle=x,n.lineWidth=S,n.setLineDash([]),n.beginPath(),n.moveTo(p,Math.round(h)+.5),n.lineTo(m,Math.round(h)+.5),n.stroke(),!y&&r.exitPrice!=null&&(n.setLineDash([3,3]),n.beginPath(),n.moveTo(p,Math.round(g)+.5),n.lineTo(m,Math.round(g)+.5),n.stroke(),n.setLineDash([])),ph(n,r.direction===`long`?t.UI_ICONS.trendingUp:t.UI_ICONS.trendingDown,p+4,h-3-ug,ug,x),n.font=`bold 10px ${o.font.family}`,n.fillStyle=x,n.textBaseline=`bottom`,n.textAlign=`left`,n.fillText((0,t.priceTagText)(r.entryPrice,a,this.pricePrecision??void 0),p+4+ug+3,h-3),s.showPnl&&!y&&r.pnl!=null){let e=r.pnl>=0?`+`:``,t=r.pnlPercent==null?`${e}${r.pnl.toFixed(2)}`:`${e}${r.pnl.toFixed(2)} (${e}${r.pnlPercent.toFixed(2)}%)`;n.font=`bold 10px ${o.font.family}`,n.fillStyle=x,n.textBaseline=`top`,n.textAlign=`right`;let i=n.measureText(t).width+8,a=m-i-2,s=_+2;n.globalAlpha=.85,n.fillStyle=o.background,w(n,a,s,i,14,o),n.globalAlpha=1,n.fillStyle=x,n.fillText(t,m-4,s+1)}s.showLabel&&r.label&&(n.font=`9px ${o.font.family}`,n.fillStyle=x,n.globalAlpha=.8,n.textBaseline=`top`,n.textAlign=`left`,n.fillText(r.label,p+4,h+3),n.globalAlpha=1)}},pg=class{active=!1;startBar=0;startPrice=0;endBar=0;endPrice=0;startTime=null;endTime=null;isActive(){return this.active}begin(t,n,r){let i=Math.round(e.A(t.x,n)),a=e.M(t.y,n);this.startBar=i,this.startPrice=a,this.endBar=i,this.endPrice=a,this.startTime=mg(i,r),this.endTime=this.startTime,this.active=!0}update(t,n,r){if(!this.active)return;let i=Math.round(e.A(t.x,n));this.endBar=i,this.endPrice=e.M(t.y,n),this.endTime=mg(i,r)}end(){this.active=!1}render(t,n,r){if(!this.active)return;let i=e.b(this.startBar,n),a=e.b(this.endBar,n),o=e.T(this.startPrice,n),s=e.T(this.endPrice,n),c=Math.min(i,a),l=Math.max(i,a),u=Math.min(o,s),d=Math.max(o,s),f=l-c,p=d-u,m=this.endPrice>=this.startPrice?r.candleUp:r.candleDown,h=bg(m,.14);t.save();let{chartRect:g}=n;t.beginPath(),t.rect(g.x,g.y,g.width,g.height),t.clip(),t.fillStyle=h,t.fillRect(c,u,f,p),t.strokeStyle=m,t.lineWidth=1,t.setLineDash([4,3]),t.strokeRect(c+.5,u+.5,f,p),t.setLineDash([]),t.strokeStyle=m,t.lineWidth=1.5,t.beginPath(),t.moveTo(i,o),t.lineTo(a,s),t.stroke(),_g(t,i,o,m),_g(t,a,s,m),t.restore();let _=Math.abs(this.endBar-this.startBar),v=this.endPrice-this.startPrice,y=this.startPrice===0?0:v/this.startPrice*100,b=this.startTime!==null&&this.endTime!==null?gg(Math.abs(this.endTime-this.startTime)):null,x=[],S=v>0?`+`:v<0?`−`:``,C=Math.abs(v);x.push(`${S}${n.formatPrice?.(C)??hg(C)} (${S}${Math.abs(y).toFixed(2)}%)`),x.push(`${_} bars${b?` · `+b:``}`),t.save(),vg(t,a,s,x,m,r),t.restore()}};function mg(e,n){return e<0||e>=n.length?null:n[e].time*(0,t.barTimeUnit)(n)}function hg(e){return e>=1e3?e.toFixed(2):e>=1?e.toFixed(4):e.toPrecision(4)}function gg(e){let t=e/1e3;if(t<60)return`${t.toFixed(0)}s`;let n=t/60;if(n<60)return`${n.toFixed(1)}m`;let r=n/60;if(r<24)return`${r.toFixed(1)}h`;let i=r/24;if(i<30)return`${i.toFixed(1)}d`;let a=i/30;return a<12?`${a.toFixed(1)}mo`:`${(i/365).toFixed(1)}y`}function _g(e,t,n,r){e.fillStyle=r,e.beginPath(),e.arc(t,n,3.5,0,Math.PI*2),e.fill(),e.fillStyle=`#fff`,e.beginPath(),e.arc(t,n,1.5,0,Math.PI*2),e.fill()}function vg(e,t,n,r,i,a){e.font=`600 11px ${a.font.family}`;let o=0;for(let t of r){let n=e.measureText(t).width;n>o&&(o=n)}let s=Math.ceil(o)+16,c=r.length*14+12,l=t+8,u=n+8,d=e.canvas.clientWidth||e.canvas.width;l+s>d-4&&(l=t-s-8),l<4&&(l=4),e.fillStyle=a.background,e.globalAlpha=.96,yg(e,l,u,s,c,6),e.fill(),e.globalAlpha=1,e.strokeStyle=i,e.lineWidth=1,yg(e,l+.5,u+.5,s-1,c-1,6),e.stroke(),e.fillStyle=a.text,e.textBaseline=`top`,e.textAlign=`left`;for(let t=0;t<r.length;t++)e.fillStyle=t===0?i:a.textSecondary,e.fillText(r[t],l+8,u+6+t*14)}function yg(e,t,n,r,i,a){e.beginPath(),e.moveTo(t+a,n),e.arcTo(t+r,n,t+r,n+i,a),e.arcTo(t+r,n+i,t,n+i,a),e.arcTo(t,n+i,t,n,a),e.arcTo(t,n,t+r,n,a),e.closePath()}function bg(e,t){if(e.startsWith(`#`)){let n=0,r=0,i=0;return e.length===4?(n=parseInt(e[1]+e[1],16),r=parseInt(e[2]+e[2],16),i=parseInt(e[3]+e[3],16)):e.length>=7&&(n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16)),`rgba(${n},${r},${i},${t})`}if(e.startsWith(`rgb`)){let n=e.match(/[\d.]+/g);if(n&&n.length>=3)return`rgba(${n[0]},${n[1]},${n[2]},${t})`}return e}var xg=6,Sg=class{start=null;current=null;isActive(){return this.start!==null}begin(e){this.start=e,this.current=e}update(e){this.start&&(this.current=e)}end(){let e=this.start,t=this.current;if(this.cancel(),!e||!t)return null;let n=Math.min(e.x,t.x),r=Math.max(e.x,t.x),i=Math.min(e.y,t.y),a=Math.max(e.y,t.y);return{x0:n,y0:i,x1:r,y1:a,isClick:r-n<6&&a-i<6}}cancel(){this.start=null,this.current=null}render(e,t,n){if(!this.start||!this.current)return;let{chartRect:r}=t,i=e=>Math.max(r.x,Math.min(r.x+r.width,e)),a=e=>Math.max(r.y,Math.min(r.y+r.height,e)),o=i(Math.min(this.start.x,this.current.x)),s=i(Math.max(this.start.x,this.current.x)),c=a(Math.min(this.start.y,this.current.y)),l=a(Math.max(this.start.y,this.current.y));e.save(),e.fillStyle=n.crosshair,e.globalAlpha=.1,e.fillRect(o,c,s-o,l-c),e.globalAlpha=.8,e.strokeStyle=n.crosshair,e.lineWidth=1,e.setLineDash([4,3]),e.strokeRect(Math.round(o)+.5,Math.round(c)+.5,Math.round(s-o),Math.round(l-c)),e.restore()}},Cg={linear:e=>e,easeOutCubic:e=>1-(1-e)**3,easeOutQuart:e=>1-(1-e)**4,easeInOutCubic:e=>e<.5?4*e*e*e:1-(-2*e+2)**3/2,easeOutExpo:e=>e===1?1:1-2**(-10*e),easeOutElastic:e=>e===0||e===1?e:2**(-10*e)*Math.sin((e*10-.75)*(2*Math.PI/3))+1,spring:e=>1-Math.E**(-6*e)*Math.cos(8*e)},wg=class{animations=new Map;frameId=0;running=!1;animate(e,t){this.animations.set(e,{startTime:-1,duration:t.duration,easing:t.easing??Cg.easeOutCubic,onUpdate:t.onUpdate,onComplete:t.onComplete}),this.running||(this.running=!0,this.tick())}cancel(e){this.animations.delete(e),this.animations.size===0&&this.stop()}cancelAll(){this.animations.clear(),this.stop()}isAnimating(e){return e?this.animations.has(e):this.animations.size>0}tick(){this.frameId=requestAnimationFrame(e=>{let t=[];for(let[n,r]of this.animations){r.startTime<0&&(r.startTime=e);let i=e-r.startTime,a=Math.min(1,i/r.duration),o=r.easing(a);r.onUpdate(o),a>=1&&(r.onComplete?.(),t.push(n))}for(let e of t)this.animations.delete(e);this.animations.size>0?this.tick():this.running=!1})}stop(){this.frameId&&=(cancelAnimationFrame(this.frameId),0),this.running=!1}dispose(){this.cancelAll()}};function Tg(e){return!e||e===`dark`?t.DARK_THEME:e===`light`?t.LIGHT_THEME:e}var Eg=class{canvas;ctx;container;theme;width=0;height=0;dpr=1;frameId=null;resizeObserver;constructor(e,t){this.container=e,this.theme=Tg(t),this.canvas=document.createElement(`canvas`),this.canvas.style.width=`100%`,this.canvas.style.height=`100%`,this.canvas.style.display=`block`,this.canvas.setAttribute(`role`,`img`),e.appendChild(this.canvas),this.ctx=this.canvas.getContext(`2d`),this.dpr=o(),this.updateSize(),this.resizeObserver=new ResizeObserver(()=>{this.updateSize(),this.requestRender()}),this.resizeObserver.observe(e)}updateSize(){this.dpr=o();let e=this.container.getBoundingClientRect();this.width=e.width||this.container.clientWidth,this.height=e.height||this.container.clientHeight,this.canvas.width=Math.max(1,Math.floor(this.width*this.dpr)),this.canvas.height=Math.max(1,Math.floor(this.height*this.dpr))}requestRender(){this.frameId===null&&(this.frameId=requestAnimationFrame(()=>{this.frameId=null,(this.width===0||this.height===0)&&this.updateSize(),!(this.width===0||this.height===0)&&(this.ctx.save(),this.ctx.scale(this.dpr,this.dpr),this.ctx.clearRect(0,0,this.width,this.height),this.renderChart(this.ctx,this.width,this.height,this.theme),this.ctx.restore())}))}setLabel(e){this.canvas.setAttribute(`aria-label`,e)}setTheme(e){this.theme=Tg(e),this.requestRender()}destroy(){this.frameId!==null&&cancelAnimationFrame(this.frameId),this.resizeObserver.disconnect(),this.canvas.width=0,this.canvas.height=0,this.canvas.remove()}},Dg=class{pos=null;canvas;onUpdate;handleMove;handleLeave;constructor(e,t){this.canvas=e,this.onUpdate=t,this.handleMove=t=>{let n=e.getBoundingClientRect();this.pos={x:t.clientX-n.left,y:t.clientY-n.top},this.onUpdate()},this.handleLeave=()=>{this.pos=null,this.onUpdate()},e.addEventListener(`pointermove`,this.handleMove),e.addEventListener(`pointerleave`,this.handleLeave)}getPosition(){return this.pos}isActive(){return this.pos!==null}drawCrosshair(e,t,n,r){this.pos&&(e.save(),e.strokeStyle=r,e.lineWidth=.5,e.setLineDash([4,4]),e.beginPath(),e.moveTo(this.pos.x,0),e.lineTo(this.pos.x,n),e.stroke(),e.beginPath(),e.moveTo(0,this.pos.y),e.lineTo(t,this.pos.y),e.stroke(),e.restore())}destroy(){this.canvas.removeEventListener(`pointermove`,this.handleMove),this.canvas.removeEventListener(`pointerleave`,this.handleLeave)}};function Og(e,t,n,r,i){let{data:a,mode:o=`area`,lineWidth:s=1.5,showLastPoint:c=!1,showMinMax:l=!1}=r;if(a.length<2||t<=0||n<=0)return;let u=r.color??i.lineColor,d=r.fillColor??u,f=t-4,p=n-4,m=1/0,h=-1/0,g=0,_=0;for(let e=0;e<a.length;e++)a[e]<m&&(m=a[e],g=e),a[e]>h&&(h=a[e],_=e);let v=h-m||1,y=e=>2+e/(a.length-1)*f,b=e=>2+p-(e-m)/v*p;if(o===`area`){let t=e.createLinearGradient(0,2,0,n-2);t.addColorStop(0,d+(d.startsWith(`#`)?`40`:``)),t.addColorStop(1,`transparent`),e.beginPath(),e.moveTo(y(0),b(a[0]));for(let t=1;t<a.length;t++)e.lineTo(y(t),b(a[t]));e.lineTo(y(a.length-1),n-2),e.lineTo(y(0),n-2),e.closePath(),e.fillStyle=t,e.fill()}e.beginPath(),e.moveTo(y(0),b(a[0]));for(let t=1;t<a.length;t++)e.lineTo(y(t),b(a[t]));if(e.strokeStyle=u,e.lineWidth=s,e.lineJoin=`round`,e.stroke(),c){let t=r.lastPointColor??u,n=y(a.length-1),i=b(a[a.length-1]);e.beginPath(),e.arc(n,i,3,0,Math.PI*2),e.fillStyle=t,e.fill()}if(l){let t=r.minPointColor??i.candleDown,n=r.maxPointColor??i.candleUp;e.beginPath(),e.arc(y(g),b(m),2.5,0,Math.PI*2),e.fillStyle=t,e.fill(),e.beginPath(),e.arc(y(_),b(h),2.5,0,Math.PI*2),e.fillStyle=n,e.fill()}}var kg=50,Ag=60,jg=20,Mg=.2;function Ng(e){let t=[...e].sort((e,t)=>t.price-e.price),n=[],r=0;for(let e of t)r+=e.volume,n.push({price:e.price,cumulativeVolume:r});return n}function Pg(e){let t=[...e].sort((e,t)=>e.price-t.price),n=[],r=0;for(let e of t)r+=e.volume,n.push({price:e.price,cumulativeVolume:r});return n}function Fg(e,t){return{left:kg,right:e-Ag,top:jg,bottom:t-jg,plotWidth:e-kg-Ag,plotHeight:t-jg*2}}function Ig(e,t,n,r){e.fillStyle=r,e.fillRect(0,0,t,n)}function Lg(e,n,r,i,a,o,s,c){let{left:l,right:u,top:d,bottom:f,plotWidth:p,plotHeight:m}=n;e.save(),e.strokeStyle=o.grid,e.lineWidth=.5,e.fillStyle=o.axisLabel,e.font=`${o.font.sizeSmall}px ${o.font.family}`;let h=(0,t.computeTickStep)(0,a,5);for(let t=0;t<=a;t+=h){let n=f-t/a*m;e.beginPath(),e.moveTo(l,n),e.lineTo(u,n),e.stroke(),e.textAlign=`right`,e.textBaseline=`middle`,e.fillText(c(t),l-4,n)}let g=i-r,_=(0,t.computeTickStep)(r,i,6),v=Math.ceil(r/_)*_;for(let t=v;t<=i;t+=_){let n=l+(t-r)/g*p;e.beginPath(),e.moveTo(n,d),e.lineTo(n,f),e.stroke(),e.textAlign=`center`,e.textBaseline=`top`,e.fillText(s(t),n,f+4)}e.restore()}function Rg(e,t,n,r,i,a,o,s,c){if(t.length===0)return;let{left:l,bottom:u,plotWidth:d,plotHeight:f}=n,p=e=>l+(e-r)/i*d,m=e=>u-e/a*f;if(e.beginPath(),c===`bid`){e.moveTo(p(t[0].price),u);for(let n=0;n<t.length;n++){let r=p(t[n].price),i=m(t[n].cumulativeVolume);e.lineTo(r,i),n<t.length-1&&e.lineTo(p(t[n+1].price),i)}e.lineTo(p(t[t.length-1].price),u)}else{e.moveTo(p(t[0].price),u);for(let n=0;n<t.length;n++){let r=p(t[n].price),i=m(t[n].cumulativeVolume);e.lineTo(r,i),n<t.length-1&&e.lineTo(p(t[n+1].price),i)}e.lineTo(p(t[t.length-1].price),u)}if(e.closePath(),e.fillStyle=o,e.fill(),e.beginPath(),c===`bid`){e.moveTo(p(t[0].price),m(t[0].cumulativeVolume));for(let n=0;n<t.length;n++){let r=p(t[n].price),i=m(t[n].cumulativeVolume);n>0&&e.lineTo(r,m(t[n-1].cumulativeVolume)),e.lineTo(r,i)}}else{e.moveTo(p(t[0].price),m(t[0].cumulativeVolume));for(let n=1;n<t.length;n++){let r=m(t[n-1].cumulativeVolume),i=p(t[n].price),a=m(t[n].cumulativeVolume);e.lineTo(i,r),e.lineTo(i,a)}}e.strokeStyle=s,e.lineWidth=1.5,e.stroke()}function zg(e,t,n,r,i,a,o,s,c){let{left:l,top:u,bottom:d,plotWidth:f}=r,p=l+(t-i)/a*f;if(e.save(),e.strokeStyle=o.textSecondary,e.lineWidth=1,e.setLineDash([4,4]),e.beginPath(),e.moveTo(p,u),e.lineTo(p,d),e.stroke(),e.restore(),s){let t=`Spread: ${c(n)}`;e.save(),e.font=`${o.font.sizeSmall}px ${o.font.family}`,e.fillStyle=o.textSecondary,e.textAlign=`center`,e.textBaseline=`bottom`,e.fillText(t,p,u-2),e.restore()}}function Bg(e,t,n,r,i,a,o,s,c,l,u){let{left:d,top:f,bottom:p,plotWidth:m,plotHeight:h}=i,g=t.x;if(g<d||g>i.right)return;let _=a+(g-d)/m*o,v=0,y=``;if(n.length>0&&_<=n[0].price){y=`Bid`;for(let e of n)if(_<=e.price)v=e.cumulativeVolume;else break}if(r.length>0&&_>=r[0].price){y=`Ask`;for(let e of r)if(_>=e.price)v=e.cumulativeVolume;else break}if(e.save(),e.strokeStyle=c.crosshair,e.lineWidth=.5,e.setLineDash([4,4]),e.beginPath(),e.moveTo(g,f),e.lineTo(g,p),e.stroke(),v>0){let t=p-v/s*h;e.beginPath(),e.moveTo(d,t),e.lineTo(i.right,t),e.stroke()}e.restore();let b=[`Price: ${l(_)}`,y?`${y} Vol: ${u(v)}`:``].filter(Boolean);e.save(),e.font=`${c.font.sizeSmall}px ${c.font.family}`;let x=Math.max(...b.map(t=>e.measureText(t).width))+16,S=b.length*(c.font.sizeSmall+4)+12,C=g+10,w=t.y-S/2;C+x>i.right&&(C=g-x-10),w<f&&(w=f),w+S>p&&(w=p-S),e.fillStyle=c.axisLabelBackground,e.globalAlpha=.9,e.fillRect(C,w,x,S),e.globalAlpha=1,e.fillStyle=c.text,e.textBaseline=`top`,e.textAlign=`left`;for(let t=0;t<b.length;t++)e.fillText(b[t],C+8,w+6+t*(c.font.sizeSmall+4));e.restore()}function Vg(e){return e.toFixed(2)}function Hg(e){return e>=1e6?(e/1e6).toFixed(2)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:e.toFixed(0)}function Ug(e,t,n,r,i,a){let{data:o}=r;if(o.bids.length===0&&o.asks.length===0||t<=0||n<=0)return;let s=r.bidColor??i.candleUp,c=r.askColor??i.candleDown,l=r.bidFillColor??s+`40`,u=r.askFillColor??c+`40`,d=r.midPriceLine!==!1,f=r.spreadLabel!==!1,p=r.priceFormat??Vg,m=r.volumeFormat??Hg,h=Ng(o.bids),g=Pg(o.asks),_=h.length>0?h[0].price:0,v=g.length>0?g[0].price:0,y=h.length>0&&g.length>0?(_+v)/2:_||v,b=g.length>0&&h.length>0?v-_:0,x=h.length>0?h[h.length-1].price:y,S=g.length>0?g[g.length-1].price:y,C=Math.max(y-x,S-y)*(1+Mg),w=y-C,T=y+C,E=T-w,D=h.length>0?h[h.length-1].cumulativeVolume:0,O=g.length>0?g[g.length-1].cumulativeVolume:0,k=Math.max(D,O)||1,A=Fg(t,n);Ig(e,t,n,i.background),Lg(e,A,w,T,k,i,p,m),Rg(e,h,A,w,E,k,l,s,`bid`),Rg(e,g,A,w,E,k,u,c,`ask`),d&&zg(e,y,b,A,w,E,i,f,p),a&&Bg(e,a,h,g,A,w,E,k,i,p,m)}var Wg=70,Gg=30,Kg=20,qg=20,Jg=.05;function Yg(e,t){return{left:Wg,right:e-Kg,top:qg,bottom:t-Gg,plotWidth:e-Wg-Kg,plotHeight:t-qg-Gg}}function Xg(e,t){let n=1/0,r=-1/0;for(let t of e)t.value<n&&(n=t.value),t.value>r&&(r=t.value);if(t)for(let e of t)e.value<n&&(n=e.value),e.value>r&&(r=e.value);let i=(r-n)*Jg;return{valMin:n-i,valMax:r+i}}function Zg(e){let t=[],n=-1/0;for(let r of e)r.value>n&&(n=r.value),t.push(n);return t}function Qg(e){let t=864e5;if(365.25*t,e<7*t){let e=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`});return t=>e.format(new Date(t))}if(e<315576e5){let e=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`});return t=>e.format(new Date(t))}let n=new Intl.DateTimeFormat(void 0,{month:`short`,year:`numeric`});return e=>n.format(new Date(e))}function $g(e){return Math.abs(e)>=1e6?(e/1e6).toFixed(2)+`M`:Math.abs(e)>=1e3?(e/1e3).toFixed(1)+`K`:e.toFixed(2)}function e_(e,t,n,r){e.fillStyle=r,e.fillRect(0,0,t,n)}function t_(e,n,r,i,a,o,s,c,l){let{left:u,right:d,top:f,bottom:p,plotWidth:m,plotHeight:h}=n;e.save(),e.strokeStyle=s.grid,e.lineWidth=.5,e.fillStyle=s.axisLabel,e.font=`${s.font.sizeSmall}px ${s.font.family}`;let g=(0,t.computeTickStep)(r,i,6),_=Math.ceil(r/g)*g;for(let t=_;t<=i;t+=g){let n=p-(t-r)/(i-r)*h;e.beginPath(),e.moveTo(u,n),e.lineTo(d,n),e.stroke(),e.textAlign=`right`,e.textBaseline=`middle`,e.fillText(c(t),u-6,n)}let v=o-a,y=(0,t.computeTickStep)(a,o,6),b=Math.ceil(a/y)*y;for(let t=b;t<=o;t+=y){let n=u+(t-a)/v*m;e.beginPath(),e.moveTo(n,f),e.lineTo(n,p),e.stroke(),e.textAlign=`center`,e.textBaseline=`top`,e.fillText(l(t),n,p+4)}e.restore()}function n_(e,t,n,r,i,a,o,s,c){if(t.length<2)return;let{left:l,bottom:u,plotWidth:d,plotHeight:f}=n,p=e=>l+(e-r)/i*d,m=e=>u-(e-a)/o*f;e.save(),e.beginPath(),e.moveTo(p(t[0].time),m(t[0].value));for(let n=1;n<t.length;n++)e.lineTo(p(t[n].time),m(t[n].value));e.strokeStyle=s,e.lineWidth=c,e.lineJoin=`round`,e.stroke(),e.restore()}function r_(e,t,n,r,i,a,o,s){if(t.length<2)return;let{left:c,bottom:l,plotWidth:u,plotHeight:d}=n,f=e=>c+(e-r)/i*u,p=e=>l-(e-a)/o*d,m=e.createLinearGradient(0,n.top,0,l);m.addColorStop(0,s+`40`),m.addColorStop(1,`transparent`),e.save(),e.beginPath(),e.moveTo(f(t[0].time),p(t[0].value));for(let n=1;n<t.length;n++)e.lineTo(f(t[n].time),p(t[n].value));e.lineTo(f(t[t.length-1].time),l),e.lineTo(f(t[0].time),l),e.closePath(),e.fillStyle=m,e.fill(),e.restore()}function i_(e,t,n,r,i,a,o,s,c){if(t.length<2)return;let{left:l,bottom:u,plotWidth:d,plotHeight:f}=r,p=e=>l+(e-i)/a*d,m=e=>u-(e-o)/s*f;e.save(),e.fillStyle=c,e.beginPath(),e.moveTo(p(t[0].time),m(n[0]));for(let r=1;r<t.length;r++)e.lineTo(p(t[r].time),m(n[r]));for(let n=t.length-1;n>=0;n--)e.lineTo(p(t[n].time),m(t[n].value));e.closePath(),e.fill(),e.restore()}function a_(e,t,n,r,i,a,o,s,c,l){if(t.length===0)return;let{left:u,bottom:d,plotWidth:f,plotHeight:p}=n,m=t[t.length-1],h=u+(m.time-r)/i*f,g=d-(m.value-a)/o*p;e.save(),e.font=`${l.font.sizeSmall}px ${l.font.family}`,e.fillStyle=c,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(s,h+4,g),e.restore()}function o_(e,t,n,r,i,a,o,s,c,l,u,d){let{left:f,top:p,bottom:m,plotWidth:h,plotHeight:g}=i,_=t.x;if(_<f||_>i.right)return;e.save(),e.strokeStyle=l.crosshair,e.lineWidth=.5,e.setLineDash([4,4]),e.beginPath(),e.moveTo(_,p),e.lineTo(_,m),e.stroke(),e.restore();let v=a+(_-f)/h*o,y=0,b=1/0;for(let e=0;e<n.length;e++){let t=Math.abs(n[e].time-v);t<b&&(b=t,y=e)}let x=n[y],S=[u(x.time),`Value: ${d(x.value)}`];r&&r.length>y&&S.push(`Benchmark: ${d(r[y].value)}`);let C=f+(x.time-a)/o*h,w=m-(x.value-s)/c*g;e.beginPath(),e.arc(C,w,3,0,Math.PI*2),e.fillStyle=l.lineColor,e.fill(),e.save(),e.font=`${l.font.sizeSmall}px ${l.font.family}`;let T=Math.max(...S.map(t=>e.measureText(t).width))+16,E=S.length*(l.font.sizeSmall+4)+12,D=_+10,O=t.y-E/2;D+T>i.right&&(D=_-T-10),O<p&&(O=p),O+E>m&&(O=m-E),e.fillStyle=l.axisLabelBackground,e.globalAlpha=.9,e.fillRect(D,O,T,E),e.globalAlpha=1,e.fillStyle=l.text,e.textBaseline=`top`,e.textAlign=`left`;for(let t=0;t<S.length;t++)e.fillText(S[t],D+8,O+6+t*(l.font.sizeSmall+4));e.restore()}function s_(e,t,n,r,i,a){let{data:o}=r;if(o.length<2||t<=0||n<=0)return;let s=r.lineColor??i.lineColor,c=r.lineWidth??1.5,l=r.drawdown===!0,u=r.drawdownColor??i.candleDown+`30`,d=r.fillArea===!0,f=r.benchmark,p=r.benchmarkColor??i.textSecondary,m=r.benchmarkLabel??`Benchmark`,h=r.valueFormat??$g,{valMin:g,valMax:_}=Xg(o,f),v=_-g||1,y=o[0].time,b=o[o.length-1].time,x=b-y||1,S=r.timeFormat??Qg(x),C=Yg(t,n);e_(e,t,n,i.background),t_(e,C,g,_,y,b,i,h,S),l&&i_(e,o,Zg(o),C,y,x,g,v,u),d&&r_(e,o,C,y,x,g,v,s),n_(e,o,C,y,x,g,v,s,c),f&&f.length>=2&&(n_(e,f,C,y,x,g,v,p,1),a_(e,f,C,y,x,g,v,m,p,i)),a&&o_(e,a,o,f,C,y,x,g,v,i,S,h)}function c_(e,t,n){if(e.length===0)return[];let r=e.length,i=Math.ceil(Math.sqrt(r)),a=Math.ceil(r/i),o=t.width/i,s=t.height/a,c=[];for(let a=0;a<r;a++){let r=a%i,l=Math.floor(a/i);c.push({id:e[a].id,rect:{x:t.x+r*o+n,y:t.y+l*s+n,width:Math.max(0,o-n*2),height:Math.max(0,s-n*2)}})}return c}function l_(e,t){let n=e.reduce((e,t)=>e+t,0);if(n===0||t===0)return 1/0;let r=0;for(let i of e){let e=n/t,a=i/e,o=e>a?e/a:a/e;o>r&&(r=o)}return r}function u_(e,t,n,r,i,a){let o=r?n.height:n.width,s=e.reduce((e,t)=>e+t,0),c=o>0?s/o:0,l=0;for(let o=0;o<e.length;o++){let s=c>0?e[o]/c:0,u;u=r?{x:n.x+i,y:n.y+l+i,width:Math.max(0,c-i*2),height:Math.max(0,s-i*2)}:{x:n.x+l+i,y:n.y+i,width:Math.max(0,s-i*2),height:Math.max(0,c-i*2)},a.push({id:t[o],rect:u}),l+=s}}function d_(e,t,n,r,i){if(e.length===0)return;let a=n.width>=n.height,o=a?n.height:n.width;if(e.length===1){u_(e,t,n,a,r,i);return}let s=[],c=[],l=0;for(;l<e.length;){let u=[...s,e[l]];if(s.length===0||l_(u,o)<=l_(s,o))s.push(e[l]),c.push(t[l]),l++;else{u_(s,c,n,a,r,i);let u=s.reduce((e,t)=>e+t,0),d=o>0?u/o:0;n=a?{x:n.x+d,y:n.y,width:n.width-d,height:n.height}:{x:n.x,y:n.y+d,width:n.width,height:n.height-d},d_(e.slice(l),t.slice(l),n,r,i);return}}s.length>0&&u_(s,c,n,a,r,i)}function f_(e,t,n){if(e.length===0)return[];let r=[...e].sort((e,t)=>t.weight-e.weight),i=r.reduce((e,t)=>e+Math.max(0,t.weight),0);if(i===0)return[];let a=t.width*t.height,o=r.map(e=>Math.max(0,e.weight)/i*a),s=r.map(e=>e.id),c=[];return d_(o,s,{...t},n,c),c}var p_=2,m_=18;function h_(e,t,n,r=18){let i=new Map;for(let t of e){if(!(t.weight>0))continue;let e=t.group??``,n=i.get(e);n?n.push(t):i.set(e,[t])}let a=[...i.keys()],o=f_(a.map((e,t)=>({id:String(t),weight:i.get(e).reduce((e,t)=>e+t.weight,0)})),t,0),s=[],c=[];for(let e of o){let t=a[Number(e.id)],o=i.get(t),l=o.reduce((e,t)=>e+t.weight,0),u=o.reduce((e,t)=>e+(Number.isFinite(t.value)?t.value*t.weight:0),0),d=e.rect,f=t!==``&&d.height>=r*2.5&&d.width>=40?r:0,p={x:d.x+p_/2,y:d.y+p_/2+f,width:Math.max(0,d.width-p_),height:Math.max(0,d.height-p_-f)};s.push({name:t,rect:{...d},header:f,value:l>0?u/l:0,count:o.length}),c.push(...f_(o,p,n))}return{groups:s,cells:c}}var g_=10,__=6,v_=16,y_=18,b_=8,x_=16,S_=15,C_={min:0,max:1,step:.2,ticks:[0,.2,.4,.6,.8,1]};function w_(e){for(let t=0;t<=S_;t++){let n=e*10**t,r=Math.round(n);if(r!==0&&Math.abs(r-n)<1e-9*Math.abs(n))return t}return S_}var T_=(e,t)=>{let n=Number(e.toFixed(t));return n===0?0:n};function E_(e,t,n=5){let r=Math.min(e,t),i=Math.max(e,t);if((!Number.isFinite(r)||!Number.isFinite(i))&&(r=0,i=1),r===i){let e=Math.abs(r)||1;r-=e/2,i+=e/2}let a=(i/2-r/2)/Math.max(1,n)*2;if(!Number.isFinite(a)||a<=0)return C_;let o=10**Math.floor(Math.log10(a)),s=a/o,c=(s<=1?1:s<=2?2:s<=2.5?2.5:s<=5?5:10)*o;if(!Number.isFinite(c)||c<=0)return C_;let l=w_(c),u=Math.floor(r/c+1e-9),d=Math.ceil(i/c-1e-9),f=[];for(let e=u;e<=d;e++)f.push(T_(e*c,l));return f.length<2||!f.every(Number.isFinite)?C_:{min:f[0],max:f[f.length-1],step:T_(c,l),ticks:f}}function Z(e,t,n,r,i=!1){let a=e.max===e.min?.5:(t-e.min)/(e.max-e.min);return i?n+r*(1-a):n+r*a}var D_=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),O_=new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1});function k_(e){return Math.abs(e)>=1e4?O_.format(e):D_.format(e)}function Q(e){let t=w_(e.step),n=new Intl.NumberFormat(void 0,{minimumFractionDigits:t,maximumFractionDigits:t});if(Math.max(Math.abs(e.min),Math.abs(e.max))>=1e4&&e.step%1e3==0){let t=new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:2}),n=e.ticks.map(e=>t.format(e));if(new Set(n).size===n.length)return e=>t.format(e)}return e=>n.format(e)}function A_(e,n){return n??t.TC_SERIES_COLORS[e%t.TC_SERIES_COLORS.length]}function $(e,t,n=``){return`${n?`${n} `:``}${t}px ${e.font.family}`}function j_(e,t){return(n,r=11)=>(e.font=$(t,r),e.measureText(n).width)}function M_(e,t,n,r=!1){let i=[],a=0,o=0;for(let s of e){let e=g_+__+n(s.label,11);a>0&&(r||a+e>t)&&(o++,a=0),i.push({...s,x:a,y:o*y_}),a+=e+v_}let s=e.length===0?0:o+1;return{items:i,rows:s,height:s*y_}}function N_(e,t,n,r,i){e.save(),e.font=$(i,11),e.textBaseline=`middle`,e.textAlign=`left`;for(let a of t.items){let t=r+a.y+y_/2;e.fillStyle=a.color,e.fillRect(n+a.x,t-g_/2,g_,g_),e.fillStyle=i.textSecondary,e.fillText(a.label,n+a.x+g_+__,t)}e.restore()}function P_(e,n,r,i,a){if(n.length===0)return;e.save();let o=n.some(e=>e.color)?g_+__:0,s=0;for(let t of n)e.font=$(a,11,t.bold?`600`:``),s=Math.max(s,e.measureText(t.text).width);let c=s+o+b_*2,l=n.length*x_+b_*2-4,u=r.x+14,d=r.y+14;u+c>i.x+i.width&&(u=r.x-14-c),d+l>i.y+i.height&&(d=r.y-14-l),u=Math.max(i.x,u),d=Math.max(i.y,d),e.fillStyle=(0,t.withAlpha)(a.axisLabelBackground,.94),e.strokeStyle=a.grid,e.lineWidth=1,e.beginPath(),typeof e.roundRect==`function`?e.roundRect(u,d,c,l,6):e.rect(u,d,c,l),e.fill(),e.stroke(),e.textBaseline=`middle`,e.textAlign=`left`,n.forEach((t,n)=>{let r=d+b_+n*x_+x_/2-2;t.color&&(e.fillStyle=t.color,e.fillRect(u+b_,r-4,8,8)),e.font=$(a,11,t.bold?`600`:``),e.fillStyle=t.bold?a.text:a.textSecondary,e.fillText(t.text,u+b_+o,r)}),e.restore()}function F_(e,t,n,r,i,a){e.save(),e.font=$(i,11),e.fillStyle=i.axisLabel,e.strokeStyle=i.grid,e.lineWidth=1;for(let i of n.ticks)if(r===`vertical`){let r=Math.round(Z(n,i,t.y,t.height,!0))+.5;e.beginPath(),e.moveTo(t.x,r),e.lineTo(t.x+t.width,r),e.stroke(),e.textAlign=`right`,e.textBaseline=`middle`,e.fillText(a(i),t.x-6,r)}else{let r=Math.round(Z(n,i,t.x,t.width))+.5;e.beginPath(),e.moveTo(r,t.y),e.lineTo(r,t.y+t.height),e.stroke(),e.textAlign=`center`,e.textBaseline=`top`,e.fillText(a(i),r,t.y+t.height+6)}e.restore()}function I_(e,t,n,r=11){if(n(e,r)<=t)return e;let i=e;for(;i.length>1&&n(`${i}…`,r)>t;)i=i.slice(0,-1);return i.length>1?`${i}…`:``}function L_(e){return(e>=0?`+`:``)+e.toFixed(2)+`%`}function R_(e){return e.label}function z_(e,n){let r=n.min??-5,i=n.max??5;if(e<=r)return n.negative;if(e>=i)return n.positive;if(e<0){let i=1-e/r;return(0,t.lerpColor)(n.negative,n.zero,i)}let a=e/i;return(0,t.lerpColor)(n.zero,n.positive,a)}function B_(e,t,n,r,i,a){let o=Math.min(a,r/2,i/2);e.beginPath(),e.moveTo(t+o,n),e.lineTo(t+r-o,n),e.arcTo(t+r,n,t+r,n+o,o),e.lineTo(t+r,n+i-o),e.arcTo(t+r,n+i,t+r-o,n+i,o),e.lineTo(t+o,n+i),e.arcTo(t,n+i,t,n+i-o,o),e.lineTo(t,n+o),e.arcTo(t,n,t+o,n,o),e.closePath()}function V_(e,t,n,r,i,a,o,s,c,l,u){if(i<40||a<30)return;let d=n+i/2,f=r+a/2;if(e.save(),e.shadowColor=`rgba(0,0,0,0.6)`,e.shadowBlur=2,e.fillStyle=`#FFFFFF`,e.textAlign=`center`,s){let n=l(t),r=Math.min(o.font.sizeMedium,i/n.length*1.5,a/4);e.font=`bold `+Math.max(8,r)+`px `+o.font.family,e.textBaseline=c?`bottom`:`middle`,e.fillText(n,d,c?f-1:f,i-8)}if(c){let n=u(t.value),r=Math.min(o.font.sizeSmall,i/n.length*1.5,a/4);e.font=Math.max(7,r)+`px `+o.font.family,e.textBaseline=s?`top`:`middle`,e.fillText(n,d,s?f+1:f,i-8)}e.restore()}function H_(e,t,n,r,i,a,o,s){let c=[o(t),s(t.value)];if(t.meta)for(let[e,n]of Object.entries(t.meta))c.push(e+`: `+String(n));e.save(),e.font=a.font.sizeSmall+`px `+a.font.family;let l=Math.max(...c.map(t=>e.measureText(t).width))+16,u=a.font.sizeSmall+4,d=c.length*u+12,f=n.x+14,p=n.y-d/2;f+l>r&&(f=n.x-l-14),p<0&&(p=0),p+d>i&&(p=i-d),e.fillStyle=a.axisLabelBackground,e.globalAlpha=.92,B_(e,f,p,l,d,4),e.fill(),e.globalAlpha=1,e.fillStyle=a.text,e.textBaseline=`top`,e.textAlign=`left`;for(let t=0;t<c.length;t++)e.fillText(c[t],f+8,p+6+t*u);e.restore()}function U_(e,t,n,r,i,a,o,s,c=[]){if(r.length===0||i.length===0||t<=0||n<=0)return null;let l=a.colorScale,u={negative:l?.negative??`#e8505b`,zero:l?.zero??`#424242`,positive:l?.positive??`#1fa874`,min:l?.min,max:l?.max},d=a.cellRadius??4,f=a.showLabels!==!1,p=a.showValues!==!1,m=a.valueFormat??L_,h=a.labelFormat??R_,g=new Map;for(let e of r)g.set(e.id,e);let _=null,v=null;if(s)for(let e of i){let{x:t,y:n,width:r,height:i}=e.rect;if(s.x>=t&&s.x<=t+r&&s.y>=n&&s.y<=n+i){_=e.id;let t=g.get(e.id);t&&(v={cell:t,rect:e});break}}e.fillStyle=o.background,e.fillRect(0,0,t,n);for(let t of i){let n=g.get(t.id);if(!n)continue;let{x:r,y:i,width:a,height:s}=t.rect;if(a<=0||s<=0)continue;let c=z_(n.value,u);B_(e,r,i,a,s,d),e.fillStyle=c,e.fill(),V_(e,n,r,i,a,s,o,f,p,h,m),t.id===_&&(B_(e,r,i,a,s,d),e.strokeStyle=`#FFFFFF`,e.lineWidth=1.5,e.stroke())}let y=s&&!v?c.find(e=>e.header>0&&W_(e,s)):void 0;return G_(e,c,o,m,y),v&&s?H_(e,v.cell,s,t,n,o,h,m):y&&s&&H_(e,{id:``,label:y.name,value:y.value},s,t,n,o,e=>e.label,m),v}function W_(e,t){let n=e.rect;return t.x>=n.x&&t.x<=n.x+n.width&&t.y>=n.y&&t.y<=n.y+e.header}function G_(e,t,n,r,i){if(t.length===0)return;e.save(),e.textBaseline=`middle`;let a=n.font.sizeSmall,o=t=>e.measureText(t).width;for(let s of t){if(s.header<=0)continue;let{x:t,y:c,width:l}=s.rect,u=c+s.header/2+1;e.font=a+`px `+n.font.family;let d=r(s.value),f=o(d),p=l>=f*2+24;p&&(e.textAlign=`right`,e.fillStyle=s.value<0?n.candleDown:s.value>0?n.candleUp:n.textSecondary,e.fillText(d,t+l-5,u)),e.font=`600 `+a+`px `+n.font.family,e.textAlign=`left`,e.fillStyle=s===i?n.text:n.textSecondary;let m=l-10-(p?f+8:0),h=I_(s.name,m,e=>o(e),a);h&&e.fillText(h,t+5,u)}e.restore()}var K_=60,q_=12,J_=24,Y_=40,X_=.7,Z_=1;function Q_(e){return e.type?e.type:e.value>0?`positive`:e.value<0?`negative`:`subtotal`}function $_(e){let t=Math.abs(e);return t>=1e6?(e/1e6).toFixed(2)+`M`:t>=1e3?(e/1e3).toFixed(1)+`K`:e.toFixed(2)}function ev(e,t){return{left:K_,right:e-q_,top:J_,bottom:t-Y_,plotWidth:e-K_-q_,plotHeight:t-J_-Y_}}function tv(e,t,n,r,i){let a=Array(e.length),o=Array(e.length),s=t.plotWidth/e.length,c=s*n,l=(s-c)/2,{left:u,bottom:d,plotHeight:f}=t,p=0;for(let t=0;t<e.length;t++){let n=e[t],m=Q_(n),h,g;m===`total`||m===`subtotal`?(h=0,g=n.value,p=n.value):(h=p,g=p+n.value,p=g);let _=Math.min(h,g),v=Math.max(h,g),y=d-(_-r)/i*f,b=d-(v-r)/i*f,x=Math.min(y,b),S=Math.max(Math.abs(b-y),Z_),C=u+t*s,w=C+l;a[t]={label:n.label,value:n.value,start:h,end:g,type:m,rectX:w,rectY:x,rectW:c,rectH:S,slotX:C,slotW:s},o[t]=p}return{bars:a,cumulatives:o}}function nv(e){if(e.length===0)return{valMin:0,valMax:1};let t=0,n=0,r=0;for(let i=0;i<e.length;i++){let a=e[i],o=Q_(a),s,c;o===`total`||o===`subtotal`?(s=0,c=a.value,r=a.value):(s=r,c=r+a.value,r=c),s<t&&(t=s),c<t&&(t=c),s>n&&(n=s),c>n&&(n=c)}let i=(n-t||1)*.1;return{valMin:t-i,valMax:n+i}}function rv(e,t,n,r){e.fillStyle=r,e.fillRect(0,0,t,n)}function iv(e,n,r,i,a,o){let{left:s,right:c,top:l,bottom:u,plotHeight:d}=n,f=i-r||1;e.strokeStyle=a.grid,e.lineWidth=.5,e.fillStyle=a.axisLabel,e.font=`${a.font.sizeSmall}px ${a.font.family}`,e.textAlign=`right`,e.textBaseline=`middle`;let p=(0,t.computeTickStep)(r,i,5),m=Math.ceil(r/p)*p;e.beginPath();for(let t=m;t<=i;t+=p){let n=Math.round(u-(t-r)/f*d)+.5;n<l||n>u||(e.moveTo(s,n),e.lineTo(c,n))}e.stroke();for(let t=m;t<=i;t+=p){let n=u-(t-r)/f*d;n<l-1||n>u+1||e.fillText(o(t),s-6,n)}if(r<0&&i>0){let t=Math.round(u-(0-r)/f*d)+.5;e.strokeStyle=a.axisLine,e.lineWidth=1,e.beginPath(),e.moveTo(s,t),e.lineTo(c,t),e.stroke()}}function av(e,t,n){let r=[`positive`,`negative`,`total`,`subtotal`];for(let i=0;i<r.length;i++){let a=r[i],o=n[a],s=!1;e.beginPath();for(let n=0;n<t.length;n++){let r=t[n];if(r.type!==a)continue;let i=Math.round(r.rectX),o=Math.round(r.rectY),c=Math.round(r.rectW),l=Math.round(r.rectH);e.rect(i,o,c,l),s=!0}s&&(e.fillStyle=o,e.fill())}}function ov(e,t,n,r,i,a,o){if(o===`none`||t.length<2)return;let{bottom:s,plotHeight:c}=n;e.strokeStyle=a,e.lineWidth=1,o===`dashed`?e.setLineDash([4,4]):e.setLineDash([]),e.beginPath();for(let n=0;n<t.length-1;n++){let a=t[n],o=t[n+1],l=a.end,u=Math.round(s-(l-r)/i*c)+.5,d=Math.round(a.rectX+a.rectW),f=Math.round(o.rectX);f<=d||(e.moveTo(d,u),e.lineTo(f,u))}e.stroke(),e.setLineDash([])}function sv(e,t,n,r,i,a){e.fillStyle=r.text,e.font=`${r.font.sizeSmall}px ${r.font.family}`,e.textAlign=`center`;for(let r=0;r<t.length;r++){let o=t[r],s;s=o.type===`total`||o.type===`subtotal`?i(o.value):a?`${o.value>=0?`+`:``}${i(o.value)}`:i(n[r]);let c=o.rectX+o.rectW/2;o.end<o.start?(e.textBaseline=`top`,e.fillText(s,c,o.rectY+o.rectH+4)):(e.textBaseline=`bottom`,e.fillText(s,c,o.rectY-4))}}function cv(e,t,n,r,i){e.fillStyle=r.axisLabel,e.font=`${r.font.sizeSmall}px ${r.font.family}`,e.textAlign=`center`,e.textBaseline=`top`;let a=n.bottom+6,o=t.length>0?t[0].slotW-4:0,s=!1;for(let n=0;n<t.length;n++)if(e.measureText(i(t[n].label)).width>o){s=!0;break}if(!s){for(let n=0;n<t.length;n++){let r=t[n],o=r.slotX+r.slotW/2;e.fillText(i(r.label),o,a)}return}e.save(),e.textAlign=`right`,e.textBaseline=`middle`;for(let n=0;n<t.length;n++){let r=t[n],o=r.slotX+r.slotW/2;e.setTransform(1,0,0,1,o,a+4),e.rotate(-Math.PI/4),e.fillText(i(r.label),0,0)}e.setTransform(1,0,0,1,0,0),e.restore()}function lv(e,t,n){if(t<n.left||t>n.right)return null;for(let n=0;n<e.length;n++){let r=e[n];if(t>=r.slotX&&t<=r.slotX+r.slotW)return n}return null}function uv(e,t,n,r,i,a,o,s){let c=t[r],l=n[r],u=Math.round(c.slotX+c.slotW/2)+.5;e.strokeStyle=o.crosshair,e.lineWidth=.5,e.setLineDash([4,4]),e.beginPath(),e.moveTo(u,a.top),e.lineTo(u,a.bottom),e.stroke(),e.setLineDash([]);let d=[c.label,`Value: ${c.value>=0&&(c.type===`positive`||c.type===`negative`)?`+`:``}${s(c.value)}`,`Total: ${s(l)}`];e.font=`${o.font.sizeSmall}px ${o.font.family}`;let f=0;for(let t=0;t<d.length;t++){let n=e.measureText(d[t]).width;n>f&&(f=n)}let p=f+16,m=d.length*(o.font.sizeSmall+4)+12,h=i.x+10,g=i.y-m/2;h+p>a.right&&(h=i.x-p-10),g<a.top&&(g=a.top),g+m>a.bottom&&(g=a.bottom-m),e.fillStyle=o.axisLabelBackground,e.globalAlpha=.9,e.fillRect(h,g,p,m),e.globalAlpha=1,e.fillStyle=o.text,e.textAlign=`left`,e.textBaseline=`top`;let _=o.font.sizeSmall+4;for(let t=0;t<d.length;t++)e.fillText(d[t],h+8,g+6+t*_)}function dv(e,t,n,r,i,a){let{data:o}=r;if(!o||o.length===0||t<=0||n<=0)return{hitBar:null};let s=r.positiveColor??i.candleUp,c=r.negativeColor??i.candleDown,l=r.totalColor??i.lineColor,u=r.subtotalColor??i.textSecondary,d=r.connectorColor??i.textSecondary,f=r.connectorStyle??`dashed`,p=r.barWidth??X_,m=r.showValues!==!1,h=r.showDelta!==!1,g=r.valueFormat??$_,_=r.labelFormat??(e=>e),{valMin:v,valMax:y}=nv(o),b=y-v||1,x=ev(t,n),{bars:S,cumulatives:C}=tv(o,x,p,v,b);rv(e,t,n,i.background),iv(e,x,v,y,i,g),ov(e,S,x,v,b,d,f),av(e,S,{positive:s,negative:c,total:l,subtotal:u}),m&&sv(e,S,C,i,g,h),cv(e,S,x,i,_);let w=a?lv(S,a.x,x):null;return a&&w!==null&&uv(e,S,C,w,a,x,i,g),{hitBar:w}}var fv=Math.PI/180,pv=150,mv=240,hv=90,gv=.14,_v=1.6*fv,vv=.22,yv=8,bv=18,xv=16,Sv=6.5,Cv=20,wv=5,Tv=28;function Ev(e,t,n){return e<t?t:e>n?n:e}function Dv(e){let t=Math.abs(e);return t>=1e6?(e/1e6).toFixed(2)+`M`:t>=1e3?(e/1e3).toFixed(1)+`K`:Number.isInteger(e)?e.toFixed(0):e.toFixed(1)}function Ov(e){let t=Number.isFinite(e.startAngle)?e.startAngle:pv,n=(Number.isFinite(e.endAngle)?e.endAngle:t+mv)-t;return n<=0&&(n=(n%360+360)%360||360),n=Ev(n,hv,360),{start:(t%360+360)%360*fv,sweep:n*fv}}function kv(e,t){let n=Math.min(Math.cos(e),Math.cos(t)),r=Math.max(Math.cos(e),Math.cos(t)),i=Math.min(Math.sin(e),Math.sin(t)),a=Math.max(Math.sin(e),Math.sin(t));for(let o=Math.ceil(e/(Math.PI/2));Math.PI/2*o<=t;o++){let e=Math.PI/2*o;n=Math.min(n,Math.cos(e)),r=Math.max(r,Math.cos(e)),i=Math.min(i,Math.sin(e)),a=Math.max(a,Math.sin(e))}return{minX:n,maxX:r,minY:i,maxY:a}}function Av(e){if(e.showZoneLabels!==!0||!e.zones)return 0;let t=e.zones.reduce((e,t)=>Math.max(e,t.label?.length??0),0);return t>0?t*Sv+12:0}function jv(e,t,n){let r=Number.isFinite(n.min)?n.min:0,i=Number.isFinite(n.max)?n.max:100;i-r>Math.abs(r)*1e-9||(i=r+Math.max(1,Math.abs(r)*1e-6));let{start:a,sweep:o}=Ov(n),s=a,c=a+o,l=Ev(n.thickness??gv,.04,.5),u=kv(s,c),d=Math.max(u.maxY,.18),f=Av(n),p=f>0?xv:0,m=Math.max(1,e-2*yv-2*f),h=Math.max(1,t-2*yv-bv-p),g=1+l/2,_=Math.max(8,Math.min(m/((u.maxX-u.minX)*g),h/((d-u.minY)*g))),v=_*l,y=(d-u.minY)*_*g+bv+p,b=e/2-(u.maxX+u.minX)/2*_,x=(t-y)/2+p-u.minY*_*g,S=_-v/2,C=Math.max(11,Math.round(S*.46)),w=u.maxY>.3?x-C*.12:x-C*.55,T=Math.max(Math.sin(s),Math.sin(c)),E=T>.2?x+T*_+v/2+2:1/0,D=Math.min(t-yv,E);return{cx:b,cy:x,radius:_,thickness:v,startAngle:s,endAngle:c,min:r,max:i,valueY:w,valueSize:C,textBottom:D}}function Mv(e,t){let n=Number.isFinite(e)?Ev((e-t.min)/(t.max-t.min),0,1):0;return t.startAngle+(t.endAngle-t.startAngle)*n}function Nv(e,t){if(!t||!Number.isFinite(e))return;let n;for(let r of t)e>=r.from&&e<=r.to&&(n=r);return n}function Pv(e,t,n){let r=(t??[]).map(t=>({a0:Mv(t.from,e),a1:Mv(t.to,e),color:t.color,track:!1})).filter(e=>e.a1>e.a0).sort((e,t)=>e.a0-t.a0),i=[],a=e.startAngle;for(let e of r)e.a1<=a||(e.a0>a+1e-9&&i.push({a0:a,a1:e.a0,color:n,track:!0}),i.push({...e,a0:Math.max(e.a0,a)}),a=e.a1);return a<e.endAngle-1e-9&&i.push({a0:a,a1:e.endAngle,color:n,track:!0}),i}function Fv(e,t,n,r,i){r<=n||(e.beginPath(),e.arc(t.cx,t.cy,t.radius,n,r,!1),e.lineWidth=t.thickness,e.lineCap=`butt`,e.strokeStyle=i,e.stroke())}function Iv(e,t,n,r,i,a){let o=t.cx+Math.cos(n)*t.radius,s=t.cy+Math.sin(n)*t.radius,c=a===`start`?n-Math.PI:n;e.globalAlpha=i,e.beginPath(),e.arc(o,s,t.thickness/2,c,c+(i>=1?Math.PI*2:Math.PI),!1),e.closePath(),e.fillStyle=r,e.fill(),e.globalAlpha=1}function Lv(e,t,n,r,i,a){let o=Pv(t,n,i),s=o.some(e=>!e.track);o.forEach((n,i)=>{let a=i>0&&!n.track&&!o[i-1].track?_v/2:0,s=i<o.length-1&&!n.track&&!o[i+1].track?_v/2:0,c=n.a0+a,l=n.a1-s;if(n.track){Fv(e,t,c,l,n.color);return}e.globalAlpha=vv,Fv(e,t,c,l,n.color),e.globalAlpha=1,Fv(e,t,c,Math.min(l,r),n.color)}),s||Fv(e,t,t.startAngle,r,a);let c=r>t.startAngle+1e-9,l=r>=t.endAngle-1e-9,u=(e,t)=>e.track?[!s&&t?a:i,1]:[e.color,t?1:vv],[d,f]=u(o[0],c),[p,m]=u(o[o.length-1],l);Iv(e,t,t.startAngle,d,f,`start`),Iv(e,t,t.endAngle,p,m,`end`)}function Rv(e,t,n){let r=t.radius-t.thickness/2;if(r<Tv)return;let i=Math.max(4,t.thickness*.45);e.strokeStyle=n,e.lineCap=`butt`;for(let n=0;n<=Cv;n++){let a=n%wv===0,o=t.startAngle+(t.endAngle-t.startAngle)*n/Cv,s=r-i,c=s-(a?Math.max(6,t.thickness*.55):Math.max(3,t.thickness*.3));e.globalAlpha=a?.55:.3,e.lineWidth=a?1.5:1,e.beginPath(),e.moveTo(t.cx+Math.cos(o)*s,t.cy+Math.sin(o)*s),e.lineTo(t.cx+Math.cos(o)*c,t.cy+Math.sin(o)*c),e.stroke()}e.globalAlpha=1}function zv(e,t,n,r,i){let a=t.cx+Math.cos(n)*t.radius,o=t.cy+Math.sin(n)*t.radius;e.beginPath(),e.arc(a,o,t.thickness*.78,0,Math.PI*2),e.fillStyle=r,e.fill(),e.lineWidth=Math.max(2,t.thickness*.32),e.strokeStyle=i,e.stroke()}function Bv(e,t,n,r,i){let a=Math.cos(n),o=Math.sin(n),s=t.radius-t.thickness*.9,c=Math.max(6,t.thickness*.6),l=Math.max(1.5,t.thickness*.14);e.beginPath(),e.moveTo(t.cx+a*s,t.cy+o*s),e.lineTo(t.cx-o*l-a*c,t.cy+a*l-o*c),e.lineTo(t.cx+o*l-a*c,t.cy-a*l-o*c),e.closePath(),e.fillStyle=r,e.fill(),e.beginPath(),e.arc(t.cx,t.cy,Math.max(4,t.thickness*.42),0,Math.PI*2),e.fill(),e.lineWidth=2,e.strokeStyle=i,e.stroke()}function Vv(e,t,n,r,i,a,o){e.font=`${n} ${r}px ${i}`;let s=e.measureText(t).width;if(s<=a)return r;let c=Math.floor(r*a/s);return c<o?0:(e.font=`${n} ${c}px ${i}`,c)}function Hv(e,t,n,r,i,a,o){let s=a.font.family,c=(t.radius-t.thickness/2)*1.3,l=a.font.sizeSmall;e.textAlign=`center`,e.textBaseline=`middle`;let u=Vv(e,n,`600`,t.valueSize,s,c,l);if(u===0)return;let d=o?Math.min(t.cy+u*.8,t.textBottom-u/2):t.valueY;e.fillStyle=a.text,e.fillText(n,t.cx,d);let f=Math.max(l,Math.round(u*.26));if(i?.label&&!o){let n=i.label.toUpperCase();Vv(e,n,`600`,f,s,c*.9,l)>0&&(e.fillStyle=i.color,e.fillText(n,t.cx,d-u*.78))}if(r){let n=d+u*.72;n+f/2<=t.textBottom&&Vv(e,r,`400`,f,s,c,l)>0&&(e.fillStyle=a.textSecondary,e.fillText(r,t.cx,n))}}function Uv(e,t,n,r){e.fillStyle=r.textSecondary,e.font=`${r.font.sizeSmall+1}px ${r.font.family}`;let i=t.thickness/2+6;for(let[r,a]of[[t.startAngle,t.min],[t.endAngle,t.max]]){let o=Math.cos(r),s=Math.sin(r),c=t.cx+o*t.radius,l=t.cy+s*t.radius;s>.2?(e.textAlign=`center`,e.textBaseline=`top`,e.fillText(n(a),c,l+i)):(e.textAlign=o<-.2?`right`:o>.2?`left`:`center`,e.textBaseline=s<-.2?`bottom`:`middle`,e.fillText(n(a),c+o*i,l+s*i))}}function Wv(e,t,n,r){e.fillStyle=r.textSecondary,e.font=`${r.font.sizeSmall}px ${r.font.family}`,e.textBaseline=`middle`;let i=t.radius+t.thickness/2+8;for(let r of n){if(!r.label)continue;let n=Mv((Ev(r.from,t.min,t.max)+Ev(r.to,t.min,t.max))/2,t),a=Math.cos(n);e.textAlign=a<-.2?`right`:a>.2?`left`:`center`,e.fillText(r.label,t.cx+a*i,t.cy+Math.sin(n)*i)}}function Gv(e,t,n,r,i,a){if(t<=0||n<=0)return;let o=jv(t,n,r),s=Number.isFinite(a),c=s?Ev(a,o.min,o.max):o.min,l=Mv(c,o),u=s?Nv(c,r.zones):void 0,d=r.pointer===`needle`,f=r.valueFormat??Dv,p=u?.color??r.needleColor??i.lineColor;e.save(),e.fillStyle=i.background,e.fillRect(0,0,t,n),Lv(e,o,r.zones,l,r.trackColor??i.grid,p),Rv(e,o,i.textSecondary),s&&(d?Bv(e,o,l,r.needleColor??i.text,i.background):zv(e,o,l,p,i.background)),r.showValue!==!1&&Hv(e,o,s?f(c):`—`,r.label,u,i,d),Uv(e,o,f,i),r.showZoneLabels===!0&&r.zones?.length&&Wv(e,o,r.zones,i),e.restore()}var Kv=12,qv=.72,Jv=20,Yv=.35;function Xv(e){let t=0,n=0,r=e.mode===`stacked`;return e.categories.forEach((i,a)=>{let o=0,s=0;for(let i of e.series){let e=i.values[a];Number.isFinite(e)&&(r?e>=0?o+=e:s+=e:(n=Math.max(n,e),t=Math.min(t,e)))}n=Math.max(n,o),t=Math.min(t,s)}),[t,n]}function Zv(e,t){let n=e.colorBySign;return n?n===!0?{positive:t.candleUp,negative:t.candleDown}:n:null}function Qv(e,t,n,r,i){let a=e.orientation===`horizontal`,o=e.legend??e.series.length>1?M_(e.series.map((e,t)=>({label:e.name,color:A_(t,e.color)})),t-Kv*2,i):null,s=Kv+(o?o.height+6:0),[c,l]=Xv(e),u=E_(c,l,a?Math.max(2,Math.floor(t/110)):5),d=e.valueFormat??Q(u),f=Math.max(0,...u.ticks.map(e=>i(d(e),11))),p;if(a){let r=Kv+Math.min(t*Yv,Math.max(0,...e.categories.map(e=>i(e,11))))+8;p={x:r,y:s,width:Math.max(1,t-r-Kv-f/2),height:Math.max(1,n-s-Kv-Jv)}}else{let e=Kv+f+8;p={x:e,y:s,width:Math.max(1,t-e-Kv),height:Math.max(1,n-s-Kv-Jv)}}let m=Math.max(1,e.categories.length),h=a?p.y:p.x,g=(a?p.height:p.width)/m,_=g*qv,v=e.mode===`stacked`,y=v?_:_/Math.max(1,e.series.length),b=e=>a?Z(u,e,p.x,p.width):Z(u,e,p.y,p.height,!0),x=b(0),S=Zv(e,r),C=Array(m).fill(0),w=Array(m).fill(0),T=[];return e.series.forEach((t,n)=>{e.categories.forEach((e,r)=>{let i=t.values[r];if(!Number.isFinite(i))return;let o=0;v&&(o=i>=0?C[r]:w[r],i>=0?C[r]+=i:w[r]+=i);let s=b(o),c=b(o+i),l=h+r*g+(g-_)/2+(v?0:n*y),u=S?i>=0?S.positive:S.negative:A_(n,t.color),d=Math.min(s,c),f=Math.abs(c-s);T.push(a?{x:d,y:l,width:f,height:y,category:e,series:t.name,value:i,index:r,color:u}:{x:l,y:d,width:y,height:f,category:e,series:t.name,value:i,index:r,color:u})})}),{plot:p,scale:u,orientation:a?`horizontal`:`vertical`,zero:x,bars:T,bandStart:h,band:g,legend:o,legendY:Kv}}function $v(e,t,n){for(let r of e.bars)if(t>=r.x-2&&t<=r.x+r.width+2&&n>=r.y-2&&n<=r.y+r.height+2)return r;return null}function ey(e,t,n,r){let{plot:i}=e;if(t<i.x||t>i.x+i.width||n<i.y||n>i.y+i.height)return-1;let a=e.orientation===`horizontal`?n:t,o=Math.floor((a-e.bandStart)/e.band);return o>=0&&o<r?o:-1}function ty(e,n,r,i,a,o,s=Qv(i,n,r,a,j_(e,a))){let c=j_(e,a),l=i.valueFormat??k_,{plot:u,orientation:d}=s,f=d===`horizontal`;e.fillStyle=a.background,e.fillRect(0,0,n,r),s.legend&&N_(e,s.legend,Kv,s.legendY,a),F_(e,u,s.scale,f?`horizontal`:`vertical`,a,i.valueFormat??Q(s.scale));let p=o&&i.crosshair!==!1?ey(s,o.x,o.y,i.categories.length):-1;if(p>=0){e.fillStyle=(0,t.withAlpha)(a.crosshair,.08);let n=s.bandStart+p*s.band;f?e.fillRect(u.x,n,u.width,s.band):e.fillRect(n,u.y,s.band,u.height)}for(let t of s.bars)e.fillStyle=t.color,e.fillRect(t.x,t.y,Math.max(t.width,+!!f),Math.max(t.height,+!f));e.strokeStyle=a.axisLine,e.lineWidth=1,e.beginPath();let m=Math.round(s.zero)+.5;if(f?(e.moveTo(m,u.y),e.lineTo(m,u.y+u.height)):(e.moveTo(u.x,m),e.lineTo(u.x+u.width,m)),e.stroke(),ny(e,i.categories,s,a,c),i.showValues&&ry(e,s,a,l,i.mode===`stacked`),p>=0&&o){let t=[{text:i.categories[p],bold:!0}];for(let e of s.bars)e.index===p&&t.push({text:`${e.series}: ${l(e.value)}`,color:e.color});P_(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}function ny(e,t,n,r,i){let{plot:a}=n;e.save(),e.font=$(r,11),e.fillStyle=r.axisLabel;let o=Math.max(0,...t.map(e=>i(e,11))),s=n.orientation===`vertical`?Math.max(1,Math.ceil((o+8)/Math.max(1,n.band))):1;t.forEach((t,r)=>{if(r%s!==0)return;let o=n.bandStart+(r+.5)*n.band;n.orientation===`horizontal`?(e.textAlign=`right`,e.textBaseline=`middle`,e.fillText(I_(t,a.x-Kv-8,i),a.x-8,o)):(e.textAlign=`center`,e.textBaseline=`top`,e.fillText(I_(t,n.band*s-4,i),o,a.y+a.height+6))}),e.restore()}function ry(e,t,n,r,i){e.save(),e.font=$(n,10),e.fillStyle=n.textSecondary;for(let n of t.bars){let a=r(n.value);if(t.orientation===`horizontal`){e.textBaseline=`middle`;let t=n.y+n.height/2;i?(e.textAlign=`center`,e.measureText(a).width<n.width-4&&e.fillText(a,n.x+n.width/2,t)):n.value>=0?(e.textAlign=`left`,e.fillText(a,n.x+n.width+4,t)):(e.textAlign=`right`,e.fillText(a,n.x-4,t))}else{e.textAlign=`center`;let t=n.x+n.width/2;i?(e.textBaseline=`middle`,n.height>13&&e.measureText(a).width<n.width&&e.fillText(a,t,n.y+n.height/2)):n.value>=0?(e.textBaseline=`bottom`,e.fillText(a,t,n.y-3)):(e.textBaseline=`top`,e.fillText(a,t,n.y+n.height+3))}}e.restore()}var iy=12,ay=-Math.PI/2,oy=Math.PI*2,sy=5,cy=1.4,ly=18,uy=new Intl.NumberFormat(void 0,{style:`percent`,maximumFractionDigits:1});function dy(e,t,n,r,i){let a=e.data.filter(e=>Number.isFinite(e.value)&&e.value>0),o=a.reduce((e,t)=>e+t.value,0),s=a.map((e,t)=>({label:`${e.label} ${uy.format(e.value/o)}`,color:A_(t,e.color)})),c=e.legend!==!1&&a.length>0,l=c&&t>=n*cy&&a.length*ly<=n-iy*2,u=l?Math.min(t*.4,Math.max(...s.map(e=>i(e.label,11)))+16):t-iy*2,d=c?M_(s,u,i,l):null,f=l?t-u-iy*3:t-iy*2,p=l?n-iy*2:n-iy*3-(d?.height??0),m=Math.max(0,Math.min(f,p)/2-sy),h=iy+f/2,g=iy+p/2,_=e.innerRadius,v=Math.min(.95,Math.max(0,_!==void 0&&Number.isFinite(_)?_:.6)),y=ay,b=a.map((e,t)=>{let n=e.value/o,r=y;return y+=n*oy,{label:e.label,value:e.value,share:n,start:r,end:y,color:A_(t,e.color),slice:e}});return{cx:h,cy:g,radius:m,inner:m*v,total:o,slices:b,legend:d,legendX:l?t-u-iy:iy,legendY:l?Math.max(iy,g-(d?.height??0)/2):iy*2+p}}function fy(e,t,n){let r=t-e.cx,i=n-e.cy,a=Math.hypot(r,i);if(a<e.inner||a>e.radius+sy)return null;let o=Math.atan2(i,r);for(;o<ay;)o+=oy;return e.slices.find(e=>o>=e.start&&o<e.end)??null}function py(e,t,n,r,i,a,o=dy(r,t,n,i,j_(e,i))){let s=j_(e,i),c=r.valueFormat??k_;e.fillStyle=i.background,e.fillRect(0,0,t,n);let l=a&&r.crosshair!==!1?fy(o,a.x,a.y):null,{cx:u,cy:d,radius:f,inner:p}=o;for(let t of o.slices){let n=(t.start+t.end)/2,r=t===l?sy:0,a=u+Math.cos(n)*r,s=d+Math.sin(n)*r;e.beginPath(),e.arc(a,s,f,t.start,t.end),p>0?e.arc(a,s,p,t.end,t.start,!0):e.lineTo(a,s),e.closePath(),e.fillStyle=t.color,e.fill(),o.slices.length>1&&(e.strokeStyle=i.background,e.lineWidth=1.5,e.stroke())}return r.showLabels!==!1&&my(e,o,i),hy(e,o,r,i,s),o.legend&&N_(e,o.legend,o.legendX,o.legendY,i),l&&a&&P_(e,[{text:l.label,bold:!0,color:l.color},{text:`${c(l.value)} · ${uy.format(l.share)}`}],a,{x:0,y:0,width:t,height:n},i),o}function my(e,t,n){let{cx:r,cy:i,radius:a,inner:o}=t,s=o>0?(a+o)/2:a*.62;e.save(),e.font=$(n,11,`600`),e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=`#fff`;for(let n of t.slices){let t=uy.format(n.share);if((n.end-n.start)*s<e.measureText(t).width+8||o>0&&a-o<15)continue;let c=(n.start+n.end)/2;e.fillText(t,r+Math.cos(c)*s,i+Math.sin(c)*s)}e.restore()}function hy(e,t,n,r,i){if(t.inner<=0||!n.centerLabel&&!n.centerValue)return;let a=t.inner*1.6;if(e.save(),e.textAlign=`center`,e.textBaseline=`middle`,n.centerValue){let o=Math.max(12,Math.min(28,t.inner*.42));e.font=$(r,o,`600`),e.fillStyle=r.text,e.fillText(I_(n.centerValue,a,i,o),t.cx,t.cy+(n.centerLabel?o*.35:0))}n.centerLabel&&(e.font=$(r,11),e.fillStyle=r.textSecondary,e.fillText(I_(n.centerLabel,a,i),t.cx,t.cy-(n.centerValue?11*1.1:0))),e.restore()}var gy=12,_y=5,vy=3,yy=18,by=20,xy=6;function Sy(e,n,r,i,a){let o=1/0,s=-1/0,c=1/0,l=-1/0,u=0;for(let t of e.series)for(let e of t.points)!Number.isFinite(e.x)||!Number.isFinite(e.y)||(e.x<o&&(o=e.x),e.x>s&&(s=e.x),e.y<c&&(c=e.y),e.y>l&&(l=e.y),e.size!==void 0&&Number.isFinite(e.size)&&e.size>u&&(u=e.size));let d=e.maxRadius??24,f=d+xy,p=(e,t,n)=>{if(e>t)return[0,1];let r=(t-e)*f/Math.max(1,n-f*2);return[e>=0?Math.max(0,e-r):e-r,t<=0?Math.min(0,t+r):t+r]},m=E_(...p(o,s,n*.8),Math.max(2,Math.floor(n/110))),h=E_(...p(c,l,r*.7),5),g=e.xFormat??Q(m),_=e.yFormat??Q(h),v=e.legend??e.series.length>1?M_(e.series.map((e,t)=>({label:e.name,color:A_(t,e.color)})),n-gy*2,a):null,y=gy+(v?v.height+6:0),b=Math.max(0,...h.ticks.map(e=>a(_(e),11))),x=gy+(e.yLabel?yy:0)+b+8,S=gy+by+(e.xLabel?yy:0),C=a(g(m.max),11)/2,w={x,y,width:Math.max(1,n-x-gy-C),height:Math.max(1,r-y-S)},T=[];return e.series.forEach((e,n)=>{let r=A_(n,e.color),i=(0,t.withAlpha)(r,.55),a=(0,t.withAlpha)(r,.85);for(let t of e.points){if(!Number.isFinite(t.x)||!Number.isFinite(t.y))continue;let n=t.size!==void 0&&Number.isFinite(t.size)&&t.size>0&&u>0?Math.max(vy,d*Math.sqrt(t.size/u)):_y;T.push({px:Z(m,t.x,w.x,w.width),py:Z(h,t.y,w.y,w.height,!0),r:n,color:r,fill:i,hoverFill:a,series:e.name,label:t.label,point:t})}}),{plot:w,xScale:m,yScale:h,points:T,drawOrder:T.map((e,t)=>t).sort((e,t)=>T[t].r-T[e].r),legend:v}}function Cy(e,t,n){let r=null,i=1/0;for(let a of e.points){let e=Math.hypot(a.px-t,a.py-n);e<=a.r+xy&&e<i&&(r=a,i=e)}return r}function wy(e,t,n,r,i,a,o=Sy(r,t,n,i,j_(e,i))){let{plot:s,xScale:c,yScale:l}=o,u=r.xFormat??Q(c),d=r.yFormat??Q(l);e.fillStyle=i.background,e.fillRect(0,0,t,n),o.legend&&N_(e,o.legend,gy,gy,i),F_(e,s,l,`vertical`,i,d),F_(e,s,c,`horizontal`,i,u),r.zeroLines!==!1&&Ty(e,o,i),Ey(e,o,r,i);let f=a&&r.crosshair!==!1?Cy(o,a.x,a.y):null;e.save(),e.beginPath(),e.rect(s.x,s.y,s.width,s.height),e.clip();for(let t of o.drawOrder){let n=o.points[t];e.beginPath(),e.arc(n.px,n.py,n===f?n.r+2:n.r,0,Math.PI*2),e.fillStyle=n===f?n.hoverFill:n.fill,e.fill(),e.strokeStyle=n.color,e.lineWidth=1,e.stroke()}if(e.restore(),r.showLabels){e.save(),e.font=$(i,10),e.fillStyle=i.textSecondary,e.textAlign=`left`,e.textBaseline=`middle`;for(let t of o.points)t.label&&e.fillText(t.label,t.px+t.r+4,t.py);e.restore()}if(f&&a){let o=[{text:f.label??f.series,bold:!0,color:f.color}];f.label&&r.series.length>1&&o.push({text:f.series}),o.push({text:`${r.xLabel??`x`}: ${(r.xFormat??k_)(f.point.x)}`}),o.push({text:`${r.yLabel??`y`}: ${(r.yFormat??k_)(f.point.y)}`}),f.point.size!==void 0&&o.push({text:k_(f.point.size)}),P_(e,o,a,{x:0,y:0,width:t,height:n},i)}return o}function Ty(e,t,n){let{plot:r,xScale:i,yScale:a}=t;if(e.save(),e.strokeStyle=n.axisLine,e.lineWidth=1,e.beginPath(),i.min<0&&i.max>0){let t=Math.round(Z(i,0,r.x,r.width))+.5;e.moveTo(t,r.y),e.lineTo(t,r.y+r.height)}if(a.min<0&&a.max>0){let t=Math.round(Z(a,0,r.y,r.height,!0))+.5;e.moveTo(r.x,t),e.lineTo(r.x+r.width,t)}e.stroke(),e.restore()}function Ey(e,t,n,r){let{plot:i}=t;e.save(),e.font=$(r,11,`600`),e.fillStyle=r.textSecondary,e.textAlign=`center`,n.xLabel&&(e.textBaseline=`bottom`,e.fillText(n.xLabel,i.x+i.width/2,i.y+i.height+by+yy)),n.yLabel&&(e.translate(gy+11/2,i.y+i.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}var Dy=1e-9,Oy=1e3,ky=e=>{let t=Number(e.toPrecision(12));return t===0?0:t};function Ay(e,t={}){let n=e.filter(e=>Number.isFinite(e));if(n.length===0)return[];let r=1/0,i=-1/0;for(let e of n)e<r&&(r=e),e>i&&(i=e);if(r===i)return[{from:r,to:i,count:n.length}];let a=t.binWidth;if(a!==void 0&&a>0&&Number.isFinite(a)){let e=Math.floor(r/a+Dy),t=Math.max(e,Math.ceil(i/a-Dy)-1)-e+1;if(t<=1e3){let r=Array.from({length:t},(t,n)=>({from:ky((e+n)*a),to:ky((e+n+1)*a),count:0}));for(let i of n)r[Math.min(t-1,Math.floor(i/a+Dy)-e)].count++;return r}}let o=t.bins,s=typeof o==`number`&&Number.isFinite(o)&&o>=1?Math.min(Oy,Math.floor(o)):Math.min(Oy,Math.ceil(Math.log2(n.length))+1),c=(i-r)/s,l=Array.from({length:s},(e,t)=>({from:ky(r+t*c),to:ky(t===s-1?i:r+(t+1)*c),count:0}));for(let e of n)l[Math.min(s-1,Math.floor((e-r)/c+Dy))].count++;return l}var jy=12,My=20,Ny=16;function Py(e,n,r){return n.colorBySign?(e.from+e.to)/2<0?r.candleDown:r.candleUp:n.color??t.TC_SERIES_COLORS[0]}function Fy(e,t,n,r,i){let a=Ay(e.values,{bins:e.bins,binWidth:e.binWidth}),o=a.length>0?a[0].from:0,s=a.length>0?a[a.length-1].to:1,c=(e.markers??[]).map(e=>e.value).filter(e=>Number.isFinite(e)),l=E_(Math.min(o,...c),Math.max(s,...c),Math.max(2,Math.floor(t/110))),u=0;for(let e of a)e.count>u&&(u=e.count);let d=E_(0,Math.max(4,u),4),f=e.valueFormat??Q(l),p=Math.max(0,...d.ticks.map(e=>i(Q(d)(e),11))),m=jy+(c.length>0?Ny:0),h=jy+p+8,g=jy+i(f(l.max),11)/2,_={x:h,y:m,width:Math.max(1,t-h-g),height:Math.max(1,n-m-jy-My)};return{plot:_,xScale:l,yScale:d,bars:a.map(t=>{let n=Z(l,t.from,_.x,_.width),i=t.to>t.from?Z(l,t.to,_.x,_.width):n+_.width/10,a=Z(d,t.count,_.y,_.height,!0);return{x:n,y:a,width:Math.max(1,i-n),height:_.y+_.height-a,bin:t,color:Py(t,e,r)}}),total:a.reduce((e,t)=>e+t.count,0)}}function Iy(e,t,n){let{plot:r}=e;return n<r.y||n>r.y+r.height?null:e.bars.find(e=>t>=e.x&&t<e.x+e.width)??null}var Ly=new Intl.NumberFormat(void 0,{style:`percent`,maximumFractionDigits:1});function Ry(e,n,r,i,a,o,s=Fy(i,n,r,a,j_(e,a))){let c=i.valueFormat??k_,{plot:l}=s;e.fillStyle=a.background,e.fillRect(0,0,n,r),F_(e,l,s.yScale,`vertical`,a,Q(s.yScale)),F_(e,l,s.xScale,`horizontal`,a,i.valueFormat??Q(s.xScale));let u=o&&i.crosshair!==!1?Iy(s,o.x,o.y):null;for(let n of s.bars)e.fillStyle=n===u?n.color:(0,t.withAlpha)(n.color,.75),e.fillRect(n.x+(n.width>3?.5:0),n.y,Math.max(1,n.width-+(n.width>3)),n.height);if(zy(e,s,i,a,c),u&&o){let{bin:t}=u;P_(e,[{text:t.to>t.from?`${c(t.from)} – ${c(t.to)}`:c(t.from),bold:!0,color:u.color},{text:`${k_(t.count)} · ${Ly.format(s.total>0?t.count/s.total:0)}`}],o,{x:0,y:0,width:n,height:r},a)}return s}function zy(e,t,n,r,i){let{plot:a}=t;e.save(),e.font=$(r,10),e.textAlign=`center`,e.textBaseline=`bottom`;let o=[];for(let s of n.markers??[]){if(!Number.isFinite(s.value))continue;let n=Math.round(Z(t.xScale,s.value,a.x,a.width))+.5,c=s.color??r.text;e.strokeStyle=c,e.setLineDash([4,3]),e.lineWidth=1,e.beginPath(),e.moveTo(n,a.y),e.lineTo(n,a.y+a.height),e.stroke(),e.setLineDash([]),e.fillStyle=c;let l=s.label?`${s.label} ${i(s.value)}`:i(s.value),u=e.measureText(l).width/2+4,d=0;for(;o.some(e=>e.row===d&&n-u<e.to&&n+u>e.from);)d++;o.push({from:n-u,to:n+u,row:d}),e.fillText(l,n,a.y-3+d*14)}e.restore()}var By=8,Vy=32,Hy=new Map;function Uy(e){let t=Hy.get(e);return t===void 0&&(t=Wy(e),Hy.size>512&&Hy.clear(),Hy.set(e,t)),t}function Wy(e){let t=e.trim(),n=t.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);if(n){let e=n[1];return e.length<=4&&(e=[...e.slice(0,3)].map(e=>e+e).join(``)),[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]}let r=t.match(/^rgba?\(\s*(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)/i);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function Gy(e,t,n){let r=Uy(e),i=Uy(t);if(!r||!i)return n<.5?e:t;let a=e=>Math.round(r[e]+(i[e]-r[e])*n);return`rgb(${a(0)},${a(1)},${a(2)})`}function Ky(e,t,n){let r=1/0,i=-1/0;for(let t of e)Number.isFinite(t)&&(t<r&&(r=t),t>i&&(i=t));let a=0,o=1;if(r<=i){let e=Math.max(Math.abs(r),Math.abs(i))||1;a=r<0?-e:0,o=r<0?e:i||1}return{negative:n?.negative??t.candleDown,zero:n?.zero??Gy(t.background,t.text,.14),positive:n?.positive??t.candleUp,min:n?.min!==void 0&&Number.isFinite(n.min)?n.min:a,max:n?.max!==void 0&&Number.isFinite(n.max)?n.max:o}}function qy(e,t){return!Number.isFinite(e)||e===0?Gy(t.zero,t.zero,0):e<0?Gy(t.zero,t.negative,t.min<0?Math.min(1,e/t.min):1):Gy(t.zero,t.positive,t.max>0?Math.min(1,e/t.max):1)}var Jy=`#11151b`,Yy=.0076;function Xy(e){let t=Uy(e);if(!t)return`#ffffff`;let[n,r,i]=t.map(e=>{let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}),a=.2126*n+.7152*r+.0722*i;return(a+.05)/(Yy+.05)>1.05/(a+.05)?Jy:`#ffffff`}function Zy(e,t,n,r,i){let a=Math.min(180,t.width);if(a<40||!(n.max>n.min))return;let{x:o,y:s}=t,c=n.max-n.min;e.save();for(let t=0;t<Vy;t++){let r=(t+.5)/Vy;e.fillStyle=qy(n.min+c*r,n),e.fillRect(o+a*t/Vy,s,a/Vy+.5,By)}e.font=$(i,10),e.fillStyle=i.textSecondary,e.textBaseline=`top`;let l=s+By+4;e.textAlign=`left`,e.fillText(r(n.min),o,l),e.textAlign=`right`,e.fillText(r(n.max),o+a,l);let u=o+a*-n.min/c;n.min<0&&n.max>0&&u-o>28&&o+a-u>28&&(e.textAlign=`center`,e.fillText(r(0),u,l)),e.restore()}var Qy=864e5,$y=3,eb=12,tb=16,nb=10,rb=28,ib=6;function ab(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;let[n,r,i]=[Number(t[1]),Number(t[2]),Number(t[3])],a=Date.UTC(n,r-1,i),o=new Date(a);return o.getUTCFullYear()!==n||o.getUTCMonth()!==r-1||o.getUTCDate()!==i?null:Math.round(a/Qy)}function ob(e){return new Date(e*Qy).toISOString().slice(0,10)}var sb=e=>((e+4)%7+7)%7;function cb(e,t){let n=e.from===void 0?null:ab(e.from),r=e.to===void 0?null:ab(e.to);if(n===null||r===null){let e=1/0,i=-1/0;for(let n of t.keys())n<e&&(e=n),n>i&&(i=n);n??=Number.isFinite(e)?e:null,r??=Number.isFinite(i)?i:null}if(n===null||r===null||n>r)return null;let i=new Date(r*Qy).getUTCFullYear()-10+1;return[Math.max(n,Math.round(Date.UTC(i,0,1)/Qy)),r]}function lb(e,t,n){let r=[],i=e;for(;i<=t;){let e=new Date(i*Qy).getUTCFullYear(),a=Math.min(t,Math.round(Date.UTC(e,11,31)/Qy)),o=i-n(i);r.push({year:e,first:i,last:a,origin:o,weeks:Math.floor((a-o)/7)+1}),i=a+1}return r}var ub=new Map;function db(e){let t=e??``,n=ub.get(t);if(!n){try{n={month:new Intl.DateTimeFormat(e,{month:`short`,timeZone:`UTC`}),weekday:new Intl.DateTimeFormat(e,{weekday:`short`,timeZone:`UTC`}),long:new Intl.DateTimeFormat(e,{dateStyle:`full`,timeZone:`UTC`})}}catch{n=db(void 0)}ub.set(t,n)}return n}function fb(e,t,n,r,i){let a=new Map;for(let t of e.data){let e=ab(t.date);e!==null&&Number.isFinite(t.value)&&a.set(e,t)}let o=db(e.locale),s=e.dateFormat??(e=>o.long.format(new Date(`${e}T00:00:00Z`))),c=e.weekdays===5,l=e=>!c||sb(e)>=1&&sb(e)<=5,u=cb(e,a),d=t-eb*2,f=e.legend===!1?0:28,p=c?5:7,m=c?1:e.weekStart??1,h=e=>(sb(e)-m+7)%7,g=u?lb(u[0],u[1],h):[],_=e=>n-eb*2-f-e*tb-(e-1)*nb;for(;g.length>1&&_(g.length)/(g.length*p)<$y;)g=g.slice(1);let v=[];for(let[e,t]of a)g.length>0&&e>=g[0].first&&e<=g[g.length-1].last&&l(e)&&v.push(t.value);let y=Ky(v,r,e.colorScale),b={cells:[],months:[],weekdays:[],years:[],scale:y,bar:null,pitch:0,formatDate:s};if(g.length===0||d<=0||_(g.length)<=0)return b;let x=g.length>1,S=g.map(e=>String(e.year)),C=Array.from({length:p},(e,t)=>o.weekday.format(new Date((3+m+t)*Qy))),w=eb+Math.max(...C.map(e=>i(e,10)),...x?S.map(e=>i(e,11)):[0])+ib,T=Math.max(...g.map(e=>e.weeks)),E=Math.min(rb,(t-w-eb)/T,_(g.length)/(g.length*p));if(!(E>0))return b;let D=E-(E>=6?Math.max(1,Math.round(E*.12)):0),O=T*E,k=w+Math.max(0,(t-w-eb-O)/2),A={...b,pitch:E},ee=eb;for(let[e,n]of g.entries()){let r=ee+tb;x&&A.years.push({label:S[e],x:k-ib,y:ee});let s=-1,c=-1/0;for(let e=n.first;e<=n.last;e++){if(!l(e))continue;let u=k+Math.floor((e-n.origin)/7)*E,d=r+h(e)*E,f=a.get(e);A.cells.push({x:u,y:d,size:D,date:ob(e),day:f,color:f&&Number.isFinite(f.value)?qy(f.value,y):null});let p=new Date(e*Qy).getUTCMonth();if(p!==s){s=p;let n=o.month.format(new Date(e*Qy)),r=u+i(n,10);u>=c&&r<=t&&(A.months.push({label:n,x:u,y:ee}),c=r+4)}}if(E>=8){let e=E>=13?1:2;for(let t=0;t<p;t+=e)A.weekdays.push({label:C[t],x:k-ib,y:r+t*E+D/2})}ee=r+p*E+nb}return f>0&&(A.bar={x:k,y:ee-nb+8,width:Math.min(O,t-k-eb),height:f-8}),A}function pb(e,t,n){for(let r of e.cells)if(t>=r.x&&t<r.x+e.pitch&&n>=r.y&&n<r.y+e.pitch)return r;return null}function mb(e,n,r,i,a,o,s=fb(i,n,r,a,j_(e,a))){let c=i.valueFormat??k_;e.fillStyle=a.background,e.fillRect(0,0,n,r);let l=o&&i.crosshair!==!1?pb(s,o.x,o.y):null,u=(0,t.withAlpha)(a.textSecondary,.12),d=s.pitch>=10?2:0;e.save();for(let t of s.cells)e.fillStyle=t.color??u,e.beginPath(),d>0&&typeof e.roundRect==`function`?e.roundRect(t.x,t.y,t.size,t.size,d):e.rect(t.x,t.y,t.size,t.size),e.fill();l&&(e.strokeStyle=a.text,e.lineWidth=1.5,e.strokeRect(l.x-.75,l.y-.75,l.size+1.5,l.size+1.5)),e.fillStyle=a.textSecondary,e.font=$(a,10),e.textAlign=`left`,e.textBaseline=`top`;for(let t of s.months)e.fillText(t.label,t.x,t.y);e.textAlign=`right`,e.textBaseline=`middle`;for(let t of s.weekdays)e.fillText(t.label,t.x,t.y);e.font=$(a,11,`600`),e.fillStyle=a.text,e.textBaseline=`top`;for(let t of s.years)e.fillText(t.label,t.x,t.y);if(e.restore(),s.bar&&Zy(e,s.bar,s.scale,c,a),l&&o){let t=[{text:s.formatDate(l.date),bold:!0,color:l.color??void 0}];if(l.day){t.push({text:c(l.day.value)});for(let[e,n]of Object.entries(l.day.meta??{}))t.push({text:`${e}: ${String(n)}`})}else t.push({text:`–`});P_(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}var hb=12,gb=6,_b=72,vb=Math.PI/4,yb=Math.sin(vb);function bb(e){let t=e.length,n=Array.from({length:t},()=>Array(t).fill(NaN));for(let r=0;r<t;r++)for(let i=r;i<t;i++){let t=xb(e[r],e[i],r===i);n[r][i]=t,n[i][r]=t}return n}function xb(e,t,n){let r=Math.min(e.length,t.length),i=0,a=0,o=0;for(let n=0;n<r;n++)Number.isFinite(e[n])&&Number.isFinite(t[n])&&(i++,a+=e[n],o+=t[n]);if(i<3)return NaN;let s=a/i,c=o/i,l=0,u=0,d=0;for(let n=0;n<r;n++){if(!Number.isFinite(e[n])||!Number.isFinite(t[n]))continue;let r=e[n]-s,i=t[n]-c;l+=r*i,u+=r*r,d+=i*i}return u===0||d===0?NaN:n?1:Math.max(-1,Math.min(1,l/Math.sqrt(u*d)))}var Sb=e=>e.toFixed(2);function Cb(e,t,n,r){return!t||!e?!0:e===`lower`?r<=n:r>=n}function wb(e,t,n,r,i){let a=e.rows.slice(0,200),o=(e.columns??e.rows).slice(0,200),s=e.columns===void 0||e.columns.length===e.rows.length&&e.columns.every((t,n)=>t===e.rows[n]),c=[];for(let t=0;t<a.length;t++)for(let n=0;n<o.length;n++){let r=e.values[t]?.[n];Number.isFinite(r)&&Cb(e.triangle,s,t,n)&&c.push(r)}let l=Ky(c,r,e.colorScale),u={cells:[],rowLabels:[],columnLabels:[],grid:{x:0,y:0,width:0,height:0},pitch:0,scale:l,bar:null,at:[]};if(a.length===0||o.length===0||t<=0||n<=0)return u;let d=Math.min(t*.3,Math.max(...a.map(e=>i(e,11)))),f=Math.max(...o.map(e=>i(e,11))),p=e.legend===!1?0:28,m=hb+d+gb,h=t-m-hb,g=e=>Math.min(_b,h/o.length,(n-e-hb-p)/a.length),_=hb+11+gb,v=g(_),y=f>v-4,b=f;if(y&&(b=Math.min(f,n*.33/yb),_=hb+b*yb+11,v=g(_)),!(v>0))return u;let x=v-+(v>=8),S=m+Math.max(0,(h-o.length*v)/2);y&&(b=Math.max(0,Math.min(b,(S+x/2-2-11*yb/2)/yb))),u.grid={x:S,y:_,width:o.length*v,height:a.length*v},u.pitch=v;let C=e.valueFormat??Sb,w=e.showValues!==!1,T=Math.max(8,Math.min(11,v/3));for(let t=0;t<a.length;t++){u.at.push([]);for(let n=0;n<o.length;n++){let r=e.values[t]?.[n];if(!Number.isFinite(r)||!Cb(e.triangle,s,t,n))continue;let c=qy(r,l),d=w?C(r):``,f=w&&v>=18&&i(d,T)<=v-4,p={x:S+n*v,y:_+t*v,size:x,cell:{row:a[t],column:o[n],value:r,rowIndex:t,columnIndex:n},color:c,text:f?d:null,textColor:Xy(c)};u.cells.push(p),u.at[t][n]=p}}let E=Math.max(1,Math.ceil(11/v)),D=Math.max(1,Math.ceil(11/(y?v*yb:v)));for(let e=0;e<a.length;e+=E)u.rowLabels.push({text:I_(a[e],d,i),index:e,x:S-gb,y:_+e*v+x/2});for(let e=0;e<o.length;e+=D)u.columnLabels.push({text:I_(o[e],b,i),index:e,x:S+e*v+x/2,y:_-gb,rotated:y});return p>0&&(u.bar={x:S,y:_+a.length*v+8,width:Math.min(u.grid.width,t-S-hb),height:p-8}),u}function Tb(e,t,n){let{grid:r,pitch:i}=e;return i<=0||t<r.x||n<r.y||t>=r.x+r.width||n>=r.y+r.height?null:e.at[Math.floor((n-r.y)/i)]?.[Math.floor((t-r.x)/i)]??null}function Eb(e,t,n,r,i,a,o=wb(r,t,n,i,j_(e,i))){let s=r.valueFormat??Sb;e.fillStyle=i.background,e.fillRect(0,0,t,n);let c=a&&r.crosshair!==!1?Tb(o,a.x,a.y):null;e.save();let l=Math.max(8,Math.min(11,o.pitch/3));e.textAlign=`center`,e.textBaseline=`middle`,e.font=$(i,l);for(let t of o.cells)e.fillStyle=t.color,e.fillRect(t.x,t.y,t.size,t.size),t.text&&(e.fillStyle=t.textColor,e.fillText(t.text,t.x+t.size/2,t.y+t.size/2));c&&(e.strokeStyle=i.text,e.lineWidth=1.5,e.strokeRect(c.x+.75,c.y+.75,c.size-1.5,c.size-1.5)),e.font=$(i,11),e.fillStyle=i.textSecondary,e.textAlign=`right`;for(let t of o.rowLabels)e.fillStyle=c&&c.cell.rowIndex===t.index?i.text:i.textSecondary,e.fillText(t.text,t.x,t.y);for(let t of o.columnLabels)e.fillStyle=c&&c.cell.columnIndex===t.index?i.text:i.textSecondary,t.rotated?(e.save(),e.translate(t.x,t.y),e.rotate(vb),e.textAlign=`right`,e.fillText(t.text,0,0),e.restore()):(e.textAlign=`center`,e.textBaseline=`bottom`,e.fillText(t.text,t.x,t.y),e.textBaseline=`middle`);if(e.restore(),o.bar&&Zy(e,o.bar,o.scale,s,i),c&&a){let{cell:r}=c;P_(e,[{text:`${r.row} × ${r.column}`,bold:!0,color:c.color},{text:s(r.value)}],a,{x:0,y:0,width:t,height:n},i)}return o}var Db=12,Ob=18,kb=20,Ab=10,jb=.2,Mb=2e3,Nb=1e-9;function Pb(e,t,n=1/0){let r=Number.isFinite(t)?Math.max(1,Math.floor(t)):25,i=[],a=Math.max(r-1,e.length-(Number.isFinite(n)?Math.max(1,Math.floor(n)):e.length));for(let t=a;t<e.length;t++){let n=0,a=0;for(let i=t-r+1;i<=t;i++)n+=e[i].volume,a+=e[i].close;i.push({time:e[t].time,volume:n/r,price:a/r})}return i}var Fb=(e,t)=>t-e>Nb*Math.max(Math.abs(e),Math.abs(t));function Ib(e){if(e.length<2)return null;let t=1/0,n=-1/0,r=1/0,i=-1/0;for(let a of e)t=Math.min(t,a.volume),n=Math.max(n,a.volume),r=Math.min(r,a.price),i=Math.max(i,a.price);let a=e[e.length-2],o=e[e.length-1],s=Fb(t,n)?(o.volume-a.volume)/(n-t):0,c=Fb(r,i)?(o.price-a.price)/(i-r):0;if(Math.abs(s)<1e-6&&Math.abs(c)<1e-6)return null;let l=(Math.atan2(c,s)+2*Math.PI)%(2*Math.PI);return Math.round(l/(Math.PI/4))%8+1}function Lb(e,n,r,i,a){let o=Pb(e.data,e.period??25,Rb(e)),s=1/0,c=-1/0,l=1/0,u=-1/0;for(let e of o)s=Math.min(s,e.volume),c=Math.max(c,e.volume),l=Math.min(l,e.price),u=Math.max(u,e.price);o.length>0&&!Fb(s,c)&&(c=s),o.length>0&&!Fb(l,u)&&(u=l);let d=E_(o.length>0?s:0,o.length>0?c:1,Math.max(2,Math.floor(n/110))),f=E_(o.length>0?l:0,o.length>0?u:1,Math.max(2,Math.floor(r/60))),p=e.priceFormat??Q(f),m=e.volumeFormat??Q(d),h=Db+Math.max(0,...f.ticks.map(e=>a(p(e),11)))+8+(e.yLabel?Ob:0),g=Db+a(m(d.max),11)/2,_=Db,v=Db+kb+(e.xLabel?Ob:0),y={x:h,y:_,width:Math.max(1,n-h-g),height:Math.max(1,r-_-v)},b=Math.max(1,o.length-1);return{plot:y,xScale:d,yScale:f,points:o.map((e,t)=>({px:Z(d,e.volume,y.x,y.width),py:Z(f,e.price,y.y,y.height,!0),alpha:jb+(1-jb)*t/b,point:e})),phase:Ib(o),color:e.color??t.TC_SERIES_COLORS[0]}}function Rb(e){let t=e.points??60;return Number.isFinite(t)?Math.min(Mb,Math.max(2,Math.floor(t))):60}function zb(e,t,n){let r=null,i=Ab*Ab;for(let a=e.points.length-1;a>=0;a--){let o=e.points[a],s=(o.px-t)**2+(o.py-n)**2;s<i&&(r=o,i=s)}return r}var Bb=new Intl.DateTimeFormat(void 0,{year:`numeric`,month:`short`,day:`numeric`});function Vb(e,n,r,i,a,o,s=Lb(i,n,r,a,j_(e,a))){let{plot:c,points:l,color:u}=s,d=i.timeFormat??(e=>Bb.format(new Date(e))),f=i.priceFormat??k_,p=i.volumeFormat??k_;e.fillStyle=a.background,e.fillRect(0,0,n,r),F_(e,c,s.yScale,`vertical`,a,i.priceFormat??Q(s.yScale)),F_(e,c,s.xScale,`horizontal`,a,i.volumeFormat??Q(s.xScale)),Hb(e,c,i,a),e.save(),e.lineWidth=1.5,e.lineJoin=`round`;for(let n=1;n<l.length;n++)e.strokeStyle=(0,t.withAlpha)(u,l[n].alpha),e.beginPath(),e.moveTo(l[n-1].px,l[n-1].py),e.lineTo(l[n].px,l[n].py),e.stroke();for(let n of l)e.fillStyle=(0,t.withAlpha)(u,n.alpha),e.beginPath(),e.arc(n.px,n.py,2,0,Math.PI*2),e.fill();let m=l[l.length-1];m&&(e.fillStyle=u,e.strokeStyle=a.background,e.lineWidth=2,e.beginPath(),e.arc(m.px,m.py,5,0,Math.PI*2),e.fill(),e.stroke()),e.restore();let h=o&&i.crosshair!==!1?zb(s,o.x,o.y):null;return h&&o&&(e.save(),e.strokeStyle=a.text,e.lineWidth=1.5,e.beginPath(),e.arc(h.px,h.py,5,0,Math.PI*2),e.stroke(),e.restore(),P_(e,[{text:d(h.point.time),bold:!0,color:u},{text:`${i.yLabel??`Price`}: ${f(h.point.price)}`},{text:`${i.xLabel??`Volume`}: ${p(h.point.volume)}`}],o,{x:0,y:0,width:n,height:r},a)),s}function Hb(e,t,n,r){e.save(),e.font=$(r,11),e.fillStyle=r.textSecondary,e.textAlign=`center`,n.xLabel&&(e.textBaseline=`bottom`,e.fillText(n.xLabel,t.x+t.width/2,t.y+t.height+kb+Ob)),n.yLabel&&(e.translate(Db+4,t.y+t.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}exports.ABCDPatternTool=Ru,exports.ADXIndicator=Jn,exports.ALMAIndicator=ci,exports.ATRIndicator=qn,exports.AXIS_LABEL_HEIGHT=E,exports.AcceleratorOscillatorIndicator=Ir,exports.AccumulationDistributionIndicator=Wr,exports.AccumulativeSwingIndexIndicator=$a,exports.AdvanceDeclineIndicator=to,exports.AlertDragHandler=fs,exports.AlertManager=Th,exports.AlligatorIndicator=Nn,exports.AnchoredVWAPIndicator=wn,exports.AnchoredVWAPTool=hu,exports.Animator=wg,exports.ArcTool=ef,exports.AreaRenderer=Me,exports.AroonIndicator=$n,exports.ArrowMarkTool=Fd,exports.ArrowTool=uu,exports.AverageDayRangeIndicator=Pi,exports.AveragePriceIndicator=Hi,exports.AwesomeOscillatorIndicator=Hn,exports.AxisDragHandler=ds,exports.BalanceOfPowerIndicator=xr,exports.BarCountdown=se,exports.BarRenderer=Ne,exports.BarsPatternTool=kf,exports.BaseFinanceChart=Eg,exports.BaselineRenderer=Ie,exports.BinanceAdapter=cm,exports.BollingerBandWidthIndicator=xi,exports.BollingerBandsIndicator=pn,exports.BollingerPercentBIndicator=bi,exports.BracketTool=ep,exports.BrushTool=qd,exports.BybitAdapter=Sm,exports.CANDLE_PATTERNS=ka,exports.CCIIndicator=Zn,exports.CMFIndicator=nr,exports.COUNTDOWN_HEIGHT=oe,exports.CalloutTool=Dd,exports.CandlestickRenderer=ie,exports.CanvasLayer=n,exports.ChaikinOscillatorIndicator=Un,exports.ChaikinVolatilityIndicator=kr,exports.ChandeKrollStopIndicator=_i,exports.ChandeMomentumIndicator=Cr,exports.ChandelierExitIndicator=Mn,exports.ChartLegend=Fm,exports.ChartStateManager=Qh,exports.ChopZoneIndicator=ao,exports.ChoppinessIndexIndicator=ar,exports.CircleTool=Hu,exports.CoinbaseAdapter=gm,exports.CompareRenderer=vt,exports.CompareSymbolIndicator=So,exports.ConnorsRSIIndicator=lr,exports.CoppockIndicator=dr,exports.CorrelationCoefficientIndicator=Do,exports.CorrelationLogIndicator=Oo,exports.CrossLineTool=Tu,exports.CrosshairHandler=hs,exports.CrosshairTooltip=Fs,exports.CurrentPriceLine=wp,exports.CurveTool=$d,exports.CyclicLinesTool=Qu,exports.CypherPatternTool=Vu,exports.DEFAULT_LEGEND_CONFIG=Pm,exports.DEFAULT_MAX_PIXEL_RATIO=a,exports.DEFAULT_MAX_WEBGL_CHARTS=e.t,exports.DEFAULT_SESSION_HOURS=nh,exports.DEMAIndicator=oi,exports.DENSE_BAR_WIDTH=e.u,exports.DOUBLE_TAP_MS=Ho,exports.DOUBLE_TAP_PX=Uo,exports.DPRManager=s,exports.DataExporter=ig,exports.DateAndPriceRangeTool=Ju,exports.DateRangeTool=ou,exports.DepthHeatmapBuffer=mt,exports.DepthHeatmapRenderer=ht,exports.DepthOverlay=Jf,exports.DetrendedPriceOscillatorIndicator=br,exports.DisparityIndexIndicator=zr,exports.DonchianChannelIndicator=yn,exports.DrawingBase=K,exports.DrawingManager=al,exports.DrawingRenderer=sl,exports.EMAIndicator=fn,exports.EaseOfMovementIndicator=Er,exports.Easing=Cg,exports.ElderRayIndicator=hr,exports.ElliottCorrectionTool=tu,exports.ElliottDoubleComboTool=ru,exports.ElliottImpulseTool=eu,exports.ElliottTriangleTool=nu,exports.ElliottTripleComboTool=iu,exports.ElliottWaveTool=$l,exports.EllipseTool=Wl,exports.Emitter=bp,exports.EnvelopeIndicator=Ln,exports.EquivolumeRenderer=Ve,exports.EventBus=Gs,exports.ExtendedLineTool=Nl,exports.FibArcsTool=pf,exports.FibChannelTool=ju,exports.FibCirclesTool=ff,exports.FibExtensionTool=Hl,exports.FibRetracementTool=Bl,exports.FibSpeedResistanceFanTool=Fu,exports.FibSpiralTool=gf,exports.FibTimeZonesTool=vu,exports.FibWedgeTool=mf,exports.FinanceCrosshair=Dg,exports.FisherTransformIndicator=yr,exports.FlagTool=Md,exports.ForceIndexIndicator=cr,exports.ForecastTool=Df,exports.GROUP_HEADER=m_,exports.GannBoxTool=mu,exports.GannFanTool=fu,exports.GannSquareTool=_f,exports.GridRenderer=e.o,exports.GuppyMMAIndicator=zi,exports.HLCAreaRenderer=Ue,exports.HammingMAIndicator=Ka,exports.HeadAndShouldersTool=zu,exports.HiLoRenderer=Je,exports.HighlighterTool=Jd,exports.HistoricalVolatilityIndicator=Ci,exports.HollowCandleRenderer=Pe,exports.HorizontalLineTool=kl,exports.HorizontalRayTool=Al,exports.HullMAIndicator=Dn,exports.ICON_GLYPHS=Id,exports.INDICATOR_CATEGORIES=ho,exports.INTERVAL_LIMITS=Xt,exports.INTERVAL_UNITS=Yt,exports.IchimokuIndicator=hn,exports.IconTool=Rd,exports.IndicatorBase=P,exports.IndicatorEngine=sn,exports.IndicatorValueMap=F,exports.IndicatorWorkerHost=yo,exports.InfoLineTool=Du,exports.InteractionManager=$o,exports.KAMAIndicator=li,exports.KSTIndicator=fr,exports.KagiRenderer=Re,exports.KeltnerChannelIndicator=vn,exports.KeyboardHandler=Ts,exports.KlingerIndicator=vr,exports.KrakenAdapter=km,exports.LSMAIndicator=ui,exports.LayerManager=r,exports.LineRenderer=je,exports.LineWithMarkersRenderer=Ge,exports.LinearRegressionChannelIndicator=En,exports.LinearRegressionSlopeIndicator=Mi,exports.MACDIndicator=Gn,exports.MAChannelIndicator=Ha,exports.MACrossIndicator=mi,exports.MADoubleIndicator=Xa,exports.MARibbonIndicator=Bi,exports.MATripleIndicator=Za,exports.MAX_ALERT_BARS=gh,exports.MAX_BASE_RATIO=Dp,exports.MAX_BASE_REQUESTS=Ep,exports.MFIIndicator=Qn,exports.MIN_ALERT_BARS=_h,exports.MIN_BAR_UNIT=ge,exports.MIN_BAR_UNIT_LIMIT=_e,exports.MTFMovingAverageIndicator=An,exports.MajorityRuleIndicator=no,exports.MarketProfileRenderer=rt,exports.MassIndexIndicator=Sr,exports.McGinleyDynamicIndicator=di,exports.MeasureOverlay=pg,exports.MeasureTool=su,exports.MedianPriceIndicator=Ui,exports.MockAdapter=lm,exports.ModifiedSchiffPitchforkTool=Jl,exports.MomentumIndicator=Si,exports.NetVolumeIndicator=Fi,exports.NoteTool=Ed,exports.OBVIndicator=Yn,exports.OrderDraftTool=op,exports.OrderRenderer=Rf,exports.PRICE_SCALE_MARGIN=ve,exports.PanHandler=ls,exports.PaneResizeHandler=ps,exports.PaperExecutionAdapter=_p,exports.ParabolicSARIndicator=gn,exports.ParallelChannelTool=Pl,exports.PathTool=Yd,exports.PercentagePriceOscillatorIndicator=Pr,exports.PeriodLevelsRenderer=ct,exports.PinnedTooltip=Bs,exports.PitchfanTool=hf,exports.PitchforkTool=Kl,exports.PivotMarkersRenderer=ft,exports.PivotPointsIndicator=Sn,exports.PointAndFigureRenderer=ze,exports.PollingAdapter=fm,exports.PolylineTool=Xd,exports.PositionRenderer=qf,exports.PrettyGoodOscillatorIndicator=Vr,exports.PriceAxis=C,exports.PriceAxisAddButton=ns,exports.PriceLabelTool=rd,exports.PriceLines=oh,exports.PriceOscillatorIndicator=co,exports.PriceRangeTool=au,exports.PriceVolumeTrendIndicator=Dr,exports.ProjectionTool=Of,exports.QstickIndicator=Br,exports.RANGE_PRESETS=Se,exports.ROCIndicator=er,exports.RSIIndicator=Wn,exports.RayTool=Ml,exports.ReconnectManager=Sp,exports.RectangleTool=Ul,exports.RegressionChannelTool=Fl,exports.RelativeMomentumIndexIndicator=Rr,exports.RelativeVigorIndicator=Ar,exports.RelativeVolatilityIndexIndicator=Ai,exports.RenderEngine=fe,exports.RenderLoop=i,exports.RenkoRenderer=Le,exports.ReplayController=qp,exports.ReplayManager=jh,exports.ResamplingAdapter=Fp,exports.RiskRewardTool=wu,exports.SELECTION_BOX_MIN_SIZE=xg,exports.SMAIndicator=dn,exports.SMIErgodicIndicator=so,exports.SMMAIndicator=si,exports.SNAPSHOT_VERSION=Nh,exports.SYMBOL_INDICATOR_IDS=bo,exports.SchaffTrendCycleIndicator=gr,exports.SchiffPitchforkTool=ql,exports.Screenshot=Vm,exports.SelectionBoxOverlay=Sg,exports.SessionBreaks=qm,exports.SessionShading=rh,exports.SessionVWAPIndicator=jn,exports.SignalMarkerManager=lg,exports.SineLineTool=Sf,exports.SpreadIndicator=Co,exports.StandardErrorBandsIndicator=Ii,exports.StandardErrorIndicator=Ni,exports.StdDevIndicator=Hr,exports.StepLineRenderer=We,exports.StochasticIndicator=Kn,exports.StochasticMomentumIndexIndicator=ki,exports.StochasticRSIIndicator=jr,exports.StreamManager=Kp,exports.SupertrendIndicator=_n,exports.SymbolSeriesStore=_t,exports.TEMAIndicator=Vn,exports.TOUCH_REACH=Vo,exports.TRIXIndicator=wr,exports.TSIIndicator=tr,exports.TapTracker=Wo,exports.TextAnnotationTool=lu,exports.ThreeDrivesTool=Bu,exports.TickAggregator=xp,exports.TickBarAdapter=Bp,exports.TickBarBuilder=zp,exports.TimeAxis=Bo,exports.TimeCyclesTool=xf,exports.TradeZoneManager=fg,exports.TradingContextMenu=Xf,exports.TradingDragHandler=Yf,exports.TradingManager=hp,exports.TradingRenderer=gp,exports.TrendAngleTool=_l,exports.TrendLineTool=Ol,exports.TrendStrengthIndexIndicator=ji,exports.TriangleTool=Gl,exports.TypicalPriceIndicator=Wi,exports.UlcerIndexIndicator=Ei,exports.UltimateOscillatorIndicator=or,exports.UndoRedoManager=$h,exports.VOLUME_HEIGHT_RATIO=Ye,exports.VROCIndicator=Gr,exports.VWAPIndicator=mn,exports.VWMAIndicator=Fn,exports.VerticalLineTool=jl,exports.Viewport=be,exports.VolatilityIndexIndicator=Qa,exports.VolatilityOHLCIndicator=fo,exports.VolatilityZeroTrendIndicator=po,exports.VolumeCandleRenderer=Be,exports.VolumeDeltaIndicator=rr,exports.VolumeOscillatorIndicator=wi,exports.VolumeProfileIndicator=Ur,exports.VolumeProfileRangeTool=gu,exports.VolumeProfileRenderer=Ze,exports.VolumeRenderer=Xe,exports.VortexIndicator=ir,exports.WMAIndicator=In,exports.Watermark=Hm,exports.WebSocketAdapter=dm,exports.WilliamsADIndicator=Or,exports.WilliamsFractalsIndicator=gi,exports.WilliamsRIndicator=Xn,exports.XABCDPatternTool=Lu,exports.ZigZagIndicator=Tn,exports.ZoomHandler=us,exports.alignOutput=qt,exports.arcPoints=Qd,exports.assignSessionLetters=tt,exports.axisFormat=Q,exports.barIndexToTime=e.y,exports.barIndexToX=e.b,exports.barTimeStep=e.x,exports.barTimeStepMs=e.S,exports.bracketRiskReward=Qf,exports.canvasMeasure=j_,exports.cappedPixelRatio=o,exports.claimGpuContext=e.n,exports.classifyPivots=ut,exports.cleanIntervals=en,exports.computeBarLayout=Qv,exports.computeBracketDefaults=Zf,exports.computeCalendarLayout=fb,exports.computeCounterClockLayout=Lb,exports.computeDonutLayout=dy,exports.computeHistogramLayout=Fy,exports.computeMarketProfile=$e,exports.computeMatrixLayout=wb,exports.computePeriodLevels=st,exports.computeScatterLayout=Sy,exports.computeSessionProfiles=nt,exports.correlationMatrix=bb,exports.counterClockPhase=Ib,exports.counterClockPoints=Pb,exports.curvePoints=Zd,exports.dayToIso=ob,exports.defaultFormat=k_,exports.detectCandlePatterns=Na,exports.drawAxisValueLabels=ee,exports.drawIcon=ph,exports.drawnKeys=kt,exports.fillTag=w,exports.findDominantSwing=cl,exports.findPivots=dt,exports.forEachPixelColumn=e.d,exports.forecastOutcome=Ef,exports.formatTooltipTime=Ns,exports.getIntParam=L,exports.getNumberParam=I,exports.getVisibleData=xe,exports.gpuContextsLeft=e.r,exports.hasHistogram=Lt,exports.hasTrades=Up,exports.histogramBins=Ay,exports.hitBar=$v,exports.hitCategory=ey,exports.hitDay=pb,exports.hitHistogramBar=Iy,exports.hitMatrixCell=Tb,exports.hitSlice=fy,exports.indicatorCategory=_o,exports.indicatorValuePrecision=T,exports.inferOrderType=ip,exports.inputSource=Wt,exports.isDense=e.f,exports.isInWindow=eh,exports.isPriceLevelAlert=yh,exports.isRegularSession=th,exports.isSeriesPalette=nn,exports.isUpTone=At,exports.isWorkerResponse=vo,exports.labelTextColor=O,exports.layoutAxisValueLabels=A,exports.layoutGroupedTreemap=h_,exports.layoutLegend=M_,exports.layoutSquarifiedTreemap=f_,exports.layoutUniformGrid=c_,exports.lineSourceBars=Kt,exports.lineSpace=Ec,exports.loadWebGL=me,exports.loadWebGLRenderer=he,exports.lttbDownsample=Oe,exports.lttbVisibleIndices=Ae,exports.mergeSessionHours=Qm,exports.minuteOfDay=$m,exports.nearestCounterClockPoint=zb,exports.nearestPoint=Cy,exports.niceScale=E_,exports.paneLogRange=Ft,exports.paneValueRange=Pt,exports.parseDay=ab,exports.pastTimeStep=e.C,exports.plotColor=Nt,exports.plotLook=N,exports.plotShown=jt,exports.priceBucketRow=e.w,exports.priceScaleText=c,exports.priceSourceBars=Gt,exports.priceToY=e.T,exports.priceToYMapper=e.E,exports.rangePresetStart=De,exports.readAlertOptions=Dh,exports.readableText=Xy,exports.registerBuiltInDrawingTools=Af,exports.registerBuiltInIndicators=mo,exports.renderAxisValueLabels=te,exports.renderBarChart=ty,exports.renderCalendar=mb,exports.renderCounterClock=Vb,exports.renderDenseBars=e.p,exports.renderDepthChart=Ug,exports.renderDonut=py,exports.renderEquityCurve=s_,exports.renderGauge=Gv,exports.renderHeatmap=U_,exports.renderHistogram=Ry,exports.renderMatrix=Eb,exports.renderPlots=Rt,exports.renderScatter=wy,exports.renderSparkline=Og,exports.renderWaterfall=dv,exports.resolveBarIndex=e.D,exports.resolveColorScale=Ky,exports.scaleColor=qy,exports.servesTimeframe=Mp,exports.setMaxWebGLCharts=e.i,exports.shownCount=Rb,exports.shownOnInterval=$t,exports.sourceParam=Ut,exports.spreadLabels=D,exports.timeToX=e.O,exports.timestampToBarIndex=e.k,exports.toHeikinAshi=yt,exports.toKagi=Ct,exports.toLineBreak=St,exports.toPointAndFigure=wt,exports.toRangeBars=Tt,exports.toRenko=bt,exports.tpoLetter=et,exports.waveLabel=Xl,exports.whenGpuContextFree=e.a,exports.withResampling=Ap,exports.withTickBars=Hp,exports.xToBarIndex=e.A,exports.xToTime=e.j,exports.yToPrice=e.M;
21
+ `,t.addEventListener(`mouseenter`,()=>{t.style.background=`#1f2630`}),t.addEventListener(`mouseleave`,()=>{t.style.background=`transparent`}),t.addEventListener(`click`,()=>{this.onItemSelect?.(e.intent),this.hide()}),s.appendChild(t)}n.appendChild(s),this.menuElement=s;let l=e=>{(e instanceof KeyboardEvent&&e.key===`Escape`||e instanceof MouseEvent&&!s.contains(e.target))&&this.hide()};document.addEventListener(`mousedown`,l),document.addEventListener(`keydown`,l),this.removeHandler=()=>{document.removeEventListener(`mousedown`,l),document.removeEventListener(`keydown`,l)}}hide(){this.menuElement?.remove(),this.menuElement=null,this.removeHandler?.(),this.removeHandler=null}destroy(){this.hide(),this.onItemSelect=null}};function Mp(e,t,n={}){let r=Math.max(Math.abs(t)*(n.riskFraction??.01),1e-8),i=r*(n.riskReward??2);return e===`buy`?{side:e,entry:t,stopLoss:t-r,takeProfit:t+i}:{side:e,entry:t,stopLoss:t+r,takeProfit:t-i}}function Np(e){let t=Math.abs(e.entry-e.stopLoss);return t===0?0:Math.abs(e.takeProfit-e.entry)/t}var Pp=6,Fp=.12,Ip=[6,3],Lp=class{draft=null;dragStart=null;dragging=null;defaults;constructor(e={}){this.defaults=e}start(e,t){this.draft=Mp(e,t,this.defaults),this.dragging=null}cancel(){this.draft=null,this.dragging=null}isActive(){return this.draft!==null}getDraft(){return this.draft?{...this.draft}:null}hitTest(t,n,r=Pp){if(!this.draft)return null;let i=[`entry`,`sl`,`tp`],a=null,o=r;for(let r of i){let i=e.T(this.priceOf(r),n),s=Math.abs(i-t.y);s<=o&&(o=s,a=r)}return a}beginDrag(e,t,n){let r=this.hitTest(e,t,n);return r!==null&&this.beginDragOn(r)}beginDragOn(e){return this.draft?(this.dragging=e,this.dragStart=this.draft,!0):!1}cancelDrag(){this.dragging&&this.dragStart&&(this.draft=this.dragStart),this.dragging=null,this.dragStart=null}drag(t,n){if(!this.draft||!this.dragging)return!1;let r=e.M(t.y,n);return this.draft=zp(this.draft,this.dragging,r),!0}endDrag(){this.dragging=null,this.dragStart=null}isDragging(){return this.dragging!==null}priceOf(e){let t=this.draft;return e===`entry`?t.entry:e===`sl`?t.stopLoss:t.takeProfit}render(e,t,n,r){this.renderLines(e,t,n),rp(e,this.tags(t,n),t,n,[])}renderLines(t,n,r){let i=this.draft;if(!i)return;let{chartRect:a}=n,o=e.T(i.entry,n),s=e.T(i.stopLoss,n),c=e.T(i.takeProfit,n),{profit:l,loss:u}=Rp(r);t.save(),t.globalAlpha=Fp,t.fillStyle=l,t.fillRect(a.x,Math.min(o,c),a.width,Math.abs(c-o)),t.fillStyle=u,t.fillRect(a.x,Math.min(o,s),a.width,Math.abs(s-o)),t.globalAlpha=1,Ff(t,n,o,r.text,Ip),Ff(t,n,c,l,[]),Ff(t,n,s,u,[]),t.restore()}tags(t,n){let r=this.draft;if(!r)return[];let{profit:i,loss:a}=Rp(n),o=r.side===`buy`?1:-1,s=e=>{let t=r.entry===0?0:(e-r.entry)/r.entry*100*o;return`${t>=0?`+`:``}${t.toFixed(2)}%`};return[{y:e.T(r.entry,t),color:n.text,grab:{kind:`bracket`,handle:`entry`},cells:[{kind:`stamp`,text:r.side===`buy`?`Long`:`Short`},{kind:`text`,text:`${Np(r).toFixed(2)}R`}]},{y:e.T(r.takeProfit,t),color:i,grab:{kind:`bracket`,handle:`tp`},cells:[{kind:`stamp`,text:`TP`},{kind:`text`,text:s(r.takeProfit),color:i}]},{y:e.T(r.stopLoss,t),color:a,grab:{kind:`bracket`,handle:`sl`},cells:[{kind:`stamp`,text:`SL`},{kind:`text`,text:s(r.stopLoss),color:a}]}].filter(e=>q(e.y,t))}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))op(e,i.y,i.text,i.color,t,n)}axisBadges(n,r,i){let a=this.draft;if(!a)return[];let{profit:o,loss:s}=Rp(r),c=[];for(let[l,u]of[[a.takeProfit,o],[a.stopLoss,s],[a.entry,r.text]]){let r=e.T(l,n);q(r,n)&&c.push({y:r,text:(0,t.priceTagText)(l,n,i),color:u})}return c}};function Rp(e){return{profit:e.style?.trading.profit??e.candleUp,loss:e.style?.trading.loss??e.candleDown}}function zp(e,t,n){let r=e.side===`buy`;if(t===`entry`){let t=n-e.entry;return{side:e.side,entry:n,stopLoss:e.stopLoss+t,takeProfit:e.takeProfit+t}}if(t===`sl`){let t=r?Math.min(n,e.entry):Math.max(n,e.entry);return{...e,stopLoss:t}}let i=r?Math.max(n,e.entry):Math.min(n,e.entry);return{...e,takeProfit:i}}function Bp(e,t,n){return n==null?`limit`:e===`buy`?t<=n?`limit`:`stop`:t>=n?`limit`:`stop`}var Vp=6,Hp=[6,3],Up=class{draft=null;dragStart=null;dragging=!1;start(e,t,n=1){this.draft={side:e,price:t,quantity:n},this.dragging=!1}cancel(){this.draft=null,this.dragging=!1}isActive(){return this.draft!==null}isDragging(){return this.dragging}getDraft(){return this.draft?{...this.draft}:null}setPrice(e){return this.draft?(this.draft={...this.draft,price:e},!0):!1}toIntent(e){return this.draft?{side:this.draft.side,type:Bp(this.draft.side,this.draft.price,e),price:this.draft.price,quantity:this.draft.quantity}:null}hitTest(t,n,r=Vp){return this.draft?Math.abs(e.T(this.draft.price,n)-t.y)<=r:!1}beginDrag(e,t,n){return this.hitTest(e,t,n)&&this.beginDragOn()}beginDragOn(){return this.draft?(this.dragging=!0,this.dragStart=this.draft,!0):!1}cancelDrag(){this.dragging&&this.dragStart&&(this.draft=this.dragStart),this.dragging=!1,this.dragStart=null}drag(t,n){return!this.draft||!this.dragging?!1:this.setPrice(e.M(t.y,n))}endDrag(){this.dragging=!1,this.dragStart=null}render(e,t,n,r,i){this.renderLines(e,t,n),rp(e,this.tags(t,n,r),t,n,[])}renderLines(t,n,r){let i=this.draft;i&&(t.save(),Ff(t,n,e.T(i.price,n),Wp(i.side,r),Hp),t.restore())}tags(t,n,r){let i=this.draft;if(!i)return[];let a=e.T(i.price,t);if(!q(a,t))return[];let o=Bp(i.side,i.price,r);return[{y:a,color:Wp(i.side,n),grab:{kind:`draft`},cells:[{kind:`stamp`,text:String(i.quantity)},{kind:`text`,text:dp({side:i.side,type:o})}]}]}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))op(e,i.y,i.text,i.color,t,n)}axisBadges(n,r,i){let a=this.draft;if(!a)return[];let o=e.T(a.price,n);return q(o,n)?[{y:o,text:(0,t.priceTagText)(a.price,n,i),color:Wp(a.side,r)}]:[]}};function Wp(e,t){return e===`buy`?t.style?.trading.buy??t.candleUp:t.style?.trading.sell??t.candleDown}var Gp=2;function Kp(e,t){return e.type===t.type?e.type===`cancelOrder`?e.orderId===t.orderId:e.type===`removeStop`?e.positionId===t.positionId&&e.which===t.which:e.positionId===t.positionId:!1}function qp(e,t,n=Gp){let r=(e,n)=>t.x>=e.x-n&&t.x<=e.x+e.size+n&&t.y>=e.y-n&&t.y<=e.y+e.size+n;for(let t=e.length-1;t>=0;t--)if(r(e[t],0))return e[t];let i=null,a=1/0;for(let o of e){if(!r(o,n))continue;let e=Math.hypot(t.x-(o.x+o.size/2),t.y-(o.y+o.size/2));e<a&&(a=e,i=o)}return i}var Jp=5,Yp=7,Xp=2;function Zp(e,n){let r=n.data;return r&&r.length>0?e/(0,t.barTimeUnit)(r):e}function Qp(t,n,r,i){if(n.length===0)return;let{chartRect:a}=r,o=i.orderColors?.buy??`#1fa874`,s=i.orderColors?.sell??`#e8505b`;t.lineWidth=1.5;for(let i of n){let n=e.O(Zp(i.time,r),r),c=e.T(i.price,r);if(n<a.x||n>a.x+a.width||c<a.y||c>a.y+a.height)continue;let l=i.side===`buy`,u=l?c+Xp:c-Xp,d=l?u+Yp:u-Yp;t.beginPath(),t.moveTo(n,u),t.lineTo(n-Jp,d),t.lineTo(n+Jp,d),t.closePath();let f=l?o:s;!i.reason||i.reason===`order`?(t.fillStyle=f,t.fill()):(t.strokeStyle=f,t.stroke())}}var $p=1e3,em=class{orders=[];positions=[];depthData=null;currentPrice=null;config;orderRenderer=new hp;positionRenderer=new Dp;depthOverlay=new Op;dragHandler;contextMenu=new jp;bracket=new Lp;orderDraft=new Up;buttons=[];tagBoxes=[];grabOffset=0;fills=[];realisedPnl=0;requestRender=null;eventCallback=null;container=null;constructor(e){this.config={...t.DEFAULT_TRADING_CONFIG,...e},this.dragHandler=new Ap(this.config.dragThreshold),this.contextMenu.onItemSelect=e=>{this.eventCallback?.(`orderPlace`,e)}}setContainer(e){this.container=e}setRequestRender(e){this.requestRender=e}setEventCallback(e){this.eventCallback=e}setOrders(e){this.orders=e,this.requestRender?.()}setPositions(e){this.positions=e,this.requestRender?.()}getOrders(){return[...this.orders]}getPositions(){return[...this.positions]}getCurrentPrice(){return this.currentPrice}setDepthData(e){this.depthData=e,this.requestRender?.()}setCurrentPrice(e){this.currentPrice=e,this.requestRender?.()}setConfig(e){Object.assign(this.config,e),this.requestRender?.()}addFill(e){this.fills=[...this.fills.slice(-($p-1)),e],this.realisedPnl+=e.pnl??0,this.requestRender?.()}setFills(e){this.fills=e.slice(-$p),this.realisedPnl=e.reduce((e,t)=>e+(t.pnl??0),0),this.requestRender?.()}getRealisedPnl(){return this.realisedPnl}getFills(){return[...this.fills]}armed=null;isOverButton(e){return this.config.enabled&&qp(this.buttons,e)!==null}runButton(e){switch(e.type){case`cancelOrder`:this.eventCallback?.(`orderCancel`,{orderId:e.orderId});break;case`closePosition`:this.eventCallback?.(`positionClose`,{positionId:e.positionId});break;case`reversePosition`:this.eventCallback?.(`positionReverse`,{positionId:e.positionId});break;case`removeStop`:this.eventCallback?.(`positionModify`,{positionId:e.positionId,[e.which]:null});break}}startBracket(e,t){this.bracket.start(e,t),this.requestRender?.()}cancelBracket(){this.bracket.isActive()&&(this.bracket.cancel(),this.requestRender?.())}confirmBracket(){let e=this.bracket.getDraft();return e?(this.eventCallback?.(`bracketPlace`,{side:e.side,entry:e.entry,stopLoss:e.stopLoss,takeProfit:e.takeProfit,riskReward:Np(e)}),this.bracket.cancel(),this.requestRender?.(),!0):!1}isBracketActive(){return this.bracket.isActive()}startOrderDraft(e,t){this.orderDraft.start(e,t),this.requestRender?.()}cancelOrderDraft(){this.orderDraft.isActive()&&(this.orderDraft.cancel(),this.requestRender?.())}confirmOrderDraft(){let e=this.orderDraft.toIntent(this.currentPrice);return e?(this.eventCallback?.(`orderPlace`,e),this.orderDraft.cancel(),this.requestRender?.(),!0):!1}isOrderDraftActive(){return this.orderDraft.isActive()}isOverDraggableLine(t,n,r=8){if(!this.config.enabled)return!1;if(Qf(this.tagBoxes,t.x,t.y)&&!qp(this.buttons,t))return!0;let i=i=>{if(i===void 0)return!1;let a=e.T(i,n);return q(a,n)&&Math.abs(t.y-a)<=r};for(let e of this.orders)if(e.draggable!==!1&&i(e.price))return!0;for(let e of this.positions)if(i(e.stopLoss)||i(e.takeProfit))return!0;return!1}onPointerDown(e,t,n){if(!this.config.enabled)return!1;let r=qp(this.buttons,e,n?.button),i=r?null:Qf(this.tagBoxes,e.x,e.y);return i&&this.grabTag(i,e)||(this.grabOffset=0,this.bracket.isActive()&&this.bracket.beginDrag(e,t,n?.handle))||this.orderDraft.isActive()&&this.orderDraft.beginDrag(e,t,n?.handle)?(this.requestRender?.(),!0):r?(this.armed=r.action,!0):this.dragHandler.onPointerDown(e,this.orders,this.positions,t,n?.order??8)}grabTag(e,t){this.grabOffset=e.lineY-t.y;let n=e.grab;switch(n.kind){case`bracket`:return this.bracket.beginDragOn(n.handle);case`draft`:return this.orderDraft.beginDragOn();case`order`:{let t=this.orders.find(e=>e.id===n.orderId);return t!==void 0&&this.dragHandler.beginOrder(t,e.lineY)}case`stop`:{let t=this.positions.find(e=>e.id===n.positionId);return t!==void 0&&this.dragHandler.beginStop(t,n.which,e.lineY)}}}onPointerMove(e,t){if(this.armed)return!0;let n=this.grabOffset===0?e:{x:e.x,y:Pf(e.y+this.grabOffset,t)};if(this.bracket.isDragging()){let e=this.bracket.drag(n,t);return e&&this.requestRender?.(),e}if(this.orderDraft.isDragging()){let e=this.orderDraft.drag(n,t);return e&&this.requestRender?.(),e}if(!this.dragHandler.isActive())return!1;let r=this.dragHandler.onPointerMove(n,t);return r&&this.requestRender?.(),r}onPointerUp(e){if(this.grabOffset=0,this.armed){let t=this.armed;this.armed=null;let n=e?qp(this.buttons,e):null;return n&&Kp(n.action,t)&&this.runButton(t),!0}if(this.bracket.isDragging())return this.bracket.endDrag(),this.requestRender?.(),!0;if(this.orderDraft.isDragging())return this.orderDraft.endDrag(),this.requestRender?.(),!0;let t=this.dragHandler.onPointerUp();return t?(t.sourceType===`order`?this.eventCallback?.(`orderModify`,{orderId:t.id,newPrice:t.newPrice,previousPrice:t.previousPrice}):this.eventCallback?.(`positionModify`,{positionId:t.id,[t.sourceType]:t.newPrice}),this.requestRender?.(),!0):!1}cancelPointer(){this.grabOffset=0;let e=!1;return this.armed&&(this.armed=null,e=!0),this.bracket.isDragging()&&(this.bracket.cancelDrag(),e=!0),this.orderDraft.isDragging()&&(this.orderDraft.cancelDrag(),e=!0),this.dragHandler.cancel()&&(e=!0),e&&this.requestRender?.(),e}onContextMenu(n,r){if(!this.config.enabled||!this.config.contextMenu?.enabled||!this.container)return!1;let i=e.M(n.y,r);return this.contextMenu.show(n,i,this.container,this.config,e=>(0,t.priceTagText)(e,r,this.config.pricePrecision)),!0}render(e,t,n){if(this.buttons=[],this.tagBoxes=[],!this.config.enabled)return;let{chartRect:r}=t;e.save();try{e.beginPath(),e.rect(r.x,r.y,r.width,r.height),e.clip(),this.renderInPlot(e,t,n)}finally{e.restore()}}renderInPlot(e,t,n){let r=Zs(this.config,n);this.depthData&&this.depthOverlay.render(e,this.depthData,t,r),r.fillMarks!==!1&&Qp(e,this.fills,t,r);let i=this.dragHandler.getDragState();this.positionRenderer.renderLines(e,this.positions,this.currentPrice,t,r,i),this.orderRenderer.renderLines(e,this.orders,t,r,i),this.bracket.renderLines(e,t,n),this.orderDraft.renderLines(e,t,n),rp(e,[...this.bracket.tags(t,n),...this.orderDraft.tags(t,n,this.currentPrice),...this.positionRenderer.tags(this.positions,this.currentPrice,t,r,i),...this.orderRenderer.tags(this.orders,t,r,i)],t,n,this.buttons,this.tagBoxes)}renderAxisBadges(e,t,n){if(this.config.enabled)for(let r of ap(this.axisBadges(t,n),t))op(e,r.at,r.text,r.color,t,n)}axisBadges(e,t){let n=Zs(this.config,t);return[...this.positionRenderer.axisBadges(this.positions,e,n,this.dragHandler.getDragState()),...this.orderRenderer.axisBadges(this.orders,e,n,this.dragHandler.getDragState()),...this.bracket.axisBadges(e,t,this.config.pricePrecision),...this.orderDraft.axisBadges(e,t,this.config.pricePrecision)]}axisTagYs(e,n=t.DARK_THEME){return this.config.enabled?ap(this.axisBadges(e,n),e).map(e=>e.at):[]}destroy(){this.contextMenu.destroy()}},tm=class{constructor(e){this.manager=e}render(e,t,n){this.manager.render(e,t,n)}renderAxisBadges(e,t,n){this.manager.renderAxisBadges(e,t,n)}axisTagYs(e,t){return this.manager.axisTagYs(e,t)}},nm=class{name=`paper`;state=`disconnected`;listeners=new Map;orders=[];positions=[];markPrice;markTime;seq=0;constructor(e={}){this.markPrice=e.markPrice??0}connect(e){this.state=`connected`,this.emit(`connectionChange`,this.state),this.emit(`orders`,this.orders),this.emit(`positions`,this.positions)}disconnect(){this.state=`disconnected`,this.emit(`connectionChange`,this.state)}getConnectionState(){return this.state}setMarkPrice(e,t){this.markPrice=e,this.markTime=t!==void 0&&Number.isFinite(t)?t:void 0,this.checkPendingOrders(),this.checkStops()}fillTime(){return this.markTime??Date.now()}getOrders(){return[...this.orders]}getPositions(){return[...this.positions]}async placeOrder(e){let t={id:this.nextId(`ord`),side:e.side,type:e.type,price:e.price,stopPrice:e.stopPrice,quantity:e.quantity??1,label:e.type===`market`?void 0:im(e.type),draggable:!0,stopLoss:e.stopLoss,takeProfit:e.takeProfit,timeInForce:e.timeInForce};return e.type===`market`?this.fill(t,this.markPrice||e.price):(this.orders=[...this.orders,t],this.emit(`orders`,this.orders)),t}async modifyOrder(e){this.orders=this.orders.map(t=>t.id===e.orderId?{...t,price:e.newPrice}:t),this.emit(`orders`,this.orders)}async cancelOrder(e){this.orders=this.orders.filter(t=>t.id!==e.orderId),this.emit(`orders`,this.orders)}async modifyPosition(e){let t=(e,t)=>e===void 0?t:e??void 0;this.positions=this.positions.map(n=>n.id===e.positionId?{...n,stopLoss:t(e.stopLoss,n.stopLoss),takeProfit:t(e.takeProfit,n.takeProfit)}:n),this.emit(`positions`,this.positions)}async closePosition(e){let t=this.positions.find(t=>t.id===e.positionId);t&&(this.close(t,this.markPrice||t.entryPrice,`close`),this.emit(`positions`,this.positions))}async reversePosition(e){let t=this.positions.find(t=>t.id===e.positionId);if(!t)return;let n=this.markPrice||t.entryPrice;this.close(t,n,`reverse`);let r=t.quantity-(t.closedQuantity??0),i={id:this.nextId(`ord`),side:rm(t.side),type:`market`,price:n,quantity:r};this.fill(i,n)}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear(),this.orders=[],this.positions=[]}fill(e,t){this.orders=this.orders.filter(t=>t.id!==e.id);let n={id:this.nextId(`pos`),side:e.side,entryPrice:t,quantity:e.quantity,stopLoss:e.stopLoss,takeProfit:e.takeProfit};this.positions=[...this.positions,n];let r={orderId:e.id,side:e.side,price:t,quantity:e.quantity,time:this.fillTime(),positionId:n.id,reason:`order`};this.emit(`fill`,r),this.emit(`orders`,this.orders),this.emit(`positions`,this.positions)}close(e,t,n){this.positions=this.positions.filter(t=>t.id!==e.id);let r=e.quantity-(e.closedQuantity??0),i=e.side===`buy`?1:-1;this.emit(`fill`,{orderId:this.nextId(`ord`),side:rm(e.side),price:t,quantity:r,time:this.fillTime(),positionId:e.id,reason:n,pnl:(t-e.entryPrice)*r*i})}checkPendingOrders(){let e=this.orders.filter(e=>this.isTriggered(e));for(let t of e)this.fill(t,t.type===`limit`?t.price:t.stopPrice??t.price)}isTriggered(e){if(e.type===`limit`)return e.side===`buy`?this.markPrice<=e.price:this.markPrice>=e.price;if(e.type===`stop`||e.type===`stopLimit`){let t=e.stopPrice??e.price;return e.side===`buy`?this.markPrice>=t:this.markPrice<=t}return!1}checkStops(){let e=!1;for(let t of[...this.positions]){let n=t.stopLoss!==void 0&&(t.side===`buy`?this.markPrice<=t.stopLoss:this.markPrice>=t.stopLoss),r=t.takeProfit!==void 0&&(t.side===`buy`?this.markPrice>=t.takeProfit:this.markPrice<=t.takeProfit);!n&&!r||(this.close(t,n?t.stopLoss:t.takeProfit,n?`stopLoss`:`takeProfit`),e=!0)}e&&this.emit(`positions`,this.positions)}nextId(e){return`${e}-${++this.seq}`}emit(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}};function rm(e){return e===`buy`?`sell`:`buy`}function im(e){switch(e){case`stop`:return`STOP`;case`stopLimit`:return`STOP LIMIT`;default:return`LIMIT`}}var am=class{listeners=new Map;on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>n.delete(t)}once(e,t){let n=this.on(e,e=>{n(),t(e)});return n}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){let n=this.listeners.get(e);if(n)for(let e of n)e(t)}removeAllListeners(){this.listeners.clear()}},om=class extends am{currentBar=null;timeframeMs;tickRing;ringHead=0;ringCount=0;ringCapacity;constructor(e,n=1e3){super(),this.timeframeMs=(0,t.timeframeToMs)(e),this.ringCapacity=n,this.tickRing=Array(n)}setTimeframe(e){this.timeframeMs=(0,t.timeframeToMs)(e),this.currentBar=null,this.ringHead=0,this.ringCount=0}processTick(e){let t=(this.ringHead+this.ringCount)%this.ringCapacity;this.tickRing[t]=e,this.ringCount<this.ringCapacity?this.ringCount++:this.ringHead=(this.ringHead+1)%this.ringCapacity;let n=this.alignToTimeframe(e.time);!this.currentBar||this.currentBar.time!==n?(this.currentBar&&(this.currentBar.closed=!0,this.emit(`barClose`,this.currentBar)),this.currentBar={time:n,open:e.price,high:e.price,low:e.price,close:e.price,volume:e.volume,closed:!1,tickCount:1}):(this.currentBar.high=Math.max(this.currentBar.high,e.price),this.currentBar.low=Math.min(this.currentBar.low,e.price),this.currentBar.close=e.price,this.currentBar.volume+=e.volume,this.currentBar.tickCount++),this.emit(`bar`,this.currentBar)}processBar(e,t){if(t&&this.currentBar&&this.currentBar.time===e.time)this.currentBar={...e,closed:!0,tickCount:this.currentBar.tickCount+1},this.emit(`barClose`,this.currentBar),this.currentBar=null;else if(!t)this.currentBar={...e,closed:!1,tickCount:(this.currentBar?.tickCount??0)+1},this.emit(`bar`,this.currentBar);else{let t={...e,closed:!0,tickCount:1};this.emit(`barClose`,t),this.currentBar=null}}getCurrentBar(){return this.currentBar?{...this.currentBar}:null}getTickBuffer(){let e=Array(this.ringCount);for(let t=0;t<this.ringCount;t++)e[t]=this.tickRing[(this.ringHead+t)%this.ringCapacity];return e}reset(){this.currentBar=null,this.ringHead=0,this.ringCount=0}alignToTimeframe(e){return this.timeframeMs>0?Math.floor(e/this.timeframeMs)*this.timeframeMs:e}},sm=class extends am{config;attempt=0;timer=null;active=!1;constructor(e){super(),this.config={...t.DEFAULT_RECONNECT,...e}}schedule(e){if(!this.config.enabled||!this.active)return;if(this.cancel(),this.attempt++,this.attempt>this.config.maxRetries){this.emit(`giveUp`,{attempts:this.attempt-1}),this.active=!1;return}let t=this.computeDelay();this.emit(`attempt`,{attempt:this.attempt,delay:t}),this.timer=setTimeout(()=>{this.timer=null,this.active&&e()},t)}onConnected(){this.attempt=0,this.cancel(),this.emit(`success`,void 0)}start(){this.active=!0}stop(){this.active=!1,this.cancel(),this.attempt=0}cancel(){this.timer&&=(clearTimeout(this.timer),null)}getAttempt(){return this.attempt}isActive(){return this.active}computeDelay(){let e=this.config.baseDelay,t=this.config.backoffMultiplier**(this.attempt-1),n=Math.min(e*t,this.config.maxDelay),r=n*.25*(Math.random()*2-1);return Math.max(0,Math.round(n+r))}},cm=20,lm=class{price=null;previousClose=null;visible=!0;flashUntil=0;pricePrecision=null;locale=`en-US`;tag=null;setLocale(e){this.locale=e}setPrice(e,t){this.price!==null&&e!==this.price&&(this.flashUntil=Date.now()+300),this.previousClose=t??this.price??e,this.price=e}setVisible(e){this.visible=e}isVisible(){return this.visible}setPricePrecision(e){this.pricePrecision=e}getPrice(){return this.price}getTag(){return this.tag}render(n,r,i){this.tag=null;let a=i.style?.lastPrice;if(!this.visible||this.price===null||a?.visible===!1)return;let o=e.T(this.price,r),{chartRect:s}=r;if(o<s.y||o>s.y+s.height)return;let c=this.previousClose===null||this.price>=this.previousClose?a?.up??i.candleUp??`#1fa874`:a?.down??i.candleDown??`#e8505b`,l=Date.now()<this.flashUntil,u=a?.width??1;n.setLineDash((0,t.lineDash)(a?.style??`solid`,[4,3],u)),n.strokeStyle=c,n.lineWidth=u,n.globalAlpha=l?1:.7,n.beginPath(),n.moveTo(s.x,Math.round(o)+.5),n.lineTo(s.x+s.width,Math.round(o)+.5),n.stroke(),n.setLineDash([]),n.globalAlpha=1;let d=s.x+s.width+1,f=this.pricePrecision??(0,t.autoPricePrecision)(r.priceRange.min,r.priceRange.max),p=r.formatPrice?r.formatPrice(this.price):(0,t.formatPrice)(this.price,f,this.locale);n.font=`bold 11px ${i.font.family}`;let m=n.measureText(p).width,h=r.priceAxisWidth??t.PRICE_AXIS_WIDTH,g=Math.min(m+12,h-2);n.fillStyle=c,E(n,d,o-cm/2,g,cm,i),this.tag={x:d,y:o-cm/2,width:g,height:cm,color:c};let _=d-5;n.beginPath(),n.moveTo(_,o),n.lineTo(_+5,o-5),n.lineTo(_+5,o+5),n.closePath(),n.fill(),n.fillStyle=A(c),n.textBaseline=`middle`,n.textAlign=`left`,n.fillText(p,d+5,o)}},um=1e3,dm=10,fm=1440,pm=[`tick`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],mm=new WeakMap;function hm(e){if(e instanceof bm||!e.supportedTimeframes?.length)return e;let t=mm.get(e);return t||(t=new bm(e,e.supportedTimeframes),mm.set(e,t)),t}function gm(e,n){if(n.includes(e))return e;let r=(0,t.pickBaseTimeframe)(e,n);return r&&Math.ceil((0,t.timeframeToMs)(e)/(0,t.timeframeToMs)(r))<=1440?r:null}function _m(e,n){if((0,t.tickBarCount)(n)!==null)return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`;let r=e.supportedTimeframes;return!r?.length||gm(n,r)!==null}function vm(e,n){let r=(0,t.parseTimeframe)(n);if(r?.unit===`M`){let t=new Date(e);return Date.UTC(t.getUTCFullYear(),t.getUTCMonth()+r.count,1)}return e+(0,t.timeframeToMs)(n)}function ym(e,t){let n=t[0],r={time:e,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume};for(let e=1;e<t.length;e++){let n=t[e];n.high>r.high&&(r.high=n.high),n.low<r.low&&(r.low=n.low),r.close=n.close,r.volume+=n.volume}return r}var bm=class{name;fetchHistoryBefore;searchSymbols;resolveSymbol;subscribeQuotes;fetchNews;fetchTrades;subscribeTrades;listeners=new Map;unsubscribe=[];live=null;bucket=null;parts=new Map;tail=null;generation=0;constructor(e,t){this.inner=e,this.baseTimeframes=t,this.name=e.name,e.fetchHistoryBefore&&(this.fetchHistoryBefore=(e,t,n,r)=>this.historyBefore(e,t,n,r)),e.searchSymbols&&(this.searchSymbols=e.searchSymbols.bind(e)),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol.bind(e)),e.subscribeQuotes&&(this.subscribeQuotes=e.subscribeQuotes.bind(e)),e.fetchNews&&(this.fetchNews=e.fetchNews.bind(e)),e.fetchTrades&&(this.fetchTrades=e.fetchTrades.bind(e)),e.subscribeTrades&&(this.subscribeTrades=e.subscribeTrades.bind(e)),this.listen(`bar`,e=>this.onBar(e));for(let e of pm)this.listen(e,t=>this.emit(e,t.data))}baseFor(e){let t=gm(e,this.baseTimeframes);if(!t)throw RangeError(`${this.name} cannot serve the ${e} timeframe`);return t}connect(e){let t=this.baseFor(e.timeframe);this.generation++,this.resetBucket(),this.live=t===e.timeframe?null:{symbol:e.symbol,target:e.timeframe,base:t},this.live&&this.resumeFromHistory(this.live.symbol,this.live.target),this.inner.connect({...e,timeframe:t})}disconnect(){this.generation++,this.inner.disconnect(),this.resetBucket(),this.live=null}getConnectionState(){return this.inner.getConnectionState()}async fetchHistory(e,t,n=500){let r=this.baseFor(t);if(r===t)return this.inner.fetchHistory(e,t,n);let i=this.generation,a=this.baseBarsFor(t,r,n),o=await this.inner.fetchHistory(e,r,Math.min(a,um)),s=await this.extendBack(e,r,o,a,i);return this.rememberTail(e,t,s),this.toTarget(s,t,n)}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.generation++;for(let e of this.unsubscribe)e();this.unsubscribe.length=0,this.listeners.clear(),this.inner.dispose()}async historyBefore(e,t,n,r){let i=this.inner.fetchHistoryBefore.bind(this.inner),a=this.baseFor(t);if(a===t)return i(e,t,n,r);let o=this.generation,s=this.baseBarsFor(t,a,r),c=await i(e,a,n,Math.min(s,um)),l=await this.extendBack(e,a,c.filter(e=>e.time<n),s,o,1);return this.toTarget(l,t,r)}baseBarsFor(e,n,r){return(r+1)*Math.ceil((0,t.timeframeToMs)(e)/(0,t.timeframeToMs)(n))}async extendBack(e,t,n,r,i,a=1){let o=this.inner.fetchHistoryBefore?.bind(this.inner),s=n,c=a;for(;o&&s.length>0&&s.length<r&&c<10&&i===this.generation;){let n=s[0].time,i=await o(e,t,n,Math.min(r-s.length,um));c++;let a=i.filter(e=>e.time<n);if(a.length===0)break;s=a.concat(s)}return s}toTarget(e,n,r){if(e.length===0)return[];let i=(0,t.resampleBars)(e,n);return i.length>1&&i[0].time!==e[0].time&&i.shift(),i.length>r?i.slice(i.length-r):i}rememberTail(e,n,r){if(r.length===0)return;let i=(0,t.timeframeBucketStart)(r[r.length-1].time,n),a=r.length;for(;a>0&&(0,t.timeframeBucketStart)(r[a-1].time,n)===i;)a--;this.tail={symbol:e,target:n,bucket:i,bars:r.slice(a)}}resumeFromHistory(e,t){let n=this.tail;if(!(!n||n.symbol!==e||n.target!==t)){this.bucket=n.bucket;for(let e of n.bars)this.parts.set(e.time,e)}}onBar(e){let n=this.live;if(!n){this.emit(`bar`,e.data);return}let{bar:r,closed:i}=e.data,a=(0,t.timeframeBucketStart)(r.time,n.target);if(this.bucket!==null&&a<this.bucket)return;if(this.bucket!==null&&a>this.bucket){let e=this.composed();e&&this.emit(`bar`,{bar:e,closed:!0}),this.resetBucket()}this.bucket=a,this.parts.set(r.time,r);let o=this.composed();if(!o)return;let s=i&&(0,t.timeframeBucketStart)(vm(r.time,n.base),n.target)!==a;this.emit(`bar`,{bar:o,closed:s}),s&&(this.resetBucket(),this.bucket=(0,t.timeframeBucketStart)(vm(r.time,n.base),n.target))}composed(){if(this.bucket===null||this.parts.size===0)return null;let e=[...this.parts.values()].sort((e,t)=>e.time-t.time);return ym(this.bucket,e)}resetBucket(){this.bucket=null,this.parts=new Map}listen(e,t){let n=e=>t(e);this.inner.on(e,n),this.unsubscribe.push(()=>this.inner.off(e,n))}emit(e,t){let n=this.listeners.get(e);if(!n)return;let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}},xm=1e3,Sm=15e3,Cm=[`tick`,`bar`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],wm=class{bar=null;count=0;lastTime=-1/0;constructor(e){this.tradesPerBar=e}push(e){let t=[],n=!1;for(let r of e){if(this.bar)this.bar={...this.bar,high:Math.max(this.bar.high,r.price),low:Math.min(this.bar.low,r.price),close:r.price,volume:this.bar.volume+r.volume};else{let e=Math.max(r.time,this.lastTime+1);this.lastTime=e,this.bar={time:e,open:r.price,high:r.price,low:r.price,close:r.price,volume:r.volume},this.count=0}this.count++,n=!0,this.count>=this.tradesPerBar&&(t.push({bar:this.bar,closed:!0}),this.bar=null,n=!1)}return n&&this.bar&&t.push({bar:this.bar,closed:!1}),t}build(e){return this.bar=null,this.count=0,this.lastTime=-1/0,this.push(e).map(e=>e.bar)}},Tm=class{name;supportedTimeframes;searchSymbols;resolveSymbol;subscribeQuotes;fetchNews;fetchTrades;subscribeTrades;listeners=new Map;tick=null;stopTrades=null;keepAlive=null;tickMode=!1;state=`disconnected`;constructor(e){this.inner=e,this.name=e.name,this.supportedTimeframes=e.supportedTimeframes,e.searchSymbols&&(this.searchSymbols=e.searchSymbols.bind(e)),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol.bind(e)),e.subscribeQuotes&&(this.subscribeQuotes=e.subscribeQuotes.bind(e)),e.fetchNews&&(this.fetchNews=e.fetchNews.bind(e)),this.fetchTrades=e.fetchTrades.bind(e),this.subscribeTrades=e.subscribeTrades.bind(e);for(let t of Cm)e.on(t,e=>{this.tickMode||this.emit(t,e.data)})}async fetchHistory(e,n,r){let i=(0,t.tickBarCount)(n);if(i===null)return this.inner.fetchHistory(e,n,r);let a=(await this.inner.fetchTrades(e,xm)).filter(km).sort((e,t)=>e.time-t.time),o=new wm(i),s=o.build(a);return this.tick={symbol:e,builder:o,after:a.length?a[a.length-1].time:-1/0},r!==void 0&&r>0?s.slice(-r):s}fetchHistoryBefore(e,n,r,i){return(0,t.tickBarCount)(n)!==null||!this.inner.fetchHistoryBefore?Promise.resolve([]):this.inner.fetchHistoryBefore(e,n,r,i)}connect(e){this.disconnect();let n=(0,t.tickBarCount)(e.timeframe);if(n===null){this.tickMode=!1,this.inner.connect(e);return}this.tickMode=!0;let r=this.tick?.symbol===e.symbol?this.tick:{symbol:e.symbol,builder:new wm(n),after:-1/0};this.tick=r,this.stopTrades=this.inner.subscribeTrades(e.symbol,e=>{let t=e.filter(e=>km(e)&&e.time>=r.after);for(let{bar:e,closed:n}of r.builder.push(t))this.emit(`bar`,{bar:e,closed:n}),this.emit(`tick`,{time:e.time,price:e.close,volume:e.volume})}),this.state=`connected`,this.emit(`connectionChange`,`connected`),this.keepAlive=setInterval(()=>this.emit(`connectionChange`,`connected`),Sm)}disconnect(){this.tickMode?(this.stopTrades?.(),this.stopTrades=null,this.keepAlive&&clearInterval(this.keepAlive),this.keepAlive=null,this.state=`disconnected`):this.inner.disconnect()}getConnectionState(){return this.tickMode?this.state:this.inner.getConnectionState()}dispose(){this.stopTrades?.(),this.stopTrades=null,this.keepAlive&&clearInterval(this.keepAlive),this.keepAlive=null,this.listeners.clear(),this.inner.dispose()}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){let n=this.listeners.get(e);if(!n)return;let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}},Em=new WeakMap;function Dm(e){if(e instanceof Tm||!Om(e))return e;let t=Em.get(e);return t||(t=new Tm(e),Em.set(e,t)),t}function Om(e){return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`}function km(e){return Number.isFinite(e?.time)&&Number.isFinite(e?.price)&&Number.isFinite(e?.volume)}var Am=2e4,jm=class extends am{config=null;adapter=null;aggregator=null;reconnector;priceLine=new lm;state=`disconnected`;lastPrice=null;previousClose=null;unsubscribers=[];heartbeatTimer=null;lastMessageTime=0;connectSeq=0;constructor(){super(),this.reconnector=new sm,this.wireReconnector()}async connect(e){this.disconnect();let n=Dm(hm(e.adapter));this.config={...t.DEFAULT_STREAM_CONFIG,...e,adapter:n},this.adapter=n,this.aggregator=new om(e.timeframe),this.reconnector.removeAllListeners(),this.reconnector.stop(),this.reconnector=new sm(e.reconnect??t.DEFAULT_RECONNECT),this.wireReconnector(),this.aggregator.on(`bar`,e=>{this.emit(`barUpdate`,e),this.updatePrice(e.close)}),this.aggregator.on(`barClose`,e=>{this.previousClose=e.close,this.emit(`barClose`,e)}),this.wireAdapter(),this.reconnector.start(),await this.doConnect()}disconnect(){this.connectSeq++,this.reconnector.stop(),this.stopHeartbeat();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.adapter&&=(this.adapter.disconnect(),null),this.aggregator?.reset(),this.aggregator?.removeAllListeners(),this.aggregator=null,this.config=null,this.lastPrice=null,this.previousClose=null,this.setState(`disconnected`)}async switchTo(e,t){!this.config||!this.adapter||(this.reconnector.stop(),this.adapter.disconnect(),this.reconnector.start(),this.aggregator?.reset(),this.aggregator?.setTimeframe(t),this.lastPrice=null,this.previousClose=null,this.config.symbol=e,this.config.timeframe=t,await this.doConnect())}getConnectionState(){return this.state}getConnectionInfo(){return{state:this.state,reconnectAttempt:this.reconnector.getAttempt(),lastMessageTime:this.lastMessageTime}}getLastPrice(){return this.lastPrice}async doConnect(){if(!this.config||!this.adapter)return;let e=++this.connectSeq,{symbol:t,timeframe:n}=this.config;this.setState(`connecting`);try{let r=await this.adapter.fetchHistory(t,n,this.config.historyLimit??500);if(e!==this.connectSeq||!this.adapter)return;r.length>0&&(this.previousClose=r[r.length-1].close,this.updatePrice(r[r.length-1].close)),this.emit(`snapshot`,r),this.adapter.connect({symbol:t,timeframe:n}),this.startHeartbeat()}catch(t){if(e!==this.connectSeq)return;let n=t instanceof Error?t.message:String(t);this.emit(`error`,{message:n,code:`CONNECT_FAILED`}),this.setState(`error`),this.reconnector.schedule(()=>this.doConnect())}}wireReconnector(){this.reconnector.on(`attempt`,({attempt:e,delay:t})=>{this.setState(`reconnecting`),this.emit(`connectionChange`,{state:`reconnecting`,reconnectAttempt:e,lastMessageTime:this.lastMessageTime})}),this.reconnector.on(`giveUp`,({attempts:e})=>{this.setState(`error`),this.emit(`error`,{message:`Reconnection failed after ${e} attempts`,code:`RECONNECT_EXHAUSTED`})})}wireAdapter(){if(!this.adapter)return;let e=this.adapter,t=e=>{let t=e.data;this.lastMessageTime=Date.now(),t===`connected`?(this.reconnector.onConnected(),this.setState(`connected`)):(t===`disconnected`||t===`error`)&&this.reconnector.schedule(()=>this.doConnect())};e.on(`connectionChange`,t),this.unsubscribers.push(()=>e.off(`connectionChange`,t));let n=e=>{this.lastMessageTime=Date.now();let t=e.data;this.emit(`tick`,t),(t.bid!==void 0||t.ask!==void 0)&&this.emit(`quote`,{bid:t.bid,ask:t.ask}),this.config?.aggregateTicks&&this.aggregator?this.aggregator.processTick(t):this.updatePrice(t.price)};e.on(`tick`,n),this.unsubscribers.push(()=>e.off(`tick`,n));let r=e=>{this.lastMessageTime=Date.now();let{bar:t,closed:n}=e.data;this.aggregator&&this.aggregator.processBar(t,n)};e.on(`bar`,r),this.unsubscribers.push(()=>e.off(`bar`,r));let i=e=>{this.emit(`error`,{message:e.data?.message??`Adapter error`})};e.on(`error`,i),this.unsubscribers.push(()=>e.off(`error`,i));let a=e=>{e?.data&&typeof e.data==`object`&&this.emit(`symbolInfo`,e.data)};try{e.on(`symbolInfo`,a),this.unsubscribers.push(()=>e.off(`symbolInfo`,a))}catch{}}updatePrice(e){e!==this.lastPrice&&(this.lastPrice=e,this.priceLine.setPrice(e,this.previousClose??void 0),this.emit(`priceChange`,{price:e,previousClose:this.previousClose}))}setState(e){this.state!==e&&(this.state=e,this.emit(`connectionChange`,{state:e,reconnectAttempt:this.reconnector.getAttempt(),lastMessageTime:this.lastMessageTime}))}wake(e){!this.adapter||!this.config||this.state===`connecting`||this.state===`disconnected`||this.state===`connected`&&e===`visible`&&Date.now()-this.lastMessageTime<=Am||(this.reconnector.stop(),this.adapter.disconnect(),this.reconnector.start(),this.doConnect())}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{Date.now()-this.lastMessageTime>6e4&&this.state===`connected`&&(this.emit(`error`,{message:`Heartbeat timeout`,code:`HEARTBEAT_TIMEOUT`}),this.adapter?.disconnect(),this.reconnector.schedule(()=>this.doConnect()))},3e4)}stopHeartbeat(){this.heartbeatTimer&&=(clearInterval(this.heartbeatTimer),null)}dispose(){this.disconnect(),this.removeAllListeners()}},Mm=class extends am{data;speed;index;status=`idle`;timer=null;constructor(e){if(super(),e.data.length===0)throw Error(`ReplayController requires non-empty data`);this.data=e.data,this.speed=Math.max(.01,e.speed??1),this.index=Math.max(0,Math.min(e.startIndex??0,e.data.length)),e.autoStart&&this.start()}getStatus(){return this.status}getIndex(){return this.index}getTotal(){return this.data.length}getPrefix(){return this.data.slice(0,this.index)}start(){if(this.status!==`playing`){if(this.index>=this.data.length){this.transition(`finished`);return}this.transition(`playing`),this.scheduleNext()}}pause(){this.status===`playing`&&(this.clearTimer(),this.transition(`paused`))}resume(){this.status===`paused`&&this.start()}stop(){this.clearTimer(),this.index=0,this.transition(`idle`)}step(e=1){if(!(e<=0)){this.clearTimer();for(let t=0;t<e;t++)if(!this.emitNext())return;this.status!==`finished`&&this.transition(`paused`)}}seek(e){let t=Math.max(0,Math.min(e,this.data.length));this.clearTimer(),this.index=t;let n=t>=this.data.length?`finished`:`paused`;this.transition(n)}setSpeed(e){this.speed=Math.max(.01,e),this.status===`playing`&&(this.clearTimer(),this.scheduleNext())}destroy(){this.clearTimer(),this.removeAllListeners()}scheduleNext(){let e=1e3/this.speed;this.timer=setTimeout(()=>{this.timer=null,this.status===`playing`&&this.emitNext()&&this.scheduleNext()},e)}emitNext(){if(this.index>=this.data.length)return this.transition(`finished`),this.emit(`finished`,{total:this.data.length}),!1;let e=this.data[this.index],t=this.index;return this.index++,this.emit(`bar`,{bar:e,index:t,total:this.data.length}),this.index>=this.data.length?(this.transition(`finished`),this.emit(`finished`,{total:this.data.length}),!1):!0}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}transition(e){this.status!==e&&(this.status=e,this.emit(`stateChange`,{status:e,index:this.index,total:this.data.length}))}};function Nm(e){if(!Array.isArray(e)||e.length<6)return null;let t=e[0];if(typeof t!=`number`||!Number.isFinite(t))return null;let n=Fm(e[1]),r=Fm(e[2]),i=Fm(e[3]),a=Fm(e[4]),o=Fm(e[5]);return n===null||r===null||i===null||a===null||o===null?null:{time:t,open:n,high:r,low:i,close:a,volume:o}}function Pm(e){if(!Im(e))return null;let t=e.t;if(typeof t!=`number`||!Number.isFinite(t))return null;let n=Fm(e.o),r=Fm(e.h),i=Fm(e.l),a=Fm(e.c),o=Fm(e.v);if(n===null||r===null||i===null||a===null||o===null)return null;let s=typeof e.x==`boolean`?e.x:!1;return{bar:{time:t,open:n,high:r,low:i,close:a,volume:o},closed:s}}function Fm(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=parseFloat(e);return Number.isFinite(t)?t:null}return null}function Im(e){return typeof e==`object`&&!!e}function J(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:void 0}function Lm(e){let n=e&&typeof e==`object`&&`data`in e?e.data:e;if(!n||typeof n!=`object`)return null;let r=n;return r.e===`24hrMiniTicker`?(0,t.readQuote)({symbol:r.s,last:J(r.c),open:J(r.o),high:J(r.h),low:J(r.l),volume:J(r.v),time:J(r.E)}):null}function Rm(e){if(!e||typeof e!=`object`)return null;let n=e;return(0,t.readQuote)({symbol:n.symbol,last:J(n.lastPrice),change:J(n.priceChange),changePercent:J(n.priceChangePercent),open:J(n.openPrice),high:J(n.highPrice),low:J(n.lowPrice),prevClose:J(n.prevClosePrice),volume:J(n.volume),bid:J(n.bidPrice),ask:J(n.askPrice),time:J(n.closeTime)})}function zm(e){if(!e||typeof e!=`object`)return null;let t=e,n=J(t.T),r=J(t.p),i=J(t.q);return n!==void 0&&r!==void 0&&i!==void 0?{time:n,price:r,volume:i}:null}var Bm={"1s":`1s`,"1m":`1m`,"3m":`3m`,"5m":`5m`,"15m":`15m`,"30m":`30m`,"1h":`1h`,"2h":`2h`,"4h":`4h`,"6h":`6h`,"8h":`8h`,"12h":`12h`,"1d":`1d`,"3d":`3d`,"1w":`1w`,"1M":`1M`},Vm=1e3,Hm=200,Um=[`USDT`,`USDC`,`FDUSD`,`BTC`,`ETH`,`BNB`,`EUR`,`TRY`,`BRL`,`JPY`];function Wm(e){let t=e.currency?Um.indexOf(e.currency):-1;return t<0?0:40-t*3}function Gm(e){if(typeof e.symbol!=`string`||e.status!==`TRADING`)return null;let n=typeof e.baseAsset==`string`?e.baseAsset:``,r=typeof e.quoteAsset==`string`?e.quoteAsset:``,i=Array.isArray(e.filters)?e.filters.find(e=>typeof e==`object`&&!!e&&e.filterType===`PRICE_FILTER`&&typeof e.tickSize==`string`):void 0,a={symbol:e.symbol,description:n&&r?`${n} / ${r}`:e.symbol,exchange:`Binance`,type:`crypto`};return i&&(a.pricePrecision=(0,t.stepDecimals)(i.tickSize),a.minTick=Number(i.tickSize)),a.timezone=`UTC`,r&&(a.currency=r),a}function Km(e){let t=e?.symbols;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=Gm(e);t&&n.push(t)}return n}var qm=class{name=`binance`;supportedTimeframes=Object.keys(Bm);ws=null;state=`disconnected`;listeners=new Map;config=null;restBase;wsBase;symbolList=null;constructor(e){this.restBase=e?.restBase??`https://api.binance.com/api/v3`,this.wsBase=e?.wsBase??`wss://stream.binance.com:9443/ws`}connect(e){this.config=e,this.connectWs()}disconnect(){if(this.ws){let e=this.ws;e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null,e.close(),this.ws=null}this.setState(`disconnected`)}getConnectionState(){return this.state}fetchHistory(e,t,n=500){return this.fetchKlines(e,t,n,``)}async searchSymbols(e,n){return(0,t.rankSymbols)(await this.loadSymbols(),e,n?.limit??50,Wm)}async resolveSymbol(e){if(this.symbolList){let t=(await this.symbolList.catch(()=>null))?.find(t=>t.symbol===e);if(t)return t}let t=await fetch(`${this.restBase}/exchangeInfo?symbol=${encodeURIComponent(e)}`);return t.ok?Km(await t.json())[0]??null:null}loadSymbols(){return this.symbolList||(this.symbolList=(async()=>{let e=await fetch(`${this.restBase}/exchangeInfo`);if(!e.ok)throw Error(`Binance REST error: ${e.status}`);return Km(await e.json())})(),this.symbolList.catch(()=>{this.symbolList=null})),this.symbolList}subscribeQuotes(e,t){let n=[...new Set(e.map(e=>e.trim().toUpperCase()))].filter(e=>/^[A-Z0-9]{2,30}$/.test(e)).slice(0,Hm);if(n.length===0)return()=>{};let r=!1,i=null,a=null,o=0,s=new Set,c=new AbortController;(async()=>{let e=await fetch(`${this.restBase}/ticker/24hr?symbols=${encodeURIComponent(JSON.stringify(n))}`,{signal:c.signal});if(e.ok)return e.json();let t=await fetch(`${this.restBase}/ticker/24hr`,{signal:c.signal});if(!t.ok)return[];let r=await t.json(),i=new Set(n);return Array.isArray(r)?r.filter(e=>i.has(e?.symbol)):[]})().then(e=>{if(r||!Array.isArray(e))return;let n=e.map(Rm).filter(e=>e!==null&&!s.has(e.symbol));n.length>0&&t(n)}).catch(()=>{});let l=this.wsBase.replace(/\/ws\/?$/,``),u=()=>{if(!r){try{i=new WebSocket(`${l}/stream?streams=${n.map(e=>`${e.toLowerCase()}@miniTicker`).join(`/`)}`)}catch{d();return}i.onopen=()=>{o=0},i.onmessage=e=>{let n;try{n=JSON.parse(typeof e.data==`string`?e.data:``)}catch{return}let i=Lm(n);!i||r||(s.add(i.symbol),t([i]))},i.onclose=()=>{i=null,d()}}},d=()=>{r||(a=setTimeout(u,Math.min(3e4,1e3*2**o++)))};return u(),()=>{r=!0,c.abort(),a&&clearTimeout(a),i&&=(i.onopen=null,i.onmessage=null,i.onclose=null,i.close(),null)}}async fetchTrades(e,t=1e3){let n=Math.max(1,Math.min(1e3,Math.floor(t))),r=await fetch(`${this.restBase}/aggTrades?symbol=${encodeURIComponent(e.toUpperCase())}&limit=${n}`);if(!r.ok)throw Error(`Binance aggTrades ${r.status}`);let i=await r.json();return Array.isArray(i)?i.map(zm).filter(e=>e!==null):[]}subscribeTrades(e,t){let n=`${e.trim().toLowerCase()}@aggTrade`;if(!/^[a-z0-9]{2,30}@aggTrade$/.test(n))return()=>{};let r=!1,i=null,a=null,o=0,s=()=>{if(!r){try{i=new WebSocket(`${this.wsBase}/${n}`)}catch{c();return}i.onopen=()=>{o=0},i.onmessage=e=>{let n;try{n=JSON.parse(typeof e.data==`string`?e.data:``)}catch{return}let i=zm(n);i&&!r&&t([i])},i.onclose=()=>{i=null,c()}}},c=()=>{r||(a=setTimeout(s,Math.min(3e4,1e3*2**o++)))};return s(),()=>{r=!0,a&&clearTimeout(a),i&&=(i.onopen=null,i.onmessage=null,i.onclose=null,i.close(),null)}}fetchHistoryBefore(e,t,n,r=500){return this.fetchKlines(e,t,Math.min(r,Vm),`&endTime=${Math.floor(n)-1}`)}async fetchKlines(e,t,n,r){let i=Bm[t]??`15m`,a=`${this.restBase}/klines?symbol=${e}&interval=${i}&limit=${n}${r}`,o=await fetch(a);if(!o.ok)throw Error(`Binance REST error: ${o.status}`);let s=await o.json();if(!Array.isArray(s))return[];let c=[];for(let e of s){let t=Nm(e);t&&c.push(t)}return c}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}connectWs(){if(!this.config)return;let e=`${this.config.symbol.toLowerCase()}@kline_${Bm[this.config.timeframe]??`15m`}`,t=`${this.wsBase}/${e}`;this.setState(`connecting`);try{this.ws=new WebSocket(t)}catch{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket creation failed`}),this.emitEvent(`connectionChange`,`error`);return}this.ws.onopen=()=>{this.setState(`connected`),this.emitEvent(`connectionChange`,`connected`)},this.ws.onmessage=e=>{let t;try{t=JSON.parse(typeof e.data==`string`?e.data:``)}catch{return}typeof t==`object`&&t&&t.e===`kline`&&this.handleKline(t.k)},this.ws.onerror=()=>{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket error`})},this.ws.onclose=()=>{this.setState(`disconnected`),this.emitEvent(`connectionChange`,`disconnected`)}}handleKline(e){let t=Pm(e);if(!t)return;let{bar:n,closed:r}=t;this.emitEvent(`bar`,{bar:n,closed:r}),this.emitEvent(`tick`,{time:Date.now(),price:n.close,volume:n.volume})}setState(e){this.state=e}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}},Jm=class{name=`mock`;state=`disconnected`;listeners=new Map;config=null;options;tickTimer=null;currentPrice;oldestOpen=new Map;forming=null;formingTimeframe=null;constructor(e){this.options={basePrice:100,volatility:1.5,tickInterval:2e3,historySize:500,...e},this.currentPrice=this.options.basePrice}connect(e){this.config=e,this.state=`connected`,this.emitEvent(`connectionChange`,`connected`),this.startTicking()}disconnect(){this.stopTicking(),this.state=`disconnected`,this.emitEvent(`connectionChange`,`disconnected`)}getConnectionState(){return this.state}subscribeQuotes(e,t){let n=[...new Set(e)].map(e=>{let t=this.options.basePrice*(.5+Ym(e)%1e3/1e3);return{symbol:e,open:t,last:t,high:t,low:t,volume:0}});if(n.length===0)return()=>{};let r=this.options.volatility/100,i=()=>t(n.map(e=>({symbol:e.symbol,last:e.last,open:e.open,high:e.high,low:e.low,volume:e.volume,change:e.last-e.open,changePercent:(e.last-e.open)/e.open*100,time:Date.now()})));i();let a=setInterval(()=>{for(let e of n)e.last=Math.max(e.open*.01,e.last*(1+(Math.random()-.5)*r)),e.high=Math.max(e.high,e.last),e.low=Math.min(e.low,e.last),e.volume+=Math.random()*100;i()},this.options.tickInterval);return()=>clearInterval(a)}async fetchTrades(e,t=1e3){let n=Math.max(1,Math.min(1e3,Math.floor(t))),r=Date.now(),i=this.options.volatility/1e3,a=this.options.basePrice*(.5+Ym(e)%1e3/1e3),o=[];for(let e=n-1;e>=0;e--)a=Math.max(a*.5,a*(1+(Math.random()-.5)*i)),o.push({time:r-e*1e3,price:a,volume:Math.random()*5});return o}subscribeTrades(e,t){let n=this.options.volatility/1e3,r=this.options.basePrice*(.5+Ym(e)%1e3/1e3),i=setInterval(()=>{let e=[];for(let t=0;t<3;t++)r=Math.max(r*.5,r*(1+(Math.random()-.5)*n)),e.push({time:Date.now(),price:r,volume:Math.random()*5});t(e)},this.options.tickInterval);return()=>clearInterval(i)}async fetchHistory(e,t,n){let r=this.options.historyGenerator?this.options.historyGenerator(e,t,n??this.options.historySize):this.generateHistory(t,n??this.options.historySize);return r.length>0&&this.oldestOpen.set(e,r[0].open),this.forming=r.length>0?{...r[r.length-1]}:null,this.formingTimeframe=t,r}async fetchHistoryBefore(e,n,r,i){let a=(0,t.timeframeToMs)(n),o=this.options.volatility/100,s=Array(Math.max(0,i)),c=this.oldestOpen.get(e)??this.options.basePrice;for(let e=0;e<i;e++){let t=c/(1+(Math.random()-.52)*o),n=Math.max(t,c)+Math.random()*c*o*.3,l=Math.max(0,Math.min(t,c)-Math.random()*c*o*.3),u=Math.floor(1e4+Math.random()*1e5);s[i-1-e]={time:r-(e+1)*a,open:t,high:n,low:l,close:c,volume:u},c=t}return this.oldestOpen.set(e,c),s}async searchSymbols(e,n){return(0,t.rankSymbols)(this.options.symbols??[],e,n?.limit??50)}async resolveSymbol(e){return this.options.symbols?.find(t=>t.symbol===e)??null}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}generateHistory(e,n){let r=[],i=(0,t.timeframeToMs)(e),a=Math.floor(Date.now()/i)*i,o=this.options.basePrice,s=this.options.volatility/100;for(let e=n-1;e>=0;e--){let t=a-e*i,n=(Math.random()-.48)*o*s,c=o;o+=n;let l=Math.max(c,o)+Math.random()*o*s*.3,u=Math.min(c,o)-Math.random()*o*s*.3,d=Math.floor(1e4+Math.random()*1e5);r.push({time:t,open:c,high:l,low:u,close:o,volume:d})}return this.currentPrice=o,r}startTicking(){this.stopTicking();let e=this.options.tickInterval??2e3;this.tickTimer=setInterval(()=>{if(this.state!==`connected`||!this.config)return;let e=this.options.volatility/100,t=(Math.random()-.48)*this.currentPrice*e*.3;this.currentPrice+=t;let n=Date.now(),r=this.tickBar(n,t,Math.floor(100+Math.random()*5e3));this.emitEvent(`bar`,{bar:r,closed:!1}),this.emitEvent(`tick`,{time:n,price:this.currentPrice,volume:r.volume})},e)}tickBar(e,n,r){let i=this.config.timeframe,a=(0,t.timeframeToMs)(i),o=Math.floor(e/a)*a,s=this.currentPrice,c=this.formingTimeframe===i?this.forming:null,l=Math.abs(n)*.2,u;if(c&&c.time===o)u={time:o,open:c.open,high:Math.max(c.high,s+l),low:Math.min(c.low,s-l),close:s,volume:c.volume+r};else{let e=c?.close??s-n;u={time:o,open:e,high:Math.max(e,s)+l,low:Math.min(e,s)-l,close:s,volume:r}}return this.forming=u,this.formingTimeframe=i,{...u}}stopTicking(){this.tickTimer&&=(clearInterval(this.tickTimer),null)}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}};function Ym(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t}var Xm=class{name;supportedTimeframes;ws=null;state=`disconnected`;config=null;listeners=new Map;opts;fetchHistoryBefore;searchSymbols;resolveSymbol;constructor(e){this.opts=e,this.name=e.name,this.supportedTimeframes=e.supportedTimeframes;let t=e.fetchHistoryBefore;t&&(this.fetchHistoryBefore=(e,n,r,i)=>t(e,n,r,i)),e.searchSymbols&&(this.searchSymbols=e.searchSymbols),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol)}connect(e){this.config=e,this.openSocket()}disconnect(){let e=this.config;if(this.ws){if(this.opts.unsubscribeMessage&&e)try{this.sendMessage(this.opts.unsubscribeMessage(e))}catch{}let t=this.ws;t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,t.close(),this.ws=null}this.setState(`disconnected`)}getConnectionState(){return this.state}fetchHistory(e,t,n){return this.opts.fetchHistory(e,t,n??this.opts.defaultHistoryLimit??500)}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}openSocket(){let e=this.config;if(!e)return;let t=this.opts.wsUrl(e);this.setState(`connecting`);let n;try{n=this.createSocket(t)}catch{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket creation failed`}),this.emitEvent(`connectionChange`,`error`);return}this.ws=n,n.onopen=()=>{if(this.setState(`connected`),this.emitEvent(`connectionChange`,`connected`),this.opts.subscribeMessage)try{this.sendMessage(this.opts.subscribeMessage(e))}catch{}},n.onmessage=t=>{let n=this.decode(t.data);if(n===void 0)return;let r;try{r=this.opts.parseMessage(n,e)}catch{return}r&&(r.bar&&this.emitEvent(`bar`,{bar:r.bar,closed:r.closed??!1}),r.tick?this.emitEvent(`tick`,r.tick):r.bar&&this.emitEvent(`tick`,{time:Date.now(),price:r.bar.close,volume:r.bar.volume}))},n.onerror=()=>{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket error`})},n.onclose=()=>{this.setState(`disconnected`),this.emitEvent(`connectionChange`,`disconnected`)}}sendMessage(e){e===void 0||!this.ws||this.ws.send(typeof e==`string`?e:JSON.stringify(e))}decode(e){if(this.opts.decode)try{return this.opts.decode(e)}catch{return}if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}createSocket(e){if(this.opts.socketFactory)return this.opts.socketFactory(e);let t=globalThis.WebSocket;if(!t)throw Error(`No WebSocket implementation available`);return new t(e)}setState(e){this.state=e}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}},Zm=class{name;supportedTimeframes;state=`disconnected`;listeners=new Map;config=null;timer=null;lastBarTime=0;opts;fetchHistoryBefore;searchSymbols;resolveSymbol;constructor(e){this.opts=e,this.name=e.name,this.supportedTimeframes=e.supportedTimeframes;let t=e.fetchHistoryBefore;t&&(this.fetchHistoryBefore=(e,n,r,i)=>t(e,n,r,i)),e.searchSymbols&&(this.searchSymbols=e.searchSymbols),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol)}connect(e){this.config=e,this.lastBarTime=0,this.state=`connected`,this.emitEvent(`connectionChange`,`connected`),this.startPolling()}disconnect(){this.stopPolling(),this.state=`disconnected`,this.emitEvent(`connectionChange`,`disconnected`)}getConnectionState(){return this.state}fetchHistory(e,t,n){return this.opts.fetchBars(e,t,n??this.opts.defaultHistoryLimit??500)}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}async poll(){let e=this.config;if(!e||this.state!==`connected`)return;let t;try{t=await this.opts.fetchBars(e.symbol,e.timeframe,this.opts.pollLimit??2)}catch(e){this.emitEvent(`error`,{message:`Poll failed`,cause:e});return}if(t.length===0)return;let n=t[t.length-1];if(this.lastBarTime>0&&n.time>this.lastBarTime){let e=t.find(e=>e.time===this.lastBarTime);e&&this.emitEvent(`bar`,{bar:e,closed:!0})}this.emitEvent(`bar`,{bar:n,closed:!1}),this.emitEvent(`tick`,{time:Date.now(),price:n.close,volume:n.volume}),this.lastBarTime=n.time}startPolling(){this.stopPolling(),this.poll();let e=this.opts.setInterval??((e,t)=>setInterval(e,t));this.timer=e(()=>{this.poll()},this.opts.intervalMs??5e3)}stopPolling(){this.timer!==null&&((this.opts.clearInterval??(e=>clearInterval(e)))(this.timer),this.timer=null)}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}};function Y(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=parseFloat(e);return Number.isFinite(t)?t:null}return null}function Qm(e){return typeof e==`object`&&!!e}var $m={"1m":60,"5m":300,"15m":900,"1h":3600,"6h":21600,"1d":86400};function eh(e){return $m[e]??3600}var th=class extends Zm{constructor(e={}){let t=e.restBase??`https://api.exchange.coinbase.com`;super({name:`coinbase`,supportedTimeframes:Object.keys($m),intervalMs:e.intervalMs??5e3,pollLimit:2,fetchBars:(e,n)=>nh(t,e,n)})}};async function nh(e,t,n){let r=`${e}/products/${t}/candles?granularity=${eh(n)}`,i=await fetch(r);if(!i.ok)throw Error(`Coinbase REST error: ${i.status}`);return rh(await i.json())}function rh(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=ih(n);e&&t.push(e)}return t.sort((e,t)=>e.time-t.time),t}function ih(e){if(!Array.isArray(e)||e.length<6)return null;let t=Y(e[0]),n=Y(e[1]),r=Y(e[2]),i=Y(e[3]),a=Y(e[4]),o=Y(e[5]);return t===null||n===null||r===null||i===null||a===null||o===null?null:{time:t*1e3,open:i,high:r,low:n,close:a,volume:o}}var ah={"1m":`1`,"3m":`3`,"5m":`5`,"15m":`15`,"30m":`30`,"1h":`60`,"2h":`120`,"4h":`240`,"6h":`360`,"12h":`720`,"1d":`D`,"1w":`W`,"1M":`M`};function oh(e){return ah[e]??`1`}var sh=class extends Xm{constructor(e={}){let t=e.restBase??`https://api.bybit.com`,n=e.wsBase??`wss://stream.bybit.com/v5/public/spot`,r=e.category??`spot`;super({name:`bybit`,wsUrl:()=>n,subscribeMessage:e=>({op:`subscribe`,args:[`kline.${oh(e.timeframe)}.${e.symbol}`]}),unsubscribeMessage:e=>({op:`unsubscribe`,args:[`kline.${oh(e.timeframe)}.${e.symbol}`]}),supportedTimeframes:Object.keys(ah),parseMessage:ch,fetchHistory:(e,n,i)=>lh(t,r,e,n,i),fetchHistoryBefore:(e,n,i,a)=>lh(t,r,e,n,a,Math.floor(i)-1)})}};function ch(e){if(!Qm(e)||typeof e.topic!=`string`||!e.topic.startsWith(`kline.`))return null;let t=e.data;if(!Array.isArray(t)||t.length===0)return null;let n=t[t.length-1];if(!Qm(n))return null;let r=Y(n.start),i=Y(n.open),a=Y(n.high),o=Y(n.low),s=Y(n.close),c=Y(n.volume);if(r===null||i===null||a===null||o===null||s===null||c===null)return null;let l=typeof n.confirm==`boolean`?n.confirm:!1;return{bar:{time:r,open:i,high:a,low:o,close:s,volume:c},closed:l}}async function lh(e,t,n,r,i,a){let o=`${e}/v5/market/kline?category=${t}&symbol=${n}&interval=${oh(r)}&limit=${Math.min(Math.max(i,1),1e3)}${a===void 0?``:`&end=${a}`}`,s=await fetch(o);if(!s.ok)throw Error(`Bybit REST error: ${s.status}`);return uh(await s.json())}function uh(e){if(!Qm(e)||!Qm(e.result))return[];let t=e.result.list;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=dh(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function dh(e){if(!Array.isArray(e)||e.length<6)return null;let t=Y(e[0]),n=Y(e[1]),r=Y(e[2]),i=Y(e[3]),a=Y(e[4]),o=Y(e[5]);return t===null||n===null||r===null||i===null||a===null||o===null?null:{time:t,open:n,high:r,low:i,close:a,volume:o}}var fh={"1m":1,"5m":5,"15m":15,"30m":30,"1h":60,"4h":240,"1d":1440,"1w":10080};function ph(e){return fh[e]??1}var mh=class extends Xm{constructor(e={}){let t=e.restBase??`https://api.kraken.com`,n=e.wsBase??`wss://ws.kraken.com/v2`;super({name:`kraken`,wsUrl:()=>n,subscribeMessage:e=>({method:`subscribe`,params:{channel:`ohlc`,symbol:[e.symbol],interval:ph(e.timeframe)}}),unsubscribeMessage:e=>({method:`unsubscribe`,params:{channel:`ohlc`,symbol:[e.symbol],interval:ph(e.timeframe)}}),supportedTimeframes:Object.keys(fh),parseMessage:hh,fetchHistory:(e,n)=>gh(t,e,n)})}};function hh(e){if(!Qm(e)||e.channel!==`ohlc`)return null;let t=e.data;if(!Array.isArray(t)||t.length===0)return null;let n=t[t.length-1];if(!Qm(n))return null;let r=Y(n.open),i=Y(n.high),a=Y(n.low),o=Y(n.close),s=Y(n.volume),c=typeof n.interval_begin==`string`?Date.parse(n.interval_begin):NaN;return r===null||i===null||a===null||o===null||s===null||!Number.isFinite(c)?null:{bar:{time:c,open:r,high:i,low:a,close:o,volume:s},closed:!1}}async function gh(e,t,n){let r=ph(n),i=t.replace(`/`,``),a=`${e}/0/public/OHLC?pair=${encodeURIComponent(i)}&interval=${r}`,o=await fetch(a);if(!o.ok)throw Error(`Kraken REST error: ${o.status}`);return _h(await o.json())}function _h(e){if(!Qm(e)||!Qm(e.result))return[];let t=null;for(let[n,r]of Object.entries(e.result))if(n!==`last`&&Array.isArray(r)){t=r;break}if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=vh(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function vh(e){if(!Array.isArray(e)||e.length<7)return null;let t=Y(e[0]),n=Y(e[1]),r=Y(e[2]),i=Y(e[3]),a=Y(e[4]),o=Y(e[6]);return t===null||n===null||r===null||i===null||a===null||o===null?null:{time:t*1e3,open:n,high:r,low:i,close:a,volume:o}}var yh={visible:!0,showSymbol:!0,showOHLC:!0,showChange:!0,showVolume:!0,position:`top-left`,fontSize:12,fontFamily:null},bh=class{config={...yh};symbol=``;timeframe=``;hoverBar=null;hoverPrev=null;indicators=[];statusText=null;exchange=``;drawnHeight=null;locale=`en-US`;pricePrecision=null;setConfig(e){Object.assign(this.config,e),this.drawnHeight=null}setPricePrecision(e){this.pricePrecision=e}setLocale(e){this.locale=e}setSymbol(e){this.symbol=e,this.drawnHeight=null}setTimeframe(e){this.timeframe=e,this.drawnHeight=null}setChartType(e){}setHoverBar(e,t=null){this.hoverBar=e,this.hoverPrev=e?t:null}setIndicatorValues(e){this.indicators=e}setStatusText(e){this.statusText=e,this.drawnHeight=null}setExchange(e){this.exchange=e,this.drawnHeight=null}title(){return this.config.showSymbol?[this.symbol,this.timeframe,this.exchange].filter(Boolean).join(` · `):``}titleCells(e,t,n,r,i){let a=[],o=this.title();if(o){let i=`600 ${t}px ${n}`;e.font=i,a.push({label:``,labelWidth:0,value:o,width:e.measureText(o).width,color:r,font:i})}if(this.statusText){let r=`${t}px ${n}`;e.font=r,a.push({label:``,labelWidth:0,value:this.statusText,width:e.measureText(this.statusText).width,color:i,font:r})}return a}priceCells(e,n,r,i,a,o,s,c){let l=`${o}px ${s}`;e.font=l;let u=i.close>=i.open,d=this.pricePrecision??(0,t.autoPricePrecision)(n.priceRange.min,n.priceRange.max),f=e=>n.formatPrice?.(e)??(0,t.formatPrice)(e,d,this.locale),p=[{label:`O`,value:f(i.open),color:c},{label:`H`,value:f(i.high),color:c},{label:`L`,value:f(i.low),color:c},{label:`C`,value:f(i.close),color:u?r.candleUp:r.candleDown}];if(this.config.showChange){let e=i.close-a.close,n=a.close===0?0:e/a.close*100,o=e>=0?`+`:``,s=(0,t.formatPrice)(n,2,this.locale);p.push({label:``,value:`${o}${f(e)} (${o}${s}%)`,color:e>=0?r.candleUp:r.candleDown})}return p.map(t=>({...t,labelWidth:t.label?e.measureText(t.label+` `).width:0,width:Th(e,t.value),font:l}))}getHeight(){if(!this.config.visible||this.config.position!==`top-left`)return 0;if(this.drawnHeight!==null)return this.drawnHeight;let e=this.config.fontSize,t=xh;return(this.config.showOHLC||this.title()||this.statusText)&&(t+=e+Ch),this.config.showVolume&&(t+=e+2),t}render(e,t,n,r){if(!this.config.visible||r.length===0)return;let i=this.hoverBar??r[r.length-1],a=this.hoverBar?this.hoverPrev??i:r.length>1?r[r.length-2]:i,{chartRect:o}=t,s=this.config.fontSize,c=this.config.fontFamily??n.font.family,l=n.style?.legend.text??n.text,u=n.style?.legend.label??n.textSecondary,d=this.config.position===`top-left`,f=d?o.x+Sh:o.x+o.width-Sh,p=o.y+xh;e.textAlign=d?`left`:`right`,e.textBaseline=`top`;let m=this.titleCells(e,s,c,l,u);if(this.config.showOHLC&&m.push(...this.priceCells(e,t,n,i,a,s,c,l)),m.length>0){e.font=`${s}px ${c}`;let t=e.measureText(` `).width;for(let n of wh(m,t,o.width-2*Sh)){let r=n.reduce((e,n)=>e+n.labelWidth+n.width+t,-t),i=d?f:f-r;e.textAlign=`left`;for(let r of n)e.font=r.font,r.label&&(e.fillStyle=u,e.fillText(r.label,i,p),i+=r.labelWidth),e.fillStyle=r.color,e.fillText(r.value,i,p),i+=r.width+t;p+=s+Ch}e.textAlign=d?`left`:`right`}if(this.config.showVolume){e.font=`${s}px ${c}`,e.fillStyle=u;let t=i.volume>=1e6?`${(i.volume/1e6).toFixed(2)}M`:i.volume>=1e3?`${(i.volume/1e3).toFixed(2)}K`:i.volume.toFixed(0);e.fillText(`Vol ${t}`,f,p),p+=s+2}if(this.drawnHeight=d?p-o.y:null,this.indicators.length>0){e.font=`${s}px ${c}`;let t=e.measureText(` `).width,n=this.indicators.map(t=>{let n=`${t.name} ${t.value}`;return{entry:n,color:t.color,width:Th(e,n)}}),r=n.reduce((e,n)=>e+n.width+t,-t),i=d?f:f-r;e.textAlign=`left`;for(let{entry:r,color:a,width:o}of n)e.fillStyle=a,e.fillText(r,i,p),i+=o+t}}},xh=6,Sh=8,Ch=3;function wh(e,t,n){let r=[],i=[],a=0;for(let o of e){let e=o.labelWidth+o.width;i.length>0&&a+t+e>n&&(r.push(i),i=[],a=0),a+=(i.length>0?t:0)+e,i.push(o)}return i.length>0&&r.push(i),r}function Th(e,t){let n=t.replace(/\d/g,`0`);return Math.max(e.measureText(t).width,e.measureText(n.replace(/[-−]/g,`+`)).width,e.measureText(n.replace(/\+/g,`-`)).width)}var Eh=class{static toDataURL(e,t){let n=e.querySelectorAll(`canvas`);if(n.length===0)return``;let r=n[0],i=r.width,a=r.height,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);t&&(s.fillStyle=t,s.fillRect(0,0,i,a));let c=Array.from(n).sort((e,t)=>(parseInt(e.style.zIndex)||0)-(parseInt(t.style.zIndex)||0));for(let e of c)s.drawImage(e,0,0);return o.toDataURL(`image/png`)}static async toBlob(e,t){let n=this.toDataURL(e,t);return n?(await fetch(n)).blob():null}static download(e,t=`chart.png`,n){let r=this.toDataURL(e,n);if(!r)return;let i=document.createElement(`a`);i.href=r,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i)}},Dh=class{config=null;setConfig(e){this.config=e}isVisible(){return!!this.config?.text}render(e,t,n){if(!this.config?.text)return;let{chartRect:r}=t,i=this.config.fontSize??48,a=n.style?.watermark.color??this.config.color??n.textSecondary;e.save(),e.globalAlpha=.07,e.font=`bold ${i}px ${n.font.family}`,e.fillStyle=a,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(this.config.text,r.x+r.width/2,r.y+r.height/2),e.restore()}},Oh={solid:null,dashed:[6,4],dotted:[2,3]},kh=6,Ah=8;function jh(e,t){let n=[...e].sort((e,t)=>t.rank-e.rank||e.px-t.px),r=[],i=[];for(let e of n){let n=0,a=r.length;for(;n<a;){let t=n+a>>1;r[t]<e.px?n=t+1:a=t}n>0&&e.px-r[n-1]<t||n<r.length&&r[n]-e.px<t||(r.splice(n,0,e.px),i.push(e))}return i.sort((e,t)=>e.px-t.px)}var Mh=class{config={visible:!1};cachedBreaksTyped=[];cachedMedianStep=0;cacheValid=!1;lastDataLength=0;locale=`en-US`;tz=null;setConfig(e){Object.assign(this.config,e)}setLocale(e){this.locale=e}setTimezone(e){e!==this.tz&&(this.tz=e,this.invalidateCache())}isVisible(){return this.config.visible}setVisible(e){this.config.visible=e}computeBreaksTyped(e){if(e.length<2)return[];if(this.cacheValid&&e.length===this.lastDataLength)return this.cachedBreaksTyped;let n=[],r=(0,t.barTimeUnit)(e),i=(0,t.timeParts)(e[0].time*r,this.tz);for(let a=1;a<e.length;a++){let o=e[a].time*r,s=(0,t.timeParts)(o,this.tz);if(s.year!==i.year)n.push({idx:a,kind:`year`,time:o,year:s.year});else if(s.month!==i.month)n.push({idx:a,kind:`month`,time:o,year:s.year});else if(s.day!==i.day){let e=new Date(Date.UTC(s.year,s.month-1,s.day)).getUTCDay()===1;n.push({idx:a,kind:e?`week`:`day`,time:o,year:s.year})}i=s}return this.lastDataLength=e.length,this.cachedBreaksTyped=n,this.cachedMedianStep=Fh(e),this.cacheValid=!0,n}render(e,t,n,r){this.renderLines(e,t,n,r),this.renderLabels(e,t,n,r)}renderLines(e,t,n,r){let i=this.lineMarks(t,r,n);if(i.length===0)return;let{chartRect:a}=t,o=this.look(n),s=Oh[o.style];e.save(),s&&e.setLineDash(s),e.strokeStyle=o.color;for(let t of i)e.globalAlpha=t.alpha,e.lineWidth=t.width,e.beginPath(),e.moveTo(t.px,a.y),e.lineTo(t.px,a.y+a.height),e.stroke();e.restore()}renderLabels(e,t,n,r){let i=this.lineMarks(t,r,n).filter(e=>e.label!==null);if(i.length===0)return;let{chartRect:a}=t;e.save(),e.font=`600 11px ${n.font.family}`,e.textBaseline=`top`,e.textAlign=`left`,e.fillStyle=n.textSecondary;let o=[],s=[...i].sort((e,t)=>t.rank-e.rank||e.px-t.px);for(let t of s){let n=t.px+4,r=n+e.measureText(t.label).width;o.some(e=>n<e.right+Ah&&r+Ah>e.left)||(o.push({left:n,right:r}),e.globalAlpha=Math.min(1,t.alpha+.35),e.fillText(t.label,n,a.y+4))}e.restore()}lineRects(e,t,n){let r=this.lineMarks(e,n,t);if(r.length===0)return[];let{color:i,style:a}=this.look(t),o=Oh[a]??void 0,{y:s,height:c}=e.chartRect;return r.map(e=>({x:e.px-e.width/2,y:s,width:e.width,height:c,color:i,alpha:e.alpha,...o?{dash:o}:{}}))}look(e){let t=e.style?.sessionBreaks;return{color:t?.color??this.config.color??e.axisLine,style:t?.style??this.config.lineStyle??`dashed`,width:t?.width??this.config.lineWidth??1}}lineMarks(e,t,n){return jh(this.marks(e,t,n),kh)}marks(n,r,i){if(!this.config.visible||r.length<2)return[];let a=this.computeBreaksTyped(r);if(a.length===0||this.cachedMedianStep>=1380*60*1e3)return[];let{chartRect:o}=n,s=this.look(i).width,c=[];for(let r of a){let i=e.b(r.idx,n)-(n.barWidth+n.barSpacing)/2;if(i<o.x-1||i>o.x+o.width+1)continue;let a=Math.round(i)+.5,l=.25,u=s,d=null,f=3;r.kind===`day`?(l=.22,f=0):r.kind===`week`?(l=.34,f=1,d=(0,t.zonedDateFormatter)(this.locale,Nh,this.tz)(r.time)):r.kind===`month`?(l=.5,f=2,u=s+.5,d=(0,t.zonedDateFormatter)(this.locale,Ph,this.tz)(r.time)):(l=.7,u=s+1,d=String(r.year)),c.push({px:a,width:u,alpha:l,label:d,rank:f})}return c}invalidateCache(){this.lastDataLength=0,this.cachedBreaksTyped=[],this.cachedMedianStep=0,this.cacheValid=!1}},Nh={month:`short`,day:`numeric`},Ph={month:`short`,year:`numeric`};function Fh(e){if(e.length<2)return 0;let n=Math.min(50,e.length-1),r=(0,t.barTimeUnit)(e),i=[];for(let t=1;t<=n;t++)i.push((e[t].time-e[t-1].time)*r);return i.sort((e,t)=>e-t),i[Math.floor(i.length/2)]}var Ih=864e5;function Lh(e,t){let n={...e,...t};return t.tzOffsetMinutes!==void 0&&t.timeZone===void 0&&delete n.timeZone,n.windows?n.windows=n.windows.map(e=>({...e})):delete n.windows,n}function Rh(e,t){let n=((e+t*6e4)%Ih+Ih)%Ih;return Math.floor(n/6e4)}function zh(e,t,n){return t===n?!0:t<n?e>=t&&e<n:e>=t||e<n}function Bh(e,n){let r=Rh(e,n.timeZone?(0,t.zoneOffsetMinutes)(n.timeZone,e):n.tzOffsetMinutes??0);return n.windows&&n.windows.length>0?n.windows.some(e=>zh(r,e.startMinute,e.endMinute)):zh(r,n.startMinute,n.endMinute)}var Vh={startMinute:570,endMinute:960,tzOffsetMinutes:-300,timeZone:`America/New_York`},Hh=class{visible=!1;config={...Vh};setVisible(e){this.visible=e}isVisible(){return this.visible}setConfig(e){this.config=Lh(this.config,e)}replaceConfig(e){this.config=Lh(e,{})}getConfig(){return{...this.config,windows:this.config.windows?.map(e=>({...e}))}}render(e,t,n,r){let i=this.rects(t,n,r);if(i.length!==0){e.save(),e.fillStyle=i[0].color;for(let t of i)e.fillRect(t.x,t.y,t.width,t.height);e.restore()}}rects(t,n,r){if(!this.visible||t.length===0)return[];let{chartRect:i}=n,{from:a,to:o}=n.visibleRange,s=Math.max(0,a),c=Math.min(o,t.length-1);if(c<s)return[];let l=n.barWidth+n.barSpacing,u=r.name===`light`?`rgba(0,0,0,0.045)`:`rgba(0,0,0,0.28)`,d=[],f=-1,p=(t,r)=>{let a=e.b(t,n)-l/2,o=e.b(r,n)+l/2;d.push({x:a,y:i.y,width:o-a,height:i.height,color:u,alpha:1})};for(let e=s;e<=c;e++){let n=!Bh(t[e].time,this.config);n&&f===-1?f=e:!n&&f!==-1&&(p(f,e-1),f=-1)}return f!==-1&&p(f,c),d}},Uh=[2,3],Wh=16,Gh=class{highLow=!1;quote=null;quoteShown=!0;priceText=null;setPriceText(e){this.priceText=e}setQuoteShown(e){this.quoteShown=e}setHighLow(e){this.highLow=e}isHighLowVisible(){return this.highLow}setBidAsk(e){this.quote=e?{...e}:null}getBidAsk(){return this.quote?{...this.quote}:null}levels(e,t){let n=[];if(this.highLow){let r=Math.max(0,t.visibleRange.from),i=Math.min(e.length-1,t.visibleRange.to),a=-1/0,o=1/0;for(let t=r;t<=i;t++)e[t].high>a&&(a=e[t].high),e[t].low<o&&(o=e[t].low);Number.isFinite(a)&&n.push({kind:`high`,price:a}),Number.isFinite(o)&&n.push({kind:`low`,price:o})}let{bid:r,ask:i}=(this.quoteShown?this.quote:null)??{};return r!==void 0&&Number.isFinite(r)&&n.push({kind:`bid`,price:r}),i!==void 0&&Number.isFinite(i)&&n.push({kind:`ask`,price:i}),n}render(t,n,r,i){let{chartRect:a}=n;t.save(),t.setLineDash(Uh),t.lineWidth=1;for(let o of this.levels(i,n)){let i=Math.round(e.T(o.price,n))+.5;i<a.y||i>a.y+a.height||(t.strokeStyle=Kh(o.kind,r),t.beginPath(),t.moveTo(a.x,i),t.lineTo(a.x+a.width,i),t.stroke())}t.restore()}renderAxisTags(n,r,i,a){let{chartRect:o}=r,s=o.x+o.width+1,c=(r.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,l=(0,t.autoPricePrecision)(r.priceRange.min,r.priceRange.max);n.save(),n.font=`${i.font.sizeSmall}px ${i.font.family}`,n.textBaseline=`middle`,n.textAlign=`left`;for(let u of this.levels(a,r)){let a=e.T(u.price,r);if(a<o.y||a>o.y+o.height)continue;n.fillStyle=Kh(u.kind,i),E(n,s,a-Wh/2,c,Wh,i),n.fillStyle=i.background;let d=r.formatPrice?.(u.price)??this.priceText?.(u.price)??(0,t.formatPrice)(u.price,l);n.fillText(d,s+5,a)}n.restore()}};function Kh(e,t){switch(e){case`bid`:return t.candleUp;case`ask`:return t.candleDown;default:return t.style?.highLow.color??t.textSecondary}}var qh=12,Jh=3,Yh=500,Xh=2,Zh=[`movesUp`,`movesDown`];function Qh(e){return e.channel===`price`&&!e.drawingId&&!e.target&&!Zh.includes(e.condition)}function $h(e,t,n,r){switch(r){case`crossingUp`:return e!==void 0&&e<n&&t>=n;case`crossingDown`:return e!==void 0&&e>n&&t<=n;case`crossing`:return e!==void 0&&(e<n&&t>=n||e>n&&t<=n);case`greaterThan`:return t>n;case`lessThan`:return t<n;default:return!1}}var eg=[`crossing`,`crossingUp`,`crossingDown`];function tg(e,t,n){let r=e<0&&t>=0,i=e>0&&t<=0;return n===`crossingUp`?r:n===`crossingDown`?i:r||i}var ng=1,rg=2**31-1,ig=class extends am{alerts=[];lastValues=new Map;drawingSides=new Map;drawingLevels=null;requestRender=null;pricePrecision=null;barTime=null;expiryTimer=null;history=new Map;lastDiffs=new Map;setBarTime(e){this.barTime=e}setRequestRender(e){this.requestRender=e}setPricePrecision(e){this.pricePrecision=e}addAlert(e,t=`crossing`,n,r=!1,i=`price`,a,o={}){let s=ag(t,i,o),c=`tc_alert_${ng++}`,l={id:c,price:e,condition:t,message:n,triggered:!1,repeating:r,channel:i,label:a,...s};return this.alerts.push(l),s.expiresAt!==void 0&&this.scheduleExpiry(),this.emit(`added`,l),this.requestRender?.(),c}setDrawingLevels(e){this.drawingLevels=e}addDrawingAlert(e,t=`crossing`,n,r=!1,i){if(!eg.includes(t))throw RangeError(`An alert on a drawing takes a crossing condition, not "${t}"`);let a=`tc_alert_${ng++}`,o={id:a,price:this.drawingLevels?.(e)?.[0]??NaN,condition:t,message:n,triggered:!1,repeating:r,channel:`price`,label:i,drawingId:e};return this.alerts.push(o),this.emit(`added`,o),a}removeDrawingAlerts(e){for(let t of this.alerts.filter(t=>t.drawingId===e))this.removeAlert(t.id)}takeDrawingAlerts(e){let t=this.alerts.filter(t=>t.drawingId===e);for(let e of t)this.removeAlert(e.id);return t.map(e=>({...e}))}restoreAlerts(e){for(let t of e){if(this.alerts.some(e=>e.id===t.id))continue;let e={...t};this.alerts.push(e),this.emit(`added`,e)}this.scheduleExpiry(),this.requestRender?.()}pruneDrawingAlerts(e){let t=this.alerts.filter(t=>t.drawingId!==void 0&&!e.has(t.drawingId));for(let e of t)this.removeAlert(e.id);return t.length}removeAlert(e){this.drawingSides.delete(e),this.lastDiffs.delete(e);let t=this.alerts.some(t=>t.id===e&&t.expiresAt!==void 0);this.alerts=this.alerts.filter(t=>t.id!==e),t&&this.scheduleExpiry(),this.emit(`removed`,e),this.requestRender?.()}getAlerts(){return[...this.alerts]}getAlertAtPoint(t,n,r=6){let{chartRect:i}=n;if(t.y<i.y||t.y>i.y+i.height)return null;let a=null,o=r;for(let r of this.alerts){if(!Qh(r))continue;let i=Math.abs(e.T(r.price,n)-t.y);i<=o&&(o=i,a=r)}return a}updateAlertPrice(e,t){let n=this.alerts.find(t=>t.id===e);!n||!Number.isFinite(t)||(n.price=t,n.triggered=!1,n.expiresAt!==void 0&&this.scheduleExpiry(),this.emit(`updated`,{...n}),this.requestRender?.())}clearAlerts(){this.alerts=[],this.lastDiffs.clear(),this.drawingSides.clear(),this.scheduleExpiry(),this.requestRender?.()}checkPrice(e){this.checkChannel(`price`,e),this.checkDrawingAlerts(e)}checkDrawings(e){this.checkDrawingAlerts(e)}expire(){let e=Date.now(),t=this.alerts.filter(t=>!t.expired&&t.expiresAt!==void 0&&e>=t.expiresAt&&!(t.triggered&&!t.repeating));if(t.length!==0){for(let e of t)e.expired=!0;try{for(let e of t)this.emit(`expired`,{...e}),this.emit(`updated`,{...e})}finally{this.requestRender?.(),this.scheduleExpiry()}}}scheduleExpiry(){this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=null;let e=Math.min(...this.alerts.filter(e=>!e.expired&&e.expiresAt!==void 0&&!(e.triggered&&!e.repeating)).map(e=>e.expiresAt));if(!Number.isFinite(e))return;let t=Math.min(Math.max(0,e-Date.now()),rg);this.expiryTimer=setTimeout(()=>{this.expiryTimer=null,this.expire(),this.expiryTimer||this.scheduleExpiry()},t)}dispose(){this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=null}checkDrawingAlerts(e){if(!(!this.drawingLevels||!Number.isFinite(e)))for(let t of this.alerts){if(!t.drawingId||t.expired)continue;let n=this.drawingLevels(t.drawingId);if(!n||n.length===0){this.drawingSides.delete(t.id);continue}t.price=n[0];let r=n.map(t=>Math.sign(e-t)),i=this.drawingSides.get(t.id);this.drawingSides.set(t.id,r),!(!i||i.length!==r.length)&&(r.some((e,n)=>tg(i[n],e,t.condition))?t.triggered||(t.triggered=!0,this.emit(`triggered`,{...t})):t.repeating&&(t.triggered=!1))}}checkChannel(e,t){this.checkChannels(new Map([[e,t]]))}checkChannels(e,t={}){let n=(e instanceof Map?[...e.entries()]:Object.entries(e)).filter(([,e])=>Number.isFinite(e));if(n.length===0)return;this.expire();let r=new Map,i=new Map;for(let[e,t]of n){r.set(e,this.lastValues.get(e));let n=this.recordBar(e,t);n&&i.set(e,n),this.lastValues.set(e,t)}for(let e of this.alerts){if(e.drawingId||e.expired)continue;let n=r.has(e.channel),a=e.target!==void 0&&r.has(e.target);if(!n&&!a||e.target!==void 0&&t.together&&!(n&&a))continue;let o;if(e.onBarClose){let t=i.get(e.channel)??(e.target?i.get(e.target):void 0);if(!t)continue;o=this.closedBarMet(e,t)}else if(e.target)o=this.targetMet(e);else if(Zh.includes(e.condition)){if(!n)continue;o=this.moveMet(e,this.history.get(e.channel)??[])}else{let t=r.get(e.channel);if(!n||t===void 0)continue;o=$h(t,this.lastValues.get(e.channel),e.price,e.condition)}this.settle(e,o)}}settle(e,t){t?e.triggered||(e.triggered=!0,this.emit(`triggered`,{...e})):e.repeating&&(e.triggered=!1)}targetMet(e){let t=this.lastValues.get(e.channel),n=e.target?this.lastValues.get(e.target):void 0;if(t===void 0||n===void 0)return!1;let r=t-n,i=this.lastDiffs.get(e.id);return this.lastDiffs.set(e.id,r),e.price=n,$h(i,r,0,e.condition)}moveMet(e,t,n=t.length){let r=e.bars??1,i=t.slice(Math.max(0,n-r),n);if(i.length<2||e.percent===void 0)return!1;let a=i[i.length-1].value,o=i.map(e=>e.value);if(e.condition===`movesUp`){let t=Math.min(...o);return t!==0&&(a-t)/Math.abs(t)*100>=e.percent}let s=Math.max(...o);return s!==0&&(s-a)/Math.abs(s)*100>=e.percent}closedBarMet(e,t){let n=this.history.get(e.channel)??[],r=n.findIndex(e=>e.time===t.time);if(r<0)return!1;if(Zh.includes(e.condition))return this.moveMet(e,n,r+1);let i=(e,t)=>{let r=this.history.get(e)??[],i=n[t]?.time;return i===void 0?void 0:r.find(e=>e.time===i)?.value},a=n[r].value,o=r>0?n[r-1].value:void 0,s=e.price;if(e.target){let t=i(e.target,r),n=r>0?i(e.target,r-1):void 0;if(t===void 0)return!1;a-=t,o=o!==void 0&&n!==void 0?o-n:void 0,s=0,e.price=t}return $h(o,a,s,e.condition)}recordBar(e,t){let n=this.barTime;if(n===null)return null;let r=this.history.get(e)??[],i=r[r.length-1];if(i&&n<i.time)return r=r.filter(e=>e.time<n),r.push({time:n,value:t}),this.history.set(e,r),null;if(i&&i.time===n)return r[r.length-1]={time:n,value:t},null;i=r[r.length-1],r.push({time:n,value:t});let a=Math.min(502,Math.max(3,...this.alerts.map(e=>(e.bars??1)+2)));return r.length>a&&r.splice(0,r.length-a),this.history.set(e,r),i?{channel:e,time:i.time}:null}clearLastValues(){this.lastValues.clear(),this.drawingSides.clear(),this.history.clear(),this.lastDiffs.clear()}saveToStorage(e){try{let t=this.alerts.map(e=>({id:e.id,price:e.price,condition:e.condition,message:e.message,triggered:e.triggered,repeating:e.repeating,channel:e.channel,label:e.label,drawingId:e.drawingId,target:e.target,percent:e.percent,bars:e.bars,onBarClose:e.onBarClose,expiresAt:e.expiresAt,expired:e.expired}));localStorage.setItem(e,JSON.stringify(t))}catch{}}loadFromStorage(e){try{let t=localStorage.getItem(e);if(!t)return;let n=JSON.parse(t);if(!Array.isArray(n))return;for(let e of n){if(typeof e.drawingId==`string`&&e.condition&&!e.triggered){eg.includes(e.condition)&&this.addDrawingAlert(e.drawingId,e.condition,e.message,e.repeating??!1,e.label);continue}if(!e.condition||e.triggered||e.expired)continue;let t=og(e),n=!t.target&&!Zh.includes(e.condition),r=typeof e.price==`number`&&Number.isFinite(e.price)?e.price:NaN;if(!(n&&Number.isNaN(r)))try{this.addAlert(r,e.condition,e.message,e.repeating??!1,e.channel??`price`,e.label,t)}catch{}}}catch{}}render(n,r,i){let{chartRect:a}=r;for(let o of this.alerts){if(!Qh(o))continue;let s=e.T(o.price,r);if(s<a.y||s>a.y+a.height)continue;let c=o.expired?`#8a93a3`:o.triggered?`#f2a93b`:`#4c8dff`;n.setLineDash([2,6]),n.strokeStyle=c,n.lineWidth=1,n.beginPath(),n.moveTo(a.x,Math.round(s)+.5),n.lineTo(a.x+a.width,Math.round(s)+.5),n.stroke(),n.setLineDash([]),n.font=`10px ${i.font.family}`,n.fillStyle=c,n.textBaseline=`bottom`,n.textAlign=`right`;let l=`${(0,t.priceTagText)(o.price,r,this.pricePrecision??void 0)}${o.message?` - ${o.message}`:``}`,u=a.x+a.width-4;n.fillText(l,u,s-2);let d=u-n.measureText(l).width-Jh-qh;d>=a.x&&Jf(n,t.UI_ICONS.bell,d,s-2-qh,qh,c)}}};function ag(e,t,n){let r={},i=Zh.includes(e);if(n.target!==void 0){if(i)throw RangeError(`An alert on a move takes no other line`);if(n.target===t)throw RangeError(`An alert can’t compare a line with itself`);r.target=n.target}if(i){let{percent:e,bars:t}=n;if(e===void 0||!Number.isFinite(e)||e<=0)throw RangeError(`An alert on a move needs a percent above 0`);if(t===void 0||!Number.isInteger(t)||t<2||t>500)throw RangeError(`An alert on a move needs 2 to 500 bars`);r.percent=e,r.bars=t}return n.onBarClose&&(r.onBarClose=!0),n.expiresAt!==void 0&&Number.isFinite(n.expiresAt)&&(r.expiresAt=n.expiresAt),r}function og(e){let t={};return typeof e.target==`string`&&e.target&&(t.target=e.target),typeof e.percent==`number`&&Number.isFinite(e.percent)&&(t.percent=e.percent),typeof e.bars==`number`&&Number.isInteger(e.bars)&&(t.bars=e.bars),e.onBarClose===!0&&(t.onBarClose=!0),typeof e.expiresAt==`number`&&Number.isFinite(e.expiresAt)&&(t.expiresAt=e.expiresAt),t}var sg=16,cg=()=>typeof requestAnimationFrame==`function`&&!(typeof document<`u`&&document.hidden),lg={now:()=>typeof performance<`u`?performance.now():Date.now(),frame:e=>cg()?{raf:requestAnimationFrame(e)}:{timeout:setTimeout(e,sg)},cancel:e=>{let t=e;t.raf!==void 0&&cancelAnimationFrame(t.raf),t.timeout!==void 0&&clearTimeout(t.timeout)}},ug=class extends am{data=[];cursor=-1;timer=null;frameHandle=null;run=0;state=`stopped`;config={speed:1,interval:500};paceMs=null;constructor(e=lg){super(),this.clock=e}load(e){this.stop(),this.data=e,this.cursor=-1}play(e){if(this.data.length===0)return;if(e){let{startIndex:t,paused:n,duration:r,...i}=e;this.config={...this.config,...i};let a=t===void 0?null:this.clamp(t);if(n){this.clearTimer(),this.seekTo(a??Math.max(0,this.cursor)),this.setPace(r),this.setState(`paused`);return}a!==null&&(this.cursor=a-1),this.setPace(r)}if(this.isAtEnd()){this.clearTimer(),this.setState(`paused`);return}this.clearTimer();let t=this.paceMs??this.config.interval/this.config.speed;if(!(t>0)||!Number.isFinite(t)){this.setState(`paused`);return}this.setState(`playing`),t<sg||this.paceMs!==null?this.runFrames(t):this.timer=setInterval(()=>this.advance(1),t)}pause(){this.clearTimer(),this.setState(`paused`)}resume(){this.state===`paused`&&this.play()}stop(){this.clearTimer(),this.cursor=-1,this.setState(`stopped`)}seekTo(e){this.data.length!==0&&(this.cursor=this.clamp(e),this.emit(`bar`,{bar:this.data[this.cursor],index:this.cursor,total:this.data.length}))}setSpeed(e){this.config={...this.config,speed:e},this.paceMs=null,this.state===`playing`&&this.play()}getState(){return this.state}isAtEnd(){return this.data.length>0&&this.cursor>=this.data.length-1}getProgress(){let e=this.data.length;return{current:Math.max(0,this.cursor),total:e,percent:e>0?(this.cursor+1)/e*100:0}}dispose(){this.stop(),this.removeAllListeners(),this.data=[]}setPace(e){this.paceMs=e!==void 0&&e>0&&Number.isFinite(e)?e/Math.max(1,this.data.length-1-this.cursor):null}runFrames(e){let t=this.run,n=this.clock.now(),r=0,i=()=>{if(t!==this.run||this.state!==`playing`)return;this.frameHandle=null;let a=this.clock.now();r+=Math.min(50,Math.max(0,a-n)),n=a;let o=Math.floor(r/e);try{o>0&&(r-=o*e,this.advance(o))}finally{t===this.run&&this.state===`playing`&&this.frameHandle===null&&(this.frameHandle=this.clock.frame(i))}};this.frameHandle=this.clock.frame(i)}advance(e){if(this.isAtEnd()){this.finish();return}this.cursor=Math.min(this.data.length-1,this.cursor+e),this.emit(`bar`,{bar:this.data[this.cursor],index:this.cursor,total:this.data.length}),this.isAtEnd()&&this.finish()}finish(){this.clearTimer(),this.setState(`paused`),this.emit(`complete`,void 0)}clamp(e){return Number.isFinite(e)?Math.max(0,Math.min(Math.floor(e),this.data.length-1)):0}clearTimer(){this.run++,this.timer&&=(clearInterval(this.timer),null),this.frameHandle!==null&&(this.clock.cancel(this.frameHandle),this.frameHandle=null)}setState(e){this.state!==e&&(this.state=e,this.emit(`stateChange`,e))}},dg=64,fg=3,pg=3;function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mg(e){return Array.isArray(e)?e:[]}function hg(e,t){return typeof e==`string`?e:t}function gg(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function _g(e){if(!X(e)||typeof e.id!=`string`||typeof e.type!=`string`||!Array.isArray(e.anchors)||e.anchors.length===0||e.anchors.length>vg||!X(e.style))return null;let n=[];for(let t of e.anchors){if(!X(t)||typeof t.time!=`number`||typeof t.price!=`number`||!Number.isFinite(t.time)||!Number.isFinite(t.price))return null;n.push({time:t.time,price:t.price})}let r=(0,t.sanitizeDrawingStyle)(e.style);return r.color===void 0||r.lineWidth===void 0?null:{id:e.id,type:e.type,anchors:n,style:{lineStyle:`solid`,...r,color:r.color,lineWidth:r.lineWidth},visible:typeof e.visible==`boolean`?e.visible:!0,locked:typeof e.locked==`boolean`?e.locked:!1,options:X(e.options)?e.options:void 0,intervals:nn(e.intervals)??void 0,group:xg(e.group),meta:X(e.meta)?e.meta:void 0}}var vg=5e3,yg=64,bg=80;function xg(e){if(!(!X(e)||typeof e.id!=`string`||typeof e.name!=`string`)&&!(e.id===``||e.id.length>yg))return{id:e.id,name:e.name.slice(0,bg)}}function Sg(e){return!X(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.type!=`string`||typeof e.price!=`number`||typeof e.quantity!=`number`?null:e}function Cg(e){if(!X(e))return;let n={},r=mg(e.colors).filter(e=>typeof e==`string`);r.length>0&&(n.colors=r);let i=mg(e.lineWidths).filter(e=>typeof e==`number`&&Number.isFinite(e)&&e>0);i.length>0&&(n.lineWidths=i),typeof e.opacity==`number`&&Number.isFinite(e.opacity)&&(n.opacity=Math.min(1,Math.max(0,e.opacity)));let a=(0,t.readIndicatorPlotStyles)(e.plots);return a&&(n.plots=a),Object.keys(n).length>0?n:void 0}var wg=[`crossingUp`,`crossingDown`,`crossing`,`greaterThan`,`lessThan`,`movesUp`,`movesDown`];function Tg(e){if(!X(e)||typeof e.id!=`string`)return null;let t=typeof e.drawingId==`string`?e.drawingId:void 0,n=typeof e.price==`number`&&Number.isFinite(e.price)?e.price:null,r=wg.find(t=>t===e.condition)??`crossing`,i=og(e),a=i.target!==void 0||r===`movesUp`||r===`movesDown`;return n===null&&!t&&!a?null:{id:e.id,price:n??NaN,drawingId:t,condition:r,message:typeof e.message==`string`?e.message:void 0,triggered:e.triggered===!0,repeating:e.repeating===!0,channel:hg(e.channel,`price`),label:typeof e.label==`string`?e.label:void 0,...i,...e.expired===!0?{expired:!0}:{}}}function Eg(e){return!X(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.entryPrice!=`number`||typeof e.quantity!=`number`?null:e}var Dg=4e3;function Og(e){if(!X(e))return;let n={},r=[];for(let[i,a]of Object.entries(e)){let e=(0,t.readChartStyleOverrides)(a);r.push(...e.rejected);let o=Object.fromEntries(Object.entries(e.overrides).filter(([,e])=>e!==null));Object.keys(o).length>0&&(n[i.slice(0,dg)]=o)}return r.length>0&&console.warn(`Saved style overrides left out: ${[...new Set(r)].join(`, `)}`),n}function kg(e){if(!X(e))return Ag();typeof e.version==`number`&&e.version>pg&&console.warn(`Chart state from a newer version (${e.version}); loading what this version understands.`);let n=X(e.viewport)?e.viewport:{},r=[];for(let n of mg(e.indicators))X(n)&&(typeof n.id!=`string`||typeof n.instanceId!=`string`||X(n.params)&&r.push({id:n.id,instanceId:n.instanceId,params:n.params,position:typeof n.position==`string`?n.position:void 0,style:Cg(n.style),visible:typeof n.visible==`boolean`?n.visible:void 0,levels:Array.isArray(n.levels)?n.levels.filter(e=>typeof e==`number`&&Number.isFinite(e)):void 0,pane:typeof n.pane==`string`?n.pane:void 0,scale:n.scale===`left`?`left`:void 0,intervals:nn(n.intervals)??void 0,paneStyle:(0,t.readPaneStyle)(n.paneStyle)??void 0,paneSize:typeof n.paneSize==`number`&&Number.isFinite(n.paneSize)&&n.paneSize>0?Math.min(n.paneSize,Dg):void 0,paneOrder:typeof n.paneOrder==`number`&&Number.isInteger(n.paneOrder)&&n.paneOrder>=0?n.paneOrder:void 0,paneCollapsed:n.paneCollapsed===!0?!0:void 0,paneMaximized:n.paneMaximized===!0?!0:void 0,paneLog:n.paneLog===!0?!0:void 0,paneInvert:n.paneInvert===!0?!0:void 0,panePercent:n.panePercent===!0?!0:void 0}));let i=[];for(let t of mg(e.drawings)){let e=_g(t);e&&i.push(e)}let a=[];for(let t of mg(e.orders)){let e=Sg(t);e&&a.push(e)}let o=[];for(let t of mg(e.positions)){let e=Eg(t);e&&o.push(e)}let s=[];for(let t of mg(e.alerts)){let e=Tg(t);e&&s.push(e)}let c=Og(e.overrides);return{version:typeof e.version==`number`&&Array.isArray(e.indicators)?e.version:1,timestamp:gg(e.timestamp,Date.now()),symbol:typeof e.symbol==`string`?e.symbol:void 0,timeframe:typeof e.timeframe==`string`?e.timeframe:void 0,chartType:hg(e.chartType,`candlestick`),...e.chartTypeOptions===void 0?{}:{chartTypeOptions:(0,t.readChartTypeOptions)(e.chartTypeOptions)},viewport:{barWidth:gg(n.barWidth,8),barSpacing:gg(n.barSpacing,2),offset:gg(n.offset,0)},theme:typeof e.theme==`string`?e.theme:void 0,...c?{overrides:c}:{},locale:typeof e.locale==`string`?e.locale:void 0,indicators:r,drawings:i,orders:a,positions:o,alerts:s}}function Ag(){return{version:1,timestamp:Date.now(),chartType:`candlestick`,viewport:{barWidth:8,barSpacing:2,offset:0},indicators:[],drawings:[],orders:[],positions:[],alerts:[]}}var jg=class{static capture(e,t){return{version:e.getIndicators?pg:1,timestamp:Date.now(),chartType:t?.chartType??`candlestick`,...t?.chartTypeOptions&&Object.keys(t.chartTypeOptions).length>0?{chartTypeOptions:t.chartTypeOptions}:{},symbol:t?.symbol,timeframe:t?.timeframe,viewport:{barWidth:8,barSpacing:2,offset:0},theme:e.getTheme().name,...e.getOverrides&&Object.keys(e.getOverrides()).length>0?{overrides:e.getOverrides()}:{},indicators:e.getIndicators?.()??[],drawings:e.getDrawings(),orders:e.getOrders?.()??[],positions:e.getPositions?.()??[],alerts:e.getAlerts?.()??[]}}static serialize(e){return JSON.stringify(e)}static deserialize(e){return kg(JSON.parse(e))}static saveToStorage(e,t){localStorage.setItem(e,this.serialize(t))}static loadFromStorage(e){let t=localStorage.getItem(e);return t?this.deserialize(t):null}static downloadFile(e,t=`tc-chart-state.json`){let n=new Blob([this.serialize(e)],{type:`application/json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}static loadFromFile(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.type=`file`,n.accept=`.json`,n.onchange=async()=>{let r=n.files?.[0];if(!r){t(Error(`No file selected`));return}let i=await r.text();e(this.deserialize(i))},n.click()})}},Mg=class{undoStack=[];redoStack=[];maxHistory=50;onChange=null;setOnChange(e){this.onChange=e}push(e){this.undoStack.push(e),this.undoStack.length>this.maxHistory&&this.undoStack.shift(),this.redoStack.length=0,this.onChange?.()}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undo(){let e=this.undoStack.pop();return e?(this.redoStack.push(e),this.onChange?.(),e):null}redo(){let e=this.redoStack.pop();return e?(this.undoStack.push(e),this.onChange?.(),e):null}clear(){this.undoStack.length=0,this.redoStack.length=0,this.onChange?.()}last(){return this.undoStack[this.undoStack.length-1]??null}dropLast(){this.undoStack.pop()&&(this.redoStack.length=0,this.onChange?.())}replaceLast(e){if(this.undoStack.length===0){this.push(e);return}this.undoStack[this.undoStack.length-1]=e,this.redoStack.length=0,this.onChange?.()}getState(){return{canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoCount:this.undoStack.length,redoCount:this.redoStack.length}}},Ng=[`Time`,`Open`,`High`,`Low`,`Close`,`Volume`];function Pg(e,n){return new Date((0,t.normalizeBarTime)(e,n)).toISOString()}function Fg(e){let t=/^[=+\-@\t\r]/.test(e)&&!/^-?\d/.test(e)?`'${e}`:e;return/[",\r\n]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}var Ig=e=>e==null||!Number.isFinite(e)?``:String(e),Lg=class{static toCSV(e,n=[]){let r=[...Ng,...n.map(e=>Fg(e.name))].join(`,`),i=(0,t.barTimeUnit)(e);return[r,...e.map((e,t)=>[Pg(e.time,i),e.open,e.high,e.low,e.close,e.volume,...n.map(e=>Ig(e.values[t]))].join(`,`))].join(`
22
+ `)}static toJSON(e,n=[]){let r=(0,t.barTimeUnit)(e);return JSON.stringify(e.map((e,t)=>{let i={time:Pg(e.time,r),open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume};for(let e of n){let n=e.values[t];i[e.name]=n==null||!Number.isFinite(n)?null:n}return i}),null,2)}static download(e,t,n){let r=new Blob([e],{type:n}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}};function Rg(e,t,n=-1/0){return t===null?e:e.filter(e=>e.time>=n&&e.time<t)}function zg(e,t,n=-1/0){return t===null?e:e.filter(e=>e.entryTime>=n&&e.entryTime<t).map(e=>{if(e.exitTime===void 0||e.exitTime<t)return e;let{exitTime:n,exitPrice:r,pnl:i,pnlPercent:a,...o}=e;return o})}var Bg=1,Vg=3,Hg=class extends am{markers=[];style={...t.DEFAULT_SIGNAL_STYLE};requestRender=null;dataGetter=null;revealUntil=null;revealFrom=-1/0;setRequestRender(e){this.requestRender=e}setDataGetter(e){this.dataGetter=e}setStyle(e){this.style={...this.style,...e},this.requestRender?.()}getStyle(){return{...this.style}}addMarker(e){let t=e.id??`tc_signal_${Bg++}`,n={...e,id:t};return this.markers.push(n),this.emit(`added`,n),this.requestRender?.(),t}removeMarker(e){this.markers=this.markers.filter(t=>t.id!==e),this.emit(`removed`,e),this.requestRender?.()}getMarkers(){return[...this.markers]}clearMarkers(){this.markers=[],this.emit(`cleared`,void 0),this.requestRender?.()}setMarkers(e){this.markers=[...e],this.requestRender?.()}setRevealUntil(e,t=-1/0){e===this.revealUntil&&t===this.revealFrom||(this.revealUntil=e,this.revealFrom=t,this.requestRender?.())}shownMarkers(){return[...Rg(this.markers,this.revealUntil,this.revealFrom)]}markerAt(t,n){let r=this.dataGetter?.();if(!r||r.length===0)return null;let{chartRect:i}=n;if(t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height)return null;let a=this.style.arrowSize??12,o=Rg(this.markers,this.revealUntil,this.revealFrom);for(let i=o.length-1;i>=0;i--){let s=o[i],c=e.b(e.k(s.time,r),n),l=e.T(s.price,n),u=a*Math.max(.6,Math.min(1,s.confidence)),d=s.direction===`long`?l-u:(s.direction,l-u*.4),f=s.direction===`long`?l+u*.4:s.direction===`short`?l+u:l+u*.4;if(Math.abs(t.x-c)<=u*.6+Vg&&t.y>=d-Vg&&t.y<=f+Vg)return s}return null}render(t,n,r){let i=this.dataGetter?.(),a=Rg(this.markers,this.revealUntil,this.revealFrom);if(!i||i.length===0||a.length===0)return;let{chartRect:o}=n,s=Qs(this.style,r),c=s.arrowSize??12;t.save(),t.beginPath(),t.rect(o.x,o.y,o.width,o.height),t.clip();for(let l of a){let a=e.b(e.k(l.time,i),n),u=e.T(l.price,n);if(a<o.x-c||a>o.x+o.width+c||u<o.y-c||u>o.y+o.height+c)continue;let d=this.resolveColor(l,s),f=c*Math.max(.6,Math.min(1,l.confidence));if(this.renderArrow(t,a,u,l.direction,f,d),s.showLabel&&l.label){t.font=`10px ${r.font.family}`,t.fillStyle=d,t.textAlign=`center`,t.textBaseline=l.direction===`long`?`top`:`bottom`;let e=l.direction===`long`?u+f+3:u-f-3;t.fillText(l.label,a,e)}if(s.showConfidence&&l.confidence<1){t.font=`9px ${r.font.family}`,t.fillStyle=d,t.globalAlpha=.7,t.textAlign=`center`,t.textBaseline=l.direction===`long`?`top`:`bottom`;let e=l.direction===`long`?u+f+(l.label?14:3):u-f-(l.label?14:3);t.fillText(`${Math.round(l.confidence*100)}%`,a,e),t.globalAlpha=1}}t.restore()}resolveColor(e,t){if(e.color)return e.color;if(t.sourceColors?.[e.source])return t.sourceColors[e.source];switch(e.direction){case`long`:return t.longColor??`#1fa874`;case`short`:return t.shortColor??`#e8505b`;default:return t.neutralColor??`#9E9E9E`}}renderArrow(e,t,n,r,i,a){e.fillStyle=a,e.beginPath(),r===`long`?(e.moveTo(t,n-i),e.lineTo(t-i*.6,n),e.lineTo(t-i*.2,n),e.lineTo(t-i*.2,n+i*.4),e.lineTo(t+i*.2,n+i*.4),e.lineTo(t+i*.2,n),e.lineTo(t+i*.6,n)):r===`short`?(e.moveTo(t,n+i),e.lineTo(t-i*.6,n),e.lineTo(t-i*.2,n),e.lineTo(t-i*.2,n-i*.4),e.lineTo(t+i*.2,n-i*.4),e.lineTo(t+i*.2,n),e.lineTo(t+i*.6,n)):e.arc(t,n,i*.4,0,Math.PI*2),e.closePath(),e.fill()}},Ug=12,Wg=1,Gg=class extends am{zones=[];style={...t.DEFAULT_TRADE_ZONE_STYLE};requestRender=null;dataGetter=null;revealUntil=null;revealFrom=-1/0;pricePrecision=null;setRequestRender(e){this.requestRender=e}setDataGetter(e){this.dataGetter=e}setPricePrecision(e){this.pricePrecision=e}setStyle(e){this.style={...this.style,...e},this.requestRender?.()}getStyle(){return{...this.style}}addZone(e){let t=e.id??`tc_zone_${Wg++}`,n={...e,id:t};return this.zones.push(n),this.emit(`added`,n),this.requestRender?.(),t}updateZone(e,t){let n=this.zones.findIndex(t=>t.id===e);n!==-1&&(this.zones[n]={...this.zones[n],...t},this.requestRender?.())}removeZone(e){this.zones=this.zones.filter(t=>t.id!==e),this.emit(`removed`,e),this.requestRender?.()}getZones(){return[...this.zones]}clearZones(){this.zones=[],this.emit(`cleared`,void 0),this.requestRender?.()}setZones(e){this.zones=[...e],this.requestRender?.()}setRevealUntil(e,t=-1/0){e===this.revealUntil&&t===this.revealFrom||(this.revealUntil=e,this.revealFrom=t,this.requestRender?.())}shownZones(){return[...zg(this.zones,this.revealUntil,this.revealFrom)]}render(e,t,n){let r=this.dataGetter?.(),i=zg(this.zones,this.revealUntil,this.revealFrom);if(!r||r.length===0||i.length===0)return;let{chartRect:a}=t,o=$s(this.style,n);e.save(),e.beginPath(),e.rect(a.x,a.y,a.width,a.height),e.clip();for(let a of i)this.renderZone(e,a,r,t,n,o);e.restore()}renderZone(n,r,i,a,o,s){let{chartRect:c}=a,l=e.k(r.entryTime,i),u=r.exitTime==null?i.length-1:e.k(r.exitTime,i),d=e.b(l,a),f=e.b(u,a),p=Math.max(c.x,Math.min(d,f)),m=Math.min(c.x+c.width,Math.max(d,f));if(m-p<1)return;let h=e.T(r.entryPrice,a),g=r.exitPrice==null?e.T(r.entryPrice,a):e.T(r.exitPrice,a),_=Math.min(h,g),v=Math.max(Math.max(h,g)-_,2),y=r.exitTime==null,b=r.pnl==null?r.direction===`long`?(r.exitPrice??r.entryPrice)>=r.entryPrice:(r.exitPrice??r.entryPrice)<=r.entryPrice:r.pnl>=0,x=y?s.activeColor??`#4c8dff`:b?s.profitColor??`#1fa874`:s.lossColor??`#e8505b`;n.fillStyle=x,n.globalAlpha=s.fillOpacity??.12,n.fillRect(p,_,m-p,v),n.globalAlpha=1;let S=s.borderWidth??1;if(n.strokeStyle=x,n.lineWidth=S,n.setLineDash([]),n.beginPath(),n.moveTo(p,Math.round(h)+.5),n.lineTo(m,Math.round(h)+.5),n.stroke(),!y&&r.exitPrice!=null&&(n.setLineDash([3,3]),n.beginPath(),n.moveTo(p,Math.round(g)+.5),n.lineTo(m,Math.round(g)+.5),n.stroke(),n.setLineDash([])),Jf(n,r.direction===`long`?t.UI_ICONS.trendingUp:t.UI_ICONS.trendingDown,p+4,h-3-Ug,Ug,x),n.font=`bold 10px ${o.font.family}`,n.fillStyle=x,n.textBaseline=`bottom`,n.textAlign=`left`,n.fillText((0,t.priceTagText)(r.entryPrice,a,this.pricePrecision??void 0),p+4+Ug+3,h-3),s.showPnl&&!y&&r.pnl!=null){let e=r.pnl>=0?`+`:``,t=r.pnlPercent==null?`${e}${r.pnl.toFixed(2)}`:`${e}${r.pnl.toFixed(2)} (${e}${r.pnlPercent.toFixed(2)}%)`;n.font=`bold 10px ${o.font.family}`,n.fillStyle=x,n.textBaseline=`top`,n.textAlign=`right`;let i=n.measureText(t).width+8,a=m-i-2,s=_+2;n.globalAlpha=.85,n.fillStyle=o.background,E(n,a,s,i,14,o),n.globalAlpha=1,n.fillStyle=x,n.fillText(t,m-4,s+1)}s.showLabel&&r.label&&(n.font=`9px ${o.font.family}`,n.fillStyle=x,n.globalAlpha=.8,n.textBaseline=`top`,n.textAlign=`left`,n.fillText(r.label,p+4,h+3),n.globalAlpha=1)}},Kg=class{active=!1;startBar=0;startPrice=0;endBar=0;endPrice=0;startTime=null;endTime=null;isActive(){return this.active}begin(t,n,r){let i=Math.round(e.A(t.x,n)),a=e.M(t.y,n);this.startBar=i,this.startPrice=a,this.endBar=i,this.endPrice=a,this.startTime=qg(i,r),this.endTime=this.startTime,this.active=!0}update(t,n,r){if(!this.active)return;let i=Math.round(e.A(t.x,n));this.endBar=i,this.endPrice=e.M(t.y,n),this.endTime=qg(i,r)}end(){this.active=!1}render(t,n,r){if(!this.active)return;let i=e.b(this.startBar,n),a=e.b(this.endBar,n),o=e.T(this.startPrice,n),s=e.T(this.endPrice,n),c=Math.min(i,a),l=Math.max(i,a),u=Math.min(o,s),d=Math.max(o,s),f=l-c,p=d-u,m=this.endPrice>=this.startPrice?r.candleUp:r.candleDown,h=$g(m,.14);t.save();let{chartRect:g}=n;t.beginPath(),t.rect(g.x,g.y,g.width,g.height),t.clip(),t.fillStyle=h,t.fillRect(c,u,f,p),t.strokeStyle=m,t.lineWidth=1,t.setLineDash([4,3]),t.strokeRect(c+.5,u+.5,f,p),t.setLineDash([]),t.strokeStyle=m,t.lineWidth=1.5,t.beginPath(),t.moveTo(i,o),t.lineTo(a,s),t.stroke(),Xg(t,i,o,m),Xg(t,a,s,m),t.restore();let _=Math.abs(this.endBar-this.startBar),v=this.endPrice-this.startPrice,y=this.startPrice===0?0:v/this.startPrice*100,b=this.startTime!==null&&this.endTime!==null?Yg(Math.abs(this.endTime-this.startTime)):null,x=[],S=v>0?`+`:v<0?`−`:``,C=Math.abs(v);x.push(`${S}${n.formatPrice?.(C)??Jg(C)} (${S}${Math.abs(y).toFixed(2)}%)`),x.push(`${_} bars${b?` · `+b:``}`),t.save(),Zg(t,a,s,x,m,r),t.restore()}};function qg(e,n){return e<0||e>=n.length?null:n[e].time*(0,t.barTimeUnit)(n)}function Jg(e){return e>=1e3?e.toFixed(2):e>=1?e.toFixed(4):e.toPrecision(4)}function Yg(e){let t=e/1e3;if(t<60)return`${t.toFixed(0)}s`;let n=t/60;if(n<60)return`${n.toFixed(1)}m`;let r=n/60;if(r<24)return`${r.toFixed(1)}h`;let i=r/24;if(i<30)return`${i.toFixed(1)}d`;let a=i/30;return a<12?`${a.toFixed(1)}mo`:`${(i/365).toFixed(1)}y`}function Xg(e,t,n,r){e.fillStyle=r,e.beginPath(),e.arc(t,n,3.5,0,Math.PI*2),e.fill(),e.fillStyle=`#fff`,e.beginPath(),e.arc(t,n,1.5,0,Math.PI*2),e.fill()}function Zg(e,t,n,r,i,a){e.font=`600 11px ${a.font.family}`;let o=0;for(let t of r){let n=e.measureText(t).width;n>o&&(o=n)}let s=Math.ceil(o)+16,c=r.length*14+12,l=t+8,u=n+8,d=e.canvas.clientWidth||e.canvas.width;l+s>d-4&&(l=t-s-8),l<4&&(l=4),e.fillStyle=a.background,e.globalAlpha=.96,Qg(e,l,u,s,c,6),e.fill(),e.globalAlpha=1,e.strokeStyle=i,e.lineWidth=1,Qg(e,l+.5,u+.5,s-1,c-1,6),e.stroke(),e.fillStyle=a.text,e.textBaseline=`top`,e.textAlign=`left`;for(let t=0;t<r.length;t++)e.fillStyle=t===0?i:a.textSecondary,e.fillText(r[t],l+8,u+6+t*14)}function Qg(e,t,n,r,i,a){e.beginPath(),e.moveTo(t+a,n),e.arcTo(t+r,n,t+r,n+i,a),e.arcTo(t+r,n+i,t,n+i,a),e.arcTo(t,n+i,t,n,a),e.arcTo(t,n,t+r,n,a),e.closePath()}function $g(e,t){if(e.startsWith(`#`)){let n=0,r=0,i=0;return e.length===4?(n=parseInt(e[1]+e[1],16),r=parseInt(e[2]+e[2],16),i=parseInt(e[3]+e[3],16)):e.length>=7&&(n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16)),`rgba(${n},${r},${i},${t})`}if(e.startsWith(`rgb`)){let n=e.match(/[\d.]+/g);if(n&&n.length>=3)return`rgba(${n[0]},${n[1]},${n[2]},${t})`}return e}var e_=6,t_=class{start=null;current=null;isActive(){return this.start!==null}begin(e){this.start=e,this.current=e}update(e){this.start&&(this.current=e)}end(){let e=this.start,t=this.current;if(this.cancel(),!e||!t)return null;let n=Math.min(e.x,t.x),r=Math.max(e.x,t.x),i=Math.min(e.y,t.y),a=Math.max(e.y,t.y);return{x0:n,y0:i,x1:r,y1:a,isClick:r-n<6&&a-i<6}}cancel(){this.start=null,this.current=null}render(e,t,n){if(!this.start||!this.current)return;let{chartRect:r}=t,i=e=>Math.max(r.x,Math.min(r.x+r.width,e)),a=e=>Math.max(r.y,Math.min(r.y+r.height,e)),o=i(Math.min(this.start.x,this.current.x)),s=i(Math.max(this.start.x,this.current.x)),c=a(Math.min(this.start.y,this.current.y)),l=a(Math.max(this.start.y,this.current.y));e.save(),e.fillStyle=n.crosshair,e.globalAlpha=.1,e.fillRect(o,c,s-o,l-c),e.globalAlpha=.8,e.strokeStyle=n.crosshair,e.lineWidth=1,e.setLineDash([4,3]),e.strokeRect(Math.round(o)+.5,Math.round(c)+.5,Math.round(s-o),Math.round(l-c)),e.restore()}},n_={linear:e=>e,easeOutCubic:e=>1-(1-e)**3,easeOutQuart:e=>1-(1-e)**4,easeInOutCubic:e=>e<.5?4*e*e*e:1-(-2*e+2)**3/2,easeOutExpo:e=>e===1?1:1-2**(-10*e),easeOutElastic:e=>e===0||e===1?e:2**(-10*e)*Math.sin((e*10-.75)*(2*Math.PI/3))+1,spring:e=>1-Math.E**(-6*e)*Math.cos(8*e)},r_=class{animations=new Map;frameId=0;running=!1;animate(e,t){this.animations.set(e,{startTime:-1,duration:t.duration,easing:t.easing??n_.easeOutCubic,onUpdate:t.onUpdate,onComplete:t.onComplete}),this.running||(this.running=!0,this.tick())}cancel(e){this.animations.delete(e),this.animations.size===0&&this.stop()}cancelAll(){this.animations.clear(),this.stop()}isAnimating(e){return e?this.animations.has(e):this.animations.size>0}tick(){this.frameId=requestAnimationFrame(e=>{let t=[];for(let[n,r]of this.animations){r.startTime<0&&(r.startTime=e);let i=e-r.startTime,a=Math.min(1,i/r.duration),o=r.easing(a);r.onUpdate(o),a>=1&&(r.onComplete?.(),t.push(n))}for(let e of t)this.animations.delete(e);this.animations.size>0?this.tick():this.running=!1})}stop(){this.frameId&&=(cancelAnimationFrame(this.frameId),0),this.running=!1}dispose(){this.cancelAll()}};function i_(e){return!e||e===`dark`?t.DARK_THEME:e===`light`?t.LIGHT_THEME:e}var a_=class{canvas;ctx;container;theme;width=0;height=0;dpr=1;frameId=null;resizeObserver;constructor(e,t){this.container=e,this.theme=i_(t),this.canvas=document.createElement(`canvas`),this.canvas.style.width=`100%`,this.canvas.style.height=`100%`,this.canvas.style.display=`block`,this.canvas.setAttribute(`role`,`img`),e.appendChild(this.canvas),this.ctx=this.canvas.getContext(`2d`),this.dpr=o(),this.updateSize(),this.resizeObserver=new ResizeObserver(()=>{this.updateSize(),this.requestRender()}),this.resizeObserver.observe(e)}updateSize(){this.dpr=o();let e=this.container.getBoundingClientRect();this.width=e.width||this.container.clientWidth,this.height=e.height||this.container.clientHeight,this.canvas.width=Math.max(1,Math.floor(this.width*this.dpr)),this.canvas.height=Math.max(1,Math.floor(this.height*this.dpr))}requestRender(){this.frameId===null&&(this.frameId=requestAnimationFrame(()=>{this.frameId=null,(this.width===0||this.height===0)&&this.updateSize(),!(this.width===0||this.height===0)&&(this.ctx.save(),this.ctx.scale(this.dpr,this.dpr),this.ctx.clearRect(0,0,this.width,this.height),this.renderChart(this.ctx,this.width,this.height,this.theme),this.ctx.restore())}))}setLabel(e){this.canvas.setAttribute(`aria-label`,e)}setTheme(e){this.theme=i_(e),this.requestRender()}destroy(){this.frameId!==null&&cancelAnimationFrame(this.frameId),this.resizeObserver.disconnect(),this.canvas.width=0,this.canvas.height=0,this.canvas.remove()}},o_=class{pos=null;canvas;onUpdate;handleMove;handleLeave;constructor(e,t){this.canvas=e,this.onUpdate=t,this.handleMove=t=>{let n=e.getBoundingClientRect();this.pos={x:t.clientX-n.left,y:t.clientY-n.top},this.onUpdate()},this.handleLeave=()=>{this.pos=null,this.onUpdate()},e.addEventListener(`pointermove`,this.handleMove),e.addEventListener(`pointerleave`,this.handleLeave)}getPosition(){return this.pos}isActive(){return this.pos!==null}drawCrosshair(e,t,n,r){this.pos&&(e.save(),e.strokeStyle=r,e.lineWidth=.5,e.setLineDash([4,4]),e.beginPath(),e.moveTo(this.pos.x,0),e.lineTo(this.pos.x,n),e.stroke(),e.beginPath(),e.moveTo(0,this.pos.y),e.lineTo(t,this.pos.y),e.stroke(),e.restore())}destroy(){this.canvas.removeEventListener(`pointermove`,this.handleMove),this.canvas.removeEventListener(`pointerleave`,this.handleLeave)}};function s_(e,t,n,r,i){let{data:a,mode:o=`area`,lineWidth:s=1.5,showLastPoint:c=!1,showMinMax:l=!1}=r;if(a.length<2||t<=0||n<=0)return;let u=r.color??i.lineColor,d=r.fillColor??u,f=t-4,p=n-4,m=1/0,h=-1/0,g=0,_=0;for(let e=0;e<a.length;e++)a[e]<m&&(m=a[e],g=e),a[e]>h&&(h=a[e],_=e);let v=h-m||1,y=e=>2+e/(a.length-1)*f,b=e=>2+p-(e-m)/v*p;if(o===`area`){let t=e.createLinearGradient(0,2,0,n-2);t.addColorStop(0,d+(d.startsWith(`#`)?`40`:``)),t.addColorStop(1,`transparent`),e.beginPath(),e.moveTo(y(0),b(a[0]));for(let t=1;t<a.length;t++)e.lineTo(y(t),b(a[t]));e.lineTo(y(a.length-1),n-2),e.lineTo(y(0),n-2),e.closePath(),e.fillStyle=t,e.fill()}e.beginPath(),e.moveTo(y(0),b(a[0]));for(let t=1;t<a.length;t++)e.lineTo(y(t),b(a[t]));if(e.strokeStyle=u,e.lineWidth=s,e.lineJoin=`round`,e.stroke(),c){let t=r.lastPointColor??u,n=y(a.length-1),i=b(a[a.length-1]);e.beginPath(),e.arc(n,i,3,0,Math.PI*2),e.fillStyle=t,e.fill()}if(l){let t=r.minPointColor??i.candleDown,n=r.maxPointColor??i.candleUp;e.beginPath(),e.arc(y(g),b(m),2.5,0,Math.PI*2),e.fillStyle=t,e.fill(),e.beginPath(),e.arc(y(_),b(h),2.5,0,Math.PI*2),e.fillStyle=n,e.fill()}}var c_=50,l_=60,u_=20,d_=.2;function f_(e){let t=[...e].sort((e,t)=>t.price-e.price),n=[],r=0;for(let e of t)r+=e.volume,n.push({price:e.price,cumulativeVolume:r});return n}function p_(e){let t=[...e].sort((e,t)=>e.price-t.price),n=[],r=0;for(let e of t)r+=e.volume,n.push({price:e.price,cumulativeVolume:r});return n}function m_(e,t){return{left:c_,right:e-l_,top:u_,bottom:t-u_,plotWidth:e-c_-l_,plotHeight:t-u_*2}}function h_(e,t,n,r){e.fillStyle=r,e.fillRect(0,0,t,n)}function g_(e,n,r,i,a,o,s,c){let{left:l,right:u,top:d,bottom:f,plotWidth:p,plotHeight:m}=n;e.save(),e.strokeStyle=o.grid,e.lineWidth=.5,e.fillStyle=o.axisLabel,e.font=`${o.font.sizeSmall}px ${o.font.family}`;let h=(0,t.computeTickStep)(0,a,5);for(let t=0;t<=a;t+=h){let n=f-t/a*m;e.beginPath(),e.moveTo(l,n),e.lineTo(u,n),e.stroke(),e.textAlign=`right`,e.textBaseline=`middle`,e.fillText(c(t),l-4,n)}let g=i-r,_=(0,t.computeTickStep)(r,i,6),v=Math.ceil(r/_)*_;for(let t=v;t<=i;t+=_){let n=l+(t-r)/g*p;e.beginPath(),e.moveTo(n,d),e.lineTo(n,f),e.stroke(),e.textAlign=`center`,e.textBaseline=`top`,e.fillText(s(t),n,f+4)}e.restore()}function __(e,t,n,r,i,a,o,s,c){if(t.length===0)return;let{left:l,bottom:u,plotWidth:d,plotHeight:f}=n,p=e=>l+(e-r)/i*d,m=e=>u-e/a*f;if(e.beginPath(),c===`bid`){e.moveTo(p(t[0].price),u);for(let n=0;n<t.length;n++){let r=p(t[n].price),i=m(t[n].cumulativeVolume);e.lineTo(r,i),n<t.length-1&&e.lineTo(p(t[n+1].price),i)}e.lineTo(p(t[t.length-1].price),u)}else{e.moveTo(p(t[0].price),u);for(let n=0;n<t.length;n++){let r=p(t[n].price),i=m(t[n].cumulativeVolume);e.lineTo(r,i),n<t.length-1&&e.lineTo(p(t[n+1].price),i)}e.lineTo(p(t[t.length-1].price),u)}if(e.closePath(),e.fillStyle=o,e.fill(),e.beginPath(),c===`bid`){e.moveTo(p(t[0].price),m(t[0].cumulativeVolume));for(let n=0;n<t.length;n++){let r=p(t[n].price),i=m(t[n].cumulativeVolume);n>0&&e.lineTo(r,m(t[n-1].cumulativeVolume)),e.lineTo(r,i)}}else{e.moveTo(p(t[0].price),m(t[0].cumulativeVolume));for(let n=1;n<t.length;n++){let r=m(t[n-1].cumulativeVolume),i=p(t[n].price),a=m(t[n].cumulativeVolume);e.lineTo(i,r),e.lineTo(i,a)}}e.strokeStyle=s,e.lineWidth=1.5,e.stroke()}function v_(e,t,n,r,i,a,o,s,c){let{left:l,top:u,bottom:d,plotWidth:f}=r,p=l+(t-i)/a*f;if(e.save(),e.strokeStyle=o.textSecondary,e.lineWidth=1,e.setLineDash([4,4]),e.beginPath(),e.moveTo(p,u),e.lineTo(p,d),e.stroke(),e.restore(),s){let t=`Spread: ${c(n)}`;e.save(),e.font=`${o.font.sizeSmall}px ${o.font.family}`,e.fillStyle=o.textSecondary,e.textAlign=`center`,e.textBaseline=`bottom`,e.fillText(t,p,u-2),e.restore()}}function y_(e,t,n,r,i,a,o,s,c,l,u){let{left:d,top:f,bottom:p,plotWidth:m,plotHeight:h}=i,g=t.x;if(g<d||g>i.right)return;let _=a+(g-d)/m*o,v=0,y=``;if(n.length>0&&_<=n[0].price){y=`Bid`;for(let e of n)if(_<=e.price)v=e.cumulativeVolume;else break}if(r.length>0&&_>=r[0].price){y=`Ask`;for(let e of r)if(_>=e.price)v=e.cumulativeVolume;else break}if(e.save(),e.strokeStyle=c.crosshair,e.lineWidth=.5,e.setLineDash([4,4]),e.beginPath(),e.moveTo(g,f),e.lineTo(g,p),e.stroke(),v>0){let t=p-v/s*h;e.beginPath(),e.moveTo(d,t),e.lineTo(i.right,t),e.stroke()}e.restore();let b=[`Price: ${l(_)}`,y?`${y} Vol: ${u(v)}`:``].filter(Boolean);e.save(),e.font=`${c.font.sizeSmall}px ${c.font.family}`;let x=Math.max(...b.map(t=>e.measureText(t).width))+16,S=b.length*(c.font.sizeSmall+4)+12,C=g+10,w=t.y-S/2;C+x>i.right&&(C=g-x-10),w<f&&(w=f),w+S>p&&(w=p-S),e.fillStyle=c.axisLabelBackground,e.globalAlpha=.9,e.fillRect(C,w,x,S),e.globalAlpha=1,e.fillStyle=c.text,e.textBaseline=`top`,e.textAlign=`left`;for(let t=0;t<b.length;t++)e.fillText(b[t],C+8,w+6+t*(c.font.sizeSmall+4));e.restore()}function b_(e){return e.toFixed(2)}function x_(e){return e>=1e6?(e/1e6).toFixed(2)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:e.toFixed(0)}function S_(e,t,n,r,i,a){let{data:o}=r;if(o.bids.length===0&&o.asks.length===0||t<=0||n<=0)return;let s=r.bidColor??i.candleUp,c=r.askColor??i.candleDown,l=r.bidFillColor??s+`40`,u=r.askFillColor??c+`40`,d=r.midPriceLine!==!1,f=r.spreadLabel!==!1,p=r.priceFormat??b_,m=r.volumeFormat??x_,h=f_(o.bids),g=p_(o.asks),_=h.length>0?h[0].price:0,v=g.length>0?g[0].price:0,y=h.length>0&&g.length>0?(_+v)/2:_||v,b=g.length>0&&h.length>0?v-_:0,x=h.length>0?h[h.length-1].price:y,S=g.length>0?g[g.length-1].price:y,C=Math.max(y-x,S-y)*(1+d_),w=y-C,T=y+C,E=T-w,D=h.length>0?h[h.length-1].cumulativeVolume:0,O=g.length>0?g[g.length-1].cumulativeVolume:0,k=Math.max(D,O)||1,A=m_(t,n);h_(e,t,n,i.background),g_(e,A,w,T,k,i,p,m),__(e,h,A,w,E,k,l,s,`bid`),__(e,g,A,w,E,k,u,c,`ask`),d&&v_(e,y,b,A,w,E,i,f,p),a&&y_(e,a,h,g,A,w,E,k,i,p,m)}var C_=70,w_=30,T_=20,E_=20,D_=.05;function O_(e,t){return{left:C_,right:e-T_,top:E_,bottom:t-w_,plotWidth:e-C_-T_,plotHeight:t-E_-w_}}function k_(e,t){let n=1/0,r=-1/0;for(let t of e)t.value<n&&(n=t.value),t.value>r&&(r=t.value);if(t)for(let e of t)e.value<n&&(n=e.value),e.value>r&&(r=e.value);let i=(r-n)*D_;return{valMin:n-i,valMax:r+i}}function A_(e){let t=[],n=-1/0;for(let r of e)r.value>n&&(n=r.value),t.push(n);return t}function j_(e){let t=864e5;if(365.25*t,e<7*t){let e=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`});return t=>e.format(new Date(t))}if(e<315576e5){let e=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`});return t=>e.format(new Date(t))}let n=new Intl.DateTimeFormat(void 0,{month:`short`,year:`numeric`});return e=>n.format(new Date(e))}function M_(e){return Math.abs(e)>=1e6?(e/1e6).toFixed(2)+`M`:Math.abs(e)>=1e3?(e/1e3).toFixed(1)+`K`:e.toFixed(2)}function N_(e,t,n,r){e.fillStyle=r,e.fillRect(0,0,t,n)}function P_(e,n,r,i,a,o,s,c,l){let{left:u,right:d,top:f,bottom:p,plotWidth:m,plotHeight:h}=n;e.save(),e.strokeStyle=s.grid,e.lineWidth=.5,e.fillStyle=s.axisLabel,e.font=`${s.font.sizeSmall}px ${s.font.family}`;let g=(0,t.computeTickStep)(r,i,6),_=Math.ceil(r/g)*g;for(let t=_;t<=i;t+=g){let n=p-(t-r)/(i-r)*h;e.beginPath(),e.moveTo(u,n),e.lineTo(d,n),e.stroke(),e.textAlign=`right`,e.textBaseline=`middle`,e.fillText(c(t),u-6,n)}let v=o-a,y=(0,t.computeTickStep)(a,o,6),b=Math.ceil(a/y)*y;for(let t=b;t<=o;t+=y){let n=u+(t-a)/v*m;e.beginPath(),e.moveTo(n,f),e.lineTo(n,p),e.stroke(),e.textAlign=`center`,e.textBaseline=`top`,e.fillText(l(t),n,p+4)}e.restore()}function F_(e,t,n,r,i,a,o,s,c){if(t.length<2)return;let{left:l,bottom:u,plotWidth:d,plotHeight:f}=n,p=e=>l+(e-r)/i*d,m=e=>u-(e-a)/o*f;e.save(),e.beginPath(),e.moveTo(p(t[0].time),m(t[0].value));for(let n=1;n<t.length;n++)e.lineTo(p(t[n].time),m(t[n].value));e.strokeStyle=s,e.lineWidth=c,e.lineJoin=`round`,e.stroke(),e.restore()}function I_(e,t,n,r,i,a,o,s){if(t.length<2)return;let{left:c,bottom:l,plotWidth:u,plotHeight:d}=n,f=e=>c+(e-r)/i*u,p=e=>l-(e-a)/o*d,m=e.createLinearGradient(0,n.top,0,l);m.addColorStop(0,s+`40`),m.addColorStop(1,`transparent`),e.save(),e.beginPath(),e.moveTo(f(t[0].time),p(t[0].value));for(let n=1;n<t.length;n++)e.lineTo(f(t[n].time),p(t[n].value));e.lineTo(f(t[t.length-1].time),l),e.lineTo(f(t[0].time),l),e.closePath(),e.fillStyle=m,e.fill(),e.restore()}function L_(e,t,n,r,i,a,o,s,c){if(t.length<2)return;let{left:l,bottom:u,plotWidth:d,plotHeight:f}=r,p=e=>l+(e-i)/a*d,m=e=>u-(e-o)/s*f;e.save(),e.fillStyle=c,e.beginPath(),e.moveTo(p(t[0].time),m(n[0]));for(let r=1;r<t.length;r++)e.lineTo(p(t[r].time),m(n[r]));for(let n=t.length-1;n>=0;n--)e.lineTo(p(t[n].time),m(t[n].value));e.closePath(),e.fill(),e.restore()}function R_(e,t,n,r,i,a,o,s,c,l){if(t.length===0)return;let{left:u,bottom:d,plotWidth:f,plotHeight:p}=n,m=t[t.length-1],h=u+(m.time-r)/i*f,g=d-(m.value-a)/o*p;e.save(),e.font=`${l.font.sizeSmall}px ${l.font.family}`,e.fillStyle=c,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(s,h+4,g),e.restore()}function z_(e,t,n,r,i,a,o,s,c,l,u,d){let{left:f,top:p,bottom:m,plotWidth:h,plotHeight:g}=i,_=t.x;if(_<f||_>i.right)return;e.save(),e.strokeStyle=l.crosshair,e.lineWidth=.5,e.setLineDash([4,4]),e.beginPath(),e.moveTo(_,p),e.lineTo(_,m),e.stroke(),e.restore();let v=a+(_-f)/h*o,y=0,b=1/0;for(let e=0;e<n.length;e++){let t=Math.abs(n[e].time-v);t<b&&(b=t,y=e)}let x=n[y],S=[u(x.time),`Value: ${d(x.value)}`];r&&r.length>y&&S.push(`Benchmark: ${d(r[y].value)}`);let C=f+(x.time-a)/o*h,w=m-(x.value-s)/c*g;e.beginPath(),e.arc(C,w,3,0,Math.PI*2),e.fillStyle=l.lineColor,e.fill(),e.save(),e.font=`${l.font.sizeSmall}px ${l.font.family}`;let T=Math.max(...S.map(t=>e.measureText(t).width))+16,E=S.length*(l.font.sizeSmall+4)+12,D=_+10,O=t.y-E/2;D+T>i.right&&(D=_-T-10),O<p&&(O=p),O+E>m&&(O=m-E),e.fillStyle=l.axisLabelBackground,e.globalAlpha=.9,e.fillRect(D,O,T,E),e.globalAlpha=1,e.fillStyle=l.text,e.textBaseline=`top`,e.textAlign=`left`;for(let t=0;t<S.length;t++)e.fillText(S[t],D+8,O+6+t*(l.font.sizeSmall+4));e.restore()}function B_(e,t,n,r,i,a){let{data:o}=r;if(o.length<2||t<=0||n<=0)return;let s=r.lineColor??i.lineColor,c=r.lineWidth??1.5,l=r.drawdown===!0,u=r.drawdownColor??i.candleDown+`30`,d=r.fillArea===!0,f=r.benchmark,p=r.benchmarkColor??i.textSecondary,m=r.benchmarkLabel??`Benchmark`,h=r.valueFormat??M_,{valMin:g,valMax:_}=k_(o,f),v=_-g||1,y=o[0].time,b=o[o.length-1].time,x=b-y||1,S=r.timeFormat??j_(x),C=O_(t,n);N_(e,t,n,i.background),P_(e,C,g,_,y,b,i,h,S),l&&L_(e,o,A_(o),C,y,x,g,v,u),d&&I_(e,o,C,y,x,g,v,s),F_(e,o,C,y,x,g,v,s,c),f&&f.length>=2&&(F_(e,f,C,y,x,g,v,p,1),R_(e,f,C,y,x,g,v,m,p,i)),a&&z_(e,a,o,f,C,y,x,g,v,i,S,h)}function V_(e,t,n){if(e.length===0)return[];let r=e.length,i=Math.ceil(Math.sqrt(r)),a=Math.ceil(r/i),o=t.width/i,s=t.height/a,c=[];for(let a=0;a<r;a++){let r=a%i,l=Math.floor(a/i);c.push({id:e[a].id,rect:{x:t.x+r*o+n,y:t.y+l*s+n,width:Math.max(0,o-n*2),height:Math.max(0,s-n*2)}})}return c}function H_(e,t){let n=e.reduce((e,t)=>e+t,0);if(n===0||t===0)return 1/0;let r=0;for(let i of e){let e=n/t,a=i/e,o=e>a?e/a:a/e;o>r&&(r=o)}return r}function U_(e,t,n,r,i,a){let o=r?n.height:n.width,s=e.reduce((e,t)=>e+t,0),c=o>0?s/o:0,l=0;for(let o=0;o<e.length;o++){let s=c>0?e[o]/c:0,u;u=r?{x:n.x+i,y:n.y+l+i,width:Math.max(0,c-i*2),height:Math.max(0,s-i*2)}:{x:n.x+l+i,y:n.y+i,width:Math.max(0,s-i*2),height:Math.max(0,c-i*2)},a.push({id:t[o],rect:u}),l+=s}}function W_(e,t,n,r,i){if(e.length===0)return;let a=n.width>=n.height,o=a?n.height:n.width;if(e.length===1){U_(e,t,n,a,r,i);return}let s=[],c=[],l=0;for(;l<e.length;){let u=[...s,e[l]];if(s.length===0||H_(u,o)<=H_(s,o))s.push(e[l]),c.push(t[l]),l++;else{U_(s,c,n,a,r,i);let u=s.reduce((e,t)=>e+t,0),d=o>0?u/o:0;n=a?{x:n.x+d,y:n.y,width:n.width-d,height:n.height}:{x:n.x,y:n.y+d,width:n.width,height:n.height-d},W_(e.slice(l),t.slice(l),n,r,i);return}}s.length>0&&U_(s,c,n,a,r,i)}function G_(e,t,n){if(e.length===0)return[];let r=[...e].sort((e,t)=>t.weight-e.weight),i=r.reduce((e,t)=>e+Math.max(0,t.weight),0);if(i===0)return[];let a=t.width*t.height,o=r.map(e=>Math.max(0,e.weight)/i*a),s=r.map(e=>e.id),c=[];return W_(o,s,{...t},n,c),c}var K_=2,q_=18;function J_(e,t,n,r=18){let i=new Map;for(let t of e){if(!(t.weight>0))continue;let e=t.group??``,n=i.get(e);n?n.push(t):i.set(e,[t])}let a=[...i.keys()],o=G_(a.map((e,t)=>({id:String(t),weight:i.get(e).reduce((e,t)=>e+t.weight,0)})),t,0),s=[],c=[];for(let e of o){let t=a[Number(e.id)],o=i.get(t),l=o.reduce((e,t)=>e+t.weight,0),u=o.reduce((e,t)=>e+(Number.isFinite(t.value)?t.value*t.weight:0),0),d=e.rect,f=t!==``&&d.height>=r*2.5&&d.width>=40?r:0,p={x:d.x+K_/2,y:d.y+K_/2+f,width:Math.max(0,d.width-K_),height:Math.max(0,d.height-K_-f)};s.push({name:t,rect:{...d},header:f,value:l>0?u/l:0,count:o.length}),c.push(...G_(o,p,n))}return{groups:s,cells:c}}var Y_=10,X_=6,Z_=16,Q_=18,$_=8,ev=16,tv=15,nv={min:0,max:1,step:.2,ticks:[0,.2,.4,.6,.8,1]};function rv(e){for(let t=0;t<=tv;t++){let n=e*10**t,r=Math.round(n);if(r!==0&&Math.abs(r-n)<1e-9*Math.abs(n))return t}return tv}var iv=(e,t)=>{let n=Number(e.toFixed(t));return n===0?0:n};function av(e,t,n=5){let r=Math.min(e,t),i=Math.max(e,t);if((!Number.isFinite(r)||!Number.isFinite(i))&&(r=0,i=1),r===i){let e=Math.abs(r)||1;r-=e/2,i+=e/2}let a=(i/2-r/2)/Math.max(1,n)*2;if(!Number.isFinite(a)||a<=0)return nv;let o=10**Math.floor(Math.log10(a)),s=a/o,c=(s<=1?1:s<=2?2:s<=2.5?2.5:s<=5?5:10)*o;if(!Number.isFinite(c)||c<=0)return nv;let l=rv(c),u=Math.floor(r/c+1e-9),d=Math.ceil(i/c-1e-9),f=[];for(let e=u;e<=d;e++)f.push(iv(e*c,l));return f.length<2||!f.every(Number.isFinite)?nv:{min:f[0],max:f[f.length-1],step:iv(c,l),ticks:f}}function Z(e,t,n,r,i=!1){let a=e.max===e.min?.5:(t-e.min)/(e.max-e.min);return i?n+r*(1-a):n+r*a}var ov=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),sv=new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1});function cv(e){return Math.abs(e)>=1e4?sv.format(e):ov.format(e)}function Q(e){let t=rv(e.step),n=new Intl.NumberFormat(void 0,{minimumFractionDigits:t,maximumFractionDigits:t});if(Math.max(Math.abs(e.min),Math.abs(e.max))>=1e4&&e.step%1e3==0){let t=new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:2}),n=e.ticks.map(e=>t.format(e));if(new Set(n).size===n.length)return e=>t.format(e)}return e=>n.format(e)}function lv(e,n){return n??t.TC_SERIES_COLORS[e%t.TC_SERIES_COLORS.length]}function $(e,t,n=``){return`${n?`${n} `:``}${t}px ${e.font.family}`}function uv(e,t){return(n,r=11)=>(e.font=$(t,r),e.measureText(n).width)}function dv(e,t,n,r=!1){let i=[],a=0,o=0;for(let s of e){let e=Y_+X_+n(s.label,11);a>0&&(r||a+e>t)&&(o++,a=0),i.push({...s,x:a,y:o*Q_}),a+=e+Z_}let s=e.length===0?0:o+1;return{items:i,rows:s,height:s*Q_}}function fv(e,t,n,r,i){e.save(),e.font=$(i,11),e.textBaseline=`middle`,e.textAlign=`left`;for(let a of t.items){let t=r+a.y+Q_/2;e.fillStyle=a.color,e.fillRect(n+a.x,t-Y_/2,Y_,Y_),e.fillStyle=i.textSecondary,e.fillText(a.label,n+a.x+Y_+X_,t)}e.restore()}function pv(e,n,r,i,a){if(n.length===0)return;e.save();let o=n.some(e=>e.color)?Y_+X_:0,s=0;for(let t of n)e.font=$(a,11,t.bold?`600`:``),s=Math.max(s,e.measureText(t.text).width);let c=s+o+$_*2,l=n.length*ev+$_*2-4,u=r.x+14,d=r.y+14;u+c>i.x+i.width&&(u=r.x-14-c),d+l>i.y+i.height&&(d=r.y-14-l),u=Math.max(i.x,u),d=Math.max(i.y,d),e.fillStyle=(0,t.withAlpha)(a.axisLabelBackground,.94),e.strokeStyle=a.grid,e.lineWidth=1,e.beginPath(),typeof e.roundRect==`function`?e.roundRect(u,d,c,l,6):e.rect(u,d,c,l),e.fill(),e.stroke(),e.textBaseline=`middle`,e.textAlign=`left`,n.forEach((t,n)=>{let r=d+$_+n*ev+ev/2-2;t.color&&(e.fillStyle=t.color,e.fillRect(u+$_,r-4,8,8)),e.font=$(a,11,t.bold?`600`:``),e.fillStyle=t.bold?a.text:a.textSecondary,e.fillText(t.text,u+$_+o,r)}),e.restore()}function mv(e,t,n,r,i,a){e.save(),e.font=$(i,11),e.fillStyle=i.axisLabel,e.strokeStyle=i.grid,e.lineWidth=1;for(let i of n.ticks)if(r===`vertical`){let r=Math.round(Z(n,i,t.y,t.height,!0))+.5;e.beginPath(),e.moveTo(t.x,r),e.lineTo(t.x+t.width,r),e.stroke(),e.textAlign=`right`,e.textBaseline=`middle`,e.fillText(a(i),t.x-6,r)}else{let r=Math.round(Z(n,i,t.x,t.width))+.5;e.beginPath(),e.moveTo(r,t.y),e.lineTo(r,t.y+t.height),e.stroke(),e.textAlign=`center`,e.textBaseline=`top`,e.fillText(a(i),r,t.y+t.height+6)}e.restore()}function hv(e,t,n,r=11){if(n(e,r)<=t)return e;let i=e;for(;i.length>1&&n(`${i}…`,r)>t;)i=i.slice(0,-1);return i.length>1?`${i}…`:``}function gv(e){return(e>=0?`+`:``)+e.toFixed(2)+`%`}function _v(e){return e.label}function vv(e,n){let r=n.min??-5,i=n.max??5;if(e<=r)return n.negative;if(e>=i)return n.positive;if(e<0){let i=1-e/r;return(0,t.lerpColor)(n.negative,n.zero,i)}let a=e/i;return(0,t.lerpColor)(n.zero,n.positive,a)}function yv(e,t,n,r,i,a){let o=Math.min(a,r/2,i/2);e.beginPath(),e.moveTo(t+o,n),e.lineTo(t+r-o,n),e.arcTo(t+r,n,t+r,n+o,o),e.lineTo(t+r,n+i-o),e.arcTo(t+r,n+i,t+r-o,n+i,o),e.lineTo(t+o,n+i),e.arcTo(t,n+i,t,n+i-o,o),e.lineTo(t,n+o),e.arcTo(t,n,t+o,n,o),e.closePath()}function bv(e,t,n,r,i,a,o,s,c,l,u){if(i<40||a<30)return;let d=n+i/2,f=r+a/2;if(e.save(),e.shadowColor=`rgba(0,0,0,0.6)`,e.shadowBlur=2,e.fillStyle=`#FFFFFF`,e.textAlign=`center`,s){let n=l(t),r=Math.min(o.font.sizeMedium,i/n.length*1.5,a/4);e.font=`bold `+Math.max(8,r)+`px `+o.font.family,e.textBaseline=c?`bottom`:`middle`,e.fillText(n,d,c?f-1:f,i-8)}if(c){let n=u(t.value),r=Math.min(o.font.sizeSmall,i/n.length*1.5,a/4);e.font=Math.max(7,r)+`px `+o.font.family,e.textBaseline=s?`top`:`middle`,e.fillText(n,d,s?f+1:f,i-8)}e.restore()}function xv(e,t,n,r,i,a,o,s){let c=[o(t),s(t.value)];if(t.meta)for(let[e,n]of Object.entries(t.meta))c.push(e+`: `+String(n));e.save(),e.font=a.font.sizeSmall+`px `+a.font.family;let l=Math.max(...c.map(t=>e.measureText(t).width))+16,u=a.font.sizeSmall+4,d=c.length*u+12,f=n.x+14,p=n.y-d/2;f+l>r&&(f=n.x-l-14),p<0&&(p=0),p+d>i&&(p=i-d),e.fillStyle=a.axisLabelBackground,e.globalAlpha=.92,yv(e,f,p,l,d,4),e.fill(),e.globalAlpha=1,e.fillStyle=a.text,e.textBaseline=`top`,e.textAlign=`left`;for(let t=0;t<c.length;t++)e.fillText(c[t],f+8,p+6+t*u);e.restore()}function Sv(e,t,n,r,i,a,o,s,c=[]){if(r.length===0||i.length===0||t<=0||n<=0)return null;let l=a.colorScale,u={negative:l?.negative??`#e8505b`,zero:l?.zero??`#424242`,positive:l?.positive??`#1fa874`,min:l?.min,max:l?.max},d=a.cellRadius??4,f=a.showLabels!==!1,p=a.showValues!==!1,m=a.valueFormat??gv,h=a.labelFormat??_v,g=new Map;for(let e of r)g.set(e.id,e);let _=null,v=null;if(s)for(let e of i){let{x:t,y:n,width:r,height:i}=e.rect;if(s.x>=t&&s.x<=t+r&&s.y>=n&&s.y<=n+i){_=e.id;let t=g.get(e.id);t&&(v={cell:t,rect:e});break}}e.fillStyle=o.background,e.fillRect(0,0,t,n);for(let t of i){let n=g.get(t.id);if(!n)continue;let{x:r,y:i,width:a,height:s}=t.rect;if(a<=0||s<=0)continue;let c=vv(n.value,u);yv(e,r,i,a,s,d),e.fillStyle=c,e.fill(),bv(e,n,r,i,a,s,o,f,p,h,m),t.id===_&&(yv(e,r,i,a,s,d),e.strokeStyle=`#FFFFFF`,e.lineWidth=1.5,e.stroke())}let y=s&&!v?c.find(e=>e.header>0&&Cv(e,s)):void 0;return wv(e,c,o,m,y),v&&s?xv(e,v.cell,s,t,n,o,h,m):y&&s&&xv(e,{id:``,label:y.name,value:y.value},s,t,n,o,e=>e.label,m),v}function Cv(e,t){let n=e.rect;return t.x>=n.x&&t.x<=n.x+n.width&&t.y>=n.y&&t.y<=n.y+e.header}function wv(e,t,n,r,i){if(t.length===0)return;e.save(),e.textBaseline=`middle`;let a=n.font.sizeSmall,o=t=>e.measureText(t).width;for(let s of t){if(s.header<=0)continue;let{x:t,y:c,width:l}=s.rect,u=c+s.header/2+1;e.font=a+`px `+n.font.family;let d=r(s.value),f=o(d),p=l>=f*2+24;p&&(e.textAlign=`right`,e.fillStyle=s.value<0?n.candleDown:s.value>0?n.candleUp:n.textSecondary,e.fillText(d,t+l-5,u)),e.font=`600 `+a+`px `+n.font.family,e.textAlign=`left`,e.fillStyle=s===i?n.text:n.textSecondary;let m=l-10-(p?f+8:0),h=hv(s.name,m,e=>o(e),a);h&&e.fillText(h,t+5,u)}e.restore()}var Tv=60,Ev=12,Dv=24,Ov=40,kv=.7,Av=1;function jv(e){return e.type?e.type:e.value>0?`positive`:e.value<0?`negative`:`subtotal`}function Mv(e){let t=Math.abs(e);return t>=1e6?(e/1e6).toFixed(2)+`M`:t>=1e3?(e/1e3).toFixed(1)+`K`:e.toFixed(2)}function Nv(e,t){return{left:Tv,right:e-Ev,top:Dv,bottom:t-Ov,plotWidth:e-Tv-Ev,plotHeight:t-Dv-Ov}}function Pv(e,t,n,r,i){let a=Array(e.length),o=Array(e.length),s=t.plotWidth/e.length,c=s*n,l=(s-c)/2,{left:u,bottom:d,plotHeight:f}=t,p=0;for(let t=0;t<e.length;t++){let n=e[t],m=jv(n),h,g;m===`total`||m===`subtotal`?(h=0,g=n.value,p=n.value):(h=p,g=p+n.value,p=g);let _=Math.min(h,g),v=Math.max(h,g),y=d-(_-r)/i*f,b=d-(v-r)/i*f,x=Math.min(y,b),S=Math.max(Math.abs(b-y),Av),C=u+t*s,w=C+l;a[t]={label:n.label,value:n.value,start:h,end:g,type:m,rectX:w,rectY:x,rectW:c,rectH:S,slotX:C,slotW:s},o[t]=p}return{bars:a,cumulatives:o}}function Fv(e){if(e.length===0)return{valMin:0,valMax:1};let t=0,n=0,r=0;for(let i=0;i<e.length;i++){let a=e[i],o=jv(a),s,c;o===`total`||o===`subtotal`?(s=0,c=a.value,r=a.value):(s=r,c=r+a.value,r=c),s<t&&(t=s),c<t&&(t=c),s>n&&(n=s),c>n&&(n=c)}let i=(n-t||1)*.1;return{valMin:t-i,valMax:n+i}}function Iv(e,t,n,r){e.fillStyle=r,e.fillRect(0,0,t,n)}function Lv(e,n,r,i,a,o){let{left:s,right:c,top:l,bottom:u,plotHeight:d}=n,f=i-r||1;e.strokeStyle=a.grid,e.lineWidth=.5,e.fillStyle=a.axisLabel,e.font=`${a.font.sizeSmall}px ${a.font.family}`,e.textAlign=`right`,e.textBaseline=`middle`;let p=(0,t.computeTickStep)(r,i,5),m=Math.ceil(r/p)*p;e.beginPath();for(let t=m;t<=i;t+=p){let n=Math.round(u-(t-r)/f*d)+.5;n<l||n>u||(e.moveTo(s,n),e.lineTo(c,n))}e.stroke();for(let t=m;t<=i;t+=p){let n=u-(t-r)/f*d;n<l-1||n>u+1||e.fillText(o(t),s-6,n)}if(r<0&&i>0){let t=Math.round(u-(0-r)/f*d)+.5;e.strokeStyle=a.axisLine,e.lineWidth=1,e.beginPath(),e.moveTo(s,t),e.lineTo(c,t),e.stroke()}}function Rv(e,t,n){let r=[`positive`,`negative`,`total`,`subtotal`];for(let i=0;i<r.length;i++){let a=r[i],o=n[a],s=!1;e.beginPath();for(let n=0;n<t.length;n++){let r=t[n];if(r.type!==a)continue;let i=Math.round(r.rectX),o=Math.round(r.rectY),c=Math.round(r.rectW),l=Math.round(r.rectH);e.rect(i,o,c,l),s=!0}s&&(e.fillStyle=o,e.fill())}}function zv(e,t,n,r,i,a,o){if(o===`none`||t.length<2)return;let{bottom:s,plotHeight:c}=n;e.strokeStyle=a,e.lineWidth=1,o===`dashed`?e.setLineDash([4,4]):e.setLineDash([]),e.beginPath();for(let n=0;n<t.length-1;n++){let a=t[n],o=t[n+1],l=a.end,u=Math.round(s-(l-r)/i*c)+.5,d=Math.round(a.rectX+a.rectW),f=Math.round(o.rectX);f<=d||(e.moveTo(d,u),e.lineTo(f,u))}e.stroke(),e.setLineDash([])}function Bv(e,t,n,r,i,a){e.fillStyle=r.text,e.font=`${r.font.sizeSmall}px ${r.font.family}`,e.textAlign=`center`;for(let r=0;r<t.length;r++){let o=t[r],s;s=o.type===`total`||o.type===`subtotal`?i(o.value):a?`${o.value>=0?`+`:``}${i(o.value)}`:i(n[r]);let c=o.rectX+o.rectW/2;o.end<o.start?(e.textBaseline=`top`,e.fillText(s,c,o.rectY+o.rectH+4)):(e.textBaseline=`bottom`,e.fillText(s,c,o.rectY-4))}}function Vv(e,t,n,r,i){e.fillStyle=r.axisLabel,e.font=`${r.font.sizeSmall}px ${r.font.family}`,e.textAlign=`center`,e.textBaseline=`top`;let a=n.bottom+6,o=t.length>0?t[0].slotW-4:0,s=!1;for(let n=0;n<t.length;n++)if(e.measureText(i(t[n].label)).width>o){s=!0;break}if(!s){for(let n=0;n<t.length;n++){let r=t[n],o=r.slotX+r.slotW/2;e.fillText(i(r.label),o,a)}return}e.save(),e.textAlign=`right`,e.textBaseline=`middle`;for(let n=0;n<t.length;n++){let r=t[n],o=r.slotX+r.slotW/2;e.setTransform(1,0,0,1,o,a+4),e.rotate(-Math.PI/4),e.fillText(i(r.label),0,0)}e.setTransform(1,0,0,1,0,0),e.restore()}function Hv(e,t,n){if(t<n.left||t>n.right)return null;for(let n=0;n<e.length;n++){let r=e[n];if(t>=r.slotX&&t<=r.slotX+r.slotW)return n}return null}function Uv(e,t,n,r,i,a,o,s){let c=t[r],l=n[r],u=Math.round(c.slotX+c.slotW/2)+.5;e.strokeStyle=o.crosshair,e.lineWidth=.5,e.setLineDash([4,4]),e.beginPath(),e.moveTo(u,a.top),e.lineTo(u,a.bottom),e.stroke(),e.setLineDash([]);let d=[c.label,`Value: ${c.value>=0&&(c.type===`positive`||c.type===`negative`)?`+`:``}${s(c.value)}`,`Total: ${s(l)}`];e.font=`${o.font.sizeSmall}px ${o.font.family}`;let f=0;for(let t=0;t<d.length;t++){let n=e.measureText(d[t]).width;n>f&&(f=n)}let p=f+16,m=d.length*(o.font.sizeSmall+4)+12,h=i.x+10,g=i.y-m/2;h+p>a.right&&(h=i.x-p-10),g<a.top&&(g=a.top),g+m>a.bottom&&(g=a.bottom-m),e.fillStyle=o.axisLabelBackground,e.globalAlpha=.9,e.fillRect(h,g,p,m),e.globalAlpha=1,e.fillStyle=o.text,e.textAlign=`left`,e.textBaseline=`top`;let _=o.font.sizeSmall+4;for(let t=0;t<d.length;t++)e.fillText(d[t],h+8,g+6+t*_)}function Wv(e,t,n,r,i,a){let{data:o}=r;if(!o||o.length===0||t<=0||n<=0)return{hitBar:null};let s=r.positiveColor??i.candleUp,c=r.negativeColor??i.candleDown,l=r.totalColor??i.lineColor,u=r.subtotalColor??i.textSecondary,d=r.connectorColor??i.textSecondary,f=r.connectorStyle??`dashed`,p=r.barWidth??kv,m=r.showValues!==!1,h=r.showDelta!==!1,g=r.valueFormat??Mv,_=r.labelFormat??(e=>e),{valMin:v,valMax:y}=Fv(o),b=y-v||1,x=Nv(t,n),{bars:S,cumulatives:C}=Pv(o,x,p,v,b);Iv(e,t,n,i.background),Lv(e,x,v,y,i,g),zv(e,S,x,v,b,d,f),Rv(e,S,{positive:s,negative:c,total:l,subtotal:u}),m&&Bv(e,S,C,i,g,h),Vv(e,S,x,i,_);let w=a?Hv(S,a.x,x):null;return a&&w!==null&&Uv(e,S,C,w,a,x,i,g),{hitBar:w}}var Gv=Math.PI/180,Kv=150,qv=240,Jv=90,Yv=.14,Xv=1.6*Gv,Zv=.22,Qv=8,$v=18,ey=16,ty=6.5,ny=20,ry=5,iy=28;function ay(e,t,n){return e<t?t:e>n?n:e}function oy(e){let t=Math.abs(e);return t>=1e6?(e/1e6).toFixed(2)+`M`:t>=1e3?(e/1e3).toFixed(1)+`K`:Number.isInteger(e)?e.toFixed(0):e.toFixed(1)}function sy(e){let t=Number.isFinite(e.startAngle)?e.startAngle:Kv,n=(Number.isFinite(e.endAngle)?e.endAngle:t+qv)-t;return n<=0&&(n=(n%360+360)%360||360),n=ay(n,Jv,360),{start:(t%360+360)%360*Gv,sweep:n*Gv}}function cy(e,t){let n=Math.min(Math.cos(e),Math.cos(t)),r=Math.max(Math.cos(e),Math.cos(t)),i=Math.min(Math.sin(e),Math.sin(t)),a=Math.max(Math.sin(e),Math.sin(t));for(let o=Math.ceil(e/(Math.PI/2));Math.PI/2*o<=t;o++){let e=Math.PI/2*o;n=Math.min(n,Math.cos(e)),r=Math.max(r,Math.cos(e)),i=Math.min(i,Math.sin(e)),a=Math.max(a,Math.sin(e))}return{minX:n,maxX:r,minY:i,maxY:a}}function ly(e){if(e.showZoneLabels!==!0||!e.zones)return 0;let t=e.zones.reduce((e,t)=>Math.max(e,t.label?.length??0),0);return t>0?t*ty+12:0}function uy(e,t,n){let r=Number.isFinite(n.min)?n.min:0,i=Number.isFinite(n.max)?n.max:100;i-r>Math.abs(r)*1e-9||(i=r+Math.max(1,Math.abs(r)*1e-6));let{start:a,sweep:o}=sy(n),s=a,c=a+o,l=ay(n.thickness??Yv,.04,.5),u=cy(s,c),d=Math.max(u.maxY,.18),f=ly(n),p=f>0?ey:0,m=Math.max(1,e-2*Qv-2*f),h=Math.max(1,t-2*Qv-$v-p),g=1+l/2,_=Math.max(8,Math.min(m/((u.maxX-u.minX)*g),h/((d-u.minY)*g))),v=_*l,y=(d-u.minY)*_*g+$v+p,b=e/2-(u.maxX+u.minX)/2*_,x=(t-y)/2+p-u.minY*_*g,S=_-v/2,C=Math.max(11,Math.round(S*.46)),w=u.maxY>.3?x-C*.12:x-C*.55,T=Math.max(Math.sin(s),Math.sin(c)),E=T>.2?x+T*_+v/2+2:1/0,D=Math.min(t-Qv,E);return{cx:b,cy:x,radius:_,thickness:v,startAngle:s,endAngle:c,min:r,max:i,valueY:w,valueSize:C,textBottom:D}}function dy(e,t){let n=Number.isFinite(e)?ay((e-t.min)/(t.max-t.min),0,1):0;return t.startAngle+(t.endAngle-t.startAngle)*n}function fy(e,t){if(!t||!Number.isFinite(e))return;let n;for(let r of t)e>=r.from&&e<=r.to&&(n=r);return n}function py(e,t,n){let r=(t??[]).map(t=>({a0:dy(t.from,e),a1:dy(t.to,e),color:t.color,track:!1})).filter(e=>e.a1>e.a0).sort((e,t)=>e.a0-t.a0),i=[],a=e.startAngle;for(let e of r)e.a1<=a||(e.a0>a+1e-9&&i.push({a0:a,a1:e.a0,color:n,track:!0}),i.push({...e,a0:Math.max(e.a0,a)}),a=e.a1);return a<e.endAngle-1e-9&&i.push({a0:a,a1:e.endAngle,color:n,track:!0}),i}function my(e,t,n,r,i){r<=n||(e.beginPath(),e.arc(t.cx,t.cy,t.radius,n,r,!1),e.lineWidth=t.thickness,e.lineCap=`butt`,e.strokeStyle=i,e.stroke())}function hy(e,t,n,r,i,a){let o=t.cx+Math.cos(n)*t.radius,s=t.cy+Math.sin(n)*t.radius,c=a===`start`?n-Math.PI:n;e.globalAlpha=i,e.beginPath(),e.arc(o,s,t.thickness/2,c,c+(i>=1?Math.PI*2:Math.PI),!1),e.closePath(),e.fillStyle=r,e.fill(),e.globalAlpha=1}function gy(e,t,n,r,i,a){let o=py(t,n,i),s=o.some(e=>!e.track);o.forEach((n,i)=>{let a=i>0&&!n.track&&!o[i-1].track?Xv/2:0,s=i<o.length-1&&!n.track&&!o[i+1].track?Xv/2:0,c=n.a0+a,l=n.a1-s;if(n.track){my(e,t,c,l,n.color);return}e.globalAlpha=Zv,my(e,t,c,l,n.color),e.globalAlpha=1,my(e,t,c,Math.min(l,r),n.color)}),s||my(e,t,t.startAngle,r,a);let c=r>t.startAngle+1e-9,l=r>=t.endAngle-1e-9,u=(e,t)=>e.track?[!s&&t?a:i,1]:[e.color,t?1:Zv],[d,f]=u(o[0],c),[p,m]=u(o[o.length-1],l);hy(e,t,t.startAngle,d,f,`start`),hy(e,t,t.endAngle,p,m,`end`)}function _y(e,t,n){let r=t.radius-t.thickness/2;if(r<iy)return;let i=Math.max(4,t.thickness*.45);e.strokeStyle=n,e.lineCap=`butt`;for(let n=0;n<=ny;n++){let a=n%ry===0,o=t.startAngle+(t.endAngle-t.startAngle)*n/ny,s=r-i,c=s-(a?Math.max(6,t.thickness*.55):Math.max(3,t.thickness*.3));e.globalAlpha=a?.55:.3,e.lineWidth=a?1.5:1,e.beginPath(),e.moveTo(t.cx+Math.cos(o)*s,t.cy+Math.sin(o)*s),e.lineTo(t.cx+Math.cos(o)*c,t.cy+Math.sin(o)*c),e.stroke()}e.globalAlpha=1}function vy(e,t,n,r,i){let a=t.cx+Math.cos(n)*t.radius,o=t.cy+Math.sin(n)*t.radius;e.beginPath(),e.arc(a,o,t.thickness*.78,0,Math.PI*2),e.fillStyle=r,e.fill(),e.lineWidth=Math.max(2,t.thickness*.32),e.strokeStyle=i,e.stroke()}function yy(e,t,n,r,i){let a=Math.cos(n),o=Math.sin(n),s=t.radius-t.thickness*.9,c=Math.max(6,t.thickness*.6),l=Math.max(1.5,t.thickness*.14);e.beginPath(),e.moveTo(t.cx+a*s,t.cy+o*s),e.lineTo(t.cx-o*l-a*c,t.cy+a*l-o*c),e.lineTo(t.cx+o*l-a*c,t.cy-a*l-o*c),e.closePath(),e.fillStyle=r,e.fill(),e.beginPath(),e.arc(t.cx,t.cy,Math.max(4,t.thickness*.42),0,Math.PI*2),e.fill(),e.lineWidth=2,e.strokeStyle=i,e.stroke()}function by(e,t,n,r,i,a,o){e.font=`${n} ${r}px ${i}`;let s=e.measureText(t).width;if(s<=a)return r;let c=Math.floor(r*a/s);return c<o?0:(e.font=`${n} ${c}px ${i}`,c)}function xy(e,t,n,r,i,a,o){let s=a.font.family,c=(t.radius-t.thickness/2)*1.3,l=a.font.sizeSmall;e.textAlign=`center`,e.textBaseline=`middle`;let u=by(e,n,`600`,t.valueSize,s,c,l);if(u===0)return;let d=o?Math.min(t.cy+u*.8,t.textBottom-u/2):t.valueY;e.fillStyle=a.text,e.fillText(n,t.cx,d);let f=Math.max(l,Math.round(u*.26));if(i?.label&&!o){let n=i.label.toUpperCase();by(e,n,`600`,f,s,c*.9,l)>0&&(e.fillStyle=i.color,e.fillText(n,t.cx,d-u*.78))}if(r){let n=d+u*.72;n+f/2<=t.textBottom&&by(e,r,`400`,f,s,c,l)>0&&(e.fillStyle=a.textSecondary,e.fillText(r,t.cx,n))}}function Sy(e,t,n,r){e.fillStyle=r.textSecondary,e.font=`${r.font.sizeSmall+1}px ${r.font.family}`;let i=t.thickness/2+6;for(let[r,a]of[[t.startAngle,t.min],[t.endAngle,t.max]]){let o=Math.cos(r),s=Math.sin(r),c=t.cx+o*t.radius,l=t.cy+s*t.radius;s>.2?(e.textAlign=`center`,e.textBaseline=`top`,e.fillText(n(a),c,l+i)):(e.textAlign=o<-.2?`right`:o>.2?`left`:`center`,e.textBaseline=s<-.2?`bottom`:`middle`,e.fillText(n(a),c+o*i,l+s*i))}}function Cy(e,t,n,r){e.fillStyle=r.textSecondary,e.font=`${r.font.sizeSmall}px ${r.font.family}`,e.textBaseline=`middle`;let i=t.radius+t.thickness/2+8;for(let r of n){if(!r.label)continue;let n=dy((ay(r.from,t.min,t.max)+ay(r.to,t.min,t.max))/2,t),a=Math.cos(n);e.textAlign=a<-.2?`right`:a>.2?`left`:`center`,e.fillText(r.label,t.cx+a*i,t.cy+Math.sin(n)*i)}}function wy(e,t,n,r,i,a){if(t<=0||n<=0)return;let o=uy(t,n,r),s=Number.isFinite(a),c=s?ay(a,o.min,o.max):o.min,l=dy(c,o),u=s?fy(c,r.zones):void 0,d=r.pointer===`needle`,f=r.valueFormat??oy,p=u?.color??r.needleColor??i.lineColor;e.save(),e.fillStyle=i.background,e.fillRect(0,0,t,n),gy(e,o,r.zones,l,r.trackColor??i.grid,p),_y(e,o,i.textSecondary),s&&(d?yy(e,o,l,r.needleColor??i.text,i.background):vy(e,o,l,p,i.background)),r.showValue!==!1&&xy(e,o,s?f(c):`—`,r.label,u,i,d),Sy(e,o,f,i),r.showZoneLabels===!0&&r.zones?.length&&Cy(e,o,r.zones,i),e.restore()}var Ty=12,Ey=.72,Dy=20,Oy=.35;function ky(e){let t=0,n=0,r=e.mode===`stacked`;return e.categories.forEach((i,a)=>{let o=0,s=0;for(let i of e.series){let e=i.values[a];Number.isFinite(e)&&(r?e>=0?o+=e:s+=e:(n=Math.max(n,e),t=Math.min(t,e)))}n=Math.max(n,o),t=Math.min(t,s)}),[t,n]}function Ay(e,t){let n=e.colorBySign;return n?n===!0?{positive:t.candleUp,negative:t.candleDown}:n:null}function jy(e,t,n,r,i){let a=e.orientation===`horizontal`,o=e.legend??e.series.length>1?dv(e.series.map((e,t)=>({label:e.name,color:lv(t,e.color)})),t-Ty*2,i):null,s=Ty+(o?o.height+6:0),[c,l]=ky(e),u=av(c,l,a?Math.max(2,Math.floor(t/110)):5),d=e.valueFormat??Q(u),f=Math.max(0,...u.ticks.map(e=>i(d(e),11))),p;if(a){let r=Ty+Math.min(t*Oy,Math.max(0,...e.categories.map(e=>i(e,11))))+8;p={x:r,y:s,width:Math.max(1,t-r-Ty-f/2),height:Math.max(1,n-s-Ty-Dy)}}else{let e=Ty+f+8;p={x:e,y:s,width:Math.max(1,t-e-Ty),height:Math.max(1,n-s-Ty-Dy)}}let m=Math.max(1,e.categories.length),h=a?p.y:p.x,g=(a?p.height:p.width)/m,_=g*Ey,v=e.mode===`stacked`,y=v?_:_/Math.max(1,e.series.length),b=e=>a?Z(u,e,p.x,p.width):Z(u,e,p.y,p.height,!0),x=b(0),S=Ay(e,r),C=Array(m).fill(0),w=Array(m).fill(0),T=[];return e.series.forEach((t,n)=>{e.categories.forEach((e,r)=>{let i=t.values[r];if(!Number.isFinite(i))return;let o=0;v&&(o=i>=0?C[r]:w[r],i>=0?C[r]+=i:w[r]+=i);let s=b(o),c=b(o+i),l=h+r*g+(g-_)/2+(v?0:n*y),u=S?i>=0?S.positive:S.negative:lv(n,t.color),d=Math.min(s,c),f=Math.abs(c-s);T.push(a?{x:d,y:l,width:f,height:y,category:e,series:t.name,value:i,index:r,color:u}:{x:l,y:d,width:y,height:f,category:e,series:t.name,value:i,index:r,color:u})})}),{plot:p,scale:u,orientation:a?`horizontal`:`vertical`,zero:x,bars:T,bandStart:h,band:g,legend:o,legendY:Ty}}function My(e,t,n){for(let r of e.bars)if(t>=r.x-2&&t<=r.x+r.width+2&&n>=r.y-2&&n<=r.y+r.height+2)return r;return null}function Ny(e,t,n,r){let{plot:i}=e;if(t<i.x||t>i.x+i.width||n<i.y||n>i.y+i.height)return-1;let a=e.orientation===`horizontal`?n:t,o=Math.floor((a-e.bandStart)/e.band);return o>=0&&o<r?o:-1}function Py(e,n,r,i,a,o,s=jy(i,n,r,a,uv(e,a))){let c=uv(e,a),l=i.valueFormat??cv,{plot:u,orientation:d}=s,f=d===`horizontal`;e.fillStyle=a.background,e.fillRect(0,0,n,r),s.legend&&fv(e,s.legend,Ty,s.legendY,a),mv(e,u,s.scale,f?`horizontal`:`vertical`,a,i.valueFormat??Q(s.scale));let p=o&&i.crosshair!==!1?Ny(s,o.x,o.y,i.categories.length):-1;if(p>=0){e.fillStyle=(0,t.withAlpha)(a.crosshair,.08);let n=s.bandStart+p*s.band;f?e.fillRect(u.x,n,u.width,s.band):e.fillRect(n,u.y,s.band,u.height)}for(let t of s.bars)e.fillStyle=t.color,e.fillRect(t.x,t.y,Math.max(t.width,+!!f),Math.max(t.height,+!f));e.strokeStyle=a.axisLine,e.lineWidth=1,e.beginPath();let m=Math.round(s.zero)+.5;if(f?(e.moveTo(m,u.y),e.lineTo(m,u.y+u.height)):(e.moveTo(u.x,m),e.lineTo(u.x+u.width,m)),e.stroke(),Fy(e,i.categories,s,a,c),i.showValues&&Iy(e,s,a,l,i.mode===`stacked`),p>=0&&o){let t=[{text:i.categories[p],bold:!0}];for(let e of s.bars)e.index===p&&t.push({text:`${e.series}: ${l(e.value)}`,color:e.color});pv(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}function Fy(e,t,n,r,i){let{plot:a}=n;e.save(),e.font=$(r,11),e.fillStyle=r.axisLabel;let o=Math.max(0,...t.map(e=>i(e,11))),s=n.orientation===`vertical`?Math.max(1,Math.ceil((o+8)/Math.max(1,n.band))):1;t.forEach((t,r)=>{if(r%s!==0)return;let o=n.bandStart+(r+.5)*n.band;n.orientation===`horizontal`?(e.textAlign=`right`,e.textBaseline=`middle`,e.fillText(hv(t,a.x-Ty-8,i),a.x-8,o)):(e.textAlign=`center`,e.textBaseline=`top`,e.fillText(hv(t,n.band*s-4,i),o,a.y+a.height+6))}),e.restore()}function Iy(e,t,n,r,i){e.save(),e.font=$(n,10),e.fillStyle=n.textSecondary;for(let n of t.bars){let a=r(n.value);if(t.orientation===`horizontal`){e.textBaseline=`middle`;let t=n.y+n.height/2;i?(e.textAlign=`center`,e.measureText(a).width<n.width-4&&e.fillText(a,n.x+n.width/2,t)):n.value>=0?(e.textAlign=`left`,e.fillText(a,n.x+n.width+4,t)):(e.textAlign=`right`,e.fillText(a,n.x-4,t))}else{e.textAlign=`center`;let t=n.x+n.width/2;i?(e.textBaseline=`middle`,n.height>13&&e.measureText(a).width<n.width&&e.fillText(a,t,n.y+n.height/2)):n.value>=0?(e.textBaseline=`bottom`,e.fillText(a,t,n.y-3)):(e.textBaseline=`top`,e.fillText(a,t,n.y+n.height+3))}}e.restore()}var Ly=12,Ry=-Math.PI/2,zy=Math.PI*2,By=5,Vy=1.4,Hy=18,Uy=new Intl.NumberFormat(void 0,{style:`percent`,maximumFractionDigits:1});function Wy(e,t,n,r,i){let a=e.data.filter(e=>Number.isFinite(e.value)&&e.value>0),o=a.reduce((e,t)=>e+t.value,0),s=a.map((e,t)=>({label:`${e.label} ${Uy.format(e.value/o)}`,color:lv(t,e.color)})),c=e.legend!==!1&&a.length>0,l=c&&t>=n*Vy&&a.length*Hy<=n-Ly*2,u=l?Math.min(t*.4,Math.max(...s.map(e=>i(e.label,11)))+16):t-Ly*2,d=c?dv(s,u,i,l):null,f=l?t-u-Ly*3:t-Ly*2,p=l?n-Ly*2:n-Ly*3-(d?.height??0),m=Math.max(0,Math.min(f,p)/2-By),h=Ly+f/2,g=Ly+p/2,_=e.innerRadius,v=Math.min(.95,Math.max(0,_!==void 0&&Number.isFinite(_)?_:.6)),y=Ry,b=a.map((e,t)=>{let n=e.value/o,r=y;return y+=n*zy,{label:e.label,value:e.value,share:n,start:r,end:y,color:lv(t,e.color),slice:e}});return{cx:h,cy:g,radius:m,inner:m*v,total:o,slices:b,legend:d,legendX:l?t-u-Ly:Ly,legendY:l?Math.max(Ly,g-(d?.height??0)/2):Ly*2+p}}function Gy(e,t,n){let r=t-e.cx,i=n-e.cy,a=Math.hypot(r,i);if(a<e.inner||a>e.radius+By)return null;let o=Math.atan2(i,r);for(;o<Ry;)o+=zy;return e.slices.find(e=>o>=e.start&&o<e.end)??null}function Ky(e,t,n,r,i,a,o=Wy(r,t,n,i,uv(e,i))){let s=uv(e,i),c=r.valueFormat??cv;e.fillStyle=i.background,e.fillRect(0,0,t,n);let l=a&&r.crosshair!==!1?Gy(o,a.x,a.y):null,{cx:u,cy:d,radius:f,inner:p}=o;for(let t of o.slices){let n=(t.start+t.end)/2,r=t===l?By:0,a=u+Math.cos(n)*r,s=d+Math.sin(n)*r;e.beginPath(),e.arc(a,s,f,t.start,t.end),p>0?e.arc(a,s,p,t.end,t.start,!0):e.lineTo(a,s),e.closePath(),e.fillStyle=t.color,e.fill(),o.slices.length>1&&(e.strokeStyle=i.background,e.lineWidth=1.5,e.stroke())}return r.showLabels!==!1&&qy(e,o,i),Jy(e,o,r,i,s),o.legend&&fv(e,o.legend,o.legendX,o.legendY,i),l&&a&&pv(e,[{text:l.label,bold:!0,color:l.color},{text:`${c(l.value)} · ${Uy.format(l.share)}`}],a,{x:0,y:0,width:t,height:n},i),o}function qy(e,t,n){let{cx:r,cy:i,radius:a,inner:o}=t,s=o>0?(a+o)/2:a*.62;e.save(),e.font=$(n,11,`600`),e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=`#fff`;for(let n of t.slices){let t=Uy.format(n.share);if((n.end-n.start)*s<e.measureText(t).width+8||o>0&&a-o<15)continue;let c=(n.start+n.end)/2;e.fillText(t,r+Math.cos(c)*s,i+Math.sin(c)*s)}e.restore()}function Jy(e,t,n,r,i){if(t.inner<=0||!n.centerLabel&&!n.centerValue)return;let a=t.inner*1.6;if(e.save(),e.textAlign=`center`,e.textBaseline=`middle`,n.centerValue){let o=Math.max(12,Math.min(28,t.inner*.42));e.font=$(r,o,`600`),e.fillStyle=r.text,e.fillText(hv(n.centerValue,a,i,o),t.cx,t.cy+(n.centerLabel?o*.35:0))}n.centerLabel&&(e.font=$(r,11),e.fillStyle=r.textSecondary,e.fillText(hv(n.centerLabel,a,i),t.cx,t.cy-(n.centerValue?11*1.1:0))),e.restore()}var Yy=12,Xy=5,Zy=3,Qy=18,$y=20,eb=6;function tb(e,n,r,i,a){let o=1/0,s=-1/0,c=1/0,l=-1/0,u=0;for(let t of e.series)for(let e of t.points)!Number.isFinite(e.x)||!Number.isFinite(e.y)||(e.x<o&&(o=e.x),e.x>s&&(s=e.x),e.y<c&&(c=e.y),e.y>l&&(l=e.y),e.size!==void 0&&Number.isFinite(e.size)&&e.size>u&&(u=e.size));let d=e.maxRadius??24,f=d+eb,p=(e,t,n)=>{if(e>t)return[0,1];let r=(t-e)*f/Math.max(1,n-f*2);return[e>=0?Math.max(0,e-r):e-r,t<=0?Math.min(0,t+r):t+r]},m=av(...p(o,s,n*.8),Math.max(2,Math.floor(n/110))),h=av(...p(c,l,r*.7),5),g=e.xFormat??Q(m),_=e.yFormat??Q(h),v=e.legend??e.series.length>1?dv(e.series.map((e,t)=>({label:e.name,color:lv(t,e.color)})),n-Yy*2,a):null,y=Yy+(v?v.height+6:0),b=Math.max(0,...h.ticks.map(e=>a(_(e),11))),x=Yy+(e.yLabel?Qy:0)+b+8,S=Yy+$y+(e.xLabel?Qy:0),C=a(g(m.max),11)/2,w={x,y,width:Math.max(1,n-x-Yy-C),height:Math.max(1,r-y-S)},T=[];return e.series.forEach((e,n)=>{let r=lv(n,e.color),i=(0,t.withAlpha)(r,.55),a=(0,t.withAlpha)(r,.85);for(let t of e.points){if(!Number.isFinite(t.x)||!Number.isFinite(t.y))continue;let n=t.size!==void 0&&Number.isFinite(t.size)&&t.size>0&&u>0?Math.max(Zy,d*Math.sqrt(t.size/u)):Xy;T.push({px:Z(m,t.x,w.x,w.width),py:Z(h,t.y,w.y,w.height,!0),r:n,color:r,fill:i,hoverFill:a,series:e.name,label:t.label,point:t})}}),{plot:w,xScale:m,yScale:h,points:T,drawOrder:T.map((e,t)=>t).sort((e,t)=>T[t].r-T[e].r),legend:v}}function nb(e,t,n){let r=null,i=1/0;for(let a of e.points){let e=Math.hypot(a.px-t,a.py-n);e<=a.r+eb&&e<i&&(r=a,i=e)}return r}function rb(e,t,n,r,i,a,o=tb(r,t,n,i,uv(e,i))){let{plot:s,xScale:c,yScale:l}=o,u=r.xFormat??Q(c),d=r.yFormat??Q(l);e.fillStyle=i.background,e.fillRect(0,0,t,n),o.legend&&fv(e,o.legend,Yy,Yy,i),mv(e,s,l,`vertical`,i,d),mv(e,s,c,`horizontal`,i,u),r.zeroLines!==!1&&ib(e,o,i),ab(e,o,r,i);let f=a&&r.crosshair!==!1?nb(o,a.x,a.y):null;e.save(),e.beginPath(),e.rect(s.x,s.y,s.width,s.height),e.clip();for(let t of o.drawOrder){let n=o.points[t];e.beginPath(),e.arc(n.px,n.py,n===f?n.r+2:n.r,0,Math.PI*2),e.fillStyle=n===f?n.hoverFill:n.fill,e.fill(),e.strokeStyle=n.color,e.lineWidth=1,e.stroke()}if(e.restore(),r.showLabels){e.save(),e.font=$(i,10),e.fillStyle=i.textSecondary,e.textAlign=`left`,e.textBaseline=`middle`;for(let t of o.points)t.label&&e.fillText(t.label,t.px+t.r+4,t.py);e.restore()}if(f&&a){let o=[{text:f.label??f.series,bold:!0,color:f.color}];f.label&&r.series.length>1&&o.push({text:f.series}),o.push({text:`${r.xLabel??`x`}: ${(r.xFormat??cv)(f.point.x)}`}),o.push({text:`${r.yLabel??`y`}: ${(r.yFormat??cv)(f.point.y)}`}),f.point.size!==void 0&&o.push({text:cv(f.point.size)}),pv(e,o,a,{x:0,y:0,width:t,height:n},i)}return o}function ib(e,t,n){let{plot:r,xScale:i,yScale:a}=t;if(e.save(),e.strokeStyle=n.axisLine,e.lineWidth=1,e.beginPath(),i.min<0&&i.max>0){let t=Math.round(Z(i,0,r.x,r.width))+.5;e.moveTo(t,r.y),e.lineTo(t,r.y+r.height)}if(a.min<0&&a.max>0){let t=Math.round(Z(a,0,r.y,r.height,!0))+.5;e.moveTo(r.x,t),e.lineTo(r.x+r.width,t)}e.stroke(),e.restore()}function ab(e,t,n,r){let{plot:i}=t;e.save(),e.font=$(r,11,`600`),e.fillStyle=r.textSecondary,e.textAlign=`center`,n.xLabel&&(e.textBaseline=`bottom`,e.fillText(n.xLabel,i.x+i.width/2,i.y+i.height+$y+Qy)),n.yLabel&&(e.translate(Yy+11/2,i.y+i.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}var ob=1e-9,sb=1e3,cb=e=>{let t=Number(e.toPrecision(12));return t===0?0:t};function lb(e,t={}){let n=e.filter(e=>Number.isFinite(e));if(n.length===0)return[];let r=1/0,i=-1/0;for(let e of n)e<r&&(r=e),e>i&&(i=e);if(r===i)return[{from:r,to:i,count:n.length}];let a=t.binWidth;if(a!==void 0&&a>0&&Number.isFinite(a)){let e=Math.floor(r/a+ob),t=Math.max(e,Math.ceil(i/a-ob)-1)-e+1;if(t<=1e3){let r=Array.from({length:t},(t,n)=>({from:cb((e+n)*a),to:cb((e+n+1)*a),count:0}));for(let i of n)r[Math.min(t-1,Math.floor(i/a+ob)-e)].count++;return r}}let o=t.bins,s=typeof o==`number`&&Number.isFinite(o)&&o>=1?Math.min(sb,Math.floor(o)):Math.min(sb,Math.ceil(Math.log2(n.length))+1),c=(i-r)/s,l=Array.from({length:s},(e,t)=>({from:cb(r+t*c),to:cb(t===s-1?i:r+(t+1)*c),count:0}));for(let e of n)l[Math.min(s-1,Math.floor((e-r)/c+ob))].count++;return l}var ub=12,db=20,fb=16;function pb(e,n,r){return n.colorBySign?(e.from+e.to)/2<0?r.candleDown:r.candleUp:n.color??t.TC_SERIES_COLORS[0]}function mb(e,t,n,r,i){let a=lb(e.values,{bins:e.bins,binWidth:e.binWidth}),o=a.length>0?a[0].from:0,s=a.length>0?a[a.length-1].to:1,c=(e.markers??[]).map(e=>e.value).filter(e=>Number.isFinite(e)),l=av(Math.min(o,...c),Math.max(s,...c),Math.max(2,Math.floor(t/110))),u=0;for(let e of a)e.count>u&&(u=e.count);let d=av(0,Math.max(4,u),4),f=e.valueFormat??Q(l),p=Math.max(0,...d.ticks.map(e=>i(Q(d)(e),11))),m=ub+(c.length>0?fb:0),h=ub+p+8,g=ub+i(f(l.max),11)/2,_={x:h,y:m,width:Math.max(1,t-h-g),height:Math.max(1,n-m-ub-db)};return{plot:_,xScale:l,yScale:d,bars:a.map(t=>{let n=Z(l,t.from,_.x,_.width),i=t.to>t.from?Z(l,t.to,_.x,_.width):n+_.width/10,a=Z(d,t.count,_.y,_.height,!0);return{x:n,y:a,width:Math.max(1,i-n),height:_.y+_.height-a,bin:t,color:pb(t,e,r)}}),total:a.reduce((e,t)=>e+t.count,0)}}function hb(e,t,n){let{plot:r}=e;return n<r.y||n>r.y+r.height?null:e.bars.find(e=>t>=e.x&&t<e.x+e.width)??null}var gb=new Intl.NumberFormat(void 0,{style:`percent`,maximumFractionDigits:1});function _b(e,n,r,i,a,o,s=mb(i,n,r,a,uv(e,a))){let c=i.valueFormat??cv,{plot:l}=s;e.fillStyle=a.background,e.fillRect(0,0,n,r),mv(e,l,s.yScale,`vertical`,a,Q(s.yScale)),mv(e,l,s.xScale,`horizontal`,a,i.valueFormat??Q(s.xScale));let u=o&&i.crosshair!==!1?hb(s,o.x,o.y):null;for(let n of s.bars)e.fillStyle=n===u?n.color:(0,t.withAlpha)(n.color,.75),e.fillRect(n.x+(n.width>3?.5:0),n.y,Math.max(1,n.width-+(n.width>3)),n.height);if(vb(e,s,i,a,c),u&&o){let{bin:t}=u;pv(e,[{text:t.to>t.from?`${c(t.from)} – ${c(t.to)}`:c(t.from),bold:!0,color:u.color},{text:`${cv(t.count)} · ${gb.format(s.total>0?t.count/s.total:0)}`}],o,{x:0,y:0,width:n,height:r},a)}return s}function vb(e,t,n,r,i){let{plot:a}=t;e.save(),e.font=$(r,10),e.textAlign=`center`,e.textBaseline=`bottom`;let o=[];for(let s of n.markers??[]){if(!Number.isFinite(s.value))continue;let n=Math.round(Z(t.xScale,s.value,a.x,a.width))+.5,c=s.color??r.text;e.strokeStyle=c,e.setLineDash([4,3]),e.lineWidth=1,e.beginPath(),e.moveTo(n,a.y),e.lineTo(n,a.y+a.height),e.stroke(),e.setLineDash([]),e.fillStyle=c;let l=s.label?`${s.label} ${i(s.value)}`:i(s.value),u=e.measureText(l).width/2+4,d=0;for(;o.some(e=>e.row===d&&n-u<e.to&&n+u>e.from);)d++;o.push({from:n-u,to:n+u,row:d}),e.fillText(l,n,a.y-3+d*14)}e.restore()}var yb=8,bb=32,xb=new Map;function Sb(e){let t=xb.get(e);return t===void 0&&(t=Cb(e),xb.size>512&&xb.clear(),xb.set(e,t)),t}function Cb(e){let t=e.trim(),n=t.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);if(n){let e=n[1];return e.length<=4&&(e=[...e.slice(0,3)].map(e=>e+e).join(``)),[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]}let r=t.match(/^rgba?\(\s*(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)/i);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function wb(e,t,n){let r=Sb(e),i=Sb(t);if(!r||!i)return n<.5?e:t;let a=e=>Math.round(r[e]+(i[e]-r[e])*n);return`rgb(${a(0)},${a(1)},${a(2)})`}function Tb(e,t,n){let r=1/0,i=-1/0;for(let t of e)Number.isFinite(t)&&(t<r&&(r=t),t>i&&(i=t));let a=0,o=1;if(r<=i){let e=Math.max(Math.abs(r),Math.abs(i))||1;a=r<0?-e:0,o=r<0?e:i||1}return{negative:n?.negative??t.candleDown,zero:n?.zero??wb(t.background,t.text,.14),positive:n?.positive??t.candleUp,min:n?.min!==void 0&&Number.isFinite(n.min)?n.min:a,max:n?.max!==void 0&&Number.isFinite(n.max)?n.max:o}}function Eb(e,t){return!Number.isFinite(e)||e===0?wb(t.zero,t.zero,0):e<0?wb(t.zero,t.negative,t.min<0?Math.min(1,e/t.min):1):wb(t.zero,t.positive,t.max>0?Math.min(1,e/t.max):1)}var Db=`#11151b`,Ob=.0076;function kb(e){let t=Sb(e);if(!t)return`#ffffff`;let[n,r,i]=t.map(e=>{let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}),a=.2126*n+.7152*r+.0722*i;return(a+.05)/(Ob+.05)>1.05/(a+.05)?Db:`#ffffff`}function Ab(e,t,n,r,i){let a=Math.min(180,t.width);if(a<40||!(n.max>n.min))return;let{x:o,y:s}=t,c=n.max-n.min;e.save();for(let t=0;t<bb;t++){let r=(t+.5)/bb;e.fillStyle=Eb(n.min+c*r,n),e.fillRect(o+a*t/bb,s,a/bb+.5,yb)}e.font=$(i,10),e.fillStyle=i.textSecondary,e.textBaseline=`top`;let l=s+yb+4;e.textAlign=`left`,e.fillText(r(n.min),o,l),e.textAlign=`right`,e.fillText(r(n.max),o+a,l);let u=o+a*-n.min/c;n.min<0&&n.max>0&&u-o>28&&o+a-u>28&&(e.textAlign=`center`,e.fillText(r(0),u,l)),e.restore()}var jb=864e5,Mb=3,Nb=12,Pb=16,Fb=10,Ib=28,Lb=6;function Rb(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;let[n,r,i]=[Number(t[1]),Number(t[2]),Number(t[3])],a=Date.UTC(n,r-1,i),o=new Date(a);return o.getUTCFullYear()!==n||o.getUTCMonth()!==r-1||o.getUTCDate()!==i?null:Math.round(a/jb)}function zb(e){return new Date(e*jb).toISOString().slice(0,10)}var Bb=e=>((e+4)%7+7)%7;function Vb(e,t){let n=e.from===void 0?null:Rb(e.from),r=e.to===void 0?null:Rb(e.to);if(n===null||r===null){let e=1/0,i=-1/0;for(let n of t.keys())n<e&&(e=n),n>i&&(i=n);n??=Number.isFinite(e)?e:null,r??=Number.isFinite(i)?i:null}if(n===null||r===null||n>r)return null;let i=new Date(r*jb).getUTCFullYear()-10+1;return[Math.max(n,Math.round(Date.UTC(i,0,1)/jb)),r]}function Hb(e,t,n){let r=[],i=e;for(;i<=t;){let e=new Date(i*jb).getUTCFullYear(),a=Math.min(t,Math.round(Date.UTC(e,11,31)/jb)),o=i-n(i);r.push({year:e,first:i,last:a,origin:o,weeks:Math.floor((a-o)/7)+1}),i=a+1}return r}var Ub=new Map;function Wb(e){let t=e??``,n=Ub.get(t);if(!n){try{n={month:new Intl.DateTimeFormat(e,{month:`short`,timeZone:`UTC`}),weekday:new Intl.DateTimeFormat(e,{weekday:`short`,timeZone:`UTC`}),long:new Intl.DateTimeFormat(e,{dateStyle:`full`,timeZone:`UTC`})}}catch{n=Wb(void 0)}Ub.set(t,n)}return n}function Gb(e,t,n,r,i){let a=new Map;for(let t of e.data){let e=Rb(t.date);e!==null&&Number.isFinite(t.value)&&a.set(e,t)}let o=Wb(e.locale),s=e.dateFormat??(e=>o.long.format(new Date(`${e}T00:00:00Z`))),c=e.weekdays===5,l=e=>!c||Bb(e)>=1&&Bb(e)<=5,u=Vb(e,a),d=t-Nb*2,f=e.legend===!1?0:28,p=c?5:7,m=c?1:e.weekStart??1,h=e=>(Bb(e)-m+7)%7,g=u?Hb(u[0],u[1],h):[],_=e=>n-Nb*2-f-e*Pb-(e-1)*Fb;for(;g.length>1&&_(g.length)/(g.length*p)<Mb;)g=g.slice(1);let v=[];for(let[e,t]of a)g.length>0&&e>=g[0].first&&e<=g[g.length-1].last&&l(e)&&v.push(t.value);let y=Tb(v,r,e.colorScale),b={cells:[],months:[],weekdays:[],years:[],scale:y,bar:null,pitch:0,formatDate:s};if(g.length===0||d<=0||_(g.length)<=0)return b;let x=g.length>1,S=g.map(e=>String(e.year)),C=Array.from({length:p},(e,t)=>o.weekday.format(new Date((3+m+t)*jb))),w=Nb+Math.max(...C.map(e=>i(e,10)),...x?S.map(e=>i(e,11)):[0])+Lb,T=Math.max(...g.map(e=>e.weeks)),E=Math.min(Ib,(t-w-Nb)/T,_(g.length)/(g.length*p));if(!(E>0))return b;let D=E-(E>=6?Math.max(1,Math.round(E*.12)):0),O=T*E,k=w+Math.max(0,(t-w-Nb-O)/2),A={...b,pitch:E},ee=Nb;for(let[e,n]of g.entries()){let r=ee+Pb;x&&A.years.push({label:S[e],x:k-Lb,y:ee});let s=-1,c=-1/0;for(let e=n.first;e<=n.last;e++){if(!l(e))continue;let u=k+Math.floor((e-n.origin)/7)*E,d=r+h(e)*E,f=a.get(e);A.cells.push({x:u,y:d,size:D,date:zb(e),day:f,color:f&&Number.isFinite(f.value)?Eb(f.value,y):null});let p=new Date(e*jb).getUTCMonth();if(p!==s){s=p;let n=o.month.format(new Date(e*jb)),r=u+i(n,10);u>=c&&r<=t&&(A.months.push({label:n,x:u,y:ee}),c=r+4)}}if(E>=8){let e=E>=13?1:2;for(let t=0;t<p;t+=e)A.weekdays.push({label:C[t],x:k-Lb,y:r+t*E+D/2})}ee=r+p*E+Fb}return f>0&&(A.bar={x:k,y:ee-Fb+8,width:Math.min(O,t-k-Nb),height:f-8}),A}function Kb(e,t,n){for(let r of e.cells)if(t>=r.x&&t<r.x+e.pitch&&n>=r.y&&n<r.y+e.pitch)return r;return null}function qb(e,n,r,i,a,o,s=Gb(i,n,r,a,uv(e,a))){let c=i.valueFormat??cv;e.fillStyle=a.background,e.fillRect(0,0,n,r);let l=o&&i.crosshair!==!1?Kb(s,o.x,o.y):null,u=(0,t.withAlpha)(a.textSecondary,.12),d=s.pitch>=10?2:0;e.save();for(let t of s.cells)e.fillStyle=t.color??u,e.beginPath(),d>0&&typeof e.roundRect==`function`?e.roundRect(t.x,t.y,t.size,t.size,d):e.rect(t.x,t.y,t.size,t.size),e.fill();l&&(e.strokeStyle=a.text,e.lineWidth=1.5,e.strokeRect(l.x-.75,l.y-.75,l.size+1.5,l.size+1.5)),e.fillStyle=a.textSecondary,e.font=$(a,10),e.textAlign=`left`,e.textBaseline=`top`;for(let t of s.months)e.fillText(t.label,t.x,t.y);e.textAlign=`right`,e.textBaseline=`middle`;for(let t of s.weekdays)e.fillText(t.label,t.x,t.y);e.font=$(a,11,`600`),e.fillStyle=a.text,e.textBaseline=`top`;for(let t of s.years)e.fillText(t.label,t.x,t.y);if(e.restore(),s.bar&&Ab(e,s.bar,s.scale,c,a),l&&o){let t=[{text:s.formatDate(l.date),bold:!0,color:l.color??void 0}];if(l.day){t.push({text:c(l.day.value)});for(let[e,n]of Object.entries(l.day.meta??{}))t.push({text:`${e}: ${String(n)}`})}else t.push({text:`–`});pv(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}var Jb=12,Yb=6,Xb=72,Zb=Math.PI/4,Qb=Math.sin(Zb);function $b(e){let t=e.length,n=Array.from({length:t},()=>Array(t).fill(NaN));for(let r=0;r<t;r++)for(let i=r;i<t;i++){let t=ex(e[r],e[i],r===i);n[r][i]=t,n[i][r]=t}return n}function ex(e,t,n){let r=Math.min(e.length,t.length),i=0,a=0,o=0;for(let n=0;n<r;n++)Number.isFinite(e[n])&&Number.isFinite(t[n])&&(i++,a+=e[n],o+=t[n]);if(i<3)return NaN;let s=a/i,c=o/i,l=0,u=0,d=0;for(let n=0;n<r;n++){if(!Number.isFinite(e[n])||!Number.isFinite(t[n]))continue;let r=e[n]-s,i=t[n]-c;l+=r*i,u+=r*r,d+=i*i}return u===0||d===0?NaN:n?1:Math.max(-1,Math.min(1,l/Math.sqrt(u*d)))}var tx=e=>e.toFixed(2);function nx(e,t,n,r){return!t||!e?!0:e===`lower`?r<=n:r>=n}function rx(e,t,n,r,i){let a=e.rows.slice(0,200),o=(e.columns??e.rows).slice(0,200),s=e.columns===void 0||e.columns.length===e.rows.length&&e.columns.every((t,n)=>t===e.rows[n]),c=[];for(let t=0;t<a.length;t++)for(let n=0;n<o.length;n++){let r=e.values[t]?.[n];Number.isFinite(r)&&nx(e.triangle,s,t,n)&&c.push(r)}let l=Tb(c,r,e.colorScale),u={cells:[],rowLabels:[],columnLabels:[],grid:{x:0,y:0,width:0,height:0},pitch:0,scale:l,bar:null,at:[]};if(a.length===0||o.length===0||t<=0||n<=0)return u;let d=Math.min(t*.3,Math.max(...a.map(e=>i(e,11)))),f=Math.max(...o.map(e=>i(e,11))),p=e.legend===!1?0:28,m=Jb+d+Yb,h=t-m-Jb,g=e=>Math.min(Xb,h/o.length,(n-e-Jb-p)/a.length),_=Jb+11+Yb,v=g(_),y=f>v-4,b=f;if(y&&(b=Math.min(f,n*.33/Qb),_=Jb+b*Qb+11,v=g(_)),!(v>0))return u;let x=v-+(v>=8),S=m+Math.max(0,(h-o.length*v)/2);y&&(b=Math.max(0,Math.min(b,(S+x/2-2-11*Qb/2)/Qb))),u.grid={x:S,y:_,width:o.length*v,height:a.length*v},u.pitch=v;let C=e.valueFormat??tx,w=e.showValues!==!1,T=Math.max(8,Math.min(11,v/3));for(let t=0;t<a.length;t++){u.at.push([]);for(let n=0;n<o.length;n++){let r=e.values[t]?.[n];if(!Number.isFinite(r)||!nx(e.triangle,s,t,n))continue;let c=Eb(r,l),d=w?C(r):``,f=w&&v>=18&&i(d,T)<=v-4,p={x:S+n*v,y:_+t*v,size:x,cell:{row:a[t],column:o[n],value:r,rowIndex:t,columnIndex:n},color:c,text:f?d:null,textColor:kb(c)};u.cells.push(p),u.at[t][n]=p}}let E=Math.max(1,Math.ceil(11/v)),D=Math.max(1,Math.ceil(11/(y?v*Qb:v)));for(let e=0;e<a.length;e+=E)u.rowLabels.push({text:hv(a[e],d,i),index:e,x:S-Yb,y:_+e*v+x/2});for(let e=0;e<o.length;e+=D)u.columnLabels.push({text:hv(o[e],b,i),index:e,x:S+e*v+x/2,y:_-Yb,rotated:y});return p>0&&(u.bar={x:S,y:_+a.length*v+8,width:Math.min(u.grid.width,t-S-Jb),height:p-8}),u}function ix(e,t,n){let{grid:r,pitch:i}=e;return i<=0||t<r.x||n<r.y||t>=r.x+r.width||n>=r.y+r.height?null:e.at[Math.floor((n-r.y)/i)]?.[Math.floor((t-r.x)/i)]??null}function ax(e,t,n,r,i,a,o=rx(r,t,n,i,uv(e,i))){let s=r.valueFormat??tx;e.fillStyle=i.background,e.fillRect(0,0,t,n);let c=a&&r.crosshair!==!1?ix(o,a.x,a.y):null;e.save();let l=Math.max(8,Math.min(11,o.pitch/3));e.textAlign=`center`,e.textBaseline=`middle`,e.font=$(i,l);for(let t of o.cells)e.fillStyle=t.color,e.fillRect(t.x,t.y,t.size,t.size),t.text&&(e.fillStyle=t.textColor,e.fillText(t.text,t.x+t.size/2,t.y+t.size/2));c&&(e.strokeStyle=i.text,e.lineWidth=1.5,e.strokeRect(c.x+.75,c.y+.75,c.size-1.5,c.size-1.5)),e.font=$(i,11),e.fillStyle=i.textSecondary,e.textAlign=`right`;for(let t of o.rowLabels)e.fillStyle=c&&c.cell.rowIndex===t.index?i.text:i.textSecondary,e.fillText(t.text,t.x,t.y);for(let t of o.columnLabels)e.fillStyle=c&&c.cell.columnIndex===t.index?i.text:i.textSecondary,t.rotated?(e.save(),e.translate(t.x,t.y),e.rotate(Zb),e.textAlign=`right`,e.fillText(t.text,0,0),e.restore()):(e.textAlign=`center`,e.textBaseline=`bottom`,e.fillText(t.text,t.x,t.y),e.textBaseline=`middle`);if(e.restore(),o.bar&&Ab(e,o.bar,o.scale,s,i),c&&a){let{cell:r}=c;pv(e,[{text:`${r.row} × ${r.column}`,bold:!0,color:c.color},{text:s(r.value)}],a,{x:0,y:0,width:t,height:n},i)}return o}var ox=12,sx=18,cx=20,lx=10,ux=.2,dx=2e3,fx=1e-9;function px(e,t,n=1/0){let r=Number.isFinite(t)?Math.max(1,Math.floor(t)):25,i=[],a=Math.max(r-1,e.length-(Number.isFinite(n)?Math.max(1,Math.floor(n)):e.length));for(let t=a;t<e.length;t++){let n=0,a=0;for(let i=t-r+1;i<=t;i++)n+=e[i].volume,a+=e[i].close;i.push({time:e[t].time,volume:n/r,price:a/r})}return i}var mx=(e,t)=>t-e>fx*Math.max(Math.abs(e),Math.abs(t));function hx(e){if(e.length<2)return null;let t=1/0,n=-1/0,r=1/0,i=-1/0;for(let a of e)t=Math.min(t,a.volume),n=Math.max(n,a.volume),r=Math.min(r,a.price),i=Math.max(i,a.price);let a=e[e.length-2],o=e[e.length-1],s=mx(t,n)?(o.volume-a.volume)/(n-t):0,c=mx(r,i)?(o.price-a.price)/(i-r):0;if(Math.abs(s)<1e-6&&Math.abs(c)<1e-6)return null;let l=(Math.atan2(c,s)+2*Math.PI)%(2*Math.PI);return Math.round(l/(Math.PI/4))%8+1}function gx(e,n,r,i,a){let o=px(e.data,e.period??25,_x(e)),s=1/0,c=-1/0,l=1/0,u=-1/0;for(let e of o)s=Math.min(s,e.volume),c=Math.max(c,e.volume),l=Math.min(l,e.price),u=Math.max(u,e.price);o.length>0&&!mx(s,c)&&(c=s),o.length>0&&!mx(l,u)&&(u=l);let d=av(o.length>0?s:0,o.length>0?c:1,Math.max(2,Math.floor(n/110))),f=av(o.length>0?l:0,o.length>0?u:1,Math.max(2,Math.floor(r/60))),p=e.priceFormat??Q(f),m=e.volumeFormat??Q(d),h=ox+Math.max(0,...f.ticks.map(e=>a(p(e),11)))+8+(e.yLabel?sx:0),g=ox+a(m(d.max),11)/2,_=ox,v=ox+cx+(e.xLabel?sx:0),y={x:h,y:_,width:Math.max(1,n-h-g),height:Math.max(1,r-_-v)},b=Math.max(1,o.length-1);return{plot:y,xScale:d,yScale:f,points:o.map((e,t)=>({px:Z(d,e.volume,y.x,y.width),py:Z(f,e.price,y.y,y.height,!0),alpha:ux+(1-ux)*t/b,point:e})),phase:hx(o),color:e.color??t.TC_SERIES_COLORS[0]}}function _x(e){let t=e.points??60;return Number.isFinite(t)?Math.min(dx,Math.max(2,Math.floor(t))):60}function vx(e,t,n){let r=null,i=lx*lx;for(let a=e.points.length-1;a>=0;a--){let o=e.points[a],s=(o.px-t)**2+(o.py-n)**2;s<i&&(r=o,i=s)}return r}var yx=new Intl.DateTimeFormat(void 0,{year:`numeric`,month:`short`,day:`numeric`});function bx(e,n,r,i,a,o,s=gx(i,n,r,a,uv(e,a))){let{plot:c,points:l,color:u}=s,d=i.timeFormat??(e=>yx.format(new Date(e))),f=i.priceFormat??cv,p=i.volumeFormat??cv;e.fillStyle=a.background,e.fillRect(0,0,n,r),mv(e,c,s.yScale,`vertical`,a,i.priceFormat??Q(s.yScale)),mv(e,c,s.xScale,`horizontal`,a,i.volumeFormat??Q(s.xScale)),xx(e,c,i,a),e.save(),e.lineWidth=1.5,e.lineJoin=`round`;for(let n=1;n<l.length;n++)e.strokeStyle=(0,t.withAlpha)(u,l[n].alpha),e.beginPath(),e.moveTo(l[n-1].px,l[n-1].py),e.lineTo(l[n].px,l[n].py),e.stroke();for(let n of l)e.fillStyle=(0,t.withAlpha)(u,n.alpha),e.beginPath(),e.arc(n.px,n.py,2,0,Math.PI*2),e.fill();let m=l[l.length-1];m&&(e.fillStyle=u,e.strokeStyle=a.background,e.lineWidth=2,e.beginPath(),e.arc(m.px,m.py,5,0,Math.PI*2),e.fill(),e.stroke()),e.restore();let h=o&&i.crosshair!==!1?vx(s,o.x,o.y):null;return h&&o&&(e.save(),e.strokeStyle=a.text,e.lineWidth=1.5,e.beginPath(),e.arc(h.px,h.py,5,0,Math.PI*2),e.stroke(),e.restore(),pv(e,[{text:d(h.point.time),bold:!0,color:u},{text:`${i.yLabel??`Price`}: ${f(h.point.price)}`},{text:`${i.xLabel??`Volume`}: ${p(h.point.volume)}`}],o,{x:0,y:0,width:n,height:r},a)),s}function xx(e,t,n,r){e.save(),e.font=$(r,11),e.fillStyle=r.textSecondary,e.textAlign=`center`,n.xLabel&&(e.textBaseline=`bottom`,e.fillText(n.xLabel,t.x+t.width/2,t.y+t.height+cx+sx)),n.yLabel&&(e.translate(ox+4,t.y+t.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}exports.ABCDPatternTool=Vu,exports.ADXIndicator=Xn,exports.ALMAIndicator=ui,exports.ATRIndicator=Yn,exports.AXIS_LABEL_HEIGHT=O,exports.AcceleratorOscillatorIndicator=Rr,exports.AccumulationDistributionIndicator=Kr,exports.AccumulativeSwingIndexIndicator=to,exports.AdvanceDeclineIndicator=ro,exports.AlertDragHandler=ms,exports.AlertManager=ig,exports.AlligatorIndicator=Fn,exports.AnchoredVWAPIndicator=En,exports.AnchoredVWAPTool=vu,exports.Animator=r_,exports.ArcTool=rf,exports.AreaRenderer=Pe,exports.AroonIndicator=tr,exports.ArrowMarkTool=Rd,exports.ArrowTool=pu,exports.AverageDayRangeIndicator=Ii,exports.AveragePriceIndicator=Wi,exports.AwesomeOscillatorIndicator=Wn,exports.AxisDragHandler=ps,exports.BalanceOfPowerIndicator=Cr,exports.BarCountdown=le,exports.BarRenderer=Fe,exports.BarsPatternTool=Mf,exports.BaseFinanceChart=a_,exports.BaselineRenderer=Re,exports.BinanceAdapter=qm,exports.BollingerBandWidthIndicator=Ci,exports.BollingerBandsIndicator=hn,exports.BollingerPercentBIndicator=Si,exports.BracketTool=Lp,exports.BrushTool=Xd,exports.BybitAdapter=sh,exports.CANDLE_PATTERNS=ja,exports.CCIIndicator=$n,exports.CMFIndicator=ir,exports.COUNTDOWN_HEIGHT=ce,exports.CalloutTool=Ad,exports.CandlestickRenderer=oe,exports.CanvasLayer=n,exports.ChaikinOscillatorIndicator=Gn,exports.ChaikinVolatilityIndicator=jr,exports.ChandeKrollStopIndicator=yi,exports.ChandeMomentumIndicator=Tr,exports.ChandelierExitIndicator=Pn,exports.ChartLegend=bh,exports.ChartStateManager=jg,exports.ChopZoneIndicator=so,exports.ChoppinessIndexIndicator=sr,exports.CircleTool=Gu,exports.CoinbaseAdapter=th,exports.CompareRenderer=bt,exports.CompareSymbolIndicator=wo,exports.ConnorsRSIIndicator=dr,exports.CoppockIndicator=pr,exports.CorrelationCoefficientIndicator=ko,exports.CorrelationLogIndicator=Ao,exports.CrossLineTool=Ou,exports.CrosshairHandler=_s,exports.CrosshairTooltip=Ls,exports.CurrentPriceLine=lm,exports.CurveTool=nf,exports.CyclicLinesTool=td,exports.CypherPatternTool=Wu,exports.DEFAULT_LEGEND_CONFIG=yh,exports.DEFAULT_MAX_PIXEL_RATIO=a,exports.DEFAULT_MAX_WEBGL_CHARTS=e.t,exports.DEFAULT_SESSION_HOURS=Vh,exports.DEMAIndicator=ci,exports.DENSE_BAR_WIDTH=e.u,exports.DOUBLE_TAP_MS=Wo,exports.DOUBLE_TAP_PX=Go,exports.DPRManager=s,exports.DataExporter=Lg,exports.DateAndPriceRangeTool=Zu,exports.DateRangeTool=lu,exports.DepthHeatmapBuffer=gt,exports.DepthHeatmapRenderer=_t,exports.DepthOverlay=Op,exports.DetrendedPriceOscillatorIndicator=Sr,exports.DisparityIndexIndicator=Vr,exports.DonchianChannelIndicator=xn,exports.DrawingBase=G,exports.DrawingManager=cl,exports.DrawingRenderer=ul,exports.EMAIndicator=mn,exports.EaseOfMovementIndicator=Or,exports.Easing=n_,exports.ElderRayIndicator=_r,exports.ElliottCorrectionTool=iu,exports.ElliottDoubleComboTool=ou,exports.ElliottImpulseTool=ru,exports.ElliottTriangleTool=au,exports.ElliottTripleComboTool=su,exports.ElliottWaveTool=nu,exports.EllipseTool=ql,exports.Emitter=am,exports.EnvelopeIndicator=zn,exports.EquivolumeRenderer=Ue,exports.EventBus=qs,exports.ExtendedLineTool=Il,exports.FibArcsTool=gf,exports.FibChannelTool=Pu,exports.FibCirclesTool=hf,exports.FibExtensionTool=Gl,exports.FibRetracementTool=Ul,exports.FibSpeedResistanceFanTool=Ru,exports.FibSpiralTool=yf,exports.FibTimeZonesTool=xu,exports.FibWedgeTool=_f,exports.FinanceCrosshair=o_,exports.FisherTransformIndicator=xr,exports.FlagTool=Fd,exports.ForceIndexIndicator=ur,exports.ForecastTool=Af,exports.GROUP_HEADER=q_,exports.GannBoxTool=_u,exports.GannFanTool=hu,exports.GannSquareTool=bf,exports.GridRenderer=e.o,exports.GuppyMMAIndicator=Vi,exports.HLCAreaRenderer=Ge,exports.HammingMAIndicator=Ja,exports.HeadAndShouldersTool=Hu,exports.HiLoRenderer=Xe,exports.HighlighterTool=Zd,exports.HistoricalVolatilityIndicator=Ti,exports.HollowCandleRenderer=Ie,exports.HorizontalLineTool=Ml,exports.HorizontalRayTool=Nl,exports.HullMAIndicator=kn,exports.ICON_GLYPHS=zd,exports.INDICATOR_CATEGORIES=_o,exports.INTERVAL_LIMITS=Qt,exports.INTERVAL_UNITS=Zt,exports.IchimokuIndicator=_n,exports.IconTool=Vd,exports.IndicatorBase=P,exports.IndicatorEngine=ln,exports.IndicatorValueMap=F,exports.IndicatorWorkerHost=xo,exports.InfoLineTool=Au,exports.InteractionManager=ts,exports.KAMAIndicator=di,exports.KSTIndicator=mr,exports.KagiRenderer=Be,exports.KeltnerChannelIndicator=bn,exports.KeyboardHandler=Ds,exports.KlingerIndicator=br,exports.KrakenAdapter=mh,exports.LSMAIndicator=fi,exports.LayerManager=r,exports.LineRenderer=Ne,exports.LineWithMarkersRenderer=qe,exports.LinearRegressionChannelIndicator=On,exports.LinearRegressionSlopeIndicator=Pi,exports.MACDIndicator=qn,exports.MAChannelIndicator=Wa,exports.MACrossIndicator=gi,exports.MADoubleIndicator=Qa,exports.MARibbonIndicator=Hi,exports.MATripleIndicator=$a,exports.MAX_ALERT_BARS=Yh,exports.MAX_BASE_RATIO=fm,exports.MAX_BASE_REQUESTS=dm,exports.MFIIndicator=er,exports.MIN_ALERT_BARS=Xh,exports.MIN_BAR_UNIT=ve,exports.MIN_BAR_UNIT_LIMIT=ye,exports.MTFMovingAverageIndicator=Mn,exports.MajorityRuleIndicator=io,exports.MarketProfileRenderer=at,exports.MassIndexIndicator=wr,exports.McGinleyDynamicIndicator=pi,exports.MeasureOverlay=Kg,exports.MeasureTool=uu,exports.MedianPriceIndicator=Gi,exports.MockAdapter=Jm,exports.ModifiedSchiffPitchforkTool=Zl,exports.MomentumIndicator=wi,exports.NetVolumeIndicator=Li,exports.NoteTool=kd,exports.OBVIndicator=Zn,exports.OrderDraftTool=Up,exports.OrderRenderer=hp,exports.PRICE_SCALE_MARGIN=be,exports.PanHandler=ds,exports.PaneResizeHandler=hs,exports.PaperExecutionAdapter=nm,exports.ParabolicSARIndicator=vn,exports.ParallelChannelTool=Ll,exports.PathTool=Qd,exports.PercentagePriceOscillatorIndicator=Ir,exports.PeriodLevelsRenderer=ut,exports.PinnedTooltip=Hs,exports.PitchfanTool=vf,exports.PitchforkTool=Yl,exports.PivotMarkersRenderer=mt,exports.PivotPointsIndicator=wn,exports.PointAndFigureRenderer=Ve,exports.PollingAdapter=Zm,exports.PolylineTool=$d,exports.PositionRenderer=Dp,exports.PrettyGoodOscillatorIndicator=Ur,exports.PriceAxis=C,exports.PriceAxisAddButton=is,exports.PriceLabelTool=od,exports.PriceLines=Gh,exports.PriceOscillatorIndicator=uo,exports.PriceRangeTool=cu,exports.PriceVolumeTrendIndicator=kr,exports.ProjectionTool=jf,exports.QstickIndicator=Hr,exports.RANGE_PRESETS=we,exports.ROCIndicator=nr,exports.RSIIndicator=Kn,exports.RayTool=Fl,exports.ReconnectManager=sm,exports.RectangleTool=Kl,exports.RegressionChannelTool=Rl,exports.RelativeMomentumIndexIndicator=Br,exports.RelativeVigorIndicator=Mr,exports.RelativeVolatilityIndexIndicator=Mi,exports.RenderEngine=me,exports.RenderLoop=i,exports.RenkoRenderer=ze,exports.ReplayController=Mm,exports.ReplayManager=ug,exports.ResamplingAdapter=bm,exports.RiskRewardTool=Du,exports.SELECTION_BOX_MIN_SIZE=e_,exports.SMAIndicator=pn,exports.SMIErgodicIndicator=lo,exports.SMMAIndicator=li,exports.SNAPSHOT_VERSION=fg,exports.SYMBOL_INDICATOR_IDS=So,exports.SchaffTrendCycleIndicator=vr,exports.SchiffPitchforkTool=Xl,exports.Screenshot=Eh,exports.SelectionBoxOverlay=t_,exports.SessionBreaks=Mh,exports.SessionShading=Hh,exports.SessionVWAPIndicator=Nn,exports.SignalMarkerManager=Hg,exports.SineLineTool=Tf,exports.SpreadIndicator=To,exports.StandardErrorBandsIndicator=Ri,exports.StandardErrorIndicator=Fi,exports.StdDevIndicator=Wr,exports.StepLineRenderer=Ke,exports.StochasticIndicator=Jn,exports.StochasticMomentumIndexIndicator=ji,exports.StochasticRSIIndicator=Nr,exports.StreamManager=jm,exports.SupertrendIndicator=yn,exports.SymbolSeriesStore=yt,exports.TEMAIndicator=Un,exports.TOUCH_REACH=Uo,exports.TRIXIndicator=Er,exports.TSIIndicator=rr,exports.TapTracker=Ko,exports.TextAnnotationTool=fu,exports.ThreeDrivesTool=Uu,exports.TickAggregator=om,exports.TickBarAdapter=Tm,exports.TickBarBuilder=wm,exports.TimeAxis=Ho,exports.TimeCyclesTool=wf,exports.TradeZoneManager=Gg,exports.TradingContextMenu=jp,exports.TradingDragHandler=Ap,exports.TradingManager=em,exports.TradingRenderer=tm,exports.TrendAngleTool=bl,exports.TrendLineTool=jl,exports.TrendStrengthIndexIndicator=Ni,exports.TriangleTool=Jl,exports.TypicalPriceIndicator=Ki,exports.UlcerIndexIndicator=Oi,exports.UltimateOscillatorIndicator=cr,exports.UndoRedoManager=Mg,exports.VOLUME_HEIGHT_RATIO=Ze,exports.VROCIndicator=qr,exports.VWAPIndicator=gn,exports.VWMAIndicator=Ln,exports.VerticalLineTool=Pl,exports.Viewport=Se,exports.VolatilityIndexIndicator=eo,exports.VolatilityOHLCIndicator=mo,exports.VolatilityZeroTrendIndicator=ho,exports.VolumeCandleRenderer=He,exports.VolumeDeltaIndicator=ar,exports.VolumeOscillatorIndicator=Ei,exports.VolumeProfileIndicator=Gr,exports.VolumeProfileRangeTool=yu,exports.VolumeProfileRenderer=$e,exports.VolumeRenderer=Qe,exports.VortexIndicator=or,exports.WMAIndicator=Rn,exports.Watermark=Dh,exports.WebSocketAdapter=Xm,exports.WilliamsADIndicator=Ar,exports.WilliamsFractalsIndicator=vi,exports.WilliamsRIndicator=Qn,exports.XABCDPatternTool=Bu,exports.ZigZagIndicator=Dn,exports.ZoomHandler=fs,exports.alignOutput=Yt,exports.arcPoints=tf,exports.assignSessionLetters=rt,exports.axisFormat=Q,exports.barIndexToTime=e.y,exports.barIndexToX=e.b,exports.barTimeStep=e.x,exports.barTimeStepMs=e.S,exports.bracketRiskReward=Np,exports.canvasMeasure=uv,exports.cappedPixelRatio=o,exports.claimGpuContext=e.n,exports.classifyPivots=ft,exports.cleanIntervals=nn,exports.computeBarLayout=jy,exports.computeBracketDefaults=Mp,exports.computeCalendarLayout=Gb,exports.computeCounterClockLayout=gx,exports.computeDonutLayout=Wy,exports.computeHistogramLayout=mb,exports.computeMarketProfile=tt,exports.computeMatrixLayout=rx,exports.computePeriodLevels=lt,exports.computeScatterLayout=tb,exports.computeSessionProfiles=it,exports.correlationMatrix=$b,exports.counterClockPhase=hx,exports.counterClockPoints=px,exports.curvePoints=ef,exports.dayToIso=zb,exports.defaultFormat=cv,exports.detectCandlePatterns=Fa,exports.drawAxisValueLabels=ne,exports.drawIcon=Jf,exports.drawnKeys=jt,exports.fillTag=E,exports.findDominantSwing=dl,exports.findPivots=pt,exports.forEachPixelColumn=e.d,exports.forecastOutcome=kf,exports.formatTooltipTime=Fs,exports.getIntParam=L,exports.getNumberParam=I,exports.getVisibleData=Ce,exports.gpuContextsLeft=e.r,exports.hasHistogram=zt,exports.hasTrades=Om,exports.histogramBins=lb,exports.hitBar=My,exports.hitCategory=Ny,exports.hitDay=Kb,exports.hitHistogramBar=hb,exports.hitMatrixCell=ix,exports.hitSlice=Gy,exports.indicatorCategory=yo,exports.indicatorValuePrecision=D,exports.inferOrderType=Bp,exports.inputSource=Kt,exports.isDense=e.f,exports.isInWindow=zh,exports.isPriceLevelAlert=Qh,exports.isRegularSession=Bh,exports.isSeriesPalette=an,exports.isUpTone=Mt,exports.isWorkerResponse=bo,exports.labelTextColor=A,exports.layoutAxisValueLabels=te,exports.layoutGroupedTreemap=J_,exports.layoutLegend=dv,exports.layoutSquarifiedTreemap=G_,exports.layoutUniformGrid=V_,exports.lineSourceBars=Jt,exports.lineSpace=kc,exports.loadWebGL=ge,exports.loadWebGLRenderer=_e,exports.lttbDownsample=Ae,exports.lttbVisibleIndices=Me,exports.mergeSessionHours=Lh,exports.minuteOfDay=Rh,exports.nearestCounterClockPoint=vx,exports.nearestPoint=nb,exports.niceScale=av,exports.paneLogRange=Lt,exports.paneValueRange=It,exports.parseDay=Rb,exports.pastTimeStep=e.C,exports.plotColor=Ft,exports.plotLook=N,exports.plotShown=Nt,exports.priceBucketRow=e.w,exports.priceScaleText=c,exports.priceSourceBars=qt,exports.priceToY=e.T,exports.priceToYMapper=e.E,exports.rangePresetStart=ke,exports.readAlertOptions=og,exports.readableText=kb,exports.registerBuiltInDrawingTools=Nf,exports.registerBuiltInIndicators=go,exports.renderAxisValueLabels=re,exports.renderBarChart=Py,exports.renderCalendar=qb,exports.renderCounterClock=bx,exports.renderDenseBars=e.p,exports.renderDepthChart=S_,exports.renderDonut=Ky,exports.renderEquityCurve=B_,exports.renderGauge=wy,exports.renderHeatmap=Sv,exports.renderHistogram=_b,exports.renderMatrix=ax,exports.renderPlots=Bt,exports.renderScatter=rb,exports.renderSparkline=s_,exports.renderWaterfall=Wv,exports.resolveBarIndex=e.D,exports.resolveColorScale=Tb,exports.scaleColor=Eb,exports.servesTimeframe=_m,exports.setMaxWebGLCharts=e.i,exports.shownCount=_x,exports.shownOnInterval=tn,exports.sourceParam=Gt,exports.spreadLabels=k,exports.timeToX=e.O,exports.timestampToBarIndex=e.k,exports.toHeikinAshi=xt,exports.toKagi=Tt,exports.toLineBreak=wt,exports.toPointAndFigure=Et,exports.toRangeBars=Dt,exports.toRenko=St,exports.tpoLetter=nt,exports.waveLabel=$l,exports.whenGpuContextFree=e.a,exports.withResampling=hm,exports.withTickBars=Dm,exports.xToBarIndex=e.A,exports.xToTime=e.j,exports.yToPrice=e.M;
23
23
  //# sourceMappingURL=index.cjs.map