@tradecanvas/core 2.0.0-beta.3 → 2.0.0-beta.4
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/{WebGLSeriesRenderer-C1ehDGNo.cjs → WebGLSeriesRenderer-BehGeCwp.cjs} +2 -2
- package/dist/{WebGLSeriesRenderer-C1ehDGNo.cjs.map → WebGLSeriesRenderer-BehGeCwp.cjs.map} +1 -1
- package/dist/{WebGLSeriesRenderer-m_tVyYqn.js → WebGLSeriesRenderer-pW5s9XIk.js} +2 -2
- package/dist/{WebGLSeriesRenderer-m_tVyYqn.js.map → WebGLSeriesRenderer-pW5s9XIk.js.map} +1 -1
- package/dist/finance/BaseFinanceChart.d.ts +8 -1
- package/dist/finance/BaseFinanceChart.d.ts.map +1 -1
- package/dist/finance/DepthChartRenderer.d.ts +24 -1
- package/dist/finance/DepthChartRenderer.d.ts.map +1 -1
- package/dist/finance/EquityCurveRenderer.d.ts +13 -1
- package/dist/finance/EquityCurveRenderer.d.ts.map +1 -1
- package/dist/finance/FinanceCrosshair.d.ts +3 -0
- package/dist/finance/FinanceCrosshair.d.ts.map +1 -1
- package/dist/finance/HeatmapRenderer.d.ts.map +1 -1
- package/dist/finance/WaterfallRenderer.d.ts +27 -1
- package/dist/finance/WaterfallRenderer.d.ts.map +1 -1
- package/dist/finance/chartKit.d.ts +36 -0
- package/dist/finance/chartKit.d.ts.map +1 -1
- package/dist/finance/index.d.ts +6 -3
- package/dist/finance/index.d.ts.map +1 -1
- package/dist/{gpuContexts-CrF09Ngz.cjs → gpuContexts-WwFdTWTn.cjs} +2 -2
- package/dist/{gpuContexts-CrF09Ngz.cjs.map → gpuContexts-WwFdTWTn.cjs.map} +1 -1
- package/dist/{gpuContexts-D9JHR3h-.js → gpuContexts-vx7rTajy.js} +2 -2
- package/dist/{gpuContexts-D9JHR3h-.js.map → gpuContexts-vx7rTajy.js.map} +1 -1
- package/dist/index.cjs +8 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +4914 -4953
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./gpuContexts-CrF09Ngz.cjs`);let t=require(`@tradecanvas/commons`);var n=2;function r(e=2){let t=typeof window<`u`&&window.devicePixelRatio||1;return e>0?Math.min(t,e):t}function i(e,t,n){let r=t/2+.5,i=(e,n)=>Number.isInteger(e)&&e>0&&Math.abs(e-n*t)<=r;return n&&i(n.width,e.width)&&i(n.height,e.height)?{width:n.width,height:n.height,exact:!0}:{width:Math.round(e.width*t),height:Math.round(e.height*t),exact:!1}}function a(e,t,n,r){let a=i(t,n,r);(e.width!==a.width||e.height!==a.height)&&(e.width=a.width,e.height=a.height),e.style.width=a.exact?`100%`:`${t.width}px`,e.style.height=a.exact?`100%`:`${t.height}px`}var o=class{observer=null;callback=null;currentDpr=1;resizeScheduled=!1;deviceChanged=!1;cachedSize;deviceSize=null;stopWatchingRatio=null;constructor(e,t=2){this.container=e,this.maxPixelRatio=t,this.currentDpr=r(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}getDeviceSize(){return this.deviceSize}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(e=>{let t=e?.[e.length-1]?.devicePixelContentBoxSize?.[0],n=t?{width:t.inlineSize,height:t.blockSize}:null;(n?.width!==this.deviceSize?.width||n?.height!==this.deviceSize?.height)&&(this.deviceSize=n,this.deviceChanged=!0),!this.resizeScheduled&&(this.resizeScheduled=!0,requestAnimationFrame(()=>{this.resizeScheduled=!1,this.update(!1)}))});try{this.observer.observe(this.container,{box:`device-pixel-content-box`})}catch{this.observer.observe(this.container)}this.watchRatio()}update(e){let t=r(this.maxPixelRatio),n=this.container.clientWidth,i=this.container.clientHeight,a=this.deviceChanged||t!==this.currentDpr||n!==this.cachedSize.width||i!==this.cachedSize.height;this.deviceChanged=!1,this.currentDpr=t,this.cachedSize={width:n,height:i},(a||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 s(e){e.style.fontFeatureSettings=`normal`}var c=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`,s(this.canvas),this.ctx=this.canvas.getContext(`2d`),e.appendChild(this.canvas)}resize(e,t,n=null){this.dpr=t,a(this.canvas,e,t,n),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()}},l=class{scene=null;top=null;back=null;gpuCanvas=null;size=null;dpr=1;device=null;constructor(e){this.container=e}createLayers(){this.destroy(),this.scene=new c(this.container,0),this.top=new c(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 c(this.container,0),this.container.insertBefore(this.back.canvas,this.gpuCanvas),this.size&&this.back.resize(this.size,this.dpr,this.device)),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,n=null){this.size=e,this.dpr=t,this.device=n,this.scene?.resize(e,t,n),this.top?.resize(e,t,n),this.back?.resize(e,t,n),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;n&&a(n,e,t,this.device)}},u=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}})}};function d(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 f(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 p=1e-9;function m(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))<=p*Math.max(1,Math.abs(e*t))))return n}return t}function h(e,t,n){return Math.floor(t/n+1e-9)-Math.ceil(e/n-1e-9)+1}function g(e,t){if(!t||!(t>0)||e>=1)return e;let n=t;for(;n<e;)n*=2;return n}var _=24,v=200;function y(e){return Math.max(2,Math.min(_,Math.round(e/56)+1))}function b(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 x(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 S(e){return e<1?Math.ceil(-Math.log10(e))+1:+(e<10)}function C(e,n,r){let i=(0,t.computeTickStep)(e,n,y(r));if(!(i>0)||!(r>0))return i;let a=n-e;for(let e=0;e<8&&i/a*r<30;e++)i=x(i);return i}function w(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<v;e++){let t=e*n;r.push(Math.abs(t)<n*1e-9?0:t)}return r}var T=12,E=14,D=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=C(n,r,e.chartRect.height),a=(0,t.autoPricePrecision)(n,r);if(e.priceUnit)return{step:g(i,e.priceUnit),precision:this.precision??a};let o=f(i,this.precision,this.tick);return h(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):w(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 w(c,l,C(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.k(t),o=Math.exp(-i*56),s=[],c=f(b(r*(1-o)),this.precision,this.tick),l=Math.floor(r/c+1e-9)*c,u=null;for(let e=0;e<200&&l>=n&&l>0;e++){let e=a(l);(u===null||Math.abs(e-u)>=30)&&(s.push(l),u=e);let t=l*o;if(c=f(b(Math.min(l-t,t)),this.precision,this.tick),!(c>0))break;let n=Math.round(t/c)*c;n>=l&&(n-=c),l=n}return s.length===0?w(n,r,this.scale(t).step):s.reverse()}labelText(e,t){return d(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,c=i===`left`,l=c?o.x:o.x+o.width;if(s.max-s.min<=0)return;let u=e.k(n);t.strokeStyle=r.style?.axis.price.line??r.axisLine,t.lineWidth=1,t.globalAlpha=.65,t.beginPath(),e.x(t,l+.5,o.y,o.y+o.height),t.stroke(),t.globalAlpha=1;let{precision:f}=this.scale(n),p=this.ticks(n),h=n.scaleMode??(n.logScale?`logarithmic`:`regular`),g=h===`regular`||h===`logarithmic`?m(p,f):f,_=`500 ${r.font.sizeSmall}px ${r.font.family}`,v=[],y=c?null:this.reservedPrice?.()??null,b=y===null?null:e.O(y,n),x=r.font.sizeSmall/2,S=o.y+x,C=o.y+o.height-x;for(let e of p){let t=u(e);t<S||t>C||b!==null&&Math.abs(t-b)<T||a.some(e=>Math.abs(t-e)<E)||v.push({y:t,text:d(e,n,g,this.locale)})}t.font=_,t.textBaseline=`middle`,t.textAlign=c?`right`:`left`,t.strokeStyle=r.style?.axis.price.line??r.axisLine,t.globalAlpha=.45,t.beginPath();let w=c?-1:1;for(let{y:n}of v)e.y(t,l+w,l+4*w,n+.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,l+8*w,e);c||(this.rows=v.map(e=>e.y))}};function ee(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 O(e,t,n,r,i,a){let o=ee(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 k(t,n,r,i,a,o){let s=e.g(t,n,r,i,a);if(!(ee(o,s.w,s.h)>0)){t.fillRect(s.x,s.y,s.w,s.h);return}O(t,s.x,s.y,s.w,s.h,o),t.fill()}function A(e){let t=Math.abs(e);return t>=1e3?1:t>=1?2:t>=.01?4:6}var te=16;function ne(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 re(e){let t=ie(e);if(!t)return`#ffffff`;let[n,r,i]=t;return(.299*n+.587*r+.114*i)/255>.62?`#10131a`:`#ffffff`}function ie(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 ae(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=ne(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 oe(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,k(e,n+1,Math.round(a.y-8),t,16,i),e.fillStyle=re(a.color),e.fillText(a.text,n+5,Math.round(a.y))}e.restore()}}function se(e,t,n,r,i,a){oe(e,ae(t,i),n,r,a)}function ce(e){return{plot:e,plotText:null,panes:new Map}}function le(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 ue=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.k(r);e.b(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 de(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 fe=16,pe=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,k(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=re(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`)}`}};function me(e,t,n){let r=e.map(e=>e.y);if(e.length===0)return r;let i=t!==null&&e[t]?t:he(e),a=e.map((e,t)=>t).filter(e=>e!==i),o=e[i].y,s=a.filter(t=>e[t].y<=o).sort((t,n)=>e[n].y-e[t].y),c=a.filter(t=>e[t].y>o).sort((t,n)=>e[t].y-e[n].y),l=r[i]-e[i].above;for(let t of s)r[t]+e[t].below>l&&(r[t]=l-e[t].below),l=r[t]-e[t].above;let u=r[i]+e[i].below;for(let t of c)r[t]-e[t].above<u&&(r[t]=u+e[t].above),u=r[t]+e[t].below;return n?r.map((t,r)=>t!==e[r].y&&(t-e[r].above<n.top||t+e[r].below>n.bottom)?NaN:t):r}function he(e){let t=e.map(e=>e.y),n=(Math.min(...t)+Math.max(...t))/2,r=0;return t.forEach((e,i)=>{Math.abs(e-n)<Math.abs(t[r]-n)&&(r=i)}),r}var ge=20,_e=3,ve=8,ye=14,be=10,xe=8,Se=`#000`,Ce=2,we=4.5;function Te(e,n){let r=n?.priceLimits??(n?.background&&Ee(n.background)?t.LIGHT_PRICE_LIMITS:t.DARK_PRICE_LIMITS),i=e=>n?.background&&n.text?ke(e,n.background,n.text):e;return[{price:e.ceiling,color:i(e.colors?.ceiling??r.ceiling),label:`CE`},{price:e.floor,color:i(e.colors?.floor??r.floor),label:`FL`},{price:e.reference,color:i(e.colors?.reference??r.reference),label:`REF`}]}function Ee(e){return(0,t.inkOn)(e,`#000000`,`#ffffff`)===`#000000`}var De=new Map,Oe=64;function ke(e,n,r){let i=`${e}|${n}|${r}`,a=De.get(i);return a===void 0&&(De.size>=Oe&&De.clear(),a=(0,t.readableOn)(e,n,r,we),De.set(i,a)),a}function Ae(e,t,n){if(!e)return null;let r=e.region(t,{text:!1});return n.every(e=>r.step(e))?e:null}var je=20,Me=20,Ne=class{layerManager;renderLoop;dprManager;renderCtx=null;sceneLayer;topLayer;gpu=null;lostGpu=null;onGpuLost=null;onGpuRestored=null;onContainerResize=null;constructor(e,t){this.layerManager=new l(e),this.renderLoop=new u,this.dprManager=new o(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.dprManager.getDeviceSize()),this.renderLoop.markAllDirty(),this.onContainerResize?.(e)});let n=this.dprManager.getContainerSize(),r=this.dprManager.getDpr();this.layerManager.resize(n,r,this.dprManager.getDeviceSize())}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 ue,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=ce(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.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);let m=this.axisTagPlan(n);n.priceLimits&&this.renderPriceLimits(o,r,i,n.priceLimits,n.formatPrice,m.limits),n.tradeZoneManager?.render(o,r,i),n.drawingRenderer?.render(o,r,i),n.priceLines?.render(o,r,i,a),n.currentPriceLine?.renderLine(o,r,i),n.tradingRenderer?.render(o,r,i),n.signalMarkerManager?.render(o,r,i),n.alertManager?.render(o,r,i);let h=m.fixed,g=n.indicatorValueLabels===!1?[]:this.overlayValueTags(n,h);n.priceAxis?.render(o,r,i,`right`,[...h.map(e=>e.y),...g.map(e=>e.y)]),oe(o,g,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,m.trading),n.priceLines?.renderAxisTags(o,r,i,a,m.quote),n.currentPriceLine?.renderTag(o,r,i),n.timeAxis?.render(o,r,i,a,n.timeAxisY),this.renderPanelAxes(o,n),this.renderDrawingSpans(o,n)}renderDrawingSpans(e,t){if(t.crosshairHandler?.beginSpans?.(),!(t.drawingAxisSpans===!1||!t.drawingRenderer||!t.crosshairHandler))for(let n of t.drawingRenderer.axisSpans(t.viewport))t.crosshairHandler.renderSpan(e,n,t.viewport,t.theme,t.data,t.timeAxisY)}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?Ae(t.recorder?.(l,r)??null,o.chartRect,u):null,p=u.length>0&&!f,m=t.recorder?.(l,r)??null,h=m?le(m,o.chartRect,i,a):ce(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 ue,volume:y,background:v,under:f,recorded:m,seriesRevision:n.seriesRevision}),x=b.recorded?h:ce(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.drawingRenderer?.renderHover(a,n,r),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),this.renderLegend(a,t),t.renderOverlayPlugins?.(a,`ui`),this.renderPanelHoverValues(a,t)}renderLegend(e,t){if(!t.chartLegend)return;let{viewport:n,theme:r,data:i}=t,a=t.tradingRenderer?.tagRects()??[];if(a.length===0){t.chartLegend.render(e,n,r,i);return}let{x:o,y:s,width:c,height:l}=n.chartRect;e.save();try{for(let t of a)e.beginPath(),e.rect(o,s,c,l),e.rect(t.x,t.y,t.width,t.height),e.clip(`evenodd`);t.chartLegend.render(e,n,r,i)}finally{e.restore()}}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+ge,width:n.width,height:n.height-ge},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(t,n,r,i){let{theme:a}=n,o=n.indicatorEngine;if(!o||r.length===0)return;let s=`10px ${a.font.family}`,c=this.panelDescriptors(o),l=new Map(n.panels.map(e=>[e.instanceId,e.style]));for(let o of r){let{rect:r,inner:u}=o,d=i.panes.get(o.id),f=l.get(o.id);t.save(),t.beginPath(),t.rect(r.x,r.y,r.width,r.height),t.clip(),d?.background||o.background(t),t.fillStyle=f?.separator??a.style?.panes.separator??a.axisLine;let p=e.v(t,r.y+_e/2,_e);t.fillRect(r.x,p.y-p.width/2,r.width,p.width),t.fillStyle=a.style?.panes.title??a.textSecondary,t.font=s,t.textBaseline=`top`,t.textAlign=`left`;let m=c.get(o.id);m&&n.paneTitles!==!1&&t.fillText(m.descriptor.name,r.x+6,r.y+6),t.save(),t.beginPath(),t.rect(u.x,u.y,u.width,u.height),t.clip(),d?.text?.drawText(t);for(let e of d?d.rest:o.steps)e(t);t.restore(),t.restore()}}axisTagPlan(t){let{viewport:n,data:r}=t,{chartRect:i}=n,a=e=>e>=i.y&&e<=i.y+i.height,o=[],s=t.currentPriceLine?.isVisible()&&t.theme.style?.lastPrice.visible!==!1?t.currentPriceLine.getPrice():null;if(s!=null&&a(e.O(s,n))){let i=t.barCountdown?.isShown(r)?16:0;o.push({y:e.O(s,n),above:be,below:be+i,source:`last`,key:0})}for(let i of t.priceLines?.levels(r,n)??[]){let t=e.O(i.price,n);a(t)&&o.push({y:t,above:xe,below:xe,source:`quote`,key:i.kind})}(t.priceLimits?Te(t.priceLimits):[]).forEach(({price:t},r)=>{let i=e.O(t,n);a(i)&&o.push({y:i,above:ye/2,below:ye/2,source:`limit`,key:r})});let c=t.alignAxisLabels!==!1;c&&(t.tradingRenderer?.axisBadgeLines(n,t.theme)??[]).forEach((e,t)=>{o.push({y:e,above:16/2,below:16/2,source:`trading`,key:t})});let l=o.findIndex(e=>e.source===`last`),u={top:i.y,bottom:i.y+i.height},d=c?me(o,l>=0?l:null,u):o.map(e=>e.y),f={fixed:[],quote:new Map,limits:[],trading:c?[]:void 0};if(o.forEach((e,t)=>{Number.isNaN(d[t])||f.fixed.push({y:d[t]+(e.below-e.above)/2,half:(e.above+e.below)/2}),e.source===`quote`?f.quote.set(e.key,d[t]):e.source===`limit`?f.limits[e.key]=d[t]:e.source===`trading`&&(f.trading[e.key]=d[t])}),!c)for(let e of t.tradingRenderer?.axisTagYs(n,t.theme)??[])a(e)&&f.fixed.push({y:e,half:16/2});return f}overlayValueTags(n,r){let i=n.indicatorEngine?.getLatestOverlayValues();if(!i?.length)return[];let{viewport:a}=n,{chartRect:o}=a,s=n.numberLocale??`en-US`,c=(a.scaleMode===`percentage`||a.scaleMode===`indexedTo100`)&&a.scaleBaseline?e=>d(e,a,2,s):n.formatPrice??(e=>(0,t.formatPrice)(e,2,s));return ae(i.map(t=>({y:e.O(t.value,a),text:c(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`;se(n,a.map(n=>({y:e.O(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.O(i,r))+.5;e.y(t,a.x,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 c=s.viewport,l=s.rect,{min:u,max:f}=c.priceRange;if(f-u<=0||l.height<=0||c.chartRect.height<ve)continue;let p=l.x+l.width,m=c.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(),e.x(n,p+.5,l.y,l.y+l.height),n.stroke();let _=C(u,f,m.height),v=S(_);n.font=o,n.textBaseline=`middle`,n.textAlign=`left`;for(let t of w(u,f,_)){let r=e.O(t,c);r<m.y||r>m.y+m.height||(n.strokeStyle=h,n.beginPath(),e.y(n,p,p+4,Math.round(r)+.5),n.stroke(),n.fillStyle=g,n.fillText(d(t,c,v,a),p+6,r))}let y=r.indicatorValueLabels===!1?null:[s.instanceId,...s.members??[]].flatMap(e=>r.indicatorEngine?.getLatestValues(e)??[]);y?.length&&se(n,y.map(n=>({y:e.O(n.value,c),text:c.scaleMode===`percentage`&&c.scaleBaseline?d(n.value,c,2,a):(0,t.formatPrice)(n.value,A(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||!r.crosshairHandler?.drawsLines())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<ve)continue;let l=e.N(i.x,c),u=e.C(Math.max(0,Math.min((r.data?.length??1)-1,Math.round(l))),c),d=de(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._(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.v(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:c}=r,l=r.numberLocale??`en-US`,u=`${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<ve)continue;let v=h.x+h.width,y=S(C(g,_,m.chartRect.height));if(r.crosshairHandler?.getMode()!==`hidden`&&i.x>=h.x&&i.x<=h.x+h.width&&i.y>=h.y&&i.y<=h.y+h.height){let r=d(e.F(i.y,m),m,y,l);n.font=`bold ${o.font.sizeSmall}px ${o.font.family}`;let a=n.measureText(r).width,c=Math.min(a+je,(s.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2),u=de(o);n.fillStyle=u.labelBackground,k(n,v+1,i.y-Me/2,c,Me,o),n.fillStyle=u.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 b=Math.max(0,Math.min((c?.length??1)-1,Math.round(e.N(i.x,m)))),x=a.peekOutput(p.instanceId),w=x?.series&&b<x.series.length?x.series[b]:null;if(!w)continue;let T=f?.get(p.instanceId),E=T?.descriptor.plots,D=[];if(E)for(let e of E){let t=w[e.key];t!==void 0&&Number.isFinite(t)&&D.push(`${e.title} ${d(t,m,y,l)}`)}else for(let e in w){let t=w[e];t!==void 0&&D.push(`${e}: ${t.toFixed(y)}`)}if(D.length===0)continue;n.font=u;let ee=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+ee,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,o,s=[]){let{chartRect:c}=r,l=o??(e=>(0,t.priceTagText)(e,r,r.pricePrecision??Ce)),u=`bold 9px ${i.font.family}`,d=`10px ${i.font.family}`;Te(a,i).forEach(({price:a,color:o,label:f},p)=>{let m=e.O(a,r);if(m<c.y||m>c.y+c.height)return;n.setLineDash([8,4]),n.strokeStyle=o,n.lineWidth=1,n.beginPath(),e.y(n,c.x,c.x+c.width,Math.round(m)+.5),n.stroke(),n.setLineDash([]),n.font=u,n.fillStyle=o,n.textBaseline=`bottom`,n.textAlign=`left`,n.fillText(`${f} ${l(a)}`,c.x+4,m-2);let h=s[p]??m;if(Number.isNaN(h))return;let g=c.x+c.width+1;n.fillStyle=o,k(n,g,h-ye/2,(r.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,ye,i),n.fillStyle=i.background&&i.text?(0,t.inkOn)(o,i.background,i.text):Se,n.font=d,n.textBaseline=`middle`,n.textAlign=`left`,n.fillText(l(a),g+4,h)})}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 Fe(t){let n=e.n();if(!n)return{gpu:null,reason:`limit`};let r;try{r=await Promise.resolve().then(()=>require(`./WebGLSeriesRenderer-C1ehDGNo.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 Ie(e){return(await Fe(e)).gpu}var Le=.25,Re=.02,ze=1/t.PHI,Be=t.PHI**4,Ve=t.CHART_SPACING[t.DEFAULT_CHART_DENSITY].priceMargin,He=.2,Ue=class{state;priceAxisWidth=t.PRICE_AXIS_WIDTH;stateCache=null;dataLength=0;margins={top:Ve,bottom:Ve};minBarWidth;maxBarWidth;rightMarginBars;freePan=!0;minVisibleBars=3;minBarUnit=Le;barLayout=`classic`;constructor(e,n,r=2,i=30,a=t.CHART_SPACING[t.DEFAULT_CHART_DENSITY].rightMargin){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,pricePrecision:this.state.pricePrecision,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()}setPricePrecision(e){this.state.pricePrecision=e!==null&&Number.isInteger(e)&&e>=0?e:void 0,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){if(e===this.rightMarginBars)return;let t=this.dataLength>0&&this.isAtEnd();this.rightMarginBars=e,t&&(this.state.offset=this.endOffset(),this.invalidate())}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()}setBarLayout(e){let t=e===`golden`?`golden`:`classic`;if(t===this.barLayout)return;let n=this.dataLength>0&&this.isAtEnd();this.barLayout=t,this.applyUnit(this.dataLength===0?this.openingUnit():this.state.barWidth+this.state.barSpacing),this.clampUnit(),n&&(this.state.offset=this.endOffset(),this.invalidate()),this.clampOffset(),this.updateVisibleRange()}getBarLayout(){return this.barLayout}openingUnit(){return this.barLayout===`golden`?Be:t.DEFAULT_BAR_WIDTH+t.DEFAULT_BAR_SPACING}floorUnit(){return this.barLayout===`golden`?this.minBarWidth/ze: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(Re,Math.min(e,this.floorUnit())):Le,this.clampUnit(),this.clampOffset(),this.updateVisibleRange(),this.invalidate()}getMinBarUnit(){return this.minBarUnit}maxUnit(){return this.barLayout===`golden`?this.maxBarWidth/ze:this.maxBarWidth+t.DEFAULT_BAR_SPACING}applyUnit(e){let n=this.floorUnit();if(this.barLayout===`golden`)this.state.barWidth=e*ze,this.state.barSpacing=e-this.state.barWidth;else 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<He||(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)(this.barLayout===`classic`&&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 We(e,n){return(0,t.sliceVisibleData)(e,n.visibleRange.from,n.visibleRange.to)}var Ge=[`1D`,`5D`,`1M`,`3M`,`6M`,`YTD`,`1Y`,`5Y`,`All`],Ke=864e5,qe=6e4,Je={"1M":1,"3M":3,"6M":6,"1Y":12,"5Y":60};function Ye(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 Xe(e,n,r=0){if(e===`All`)return null;if(e===`1D`)return n-Ke;if(e===`5D`)return n-5*Ke;let i=n+(0,t.offsetAt)(r,n)*qe;return e===`YTD`?(0,t.wallToUtc)(Date.UTC(new Date(i).getUTCFullYear(),0,1),r):(0,t.wallToUtc)(Ye(i,-(Je[e]??0)),r)}function Ze(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 Qe=64;function $e(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(Qe,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=Ze(s,c,e=>i(a+e));for(let e=0;e<l.length;e++)l[e]+=a;return l}var et=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.k(r);t.beginPath(),t.strokeStyle=i.lineColor,t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`round`;let f=$e(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()}},tt=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.k(r),f=d(l),p=$e(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()}},nt=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.k(r);e.b(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)})}},rt=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.k(r);e.b(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])}})}},it=32/255,at=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.k(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*=it,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*=it,t.fillStyle=i.candleDown,t.fill(T),t.restore();let E=new Path2D,D=new Path2D,ee=null;for(let e=1;e<=y;e++){let t=r.invertScale?v[e]>=h:v[e]<=h,n=t?E:D;t!==ee&&n.moveTo(_[e-1],v[e-1]),ee=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 O=new Path2D;O.moveTo(g.x,h),O.lineTo(g.x+g.width,h),t.stroke(O),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}},ot=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.k(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)}},st=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.k(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()}},ct=3,lt=.8,ut=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.k(r),_=Math.abs(this.boxSize*m);if(_<ct){this.renderSolid(t,n,a,o,h,g,Math.max(1,s*lt),i);return}let v=Math.min(c*lt,_*lt)*.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));for(let e=c;e<=l;e++){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)}renderSolid(e,t,n,r,i,a,o,s){for(let c=Math.max(0,n);c<=r&&c<t.length;c++){let n=t[c],r=a(n.high),l=a(n.low);e.fillStyle=n.close>=n.open?s.candleUp:s.candleDown,e.fillRect(i(c)-o/2,Math.min(r,l),o,Math.max(1,Math.abs(l-r)))}}},dt=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.k(r);e.b(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)})}},ft=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.k(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=pt(i.candleUp,.55),t.fill(p),t.fillStyle=pt(i.candleDown,.55),t.fill(m),t.lineWidth=1,t.strokeStyle=i.candleUpWick,t.stroke(h),t.strokeStyle=i.candleDownWick,t.stroke(g)}};function pt(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 mt=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.k(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()}},ht=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.k(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()}},gt=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.k(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)}},_t=28,vt=3,yt=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.k(i),p=Math.max(1,Math.round(i.barWidth*.6)),m=i.barWidth>=_t,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-vt),n.textBaseline=`top`,n.fillText(g(c?t.low:t.high),i,s+vt)}}},bt=t.PHI**-4.5,xt=class{visible=!0;heightRatio=bt;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.b(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)})}},St=.32;function Ct(e){return Number.isFinite(e)?St*Math.min(1,Math.max(0,e)):St}var wt=class{visible=!1;buckets=48;widthRatio=.18;opacity=St;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.k(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.D(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()}},Tt={session:`1d`,week:`1w`,month:`1M`},Et=6e4,Dt=864e5,Ot={},kt=1.5;function At(e){return e===`session`||e===`week`||e===`month`}function jt(e,n,r){let i=At(n)?Tt[n]:n,a=(0,t.barTimeUnit)(e),o=r&&!(0,t.isUtcTimeZone)(r)&&(0,t.timeframeFollowsDays)(i)&&(0,t.isValidTimeZone)(r)?r:null,s=o===null?Ot:{timeZone:o},c=o!==null&&(0,t.barsAreDaily)(e)===!0,l=(0,t.timeframeToMs)(i),u=(Number.isFinite(l)?l:Et)*kt,d=NaN,f=NaN,p=NaN,m=!1;return e=>{let n=e*a,r=c&&n%Dt===0;if(n>=d&&n<f&&r===m)return p;m=r;let l=r?Ot:s;return d=(0,t.timeframeBucketStart)(n,i,l),f=(0,t.timeframeBucketStart)(d+u,i,l),p=o===null||r?d:(0,t.timeframeBucketStart)(n+(0,t.zoneOffsetMinutes)(o,n)*Et,i),p}}function Mt(e,t,n){let r=e[t]?.[n];return e[t-1]?.[n]!==r&&e[t+1]?.[n]!==r}function Nt(e,t,n,r=`session`){return e[t]?.[r]===e[n]?.[r]?!1:!(Mt(e,t,r)&&Mt(e,n,r))}function Pt(e,t){return e<0?0:e>t?t:e}function Ft(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=Pt(Math.floor((e-t)/o),i-1),l=Pt(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 It(e){let t=(e%52+52)%52;return t<26?String.fromCharCode(65+t):String.fromCharCode(97+t-26)}function Lt(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 Rt(e,t,n,r={},i){if(e.length===0||n-t<=0)return[];let a=[],o=jt(e,`session`,i),s=0,c=o(e[0].time),l=(i,o,s)=>{let c=Ft(e.slice(i,o+1),t,n,r);c&&a.push({startIndex:i,endIndex:o,startTime:s,profile:c})};for(let t=1;t<e.length;t++){let n=o(e[t].time);n!==c&&(l(s,t-1,c),s=t,c=n)}return l(s,e.length-1,c),a}var zt=class{visible=!1;buckets=48;widthRatio=.18;opacity=.32;valueAreaPct=.7;highlightPoC=!0;showStats=!0;splitBySession=!1;letters=!1;lastStats=null;exchangeZone=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}getConfig(){let{buckets:e,widthRatio:t,opacity:n,valueAreaPct:r,highlightPoC:i,showStats:a,splitBySession:o,letters:s}=this;return{buckets:e,widthRatio:t,opacity:n,valueAreaPct:r,highlightPoC:i,showStats:a,splitBySession:o,letters:s}}setExchangeTimeZone(e){this.exchangeZone=e}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=Ft(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.k(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.D(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,r,i),t.restore()}renderSplit(t,n,r,i,a){let{chartRect:o,priceRange:s}=i,c=Rt(n,s.min,s.max,{buckets:this.buckets,valueAreaPct:this.valueAreaPct},this.exchangeZone);if(c.length===0)return;let l=e.k(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.C(r+d.startIndex,i)-u,h=e.C(r+d.endIndex,i)+u,g=Math.max(2,h-m),_=1/c.maxCount,v=this.letters&&p>=7,y=v?Lt(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.D(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(It(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.D(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,n,r,i,a,o,s,c){let l=s.pricePrecision??Bt(i),u=e=>(0,t.priceTagText)(e,s,l),d=[[`POC`,u(i),c.text],[`VAH`,u(a),c.candleUp],[`VAL`,u(o),c.candleUp]];e.globalAlpha=1,e.font=`600 10px ${c.font.family}`,e.textBaseline=`middle`;let f=0;for(let[,t]of d)f=Math.max(f,e.measureText(t).width);let p=38+f,m=6+d.length*14;e.fillStyle=c.background,e.globalAlpha=.82,Vt(e,n,r,p,m,4),e.fill(),e.globalAlpha=1,d.forEach(([t,i,a],o)=>{let s=r+6/2+14/2+o*14;e.fillStyle=a,e.textAlign=`left`,e.fillText(t,n+6,s),e.fillStyle=c.text,e.textAlign=`right`,e.fillText(i,n+p-6,s)}),e.textAlign=`left`}};function Bt(e){let t=Math.abs(e);return t>=1e3?2:t>=1?4:6}function Vt(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 Ht(e,t,n){let r=jt(e,t===`day`?`session`:`week`,n),i=[];for(let t of e){let e=r(t.time),n=i[i.length-1];n&&n.key===e?(n.high=Math.max(n.high,t.high),n.low=Math.min(n.low,t.low),n.close=t.close):i.push({key:e,open:t.open,high:t.high,low:t.low,close:t.close})}return i}function Ut(e,t=`day`,n){let r=Ht(e,t,n);if(r.length<2)return[];let i=r[r.length-2],a=r[r.length-1],o=t===`day`?`D`:`W`;return[{id:`p${o}h`,label:`P${o}H`,price:i.high},{id:`p${o}c`,label:`P${o}C`,price:i.close},{id:`p${o}l`,label:`P${o}L`,price:i.low},{id:`open`,label:t===`day`?`Day Open`:`Week Open`,price:a.open}]}var Wt=class{visible=!1;period=`day`;exchangeZone=null;setVisible(e){this.visible=e}isVisible(){return this.visible}setPeriod(e){this.period=e}getPeriod(){return this.period}setExchangeTimeZone(e){this.exchangeZone=e}render(t,n,r,i){if(!this.visible||n.length===0)return;let a=Ut(n,this.period,this.exchangeZone);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.O(n.price,r);if(a<s||a>c)continue;let l=Gt(n,i);t.strokeStyle=l,t.globalAlpha=.7,t.lineWidth=1,t.setLineDash([5,4]),t.beginPath(),e.y(t,o.x,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,k(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 Gt(e,t){return e.id.endsWith(`h`)?t.candleUp:e.id.endsWith(`l`)?t.candleDown:t.textSecondary}function Kt(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 qt(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 Jt=4,Yt=10,Xt=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}getConfig(){return{left:this.left,right:this.right,showLabels:this.showLabels,structureLabels:this.structureLabels}}render(t,n,r,i){if(!this.visible||n.length===0)return;let a=qt(n,this.left,this.right);if(a.length===0)return;let o=this.structureLabels?Kt(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.C(n.index,r),o=e.O(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?Zt(n.price,r):null;p&&(t.textBaseline=d?`bottom`:`top`,t.fillText(p,a,d?f-5-1:f+5+1))}t.restore()}};function Zt(e,n){return(0,t.priceTagText)(e,n,n.pricePrecision??Qt(e))}function Qt(e){let t=Math.abs(e);return t>=1?2:t===0?Jt-1:Math.min(Yt,Jt-1-Math.floor(Math.log10(t)))}function $t(e){if(e.length<2)return 0;let t=e.map(e=>e.price).sort((e,t)=>e-t),n=[];for(let e=1;e<t.length;e++){let r=t[e]-t[e-1];r>0&&n.push(r)}return n.length===0?0:(n.sort((e,t)=>e-t),n[Math.floor(n.length/2)])}var en=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})),bidStep:$t(t.bids),askStep:$t(t.asks)},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}getCapacity(){return this.capacity}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}},tn=class{buffer=new en(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)}getConfig(){return{opacity:this.opacity,capacity:this.buffer.getCapacity()}}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.j(a.time,n);if(i<l-c||i>u+c)continue;let s=i-c/2;this.drawSide(t,a.bids,a.bidStep??$t(a.bids),r.candleUp,s,c,n,o,d,f),this.drawSide(t,a.asks,a.askStep??$t(a.asks),r.candleDown,s,c,n,o,d,f)}t.restore()}drawSide(t,n,r,i,a,o,s,c,l,u){if(n.length===0)return;let d=nn(Math.min(n[0].price,n[n.length-1].price),r,s);t.fillStyle=i;for(let r of n){let n=e.O(r.price,s);n<l-d||n>u+d||(t.globalAlpha=Math.min(1,Math.sqrt(r.volume*c))*this.opacity,t.fillRect(a,n-d/2,o,d))}t.globalAlpha=1}};function nn(t,n,r){if(!(n>0))return 3;let i=Math.abs(e.O(t,r)-e.O(t+n,r));return Math.max(2,Math.min(i,12))}var rn=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}lastCloseAt(e,n,r){let i=this.closeAt(e,n,r);if(i!==void 0)return{close:i,stale:!1};let a=this.series.get(e);if(!(!a||(0,t.normalizeBarTime)(n,r)<a.times[0]))return{close:a.bars[a.bars.length-1].close,stale:!0}}},an=11,on={mark:11,label:12,letter:13,text:14},sn={mark:0,label:1,letter:2,text:3},cn=12,ln=.12,un=`#131416`,dn=`#1fa874`,fn=`#e8505b`,pn=`#e6e3dc`;function mn(e){let n=e?.font,r=n?.sizeSmall??an,i=e=>Math.max(on[e],r+sn[e]),a=e?.background??un;return{sizes:{mark:i(`mark`),label:i(`label`),letter:i(`letter`),text:i(`text`)},figures:n?.family||t.DEFAULT_FONT_FAMILY,prose:n?.textFamily||t.SANS_FONT_FAMILY,background:a,ink:e?.text??pn,handleFill:e?.style?.drawings?.handle??a,scale:Math.max(1,r/an),rise:e?.style?.trading?.profit??dn,fall:e?.style?.trading?.loss??fn}}var hn=mn(null),gn=null,_n=!1;function vn(){_n=!0,gn=null}function yn(e,t,n,r){_n&&(gn=gn?{x0:Math.min(gn.x0,e),y0:Math.min(gn.y0,t),x1:Math.max(gn.x1,e+n),y1:Math.max(gn.y1,t+r)}:{x0:e,y0:t,x1:e+n,y1:t+r})}function bn(){_n=!1;let e=gn;return gn=null,e?{x:e.x0,y:e.y0,width:e.x1-e.x0,height:e.y1-e.y0}:null}var xn=null;function Sn(e){xn=e}var Cn=4;function wn(e,t,n,r){if(!xn)return{left:e,top:t};let i=xn.x+xn.width-Cn-n,a=xn.y+xn.height-Cn-r;return{left:Math.max(xn.x+Cn,Math.min(e,i)),top:Math.max(xn.y+Cn,Math.min(t,a))}}function Tn(e){hn=mn(e)}function j(){return hn}function M(e,t={}){return`${t.weight?`${t.weight} `:``}${hn.sizes[e]}px ${t.prose?hn.prose:hn.figures}`}function En(e,t=`text`){let n=e.fontSize;return n&&n!==cn?n:hn.sizes[t]}function Dn(e){return On+kn*Math.max(1,Number.isFinite(e)?e:1)}var On=9,kn=3,An=new Map,jn=64,Mn=4.5;function N(e){let n=`${e}|${hn.background}|${hn.ink}`,r=An.get(n);return r===void 0&&(An.size>=jn&&An.clear(),r=(0,t.readableOn)(e,hn.background,hn.ink,Mn),An.set(n,r)),r}function Nn(e,t=hn.scale){return Math.min(In,Pn+Fn*(Math.max(1,Number.isFinite(e)?e:1)-1))*t}var Pn=4.5,Fn=.75,In=8;function Ln(e,t){let n=Math.max(1,t);switch(e){case`dashed`:return[Math.max(5,3*n),Math.max(4,2*n)];case`dotted`:return[0,Math.max(3,2.5*n)];case`guide`:return[3,3];default:return[]}}function P(e,n=ln){return(0,t.ownFillColor)(e)??(0,t.withAlpha)(e.color,n)}function Rn(e){return(0,t.ownFillColor)(e)!==void 0}function zn(e){return(0,t.inkOn)(e,`#0b0d10`,`#ffffff`)}var Bn=`rgba(12, 16, 22, 0.85)`,Vn=Bn;function Hn(e){Vn=e?.background??Bn,Tn(e)}function Un(){return j().handleFill}function F(e,t,n,r,i=Vn){e.save(),e.lineJoin=`round`,e.lineWidth=Wn,e.strokeStyle=i,e.setLineDash([]),e.strokeText(t,n,r),e.restore(),e.fillText(t,n,r)}var Wn=4,Gn=()=>j().sizes.label,Kn=4,qn=3,Jn=[],Yn=[],Xn=!1;function Zn(e){Jn=e??[],Yn=[],Xn=e!==null}function Qn(e,t,n,r){Xn&&Yn.push({x:e,y:t,width:n-e,height:r-t})}function $n(e,t,n,r,i){return r>e.x&&t<e.x+e.width&&i>e.y&&n<e.y+e.height}function er(e,t,n,r){return Jn.some(i=>$n(i,e,t,n,r))}function tr(e,t,n,r){return er(e,t,n,r)||Yn.some(i=>$n(i,e,t,n,r))}function nr(e,t,n){let r=n;for(let n of[...Jn,...Yn])t>n.x&&e<n.x+n.width&&(r=Math.max(r,n.y+n.height));return r}function rr(e,t){let n=null;for(let r of[...Jn,...Yn])t>r.y&&e<r.y+r.height&&(n=Math.max(n??r.x+r.width,r.x+r.width));return n}var ir=()=>2*Gn();function ar(e,t,n,r,i=n,a=-1/0){e.font=M(`label`);let o=e.measureText(t).width,s=or(n,i,r,o,a);e.textAlign=s.align,e.textBaseline=s.baseline,F(e,t,s.x,s.y),Qn(s.left,s.top,s.left+o,s.top+Gn())}function or(e,t,n,r,i){let a=e+Kn,o=t-Kn-r,s=o>a?[a,o]:[a],c={top:n-qn-Gn(),bottom:n-qn},l={top:n+qn,bottom:n+qn+Gn()};for(let e of[c,l])if(!(e.top<i)){for(let t of s)if(!tr(t,e.top,t+r,e.bottom)){let n=e===c;return{x:t,y:n?e.bottom:e.top,align:`left`,baseline:n?`bottom`:`top`,left:t,top:e.top}}}let u=s.map(e=>({l:e,top:nr(e,e+r,n)+qn})),d=u.find(e=>e.top-n<=ir());if(d)return{x:d.l,y:d.top,align:`left`,baseline:`top`,left:d.l,top:d.top};let f=t-Kn,p={left:f-r,top:n-Gn()/2};if(!tr(p.left,p.top,f,p.top+Gn()))return{x:f,y:n,align:`right`,baseline:`middle`,...p};let m=u.reduce((e,t)=>t.top<e.top?t:e);return{x:m.l,y:m.top,align:`left`,baseline:`top`,left:m.l,top:m.top}}function sr(){return Math.round(j().sizes.label*cr)}var cr=1.5,lr=4,ur=6;function dr(e,t){return Math.ceil(e.measureText(t).width)+2*ur}function fr(e,t,n,r,i,a=zn(i)){let o=dr(e,t),s=sr(),c=Math.round(r-s/2);return yn(Math.round(n),c,o,s),e.fillStyle=i,e.beginPath(),typeof e.roundRect==`function`?e.roundRect(Math.round(n),c,o,s,lr):e.rect(Math.round(n),c,o,s),e.fill(),e.fillStyle=a,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(t,Math.round(n)+ur,c+s/2+.5),o}var pr=1.35,mr=8,hr=5,gr=4,_r=.94,vr=.16,yr=6e4,br=60*yr,xr=24*br;function Sr(e){let t=Math.abs(e);return t>=10||t===0?2:t>=1?4:Math.min(10,Math.ceil(-Math.log10(t))+3)}var Cr=2;function wr(e,n=e,r){return r?(0,t.priceTagText)(e,r,r.pricePrecision??Sr(n)):e.toFixed(Sr(n))}function Tr(e,n){return n?(0,t.formatPrice)(e,Cr,n.numberLocale??`en-US`):e.toFixed(Cr)}function Er(e,t,n){let r=t-e,i=e===0?0:r/e*100,a=r>=0?`+`:``;return`${a}${wr(r,e,n)} (${a}${Tr(i,n)}%)`}function Dr(e){let t=Math.abs(e);if(t<br)return`${Math.round(t/yr)}m`;if(t<xr){let e=Math.floor(t/br),n=Math.round((t-e*br)/yr);return n>0?`${e}h ${n}m`:`${e}h`}let n=Math.floor(t/xr),r=Math.round((t-n*xr)/br);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 Or(e){return!!e.data&&e.data.length>0}function kr(t,n,r,i){let a=e.A(t.anchors[n].time,i),o=e.A(t.anchors[r].time,i);return Math.round(Math.abs(o-a))}function Ar(e,t,n,r){return Or(r)?Dr(e.anchors[n].time-e.anchors[t].time):null}function jr(e,t,n,r,i=`center`,a=!0){let o=j();e.font=M(`label`);let s=Math.round(o.sizes.label*pr),c=0;for(let n of t)c=Math.max(c,e.measureText(n).width);let l=Math.ceil(c+mr*2),u=t.length*s+hr*2,d=wn(i===`left`?n:i===`right`?n-l:n-l/2,a?r-u:r,l,u),f=Math.round(d.left),p=Math.round(d.top);Mr(e,f,p,l,u),e.fillStyle=o.ink,e.textAlign=`left`,e.textBaseline=`top`;for(let n=0;n<t.length;n++)e.fillText(t[n],f+mr,p+hr+n*s+(s-o.sizes.label)/2);return{x:f,y:p,width:l,height:u}}function Mr(e,n,r,i,a){let o=j(),s=Math.round(n),c=Math.round(r),l=Math.round(i),u=Math.round(a);yn(s,c,l,u),e.beginPath(),typeof e.roundRect==`function`?e.roundRect(s+.5,c+.5,l-1,u-1,gr):e.rect(s+.5,c+.5,l-1,u-1),e.fillStyle=(0,t.withAlpha)(o.background,_r),e.fill(),e.strokeStyle=(0,t.withAlpha)(o.ink,vr),e.lineWidth=1,e.setLineDash([]),e.stroke()}function Nr(e,t){return e.find(e=>!er(e.left,e.top,e.right,e.bottom)&&t.every(t=>e.right<=t.left||t.right<=e.left||e.bottom<=t.top||t.bottom<=e.top))??null}function Pr(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 Fr=4,Ir=10,Lr=3,Rr=14,zr=8,Br=2,Vr=3,Hr=4,Ur=2,Wr=(e,t)=>e.left<t.right&&t.left<e.right&&e.top<t.bottom&&t.top<e.bottom,Gr=class{symbols=new Map;mode=`percent`;store=new rn;aligned=new Map;reservedLevels=()=>[];setReservedLevels(e){this.reservedLevels=e}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();let a=[];for(let r of this.symbols.values()){if(!r.visible||r.data.length===0)continue;let i=this.renderSymbol(e,r,t,n);i&&a.push({sym:r,...i})}this.renderLabels(e,a,n,r),e.restore()}renderLabels(e,t,n,r){if(t.length===0)return;e.font=`bold ${Ir}px sans-serif`,e.textBaseline=`middle`,e.textAlign=`right`;let i=this.reservedBoxes(n);for(let a of t){let o=zr+Vr+e.measureText(a.sym.label).width+2*Lr,s=this.placeLabel(a,o,i,t,n.chartRect);i.push(s),this.drawLabel(e,a.sym,s,r)}}drawLabel(e,t,n,r){let i=(n.top+n.bottom)/2,a=n.left+Lr;e.strokeStyle=t.color,e.lineWidth=Br,e.beginPath(),e.moveTo(a,i),e.lineTo(a+zr,i),e.stroke(),e.fillStyle=r.text,F(e,t.label,n.right-Lr,i,r.background)}placeLabel(e,t,n,r,i){let a=e.x-Fr,o=e=>({left:a-t,top:e,right:a,bottom:e+Rr}),s=e.y-Fr-Rr,c=e.y+Fr,l=Array.from({length:Hr},(e,t)=>[o(s-t*Rr),o(c+t*Rr)]).flat(),u=i.y+i.height,d=e=>e.top>=i.y&&e.bottom<=u&&!n.some(t=>Wr(t,e)),f=t=>{let n=(t.top+t.bottom)/2,i=t=>Math.hypot(t.x-e.x,t.y-n);return r.every(t=>t===e||i(t)>i(e))};return l.find(e=>d(e)&&f(e))??l.find(d)??o(Math.max(i.y,Math.min(s,u-Rr)))}reservedBoxes(t){let{chartRect:n}=t;return this.reservedLevels().map(r=>{let i=e.O(r,t)-Ur;return{left:n.x,top:i-Rr,right:n.x+n.width,bottom:i}})}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}anchor(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=n.scaleBaseline||t[i]?.close||t[o].close;return{closes:r,base:o,to:a,mainBase:s,symBase:r[o]}}line(e,t,n){let r=this.anchor(e,t,n);if(!r)return null;let{closes:i,mainBase:a,symBase:o}=r,s=this.mode===`percent`;return{from:r.base,to:r.to,priceAt:e=>{let t=i[e];return Number.isFinite(t)?s?t/o*a:t:null}}}valuesAt(e,n,r){let i=e[r]?.time,a=(0,t.barTimeUnit)(e);return this.getSymbols().map(t=>{let r=i===void 0?void 0:this.store.lastCloseAt(t.id,i,a),o=r&&n?this.anchor(t,e,n)?.symBase:void 0,s=r?.close??null;return{id:t.id,label:t.label,color:t.color,visible:t.visible,close:s,change:s!==null&&o?(s/o-1)*100:null,stale:r?.stale??!1}})}renderSymbol(t,n,r,i){let a=this.line(n,r,i);if(!a)return null;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.C(n,i),l=e.O(r,i);o===0?t.moveTo(c,l):t.lineTo(c,l),s={x:c,y:l},o++}return t.stroke(),s}};function Kr(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}var qr=1e5,Jr=[1,2,5],Yr=15;function Xr(e,t){if(t===0)return e;let n=Jr[t%Jr.length],r=Math.floor(t/Jr.length),i=n*10**r;if(Number.isFinite(i))return Number((e*i).toPrecision(Yr));let[a,o]=e.toExponential().split(`e`);return Number(`${(Number(a)*n).toPrecision(Yr)}e${Number(o)+r}`)}function Zr(e,t,n){return e===t-1?n+qr:qr}var Qr=class{reached=null;clear(){this.reached=null}startStep(e,t,n){let r=this.reached;if(!r||r.kind!==e||r.asked!==t||n.length<r.length||n[0].time!==r.first)return 0;let i=n[r.length-1];return i.high>=r.high&&i.low<=r.low?r.step:0}keep(e,t,n,r){let i=r[r.length-1];this.reached=i?{kind:e,asked:t,step:n,first:r[0].time,length:r.length,high:i.high,low:i.low}:null}};function $r(e,t,n,r,i){let a=i(e?.startStep(t,n,r)??0);return e?.keep(t,n,a.step,r),a}function ei(e,t,n=0){return ni(e,t,()=>({bars:[],size:1/0,step:0}),n)}function ti(e,t,n=0){return ni(e,t,()=>({bars:ri(e,t,!1)??[],size:e,step:0}),n)}function ni(e,t,n,r){let i=Xr(e,r),a=ri(i,t,!0);if(a)return{bars:a,size:i,step:r};let o=ii(e,e=>t(e,!0),r),s=Number.isFinite(o)?Xr(e,o):1/0,c=Number.isFinite(s)?ri(s,t,!0):null;return c?{bars:c,size:s,step:o}:n()}function ri(e,t,n){let r=[];return t(e,n,e=>{r.push(e)})?r:null}function ii(e,t,n){if(!(e>0))return 1/0;let r=n=>{let r=Xr(e,n);return r===1/0||t(r)};if(r(n+1))return n+1;if(!t(Number.MAX_VALUE))return 1/0;let i=n+1,a=n+2;for(;!r(a);)i=a,a=n+2*(a-n);for(;a-i>1;){let e=Math.floor((i+a)/2);r(e)?a=e:i=e}return a}var ai=new WeakMap,oi=new WeakMap;function si(e,t){return ai.set(e,t),e}function ci(e){let t=e[e.length-1];if(!t||!ai.has(t))return e;let n=oi.get(e);if(!n){let t=ai.get(e[0])??e[0].time;n=e.map(e=>(t=ai.get(e)??t,{time:t})),oi.set(e,n)}return n}function li(e,t,n){if(e.length===0)return[];let r=ui(e,t),i=(t,n,r)=>di(e,t,n,r);return $r(n,`renko`,r,e,e=>ei(r,i,e)).bars}function ui(e,t){let n=t.useATR&&e.length>2?pi(e,t.atrPeriod??14):t.brickSize;return n>0?n:Math.abs(e[e.length-1].close)/100||1}function di(e,t,n,r){let i=e.findIndex(e=>Number.isFinite(e.close));if(i<0)return!0;let a=e[0].time,o=Math.round(e[i].close/t)*t,s=0;for(let c=i+1;c<e.length;c++){let{close:i,volume:l}=e[c],u=i-o,d=Math.floor(Math.abs(u)/t);if(!Number.isFinite(i)||!(d>=1))continue;if(n&&s+d>Zr(c,e.length,s))return!1;let f=u>0?1:-1;for(let n=0;n<d;n++){let i=o;o+=f*t,r?.(si(fi(a+s+n,i,o,l/d),e[c].time))}s+=d}return!0}function fi(e,t,n,r){return{time:e,open:t,high:Math.max(t,n),low:Math.min(t,n),close:n,volume:r}}function pi(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 mi(e,t=3){if(e.length===0)return[];let n=[],r=0;n.push(si({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},e[0].time));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(si({time:r++,open:o.close,high:a,low:o.close,close:a,volume:e[i].volume},e[i].time)):!s&&a<o.close||s&&a<u?n.push(si({time:r++,open:o.close,high:o.close,low:a,close:a,volume:e[i].volume},e[i].time)):!s&&a>l&&n.push(si({time:r++,open:o.close,high:a,low:o.close,close:a,volume:e[i].volume},e[i].time))}return n}function hi(e,t=4,n=`percent`,r){if(e.length<2)return e.slice();let i=(t,r,i)=>gi(e,t,n,r,i);return $r(r,`kagi:${n}`,t,e,e=>ti(t,i,e)).bars}function gi(e,t,n,r,i){let a=e[1].close>=e[0].close?1:-1,o=e[0].close,s=e[0].close,c=e[0].close,l=0;for(let u=1;u<e.length;u++){let d=e[u].close,f=n===`price`?t:t/100*c;if(a===1&&d>o&&(o=d),a===-1&&d<s&&(s=d),a===1?o-d>=f:d-s>=f){if(r&&l+1>Zr(u,e.length,l))return!1;i?.(si(_i(l,c,a===1?o:s,e[u].volume),e[u].time)),l++,c=a===1?o:s,a=-a,o=d,s=d}}return i?.(si(_i(l,c,a===1?o:s,0),e[e.length-1].time)),!0}function _i(e,t,n,r){return{time:e,open:t,high:Math.max(t,n),low:Math.min(t,n),close:n,volume:r}}function vi(e,t,n=3,r){return yi(e,t,n,r).columns}function yi(e,t,n=3,r){if(e.length===0||!(t>0))return{columns:[],boxSize:t};let i=(t,r,i)=>bi(e,t,n,r,i),{bars:a,size:o}=$r(r,`pointAndFigure:${n}`,t,e,e=>ti(t,i,e));return{columns:a,boxSize:o}}function bi(e,t,n,r,i){let a=1,o=0,s=e[0].close,c=Math.round(s/t)*t;if(xi(s,c))return!1;let l=c,u=c,d=e[0].volume,f=t*n;for(let n=1;n<e.length;n++){let s=e[n].close,c=Math.round(s/t)*t;if(xi(s,c))return!1;let p=!1;if(a===1?c>l?l=c:p=l-c>=f:c<u?u=c:p=c-u>=f,!p){d+=e[n].volume;continue}if(r&&o+1>Zr(n,e.length,o))return!1;i?.(si(Si(o,a===1,u,l,d),e[n].time)),d=e[n].volume,o++,a===1?(u=c,l-=t):(l=c,u+=t),a=-a}return i?.(si(Si(o,a===1,u,l,d),e[e.length-1].time)),!0}function xi(e,t){return Number.isFinite(e)&&!Number.isFinite(t)}function Si(e,t,n,r,i){return{time:e,open:t?n:r,high:r,low:n,close:t?r:n,volume:i}}var Ci=15,wi=`rangeBars`,Ti=3,Ei=4,Di=64,Oi=2;function ki(e){let t=0;for(let n of e){let e=Math.abs(n.high),r=Math.abs(n.low);e>t&&e!==1/0&&(t=e),r>t&&r!==1/0&&(t=r)}return t}function Ai(e,t){let n=Math.max(e,t),r=Math.floor(Math.log10(n))+1,i=Number.isFinite(n)?Ci-r:0,a=10**-i;if(i<=0)return{clean:e=>e,unit:a,half:0};let o=10**i;return{clean:e=>Math.round(e*o)/o,unit:a,half:a/2}}function ji(e,t){let n=-1/0,r=1/0;for(let i of[t,e.open,e.high,e.low,e.close])Number.isFinite(i)&&(n=Math.max(n,i),r=Math.min(r,i));return n>r?n-r:0}function Mi(e){let t=0,n=e[0].open;for(let r=0;r<e.length-1;r++)t+=ji(e[r],n),n=e[r].close;return{distance:t,bars:e.length-1,lastSpan:ji(e[e.length-1],n)}}function Ni(e,t,n){if(t<Oi*n)return!1;let r=t+n,i=(e.distance-e.bars*n)/r-e.bars,a=(e.lastSpan-n)/r-1;return Math.max(i,a)>qr+1}function Pi(e){let t=new Float64Array(e.length*2);return t.set(e),t}function Fi(e,t,n,r){let i=r/(n-t);for(let r=t;r<n;r++)e[r*Ei+2]+=i}function Ii(e,t,n,r){let i=Array(t);for(let a=0;a<t;a++){let t=e[a*Ei],o=e[a*Ei+1],s=t>o;i[a]=si({time:r+a,open:n,high:s?t:o,low:s?o:t,close:t,volume:e[a*Ei+2]},e[a*Ei+3]),n=t}return i}function Li(e,t,n,r){let{clean:i,unit:a,half:o}=n,s=0,c=e[0].open,l=c,u=c,d=c,f=0,p=i(c+t),m=i(c-t);for(let n=0;n<e.length;n++){let h=Zr(n,e.length,s),g=e[n],_=g.close>=g.open,v=g.volume/Ti;for(let e=0;e<=Ti;e++){let n=e===0?g.open:e===1?_?g.low:g.high:e===2?_?g.high:g.low:g.close;if(!Number.isFinite(n))continue;d=n;let y=s;for(;;){let e=n>l&&n>=p-o&&p>u;if(!e&&!(n<u&&n<=m+o&&m<l))break;let d=e?p:m;if(e?d<l-a:d>u+a)return{cells:r,count:s,forming:null};let _=s*Ei;if(_===r.length&&(r=Pi(r)),r[_]=d,r[_+1]=e?u:l,r[_+2]=f,r[_+3]=g.time,++s>h)return{cells:r,count:s,forming:null};c=l=u=d,p=i(d+t),m=i(d-t),f=0}n>l&&(l=n,m=i(n-t)),n<u&&(u=n,p=i(n+t));let b=e===0?0:v;s===y?f+=b:Fi(r,y,s,b)}}let h={time:e[0].time+s,open:c,high:l,low:u,close:d,volume:f};return{cells:r,count:s,forming:si(h,e[e.length-1].time)}}function Ri(e,t,n){if(e.length===0||!(t.rangeSize>0))return[];let r=ki(e),i=new Float64Array(Ei*Math.max(Di,Math.min(e.length,qr))),a=null,o=n?.startStep(wi,t.rangeSize,e)??0;for(let s=o;;s++){let c=Xr(t.rangeSize,s),l=Ai(r,c);if(s>o&&(a??=Mi(e),Ni(a,c,l.unit)))continue;let u=Li(e,c<l.half?1/0:c,l,i);if(i=u.cells,!u.forming)continue;let d=Ii(i,u.count,e[0].open,e[0].time),{forming:f}=u;return t.includeForming&&(d.length===0||f.high-f.low>l.half)&&d.push(f),n?.keep(wi,t.rangeSize,s,e),d}}function zi(e){return e.barWidth+e.barSpacing<1}function Bi(e,t,n){return e>1.5*(Math.abs(n-t)+1)}var Vi=3,Hi=class{started=!1;piece=0;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.piece++,this.lastX=e,this.lastY=t)}gap(){this.endPiece(),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.endPiece(),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()}endPiece(){if(!this.dense&&this.piece===1){let e=Math.max(this.width,Vi);this.ctx.moveTo(this.lastX-e,this.lastY),this.ctx.lineTo(this.lastX+e,this.lastY)}this.piece=0}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 Ui(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 Wi=.1;function Gi(e){return e.plots?e.plots.map(e=>e.key):null}function Ki(e,t){return e.tone?e.tone===`sign`?(t[e.key]??0)>=0:t[e.tone.field]===1:!0}function qi(e,t){return t.plots?.[e.key]?.visible!==!1}var Ji=[6,4];function Yi(e,n,r){let i=e.plots?.[n];return{visible:i?.visible!==!1,dash:(0,t.lineDash)(i?.lineStyle??`solid`,Ji,r)}}function Xi(e,t,n){let r=t.colors[e.color]??t.colors[0];return!e.tone||e.downColor===void 0||!n||Ki(e,n)?r:t.colors[e.downColor]??r}function Zi(e,t,n,r){let{lo:i,hi:a}=$i(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*Wi,a+=e*Wi}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 Qi(e,t,n,r){let{lo:i,hi:a}=$i(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)*Wi);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 $i(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 ea(e){return!!e?.some(e=>e.kind===`histogram`)}function ta(n,r,i,a,o,s=[]){let c=r.series;if(!c)return;let l=Math.max(0,i.visibleRange.from),u=Math.min(i.visibleRange.to,c.length-1);if(u<l)return;let d=e.k(i);for(let e of s){let r=(0,t.withAlpha)(a.colors[e.color]??a.colors[0],e.opacity??na);ra(n,c,e.between,l,u,i,d,r)}for(let e=0;e<o.length;e++){let r=o[e];if(!qi(r,a))continue;let s=(e>0?a.lineWidths[e]:void 0)??r.width??a.lineWidths[0]??1.5,f=(0,t.lineDash)(a.plots?.[r.key]?.lineStyle??r.lineStyle??`solid`,Ji,s),p=r.kind??`line`,m=r.breakOn,h=m===void 0?null:(e,t)=>Nt(c,e,t,m),g=n.globalAlpha;r.opacity!==void 0&&(n.globalAlpha=g*r.opacity);let _=r.tone&&r.downColor!==void 0?[!0,!1]:[null];try{for(let e of _){let t=a.colors[r.color]??a.colors[0],o=e===!1?a.colors[r.downColor]??t:t,m=t=>e===null||Ki(r,t)===e;p===`histogram`?ca(n,c,r.key,l,u,i,d,o,m):p===`dots`?sa(n,c,r.key,l,u,i,d,o,m):oa(n,c,r.key,l,u,i,d,o,s,p===`step`,e===null?null:m,f,h)}}finally{n.globalAlpha=g}}}var na=.1;function ra(t,n,r,i,a,o,s,c){let l=a-i+1,u=new Float64Array(l),d=new Float64Array(l),f=new Float64Array(l),p=zi(o),m=0,h=()=>{m>=2&&(p?Ui(t,u,d,f,c,m):ia(t,u,d,f,c,m)),m=0};for(let t=i;t<=a;t++){let i=aa(n[t],r[0]),a=aa(n[t],r[1]);if(i===void 0||a===void 0){h();continue}u[m]=e.C(t,o),d[m]=s(i),f[m]=s(a),m++}h()}function ia(e,t,n,r,i,a){e.beginPath(),e.moveTo(t[0],n[0]);for(let r=1;r<a;r++)e.lineTo(t[r],n[r]);for(let n=a-1;n>=0;n--)e.lineTo(t[n],r[n]);e.closePath(),e.fillStyle=i,e.fill()}function aa(e,t){let n=e?.[t];return n!==void 0&&Number.isFinite(n)?n:void 0}function oa(t,n,r,i,a,o,s,c,l,u,d,f=[],p=null){let m=new Hi(t,c,l,zi(o),f),h=0,g=0,_=!1,v=-1;for(let t=i;t<=a;t++){let i=n[t],a=aa(i,r);if(a===void 0){_=!1,m.gap();continue}_&&p?.(v,t)&&(_=!1,m.gap()),v=t;let c=e.C(t,o),l=s(a);d?_&&d(i)&&(u?(m.segment(h,g,c,g),m.add(c,l)):m.segment(h,g,c,l)):(_&&u&&m.add(c,g),m.add(c,l)),h=c,g=l,_=!0}m.finish()}function sa(t,n,r,i,a,o,s,c,l){let u=Math.max(1.5,o.barWidth*.15),d=zi(o),f=NaN;t.beginPath(),t.fillStyle=c;for(let c=i;c<=a;c++){let i=n[c],a=aa(i,r);if(a===void 0||!l(i))continue;let p=e.C(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 ca(t,n,r,i,a,o,s,c,l){let u=s(0);if(t.beginPath(),t.fillStyle=c,zi(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=aa(i,r);if(a===void 0||!l(i))continue;let s=Math.floor(e.C(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=aa(i,r);if(a===void 0||!l(i))continue;let f=e.C(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 I=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&&ta(e,t,n,r,this.descriptor.plots,this.descriptor.fills)}drawLine(e,t,n,r,i){if(t.length<2||i?.visible===!1)return;let a=new Hi(e,n,r,Bi(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&&Bi(t.length,t[0].x,t[t.length-1].x)){Ui(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.C(c,i),y:e.O(o[n],i)})}return a}};function la(e){return e.config.visible!==!1&&!e.offInterval&&!e.offChartType}function ua(e){let t=Gi(e.plugin.descriptor),n=e.style.plots;return t&&n?t.filter(e=>n[e]?.visible!==!1):t}function da(e,t){return e.plugin.descriptor.placement!==`overlay`||e.config.pane?!1:e.config.scale===`left`==(t===`left`)}function fa(e){let t=e.output?.series,n=e.plugin.descriptor.plots;if(!t||!n||!la(e))return[];let r=t[t.length-1];if(!r)return[];let i=[];for(let t of n){if(!qi(t,e.style))continue;let n=r[t.key];n!==void 0&&Number.isFinite(n)&&i.push({value:n,color:Xi(t,e.style,r)})}return i}function pa(e,t){let n=[];for(let r of e)da(r,t)&&n.push(...fa(r));return n}function ma(e,t,n,r){let i=null;for(let a of e){if(!la(a))continue;let e=a.plugin.descriptor,o={keys:ua(a),scale:e.scale,levels:a.config.levels??e.levels,zero:ea(e.plots)},s=r?Qi(a.output,t,n,o):Zi(a.output,t,n,o);if(s===!1)return null;s&&(i=i?{min:Math.min(i.min,s.min),max:Math.max(i.max,s.max)}:s)}return i}function ha(e,t){let n=[];for(let r of e){if(!la(r))continue;let e=r.output?.series?.[t];if(!e)continue;let i=ua(r)??Object.keys(e);for(let t of i){let r=e[t];typeof r==`number`&&Number.isFinite(r)&&n.push(r)}}return n}function ga(e,t,n){if(n){for(let r=0;r<n.length;r++){let i=t[n[r]];i!==void 0&&isFinite(i)&&(i<e.min&&(e.min=i),i>e.max&&(e.max=i))}return}for(let n in t){let r=t[n];r!==void 0&&isFinite(r)&&(r<e.min&&(e.min=r),r>e.max&&(e.max=r))}}function _a(e,t,n,r){let i=t.output?.series;if(!i)return;let a=ua(t),o=Math.min(r,i.length-1),s=r>=i.length-1?t.output?.meta?.ahead:void 0,c=Array.isArray(s)?s:[];for(let t=Math.max(0,n);t<=o+c.length;t++){let n=t<=o?i[t]:c[t-o-1];n&&ga(e,n,a)}}function va(e,t,n,r){let i={min:1/0,max:-1/0};for(let a of e)!a.output||!la(a)||!da(a,r)||_a(i,a,t,n);return i.min===1/0?null:i}function ya(e,t,n,r){let i=new Set;for(let a of e)a.config.instanceId!==r&&(n===null?t===`overlay`&&a.plugin.descriptor.placement===`overlay`&&!a.config.pane:a.config.instanceId===n||a.config.pane===n)&&i.add(a.style.colors[0]);return i}function ba(e,n,r,i,a){let o=ya(e,r,i,a);for(let t of e)t.config.id===n&&t.config.instanceId!==a&&o.add(t.style.colors[0]);let s=t.TC_SERIES_COLORS.findIndex(e=>!o.has(e));return s>=0?s:o.size%t.TC_SERIES_COLORS.length}function xa(e){let t=e.inputs;if(!t)return null;for(let e in t)if(t[e]?.source)return e;return null}function Sa(e,n){let r=xa(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 Ca(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 wa(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 Ta(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 Ea(e){return{values:new Map,series:Array(e).fill(null)}}var Da=[`ticks`,`seconds`,`minutes`,`hours`,`days`,`weeks`,`months`],Oa={ticks:1e6,seconds:59,minutes:59,hours:24,days:366,weeks:52,months:12},ka={s:`seconds`,m:`minutes`,h:`hours`,d:`days`,w:`weeks`,M:`months`};function Aa(e){let n=(0,t.tickBarCount)(e);if(n!==null)return{unit:`ticks`,count:n};let r=(0,t.parseTimeframe)(e);return r?{unit:ka[r.unit],count:r.count}:null}function ja(e,t){if(!e||!t)return!0;let n=Aa(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]>=Oa[n.unit])}function Ma(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=e,n={};for(let e of Da){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=Oa[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 Na(e){return[...t.TC_SERIES_COLORS.slice(e),...t.TC_SERIES_COLORS.slice(0,e)]}function Pa(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 Fa(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t}]))}function Ia(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t===!1?!1:[t[0],t[1]]]))}var La=new WeakSet,L=class e extends Map{keyBuf=[];valBuf=[];folded=!1;constructor(){super()}static fromAscending(t,n){let r=new e;for(let e=1;e<t.length;e++)if(!(t[e]>t[e-1])){for(let e=0;e<t.length;e++)r.set(t[e],n[e]);return r}return r.keyBuf=t,r.valBuf=n,r}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 R(e,t){let n=new L;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 Ra(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 za(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 za(e,t,2/(t+1))}function Ba(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 Va(e,t){return za(e,t,1/t)}function Ha(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 Ua(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 Wa(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 Ga(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 Ka(e,t=`value`){return e.map(e=>e!==void 0&&Number.isFinite(e)?{[t]:e}:null)}function qa(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 Ja(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 Ya(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 Xa(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 Za(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 Qa=new WeakMap;function $a(e){let t=Qa.get(e);return t||Qa.set(e,t=Array.from(e)),t}var V=class extends I{times=new WeakMap;workerState(){}adoptWorkerState(e,t,n){this.times.set(e,$a(n))}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}},eo=new Set([`compareSymbol`,`compareSymbolPane`,`spread`,`correlation`,`correlationlog`]),to=e=>typeof e.params.symbol==`string`?e.params.symbol.trim():``,no=class extends V{descriptor={id:`compareSymbol`,name:`Compare Symbol`,placement:`overlay`,defaultConfig:{symbol:``},shortName:`Compare`,plots:[{key:`value`,title:`Close`,color:0}],readsExchangeTimeZone:!1};constructor(e){super(),this.store=e}read(e){return{symbol:to(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}}},ro=class extends no{descriptor={id:`compareSymbolPane`,name:`Compare Symbol (Pane)`,placement:`panel`,defaultConfig:{symbol:``},shortName:`Compare`,plots:[{key:`value`,title:`Close`,color:0}],readsExchangeTimeZone:!1}},io=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`]}},readsExchangeTimeZone:!1};constructor(e){super(),this.store=e}read(e){return{symbol:to(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}}},ao=e=>{let t=Math.round(Number(e.params.length??20));return{symbol:to(e),length:Number.isFinite(t)?Math.max(2,t):20}};function oo(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 so={placement:`panel`,defaultConfig:{symbol:``,length:20},inputs:{length:{kind:`int`,min:2}},plots:[{key:`value`,title:`Correlation`,color:0}],scale:{min:-1,max:1},levels:[0],readsExchangeTimeZone:!1},co=class extends V{descriptor={...so,id:`correlation`,name:`Correlation Coefficient`,shortName:`Correlation`};constructor(e){super(),this.store=e}read(e){return ao(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=oo(a,o);return s===null?null:{value:s}}},lo=class extends V{descriptor={...so,id:`correlationlog`,name:`Correlation Log`,shortName:`Correlation Log`};constructor(e){super(),this.store=e}read(e){return ao(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=oo(a,o);return c===null?null:{value:c}}};function uo(e){let t=e.length,n={time:new Float64Array(t),open:new Float64Array(t),high:new Float64Array(t),low:new Float64Array(t),close:new Float64Array(t),volume:new Float64Array(t)};for(let r=0;r<t;r++){let t=e[r];n.time[r]=t.time,n.open[r]=t.open,n.high[r]=t.high,n.low[r]=t.low,n.close[r]=t.close,n.volume[r]=t.volume}return n}function fo(e){let{time:t,open:n,high:r,low:i,close:a,volume:o}=e,s=Array(t.length);for(let e=0;e<t.length;e++)s[e]={time:t[e],open:n[e],high:r[e],low:i[e],close:a[e],volume:o[e]};return s}function po(e){let{time:t,open:n,high:r,low:i,close:a,volume:o}=e;return[t,n,r,i,a,o].map(e=>e.buffer)}function mo(e){let t=new Set;for(let n of e)if(n)for(let e in n)t.add(e);return[...t]}function ho(e,t){if(e===t)return!0;let n=Object.keys(e);return n.length===Object.keys(t).length?n.every(n=>Object.is(e[n],t[n])):!1}function go(e,t,n){if(t.length>n.length)return!1;let r=0;for(let i=0;i<t.length;i++){let a=t[i];if(!a)continue;r++;let o=e.values.get(n[i]);if(!o||!ho(o,a))return!1}return r===e.values.size}function _o(e,t){let n=e.meta?{meta:e.meta}:{},r=e.series;if(!r)return{present:null,keys:[],columns:[],nans:[],values:new Map(e.values),...n};let i=mo(r),a=new Uint8Array(r.length),o=i.map(()=>new Float64Array(r.length).fill(NaN)),s=i.map(()=>null);for(let e=0;e<r.length;e++){let t=r[e];if(t){a[e]=1;for(let n=0;n<i.length;n++){let a=t[i[n]];a!==void 0&&(o[n][e]=a,Number.isNaN(a)&&((s[n]??=new Uint8Array(r.length))[e]=1))}}}return{present:a,keys:i,columns:o,nans:s,values:go(e,r,t)?null:new Map(e.values),...n}}function vo(e,t){let n={};for(let r=0;r<e.keys.length;r++){let i=e.columns[r][t];(!Number.isNaN(i)||e.nans[r]?.[t]===1)&&(n[e.keys[r]]=i)}return n}function yo(e,t){let[n,r,i,a]=e,[o,s,c,l]=t;switch(e.length){case 1:return n===`value`?e=>({value:o[e]}):e=>({[n]:o[e]});case 2:return e=>({[n]:o[e],[r]:s[e]});case 3:return e=>({[n]:o[e],[r]:s[e],[i]:c[e]});case 4:return e=>({[n]:o[e],[r]:s[e],[i]:c[e],[a]:l[e]});default:return null}}function bo(e,t){for(let n=0;n<e.length;n++)if(Number.isNaN(e[n][t]))return!1;return!0}var xo=class{next=0;series;full;keys=[];points=[];constructor(e,t){this.columns=e,this.time=t,this.series=Array(e.present?.length??0),this.full=yo(e.keys,e.columns)}step(e){let t=this.columns.present;if(!t)return!0;let n=Math.min(t.length,this.next+e),r=this.columns.values===null;for(let e=this.next;e<n;e++){if(t[e]===0){this.series[e]=null;continue}let n=this.full&&bo(this.columns.columns,e)?this.full(e):vo(this.columns,e);this.series[e]=n,r&&(this.keys.push(this.time[e]),this.points.push(n))}return this.next=n,n===t.length}output(){let{columns:e}=this,t=e.meta?{meta:e.meta}:{};return e.present?{values:e.values??L.fromAscending(this.keys,this.points),series:this.series,...t}:{values:e.values??new Map,...t}}};function So(e,t){let n=new xo(e,t);return n.step(1/0),n.output()}function Co(e){let t=e;return typeof t.workerState==`function`&&typeof t.adoptWorkerState==`function`}function wo(e){return!!e&&typeof e==`object`&&e.tcPacked===`numbers`}function To({values:e,missing:t}){let n=Array.from(e);if(t)for(let e=0;e<n.length;e++)t[e]===1&&(n[e]=void 0);return n}function Eo(e){if(wo(e))return To(e);if(Array.isArray(e))return e.map(Eo);if(!e||typeof e!=`object`)return e;let t={};for(let[n,r]of Object.entries(e))t[n]=Eo(r);return t}var Do=5e4;function Oo(e){let t=uo(e);return{data:e,columns:t,times:t.time.slice()}}function ko(e,t,n,r,i,a){let o=0,s=e=>a(o,e),c=e.submit({indicatorId:t.descriptor.id,config:n,...i.kind===`price`?{source:i.source}:{},bars:r.columns,times:r.times},s);return c===null?null:(o=c,{requestId:o,data:r.data,times:r.times,from:1/0})}function Ao(e){let{data:t,times:n}=e,r=Math.min(e.from,n.length);return r===0||t.length<r?!1:t[0].time===n[0]&&t[r-1].time===n[r-1]}function jo(e,t,n,r,i){if(!Ao(e))return null;let a=t.output;Co(n)&&n.adoptWorkerState(a,t.state,e.times);let o=Math.min(e.from,e.times.length);return o===e.times.length&&e.data.length===o?a:n.update?.(i(),r,a,o)??null}var Mo=class{worker=null;jobs=new Map;sharedBars=null;constructor(e){this.host=e}use(e,t){this.settle(),this.worker=e?{client:e,minBars:t.minBars??5e4,onLand:t.onLand??null}:null}computing(e){if(e===void 0)return this.jobs.size>0;if(this.jobs.has(e))return!0;let t=this.host.instance(e);return!!t&&this.jobReadBy(t,this.jobs)!==null}stop(){this.worker?.client.cancel([...this.jobs.values()].map(e=>e.requestId)),this.jobs.clear(),this.worker=null}barsChanged(){this.sharedBars=null}takes(e,t,n){if(!this.worker&&this.jobs.size===0)return!1;let r=e.config.instanceId,i=this.jobs.get(r);return i&&n!==void 0?(i.from=Math.min(i.from,n),i.data=t,!0):(i&&this.drop(r),this.jobReadBy(e,this.jobs)?!0:n===void 0&&this.send(e,t))}drop(e){let t=this.jobs.get(e);t&&(this.jobs.delete(e),this.worker?.client.cancel([t.requestId]))}settle(){if(this.jobs.size===0)return;this.host.runPending();let e=this.jobs;this.jobs=new Map,this.worker?.client.cancel([...e.values()].map(e=>e.requestId));for(let t of this.host.ordered()){let n=e.get(t.config.instanceId)??this.jobReadBy(t,e);n&&this.host.compute(t,n.data,void 0,!0)}this.worker?.onLand?.()}send(e,t){let n=this.worker,{plugin:r,config:i}=e;if(!n?.client.usable||t.length<n.minBars||!La.has(r))return!1;let a=Sa(r.descriptor,i.params);if(a.kind===`line`)return!1;let o=i.instanceId,s=this.barsFor(t),c=ko(n.client,r,i,s,a,(e,t)=>this.land(o,e,t));return c?(this.jobs.set(o,c),!0):!1}barsFor(e){let t=this.sharedBars;if(t?.data===e&&t.times.length===e.length)return t;let n=Oo(e);return this.sharedBars=n,queueMicrotask(()=>{this.sharedBars===n&&(this.sharedBars=null)}),n}jobReadBy(e,t){if(t.size===0)return null;let n=Sa(e.plugin.descriptor,e.config.params),r=new Set;for(;n.kind===`line`&&!r.has(n.instanceId);){let e=t.get(n.instanceId);if(e)return e;r.add(n.instanceId);let i=this.host.instance(n.instanceId);if(!i)return null;n=Sa(i.plugin.descriptor,i.config.params)}return null}land(e,t,n){let r=this.jobs.get(e);if(r?.requestId!==t)return;this.host.runPending();let i=this.host.instance(e);if(this.jobs.get(e)!==r||!i)return;this.jobs.delete(e),this.apply(i,r,n);let a=new Set(this.host.dependents(e));for(let e of this.host.ordered())a.has(e.config.instanceId)&&this.host.compute(e,r.data);this.worker?.onLand?.()}apply(e,t,n){let{plugin:r,config:i}=e;delete e.sourceBars;let a=n instanceof Error?null:n,o=a&&jo(t,a,r,i,()=>No(e,t.data));if(!o){this.host.compute(e,t.data,void 0,!0);return}e.output=o,e.changedFrom=0}};function No(e,t){let n=Sa(e.plugin.descriptor,e.config.params);return n.kind===`price`?(e.sourceBars=Ca(t,n.source),e.sourceBars):t}var Po=1;function Fo(e){return e.descriptor.readsExchangeTimeZone??!La.has(e)}var Io=class{registry=new Map;instances=new Map;styleDefaults=new Map;order=null;pending=null;timeframe=null;exchangeTimeZone=null;barsTimed=!0;worker=new Mo({instance:e=>this.instances.get(e),ordered:()=>this.ordered(),dependents:e=>this.getDependents(e),compute:(e,t,n,r)=>this.compute(e,t,n,r),runPending:()=>this.runPending()});useWorker(e,t={}){this.worker.use(e,t)}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`),this.exchangeTimeZone&&(o.exchangeTimeZone=this.exchangeTimeZone);let s=this.styleDefaults.get(e),c={...s?.plots,...o.style?.plots},l={colors:o.style?.colors??s?.colors?.slice()??Na(ba([...this.instances.values()],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:Fa(c)}:{}};this.runPending();let u={plugin:i,config:o,output:null,style:l,changedFrom:0,offInterval:!1,offChartType:!1};return this.placeOnChartType(u),this.instances.set(a,u),this.order=null,n&&this.compute(u,n),a}removeIndicator(e){this.worker.drop(e),this.instances.delete(e),this.order=null}updateIndicator(e,t,n){this.runPending();let r=this.instances.get(e);if(!r)return;let i=xa(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){this.worker.barsChanged();let n=this.waitingOn(e);n.from=Math.min(n.from,t)}waitingOn(e){let t=this.pending;return t&&t.data===e?t:(this.runPending(),this.pending={data:e,from:1/0,full:new Set},this.pending)}flush(){this.worker.settle(),this.runPending()}runPending(){let e=this.pending;if(!e)return;this.pending=null;let{data:t,from:n,full:r}=e;for(let e of this.ordered())r.has(e.config.instanceId)?this.compute(e,t):n!==1/0&&this.compute(e,t,n)}recalculateFrom(e,t){this.deferRecalculateFrom(e,t),this.runPending()}compute(e,t,n,r=!1){if(!r&&this.worker.takes(e,t,n))return;let{plugin:i,config:a}=e,o=Sa(i.descriptor,a.params);if(o.kind===`line`){this.computeFromLine(e,t,o.instanceId,o.key,n);return}delete e.lineInput;let s=t;o.kind===`price`?(e.sourceBars=Ca(t,o.source,e.sourceBars??null,n??0),s=e.sourceBars):delete e.sourceBars;let c=e.output,l=null;n!==void 0&&n>0&&c&&i.update&&(l=i.update(s,a,c,n)),e.changedFrom=l?Math.max(0,n-(i.revisesBefore?.(a)??0)):0,e.output=l??i.calculate(s,a)}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=wa(t,c,r);if(!d){delete e.lineInput,e.output=Ea(t.length);return}let f=a.calculate(d.bars,o),p=Ta(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=Sa(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=Sa(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=Sa(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=Sa(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>=Po&&(Po=e+1),t}let n=`tc_${e}_${Po++}`;for(;this.instances.has(n);)n=`tc_${e}_${Po++}`;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),Pa(n.style.colors)){let t=n.plugin.descriptor.placement,r=n.config.pane??null,i=[...this.instances.values()];ya(i,t,r,e).has(n.style.colors[0])&&(n.style.colors=Na(ba(i,n.config.id,t,r,e)))}return!0}getOutput(e){return this.flush(),this.instances.get(e)?.output??null}peekOutput(e){return this.runPending(),this.instances.get(e)?.output??null}isComputingInWorker(e){return this.worker.computing(e)}stopWorker(){this.worker.stop()}renderOverlays(e,t,n){for(let r of this.overlayDraws(t,n))r(e)}overlayDraws(e,t){this.runPending();let n=[];for(let r of this.instances.values()){let i=r.output;if(!i||!la(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(){return[...this.instances.values()].some(e=>e.config.scale===`left`&&la(e))}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.runPending();let r=this.instances.get(t);!r?.output||!la(r)||r.plugin.render(e,r.output,n,r.style)}getLatestValues(e){this.runPending();let t=this.instances.get(e);return t?fa(t):[]}getLatestOverlayValues(e=`right`){return this.runPending(),pa(this.instances.values(),e)}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?la(t):!1}setTimeframe(e){this.timeframe=e;let t=!1;for(let e of this.instances.values())t=this.placeOnInterval(e)||t;return t}setExchangeTimeZone(e,n){let r=e&&!(0,t.isUtcTimeZone)(e)&&(0,t.isValidTimeZone)(e)?e:null;if(r===this.exchangeTimeZone)return!1;this.exchangeTimeZone=r;for(let{config:e}of this.instances.values())r?e.exchangeTimeZone=r:delete e.exchangeTimeZone;if(n){let e=this.waitingOn(n).full;for(let t of this.zoneDependents())e.add(t)}return!0}zoneDependents(){let e=new Set;for(let t of this.instances.values())if(Fo(t.plugin)){e.add(t.config.instanceId);for(let n of this.getDependents(t.config.instanceId))e.add(n)}return e}setIntervals(e,t){let n=this.instances.get(e);if(!n)return!1;let r=t?Ma(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?Ia(t):null}setBarsTimed(e){if(e===this.barsTimed)return!1;this.barsTimed=e;let t=!1;for(let e of this.instances.values())t=this.placeOnChartType(e)||t;return t}placeOnChartType(e){let t=eo.has(e.config.id)||e.plugin.descriptor.readsExchangeTimeZone===!0,n=!this.barsTimed&&t;return n===e.offChartType?!1:(e.offChartType=n,!0)}placeOnInterval(e){let t=!ja(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){return this.runPending(),ma(this.paneInstances(e),t,n,r)}getPaneValuesAt(e,t){return this.runPending(),ha(this.paneInstances(e),t)}paneInstances(e){return[e,...this.getPaneMembers(e)].map(e=>this.instances.get(e)).filter(e=>e!==void 0)}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:la(n),...n.offChartType?{offChartType:!0}:{},...n.config.intervals?{intervals:Ia(n.config.intervals)}:{},...n.config.pane?{pane:n.config.pane}:{},...n.config.scale===`left`?{scale:`left`}:{}});return e}orderIndicators(e){let t=new Map;for(let n of e){let e=this.instances.get(n);e&&!t.has(n)&&t.set(n,e)}for(let[e,n]of this.instances)t.has(e)||t.set(e,n);this.instances=t,this.order=null}getIndicatorStyle(e){let t=this.instances.get(e)?.style;return t?{colors:[...t.colors],lineWidths:[...t.lineWidths],opacity:t.opacity,...t.plots?{plots:Fa(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=Fa(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=Fa(t):delete n.style.plots)}setStyleDefaults(e,t){t?this.styleDefaults.set(e,{...t,...t.plots?{plots:Fa(t.plots)}:{}}):this.styleDefaults.delete(e)}getOverlayPriceRange(e,t,n=`right`){return this.runPending(),va(this.instances.values(),e,t,n)}getPanelIndicators(){return[...this.instances.values()].filter(e=>e.plugin.descriptor.placement===`panel`).map(e=>({instanceId:e.config.instanceId,descriptor:e.plugin.descriptor}))}};function H(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 U(e,t,n,r=1){let i=H(e,t,n);return Math.max(r,Math.floor(i))}var Lo=class extends I{descriptor={id:`sma`,name:`Simple Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`SMA`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`SMA`,color:0}]};calculate(e,t){let n=U(t,`period`,20,1),r=new L,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=U(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}},Ro=class extends I{descriptor={id:`ema`,name:`Exponential Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`EMA`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`EMA`,color:0}]};calculate(e,t){let n=U(t,`period`,20,1),r=2/(n+1),i=new L,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=U(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}},zo=class extends I{descriptor={id:`bb`,name:`Bollinger Bands`,placement:`overlay`,defaultConfig:{period:20,stdDev:2,source:`close`},shortName:`BB`,inputs:{source:{source:!0},period:{kind:`int`,min:1},stdDev:{kind:`number`,min:.1,step:.1}},fills:[{between:[`upper`,`lower`],color:0,opacity:.1}],plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=U(t,`period`,20,1),r=H(t,`stdDev`,2),i=new L,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=U(t,`period`,20,1),a=H(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}},Bo=[`session`,`week`,`month`,`all`],Vo=64,Ho=2;function Uo(e){let t=e.params.anchor;return Bo.includes(t)?t:`session`}function Wo(e,t){let n=Uo(t);return n===`all`?null:jt(e,n,t.exchangeTimeZone)}var Go=class extends I{descriptor={readsExchangeTimeZone:!0,id:`vwap`,name:`Volume Weighted Average Price`,placement:`overlay`,defaultConfig:{anchor:`session`},shortName:`VWAP`,inputs:{anchor:{options:Bo}},plots:[{key:`value`,title:`VWAP`,color:0,breakOn:`session`}]};kept=new WeakMap;workerState(e){return this.kept.get(e)}adoptWorkerState(e,t){t&&this.kept.set(e,t)}calculate(e,t){let n={values:new L,series:Array(e.length).fill(null)},r=Wo(e,t),i=this.fill(n,e,r,0,null);return r&&this.kept.set(n,i),n}update(e,t,n,r){let i=Wo(e,t),a=this.kept.get(n)??[],o=a.find(e=>e.index===r-1);if(!i||!o||r<Vo||r>=e.length||!this.canResume(e,n,r))return null;n.series.length=e.length;let s=this.fill(n,e,i,r,o),c=a.filter(t=>t.index<r&&t.index>=e.length-Ho);return this.kept.set(n,[...c,...s]),n}fill(e,t,n,r,i){let a=i&&n?n(t[i.index].time):void 0,o=i?.volume??0,s=i?.volumePrice??0,c=[];for(let i=r;i<t.length;i++){let r=t[i];if(n){let e=n(r.time);e!==a&&(o=0,s=0,a=e)}o+=r.volume,s+=(r.high+r.low+r.close)/3*r.volume,i>=t.length-Ho&&c.push({index:i,volume:o,volumePrice:s});let l=o>0?a===void 0?{value:s/o}:{value:s/o,session:a}:null;this.writePoint(e,t,i,l)}return c}},Ko=4,qo=t.TC_SERIES_COLORS[Ko],Jo=class extends I{descriptor={id:`ichimoku`,name:`Ichimoku Cloud`,placement:`overlay`,defaultConfig:{tenkan:9,kijun:26,senkou:52,displacement:26},inputs:{tenkan:{kind:`int`,min:1},kijun:{kind:`int`,min:1},senkou:{kind:`int`,min:1},displacement:{kind:`int`,min:0}},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},{key:`chikou`,title:`Lagging Span`,color:Ko}]};calculate(e,t){let n=U(t,`tenkan`,9,1),r=U(t,`kijun`,26,1),i=U(t,`senkou`,52,1),a=U(t,`displacement`,26,0),o=new L,s=Array(e.length).fill(null),c=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}},l=c(n),u=c(r),d=c(i),f=(e,t,n)=>n>=t-1?(e.highs[n]+e.lows[n])/2:void 0,p=e=>{let t=f(l,n,e),a=f(u,r,e),o={};t!==void 0&&a!==void 0&&(o.senkouA=(t+a)/2);let s=f(d,i,e);return s!==void 0&&(o.senkouB=s),o};for(let t=0;t<e.length;t++){let i={},c=f(l,n,t);c!==void 0&&(i.tenkan=c);let d=f(u,r,t);d!==void 0&&(i.kijun=d),t>=a&&Object.assign(i,p(t-a)),t+a<e.length&&(i.chikou=e[t+a].close),Object.keys(i).length>0&&(o.set(e[t].time,i),s[t]=i)}let m=Math.max(0,e.length-a),h=[];for(let t=m;t<e.length;t++)h.push(p(t));return{values:o,series:s,meta:{ahead:h,aheadFrom:m+a}}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=r.meta?.ahead,u=r.meta?.aheadFrom??o.length,d=c-s+1,f=d+(l?.length??0),p=new Float64Array(d),m=new Float64Array(d),h=0,g=new Float64Array(d),_=new Float64Array(d),v=0,y=new Float64Array(f),b=new Float64Array(f),x=0,S=new Float64Array(f),C=new Float64Array(f),w=0,T=new Float64Array(d),E=new Float64Array(d),D=0,ee=new Float64Array(f),O=new Float64Array(f),k=new Float64Array(f),A=0,te=(t,n)=>{let r=n.senkouA,a=n.senkouB;r!==void 0&&(y[x]=t,b[x]=e.O(r,i),x++),a!==void 0&&(S[w]=t,C[w]=e.O(a,i),w++),r!==void 0&&a!==void 0&&(ee[A]=t,O[A]=b[x-1],k[A]=C[w-1],A++)};for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n)continue;let r=e.C(t,i);n.tenkan!==void 0&&(p[h]=r,m[h]=e.O(n.tenkan,i),h++),n.kijun!==void 0&&(g[v]=r,_[v]=e.O(n.kijun,i),v++),te(r,n),n.chikou!==void 0&&(T[D]=r,E[D]=e.O(n.chikou,i),D++)}if(l){let t=i.chartRect.x-i.barWidth-i.barSpacing,n=i.chartRect.x+i.chartRect.width+i.barWidth+i.barSpacing;for(let r=0;r<l.length;r++){let a=e.C(u+r,i);if(a>n)break;a>=t&&te(a,l[r])}}if(A>1){n.beginPath(),n.moveTo(ee[0],O[0]);for(let e=1;e<A;e++)n.lineTo(ee[e],O[e]);for(let e=A-1;e>=0;e--)n.lineTo(ee[e],k[e]);n.closePath(),n.fillStyle=(0,t.withAlpha)(a.colors[2]??`#1fa874`,.15),n.fill()}let ne=(e,t,r,i,o,s)=>{let c=Yi(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([])}};ne(`tenkan`,p,m,h,a.colors[0],a.lineWidths[0]),ne(`kijun`,g,_,v,a.colors[1]??`#f2a93b`,a.lineWidths[0]),ne(`senkouA`,y,b,x,a.colors[2]??`#1fa874`,1),ne(`senkouB`,S,C,w,a.colors[3]??`#e8505b`,1),ne(`chikou`,T,E,D,a.colors[Ko]??qo,1)}},Yo=class extends I{descriptor={id:`psar`,name:`Parabolic SAR`,placement:`overlay`,defaultConfig:{step:.02,max:.2},inputs:{step:{kind:`number`,min:.01,step:.01},max:{kind:`number`,min:.01,step:.01}},shortName:`SAR`,plots:[{key:`value`,title:`SAR`,color:0,kind:`dots`,tone:{field:`trend`},downColor:1}]};calculate(e,t){let n=H(t,`step`,.02),r=H(t,`max`,.2),i=new L,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}}},Xo=class extends I{descriptor={id:`supertrend`,name:`Supertrend`,placement:`overlay`,defaultConfig:{period:10,multiplier:3},inputs:{period:{kind:`int`,min:1},multiplier:{kind:`number`,min:.1,step:.1}},shortName:`Supertrend`,plots:[{key:`value`,title:`Supertrend`,color:0,tone:{field:`trend`},downColor:1}]};calculate(e,t){let n=U(t,`period`,10,1),r=H(t,`multiplier`,3),i=new L,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,v=e[Math.max(0,t-1)].close;c=g<u||v>u?g:u,l=_>d||v<d?_:d,f=p===u?e[t].close<=c?c:l:e[t].close>=l?l:c,m=f===l?1:-1;let y={value:f,trend:m};i.set(e[t].time,y),a[t]=y,u=c,d=l,p=f}return{values:i,series:a}}},Zo=class extends I{descriptor={id:`keltner`,name:`Keltner Channel`,placement:`overlay`,defaultConfig:{emaPeriod:20,atrPeriod:10,multiplier:1.5},inputs:{emaPeriod:{kind:`int`,min:1},atrPeriod:{kind:`int`,min:1},multiplier:{kind:`number`,min:.1,step:.1}},shortName:`KC`,fills:[{between:[`upper`,`lower`],color:0,opacity:.08}],plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=U(t,`emaPeriod`,20,1),r=U(t,`atrPeriod`,10,1),i=H(t,`multiplier`,1.5),a=new L;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}}},Qo=class extends I{descriptor={id:`donchian`,name:`Donchian Channel`,placement:`overlay`,defaultConfig:{period:20},inputs:{period:{kind:`int`,min:1}},shortName:`DC`,fills:[{between:[`upper`,`lower`],color:0,opacity:.08}],plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1,width:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=U(t,`period`,20,1),r=new L,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}}},$o=[`traditional`,`fibonacci`,`woodie`,`classic`,`camarilla`,`dm`],es=class extends I{descriptor={id:`pivots`,name:`Pivot Points`,placement:`overlay`,defaultConfig:{lookback:24,type:`traditional`},shortName:`Pivots`,inputs:{lookback:{kind:`int`,min:1},type:{options:$o}},plots:[{key:`r3`,title:`R3`,color:1,width:1,lineStyle:`dashed`},{key:`r2`,title:`R2`,color:1,width:1,lineStyle:`dashed`},{key:`r1`,title:`R1`,color:1,width:1,lineStyle:`dashed`},{key:`pp`,title:`P`,color:0},{key:`s1`,title:`S1`,color:2,width:1,lineStyle:`dashed`},{key:`s2`,title:`S2`,color:2,width:1,lineStyle:`dashed`},{key:`s3`,title:`S3`,color:2,width:1,lineStyle:`dashed`}]};calculate(e,t){let n=U(t,`lookback`,24,1),r=$o.includes(t.params.type)?t.params.type:`traditional`,i=new L,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=ts(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}}};function ts(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 ns=class extends I{descriptor={id:`avwap`,name:`Anchored VWAP`,placement:`overlay`,defaultConfig:{anchorTime:0},inputs:{anchorTime:{kind:`int`}},shortName:`AVWAP`,plots:[{key:`value`,title:`AVWAP`,color:0}]};calculate(e,n){let r=H(n,`anchorTime`,0),i=new L,a=Array(e.length).fill(null),o=0;if(r>0){let n=(0,t.barTimeUnit)(e),s=(0,t.normalizeBarTime)(r);if(o=e.findIndex(e=>e.time*n>=s),o<0)return{values:i,series:a}}let s=0,c=0;for(let t=o;t<e.length;t++){let n=(e[t].high+e[t].low+e[t].close)/3;if(s+=e[t].volume,c+=n*e[t].volume,s>0){let n={value:c/s};i.set(e[t].time,n),a[t]=n}}return{values:i,series:a}}},rs=class extends I{descriptor={id:`zigzag`,name:`ZigZag`,placement:`overlay`,defaultConfig:{deviation:5},inputs:{deviation:{kind:`number`,min:.1,step:.1}},shortName:`ZigZag`,plots:[{key:`pivot`,title:`Pivot`,color:0}]};calculate(e,t){let n=Math.max(.01,H(t,`deviation`,5))/100,r=new L,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.C(i.idx,r),s=e.O(i.price,r);n===0?t.moveTo(o,s):t.lineTo(o,s)}t.stroke()}}},is=class extends I{descriptor={id:`lrc`,name:`Linear Regression Channel`,placement:`overlay`,defaultConfig:{period:100,stdDev:2,source:`close`},shortName:`LRC`,inputs:{source:{source:!0},period:{kind:`int`,min:2},stdDev:{kind:`number`,min:.1,step:.1}},fills:[{between:[`upper`,`lower`],color:0,opacity:.08}],plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=U(t,`period`,100,2),r=H(t,`stdDev`,2),i=new L,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}}},as=class extends I{descriptor={id:`hma`,name:`Hull Moving Average`,placement:`overlay`,defaultConfig:{period:21,source:`close`},shortName:`HMA`,inputs:{source:{source:!0},period:{kind:`int`,min:2}},plots:[{key:`value`,title:`HMA`,color:0}]};calculate(e,t){let n=U(t,`period`,21,2),r=new L,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=os(a,n),l=os(a,o),u=ss(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}}};function os(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 ss(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 cs=class extends I{descriptor={readsExchangeTimeZone:!0,id:`mtfma`,name:`MTF Moving Average`,placement:`overlay`,defaultConfig:{period:50,timeframe:`1d`,source:`close`},shortName:`MTF MA`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`MA`,color:0}]};calculate(e,t){let n=U(t,`period`,50,1),r=String(t.params.timeframe??`1d`),i=new L,a=Array(e.length).fill(null);if(e.length===0)return{values:i,series:a};let o=[],s=jt(e,r,t.exchangeTimeZone),c=s(e[0].time),l=e[0].close,u=null,d=()=>{if(o.length<n)return;let e=0;for(let t=o.length-n;t<o.length;t++)e+=o[t];u=e/n};for(let t=0;t<e.length;t++){let n=s(e[t].time);if(n!==c&&(o.push(l),d(),c=n),l=e[t].close,u!==null){let n={value:u};i.set(e[t].time,n),a[t]=n}}return{values:i,series:a}}},ls=class extends I{descriptor={readsExchangeTimeZone:!0,id:`svwap`,name:`Session VWAP`,placement:`overlay`,defaultConfig:{bands:1},inputs:{bands:{kind:`int`,min:0,max:3}},shortName:`SVWAP`,plots:[{key:`value`,title:`VWAP`,color:0,breakOn:`session`},{key:`u1`,title:`+1σ`,color:1,width:1,lineStyle:`dashed`,opacity:.55,breakOn:`session`},{key:`l1`,title:`−1σ`,color:1,width:1,lineStyle:`dashed`,opacity:.55,breakOn:`session`},{key:`u2`,title:`+2σ`,color:1,width:1,lineStyle:`dashed`,opacity:.55,breakOn:`session`},{key:`l2`,title:`−2σ`,color:1,width:1,lineStyle:`dashed`,opacity:.55,breakOn:`session`},{key:`u3`,title:`+3σ`,color:1,width:1,lineStyle:`dashed`,opacity:.55,breakOn:`session`},{key:`l3`,title:`−3σ`,color:1,width:1,lineStyle:`dashed`,opacity:.55,breakOn:`session`}]};calculate(e,n){let r=(0,t.barsAreDaily)(e)===!0?0:Math.min(3,U(n,`bands`,1,0)),i=new L,a=Array(e.length).fill(null);if(e.length===0)return{values:i,series:a};let o=jt(e,`session`,n.exchangeTimeZone),s=o(e[0].time),c=0,l=0,u=0;for(let t=0;t<e.length;t++){let n=e[t],d=o(n.time);d!==s&&(c=0,l=0,u=0,s=d);let f=(n.high+n.low+n.close)/3;if(c+=f*n.volume,l+=f*f*n.volume,u+=n.volume,u>0){let e=c/u,o={value:e,session:s};if(r>0){let t=Math.max(0,l/u-e*e),n=Math.sqrt(t);for(let t=1;t<=r;t++)o[`u${t}`]=e+t*n,o[`l${t}`]=e-t*n}i.set(n.time,o),a[t]=o}}return{values:i,series:a}}},us=class extends I{descriptor={id:`chandelier`,name:`Chandelier Exit`,placement:`overlay`,defaultConfig:{period:22,multiplier:3},inputs:{period:{kind:`int`,min:1},multiplier:{kind:`number`,min:.1,step:.1}},shortName:`CE`,plots:[{key:`long`,title:`Long`,color:0,lineStyle:`dashed`},{key:`short`,title:`Short`,color:1,lineStyle:`dashed`}]};calculate(e,t){let n=U(t,`period`,22,1),r=H(t,`multiplier`,3),i=new L,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}}},ds=class extends I{descriptor={id:`alligator`,name:`Alligator`,placement:`overlay`,defaultConfig:{jaw:13,teeth:8,lips:5,jawShift:8,teethShift:5,lipsShift:3},inputs:{jaw:{kind:`int`,min:1},teeth:{kind:`int`,min:1},lips:{kind:`int`,min:1},jawShift:{kind:`int`,min:0},teethShift:{kind:`int`,min:0},lipsShift:{kind:`int`,min:0}},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=U(t,`jaw`,13,1),r=U(t,`teeth`,8,1),i=U(t,`lips`,5,1),a=U(t,`jawShift`,8,0),o=U(t,`teethShift`,5,0),s=U(t,`lipsShift`,3,0),c=new L,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=fs(d,n),p=fs(d,r),m=fs(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}}};function fs(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 ps=class extends I{descriptor={id:`vwma`,name:`Volume Weighted Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`VWMA`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`VWMA`,color:0}]};calculate(e,t){let n=U(t,`period`,20,1),r=new L,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=U(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}},ms=class extends I{descriptor={id:`wma`,name:`Weighted Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`WMA`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`WMA`,color:0}]};calculate(e,t){let n=U(t,`period`,20,1),r=new L,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=U(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}},hs=class extends I{descriptor={id:`envelope`,name:`Moving Average Envelope`,placement:`overlay`,defaultConfig:{period:20,percent:2.5,source:`close`},shortName:`Env`,inputs:{source:{source:!0},period:{kind:`int`,min:1},percent:{kind:`number`,min:0,step:.1}},fills:[{between:[`upper`,`lower`],color:0,opacity:.08}],plots:[{key:`upper`,title:`Upper`,color:0},{key:`basis`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=U(t,`period`,20,1),r=H(t,`percent`,2.5)/100,i=new L,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=U(t,`period`,20,1),a=H(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}};function gs(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 _s(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 vs(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 ys=class extends I{descriptor={id:`tema`,name:`Triple EMA`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`TEMA`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`TEMA`,color:0}]};calculate(e,t){let n=U(t,`period`,20,1),r=new L,i=Array(e.length).fill(null),a=gs(e.map(e=>e.close),n),o=vs(a),s=_s(gs(o.values,n),o.indices,e.length),c=vs(s),l=_s(gs(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}}},bs=class extends I{descriptor={id:`ao`,name:`Awesome Oscillator`,placement:`panel`,defaultConfig:{fast:5,slow:34},inputs:{fast:{kind:`int`,min:1},slow:{kind:`int`,min:1}},shortName:`AO`,plots:[{key:`value`,title:`AO`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}]};calculate(e,t){let n=U(t,`fast`,5,1),r=U(t,`slow`,34,1),i=new L,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}}},xs=class extends I{descriptor={id:`chaikinOsc`,name:`Chaikin Oscillator`,placement:`panel`,defaultConfig:{fast:3,slow:10},inputs:{fast:{kind:`int`,min:1},slow:{kind:`int`,min:1}},shortName:`Chaikin Osc`,plots:[{key:`value`,title:`Chaikin`,color:0,kind:`histogram`,tone:`sign`,downColor:1}]};calculate(e,t){let n=U(t,`fast`,3,1),r=U(t,`slow`,10,1),i=new L,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}}},Ss=class extends I{descriptor={id:`rsi`,name:`Relative Strength Index`,placement:`panel`,defaultConfig:{period:14,source:`close`},shortName:`RSI`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`RSI`,color:0}],scale:{min:0,max:100},levels:[30,70]};smoothing=new WeakMap;workerState(e){return this.smoothing.get(e)}adoptWorkerState(e,t){t&&this.smoothing.set(e,t)}calculate(e,t){let n=U(t,`period`,14,1),r=new L,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=U(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}},Cs=class extends I{descriptor={id:`macd`,name:`MACD`,placement:`panel`,defaultConfig:{fast:12,slow:26,signal:9,source:`close`},shortName:`MACD`,inputs:{source:{source:!0},fast:{kind:`int`,min:1},slow:{kind:`int`,min:1},signal:{kind:`int`,min:1}},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;workerState(e){return this.emas.get(e)}adoptWorkerState(e,t){t&&this.emas.set(e,t)}calculate(e,t){let n=U(t,`fast`,12,1),r=U(t,`slow`,26,1),i=U(t,`signal`,9,1),a=new L,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=U(t,`fast`,12,1),a=U(t,`slow`,26,1),o=U(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}},ws=class extends I{descriptor={id:`stochastic`,name:`Stochastic Oscillator`,placement:`panel`,defaultConfig:{kPeriod:14,dPeriod:3,smooth:3},inputs:{kPeriod:{kind:`int`,min:1},dPeriod:{kind:`int`,min:1},smooth:{kind:`int`,min:1}},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=U(t,`kPeriod`,14,1),r=U(t,`dPeriod`,3,1),i=U(t,`smooth`,3,1),a=new L,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=U(t,`kPeriod`,14,1),a=U(t,`dPeriod`,3,1),o=U(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}},Ts=class extends I{descriptor={id:`atr`,name:`Average True Range`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`ATR`,plots:[{key:`value`,title:`ATR`,color:0}]};calculate(e,t){let n=U(t,`period`,14,1),r=new L,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=U(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}},Es=class extends I{descriptor={id:`adx`,name:`Average Directional Index`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},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=U(t,`period`,14,1),r=new L,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}}},Ds=class extends I{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 L,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}},Os=class extends I{descriptor={id:`williamsR`,name:`Williams %R`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`%R`,plots:[{key:`value`,title:`%R`,color:0}],scale:{min:-100,max:0},levels:[-80,-20]};calculate(e,t){let n=U(t,`period`,14,1),r=new L,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}}},ks=class extends I{descriptor={id:`cci`,name:`Commodity Channel Index`,placement:`panel`,defaultConfig:{period:20},inputs:{period:{kind:`int`,min:1}},shortName:`CCI`,plots:[{key:`value`,title:`CCI`,color:0}],levels:[-100,0,100]};calculate(e,t){let n=U(t,`period`,20,1),r=new L,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}}},As=class extends I{descriptor={id:`mfi`,name:`Money Flow Index`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`MFI`,plots:[{key:`value`,title:`MFI`,color:0}],scale:{min:0,max:100},levels:[20,80]};calculate(e,t){let n=U(t,`period`,14,1),r=new L,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}}},js=class extends I{descriptor={id:`aroon`,name:`Aroon`,placement:`panel`,defaultConfig:{period:25},inputs:{period:{kind:`int`,min:1}},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=U(t,`period`,25,1),r=new L,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}}},Ms=class extends I{descriptor={id:`roc`,name:`Rate of Change`,placement:`panel`,defaultConfig:{period:12,source:`close`},shortName:`ROC`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`ROC`,color:0}],levels:[0]};calculate(e,t){let n=U(t,`period`,12,1),r=new L,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}}},Ns=class extends I{descriptor={id:`tsi`,name:`True Strength Index`,placement:`panel`,defaultConfig:{longPeriod:25,shortPeriod:13,signalPeriod:7,source:`close`},shortName:`TSI`,inputs:{source:{source:!0},longPeriod:{kind:`int`,min:1},shortPeriod:{kind:`int`,min:1},signalPeriod:{kind:`int`,min:1}},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=U(t,`longPeriod`,25,1),r=U(t,`shortPeriod`,13,1),i=U(t,`signalPeriod`,7,1),a=new L,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}}},Ps=class extends I{descriptor={id:`cmf`,name:`Chaikin Money Flow`,placement:`panel`,defaultConfig:{period:20},inputs:{period:{kind:`int`,min:1}},shortName:`CMF`,plots:[{key:`value`,title:`CMF`,color:0,kind:`histogram`,tone:`sign`,downColor:1}]};calculate(e,t){let n=U(t,`period`,20,1),r=new L,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}}},Fs=class extends I{descriptor={id:`voldelta`,name:`Volume Delta`,placement:`panel`,defaultConfig:{mode:0},inputs:{mode:{kind:`int`,min:0,max:1}},shortName:`Vol Δ`,plots:[{key:`value`,title:`Delta`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}]};calculate(e,t){let n=H(t,`mode`,0)>=1,r=new L,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}}},Is=class extends I{descriptor={id:`vortex`,name:`Vortex Indicator`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`VI`,plots:[{key:`viPlus`,title:`VI+`,color:0},{key:`viMinus`,title:`VI−`,color:1}],levels:[1]};calculate(e,t){let n=U(t,`period`,14,1),r=new L,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}}},Ls=class extends I{descriptor={id:`chop`,name:`Choppiness Index`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:2}},shortName:`CHOP`,plots:[{key:`value`,title:`CHOP`,color:0}],scale:{min:0,max:100},levels:[38.2,61.8]};calculate(e,t){let n=U(t,`period`,14,2),r=new L,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}}},Rs=class extends I{descriptor={id:`uo`,name:`Ultimate Oscillator`,placement:`panel`,defaultConfig:{fast:7,mid:14,slow:28},inputs:{fast:{kind:`int`,min:1},mid:{kind:`int`,min:1},slow:{kind:`int`,min:1}},shortName:`UO`,plots:[{key:`value`,title:`UO`,color:0}],scale:{min:0,max:100},levels:[30,70]};calculate(e,t){let n=U(t,`fast`,7,1),r=U(t,`mid`,14,1),i=U(t,`slow`,28,1),a=new L,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=zs(l(s,t,n),l(c,t,n)),d=zs(l(s,t,r),l(c,t,r)),f=zs(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 zs(e,t){return t===0?0:e/t}var Bs=class extends I{descriptor={id:`fi`,name:`Force Index`,placement:`panel`,defaultConfig:{period:13},inputs:{period:{kind:`int`,min:1}},shortName:`EFI`,plots:[{key:`value`,title:`EFI`,color:0}],levels:[0]};calculate(e,t){let n=U(t,`period`,13,1),r=new L,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}}},Vs=class extends I{descriptor={id:`crsi`,name:`Connors RSI`,placement:`panel`,defaultConfig:{rsiPeriod:3,streakPeriod:2,rankPeriod:100,source:`close`},shortName:`CRSI`,inputs:{source:{source:!0},rsiPeriod:{kind:`int`,min:1},streakPeriod:{kind:`int`,min:1},rankPeriod:{kind:`int`,min:1}},plots:[{key:`value`,title:`CRSI`,color:0}],scale:{min:0,max:100},levels:[10,90]};calculate(e,t){let n=U(t,`rsiPeriod`,3,1),r=U(t,`streakPeriod`,2,1),i=U(t,`rankPeriod`,100,1),a=new L,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=Hs(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=Hs(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 Hs(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 Us=class extends I{descriptor={id:`coppock`,name:`Coppock Curve`,placement:`panel`,defaultConfig:{longRoc:14,shortRoc:11,wma:10,source:`close`},shortName:`Coppock`,inputs:{source:{source:!0},longRoc:{kind:`int`,min:1},shortRoc:{kind:`int`,min:1},wma:{kind:`int`,min:1}},plots:[{key:`value`,title:`Coppock`,color:0}],levels:[0]};calculate(e,t){let n=U(t,`longRoc`,14,1),r=U(t,`shortRoc`,11,1),i=U(t,`wma`,10,1),a=new L,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}}},Ws=class extends I{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},roc1:{kind:`int`,min:1},roc2:{kind:`int`,min:1},roc3:{kind:`int`,min:1},roc4:{kind:`int`,min:1},sma1:{kind:`int`,min:1},sma2:{kind:`int`,min:1},sma3:{kind:`int`,min:1},sma4:{kind:`int`,min:1},signal:{kind:`int`,min:1}},plots:[{key:`value`,title:`KST`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=U(t,`roc1`,10,1),r=U(t,`roc2`,15,1),i=U(t,`roc3`,20,1),a=U(t,`roc4`,30,1),o=U(t,`sma1`,10,1),s=U(t,`sma2`,10,1),c=U(t,`sma3`,10,1),l=U(t,`sma4`,15,1),u=U(t,`signal`,9,1),d=new L,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=Ks(Gs(m,n),o),g=Ks(Gs(m,r),s),_=Ks(Gs(m,i),c),v=Ks(Gs(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=Ks(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 Gs(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 Ks(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 qs=class extends I{descriptor={id:`elderray`,name:`Elder Ray`,placement:`panel`,defaultConfig:{period:13},inputs:{period:{kind:`int`,min:1}},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=U(t,`period`,13,1),r=new L,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.k(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.C(i,r)+p,Math.min(s,l),u,Math.max(1,Math.abs(s-l)))}t.fill()}}},Js=class extends I{descriptor={id:`stc`,name:`Schaff Trend Cycle`,placement:`panel`,defaultConfig:{fast:23,slow:50,cycle:10,source:`close`},shortName:`STC`,inputs:{source:{source:!0},fast:{kind:`int`,min:1},slow:{kind:`int`,min:1},cycle:{kind:`int`,min:1}},plots:[{key:`value`,title:`STC`,color:0}],scale:{min:0,max:100},levels:[25,75]};calculate(e,t){let n=U(t,`fast`,23,1),r=U(t,`slow`,50,1),i=U(t,`cycle`,10,1),a=new L,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=Ys(Ys(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 Ys(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 Xs=class extends I{descriptor={id:`kvo`,name:`Klinger Oscillator`,placement:`panel`,defaultConfig:{fast:34,slow:55,signal:13},inputs:{fast:{kind:`int`,min:1},slow:{kind:`int`,min:1},signal:{kind:`int`,min:1}},shortName:`KVO`,plots:[{key:`value`,title:`KVO`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=U(t,`fast`,34,1),r=U(t,`slow`,55,1),i=U(t,`signal`,13,1),a=new L,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}}},Zs=class extends I{descriptor={id:`fisher`,name:`Fisher Transform`,placement:`panel`,defaultConfig:{period:9},inputs:{period:{kind:`int`,min:1}},shortName:`Fisher`,plots:[{key:`value`,title:`Fisher`,color:0},{key:`trigger`,title:`Trigger`,color:1}],levels:[0]};calculate(e,t){let n=U(t,`period`,9,1),r=new L,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}}},Qs=class extends I{descriptor={id:`dpo`,name:`Detrended Price Oscillator`,placement:`panel`,defaultConfig:{period:20,source:`close`},shortName:`DPO`,inputs:{source:{source:!0},period:{kind:`int`,min:2}},plots:[{key:`value`,title:`DPO`,color:0,kind:`histogram`,tone:`sign`,downColor:1}]};calculate(e,t){let n=U(t,`period`,20,2),r=Math.floor(n/2)+1,i=new L,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}}},$s=class extends I{descriptor={id:`bop`,name:`Balance of Power`,placement:`panel`,defaultConfig:{smooth:14},inputs:{smooth:{kind:`int`,min:1}},shortName:`BOP`,plots:[{key:`value`,title:`BOP`,color:0}],scale:{min:-1,max:1},levels:[0]};calculate(e,t){let n=U(t,`smooth`,14,1),r=new L,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}}},ec=class extends I{descriptor={id:`massindex`,name:`Mass Index`,placement:`panel`,defaultConfig:{ema:9,sum:25},inputs:{ema:{kind:`int`,min:1},sum:{kind:`int`,min:1}},shortName:`Mass`,plots:[{key:`value`,title:`Mass`,color:0}],levels:[26.5,27]};calculate(e,t){let n=U(t,`ema`,9,1),r=U(t,`sum`,25,1),i=new L,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}}},tc=class extends I{descriptor={id:`cmo`,name:`Chande Momentum`,placement:`panel`,defaultConfig:{period:9,source:`close`},shortName:`CMO`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`CMO`,color:0}],scale:{min:-100,max:100},levels:[-50,0,50]};calculate(e,t){let n=U(t,`period`,9,1),r=new L,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}}},nc=class extends I{descriptor={id:`trix`,name:`TRIX`,placement:`panel`,defaultConfig:{period:15,signal:9,source:`close`},shortName:`TRIX`,inputs:{source:{source:!0},period:{kind:`int`,min:1},signal:{kind:`int`,min:1}},plots:[{key:`value`,title:`TRIX`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=U(t,`period`,15,1),r=U(t,`signal`,9,1),i=new L,a=Array(e.length).fill(null),o=e.length;if(o<2)return{values:i,series:a};let s=rc(rc(rc(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=rc(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 rc(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 ic=class extends I{descriptor={id:`emv`,name:`Ease of Movement`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`EOM`,plots:[{key:`value`,title:`EOM`,color:0}],levels:[0]};calculate(e,t){let n=U(t,`period`,14,1),r=new L,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}}},ac=class extends I{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 L,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}}},oc=class extends I{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 L,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}}},sc=class extends I{descriptor={id:`chaikinvol`,name:`Chaikin Volatility`,placement:`panel`,defaultConfig:{ema:10,roc:10},inputs:{ema:{kind:`int`,min:1},roc:{kind:`int`,min:1}},shortName:`CV`,plots:[{key:`value`,title:`CV`,color:0}],levels:[0]};calculate(e,t){let n=U(t,`ema`,10,1),r=U(t,`roc`,10,1),i=new L,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}}},cc=class extends I{descriptor={id:`rvi`,name:`Relative Vigor Index`,placement:`panel`,defaultConfig:{period:10},inputs:{period:{kind:`int`,min:1}},shortName:`RVGI`,plots:[{key:`value`,title:`RVGI`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=U(t,`period`,10,1),r=new L,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}}},lc=class extends I{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},rsiPeriod:{kind:`int`,min:1},stochPeriod:{kind:`int`,min:1},k:{kind:`int`,min:1},d:{kind:`int`,min:1}},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=U(t,`rsiPeriod`,14,1),r=U(t,`stochPeriod`,14,1),i=U(t,`k`,3,1),a=U(t,`d`,3,1),o=new L,s=Array(e.length).fill(null),c=e.length;if(c<=n+r)return{values:o,series:s};let l=uc(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=dc(u,i),f=dc(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 uc(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 dc(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 fc=class extends I{descriptor={id:`ppo`,name:`Percentage Price Oscillator`,placement:`panel`,defaultConfig:{fast:12,slow:26,signal:9,source:`close`},shortName:`PPO`,inputs:{source:{source:!0},fast:{kind:`int`,min:1},slow:{kind:`int`,min:1},signal:{kind:`int`,min:1}},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=U(t,`fast`,12,1),r=U(t,`slow`,26,1),i=U(t,`signal`,9,1),a=new L,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=pc(c,n),u=pc(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=pc(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 pc(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 mc=class extends I{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 L,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]=hc(i,e,5)-hc(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 hc(e,t,n){let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i];return r/n}var gc=class extends I{descriptor={id:`rmi`,name:`Relative Momentum Index`,placement:`panel`,defaultConfig:{period:20,momentum:5,source:`close`},shortName:`RMI`,inputs:{source:{source:!0},period:{kind:`int`,min:1},momentum:{kind:`int`,min:1}},plots:[{key:`value`,title:`RMI`,color:0}],scale:{min:0,max:100},levels:[30,70]};calculate(e,t){let n=U(t,`period`,20,1),r=U(t,`momentum`,5,1),i=new L,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}}},_c=class extends I{descriptor={id:`disparity`,name:`Disparity Index`,placement:`panel`,defaultConfig:{period:14,source:`close`},shortName:`DI`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`DI`,color:0}],levels:[0]};calculate(e,t){let n=U(t,`period`,14,1),r=new L,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}}},vc=class extends I{descriptor={id:`qstick`,name:`Qstick`,placement:`panel`,defaultConfig:{period:8},inputs:{period:{kind:`int`,min:1}},shortName:`Qstick`,plots:[{key:`value`,title:`Qstick`,color:0}],levels:[0]};calculate(e,t){let n=U(t,`period`,8,1),r=new L,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}}},yc=class extends I{descriptor={id:`pgo`,name:`Pretty Good Oscillator`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`PGO`,plots:[{key:`value`,title:`PGO`,color:0}],levels:[-3,0,3]};calculate(e,t){let n=U(t,`period`,14,1),r=new L,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}}},bc=class extends I{descriptor={id:`stddev`,name:`Standard Deviation`,placement:`panel`,defaultConfig:{period:20,source:`close`},shortName:`StdDev`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`StdDev`,color:0}]};calculate(e,t){let n=U(t,`period`,20,1),r=new L,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}}},xc=.3,Sc=.7,Cc=class extends I{descriptor={id:`volumeProfile`,name:`Volume Profile`,placement:`overlay`,defaultConfig:{rows:24},inputs:{rows:{kind:`int`,min:1}},shortName:`VP`,plots:[]};calculate(e,t){let n=U(t,`rows`,24,1),r=new L,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(n,r,i,a){let{chartRect:o}=i,s=r.meta;if(!s||s.maxVolume===0)return;let{minPrice:c,rows:l,rowHeight:u,bins:d,maxVolume:f}=s,p=o.width*xc,m=e.k(i),h=a.colors[0]??t.TC_PALETTE.blue,g=a.colors[1]??t.TC_PALETTE.amber;n.save(),n.globalAlpha=Ct(a.opacity);for(let e=0;e<l;e++){let t=d[e]/f*p;if(t<=0)continue;let r=m(c+e*u),i=m(c+(e+1)*u);n.fillStyle=d[e]>f*Sc?g:h,n.fillRect(o.x,Math.min(r,i),t,Math.max(Math.abs(r-i)-1,1))}n.restore()}},wc=class extends I{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 L,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}}},Tc=class extends I{descriptor={id:`vroc`,name:`Volume Rate of Change`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`VROC`,plots:[{key:`value`,title:`VROC`,color:0}],levels:[0]};calculate(e,t){let n=U(t,`period`,14,1),r=new L,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}}},Ec=class extends I{descriptor={id:`dema`,name:`Double Exponential Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`DEMA`,inputs:{period:{kind:`int`,min:1},source:{source:!0}},plots:[{key:`value`,title:`DEMA`,color:0}]};emas=new WeakMap;workerState(e){return this.emas.get(e)}adoptWorkerState(e,t){t&&this.emas.set(e,t)}calculate(e,t){let n=U(t,`period`,20,1),r=B(z(e),n),i=B(r,n),a=R(e,Ka(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/(U(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}},Dc=class extends I{descriptor={id:`smma`,name:`Smoothed Moving Average`,placement:`overlay`,defaultConfig:{period:14,source:`close`},shortName:`SMMA`,inputs:{period:{kind:`int`,min:1},source:{source:!0}},plots:[{key:`value`,title:`SMMA`,color:0}]};calculate(e,t){return R(e,Ka(Va(z(e),U(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=U(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}},Oc=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:{kind:`int`,min:1,max:5e3},offset:{kind:`number`,min:0,max:1,step:.05},sigma:{kind:`number`,min:.5,step:.5},source:{source:!0}},plots:[{key:`value`,title:`ALMA`,color:0}]};read(e){let t=Math.min(5e3,U(e,`period`,9,1)),n=Math.min(1,Math.max(0,H(e,`offset`,.85))),r=Math.max(.5,H(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}}},kc=class extends I{descriptor={id:`kama`,name:`Kaufman Adaptive Moving Average`,placement:`overlay`,defaultConfig:{period:10,fast:2,slow:30,source:`close`},shortName:`KAMA`,inputs:{period:{kind:`int`,min:1},fast:{kind:`int`,min:1},slow:{kind:`int`,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=U(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<=U(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=U(t,`period`,10,1),o=2/(U(t,`fast`,2,1)+1),s=2/(U(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})}}},Ac=class extends V{descriptor={id:`lsma`,name:`Least Squares Moving Average`,placement:`overlay`,defaultConfig:{period:25,offset:0,source:`close`},shortName:`LSMA`,inputs:{period:{kind:`int`,min:2,max:5e3},offset:{kind:`int`,step:1},source:{source:!0}},plots:[{key:`value`,title:`LSMA`,color:0}]};read(e){let t=Math.min(5e3,U(e,`period`,25,2)),n=Math.round(U(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)}}},jc=class extends I{descriptor={id:`mcginley`,name:`McGinley Dynamic`,placement:`overlay`,defaultConfig:{period:14,source:`close`},shortName:`McGinley`,inputs:{period:{kind:`int`,min:1},source:{source:!0}},plots:[{key:`value`,title:`McGinley`,color:0}]};calculate(e,t){let n=U(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]:Mc(a,e[t].close,n),i[t]=a;return R(e,Ka(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=U(t,`period`,14,1);for(let t=r;t<e.length;t++)i=Mc(i,e[t].close,a),this.writePoint(n,e,t,{value:i});return n}};function Mc(e,t,n){return e>0&&t>0?e+(t-e)/(n*(t/e)**4):t}function Nc(e){return e.params.type===`ema`?[`ema`,`ema`]:e.params.type===`sma-ema`?[`sma`,`ema`]:[`sma`,`sma`]}var Pc=class extends I{descriptor={id:`macross`,name:`MA Cross`,placement:`overlay`,defaultConfig:{fast:9,slow:21,type:`sma`,source:`close`},shortName:`MA Cross`,inputs:{fast:{kind:`int`,min:1},slow:{kind:`int`,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]=Nc(t),i=z(e),a=(t,n)=>t===`ema`?B(i,n):e.map((t,r)=>Xa(e,r,n)),o=a(n,U(t,`fast`,9,1)),s=a(r,U(t,`slow`,21,1));return R(e,o.map((e,t)=>Fc(e,s[t])))}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let[i,a]=Nc(t),o=U(t,`fast`,9,1),s=U(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):Xa(e,t,o),l=a===`ema`?l+2/(s+1)*(r-l):Xa(e,t,s),this.writePoint(n,e,t,Fc(c,l))}return n}};function Fc(e,t){return e===void 0&&t===void 0?null:{...e===void 0?{}:{fast:e},...t===void 0?{}:{slow:t}}}var Ic=class extends V{descriptor={id:`fractals`,name:`Williams Fractals`,placement:`overlay`,defaultConfig:{period:2},shortName:`Fractals`,inputs:{period:{kind:`int`,min:1,max:10}},plots:[{key:`up`,title:`Up`,color:0,kind:`dots`},{key:`down`,title:`Down`,color:1,kind:`dots`}]};read(e){return U(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}:{}}}},Lc=class extends I{descriptor={id:`cks`,name:`Chande Kroll Stop`,placement:`overlay`,defaultConfig:{p:10,x:1,q:9},shortName:`CKS`,inputs:{p:{kind:`int`,label:`ATR length`,min:1},x:{kind:`number`,label:`ATR multiplier`,min:0,step:.1},q:{kind:`int`,label:`Stop length`,min:1}},plots:[{key:`long`,title:`Stop Long`,color:0},{key:`short`,title:`Stop Short`,color:1}]};states=new WeakMap;workerState(e){return this.states.get(e)}adoptWorkerState(e,t){t&&this.states.set(e,t)}calculate(e,t){let n=U(t,`p`,10,1),r=H(t,`x`,1),i=U(t,`q`,9,1),a={atr:Va(Ua(e),n),firstHigh:[],firstLow:[]};for(let t=0;t<e.length;t++)Rc(e,a,t,n,r);let o=R(e,e.map((e,t)=>zc(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=U(t,`p`,10,1),s=H(t,`x`,1),c=U(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,Rc(e,i,t,o,s),this.writePoint(n,e,t,zc(i,t,c))}return n}};function Rc(e,t,n,r,i){let a=t.atr[n],o=Ja(e,n,r),s=Ya(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 zc(e,t,n){let r=Wa(e.firstHigh,t,n),i=Ga(e.firstLow,t,n);return r!==void 0&&i!==void 0?{long:i,short:r}:null}var Bc=class extends V{descriptor={id:`bbpb`,name:`Bollinger Bands %B`,placement:`panel`,defaultConfig:{period:20,stdDev:2,source:`close`},shortName:`%B`,inputs:{period:{kind:`int`,min:2},stdDev:{kind:`number`,min:.1,step:.1},source:{source:!0}},plots:[{key:`value`,title:`%B`,color:0}],levels:[0,.5,1]};read(e){return{period:U(e,`period`,20,2),k:H(e,`stdDev`,2)}}pointAt(e,t,{period:n,k:r}){let i=qa(e,t,n);return!i||i.sd===0?null:{value:(e[t].close-(i.mean-r*i.sd))/(2*r*i.sd)}}},Vc=class extends V{descriptor={id:`bbw`,name:`Bollinger BandWidth`,placement:`panel`,defaultConfig:{period:20,stdDev:2,source:`close`},shortName:`BBW`,inputs:{period:{kind:`int`,min:2},stdDev:{kind:`number`,min:.1,step:.1},source:{source:!0}},plots:[{key:`value`,title:`BBW`,color:0}]};read(e){return{period:U(e,`period`,20,2),k:H(e,`stdDev`,2)}}pointAt(e,t,{period:n,k:r}){let i=qa(e,t,n);return!i||i.mean===0?null:{value:2*r*i.sd/i.mean}}},Hc=class extends V{descriptor={id:`mom`,name:`Momentum`,placement:`panel`,defaultConfig:{period:10,source:`close`},shortName:`MOM`,inputs:{period:{kind:`int`,min:1},source:{source:!0}},plots:[{key:`value`,title:`MOM`,color:0}],levels:[0]};read(e){return U(e,`period`,10,1)}pointAt(e,t,n){return t>=n?{value:e[t].close-e[t-n].close}:null}},Uc=class extends V{descriptor={id:`hv`,name:`Historical Volatility`,placement:`panel`,defaultConfig:{period:10,annual:365,source:`close`},shortName:`HV`,inputs:{period:{kind:`int`,min:2},annual:{kind:`number`,label:`Bars per year`,min:1},source:{source:!0}},plots:[{key:`value`,title:`HV`,color:0}],scale:{min:0}};read(e){return{period:U(e,`period`,10,2),annual:Math.max(1,H(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)}}},Wc=class extends I{descriptor={id:`vo`,name:`Volume Oscillator`,placement:`panel`,defaultConfig:{short:5,long:10},shortName:`Vol Osc`,inputs:{short:{kind:`int`,min:1},long:{kind:`int`,min:1}},plots:[{key:`value`,title:`Vol Osc`,color:0}],levels:[0]};emas=new WeakMap;workerState(e){return this.emas.get(e)}adoptWorkerState(e,t){t&&this.emas.set(e,t)}calculate(e,t){let n=e.map(e=>e.volume),r=B(n,U(t,`short`,5,1)),i=B(n,U(t,`long`,10,1)),a=R(e,Ka(r.map((e,t)=>Gc(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/(U(t,`short`,5,1)+1),c=2/(U(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=Gc(a,o);this.writePoint(n,e,t,r===void 0?null:{value:r})}return n}};function Gc(e,t){return e===void 0||t===void 0||t===0?void 0:100*(e-t)/t}var Kc=class extends I{descriptor={id:`ulcer`,name:`Ulcer Index`,placement:`panel`,defaultConfig:{period:14,source:`close`},shortName:`Ulcer`,inputs:{period:{kind:`int`,min:1},source:{source:!0}},plots:[{key:`value`,title:`Ulcer`,color:0}],scale:{min:0}};drawdowns=new WeakMap;workerState(e){return this.drawdowns.get(e)}adoptWorkerState(e,t){t&&this.drawdowns.set(e,t)}calculate(e,t){let n=U(t,`period`,14,1),r=e.map((t,r)=>qc(e,r,n)),i=R(e,e.map((e,t)=>Jc(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=U(t,`period`,14,1);for(let t=r;t<e.length;t++)i[t]=qc(e,t,a);i.length=e.length;for(let t=r;t<e.length;t++)this.writePoint(n,e,t,Jc(i,t,a));return n}};function qc(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 Jc(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 Yc=class extends I{descriptor={id:`smi`,name:`Stochastic Momentum Index`,placement:`panel`,defaultConfig:{period:10,smooth:3,signal:3},shortName:`SMI`,inputs:{period:{kind:`int`,min:1},smooth:{kind:`int`,min:1},signal:{kind:`int`,min:1}},plots:[{key:`smi`,title:`SMI`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[40,-40]};calculate(e,t){let n=U(t,`period`,10,1),r=U(t,`smooth`,3,1),i=U(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=Ja(e,t,n),i=Ya(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}))}},Xc=class extends I{descriptor={id:`rvix`,name:`Relative Volatility Index`,placement:`panel`,defaultConfig:{period:10,smooth:14},shortName:`RVI (vol)`,inputs:{period:{kind:`int`,min:2},smooth:{kind:`int`,min:1}},plots:[{key:`value`,title:`RVI`,color:0}],levels:[80,50,20],scale:{min:0,max:100}};calculate(e,t){let n=U(t,`period`,10,2),r=U(t,`smooth`,14,1),i=Ha(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,Ka(s.map((e,t)=>{let n=c[t];if(!(e===void 0||n===void 0))return e+n===0?50:100*e/(e+n)})))}},Zc=class extends V{descriptor={id:`trendstrength`,name:`Trend Strength Index`,placement:`panel`,defaultConfig:{period:14},shortName:`TSI (trend)`,inputs:{period:{kind:`int`,min:2}},plots:[{key:`value`,title:`Trend`,color:0}],levels:[0],scale:{min:-1,max:1}};read(e){return U(e,`period`,14,2)}pointAt(e,t,n){let r=Za(e,t,n);return r?{value:r.r}:null}},Qc=class extends V{descriptor={id:`lrslope`,name:`Linear Regression Slope`,placement:`panel`,defaultConfig:{period:14},shortName:`LR Slope`,inputs:{period:{kind:`int`,min:2}},plots:[{key:`value`,title:`Slope`,color:0}],levels:[0]};read(e){return U(e,`period`,14,2)}pointAt(e,t,n){let r=Za(e,t,n);return r?{value:r.slope}:null}},$c=class extends V{descriptor={id:`stderror`,name:`Standard Error`,placement:`panel`,defaultConfig:{period:14},shortName:`StdErr`,inputs:{period:{kind:`int`,min:3}},plots:[{key:`value`,title:`StdErr`,color:0}],scale:{min:0}};read(e){return U(e,`period`,14,3)}pointAt(e,t,n){let r=Za(e,t,n);return r?{value:r.stdErr}:null}},el=class extends V{descriptor={id:`adr`,name:`Average Day Range`,placement:`panel`,defaultConfig:{period:14},shortName:`ADR`,inputs:{period:{kind:`int`,min:1}},plots:[{key:`value`,title:`ADR`,color:0}],scale:{min:0}};read(e){return U(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}}},tl=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}},nl=class extends I{descriptor={id:`seb`,name:`Standard Error Bands`,placement:`overlay`,defaultConfig:{period:21,mult:2,smooth:3},shortName:`SEB`,inputs:{period:{kind:`int`,min:3},mult:{kind:`number`,min:0,step:.1},smooth:{kind:`int`,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=U(t,`period`,21,3),r=H(t,`mult`,2),i=U(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=Za(e,t,n);i&&(a[t]=i.end,o[t]=i.end+r*i.stdErr,s[t]=i.end-r*i.stdErr)}let c=Ra(a,i),l=Ra(o,i),u=Ra(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]}))}},rl=[3,5,8,10,12,15],il=[30,35,40,45,50,60],al=class extends I{descriptor={id:`gmma`,name:`Guppy Multiple Moving Average`,placement:`overlay`,defaultConfig:{},shortName:`GMMA`,plots:[...rl.map(e=>({key:`s${e}`,title:`EMA ${e}`,color:0})),...il.map(e=>({key:`l${e}`,title:`EMA ${e}`,color:1}))]};calculate(e,t){let n=z(e),r=[...rl.map(e=>[`s${e}`,B(n,e)]),...il.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}))}},ol=class extends I{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:{kind:`int`,min:1},ma2:{kind:`int`,min:1},ma3:{kind:`int`,min:1},ma4:{kind:`int`,min:1},exponential:{kind:`int`,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=H(t,`exponential`,0)>=1?B:Ra,r=z(e),i=[`ma1`,`ma2`,`ma3`,`ma4`],a=[20,50,100,200],o=i.map((e,i)=>[e,n(r,U(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}))}},sl=class extends V{read(e){return null}pointAt(e,t){return{value:this.price(e[t])}}},cl=class extends sl{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}},ll=class extends sl{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}},ul=class extends sl{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}},dl=class extends sl{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}},fl=class extends V{descriptor={id:`psy`,name:`Psychological Line`,placement:`panel`,defaultConfig:{period:10},inputs:{period:{kind:`int`,min:1}},shortName:`PSY`,plots:[{key:`value`,title:`PSY`,color:0}],scale:{min:0,max:100},levels:[25,75]};read(e){return U(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}}},pl=class extends V{descriptor={id:`newpsy`,name:`New Psychological Line`,placement:`panel`,defaultConfig:{period:10},inputs:{period:{kind:`int`,min:1}},shortName:`New PSY`,plots:[{key:`value`,title:`New PSY`,color:0}],scale:{min:-100,max:100},levels:[-50,0,50]};read(e){return U(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}}},ml=class extends V{descriptor={id:`vr`,name:`Volume Ratio`,placement:`panel`,defaultConfig:{period:20},inputs:{period:{kind:`int`,min:1}},shortName:`VR`,plots:[{key:`value`,title:`VR`,color:0}],levels:[70,150,450]};read(e){return U(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}},hl=class extends V{descriptor={id:`abratio`,name:`AB Ratio`,placement:`panel`,defaultConfig:{period:26},inputs:{period:{kind:`int`,min:1}},shortName:`AB Ratio`,plots:[{key:`a`,title:`A`,color:0},{key:`b`,title:`B`,color:1}],levels:[100]};read(e){return U(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}},gl=class extends I{descriptor={id:`sonar`,name:`Sonar`,placement:`panel`,defaultConfig:{period:20,lookback:9,signal:9},inputs:{period:{kind:`int`,min:1},lookback:{kind:`int`,min:1},signal:{kind:`int`,min:1}},shortName:`Sonar`,plots:[{key:`sonar`,title:`Sonar`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=U(t,`period`,20,1),r=U(t,`lookback`,9,1),i=U(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]}))}},_l=class extends V{descriptor={id:`sigma`,name:`Sigma`,placement:`panel`,defaultConfig:{period:20},inputs:{period:{kind:`int`,min:2}},shortName:`Sigma`,plots:[{key:`value`,title:`Sigma`,color:0}],levels:[-2,0,2]};read(e){return U(e,`period`,20,2)}pointAt(e,t,n){let r=qa(e,t,n);return r?{value:r.sd<=Math.abs(r.mean)*1e-9?0:(e[t].close-r.mean)/r.sd}:null}},vl=class extends V{descriptor={id:`vhf`,name:`Vertical Horizontal Filter`,placement:`panel`,defaultConfig:{period:28},inputs:{period:{kind:`int`,min:1}},shortName:`VHF`,plots:[{key:`value`,title:`VHF`,color:0}]};read(e){return U(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}},yl=class extends V{descriptor={id:`rsquared`,name:`R-Squared`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:2}},shortName:`R²`,plots:[{key:`value`,title:`R²`,color:0}],scale:{min:0,max:1}};read(e){return U(e,`period`,14,2)}pointAt(e,t,n){let r=Za(e,t,n);return r?{value:r.r*r.r}:null}};function bl(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 xl=class extends V{descriptor={id:`rwi`,name:`Random Walk Index`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:2}},shortName:`RWI`,plots:[{key:`high`,title:`RWI High`,color:0},{key:`low`,title:`RWI Low`,color:1}],levels:[1]};read(e){return U(e,`period`,14,2)}pointAt(e,t,n){if(t<n)return null;let r=0,i=0,a=bl(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+=bl(e,t-o)}return{high:r,low:i}}},Sl=1e3,Cl=class extends I{calculate(e,t){let n=Array(e.length).fill(void 0),r=Sl;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,U(t,`signal`,255,1));return R(e,n.map((e,t)=>i[t]===void 0?{value:e}:{value:e,signal:i[t]}))}},wl=class extends Cl{descriptor={id:`nvi`,name:`Negative Volume Index`,placement:`panel`,defaultConfig:{signal:255},inputs:{signal:{kind:`int`,min:1}},shortName:`NVI`,plots:[{key:`value`,title:`NVI`,color:0},{key:`signal`,title:`Signal`,color:1}]};counts(e,t){return e<t}},Tl=class extends Cl{descriptor={id:`pvi`,name:`Positive Volume Index`,placement:`panel`,defaultConfig:{signal:255},inputs:{signal:{kind:`int`,min:1}},shortName:`PVI`,plots:[{key:`value`,title:`PVI`,color:0},{key:`signal`,title:`Signal`,color:1}]};counts(e,t){return e>t}},El=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))}}},Dl=class extends V{descriptor={id:`iii`,name:`Intraday Intensity`,placement:`panel`,defaultConfig:{period:21},inputs:{period:{kind:`int`,min:1}},shortName:`III`,plots:[{key:`value`,title:`III %`,color:0,kind:`histogram`,tone:`sign`,downColor:1}],scale:{zero:!0},levels:[0]};read(e){return U(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}}},Ol=class extends V{descriptor={id:`volpct`,name:`Volume vs Average`,placement:`panel`,defaultConfig:{period:20},inputs:{period:{kind:`int`,min:1}},shortName:`Vol %`,plots:[{key:`value`,title:`Vol %`,color:0,kind:`histogram`,tone:`sign`,downColor:1}],scale:{zero:!0},levels:[0]};read(e){return U(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}},kl=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}},Al=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}},jl=class extends I{descriptor={id:`binarywave`,name:`Binary Wave`,placement:`panel`,defaultConfig:{ma:20,fast:12,slow:26,signal:9,roc:12,stoch:14},inputs:{ma:{kind:`int`,min:1},fast:{kind:`int`,min:1},slow:{kind:`int`,min:1},signal:{kind:`int`,min:1},roc:{kind:`int`,min:1},stoch:{kind:`int`,min:1}},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=Ra(n,U(t,`ma`,20,1)),i=B(n,U(t,`fast`,12,1)),a=B(n,U(t,`slow`,26,1)),o=i.map((e,t)=>e!==void 0&&a[t]!==void 0?e-a[t]:void 0),s=B(o,U(t,`signal`,9,1)),c=U(t,`roc`,12,1),l=U(t,`stoch`,14,1),u=e=>e?1:-1;return R(e,Ka(e.map((t,i)=>{let a=Ja(e,i,l),d=Ya(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)})))}},Ml=class extends I{descriptor={id:`sroc`,name:`Smoothed Rate of Change`,placement:`panel`,defaultConfig:{ema:13,roc:21},inputs:{ema:{kind:`int`,min:1},roc:{kind:`int`,min:1}},shortName:`S-ROC`,plots:[{key:`value`,title:`S-ROC`,color:0}],levels:[0]};calculate(e,t){let n=B(z(e),U(t,`ema`,13,1)),r=U(t,`roc`,21,1);return R(e,Ka(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})))}},Nl=class extends V{descriptor={id:`tsf`,name:`Time Series Forecast`,placement:`overlay`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:2}},shortName:`TSF`,plots:[{key:`value`,title:`TSF`,color:0}]};read(e){return U(e,`period`,14,2)}pointAt(e,t,n){let r=Za(e,t,n);return r?{value:r.end+r.slope}:null}},Pl=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}}},Fl=class extends I{descriptor={id:`rainbow`,name:`Moving Average Rainbow`,placement:`overlay`,defaultConfig:{first:10,step:10,count:10,exponential:0},shortName:`Rainbow`,inputs:{first:{kind:`int`,min:1},step:{kind:`int`,min:1},count:{kind:`int`,min:1,max:20},exponential:{kind:`int`,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=U(t,`first`,10,1),r=U(t,`step`,10,1),i=Math.min(20,U(t,`count`,10,1)),a=U(t,`exponential`,0,0)>=1?B:Ra,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}))}},Il=.05,Ll=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)*Il}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 W(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 Rl(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 zl(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 Bl=[W(`doji`,`Doji`,`Doji`,`neutral`,`indecision`,1,null,(e,t)=>e.doji(t)),W(`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)),W(`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),W(`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),W(`hammer`,`Hammer`,`Hammer`,`bullish`,`reversal`,1,`down`,Rl),W(`hangingMan`,`Hanging Man`,`Hanging`,`bearish`,`reversal`,1,`up`,Rl),W(`invertedHammer`,`Inverted Hammer`,`Inv Hammer`,`bullish`,`reversal`,1,`down`,zl),W(`shootingStar`,`Shooting Star`,`Shooting`,`bearish`,`reversal`,1,`up`,zl),W(`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)),W(`bullishMarubozu`,`Bullish Marubozu`,`Marubozu`,`bullish`,`continuation`,1,null,(e,t)=>e.white(t)&&e.marubozu(t)),W(`bearishMarubozu`,`Bearish Marubozu`,`Marubozu`,`bearish`,`continuation`,1,null,(e,t)=>e.black(t)&&e.marubozu(t)),W(`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),W(`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)],Vl=[W(`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)}),W(`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)}),W(`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),W(`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),W(`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)),W(`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)),W(`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)}),W(`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)}),W(`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)),W(`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)),W(`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)),W(`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)),W(`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)),W(`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)),W(`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)),W(`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)),W(`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)}),W(`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}),W(`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)}),W(`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)),W(`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 Hl(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 Ul(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 Wl(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 Gl(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 Kl=[W(`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)}),W(`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)}),W(`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)}),W(`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)}),W(`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)}),W(`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)}),W(`threeWhiteSoldiers`,`Three White Soldiers`,`3 Soldiers`,`bullish`,`reversal`,3,null,(e,t)=>Hl(e,t-2)),W(`threeBlackCrows`,`Three Black Crows`,`3 Crows`,`bearish`,`reversal`,3,null,(e,t)=>Ul(e,t-2)),W(`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)}),W(`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)}),W(`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)}),W(`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)}),W(`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)}),W(`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)}),W(`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)}),W(`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)}),W(`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)}),W(`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)}),W(`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)}),W(`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)}),W(`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})],ql=[W(`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)&&Wl(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)}),W(`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)&&Wl(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)}),W(`risingThreeMethods`,`Rising Three Methods`,`Rising 3`,`bullish`,`continuation`,5,`up`,(e,t)=>{let n=t-4;return e.white(n)&&e.long(n,n)&&Gl(e,n,n+1,n+3,!0)&&Wl(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)}),W(`fallingThreeMethods`,`Falling Three Methods`,`Falling 3`,`bearish`,`continuation`,5,`down`,(e,t)=>{let n=t-4;return e.black(n)&&e.long(n,n)&&Gl(e,n,n+1,n+3,!1)&&Wl(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)}),W(`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}),W(`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)}),W(`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)}),W(`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)}),W(`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)})],Jl=[...Bl,...Vl,...Kl,...ql],Yl=Jl.map(e=>e.info);function Xl(e){let t=e.trendPeriod;return t!==void 0&&Number.isFinite(t)?Math.max(2,Math.floor(t)):10}function Zl(e){if(!e.patterns)return Jl;let t=new Set(e.patterns);return Jl.filter(e=>t.has(e.info.id))}function Ql(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 $l(e,t={}){let n=new Ll(e,Xl(t)),r=Zl(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 Ql(n,t,r))i.push({index:t,time:e[t].time,pattern:a.info});return i}function eu(e={}){return Zl(e)}var tu=6,nu=4,ru=12,iu=class extends V{descriptor={id:`candlepatterns`,name:`Candlestick Patterns`,placement:`overlay`,defaultConfig:{trendPeriod:10,reversal:1,continuation:1,indecision:0},shortName:`Patterns`,inputs:{trendPeriod:{kind:`int`,min:2},reversal:{kind:`int`,min:0,max:1},continuation:{kind:`int`,min:0,max:1},indecision:{kind:`int`,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 U(e,`reversal`,1,0)>=1&&t.add(`reversal`),U(e,`continuation`,1,0)>=1&&t.add(`continuation`),U(e,`indecision`,0,0)>=1&&t.add(`indecision`),{trendPeriod:U(e,`trendPeriod`,10,2),defs:eu().filter(e=>t.has(e.info.kind))}}pointAt(e,t,{trendPeriod:n,defs:r}){let i=Ql(new Ll(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:Yl.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>=ru,{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.C(n,r),l=Yl[o.code??-1]?.short??``;if(o.bull!==void 0&&f(`bull`)){let n=e.O(o.bull,r)+nu;t.fillStyle=i.colors[3]??i.colors[0],au(t,s,n,`up`),c&&l&&(m=ou(t,l,s,Math.min(d,n+tu+2),`top`,m))}else if(o.bear!==void 0&&f(`bear`)){let n=e.O(o.bear,r)-nu;t.fillStyle=i.colors[4]??i.colors[0],au(t,s,n,`down`),c&&l&&(p=ou(t,l,s,Math.max(u,n-tu-2),`bottom`,p))}else if(o.neutral!==void 0&&f(`neutral`)){let n=e.O(o.neutral,r)-nu-tu/2;t.fillStyle=i.colors[1]??i.colors[0],t.beginPath(),t.arc(s,n,tu/2-1,0,Math.PI*2),t.fill(),c&&l&&(p=ou(t,l,s,Math.max(u,n-tu/2-2),`bottom`,p))}}t.restore()}};function au(e,t,n,r){let i=tu/2;e.beginPath(),r===`up`?(e.moveTo(t,n),e.lineTo(t-i,n+tu),e.lineTo(t+i,n+tu)):(e.moveTo(t,n),e.lineTo(t-i,n-tu),e.lineTo(t+i,n-tu)),e.closePath(),e.fill()}function ou(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 su=500,cu=class extends I{descriptor={id:`machannel`,name:`Moving Average Channel`,placement:`overlay`,defaultConfig:{upperLength:20,lowerLength:20,upperOffset:0,lowerOffset:0},shortName:`MA Channel`,inputs:{upperLength:{kind:`int`,min:1},lowerLength:{kind:`int`,min:1},upperOffset:{kind:`int`,min:-su,max:su},lowerOffset:{kind:`int`,min:-su,max:su}},fills:[{between:[`upper`,`lower`],color:0,opacity:.08}],plots:[{key:`upper`,title:`Upper`,color:0},{key:`lower`,title:`Lower`,color:1}]};calculate(e,t){let n=uu(Ra(e.map(e=>e.high),U(t,`upperLength`,20,1)),lu(t,`upperOffset`)),r=uu(Ra(e.map(e=>e.low),U(t,`lowerLength`,20,1)),lu(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}}}))}};function lu(e,t){let n=Number(e.params[t]??0);return Number.isFinite(n)?Math.max(-su,Math.min(su,Math.round(n))):0}function uu(e,t){return e.map((n,r)=>e[r-t])}var du=500,fu=class extends V{descriptor={id:`hamming`,name:`Moving Average Hamming`,placement:`overlay`,defaultConfig:{period:10,source:`close`},shortName:`HMA (Hamming)`,inputs:{period:{kind:`int`,min:2,max:du},source:{source:!0}},plots:[{key:`value`,title:`MA`,color:0}]};read(e){let t=Math.min(du,U(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}}},pu=[`sma`,`ema`,`wma`];function mu(e,t,n){return e===`ema`?B(t,n):e===`wma`?Ba(t,n):Ra(t,n)}var hu=class extends I{calculate(e,t){let n=pu.includes(t.params.type)?t.params.type:`sma`,r=z(e),i=this.lengths.map(([e,i])=>mu(n,r,U(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}))}},gu=class extends hu{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:{kind:`int`,min:1},second:{kind:`int`,min:1},type:{options:pu},source:{source:!0}},plots:[{key:`ma1`,title:`MA 1`,color:0},{key:`ma2`,title:`MA 2`,color:1}]}},_u=class extends hu{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:{kind:`int`,min:1},second:{kind:`int`,min:1},third:{kind:`int`,min:1},type:{options:pu},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}]}},vu=class extends I{descriptor={id:`volindex`,name:`Volatility Index`,placement:`overlay`,defaultConfig:{period:7,mult:3},shortName:`VI`,inputs:{period:{kind:`int`,min:1},mult:{kind:`number`,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=U(t,`period`,7,1),r=Math.max(.1,H(t,`mult`,3)),i=Va(Ua(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)}},yu=class extends I{descriptor={id:`asi`,name:`Accumulative Swing Index`,placement:`panel`,defaultConfig:{limit:10},shortName:`ASI`,inputs:{limit:{kind:`number`,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,H(t,`limit`,10)),r=Array(e.length).fill(null),i=0;for(let t=1;t<e.length;t++)i+=bu(e[t-1],e[t],n),r[t]={value:i};return R(e,r)}};function bu(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 xu=class extends V{descriptor={id:`advdecline`,name:`Advance/Decline`,placement:`panel`,defaultConfig:{length:10},shortName:`A/D Ratio`,inputs:{length:{kind:`int`,min:1}},plots:[{key:`value`,title:`Ratio`,color:0}],scale:{min:0}};read(e){return{length:U(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}}},Su=class extends V{descriptor={id:`majority`,name:`Majority Rule`,placement:`panel`,defaultConfig:{period:14},shortName:`Majority`,inputs:{period:{kind:`int`,min:1}},plots:[{key:`value`,title:`Majority`,color:0}],scale:{min:0,max:100},levels:[50]};read(e){return{period:U(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}}},Cu=34,wu=30,Tu=class extends I{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),Cu),r=Array(e.length).fill(null);for(let t=1;t<e.length;t++){let i=n[t],a=n[t-1],o=Ja(e,t,wu),s=Ya(e,t,wu);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.O(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.C(t,r),y:e.O(n,r),baseY:c,color:Eu(n)})}this.drawHistogram(t,l,Math.max(1,r.barWidth))}};function Eu(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 Du=class extends I{descriptor={id:`smiergodic`,name:`SMI Ergodic`,placement:`panel`,defaultConfig:{short:5,long:20,signal:5,source:`close`},shortName:`SMIIO`,inputs:{short:{kind:`int`,min:1},long:{kind:`int`,min:1},signal:{kind:`int`,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=U(t,`short`,5,1),r=U(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,U(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}}))}},Ou=class extends I{descriptor={id:`po`,name:`Price Oscillator`,placement:`panel`,defaultConfig:{short:10,long:21,source:`close`},shortName:`PO`,inputs:{short:{kind:`int`,min:1},long:{kind:`int`,min:1},source:{source:!0}},plots:[{key:`value`,title:`PO`,color:0}],scale:{zero:!0}};calculate(e,t){let n=z(e),r=Ra(n,U(t,`short`,10,1)),i=Ra(n,U(t,`long`,21,1));return R(e,Ka(r.map((e,t)=>e===void 0||i[t]===void 0?void 0:e-i[t])))}},ku=e=>({period:U(e,`period`,10,1),annual:Math.max(1,H(e,`annual`,365))}),Au={period:{kind:`int`,min:1},annual:{kind:`number`,label:`Bars per year`,min:1}},ju=class extends V{descriptor={id:`volohlc`,name:`Volatility O-H-L-C`,placement:`panel`,defaultConfig:{period:10,annual:365},shortName:`Vol OHLC`,inputs:Au,plots:[{key:`value`,title:`Volatility`,color:0}],scale:{min:0}};read(e){return ku(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))}}},Mu=class extends V{descriptor={id:`volzt`,name:`Volatility Zero Trend Close-to-Close`,placement:`panel`,defaultConfig:{period:10,annual:365},shortName:`Vol ZT`,inputs:Au,plots:[{key:`value`,title:`Volatility`,color:0}],scale:{min:0}};read(e){return ku(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)}}},Nu=[()=>new Lo,()=>new Ro,()=>new zo,()=>new Go,()=>new Jo,()=>new Yo,()=>new Xo,()=>new Zo,()=>new Qo,()=>new es,()=>new ns,()=>new rs,()=>new is,()=>new as,()=>new cs,()=>new ls,()=>new us,()=>new ds,()=>new ps,()=>new ms,()=>new hs,()=>new ys,()=>new Ss,()=>new Cs,()=>new ws,()=>new Ts,()=>new Es,()=>new Ds,()=>new Os,()=>new ks,()=>new As,()=>new js,()=>new Ms,()=>new Ns,()=>new Ps,()=>new bc,()=>new Cc,()=>new wc,()=>new Tc,()=>new bs,()=>new xs,()=>new Fs,()=>new Is,()=>new Ls,()=>new Rs,()=>new Bs,()=>new Vs,()=>new Us,()=>new Ws,()=>new qs,()=>new Js,()=>new Xs,()=>new Zs,()=>new Qs,()=>new $s,()=>new ec,()=>new tc,()=>new nc,()=>new ic,()=>new ac,()=>new oc,()=>new sc,()=>new cc,()=>new lc,()=>new fc,()=>new mc,()=>new gc,()=>new _c,()=>new vc,()=>new yc,()=>new Ec,()=>new Dc,()=>new Oc,()=>new kc,()=>new Ac,()=>new jc,()=>new Pc,()=>new Ic,()=>new Lc,()=>new Bc,()=>new Vc,()=>new Hc,()=>new Uc,()=>new Wc,()=>new Kc,()=>new Yc,()=>new Xc,()=>new Zc,()=>new Qc,()=>new $c,()=>new el,()=>new tl,()=>new nl,()=>new al,()=>new ol,()=>new cl,()=>new ll,()=>new ul,()=>new cu,()=>new fu,()=>new gu,()=>new _u,()=>new vu,()=>new yu,()=>new xu,()=>new Su,()=>new Tu,()=>new Du,()=>new Ou,()=>new ju,()=>new Mu,()=>new fl,()=>new pl,()=>new ml,()=>new hl,()=>new gl,()=>new _l,()=>new vl,()=>new yl,()=>new xl,()=>new wl,()=>new Tl,()=>new El,()=>new Dl,()=>new Ol,()=>new kl,()=>new Al,()=>new jl,()=>new Ml,()=>new Nl,()=>new dl,()=>new Pl,()=>new Fl,()=>new iu];function Pu(e){for(let t of Nu){let n=t();La.add(n),e.register(n)}}var Fu=[`movingAverages`,`trend`,`oscillators`,`volatility`,`volume`,`bands`,`patterns`,`other`],Iu=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 Lu(e){return e.category??Iu.get(e.id)??`other`}var Ru=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,zu=1,Bu=.1;function Vu(e,t){return t?.kind?t.kind:t?.source?`source`:t?.options?`choice`:typeof e==`boolean`?`boolean`:typeof e==`number`?`number`:typeof e==`string`&&Ru.test(e)?`color`:`text`}function Hu(e){return Object.entries(e.defaultConfig).map(([t,n])=>{let r=e.inputs?.[t],i=Vu(n,r),a={name:t,kind:i,default:n};return r?.label!==void 0&&(a.label=r.label),r?.min!==void 0&&(a.min=r.min),r?.max!==void 0&&(a.max=r.max),i===`int`&&(a.step=r?.step??zu),i===`number`&&(a.step=r?.step??(Number.isInteger(n)?zu:Bu)),i===`choice`&&r?.options&&(a.options=r.options),a})}function Uu(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 Wu=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=uo(n),a={type:`calculate`,bars:i,jobs:[{requestId:r,indicatorId:e,config:t}]},o=i.time.slice();return new Promise((t,n)=>{let s={resolve:t,reject:n,timer:null,times:o};this.timeoutMs>0&&(s.timer=setTimeout(()=>{this.pending.delete(r),n(Error(`Indicator worker timeout (${this.timeoutMs}ms): ${e}`))},this.timeoutMs)),this.pending.set(r,s),this.worker.postMessage(a,po(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(!Uu(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(So(e.output,t.times??[]))}}};function Gu(){return typeof Worker>`u`?Promise.reject(Error(`Web Workers are not available here`)):Promise.resolve().then(()=>require(`./indicator.worker-Cd8ymg6p.cjs`)).then(({default:e})=>new e({name:`tradecanvas-indicators`}))}function Ku(){if(typeof Worker>`u`)throw Error(`Web Workers are not available here`);return Gu()}var qu=class{state=`starting`;worker=null;outbox=[];jobs=new Map;batch=null;nextId=1;pingId=0;onMessage=e=>this.receive(e.data);onError=e=>this.fail(Error(e.message||`Indicator worker error`));constructor(e){let t;try{t=e()}catch(e){this.fail(Ju(e));return}t instanceof Promise?t.then(e=>this.attach(e),e=>this.fail(Ju(e))):this.attach(t)}get usable(){return this.state===`starting`||this.state===`ready`}get ready(){return this.state===`ready`}submit(e,t){if(!this.usable)return null;let n=this.nextId++;this.jobs.set(n,{done:t,times:e.times});let{indicatorId:r,config:i,source:a,bars:o}=e;return this.batchFor(o).jobs.push({requestId:n,indicatorId:r,config:i,...a?{source:a}:{}}),n}batchFor(e){if(this.batch?.bars===e)return this.batch;this.sendBatch();let t={bars:e,jobs:[]};return this.batch=t,queueMicrotask(()=>{this.batch===t&&this.sendBatch()}),t}sendBatch(){let e=this.batch;this.batch=null;let t=e?.jobs.filter(e=>this.jobs.has(e.requestId))??[];!e||t.length===0||!this.usable||this.send({message:{type:`calculate`,bars:e.bars,jobs:t},transfer:po(e.bars)})}cancel(e){let t=new Set(this.batch?.jobs.map(e=>e.requestId)),n=e.filter(e=>this.jobs.delete(e)&&!t.has(e));n.length>0&&this.usable&&this.send({message:{type:`cancel`,requestIds:n},transfer:[]})}terminate(){this.state=`closed`,this.jobs.clear(),this.batch=null,this.outbox=[],this.detach()}attach(e){if(!this.usable){e.terminate();return}this.worker=e,e.addEventListener(`message`,this.onMessage),e.addEventListener(`error`,this.onError),e.addEventListener(`messageerror`,this.onError),this.pingId=this.nextId++,e.postMessage({type:`ping`,requestId:this.pingId});let t=this.outbox;this.outbox=[];for(let n of t)e.postMessage(n.message,n.transfer)}send(e){this.worker?this.worker.postMessage(e.message,e.transfer):this.outbox.push(e)}receive(e){if(!Uu(e))return;if(e.type===`pong`){e.requestId===this.pingId&&this.state===`starting`&&(this.state=`ready`);return}let t=this.jobs.get(e.requestId);if(t){if(e.type===`result`){this.decode(e.requestId,t,e.output);return}this.jobs.delete(e.requestId),t.done(Error(e.message))}}decode(e,t,n){let r=new xo(n,t.times),i=()=>{if(this.jobs.get(e)===t){if(!r.step(5e4)){setTimeout(i,0);return}this.jobs.delete(e),t.done({output:r.output(),...n.state===void 0?{}:{state:Eo(n.state)}})}};i()}fail(e){if(!this.usable)return;this.state=`failed`,this.outbox=[],this.detach(),this.batch=null;let t=[...this.jobs.values()];this.jobs.clear();for(let{done:n}of t)n(e)}detach(){let e=this.worker;e&&(this.worker=null,e.removeEventListener(`message`,this.onMessage),e.removeEventListener(`error`,this.onError),e.removeEventListener(`messageerror`,this.onError),e.terminate())}};function Ju(e){return e instanceof Error?e:Error(String(e))}var Yu=class{client=null;holders=0;constructor(e=Ku){this.spawn=e}acquire(){let e=this.client??=new qu(this.spawn);this.holders++;let t=!0;return{client:e,release:()=>{t&&(t=!1,this.holders--,this.holders===0&&this.client===e&&(e.terminate(),this.client=null))}}}},Xu=new Yu,G={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},Zu=[...new Set(Object.values(G))].sort((e,t)=>t-e),Qu=256;function $u(e){return e>=G.year?`year`:e>=G.month?`month`:e>=G.day?`day`:`time`}function ed(e,t){if(!e)return 0;if(t.year!==e.year)return G.year;if(t.month!==e.month)return t.month%3==1?G.quarter:G.month;if(t.day!==e.day)return t.day%5==0?G.dayOfFive:G.day;if(t.hours!==e.hours){let e=t.hours;return e%12==0?G.hour12:e%6==0?G.hour6:e%3==0?G.hour3:G.hour}if(t.minutes!==e.minutes){let e=t.minutes;return e%30==0?G.minute30:e%15==0?G.minute15:e%5==0?G.minute5:G.minute}return G.within}var td=256,nd=1.25;function rd(e){return e>1?Math.ceil(nd**Math.ceil(Math.log(e)/Math.log(nd)-1e-9)):1}var id=class{weights=new Uint8Array;times=[];weighed=null;weighedFrom=null;revision=0;chosen=new Int32Array;chosenFor=null;marks(e,t){let n=e.length;if(n===0)return[];let r=rd(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)/td)*td+n;this.weigh(e,t.tz,t.exchangeZone??null,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,a){let o=n.length,s=(0,t.barTimeUnit)(n),c=(0,t.barsAreDaily)(n)===!0,l=c?e=>(0,t.barDateParts)(e,r,i):e=>(0,t.timeParts)(e,r),u=this.weighed,d=0;if(u&&u.tz===r&&u.exchangeZone===i&&u.daily===c&&u.unit===s){let e=Math.min(u.bars,o),t=this.times;if(n===this.weighedFrom?.deref()&&o>=u.bars)d=e>0&&n[e-1].time*s===t[e-1]?e:0;else{for(;d<e&&n[d].time*s===t[d];)d++;d<e&&(d=0)}}if(this.weighedFrom?.deref()!==n&&(this.weighedFrom=new WeakRef(n)),u&&d===o&&u.bars===o&&u.extent===a)return;let f=d>0&&this.weights.length>=a,p=f?this.weights:new Uint8Array(a+(a>>3)),m=d>0?this.times:[];d>0&&!f&&p.set(this.weights.subarray(0,d)),m.length=d;let h=d>0?l(m[d-1]):null;for(let t=d;t<a;t++){let r=(t<o?n[t].time:e.S(t,n))*s,i=l(r);p[t]=t>0&&r===m[t-1]?0:ed(h,i),m[t]=r,h=i}this.weights=p,this.times=m,this.weighed={bars:o,tz:r,exchangeZone:i,daily:c,extent:a,unit:s},this.revision++}choose(e,t){let n=this.chosenFor;if(n&&n.gapBars===e&&n.extent===t&&n.revision===this.revision)return;let r=this.weights,i=new Uint8Array(t),a=[],o=new Int32Array(Qu+1);for(let e=0;e<t;e++)o[r[e]+1]++;for(let e=1;e<=Qu;e++)o[e]+=o[e-1];let s=new Int32Array(t),c=o.slice(0,Qu);for(let e=0;e<t;e++)s[c[r[e]]++]=e;for(let n of Zu)for(let r=o[n];r<o[n+1];r++){let n=s[r];if(i[n])continue;a.push(n);let o=Math.max(0,n-e+1),c=Math.min(t-1,n+e-1);for(let e=o;e<=c;e++)i[e]=1}this.chosen=Int32Array.from(a).sort(),this.chosenFor={gapBars:e,extent:t,revision:this.revision}}},ad=e=>e<10?`0`+e:``+e,od=8,sd=new Map;function cd(e){let t=sd.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))),sd.set(e,t)}return t}var ld=class{tz=null;exchangeZone=null;timeFormatter=null;timesPastData=!0;locale=`en-US`;columns=[];marker=new id;setLocale(e){this.locale=e}setTimezoneOffset(e){this.tz=e}setExchangeTimeZone(e){this.exchangeZone=e}setTimeFormatter(e){this.timeFormatter=e}setTimesPastData(e){this.timesPastData=e}getTimesPastData(){return this.timesPastData}marks(e,t){let n=e.barWidth+e.barSpacing;if(!(n>0)||t.length===0)return[];let r=ci(t),i=this.marker.marks(r,{from:Math.floor(e.offset/n),to:Math.ceil((e.offset+e.chartRect.width)/n),gapBars:80/n,tz:this.tz,timesPastData:this.timesPastData,exchangeZone:this.exchangeZone});return r===t?i:fd(i)}label(e,n,r){if(this.timeFormatter)return this.timeFormatter(e.time,{kind:n,timeZone:this.tz});let i=r?(0,t.barDateParts)(e.time,this.tz,this.exchangeZone):(0,t.timeParts)(e.time,this.tz);if(n===`year`)return String(i.year);if(n===`month`)return cd(this.locale)[i.month-1];if(n===`day`)return String(i.day);let a=`${ad(i.hours)}:${ad(i.minutes)}`;return e.weight===G.within?`${a}:${ad(new Date(e.time).getUTCSeconds())}`:a}labelColumns(){return this.columns}render(n,r,i,a,o){let{chartRect:s}=r,c=ci(a),l=o??s.y+s.height;n.strokeStyle=i.style?.axis.time.line??i.axisLine,n.lineWidth=1,n.globalAlpha=.65,n.beginPath(),e.y(n,s.x,s.x+s.width,l+.5),n.stroke(),n.globalAlpha=1;let u=r.barWidth+r.barSpacing,d=-r.offset+s.x+r.barWidth/2,f=Math.ceil((r.offset+s.width)/u),p=(0,t.barTimeUnit)(c),m=c.length>0?e.S(Math.min(f,c.length-1),c):Date.now(),h=(0,t.tzLabel)(this.tz,m*p),g=`500 ${i.font.sizeSmall-1}px ${i.font.family}`,_=s.x+s.width-4;n.font=g;let v=_-n.measureText(h).width-8,y=`500 ${i.font.sizeSmall}px ${i.font.family}`,b=`600 ${i.font.sizeSmall}px ${i.font.family}`;n.textBaseline=`top`,n.textAlign=`center`,n.fillStyle=i.style?.axis.time.text??i.axisLabel;let x=[],S=this.marks(r,a).sort((e,t)=>t.weight-e.weight||e.index-t.index),C=(0,t.barsAreDaily)(c)===!0;for(let e of S){let t=e.index*u+d;if(t<s.x)continue;let r=$u(e.weight),i=this.label(e,r,C);n.font=r===`year`?b:y;let a=n.measureText(i).width/2,o=Math.max(t,s.x+a);o+a>v||x.some(e=>o-a<e.right+od&&o+a+od>e.left)||(x.push({left:o-a,right:o+a}),n.fillText(i,o,l+7))}this.columns=x,n.font=g,n.textAlign=`right`,n.textBaseline=`top`,n.globalAlpha=.75,n.fillStyle=i.textSecondary,n.fillText(h,_,l+7),n.globalAlpha=1}},ud={year:3,month:2,day:1,time:0},dd=2;function fd(e){let t=[...new Set(e.map(e=>ud[$u(e.weight)]))].sort((e,t)=>t-e);if(t.length<=dd)return e;let n=t[dd-1];return e.filter(e=>ud[$u(e.weight)]>=n)}var pd={line:16,handle:22,alert:16,order:16,button:8,divider:12},md=300,hd=24,gd=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}},_d=new Set,vd=null,yd=4,bd=8,xd=500,Sd=800,Cd={ctrl:!1,shift:!1,alt:!1};function wd(){let e=typeof document<`u`?document.activeElement:null;return e instanceof Element&&e.closest(`[aria-modal="true"], [role="dialog"], [role="menu"]`)!==null}var Td=class{panHandler=null;zoomHandler=null;crosshairHandler=null;axisDragHandler=null;alertDragHandler=null;axisViewportGetter=null;onAxisDoubleClick=null;onDrawingDoubleClick=null;onDrawingContextMenu=null;zoomArea=!1;idleCss=`crosshair`;showingIdle=!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 gd;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}setIdleCursor(e){this.idleCss=e,this.showingIdle&&(this.element.style.cursor=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}takesPressFromAddButton(e){return e===`move`||e!==null&&!!this.drawingManager?.isEraser()}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(){_d.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;_d.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`?this.idleCss:``,a=e=>{this.element.style.cursor!==e&&(this.element.style.cursor=e),this.showingIdle=e!==``&&e===this.idleCss},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();if(this.tradingManager?.isOverButton(n))return`pointer`;if(o&&this.tradingManager?.isOverDraggableLine(n,o))return`ns-resize`;if(this.zoomArea)return`zoom-in`;let s=o?this.drawingManager?.hoverCursorAt(n,o):null;return this.takesPressFromAddButton(s??null)?s??i():o&&this.priceAxisAdd?.button.hit(n,o)?(this.drawingManager?.clearHover(),`pointer`):s||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:pd;this.pressPlacedPoint=!1,c||this.drawingManager?.setModifiers({ctrl:!1,shift:!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 r.ctrl&&!d&&!this.zoomArea&&s&&this.drawingManager?.beginCopyDrag(n,s,l)?(c&&a(`copy`),`taken`):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&&!d&&!(s&&this.drawingManager?.hoverCursorAt(n,s))?(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.takesPressFromAddButton(this.drawingManager?.hoverCursorAt(n,s)??null)?(this.drawingManager?.clearHover(),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(vd=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};this.drawingManager?.setModifiers({ctrl:t.ctrl,shift:t.shift}),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(this.drawingManager?.setModifiers({ctrl:e.ctrlKey||e.metaKey,shift:e.shiftKey}),!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`?yd:bd;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.drawingManager?.clearHover(),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=>{(e.key===`Shift`||e.key===`Control`||e.key===`Meta`)&&this.drawingManager?.setModifiers({ctrl:e.ctrlKey||e.metaKey,shift:e.shiftKey})},T=()=>this.drawingManager?.setModifiers({ctrl:!1,shift:!1}),E=e=>{if(w(e),wd())return;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}if(e.key!==`Escape`&&!this.ownsShortcuts())return;let t=this.drawingManager?.isDragging()??!1;this.drawingManager?.onKeyDown(e.key,e.ctrlKey||e.metaKey,e.shiftKey)&&(e.preventDefault(),t&&e.key===`Escape`&&a(i()))},D=t=>{if(this.touchActive||Date.now()-this.lastTouchAt<Sd){t.preventDefault();return}let r=e();if(!r)return;let i=this.getMousePos(t),a=this.onDrawingContextMenu&&!this.drawingManager?.getActiveTool()?this.drawingManager?.drawingAt(i,r):null;if(a){t.preventDefault(),this.onDrawingContextMenu?.(a,i);return}if(this.tradingManager?.onContextMenu(i,r)){t.preventDefault();return}this.onChartContextMenu?.(n(i),i)&&t.preventDefault()},ee=e=>{if(vd=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,Cd,`touch`);if(this.touchActive=!0,this.touchFallthrough=n===`pan`||n===`inert`,this.touchStartPrevented=!(this.touchFallthrough&&this.pageTakes().any),this.touchStartPrevented&&e.preventDefault(),n===`drawing`){O(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)},xd)),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}}},O=t=>{this.onDrawingContextMenu&&(this.clearLongPress(),this.longPressTimer=setTimeout(()=>{this.longPressTimer=null;let n=e(),r=n?this.drawingManager?.drawingAt(t,n,pd.line):null;r&&(v(null,`touch`,!0),this.longPressed=!0,this.touchYielded=!0,this.crosshairHandler?.onPointerLeave(),this.onDrawingContextMenu?.(r,t),this.onOverlayDirty?.())},xd))},k=e=>{if(this.touchDecided)return!1;let t=e.x-this.touchStartPos.x,n=e.y-this.touchStartPos.y;if(Math.hypot(t,n)<=bd)return!1;this.touchDecided=!0;let r=this.pageTakes();return Math.abs(n)>=Math.abs(t)?r.y:r.x},A=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)>bd&&this.clearLongPress(),this.touchFallthrough&&this.pageTakes().any){if(!this.touchDecided&&Math.hypot(t.x-this.touchStartPos.x,t.y-this.touchStartPos.y)<=bd)return;if(k(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?.()}}},te=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,pd.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]))},ne=()=>{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?.())},re=()=>this.invalidateRect(),ie=()=>this.invalidateRect(),ae=()=>this.invalidateRect(),oe=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`,oe,!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`,D),this.element.addEventListener(`touchstart`,ee,{passive:!1}),this.element.addEventListener(`touchmove`,A,{passive:!1}),this.element.addEventListener(`touchend`,te),this.element.addEventListener(`touchcancel`,ne),document.addEventListener(`keydown`,E),document.addEventListener(`keyup`,w),window.addEventListener(`blur`,T),window.addEventListener(`resize`,re),document.addEventListener(`scroll`,ie,{capture:!0,passive:!0}),this.element.addEventListener(`mouseenter`,ae),this.boundHandlers.push(d,()=>this.element.removeEventListener(`mousedown`,m),()=>document.removeEventListener(`keyup`,w),()=>window.removeEventListener(`blur`,T),()=>document.removeEventListener(`dragstart`,oe,!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`,D),()=>this.element.removeEventListener(`touchstart`,ee),()=>this.element.removeEventListener(`touchmove`,A),()=>this.element.removeEventListener(`touchend`,te),()=>this.element.removeEventListener(`touchcancel`,ne),()=>document.removeEventListener(`keydown`,E),()=>window.removeEventListener(`resize`,re),()=>document.removeEventListener(`scroll`,ie,{capture:!0}),()=>this.element.removeEventListener(`mouseenter`,ae))}detach(){_d.delete(this.element),this.savedTouchAction?this.element.style.setProperty(`touch-action`,this.savedTouchAction):this.element.style.removeProperty(`touch-action`),vd===this.element&&(vd=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 _d)if(e&&t.contains(e))return t===this.element;return vd===null||vd===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}}},Ed=16,Dd=3,Od=Ed+Dd,kd=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-Ed-Dd;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-Dd-Ed/2,l=Ed/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()}},Ad=100,jd=50,Md=.1,Nd=60,Pd=16;function Fd(){return typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches}var Id=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>Ad;)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=[],!Fd()&&e&&Math.hypot(e.x,e.y)>Md&&this.startMomentum(e.x,e.y)}cancelMomentum(){this.stopMomentum()}releaseVelocity(e){let t=this.samples[this.samples.length-1];if(!t||e-t.t>jd)return null;let n=this.samples.find(e=>t.t-e.t<=Ad)??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*Pd,r=t*Pd,i=Math.hypot(n,r);i>Nd&&(n*=Nd/i,r*=Nd/i);let a=null,o=e=>{let t=a===null?1:Math.min(4,Math.max(0,(e-a)/Pd));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)}},Ld=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)}},Rd=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}},zd=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.F(t.y,n))}end(){this.draggingId=null}isActive(){return this.draggingId!==null}},Bd=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(Vd(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 Vd(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 Hd=.25,Ud=10,Wd=6,Gd=16,Kd=18,qd=8,Jd=16,Yd=15,Xd={min:0,max:1,step:.2,ticks:[0,.2,.4,.6,.8,1]};function Zd(e){for(let t=0;t<=Yd;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 Yd}var Qd=(e,t)=>{let n=Number(e.toFixed(t));return n===0?0:n};function $d(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 Xd;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 Xd;let l=Zd(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(Qd(e*c,l));return f.length<2||!f.every(Number.isFinite)?Xd:{min:f[0],max:f[f.length-1],step:Qd(c,l),ticks:f}}function ef(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 tf=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),nf=new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1});function rf(e){return Math.abs(e)>=1e4?nf.format(e):tf.format(e)}function K(e){let t=Zd(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 af(e,n){return n??t.TC_SERIES_COLORS[e%t.TC_SERIES_COLORS.length]}function q(e,t,n=``){return`${n?`${n} `:``}${t}px ${e.font.family}`}function of(e,t){return(n,r=11)=>(e.font=q(t,r),e.measureText(n).width)}function sf(e,t,n,r=!1){let i=[],a=0,o=0;for(let s of e){let e=Ud+Wd+n(s.label,11);a>0&&(r||a+e>t)&&(o++,a=0),i.push({...s,x:a,y:o*Kd}),a+=e+Gd}let s=e.length===0?0:o+1;return{items:i,rows:s,height:s*Kd}}function cf(e,t,n,r,i){e.save(),e.font=q(i,11),e.textBaseline=`middle`,e.textAlign=`left`;for(let a of t.items){let t=r+a.y+Kd/2;e.fillStyle=a.color,e.fillRect(n+a.x,t-Ud/2,Ud,Ud),e.fillStyle=i.textSecondary,e.fillText(a.label,n+a.x+Ud+Wd,t)}e.restore()}function lf(e,n,r,i,a){if(n.length===0)return;e.save();let o=n.some(e=>e.color)?Ud+Wd:0,s=0;for(let t of n)e.font=q(a,11,t.bold?`600`:``),s=Math.max(s,e.measureText(t.text).width);let c=s+o+qd*2,l=n.length*Jd+qd*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+qd+n*Jd+Jd/2-2;t.color&&(e.fillStyle=t.color,e.fillRect(u+qd,r-4,8,8)),e.font=q(a,11,t.bold?`600`:``),e.fillStyle=t.bold?a.text:a.textSecondary,e.fillText(t.text,u+qd+o,r)}),e.restore()}function uf(e,t,n,r,i,a){e.save(),e.font=q(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(ef(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(ef(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 df(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}…`:``}var ff=8,pf=32,mf=new Map;function hf(e){let t=mf.get(e);return t===void 0&&(t=gf(e),mf.size>512&&mf.clear(),mf.set(e,t)),t}function gf(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 _f(e,t,n){let r=hf(e),i=hf(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 vf(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??_f(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 yf(e,t){return!Number.isFinite(e)||e===0?_f(t.zero,t.zero,0):e<0?_f(t.zero,t.negative,t.min<0?Math.min(1,e/t.min):1):_f(t.zero,t.positive,t.max>0?Math.min(1,e/t.max):1)}var bf=`#11151b`,xf=.0076;function Sf(e){let t=hf(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)/(xf+.05)>1.05/(a+.05)?bf:`#ffffff`}function Cf(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<pf;t++){let r=(t+.5)/pf;e.fillStyle=yf(n.min+c*r,n),e.fillRect(o+a*t/pf,s,a/pf+.5,ff)}e.font=q(i,10),e.fillStyle=i.textSecondary,e.textBaseline=`top`;let l=s+ff+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 wf=.2,Tf=class{position=null;callback=null;data=[];source=null;tz=null;exchangeZone=null;timeFormatter=null;timesPastData=!0;setTimesPastData(e){this.timesPastData=e}getTimesPastData(){return this.timesPastData}setTimeFormatter(e){this.timeFormatter=e}setTimezoneOffset(e){this.tz=e}setExchangeTimeZone(e){this.exchangeZone=e}magnetMode=!0;mode=`magnet`;cursor=`cross`;spanTints=[];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}setCursor(e){this.cursor=e}getCursor(){return this.cursor}drawsLines(){return this.mode!==`hidden`&&this.cursor!==`arrow`}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}getReportedBarIndex(){return this.lastCallbackBarIndex>=0?this.lastCallbackBarIndex:null}refresh(){this.lastCallbackBarIndex<0||!this.pendingPoint||(this.pendingBarIndex=this.lastCallbackBarIndex,this.scheduleCallback())}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;let a=this.cursor!==`arrow`;if(!this.position){this.syncedSlot!==null&&a&&this.renderSynced(n,r,i,this.syncedSlot);return}let{chartRect:o}=r,{x:s,y:c}=this.position;if(s<o.x||s>o.x+o.width)return;let l=o.y+o.height;if(c<Math.min(this.reportTop??o.y,o.y)||c>Math.max(this.reportBottom??l,l))return;let u=c>=o.y&&c<=l,d=e.N(s,r),f=this.series().length,p=Math.max(0,Math.min(f-1,d)),m=d>=0&&d<f;if(this.magnetMode&&(s=e.C(d,r)),p!==this.lastCallbackBarIndex&&(this.pendingBarIndex=p,this.pendingPoint={x:s,y:c},this.lastCallbackBarIndex=p,this.scheduleCallback()),!u||!a)return;let h=de(i);this.magnetMode&&m&&Df(n,s,r,h.vertical.color),Of(n,s,o,h.vertical);let g=h.horizontal;if(g.visible){n.setLineDash((0,t.lineDash)(g.style,Ef,g.width)),n.strokeStyle=g.color;let r=e.v(n,c,g.width);n.lineWidth=r.width,n.beginPath(),n.moveTo(o.x,r.y),n.lineTo(o.x+o.width,r.y),n.stroke()}n.setLineDash([])}renderAxisLabels(n,r,i,a,o,s=[],c=[]){if(this.mode===`hidden`)return;if(!this.position){this.syncedSlot!==null&&this.renderSyncedTimeLabel(n,r,i,a,this.syncedSlot,o,c);return}let{chartRect:l}=r,{x:u,y:f}=this.position;if(u<l.x||u>l.x+l.width||f<l.y||f>l.y+l.height)return;let p=e.N(u,r);this.magnetMode&&(u=e.C(p,r));let m=`600 ${i.font.sizeSmall}px ${i.font.family}`,h=d(e.F(f,r),r,this.pricePrecision??(0,t.autoPricePrecision)(r.priceRange.min,r.priceRange.max),this.locale),g=l.x+l.width;Mf(n,s,f,g,r.priceAxisWidth??t.PRICE_AXIS_WIDTH,i,this.spanTints),Nf(n,{text:h,anchorX:g,anchorY:f,orientation:`right`,bg:de(i).labelBackground,fg:de(i).labelText,theme:i,font:m}),this.drawTimePill(n,r,i,a,p,u,o,c)}beginSpans(){this.spanTints=[]}renderSpan(e,n,r,i,a,o){let s=`600 ${i.font.sizeSmall}px ${i.font.family}`,c=(0,t.withAlpha)(n.color,wf),l=Sf(n.color);n.prices.length>0&&this.renderPriceSpan(e,n,i,s,c,l,r),n.times.length>0&&this.renderTimeSpan(e,n,r,i,a,s,c,l,o)}renderPriceSpan(n,r,i,a,o,s,c){let l=r.viewport,u=l.chartRect,f=u.x+u.width,p=l.priceAxisWidth??t.PRICE_AXIS_WIDTH,m=r.prices.map(t=>e.O(t,l)),h=l===c?this.pricePrecision??(0,t.autoPricePrecision)(l.priceRange.min,l.priceRange.max):S(C(l.priceRange.min,l.priceRange.max,u.height));n.save(),n.beginPath(),n.rect(f,u.y,p,u.height),n.clip(),m.length>1&&(n.fillStyle=o,n.fillRect(f,Math.min(...m),p,Math.abs(m[m.length-1]-m[0])),l===c&&this.spanTints.push({axis:`price`,from:Math.min(...m),to:Math.max(...m),tint:o})),r.prices.forEach((e,t)=>{let o=m[t];o<u.y||o>u.y+u.height||Nf(n,{text:d(e,l,h,this.locale),anchorX:f,anchorY:o,orientation:`right`,bg:r.color,fg:s,theme:i,font:a})}),n.restore()}renderTimeSpan(n,r,i,a,o,s,c,l,u){let d=i.chartRect,f=u??d.y+d.height,p=r.times.map(t=>e.j(t,i));n.save(),n.beginPath(),n.rect(d.x,f,d.width,t.TIME_AXIS_HEIGHT),n.clip(),p.length>1&&(n.fillStyle=c,n.fillRect(Math.min(...p),f,Math.abs(p[p.length-1]-p[0]),t.TIME_AXIS_HEIGHT),this.spanTints.push({axis:`time`,from:Math.min(...p),to:Math.max(...p),tint:c})),r.times.forEach((e,t)=>{let i=p[t];i<d.x||i>d.x+d.width||Nf(n,{text:this.formatTime(e,o),anchorX:i,anchorY:f,orientation:`bottom`,bg:r.color,fg:l,theme:a,font:s})}),n.restore()}renderSynced(t,n,r,i){let a=e.C(i,n),{chartRect:o}=n;if(a<o.x||a>o.x+o.width)return;let s=de(r);this.magnetMode&&i>=0&&i<this.series().length&&Df(t,a,n,s.vertical.color),Of(t,a,o,s.vertical)}renderSyncedTimeLabel(t,n,r,i,a,o,s=[]){let c=e.C(a,n),{chartRect:l}=n;c<l.x||c>l.x+l.width||this.drawTimePill(t,n,r,i,a,c,o,s)}formatTime(e,t){return this.timeText(e,ci(t))}timeText(e,n){return this.timeFormatter?this.timeFormatter(e*(0,t.barTimeUnit)(n),{kind:`crosshair`,timeZone:this.tz}):Pf(e*(0,t.barTimeUnit)(n),this.tz,(0,t.barsAreDaily)(n),this.exchangeZone)}drawTimePill(t,n,r,i,a,o,s,c=[]){if(i.length===0||!this.timesPastData&&(a<0||a>=i.length))return;let l=ci(i),u=e.S(a,l),d=this.timeText(u,l),f=`600 ${r.font.sizeSmall}px ${r.font.family}`,p=s??n.chartRect.y+n.chartRect.height;t.font=f;let m=Math.ceil(t.measureText(d).width)/2+Af;jf(t,c,o-m,o+m,p,r,this.spanTints),Nf(t,{text:d,anchorX:o,anchorY:p,orientation:`bottom`,bg:de(r).labelBackground,fg:de(r).labelText,theme:r,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)}},Ef=[4,4];function Df(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 Of(n,r,i,a){if(!a.visible)return;n.setLineDash((0,t.lineDash)(a.style,Ef,a.width)),n.strokeStyle=a.color;let o=e._(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 kf=20,Af=8;function jf(e,t,n,r,i,a,o=[]){let s=t.filter(e=>e.right>n-2&&e.left<r+2);if(s.length===0)return;e.save();let c=a.font.sizeSmall+12;for(let t of s){let n=t.left-2,r=t.right-t.left+4;e.fillStyle=a.background,e.fillRect(n,i+1,r,c);for(let t of o){if(t.axis!==`time`)continue;let a=Math.max(n,t.from),o=Math.min(n+r,t.to);o<=a||(e.fillStyle=t.tint,e.fillRect(a,i+1,o-a,c))}}e.restore()}function Mf(e,t,n,r,i,a,o=[]){let s=Math.ceil(a.font.sizeSmall/2)+1,c=t.filter(e=>Math.abs(e-n)<kf/2+s);if(c.length!==0){e.save();for(let t of c){e.fillStyle=a.background,e.fillRect(r+1,t-s,i-1,s*2);for(let n of o){if(n.axis!==`price`)continue;let a=Math.max(t-s,n.from),o=Math.min(t+s,n.to);o<=a||(e.fillStyle=n.tint,e.fillRect(r+1,a,i-1,o-a))}}e.restore()}}function Nf(e,t){e.save(),e.font=t.font;let n=Af,r=Math.ceil(e.measureText(t.text).width)+n*2,i=kf;if(e.fillStyle=t.bg,e.textBaseline=`middle`,t.orientation===`right`){let a=t.anchorX+5;k(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;k(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 Pf(e,n,r,i){if(r){let r=(0,t.barDateParts)(e,n,i);return`${r.month}/${r.day}/${r.year}`}let a=(0,t.timeParts)(e,n),{year:o,month:s,day:c,hours:l,minutes:u}=a;return r===void 0&&(0,t.isDateOnly)(a)?`${s}/${c}/${o}`:`${s}/${c} ${l<10?`0`+l:l}:${u<10?`0`+u:u}`}var Ff=[`cross`,`dot`,`arrow`];function If(e){return typeof e==`string`&&Ff.includes(e)}var Lf=9,Rf=3,zf=1.5;function Bf(e){return e.replace(/['"<>&]/g,``)}function Vf(e,t,n){if(e===`arrow`)return`default`;if(e===`cross`)return`crosshair`;let r=Lf/2,i=`<svg xmlns='http://www.w3.org/2000/svg' width='${Lf}' height='${Lf}'><circle cx='${r}' cy='${r}' r='${Rf}' fill='${Bf(t)}' stroke='${Bf(n)}' stroke-width='${zf}'/></svg>`,a=Math.floor(r);return`url("data:image/svg+xml,${encodeURIComponent(i)}") ${a} ${a}, crosshair`}var Hf=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}}},Uf=16,Wf=80,Gf=864e5,Kf={month:`short`,day:`numeric`},qf={month:`short`,day:`numeric`,year:`numeric`};function Jf(e,n,r,i){return(0,t.zonedDateFormatter)(r,i?qf:Kf,n)(e)}var Yf=e=>e<10?`0${e}`:`${e}`;function Xf(e,n,r,i=`en-US`,a,o){let s=(0,t.normalizeBarTime)(e,a),c=(0,t.timeParts)(s,n);if(r!==void 0&&r>0?r>=Gf:(0,t.isDateOnly)(c))return Jf(s,(0,t.barDateZone)(s,n,o),i,!0);let l=Jf(s,n,i,!1),u=`${Yf(c.hours)}:${Yf(c.minutes)}`;return r!==void 0&&r>0&&r<6e4?`${l} · ${u}:${Yf(new Date(s).getUTCSeconds())}`:`${l} · ${u}`}var Zf=1e4;function Qf(e,n){return Number.isFinite(e)?(0,t.usesKoreanUnits)(n)&&e>=Zf?(0,t.formatVolumeLoc)(e,n):(0,t.usesKoreanUnits)(n)?(0,t.formatPrice)(e,e%1==0?0:2,n):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 $f=class{el=null;visible=!1;appliedTheme=null;locale=`en-US`;pricePrecision=null;tz=null;exchangeZone=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)`}),s(t);let n=ep({display:`flex`,alignItems:`center`,gap:`7px`,marginBottom:`6px`});this.dirEl=ep({width:`3px`,height:`12px`,borderRadius:`2px`,flex:`none`}),this.timeEl=ep({flex:`1`,fontSize:`11px`,letterSpacing:`0.01em`}),this.changeEl=ep({padding:`1px 6px`,borderRadius:`999px`,fontSize:`10.5px`,fontWeight:`600`}),n.append(this.dirEl,this.timeEl,this.changeEl);let r=ep({display:`grid`,gridTemplateColumns:`auto 1fr auto 1fr`,columnGap:`8px`,rowGap:`1px`,alignItems:`baseline`}),i=e=>{let t=ep({fontSize:`10px`,letterSpacing:`0.04em`});t.textContent=e,this.labelEls.push(t);let n=ep({textAlign:`right`,fontWeight:`500`});return r.append(t,n),n},a=i(`O`),o=i(`H`),c=i(`L`),l=i(`C`);this.dividerEl=ep({height:`1px`,margin:`6px 0 5px`});let u=ep({display:`flex`,justifyContent:`space-between`,gap:`12px`}),d=ep({fontSize:`10px`,letterSpacing:`0.04em`});d.textContent=`VOL`,this.labelEls.push(d);let f=ep({fontWeight:`500`});u.append(d,f),this.valueEls={open:a,high:o,low:c,close:l,volume:f},t.append(n,r,this.dividerEl,u),e.appendChild(t),this.el=t}setLocale(e){this.locale=e}setPricePrecision(e){this.pricePrecision=e}setTimezoneOffset(e){this.tz=e}setExchangeTimeZone(e){this.exchangeZone=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}):Xf(n.time,this.tz,a.barStepMs,this.locale,a.timeUnit,this.exchangeZone),this.changeEl.textContent=`${m}${(0,t.formatPrice)(Math.abs(d),2,this.locale)}%`,this.changeEl.style.color=p,this.changeEl.style.background=rp(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=Qf(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-Wf,height:i.height},g=h.x+h.width,_=h.y+h.height,v=e.x+Uf,y=e.y-this.height/2;v+this.width>g-4&&(v=e.x-this.width-Uf),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=tp(e.background);t.style.background=rp(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 ep(e){let t=document.createElement(`div`);return Object.assign(t.style,e),t}function tp(e){let t=np(e);return t?(.299*t[0]+.587*t[1]+.114*t[2])/255<.5:!0}function np(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 rp(e,t){let n=np(e);return n?`rgba(${n[0]}, ${n[1]}, ${n[2]}, ${t})`:`color-mix(in srgb, ${e} ${Math.round(t*100)}%, transparent)`}var ip=2,ap=2,op=`0.7`,sp=class{el=null;deltaEl=null;timeEl=null;ohlcEl=null;pinnedBar=null;pinnedIndex=-1;tz=null;exchangeZone=null;priceFormatter=null;pricePrecision=null;locale=`en-US`;setTimezone(e){this.tz=e}setExchangeTimeZone(e){this.exchangeZone=e}setPriceFormatter(e){this.priceFormatter=e}setPricePrecision(e){this.pricePrecision=e!==null&&Number.isInteger(e)&&e>=0?e:null}setLocale(e){this.locale=e}fmt(e){return this.priceFormatter?this.priceFormatter(e):(0,t.formatPrice)(e,this.pricePrecision??ip,this.locale)}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`}),s(this.el),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,a=!1){if(!this.el||!this.timeEl||!this.ohlcEl)return;this.pinnedBar=e,this.pinnedIndex=n;let o=e.close>=e.open?r.candleUp:r.candleDown,s=(0,t.normalizeBarTime)(e.time,i),c=a?(0,t.barDateParts)(s,this.tz,this.exchangeZone):(0,t.timeParts)(s,this.tz);this.timeEl.textContent=a?`${c.month}/${c.day}/${c.year}`:`${c.month}/${c.day} ${cp(c.hours)}:${cp(c.minutes)}`,this.timeEl.style.color=r.textSecondary;let l=[];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=o,r.textContent=this.fmt(n),l.push(e,r)}this.ohlcEl.replaceChildren(...l);let u=lp(r.background);this.el.style.background=up(r.background,u?.96:.97),this.el.style.border=`1px solid ${o}`,this.el.style.boxShadow=u?`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(n,r,i,a){if(!this.el||!this.pinnedBar)return;let o=e.C(this.pinnedIndex,n),s=e.O(this.pinnedBar.close,n),c=n.chartRect,l=o>=c.x-4&&o<=c.x+c.width+4;this.el.style.opacity=l?`1`:`0.35`;let u=Math.max(c.x,Math.min(c.x+c.width-180,o+8)),d=Math.max(c.y,Math.min(c.y+c.height-90,s-64));if(this.el.style.transform=`translate(${Math.round(u)}px, ${Math.round(d)}px)`,this.el.style.left=`0`,this.el.style.top=`0`,this.deltaEl)if(r&&i!==null&&i!==this.pinnedIndex){let e=r.close-this.pinnedBar.close,n=this.pinnedBar.close===0?0:e/this.pinnedBar.close*100,o=e>0?`+`:e<0?`−`:``,s=i-this.pinnedIndex,c=e>=0?a.candleUp:a.candleDown;this.deltaEl.style.color=c;let l=(0,t.formatPrice)(Math.abs(n),ap,this.locale),u=document.createElement(`span`);u.style.opacity=op,u.textContent=`(${o}${l}%)`,this.deltaEl.replaceChildren(`Δ ${o}${this.fmt(Math.abs(e))} `,u,` · ${s>0?`+`:``}${s} 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 cp(e){return e<10?`0`+e:``+e}function lp(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 up(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 dp=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}},fp=1.5,pp=1.5,mp=1,hp=2.5,gp=.7,_p=4,vp=.2,yp={primary:null,hover:null,drag:null};function bp(e){yp=e??{primary:null,hover:null,drag:null}}function xp(e,t,n){return(Math.round(e*t+n-.5)+.5-n)/t}function Sp(e,t,n,r){e.beginPath(),e.arc(t,n,r,0,Math.PI*2)}function Cp(e,n,r,i={}){let a=j(),o=n.style.color,s=e.getTransform?.()??{a:1,d:1,e:0,f:0},c=n.id===yp.primary&&!n.locked;e.save(),e.setLineDash([]),r.forEach((r,l)=>{let u=xp(r.x,s.a||1,s.e??0),d=xp(r.y,s.d||1,s.f??0),f=Nn(n.style.lineWidth)+pp;if(yn(u-f,d-f,f*2,f*2),!c){Sp(e,u,d,hp*a.scale),e.globalAlpha=gp,e.fillStyle=o,e.fill(),e.globalAlpha=1;return}let p=Nn(n.style.lineWidth)-(i.sides?.has(l)?mp:0),m=yp.drag?.id===n.id&&yp.drag.index===l,h=!m&&yp.hover?.id===n.id&&yp.hover.index===l||m?p+pp:p;m&&(Sp(e,u,d,h+_p),e.fillStyle=(0,t.withAlpha)(o,vp),e.fill()),Sp(e,u,d,h),e.fillStyle=m?o:a.handleFill,e.fill(),e.strokeStyle=m?a.background:o,e.lineWidth=fp,e.stroke()}),e.restore()}function wp(e){return e?.anchoring===`screen`}var Tp=24;function Ep(e,t,n){return Math.max(t,Math.min(e,Math.max(t,n)))}function Dp(e,t){let n=t.chartRect;return{x:Ep(n.x+e.time*n.width,n.x,n.x+n.width-Tp),y:Ep(n.y+e.price*n.height,n.y+Tp,n.y+n.height-Tp)}}function Op(e){let t=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0;return e.map(e=>({time:t(e.time),price:t(e.price)}))}function kp(e,t){let n=t.chartRect,r=(e,t)=>t>0?Math.min(1,Math.max(0,e/t)):0;return{time:r(e.x-n.x,n.width),price:r(e.y-n.y,n.height)}}function Ap(e,t,n,r){return e.map(e=>{let i=Dp(e,r);return kp({x:i.x+t,y:i.y+n},r)})}function jp(e,t){let n=e=>Math.min(1,Math.max(0,e+t<=1?e+t:e-t));return e.map(e=>({time:n(e.time),price:n(e.price)}))}var Mp={at:e=>e,value:e=>e,price:e=>e};function Np(t){if(!t)return Mp;let{min:n,max:r}=t.priceRange,i=t.logScale===!0&&n>0&&r>0;return{at:n=>e.A(n,t),value:i?e=>Math.log(Math.max(e,2**-52)):e=>e,price:i?Math.exp:e=>e}}function Pp(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 Fp(e,t,n,r=!1){for(let r=0;r<t.length-1;r++)if(Pp(e,t[r],t[r+1])<=n)return!0;return r&&t.length>2&&Pp(e,t[t.length-1],t[0])<=n}function Ip(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 Lp=.55,J=class{hitTestAnchor(e,t,n,r){let i=-1,a=1/0,o=this.handlePoints(t,n);for(let t=0;t<o.length;t++){let n=o[t],s=Math.hypot(e.x-n.x,e.y-n.y);s<=r&&s<a&&(i=t,a=s)}return i}option(e,t){let n=this.descriptor.options?.[t],r=e.options?.[t];return n?r!==void 0&&Ip(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=Mp){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 wp(this.descriptor)?Dp(t,n):{x:e.j(t.time,n),y:e.O(t.price,n)}}pixelToAnchor(t,n){return wp(this.descriptor)?kp(t,n):{time:e.P(t.x,n),price:e.F(t.y,n)}}applyLineStyle(e,t){e.strokeStyle=t.color,e.lineWidth=t.lineWidth,e.lineCap=t.lineStyle===`dashed`?`butt`:`round`,e.lineJoin=`round`,e.setLineDash(Ln(t.lineStyle,t.lineWidth))}strokeHorizontal(t,n,r,i){let a=e.v(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._(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`}handlePoints(e,t){return e.anchors.map(e=>this.anchorToPixel(e,t))}timeHandles(e,t){let n=t.chartRect.y+t.chartRect.height/2;return e.anchors.map(e=>({x:this.anchorToPixel(e,t).x,y:n}))}strokeCrispRect(e,t,n,r,i){let a=Math.min(t,t+r),o=Math.max(t,t+r),s=Math.min(n,n+i),c=Math.max(n,n+i);this.strokeHorizontal(e,a,o,s),this.strokeHorizontal(e,a,o,c),this.strokeVertical(e,a,s,c),this.strokeVertical(e,o,s,c)}applyGuideStyle(e,t,n=!1){e.strokeStyle=t,e.lineWidth=1,e.lineCap=`butt`,e.globalAlpha=Lp,e.setLineDash(n?Ln(`guide`,1):[])}renderAnchorHandles(e,t,n){Cp(e,t,this.handlePoints(t,n))}distanceToLine(e,t,n){return Pp(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 Rp(e){if(typeof e!=`string`)return;let t=e.trim().slice(0,80);return t.length>0?t:void 0}function zp(e){let t={};for(let[n,r]of Object.entries(e))t[n]=Array.isArray(r)?r.map(e=>({...e})):r;return t}function Y(e){return{...e,anchors:e.anchors.map(e=>({...e})),style:{...e.style},options:e.options?zp(e.options):void 0,intervals:e.intervals?Ia(e.intervals):void 0,group:e.group?{...e.group}:void 0,meta:e.meta?{...e.meta}:void 0}}function Bp(e,t){return JSON.stringify(e??{})===JSON.stringify(t??{})}function Vp(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 Hp=1,Up=1,Wp=/^tc_drawing_(\d+)$/,Gp=/^tc_group_(\d+)$/;function Kp(){return`tc_drawing_${Hp++}`}function qp(){let e=Up++;return{id:`tc_group_${e}`,number:e}}function Jp(e){for(let t of e){let e=Wp.exec(t.id);e&&(Hp=Math.max(Hp,Number(e[1])+1));let n=t.group?Gp.exec(t.group.id):null;n&&(Up=Math.max(Up,Number(n[1])+1))}}function Yp(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 Xp(e,t,n){let r=t-1;if(typeof n==`number`)return Number.isInteger(n)?Math.min(r,Math.max(0,n)):e;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 Zp(e,t){return e.map(e=>e.id===t.id?structuredClone(t):e)}function Qp(e,t){switch(t.type){case`drawingBatch`:return[...t.actions??[]].reverse().reduce(Qp,[...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?Yp(e,t.order.before):[...e];case`drawingModify`:return t.before?Zp(e,t.before):[...e];default:return[...e]}}function $p(e,t){switch(t.type){case`drawingBatch`:return(t.actions??[]).reduce($p,[...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?Yp(e,t.order.after):[...e];case`drawingModify`:return t.after?Zp(e,t.after):[...e];default:return[...e]}}var em={"]":[`forward`,`front`],"}":[`front`,`front`],"[":[`backward`,`back`],"{":[`back`,`back`]};function tm(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=em[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 nm=2,rm=6;function im(e){return e.descriptor.creation??`clicks`}var am=class{drawing=null;plugin=null;preview=null;lastPos=null;dragging=!1;step=nm;get current(){return this.drawing}reset(){this.drawing=null,this.plugin=null,this.preview=null,this.lastPos=null,this.dragging=!1,this.step=nm}press(e,t,n,r,i){if(this.dragging)return`continue`;let a=im(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)<=rm)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 im(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||im(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}},om=50;function sm(e,t,n,r,i){return cm(e,t,n,r,e=>[r[e].open,r[e].high,r[e].low,r[e].close],i)}function cm(t,n,r,i,a,o){if(r===`none`||i.length===0)return{time:t,price:n};let s=!!(o?.data&&o.data.length>0),c=Math.round(s?e.M(t,i):t);if(c<0||c>i.length-1)return{time:t,price:n};let l=s?i[c].time:c,u=a(c).filter(e=>Number.isFinite(e));if(u.length===0)return{time:l,price:n};let d=u[0];for(let e of u)Math.abs(n-e)<Math.abs(n-d)&&(d=e);return r===`magnet`&&o&&Math.abs(e.O(n,o)-e.O(d,o))>om?{time:l,price:n}:{time:l,price:d}}var lm=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}},um=Math.PI/4,dm=new Set([`trendLine`,`ray`,`extendedLine`,`infoLine`,`trendAngle`,`arrow`,`horizontalRay`,`measure`,`priceRange`,`dateRange`,`dateAndPriceRange`,`path`,`polyline`,`fibRetracement`,`fibExtension`]);function fm(e){return dm.has(e)}function pm(e,t){let n=t.x-e.x,r=t.y-e.y;if(n===0&&r===0)return t;let i=Math.round(Math.atan2(r,n)/um)*um,a=Math.cos(i),o=Math.sin(i),s=n*a+r*o;return{x:e.x+mm(s*a),y:e.y+mm(s*o)}}function mm(e){return Math.abs(e)<1e-9?0:e}function hm(t,n,r){let i=gm(t,r),a=pm(i,n);if(a.x===i.x)return{time:t.time,price:e.F(a.y,r)};let o=e.P(a.x,r);if(a.y===i.y)return{time:o,price:t.price};let s=e.j(o,r)-i.x;return{time:o,price:e.F(i.y+Math.sign(a.y-i.y)*Math.abs(s),r)}}function gm(t,n){return{x:e.j(t.time,n),y:e.O(t.price,n)}}function _m(e,t,n){let r=-1,i=1/0;return e.forEach((e,a)=>{let o=gm(e,n),s=Math.hypot(o.x-t.x,o.y-t.y);s<i&&(r=a,i=s)}),r}var vm=3,ym=class{start=null;handle=-1;grabbed=[];held=-1;constructor(e,t=()=>!1){this.find=e,this.onScreen=t}isActive(){return this.start!==null}activeHandle(){return this.start===null?-1:this.handle}beginMove(e,t){this.start=e,this.handle=-1,this.held=-1,this.grabbed=t.map(e=>({id:e.id,anchors:e.anchors.map(e=>({...e})),before:Y(e)}))}beginResize(e,t,n){this.start=e,this.handle=n,this.grabbed=[{id:t.id,anchors:t.anchors.map(e=>({...e})),before:Y(t)}]}move(e,t,n,r){return!this.start||this.grabbed.length===0?!1:this.handle>=0?this.reshape(e,t,n,r):this.translate(e,t,r)}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(e,t,n){let r=this.start,i=e.x-r.x,a=e.y-r.y;if(Math.hypot(i,a)<vm&&this.unmoved())return!0;let o=t.barWidth+t.barSpacing,s=o>0?Math.round(i/o):0,c=this.find(this.grabbed[0].id),l=n&&c&&!this.onScreen(c)?this.snapHeld(s,a,t,n):null;return l&&(a+=l.dy),this.grabbed.forEach(({id:n,anchors:o},c)=>{let u=this.find(n);if(!(!u||u.locked)){if(this.onScreen(u)){u.anchors=Ap(o,i,e.y-r.y,t);return}u.anchors=bm(o,s,a,t),c===0&&l&&(u.anchors[this.held]={...u.anchors[this.held],price:l.price})}}),!0}snapHeld(t,n,r,i){let a=this.grabbed[0];this.held<0&&(this.held=_m(a.anchors,this.start,r));let o=a.anchors[this.held];if(!o)return null;let[s]=bm([o],t,n,r),{price:c}=i.snap(s);return c===s.price?null:{price:c,dy:e.O(c,r)-e.O(s.price,r)}}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,a){let o=this.find(this.grabbed[0].id);if(!o)return!1;let s=this.onScreen(o)?kp(n,r):a?a.handleAt(n,o,this.handle):{time:e.P(n.x,r),price:e.F(n.y,r)};if(i?.moveHandle){let e=i.moveHandle(Y(o),this.handle,s);o.anchors=e.anchors,o.options=e.options&&Object.keys(e.options).length>0?(0,t.sanitizeDrawingOptions)(i.descriptor.options,e.options):void 0}else this.handle<o.anchors.length&&(o.anchors[this.handle]=s);return!0}};function bm(t,n,r,i){let a=i.data,o=t=>{let r=e.A(t,i)+n;return a&&a.length>0?e.S(r,a):r};return t.map(t=>({time:n===0?t.time:o(t.time),price:r===0?t.price:e.F(e.O(t.price,i)+r,i)}))}function xm(e){let t=e.filter(Number.isFinite);if(t.length===0)return[];let n=Math.min(...t),r=Math.max(...t);return n===r?[n]:[n,r]}function Sm(e,t){let n=t.axisSpan??`both`;if(n===`none`||t.anchoring===`screen`)return null;let r=n===`time`?[]:xm(e.anchors.map(e=>e.price)),i=n===`price`?[]:xm(e.anchors.map(e=>e.time));return r.length===0&&i.length===0?null:{prices:r,times:i}}var Cm={drawings:[],pastes:0},wm=1e7,Tm={line:8,handle:8},Em=8,Dm=1e3,Om=.02;function km(e,t){return e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height}function Am(e){return e.type===`indicators`||e.type===`custom`}function jm(e){return(e.actions??[]).some(e=>Am(e)||jm(e))}var Mm=class{registry=new Map;drawings=[];state=`idle`;activeTool=null;activeStyle={color:`#4c8dff`,lineWidth:1,lineStyle:`solid`,fillColor:t.LINE_TINT_FILL,fillOpacity:.12};hoverHandle=null;extents=new Map;hoverDrawing=null;creator=new am;finishedAt=-1/0;creationPressAt=-1/0;eraser=!1;selection=new lm;drag=new ym(e=>this.drawings.find(t=>t.id===e),e=>this.onScreen(e.type));eventCallback=null;requestRender=null;undoRedo=null;magnetMode=`none`;mods={ctrl:!1,shift:!1};pendingCopy=null;copies=null;copiedFrom=[];copySources=new Map;lastNudge=null;dataGetter=null;dataRevision=()=>0;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,this.dataRevision)}setEventCallback(e){this.eventCallback=e}setRequestRender(e){this.requestRender=e}setUndoRedoManager(e){this.undoRedo=e}setMagnetMode(e){this.magnetMode=e}getMagnetMode(){return this.magnetMode}setModifiers(e){this.mods={ctrl:e.ctrl,shift:e.shift}}activeMagnet(){return!this.mods.ctrl||this.copies?this.magnetMode:this.magnetMode===`none`?`strong`:`none`}setDataGetter(e,t=()=>0){this.dataGetter=e,this.dataRevision=t;for(let n of this.registry.values())n.setDataGetter?.(e,t)}setDisplayDataGetter(e){this.displayDataGetter=e}panes=null;setPanes(e){this.panes=e}paneAt(e){return this.panes?this.panes.paneAt(e):void 0}viewportFor(e,t){if(e===void 0)return t;let n=this.panes?.viewportOf(e)??null;return n&&t.formatTime&&!n.formatTime?{...n,formatTime:t.formatTime}:n}scopeAt(e,t){if(!this.panes&&!km(e,t.chartRect))return null;let n=this.paneAt(e);if(n===null)return null;let r=this.viewportFor(n,t);return r?{pane:n,viewport:r}:null}renamePanes(e){let t=!1;this.drawings=this.drawings.map(n=>{let r=n.paneId===void 0?void 0:e.get(n.paneId);return r===void 0||r===n.paneId?n:(t=!0,{...n,paneId:r})}),t&&this.requestRender?.()}onScreen(e){return wp(this.registry.get(e)?.descriptor)}anchorPoint(t,n,r){return this.onScreen(t)?Dp(n,r):{x:e.j(n.time,r),y:e.O(n.price,r)}}snapToOHLC(e,t,n,r){let i=this.activeMagnet(),a=i===`none`?[]:this.displayDataGetter?.()??this.dataGetter?.()??[];if(r!==void 0){let o=this.panes?.valuesAt;return cm(e,t,i,a,e=>o?.(r,e)??[],n)}return sm(e,t,i,a,n)}dragEdit(t,n){if(!(this.registry.get(t.type)?.descriptor.creation===`freehand`||this.onScreen(t.type)))return{handleAt:(t,r,i)=>{let a=fm(r.type)&&r.anchors.length>=2&&i<r.anchors.length?r.anchors[i===0?1:i-1]:void 0;return this.mods.shift&&a?hm(a,t,n):this.snapToOHLC(e.P(t.x,n),e.F(t.y,n),n,r.paneId)},snap:e=>this.snapToOHLC(e.time,e.price,n,t.paneId)}}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(Am(e)){this.foreignHistory?.(e,`undo`);return}if(e.type===`drawingBatch`&&jm(e)){for(let t of[...e.actions??[]].reverse())this.applyUndoAction(t);return}this.applyHistory(Qp(this.drawings,e))}applyRedoAction(e){if(Am(e)){this.foreignHistory?.(e,`redo`);return}if(e.type===`drawingBatch`&&jm(e)){for(let t of e.actions??[])this.applyRedoAction(t);return}this.applyHistory($p(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.dropCopyGesture(),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(e,t,n){if(this.state===`creating`)return 0;let r=this.viewportFor(n,t);if(!r)return 0;this.selection.clear(),this.state=`idle`;let i=Math.min(e.x0,e.x1),a=Math.max(e.x0,e.x1),o=Math.min(e.y0,e.y1),s=Math.max(e.y0,e.y1);for(let e of this.drawings)!this.shown(e)||e.paneId!==n||e.anchors.some(t=>{let{x:n,y:c}=this.anchorPoint(e.type,t,r);return n>=i&&n<=a&&c>=o&&c<=s})&&this.addToSelection(e.id);return this.requestRender?.(),this.getSelectedDrawingIds().length}toggleSelectionAt(e,t){if(this.state===`creating`)return!1;let n=this.scopeAt(e,t);if(!n)return!1;for(let t=this.drawings.length-1;t>=0;t--){let r=this.drawings[t];if(!(!this.shown(r)||r.paneId!==n.pane)&&this.registry.get(r.type)?.hitTest(e,r,n.viewport,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&&e.paneId===t.paneId);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=Y(n);Object.assign(n,t),this.record({type:`drawingModify`,before:e,after:Y(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)}onDrawnPane(e){return e.paneId===void 0||(this.panes?.viewportOf(e.paneId)??null)!==null}shown(e){return e.visible&&ja(e.intervals,this.timeframe)&&this.onDrawnPane(e)}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),this.clearHover(),this.dropCopyGesture();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:(Cm.drawings=e.map(e=>structuredClone(e)),Cm.pastes=0,e.length)}canPaste(){return this.state!==`creating`&&Cm.drawings.some(e=>this.canPasteType(e.type))}canPasteType(e){return this.registry.has(e)&&this.toolAllowed(e)}paste(){if(Cm.drawings.length===0||this.state===`creating`)return[];let e=Cm.drawings.every(e=>this.drawings.some(t=>t.id===e.id));Cm.pastes+=1;let t=e?this.computeBarOffsetTime(3*Cm.pastes):0,n=[];if(this.batchUndo(()=>{for(let e of Cm.drawings)this.canPasteType(e.type)&&(e.paneId!==void 0&&(!this.panes?.hasPane(e.paneId)||this.registry.get(e.type)?.descriptor.priceOnly)||n.push(this.addDrawing({...e.paneId===void 0?{}:{paneId:e.paneId},type:e.type,anchors:this.onScreen(e.type)?jp(e.anchors,Om*Cm.pastes):e.anchors.map(e=>({...e,time:e.time+t})),style:{...e.style},options:e.options?zp(e.options):void 0,intervals:e.intervals,meta:e.meta?structuredClone(e.meta):void 0,name:e.name})))}),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=Y(n);n.style={...n.style,...e},this.record({type:`drawingModify`,before:i,after:Y(n)}),r=!0}}),r&&this.requestRender?.(),r}onPointerDown(e,t,n=Tm){if(this.eraser){let r=this.scopeAt(e,t);return r?this.erase(e,r,n.line):!1}return 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,r=n?this.viewportFor(n.paneId,t):null;if(n&&r&&this.creator.move(this.creationAnchor(n.type,e,r,n.paneId),e))return this.requestRender?.(),!0;if(this.pendingCopy){let{pos:t}=this.pendingCopy;if(Math.hypot(e.x-t.x,e.y-t.y)<Em)return!0;this.startCopy()}if((this.state===`moving`||this.state===`resizing`)&&this.drag.isActive()){let n=this.drawings.find(e=>e.id===this.selection.primary),r=this.viewportFor(n?.paneId,t),i=n&&r?this.dragEdit(n,r):void 0;return!r||!this.drag.move(e,r,n&&this.registry.get(n.type),i)?!1:(this.requestRender?.(),!0)}return!1}onPointerUp(){let e=this.state===`creating`?this.creator.release():null;if(e)return this.afterCreationStep(e),!0;if(this.pendingCopy)return this.toggleCopied();if(this.copies)return this.endCopy(),!0;if(this.state===`moving`||this.state===`resizing`){let e=this.drag.end();return this.batchUndo(()=>{for(let{before:t,drawing:n}of e)Vp(n.anchors,t.anchors)&&Bp(n.options,t.options)||this.record({type:`drawingModify`,before:t,after:Y(n)})}),this.state=`selected`,this.requestRender?.(),!0}return!1}beginCopyDrag(e,t,n=Tm){if(this.state===`creating`||this.state===`moving`||this.state===`resizing`||this.eraser)return!1;if(this.beginHandleDrag(e,t,n))return!0;let r=this.drawingAt(e,t,n.line);return r?(this.pendingCopy={pos:e,id:r},!0):!1}beginHandleDrag(e,t,n){let r=this.scopeAt(e,t),i=this.drawings.find(e=>e.id===this.selection.primary);if(!r||!i||i.locked||!this.shown(i)||i.paneId!==r.pane)return!1;let a=this.registry.get(i.type)?.hitTestAnchor(e,i,r.viewport,n.handle)??-1;return a<0?!1:(this.state=`resizing`,this.drag.beginResize(e,i,a),!0)}dropCopyGesture(){this.pendingCopy=null;let e=this.copies;e&&(this.copies=null,this.copySources=new Map,this.drag.end(),this.drawings=this.drawings.filter(t=>!e.includes(t.id)),this.deselect(e),this.state===`moving`&&(this.state=`idle`))}startCopy(){let{pos:e,id:t}=this.pendingCopy;this.pendingCopy=null;let n=this.selection.has(t)?[t,...this.getSelectedDrawingIds().filter(e=>e!==t)]:[t],r=this.drawings.find(e=>e.id===t),i=n.map(e=>this.drawings.find(t=>t.id===e)).filter(e=>e!==void 0&&this.shown(e)&&e.paneId===r?.paneId&&this.canPasteType(e.type));if(i.length===0)return;let a=i.map(e=>{let{group:t,...n}=structuredClone(e);return{...n,id:Kp(),locked:!1}});this.copySources=new Map(a.map((e,t)=>[e.id,i[t].anchors.map(e=>({...e}))])),this.drawings=[...this.drawings,...a],this.copies=a.map(e=>e.id),this.copiedFrom=this.getSelectedDrawingIds(),this.selection.only(a[0].id,this.copies.slice(1)),this.beginMove(e,a[0]),this.requestRender?.()}endCopy(){let e=this.copies;this.copies=null,this.drag.end(),this.state=`selected`;let t=this.copySources;this.copySources=new Map;let n=e.map(e=>this.drawings.find(t=>t.id===e)).filter(e=>e!==void 0);if(n.every(e=>{let n=t.get(e.id);return!!n&&Vp(e.anchors,n)})){this.drawings=this.drawings.filter(t=>!e.includes(t.id)),this.deselect(e),this.requestRender?.();return}this.batchUndo(()=>{for(let e of n)this.record({type:`drawingCreate`,before:null,after:Y(e)})});for(let e of n)this.eventCallback?.(`drawingCreate`,{id:e.id,type:e.type,drawing:e});this.requestRender?.()}toggleCopied(){let{id:e}=this.pendingCopy;return this.pendingCopy=null,this.selection.has(e)?this.deselect([e]):this.addToSelection(e),this.requestRender?.(),!0}nudge(e,t,n){if(this.state!==`selected`)return!1;let r=this.getSelectedDrawingIds().map(e=>this.drawings.find(t=>t.id===e)).filter(e=>e!==void 0&&!e.locked&&this.shown(e));if(r.length===0||e===0&&t===0)return!1;let i=r.map(e=>e.id).join(`,`),a=Date.now(),o=this.lastNudge,s=o&&o.key===i&&a-o.at<Dm&&o.action!==null&&this.undoRedo?.last()===o.action?o:null,c=s?s.before:r.map(Y),l=r.filter(r=>{let i=this.viewportFor(r.paneId,n);return i?(r.anchors=this.onScreen(r.type)?Ap(r.anchors,e*(i.barWidth+i.barSpacing),t,i):bm(r.anchors,e,t,i),!0):!1});if(l.length===0)return!1;s&&this.undoRedo?.dropLast(),this.batchUndo(()=>{for(let e of l){let t=c.find(t=>t.id===e.id);t&&this.record({type:`drawingModify`,before:t,after:Y(e)})}}),this.lastNudge={key:i,at:a,before:c,action:this.undoRedo?.last()??null};for(let e of l)this.eventCallback?.(`drawingUpdate`,{id:e.id});return this.requestRender?.(),!0}onKeyDown(e,t=!1,n){let r=tm(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(){if(this.pendingCopy||this.copies){let e=this.copies?this.copiedFrom.filter(e=>this.isShown(e)):[];return this.dropCopyGesture(),e.length>0&&(this.selection.only(e[0],e.slice(1)),this.state=`selected`),this.requestRender?.(),!0}if(this.state===`moving`||this.state===`resizing`){let e=new Map(this.drag.end().map(({before:e})=>[e.id,Y(e)]));return this.drawings=this.drawings.map(t=>e.get(t.id)??t),this.state=`selected`,this.requestRender?.(),!0}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){this.dropCopyGesture(),Jp(e),this.drawings=this.upgradeLegacyAnchors(e).map(e=>{let n=e.name===void 0||e.name===Rp(e.name)?e:Rm(e,Rp(e.name)),r=this.onScreen(n.type)?{...n,anchors:Op(n.anchors)}:n;if(!r.options&&r.intervals===void 0)return r;let i=(0,t.sanitizeDrawingOptions)(this.optionDefs(r.type),r.options);return{...r,options:Object.keys(i).length>0?i:void 0,intervals:Ma(r.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=Xp(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=Y(e);t(e),this.record({type:`drawingModify`,before:n,after:Y(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}=qp(),o={id:i,name:zm(t)||`Group ${a}`};return this.batchUndo(()=>{for(let e of r){let t=Y(e);e.group={...o},this.record({type:`drawingModify`,before:t,after:Y(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=zm(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`}getPlugin(e){return this.registry.get(e)??null}textBoxOf(e,t){let n=this.drawings.find(t=>t.id===e),r=n?this.viewportFor(n.paneId,t):null;return!n||!r?null:this.registry.get(n.type)?.textBox?.(n,r)??null}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={...zp(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 zp(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:Y(r);if(n.anchors&&(r.anchors=this.onScreen(r.type)?Op(n.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}if(n.name!==void 0){let e=Rp(n.name);e===void 0?delete r.name:r.name=e}return n.intervals!==void 0&&(r.intervals=Ma(n.intervals)??void 0,!this.edits.has(e)&&!this.shown(r)&&this.deselect([e])),i&&this.record({type:`drawingModify`,before:i,after:Y(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,Y(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:Y(this.drawings[r])}),this.shown(this.drawings[r])||this.deselect([e]),this.eventCallback?.(`drawingUpdate`,{id:e}))}addDrawing(e){e.id&&Jp([{id:e.id}]);let t=e.id??Kp(),n={id:t,type:e.type,anchors:this.onScreen(e.type)?Op(e.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:Ma(e.intervals)??void 0,meta:e.meta,...typeof e.paneId==`string`?{paneId:e.paneId}:{}},r=Rp(e.name);return r!==void 0&&(n.name=r),this.drawings=[...this.drawings,n],this.record({type:`drawingCreate`,before:null,after:Y(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=wm;return t[t.length-1].time<n?e:e.map(e=>this.onScreen(e.type)?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){this.hoverDrawing===e&&this.clearHover();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)}amendNew(e,t){let n=this.drawings.find(t=>t.id===e);if(!n)return!1;let r=this.undoRedo?.last();if(!this.undoRedo||r?.type!==`drawingCreate`||r.after?.id!==e)return this.updateDrawing(e,t);let i=[],a=this.batch;this.batch=i;let o=!1;try{o=this.updateDrawing(e,t)}finally{this.batch=a}return o?(this.undoRedo.replaceLast({...r,after:Y(n)}),!0):!1}takeBack(e){let t=this.undoRedo?.last();if(!this.undoRedo||t?.type!==`drawingCreate`||t.after?.id!==e){this.removeDrawing(e);return}this.undoRedo.dropLast(),this.drawings=this.drawings.filter(t=>t.id!==e),this.deselect([e]),this.edits.delete(e),this.eventCallback?.(`drawingRemove`,{id:e}),this.requestRender?.()}duplicateDrawing(e){let t=this.drawings.find(t=>t.id===e);if(!t)return null;let n=structuredClone(t);n.id=Kp();let r=this.computeBarOffsetTime(3);return n.anchors=this.onScreen(n.type)?jp(n.anchors,Om):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.dropCopyGesture(),this.drawings=[],this.selection.clear(),this.state=`idle`,this.requestRender?.()}getSelectedDrawingId(){return this.selection.primary}render(t,n){t.save(),t.textAlign=`left`,t.textBaseline=`alphabetic`;let r=this.selection.primary,i=this.state===`resizing`&&r?this.drag.activeHandle():-1;bp({primary:r,hover:this.hoverHandle,drag:i>=0&&r?{id:r,index:i}:null});let a=new Map;this.extents=a;try{for(let e of this.drawings){if(!this.shown(e))continue;let r=this.registry.get(e.type),i=this.viewportFor(e.paneId,n);if(!r||!i)continue;vn();let o=null;try{Lm(t,r,e,i,this.selection.has(e.id))}finally{o=bn()}o&&a.set(e.id,o)}let r=this.creator.previewState(),i=r?this.registry.get(r.type):void 0,o=r?this.viewportFor(r.paneId,n):null;if(r&&i&&o&&(bp({primary:r.id,hover:null,drag:null}),Lm(t,i,r,o,!0),r.anchors.length<2)){let n=o;Cp(t,r,r.anchors.map(t=>this.onScreen(r.type)?Dp(t,n):{x:e.j(t.time,n),y:e.O(t.price,n)}))}}finally{bp(null)}t.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,i){if(this.onScreen(t))return kp(n,r);let a=e.P(n.x,r),o=e.F(n.y,r);if(this.registry.get(t)?.descriptor.creation===`freehand`)return{time:a,price:o};let s=this.creator.current?.anchors,c=s&&s.length>0?s[s.length-1]:void 0;return this.mods.shift&&c&&fm(t)?hm(c,n,r):this.snapToOHLC(a,o,r,i)}handleCreationClick(e,t){let n=this.activeTool,r=n?this.registry.get(n):void 0;if(!n||!r)return!1;let i=this.creator.current,a=i?i.paneId:this.paneAt(e);if(a===null||a!==void 0&&r.descriptor.priceOnly)return!1;let o=this.viewportFor(a,t);if(!o)return!1;let s=()=>({id:Kp(),type:n,anchors:[],style:{...this.activeStyle},visible:!0,locked:!1,options:this.initialOptions(n),...a===void 0?{}:{paneId:a}});return this.creationPressAt=Date.now(),this.afterCreationStep(this.creator.press(r,s,this.creationAnchor(n,e,o,a),e,e=>this.anchorPoint(n,e,o))),!0}afterCreationStep(e){e===`done`?this.finalizeCreation():e===`cancel`&&this.creator.reset(),this.requestRender?.()}setEraser(e){e!==this.eraser&&(this.eraser=e,this.clearHover(),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=Tm.line){for(let r=this.drawings.length-1;r>=0;r--){let i=this.drawings[r];if(!(!this.shown(i)||i.locked||i.paneId!==t.pane)&&this.registry.get(i.type)?.hitTest(e,i,t.viewport,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,drawn:!0}),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=Tm.line){let r=this.scopeAt(e,t);if(!r)return null;for(let t=this.drawings.length-1;t>=0;t--){let i=this.drawings[t];if(!(!this.shown(i)||i.paneId!==r.pane)&&this.registry.get(i.type)?.hitTest(e,i,r.viewport,n))return i.id}return null}hoverCursorAt(e,t){let n=this.hoverAt(e,t),r=n.handle?.id!==this.hoverHandle?.id||n.handle?.index!==this.hoverHandle?.index;return this.hoverHandle=n.handle,this.hoverDrawing=n.drawing,r&&this.requestRender?.(),n.cursor}drawnExtent(e){return this.extents.get(e)??null}clearHover(){let e=this.hoverHandle;this.hoverHandle=null,this.hoverDrawing=null,e&&this.requestRender?.()}renderHover(e,t){let n=this.hoverDrawing;if(!n||this.selection.has(n)&&!this.eraser||this.activeTool||this.state===`creating`)return;let r=this.drawings.find(e=>e.id===n);if(!r||r.locked||!this.shown(r))return;let i=this.registry.get(r.type),a=this.viewportFor(r.paneId,t);i&&a&&Lm(e,i,r,a,!1,!0)}axisSpans(e){let t=this.creator.previewState(),n=t??(this.selection.primary?this.drawings.find(e=>e.id===this.selection.primary):void 0);if(!n||!t&&!this.shown(n))return[];let r=this.registry.get(n.type),i=this.viewportFor(n.paneId,e),a=r&&i?Sm(n,r.descriptor):null;return a&&i?[{...a,color:n.style.color,viewport:i}]:[]}hoverAt(e,t){let n={cursor:null,handle:null,drawing:null},r=this.scopeAt(e,t);if(!r)return n;if(this.eraser){let t=this.erasableAt(e,r);return{...n,cursor:t?`pointer`:null,drawing:t}}if(this.activeTool||this.state===`creating`)return n;let i=Tm.handle,a=r.viewport;if(this.selection.primary){let t=this.drawings.find(e=>e.id===this.selection.primary),n=t&&this.shown(t)&&!t.locked&&t.paneId===r.pane?this.registry.get(t.type):void 0,o=t&&n?n.hitTestAnchor(e,t,a,i):-1;if(t&&o>=0)return{cursor:`move`,handle:{id:t.id,index:o},drawing:t.id}}for(let t=this.drawings.length-1;t>=0;t--){let n=this.drawings[t];if(!(!this.shown(n)||n.locked||n.paneId!==r.pane)&&this.registry.get(n.type)?.hitTest(e,n,a,Tm.line))return{cursor:`pointer`,handle:null,drawing:n.id}}return n}handleSelectionClick(e,t,n){let r=n.line,i=this.scopeAt(e,t);if(!i)return!1;let a=i.viewport;if(this.selection.primary){let t=this.drawings.find(e=>e.id===this.selection.primary);if(t&&this.shown(t)&&!t.locked&&t.paneId===i.pane){let i=this.registry.get(t.type);if(i){let o=i.hitTestAnchor(e,t,a,n.handle);if(o>=0)return this.state=`resizing`,this.drag.beginResize(e,t,o),!0;if(i.hitTest(e,t,a,r))return this.beginMove(e,t),!0}}}for(let t=this.drawings.length-1;t>=0;t--){let n=this.drawings[t];if(!this.shown(n)||n.paneId!==i.pane)continue;let o=this.registry.get(n.type);if(o&&o.hitTest(e,n,a,r))return this.selection.has(n.id)?this.selection.focus(n.id):this.selection.only(n.id,this.groupMates(n)),this.requestRender?.(),n.locked?(this.state=`selected`,!1):(this.beginMove(e,n),!0)}return this.selection.primary&&(this.selection.clear(),this.state=`idle`,this.requestRender?.()),!1}},Nm=.55,Pm=6,Fm=[`fill`,`fillRect`,`fillText`,`strokeText`];function Im(e,n){e.shadowColor=(0,t.withAlpha)(n,Nm),e.shadowBlur=Pm;let r=e;for(let e of Fm)r[e]=()=>void 0;return()=>{for(let e of Fm)delete r[e]}}function Lm(e,t,n,r,i,a=!1){let o=r.chartRect;e.save(),e.beginPath(),e.rect(o.x,o.y,o.width,o.height),e.clip(),Sn(o);let s=a?Im(e,n.style.color):null;try{t.render(e,n,r,i)}finally{s?.(),Sn(null),e.restore()}}function Rm(e,t){let{name:n,...r}=e;return t===void 0?r:{...r,name:t}}function zm(e){return(e??``).trim().slice(0,80)}var Bm=class{keepOut=null;formatTime=null;constructor(e){this.manager=e}setKeepOut(e){this.keepOut=e}setTimeFormat(e){this.formatTime=e}getKeepOut(){return this.keepOut?.()??[]}renderHover(e,t,n){Hn(n??null);try{this.manager.renderHover(e,t)}finally{Hn(null)}}axisSpans(e){return this.manager.axisSpans(e)}render(e,t,n){Hn(n??null),Zn(this.getKeepOut());try{this.manager.render(e,this.formatTime?{...t,formatTime:this.formatTime}:t)}finally{Zn(null),Hn(null)}}};function Vm(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 Hm={0:`#787b86`,.236:`#e8505b`,.25:`#e8505b`,.382:`#d97a0e`,.5:`#1a9a6a`,.618:`#0e93a3`,.75:`#2f7fd8`,.786:`#5b6cf0`,1:`#787b86`,1.272:`#b25ad1`,1.414:`#d6487f`,1.618:`#2f7fd8`,2:`#7a5cff`,2.618:`#e8505b`,3.618:`#b25ad1`,4.236:`#d6487f`};function Um(e,t=[]){return Wm(e,t).map(e=>{let t=Hm[e.value];return t?{...e,color:t}:e})}function Wm(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 Gm(e=!1,t=!1){return{extendLeft:{kind:`boolean`,label:`Extend left`,default:e},extendRight:{kind:`boolean`,label:`Extend right`,default:t}}}var Km={showPrice:{kind:`boolean`,label:`Show price`,default:!0}},qm={trendLine:{kind:`boolean`,label:`Trend line`,default:!0},oneColor:{kind:`boolean`,label:`Use one color`,default:!1}},Jm={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`}]}};function Ym(e,t){let n=e.textBackground??t.box,r=e.textBorder??t.border,i=!t.fill&&!e.fillColor?void 0:P(e);return{fontSize:En(e),color:e.textColor??N(e.color),fill:n&&i?i:void 0,stroke:r?e.borderColor??e.color:void 0,maxWidth:e.textWrap===void 0?t.width:e.textWrap>0?e.textWrap:1/0,bold:e.bold,italic:e.italic,align:e.textAlign}}var Xm=1.3,Zm=12,Qm=3;function $m(e,t=!1,n=!1,r=!0){let i=j();return`${n?`italic `:``}${t?`bold `:``}${e}px ${r?i.prose:i.figures}`}function eh(e,t,n,r=Zm){let i=[];for(let a of t.split(`
|
|
2
|
-
`)){let t=``;for(let r of a.split(/\s+/).filter(Boolean)){let a=t?`${t} ${r}`:r;if(e(a)<=n){t=a;continue}t&&i.push(t),t=e(r)<=n?r:
|
|
3
|
-
`).slice(0,_h):[]}function wh(e,t){let n=En(t);return e.font=$m(n,t.bold,t.italic),e.fillStyle=t.textColor??t.color,n*gh}function Th(e,t,n,r,i){let a=Ch(t);if(a.length===0)return null;let o=i?bh(n,r,i):[n,r];if(!o)return null;let[s,c]=o,[l,u]=Math.abs(c.x-s.x)<vh?s.y>c.y?[s,c]:[c,s]:s.x<c.x?[s,c]:[c,s],d=Math.atan2(u.y-l.y,u.x-l.x),f=t.textAlign??`center`,p=f===`left`?l:f===`right`?u:{x:(l.x+u.x)/2,y:(l.y+u.y)/2},m=f===`left`?hh:f===`right`?-hh:0;e.save();let h=wh(e,t);e.translate(p.x,p.y),e.rotate(d),e.textAlign=f;let g=t.textVAlign??`top`;e.textBaseline=g===`top`?`bottom`:g===`bottom`?`top`:`middle`;let _=0;a.forEach((t,n)=>{_=Math.max(_,e.measureText(t).width);let r=g===`top`?-mh-(a.length-1-n)*h:g===`bottom`?mh+n*h:(n-(a.length-1)/2)*h;if(F(e,t,m,r),Math.abs(d)<yh){let n=e.measureText(t).width,i=p.x+m-(f===`left`?0:f===`right`?n:n/2),a=p.y+r-(g===`top`?h:g===`bottom`?0:h/2);Qn(i,a,i+n,a+h)}}),e.restore();let v=a.length*h;return{x:p.x,y:p.y,angle:d,left:m-(f===`left`?0:f===`right`?_:_/2),top:g===`top`?-mh-v:g===`bottom`?mh:-v/2,width:_,height:v}}function Eh(e,t,n){let r=Ch(t);if(r.length===0)return null;e.save();let i=wh(e,t),a=t.textAlign??`center`,o=a===`left`?n.x+8:a===`right`?n.x+n.width-8:n.x+n.width/2,s=t.textVAlign??`top`,c=r.length*i,l=s===`top`?n.y+6:s===`bottom`?n.y+n.height-6-c:n.y+(n.height-c)/2;e.textAlign=a,e.textBaseline=`top`;let u=0;return r.forEach((t,n)=>{u=Math.max(u,e.measureText(t).width),F(e,t,o,l+n*i)}),e.restore(),{x:0,y:0,angle:0,left:a===`left`?o:a===`right`?o-u:o-u/2,top:l,width:u,height:c}}var Dh=28,Oh=48;function kh(e,t){return Math.atan2(e.y-t.y,t.x-e.x)*180/Math.PI}var Ah=class extends J{descriptor={type:`trendAngle`,name:`Trend Angle`,requiredAnchors:2,text:!0};render(e,t,n,r){if(this.texts.set(t.id,null),t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=kh(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),this.applyGuideStyle(e,t.style.color,!0),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x+s*Oh,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,Dh,Math.min(l,c),Math.max(l,c)),e.stroke(),e.globalAlpha=1,e.font=M(`label`),e.fillStyle=N(t.style.color),e.textAlign=s>0?`left`:`right`,e.textBaseline=`middle`,F(e,`${o.toFixed(1)}°`,i.x+s*(Dh+6),i.y+(o>=0?-8:8)),this.texts.set(t.id,Th(e,t.style,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n),n.chartRect)),r&&this.renderAnchorHandles(e,t,n)}texts=new Sh;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},jh=3.5,Mh=1.5,Nh=8,Ph=[{value:`normal`,label:`Normal`},{value:`arrow`,label:`Arrow`}],Fh={leftEnd:{kind:`choice`,label:`Left end`,default:`normal`,choices:Ph},rightEnd:{kind:`choice`,label:`Right end`,default:`normal`,choices:Ph}},Ih={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 Lh(e,t,n,r,i=1){let a=Dn(i),o=Math.atan2(n.y-t.y,n.x-t.x);e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-a*Math.cos(o-Math.PI/6),n.y-a*Math.sin(o-Math.PI/6)),e.lineTo(n.x-a*Math.cos(o+Math.PI/6),n.y-a*Math.sin(o+Math.PI/6)),e.closePath(),e.fillStyle=r,e.fill()}var Rh=1.5;function zh(e,t,n,r,i=1){Math.hypot(n.x-t.x,n.y-t.y)<Dn(i)*Rh||Lh(e,t,n,r,i)}function Bh(e,t,n,r){let[i,a]=t;i.x===a.x&&i.y===a.y||(r(`leftEnd`)===`arrow`&&Lh(e,a,i,n,Number(e.lineWidth)||1),r(`rightEnd`)===`arrow`&&Lh(e,i,a,n,Number(e.lineWidth)||1))}function Vh(e,t,n,r,i){let a=[];i(`showPriceRange`)&&a.push(Er(e.anchors[0].price,e.anchors[1].price,t)),i(`showBarsRange`)&&a.push(`${kr(e,0,1,t)} bars`);let o=i(`showDateRange`)?Ar(e,0,1,t):null;return o&&a.push(o),i(`showAngle`)&&a.push(`${kh(n,r).toFixed(1)}°`),a}function Hh(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,Math.max(jh,Nn(t.style.lineWidth)-1),0,Math.PI*2),e.fillStyle=Un(),e.fill(),e.strokeStyle=t.style.color,e.lineWidth=Mh,e.setLineDash([]),e.stroke()),!a&&!o(`alwaysShowStats`))return;let c=Vh(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`){jr(e,c,s.x,s.y-Nh,`center`,!0);return}let[f,p]=d===`left`?[l,u]:[u,l],m=f.y<=p.y;jr(e,c,d===`left`?f.x-Nh:f.x+Nh,f.y+(m?-Nh:Nh),d===`left`?`right`:`left`,m)}var Uh=class extends J{descriptor={type:`trendLine`,name:`Trend Line`,requiredAnchors:2,text:!0,options:{...Gm(),...Fh,...Ih}};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(this.texts.set(t.id,null),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);Bh(e,[i,a],t.style.color,o),Hh(e,t,n,[this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n)],r,o),this.texts.set(t.id,Th(e,t.style,i,a,n.chartRect)),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`),Np(n));return r===null?null:[r]}texts=new Sh;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},Wh=class extends J{descriptor={type:`horizontalLine`,name:`Horizontal Line`,requiredAnchors:1,text:!0,options:Km,axisSpan:`price`};priceAt(e){return e.anchors.length<1?null:[e.anchors[0].price]}render(t,n,r,i){if(this.texts.set(n.id,null),n.anchors.length<1)return;let a=e.O(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),this.texts.set(n.id,Th(t,n.style,{x:o.x,y:a},{x:o.x+o.width,y:a})),this.option(n,`showPrice`)&&(t.fillStyle=N(n.style.color),ar(t,wr(n.anchors[0].price,n.anchors[0].price,r),o.x,a,o.x+o.width,o.y)),i&&this.renderAnchorHandles(t,n,r)}texts=new Sh;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(t,n,r,i){if(n.anchors.length<1)return!1;let a=e.O(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}},Gh=class extends J{descriptor={type:`horizontalRay`,name:`Horizontal Ray`,requiredAnchors:1,text:!0,options:Km,axisSpan:`price`};priceAt(e,t){return e.anchors.length<1||t<e.anchors[0].time?null:[e.anchors[0].price]}render(e,t,n,r){if(this.texts.set(t.id,null),t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=i.y,{chartRect:o}=n;if(this.applyLineStyle(e,t.style),this.strokeHorizontal(e,i.x,o.x+o.width,a),this.resetLineStyle(e),this.texts.set(t.id,Th(e,t.style,i,{x:o.x+o.width,y:a},o)),this.option(t,`showPrice`)){e.fillStyle=N(t.style.color);let r=i.x+Nn(t.style.lineWidth);ar(e,wr(t.anchors[0].price,t.anchors[0].price,n),r,a,o.x+o.width,o.y)}r&&this.renderAnchorHandles(e,t,n)}texts=new Sh;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},Kh=4,qh=class extends J{descriptor={type:`verticalLine`,name:`Vertical Line`,requiredAnchors:1,text:!0,axisSpan:`time`,options:{showTime:{kind:`boolean`,label:`Show time`,default:!1}}};render(e,t,n,r){if(this.texts.set(t.id,null),t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),{chartRect:a}=n,o=a.y+a.height;this.applyLineStyle(e,t.style),this.strokeVertical(e,i.x,a.y,o),this.resetLineStyle(e);let s=this.option(t,`showTime`)?this.timeText(t,n):null,c=s?o-Kh*2-sr():o;if(this.texts.set(t.id,Th(e,t.style,{x:i.x,y:c},{x:i.x,y:a.y})),s){e.font=M(`label`);let n=e.measureText(s).width+12;fr(e,s,i.x-n/2,o-Kh-sr()/2,t.style.color)}r&&this.renderAnchorHandles(e,t,n)}timeText(e,t){if(!t.formatTime)return null;try{return t.formatTime(e.anchors[0].time)}catch{return null}}texts=new Sh;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},Jh=class extends J{descriptor={type:`ray`,name:`Ray`,requiredAnchors:2,text:!0,options:Ih};render(e,t,n,r){if(this.texts.set(t.id,null),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),Hh(e,t,n,[i,a],r,this.optionsOf(t)),this.texts.set(t.id,Th(e,t.style,i,{x:d,y:f},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,!1,!0,Np(n));return r===null?null:[r]}texts=new Sh;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},Yh=class extends J{descriptor={type:`extendedLine`,name:`Extended Line`,requiredAnchors:2,text:!0,options:Ih};render(e,t,n,r){if(this.texts.set(t.id,null),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),Hh(e,t,n,[i,a],r,this.optionsOf(t)),this.texts.set(t.id,Th(e,t.style,{x:d,y:f},{x:p,y:m},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,!0,!0,Np(n));return r===null?null:[r]}texts=new Sh;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},Xh=.7,Zh=.5,Qh=class extends J{descriptor={type:`parallelChannel`,name:`Parallel Channel`,requiredAnchors:3,fill:!0,options:{...Gm(),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=Math.abs(c)<Zh,u=l?s.y:n.y+(s.x-n.x)*(r.y-n.y)/c,d=l?{x:s.x-n.x,y:0}:{x:0,y:s.y-u},f=(e,t)=>({x:e.x+d.x*t,y:e.y+d.y*t}),p=f(n,1),m=f(r,1);return{base:o,parallel:this.extendLine(p,m,t,i,a),middle:this.option(e,`middleLine`)?this.extendLine(f(n,.5),f(r,.5),t,i,a):null,corners:[n,r,m,p]}}handlePoints(e,t){let n=super.handlePoints(e,t),{corners:r}=this.lines(e,t);if(!r||n.length<3)return n;let[,,i,a]=r;return[n[0],n[1],{x:(a.x+i.x)/2,y:(a.y+i.y)/2}]}render(e,t,n,r){if(t.anchors.length<2)return;let{base:i,parallel:a,middle:o,corners:s}=this.lines(t,n);if(s&&t.style.fillColor){e.fillStyle=P(t.style),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.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());o&&(e.setLineDash(Ln(`dashed`,t.style.lineWidth)),e.lineCap=`butt`,e.globalAlpha=Xh,e.beginPath(),e.moveTo(o[0].x,o[0].y),e.lineTo(o[1].x,o[1].y),e.stroke(),e.globalAlpha=1),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=Np(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)}},$h=2,eg=.8,tg=64;function ng(e,t,n){let r=Math.max(0,Math.round(Math.min(t,n))),i=Math.min(e.length-1,Math.round(Math.max(t,n))),a=i-r+1;if(a<2)return null;let o=0,s=0,c=0,l=0;for(let t=r;t<=i;t++){let n=e[t].close;o+=t,s+=n,c+=t*t,l+=t*n}let u=a*c-o*o;if(u===0)return null;let d=(a*l-o*s)/u,f=(s-d*o)/a,p=e=>f+d*e,m=0;for(let t=r;t<=i;t++)m+=(e[t].close-p(t))**2;return{from:r,to:i,slope:d,intercept:f,deviation:Math.sqrt(m/a),at:p}}var rg=class extends J{descriptor={type:`regressionChannel`,name:`Regression Channel`,requiredAnchors:2,fill:!0};dataGetter=null;dataRevision=()=>0;fits=new Map;fitsFor={data:null,length:0,revision:-1};setDataGetter(e,t=()=>0){this.dataGetter=e,this.dataRevision=t,this.fits.clear()}fit(t,n){let r=this.dataGetter?.();if(!r||r.length<2||t.anchors.length<2)return null;let i=this.dataRevision(),a=this.fitsFor;(a.data!==r||a.length!==r.length||a.revision!==i)&&(this.fits.clear(),this.fitsFor={data:r,length:r.length,revision:i});let o=Math.round(e.A(t.anchors[0].time,n)),s=Math.round(e.A(t.anchors[1].time,n)),c=`${o}:${s}`,l=this.fits.get(c);return l===void 0&&(this.fits.size>=tg&&this.fits.clear(),l=ng(r,o,s),this.fits.set(c,l)),l}lines(t,n){let r=this.fit(t,n);if(!r)return{middle:[this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n)],upper:null,lower:null};let i=t=>[{x:e.C(r.from,n),y:e.O(r.at(r.from)+t,n)},{x:e.C(r.to,n),y:e.O(r.at(r.to)+t,n)}],a=r.deviation*$h;return{middle:i(0),upper:i(a),lower:i(-a)}}handlePoints(t,n){let r=this.fit(t,n);return r?t.anchors.map(t=>{let i=Math.max(r.from,Math.min(r.to,Math.round(e.A(t.time,n))));return{x:e.C(i,n),y:e.O(r.at(i),n)}}):super.handlePoints(t,n)}render(e,t,n,r){if(t.anchors.length<2)return;let{middle:i,upper:a,lower:o}=this.lines(t,n);a&&o&&t.style.fillColor&&(e.fillStyle=P(t.style),e.beginPath(),e.moveTo(a[0].x,a[0].y),e.lineTo(a[1].x,a[1].y),e.lineTo(o[1].x,o[1].y),e.lineTo(o[0].x,o[0].y),e.closePath(),e.fill()),this.applyLineStyle(e,t.style);for(let t of[a,o])t&&(e.beginPath(),e.moveTo(t[0].x,t[0].y),e.lineTo(t[1].x,t[1].y),e.stroke());a&&(e.setLineDash(Ln(`dashed`,t.style.lineWidth)),e.lineCap=`butt`,e.globalAlpha=eg),e.beginPath(),e.moveTo(i[0].x,i[0].y),e.lineTo(i[1].x,i[1].y),e.stroke(),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{middle:i,upper:a,lower:o}=this.lines(t,n);return[i,a,o].some(t=>t!==null&&this.distanceToLine(e,t[0],t[1])<=r)}},ig=1,ag=.06,og=3,sg=.8;function cg(e,n,r,i,a=e=>e.toFixed(2),o=`en-US`){let s=e*100,c=`${(0,t.formatPrice)(s,Math.abs(s-Math.round(s))<1e-9?0:ig,o)}%`,l=a(n);return r&&i?`${c} (${l})`:r?c:i?l:``}function lg(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.O(o[i].price,r),l=e.O(o[i+1].price,r);t.fillStyle=o[i+1].level.color??P(n.style,1),t.globalAlpha=ag,t.fillRect(a.x0,Math.min(c,l),s,Math.abs(l-c))}t.globalAlpha=1}t.font=M(`label`),t.textBaseline=`bottom`,t.textAlign=a.labelPosition===`right`?`right`:`left`;let c=a.labelPosition===`right`?a.x1-4:a.x0+4,l=j().sizes.label,u=[],d=e=>e===0||e===1,f=i.map(({level:t,price:n})=>({level:t,price:n,y:e.O(n,r)}));for(let{level:r,y:i}of f){o(r.color??n.style.color),t.globalAlpha=d(r.value)?1:sg;let s=e.v(t,i,Number(t.lineWidth)||1);t.lineWidth=s.width,t.beginPath(),t.moveTo(a.x0,s.y),t.lineTo(a.x1,s.y),t.stroke()}t.globalAlpha=1;let p=[...f].sort((e,t)=>Number(d(t.level.value))-Number(d(e.level.value)));for(let{level:e,price:i,y:o}of p){let s=cg(e.value,i,a.showLevels,a.showPrices,e=>wr(e,e,r),r.numberLocale);if(!s)continue;let f=t.measureText(s).width,p=a.labelPosition===`right`?c-f:c,m={left:p,right:p+f,top:o-og-l,bottom:o-og},h={left:p,right:p+f,top:o+og,bottom:o+og+l},g=nr(p,p+f,o+og)+og,_={left:p,right:p+f,top:g,bottom:g+l},v=Nr([m,h,_],u)??(d(e.value)?_:null);v&&(u.push(v),t.fillStyle=N(e.color??n.style.color),t.textBaseline=`top`,F(t,s,c,v.top))}t.globalAlpha=1}var ug=[5,4],dg=.8;function fg(e,t,n){t.length<2||(e.save(),e.strokeStyle=n,e.lineWidth=1,e.globalAlpha=dg,e.setLineDash(ug),e.beginPath(),t.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.stroke(),e.restore())}function pg(e){return e.map(({level:e,price:t})=>({level:{...e,color:void 0},price:t}))}function mg(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.O(r,n))<=o)}var hg=Um([0,.236,.382,.5,.618,.786,1],[1.272,1.414,1.618,2.618,3.618,4.236]),gg=class extends J{descriptor={type:`fibRetracement`,name:`Fibonacci Retracement`,requiredAnchors:2,fill:!0,options:{levels:{kind:`levels`,label:`Levels`,default:hg},...Gm(!0,!0),reverse:{kind:`boolean`,label:`Reverse`,default:!1},...Jm,...qm,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);this.option(t,`trendLine`)&&fg(e,t.anchors.slice(0,2).map(e=>this.anchorToPixel(e,n)),t.style.color),lg(e,t,n,this.option(t,`oneColor`)?pg(this.levels(t)):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 mg(e,n,this.levels(t),i,a,r)}},_g=Um([0,.618,1,1.618,2,2.618,3.618,4.236],[.382,.5,.786,1.272,1.414]),vg=class extends J{descriptor={type:`fibExtension`,name:`Fibonacci Extension`,requiredAnchors:3,fill:!0,options:{levels:{kind:`levels`,label:`Levels`,default:_g},...Gm(!0,!0),...Jm,...qm,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);this.option(t,`trendLine`)&&fg(e,t.anchors.slice(0,3).map(e=>this.anchorToPixel(e,n)),t.style.color),lg(e,t,n,this.option(t,`oneColor`)?pg(this.levels(t)):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 mg(e,n,this.levels(t),i,a,r)}},yg=new Set([4,5,6,7]),bg=class extends J{descriptor={type:`rectangle`,name:`Rectangle`,requiredAnchors:2,fill:!0,text:!0};render(e,t,n,r){if(this.texts.set(t.id,null),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=P(t.style),e.fillRect(o,s,c,l)),this.applyLineStyle(e,t.style),e.strokeRect(o,s,c,l),this.resetLineStyle(e),this.texts.set(t.id,Eh(e,t.style,{x:o,y:s,width:c,height:l})),r&&this.renderBoxHandles(e,t,n)}handlePoints(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i={x:(n.x+r.x)/2,y:(n.y+r.y)/2};return[n,r,{x:n.x,y:r.y},{x:r.x,y:n.y},{x:i.x,y:n.y},{x:i.x,y:r.y},{x:n.x,y:i.y},{x:r.x,y:i.y}]}renderBoxHandles(e,t,n){Cp(e,t,this.handlePoints(t,n),{sides:yg})}hitTestAnchor(e,t,n,r){if(t.anchors.length<2)return super.hitTestAnchor(e,t,n,r);let i=-1,a=r;return this.handlePoints(t,n).forEach((t,n)=>{let o=Math.hypot(e.x-t.x,e.y-t.y);(o<a||i<0&&o<=r)&&(i=n,a=o)}),i}moveHandle(e,t,n){let[r,i]=e.anchors,a={0:[n,i],1:[r,n],2:[{time:n.time,price:r.price},{time:i.time,price:n.price}],3:[{time:r.time,price:n.price},{time:n.time,price:i.price}],4:[{time:r.time,price:n.price},i],5:[r,{time:i.time,price:n.price}],6:[{time:n.time,price:r.price},i],7:[r,{time:n.time,price:i.price}]};return a[t]?{...e,anchors:a[t]}:e}texts=new Sh;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},xg=class extends J{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=P(t.style),e.fill()),this.applyLineStyle(e,t.style),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}handlePoints(e,t){if(e.anchors.length<2)return super.handlePoints(e,t);let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i={x:(n.x+r.x)/2,y:(n.y+r.y)/2};return[{x:i.x,y:n.y},{x:i.x,y:r.y},{x:n.x,y:i.y},{x:r.x,y:i.y}]}moveHandle(e,t,n){let[r,i]=e.anchors,a={0:[{time:r.time,price:n.price},i],1:[r,{time:i.time,price:n.price}],2:[{time:n.time,price:r.price},i],3:[r,{time:n.time,price:i.price}]};return a[t]?{...e,anchors:a[t]}:e}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}},Sg=class extends J{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=P(t.style),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}};function Cg(e,t,n){let r=1/0;return t.x>0&&(r=Math.min(r,(n.x+n.width-e.x)/t.x)),t.x<0&&(r=Math.min(r,(n.x-e.x)/t.x)),t.y>0&&(r=Math.min(r,(n.y+n.height-e.y)/t.y)),t.y<0&&(r=Math.min(r,(n.y-e.y)/t.y)),Number.isFinite(r)?Math.max(0,r):0}function wg(e,t,n){return{x:e.x+t.x*n,y:e.y+t.y*n}}function Tg(e,t){let{origin:n,b:r,c:i,dir:a}=e,o=[n,r,i].map(e=>[e,wg(e,a,Cg(e,a,t))]);return[[r,i],...o]}var Eg=class extends J{descriptor={type:`pitchfork`,name:`Andrews' Pitchfork`,requiredAnchors:3,fill:!0};origin(e,t){return e}fork(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i=this.anchorToPixel(e.anchors[2],t),a=this.origin(n,r),o={x:(r.x+i.x)/2,y:(r.y+i.y)/2},s=o.x-a.x,c=o.y-a.y,l=Math.hypot(s,c)||1;return{pivot:n,origin:a,b:r,c:i,dir:{x:s/l,y:c/l}}}render(e,t,n,r){if(t.anchors.length<3){t.anchors.length===2&&this.renderFirstLeg(e,t,n);return}let i=this.fork(t,n),a=n.chartRect;this.fillTines(e,t,i,a),this.renderOriginGuide(e,t,i),this.applyLineStyle(e,t.style);for(let[t,n]of Tg(i,a))this.strokeSegment(e,t,n);this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}renderFirstLeg(e,t,n){let r=this.anchorToPixel(t.anchors[0],n),i=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),this.strokeSegment(e,r,i),this.resetLineStyle(e)}fillTines(e,t,n,r){let{b:i,c:a,dir:o}=n,s=Math.max(Cg(i,o,r),Cg(a,o,r));if(s<=0)return;e.save(),e.beginPath(),e.rect(r.x,r.y,r.width,r.height),e.clip(),e.fillStyle=P(t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y);let c=wg(a,o,s),l=wg(i,o,s);e.lineTo(c.x,c.y),e.lineTo(l.x,l.y),e.closePath(),e.fill(),e.restore()}renderOriginGuide(e,t,n){let{pivot:r,origin:i}=n;r.x===i.x&&r.y===i.y||(this.applyGuideStyle(e,t.style.color,!0),this.strokeSegment(e,r,i),e.globalAlpha=1,e.setLineDash([]))}strokeSegment(e,t,n){e.beginPath(),e.moveTo(t.x,t.y),e.lineTo(n.x,n.y),e.stroke()}hitTest(e,t,n,r){return t.anchors.length<3?!1:Tg(this.fork(t,n),n.chartRect).some(([t,n])=>this.distanceToLine(e,t,n)<=r)}},Dg=class extends Eg{descriptor={type:`schiffPitchfork`,name:`Schiff Pitchfork`,requiredAnchors:3,fill:!0};origin(e,t){return{x:e.x,y:(e.y+t.y)/2}}},Og=class extends Eg{descriptor={type:`modifiedSchiffPitchfork`,name:`Modified Schiff Pitchfork`,requiredAnchors:3,fill:!0};origin(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}},kg=5,Ag=3,jg=1.25,Mg=1.5,Ng=[.5,.38,.62,.26,.74,.15,.85],Pg=8,Fg=3;function Ig(e,t){let n=e[t-1],r=e[t+1],i=e[t];return!n&&!r?`above`:!n||!r?i.y<=(n??r).y?`above`:`below`:i.y<=(n.y+r.y)/2?`above`:`below`}function Lg(e){return Nn(e)+kg}function Rg(e,t,n,r,i){let a=t===`above`?e.y-i-r:e.y+i;return{left:e.x-n/2,right:e.x+n/2,top:a,bottom:a+r}}function zg(e,t,n,r,i){let a=Ig(e,t),o=Rg(e[t],a,n,r,i);return wn(o.left,o.top,n,r).top===o.top?o:Rg(e[t],a===`above`?`below`:`above`,n,r,i)}function Bg(e,t){return e.left<t.right&&t.left<e.right&&e.top<t.bottom&&t.top<e.bottom}function Vg(e,t,n,r){let i=e.measureText(t).width;if(!n)return{width:i,height:r};let a=2*Hg(i,r);return{width:a,height:a}}function Hg(e,t){return Math.max(e,t)/2+Ag}function Ug(e,t,n,r,i){let a=a=>n.slice(0,t.length).map((n,o)=>{let s=a&&n.short?n.short:n.text,c=Vg(e,s,!!n.ring,r);return{text:s,ring:!!n.ring,first:!!n.first,box:zg(t,o,c.width,c.height,i)}}).filter(e=>e.text),o=a(!1),s=o.some((e,t)=>o.slice(t+1).some(t=>Bg(e.box,t.box)))?a(!0):o,c=[...s.filter(e=>e.first),...s.filter(e=>!e.first)],l=[];for(let e of c)l.every(t=>!Bg(t.box,e.box))&&l.push(e);return s.filter(e=>l.includes(e))}function Wg(e,t,n,r,i){let a=Ug(e,n,r,i,Lg(t.style.lineWidth)),o=N(t.style.color);e.textAlign=`center`,e.textBaseline=`middle`;for(let n of a){let r=(n.box.left+n.box.right)/2,i=(n.box.top+n.box.bottom)/2;n.ring&&Gg(e,r,i,(n.box.right-n.box.left)/2,t.style.color),e.fillStyle=o,F(e,n.text,r,i),Kg(n.box)}return a.map(e=>e.box)}function Gg(e,t,n,r,i){e.save(),e.beginPath(),e.arc(t,n,r,0,Math.PI*2),e.fillStyle=j().background,e.fill(),e.strokeStyle=i,e.lineWidth=jg,e.setLineDash([]),e.stroke(),e.restore()}function Kg(e){yn(e.left,e.top,e.right-e.left,e.bottom-e.top),Qn(e.left,e.top,e.right,e.bottom)}function qg(e,t){let n=Nn(t)+Mg;return e.map(e=>({left:e.x-n,right:e.x+n,top:e.y-n,bottom:e.y+n}))}function Jg(e,t,n,r,i){e.font=M(`mark`);let a=e.measureText(t).width,o=j().sizes.mark,s=o+Fg,c=[0,s,-s].flatMap(e=>Ng.map(t=>{let i=n.x+(r.x-n.x)*t,s=n.y+(r.y-n.y)*t+e;return{left:i-a/2,right:i+a/2,top:s-o/2,bottom:s+o/2}})),l=c.map(e=>({...e,left:e.left-Pg,right:e.right+Pg})),u=Nr(l,i);if(!u)return null;let d=c[l.indexOf(u)];return e.textAlign=`center`,e.textBaseline=`middle`,F(e,t,(d.left+d.right)/2,(d.top+d.bottom)/2),Kg(d),d}var Yg=[`0`,`i`,`ii`,`iii`,`iv`,`v`];function Xg(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?Yg[Number(e)]??e:e.toLowerCase();default:return e}}function Zg(e,t){return t===`primary`?{text:e,ring:!0}:{text:Xg(e,t)}}var Qg={degree:{kind:`choice`,label:`Degree`,default:`minor`,choices:[{value:`primary`,label:`Primary`},{value:`intermediate`,label:`Intermediate`},{value:`minor`,label:`Minor`},{value:`minute`,label:`Minute`}]}},$g=class extends J{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=M(`letter`,{weight:600}),Wg(e,t,i,this.labels.map(e=>Zg(e,a)),j().sizes.letter),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:Fp(e,t.anchors.map(e=>this.anchorToPixel(e,n)),r)}},e_=class extends $g{descriptor={type:`elliottWave`,name:`Elliott Wave`,requiredAnchors:8,options:Qg};labels=[`1`,`2`,`3`,`4`,`5`,`A`,`B`,`C`]},t_=class extends $g{descriptor={type:`elliottImpulse`,name:`Elliott Impulse Wave`,requiredAnchors:6,options:Qg};labels=[`0`,`1`,`2`,`3`,`4`,`5`]},n_=class extends $g{descriptor={type:`elliottCorrection`,name:`Elliott Correction Wave`,requiredAnchors:4,options:Qg};labels=[`0`,`A`,`B`,`C`]},r_=class extends $g{descriptor={type:`elliottTriangle`,name:`Elliott Triangle Wave`,requiredAnchors:6,options:Qg};labels=[`0`,`A`,`B`,`C`,`D`,`E`]},i_=class extends $g{descriptor={type:`elliottDoubleCombo`,name:`Elliott Double Combo Wave`,requiredAnchors:4,options:Qg};labels=[`0`,`W`,`X`,`Y`]},a_=class extends $g{descriptor={type:`elliottTripleCombo`,name:`Elliott Triple Combo Wave`,requiredAnchors:6,options:Qg};labels=[`0`,`W`,`X`,`Y`,`X`,`Z`]},o_=.6,s_=6,c_=class extends J{descriptor={type:`priceRange`,name:`Price Range`,requiredAnchors:2};render(e,n,r,i){if(n.anchors.length<2)return;let a=this.anchorToPixel(n.anchors[0],r),o=this.anchorToPixel(n.anchors[1],r),s=Math.min(a.x,o.x),c=Math.abs(o.x-a.x),l=Math.min(a.y,o.y),u=Math.abs(o.y-a.y),d=j(),f=n.anchors[1].price>=n.anchors[0].price,p=n.style.color.toLowerCase()===t.DEFAULT_DRAWING_STYLE.color?f?d.rise:d.fall:n.style.color;e.fillStyle=(0,t.withAlpha)(p,ln),e.fillRect(s,l,c,u),e.save(),this.applyGuideStyle(e,p),e.globalAlpha=o_,this.strokeCrispRect(e,s,l,c,u),e.restore();let m=s+c/2;this.applyLineStyle(e,{...n.style,color:p}),e.beginPath(),e.moveTo(m,a.y),e.lineTo(m,o.y),e.stroke(),this.resetLineStyle(e),zh(e,{x:m,y:a.y},{x:m,y:o.y},p,n.style.lineWidth),e.font=M(`label`);let h=Er(n.anchors[0].price,n.anchors[1].price,r),g=dr(e,h),_=sr(),v=f?l-s_-_:l+u+s_,y=wn(m-g/2,v,g,_);fr(e,h,y.left,y.top+_/2,p),i&&this.renderAnchorHandles(e,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),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}},l_=.08,u_=6,d_=class extends J{descriptor={type:`dateRange`,name:`Date Range`,requiredAnchors:2};handlePoints(e,t){return this.timeHandles(e,t)}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=Math.min(i.x,a.x),c=Math.max(i.x,a.x),l=o.y,u=o.y+o.height;e.fillStyle=P(t.style,l_),e.fillRect(s,l,c-s,u-l),this.applyLineStyle(e,t.style),this.strokeVertical(e,s,l,u),e.lineWidth=t.style.lineWidth,this.strokeVertical(e,c,l,u);let d=l+(u-l)/2;e.lineWidth=t.style.lineWidth,e.beginPath(),e.moveTo(i.x,d),e.lineTo(a.x,d),e.stroke(),this.resetLineStyle(e),zh(e,{x:i.x,y:d},{x:a.x,y:d},t.style.color,t.style.lineWidth);let f=kr(t,0,1,n),p=Ar(t,0,1,n),m=p?`${f} bars · ${p}`:`${f} bars`;e.font=M(`label`);let h=dr(e,m),g=sr(),_=wn((s+c)/2-h/2,d-u_-g,h,g);fr(e,m,_.left,_.top+g/2,t.style.color),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),{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}},f_=class extends J{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.lineCap=`butt`,t.setLineDash(Ln(`dashed`,n.style.lineWidth)),t.beginPath(),t.moveTo(a.x,a.y),t.lineTo(o.x,o.y),t.stroke(),this.resetLineStyle(t);let s=e.A(n.anchors[0].time,r),c=e.A(n.anchors[1].time,r),l=Math.max(0,Math.round(Math.abs(c-s))),u=[Er(n.anchors[0].price,n.anchors[1].price,r),`${l} bars`];t.font=M(`label`),t.textAlign=`center`,t.textBaseline=`bottom`;let d=Math.max(...u.map(e=>t.measureText(e).width)),f=g_((a.x+o.x)/2,(a.y+o.y)/2,d,u.length,r);Mr(t,f.x,f.y,f.width,f.height),t.fillStyle=j().ink;let p=f.x+f.width/2,m=f.y+f.height-h_;for(let e=0;e<u.length;e++)t.fillText(u[e],p,m-(u.length-1-e)*p_);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}},p_=14,m_=6,h_=4;function g_(e,t,n,r,i){let{chartRect:a}=i,o=n+2*m_,s=r*p_+2*h_,c=__(e-o/2,a.x,a.x+a.width-o),l=__(t-s+h_,a.y,a.y+a.height-s);if(!er(c,l,c+o,l+s))return{x:c,y:l,width:o,height:s};let u=nr(c,c+o,l);return{x:c,y:u+s<=a.y+a.height?u:l,width:o,height:s}}function __(e,t,n){return Math.max(t,Math.min(e,n))}var v_=500;function y_(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 b_=class extends J{descriptor={type:`text`,name:`Text`,requiredAnchors:1,text:!0,fill:!0};boxes=new ph;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a={...Ym(t.style,{box:!1,border:!1,width:1/0}),maxLines:v_},o=sh(e,y_(t),i.x-8,i.y-6,a);this.boxes.set(t.id,o),lh(e,o,t.style.color,r)}handlePoints(){return[]}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n);return dh(e,this.boxes.get(t.id)??x_(t,i),r)}textBox(e){return this.boxes.get(e.id)??null}};function x_(e,t){let n=En(e.style),r=y_(e).split(`
|
|
4
|
-
`),i=Math.max(...r.map(e=>e.length));return{x:t.x-8,y:t.y-6,width:i*n*.6+16,height:r.length*n*1.3+12}}var S_=class extends J{descriptor={type:`arrow`,name:`Arrow`,requiredAnchors:2,text:!0};render(e,t,n,r){if(this.texts.set(t.id,null),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(),Lh(e,i,a,t.style.color,t.style.lineWidth),this.resetLineStyle(e),this.texts.set(t.id,Th(e,t.style,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n),n.chartRect)),r&&this.renderAnchorHandles(e,t,n)}texts=new Sh;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},C_=[{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}],w_=4,T_=class extends J{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,f=u.y,p=u.y+u.height;e.font=M(`mark`);for(let{label:n,ratio:r}of C_){let a=c*r,o=d,s=i.y+a*(o-i.x);e.globalAlpha=1,r===1?this.applyLineStyle(e,t.style):this.applyGuideStyle(e,t.style.color),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(o,s),e.stroke();let m=Math.max(f,Math.min(p,s)),h=a===0||m===s?o:i.x+(m-i.y)/a;if(h<u.x||h>u.x+u.width)continue;e.globalAlpha=1,e.fillStyle=N(t.style.color);let g=m===s;e.textAlign=g?l>0?`right`:`left`:`center`,e.textBaseline=m<=f+1?`top`:`bottom`;let _=g?h-l*w_:h,v=e.measureText(n).width,y=e.textAlign===`right`?_-v:e.textAlign===`left`?_:_-v/2;F(e,n,_,m<=f+1?nr(y,y+v,m)+w_:m-w_)}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 C_){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}},E_=[0,.25,.333,.5,.667,.75,1].filter(e=>e>0&&e<1),D_=.3,O_=4,k_=2,A_=class extends J{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),this.strokeCrispRect(e,o,c,u,d),e.save(),this.applyGuideStyle(e,t.style.color),e.globalAlpha=D_;for(let t of E_)this.strokeHorizontal(e,o,s,c+d*t),e.lineWidth=1,this.strokeVertical(e,o+u*t,c,l),e.lineWidth=1;this.applyGuideStyle(e,t.style.color,!0),e.beginPath(),e.moveTo(o,c),e.lineTo(s,l),e.moveTo(s,c),e.lineTo(o,l),e.stroke(),e.restore(),this.resetLineStyle(e),this.renderLabels(e,t,{left:o,right:s,top:c,bottom:l,w:u,h:d}),r&&this.renderAnchorHandles(e,t,n)}}renderLabels(e,t,n){let r=j().sizes.mark;e.font=M(`mark`),e.fillStyle=N(t.style.color);let i=[...E_].sort((e,t)=>Math.abs(e-.5)-Math.abs(t-.5)),a=[],o=e=>a.every(t=>e.x1+k_<=t.x0||t.x1+k_<=e.x0||e.y1+k_<=t.y0||t.y1+k_<=e.y0);for(let t of i){let i=`${Math.round(t*100)}%`,s=e.measureText(i).width,c=n.top+n.h*t,l={x0:n.left-O_-s,x1:n.left-O_,y0:c-r/2,y1:c+r/2};o(l)&&(a.push(l),e.textAlign=`right`,e.textBaseline=`middle`,F(e,i,l.x1,c));let u=n.left+n.w*t,d={x0:u-s/2,x1:u+s/2,y0:n.bottom+O_,y1:n.bottom+O_+r};o(d)&&(a.push(d),e.textAlign=`center`,e.textBaseline=`top`,F(e,i,u,d.y0))}}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}},j_=6,M_=class extends J{descriptor={type:`anchoredVWAP`,name:`Anchored VWAP`,requiredAnchors:1,priceOnly:!0};dataGetter=null;dataRevision=()=>0;showBands=!0;setDataGetter(e,t=()=>0){this.dataGetter=e,this.dataRevision=t}setShowBands(e){this.showBands=e}handlePoints(t,n){let r=this.dataGetter?.(),i=Math.max(0,Math.round(e.A(t.anchors[0]?.time??0,n)));if(!r||t.anchors.length<1||i>=r.length)return super.handlePoints(t,n);let a=r[i],o=(a.high+a.low+a.close)/3;return[{x:e.C(i,n),y:e.O(o,n)}]}render(t,n,r,i){if(n.anchors.length<1||!this.dataGetter)return;let a=this.dataGetter(),o=Math.max(0,Math.round(e.A(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.C(o+s.length-1,r),c=e.O(i,r);if(a>=f.x&&a<=f.x+f.width){t.fillStyle=n.style.color,t.font=M(`mark`,{weight:600}),t.textBaseline=`middle`;let e=`AVWAP ${wr(i,i,r)}`,o=wn(a+j_,c,t.measureText(e).width,0);t.textAlign=`left`,F(t,e,o.left,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.C(r+c,i);if(l<a.x-o)continue;if(l>a.x+a.width+o)break;let u=e.O(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.dataRevision(),i=this.vwapCache;if(i&&i.data===e&&i.revision===r&&i.length===e.length&&i.startIdx===t&&i.lastClose===n?.close&&i.lastVolume===(n?.volume??0))return i.result;let a=this.computeVWAPUncached(e,t);return this.vwapCache={data:e,revision:r,length:e.length,startIdx:t,lastClose:n?.close,lastVolume:n?.volume??0,result:a},a}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.A(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.C(o+n-1,r),c=e.O(s[n-1],r),l=e.C(o+n,r),u=e.O(s[n],r);if(this.distanceToLine(t,{x:a,y:c},{x:l,y:u})<=i)return!0}return!1}},N_=`#f2a93b`,P_=40,F_=1/3,I_=.7,L_=.45,R_=.2,z_=.5,B_=.5,V_=class extends J{descriptor={type:`volumeProfileRange`,name:`Volume Profile (Range)`,requiredAnchors:2,fill:!0,priceOnly:!0};dataGetter=null;dataRevision=()=>0;cached=null;setDataGetter(e,t=()=>0){this.dataGetter=e,this.dataRevision=t,this.cached=null}profile(t,n){if(t.anchors.length<2||!this.dataGetter)return null;let r=this.dataGetter(),i=Math.round(e.A(t.anchors[0].time,n)),a=Math.round(e.A(t.anchors[1].time,n)),o=Math.max(0,Math.min(i,a)),s=Math.min(r.length-1,Math.max(i,a));if(o>=r.length||s<0||o>s)return null;let c=this.dataRevision(),l=this.cached,u=l&&l.data===r&&l.length===r.length&&l.revision===c&&l.start===o&&l.end===s?l.rows:this.rowsOf(r,o,s);return this.cached={data:r,length:r.length,revision:c,start:o,end:s,rows:u},u?{startX:e.C(o,n),endX:e.C(s,n),left:e.C(o,n)-n.barWidth/2,right:e.C(s,n)+n.barWidth/2,top:e.O(u.pMax,n),bottom:e.O(u.pMin,n),pMin:u.pMin,binSize:u.binSize,bins:u.bins,maxBin:u.maxBin,poc:u.poc,valueLow:u.valueLow,valueHigh:u.valueHigh}:null}rowsOf(e,t,n){let r=1/0,i=-1/0;for(let a=t;a<=n;a++)e[a].low<r&&(r=e[a].low),e[a].high>i&&(i=e[a].high);if(!(r<i))return null;let a=(i-r)/P_,o=new Float64Array(P_);for(let i=t;i<=n;i++){let t=e[i],n=Math.max(0,Math.floor((t.low-r)/a)),s=Math.min(P_-1,Math.floor((t.high-r)/a)),c=(t.volume??1)/(s-n+1);for(let e=n;e<=s;e++)o[e]+=c}let s=0,c=0;for(let e=0;e<P_;e++)c+=o[e],o[e]>o[s]&&(s=e);if(o[s]===0)return null;let l=s,u=s,d=o[s];for(;d<c*I_&&(l>0||u<P_-1);){let e=l>0?o[l-1]:-1;(u<P_-1?o[u+1]:-1)>=e?d+=o[++u]:d+=o[--l]}return{start:t,end:n,pMin:r,pMax:i,binSize:a,bins:o,maxBin:o[s],poc:s,valueLow:l,valueHigh:u}}handlePoints(e,t){let n=this.profile(e,t);if(!n)return super.handlePoints(e,t);let r=e.anchors[0].time<=e.anchors[1].time;return[{x:r?n.startX:n.endX,y:n.top},{x:r?n.endX:n.startX,y:n.bottom}]}render(t,n,r,i){let a=this.profile(n,r);if(!a)return;let o=n.style.color,s=Rn(n.style)?n.style.fillColor:N_,c=Math.max(1,(a.right-a.left)*F_);t.save();for(let n=0;n<P_;n++){let i=e.O(a.pMin+(n+1)*a.binSize,r),l=e.O(a.pMin+n*a.binSize,r);t.globalAlpha=n>=a.valueLow&&n<=a.valueHigh?L_:R_,t.fillStyle=n===a.poc?s:o,t.fillRect(a.left,Math.min(i,l),a.bins[n]/a.maxBin*c,Math.max(1,Math.abs(l-i)-B_))}t.restore(),t.save(),this.applyGuideStyle(t,o),t.globalAlpha=z_,this.strokeCrispRect(t,a.left,a.top,a.right-a.left,a.bottom-a.top),t.restore();let l=a.pMin+(a.poc+.5)*a.binSize,u=e.O(l,r);t.save(),t.strokeStyle=s,t.lineWidth=1,t.setLineDash(Ln(`dashed`,1)),this.strokeHorizontal(t,a.left,a.right,u),t.setLineDash([]),t.fillStyle=N(s),t.font=M(`mark`),t.textAlign=`left`,t.textBaseline=`bottom`;let d=`POC ${wr(l,l,r)}`;F(t,d,wn(a.right+4,u-2,t.measureText(d).width,0).left,u-2),t.restore(),i&&this.renderAnchorHandles(t,n,r)}hitTest(e,t,n,r){let i=this.profile(t,n);return i?e.x>=i.left-r&&e.x<=i.right+r&&e.y>=i.top-r&&e.y<=i.bottom+r:!1}},H_=[1,2,3,5,8,13,21,34,55],U_=.6,W_=4,G_=class extends J{descriptor={type:`fibTimeZones`,name:`Fibonacci Time Zones`,requiredAnchors:2,options:{levels:{kind:`levels`,label:`Levels`,default:Wm([0,...H_],[89,144])}}};handlePoints(e,t){return this.timeHandles(e,t)}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=M(`label`),t.textBaseline=`top`,t.textAlign=`center`;let c=j().sizes.label,l=[];for(let{value:i,color:u}of this.visibleLevels(n)){this.applyLineStyle(t,{...n.style,color:u??n.style.color});let d=e.j(a.time+o*i,r);if(d<s.x||d>s.x+s.width)continue;t.globalAlpha=i===0||i===1?1:U_,this.strokeVertical(t,d,s.y,s.y+s.height),t.globalAlpha=1;let f=String(i),p=t.measureText(f).width/2,m=nr(d-p,d+p,s.y)+W_,h={left:d-p,right:d+p,top:m,bottom:m+c};Nr([h],l)&&(l.push(h),t.fillStyle=N(u??n.style.color),F(t,f,d,m))}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.j(a.time+o*s,r);if(Math.abs(t.x-n)<=i)return!0}return!1}},K_=.14,q_=.6,J_=40,Y_=2,X_=.1,Z_=100,Q_=0x38d7ea4c68000,$_=2,ev=2,tv=4,nv=6,rv=class extends J{descriptor={type:`riskReward`,name:`Long/Short Position`,priceOnly:!0,requiredAnchors:2,options:{rewardRatio:{kind:`number`,label:`Reward:risk`,default:2,min:X_,max:Z_,step:.1},accountSize:{kind:`number`,label:`Account size`,default:1e3,min:0,max:Q_},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:Q_},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),J_),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),d=j();e.fillStyle=(0,t.withAlpha)(d.fall,K_),e.fillRect(o,Math.min(c.y,l.y),s,Math.abs(l.y-c.y)),e.fillStyle=(0,t.withAlpha)(d.rise,K_),e.fillRect(o,Math.min(c.y,u.y),s,Math.abs(u.y-c.y)),e.save();for(let[t,n]of[[l.y,d.fall],[u.y,d.rise]])this.applyGuideStyle(e,n),e.globalAlpha=q_,this.strokeHorizontal(e,o,o+s,t);e.restore(),this.applyLineStyle(e,n.style),e.setLineDash([]),this.strokeHorizontal(e,o,o+s,c.y),this.resetLineStyle(e);let{chartRect:f}=r,p=f.x,m=f.x+f.width;if(this.option(n,`showLabels`)&&o+s>=p&&o<=m){let i=r.pricePrecision??(0,t.autoPricePrecision)(Math.min(a.stop,a.target),Math.max(a.stop,a.target)),s=r.numberLocale??`en-US`,h=this.option(n,`qtyDecimals`),g=e=>a.entry===0?0:(e-a.entry)/a.entry*100,_=a.ratio.toLocaleString(s,{maximumFractionDigits:ev});e.font=M(`label`);let v=e=>(0,t.priceTagText)(e,r,i),y=e=>(0,t.formatPrice)(e,$_,s),b=e=>`${e>=a.entry?`+`:`−`}${Tr(Math.abs(g(e)),r)}%`,x=sr()+2,S=sr()/2,C=e=>{let t=e<c.y,n=e+(t?-1:1)*(S+2),r=t?Math.min(n,c.y-x):Math.max(n,c.y+x);return Math.min(Math.max(r,f.y+S),f.y+f.height-S)},w=({text:t,y:n,start:r})=>{let i=dr(e,t),a=Math.max(p+4,Math.min(Math.max(o+4,r??-1/0),m-4-i)),s=n-S;if(tr(a,s,a+i,s+sr())){let e=(rr(s,s+sr())??a)+tv;e+i<=m-4&&!tr(e,s,e+i,s+sr())?a=e:s=nr(a,a+i,s)+2}return Qn(a,s,a+i,s+sr()),{left:a,top:s}},T=[{text:`${a.isLong?`Long`:`Short`} · Qty ${(0,t.formatPrice)(a.qty,h,s)} · R:R ${_}`,y:c.y,color:n.style.color,start:c.x+Nn(n.style.lineWidth)+nv}];Math.abs(l.y-c.y)>=1&&T.push({text:`Target ${v(a.target)} (${b(a.target)}) · ${y(a.rewardAmount)}`,y:C(u.y),color:d.rise},{text:`Stop ${v(a.stop)} (${b(a.stop)}) · ${y(a.riskAmount)}`,y:C(l.y),color:d.fall});let E=new Map([...T].sort((e,t)=>e.y-t.y).map(e=>[e,w(e)]));for(let t of T){let n=E.get(t);fr(e,t.text,n.left,n.top+S,t.color)}}i&&this.renderHandles(e,n,r)}renderHandles(e,t,n){Cp(e,t,this.handles(t,n))}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!==Y_){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(Z_,Math.max(X_,o/a)):X_;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}},iv=class extends J{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 av(e,t,n){let r=Ar(e,0,1,t),i=kr(e,0,1,t);return[Er(e.anchors[0].price,e.anchors[1].price,t),r?`${i} bars, ${r}`:`${i} bars`,`${n.toFixed(1)}°`]}var ov=class extends J{descriptor={type:`infoLine`,name:`Info Line`,requiredAnchors:2,text:!0};render(e,t,n,r){if(this.texts.set(t.id,null),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=av(t,n,kh(i,a)),s=a.y<=i.y;jr(e,o,a.x+(a.x>=i.x?8:-8),a.y+(s?-6:6),a.x>=i.x?`left`:`right`,s),this.texts.set(t.id,Th(e,t.style,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n),n.chartRect)),r&&this.renderAnchorHandles(e,t,n)}texts=new Sh;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},sv=.7,cv=10,lv=[0,.236,.382,.5,.618,.786,1,1.618];function uv(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 dv(e,t,n,r){let i=uv(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 fv=class extends J{descriptor={type:`fibChannel`,name:`Fibonacci Channel`,requiredAnchors:3,options:{levels:{kind:`levels`,label:`Levels`,default:Um(lv,[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=M(`label`),e.textAlign=`right`,e.textBaseline=`middle`;let s=this.visibleLevels(t);for(let{value:n,color:r}of s){let[s,c]=dv(i,a,o,n);this.applyLineStyle(e,{...t.style,color:r??t.style.color}),e.globalAlpha=n===0||n===1?1:sv,e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(c.x,c.y),e.stroke()}e.globalAlpha=1;let c=j().sizes.label,l=[],u=e=>e===0||e===1;for(let{value:n,color:r}of[...s].sort((e,t)=>Number(u(t.value))-Number(u(e.value)))){let[s,d]=dv(i,a,o,n),f=s.x<=d.x?s:d,p=String(n),m=e.measureText(p).width,h={left:f.x-cv-m,right:f.x-cv,top:f.y-c/2,bottom:f.y+c/2};!Nr([h],l)&&!u(n)||(l.push(h),e.fillStyle=N(r??t.style.color),F(e,p,h.right,f.y))}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]=dv(i,a,o,n);if(this.distanceToLine(e,t,s)<=r)return!0}return!1}},pv=.4,mv=.8,hv=4,gv=[.25,.382,.5,.618,.75];function _v(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 vv(e,t,n=gv){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 yv=class extends J{descriptor={type:`fibSpeedResistanceFan`,name:`Fib Speed Resistance Fan`,requiredAnchors:2,options:{levels:{kind:`levels`,label:`Levels`,default:Um(gv,[.236,.786])}}};targets(e,t,n){return vv(t,n,this.visibleLevels(e).map(e=>e.value))}colorOf(e,t){return this.visibleLevels(e).find(e=>e.value===t)?.color??e.style.color}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.save(),this.applyGuideStyle(e,t.style.color),e.globalAlpha=pv,this.strokeCrispRect(e,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.restore(),e.font=M(`label`);let o=a.x>=i.x,s=a.y>=i.y;for(let r of this.targets(t,i,a)){let a=_v(i,r.point,n);if(!a)continue;let c=r.kind===`diagonal`?t.style.color:this.colorOf(t,r.level);this.applyLineStyle(e,{...t.style,color:c,lineStyle:r.kind===`time`?`dashed`:t.style.lineStyle}),e.globalAlpha=r.kind===`diagonal`?1:mv,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),r.kind!==`diagonal`&&(e.globalAlpha=1,e.fillStyle=N(c),r.kind===`price`?(e.textAlign=o?`left`:`right`,e.textBaseline=`middle`,F(e,String(r.level),r.point.x+(o?hv:-hv),r.point.y)):(e.textAlign=`center`,e.textBaseline=s?`top`:`bottom`,F(e,String(r.level),r.point.x,r.point.y+(s?hv:-hv))))}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=_v(i,o.point,n);if(t&&this.distanceToLine(e,i,t)<=r)return!0}return!1}},bv=class extends J{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.renderGuides(e,t,i),this.renderExtras(e,t,i,n);let a=this.renderPointLabels(e,t,i);this.renderRatios(e,t,i,[...qg(i,t.style.lineWidth),...a]),r&&this.renderAnchorHandles(e,t,n)}renderExtras(e,t,n,r){}pointFont(){return{font:M(`letter`,{weight:600}),height:j().sizes.letter}}renderTriangles(e,t,n){e.fillStyle=P(t.style);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()}linksIn(e){return this.ratioLinks.filter(t=>Math.max(t.from,t.to,...t.num,...t.den)<e.length)}renderGuides(e,t,n){e.save(),this.applyGuideStyle(e,t.style.color,!0);for(let t of this.linksIn(n))e.beginPath(),e.moveTo(n[t.from].x,n[t.from].y),e.lineTo(n[t.to].x,n[t.to].y),e.stroke();e.restore()}renderRatios(e,t,n,r){let i=[...r];e.fillStyle=N(t.style.color);for(let r of this.linksIn(n)){let a=Jg(e,Pr(t,r.num,r.den),n[r.from],n[r.to],i);a&&i.push(a)}}renderPointLabels(e,t,n){let{font:r,height:i}=this.pointFont();return e.font=r,Wg(e,t,n,this.pointLabels.map(e=>typeof e==`string`?{text:e}:e),i)}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}},xv=class extends bv{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]]},Sv=class extends bv{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]}]},Cv=class extends bv{descriptor={type:`headAndShoulders`,name:`Head and Shoulders`,requiredAnchors:7,fill:!0};pointLabels=[{text:``},{text:`Left Shoulder`,short:`LS`},{text:``},{text:`Head`,short:`H`,first:!0},{text:``},{text:`Right Shoulder`,short:`RS`},{text:``}];pointFont(){return{font:M(`label`,{weight:600,prose:!0}),height:j().sizes.label}}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([])}},wv=class extends bv{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]}]},Tv=class extends bv{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]]},Ev=class extends J{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=P(t.style),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}},Dv=.5;function Ov(t,n){let r=n.data;if(!r||r.length===0)return null;let i=Math.round(e.A(t.anchors[0].time,n)),a=Math.round(e.A(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 kv(e,n){let r=Ar(e,0,1,n),i=kr(e,0,1,n),a=[Er(e.anchors[0].price,e.anchors[1].price,n),r?`${i} bars · ${r}`:`${i} bars`],o=Ov(e,n);return o!==null&&a.push(`Vol ${(0,t.formatVolumeLoc)(o,n.numberLocale??`en-US`)}`),a}var Av=class extends J{descriptor={type:`dateAndPriceRange`,name:`Date and Price Range`,requiredAnchors:2};render(e,n,r,i){if(n.anchors.length<2)return;let a=this.anchorToPixel(n.anchors[0],r),o=this.anchorToPixel(n.anchors[1],r),s=Math.min(a.x,o.x),c=Math.min(a.y,o.y),l=Math.abs(o.x-a.x),u=Math.abs(o.y-a.y),d=n.anchors[1].price>=n.anchors[0].price,f=j(),p=d?n.style.color:f.fall;e.fillStyle=d?P(n.style):(0,t.withAlpha)(f.fall,ln),e.fillRect(s,c,l,u),e.save(),this.applyGuideStyle(e,p),e.globalAlpha=Dv,this.strokeCrispRect(e,s,c,l,u),e.restore(),this.applyLineStyle(e,{...n.style,color:p});let m=s+l/2,h=c+u/2;e.beginPath(),e.moveTo(m,a.y),e.lineTo(m,o.y),e.moveTo(a.x,h),e.lineTo(o.x,h),e.stroke(),this.resetLineStyle(e),zh(e,{x:m,y:a.y},{x:m,y:o.y},p,n.style.lineWidth),zh(e,{x:a.x,y:h},{x:o.x,y:h},p,n.style.lineWidth),jr(e,kv(n,r),m,d?c-6:c+u+6,`center`,d),i&&this.renderAnchorHandles(e,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 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}},jv=400,Mv=2;function Nv(e,t,n){let r=Math.abs(t.x-e.x);if(r<Mv)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<jv;e+=r)a.push(e);return a}var Pv=class extends J{descriptor={type:`cyclicLines`,name:`Cyclic Lines`,requiredAnchors:2};handlePoints(e,t){return this.timeHandles(e,t)}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);for(let r of Nv(i,a,n))r<o.x||(this.strokeVertical(e,r,o.y,o.y+o.height),e.lineWidth=t.style.lineWidth);this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:Nv(this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n),n).some(t=>Math.abs(e.x-t)<=r)}},Fv=240;function Iv(e){return En(e.style)}function Lv(e){return Ym(e.style,{box:!0,border:!0,width:Fv,fill:!0})}function Rv(e,t,n,r){let i=Iv(e),a=Math.max(...t.split(`
|
|
5
|
-
`).map(e=>e.length));return{x:n,y:r,width:Math.min(
|
|
6
|
-
`),i=Math.max(...r.map(e=>e.length));return{width:Math.min(ty,i*n*.6)+16,height:r.length*n*1.3+12}}var dy=class extends J{descriptor={type:`signpost`,name:`Signpost`,requiredAnchors:1,text:!0,fill:!0};boxes=new ph;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=y_(t,`Signpost`),o=cy(t),s=ly(i,oh(e,a,o),ny,n);this.applyLineStyle(e,{...t.style,lineStyle:`solid`}),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x,s.below?i.y+ny:i.y-ny),e.stroke(),this.resetLineStyle(e),this.boxes.set(t.id,sh(e,a,s.x,s.y,o)),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.boxes.get(t.id)??ly(i,uy(t,y_(t,`Signpost`)),ny,n),[o,s]=a.y>i.y?[i.y,i.y+ny]:[i.y-ny,i.y];return Math.abs(e.x-i.x)<=r&&e.y>=o-r&&e.y<=s+r?!0:dh(e,a,r)}textBox(e){return this.boxes.get(e.id)??null}},fy=class extends J{descriptor={type:`balloon`,name:`Balloon`,requiredAnchors:1,text:!0,fill:!0};boxes=new ph;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=y_(t,`Comment`),o=cy(t),s=oh(e,a,o),c=oy(s.height),l=ly(i,s,c.length,n),u={...o,traceBox:sy(i,c.half,l.below)};this.boxes.set(t.id,sh(e,a,l.x,l.y,u)),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=uy(t,y_(t,`Comment`)),o=this.boxes.get(t.id)??ly(i,a,oy(a.height).length,n),s=oy(o.height),[c,l]=o.y>i.y?[i.y,i.y+s.length]:[i.y-s.length,i.y];return Math.abs(e.x-i.x)<=s.half+r&&e.y>=c-r&&e.y<=l+r?!0:dh(e,o,r)}textBox(e){return this.boxes.get(e.id)??null}},py=class extends b_{descriptor={type:`anchoredText`,name:`Anchored Text`,requiredAnchors:1,text:!0,fill:!0,anchoring:`screen`}},my=class extends Vv{descriptor={type:`anchoredNote`,name:`Anchored Note`,requiredAnchors:1,text:!0,fill:!0,anchoring:`screen`,options:{showText:{kind:`boolean`,label:`Show text`,default:!0}}}},hy=14,gy=18,_y=8,vy=5,yy=1.35,by=3,xy=3;function Sy(e){return Math.round(e*yy)+vy*2}var Cy=class extends J{drawn=new ph;descriptor={type:`priceLabel`,name:`Price Label`,requiredAnchors:1,text:!0};text(e,t){return e.style.text||wr(e.anchors[0].price,e.anchors[0].price,t)}box(e,t,n,r){let i=En(t.style,`label`),a=this.text(t,r),o=e?e.measureText(a).width:a.length*i*.6,s=Sy(i);return{x:n.x+hy,y:n.y-gy-s/2,w:Math.ceil(o)+_y*2,h:s}}render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n);e.font=$m(En(t.style,`label`),t.style.bold,t.style.italic);let a=this.box(e,t,i,n);this.drawn.set(t.id,{x:a.x,y:a.y,width:a.w,height:a.h}),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(),this.fillBox(e,a,t.style.color),e.fillStyle=t.style.textColor??zn(t.style.color),e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(this.text(t,n),a.x+_y,a.y+a.h/2),e.beginPath(),e.arc(i.x,i.y,xy,0,Math.PI*2),e.fillStyle=t.style.color,e.fill(),r&&this.renderAnchorHandles(e,t,n)}fillBox(e,t,n){let r=Math.round(t.x),i=Math.round(t.y);e.fillStyle=n,e.beginPath(),typeof e.roundRect==`function`?e.roundRect(r,i,Math.round(t.w),Math.round(t.h),by):e.rect(r,i,Math.round(t.w),Math.round(t.h)),e.fill()}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.drawn.get(t.id),o=a?{...this.box(null,t,i,n),w:a.width}:this.box(null,t,i,n);return e.x>=o.x-r&&e.x<=o.x+o.w+r&&e.y>=o.y-r&&e.y<=o.y+o.h+r}},wy=48;function Ty(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 Ey(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 Dy(e,t,n,r=Dn(Number(e.lineWidth)||1)){let i=Math.atan2(n.y-t.y,n.x-t.x);e.save(),e.setLineDash([]),e.lineJoin=`round`,e.lineCap=`round`,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(),e.restore()}function Oy(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 ky=new WeakMap;function Ay(e){let t=ky.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);ky.set(e,t)}return t}var jy=class extends J{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,Ty(e,i),e.globalAlpha=1,e.lineCap=`butt`,e.lineJoin=`miter`,this.resetLineStyle(e),this.renderBounds(e,t,n,r)}renderBounds(e,t,n,r){let i=this.screenBox(t,n),a=this.stroke(t).width/2;lh(e,{x:i.x0-a,y:i.y0-a,width:i.x1-i.x0+a*2,height:i.y1-i.y0+a*2},t.style.color,r)}screenBox(t,n){let{t0:r,t1:i,p0:a,p1:o}=Ay(t.anchors),s=e.O(a,n),c=e.O(o,n);return{x0:e.j(r,n),x1:e.j(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:Fp(e,t.anchors.map(e=>this.anchorToPixel(e,n)),i)}},My=class extends jy{descriptor={type:`highlighter`,name:`Highlighter`,requiredAnchors:2,creation:`freehand`};stroke(e){return{width:Math.max(10,e.style.lineWidth*8),alpha:.3}}},Ny=class extends J{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`,Ey(e,i),e.stroke(),this.resetLineStyle(e),this.option(t,`arrowEnd`)&&Dy(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:Fp(e,t.anchors.map(e=>this.anchorToPixel(e,n)),r)}},Py=class extends J{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;Ey(e,i,a),a&&(e.fillStyle=P(t.style),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 Fp(e,i,r,!0)||i.length>=3&&Oy(e,i)}};function Fy(e,t,n,r=wy){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 Iy(e,t,n,r=wy){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 Ly=class extends J{descriptor={type:`curve`,name:`Curve`,requiredAnchors:3};shape(e,t,n){return Fy(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),Ey(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:Fp(e,this.points(t,n),r)}},Ry=class extends Ly{descriptor={type:`arc`,name:`Arc`,requiredAnchors:3};shape(e,t,n){return Iy(e,t,n)}},zy=(1+Math.sqrt(5))/2,By=64,Vy=2,Hy=6,Uy=-Math.PI/4,Wy=.7,Gy=.3,Ky=.7,qy=8;function Jy(e,t=[]){return{levels:{kind:`levels`,label:`Levels`,default:Um(e,t)},showLevels:{kind:`boolean`,label:`Show levels`,default:!0}}}var Yy=[.236,.382,.5,.618,.786,1];function Xy(e){return String(Number(e.toFixed(3)))}function Zy(e,t,n,r,i,a=By){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 Qy(e,t){e.beginPath(),t.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.stroke()}function $y(e,t){let n=Math.hypot(t.x-e.x,t.y-e.y)||1;return{x:-(t.y-e.y)/n,y:(t.x-e.x)/n}}var eb=class extends J{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.applyGuideStyle(e,t.style.color,!0),e.globalAlpha=Wy;for(let[t,n]of this.guides(i))Qy(e,[t,n]);e.globalAlpha=1,this.applyLineStyle(e,t.style);let a=this.option(t,`showLevels`);e.font=M(`label`),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,Qy(e,n.points);a&&this.renderLabels(e,t,o),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}renderLabels(e,t,n){let r=j().sizes.label,i=[],a=[...n].reverse().sort((e,t)=>Number(t.level.value===1)-Number(e.level.value===1));for(let{level:n,label:o,away:s}of a){let a=Xy(n.value),c=e.measureText(a).width,l=s??{x:0,y:-1},u=o.x+l.x*Hy,d=o.y+l.y*Hy,f=l.x<-.3?u-c:l.x>.3?u:u-c/2,p=l.y<-.3?d-r:l.y>.3?d:d-r/2,m={x0:f,x1:f+c,y0:p,y1:p+r};i.some(e=>m.x1+Vy>e.x0&&e.x1+Vy>m.x0&&m.y1+Vy>e.y0&&e.y1+Vy>m.y0)||(i.push(m),e.fillStyle=N(n.color??t.style.color),e.textAlign=`left`,e.textBaseline=`top`,F(e,a,m.x0,m.y0))}}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])=>Pp(e,t,n)<=r)?!0:this.shapes(i,this.visibleLevels(t),n,t).some(t=>Fp(e,t.points,r))}},tb=class extends eb{descriptor={type:`fibCircles`,name:`Fib Circles`,requiredAnchors:2,options:Jy([...Yy,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,r={x:n.x+t*Math.cos(Uy),y:n.y+t*Math.sin(Uy)};return{level:e,points:Zy(n,t,t,0,Math.PI*2),label:r,away:{x:Math.SQRT1_2,y:-Math.SQRT1_2}}})}},nb=class extends eb{descriptor={type:`fibArcs`,name:`Fib Speed Resistance Arcs`,requiredAnchors:2,options:{...Jy(Yy),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?Zy(i,t,t,0,Math.PI*2):Zy(i,t,t,s-Math.PI/2,Math.PI),label:{x:i.x+t*Math.cos(s),y:i.y+t*Math.sin(s)},away:$y(i,a)}})}},rb=class extends eb{descriptor={type:`fibWedge`,name:`Fib Wedge`,requiredAnchors:3,options:Jy(Yy)};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,i=$y(n,r),c=s>0?-1:1;return{level:e,points:Zy(n,t,t,o,s,32),label:{x:n.x+t*Math.cos(o),y:n.y+t*Math.sin(o)},away:{x:i.x*c,y:i.y*c}}})}},ib=class extends eb{descriptor={type:`pitchfan`,name:`Pitchfan`,requiredAnchors:3,options:Jy([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,away:$y(r,t)}})}},ab=class extends J{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(zy),u=Math.log(i/qy)/Math.log(zy),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*zy**+(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),Qy(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:Fp(e,this.points(t,n),r)}},ob=class extends J{descriptor={type:`gannSquare`,name:`Gann Square`,requiredAnchors:2,options:{...Jy([.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 Zy(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.slice(0,6).forEach(([n,r])=>this.strokeSegment(e,n,r,t.style.lineWidth)),this.applyGuideStyle(e,t.style.color),e.globalAlpha=Gy,i.slice(6).forEach(([t,n])=>this.strokeSegment(e,t,n,1));let o=this.visibleLevels(t);a.forEach((n,r)=>{this.applyLineStyle(e,{...t.style,color:o[r]?.color??t.style.color}),e.globalAlpha=Ky,Qy(e,n)}),e.globalAlpha=1,this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}strokeSegment(e,t,n,r){e.lineWidth=r,Math.abs(t.y-n.y)<.5?this.strokeHorizontal(e,t.x,n.x,t.y):Math.abs(t.x-n.x)<.5?this.strokeVertical(e,t.x,t.y,n.y):Qy(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])=>Pp(e,t,n)<=r)}},sb=400,cb=32,lb=3,ub=class extends J{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<sb;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<=cb;i++){let a=Math.PI+Math.PI*i/cb;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=P(t.style),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)}},db=class extends J{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+=lb)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:Fp(e,this.points(t,n),r)}},fb=5,pb=.85,mb=.08,hb=500;function gb(t,n,r){let i=r.price>=n.price,a=t.length>0?Math.max(0,Math.floor(e.M(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 _b=class extends J{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=gb(this.bars(),i,a),l=j(),u=c===`reached`?l.rise:c===`missed`?l.fall:t.style.color,d=Math.hypot(s.x-o.x,s.y-o.y),f=d>fb?{x:s.x-(s.x-o.x)/d*fb,y:s.y-(s.y-o.y)/d*fb}:s;this.applyLineStyle(e,{...t.style,color:u}),e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(f.x,f.y),e.stroke(),this.resetLineStyle(e),e.strokeStyle=u,e.lineWidth=Math.max(1,t.style.lineWidth),e.beginPath(),e.arc(s.x,s.y,fb,0,Math.PI*2),e.stroke();let p=Ar(t,0,1,n);jr(e,[Er(i.price,a.price,n),`${wr(a.price,i.price,n)} · ${kr(t,0,1,n)} bars${p?` · ${p}`:``}`,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:Pp(e,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n))<=r}},vb=class extends J{descriptor={type:`projection`,name:`Projection`,requiredAnchors:3,fill:!0};target(t,n){let[r,i,a]=t.anchors,o=e.A(i.time,n)-e.A(r.time,n);return{x:e.C(e.A(a.time,n)+o,n),y:e.O(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=P(t.style),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(),Dy(e,r,a);let[o,s,c]=t.anchors,l=c.price+(s.price-o.price);jr(e,[wr(l,c.price,n),Er(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 Pp(e,i[0],i[1])<=r?!0:i.length>=3&&Pp(e,i[2],this.target(t,n))<=r}},yb=class extends J{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.M(Math.min(r.time,i.time),n))),s=Math.min(n.length-1,Math.round(e.M(Math.max(r.time,i.time),n)));if(s<o)return[];let c=n.slice(o,Math.min(s+1,o+hb));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.A(t.anchors[2].time,n),a=e.C(i,n)-n.barWidth/2,o=e.C(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.O(s,n),u=e.O(c,n);return{x:a,y:Math.min(l,u),width:o-a,height:Math.abs(u-l)}}source(t,n){let r=this.bars();if(r.length===0)return null;let[i,a]=t.anchors,o=Math.max(0,Math.round(e.M(Math.min(i.time,a.time),r))),s=Math.min(r.length-1,Math.round(e.M(Math.max(i.time,a.time),r)));if(s<o)return null;let c=-1/0,l=1/0;for(let e=o;e<=s;e++)r[e].high>c&&(c=r[e].high),r[e].low<l&&(l=r[e].low);let u=e.C(e.A(r[o].time,n),n)-n.barWidth/2,d=e.C(e.A(r[s].time,n),n)+n.barWidth/2,f=e.O(c,n),p=e.O(l,n);return{x:u,y:Math.min(f,p),width:d-u,height:Math.abs(p-f)}}handlePoints(e,t){let n=super.handlePoints(e,t),r=this.source(e,t);if(!r||n.length<2)return n;let[i,a]=e.anchors,o=i.time<=a.time,s=t.barWidth/2,c=r.x+s,l=r.x+r.width-s;return[{x:o?c:l,y:r.y},{x:o?l:c,y:r.y},...n.slice(2)]}render(e,n,r,i){if(n.anchors.length<2)return;let a=this.source(n,r);a&&(e.fillStyle=(0,t.withAlpha)(n.style.color,mb),e.fillRect(a.x,a.y,a.width,a.height)),n.anchors.length>=3&&this.renderCopy(e,n,r);let o=i&&n.anchors.length>=3?this.box(n,r,this.copied(n)):null;o&&(e.save(),this.applyGuideStyle(e,n.style.color,!0),this.strokeCrispRect(e,o.x,o.y,o.width,o.height),e.restore()),i&&this.renderAnchorHandles(e,n,r)}renderCopy(t,n,r){let i=this.copied(n);if(i.length===0)return;let a=e.A(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=pb,o===`line`)t.beginPath(),i.forEach((n,i)=>{let o=e.C(a+i,r),s=e.O(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=Math.round(e.C(a+s,r))+.5;if(t.lineWidth=1,this.strokeVertical(t,c,e.O(i.high,r),e.O(i.low,r)),o===`highLow`)return;let l=Math.round(e.O(Math.max(i.open,i.close),r)),u=Math.max(1,Math.round(e.O(Math.min(i.open,i.close),r))-l),d=Math.round(c-n),f=Math.max(1,Math.round(n*2));i.close>=i.open?(t.lineWidth=1,this.strokeCrispRect(t,d,l,f,u)):t.fillRect(d,l,f,u)})}t.globalAlpha=1}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.source(t,n);if(i&&dh(e,i,r))return!0;let a=t.anchors.length>=3?this.box(t,n,this.copied(t)):null;return a!==null&&dh(e,a,r)}};function bb(e){e.register(new Uh),e.register(new Wh),e.register(new Gh),e.register(new qh),e.register(new Jh),e.register(new Yh),e.register(new Qh),e.register(new rg),e.register(new gg),e.register(new vg),e.register(new bg),e.register(new xg),e.register(new Sg),e.register(new Eg),e.register(new e_),e.register(new c_),e.register(new d_),e.register(new f_),e.register(new b_),e.register(new S_),e.register(new T_),e.register(new A_),e.register(new M_),e.register(new V_),e.register(new G_),e.register(new rv),e.register(new iv),e.register(new Ah),e.register(new ov),e.register(new fv),e.register(new yv),e.register(new Dg),e.register(new Og),e.register(new xv),e.register(new Sv),e.register(new Cv),e.register(new Ev),e.register(new Av),e.register(new Pv),e.register(new Cy),e.register(new Vv),e.register(new Hv),e.register(new Jv),e.register(new Zv),e.register(new ey),e.register(new dy),e.register(new fy),e.register(new py),e.register(new my),e.register(new jy),e.register(new My),e.register(new Ny),e.register(new Py),e.register(new Ly),e.register(new Ry),e.register(new tb),e.register(new ab),e.register(new nb),e.register(new rb),e.register(new ib),e.register(new ob),e.register(new t_),e.register(new n_),e.register(new r_),e.register(new i_),e.register(new a_),e.register(new wv),e.register(new Tv),e.register(new ub),e.register(new db),e.register(new _b),e.register(new vb),e.register(new yb)}function X(e,t){let{chartRect:n}=t;return e>=n.y&&e<=n.y+n.height}function xb(e,t){let{chartRect:n}=t;return Math.min(Math.max(e,n.y),n.y+n.height)}function Sb(t,n,r,i,a){let{chartRect:o}=n;t.setLineDash(a),t.strokeStyle=i,t.lineWidth=1,t.beginPath(),e.y(t,o.x,o.x+o.width,Math.round(r)+.5),t.stroke(),t.setLineDash([])}function Cb(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 wb=/\{(side|qty|closedQty|openQty|entry|price|pnl|pnlPct|pnlSign)\}/g;function Tb(e,n){return e.replace(wb,(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 Eb(e,n,r){let i=10**n,a=Math.round(e*i)/i||0;return`${a>0?`+`:``}${(0,t.formatPrice)(a,n,r)}`}function Db(e,t,n,r){return(r-t)*n*(e===`buy`?1:-1)}function Ob(e,t){return typeof e==`function`?e(t):Tb(e??`{side} {qty} | P&L: {pnlSign}{pnl}`,t)}function kb(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 Ab=24,jb=1.75,Mb=[2,2.5],Nb=new Map,Pb=e=>{let t=Nb.get(e);return t||(t=new Path2D(e),Nb.set(e,t)),t};function Fb(e,n,r,i,a,o){if(!(typeof Path2D>`u`)){if(e.save(),e.translate(Math.round(r),Math.round(i)),e.scale(a/Ab,a/Ab),e.strokeStyle=o,e.fillStyle=o,e.lineWidth=Math.max(jb,Ab/a),e.lineCap=`round`,e.lineJoin=`round`,e.setLineDash([]),n.soft){let r=e.globalAlpha;e.globalAlpha=r*t.ICON_SOFT_OPACITY,e.fill(Pb(n.soft)),e.globalAlpha=r}for(let t of n.fills??[])e.fill(Pb(t));n.d&&e.stroke(Pb(n.d)),n.dash&&(e.setLineDash(Mb),e.stroke(Pb(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 Ib=5,Lb=13,Rb=22;function zb(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 Bb(e,t){return`${e.kind===`stamp`?`600 `:``}${t.font.sizeSmall}px ${t.font.family}`}function Vb(e,t,n){return t.kind===`button`?21:(e.font=Bb(t,n),Math.ceil(e.measureText(t.text).width)+Ib*2)}function Hb(e){return Math.round(e)-10}function Ub(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)<Rb&&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 Wb(e,t,n,r,i,a=[],o=0,s=[]){if(t.length===0)return;let{chartRect:c}=n,l=t.map(t=>t.cells.map(t=>Vb(e,t,r))),u=l.map(e=>e.reduce((e,t)=>e+t,0)),d=Ub(t.map((e,t)=>({y:e.y,width:u[t]})),{left:c.x,right:c.x+c.width-o}),f=t.map((e,t)=>t).sort((e,t)=>Number(d[e].fits)-Number(d[t].fits));for(let n of f){let{x:o,fits:f}=d[n],p=Hb(t[n].y);Gb(e,t[n],o,p,l[n],u[n],r,f?i:[]),s.push({x:o,y:p,width:u[n],height:21});let m=t[n].grab;if(!f||!m)continue;let h=Math.max(p,c.y),g=Math.min(p+21,c.y+c.height);g>h&&a.push({x:o,y:h,width:u[n],height:g-h,lineY:t[n].y,grab:m})}}function Gb(e,t,n,r,i,a,o,s){let c=r+21/2;e.save(),O(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`?(Fb(e,n.icon,l+(u-Lb)/2,r+(21-Lb)/2,Lb,o.text),s.push({x:l,y:r,size:21,action:n.action})):(e.font=Bb(n,o),e.fillStyle=n.kind===`stamp`?re(t.color):n.color??o.text,e.fillText(n.text,l+Ib,c)),l+=u}),O(e,n+.5,r+.5,a-1,20,o),e.strokeStyle=t.color,e.lineWidth=1,e.stroke(),e.restore()}function Kb(e,t){let{chartRect:n}=t,r=n.y+n.height,i=[...e].sort((e,t)=>e.y-t.y),a=ne(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 qb(e,n,r,i,a,o){let{chartRect:s}=a,c=s.x+s.width+1;e.fillStyle=i,k(e,c,Math.round(n)-16/2,(a.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,16,o),e.fillStyle=re(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 Jb=[6,4],Yb=[2,3],Xb=[2,4],Zb=.3;function Qb(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 $b(e){return{buy:e.orderColors?.buy??`#1fa874`,sell:e.orderColors?.sell??`#e8505b`,profit:e.positionColors?.profit??`#1fa874`,loss:e.positionColors?.loss??`#e8505b`}}function ex(e,t){return t?.orderId===e.id&&t.sourceType===`order`}function tx(e,t){return ex(e,t)?t.currentPrice:e.price}var nx=class{render(e,t,n,r,i,a,o=[]){this.renderLines(e,t,n,i,a),Wb(e,this.tags(t,n,i,a),n,r,o)}renderLines(t,n,r,i,a){let o=$b(i);for(let i of n){let n=e.O(tx(i,a),r),s=i.side===`buy`?o.buy:o.sell;X(n,r)&&Sb(t,r,n,s,Jb),ex(i,a)&&(t.globalAlpha=Zb,Sb(t,r,e.O(a.startPrice,r),s,Xb),t.globalAlpha=1);for(let[n,a]of[[i.stopLoss,o.loss],[i.takeProfit,o.profit]]){let i=n===void 0?NaN:e.O(n,r);X(i,r)&&Sb(t,r,i,a,Yb)}}}tags(n,r,i,a){let o=$b(i),s=i.pricePrecision??2,c=[];for(let l of n){let n=tx(l,a),u=e.O(n,r);if(X(u,r)){let e=[{kind:`stamp`,text:String(l.quantity)},{kind:`text`,text:Qb(l)}];i.lineButtons?.cancel!==!1&&!ex(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.O(i,r);if(i===void 0||!X(a,r))continue;let u=Db(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:Eb(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))qb(e,o.y,o.text,o.color,n,r)}axisBadges(n,r,i,a){let o=$b(i),s=[];for(let c of n){let n=tx(c,a),l=e.O(n,r);X(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.O(a.price,r);if(Math.abs(t-n)<=i)return a}return null}},rx=[4,4],ix=[2,4],ax=.3,ox=.08,sx=.25,cx=.04,lx=[`stopLoss`,`takeProfit`];function ux(e){return{profit:e.positionColors?.profit??`#1fa874`,loss:e.positionColors?.loss??`#e8505b`,entry:e.positionColors?.entry??`#4c8dff`}}function dx(e,t){let{chartRect:n}=t;return e-21/2>=n.y&&e+21/2<=n.y+n.height}function fx(e){return e.quantity-Math.min(Math.max(e.closedQuantity??0,0),e.quantity)}function px(e,t,n){return n?.orderId===e.id&&n.sourceType===t?n.currentPrice:e[t]}var mx=class{render(e,t,n,r,i,a,o=[],s=null){this.renderLines(e,t,n,r,a,s),Wb(e,this.tags(t,n,r,a,s),r,i,o)}renderLines(t,n,r,i,a,o=null){let s=ux(a);for(let c of n){let n=e.O(c.entryPrice,i);Sb(t,i,n,s.entry,[]),r!==null&&this.renderBand(t,c,n,e.O(r,i),r,i,a);for(let n of lx){let r=px(c,n,o),a=r===void 0?NaN:e.O(r,i),l=n===`stopLoss`?s.loss:s.profit;X(a,i)&&Sb(t,i,a,l,rx);let u=c[n];u!==void 0&&r!==u&&(t.globalAlpha=ax,Sb(t,i,e.O(u,i),l,ix),t.globalAlpha=1)}}}renderBand(e,t,n,r,i,a,o){let{chartRect:s}=a,c=ux(o),l=Cb(t,i,o.pricePrecision??2),u=Math.min(n,r),d=Math.abs(r-n);e.fillStyle=kb(l.pnl,o.pnlThresholds,l.pnl>=0?c.profit:c.loss),e.globalAlpha=ox,e.fillRect(s.x,u,s.width,d),l.closedQuantity>0&&t.quantity>0&&(e.fillStyle=c.entry,e.globalAlpha=sx,e.fillRect(s.x,u,Math.max(2,s.width*(l.closedQuantity/t.quantity)*cx)+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 lx){let t=this.stopTag(o,e,n,r,i);t&&a.push(t)}}return a}entryTag(n,r,i,a){let o=e.O(n.entryPrice,i);if(!X(o,i))return null;let s=ux(a),c=n.side===`buy`?`Long`:`Short`,l=[{kind:`stamp`,text:String(fx(n))}];if(r===null)l.push({kind:`text`,text:c});else{let e=a.pricePrecision??2,o=Cb(n,r,e,e=>(0,t.priceTagText)(e,i,a.pricePrecision),i.numberLocale);if(a.positionLabel!==void 0)l.push({kind:`text`,text:Ob(a.positionLabel,o)});else{let t=kb(o.pnl,a.pnlThresholds,o.pnl>=0?s.profit:s.loss);l.push({kind:`text`,text:c},{kind:`text`,text:Eb(o.pnl,e,i.numberLocale),color:t})}}let u=a.lineButtons??{};return dx(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=px(n,r,o),c=s===void 0?NaN:e.O(s,i);if(s===void 0||!X(c,i))return null;let l=ux(a),u=Db(n.side,n.entryPrice,fx(n),s),d=[{kind:`stamp`,text:r===`stopLoss`?`SL`:`TP`},{kind:`text`,text:Eb(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&&dx(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))qb(e,a.y,a.text,a.color,n,r)}axisBadges(n,r,i,a=null){let o=ux(i),s=[];for(let c of n){let n=[[px(c,`stopLoss`,a),o.loss],[px(c,`takeProfit`,a),o.profit],[c.entryPrice,o.entry]];for(let[a,o]of n){if(a===void 0)continue;let n=e.O(a,r);X(n,r)&&s.push({y:n,text:(0,t.priceTagText)(a,r,i.pricePrecision),color:o})}}return s}},hx=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.O(n.bids[0].price,r)-e.O(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.O(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.O(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)}}},gx=[`stopLoss`,`takeProfit`],_x=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.O(n,i);return X(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 gx){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.F(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}},vx=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-WwFdTWTn.cjs`);let t=require(`@tradecanvas/commons`);var n=2;function r(e=2){let t=typeof window<`u`&&window.devicePixelRatio||1;return e>0?Math.min(t,e):t}function i(e,t,n){let r=t/2+.5,i=(e,n)=>Number.isInteger(e)&&e>0&&Math.abs(e-n*t)<=r;return n&&i(n.width,e.width)&&i(n.height,e.height)?{width:n.width,height:n.height,exact:!0}:{width:Math.round(e.width*t),height:Math.round(e.height*t),exact:!1}}function a(e,t,n,r){let a=i(t,n,r);(e.width!==a.width||e.height!==a.height)&&(e.width=a.width,e.height=a.height),e.style.width=a.exact?`100%`:`${t.width}px`,e.style.height=a.exact?`100%`:`${t.height}px`}var o=class{observer=null;callback=null;currentDpr=1;resizeScheduled=!1;deviceChanged=!1;cachedSize;deviceSize=null;stopWatchingRatio=null;constructor(e,t=2){this.container=e,this.maxPixelRatio=t,this.currentDpr=r(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}getDeviceSize(){return this.deviceSize}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(e=>{let t=e?.[e.length-1]?.devicePixelContentBoxSize?.[0],n=t?{width:t.inlineSize,height:t.blockSize}:null;(n?.width!==this.deviceSize?.width||n?.height!==this.deviceSize?.height)&&(this.deviceSize=n,this.deviceChanged=!0),!this.resizeScheduled&&(this.resizeScheduled=!0,requestAnimationFrame(()=>{this.resizeScheduled=!1,this.update(!1)}))});try{this.observer.observe(this.container,{box:`device-pixel-content-box`})}catch{this.observer.observe(this.container)}this.watchRatio()}update(e){let t=r(this.maxPixelRatio),n=this.container.clientWidth,i=this.container.clientHeight,a=this.deviceChanged||t!==this.currentDpr||n!==this.cachedSize.width||i!==this.cachedSize.height;this.deviceChanged=!1,this.currentDpr=t,this.cachedSize={width:n,height:i},(a||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 s(e){e.style.fontFeatureSettings=`normal`}var c=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`,s(this.canvas),this.ctx=this.canvas.getContext(`2d`),e.appendChild(this.canvas)}resize(e,t,n=null){this.dpr=t,a(this.canvas,e,t,n),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()}},l=class{scene=null;top=null;back=null;gpuCanvas=null;size=null;dpr=1;device=null;constructor(e){this.container=e}createLayers(){this.destroy(),this.scene=new c(this.container,0),this.top=new c(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 c(this.container,0),this.container.insertBefore(this.back.canvas,this.gpuCanvas),this.size&&this.back.resize(this.size,this.dpr,this.device)),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,n=null){this.size=e,this.dpr=t,this.device=n,this.scene?.resize(e,t,n),this.top?.resize(e,t,n),this.back?.resize(e,t,n),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;n&&a(n,e,t,this.device)}},u=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}})}};function d(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 f(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 p=1e-9;function m(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))<=p*Math.max(1,Math.abs(e*t))))return n}return t}function h(e,t,n){return Math.floor(t/n+1e-9)-Math.ceil(e/n-1e-9)+1}function g(e,t){if(!t||!(t>0)||e>=1)return e;let n=t;for(;n<e;)n*=2;return n}var _=24,v=200;function y(e){return Math.max(2,Math.min(_,Math.round(e/56)+1))}function b(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 x(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 S(e){return e<1?Math.ceil(-Math.log10(e))+1:+(e<10)}function C(e,n,r){let i=(0,t.computeTickStep)(e,n,y(r));if(!(i>0)||!(r>0))return i;let a=n-e;for(let e=0;e<8&&i/a*r<30;e++)i=x(i);return i}function w(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<v;e++){let t=e*n;r.push(Math.abs(t)<n*1e-9?0:t)}return r}var T=12,E=14,D=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=C(n,r,e.chartRect.height),a=(0,t.autoPricePrecision)(n,r);if(e.priceUnit)return{step:g(i,e.priceUnit),precision:this.precision??a};let o=f(i,this.precision,this.tick);return h(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):w(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 w(c,l,C(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.A(t),o=Math.exp(-i*56),s=[],c=f(b(r*(1-o)),this.precision,this.tick),l=Math.floor(r/c+1e-9)*c,u=null;for(let e=0;e<200&&l>=n&&l>0;e++){let e=a(l);(u===null||Math.abs(e-u)>=30)&&(s.push(l),u=e);let t=l*o;if(c=f(b(Math.min(l-t,t)),this.precision,this.tick),!(c>0))break;let n=Math.round(t/c)*c;n>=l&&(n-=c),l=n}return s.length===0?w(n,r,this.scale(t).step):s.reverse()}labelText(e,t){return d(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,c=i===`left`,l=c?o.x:o.x+o.width;if(s.max-s.min<=0)return;let u=e.A(n);t.strokeStyle=r.style?.axis.price.line??r.axisLine,t.lineWidth=1,t.globalAlpha=.65,t.beginPath(),e.S(t,l+.5,o.y,o.y+o.height),t.stroke(),t.globalAlpha=1;let{precision:f}=this.scale(n),p=this.ticks(n),h=n.scaleMode??(n.logScale?`logarithmic`:`regular`),g=h===`regular`||h===`logarithmic`?m(p,f):f,_=`500 ${r.font.sizeSmall}px ${r.font.family}`,v=[],y=c?null:this.reservedPrice?.()??null,b=y===null?null:e.k(y,n),x=r.font.sizeSmall/2,S=o.y+x,C=o.y+o.height-x;for(let e of p){let t=u(e);t<S||t>C||b!==null&&Math.abs(t-b)<T||a.some(e=>Math.abs(t-e)<E)||v.push({y:t,text:d(e,n,g,this.locale)})}t.font=_,t.textBaseline=`middle`,t.textAlign=c?`right`:`left`,t.strokeStyle=r.style?.axis.price.line??r.axisLine,t.globalAlpha=.45,t.beginPath();let w=c?-1:1;for(let{y:n}of v)e.y(t,l+w,l+4*w,n+.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,l+8*w,e);c||(this.rows=v.map(e=>e.y))}};function O(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 k(e,t,n,r,i,a){let o=O(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 A(t,n,r,i,a,o){let s=e.g(t,n,r,i,a);if(!(O(o,s.w,s.h)>0)){t.fillRect(s.x,s.y,s.w,s.h);return}k(t,s.x,s.y,s.w,s.h,o),t.fill()}function j(e){let t=Math.abs(e);return t>=1e3?1:t>=1?2:t>=.01?4:6}var ee=16;function te(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 ne(e){let t=re(e);if(!t)return`#ffffff`;let[n,r,i]=t;return(.299*n+.587*r+.114*i)/255>.62?`#10131a`:`#ffffff`}function re(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 ie(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=te(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 ae(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,A(e,n+1,Math.round(a.y-8),t,16,i),e.fillStyle=ne(a.color),e.fillText(a.text,n+5,Math.round(a.y))}e.restore()}}function oe(e,t,n,r,i,a){ae(e,ie(t,i),n,r,a)}function se(e){return{plot:e,plotText:null,panes:new Map}}function ce(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 le=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.A(r);e.b(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 ue(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 de=16,fe=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,A(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=ne(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`)}`}};function pe(e,t,n){let r=e.map(e=>e.y);if(e.length===0)return r;let i=t!==null&&e[t]?t:me(e),a=e.map((e,t)=>t).filter(e=>e!==i),o=e[i].y,s=a.filter(t=>e[t].y<=o).sort((t,n)=>e[n].y-e[t].y),c=a.filter(t=>e[t].y>o).sort((t,n)=>e[t].y-e[n].y),l=r[i]-e[i].above;for(let t of s)r[t]+e[t].below>l&&(r[t]=l-e[t].below),l=r[t]-e[t].above;let u=r[i]+e[i].below;for(let t of c)r[t]-e[t].above<u&&(r[t]=u+e[t].above),u=r[t]+e[t].below;return n?r.map((t,r)=>t!==e[r].y&&(t-e[r].above<n.top||t+e[r].below>n.bottom)?NaN:t):r}function me(e){let t=e.map(e=>e.y),n=(Math.min(...t)+Math.max(...t))/2,r=0;return t.forEach((e,i)=>{Math.abs(e-n)<Math.abs(t[r]-n)&&(r=i)}),r}var he=20,ge=3,_e=8,ve=14,ye=10,be=8,xe=`#000`,Se=2,Ce=4.5;function we(e,n){let r=n?.priceLimits??(n?.background&&Te(n.background)?t.LIGHT_PRICE_LIMITS:t.DARK_PRICE_LIMITS),i=e=>n?.background&&n.text?Oe(e,n.background,n.text):e;return[{price:e.ceiling,color:i(e.colors?.ceiling??r.ceiling),label:`CE`},{price:e.floor,color:i(e.colors?.floor??r.floor),label:`FL`},{price:e.reference,color:i(e.colors?.reference??r.reference),label:`REF`}]}function Te(e){return(0,t.inkOn)(e,`#000000`,`#ffffff`)===`#000000`}var Ee=new Map,De=64;function Oe(e,n,r){let i=`${e}|${n}|${r}`,a=Ee.get(i);return a===void 0&&(Ee.size>=De&&Ee.clear(),a=(0,t.readableOn)(e,n,r,Ce),Ee.set(i,a)),a}function ke(e,t,n){if(!e)return null;let r=e.region(t,{text:!1});return n.every(e=>r.step(e))?e:null}var Ae=20,je=20,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 l(e),this.renderLoop=new u,this.dprManager=new o(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.dprManager.getDeviceSize()),this.renderLoop.markAllDirty(),this.onContainerResize?.(e)});let n=this.dprManager.getContainerSize(),r=this.dprManager.getDpr();this.layerManager.resize(n,r,this.dprManager.getDeviceSize())}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 le,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=se(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.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);let m=this.axisTagPlan(n);n.priceLimits&&this.renderPriceLimits(o,r,i,n.priceLimits,n.formatPrice,m.limits),n.tradeZoneManager?.render(o,r,i),n.drawingRenderer?.render(o,r,i),n.priceLines?.render(o,r,i,a),n.currentPriceLine?.renderLine(o,r,i),n.tradingRenderer?.render(o,r,i),n.signalMarkerManager?.render(o,r,i),n.alertManager?.render(o,r,i);let h=m.fixed,g=n.indicatorValueLabels===!1?[]:this.overlayValueTags(n,h);n.priceAxis?.render(o,r,i,`right`,[...h.map(e=>e.y),...g.map(e=>e.y)]),ae(o,g,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,m.trading),n.priceLines?.renderAxisTags(o,r,i,a,m.quote),n.currentPriceLine?.renderTag(o,r,i),n.timeAxis?.render(o,r,i,a,n.timeAxisY),this.renderPanelAxes(o,n),this.renderDrawingSpans(o,n)}renderDrawingSpans(e,t){if(t.crosshairHandler?.beginSpans?.(),!(t.drawingAxisSpans===!1||!t.drawingRenderer||!t.crosshairHandler))for(let n of t.drawingRenderer.axisSpans(t.viewport))t.crosshairHandler.renderSpan(e,n,t.viewport,t.theme,t.data,t.timeAxisY)}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?ke(t.recorder?.(l,r)??null,o.chartRect,u):null,p=u.length>0&&!f,m=t.recorder?.(l,r)??null,h=m?ce(m,o.chartRect,i,a):se(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()?Ne(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 le,volume:y,background:v,under:f,recorded:m,seriesRevision:n.seriesRevision}),x=b.recorded?h:se(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,Ne(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.drawingRenderer?.renderHover(a,n,r),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),this.renderLegend(a,t),t.renderOverlayPlugins?.(a,`ui`),this.renderPanelHoverValues(a,t)}renderLegend(e,t){if(!t.chartLegend)return;let{viewport:n,theme:r,data:i}=t,a=t.tradingRenderer?.tagRects()??[];if(a.length===0){t.chartLegend.render(e,n,r,i);return}let{x:o,y:s,width:c,height:l}=n.chartRect;e.save();try{for(let t of a)e.beginPath(),e.rect(o,s,c,l),e.rect(t.x,t.y,t.width,t.height),e.clip(`evenodd`);t.chartLegend.render(e,n,r,i)}finally{e.restore()}}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+he,width:n.width,height:n.height-he},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(t,n,r,i){let{theme:a}=n,o=n.indicatorEngine;if(!o||r.length===0)return;let s=`10px ${a.font.family}`,c=this.panelDescriptors(o),l=new Map(n.panels.map(e=>[e.instanceId,e.style]));for(let o of r){let{rect:r,inner:u}=o,d=i.panes.get(o.id),f=l.get(o.id);t.save(),t.beginPath(),t.rect(r.x,r.y,r.width,r.height),t.clip(),d?.background||o.background(t),t.fillStyle=f?.separator??a.style?.panes.separator??a.axisLine;let p=e.v(t,r.y+ge/2,ge);t.fillRect(r.x,p.y-p.width/2,r.width,p.width),t.fillStyle=a.style?.panes.title??a.textSecondary,t.font=s,t.textBaseline=`top`,t.textAlign=`left`;let m=c.get(o.id);m&&n.paneTitles!==!1&&t.fillText(m.descriptor.name,r.x+6,r.y+6),t.save(),t.beginPath(),t.rect(u.x,u.y,u.width,u.height),t.clip(),d?.text?.drawText(t);for(let e of d?d.rest:o.steps)e(t);t.restore(),t.restore()}}axisTagPlan(t){let{viewport:n,data:r}=t,{chartRect:i}=n,a=e=>e>=i.y&&e<=i.y+i.height,o=[],s=t.currentPriceLine?.isVisible()&&t.theme.style?.lastPrice.visible!==!1?t.currentPriceLine.getPrice():null;if(s!=null&&a(e.k(s,n))){let i=t.barCountdown?.isShown(r)?16:0;o.push({y:e.k(s,n),above:ye,below:ye+i,source:`last`,key:0})}for(let i of t.priceLines?.levels(r,n)??[]){let t=e.k(i.price,n);a(t)&&o.push({y:t,above:be,below:be,source:`quote`,key:i.kind})}(t.priceLimits?we(t.priceLimits):[]).forEach(({price:t},r)=>{let i=e.k(t,n);a(i)&&o.push({y:i,above:ve/2,below:ve/2,source:`limit`,key:r})});let c=t.alignAxisLabels!==!1;c&&(t.tradingRenderer?.axisBadgeLines(n,t.theme)??[]).forEach((e,t)=>{o.push({y:e,above:16/2,below:16/2,source:`trading`,key:t})});let l=o.findIndex(e=>e.source===`last`),u={top:i.y,bottom:i.y+i.height},d=c?pe(o,l>=0?l:null,u):o.map(e=>e.y),f={fixed:[],quote:new Map,limits:[],trading:c?[]:void 0};if(o.forEach((e,t)=>{Number.isNaN(d[t])||f.fixed.push({y:d[t]+(e.below-e.above)/2,half:(e.above+e.below)/2}),e.source===`quote`?f.quote.set(e.key,d[t]):e.source===`limit`?f.limits[e.key]=d[t]:e.source===`trading`&&(f.trading[e.key]=d[t])}),!c)for(let e of t.tradingRenderer?.axisTagYs(n,t.theme)??[])a(e)&&f.fixed.push({y:e,half:16/2});return f}overlayValueTags(n,r){let i=n.indicatorEngine?.getLatestOverlayValues();if(!i?.length)return[];let{viewport:a}=n,{chartRect:o}=a,s=n.numberLocale??`en-US`,c=(a.scaleMode===`percentage`||a.scaleMode===`indexedTo100`)&&a.scaleBaseline?e=>d(e,a,2,s):n.formatPrice??(e=>(0,t.formatPrice)(e,2,s));return ie(i.map(t=>({y:e.k(t.value,a),text:c(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`;oe(n,a.map(n=>({y:e.k(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.k(i,r))+.5;e.y(t,a.x,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 c=s.viewport,l=s.rect,{min:u,max:f}=c.priceRange;if(f-u<=0||l.height<=0||c.chartRect.height<_e)continue;let p=l.x+l.width,m=c.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(),e.S(n,p+.5,l.y,l.y+l.height),n.stroke();let _=C(u,f,m.height),v=S(_);n.font=o,n.textBaseline=`middle`,n.textAlign=`left`;for(let t of w(u,f,_)){let r=e.k(t,c);r<m.y||r>m.y+m.height||(n.strokeStyle=h,n.beginPath(),e.y(n,p,p+4,Math.round(r)+.5),n.stroke(),n.fillStyle=g,n.fillText(d(t,c,v,a),p+6,r))}let y=r.indicatorValueLabels===!1?null:[s.instanceId,...s.members??[]].flatMap(e=>r.indicatorEngine?.getLatestValues(e)??[]);y?.length&&oe(n,y.map(n=>({y:e.k(n.value,c),text:c.scaleMode===`percentage`&&c.scaleBaseline?d(n.value,c,2,a):(0,t.formatPrice)(n.value,j(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||!r.crosshairHandler?.drawsLines())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<_e)continue;let l=e.P(i.x,c),u=e.w(Math.max(0,Math.min((r.data?.length??1)-1,Math.round(l))),c),d=ue(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._(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.v(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:c}=r,l=r.numberLocale??`en-US`,u=`${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<_e)continue;let v=h.x+h.width,y=S(C(g,_,m.chartRect.height));if(r.crosshairHandler?.getMode()!==`hidden`&&i.x>=h.x&&i.x<=h.x+h.width&&i.y>=h.y&&i.y<=h.y+h.height){let r=d(e.I(i.y,m),m,y,l);n.font=`bold ${o.font.sizeSmall}px ${o.font.family}`;let a=n.measureText(r).width,c=Math.min(a+Ae,(s.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2),u=ue(o);n.fillStyle=u.labelBackground,A(n,v+1,i.y-je/2,c,je,o),n.fillStyle=u.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 b=Math.max(0,Math.min((c?.length??1)-1,Math.round(e.P(i.x,m)))),x=a.peekOutput(p.instanceId),w=x?.series&&b<x.series.length?x.series[b]:null;if(!w)continue;let T=f?.get(p.instanceId),E=T?.descriptor.plots,D=[];if(E)for(let e of E){let t=w[e.key];t!==void 0&&Number.isFinite(t)&&D.push(`${e.title} ${d(t,m,y,l)}`)}else for(let e in w){let t=w[e];t!==void 0&&D.push(`${e}: ${t.toFixed(y)}`)}if(D.length===0)continue;n.font=u;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,o,s=[]){let{chartRect:c}=r,l=o??(e=>(0,t.priceTagText)(e,r,r.pricePrecision??Se)),u=`bold 9px ${i.font.family}`,d=`10px ${i.font.family}`;we(a,i).forEach(({price:a,color:o,label:f},p)=>{let m=e.k(a,r);if(m<c.y||m>c.y+c.height)return;n.setLineDash([8,4]),n.strokeStyle=o,n.lineWidth=1,n.beginPath(),e.y(n,c.x,c.x+c.width,Math.round(m)+.5),n.stroke(),n.setLineDash([]),n.font=u,n.fillStyle=o,n.textBaseline=`bottom`,n.textAlign=`left`,n.fillText(`${f} ${l(a)}`,c.x+4,m-2);let h=s[p]??m;if(Number.isNaN(h))return;let g=c.x+c.width+1;n.fillStyle=o,A(n,g,h-ve/2,(r.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,ve,i),n.fillStyle=i.background&&i.text?(0,t.inkOn)(o,i.background,i.text):xe,n.font=d,n.textBaseline=`middle`,n.textAlign=`left`,n.fillText(l(a),g+4,h)})}destroy(){this.renderLoop.stop(),this.detachGpu(),this.dprManager.destroy(),this.layerManager.destroy()}};function Ne(e){return{prices:e.priceAxis?.ticks(e.viewport),slots:e.timeAxis?.marks(e.viewport,e.data).map(e=>e.index)}}async function Pe(t){let n=e.n();if(!n)return{gpu:null,reason:`limit`};let r;try{r=await Promise.resolve().then(()=>require(`./WebGLSeriesRenderer-BehGeCwp.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 Fe(e){return(await Pe(e)).gpu}var Ie=.25,Le=.02,Re=1/t.PHI,ze=t.PHI**4,Be=t.CHART_SPACING[t.DEFAULT_CHART_DENSITY].priceMargin,Ve=.2,He=class{state;priceAxisWidth=t.PRICE_AXIS_WIDTH;stateCache=null;dataLength=0;margins={top:Be,bottom:Be};minBarWidth;maxBarWidth;rightMarginBars;freePan=!0;minVisibleBars=3;minBarUnit=Ie;barLayout=`classic`;constructor(e,n,r=2,i=30,a=t.CHART_SPACING[t.DEFAULT_CHART_DENSITY].rightMargin){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,pricePrecision:this.state.pricePrecision,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()}setPricePrecision(e){this.state.pricePrecision=e!==null&&Number.isInteger(e)&&e>=0?e:void 0,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){if(e===this.rightMarginBars)return;let t=this.dataLength>0&&this.isAtEnd();this.rightMarginBars=e,t&&(this.state.offset=this.endOffset(),this.invalidate())}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()}setBarLayout(e){let t=e===`golden`?`golden`:`classic`;if(t===this.barLayout)return;let n=this.dataLength>0&&this.isAtEnd();this.barLayout=t,this.applyUnit(this.dataLength===0?this.openingUnit():this.state.barWidth+this.state.barSpacing),this.clampUnit(),n&&(this.state.offset=this.endOffset(),this.invalidate()),this.clampOffset(),this.updateVisibleRange()}getBarLayout(){return this.barLayout}openingUnit(){return this.barLayout===`golden`?ze:t.DEFAULT_BAR_WIDTH+t.DEFAULT_BAR_SPACING}floorUnit(){return this.barLayout===`golden`?this.minBarWidth/Re: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(Le,Math.min(e,this.floorUnit())):Ie,this.clampUnit(),this.clampOffset(),this.updateVisibleRange(),this.invalidate()}getMinBarUnit(){return this.minBarUnit}maxUnit(){return this.barLayout===`golden`?this.maxBarWidth/Re:this.maxBarWidth+t.DEFAULT_BAR_SPACING}applyUnit(e){let n=this.floorUnit();if(this.barLayout===`golden`)this.state.barWidth=e*Re,this.state.barSpacing=e-this.state.barWidth;else 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<Ve||(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)(this.barLayout===`classic`&&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 Ue(e,n){return(0,t.sliceVisibleData)(e,n.visibleRange.from,n.visibleRange.to)}var We=[`1D`,`5D`,`1M`,`3M`,`6M`,`YTD`,`1Y`,`5Y`,`All`],Ge=864e5,Ke=6e4,qe={"1M":1,"3M":3,"6M":6,"1Y":12,"5Y":60};function Je(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 Ye(e,n,r=0){if(e===`All`)return null;if(e===`1D`)return n-Ge;if(e===`5D`)return n-5*Ge;let i=n+(0,t.offsetAt)(r,n)*Ke;return e===`YTD`?(0,t.wallToUtc)(Date.UTC(new Date(i).getUTCFullYear(),0,1),r):(0,t.wallToUtc)(Je(i,-(qe[e]??0)),r)}function Xe(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 Ze=64;function Qe(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(Ze,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=Xe(s,c,e=>i(a+e));for(let e=0;e<l.length;e++)l[e]+=a;return l}var $e=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.A(r);t.beginPath(),t.strokeStyle=i.lineColor,t.lineWidth=i.style?.series.lineWidth??2,t.lineJoin=`round`;let f=Qe(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()}},et=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.A(r),f=d(l),p=Qe(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()}},tt=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.A(r);e.b(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)})}},nt=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.A(r);e.b(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])}})}},rt=32/255,it=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.A(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*=rt,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*=rt,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}},at=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.A(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)}},ot=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.A(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()}},st=3,ct=.8,lt=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.A(r),_=Math.abs(this.boxSize*m);if(_<st){this.renderSolid(t,n,a,o,h,g,Math.max(1,s*ct),i);return}let v=Math.min(c*ct,_*ct)*.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));for(let e=c;e<=l;e++){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)}renderSolid(e,t,n,r,i,a,o,s){for(let c=Math.max(0,n);c<=r&&c<t.length;c++){let n=t[c],r=a(n.high),l=a(n.low);e.fillStyle=n.close>=n.open?s.candleUp:s.candleDown,e.fillRect(i(c)-o/2,Math.min(r,l),o,Math.max(1,Math.abs(l-r)))}}},ut=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.A(r);e.b(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)})}},dt=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.A(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=ft(i.candleUp,.55),t.fill(p),t.fillStyle=ft(i.candleDown,.55),t.fill(m),t.lineWidth=1,t.strokeStyle=i.candleUpWick,t.stroke(h),t.strokeStyle=i.candleDownWick,t.stroke(g)}};function ft(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 pt=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.A(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()}},mt=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.A(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()}},ht=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.A(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)}},gt=28,_t=3,vt=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.A(i),p=Math.max(1,Math.round(i.barWidth*.6)),m=i.barWidth>=gt,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-_t),n.textBaseline=`top`,n.fillText(g(c?t.low:t.high),i,s+_t)}}},yt=t.PHI**-4.5,bt=class{visible=!0;heightRatio=yt;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.b(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)})}},xt=.32;function St(e){return Number.isFinite(e)?xt*Math.min(1,Math.max(0,e)):xt}var Ct=class{visible=!1;buckets=48;widthRatio=.18;opacity=xt;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.A(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.O(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()}},wt={session:`1d`,week:`1w`,month:`1M`},Tt=6e4,Et=864e5,Dt={},Ot=1.5;function kt(e){return e===`session`||e===`week`||e===`month`}function At(e,n,r){let i=kt(n)?wt[n]:n,a=(0,t.barTimeUnit)(e),o=r&&!(0,t.isUtcTimeZone)(r)&&(0,t.timeframeFollowsDays)(i)&&(0,t.isValidTimeZone)(r)?r:null,s=o===null?Dt:{timeZone:o},c=o!==null&&(0,t.barsAreDaily)(e)===!0,l=(0,t.timeframeToMs)(i),u=(Number.isFinite(l)?l:Tt)*Ot,d=NaN,f=NaN,p=NaN,m=!1;return e=>{let n=e*a,r=c&&n%Et===0;if(n>=d&&n<f&&r===m)return p;m=r;let l=r?Dt:s;return d=(0,t.timeframeBucketStart)(n,i,l),f=(0,t.timeframeBucketStart)(d+u,i,l),p=o===null||r?d:(0,t.timeframeBucketStart)(n+(0,t.zoneOffsetMinutes)(o,n)*Tt,i),p}}function jt(e,t,n){let r=e[t]?.[n];return e[t-1]?.[n]!==r&&e[t+1]?.[n]!==r}function Mt(e,t,n,r=`session`){return e[t]?.[r]===e[n]?.[r]?!1:!(jt(e,t,r)&&jt(e,n,r))}function Nt(e,t){return e<0?0:e>t?t:e}function Pt(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=Nt(Math.floor((e-t)/o),i-1),l=Nt(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 Ft(e){let t=(e%52+52)%52;return t<26?String.fromCharCode(65+t):String.fromCharCode(97+t-26)}function It(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 Lt(e,t,n,r={},i){if(e.length===0||n-t<=0)return[];let a=[],o=At(e,`session`,i),s=0,c=o(e[0].time),l=(i,o,s)=>{let c=Pt(e.slice(i,o+1),t,n,r);c&&a.push({startIndex:i,endIndex:o,startTime:s,profile:c})};for(let t=1;t<e.length;t++){let n=o(e[t].time);n!==c&&(l(s,t-1,c),s=t,c=n)}return l(s,e.length-1,c),a}var Rt=class{visible=!1;buckets=48;widthRatio=.18;opacity=.32;valueAreaPct=.7;highlightPoC=!0;showStats=!0;splitBySession=!1;letters=!1;lastStats=null;exchangeZone=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}getConfig(){let{buckets:e,widthRatio:t,opacity:n,valueAreaPct:r,highlightPoC:i,showStats:a,splitBySession:o,letters:s}=this;return{buckets:e,widthRatio:t,opacity:n,valueAreaPct:r,highlightPoC:i,showStats:a,splitBySession:o,letters:s}}setExchangeTimeZone(e){this.exchangeZone=e}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=Pt(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.A(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.O(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,r,i),t.restore()}renderSplit(t,n,r,i,a){let{chartRect:o,priceRange:s}=i,c=Lt(n,s.min,s.max,{buckets:this.buckets,valueAreaPct:this.valueAreaPct},this.exchangeZone);if(c.length===0)return;let l=e.A(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.w(r+d.startIndex,i)-u,h=e.w(r+d.endIndex,i)+u,g=Math.max(2,h-m),_=1/c.maxCount,v=this.letters&&p>=7,y=v?It(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.O(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(Ft(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.O(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,n,r,i,a,o,s,c){let l=s.pricePrecision??zt(i),u=e=>(0,t.priceTagText)(e,s,l),d=[[`POC`,u(i),c.text],[`VAH`,u(a),c.candleUp],[`VAL`,u(o),c.candleUp]];e.globalAlpha=1,e.font=`600 10px ${c.font.family}`,e.textBaseline=`middle`;let f=0;for(let[,t]of d)f=Math.max(f,e.measureText(t).width);let p=38+f,m=6+d.length*14;e.fillStyle=c.background,e.globalAlpha=.82,Bt(e,n,r,p,m,4),e.fill(),e.globalAlpha=1,d.forEach(([t,i,a],o)=>{let s=r+6/2+14/2+o*14;e.fillStyle=a,e.textAlign=`left`,e.fillText(t,n+6,s),e.fillStyle=c.text,e.textAlign=`right`,e.fillText(i,n+p-6,s)}),e.textAlign=`left`}};function zt(e){let t=Math.abs(e);return t>=1e3?2:t>=1?4:6}function Bt(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 Vt(e,t,n){let r=At(e,t===`day`?`session`:`week`,n),i=[];for(let t of e){let e=r(t.time),n=i[i.length-1];n&&n.key===e?(n.high=Math.max(n.high,t.high),n.low=Math.min(n.low,t.low),n.close=t.close):i.push({key:e,open:t.open,high:t.high,low:t.low,close:t.close})}return i}function Ht(e,t=`day`,n){let r=Vt(e,t,n);if(r.length<2)return[];let i=r[r.length-2],a=r[r.length-1],o=t===`day`?`D`:`W`;return[{id:`p${o}h`,label:`P${o}H`,price:i.high},{id:`p${o}c`,label:`P${o}C`,price:i.close},{id:`p${o}l`,label:`P${o}L`,price:i.low},{id:`open`,label:t===`day`?`Day Open`:`Week Open`,price:a.open}]}var Ut=class{visible=!1;period=`day`;exchangeZone=null;setVisible(e){this.visible=e}isVisible(){return this.visible}setPeriod(e){this.period=e}getPeriod(){return this.period}setExchangeTimeZone(e){this.exchangeZone=e}render(t,n,r,i){if(!this.visible||n.length===0)return;let a=Ht(n,this.period,this.exchangeZone);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.k(n.price,r);if(a<s||a>c)continue;let l=Wt(n,i);t.strokeStyle=l,t.globalAlpha=.7,t.lineWidth=1,t.setLineDash([5,4]),t.beginPath(),e.y(t,o.x,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,A(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 Wt(e,t){return e.id.endsWith(`h`)?t.candleUp:e.id.endsWith(`l`)?t.candleDown:t.textSecondary}function Gt(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 Kt(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 qt=4,Jt=10,Yt=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}getConfig(){return{left:this.left,right:this.right,showLabels:this.showLabels,structureLabels:this.structureLabels}}render(t,n,r,i){if(!this.visible||n.length===0)return;let a=Kt(n,this.left,this.right);if(a.length===0)return;let o=this.structureLabels?Gt(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.w(n.index,r),o=e.k(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?Xt(n.price,r):null;p&&(t.textBaseline=d?`bottom`:`top`,t.fillText(p,a,d?f-5-1:f+5+1))}t.restore()}};function Xt(e,n){return(0,t.priceTagText)(e,n,n.pricePrecision??Zt(e))}function Zt(e){let t=Math.abs(e);return t>=1?2:t===0?qt-1:Math.min(Jt,qt-1-Math.floor(Math.log10(t)))}function Qt(e){if(e.length<2)return 0;let t=e.map(e=>e.price).sort((e,t)=>e-t),n=[];for(let e=1;e<t.length;e++){let r=t[e]-t[e-1];r>0&&n.push(r)}return n.length===0?0:(n.sort((e,t)=>e-t),n[Math.floor(n.length/2)])}var $t=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})),bidStep:Qt(t.bids),askStep:Qt(t.asks)},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}getCapacity(){return this.capacity}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}},en=class{buffer=new $t(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)}getConfig(){return{opacity:this.opacity,capacity:this.buffer.getCapacity()}}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.M(a.time,n);if(i<l-c||i>u+c)continue;let s=i-c/2;this.drawSide(t,a.bids,a.bidStep??Qt(a.bids),r.candleUp,s,c,n,o,d,f),this.drawSide(t,a.asks,a.askStep??Qt(a.asks),r.candleDown,s,c,n,o,d,f)}t.restore()}drawSide(t,n,r,i,a,o,s,c,l,u){if(n.length===0)return;let d=tn(Math.min(n[0].price,n[n.length-1].price),r,s);t.fillStyle=i;for(let r of n){let n=e.k(r.price,s);n<l-d||n>u+d||(t.globalAlpha=Math.min(1,Math.sqrt(r.volume*c))*this.opacity,t.fillRect(a,n-d/2,o,d))}t.globalAlpha=1}};function tn(t,n,r){if(!(n>0))return 3;let i=Math.abs(e.k(t,r)-e.k(t+n,r));return Math.max(2,Math.min(i,12))}var nn=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}lastCloseAt(e,n,r){let i=this.closeAt(e,n,r);if(i!==void 0)return{close:i,stale:!1};let a=this.series.get(e);if(!(!a||(0,t.normalizeBarTime)(n,r)<a.times[0]))return{close:a.bars[a.bars.length-1].close,stale:!0}}},rn=11,an={mark:11,label:12,letter:13,text:14},on={mark:0,label:1,letter:2,text:3},sn=12,cn=.12,ln=`#131416`,un=`#1fa874`,dn=`#e8505b`,fn=`#e6e3dc`;function pn(e){let n=e?.font,r=n?.sizeSmall??rn,i=e=>Math.max(an[e],r+on[e]),a=e?.background??ln;return{sizes:{mark:i(`mark`),label:i(`label`),letter:i(`letter`),text:i(`text`)},figures:n?.family||t.DEFAULT_FONT_FAMILY,prose:n?.textFamily||t.SANS_FONT_FAMILY,background:a,ink:e?.text??fn,handleFill:e?.style?.drawings?.handle??a,scale:Math.max(1,r/rn),rise:e?.style?.trading?.profit??un,fall:e?.style?.trading?.loss??dn}}var mn=pn(null),hn=null,gn=!1;function _n(){gn=!0,hn=null}function vn(e,t,n,r){gn&&(hn=hn?{x0:Math.min(hn.x0,e),y0:Math.min(hn.y0,t),x1:Math.max(hn.x1,e+n),y1:Math.max(hn.y1,t+r)}:{x0:e,y0:t,x1:e+n,y1:t+r})}function yn(){gn=!1;let e=hn;return hn=null,e?{x:e.x0,y:e.y0,width:e.x1-e.x0,height:e.y1-e.y0}:null}var bn=null;function xn(e){bn=e}var Sn=4;function Cn(e,t,n,r){if(!bn)return{left:e,top:t};let i=bn.x+bn.width-Sn-n,a=bn.y+bn.height-Sn-r;return{left:Math.max(bn.x+Sn,Math.min(e,i)),top:Math.max(bn.y+Sn,Math.min(t,a))}}function wn(e){mn=pn(e)}function M(){return mn}function N(e,t={}){return`${t.weight?`${t.weight} `:``}${mn.sizes[e]}px ${t.prose?mn.prose:mn.figures}`}function Tn(e,t=`text`){let n=e.fontSize;return n&&n!==sn?n:mn.sizes[t]}function En(e){return Dn+On*Math.max(1,Number.isFinite(e)?e:1)}var Dn=9,On=3,kn=new Map,An=64,jn=4.5;function Mn(e){let n=`${e}|${mn.background}|${mn.ink}`,r=kn.get(n);return r===void 0&&(kn.size>=An&&kn.clear(),r=(0,t.readableOn)(e,mn.background,mn.ink,jn),kn.set(n,r)),r}function Nn(e,t=mn.scale){return Math.min(In,Pn+Fn*(Math.max(1,Number.isFinite(e)?e:1)-1))*t}var Pn=4.5,Fn=.75,In=8;function Ln(e,t){let n=Math.max(1,t);switch(e){case`dashed`:return[Math.max(5,3*n),Math.max(4,2*n)];case`dotted`:return[0,Math.max(3,2.5*n)];case`guide`:return[3,3];default:return[]}}function P(e,n=cn){return(0,t.ownFillColor)(e)??(0,t.withAlpha)(e.color,n)}function Rn(e){return(0,t.ownFillColor)(e)!==void 0}function zn(e){return(0,t.inkOn)(e,`#0b0d10`,`#ffffff`)}var Bn=`rgba(12, 16, 22, 0.85)`,Vn=Bn;function Hn(e){Vn=e?.background??Bn,wn(e)}function Un(){return M().handleFill}function F(e,t,n,r,i=Vn){e.save(),e.lineJoin=`round`,e.lineWidth=Wn,e.strokeStyle=i,e.setLineDash([]),e.strokeText(t,n,r),e.restore(),e.fillText(t,n,r)}var Wn=4,Gn=()=>M().sizes.label,Kn=4,qn=3,Jn=[],Yn=[],Xn=!1;function Zn(e){Jn=e??[],Yn=[],Xn=e!==null}function Qn(e,t,n,r){Xn&&Yn.push({x:e,y:t,width:n-e,height:r-t})}function $n(e,t,n,r,i){return r>e.x&&t<e.x+e.width&&i>e.y&&n<e.y+e.height}function er(e,t,n,r){return Jn.some(i=>$n(i,e,t,n,r))}function tr(e,t,n,r){return er(e,t,n,r)||Yn.some(i=>$n(i,e,t,n,r))}function nr(e,t,n){let r=n;for(let n of[...Jn,...Yn])t>n.x&&e<n.x+n.width&&(r=Math.max(r,n.y+n.height));return r}function rr(e,t){let n=null;for(let r of[...Jn,...Yn])t>r.y&&e<r.y+r.height&&(n=Math.max(n??r.x+r.width,r.x+r.width));return n}var ir=()=>2*Gn();function ar(e,t,n,r,i=n,a=-1/0){e.font=N(`label`);let o=e.measureText(t).width,s=or(n,i,r,o,a);e.textAlign=s.align,e.textBaseline=s.baseline,F(e,t,s.x,s.y),Qn(s.left,s.top,s.left+o,s.top+Gn())}function or(e,t,n,r,i){let a=e+Kn,o=t-Kn-r,s=o>a?[a,o]:[a],c={top:n-qn-Gn(),bottom:n-qn},l={top:n+qn,bottom:n+qn+Gn()};for(let e of[c,l])if(!(e.top<i)){for(let t of s)if(!tr(t,e.top,t+r,e.bottom)){let n=e===c;return{x:t,y:n?e.bottom:e.top,align:`left`,baseline:n?`bottom`:`top`,left:t,top:e.top}}}let u=s.map(e=>({l:e,top:nr(e,e+r,n)+qn})),d=u.find(e=>e.top-n<=ir());if(d)return{x:d.l,y:d.top,align:`left`,baseline:`top`,left:d.l,top:d.top};let f=t-Kn,p={left:f-r,top:n-Gn()/2};if(!tr(p.left,p.top,f,p.top+Gn()))return{x:f,y:n,align:`right`,baseline:`middle`,...p};let m=u.reduce((e,t)=>t.top<e.top?t:e);return{x:m.l,y:m.top,align:`left`,baseline:`top`,left:m.l,top:m.top}}function sr(){return Math.round(M().sizes.label*cr)}var cr=1.5,lr=4,ur=6;function dr(e,t){return Math.ceil(e.measureText(t).width)+2*ur}function fr(e,t,n,r,i,a=zn(i)){let o=dr(e,t),s=sr(),c=Math.round(r-s/2);return vn(Math.round(n),c,o,s),e.fillStyle=i,e.beginPath(),typeof e.roundRect==`function`?e.roundRect(Math.round(n),c,o,s,lr):e.rect(Math.round(n),c,o,s),e.fill(),e.fillStyle=a,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(t,Math.round(n)+ur,c+s/2+.5),o}var pr=1.35,mr=8,hr=5,gr=4,_r=.94,vr=.16,yr=6e4,br=60*yr,xr=24*br;function Sr(e){let t=Math.abs(e);return t>=10||t===0?2:t>=1?4:Math.min(10,Math.ceil(-Math.log10(t))+3)}var Cr=2;function wr(e,n=e,r){return r?(0,t.priceTagText)(e,r,r.pricePrecision??Sr(n)):e.toFixed(Sr(n))}function Tr(e,n){return n?(0,t.formatPrice)(e,Cr,n.numberLocale??`en-US`):e.toFixed(Cr)}function Er(e,t,n){let r=t-e,i=e===0?0:r/e*100,a=r>=0?`+`:``;return`${a}${wr(r,e,n)} (${a}${Tr(i,n)}%)`}function Dr(e){let t=Math.abs(e);if(t<br)return`${Math.round(t/yr)}m`;if(t<xr){let e=Math.floor(t/br),n=Math.round((t-e*br)/yr);return n>0?`${e}h ${n}m`:`${e}h`}let n=Math.floor(t/xr),r=Math.round((t-n*xr)/br);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 Or(e){return!!e.data&&e.data.length>0}function kr(t,n,r,i){let a=e.j(t.anchors[n].time,i),o=e.j(t.anchors[r].time,i);return Math.round(Math.abs(o-a))}function Ar(e,t,n,r){return Or(r)?Dr(e.anchors[n].time-e.anchors[t].time):null}function jr(e,t,n,r,i=`center`,a=!0){let o=M();e.font=N(`label`);let s=Math.round(o.sizes.label*pr),c=0;for(let n of t)c=Math.max(c,e.measureText(n).width);let l=Math.ceil(c+mr*2),u=t.length*s+hr*2,d=Cn(i===`left`?n:i===`right`?n-l:n-l/2,a?r-u:r,l,u),f=Math.round(d.left),p=Math.round(d.top);Mr(e,f,p,l,u),e.fillStyle=o.ink,e.textAlign=`left`,e.textBaseline=`top`;for(let n=0;n<t.length;n++)e.fillText(t[n],f+mr,p+hr+n*s+(s-o.sizes.label)/2);return{x:f,y:p,width:l,height:u}}function Mr(e,n,r,i,a){let o=M(),s=Math.round(n),c=Math.round(r),l=Math.round(i),u=Math.round(a);vn(s,c,l,u),e.beginPath(),typeof e.roundRect==`function`?e.roundRect(s+.5,c+.5,l-1,u-1,gr):e.rect(s+.5,c+.5,l-1,u-1),e.fillStyle=(0,t.withAlpha)(o.background,_r),e.fill(),e.strokeStyle=(0,t.withAlpha)(o.ink,vr),e.lineWidth=1,e.setLineDash([]),e.stroke()}function Nr(e,t){return e.find(e=>!er(e.left,e.top,e.right,e.bottom)&&t.every(t=>e.right<=t.left||t.right<=e.left||e.bottom<=t.top||t.bottom<=e.top))??null}function Pr(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 Fr=4,Ir=10,Lr=3,Rr=14,zr=8,Br=2,Vr=3,Hr=4,Ur=2,Wr=(e,t)=>e.left<t.right&&t.left<e.right&&e.top<t.bottom&&t.top<e.bottom,Gr=class{symbols=new Map;mode=`percent`;store=new nn;aligned=new Map;reservedLevels=()=>[];setReservedLevels(e){this.reservedLevels=e}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();let a=[];for(let r of this.symbols.values()){if(!r.visible||r.data.length===0)continue;let i=this.renderSymbol(e,r,t,n);i&&a.push({sym:r,...i})}this.renderLabels(e,a,n,r),e.restore()}renderLabels(e,t,n,r){if(t.length===0)return;e.font=`bold ${Ir}px sans-serif`,e.textBaseline=`middle`,e.textAlign=`right`;let i=this.reservedBoxes(n);for(let a of t){let o=zr+Vr+e.measureText(a.sym.label).width+2*Lr,s=this.placeLabel(a,o,i,t,n.chartRect);i.push(s),this.drawLabel(e,a.sym,s,r)}}drawLabel(e,t,n,r){let i=(n.top+n.bottom)/2,a=n.left+Lr;e.strokeStyle=t.color,e.lineWidth=Br,e.beginPath(),e.moveTo(a,i),e.lineTo(a+zr,i),e.stroke(),e.fillStyle=r.text,F(e,t.label,n.right-Lr,i,r.background)}placeLabel(e,t,n,r,i){let a=e.x-Fr,o=e=>({left:a-t,top:e,right:a,bottom:e+Rr}),s=e.y-Fr-Rr,c=e.y+Fr,l=Array.from({length:Hr},(e,t)=>[o(s-t*Rr),o(c+t*Rr)]).flat(),u=i.y+i.height,d=e=>e.top>=i.y&&e.bottom<=u&&!n.some(t=>Wr(t,e)),f=t=>{let n=(t.top+t.bottom)/2,i=t=>Math.hypot(t.x-e.x,t.y-n);return r.every(t=>t===e||i(t)>i(e))};return l.find(e=>d(e)&&f(e))??l.find(d)??o(Math.max(i.y,Math.min(s,u-Rr)))}reservedBoxes(t){let{chartRect:n}=t;return this.reservedLevels().map(r=>{let i=e.k(r,t)-Ur;return{left:n.x,top:i-Rr,right:n.x+n.width,bottom:i}})}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}anchor(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=n.scaleBaseline||t[i]?.close||t[o].close;return{closes:r,base:o,to:a,mainBase:s,symBase:r[o]}}line(e,t,n){let r=this.anchor(e,t,n);if(!r)return null;let{closes:i,mainBase:a,symBase:o}=r,s=this.mode===`percent`;return{from:r.base,to:r.to,priceAt:e=>{let t=i[e];return Number.isFinite(t)?s?t/o*a:t:null}}}valuesAt(e,n,r){let i=e[r]?.time,a=(0,t.barTimeUnit)(e);return this.getSymbols().map(t=>{let r=i===void 0?void 0:this.store.lastCloseAt(t.id,i,a),o=r&&n?this.anchor(t,e,n)?.symBase:void 0,s=r?.close??null;return{id:t.id,label:t.label,color:t.color,visible:t.visible,close:s,change:s!==null&&o?(s/o-1)*100:null,stale:r?.stale??!1}})}renderSymbol(t,n,r,i){let a=this.line(n,r,i);if(!a)return null;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.w(n,i),l=e.k(r,i);o===0?t.moveTo(c,l):t.lineTo(c,l),s={x:c,y:l},o++}return t.stroke(),s}};function Kr(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}var qr=1e5,Jr=[1,2,5],Yr=15;function Xr(e,t){if(t===0)return e;let n=Jr[t%Jr.length],r=Math.floor(t/Jr.length),i=n*10**r;if(Number.isFinite(i))return Number((e*i).toPrecision(Yr));let[a,o]=e.toExponential().split(`e`);return Number(`${(Number(a)*n).toPrecision(Yr)}e${Number(o)+r}`)}function Zr(e,t,n){return e===t-1?n+qr:qr}var Qr=class{reached=null;clear(){this.reached=null}startStep(e,t,n){let r=this.reached;if(!r||r.kind!==e||r.asked!==t||n.length<r.length||n[0].time!==r.first)return 0;let i=n[r.length-1];return i.high>=r.high&&i.low<=r.low?r.step:0}keep(e,t,n,r){let i=r[r.length-1];this.reached=i?{kind:e,asked:t,step:n,first:r[0].time,length:r.length,high:i.high,low:i.low}:null}};function $r(e,t,n,r,i){let a=i(e?.startStep(t,n,r)??0);return e?.keep(t,n,a.step,r),a}function ei(e,t,n=0){return ni(e,t,()=>({bars:[],size:1/0,step:0}),n)}function ti(e,t,n=0){return ni(e,t,()=>({bars:ri(e,t,!1)??[],size:e,step:0}),n)}function ni(e,t,n,r){let i=Xr(e,r),a=ri(i,t,!0);if(a)return{bars:a,size:i,step:r};let o=ii(e,e=>t(e,!0),r),s=Number.isFinite(o)?Xr(e,o):1/0,c=Number.isFinite(s)?ri(s,t,!0):null;return c?{bars:c,size:s,step:o}:n()}function ri(e,t,n){let r=[];return t(e,n,e=>{r.push(e)})?r:null}function ii(e,t,n){if(!(e>0))return 1/0;let r=n=>{let r=Xr(e,n);return r===1/0||t(r)};if(r(n+1))return n+1;if(!t(Number.MAX_VALUE))return 1/0;let i=n+1,a=n+2;for(;!r(a);)i=a,a=n+2*(a-n);for(;a-i>1;){let e=Math.floor((i+a)/2);r(e)?a=e:i=e}return a}var ai=new WeakMap,oi=new WeakMap;function si(e,t){return ai.set(e,t),e}function ci(e){let t=e[e.length-1];if(!t||!ai.has(t))return e;let n=oi.get(e);if(!n){let t=ai.get(e[0])??e[0].time;n=e.map(e=>(t=ai.get(e)??t,{time:t})),oi.set(e,n)}return n}function li(e,t,n){if(e.length===0)return[];let r=ui(e,t),i=(t,n,r)=>di(e,t,n,r);return $r(n,`renko`,r,e,e=>ei(r,i,e)).bars}function ui(e,t){let n=t.useATR&&e.length>2?pi(e,t.atrPeriod??14):t.brickSize;return n>0?n:Math.abs(e[e.length-1].close)/100||1}function di(e,t,n,r){let i=e.findIndex(e=>Number.isFinite(e.close));if(i<0)return!0;let a=e[0].time,o=Math.round(e[i].close/t)*t,s=0;for(let c=i+1;c<e.length;c++){let{close:i,volume:l}=e[c],u=i-o,d=Math.floor(Math.abs(u)/t);if(!Number.isFinite(i)||!(d>=1))continue;if(n&&s+d>Zr(c,e.length,s))return!1;let f=u>0?1:-1;for(let n=0;n<d;n++){let i=o;o+=f*t,r?.(si(fi(a+s+n,i,o,l/d),e[c].time))}s+=d}return!0}function fi(e,t,n,r){return{time:e,open:t,high:Math.max(t,n),low:Math.min(t,n),close:n,volume:r}}function pi(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 mi(e,t=3){if(e.length===0)return[];let n=[],r=0;n.push(si({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},e[0].time));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(si({time:r++,open:o.close,high:a,low:o.close,close:a,volume:e[i].volume},e[i].time)):!s&&a<o.close||s&&a<u?n.push(si({time:r++,open:o.close,high:o.close,low:a,close:a,volume:e[i].volume},e[i].time)):!s&&a>l&&n.push(si({time:r++,open:o.close,high:a,low:o.close,close:a,volume:e[i].volume},e[i].time))}return n}function hi(e,t=4,n=`percent`,r){if(e.length<2)return e.slice();let i=(t,r,i)=>gi(e,t,n,r,i);return $r(r,`kagi:${n}`,t,e,e=>ti(t,i,e)).bars}function gi(e,t,n,r,i){let a=e[1].close>=e[0].close?1:-1,o=e[0].close,s=e[0].close,c=e[0].close,l=0;for(let u=1;u<e.length;u++){let d=e[u].close,f=n===`price`?t:t/100*c;if(a===1&&d>o&&(o=d),a===-1&&d<s&&(s=d),a===1?o-d>=f:d-s>=f){if(r&&l+1>Zr(u,e.length,l))return!1;i?.(si(_i(l,c,a===1?o:s,e[u].volume),e[u].time)),l++,c=a===1?o:s,a=-a,o=d,s=d}}return i?.(si(_i(l,c,a===1?o:s,0),e[e.length-1].time)),!0}function _i(e,t,n,r){return{time:e,open:t,high:Math.max(t,n),low:Math.min(t,n),close:n,volume:r}}function vi(e,t,n=3,r){return yi(e,t,n,r).columns}function yi(e,t,n=3,r){if(e.length===0||!(t>0))return{columns:[],boxSize:t};let i=(t,r,i)=>bi(e,t,n,r,i),{bars:a,size:o}=$r(r,`pointAndFigure:${n}`,t,e,e=>ti(t,i,e));return{columns:a,boxSize:o}}function bi(e,t,n,r,i){let a=1,o=0,s=e[0].close,c=Math.round(s/t)*t;if(xi(s,c))return!1;let l=c,u=c,d=e[0].volume,f=t*n;for(let n=1;n<e.length;n++){let s=e[n].close,c=Math.round(s/t)*t;if(xi(s,c))return!1;let p=!1;if(a===1?c>l?l=c:p=l-c>=f:c<u?u=c:p=c-u>=f,!p){d+=e[n].volume;continue}if(r&&o+1>Zr(n,e.length,o))return!1;i?.(si(Si(o,a===1,u,l,d),e[n].time)),d=e[n].volume,o++,a===1?(u=c,l-=t):(l=c,u+=t),a=-a}return i?.(si(Si(o,a===1,u,l,d),e[e.length-1].time)),!0}function xi(e,t){return Number.isFinite(e)&&!Number.isFinite(t)}function Si(e,t,n,r,i){return{time:e,open:t?n:r,high:r,low:n,close:t?r:n,volume:i}}var Ci=15,wi=`rangeBars`,Ti=3,Ei=4,Di=64,Oi=2;function ki(e){let t=0;for(let n of e){let e=Math.abs(n.high),r=Math.abs(n.low);e>t&&e!==1/0&&(t=e),r>t&&r!==1/0&&(t=r)}return t}function Ai(e,t){let n=Math.max(e,t),r=Math.floor(Math.log10(n))+1,i=Number.isFinite(n)?Ci-r:0,a=10**-i;if(i<=0)return{clean:e=>e,unit:a,half:0};let o=10**i;return{clean:e=>Math.round(e*o)/o,unit:a,half:a/2}}function ji(e,t){let n=-1/0,r=1/0;for(let i of[t,e.open,e.high,e.low,e.close])Number.isFinite(i)&&(n=Math.max(n,i),r=Math.min(r,i));return n>r?n-r:0}function Mi(e){let t=0,n=e[0].open;for(let r=0;r<e.length-1;r++)t+=ji(e[r],n),n=e[r].close;return{distance:t,bars:e.length-1,lastSpan:ji(e[e.length-1],n)}}function Ni(e,t,n){if(t<Oi*n)return!1;let r=t+n,i=(e.distance-e.bars*n)/r-e.bars,a=(e.lastSpan-n)/r-1;return Math.max(i,a)>qr+1}function Pi(e){let t=new Float64Array(e.length*2);return t.set(e),t}function Fi(e,t,n,r){let i=r/(n-t);for(let r=t;r<n;r++)e[r*Ei+2]+=i}function Ii(e,t,n,r){let i=Array(t);for(let a=0;a<t;a++){let t=e[a*Ei],o=e[a*Ei+1],s=t>o;i[a]=si({time:r+a,open:n,high:s?t:o,low:s?o:t,close:t,volume:e[a*Ei+2]},e[a*Ei+3]),n=t}return i}function Li(e,t,n,r){let{clean:i,unit:a,half:o}=n,s=0,c=e[0].open,l=c,u=c,d=c,f=0,p=i(c+t),m=i(c-t);for(let n=0;n<e.length;n++){let h=Zr(n,e.length,s),g=e[n],_=g.close>=g.open,v=g.volume/Ti;for(let e=0;e<=Ti;e++){let n=e===0?g.open:e===1?_?g.low:g.high:e===2?_?g.high:g.low:g.close;if(!Number.isFinite(n))continue;d=n;let y=s;for(;;){let e=n>l&&n>=p-o&&p>u;if(!e&&!(n<u&&n<=m+o&&m<l))break;let d=e?p:m;if(e?d<l-a:d>u+a)return{cells:r,count:s,forming:null};let _=s*Ei;if(_===r.length&&(r=Pi(r)),r[_]=d,r[_+1]=e?u:l,r[_+2]=f,r[_+3]=g.time,++s>h)return{cells:r,count:s,forming:null};c=l=u=d,p=i(d+t),m=i(d-t),f=0}n>l&&(l=n,m=i(n-t)),n<u&&(u=n,p=i(n+t));let b=e===0?0:v;s===y?f+=b:Fi(r,y,s,b)}}let h={time:e[0].time+s,open:c,high:l,low:u,close:d,volume:f};return{cells:r,count:s,forming:si(h,e[e.length-1].time)}}function Ri(e,t,n){if(e.length===0||!(t.rangeSize>0))return[];let r=ki(e),i=new Float64Array(Ei*Math.max(Di,Math.min(e.length,qr))),a=null,o=n?.startStep(wi,t.rangeSize,e)??0;for(let s=o;;s++){let c=Xr(t.rangeSize,s),l=Ai(r,c);if(s>o&&(a??=Mi(e),Ni(a,c,l.unit)))continue;let u=Li(e,c<l.half?1/0:c,l,i);if(i=u.cells,!u.forming)continue;let d=Ii(i,u.count,e[0].open,e[0].time),{forming:f}=u;return t.includeForming&&(d.length===0||f.high-f.low>l.half)&&d.push(f),n?.keep(wi,t.rangeSize,s,e),d}}function zi(e){return e.barWidth+e.barSpacing<1}function Bi(e,t,n){return e>1.5*(Math.abs(n-t)+1)}var Vi=3,Hi=class{started=!1;piece=0;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.piece++,this.lastX=e,this.lastY=t)}gap(){this.endPiece(),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.endPiece(),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()}endPiece(){if(!this.dense&&this.piece===1){let e=Math.max(this.width,Vi);this.ctx.moveTo(this.lastX-e,this.lastY),this.ctx.lineTo(this.lastX+e,this.lastY)}this.piece=0}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 Ui(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 Wi=.1;function Gi(e){return e.plots?e.plots.map(e=>e.key):null}function Ki(e,t){return e.tone?e.tone===`sign`?(t[e.key]??0)>=0:t[e.tone.field]===1:!0}function qi(e,t){return t.plots?.[e.key]?.visible!==!1}var Ji=[6,4];function Yi(e,n,r){let i=e.plots?.[n];return{visible:i?.visible!==!1,dash:(0,t.lineDash)(i?.lineStyle??`solid`,Ji,r)}}function Xi(e,t,n){let r=t.colors[e.color]??t.colors[0];return!e.tone||e.downColor===void 0||!n||Ki(e,n)?r:t.colors[e.downColor]??r}function Zi(e,t,n,r){let{lo:i,hi:a}=$i(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*Wi,a+=e*Wi}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 Qi(e,t,n,r){let{lo:i,hi:a}=$i(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)*Wi);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 $i(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 ea(e){return!!e?.some(e=>e.kind===`histogram`)}function ta(n,r,i,a,o,s=[]){let c=r.series;if(!c)return;let l=Math.max(0,i.visibleRange.from),u=Math.min(i.visibleRange.to,c.length-1);if(u<l)return;let d=e.A(i);for(let e of s){let r=(0,t.withAlpha)(a.colors[e.color]??a.colors[0],e.opacity??na);ra(n,c,e.between,l,u,i,d,r)}for(let e=0;e<o.length;e++){let r=o[e];if(!qi(r,a))continue;let s=(e>0?a.lineWidths[e]:void 0)??r.width??a.lineWidths[0]??1.5,f=(0,t.lineDash)(a.plots?.[r.key]?.lineStyle??r.lineStyle??`solid`,Ji,s),p=r.kind??`line`,m=r.breakOn,h=m===void 0?null:(e,t)=>Mt(c,e,t,m),g=n.globalAlpha;r.opacity!==void 0&&(n.globalAlpha=g*r.opacity);let _=r.tone&&r.downColor!==void 0?[!0,!1]:[null];try{for(let e of _){let t=a.colors[r.color]??a.colors[0],o=e===!1?a.colors[r.downColor]??t:t,m=t=>e===null||Ki(r,t)===e;p===`histogram`?ca(n,c,r.key,l,u,i,d,o,m):p===`dots`?sa(n,c,r.key,l,u,i,d,o,m):oa(n,c,r.key,l,u,i,d,o,s,p===`step`,e===null?null:m,f,h)}}finally{n.globalAlpha=g}}}var na=.1;function ra(t,n,r,i,a,o,s,c){let l=a-i+1,u=new Float64Array(l),d=new Float64Array(l),f=new Float64Array(l),p=zi(o),m=0,h=()=>{m>=2&&(p?Ui(t,u,d,f,c,m):ia(t,u,d,f,c,m)),m=0};for(let t=i;t<=a;t++){let i=aa(n[t],r[0]),a=aa(n[t],r[1]);if(i===void 0||a===void 0){h();continue}u[m]=e.w(t,o),d[m]=s(i),f[m]=s(a),m++}h()}function ia(e,t,n,r,i,a){e.beginPath(),e.moveTo(t[0],n[0]);for(let r=1;r<a;r++)e.lineTo(t[r],n[r]);for(let n=a-1;n>=0;n--)e.lineTo(t[n],r[n]);e.closePath(),e.fillStyle=i,e.fill()}function aa(e,t){let n=e?.[t];return n!==void 0&&Number.isFinite(n)?n:void 0}function oa(t,n,r,i,a,o,s,c,l,u,d,f=[],p=null){let m=new Hi(t,c,l,zi(o),f),h=0,g=0,_=!1,v=-1;for(let t=i;t<=a;t++){let i=n[t],a=aa(i,r);if(a===void 0){_=!1,m.gap();continue}_&&p?.(v,t)&&(_=!1,m.gap()),v=t;let c=e.w(t,o),l=s(a);d?_&&d(i)&&(u?(m.segment(h,g,c,g),m.add(c,l)):m.segment(h,g,c,l)):(_&&u&&m.add(c,g),m.add(c,l)),h=c,g=l,_=!0}m.finish()}function sa(t,n,r,i,a,o,s,c,l){let u=Math.max(1.5,o.barWidth*.15),d=zi(o),f=NaN;t.beginPath(),t.fillStyle=c;for(let c=i;c<=a;c++){let i=n[c],a=aa(i,r);if(a===void 0||!l(i))continue;let p=e.w(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 ca(t,n,r,i,a,o,s,c,l){let u=s(0);if(t.beginPath(),t.fillStyle=c,zi(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=aa(i,r);if(a===void 0||!l(i))continue;let s=Math.floor(e.w(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=aa(i,r);if(a===void 0||!l(i))continue;let f=e.w(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 I=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&&ta(e,t,n,r,this.descriptor.plots,this.descriptor.fills)}drawLine(e,t,n,r,i){if(t.length<2||i?.visible===!1)return;let a=new Hi(e,n,r,Bi(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&&Bi(t.length,t[0].x,t[t.length-1].x)){Ui(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.w(c,i),y:e.k(o[n],i)})}return a}};function la(e){return e.config.visible!==!1&&!e.offInterval&&!e.offChartType}function ua(e){let t=Gi(e.plugin.descriptor),n=e.style.plots;return t&&n?t.filter(e=>n[e]?.visible!==!1):t}function da(e,t){return e.plugin.descriptor.placement!==`overlay`||e.config.pane?!1:e.config.scale===`left`==(t===`left`)}function fa(e){let t=e.output?.series,n=e.plugin.descriptor.plots;if(!t||!n||!la(e))return[];let r=t[t.length-1];if(!r)return[];let i=[];for(let t of n){if(!qi(t,e.style))continue;let n=r[t.key];n!==void 0&&Number.isFinite(n)&&i.push({value:n,color:Xi(t,e.style,r)})}return i}function pa(e,t){let n=[];for(let r of e)da(r,t)&&n.push(...fa(r));return n}function ma(e,t,n,r){let i=null;for(let a of e){if(!la(a))continue;let e=a.plugin.descriptor,o={keys:ua(a),scale:e.scale,levels:a.config.levels??e.levels,zero:ea(e.plots)},s=r?Qi(a.output,t,n,o):Zi(a.output,t,n,o);if(s===!1)return null;s&&(i=i?{min:Math.min(i.min,s.min),max:Math.max(i.max,s.max)}:s)}return i}function ha(e,t){let n=[];for(let r of e){if(!la(r))continue;let e=r.output?.series?.[t];if(!e)continue;let i=ua(r)??Object.keys(e);for(let t of i){let r=e[t];typeof r==`number`&&Number.isFinite(r)&&n.push(r)}}return n}function ga(e,t,n){if(n){for(let r=0;r<n.length;r++){let i=t[n[r]];i!==void 0&&isFinite(i)&&(i<e.min&&(e.min=i),i>e.max&&(e.max=i))}return}for(let n in t){let r=t[n];r!==void 0&&isFinite(r)&&(r<e.min&&(e.min=r),r>e.max&&(e.max=r))}}function _a(e,t,n,r){let i=t.output?.series;if(!i)return;let a=ua(t),o=Math.min(r,i.length-1),s=r>=i.length-1?t.output?.meta?.ahead:void 0,c=Array.isArray(s)?s:[];for(let t=Math.max(0,n);t<=o+c.length;t++){let n=t<=o?i[t]:c[t-o-1];n&&ga(e,n,a)}}function va(e,t,n,r){let i={min:1/0,max:-1/0};for(let a of e)!a.output||!la(a)||!da(a,r)||_a(i,a,t,n);return i.min===1/0?null:i}function ya(e,t,n,r){let i=new Set;for(let a of e)a.config.instanceId!==r&&(n===null?t===`overlay`&&a.plugin.descriptor.placement===`overlay`&&!a.config.pane:a.config.instanceId===n||a.config.pane===n)&&i.add(a.style.colors[0]);return i}function ba(e,n,r,i,a){let o=ya(e,r,i,a);for(let t of e)t.config.id===n&&t.config.instanceId!==a&&o.add(t.style.colors[0]);let s=t.TC_SERIES_COLORS.findIndex(e=>!o.has(e));return s>=0?s:o.size%t.TC_SERIES_COLORS.length}function xa(e){let t=e.inputs;if(!t)return null;for(let e in t)if(t[e]?.source)return e;return null}function Sa(e,n){let r=xa(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 Ca(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 wa(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 Ta(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 Ea(e){return{values:new Map,series:Array(e).fill(null)}}var Da=[`ticks`,`seconds`,`minutes`,`hours`,`days`,`weeks`,`months`],Oa={ticks:1e6,seconds:59,minutes:59,hours:24,days:366,weeks:52,months:12},ka={s:`seconds`,m:`minutes`,h:`hours`,d:`days`,w:`weeks`,M:`months`};function Aa(e){let n=(0,t.tickBarCount)(e);if(n!==null)return{unit:`ticks`,count:n};let r=(0,t.parseTimeframe)(e);return r?{unit:ka[r.unit],count:r.count}:null}function ja(e,t){if(!e||!t)return!0;let n=Aa(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]>=Oa[n.unit])}function Ma(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=e,n={};for(let e of Da){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=Oa[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 Na(e){return[...t.TC_SERIES_COLORS.slice(e),...t.TC_SERIES_COLORS.slice(0,e)]}function Pa(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 Fa(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t}]))}function Ia(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t===!1?!1:[t[0],t[1]]]))}var La=new WeakSet,L=class e extends Map{keyBuf=[];valBuf=[];folded=!1;constructor(){super()}static fromAscending(t,n){let r=new e;for(let e=1;e<t.length;e++)if(!(t[e]>t[e-1])){for(let e=0;e<t.length;e++)r.set(t[e],n[e]);return r}return r.keyBuf=t,r.valBuf=n,r}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 R(e,t){let n=new L;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 Ra(e){return e.map(e=>e.close)}function za(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 Ba(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 z(e,t){return Ba(e,t,2/(t+1))}function Va(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 Ha(e,t){return Ba(e,t,1/t)}function Ua(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 Wa(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 Ga(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 Ka(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 qa(e,t=`value`){return e.map(e=>e!==void 0&&Number.isFinite(e)?{[t]:e}:null)}function Ja(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 Ya(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 Xa(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 Za(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 Qa(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 $a=new WeakMap;function eo(e){let t=$a.get(e);return t||$a.set(e,t=Array.from(e)),t}var B=class extends I{times=new WeakMap;workerState(){}adoptWorkerState(e,t,n){this.times.set(e,eo(n))}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}},to=new Set([`compareSymbol`,`compareSymbolPane`,`spread`,`correlation`,`correlationlog`]),no=e=>typeof e.params.symbol==`string`?e.params.symbol.trim():``,ro=class extends B{descriptor={id:`compareSymbol`,name:`Compare Symbol`,placement:`overlay`,defaultConfig:{symbol:``},shortName:`Compare`,plots:[{key:`value`,title:`Close`,color:0}],readsExchangeTimeZone:!1};constructor(e){super(),this.store=e}read(e){return{symbol:no(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}}},io=class extends ro{descriptor={id:`compareSymbolPane`,name:`Compare Symbol (Pane)`,placement:`panel`,defaultConfig:{symbol:``},shortName:`Compare`,plots:[{key:`value`,title:`Close`,color:0}],readsExchangeTimeZone:!1}},ao=class extends B{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`]}},readsExchangeTimeZone:!1};constructor(e){super(),this.store=e}read(e){return{symbol:no(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}}},oo=e=>{let t=Math.round(Number(e.params.length??20));return{symbol:no(e),length:Number.isFinite(t)?Math.max(2,t):20}};function so(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 co={placement:`panel`,defaultConfig:{symbol:``,length:20},inputs:{length:{kind:`int`,min:2}},plots:[{key:`value`,title:`Correlation`,color:0}],scale:{min:-1,max:1},levels:[0],readsExchangeTimeZone:!1},lo=class extends B{descriptor={...co,id:`correlation`,name:`Correlation Coefficient`,shortName:`Correlation`};constructor(e){super(),this.store=e}read(e){return oo(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=so(a,o);return s===null?null:{value:s}}},uo=class extends B{descriptor={...co,id:`correlationlog`,name:`Correlation Log`,shortName:`Correlation Log`};constructor(e){super(),this.store=e}read(e){return oo(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=so(a,o);return c===null?null:{value:c}}};function fo(e){let t=e.length,n={time:new Float64Array(t),open:new Float64Array(t),high:new Float64Array(t),low:new Float64Array(t),close:new Float64Array(t),volume:new Float64Array(t)};for(let r=0;r<t;r++){let t=e[r];n.time[r]=t.time,n.open[r]=t.open,n.high[r]=t.high,n.low[r]=t.low,n.close[r]=t.close,n.volume[r]=t.volume}return n}function po(e){let{time:t,open:n,high:r,low:i,close:a,volume:o}=e,s=Array(t.length);for(let e=0;e<t.length;e++)s[e]={time:t[e],open:n[e],high:r[e],low:i[e],close:a[e],volume:o[e]};return s}function mo(e){let{time:t,open:n,high:r,low:i,close:a,volume:o}=e;return[t,n,r,i,a,o].map(e=>e.buffer)}function ho(e){let t=new Set;for(let n of e)if(n)for(let e in n)t.add(e);return[...t]}function go(e,t){if(e===t)return!0;let n=Object.keys(e);return n.length===Object.keys(t).length?n.every(n=>Object.is(e[n],t[n])):!1}function _o(e,t,n){if(t.length>n.length)return!1;let r=0;for(let i=0;i<t.length;i++){let a=t[i];if(!a)continue;r++;let o=e.values.get(n[i]);if(!o||!go(o,a))return!1}return r===e.values.size}function vo(e,t){let n=e.meta?{meta:e.meta}:{},r=e.series;if(!r)return{present:null,keys:[],columns:[],nans:[],values:new Map(e.values),...n};let i=ho(r),a=new Uint8Array(r.length),o=i.map(()=>new Float64Array(r.length).fill(NaN)),s=i.map(()=>null);for(let e=0;e<r.length;e++){let t=r[e];if(t){a[e]=1;for(let n=0;n<i.length;n++){let a=t[i[n]];a!==void 0&&(o[n][e]=a,Number.isNaN(a)&&((s[n]??=new Uint8Array(r.length))[e]=1))}}}return{present:a,keys:i,columns:o,nans:s,values:_o(e,r,t)?null:new Map(e.values),...n}}function yo(e,t){let n={};for(let r=0;r<e.keys.length;r++){let i=e.columns[r][t];(!Number.isNaN(i)||e.nans[r]?.[t]===1)&&(n[e.keys[r]]=i)}return n}function bo(e,t){let[n,r,i,a]=e,[o,s,c,l]=t;switch(e.length){case 1:return n===`value`?e=>({value:o[e]}):e=>({[n]:o[e]});case 2:return e=>({[n]:o[e],[r]:s[e]});case 3:return e=>({[n]:o[e],[r]:s[e],[i]:c[e]});case 4:return e=>({[n]:o[e],[r]:s[e],[i]:c[e],[a]:l[e]});default:return null}}function xo(e,t){for(let n=0;n<e.length;n++)if(Number.isNaN(e[n][t]))return!1;return!0}var So=class{next=0;series;full;keys=[];points=[];constructor(e,t){this.columns=e,this.time=t,this.series=Array(e.present?.length??0),this.full=bo(e.keys,e.columns)}step(e){let t=this.columns.present;if(!t)return!0;let n=Math.min(t.length,this.next+e),r=this.columns.values===null;for(let e=this.next;e<n;e++){if(t[e]===0){this.series[e]=null;continue}let n=this.full&&xo(this.columns.columns,e)?this.full(e):yo(this.columns,e);this.series[e]=n,r&&(this.keys.push(this.time[e]),this.points.push(n))}return this.next=n,n===t.length}output(){let{columns:e}=this,t=e.meta?{meta:e.meta}:{};return e.present?{values:e.values??L.fromAscending(this.keys,this.points),series:this.series,...t}:{values:e.values??new Map,...t}}};function Co(e,t){let n=new So(e,t);return n.step(1/0),n.output()}function wo(e){let t=e;return typeof t.workerState==`function`&&typeof t.adoptWorkerState==`function`}function To(e){return!!e&&typeof e==`object`&&e.tcPacked===`numbers`}function Eo({values:e,missing:t}){let n=Array.from(e);if(t)for(let e=0;e<n.length;e++)t[e]===1&&(n[e]=void 0);return n}function Do(e){if(To(e))return Eo(e);if(Array.isArray(e))return e.map(Do);if(!e||typeof e!=`object`)return e;let t={};for(let[n,r]of Object.entries(e))t[n]=Do(r);return t}var Oo=5e4;function ko(e){let t=fo(e);return{data:e,columns:t,times:t.time.slice()}}function Ao(e,t,n,r,i,a){let o=0,s=e=>a(o,e),c=e.submit({indicatorId:t.descriptor.id,config:n,...i.kind===`price`?{source:i.source}:{},bars:r.columns,times:r.times},s);return c===null?null:(o=c,{requestId:o,data:r.data,times:r.times,from:1/0})}function jo(e){let{data:t,times:n}=e,r=Math.min(e.from,n.length);return r===0||t.length<r?!1:t[0].time===n[0]&&t[r-1].time===n[r-1]}function Mo(e,t,n,r,i){if(!jo(e))return null;let a=t.output;wo(n)&&n.adoptWorkerState(a,t.state,e.times);let o=Math.min(e.from,e.times.length);return o===e.times.length&&e.data.length===o?a:n.update?.(i(),r,a,o)??null}var No=class{worker=null;jobs=new Map;sharedBars=null;constructor(e){this.host=e}use(e,t){this.settle(),this.worker=e?{client:e,minBars:t.minBars??5e4,onLand:t.onLand??null}:null}computing(e){if(e===void 0)return this.jobs.size>0;if(this.jobs.has(e))return!0;let t=this.host.instance(e);return!!t&&this.jobReadBy(t,this.jobs)!==null}stop(){this.worker?.client.cancel([...this.jobs.values()].map(e=>e.requestId)),this.jobs.clear(),this.worker=null}barsChanged(){this.sharedBars=null}takes(e,t,n){if(!this.worker&&this.jobs.size===0)return!1;let r=e.config.instanceId,i=this.jobs.get(r);return i&&n!==void 0?(i.from=Math.min(i.from,n),i.data=t,!0):(i&&this.drop(r),this.jobReadBy(e,this.jobs)?!0:n===void 0&&this.send(e,t))}drop(e){let t=this.jobs.get(e);t&&(this.jobs.delete(e),this.worker?.client.cancel([t.requestId]))}settle(){if(this.jobs.size===0)return;this.host.runPending();let e=this.jobs;this.jobs=new Map,this.worker?.client.cancel([...e.values()].map(e=>e.requestId));for(let t of this.host.ordered()){let n=e.get(t.config.instanceId)??this.jobReadBy(t,e);n&&this.host.compute(t,n.data,void 0,!0)}this.worker?.onLand?.()}send(e,t){let n=this.worker,{plugin:r,config:i}=e;if(!n?.client.usable||t.length<n.minBars||!La.has(r))return!1;let a=Sa(r.descriptor,i.params);if(a.kind===`line`)return!1;let o=i.instanceId,s=this.barsFor(t),c=Ao(n.client,r,i,s,a,(e,t)=>this.land(o,e,t));return c?(this.jobs.set(o,c),!0):!1}barsFor(e){let t=this.sharedBars;if(t?.data===e&&t.times.length===e.length)return t;let n=ko(e);return this.sharedBars=n,queueMicrotask(()=>{this.sharedBars===n&&(this.sharedBars=null)}),n}jobReadBy(e,t){if(t.size===0)return null;let n=Sa(e.plugin.descriptor,e.config.params),r=new Set;for(;n.kind===`line`&&!r.has(n.instanceId);){let e=t.get(n.instanceId);if(e)return e;r.add(n.instanceId);let i=this.host.instance(n.instanceId);if(!i)return null;n=Sa(i.plugin.descriptor,i.config.params)}return null}land(e,t,n){let r=this.jobs.get(e);if(r?.requestId!==t)return;this.host.runPending();let i=this.host.instance(e);if(this.jobs.get(e)!==r||!i)return;this.jobs.delete(e),this.apply(i,r,n);let a=new Set(this.host.dependents(e));for(let e of this.host.ordered())a.has(e.config.instanceId)&&this.host.compute(e,r.data);this.worker?.onLand?.()}apply(e,t,n){let{plugin:r,config:i}=e;delete e.sourceBars;let a=n instanceof Error?null:n,o=a&&Mo(t,a,r,i,()=>Po(e,t.data));if(!o){this.host.compute(e,t.data,void 0,!0);return}e.output=o,e.changedFrom=0}};function Po(e,t){let n=Sa(e.plugin.descriptor,e.config.params);return n.kind===`price`?(e.sourceBars=Ca(t,n.source),e.sourceBars):t}var Fo=1;function Io(e){return e.descriptor.readsExchangeTimeZone??!La.has(e)}var Lo=class{registry=new Map;instances=new Map;styleDefaults=new Map;order=null;pending=null;timeframe=null;exchangeTimeZone=null;barsTimed=!0;worker=new No({instance:e=>this.instances.get(e),ordered:()=>this.ordered(),dependents:e=>this.getDependents(e),compute:(e,t,n,r)=>this.compute(e,t,n,r),runPending:()=>this.runPending()});useWorker(e,t={}){this.worker.use(e,t)}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`),this.exchangeTimeZone&&(o.exchangeTimeZone=this.exchangeTimeZone);let s=this.styleDefaults.get(e),c={...s?.plots,...o.style?.plots},l={colors:o.style?.colors??s?.colors?.slice()??Na(ba([...this.instances.values()],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:Fa(c)}:{}};this.runPending();let u={plugin:i,config:o,output:null,style:l,changedFrom:0,offInterval:!1,offChartType:!1};return this.placeOnChartType(u),this.instances.set(a,u),this.order=null,n&&this.compute(u,n),a}removeIndicator(e){this.worker.drop(e),this.instances.delete(e),this.order=null}updateIndicator(e,t,n){this.runPending();let r=this.instances.get(e);if(!r)return;let i=xa(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){this.worker.barsChanged();let n=this.waitingOn(e);n.from=Math.min(n.from,t)}waitingOn(e){let t=this.pending;return t&&t.data===e?t:(this.runPending(),this.pending={data:e,from:1/0,full:new Set},this.pending)}flush(){this.worker.settle(),this.runPending()}runPending(){let e=this.pending;if(!e)return;this.pending=null;let{data:t,from:n,full:r}=e;for(let e of this.ordered())r.has(e.config.instanceId)?this.compute(e,t):n!==1/0&&this.compute(e,t,n)}recalculateFrom(e,t){this.deferRecalculateFrom(e,t),this.runPending()}compute(e,t,n,r=!1){if(!r&&this.worker.takes(e,t,n))return;let{plugin:i,config:a}=e,o=Sa(i.descriptor,a.params);if(o.kind===`line`){this.computeFromLine(e,t,o.instanceId,o.key,n);return}delete e.lineInput;let s=t;o.kind===`price`?(e.sourceBars=Ca(t,o.source,e.sourceBars??null,n??0),s=e.sourceBars):delete e.sourceBars;let c=e.output,l=null;n!==void 0&&n>0&&c&&i.update&&(l=i.update(s,a,c,n)),e.changedFrom=l?Math.max(0,n-(i.revisesBefore?.(a)??0)):0,e.output=l??i.calculate(s,a)}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=wa(t,c,r);if(!d){delete e.lineInput,e.output=Ea(t.length);return}let f=a.calculate(d.bars,o),p=Ta(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=Sa(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=Sa(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=Sa(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=Sa(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>=Fo&&(Fo=e+1),t}let n=`tc_${e}_${Fo++}`;for(;this.instances.has(n);)n=`tc_${e}_${Fo++}`;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),Pa(n.style.colors)){let t=n.plugin.descriptor.placement,r=n.config.pane??null,i=[...this.instances.values()];ya(i,t,r,e).has(n.style.colors[0])&&(n.style.colors=Na(ba(i,n.config.id,t,r,e)))}return!0}getOutput(e){return this.flush(),this.instances.get(e)?.output??null}peekOutput(e){return this.runPending(),this.instances.get(e)?.output??null}isComputingInWorker(e){return this.worker.computing(e)}stopWorker(){this.worker.stop()}renderOverlays(e,t,n){for(let r of this.overlayDraws(t,n))r(e)}overlayDraws(e,t){this.runPending();let n=[];for(let r of this.instances.values()){let i=r.output;if(!i||!la(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(){return[...this.instances.values()].some(e=>e.config.scale===`left`&&la(e))}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.runPending();let r=this.instances.get(t);!r?.output||!la(r)||r.plugin.render(e,r.output,n,r.style)}getLatestValues(e){this.runPending();let t=this.instances.get(e);return t?fa(t):[]}getLatestOverlayValues(e=`right`){return this.runPending(),pa(this.instances.values(),e)}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?la(t):!1}setTimeframe(e){this.timeframe=e;let t=!1;for(let e of this.instances.values())t=this.placeOnInterval(e)||t;return t}setExchangeTimeZone(e,n){let r=e&&!(0,t.isUtcTimeZone)(e)&&(0,t.isValidTimeZone)(e)?e:null;if(r===this.exchangeTimeZone)return!1;this.exchangeTimeZone=r;for(let{config:e}of this.instances.values())r?e.exchangeTimeZone=r:delete e.exchangeTimeZone;if(n){let e=this.waitingOn(n).full;for(let t of this.zoneDependents())e.add(t)}return!0}zoneDependents(){let e=new Set;for(let t of this.instances.values())if(Io(t.plugin)){e.add(t.config.instanceId);for(let n of this.getDependents(t.config.instanceId))e.add(n)}return e}setIntervals(e,t){let n=this.instances.get(e);if(!n)return!1;let r=t?Ma(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?Ia(t):null}setBarsTimed(e){if(e===this.barsTimed)return!1;this.barsTimed=e;let t=!1;for(let e of this.instances.values())t=this.placeOnChartType(e)||t;return t}placeOnChartType(e){let t=to.has(e.config.id)||e.plugin.descriptor.readsExchangeTimeZone===!0,n=!this.barsTimed&&t;return n===e.offChartType?!1:(e.offChartType=n,!0)}placeOnInterval(e){let t=!ja(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){return this.runPending(),ma(this.paneInstances(e),t,n,r)}getPaneValuesAt(e,t){return this.runPending(),ha(this.paneInstances(e),t)}paneInstances(e){return[e,...this.getPaneMembers(e)].map(e=>this.instances.get(e)).filter(e=>e!==void 0)}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:la(n),...n.offChartType?{offChartType:!0}:{},...n.config.intervals?{intervals:Ia(n.config.intervals)}:{},...n.config.pane?{pane:n.config.pane}:{},...n.config.scale===`left`?{scale:`left`}:{}});return e}orderIndicators(e){let t=new Map;for(let n of e){let e=this.instances.get(n);e&&!t.has(n)&&t.set(n,e)}for(let[e,n]of this.instances)t.has(e)||t.set(e,n);this.instances=t,this.order=null}getIndicatorStyle(e){let t=this.instances.get(e)?.style;return t?{colors:[...t.colors],lineWidths:[...t.lineWidths],opacity:t.opacity,...t.plots?{plots:Fa(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=Fa(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=Fa(t):delete n.style.plots)}setStyleDefaults(e,t){t?this.styleDefaults.set(e,{...t,...t.plots?{plots:Fa(t.plots)}:{}}):this.styleDefaults.delete(e)}getOverlayPriceRange(e,t,n=`right`){return this.runPending(),va(this.instances.values(),e,t,n)}getPanelIndicators(){return[...this.instances.values()].filter(e=>e.plugin.descriptor.placement===`panel`).map(e=>({instanceId:e.config.instanceId,descriptor:e.plugin.descriptor}))}};function V(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 H(e,t,n,r=1){let i=V(e,t,n);return Math.max(r,Math.floor(i))}var Ro=class extends I{descriptor={id:`sma`,name:`Simple Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`SMA`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`SMA`,color:0}]};calculate(e,t){let n=H(t,`period`,20,1),r=new L,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=H(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}},zo=class extends I{descriptor={id:`ema`,name:`Exponential Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`EMA`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`EMA`,color:0}]};calculate(e,t){let n=H(t,`period`,20,1),r=2/(n+1),i=new L,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=H(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}},Bo=class extends I{descriptor={id:`bb`,name:`Bollinger Bands`,placement:`overlay`,defaultConfig:{period:20,stdDev:2,source:`close`},shortName:`BB`,inputs:{source:{source:!0},period:{kind:`int`,min:1},stdDev:{kind:`number`,min:.1,step:.1}},fills:[{between:[`upper`,`lower`],color:0,opacity:.1}],plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=H(t,`period`,20,1),r=V(t,`stdDev`,2),i=new L,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=H(t,`period`,20,1),a=V(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}},Vo=[`session`,`week`,`month`,`all`],Ho=64,Uo=2;function Wo(e){let t=e.params.anchor;return Vo.includes(t)?t:`session`}function Go(e,t){let n=Wo(t);return n===`all`?null:At(e,n,t.exchangeTimeZone)}var Ko=class extends I{descriptor={readsExchangeTimeZone:!0,id:`vwap`,name:`Volume Weighted Average Price`,placement:`overlay`,defaultConfig:{anchor:`session`},shortName:`VWAP`,inputs:{anchor:{options:Vo}},plots:[{key:`value`,title:`VWAP`,color:0,breakOn:`session`}]};kept=new WeakMap;workerState(e){return this.kept.get(e)}adoptWorkerState(e,t){t&&this.kept.set(e,t)}calculate(e,t){let n={values:new L,series:Array(e.length).fill(null)},r=Go(e,t),i=this.fill(n,e,r,0,null);return r&&this.kept.set(n,i),n}update(e,t,n,r){let i=Go(e,t),a=this.kept.get(n)??[],o=a.find(e=>e.index===r-1);if(!i||!o||r<Ho||r>=e.length||!this.canResume(e,n,r))return null;n.series.length=e.length;let s=this.fill(n,e,i,r,o),c=a.filter(t=>t.index<r&&t.index>=e.length-Uo);return this.kept.set(n,[...c,...s]),n}fill(e,t,n,r,i){let a=i&&n?n(t[i.index].time):void 0,o=i?.volume??0,s=i?.volumePrice??0,c=[];for(let i=r;i<t.length;i++){let r=t[i];if(n){let e=n(r.time);e!==a&&(o=0,s=0,a=e)}o+=r.volume,s+=(r.high+r.low+r.close)/3*r.volume,i>=t.length-Uo&&c.push({index:i,volume:o,volumePrice:s});let l=o>0?a===void 0?{value:s/o}:{value:s/o,session:a}:null;this.writePoint(e,t,i,l)}return c}},qo=4,Jo=t.TC_SERIES_COLORS[qo],Yo=class extends I{descriptor={id:`ichimoku`,name:`Ichimoku Cloud`,placement:`overlay`,defaultConfig:{tenkan:9,kijun:26,senkou:52,displacement:26},inputs:{tenkan:{kind:`int`,min:1},kijun:{kind:`int`,min:1},senkou:{kind:`int`,min:1},displacement:{kind:`int`,min:0}},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},{key:`chikou`,title:`Lagging Span`,color:qo}]};calculate(e,t){let n=H(t,`tenkan`,9,1),r=H(t,`kijun`,26,1),i=H(t,`senkou`,52,1),a=H(t,`displacement`,26,0),o=new L,s=Array(e.length).fill(null),c=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}},l=c(n),u=c(r),d=c(i),f=(e,t,n)=>n>=t-1?(e.highs[n]+e.lows[n])/2:void 0,p=e=>{let t=f(l,n,e),a=f(u,r,e),o={};t!==void 0&&a!==void 0&&(o.senkouA=(t+a)/2);let s=f(d,i,e);return s!==void 0&&(o.senkouB=s),o};for(let t=0;t<e.length;t++){let i={},c=f(l,n,t);c!==void 0&&(i.tenkan=c);let d=f(u,r,t);d!==void 0&&(i.kijun=d),t>=a&&Object.assign(i,p(t-a)),t+a<e.length&&(i.chikou=e[t+a].close),Object.keys(i).length>0&&(o.set(e[t].time,i),s[t]=i)}let m=Math.max(0,e.length-a),h=[];for(let t=m;t<e.length;t++)h.push(p(t));return{values:o,series:s,meta:{ahead:h,aheadFrom:m+a}}}render(n,r,i,a){let o=r.series;if(!o)return;let{from:s,to:c}=i.visibleRange,l=r.meta?.ahead,u=r.meta?.aheadFrom??o.length,d=c-s+1,f=d+(l?.length??0),p=new Float64Array(d),m=new Float64Array(d),h=0,g=new Float64Array(d),_=new Float64Array(d),v=0,y=new Float64Array(f),b=new Float64Array(f),x=0,S=new Float64Array(f),C=new Float64Array(f),w=0,T=new Float64Array(d),E=new Float64Array(d),D=0,O=new Float64Array(f),k=new Float64Array(f),A=new Float64Array(f),j=0,ee=(t,n)=>{let r=n.senkouA,a=n.senkouB;r!==void 0&&(y[x]=t,b[x]=e.k(r,i),x++),a!==void 0&&(S[w]=t,C[w]=e.k(a,i),w++),r!==void 0&&a!==void 0&&(O[j]=t,k[j]=b[x-1],A[j]=C[w-1],j++)};for(let t=s;t<=c&&t<o.length;t++){let n=o[t];if(!n)continue;let r=e.w(t,i);n.tenkan!==void 0&&(p[h]=r,m[h]=e.k(n.tenkan,i),h++),n.kijun!==void 0&&(g[v]=r,_[v]=e.k(n.kijun,i),v++),ee(r,n),n.chikou!==void 0&&(T[D]=r,E[D]=e.k(n.chikou,i),D++)}if(l){let t=i.chartRect.x-i.barWidth-i.barSpacing,n=i.chartRect.x+i.chartRect.width+i.barWidth+i.barSpacing;for(let r=0;r<l.length;r++){let a=e.w(u+r,i);if(a>n)break;a>=t&&ee(a,l[r])}}if(j>1){n.beginPath(),n.moveTo(O[0],k[0]);for(let e=1;e<j;e++)n.lineTo(O[e],k[e]);for(let e=j-1;e>=0;e--)n.lineTo(O[e],A[e]);n.closePath(),n.fillStyle=(0,t.withAlpha)(a.colors[2]??`#1fa874`,.15),n.fill()}let te=(e,t,r,i,o,s)=>{let c=Yi(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([])}};te(`tenkan`,p,m,h,a.colors[0],a.lineWidths[0]),te(`kijun`,g,_,v,a.colors[1]??`#f2a93b`,a.lineWidths[0]),te(`senkouA`,y,b,x,a.colors[2]??`#1fa874`,1),te(`senkouB`,S,C,w,a.colors[3]??`#e8505b`,1),te(`chikou`,T,E,D,a.colors[qo]??Jo,1)}},Xo=class extends I{descriptor={id:`psar`,name:`Parabolic SAR`,placement:`overlay`,defaultConfig:{step:.02,max:.2},inputs:{step:{kind:`number`,min:.01,step:.01},max:{kind:`number`,min:.01,step:.01}},shortName:`SAR`,plots:[{key:`value`,title:`SAR`,color:0,kind:`dots`,tone:{field:`trend`},downColor:1}]};calculate(e,t){let n=V(t,`step`,.02),r=V(t,`max`,.2),i=new L,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}}},Zo=class extends I{descriptor={id:`supertrend`,name:`Supertrend`,placement:`overlay`,defaultConfig:{period:10,multiplier:3},inputs:{period:{kind:`int`,min:1},multiplier:{kind:`number`,min:.1,step:.1}},shortName:`Supertrend`,plots:[{key:`value`,title:`Supertrend`,color:0,tone:{field:`trend`},downColor:1}]};calculate(e,t){let n=H(t,`period`,10,1),r=V(t,`multiplier`,3),i=new L,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,v=e[Math.max(0,t-1)].close;c=g<u||v>u?g:u,l=_>d||v<d?_:d,f=p===u?e[t].close<=c?c:l:e[t].close>=l?l:c,m=f===l?1:-1;let y={value:f,trend:m};i.set(e[t].time,y),a[t]=y,u=c,d=l,p=f}return{values:i,series:a}}},Qo=class extends I{descriptor={id:`keltner`,name:`Keltner Channel`,placement:`overlay`,defaultConfig:{emaPeriod:20,atrPeriod:10,multiplier:1.5},inputs:{emaPeriod:{kind:`int`,min:1},atrPeriod:{kind:`int`,min:1},multiplier:{kind:`number`,min:.1,step:.1}},shortName:`KC`,fills:[{between:[`upper`,`lower`],color:0,opacity:.08}],plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=H(t,`emaPeriod`,20,1),r=H(t,`atrPeriod`,10,1),i=V(t,`multiplier`,1.5),a=new L;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}}},$o=class extends I{descriptor={id:`donchian`,name:`Donchian Channel`,placement:`overlay`,defaultConfig:{period:20},inputs:{period:{kind:`int`,min:1}},shortName:`DC`,fills:[{between:[`upper`,`lower`],color:0,opacity:.08}],plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1,width:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=H(t,`period`,20,1),r=new L,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}}},es=[`traditional`,`fibonacci`,`woodie`,`classic`,`camarilla`,`dm`],ts=class extends I{descriptor={id:`pivots`,name:`Pivot Points`,placement:`overlay`,defaultConfig:{lookback:24,type:`traditional`},shortName:`Pivots`,inputs:{lookback:{kind:`int`,min:1},type:{options:es}},plots:[{key:`r3`,title:`R3`,color:1,width:1,lineStyle:`dashed`},{key:`r2`,title:`R2`,color:1,width:1,lineStyle:`dashed`},{key:`r1`,title:`R1`,color:1,width:1,lineStyle:`dashed`},{key:`pp`,title:`P`,color:0},{key:`s1`,title:`S1`,color:2,width:1,lineStyle:`dashed`},{key:`s2`,title:`S2`,color:2,width:1,lineStyle:`dashed`},{key:`s3`,title:`S3`,color:2,width:1,lineStyle:`dashed`}]};calculate(e,t){let n=H(t,`lookback`,24,1),r=es.includes(t.params.type)?t.params.type:`traditional`,i=new L,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=ns(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}}};function ns(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 rs=class extends I{descriptor={id:`avwap`,name:`Anchored VWAP`,placement:`overlay`,defaultConfig:{anchorTime:0},inputs:{anchorTime:{kind:`int`}},shortName:`AVWAP`,plots:[{key:`value`,title:`AVWAP`,color:0}]};calculate(e,n){let r=V(n,`anchorTime`,0),i=new L,a=Array(e.length).fill(null),o=0;if(r>0){let n=(0,t.barTimeUnit)(e),s=(0,t.normalizeBarTime)(r);if(o=e.findIndex(e=>e.time*n>=s),o<0)return{values:i,series:a}}let s=0,c=0;for(let t=o;t<e.length;t++){let n=(e[t].high+e[t].low+e[t].close)/3;if(s+=e[t].volume,c+=n*e[t].volume,s>0){let n={value:c/s};i.set(e[t].time,n),a[t]=n}}return{values:i,series:a}}},is=class extends I{descriptor={id:`zigzag`,name:`ZigZag`,placement:`overlay`,defaultConfig:{deviation:5},inputs:{deviation:{kind:`number`,min:.1,step:.1}},shortName:`ZigZag`,plots:[{key:`pivot`,title:`Pivot`,color:0}]};calculate(e,t){let n=Math.max(.01,V(t,`deviation`,5))/100,r=new L,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.w(i.idx,r),s=e.k(i.price,r);n===0?t.moveTo(o,s):t.lineTo(o,s)}t.stroke()}}},as=class extends I{descriptor={id:`lrc`,name:`Linear Regression Channel`,placement:`overlay`,defaultConfig:{period:100,stdDev:2,source:`close`},shortName:`LRC`,inputs:{source:{source:!0},period:{kind:`int`,min:2},stdDev:{kind:`number`,min:.1,step:.1}},fills:[{between:[`upper`,`lower`],color:0,opacity:.08}],plots:[{key:`upper`,title:`Upper`,color:0},{key:`middle`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=H(t,`period`,100,2),r=V(t,`stdDev`,2),i=new L,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}}},os=class extends I{descriptor={id:`hma`,name:`Hull Moving Average`,placement:`overlay`,defaultConfig:{period:21,source:`close`},shortName:`HMA`,inputs:{source:{source:!0},period:{kind:`int`,min:2}},plots:[{key:`value`,title:`HMA`,color:0}]};calculate(e,t){let n=H(t,`period`,21,2),r=new L,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=ss(a,n),l=ss(a,o),u=cs(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}}};function ss(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 cs(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 ls=class extends I{descriptor={readsExchangeTimeZone:!0,id:`mtfma`,name:`MTF Moving Average`,placement:`overlay`,defaultConfig:{period:50,timeframe:`1d`,source:`close`},shortName:`MTF MA`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`MA`,color:0}]};calculate(e,t){let n=H(t,`period`,50,1),r=String(t.params.timeframe??`1d`),i=new L,a=Array(e.length).fill(null);if(e.length===0)return{values:i,series:a};let o=[],s=At(e,r,t.exchangeTimeZone),c=s(e[0].time),l=e[0].close,u=null,d=()=>{if(o.length<n)return;let e=0;for(let t=o.length-n;t<o.length;t++)e+=o[t];u=e/n};for(let t=0;t<e.length;t++){let n=s(e[t].time);if(n!==c&&(o.push(l),d(),c=n),l=e[t].close,u!==null){let n={value:u};i.set(e[t].time,n),a[t]=n}}return{values:i,series:a}}},us=class extends I{descriptor={readsExchangeTimeZone:!0,id:`svwap`,name:`Session VWAP`,placement:`overlay`,defaultConfig:{bands:1},inputs:{bands:{kind:`int`,min:0,max:3}},shortName:`SVWAP`,plots:[{key:`value`,title:`VWAP`,color:0,breakOn:`session`},{key:`u1`,title:`+1σ`,color:1,width:1,lineStyle:`dashed`,opacity:.55,breakOn:`session`},{key:`l1`,title:`−1σ`,color:1,width:1,lineStyle:`dashed`,opacity:.55,breakOn:`session`},{key:`u2`,title:`+2σ`,color:1,width:1,lineStyle:`dashed`,opacity:.55,breakOn:`session`},{key:`l2`,title:`−2σ`,color:1,width:1,lineStyle:`dashed`,opacity:.55,breakOn:`session`},{key:`u3`,title:`+3σ`,color:1,width:1,lineStyle:`dashed`,opacity:.55,breakOn:`session`},{key:`l3`,title:`−3σ`,color:1,width:1,lineStyle:`dashed`,opacity:.55,breakOn:`session`}]};calculate(e,n){let r=(0,t.barsAreDaily)(e)===!0?0:Math.min(3,H(n,`bands`,1,0)),i=new L,a=Array(e.length).fill(null);if(e.length===0)return{values:i,series:a};let o=At(e,`session`,n.exchangeTimeZone),s=o(e[0].time),c=0,l=0,u=0;for(let t=0;t<e.length;t++){let n=e[t],d=o(n.time);d!==s&&(c=0,l=0,u=0,s=d);let f=(n.high+n.low+n.close)/3;if(c+=f*n.volume,l+=f*f*n.volume,u+=n.volume,u>0){let e=c/u,o={value:e,session:s};if(r>0){let t=Math.max(0,l/u-e*e),n=Math.sqrt(t);for(let t=1;t<=r;t++)o[`u${t}`]=e+t*n,o[`l${t}`]=e-t*n}i.set(n.time,o),a[t]=o}}return{values:i,series:a}}},ds=class extends I{descriptor={id:`chandelier`,name:`Chandelier Exit`,placement:`overlay`,defaultConfig:{period:22,multiplier:3},inputs:{period:{kind:`int`,min:1},multiplier:{kind:`number`,min:.1,step:.1}},shortName:`CE`,plots:[{key:`long`,title:`Long`,color:0,lineStyle:`dashed`},{key:`short`,title:`Short`,color:1,lineStyle:`dashed`}]};calculate(e,t){let n=H(t,`period`,22,1),r=V(t,`multiplier`,3),i=new L,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}}},fs=class extends I{descriptor={id:`alligator`,name:`Alligator`,placement:`overlay`,defaultConfig:{jaw:13,teeth:8,lips:5,jawShift:8,teethShift:5,lipsShift:3},inputs:{jaw:{kind:`int`,min:1},teeth:{kind:`int`,min:1},lips:{kind:`int`,min:1},jawShift:{kind:`int`,min:0},teethShift:{kind:`int`,min:0},lipsShift:{kind:`int`,min:0}},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=H(t,`jaw`,13,1),r=H(t,`teeth`,8,1),i=H(t,`lips`,5,1),a=H(t,`jawShift`,8,0),o=H(t,`teethShift`,5,0),s=H(t,`lipsShift`,3,0),c=new L,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=ps(d,n),p=ps(d,r),m=ps(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}}};function ps(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 ms=class extends I{descriptor={id:`vwma`,name:`Volume Weighted Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`VWMA`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`VWMA`,color:0}]};calculate(e,t){let n=H(t,`period`,20,1),r=new L,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=H(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}},hs=class extends I{descriptor={id:`wma`,name:`Weighted Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`WMA`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`WMA`,color:0}]};calculate(e,t){let n=H(t,`period`,20,1),r=new L,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=H(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}},gs=class extends I{descriptor={id:`envelope`,name:`Moving Average Envelope`,placement:`overlay`,defaultConfig:{period:20,percent:2.5,source:`close`},shortName:`Env`,inputs:{source:{source:!0},period:{kind:`int`,min:1},percent:{kind:`number`,min:0,step:.1}},fills:[{between:[`upper`,`lower`],color:0,opacity:.08}],plots:[{key:`upper`,title:`Upper`,color:0},{key:`basis`,title:`Basis`,color:1},{key:`lower`,title:`Lower`,color:0}]};calculate(e,t){let n=H(t,`period`,20,1),r=V(t,`percent`,2.5)/100,i=new L,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=H(t,`period`,20,1),a=V(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}};function _s(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 vs(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 ys(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 bs=class extends I{descriptor={id:`tema`,name:`Triple EMA`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`TEMA`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`TEMA`,color:0}]};calculate(e,t){let n=H(t,`period`,20,1),r=new L,i=Array(e.length).fill(null),a=_s(e.map(e=>e.close),n),o=ys(a),s=vs(_s(o.values,n),o.indices,e.length),c=ys(s),l=vs(_s(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}}},xs=class extends I{descriptor={id:`ao`,name:`Awesome Oscillator`,placement:`panel`,defaultConfig:{fast:5,slow:34},inputs:{fast:{kind:`int`,min:1},slow:{kind:`int`,min:1}},shortName:`AO`,plots:[{key:`value`,title:`AO`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}]};calculate(e,t){let n=H(t,`fast`,5,1),r=H(t,`slow`,34,1),i=new L,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}}},Ss=class extends I{descriptor={id:`chaikinOsc`,name:`Chaikin Oscillator`,placement:`panel`,defaultConfig:{fast:3,slow:10},inputs:{fast:{kind:`int`,min:1},slow:{kind:`int`,min:1}},shortName:`Chaikin Osc`,plots:[{key:`value`,title:`Chaikin`,color:0,kind:`histogram`,tone:`sign`,downColor:1}]};calculate(e,t){let n=H(t,`fast`,3,1),r=H(t,`slow`,10,1),i=new L,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}}},Cs=class extends I{descriptor={id:`rsi`,name:`Relative Strength Index`,placement:`panel`,defaultConfig:{period:14,source:`close`},shortName:`RSI`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`RSI`,color:0}],scale:{min:0,max:100},levels:[30,70]};smoothing=new WeakMap;workerState(e){return this.smoothing.get(e)}adoptWorkerState(e,t){t&&this.smoothing.set(e,t)}calculate(e,t){let n=H(t,`period`,14,1),r=new L,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=H(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}},ws=class extends I{descriptor={id:`macd`,name:`MACD`,placement:`panel`,defaultConfig:{fast:12,slow:26,signal:9,source:`close`},shortName:`MACD`,inputs:{source:{source:!0},fast:{kind:`int`,min:1},slow:{kind:`int`,min:1},signal:{kind:`int`,min:1}},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;workerState(e){return this.emas.get(e)}adoptWorkerState(e,t){t&&this.emas.set(e,t)}calculate(e,t){let n=H(t,`fast`,12,1),r=H(t,`slow`,26,1),i=H(t,`signal`,9,1),a=new L,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=H(t,`fast`,12,1),a=H(t,`slow`,26,1),o=H(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}},Ts=class extends I{descriptor={id:`stochastic`,name:`Stochastic Oscillator`,placement:`panel`,defaultConfig:{kPeriod:14,dPeriod:3,smooth:3},inputs:{kPeriod:{kind:`int`,min:1},dPeriod:{kind:`int`,min:1},smooth:{kind:`int`,min:1}},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=H(t,`kPeriod`,14,1),r=H(t,`dPeriod`,3,1),i=H(t,`smooth`,3,1),a=new L,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=H(t,`kPeriod`,14,1),a=H(t,`dPeriod`,3,1),o=H(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}},Es=class extends I{descriptor={id:`atr`,name:`Average True Range`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`ATR`,plots:[{key:`value`,title:`ATR`,color:0}]};calculate(e,t){let n=H(t,`period`,14,1),r=new L,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=H(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}},Ds=class extends I{descriptor={id:`adx`,name:`Average Directional Index`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},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=H(t,`period`,14,1),r=new L,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}}},Os=class extends I{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 L,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}},ks=class extends I{descriptor={id:`williamsR`,name:`Williams %R`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`%R`,plots:[{key:`value`,title:`%R`,color:0}],scale:{min:-100,max:0},levels:[-80,-20]};calculate(e,t){let n=H(t,`period`,14,1),r=new L,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}}},As=class extends I{descriptor={id:`cci`,name:`Commodity Channel Index`,placement:`panel`,defaultConfig:{period:20},inputs:{period:{kind:`int`,min:1}},shortName:`CCI`,plots:[{key:`value`,title:`CCI`,color:0}],levels:[-100,0,100]};calculate(e,t){let n=H(t,`period`,20,1),r=new L,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}}},js=class extends I{descriptor={id:`mfi`,name:`Money Flow Index`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`MFI`,plots:[{key:`value`,title:`MFI`,color:0}],scale:{min:0,max:100},levels:[20,80]};calculate(e,t){let n=H(t,`period`,14,1),r=new L,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}}},Ms=class extends I{descriptor={id:`aroon`,name:`Aroon`,placement:`panel`,defaultConfig:{period:25},inputs:{period:{kind:`int`,min:1}},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=H(t,`period`,25,1),r=new L,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}}},Ns=class extends I{descriptor={id:`roc`,name:`Rate of Change`,placement:`panel`,defaultConfig:{period:12,source:`close`},shortName:`ROC`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`ROC`,color:0}],levels:[0]};calculate(e,t){let n=H(t,`period`,12,1),r=new L,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}}},Ps=class extends I{descriptor={id:`tsi`,name:`True Strength Index`,placement:`panel`,defaultConfig:{longPeriod:25,shortPeriod:13,signalPeriod:7,source:`close`},shortName:`TSI`,inputs:{source:{source:!0},longPeriod:{kind:`int`,min:1},shortPeriod:{kind:`int`,min:1},signalPeriod:{kind:`int`,min:1}},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=H(t,`longPeriod`,25,1),r=H(t,`shortPeriod`,13,1),i=H(t,`signalPeriod`,7,1),a=new L,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}}},Fs=class extends I{descriptor={id:`cmf`,name:`Chaikin Money Flow`,placement:`panel`,defaultConfig:{period:20},inputs:{period:{kind:`int`,min:1}},shortName:`CMF`,plots:[{key:`value`,title:`CMF`,color:0,kind:`histogram`,tone:`sign`,downColor:1}]};calculate(e,t){let n=H(t,`period`,20,1),r=new L,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}}},Is=class extends I{descriptor={id:`voldelta`,name:`Volume Delta`,placement:`panel`,defaultConfig:{mode:0},inputs:{mode:{kind:`int`,min:0,max:1}},shortName:`Vol Δ`,plots:[{key:`value`,title:`Delta`,color:0,kind:`histogram`,tone:{field:`up`},downColor:1}]};calculate(e,t){let n=V(t,`mode`,0)>=1,r=new L,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}}},Ls=class extends I{descriptor={id:`vortex`,name:`Vortex Indicator`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`VI`,plots:[{key:`viPlus`,title:`VI+`,color:0},{key:`viMinus`,title:`VI−`,color:1}],levels:[1]};calculate(e,t){let n=H(t,`period`,14,1),r=new L,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}}},Rs=class extends I{descriptor={id:`chop`,name:`Choppiness Index`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:2}},shortName:`CHOP`,plots:[{key:`value`,title:`CHOP`,color:0}],scale:{min:0,max:100},levels:[38.2,61.8]};calculate(e,t){let n=H(t,`period`,14,2),r=new L,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}}},zs=class extends I{descriptor={id:`uo`,name:`Ultimate Oscillator`,placement:`panel`,defaultConfig:{fast:7,mid:14,slow:28},inputs:{fast:{kind:`int`,min:1},mid:{kind:`int`,min:1},slow:{kind:`int`,min:1}},shortName:`UO`,plots:[{key:`value`,title:`UO`,color:0}],scale:{min:0,max:100},levels:[30,70]};calculate(e,t){let n=H(t,`fast`,7,1),r=H(t,`mid`,14,1),i=H(t,`slow`,28,1),a=new L,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=Bs(l(s,t,n),l(c,t,n)),d=Bs(l(s,t,r),l(c,t,r)),f=Bs(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 Bs(e,t){return t===0?0:e/t}var Vs=class extends I{descriptor={id:`fi`,name:`Force Index`,placement:`panel`,defaultConfig:{period:13},inputs:{period:{kind:`int`,min:1}},shortName:`EFI`,plots:[{key:`value`,title:`EFI`,color:0}],levels:[0]};calculate(e,t){let n=H(t,`period`,13,1),r=new L,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}}},Hs=class extends I{descriptor={id:`crsi`,name:`Connors RSI`,placement:`panel`,defaultConfig:{rsiPeriod:3,streakPeriod:2,rankPeriod:100,source:`close`},shortName:`CRSI`,inputs:{source:{source:!0},rsiPeriod:{kind:`int`,min:1},streakPeriod:{kind:`int`,min:1},rankPeriod:{kind:`int`,min:1}},plots:[{key:`value`,title:`CRSI`,color:0}],scale:{min:0,max:100},levels:[10,90]};calculate(e,t){let n=H(t,`rsiPeriod`,3,1),r=H(t,`streakPeriod`,2,1),i=H(t,`rankPeriod`,100,1),a=new L,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=Us(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=Us(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 Us(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 Ws=class extends I{descriptor={id:`coppock`,name:`Coppock Curve`,placement:`panel`,defaultConfig:{longRoc:14,shortRoc:11,wma:10,source:`close`},shortName:`Coppock`,inputs:{source:{source:!0},longRoc:{kind:`int`,min:1},shortRoc:{kind:`int`,min:1},wma:{kind:`int`,min:1}},plots:[{key:`value`,title:`Coppock`,color:0}],levels:[0]};calculate(e,t){let n=H(t,`longRoc`,14,1),r=H(t,`shortRoc`,11,1),i=H(t,`wma`,10,1),a=new L,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}}},Gs=class extends I{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},roc1:{kind:`int`,min:1},roc2:{kind:`int`,min:1},roc3:{kind:`int`,min:1},roc4:{kind:`int`,min:1},sma1:{kind:`int`,min:1},sma2:{kind:`int`,min:1},sma3:{kind:`int`,min:1},sma4:{kind:`int`,min:1},signal:{kind:`int`,min:1}},plots:[{key:`value`,title:`KST`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=H(t,`roc1`,10,1),r=H(t,`roc2`,15,1),i=H(t,`roc3`,20,1),a=H(t,`roc4`,30,1),o=H(t,`sma1`,10,1),s=H(t,`sma2`,10,1),c=H(t,`sma3`,10,1),l=H(t,`sma4`,15,1),u=H(t,`signal`,9,1),d=new L,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=qs(Ks(m,n),o),g=qs(Ks(m,r),s),_=qs(Ks(m,i),c),v=qs(Ks(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=qs(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 Ks(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 qs(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 Js=class extends I{descriptor={id:`elderray`,name:`Elder Ray`,placement:`panel`,defaultConfig:{period:13},inputs:{period:{kind:`int`,min:1}},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=H(t,`period`,13,1),r=new L,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.A(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.w(i,r)+p,Math.min(s,l),u,Math.max(1,Math.abs(s-l)))}t.fill()}}},Ys=class extends I{descriptor={id:`stc`,name:`Schaff Trend Cycle`,placement:`panel`,defaultConfig:{fast:23,slow:50,cycle:10,source:`close`},shortName:`STC`,inputs:{source:{source:!0},fast:{kind:`int`,min:1},slow:{kind:`int`,min:1},cycle:{kind:`int`,min:1}},plots:[{key:`value`,title:`STC`,color:0}],scale:{min:0,max:100},levels:[25,75]};calculate(e,t){let n=H(t,`fast`,23,1),r=H(t,`slow`,50,1),i=H(t,`cycle`,10,1),a=new L,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=Xs(Xs(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 Xs(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 Zs=class extends I{descriptor={id:`kvo`,name:`Klinger Oscillator`,placement:`panel`,defaultConfig:{fast:34,slow:55,signal:13},inputs:{fast:{kind:`int`,min:1},slow:{kind:`int`,min:1},signal:{kind:`int`,min:1}},shortName:`KVO`,plots:[{key:`value`,title:`KVO`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=H(t,`fast`,34,1),r=H(t,`slow`,55,1),i=H(t,`signal`,13,1),a=new L,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}}},Qs=class extends I{descriptor={id:`fisher`,name:`Fisher Transform`,placement:`panel`,defaultConfig:{period:9},inputs:{period:{kind:`int`,min:1}},shortName:`Fisher`,plots:[{key:`value`,title:`Fisher`,color:0},{key:`trigger`,title:`Trigger`,color:1}],levels:[0]};calculate(e,t){let n=H(t,`period`,9,1),r=new L,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}}},$s=class extends I{descriptor={id:`dpo`,name:`Detrended Price Oscillator`,placement:`panel`,defaultConfig:{period:20,source:`close`},shortName:`DPO`,inputs:{source:{source:!0},period:{kind:`int`,min:2}},plots:[{key:`value`,title:`DPO`,color:0,kind:`histogram`,tone:`sign`,downColor:1}]};calculate(e,t){let n=H(t,`period`,20,2),r=Math.floor(n/2)+1,i=new L,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}}},ec=class extends I{descriptor={id:`bop`,name:`Balance of Power`,placement:`panel`,defaultConfig:{smooth:14},inputs:{smooth:{kind:`int`,min:1}},shortName:`BOP`,plots:[{key:`value`,title:`BOP`,color:0}],scale:{min:-1,max:1},levels:[0]};calculate(e,t){let n=H(t,`smooth`,14,1),r=new L,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}}},tc=class extends I{descriptor={id:`massindex`,name:`Mass Index`,placement:`panel`,defaultConfig:{ema:9,sum:25},inputs:{ema:{kind:`int`,min:1},sum:{kind:`int`,min:1}},shortName:`Mass`,plots:[{key:`value`,title:`Mass`,color:0}],levels:[26.5,27]};calculate(e,t){let n=H(t,`ema`,9,1),r=H(t,`sum`,25,1),i=new L,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}}},nc=class extends I{descriptor={id:`cmo`,name:`Chande Momentum`,placement:`panel`,defaultConfig:{period:9,source:`close`},shortName:`CMO`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`CMO`,color:0}],scale:{min:-100,max:100},levels:[-50,0,50]};calculate(e,t){let n=H(t,`period`,9,1),r=new L,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}}},rc=class extends I{descriptor={id:`trix`,name:`TRIX`,placement:`panel`,defaultConfig:{period:15,signal:9,source:`close`},shortName:`TRIX`,inputs:{source:{source:!0},period:{kind:`int`,min:1},signal:{kind:`int`,min:1}},plots:[{key:`value`,title:`TRIX`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=H(t,`period`,15,1),r=H(t,`signal`,9,1),i=new L,a=Array(e.length).fill(null),o=e.length;if(o<2)return{values:i,series:a};let s=ic(ic(ic(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=ic(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 ic(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 ac=class extends I{descriptor={id:`emv`,name:`Ease of Movement`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`EOM`,plots:[{key:`value`,title:`EOM`,color:0}],levels:[0]};calculate(e,t){let n=H(t,`period`,14,1),r=new L,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}}},oc=class extends I{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 L,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}}},sc=class extends I{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 L,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}}},cc=class extends I{descriptor={id:`chaikinvol`,name:`Chaikin Volatility`,placement:`panel`,defaultConfig:{ema:10,roc:10},inputs:{ema:{kind:`int`,min:1},roc:{kind:`int`,min:1}},shortName:`CV`,plots:[{key:`value`,title:`CV`,color:0}],levels:[0]};calculate(e,t){let n=H(t,`ema`,10,1),r=H(t,`roc`,10,1),i=new L,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}}},lc=class extends I{descriptor={id:`rvi`,name:`Relative Vigor Index`,placement:`panel`,defaultConfig:{period:10},inputs:{period:{kind:`int`,min:1}},shortName:`RVGI`,plots:[{key:`value`,title:`RVGI`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=H(t,`period`,10,1),r=new L,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}}},uc=class extends I{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},rsiPeriod:{kind:`int`,min:1},stochPeriod:{kind:`int`,min:1},k:{kind:`int`,min:1},d:{kind:`int`,min:1}},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=H(t,`rsiPeriod`,14,1),r=H(t,`stochPeriod`,14,1),i=H(t,`k`,3,1),a=H(t,`d`,3,1),o=new L,s=Array(e.length).fill(null),c=e.length;if(c<=n+r)return{values:o,series:s};let l=dc(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=fc(u,i),f=fc(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 dc(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 fc(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 pc=class extends I{descriptor={id:`ppo`,name:`Percentage Price Oscillator`,placement:`panel`,defaultConfig:{fast:12,slow:26,signal:9,source:`close`},shortName:`PPO`,inputs:{source:{source:!0},fast:{kind:`int`,min:1},slow:{kind:`int`,min:1},signal:{kind:`int`,min:1}},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=H(t,`fast`,12,1),r=H(t,`slow`,26,1),i=H(t,`signal`,9,1),a=new L,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=mc(c,n),u=mc(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=mc(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 mc(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 hc=class extends I{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 L,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]=gc(i,e,5)-gc(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 gc(e,t,n){let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i];return r/n}var _c=class extends I{descriptor={id:`rmi`,name:`Relative Momentum Index`,placement:`panel`,defaultConfig:{period:20,momentum:5,source:`close`},shortName:`RMI`,inputs:{source:{source:!0},period:{kind:`int`,min:1},momentum:{kind:`int`,min:1}},plots:[{key:`value`,title:`RMI`,color:0}],scale:{min:0,max:100},levels:[30,70]};calculate(e,t){let n=H(t,`period`,20,1),r=H(t,`momentum`,5,1),i=new L,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}}},vc=class extends I{descriptor={id:`disparity`,name:`Disparity Index`,placement:`panel`,defaultConfig:{period:14,source:`close`},shortName:`DI`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`DI`,color:0}],levels:[0]};calculate(e,t){let n=H(t,`period`,14,1),r=new L,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}}},yc=class extends I{descriptor={id:`qstick`,name:`Qstick`,placement:`panel`,defaultConfig:{period:8},inputs:{period:{kind:`int`,min:1}},shortName:`Qstick`,plots:[{key:`value`,title:`Qstick`,color:0}],levels:[0]};calculate(e,t){let n=H(t,`period`,8,1),r=new L,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}}},bc=class extends I{descriptor={id:`pgo`,name:`Pretty Good Oscillator`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`PGO`,plots:[{key:`value`,title:`PGO`,color:0}],levels:[-3,0,3]};calculate(e,t){let n=H(t,`period`,14,1),r=new L,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}}},xc=class extends I{descriptor={id:`stddev`,name:`Standard Deviation`,placement:`panel`,defaultConfig:{period:20,source:`close`},shortName:`StdDev`,inputs:{source:{source:!0},period:{kind:`int`,min:1}},plots:[{key:`value`,title:`StdDev`,color:0}]};calculate(e,t){let n=H(t,`period`,20,1),r=new L,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}}},Sc=.3,Cc=.7,wc=class extends I{descriptor={id:`volumeProfile`,name:`Volume Profile`,placement:`overlay`,defaultConfig:{rows:24},inputs:{rows:{kind:`int`,min:1}},shortName:`VP`,plots:[]};calculate(e,t){let n=H(t,`rows`,24,1),r=new L,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(n,r,i,a){let{chartRect:o}=i,s=r.meta;if(!s||s.maxVolume===0)return;let{minPrice:c,rows:l,rowHeight:u,bins:d,maxVolume:f}=s,p=o.width*Sc,m=e.A(i),h=a.colors[0]??t.TC_PALETTE.blue,g=a.colors[1]??t.TC_PALETTE.amber;n.save(),n.globalAlpha=St(a.opacity);for(let e=0;e<l;e++){let t=d[e]/f*p;if(t<=0)continue;let r=m(c+e*u),i=m(c+(e+1)*u);n.fillStyle=d[e]>f*Cc?g:h,n.fillRect(o.x,Math.min(r,i),t,Math.max(Math.abs(r-i)-1,1))}n.restore()}},Tc=class extends I{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 L,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}}},Ec=class extends I{descriptor={id:`vroc`,name:`Volume Rate of Change`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:1}},shortName:`VROC`,plots:[{key:`value`,title:`VROC`,color:0}],levels:[0]};calculate(e,t){let n=H(t,`period`,14,1),r=new L,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}}},Dc=class extends I{descriptor={id:`dema`,name:`Double Exponential Moving Average`,placement:`overlay`,defaultConfig:{period:20,source:`close`},shortName:`DEMA`,inputs:{period:{kind:`int`,min:1},source:{source:!0}},plots:[{key:`value`,title:`DEMA`,color:0}]};emas=new WeakMap;workerState(e){return this.emas.get(e)}adoptWorkerState(e,t){t&&this.emas.set(e,t)}calculate(e,t){let n=H(t,`period`,20,1),r=z(Ra(e),n),i=z(r,n),a=R(e,qa(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/(H(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}},Oc=class extends I{descriptor={id:`smma`,name:`Smoothed Moving Average`,placement:`overlay`,defaultConfig:{period:14,source:`close`},shortName:`SMMA`,inputs:{period:{kind:`int`,min:1},source:{source:!0}},plots:[{key:`value`,title:`SMMA`,color:0}]};calculate(e,t){return R(e,qa(Ha(Ra(e),H(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=H(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}},kc=class extends B{descriptor={id:`alma`,name:`Arnaud Legoux Moving Average`,placement:`overlay`,defaultConfig:{period:9,offset:.85,sigma:6,source:`close`},shortName:`ALMA`,inputs:{period:{kind:`int`,min:1,max:5e3},offset:{kind:`number`,min:0,max:1,step:.05},sigma:{kind:`number`,min:.5,step:.5},source:{source:!0}},plots:[{key:`value`,title:`ALMA`,color:0}]};read(e){let t=Math.min(5e3,H(e,`period`,9,1)),n=Math.min(1,Math.max(0,V(e,`offset`,.85))),r=Math.max(.5,V(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}}},Ac=class extends I{descriptor={id:`kama`,name:`Kaufman Adaptive Moving Average`,placement:`overlay`,defaultConfig:{period:10,fast:2,slow:30,source:`close`},shortName:`KAMA`,inputs:{period:{kind:`int`,min:1},fast:{kind:`int`,min:1},slow:{kind:`int`,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=H(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<=H(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=H(t,`period`,10,1),o=2/(H(t,`fast`,2,1)+1),s=2/(H(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})}}},jc=class extends B{descriptor={id:`lsma`,name:`Least Squares Moving Average`,placement:`overlay`,defaultConfig:{period:25,offset:0,source:`close`},shortName:`LSMA`,inputs:{period:{kind:`int`,min:2,max:5e3},offset:{kind:`int`,step:1},source:{source:!0}},plots:[{key:`value`,title:`LSMA`,color:0}]};read(e){let t=Math.min(5e3,H(e,`period`,25,2)),n=Math.round(H(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)}}},Mc=class extends I{descriptor={id:`mcginley`,name:`McGinley Dynamic`,placement:`overlay`,defaultConfig:{period:14,source:`close`},shortName:`McGinley`,inputs:{period:{kind:`int`,min:1},source:{source:!0}},plots:[{key:`value`,title:`McGinley`,color:0}]};calculate(e,t){let n=H(t,`period`,14,1),r=z(Ra(e),n),i=Array(e.length).fill(void 0),a;for(let t=0;t<e.length;t++)a=a===void 0?r[t]:Nc(a,e[t].close,n),i[t]=a;return R(e,qa(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=H(t,`period`,14,1);for(let t=r;t<e.length;t++)i=Nc(i,e[t].close,a),this.writePoint(n,e,t,{value:i});return n}};function Nc(e,t,n){return e>0&&t>0?e+(t-e)/(n*(t/e)**4):t}function Pc(e){return e.params.type===`ema`?[`ema`,`ema`]:e.params.type===`sma-ema`?[`sma`,`ema`]:[`sma`,`sma`]}var Fc=class extends I{descriptor={id:`macross`,name:`MA Cross`,placement:`overlay`,defaultConfig:{fast:9,slow:21,type:`sma`,source:`close`},shortName:`MA Cross`,inputs:{fast:{kind:`int`,min:1},slow:{kind:`int`,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]=Pc(t),i=Ra(e),a=(t,n)=>t===`ema`?z(i,n):e.map((t,r)=>Za(e,r,n)),o=a(n,H(t,`fast`,9,1)),s=a(r,H(t,`slow`,21,1));return R(e,o.map((e,t)=>Ic(e,s[t])))}update(e,t,n,r){if(!this.canResume(e,n,r))return null;let[i,a]=Pc(t),o=H(t,`fast`,9,1),s=H(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):Za(e,t,o),l=a===`ema`?l+2/(s+1)*(r-l):Za(e,t,s),this.writePoint(n,e,t,Ic(c,l))}return n}};function Ic(e,t){return e===void 0&&t===void 0?null:{...e===void 0?{}:{fast:e},...t===void 0?{}:{slow:t}}}var Lc=class extends B{descriptor={id:`fractals`,name:`Williams Fractals`,placement:`overlay`,defaultConfig:{period:2},shortName:`Fractals`,inputs:{period:{kind:`int`,min:1,max:10}},plots:[{key:`up`,title:`Up`,color:0,kind:`dots`},{key:`down`,title:`Down`,color:1,kind:`dots`}]};read(e){return H(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}:{}}}},Rc=class extends I{descriptor={id:`cks`,name:`Chande Kroll Stop`,placement:`overlay`,defaultConfig:{p:10,x:1,q:9},shortName:`CKS`,inputs:{p:{kind:`int`,label:`ATR length`,min:1},x:{kind:`number`,label:`ATR multiplier`,min:0,step:.1},q:{kind:`int`,label:`Stop length`,min:1}},plots:[{key:`long`,title:`Stop Long`,color:0},{key:`short`,title:`Stop Short`,color:1}]};states=new WeakMap;workerState(e){return this.states.get(e)}adoptWorkerState(e,t){t&&this.states.set(e,t)}calculate(e,t){let n=H(t,`p`,10,1),r=V(t,`x`,1),i=H(t,`q`,9,1),a={atr:Ha(Wa(e),n),firstHigh:[],firstLow:[]};for(let t=0;t<e.length;t++)zc(e,a,t,n,r);let o=R(e,e.map((e,t)=>Bc(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=H(t,`p`,10,1),s=V(t,`x`,1),c=H(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,zc(e,i,t,o,s),this.writePoint(n,e,t,Bc(i,t,c))}return n}};function zc(e,t,n,r,i){let a=t.atr[n],o=Ya(e,n,r),s=Xa(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 Bc(e,t,n){let r=Ga(e.firstHigh,t,n),i=Ka(e.firstLow,t,n);return r!==void 0&&i!==void 0?{long:i,short:r}:null}var Vc=class extends B{descriptor={id:`bbpb`,name:`Bollinger Bands %B`,placement:`panel`,defaultConfig:{period:20,stdDev:2,source:`close`},shortName:`%B`,inputs:{period:{kind:`int`,min:2},stdDev:{kind:`number`,min:.1,step:.1},source:{source:!0}},plots:[{key:`value`,title:`%B`,color:0}],levels:[0,.5,1]};read(e){return{period:H(e,`period`,20,2),k:V(e,`stdDev`,2)}}pointAt(e,t,{period:n,k:r}){let i=Ja(e,t,n);return!i||i.sd===0?null:{value:(e[t].close-(i.mean-r*i.sd))/(2*r*i.sd)}}},Hc=class extends B{descriptor={id:`bbw`,name:`Bollinger BandWidth`,placement:`panel`,defaultConfig:{period:20,stdDev:2,source:`close`},shortName:`BBW`,inputs:{period:{kind:`int`,min:2},stdDev:{kind:`number`,min:.1,step:.1},source:{source:!0}},plots:[{key:`value`,title:`BBW`,color:0}]};read(e){return{period:H(e,`period`,20,2),k:V(e,`stdDev`,2)}}pointAt(e,t,{period:n,k:r}){let i=Ja(e,t,n);return!i||i.mean===0?null:{value:2*r*i.sd/i.mean}}},Uc=class extends B{descriptor={id:`mom`,name:`Momentum`,placement:`panel`,defaultConfig:{period:10,source:`close`},shortName:`MOM`,inputs:{period:{kind:`int`,min:1},source:{source:!0}},plots:[{key:`value`,title:`MOM`,color:0}],levels:[0]};read(e){return H(e,`period`,10,1)}pointAt(e,t,n){return t>=n?{value:e[t].close-e[t-n].close}:null}},Wc=class extends B{descriptor={id:`hv`,name:`Historical Volatility`,placement:`panel`,defaultConfig:{period:10,annual:365,source:`close`},shortName:`HV`,inputs:{period:{kind:`int`,min:2},annual:{kind:`number`,label:`Bars per year`,min:1},source:{source:!0}},plots:[{key:`value`,title:`HV`,color:0}],scale:{min:0}};read(e){return{period:H(e,`period`,10,2),annual:Math.max(1,V(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)}}},Gc=class extends I{descriptor={id:`vo`,name:`Volume Oscillator`,placement:`panel`,defaultConfig:{short:5,long:10},shortName:`Vol Osc`,inputs:{short:{kind:`int`,min:1},long:{kind:`int`,min:1}},plots:[{key:`value`,title:`Vol Osc`,color:0}],levels:[0]};emas=new WeakMap;workerState(e){return this.emas.get(e)}adoptWorkerState(e,t){t&&this.emas.set(e,t)}calculate(e,t){let n=e.map(e=>e.volume),r=z(n,H(t,`short`,5,1)),i=z(n,H(t,`long`,10,1)),a=R(e,qa(r.map((e,t)=>Kc(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/(H(t,`short`,5,1)+1),c=2/(H(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=Kc(a,o);this.writePoint(n,e,t,r===void 0?null:{value:r})}return n}};function Kc(e,t){return e===void 0||t===void 0||t===0?void 0:100*(e-t)/t}var qc=class extends I{descriptor={id:`ulcer`,name:`Ulcer Index`,placement:`panel`,defaultConfig:{period:14,source:`close`},shortName:`Ulcer`,inputs:{period:{kind:`int`,min:1},source:{source:!0}},plots:[{key:`value`,title:`Ulcer`,color:0}],scale:{min:0}};drawdowns=new WeakMap;workerState(e){return this.drawdowns.get(e)}adoptWorkerState(e,t){t&&this.drawdowns.set(e,t)}calculate(e,t){let n=H(t,`period`,14,1),r=e.map((t,r)=>Jc(e,r,n)),i=R(e,e.map((e,t)=>Yc(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=H(t,`period`,14,1);for(let t=r;t<e.length;t++)i[t]=Jc(e,t,a);i.length=e.length;for(let t=r;t<e.length;t++)this.writePoint(n,e,t,Yc(i,t,a));return n}};function Jc(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 Yc(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 Xc=class extends I{descriptor={id:`smi`,name:`Stochastic Momentum Index`,placement:`panel`,defaultConfig:{period:10,smooth:3,signal:3},shortName:`SMI`,inputs:{period:{kind:`int`,min:1},smooth:{kind:`int`,min:1},signal:{kind:`int`,min:1}},plots:[{key:`smi`,title:`SMI`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[40,-40]};calculate(e,t){let n=H(t,`period`,10,1),r=H(t,`smooth`,3,1),i=H(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=Ya(e,t,n),i=Xa(e,t,n);r===void 0||i===void 0||(a[t]=e[t].close-(r+i)/2,o[t]=r-i)}let s=z(z(a,r),r),c=z(z(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=z(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}))}},Zc=class extends I{descriptor={id:`rvix`,name:`Relative Volatility Index`,placement:`panel`,defaultConfig:{period:10,smooth:14},shortName:`RVI (vol)`,inputs:{period:{kind:`int`,min:2},smooth:{kind:`int`,min:1}},plots:[{key:`value`,title:`RVI`,color:0}],levels:[80,50,20],scale:{min:0,max:100}};calculate(e,t){let n=H(t,`period`,10,2),r=H(t,`smooth`,14,1),i=Ua(Ra(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=z(a,r),c=z(o,r);return R(e,qa(s.map((e,t)=>{let n=c[t];if(!(e===void 0||n===void 0))return e+n===0?50:100*e/(e+n)})))}},Qc=class extends B{descriptor={id:`trendstrength`,name:`Trend Strength Index`,placement:`panel`,defaultConfig:{period:14},shortName:`TSI (trend)`,inputs:{period:{kind:`int`,min:2}},plots:[{key:`value`,title:`Trend`,color:0}],levels:[0],scale:{min:-1,max:1}};read(e){return H(e,`period`,14,2)}pointAt(e,t,n){let r=Qa(e,t,n);return r?{value:r.r}:null}},$c=class extends B{descriptor={id:`lrslope`,name:`Linear Regression Slope`,placement:`panel`,defaultConfig:{period:14},shortName:`LR Slope`,inputs:{period:{kind:`int`,min:2}},plots:[{key:`value`,title:`Slope`,color:0}],levels:[0]};read(e){return H(e,`period`,14,2)}pointAt(e,t,n){let r=Qa(e,t,n);return r?{value:r.slope}:null}},el=class extends B{descriptor={id:`stderror`,name:`Standard Error`,placement:`panel`,defaultConfig:{period:14},shortName:`StdErr`,inputs:{period:{kind:`int`,min:3}},plots:[{key:`value`,title:`StdErr`,color:0}],scale:{min:0}};read(e){return H(e,`period`,14,3)}pointAt(e,t,n){let r=Qa(e,t,n);return r?{value:r.stdErr}:null}},tl=class extends B{descriptor={id:`adr`,name:`Average Day Range`,placement:`panel`,defaultConfig:{period:14},shortName:`ADR`,inputs:{period:{kind:`int`,min:1}},plots:[{key:`value`,title:`ADR`,color:0}],scale:{min:0}};read(e){return H(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}}},nl=class extends B{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}},rl=class extends I{descriptor={id:`seb`,name:`Standard Error Bands`,placement:`overlay`,defaultConfig:{period:21,mult:2,smooth:3},shortName:`SEB`,inputs:{period:{kind:`int`,min:3},mult:{kind:`number`,min:0,step:.1},smooth:{kind:`int`,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=H(t,`period`,21,3),r=V(t,`mult`,2),i=H(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=Qa(e,t,n);i&&(a[t]=i.end,o[t]=i.end+r*i.stdErr,s[t]=i.end-r*i.stdErr)}let c=za(a,i),l=za(o,i),u=za(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]}))}},il=[3,5,8,10,12,15],al=[30,35,40,45,50,60],ol=class extends I{descriptor={id:`gmma`,name:`Guppy Multiple Moving Average`,placement:`overlay`,defaultConfig:{},shortName:`GMMA`,plots:[...il.map(e=>({key:`s${e}`,title:`EMA ${e}`,color:0})),...al.map(e=>({key:`l${e}`,title:`EMA ${e}`,color:1}))]};calculate(e,t){let n=Ra(e),r=[...il.map(e=>[`s${e}`,z(n,e)]),...al.map(e=>[`l${e}`,z(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}))}},sl=class extends I{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:{kind:`int`,min:1},ma2:{kind:`int`,min:1},ma3:{kind:`int`,min:1},ma4:{kind:`int`,min:1},exponential:{kind:`int`,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=V(t,`exponential`,0)>=1?z:za,r=Ra(e),i=[`ma1`,`ma2`,`ma3`,`ma4`],a=[20,50,100,200],o=i.map((e,i)=>[e,n(r,H(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}))}},cl=class extends B{read(e){return null}pointAt(e,t){return{value:this.price(e[t])}}},ll=class extends cl{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}},ul=class extends cl{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}},dl=class extends cl{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}},fl=class extends cl{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}},pl=class extends B{descriptor={id:`psy`,name:`Psychological Line`,placement:`panel`,defaultConfig:{period:10},inputs:{period:{kind:`int`,min:1}},shortName:`PSY`,plots:[{key:`value`,title:`PSY`,color:0}],scale:{min:0,max:100},levels:[25,75]};read(e){return H(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}}},ml=class extends B{descriptor={id:`newpsy`,name:`New Psychological Line`,placement:`panel`,defaultConfig:{period:10},inputs:{period:{kind:`int`,min:1}},shortName:`New PSY`,plots:[{key:`value`,title:`New PSY`,color:0}],scale:{min:-100,max:100},levels:[-50,0,50]};read(e){return H(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}}},hl=class extends B{descriptor={id:`vr`,name:`Volume Ratio`,placement:`panel`,defaultConfig:{period:20},inputs:{period:{kind:`int`,min:1}},shortName:`VR`,plots:[{key:`value`,title:`VR`,color:0}],levels:[70,150,450]};read(e){return H(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}},gl=class extends B{descriptor={id:`abratio`,name:`AB Ratio`,placement:`panel`,defaultConfig:{period:26},inputs:{period:{kind:`int`,min:1}},shortName:`AB Ratio`,plots:[{key:`a`,title:`A`,color:0},{key:`b`,title:`B`,color:1}],levels:[100]};read(e){return H(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}},_l=class extends I{descriptor={id:`sonar`,name:`Sonar`,placement:`panel`,defaultConfig:{period:20,lookback:9,signal:9},inputs:{period:{kind:`int`,min:1},lookback:{kind:`int`,min:1},signal:{kind:`int`,min:1}},shortName:`Sonar`,plots:[{key:`sonar`,title:`Sonar`,color:0},{key:`signal`,title:`Signal`,color:1}],levels:[0]};calculate(e,t){let n=H(t,`period`,20,1),r=H(t,`lookback`,9,1),i=H(t,`signal`,9,1),a=z(Ra(e),n),o=a.map((e,t)=>e!==void 0&&t>=r&&a[t-r]!==void 0?e-a[t-r]:void 0),s=z(o,i);return R(e,o.map((e,t)=>e===void 0?null:s[t]===void 0?{sonar:e}:{sonar:e,signal:s[t]}))}},vl=class extends B{descriptor={id:`sigma`,name:`Sigma`,placement:`panel`,defaultConfig:{period:20},inputs:{period:{kind:`int`,min:2}},shortName:`Sigma`,plots:[{key:`value`,title:`Sigma`,color:0}],levels:[-2,0,2]};read(e){return H(e,`period`,20,2)}pointAt(e,t,n){let r=Ja(e,t,n);return r?{value:r.sd<=Math.abs(r.mean)*1e-9?0:(e[t].close-r.mean)/r.sd}:null}},yl=class extends B{descriptor={id:`vhf`,name:`Vertical Horizontal Filter`,placement:`panel`,defaultConfig:{period:28},inputs:{period:{kind:`int`,min:1}},shortName:`VHF`,plots:[{key:`value`,title:`VHF`,color:0}]};read(e){return H(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}},bl=class extends B{descriptor={id:`rsquared`,name:`R-Squared`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:2}},shortName:`R²`,plots:[{key:`value`,title:`R²`,color:0}],scale:{min:0,max:1}};read(e){return H(e,`period`,14,2)}pointAt(e,t,n){let r=Qa(e,t,n);return r?{value:r.r*r.r}:null}};function xl(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 Sl=class extends B{descriptor={id:`rwi`,name:`Random Walk Index`,placement:`panel`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:2}},shortName:`RWI`,plots:[{key:`high`,title:`RWI High`,color:0},{key:`low`,title:`RWI Low`,color:1}],levels:[1]};read(e){return H(e,`period`,14,2)}pointAt(e,t,n){if(t<n)return null;let r=0,i=0,a=xl(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+=xl(e,t-o)}return{high:r,low:i}}},Cl=1e3,wl=class extends I{calculate(e,t){let n=Array(e.length).fill(void 0),r=Cl;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=z(n,H(t,`signal`,255,1));return R(e,n.map((e,t)=>i[t]===void 0?{value:e}:{value:e,signal:i[t]}))}},Tl=class extends wl{descriptor={id:`nvi`,name:`Negative Volume Index`,placement:`panel`,defaultConfig:{signal:255},inputs:{signal:{kind:`int`,min:1}},shortName:`NVI`,plots:[{key:`value`,title:`NVI`,color:0},{key:`signal`,title:`Signal`,color:1}]};counts(e,t){return e<t}},El=class extends wl{descriptor={id:`pvi`,name:`Positive Volume Index`,placement:`panel`,defaultConfig:{signal:255},inputs:{signal:{kind:`int`,min:1}},shortName:`PVI`,plots:[{key:`value`,title:`PVI`,color:0},{key:`signal`,title:`Signal`,color:1}]};counts(e,t){return e>t}},Dl=class extends B{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))}}},Ol=class extends B{descriptor={id:`iii`,name:`Intraday Intensity`,placement:`panel`,defaultConfig:{period:21},inputs:{period:{kind:`int`,min:1}},shortName:`III`,plots:[{key:`value`,title:`III %`,color:0,kind:`histogram`,tone:`sign`,downColor:1}],scale:{zero:!0},levels:[0]};read(e){return H(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}}},kl=class extends B{descriptor={id:`volpct`,name:`Volume vs Average`,placement:`panel`,defaultConfig:{period:20},inputs:{period:{kind:`int`,min:1}},shortName:`Vol %`,plots:[{key:`value`,title:`Vol %`,color:0,kind:`histogram`,tone:`sign`,downColor:1}],scale:{zero:!0},levels:[0]};read(e){return H(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}},Al=class extends B{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}},jl=class extends B{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}},Ml=class extends I{descriptor={id:`binarywave`,name:`Binary Wave`,placement:`panel`,defaultConfig:{ma:20,fast:12,slow:26,signal:9,roc:12,stoch:14},inputs:{ma:{kind:`int`,min:1},fast:{kind:`int`,min:1},slow:{kind:`int`,min:1},signal:{kind:`int`,min:1},roc:{kind:`int`,min:1},stoch:{kind:`int`,min:1}},shortName:`Binary Wave`,plots:[{key:`value`,title:`Wave`,color:0,kind:`step`}],scale:{min:-4,max:4},levels:[0]};calculate(e,t){let n=Ra(e),r=za(n,H(t,`ma`,20,1)),i=z(n,H(t,`fast`,12,1)),a=z(n,H(t,`slow`,26,1)),o=i.map((e,t)=>e!==void 0&&a[t]!==void 0?e-a[t]:void 0),s=z(o,H(t,`signal`,9,1)),c=H(t,`roc`,12,1),l=H(t,`stoch`,14,1),u=e=>e?1:-1;return R(e,qa(e.map((t,i)=>{let a=Ya(e,i,l),d=Xa(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)})))}},Nl=class extends I{descriptor={id:`sroc`,name:`Smoothed Rate of Change`,placement:`panel`,defaultConfig:{ema:13,roc:21},inputs:{ema:{kind:`int`,min:1},roc:{kind:`int`,min:1}},shortName:`S-ROC`,plots:[{key:`value`,title:`S-ROC`,color:0}],levels:[0]};calculate(e,t){let n=z(Ra(e),H(t,`ema`,13,1)),r=H(t,`roc`,21,1);return R(e,qa(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})))}},Pl=class extends B{descriptor={id:`tsf`,name:`Time Series Forecast`,placement:`overlay`,defaultConfig:{period:14},inputs:{period:{kind:`int`,min:2}},shortName:`TSF`,plots:[{key:`value`,title:`TSF`,color:0}]};read(e){return H(e,`period`,14,2)}pointAt(e,t,n){let r=Qa(e,t,n);return r?{value:r.end+r.slope}:null}},Fl=class extends B{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}}},Il=class extends I{descriptor={id:`rainbow`,name:`Moving Average Rainbow`,placement:`overlay`,defaultConfig:{first:10,step:10,count:10,exponential:0},shortName:`Rainbow`,inputs:{first:{kind:`int`,min:1},step:{kind:`int`,min:1},count:{kind:`int`,min:1,max:20},exponential:{kind:`int`,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=H(t,`first`,10,1),r=H(t,`step`,10,1),i=Math.min(20,H(t,`count`,10,1)),a=H(t,`exponential`,0,0)>=1?z:za,o=Ra(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}))}},Ll=.05,Rl=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)*Ll}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 U(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 zl(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 Bl(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 Vl=[U(`doji`,`Doji`,`Doji`,`neutral`,`indecision`,1,null,(e,t)=>e.doji(t)),U(`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)),U(`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),U(`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),U(`hammer`,`Hammer`,`Hammer`,`bullish`,`reversal`,1,`down`,zl),U(`hangingMan`,`Hanging Man`,`Hanging`,`bearish`,`reversal`,1,`up`,zl),U(`invertedHammer`,`Inverted Hammer`,`Inv Hammer`,`bullish`,`reversal`,1,`down`,Bl),U(`shootingStar`,`Shooting Star`,`Shooting`,`bearish`,`reversal`,1,`up`,Bl),U(`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)),U(`bullishMarubozu`,`Bullish Marubozu`,`Marubozu`,`bullish`,`continuation`,1,null,(e,t)=>e.white(t)&&e.marubozu(t)),U(`bearishMarubozu`,`Bearish Marubozu`,`Marubozu`,`bearish`,`continuation`,1,null,(e,t)=>e.black(t)&&e.marubozu(t)),U(`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),U(`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)],Hl=[U(`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)}),U(`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)}),U(`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),U(`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),U(`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)),U(`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)),U(`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)}),U(`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)}),U(`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)),U(`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)),U(`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)),U(`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)),U(`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)),U(`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)),U(`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)),U(`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)),U(`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)}),U(`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}),U(`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)}),U(`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)),U(`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 Ul(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 Wl(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 Gl(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 Kl(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 ql=[U(`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)}),U(`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)}),U(`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)}),U(`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)}),U(`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)}),U(`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)}),U(`threeWhiteSoldiers`,`Three White Soldiers`,`3 Soldiers`,`bullish`,`reversal`,3,null,(e,t)=>Ul(e,t-2)),U(`threeBlackCrows`,`Three Black Crows`,`3 Crows`,`bearish`,`reversal`,3,null,(e,t)=>Wl(e,t-2)),U(`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)}),U(`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)}),U(`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)}),U(`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)}),U(`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)}),U(`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)}),U(`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)}),U(`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)}),U(`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)}),U(`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)}),U(`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)}),U(`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)}),U(`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})],Jl=[U(`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)&&Gl(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)}),U(`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)&&Gl(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)}),U(`risingThreeMethods`,`Rising Three Methods`,`Rising 3`,`bullish`,`continuation`,5,`up`,(e,t)=>{let n=t-4;return e.white(n)&&e.long(n,n)&&Kl(e,n,n+1,n+3,!0)&&Gl(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)}),U(`fallingThreeMethods`,`Falling Three Methods`,`Falling 3`,`bearish`,`continuation`,5,`down`,(e,t)=>{let n=t-4;return e.black(n)&&e.long(n,n)&&Kl(e,n,n+1,n+3,!1)&&Gl(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)}),U(`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}),U(`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)}),U(`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)}),U(`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)}),U(`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)})],Yl=[...Vl,...Hl,...ql,...Jl],Xl=Yl.map(e=>e.info);function Zl(e){let t=e.trendPeriod;return t!==void 0&&Number.isFinite(t)?Math.max(2,Math.floor(t)):10}function Ql(e){if(!e.patterns)return Yl;let t=new Set(e.patterns);return Yl.filter(e=>t.has(e.info.id))}function $l(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 eu(e,t={}){let n=new Rl(e,Zl(t)),r=Ql(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 $l(n,t,r))i.push({index:t,time:e[t].time,pattern:a.info});return i}function tu(e={}){return Ql(e)}var nu=6,ru=4,iu=12,au=class extends B{descriptor={id:`candlepatterns`,name:`Candlestick Patterns`,placement:`overlay`,defaultConfig:{trendPeriod:10,reversal:1,continuation:1,indecision:0},shortName:`Patterns`,inputs:{trendPeriod:{kind:`int`,min:2},reversal:{kind:`int`,min:0,max:1},continuation:{kind:`int`,min:0,max:1},indecision:{kind:`int`,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 H(e,`reversal`,1,0)>=1&&t.add(`reversal`),H(e,`continuation`,1,0)>=1&&t.add(`continuation`),H(e,`indecision`,0,0)>=1&&t.add(`indecision`),{trendPeriod:H(e,`trendPeriod`,10,2),defs:tu().filter(e=>t.has(e.info.kind))}}pointAt(e,t,{trendPeriod:n,defs:r}){let i=$l(new Rl(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:Xl.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>=iu,{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.w(n,r),l=Xl[o.code??-1]?.short??``;if(o.bull!==void 0&&f(`bull`)){let n=e.k(o.bull,r)+ru;t.fillStyle=i.colors[3]??i.colors[0],ou(t,s,n,`up`),c&&l&&(m=su(t,l,s,Math.min(d,n+nu+2),`top`,m))}else if(o.bear!==void 0&&f(`bear`)){let n=e.k(o.bear,r)-ru;t.fillStyle=i.colors[4]??i.colors[0],ou(t,s,n,`down`),c&&l&&(p=su(t,l,s,Math.max(u,n-nu-2),`bottom`,p))}else if(o.neutral!==void 0&&f(`neutral`)){let n=e.k(o.neutral,r)-ru-nu/2;t.fillStyle=i.colors[1]??i.colors[0],t.beginPath(),t.arc(s,n,nu/2-1,0,Math.PI*2),t.fill(),c&&l&&(p=su(t,l,s,Math.max(u,n-nu/2-2),`bottom`,p))}}t.restore()}};function ou(e,t,n,r){let i=nu/2;e.beginPath(),r===`up`?(e.moveTo(t,n),e.lineTo(t-i,n+nu),e.lineTo(t+i,n+nu)):(e.moveTo(t,n),e.lineTo(t-i,n-nu),e.lineTo(t+i,n-nu)),e.closePath(),e.fill()}function su(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 cu=500,lu=class extends I{descriptor={id:`machannel`,name:`Moving Average Channel`,placement:`overlay`,defaultConfig:{upperLength:20,lowerLength:20,upperOffset:0,lowerOffset:0},shortName:`MA Channel`,inputs:{upperLength:{kind:`int`,min:1},lowerLength:{kind:`int`,min:1},upperOffset:{kind:`int`,min:-cu,max:cu},lowerOffset:{kind:`int`,min:-cu,max:cu}},fills:[{between:[`upper`,`lower`],color:0,opacity:.08}],plots:[{key:`upper`,title:`Upper`,color:0},{key:`lower`,title:`Lower`,color:1}]};calculate(e,t){let n=du(za(e.map(e=>e.high),H(t,`upperLength`,20,1)),uu(t,`upperOffset`)),r=du(za(e.map(e=>e.low),H(t,`lowerLength`,20,1)),uu(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}}}))}};function uu(e,t){let n=Number(e.params[t]??0);return Number.isFinite(n)?Math.max(-cu,Math.min(cu,Math.round(n))):0}function du(e,t){return e.map((n,r)=>e[r-t])}var fu=500,pu=class extends B{descriptor={id:`hamming`,name:`Moving Average Hamming`,placement:`overlay`,defaultConfig:{period:10,source:`close`},shortName:`HMA (Hamming)`,inputs:{period:{kind:`int`,min:2,max:fu},source:{source:!0}},plots:[{key:`value`,title:`MA`,color:0}]};read(e){let t=Math.min(fu,H(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}}},mu=[`sma`,`ema`,`wma`];function hu(e,t,n){return e===`ema`?z(t,n):e===`wma`?Va(t,n):za(t,n)}var gu=class extends I{calculate(e,t){let n=mu.includes(t.params.type)?t.params.type:`sma`,r=Ra(e),i=this.lengths.map(([e,i])=>hu(n,r,H(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}))}},_u=class extends gu{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:{kind:`int`,min:1},second:{kind:`int`,min:1},type:{options:mu},source:{source:!0}},plots:[{key:`ma1`,title:`MA 1`,color:0},{key:`ma2`,title:`MA 2`,color:1}]}},vu=class extends gu{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:{kind:`int`,min:1},second:{kind:`int`,min:1},third:{kind:`int`,min:1},type:{options:mu},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}]}},yu=class extends I{descriptor={id:`volindex`,name:`Volatility Index`,placement:`overlay`,defaultConfig:{period:7,mult:3},shortName:`VI`,inputs:{period:{kind:`int`,min:1},mult:{kind:`number`,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=H(t,`period`,7,1),r=Math.max(.1,V(t,`mult`,3)),i=Ha(Wa(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)}},bu=class extends I{descriptor={id:`asi`,name:`Accumulative Swing Index`,placement:`panel`,defaultConfig:{limit:10},shortName:`ASI`,inputs:{limit:{kind:`number`,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,V(t,`limit`,10)),r=Array(e.length).fill(null),i=0;for(let t=1;t<e.length;t++)i+=xu(e[t-1],e[t],n),r[t]={value:i};return R(e,r)}};function xu(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 Su=class extends B{descriptor={id:`advdecline`,name:`Advance/Decline`,placement:`panel`,defaultConfig:{length:10},shortName:`A/D Ratio`,inputs:{length:{kind:`int`,min:1}},plots:[{key:`value`,title:`Ratio`,color:0}],scale:{min:0}};read(e){return{length:H(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}}},Cu=class extends B{descriptor={id:`majority`,name:`Majority Rule`,placement:`panel`,defaultConfig:{period:14},shortName:`Majority`,inputs:{period:{kind:`int`,min:1}},plots:[{key:`value`,title:`Majority`,color:0}],scale:{min:0,max:100},levels:[50]};read(e){return{period:H(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}}},wu=34,Tu=30,Eu=class extends I{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=z(Ra(e),wu),r=Array(e.length).fill(null);for(let t=1;t<e.length;t++){let i=n[t],a=n[t-1],o=Ya(e,t,Tu),s=Xa(e,t,Tu);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.k(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.w(t,r),y:e.k(n,r),baseY:c,color:Du(n)})}this.drawHistogram(t,l,Math.max(1,r.barWidth))}};function Du(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 Ou=class extends I{descriptor={id:`smiergodic`,name:`SMI Ergodic`,placement:`panel`,defaultConfig:{short:5,long:20,signal:5,source:`close`},shortName:`SMIIO`,inputs:{short:{kind:`int`,min:1},long:{kind:`int`,min:1},signal:{kind:`int`,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=H(t,`short`,5,1),r=H(t,`long`,20,1),i=e.map((t,n)=>n===0?void 0:t.close-e[n-1].close),a=z(z(i,r),n),o=z(z(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=z(s,H(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}}))}},ku=class extends I{descriptor={id:`po`,name:`Price Oscillator`,placement:`panel`,defaultConfig:{short:10,long:21,source:`close`},shortName:`PO`,inputs:{short:{kind:`int`,min:1},long:{kind:`int`,min:1},source:{source:!0}},plots:[{key:`value`,title:`PO`,color:0}],scale:{zero:!0}};calculate(e,t){let n=Ra(e),r=za(n,H(t,`short`,10,1)),i=za(n,H(t,`long`,21,1));return R(e,qa(r.map((e,t)=>e===void 0||i[t]===void 0?void 0:e-i[t])))}},Au=e=>({period:H(e,`period`,10,1),annual:Math.max(1,V(e,`annual`,365))}),ju={period:{kind:`int`,min:1},annual:{kind:`number`,label:`Bars per year`,min:1}},Mu=class extends B{descriptor={id:`volohlc`,name:`Volatility O-H-L-C`,placement:`panel`,defaultConfig:{period:10,annual:365},shortName:`Vol OHLC`,inputs:ju,plots:[{key:`value`,title:`Volatility`,color:0}],scale:{min:0}};read(e){return Au(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))}}},Nu=class extends B{descriptor={id:`volzt`,name:`Volatility Zero Trend Close-to-Close`,placement:`panel`,defaultConfig:{period:10,annual:365},shortName:`Vol ZT`,inputs:ju,plots:[{key:`value`,title:`Volatility`,color:0}],scale:{min:0}};read(e){return Au(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)}}},Pu=[()=>new Ro,()=>new zo,()=>new Bo,()=>new Ko,()=>new Yo,()=>new Xo,()=>new Zo,()=>new Qo,()=>new $o,()=>new ts,()=>new rs,()=>new is,()=>new as,()=>new os,()=>new ls,()=>new us,()=>new ds,()=>new fs,()=>new ms,()=>new hs,()=>new gs,()=>new bs,()=>new Cs,()=>new ws,()=>new Ts,()=>new Es,()=>new Ds,()=>new Os,()=>new ks,()=>new As,()=>new js,()=>new Ms,()=>new Ns,()=>new Ps,()=>new Fs,()=>new xc,()=>new wc,()=>new Tc,()=>new Ec,()=>new xs,()=>new Ss,()=>new Is,()=>new Ls,()=>new Rs,()=>new zs,()=>new Vs,()=>new Hs,()=>new Ws,()=>new Gs,()=>new Js,()=>new Ys,()=>new Zs,()=>new Qs,()=>new $s,()=>new ec,()=>new tc,()=>new nc,()=>new rc,()=>new ac,()=>new oc,()=>new sc,()=>new cc,()=>new lc,()=>new uc,()=>new pc,()=>new hc,()=>new _c,()=>new vc,()=>new yc,()=>new bc,()=>new Dc,()=>new Oc,()=>new kc,()=>new Ac,()=>new jc,()=>new Mc,()=>new Fc,()=>new Lc,()=>new Rc,()=>new Vc,()=>new Hc,()=>new Uc,()=>new Wc,()=>new Gc,()=>new qc,()=>new Xc,()=>new Zc,()=>new Qc,()=>new $c,()=>new el,()=>new tl,()=>new nl,()=>new rl,()=>new ol,()=>new sl,()=>new ll,()=>new ul,()=>new dl,()=>new lu,()=>new pu,()=>new _u,()=>new vu,()=>new yu,()=>new bu,()=>new Su,()=>new Cu,()=>new Eu,()=>new Ou,()=>new ku,()=>new Mu,()=>new Nu,()=>new pl,()=>new ml,()=>new hl,()=>new gl,()=>new _l,()=>new vl,()=>new yl,()=>new bl,()=>new Sl,()=>new Tl,()=>new El,()=>new Dl,()=>new Ol,()=>new kl,()=>new Al,()=>new jl,()=>new Ml,()=>new Nl,()=>new Pl,()=>new fl,()=>new Fl,()=>new Il,()=>new au];function Fu(e){for(let t of Pu){let n=t();La.add(n),e.register(n)}}var Iu=[`movingAverages`,`trend`,`oscillators`,`volatility`,`volume`,`bands`,`patterns`,`other`],Lu=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 Ru(e){return e.category??Lu.get(e.id)??`other`}var zu=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Bu=1,Vu=.1;function Hu(e,t){return t?.kind?t.kind:t?.source?`source`:t?.options?`choice`:typeof e==`boolean`?`boolean`:typeof e==`number`?`number`:typeof e==`string`&&zu.test(e)?`color`:`text`}function Uu(e){return Object.entries(e.defaultConfig).map(([t,n])=>{let r=e.inputs?.[t],i=Hu(n,r),a={name:t,kind:i,default:n};return r?.label!==void 0&&(a.label=r.label),r?.min!==void 0&&(a.min=r.min),r?.max!==void 0&&(a.max=r.max),i===`int`&&(a.step=r?.step??Bu),i===`number`&&(a.step=r?.step??(Number.isInteger(n)?Bu:Vu)),i===`choice`&&r?.options&&(a.options=r.options),a})}function Wu(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 Gu=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=fo(n),a={type:`calculate`,bars:i,jobs:[{requestId:r,indicatorId:e,config:t}]},o=i.time.slice();return new Promise((t,n)=>{let s={resolve:t,reject:n,timer:null,times:o};this.timeoutMs>0&&(s.timer=setTimeout(()=>{this.pending.delete(r),n(Error(`Indicator worker timeout (${this.timeoutMs}ms): ${e}`))},this.timeoutMs)),this.pending.set(r,s),this.worker.postMessage(a,mo(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(!Wu(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(Co(e.output,t.times??[]))}}};function Ku(){return typeof Worker>`u`?Promise.reject(Error(`Web Workers are not available here`)):Promise.resolve().then(()=>require(`./indicator.worker-Cd8ymg6p.cjs`)).then(({default:e})=>new e({name:`tradecanvas-indicators`}))}function qu(){if(typeof Worker>`u`)throw Error(`Web Workers are not available here`);return Ku()}var Ju=class{state=`starting`;worker=null;outbox=[];jobs=new Map;batch=null;nextId=1;pingId=0;onMessage=e=>this.receive(e.data);onError=e=>this.fail(Error(e.message||`Indicator worker error`));constructor(e){let t;try{t=e()}catch(e){this.fail(Yu(e));return}t instanceof Promise?t.then(e=>this.attach(e),e=>this.fail(Yu(e))):this.attach(t)}get usable(){return this.state===`starting`||this.state===`ready`}get ready(){return this.state===`ready`}submit(e,t){if(!this.usable)return null;let n=this.nextId++;this.jobs.set(n,{done:t,times:e.times});let{indicatorId:r,config:i,source:a,bars:o}=e;return this.batchFor(o).jobs.push({requestId:n,indicatorId:r,config:i,...a?{source:a}:{}}),n}batchFor(e){if(this.batch?.bars===e)return this.batch;this.sendBatch();let t={bars:e,jobs:[]};return this.batch=t,queueMicrotask(()=>{this.batch===t&&this.sendBatch()}),t}sendBatch(){let e=this.batch;this.batch=null;let t=e?.jobs.filter(e=>this.jobs.has(e.requestId))??[];!e||t.length===0||!this.usable||this.send({message:{type:`calculate`,bars:e.bars,jobs:t},transfer:mo(e.bars)})}cancel(e){let t=new Set(this.batch?.jobs.map(e=>e.requestId)),n=e.filter(e=>this.jobs.delete(e)&&!t.has(e));n.length>0&&this.usable&&this.send({message:{type:`cancel`,requestIds:n},transfer:[]})}terminate(){this.state=`closed`,this.jobs.clear(),this.batch=null,this.outbox=[],this.detach()}attach(e){if(!this.usable){e.terminate();return}this.worker=e,e.addEventListener(`message`,this.onMessage),e.addEventListener(`error`,this.onError),e.addEventListener(`messageerror`,this.onError),this.pingId=this.nextId++,e.postMessage({type:`ping`,requestId:this.pingId});let t=this.outbox;this.outbox=[];for(let n of t)e.postMessage(n.message,n.transfer)}send(e){this.worker?this.worker.postMessage(e.message,e.transfer):this.outbox.push(e)}receive(e){if(!Wu(e))return;if(e.type===`pong`){e.requestId===this.pingId&&this.state===`starting`&&(this.state=`ready`);return}let t=this.jobs.get(e.requestId);if(t){if(e.type===`result`){this.decode(e.requestId,t,e.output);return}this.jobs.delete(e.requestId),t.done(Error(e.message))}}decode(e,t,n){let r=new So(n,t.times),i=()=>{if(this.jobs.get(e)===t){if(!r.step(5e4)){setTimeout(i,0);return}this.jobs.delete(e),t.done({output:r.output(),...n.state===void 0?{}:{state:Do(n.state)}})}};i()}fail(e){if(!this.usable)return;this.state=`failed`,this.outbox=[],this.detach(),this.batch=null;let t=[...this.jobs.values()];this.jobs.clear();for(let{done:n}of t)n(e)}detach(){let e=this.worker;e&&(this.worker=null,e.removeEventListener(`message`,this.onMessage),e.removeEventListener(`error`,this.onError),e.removeEventListener(`messageerror`,this.onError),e.terminate())}};function Yu(e){return e instanceof Error?e:Error(String(e))}var Xu=class{client=null;holders=0;constructor(e=qu){this.spawn=e}acquire(){let e=this.client??=new Ju(this.spawn);this.holders++;let t=!0;return{client:e,release:()=>{t&&(t=!1,this.holders--,this.holders===0&&this.client===e&&(e.terminate(),this.client=null))}}}},Zu=new Xu,W={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},Qu=[...new Set(Object.values(W))].sort((e,t)=>t-e),$u=256;function ed(e){return e>=W.year?`year`:e>=W.month?`month`:e>=W.day?`day`:`time`}function td(e,t){if(!e)return 0;if(t.year!==e.year)return W.year;if(t.month!==e.month)return t.month%3==1?W.quarter:W.month;if(t.day!==e.day)return t.day%5==0?W.dayOfFive:W.day;if(t.hours!==e.hours){let e=t.hours;return e%12==0?W.hour12:e%6==0?W.hour6:e%3==0?W.hour3:W.hour}if(t.minutes!==e.minutes){let e=t.minutes;return e%30==0?W.minute30:e%15==0?W.minute15:e%5==0?W.minute5:W.minute}return W.within}var nd=256,rd=1.25;function id(e){return e>1?Math.ceil(rd**Math.ceil(Math.log(e)/Math.log(rd)-1e-9)):1}var ad=class{weights=new Uint8Array;times=[];weighed=null;weighedFrom=null;revision=0;chosen=new Int32Array;chosenFor=null;marks(e,t){let n=e.length;if(n===0)return[];let r=id(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)/nd)*nd+n;this.weigh(e,t.tz,t.exchangeZone??null,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,a){let o=n.length,s=(0,t.barTimeUnit)(n),c=(0,t.barsAreDaily)(n)===!0,l=c?e=>(0,t.barDateParts)(e,r,i):e=>(0,t.timeParts)(e,r),u=this.weighed,d=0;if(u&&u.tz===r&&u.exchangeZone===i&&u.daily===c&&u.unit===s){let e=Math.min(u.bars,o),t=this.times;if(n===this.weighedFrom?.deref()&&o>=u.bars)d=e>0&&n[e-1].time*s===t[e-1]?e:0;else{for(;d<e&&n[d].time*s===t[d];)d++;d<e&&(d=0)}}if(this.weighedFrom?.deref()!==n&&(this.weighedFrom=new WeakRef(n)),u&&d===o&&u.bars===o&&u.extent===a)return;let f=d>0&&this.weights.length>=a,p=f?this.weights:new Uint8Array(a+(a>>3)),m=d>0?this.times:[];d>0&&!f&&p.set(this.weights.subarray(0,d)),m.length=d;let h=d>0?l(m[d-1]):null;for(let t=d;t<a;t++){let r=(t<o?n[t].time:e.C(t,n))*s,i=l(r);p[t]=t>0&&r===m[t-1]?0:td(h,i),m[t]=r,h=i}this.weights=p,this.times=m,this.weighed={bars:o,tz:r,exchangeZone:i,daily:c,extent:a,unit:s},this.revision++}choose(e,t){let n=this.chosenFor;if(n&&n.gapBars===e&&n.extent===t&&n.revision===this.revision)return;let r=this.weights,i=new Uint8Array(t),a=[],o=new Int32Array($u+1);for(let e=0;e<t;e++)o[r[e]+1]++;for(let e=1;e<=$u;e++)o[e]+=o[e-1];let s=new Int32Array(t),c=o.slice(0,$u);for(let e=0;e<t;e++)s[c[r[e]]++]=e;for(let n of Qu)for(let r=o[n];r<o[n+1];r++){let n=s[r];if(i[n])continue;a.push(n);let o=Math.max(0,n-e+1),c=Math.min(t-1,n+e-1);for(let e=o;e<=c;e++)i[e]=1}this.chosen=Int32Array.from(a).sort(),this.chosenFor={gapBars:e,extent:t,revision:this.revision}}},od=e=>e<10?`0`+e:``+e,sd=8,cd=new Map;function ld(e){let t=cd.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))),cd.set(e,t)}return t}var ud=class{tz=null;exchangeZone=null;timeFormatter=null;timesPastData=!0;locale=`en-US`;columns=[];marker=new ad;setLocale(e){this.locale=e}setTimezoneOffset(e){this.tz=e}setExchangeTimeZone(e){this.exchangeZone=e}setTimeFormatter(e){this.timeFormatter=e}setTimesPastData(e){this.timesPastData=e}getTimesPastData(){return this.timesPastData}marks(e,t){let n=e.barWidth+e.barSpacing;if(!(n>0)||t.length===0)return[];let r=ci(t),i=this.marker.marks(r,{from:Math.floor(e.offset/n),to:Math.ceil((e.offset+e.chartRect.width)/n),gapBars:80/n,tz:this.tz,timesPastData:this.timesPastData,exchangeZone:this.exchangeZone});return r===t?i:pd(i)}label(e,n,r){if(this.timeFormatter)return this.timeFormatter(e.time,{kind:n,timeZone:this.tz});let i=r?(0,t.barDateParts)(e.time,this.tz,this.exchangeZone):(0,t.timeParts)(e.time,this.tz);if(n===`year`)return String(i.year);if(n===`month`)return ld(this.locale)[i.month-1];if(n===`day`)return String(i.day);let a=`${od(i.hours)}:${od(i.minutes)}`;return e.weight===W.within?`${a}:${od(new Date(e.time).getUTCSeconds())}`:a}labelColumns(){return this.columns}render(n,r,i,a,o){let{chartRect:s}=r,c=ci(a),l=o??s.y+s.height;n.strokeStyle=i.style?.axis.time.line??i.axisLine,n.lineWidth=1,n.globalAlpha=.65,n.beginPath(),e.y(n,s.x,s.x+s.width,l+.5),n.stroke(),n.globalAlpha=1;let u=r.barWidth+r.barSpacing,d=-r.offset+s.x+r.barWidth/2,f=Math.ceil((r.offset+s.width)/u),p=(0,t.barTimeUnit)(c),m=c.length>0?e.C(Math.min(f,c.length-1),c):Date.now(),h=(0,t.tzLabel)(this.tz,m*p),g=`500 ${i.font.sizeSmall-1}px ${i.font.family}`,_=s.x+s.width-4;n.font=g;let v=_-n.measureText(h).width-8,y=`500 ${i.font.sizeSmall}px ${i.font.family}`,b=`600 ${i.font.sizeSmall}px ${i.font.family}`;n.textBaseline=`top`,n.textAlign=`center`,n.fillStyle=i.style?.axis.time.text??i.axisLabel;let x=[],S=this.marks(r,a).sort((e,t)=>t.weight-e.weight||e.index-t.index),C=(0,t.barsAreDaily)(c)===!0;for(let e of S){let t=e.index*u+d;if(t<s.x)continue;let r=ed(e.weight),i=this.label(e,r,C);n.font=r===`year`?b:y;let a=n.measureText(i).width/2,o=Math.max(t,s.x+a);o+a>v||x.some(e=>o-a<e.right+sd&&o+a+sd>e.left)||(x.push({left:o-a,right:o+a}),n.fillText(i,o,l+7))}this.columns=x,n.font=g,n.textAlign=`right`,n.textBaseline=`top`,n.globalAlpha=.75,n.fillStyle=i.textSecondary,n.fillText(h,_,l+7),n.globalAlpha=1}},dd={year:3,month:2,day:1,time:0},fd=2;function pd(e){let t=[...new Set(e.map(e=>dd[ed(e.weight)]))].sort((e,t)=>t-e);if(t.length<=fd)return e;let n=t[fd-1];return e.filter(e=>dd[ed(e.weight)]>=n)}var md={line:16,handle:22,alert:16,order:16,button:8,divider:12},hd=300,gd=24,_d=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}},vd=new Set,yd=null,bd=4,xd=8,Sd=500,Cd=800,wd={ctrl:!1,shift:!1,alt:!1};function Td(){let e=typeof document<`u`?document.activeElement:null;return e instanceof Element&&e.closest(`[aria-modal="true"], [role="dialog"], [role="menu"]`)!==null}var Ed=class{panHandler=null;zoomHandler=null;crosshairHandler=null;axisDragHandler=null;alertDragHandler=null;axisViewportGetter=null;onAxisDoubleClick=null;onDrawingDoubleClick=null;onDrawingContextMenu=null;zoomArea=!1;idleCss=`crosshair`;showingIdle=!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 _d;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}setIdleCursor(e){this.idleCss=e,this.showingIdle&&(this.element.style.cursor=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}takesPressFromAddButton(e){return e===`move`||e!==null&&!!this.drawingManager?.isEraser()}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(){vd.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;vd.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`?this.idleCss:``,a=e=>{this.element.style.cursor!==e&&(this.element.style.cursor=e),this.showingIdle=e!==``&&e===this.idleCss},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();if(this.tradingManager?.isOverButton(n))return`pointer`;if(o&&this.tradingManager?.isOverDraggableLine(n,o))return`ns-resize`;if(this.zoomArea)return`zoom-in`;let s=o?this.drawingManager?.hoverCursorAt(n,o):null;return this.takesPressFromAddButton(s??null)?s??i():o&&this.priceAxisAdd?.button.hit(n,o)?(this.drawingManager?.clearHover(),`pointer`):s||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:md;this.pressPlacedPoint=!1,c||this.drawingManager?.setModifiers({ctrl:!1,shift:!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 r.ctrl&&!d&&!this.zoomArea&&s&&this.drawingManager?.beginCopyDrag(n,s,l)?(c&&a(`copy`),`taken`):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&&!d&&!(s&&this.drawingManager?.hoverCursorAt(n,s))?(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.takesPressFromAddButton(this.drawingManager?.hoverCursorAt(n,s)??null)?(this.drawingManager?.clearHover(),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(yd=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};this.drawingManager?.setModifiers({ctrl:t.ctrl,shift:t.shift}),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(this.drawingManager?.setModifiers({ctrl:e.ctrlKey||e.metaKey,shift:e.shiftKey}),!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`?bd:xd;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.drawingManager?.clearHover(),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=>{(e.key===`Shift`||e.key===`Control`||e.key===`Meta`)&&this.drawingManager?.setModifiers({ctrl:e.ctrlKey||e.metaKey,shift:e.shiftKey})},T=()=>this.drawingManager?.setModifiers({ctrl:!1,shift:!1}),E=e=>{if(w(e),Td())return;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}if(e.key!==`Escape`&&!this.ownsShortcuts())return;let t=this.drawingManager?.isDragging()??!1;this.drawingManager?.onKeyDown(e.key,e.ctrlKey||e.metaKey,e.shiftKey)&&(e.preventDefault(),t&&e.key===`Escape`&&a(i()))},D=t=>{if(this.touchActive||Date.now()-this.lastTouchAt<Cd){t.preventDefault();return}let r=e();if(!r)return;let i=this.getMousePos(t),a=this.onDrawingContextMenu&&!this.drawingManager?.getActiveTool()?this.drawingManager?.drawingAt(i,r):null;if(a){t.preventDefault(),this.onDrawingContextMenu?.(a,i);return}if(this.tradingManager?.onContextMenu(i,r)){t.preventDefault();return}this.onChartContextMenu?.(n(i),i)&&t.preventDefault()},O=e=>{if(yd=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,wd,`touch`);if(this.touchActive=!0,this.touchFallthrough=n===`pan`||n===`inert`,this.touchStartPrevented=!(this.touchFallthrough&&this.pageTakes().any),this.touchStartPrevented&&e.preventDefault(),n===`drawing`){k(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)},Sd)),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}}},k=t=>{this.onDrawingContextMenu&&(this.clearLongPress(),this.longPressTimer=setTimeout(()=>{this.longPressTimer=null;let n=e(),r=n?this.drawingManager?.drawingAt(t,n,md.line):null;r&&(v(null,`touch`,!0),this.longPressed=!0,this.touchYielded=!0,this.crosshairHandler?.onPointerLeave(),this.onDrawingContextMenu?.(r,t),this.onOverlayDirty?.())},Sd))},A=e=>{if(this.touchDecided)return!1;let t=e.x-this.touchStartPos.x,n=e.y-this.touchStartPos.y;if(Math.hypot(t,n)<=xd)return!1;this.touchDecided=!0;let r=this.pageTakes();return Math.abs(n)>=Math.abs(t)?r.y:r.x},j=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)>xd&&this.clearLongPress(),this.touchFallthrough&&this.pageTakes().any){if(!this.touchDecided&&Math.hypot(t.x-this.touchStartPos.x,t.y-this.touchStartPos.y)<=xd)return;if(A(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?.()}}},ee=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,md.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]))},te=()=>{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?.())},ne=()=>this.invalidateRect(),re=()=>this.invalidateRect(),ie=()=>this.invalidateRect(),ae=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`,ae,!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`,D),this.element.addEventListener(`touchstart`,O,{passive:!1}),this.element.addEventListener(`touchmove`,j,{passive:!1}),this.element.addEventListener(`touchend`,ee),this.element.addEventListener(`touchcancel`,te),document.addEventListener(`keydown`,E),document.addEventListener(`keyup`,w),window.addEventListener(`blur`,T),window.addEventListener(`resize`,ne),document.addEventListener(`scroll`,re,{capture:!0,passive:!0}),this.element.addEventListener(`mouseenter`,ie),this.boundHandlers.push(d,()=>this.element.removeEventListener(`mousedown`,m),()=>document.removeEventListener(`keyup`,w),()=>window.removeEventListener(`blur`,T),()=>document.removeEventListener(`dragstart`,ae,!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`,D),()=>this.element.removeEventListener(`touchstart`,O),()=>this.element.removeEventListener(`touchmove`,j),()=>this.element.removeEventListener(`touchend`,ee),()=>this.element.removeEventListener(`touchcancel`,te),()=>document.removeEventListener(`keydown`,E),()=>window.removeEventListener(`resize`,ne),()=>document.removeEventListener(`scroll`,re,{capture:!0}),()=>this.element.removeEventListener(`mouseenter`,ie))}detach(){vd.delete(this.element),this.savedTouchAction?this.element.style.setProperty(`touch-action`,this.savedTouchAction):this.element.style.removeProperty(`touch-action`),yd===this.element&&(yd=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 vd)if(e&&t.contains(e))return t===this.element;return yd===null||yd===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}}},Dd=16,Od=3,kd=Dd+Od,Ad=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-Dd-Od;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-Od-Dd/2,l=Dd/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()}},jd=100,Md=50,Nd=.1,Pd=60,Fd=16;function Id(){return typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches}var Ld=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>jd;)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=[],!Id()&&e&&Math.hypot(e.x,e.y)>Nd&&this.startMomentum(e.x,e.y)}cancelMomentum(){this.stopMomentum()}releaseVelocity(e){let t=this.samples[this.samples.length-1];if(!t||e-t.t>Md)return null;let n=this.samples.find(e=>t.t-e.t<=jd)??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*Fd,r=t*Fd,i=Math.hypot(n,r);i>Pd&&(n*=Pd/i,r*=Pd/i);let a=null,o=e=>{let t=a===null?1:Math.min(4,Math.max(0,(e-a)/Fd));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)}},Rd=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)}},zd=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}},Bd=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.I(t.y,n))}end(){this.draggingId=null}isActive(){return this.draggingId!==null}},Vd=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(Hd(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 Hd(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 Ud=.25,Wd=10,Gd=6,Kd=16,qd=18,Jd=8,Yd=16,Xd=15,Zd={min:0,max:1,step:.2,ticks:[0,.2,.4,.6,.8,1]};function Qd(e){for(let t=0;t<=Xd;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 Xd}var $d=(e,t)=>{let n=Number(e.toFixed(t));return n===0?0:n};function ef(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 Zd;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 Zd;let l=Qd(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($d(e*c,l));return f.length<2||!f.every(Number.isFinite)?Zd:{min:f[0],max:f[f.length-1],step:$d(c,l),ticks:f}}function G(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 tf=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),nf=new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1});function rf(e){return Math.abs(e)>=1e4?nf.format(e):tf.format(e)}function K(e){let t=Qd(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 af(e,n){return n??t.TC_SERIES_COLORS[e%t.TC_SERIES_COLORS.length]}function q(e,t,n=``){return`${n?`${n} `:``}${t}px ${e.font.family}`}function of(e,t){return(n,r=11)=>(e.font=q(t,r),e.measureText(n).width)}function sf(e,t,n,r=!1){let i=[],a=0,o=0;for(let s of e){let e=Wd+Gd+n(s.label,11);a>0&&(r||a+e>t)&&(o++,a=0),i.push({...s,x:a,y:o*qd}),a+=e+Kd}let s=e.length===0?0:o+1;return{items:i,rows:s,height:s*qd}}function cf(e,t,n,r,i){e.save(),e.font=q(i,11),e.textBaseline=`middle`,e.textAlign=`left`;for(let a of t.items){let t=r+a.y+qd/2;e.fillStyle=a.color,e.fillRect(n+a.x,t-Wd/2,Wd,Wd),e.fillStyle=i.textSecondary,e.fillText(a.label,n+a.x+Wd+Gd,t)}e.restore()}function lf(e,n,r,i,a){if(n.length===0)return;e.save();let o=n.some(e=>e.color)?Wd+Gd:0,s=0;for(let t of n)e.font=q(a,11,t.bold?`600`:``),s=Math.max(s,e.measureText(t.text).width);let c=s+o+Jd*2,l=n.length*Yd+Jd*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+Jd+n*Yd+Yd/2-2;t.color&&(e.fillStyle=t.color,e.fillRect(u+Jd,r-4,8,8)),e.font=q(a,11,t.bold?`600`:``),e.fillStyle=t.bold?a.text:a.textSecondary,e.fillText(t.text,u+Jd+o,r)}),e.restore()}function uf(t){let n=typeof t.getTransform==`function`?t.getTransform():void 0,r=n&&Number.isFinite(n.a)&&n.a>0?n.a:1,i=n&&Number.isFinite(n.d)&&n.d>0?n.d:1,a=n&&Number.isFinite(n.e)?n.e:0,o=n&&Number.isFinite(n.f)?n.f:0,s=Math.max(1,Math.floor(r));return{x:t=>(e.x(t*r+a-s/2)+s/2-a)/r,y:t=>(e.x(t*i+o-s/2)+s/2-o)/i,width:s/r}}function df(e,t,n,r,i){let a=uf(e);if(e.lineWidth=a.width,e.beginPath(),n===i){let i=a.y(n);e.moveTo(t,i),e.lineTo(r,i)}else{let r=a.x(t);e.moveTo(r,n),e.lineTo(r,i)}e.stroke()}var ff=6e4,pf=60*ff,mf=24*pf,hf=[ff,5*ff,15*ff,30*ff,pf,2*pf,4*pf,12*pf,mf,2*mf,7*mf,14*mf,30*mf,91*mf,182*mf,365*mf];function gf(e,t,n){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=e)return[];let r=(t-e)/Math.max(1,n),i=hf.find(e=>e>=r);i===void 0&&(i=Math.ceil(r/(365*mf))*365*mf);let a=[];for(let n=Math.ceil(e/i)*i;n<=t;n+=i)a.push(n);return a}function _f(e,t=8){let n=0;for(let r of e)if(Number.isFinite(r))for(;n<t&&Math.abs(r*10**n-Math.round(r*10**n))>1e-9*Math.max(1,Math.abs(r*10**n));)n++;return n}function vf(e,t,n,r,i,a){e.save(),e.font=q(i,11),e.fillStyle=i.axisLabel,e.strokeStyle=i.grid;for(let i of n.ticks)if(r===`vertical`){let r=G(n,i,t.y,t.height,!0);df(e,t.x,r,t.x+t.width,r),e.textAlign=`right`,e.textBaseline=`middle`,e.fillText(a(i),t.x-6,Math.round(r))}else{let r=G(n,i,t.x,t.width);df(e,r,t.y,r,t.y+t.height),e.textAlign=`center`,e.textBaseline=`top`,e.fillText(a(i),Math.round(r),t.y+t.height+6)}e.restore()}function yf(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}…`:``}var bf=8,xf=32,Sf=new Map;function Cf(e){let t=Sf.get(e);return t===void 0&&(t=wf(e),Sf.size>512&&Sf.clear(),Sf.set(e,t)),t}function wf(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 Tf(e,t,n){let r=Cf(e),i=Cf(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 Ef(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??Tf(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 Df(e,t){return!Number.isFinite(e)||e===0?Tf(t.zero,t.zero,0):e<0?Tf(t.zero,t.negative,t.min<0?Math.min(1,e/t.min):1):Tf(t.zero,t.positive,t.max>0?Math.min(1,e/t.max):1)}var Of=`#11151b`,kf=.0076;function Af(e){let t=Cf(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)/(kf+.05)>1.05/(a+.05)?Of:`#ffffff`}function jf(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<xf;t++){let r=(t+.5)/xf;e.fillStyle=Df(n.min+c*r,n),e.fillRect(o+a*t/xf,s,a/xf+.5,bf)}e.font=q(i,10),e.fillStyle=i.textSecondary,e.textBaseline=`top`;let l=s+bf+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 Mf=.2,Nf=class{position=null;callback=null;data=[];source=null;tz=null;exchangeZone=null;timeFormatter=null;timesPastData=!0;setTimesPastData(e){this.timesPastData=e}getTimesPastData(){return this.timesPastData}setTimeFormatter(e){this.timeFormatter=e}setTimezoneOffset(e){this.tz=e}setExchangeTimeZone(e){this.exchangeZone=e}magnetMode=!0;mode=`magnet`;cursor=`cross`;spanTints=[];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}setCursor(e){this.cursor=e}getCursor(){return this.cursor}drawsLines(){return this.mode!==`hidden`&&this.cursor!==`arrow`}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}getReportedBarIndex(){return this.lastCallbackBarIndex>=0?this.lastCallbackBarIndex:null}refresh(){this.lastCallbackBarIndex<0||!this.pendingPoint||(this.pendingBarIndex=this.lastCallbackBarIndex,this.scheduleCallback())}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;let a=this.cursor!==`arrow`;if(!this.position){this.syncedSlot!==null&&a&&this.renderSynced(n,r,i,this.syncedSlot);return}let{chartRect:o}=r,{x:s,y:c}=this.position;if(s<o.x||s>o.x+o.width)return;let l=o.y+o.height;if(c<Math.min(this.reportTop??o.y,o.y)||c>Math.max(this.reportBottom??l,l))return;let u=c>=o.y&&c<=l,d=e.P(s,r),f=this.series().length,p=Math.max(0,Math.min(f-1,d)),m=d>=0&&d<f;if(this.magnetMode&&(s=e.w(d,r)),p!==this.lastCallbackBarIndex&&(this.pendingBarIndex=p,this.pendingPoint={x:s,y:c},this.lastCallbackBarIndex=p,this.scheduleCallback()),!u||!a)return;let h=ue(i);this.magnetMode&&m&&Ff(n,s,r,h.vertical.color),If(n,s,o,h.vertical);let g=h.horizontal;if(g.visible){n.setLineDash((0,t.lineDash)(g.style,Pf,g.width)),n.strokeStyle=g.color;let r=e.v(n,c,g.width);n.lineWidth=r.width,n.beginPath(),n.moveTo(o.x,r.y),n.lineTo(o.x+o.width,r.y),n.stroke()}n.setLineDash([])}renderAxisLabels(n,r,i,a,o,s=[],c=[]){if(this.mode===`hidden`)return;if(!this.position){this.syncedSlot!==null&&this.renderSyncedTimeLabel(n,r,i,a,this.syncedSlot,o,c);return}let{chartRect:l}=r,{x:u,y:f}=this.position;if(u<l.x||u>l.x+l.width||f<l.y||f>l.y+l.height)return;let p=e.P(u,r);this.magnetMode&&(u=e.w(p,r));let m=`600 ${i.font.sizeSmall}px ${i.font.family}`,h=d(e.I(f,r),r,this.pricePrecision??(0,t.autoPricePrecision)(r.priceRange.min,r.priceRange.max),this.locale),g=l.x+l.width;Bf(n,s,f,g,r.priceAxisWidth??t.PRICE_AXIS_WIDTH,i,this.spanTints),Vf(n,{text:h,anchorX:g,anchorY:f,orientation:`right`,bg:ue(i).labelBackground,fg:ue(i).labelText,theme:i,font:m}),this.drawTimePill(n,r,i,a,p,u,o,c)}beginSpans(){this.spanTints=[]}renderSpan(e,n,r,i,a,o){let s=`600 ${i.font.sizeSmall}px ${i.font.family}`,c=(0,t.withAlpha)(n.color,Mf),l=Af(n.color);n.prices.length>0&&this.renderPriceSpan(e,n,i,s,c,l,r),n.times.length>0&&this.renderTimeSpan(e,n,r,i,a,s,c,l,o)}renderPriceSpan(n,r,i,a,o,s,c){let l=r.viewport,u=l.chartRect,f=u.x+u.width,p=l.priceAxisWidth??t.PRICE_AXIS_WIDTH,m=r.prices.map(t=>e.k(t,l)),h=l===c?this.pricePrecision??(0,t.autoPricePrecision)(l.priceRange.min,l.priceRange.max):S(C(l.priceRange.min,l.priceRange.max,u.height));n.save(),n.beginPath(),n.rect(f,u.y,p,u.height),n.clip(),m.length>1&&(n.fillStyle=o,n.fillRect(f,Math.min(...m),p,Math.abs(m[m.length-1]-m[0])),l===c&&this.spanTints.push({axis:`price`,from:Math.min(...m),to:Math.max(...m),tint:o})),r.prices.forEach((e,t)=>{let o=m[t];o<u.y||o>u.y+u.height||Vf(n,{text:d(e,l,h,this.locale),anchorX:f,anchorY:o,orientation:`right`,bg:r.color,fg:s,theme:i,font:a})}),n.restore()}renderTimeSpan(n,r,i,a,o,s,c,l,u){let d=i.chartRect,f=u??d.y+d.height,p=r.times.map(t=>e.M(t,i));n.save(),n.beginPath(),n.rect(d.x,f,d.width,t.TIME_AXIS_HEIGHT),n.clip(),p.length>1&&(n.fillStyle=c,n.fillRect(Math.min(...p),f,Math.abs(p[p.length-1]-p[0]),t.TIME_AXIS_HEIGHT),this.spanTints.push({axis:`time`,from:Math.min(...p),to:Math.max(...p),tint:c})),r.times.forEach((e,t)=>{let i=p[t];i<d.x||i>d.x+d.width||Vf(n,{text:this.formatTime(e,o),anchorX:i,anchorY:f,orientation:`bottom`,bg:r.color,fg:l,theme:a,font:s})}),n.restore()}renderSynced(t,n,r,i){let a=e.w(i,n),{chartRect:o}=n;if(a<o.x||a>o.x+o.width)return;let s=ue(r);this.magnetMode&&i>=0&&i<this.series().length&&Ff(t,a,n,s.vertical.color),If(t,a,o,s.vertical)}renderSyncedTimeLabel(t,n,r,i,a,o,s=[]){let c=e.w(a,n),{chartRect:l}=n;c<l.x||c>l.x+l.width||this.drawTimePill(t,n,r,i,a,c,o,s)}formatTime(e,t){return this.timeText(e,ci(t))}timeText(e,n){return this.timeFormatter?this.timeFormatter(e*(0,t.barTimeUnit)(n),{kind:`crosshair`,timeZone:this.tz}):Hf(e*(0,t.barTimeUnit)(n),this.tz,(0,t.barsAreDaily)(n),this.exchangeZone)}drawTimePill(t,n,r,i,a,o,s,c=[]){if(i.length===0||!this.timesPastData&&(a<0||a>=i.length))return;let l=ci(i),u=e.C(a,l),d=this.timeText(u,l),f=`600 ${r.font.sizeSmall}px ${r.font.family}`,p=s??n.chartRect.y+n.chartRect.height;t.font=f;let m=Math.ceil(t.measureText(d).width)/2+Rf;zf(t,c,o-m,o+m,p,r,this.spanTints),Vf(t,{text:d,anchorX:o,anchorY:p,orientation:`bottom`,bg:ue(r).labelBackground,fg:ue(r).labelText,theme:r,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)}},Pf=[4,4];function Ff(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 If(n,r,i,a){if(!a.visible)return;n.setLineDash((0,t.lineDash)(a.style,Pf,a.width)),n.strokeStyle=a.color;let o=e._(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 Lf=20,Rf=8;function zf(e,t,n,r,i,a,o=[]){let s=t.filter(e=>e.right>n-2&&e.left<r+2);if(s.length===0)return;e.save();let c=a.font.sizeSmall+12;for(let t of s){let n=t.left-2,r=t.right-t.left+4;e.fillStyle=a.background,e.fillRect(n,i+1,r,c);for(let t of o){if(t.axis!==`time`)continue;let a=Math.max(n,t.from),o=Math.min(n+r,t.to);o<=a||(e.fillStyle=t.tint,e.fillRect(a,i+1,o-a,c))}}e.restore()}function Bf(e,t,n,r,i,a,o=[]){let s=Math.ceil(a.font.sizeSmall/2)+1,c=t.filter(e=>Math.abs(e-n)<Lf/2+s);if(c.length!==0){e.save();for(let t of c){e.fillStyle=a.background,e.fillRect(r+1,t-s,i-1,s*2);for(let n of o){if(n.axis!==`price`)continue;let a=Math.max(t-s,n.from),o=Math.min(t+s,n.to);o<=a||(e.fillStyle=n.tint,e.fillRect(r+1,a,i-1,o-a))}}e.restore()}}function Vf(e,t){e.save(),e.font=t.font;let n=Rf,r=Math.ceil(e.measureText(t.text).width)+n*2,i=Lf;if(e.fillStyle=t.bg,e.textBaseline=`middle`,t.orientation===`right`){let a=t.anchorX+5;A(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;A(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 Hf(e,n,r,i){if(r){let r=(0,t.barDateParts)(e,n,i);return`${r.month}/${r.day}/${r.year}`}let a=(0,t.timeParts)(e,n),{year:o,month:s,day:c,hours:l,minutes:u}=a;return r===void 0&&(0,t.isDateOnly)(a)?`${s}/${c}/${o}`:`${s}/${c} ${l<10?`0`+l:l}:${u<10?`0`+u:u}`}var Uf=[`cross`,`dot`,`arrow`];function Wf(e){return typeof e==`string`&&Uf.includes(e)}var Gf=9,Kf=3,qf=1.5;function Jf(e){return e.replace(/['"<>&]/g,``)}function Yf(e,t,n){if(e===`arrow`)return`default`;if(e===`cross`)return`crosshair`;let r=Gf/2,i=`<svg xmlns='http://www.w3.org/2000/svg' width='${Gf}' height='${Gf}'><circle cx='${r}' cy='${r}' r='${Kf}' fill='${Jf(t)}' stroke='${Jf(n)}' stroke-width='${qf}'/></svg>`,a=Math.floor(r);return`url("data:image/svg+xml,${encodeURIComponent(i)}") ${a} ${a}, crosshair`}var Xf=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}}},Zf=16,Qf=80,$f=864e5,ep={month:`short`,day:`numeric`},tp={month:`short`,day:`numeric`,year:`numeric`};function np(e,n,r,i){return(0,t.zonedDateFormatter)(r,i?tp:ep,n)(e)}var rp=e=>e<10?`0${e}`:`${e}`;function ip(e,n,r,i=`en-US`,a,o){let s=(0,t.normalizeBarTime)(e,a),c=(0,t.timeParts)(s,n);if(r!==void 0&&r>0?r>=$f:(0,t.isDateOnly)(c))return np(s,(0,t.barDateZone)(s,n,o),i,!0);let l=np(s,n,i,!1),u=`${rp(c.hours)}:${rp(c.minutes)}`;return r!==void 0&&r>0&&r<6e4?`${l} · ${u}:${rp(new Date(s).getUTCSeconds())}`:`${l} · ${u}`}var ap=1e4;function op(e,n){return Number.isFinite(e)?(0,t.usesKoreanUnits)(n)&&e>=ap?(0,t.formatVolumeLoc)(e,n):(0,t.usesKoreanUnits)(n)?(0,t.formatPrice)(e,e%1==0?0:2,n):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 sp=class{el=null;visible=!1;appliedTheme=null;locale=`en-US`;pricePrecision=null;tz=null;exchangeZone=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)`}),s(t);let n=cp({display:`flex`,alignItems:`center`,gap:`7px`,marginBottom:`6px`});this.dirEl=cp({width:`3px`,height:`12px`,borderRadius:`2px`,flex:`none`}),this.timeEl=cp({flex:`1`,fontSize:`11px`,letterSpacing:`0.01em`}),this.changeEl=cp({padding:`1px 6px`,borderRadius:`999px`,fontSize:`10.5px`,fontWeight:`600`}),n.append(this.dirEl,this.timeEl,this.changeEl);let r=cp({display:`grid`,gridTemplateColumns:`auto 1fr auto 1fr`,columnGap:`8px`,rowGap:`1px`,alignItems:`baseline`}),i=e=>{let t=cp({fontSize:`10px`,letterSpacing:`0.04em`});t.textContent=e,this.labelEls.push(t);let n=cp({textAlign:`right`,fontWeight:`500`});return r.append(t,n),n},a=i(`O`),o=i(`H`),c=i(`L`),l=i(`C`);this.dividerEl=cp({height:`1px`,margin:`6px 0 5px`});let u=cp({display:`flex`,justifyContent:`space-between`,gap:`12px`}),d=cp({fontSize:`10px`,letterSpacing:`0.04em`});d.textContent=`VOL`,this.labelEls.push(d);let f=cp({fontWeight:`500`});u.append(d,f),this.valueEls={open:a,high:o,low:c,close:l,volume:f},t.append(n,r,this.dividerEl,u),e.appendChild(t),this.el=t}setLocale(e){this.locale=e}setPricePrecision(e){this.pricePrecision=e}setTimezoneOffset(e){this.tz=e}setExchangeTimeZone(e){this.exchangeZone=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}):ip(n.time,this.tz,a.barStepMs,this.locale,a.timeUnit,this.exchangeZone),this.changeEl.textContent=`${m}${(0,t.formatPrice)(Math.abs(d),2,this.locale)}%`,this.changeEl.style.color=p,this.changeEl.style.background=dp(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=op(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-Qf,height:i.height},g=h.x+h.width,_=h.y+h.height,v=e.x+Zf,y=e.y-this.height/2;v+this.width>g-4&&(v=e.x-this.width-Zf),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=lp(e.background);t.style.background=dp(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 cp(e){let t=document.createElement(`div`);return Object.assign(t.style,e),t}function lp(e){let t=up(e);return t?(.299*t[0]+.587*t[1]+.114*t[2])/255<.5:!0}function up(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 dp(e,t){let n=up(e);return n?`rgba(${n[0]}, ${n[1]}, ${n[2]}, ${t})`:`color-mix(in srgb, ${e} ${Math.round(t*100)}%, transparent)`}var fp=2,pp=2,mp=`0.7`,hp=class{el=null;deltaEl=null;timeEl=null;ohlcEl=null;pinnedBar=null;pinnedIndex=-1;tz=null;exchangeZone=null;priceFormatter=null;pricePrecision=null;locale=`en-US`;setTimezone(e){this.tz=e}setExchangeTimeZone(e){this.exchangeZone=e}setPriceFormatter(e){this.priceFormatter=e}setPricePrecision(e){this.pricePrecision=e!==null&&Number.isInteger(e)&&e>=0?e:null}setLocale(e){this.locale=e}fmt(e){return this.priceFormatter?this.priceFormatter(e):(0,t.formatPrice)(e,this.pricePrecision??fp,this.locale)}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`}),s(this.el),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,a=!1){if(!this.el||!this.timeEl||!this.ohlcEl)return;this.pinnedBar=e,this.pinnedIndex=n;let o=e.close>=e.open?r.candleUp:r.candleDown,s=(0,t.normalizeBarTime)(e.time,i),c=a?(0,t.barDateParts)(s,this.tz,this.exchangeZone):(0,t.timeParts)(s,this.tz);this.timeEl.textContent=a?`${c.month}/${c.day}/${c.year}`:`${c.month}/${c.day} ${gp(c.hours)}:${gp(c.minutes)}`,this.timeEl.style.color=r.textSecondary;let l=[];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=o,r.textContent=this.fmt(n),l.push(e,r)}this.ohlcEl.replaceChildren(...l);let u=_p(r.background);this.el.style.background=vp(r.background,u?.96:.97),this.el.style.border=`1px solid ${o}`,this.el.style.boxShadow=u?`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(n,r,i,a){if(!this.el||!this.pinnedBar)return;let o=e.w(this.pinnedIndex,n),s=e.k(this.pinnedBar.close,n),c=n.chartRect,l=o>=c.x-4&&o<=c.x+c.width+4;this.el.style.opacity=l?`1`:`0.35`;let u=Math.max(c.x,Math.min(c.x+c.width-180,o+8)),d=Math.max(c.y,Math.min(c.y+c.height-90,s-64));if(this.el.style.transform=`translate(${Math.round(u)}px, ${Math.round(d)}px)`,this.el.style.left=`0`,this.el.style.top=`0`,this.deltaEl)if(r&&i!==null&&i!==this.pinnedIndex){let e=r.close-this.pinnedBar.close,n=this.pinnedBar.close===0?0:e/this.pinnedBar.close*100,o=e>0?`+`:e<0?`−`:``,s=i-this.pinnedIndex,c=e>=0?a.candleUp:a.candleDown;this.deltaEl.style.color=c;let l=(0,t.formatPrice)(Math.abs(n),pp,this.locale),u=document.createElement(`span`);u.style.opacity=mp,u.textContent=`(${o}${l}%)`,this.deltaEl.replaceChildren(`Δ ${o}${this.fmt(Math.abs(e))} `,u,` · ${s>0?`+`:``}${s} 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 gp(e){return e<10?`0`+e:``+e}function _p(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 vp(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 yp=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}},bp=1.5,xp=1.5,Sp=1,Cp=2.5,wp=.7,Tp=4,Ep=.2,Dp={primary:null,hover:null,drag:null};function Op(e){Dp=e??{primary:null,hover:null,drag:null}}function kp(e,t,n){return(Math.round(e*t+n-.5)+.5-n)/t}function Ap(e,t,n,r){e.beginPath(),e.arc(t,n,r,0,Math.PI*2)}function jp(e,n,r,i={}){let a=M(),o=n.style.color,s=e.getTransform?.()??{a:1,d:1,e:0,f:0},c=n.id===Dp.primary&&!n.locked;e.save(),e.setLineDash([]),r.forEach((r,l)=>{let u=kp(r.x,s.a||1,s.e??0),d=kp(r.y,s.d||1,s.f??0),f=Nn(n.style.lineWidth)+xp;if(vn(u-f,d-f,f*2,f*2),!c){Ap(e,u,d,Cp*a.scale),e.globalAlpha=wp,e.fillStyle=o,e.fill(),e.globalAlpha=1;return}let p=Nn(n.style.lineWidth)-(i.sides?.has(l)?Sp:0),m=Dp.drag?.id===n.id&&Dp.drag.index===l,h=!m&&Dp.hover?.id===n.id&&Dp.hover.index===l||m?p+xp:p;m&&(Ap(e,u,d,h+Tp),e.fillStyle=(0,t.withAlpha)(o,Ep),e.fill()),Ap(e,u,d,h),e.fillStyle=m?o:a.handleFill,e.fill(),e.strokeStyle=m?a.background:o,e.lineWidth=bp,e.stroke()}),e.restore()}function Mp(e){return e?.anchoring===`screen`}var Np=24;function Pp(e,t,n){return Math.max(t,Math.min(e,Math.max(t,n)))}function Fp(e,t){let n=t.chartRect;return{x:Pp(n.x+e.time*n.width,n.x,n.x+n.width-Np),y:Pp(n.y+e.price*n.height,n.y+Np,n.y+n.height-Np)}}function Ip(e){let t=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0;return e.map(e=>({time:t(e.time),price:t(e.price)}))}function Lp(e,t){let n=t.chartRect,r=(e,t)=>t>0?Math.min(1,Math.max(0,e/t)):0;return{time:r(e.x-n.x,n.width),price:r(e.y-n.y,n.height)}}function Rp(e,t,n,r){return e.map(e=>{let i=Fp(e,r);return Lp({x:i.x+t,y:i.y+n},r)})}function zp(e,t){let n=e=>Math.min(1,Math.max(0,e+t<=1?e+t:e-t));return e.map(e=>({time:n(e.time),price:n(e.price)}))}var Bp={at:e=>e,value:e=>e,price:e=>e};function Vp(t){if(!t)return Bp;let{min:n,max:r}=t.priceRange,i=t.logScale===!0&&n>0&&r>0;return{at:n=>e.j(n,t),value:i?e=>Math.log(Math.max(e,2**-52)):e=>e,price:i?Math.exp:e=>e}}function Hp(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 Up(e,t,n,r=!1){for(let r=0;r<t.length-1;r++)if(Hp(e,t[r],t[r+1])<=n)return!0;return r&&t.length>2&&Hp(e,t[t.length-1],t[0])<=n}function Wp(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 Gp=.55,J=class{hitTestAnchor(e,t,n,r){let i=-1,a=1/0,o=this.handlePoints(t,n);for(let t=0;t<o.length;t++){let n=o[t],s=Math.hypot(e.x-n.x,e.y-n.y);s<=r&&s<a&&(i=t,a=s)}return i}option(e,t){let n=this.descriptor.options?.[t],r=e.options?.[t];return n?r!==void 0&&Wp(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=Bp){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 Mp(this.descriptor)?Fp(t,n):{x:e.M(t.time,n),y:e.k(t.price,n)}}pixelToAnchor(t,n){return Mp(this.descriptor)?Lp(t,n):{time:e.F(t.x,n),price:e.I(t.y,n)}}applyLineStyle(e,t){e.strokeStyle=t.color,e.lineWidth=t.lineWidth,e.lineCap=t.lineStyle===`dashed`?`butt`:`round`,e.lineJoin=`round`,e.setLineDash(Ln(t.lineStyle,t.lineWidth))}strokeHorizontal(t,n,r,i){let a=e.v(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._(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`}handlePoints(e,t){return e.anchors.map(e=>this.anchorToPixel(e,t))}timeHandles(e,t){let n=t.chartRect.y+t.chartRect.height/2;return e.anchors.map(e=>({x:this.anchorToPixel(e,t).x,y:n}))}strokeCrispRect(e,t,n,r,i){let a=Math.min(t,t+r),o=Math.max(t,t+r),s=Math.min(n,n+i),c=Math.max(n,n+i);this.strokeHorizontal(e,a,o,s),this.strokeHorizontal(e,a,o,c),this.strokeVertical(e,a,s,c),this.strokeVertical(e,o,s,c)}applyGuideStyle(e,t,n=!1){e.strokeStyle=t,e.lineWidth=1,e.lineCap=`butt`,e.globalAlpha=Gp,e.setLineDash(n?Ln(`guide`,1):[])}renderAnchorHandles(e,t,n){jp(e,t,this.handlePoints(t,n))}distanceToLine(e,t,n){return Hp(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 Kp(e){if(typeof e!=`string`)return;let t=e.trim().slice(0,80);return t.length>0?t:void 0}function qp(e){let t={};for(let[n,r]of Object.entries(e))t[n]=Array.isArray(r)?r.map(e=>({...e})):r;return t}function Y(e){return{...e,anchors:e.anchors.map(e=>({...e})),style:{...e.style},options:e.options?qp(e.options):void 0,intervals:e.intervals?Ia(e.intervals):void 0,group:e.group?{...e.group}:void 0,meta:e.meta?{...e.meta}:void 0}}function Jp(e,t){return JSON.stringify(e??{})===JSON.stringify(t??{})}function Yp(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 Xp=1,Zp=1,Qp=/^tc_drawing_(\d+)$/,$p=/^tc_group_(\d+)$/;function em(){return`tc_drawing_${Xp++}`}function tm(){let e=Zp++;return{id:`tc_group_${e}`,number:e}}function nm(e){for(let t of e){let e=Qp.exec(t.id);e&&(Xp=Math.max(Xp,Number(e[1])+1));let n=t.group?$p.exec(t.group.id):null;n&&(Zp=Math.max(Zp,Number(n[1])+1))}}function rm(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 im(e,t,n){let r=t-1;if(typeof n==`number`)return Number.isInteger(n)?Math.min(r,Math.max(0,n)):e;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 am(e,t){return e.map(e=>e.id===t.id?structuredClone(t):e)}function om(e,t){switch(t.type){case`drawingBatch`:return[...t.actions??[]].reverse().reduce(om,[...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?rm(e,t.order.before):[...e];case`drawingModify`:return t.before?am(e,t.before):[...e];default:return[...e]}}function sm(e,t){switch(t.type){case`drawingBatch`:return(t.actions??[]).reduce(sm,[...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?rm(e,t.order.after):[...e];case`drawingModify`:return t.after?am(e,t.after):[...e];default:return[...e]}}var cm={"]":[`forward`,`front`],"}":[`front`,`front`],"[":[`backward`,`back`],"{":[`back`,`back`]};function lm(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=cm[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 um=2,dm=6;function fm(e){return e.descriptor.creation??`clicks`}var pm=class{drawing=null;plugin=null;preview=null;lastPos=null;dragging=!1;step=um;get current(){return this.drawing}reset(){this.drawing=null,this.plugin=null,this.preview=null,this.lastPos=null,this.dragging=!1,this.step=um}press(e,t,n,r,i){if(this.dragging)return`continue`;let a=fm(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)<=dm)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 fm(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||fm(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}},mm=50;function hm(e,t,n,r,i){return gm(e,t,n,r,e=>[r[e].open,r[e].high,r[e].low,r[e].close],i)}function gm(t,n,r,i,a,o){if(r===`none`||i.length===0)return{time:t,price:n};let s=!!(o?.data&&o.data.length>0),c=Math.round(s?e.N(t,i):t);if(c<0||c>i.length-1)return{time:t,price:n};let l=s?i[c].time:c,u=a(c).filter(e=>Number.isFinite(e));if(u.length===0)return{time:l,price:n};let d=u[0];for(let e of u)Math.abs(n-e)<Math.abs(n-d)&&(d=e);return r===`magnet`&&o&&Math.abs(e.k(n,o)-e.k(d,o))>mm?{time:l,price:n}:{time:l,price:d}}var _m=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}},vm=Math.PI/4,ym=new Set([`trendLine`,`ray`,`extendedLine`,`infoLine`,`trendAngle`,`arrow`,`horizontalRay`,`measure`,`priceRange`,`dateRange`,`dateAndPriceRange`,`path`,`polyline`,`fibRetracement`,`fibExtension`]);function bm(e){return ym.has(e)}function xm(e,t){let n=t.x-e.x,r=t.y-e.y;if(n===0&&r===0)return t;let i=Math.round(Math.atan2(r,n)/vm)*vm,a=Math.cos(i),o=Math.sin(i),s=n*a+r*o;return{x:e.x+Sm(s*a),y:e.y+Sm(s*o)}}function Sm(e){return Math.abs(e)<1e-9?0:e}function Cm(t,n,r){let i=wm(t,r),a=xm(i,n);if(a.x===i.x)return{time:t.time,price:e.I(a.y,r)};let o=e.F(a.x,r);if(a.y===i.y)return{time:o,price:t.price};let s=e.M(o,r)-i.x;return{time:o,price:e.I(i.y+Math.sign(a.y-i.y)*Math.abs(s),r)}}function wm(t,n){return{x:e.M(t.time,n),y:e.k(t.price,n)}}function Tm(e,t,n){let r=-1,i=1/0;return e.forEach((e,a)=>{let o=wm(e,n),s=Math.hypot(o.x-t.x,o.y-t.y);s<i&&(r=a,i=s)}),r}var Em=3,Dm=class{start=null;handle=-1;grabbed=[];held=-1;constructor(e,t=()=>!1){this.find=e,this.onScreen=t}isActive(){return this.start!==null}activeHandle(){return this.start===null?-1:this.handle}beginMove(e,t){this.start=e,this.handle=-1,this.held=-1,this.grabbed=t.map(e=>({id:e.id,anchors:e.anchors.map(e=>({...e})),before:Y(e)}))}beginResize(e,t,n){this.start=e,this.handle=n,this.grabbed=[{id:t.id,anchors:t.anchors.map(e=>({...e})),before:Y(t)}]}move(e,t,n,r){return!this.start||this.grabbed.length===0?!1:this.handle>=0?this.reshape(e,t,n,r):this.translate(e,t,r)}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(e,t,n){let r=this.start,i=e.x-r.x,a=e.y-r.y;if(Math.hypot(i,a)<Em&&this.unmoved())return!0;let o=t.barWidth+t.barSpacing,s=o>0?Math.round(i/o):0,c=this.find(this.grabbed[0].id),l=n&&c&&!this.onScreen(c)?this.snapHeld(s,a,t,n):null;return l&&(a+=l.dy),this.grabbed.forEach(({id:n,anchors:o},c)=>{let u=this.find(n);if(!(!u||u.locked)){if(this.onScreen(u)){u.anchors=Rp(o,i,e.y-r.y,t);return}u.anchors=Om(o,s,a,t),c===0&&l&&(u.anchors[this.held]={...u.anchors[this.held],price:l.price})}}),!0}snapHeld(t,n,r,i){let a=this.grabbed[0];this.held<0&&(this.held=Tm(a.anchors,this.start,r));let o=a.anchors[this.held];if(!o)return null;let[s]=Om([o],t,n,r),{price:c}=i.snap(s);return c===s.price?null:{price:c,dy:e.k(c,r)-e.k(s.price,r)}}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,a){let o=this.find(this.grabbed[0].id);if(!o)return!1;let s=this.onScreen(o)?Lp(n,r):a?a.handleAt(n,o,this.handle):{time:e.F(n.x,r),price:e.I(n.y,r)};if(i?.moveHandle){let e=i.moveHandle(Y(o),this.handle,s);o.anchors=e.anchors,o.options=e.options&&Object.keys(e.options).length>0?(0,t.sanitizeDrawingOptions)(i.descriptor.options,e.options):void 0}else this.handle<o.anchors.length&&(o.anchors[this.handle]=s);return!0}};function Om(t,n,r,i){let a=i.data,o=t=>{let r=e.j(t,i)+n;return a&&a.length>0?e.C(r,a):r};return t.map(t=>({time:n===0?t.time:o(t.time),price:r===0?t.price:e.I(e.k(t.price,i)+r,i)}))}function km(e){let t=e.filter(Number.isFinite);if(t.length===0)return[];let n=Math.min(...t),r=Math.max(...t);return n===r?[n]:[n,r]}function Am(e,t){let n=t.axisSpan??`both`;if(n===`none`||t.anchoring===`screen`)return null;let r=n===`time`?[]:km(e.anchors.map(e=>e.price)),i=n===`price`?[]:km(e.anchors.map(e=>e.time));return r.length===0&&i.length===0?null:{prices:r,times:i}}var jm={drawings:[],pastes:0},Mm=1e7,Nm={line:8,handle:8},Pm=8,Fm=1e3,Im=.02;function Lm(e,t){return e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height}function Rm(e){return e.type===`indicators`||e.type===`custom`}function zm(e){return(e.actions??[]).some(e=>Rm(e)||zm(e))}var Bm=class{registry=new Map;drawings=[];state=`idle`;activeTool=null;activeStyle={color:`#4c8dff`,lineWidth:1,lineStyle:`solid`,fillColor:t.LINE_TINT_FILL,fillOpacity:.12};hoverHandle=null;extents=new Map;hoverDrawing=null;creator=new pm;finishedAt=-1/0;creationPressAt=-1/0;eraser=!1;selection=new _m;drag=new Dm(e=>this.drawings.find(t=>t.id===e),e=>this.onScreen(e.type));eventCallback=null;requestRender=null;undoRedo=null;magnetMode=`none`;mods={ctrl:!1,shift:!1};pendingCopy=null;copies=null;copiedFrom=[];copySources=new Map;lastNudge=null;dataGetter=null;dataRevision=()=>0;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,this.dataRevision)}setEventCallback(e){this.eventCallback=e}setRequestRender(e){this.requestRender=e}setUndoRedoManager(e){this.undoRedo=e}setMagnetMode(e){this.magnetMode=e}getMagnetMode(){return this.magnetMode}setModifiers(e){this.mods={ctrl:e.ctrl,shift:e.shift}}activeMagnet(){return!this.mods.ctrl||this.copies?this.magnetMode:this.magnetMode===`none`?`strong`:`none`}setDataGetter(e,t=()=>0){this.dataGetter=e,this.dataRevision=t;for(let n of this.registry.values())n.setDataGetter?.(e,t)}setDisplayDataGetter(e){this.displayDataGetter=e}panes=null;setPanes(e){this.panes=e}paneAt(e){return this.panes?this.panes.paneAt(e):void 0}viewportFor(e,t){if(e===void 0)return t;let n=this.panes?.viewportOf(e)??null;return n&&t.formatTime&&!n.formatTime?{...n,formatTime:t.formatTime}:n}scopeAt(e,t){if(!this.panes&&!Lm(e,t.chartRect))return null;let n=this.paneAt(e);if(n===null)return null;let r=this.viewportFor(n,t);return r?{pane:n,viewport:r}:null}renamePanes(e){let t=!1;this.drawings=this.drawings.map(n=>{let r=n.paneId===void 0?void 0:e.get(n.paneId);return r===void 0||r===n.paneId?n:(t=!0,{...n,paneId:r})}),t&&this.requestRender?.()}onScreen(e){return Mp(this.registry.get(e)?.descriptor)}anchorPoint(t,n,r){return this.onScreen(t)?Fp(n,r):{x:e.M(n.time,r),y:e.k(n.price,r)}}snapToOHLC(e,t,n,r){let i=this.activeMagnet(),a=i===`none`?[]:this.displayDataGetter?.()??this.dataGetter?.()??[];if(r!==void 0){let o=this.panes?.valuesAt;return gm(e,t,i,a,e=>o?.(r,e)??[],n)}return hm(e,t,i,a,n)}dragEdit(t,n){if(!(this.registry.get(t.type)?.descriptor.creation===`freehand`||this.onScreen(t.type)))return{handleAt:(t,r,i)=>{let a=bm(r.type)&&r.anchors.length>=2&&i<r.anchors.length?r.anchors[i===0?1:i-1]:void 0;return this.mods.shift&&a?Cm(a,t,n):this.snapToOHLC(e.F(t.x,n),e.I(t.y,n),n,r.paneId)},snap:e=>this.snapToOHLC(e.time,e.price,n,t.paneId)}}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(Rm(e)){this.foreignHistory?.(e,`undo`);return}if(e.type===`drawingBatch`&&zm(e)){for(let t of[...e.actions??[]].reverse())this.applyUndoAction(t);return}this.applyHistory(om(this.drawings,e))}applyRedoAction(e){if(Rm(e)){this.foreignHistory?.(e,`redo`);return}if(e.type===`drawingBatch`&&zm(e)){for(let t of e.actions??[])this.applyRedoAction(t);return}this.applyHistory(sm(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.dropCopyGesture(),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(e,t,n){if(this.state===`creating`)return 0;let r=this.viewportFor(n,t);if(!r)return 0;this.selection.clear(),this.state=`idle`;let i=Math.min(e.x0,e.x1),a=Math.max(e.x0,e.x1),o=Math.min(e.y0,e.y1),s=Math.max(e.y0,e.y1);for(let e of this.drawings)!this.shown(e)||e.paneId!==n||e.anchors.some(t=>{let{x:n,y:c}=this.anchorPoint(e.type,t,r);return n>=i&&n<=a&&c>=o&&c<=s})&&this.addToSelection(e.id);return this.requestRender?.(),this.getSelectedDrawingIds().length}toggleSelectionAt(e,t){if(this.state===`creating`)return!1;let n=this.scopeAt(e,t);if(!n)return!1;for(let t=this.drawings.length-1;t>=0;t--){let r=this.drawings[t];if(!(!this.shown(r)||r.paneId!==n.pane)&&this.registry.get(r.type)?.hitTest(e,r,n.viewport,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&&e.paneId===t.paneId);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=Y(n);Object.assign(n,t),this.record({type:`drawingModify`,before:e,after:Y(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)}onDrawnPane(e){return e.paneId===void 0||(this.panes?.viewportOf(e.paneId)??null)!==null}shown(e){return e.visible&&ja(e.intervals,this.timeframe)&&this.onDrawnPane(e)}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),this.clearHover(),this.dropCopyGesture();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:(jm.drawings=e.map(e=>structuredClone(e)),jm.pastes=0,e.length)}canPaste(){return this.state!==`creating`&&jm.drawings.some(e=>this.canPasteType(e.type))}canPasteType(e){return this.registry.has(e)&&this.toolAllowed(e)}paste(){if(jm.drawings.length===0||this.state===`creating`)return[];let e=jm.drawings.every(e=>this.drawings.some(t=>t.id===e.id));jm.pastes+=1;let t=e?this.computeBarOffsetTime(3*jm.pastes):0,n=[];if(this.batchUndo(()=>{for(let e of jm.drawings)this.canPasteType(e.type)&&(e.paneId!==void 0&&(!this.panes?.hasPane(e.paneId)||this.registry.get(e.type)?.descriptor.priceOnly)||n.push(this.addDrawing({...e.paneId===void 0?{}:{paneId:e.paneId},type:e.type,anchors:this.onScreen(e.type)?zp(e.anchors,Im*jm.pastes):e.anchors.map(e=>({...e,time:e.time+t})),style:{...e.style},options:e.options?qp(e.options):void 0,intervals:e.intervals,meta:e.meta?structuredClone(e.meta):void 0,name:e.name})))}),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=Y(n);n.style={...n.style,...e},this.record({type:`drawingModify`,before:i,after:Y(n)}),r=!0}}),r&&this.requestRender?.(),r}onPointerDown(e,t,n=Nm){if(this.eraser){let r=this.scopeAt(e,t);return r?this.erase(e,r,n.line):!1}return 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,r=n?this.viewportFor(n.paneId,t):null;if(n&&r&&this.creator.move(this.creationAnchor(n.type,e,r,n.paneId),e))return this.requestRender?.(),!0;if(this.pendingCopy){let{pos:t}=this.pendingCopy;if(Math.hypot(e.x-t.x,e.y-t.y)<Pm)return!0;this.startCopy()}if((this.state===`moving`||this.state===`resizing`)&&this.drag.isActive()){let n=this.drawings.find(e=>e.id===this.selection.primary),r=this.viewportFor(n?.paneId,t),i=n&&r?this.dragEdit(n,r):void 0;return!r||!this.drag.move(e,r,n&&this.registry.get(n.type),i)?!1:(this.requestRender?.(),!0)}return!1}onPointerUp(){let e=this.state===`creating`?this.creator.release():null;if(e)return this.afterCreationStep(e),!0;if(this.pendingCopy)return this.toggleCopied();if(this.copies)return this.endCopy(),!0;if(this.state===`moving`||this.state===`resizing`){let e=this.drag.end();return this.batchUndo(()=>{for(let{before:t,drawing:n}of e)Yp(n.anchors,t.anchors)&&Jp(n.options,t.options)||this.record({type:`drawingModify`,before:t,after:Y(n)})}),this.state=`selected`,this.requestRender?.(),!0}return!1}beginCopyDrag(e,t,n=Nm){if(this.state===`creating`||this.state===`moving`||this.state===`resizing`||this.eraser)return!1;if(this.beginHandleDrag(e,t,n))return!0;let r=this.drawingAt(e,t,n.line);return r?(this.pendingCopy={pos:e,id:r},!0):!1}beginHandleDrag(e,t,n){let r=this.scopeAt(e,t),i=this.drawings.find(e=>e.id===this.selection.primary);if(!r||!i||i.locked||!this.shown(i)||i.paneId!==r.pane)return!1;let a=this.registry.get(i.type)?.hitTestAnchor(e,i,r.viewport,n.handle)??-1;return a<0?!1:(this.state=`resizing`,this.drag.beginResize(e,i,a),!0)}dropCopyGesture(){this.pendingCopy=null;let e=this.copies;e&&(this.copies=null,this.copySources=new Map,this.drag.end(),this.drawings=this.drawings.filter(t=>!e.includes(t.id)),this.deselect(e),this.state===`moving`&&(this.state=`idle`))}startCopy(){let{pos:e,id:t}=this.pendingCopy;this.pendingCopy=null;let n=this.selection.has(t)?[t,...this.getSelectedDrawingIds().filter(e=>e!==t)]:[t],r=this.drawings.find(e=>e.id===t),i=n.map(e=>this.drawings.find(t=>t.id===e)).filter(e=>e!==void 0&&this.shown(e)&&e.paneId===r?.paneId&&this.canPasteType(e.type));if(i.length===0)return;let a=i.map(e=>{let{group:t,...n}=structuredClone(e);return{...n,id:em(),locked:!1}});this.copySources=new Map(a.map((e,t)=>[e.id,i[t].anchors.map(e=>({...e}))])),this.drawings=[...this.drawings,...a],this.copies=a.map(e=>e.id),this.copiedFrom=this.getSelectedDrawingIds(),this.selection.only(a[0].id,this.copies.slice(1)),this.beginMove(e,a[0]),this.requestRender?.()}endCopy(){let e=this.copies;this.copies=null,this.drag.end(),this.state=`selected`;let t=this.copySources;this.copySources=new Map;let n=e.map(e=>this.drawings.find(t=>t.id===e)).filter(e=>e!==void 0);if(n.every(e=>{let n=t.get(e.id);return!!n&&Yp(e.anchors,n)})){this.drawings=this.drawings.filter(t=>!e.includes(t.id)),this.deselect(e),this.requestRender?.();return}this.batchUndo(()=>{for(let e of n)this.record({type:`drawingCreate`,before:null,after:Y(e)})});for(let e of n)this.eventCallback?.(`drawingCreate`,{id:e.id,type:e.type,drawing:e});this.requestRender?.()}toggleCopied(){let{id:e}=this.pendingCopy;return this.pendingCopy=null,this.selection.has(e)?this.deselect([e]):this.addToSelection(e),this.requestRender?.(),!0}nudge(e,t,n){if(this.state!==`selected`)return!1;let r=this.getSelectedDrawingIds().map(e=>this.drawings.find(t=>t.id===e)).filter(e=>e!==void 0&&!e.locked&&this.shown(e));if(r.length===0||e===0&&t===0)return!1;let i=r.map(e=>e.id).join(`,`),a=Date.now(),o=this.lastNudge,s=o&&o.key===i&&a-o.at<Fm&&o.action!==null&&this.undoRedo?.last()===o.action?o:null,c=s?s.before:r.map(Y),l=r.filter(r=>{let i=this.viewportFor(r.paneId,n);return i?(r.anchors=this.onScreen(r.type)?Rp(r.anchors,e*(i.barWidth+i.barSpacing),t,i):Om(r.anchors,e,t,i),!0):!1});if(l.length===0)return!1;s&&this.undoRedo?.dropLast(),this.batchUndo(()=>{for(let e of l){let t=c.find(t=>t.id===e.id);t&&this.record({type:`drawingModify`,before:t,after:Y(e)})}}),this.lastNudge={key:i,at:a,before:c,action:this.undoRedo?.last()??null};for(let e of l)this.eventCallback?.(`drawingUpdate`,{id:e.id});return this.requestRender?.(),!0}onKeyDown(e,t=!1,n){let r=lm(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(){if(this.pendingCopy||this.copies){let e=this.copies?this.copiedFrom.filter(e=>this.isShown(e)):[];return this.dropCopyGesture(),e.length>0&&(this.selection.only(e[0],e.slice(1)),this.state=`selected`),this.requestRender?.(),!0}if(this.state===`moving`||this.state===`resizing`){let e=new Map(this.drag.end().map(({before:e})=>[e.id,Y(e)]));return this.drawings=this.drawings.map(t=>e.get(t.id)??t),this.state=`selected`,this.requestRender?.(),!0}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){this.dropCopyGesture(),nm(e),this.drawings=this.upgradeLegacyAnchors(e).map(e=>{let n=e.name===void 0||e.name===Kp(e.name)?e:Km(e,Kp(e.name)),r=this.onScreen(n.type)?{...n,anchors:Ip(n.anchors)}:n;if(!r.options&&r.intervals===void 0)return r;let i=(0,t.sanitizeDrawingOptions)(this.optionDefs(r.type),r.options);return{...r,options:Object.keys(i).length>0?i:void 0,intervals:Ma(r.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=im(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=Y(e);t(e),this.record({type:`drawingModify`,before:n,after:Y(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}=tm(),o={id:i,name:qm(t)||`Group ${a}`};return this.batchUndo(()=>{for(let e of r){let t=Y(e);e.group={...o},this.record({type:`drawingModify`,before:t,after:Y(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=qm(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`}getPlugin(e){return this.registry.get(e)??null}textBoxOf(e,t){let n=this.drawings.find(t=>t.id===e),r=n?this.viewportFor(n.paneId,t):null;return!n||!r?null:this.registry.get(n.type)?.textBox?.(n,r)??null}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={...qp(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 qp(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:Y(r);if(n.anchors&&(r.anchors=this.onScreen(r.type)?Ip(n.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}if(n.name!==void 0){let e=Kp(n.name);e===void 0?delete r.name:r.name=e}return n.intervals!==void 0&&(r.intervals=Ma(n.intervals)??void 0,!this.edits.has(e)&&!this.shown(r)&&this.deselect([e])),i&&this.record({type:`drawingModify`,before:i,after:Y(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,Y(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:Y(this.drawings[r])}),this.shown(this.drawings[r])||this.deselect([e]),this.eventCallback?.(`drawingUpdate`,{id:e}))}addDrawing(e){e.id&&nm([{id:e.id}]);let t=e.id??em(),n={id:t,type:e.type,anchors:this.onScreen(e.type)?Ip(e.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:Ma(e.intervals)??void 0,meta:e.meta,...typeof e.paneId==`string`?{paneId:e.paneId}:{}},r=Kp(e.name);return r!==void 0&&(n.name=r),this.drawings=[...this.drawings,n],this.record({type:`drawingCreate`,before:null,after:Y(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=Mm;return t[t.length-1].time<n?e:e.map(e=>this.onScreen(e.type)?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){this.hoverDrawing===e&&this.clearHover();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)}amendNew(e,t){let n=this.drawings.find(t=>t.id===e);if(!n)return!1;let r=this.undoRedo?.last();if(!this.undoRedo||r?.type!==`drawingCreate`||r.after?.id!==e)return this.updateDrawing(e,t);let i=[],a=this.batch;this.batch=i;let o=!1;try{o=this.updateDrawing(e,t)}finally{this.batch=a}return o?(this.undoRedo.replaceLast({...r,after:Y(n)}),!0):!1}takeBack(e){let t=this.undoRedo?.last();if(!this.undoRedo||t?.type!==`drawingCreate`||t.after?.id!==e){this.removeDrawing(e);return}this.undoRedo.dropLast(),this.drawings=this.drawings.filter(t=>t.id!==e),this.deselect([e]),this.edits.delete(e),this.eventCallback?.(`drawingRemove`,{id:e}),this.requestRender?.()}duplicateDrawing(e){let t=this.drawings.find(t=>t.id===e);if(!t)return null;let n=structuredClone(t);n.id=em();let r=this.computeBarOffsetTime(3);return n.anchors=this.onScreen(n.type)?zp(n.anchors,Im):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.dropCopyGesture(),this.drawings=[],this.selection.clear(),this.state=`idle`,this.requestRender?.()}getSelectedDrawingId(){return this.selection.primary}render(t,n){t.save(),t.textAlign=`left`,t.textBaseline=`alphabetic`;let r=this.selection.primary,i=this.state===`resizing`&&r?this.drag.activeHandle():-1;Op({primary:r,hover:this.hoverHandle,drag:i>=0&&r?{id:r,index:i}:null});let a=new Map;this.extents=a;try{for(let e of this.drawings){if(!this.shown(e))continue;let r=this.registry.get(e.type),i=this.viewportFor(e.paneId,n);if(!r||!i)continue;_n();let o=null;try{Gm(t,r,e,i,this.selection.has(e.id))}finally{o=yn()}o&&a.set(e.id,o)}let r=this.creator.previewState(),i=r?this.registry.get(r.type):void 0,o=r?this.viewportFor(r.paneId,n):null;if(r&&i&&o&&(Op({primary:r.id,hover:null,drag:null}),Gm(t,i,r,o,!0),r.anchors.length<2)){let n=o;jp(t,r,r.anchors.map(t=>this.onScreen(r.type)?Fp(t,n):{x:e.M(t.time,n),y:e.k(t.price,n)}))}}finally{Op(null)}t.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,i){if(this.onScreen(t))return Lp(n,r);let a=e.F(n.x,r),o=e.I(n.y,r);if(this.registry.get(t)?.descriptor.creation===`freehand`)return{time:a,price:o};let s=this.creator.current?.anchors,c=s&&s.length>0?s[s.length-1]:void 0;return this.mods.shift&&c&&bm(t)?Cm(c,n,r):this.snapToOHLC(a,o,r,i)}handleCreationClick(e,t){let n=this.activeTool,r=n?this.registry.get(n):void 0;if(!n||!r)return!1;let i=this.creator.current,a=i?i.paneId:this.paneAt(e);if(a===null||a!==void 0&&r.descriptor.priceOnly)return!1;let o=this.viewportFor(a,t);if(!o)return!1;let s=()=>({id:em(),type:n,anchors:[],style:{...this.activeStyle},visible:!0,locked:!1,options:this.initialOptions(n),...a===void 0?{}:{paneId:a}});return this.creationPressAt=Date.now(),this.afterCreationStep(this.creator.press(r,s,this.creationAnchor(n,e,o,a),e,e=>this.anchorPoint(n,e,o))),!0}afterCreationStep(e){e===`done`?this.finalizeCreation():e===`cancel`&&this.creator.reset(),this.requestRender?.()}setEraser(e){e!==this.eraser&&(this.eraser=e,this.clearHover(),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=Nm.line){for(let r=this.drawings.length-1;r>=0;r--){let i=this.drawings[r];if(!(!this.shown(i)||i.locked||i.paneId!==t.pane)&&this.registry.get(i.type)?.hitTest(e,i,t.viewport,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,drawn:!0}),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=Nm.line){let r=this.scopeAt(e,t);if(!r)return null;for(let t=this.drawings.length-1;t>=0;t--){let i=this.drawings[t];if(!(!this.shown(i)||i.paneId!==r.pane)&&this.registry.get(i.type)?.hitTest(e,i,r.viewport,n))return i.id}return null}hoverCursorAt(e,t){let n=this.hoverAt(e,t),r=n.handle?.id!==this.hoverHandle?.id||n.handle?.index!==this.hoverHandle?.index;return this.hoverHandle=n.handle,this.hoverDrawing=n.drawing,r&&this.requestRender?.(),n.cursor}drawnExtent(e){return this.extents.get(e)??null}clearHover(){let e=this.hoverHandle;this.hoverHandle=null,this.hoverDrawing=null,e&&this.requestRender?.()}renderHover(e,t){let n=this.hoverDrawing;if(!n||this.selection.has(n)&&!this.eraser||this.activeTool||this.state===`creating`)return;let r=this.drawings.find(e=>e.id===n);if(!r||r.locked||!this.shown(r))return;let i=this.registry.get(r.type),a=this.viewportFor(r.paneId,t);i&&a&&Gm(e,i,r,a,!1,!0)}axisSpans(e){let t=this.creator.previewState(),n=t??(this.selection.primary?this.drawings.find(e=>e.id===this.selection.primary):void 0);if(!n||!t&&!this.shown(n))return[];let r=this.registry.get(n.type),i=this.viewportFor(n.paneId,e),a=r&&i?Am(n,r.descriptor):null;return a&&i?[{...a,color:n.style.color,viewport:i}]:[]}hoverAt(e,t){let n={cursor:null,handle:null,drawing:null},r=this.scopeAt(e,t);if(!r)return n;if(this.eraser){let t=this.erasableAt(e,r);return{...n,cursor:t?`pointer`:null,drawing:t}}if(this.activeTool||this.state===`creating`)return n;let i=Nm.handle,a=r.viewport;if(this.selection.primary){let t=this.drawings.find(e=>e.id===this.selection.primary),n=t&&this.shown(t)&&!t.locked&&t.paneId===r.pane?this.registry.get(t.type):void 0,o=t&&n?n.hitTestAnchor(e,t,a,i):-1;if(t&&o>=0)return{cursor:`move`,handle:{id:t.id,index:o},drawing:t.id}}for(let t=this.drawings.length-1;t>=0;t--){let n=this.drawings[t];if(!(!this.shown(n)||n.locked||n.paneId!==r.pane)&&this.registry.get(n.type)?.hitTest(e,n,a,Nm.line))return{cursor:`pointer`,handle:null,drawing:n.id}}return n}handleSelectionClick(e,t,n){let r=n.line,i=this.scopeAt(e,t);if(!i)return!1;let a=i.viewport;if(this.selection.primary){let t=this.drawings.find(e=>e.id===this.selection.primary);if(t&&this.shown(t)&&!t.locked&&t.paneId===i.pane){let i=this.registry.get(t.type);if(i){let o=i.hitTestAnchor(e,t,a,n.handle);if(o>=0)return this.state=`resizing`,this.drag.beginResize(e,t,o),!0;if(i.hitTest(e,t,a,r))return this.beginMove(e,t),!0}}}for(let t=this.drawings.length-1;t>=0;t--){let n=this.drawings[t];if(!this.shown(n)||n.paneId!==i.pane)continue;let o=this.registry.get(n.type);if(o&&o.hitTest(e,n,a,r))return this.selection.has(n.id)?this.selection.focus(n.id):this.selection.only(n.id,this.groupMates(n)),this.requestRender?.(),n.locked?(this.state=`selected`,!1):(this.beginMove(e,n),!0)}return this.selection.primary&&(this.selection.clear(),this.state=`idle`,this.requestRender?.()),!1}},Vm=.55,Hm=6,Um=[`fill`,`fillRect`,`fillText`,`strokeText`];function Wm(e,n){e.shadowColor=(0,t.withAlpha)(n,Vm),e.shadowBlur=Hm;let r=e;for(let e of Um)r[e]=()=>void 0;return()=>{for(let e of Um)delete r[e]}}function Gm(e,t,n,r,i,a=!1){let o=r.chartRect;e.save(),e.beginPath(),e.rect(o.x,o.y,o.width,o.height),e.clip(),xn(o);let s=a?Wm(e,n.style.color):null;try{t.render(e,n,r,i)}finally{s?.(),xn(null),e.restore()}}function Km(e,t){let{name:n,...r}=e;return t===void 0?r:{...r,name:t}}function qm(e){return(e??``).trim().slice(0,80)}var Jm=class{keepOut=null;formatTime=null;constructor(e){this.manager=e}setKeepOut(e){this.keepOut=e}setTimeFormat(e){this.formatTime=e}getKeepOut(){return this.keepOut?.()??[]}renderHover(e,t,n){Hn(n??null);try{this.manager.renderHover(e,t)}finally{Hn(null)}}axisSpans(e){return this.manager.axisSpans(e)}render(e,t,n){Hn(n??null),Zn(this.getKeepOut());try{this.manager.render(e,this.formatTime?{...t,formatTime:this.formatTime}:t)}finally{Zn(null),Hn(null)}}};function Ym(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 Xm={0:`#787b86`,.236:`#e8505b`,.25:`#e8505b`,.382:`#d97a0e`,.5:`#1a9a6a`,.618:`#0e93a3`,.75:`#2f7fd8`,.786:`#5b6cf0`,1:`#787b86`,1.272:`#b25ad1`,1.414:`#d6487f`,1.618:`#2f7fd8`,2:`#7a5cff`,2.618:`#e8505b`,3.618:`#b25ad1`,4.236:`#d6487f`};function Zm(e,t=[]){return Qm(e,t).map(e=>{let t=Xm[e.value];return t?{...e,color:t}:e})}function Qm(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 $m(e=!1,t=!1){return{extendLeft:{kind:`boolean`,label:`Extend left`,default:e},extendRight:{kind:`boolean`,label:`Extend right`,default:t}}}var eh={showPrice:{kind:`boolean`,label:`Show price`,default:!0}},th={trendLine:{kind:`boolean`,label:`Trend line`,default:!0},oneColor:{kind:`boolean`,label:`Use one color`,default:!1}},nh={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`}]}};function rh(e,t){let n=e.textBackground??t.box,r=e.textBorder??t.border,i=!t.fill&&!e.fillColor?void 0:P(e);return{fontSize:Tn(e),color:e.textColor??Mn(e.color),fill:n&&i?i:void 0,stroke:r?e.borderColor??e.color:void 0,maxWidth:e.textWrap===void 0?t.width:e.textWrap>0?e.textWrap:1/0,bold:e.bold,italic:e.italic,align:e.textAlign}}var ih=1.3,ah=12,oh=3;function sh(e,t=!1,n=!1,r=!0){let i=M();return`${n?`italic `:``}${t?`bold `:``}${e}px ${r?i.prose:i.figures}`}function ch(e,t,n,r=ah){let i=[];for(let a of t.split(`
|
|
2
|
+
`)){let t=``;for(let r of a.split(/\s+/).filter(Boolean)){let a=t?`${t} ${r}`:r;if(e(a)<=n){t=a;continue}t&&i.push(t),t=e(r)<=n?r:lh(e,r,n)}if(i.push(t),i.length>=r)break}return i.length>r&&(i.length=r),i}function lh(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 uh=200,dh=new Map;function fh(e,t,n,r,i){let a=`${r}|${n}|${i}|${t}`,o=dh.get(a);if(o)return o;dh.size>=uh&&dh.clear();let s=ch(e,t,n,i);return dh.set(a,s),s}function ph(e,t,n,r,i){return{x:n,y:r,width:Math.max(0,...t.map(e))+16,height:t.length*i*ih+12}}function mh(e,t,n){let r=sh(n.fontSize,n.bold,n.italic);e.font=r;let i=t=>e.measureText(t).width,{width:a,height:o}=ph(i,fh(i,t,n.maxWidth,r,n.maxLines??ah),0,0,n.fontSize);return{width:a,height:o}}function hh(e,t,n,r,i){let a=sh(i.fontSize,i.bold,i.italic);e.font=a;let o=t=>e.measureText(t).width,s=fh(o,t,i.maxWidth,a,i.maxLines??ah),c=ph(o,s,n,r,i.fontSize);if(i.fill||i.stroke){let t=Math.round(c.x)+.5,n=Math.round(c.y)+.5;e.beginPath(),i.traceBox?i.traceBox(e,t,n,Math.round(c.width)-1,Math.round(c.height)-1,oh):typeof e.roundRect==`function`?e.roundRect(t,n,Math.round(c.width)-1,Math.round(c.height)-1,oh):e.rect(t,n,Math.round(c.width)-1,Math.round(c.height)-1),i.fill&&(e.fillStyle=i.fill,e.fill()),i.stroke&&(e.strokeStyle=i.stroke,e.lineWidth=1,e.setLineDash([]),e.stroke())}e.fillStyle=i.color,e.textAlign=`left`,e.textBaseline=`top`;let l=c.width-16;return s.forEach((t,a)=>{let s=l-o(t),c=i.align===`center`?s/2:i.align===`right`?s:0,u=r+6+a*i.fontSize*ih;i.fill?e.fillText(t,n+8+c,u):F(e,t,n+8+c,u)}),c}var gh=3;function _h(e,t,n,r=!0){let i=Math.round(t.x-gh)+.5,a=Math.round(t.y-gh)+.5,o=Math.round(t.width+gh*2)-1,s=Math.round(t.height+gh*2)-1;vn(i-1,a-1,o+2,s+2),r&&(e.save(),e.strokeStyle=n,e.lineWidth=1,e.globalAlpha=1,e.setLineDash([]),e.beginPath(),typeof e.roundRect==`function`?e.roundRect(i,a,o,s,oh+gh):e.rect(i,a,o,s),e.stroke(),e.restore())}function vh(e){let t=e.map(e=>e.x),n=e.map(e=>e.y),r=Math.min(...t),i=Math.min(...n);return{x:r,y:i,width:Math.max(...t)-r,height:Math.max(...n)-i}}function yh(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 bh=1e3,xh=class{boxes=new Map;set(e,t){this.boxes.size>=bh&&!this.boxes.has(e)&&this.boxes.clear(),this.boxes.set(e,t)}get(e){return this.boxes.get(e)}},Sh=4,Ch=6,wh=1.3,Th=20,Eh=.5,Dh=1e-6;function Oh(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=0,o=1,s=[[-r,e.x-n.x],[r,n.x+n.width-e.x],[-i,e.y-n.y],[i,n.y+n.height-e.y]];for(let[e,t]of s){if(e===0){if(t<0)return null;continue}let n=t/e;if(e<0?a=Math.max(a,n):o=Math.min(o,n),a>o)return null}return[{x:e.x+a*r,y:e.y+a*i},{x:e.x+o*r,y:e.y+o*i}]}var kh=1e4,Ah=class{boxes=new Map;set(e,t){if(!t){this.boxes.delete(e);return}this.boxes.delete(e),this.boxes.size>=kh&&this.boxes.delete(this.boxes.keys().next().value),this.boxes.set(e,t)}bounds(e){let t=this.boxes.get(e);if(!t)return null;let n=Math.cos(t.angle),r=Math.sin(t.angle),i=[[t.left,t.top],[t.left+t.width,t.top],[t.left,t.top+t.height],[t.left+t.width,t.top+t.height]].map(([e,i])=>({x:t.x+e*n-i*r,y:t.y+e*r+i*n})),a=i.map(e=>e.x),o=i.map(e=>e.y),s=Math.min(...a),c=Math.min(...o);return{x:s,y:c,width:Math.max(...a)-s,height:Math.max(...o)-c}}hit(e,t,n){let r=this.boxes.get(e);if(!r)return!1;let i=t.x-r.x,a=t.y-r.y,o=Math.cos(r.angle),s=Math.sin(r.angle),c=i*o+a*s,l=-i*s+a*o;return c>=r.left-n&&c<=r.left+r.width+n&&l>=r.top-n&&l<=r.top+r.height+n}};function jh(e){let t=e.text?.trim();return t?t.split(`
|
|
3
|
+
`).slice(0,Th):[]}function Mh(e,t){let n=Tn(t);return e.font=sh(n,t.bold,t.italic),e.fillStyle=t.textColor??t.color,n*wh}function Nh(e,t,n,r,i){let a=jh(t);if(a.length===0)return null;let o=i?Oh(n,r,i):[n,r];if(!o)return null;let[s,c]=o,[l,u]=Math.abs(c.x-s.x)<Eh?s.y>c.y?[s,c]:[c,s]:s.x<c.x?[s,c]:[c,s],d=Math.atan2(u.y-l.y,u.x-l.x),f=t.textAlign??`center`,p=f===`left`?l:f===`right`?u:{x:(l.x+u.x)/2,y:(l.y+u.y)/2},m=f===`left`?Ch:f===`right`?-Ch:0;e.save();let h=Mh(e,t);e.translate(p.x,p.y),e.rotate(d),e.textAlign=f;let g=t.textVAlign??`top`;e.textBaseline=g===`top`?`bottom`:g===`bottom`?`top`:`middle`;let _=0;a.forEach((t,n)=>{_=Math.max(_,e.measureText(t).width);let r=g===`top`?-Sh-(a.length-1-n)*h:g===`bottom`?Sh+n*h:(n-(a.length-1)/2)*h;if(F(e,t,m,r),Math.abs(d)<Dh){let n=e.measureText(t).width,i=p.x+m-(f===`left`?0:f===`right`?n:n/2),a=p.y+r-(g===`top`?h:g===`bottom`?0:h/2);Qn(i,a,i+n,a+h)}}),e.restore();let v=a.length*h;return{x:p.x,y:p.y,angle:d,left:m-(f===`left`?0:f===`right`?_:_/2),top:g===`top`?-Sh-v:g===`bottom`?Sh:-v/2,width:_,height:v}}function Ph(e,t,n){let r=jh(t);if(r.length===0)return null;e.save();let i=Mh(e,t),a=t.textAlign??`center`,o=a===`left`?n.x+8:a===`right`?n.x+n.width-8:n.x+n.width/2,s=t.textVAlign??`top`,c=r.length*i,l=s===`top`?n.y+6:s===`bottom`?n.y+n.height-6-c:n.y+(n.height-c)/2;e.textAlign=a,e.textBaseline=`top`;let u=0;return r.forEach((t,n)=>{u=Math.max(u,e.measureText(t).width),F(e,t,o,l+n*i)}),e.restore(),{x:0,y:0,angle:0,left:a===`left`?o:a===`right`?o-u:o-u/2,top:l,width:u,height:c}}var Fh=28,Ih=48;function Lh(e,t){return Math.atan2(e.y-t.y,t.x-e.x)*180/Math.PI}var Rh=class extends J{descriptor={type:`trendAngle`,name:`Trend Angle`,requiredAnchors:2,text:!0};render(e,t,n,r){if(this.texts.set(t.id,null),t.anchors.length<2)return;let i=this.anchorToPixel(t.anchors[0],n),a=this.anchorToPixel(t.anchors[1],n),o=Lh(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),this.applyGuideStyle(e,t.style.color,!0),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x+s*Ih,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,Fh,Math.min(l,c),Math.max(l,c)),e.stroke(),e.globalAlpha=1,e.font=N(`label`),e.fillStyle=Mn(t.style.color),e.textAlign=s>0?`left`:`right`,e.textBaseline=`middle`,F(e,`${o.toFixed(1)}°`,i.x+s*(Fh+6),i.y+(o>=0?-8:8)),this.texts.set(t.id,Nh(e,t.style,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n),n.chartRect)),r&&this.renderAnchorHandles(e,t,n)}texts=new Ah;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},zh=3.5,Bh=1.5,Vh=8,Hh=[{value:`normal`,label:`Normal`},{value:`arrow`,label:`Arrow`}],Uh={leftEnd:{kind:`choice`,label:`Left end`,default:`normal`,choices:Hh},rightEnd:{kind:`choice`,label:`Right end`,default:`normal`,choices:Hh}},Wh={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 Gh(e,t,n,r,i=1){let a=En(i),o=Math.atan2(n.y-t.y,n.x-t.x);e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-a*Math.cos(o-Math.PI/6),n.y-a*Math.sin(o-Math.PI/6)),e.lineTo(n.x-a*Math.cos(o+Math.PI/6),n.y-a*Math.sin(o+Math.PI/6)),e.closePath(),e.fillStyle=r,e.fill()}var Kh=1.5;function qh(e,t,n,r,i=1){Math.hypot(n.x-t.x,n.y-t.y)<En(i)*Kh||Gh(e,t,n,r,i)}function Jh(e,t,n,r){let[i,a]=t;i.x===a.x&&i.y===a.y||(r(`leftEnd`)===`arrow`&&Gh(e,a,i,n,Number(e.lineWidth)||1),r(`rightEnd`)===`arrow`&&Gh(e,i,a,n,Number(e.lineWidth)||1))}function Yh(e,t,n,r,i){let a=[];i(`showPriceRange`)&&a.push(Er(e.anchors[0].price,e.anchors[1].price,t)),i(`showBarsRange`)&&a.push(`${kr(e,0,1,t)} bars`);let o=i(`showDateRange`)?Ar(e,0,1,t):null;return o&&a.push(o),i(`showAngle`)&&a.push(`${Lh(n,r).toFixed(1)}°`),a}function Xh(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,Math.max(zh,Nn(t.style.lineWidth)-1),0,Math.PI*2),e.fillStyle=Un(),e.fill(),e.strokeStyle=t.style.color,e.lineWidth=Bh,e.setLineDash([]),e.stroke()),!a&&!o(`alwaysShowStats`))return;let c=Yh(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`){jr(e,c,s.x,s.y-Vh,`center`,!0);return}let[f,p]=d===`left`?[l,u]:[u,l],m=f.y<=p.y;jr(e,c,d===`left`?f.x-Vh:f.x+Vh,f.y+(m?-Vh:Vh),d===`left`?`right`:`left`,m)}var Zh=class extends J{descriptor={type:`trendLine`,name:`Trend Line`,requiredAnchors:2,text:!0,options:{...$m(),...Uh,...Wh}};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(this.texts.set(t.id,null),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);Jh(e,[i,a],t.style.color,o),Xh(e,t,n,[this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n)],r,o),this.texts.set(t.id,Nh(e,t.style,i,a,n.chartRect)),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`),Vp(n));return r===null?null:[r]}texts=new Ah;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},Qh=class extends J{descriptor={type:`horizontalLine`,name:`Horizontal Line`,requiredAnchors:1,text:!0,options:eh,axisSpan:`price`};priceAt(e){return e.anchors.length<1?null:[e.anchors[0].price]}render(t,n,r,i){if(this.texts.set(n.id,null),n.anchors.length<1)return;let a=e.k(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),this.texts.set(n.id,Nh(t,n.style,{x:o.x,y:a},{x:o.x+o.width,y:a})),this.option(n,`showPrice`)&&(t.fillStyle=Mn(n.style.color),ar(t,wr(n.anchors[0].price,n.anchors[0].price,r),o.x,a,o.x+o.width,o.y)),i&&this.renderAnchorHandles(t,n,r)}texts=new Ah;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(t,n,r,i){if(n.anchors.length<1)return!1;let a=e.k(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}},$h=class extends J{descriptor={type:`horizontalRay`,name:`Horizontal Ray`,requiredAnchors:1,text:!0,options:eh,axisSpan:`price`};priceAt(e,t){return e.anchors.length<1||t<e.anchors[0].time?null:[e.anchors[0].price]}render(e,t,n,r){if(this.texts.set(t.id,null),t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=i.y,{chartRect:o}=n;if(this.applyLineStyle(e,t.style),this.strokeHorizontal(e,i.x,o.x+o.width,a),this.resetLineStyle(e),this.texts.set(t.id,Nh(e,t.style,i,{x:o.x+o.width,y:a},o)),this.option(t,`showPrice`)){e.fillStyle=Mn(t.style.color);let r=i.x+Nn(t.style.lineWidth);ar(e,wr(t.anchors[0].price,t.anchors[0].price,n),r,a,o.x+o.width,o.y)}r&&this.renderAnchorHandles(e,t,n)}texts=new Ah;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},eg=4,tg=class extends J{descriptor={type:`verticalLine`,name:`Vertical Line`,requiredAnchors:1,text:!0,axisSpan:`time`,options:{showTime:{kind:`boolean`,label:`Show time`,default:!1}}};render(e,t,n,r){if(this.texts.set(t.id,null),t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),{chartRect:a}=n,o=a.y+a.height;this.applyLineStyle(e,t.style),this.strokeVertical(e,i.x,a.y,o),this.resetLineStyle(e);let s=this.option(t,`showTime`)?this.timeText(t,n):null,c=s?o-eg*2-sr():o;if(this.texts.set(t.id,Nh(e,t.style,{x:i.x,y:c},{x:i.x,y:a.y})),s){e.font=N(`label`);let n=e.measureText(s).width+12;fr(e,s,i.x-n/2,o-eg-sr()/2,t.style.color)}r&&this.renderAnchorHandles(e,t,n)}timeText(e,t){if(!t.formatTime)return null;try{return t.formatTime(e.anchors[0].time)}catch{return null}}texts=new Ah;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},ng=class extends J{descriptor={type:`ray`,name:`Ray`,requiredAnchors:2,text:!0,options:Wh};render(e,t,n,r){if(this.texts.set(t.id,null),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),Xh(e,t,n,[i,a],r,this.optionsOf(t)),this.texts.set(t.id,Nh(e,t.style,i,{x:d,y:f},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,!1,!0,Vp(n));return r===null?null:[r]}texts=new Ah;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},rg=class extends J{descriptor={type:`extendedLine`,name:`Extended Line`,requiredAnchors:2,text:!0,options:Wh};render(e,t,n,r){if(this.texts.set(t.id,null),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),Xh(e,t,n,[i,a],r,this.optionsOf(t)),this.texts.set(t.id,Nh(e,t.style,{x:d,y:f},{x:p,y:m},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,!0,!0,Vp(n));return r===null?null:[r]}texts=new Ah;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},ig=.7,ag=.5,og=class extends J{descriptor={type:`parallelChannel`,name:`Parallel Channel`,requiredAnchors:3,fill:!0,options:{...$m(),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=Math.abs(c)<ag,u=l?s.y:n.y+(s.x-n.x)*(r.y-n.y)/c,d=l?{x:s.x-n.x,y:0}:{x:0,y:s.y-u},f=(e,t)=>({x:e.x+d.x*t,y:e.y+d.y*t}),p=f(n,1),m=f(r,1);return{base:o,parallel:this.extendLine(p,m,t,i,a),middle:this.option(e,`middleLine`)?this.extendLine(f(n,.5),f(r,.5),t,i,a):null,corners:[n,r,m,p]}}handlePoints(e,t){let n=super.handlePoints(e,t),{corners:r}=this.lines(e,t);if(!r||n.length<3)return n;let[,,i,a]=r;return[n[0],n[1],{x:(a.x+i.x)/2,y:(a.y+i.y)/2}]}render(e,t,n,r){if(t.anchors.length<2)return;let{base:i,parallel:a,middle:o,corners:s}=this.lines(t,n);if(s&&t.style.fillColor){e.fillStyle=P(t.style),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.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());o&&(e.setLineDash(Ln(`dashed`,t.style.lineWidth)),e.lineCap=`butt`,e.globalAlpha=ig,e.beginPath(),e.moveTo(o[0].x,o[0].y),e.lineTo(o[1].x,o[1].y),e.stroke(),e.globalAlpha=1),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=Vp(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)}},sg=2,cg=.8,lg=64;function ug(e,t,n){let r=Math.max(0,Math.round(Math.min(t,n))),i=Math.min(e.length-1,Math.round(Math.max(t,n))),a=i-r+1;if(a<2)return null;let o=0,s=0,c=0,l=0;for(let t=r;t<=i;t++){let n=e[t].close;o+=t,s+=n,c+=t*t,l+=t*n}let u=a*c-o*o;if(u===0)return null;let d=(a*l-o*s)/u,f=(s-d*o)/a,p=e=>f+d*e,m=0;for(let t=r;t<=i;t++)m+=(e[t].close-p(t))**2;return{from:r,to:i,slope:d,intercept:f,deviation:Math.sqrt(m/a),at:p}}var dg=class extends J{descriptor={type:`regressionChannel`,name:`Regression Channel`,requiredAnchors:2,fill:!0};dataGetter=null;dataRevision=()=>0;fits=new Map;fitsFor={data:null,length:0,revision:-1};setDataGetter(e,t=()=>0){this.dataGetter=e,this.dataRevision=t,this.fits.clear()}fit(t,n){let r=this.dataGetter?.();if(!r||r.length<2||t.anchors.length<2)return null;let i=this.dataRevision(),a=this.fitsFor;(a.data!==r||a.length!==r.length||a.revision!==i)&&(this.fits.clear(),this.fitsFor={data:r,length:r.length,revision:i});let o=Math.round(e.j(t.anchors[0].time,n)),s=Math.round(e.j(t.anchors[1].time,n)),c=`${o}:${s}`,l=this.fits.get(c);return l===void 0&&(this.fits.size>=lg&&this.fits.clear(),l=ug(r,o,s),this.fits.set(c,l)),l}lines(t,n){let r=this.fit(t,n);if(!r)return{middle:[this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n)],upper:null,lower:null};let i=t=>[{x:e.w(r.from,n),y:e.k(r.at(r.from)+t,n)},{x:e.w(r.to,n),y:e.k(r.at(r.to)+t,n)}],a=r.deviation*sg;return{middle:i(0),upper:i(a),lower:i(-a)}}handlePoints(t,n){let r=this.fit(t,n);return r?t.anchors.map(t=>{let i=Math.max(r.from,Math.min(r.to,Math.round(e.j(t.time,n))));return{x:e.w(i,n),y:e.k(r.at(i),n)}}):super.handlePoints(t,n)}render(e,t,n,r){if(t.anchors.length<2)return;let{middle:i,upper:a,lower:o}=this.lines(t,n);a&&o&&t.style.fillColor&&(e.fillStyle=P(t.style),e.beginPath(),e.moveTo(a[0].x,a[0].y),e.lineTo(a[1].x,a[1].y),e.lineTo(o[1].x,o[1].y),e.lineTo(o[0].x,o[0].y),e.closePath(),e.fill()),this.applyLineStyle(e,t.style);for(let t of[a,o])t&&(e.beginPath(),e.moveTo(t[0].x,t[0].y),e.lineTo(t[1].x,t[1].y),e.stroke());a&&(e.setLineDash(Ln(`dashed`,t.style.lineWidth)),e.lineCap=`butt`,e.globalAlpha=cg),e.beginPath(),e.moveTo(i[0].x,i[0].y),e.lineTo(i[1].x,i[1].y),e.stroke(),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{middle:i,upper:a,lower:o}=this.lines(t,n);return[i,a,o].some(t=>t!==null&&this.distanceToLine(e,t[0],t[1])<=r)}},fg=1,pg=.06,mg=3,hg=.8;function gg(e,n,r,i,a=e=>e.toFixed(2),o=`en-US`){let s=e*100,c=`${(0,t.formatPrice)(s,Math.abs(s-Math.round(s))<1e-9?0:fg,o)}%`,l=a(n);return r&&i?`${c} (${l})`:r?c:i?l:``}function _g(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.k(o[i].price,r),l=e.k(o[i+1].price,r);t.fillStyle=o[i+1].level.color??P(n.style,1),t.globalAlpha=pg,t.fillRect(a.x0,Math.min(c,l),s,Math.abs(l-c))}t.globalAlpha=1}t.font=N(`label`),t.textBaseline=`bottom`,t.textAlign=a.labelPosition===`right`?`right`:`left`;let c=a.labelPosition===`right`?a.x1-4:a.x0+4,l=M().sizes.label,u=[],d=e=>e===0||e===1,f=i.map(({level:t,price:n})=>({level:t,price:n,y:e.k(n,r)}));for(let{level:r,y:i}of f){o(r.color??n.style.color),t.globalAlpha=d(r.value)?1:hg;let s=e.v(t,i,Number(t.lineWidth)||1);t.lineWidth=s.width,t.beginPath(),t.moveTo(a.x0,s.y),t.lineTo(a.x1,s.y),t.stroke()}t.globalAlpha=1;let p=[...f].sort((e,t)=>Number(d(t.level.value))-Number(d(e.level.value)));for(let{level:e,price:i,y:o}of p){let s=gg(e.value,i,a.showLevels,a.showPrices,e=>wr(e,e,r),r.numberLocale);if(!s)continue;let f=t.measureText(s).width,p=a.labelPosition===`right`?c-f:c,m={left:p,right:p+f,top:o-mg-l,bottom:o-mg},h={left:p,right:p+f,top:o+mg,bottom:o+mg+l},g=nr(p,p+f,o+mg)+mg,_={left:p,right:p+f,top:g,bottom:g+l},v=Nr([m,h,_],u)??(d(e.value)?_:null);v&&(u.push(v),t.fillStyle=Mn(e.color??n.style.color),t.textBaseline=`top`,F(t,s,c,v.top))}t.globalAlpha=1}var vg=[5,4],yg=.8;function bg(e,t,n){t.length<2||(e.save(),e.strokeStyle=n,e.lineWidth=1,e.globalAlpha=yg,e.setLineDash(vg),e.beginPath(),t.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.stroke(),e.restore())}function xg(e){return e.map(({level:e,price:t})=>({level:{...e,color:void 0},price:t}))}function Sg(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.k(r,n))<=o)}var Cg=Zm([0,.236,.382,.5,.618,.786,1],[1.272,1.414,1.618,2.618,3.618,4.236]),wg=class extends J{descriptor={type:`fibRetracement`,name:`Fibonacci Retracement`,requiredAnchors:2,fill:!0,options:{levels:{kind:`levels`,label:`Levels`,default:Cg},...$m(!0,!0),reverse:{kind:`boolean`,label:`Reverse`,default:!1},...nh,...th,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);this.option(t,`trendLine`)&&bg(e,t.anchors.slice(0,2).map(e=>this.anchorToPixel(e,n)),t.style.color),_g(e,t,n,this.option(t,`oneColor`)?xg(this.levels(t)):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 Sg(e,n,this.levels(t),i,a,r)}},Tg=Zm([0,.618,1,1.618,2,2.618,3.618,4.236],[.382,.5,.786,1.272,1.414]),Eg=class extends J{descriptor={type:`fibExtension`,name:`Fibonacci Extension`,requiredAnchors:3,fill:!0,options:{levels:{kind:`levels`,label:`Levels`,default:Tg},...$m(!0,!0),...nh,...th,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);this.option(t,`trendLine`)&&bg(e,t.anchors.slice(0,3).map(e=>this.anchorToPixel(e,n)),t.style.color),_g(e,t,n,this.option(t,`oneColor`)?xg(this.levels(t)):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 Sg(e,n,this.levels(t),i,a,r)}},Dg=new Set([4,5,6,7]),Og=class extends J{descriptor={type:`rectangle`,name:`Rectangle`,requiredAnchors:2,fill:!0,text:!0};render(e,t,n,r){if(this.texts.set(t.id,null),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=P(t.style),e.fillRect(o,s,c,l)),this.applyLineStyle(e,t.style),e.strokeRect(o,s,c,l),this.resetLineStyle(e),this.texts.set(t.id,Ph(e,t.style,{x:o,y:s,width:c,height:l})),r&&this.renderBoxHandles(e,t,n)}handlePoints(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i={x:(n.x+r.x)/2,y:(n.y+r.y)/2};return[n,r,{x:n.x,y:r.y},{x:r.x,y:n.y},{x:i.x,y:n.y},{x:i.x,y:r.y},{x:n.x,y:i.y},{x:r.x,y:i.y}]}renderBoxHandles(e,t,n){jp(e,t,this.handlePoints(t,n),{sides:Dg})}hitTestAnchor(e,t,n,r){if(t.anchors.length<2)return super.hitTestAnchor(e,t,n,r);let i=-1,a=r;return this.handlePoints(t,n).forEach((t,n)=>{let o=Math.hypot(e.x-t.x,e.y-t.y);(o<a||i<0&&o<=r)&&(i=n,a=o)}),i}moveHandle(e,t,n){let[r,i]=e.anchors,a={0:[n,i],1:[r,n],2:[{time:n.time,price:r.price},{time:i.time,price:n.price}],3:[{time:r.time,price:n.price},{time:n.time,price:i.price}],4:[{time:r.time,price:n.price},i],5:[r,{time:i.time,price:n.price}],6:[{time:n.time,price:r.price},i],7:[r,{time:n.time,price:i.price}]};return a[t]?{...e,anchors:a[t]}:e}texts=new Ah;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},kg=class extends J{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=P(t.style),e.fill()),this.applyLineStyle(e,t.style),e.stroke(),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}handlePoints(e,t){if(e.anchors.length<2)return super.handlePoints(e,t);let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i={x:(n.x+r.x)/2,y:(n.y+r.y)/2};return[{x:i.x,y:n.y},{x:i.x,y:r.y},{x:n.x,y:i.y},{x:r.x,y:i.y}]}moveHandle(e,t,n){let[r,i]=e.anchors,a={0:[{time:r.time,price:n.price},i],1:[r,{time:i.time,price:n.price}],2:[{time:n.time,price:r.price},i],3:[r,{time:n.time,price:i.price}]};return a[t]?{...e,anchors:a[t]}:e}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}},Ag=class extends J{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=P(t.style),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}};function jg(e,t,n){let r=1/0;return t.x>0&&(r=Math.min(r,(n.x+n.width-e.x)/t.x)),t.x<0&&(r=Math.min(r,(n.x-e.x)/t.x)),t.y>0&&(r=Math.min(r,(n.y+n.height-e.y)/t.y)),t.y<0&&(r=Math.min(r,(n.y-e.y)/t.y)),Number.isFinite(r)?Math.max(0,r):0}function Mg(e,t,n){return{x:e.x+t.x*n,y:e.y+t.y*n}}function Ng(e,t){let{origin:n,b:r,c:i,dir:a}=e,o=[n,r,i].map(e=>[e,Mg(e,a,jg(e,a,t))]);return[[r,i],...o]}var Pg=class extends J{descriptor={type:`pitchfork`,name:`Andrews' Pitchfork`,requiredAnchors:3,fill:!0};origin(e,t){return e}fork(e,t){let n=this.anchorToPixel(e.anchors[0],t),r=this.anchorToPixel(e.anchors[1],t),i=this.anchorToPixel(e.anchors[2],t),a=this.origin(n,r),o={x:(r.x+i.x)/2,y:(r.y+i.y)/2},s=o.x-a.x,c=o.y-a.y,l=Math.hypot(s,c)||1;return{pivot:n,origin:a,b:r,c:i,dir:{x:s/l,y:c/l}}}render(e,t,n,r){if(t.anchors.length<3){t.anchors.length===2&&this.renderFirstLeg(e,t,n);return}let i=this.fork(t,n),a=n.chartRect;this.fillTines(e,t,i,a),this.renderOriginGuide(e,t,i),this.applyLineStyle(e,t.style);for(let[t,n]of Ng(i,a))this.strokeSegment(e,t,n);this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}renderFirstLeg(e,t,n){let r=this.anchorToPixel(t.anchors[0],n),i=this.anchorToPixel(t.anchors[1],n);this.applyLineStyle(e,t.style),this.strokeSegment(e,r,i),this.resetLineStyle(e)}fillTines(e,t,n,r){let{b:i,c:a,dir:o}=n,s=Math.max(jg(i,o,r),jg(a,o,r));if(s<=0)return;e.save(),e.beginPath(),e.rect(r.x,r.y,r.width,r.height),e.clip(),e.fillStyle=P(t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y);let c=Mg(a,o,s),l=Mg(i,o,s);e.lineTo(c.x,c.y),e.lineTo(l.x,l.y),e.closePath(),e.fill(),e.restore()}renderOriginGuide(e,t,n){let{pivot:r,origin:i}=n;r.x===i.x&&r.y===i.y||(this.applyGuideStyle(e,t.style.color,!0),this.strokeSegment(e,r,i),e.globalAlpha=1,e.setLineDash([]))}strokeSegment(e,t,n){e.beginPath(),e.moveTo(t.x,t.y),e.lineTo(n.x,n.y),e.stroke()}hitTest(e,t,n,r){return t.anchors.length<3?!1:Ng(this.fork(t,n),n.chartRect).some(([t,n])=>this.distanceToLine(e,t,n)<=r)}},Fg=class extends Pg{descriptor={type:`schiffPitchfork`,name:`Schiff Pitchfork`,requiredAnchors:3,fill:!0};origin(e,t){return{x:e.x,y:(e.y+t.y)/2}}},Ig=class extends Pg{descriptor={type:`modifiedSchiffPitchfork`,name:`Modified Schiff Pitchfork`,requiredAnchors:3,fill:!0};origin(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}},Lg=5,Rg=3,zg=1.25,Bg=1.5,Vg=[.5,.38,.62,.26,.74,.15,.85],Hg=8,Ug=3;function Wg(e,t){let n=e[t-1],r=e[t+1],i=e[t];return!n&&!r?`above`:!n||!r?i.y<=(n??r).y?`above`:`below`:i.y<=(n.y+r.y)/2?`above`:`below`}function Gg(e){return Nn(e)+Lg}function Kg(e,t,n,r,i){let a=t===`above`?e.y-i-r:e.y+i;return{left:e.x-n/2,right:e.x+n/2,top:a,bottom:a+r}}function qg(e,t,n,r,i){let a=Wg(e,t),o=Kg(e[t],a,n,r,i);return Cn(o.left,o.top,n,r).top===o.top?o:Kg(e[t],a===`above`?`below`:`above`,n,r,i)}function Jg(e,t){return e.left<t.right&&t.left<e.right&&e.top<t.bottom&&t.top<e.bottom}function Yg(e,t,n,r){let i=e.measureText(t).width;if(!n)return{width:i,height:r};let a=2*Xg(i,r);return{width:a,height:a}}function Xg(e,t){return Math.max(e,t)/2+Rg}function Zg(e,t,n,r,i){let a=a=>n.slice(0,t.length).map((n,o)=>{let s=a&&n.short?n.short:n.text,c=Yg(e,s,!!n.ring,r);return{text:s,ring:!!n.ring,first:!!n.first,box:qg(t,o,c.width,c.height,i)}}).filter(e=>e.text),o=a(!1),s=o.some((e,t)=>o.slice(t+1).some(t=>Jg(e.box,t.box)))?a(!0):o,c=[...s.filter(e=>e.first),...s.filter(e=>!e.first)],l=[];for(let e of c)l.every(t=>!Jg(t.box,e.box))&&l.push(e);return s.filter(e=>l.includes(e))}function Qg(e,t,n,r,i){let a=Zg(e,n,r,i,Gg(t.style.lineWidth)),o=Mn(t.style.color);e.textAlign=`center`,e.textBaseline=`middle`;for(let n of a){let r=(n.box.left+n.box.right)/2,i=(n.box.top+n.box.bottom)/2;n.ring&&$g(e,r,i,(n.box.right-n.box.left)/2,t.style.color),e.fillStyle=o,F(e,n.text,r,i),e_(n.box)}return a.map(e=>e.box)}function $g(e,t,n,r,i){e.save(),e.beginPath(),e.arc(t,n,r,0,Math.PI*2),e.fillStyle=M().background,e.fill(),e.strokeStyle=i,e.lineWidth=zg,e.setLineDash([]),e.stroke(),e.restore()}function e_(e){vn(e.left,e.top,e.right-e.left,e.bottom-e.top),Qn(e.left,e.top,e.right,e.bottom)}function t_(e,t){let n=Nn(t)+Bg;return e.map(e=>({left:e.x-n,right:e.x+n,top:e.y-n,bottom:e.y+n}))}function n_(e,t,n,r,i){e.font=N(`mark`);let a=e.measureText(t).width,o=M().sizes.mark,s=o+Ug,c=[0,s,-s].flatMap(e=>Vg.map(t=>{let i=n.x+(r.x-n.x)*t,s=n.y+(r.y-n.y)*t+e;return{left:i-a/2,right:i+a/2,top:s-o/2,bottom:s+o/2}})),l=c.map(e=>({...e,left:e.left-Hg,right:e.right+Hg})),u=Nr(l,i);if(!u)return null;let d=c[l.indexOf(u)];return e.textAlign=`center`,e.textBaseline=`middle`,F(e,t,(d.left+d.right)/2,(d.top+d.bottom)/2),e_(d),d}var r_=[`0`,`i`,`ii`,`iii`,`iv`,`v`];function i_(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?r_[Number(e)]??e:e.toLowerCase();default:return e}}function a_(e,t){return t===`primary`?{text:e,ring:!0}:{text:i_(e,t)}}var o_={degree:{kind:`choice`,label:`Degree`,default:`minor`,choices:[{value:`primary`,label:`Primary`},{value:`intermediate`,label:`Intermediate`},{value:`minor`,label:`Minor`},{value:`minute`,label:`Minute`}]}},s_=class extends J{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=N(`letter`,{weight:600}),Qg(e,t,i,this.labels.map(e=>a_(e,a)),M().sizes.letter),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:Up(e,t.anchors.map(e=>this.anchorToPixel(e,n)),r)}},c_=class extends s_{descriptor={type:`elliottWave`,name:`Elliott Wave`,requiredAnchors:8,options:o_};labels=[`1`,`2`,`3`,`4`,`5`,`A`,`B`,`C`]},l_=class extends s_{descriptor={type:`elliottImpulse`,name:`Elliott Impulse Wave`,requiredAnchors:6,options:o_};labels=[`0`,`1`,`2`,`3`,`4`,`5`]},u_=class extends s_{descriptor={type:`elliottCorrection`,name:`Elliott Correction Wave`,requiredAnchors:4,options:o_};labels=[`0`,`A`,`B`,`C`]},d_=class extends s_{descriptor={type:`elliottTriangle`,name:`Elliott Triangle Wave`,requiredAnchors:6,options:o_};labels=[`0`,`A`,`B`,`C`,`D`,`E`]},f_=class extends s_{descriptor={type:`elliottDoubleCombo`,name:`Elliott Double Combo Wave`,requiredAnchors:4,options:o_};labels=[`0`,`W`,`X`,`Y`]},p_=class extends s_{descriptor={type:`elliottTripleCombo`,name:`Elliott Triple Combo Wave`,requiredAnchors:6,options:o_};labels=[`0`,`W`,`X`,`Y`,`X`,`Z`]},m_=.6,h_=6,g_=class extends J{descriptor={type:`priceRange`,name:`Price Range`,requiredAnchors:2};render(e,n,r,i){if(n.anchors.length<2)return;let a=this.anchorToPixel(n.anchors[0],r),o=this.anchorToPixel(n.anchors[1],r),s=Math.min(a.x,o.x),c=Math.abs(o.x-a.x),l=Math.min(a.y,o.y),u=Math.abs(o.y-a.y),d=M(),f=n.anchors[1].price>=n.anchors[0].price,p=n.style.color.toLowerCase()===t.DEFAULT_DRAWING_STYLE.color?f?d.rise:d.fall:n.style.color;e.fillStyle=(0,t.withAlpha)(p,cn),e.fillRect(s,l,c,u),e.save(),this.applyGuideStyle(e,p),e.globalAlpha=m_,this.strokeCrispRect(e,s,l,c,u),e.restore();let m=s+c/2;this.applyLineStyle(e,{...n.style,color:p}),e.beginPath(),e.moveTo(m,a.y),e.lineTo(m,o.y),e.stroke(),this.resetLineStyle(e),qh(e,{x:m,y:a.y},{x:m,y:o.y},p,n.style.lineWidth),e.font=N(`label`);let h=Er(n.anchors[0].price,n.anchors[1].price,r),g=dr(e,h),_=sr(),v=f?l-h_-_:l+u+h_,y=Cn(m-g/2,v,g,_);fr(e,h,y.left,y.top+_/2,p),i&&this.renderAnchorHandles(e,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),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}},__=.08,v_=6,y_=class extends J{descriptor={type:`dateRange`,name:`Date Range`,requiredAnchors:2};handlePoints(e,t){return this.timeHandles(e,t)}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=Math.min(i.x,a.x),c=Math.max(i.x,a.x),l=o.y,u=o.y+o.height;e.fillStyle=P(t.style,__),e.fillRect(s,l,c-s,u-l),this.applyLineStyle(e,t.style),this.strokeVertical(e,s,l,u),e.lineWidth=t.style.lineWidth,this.strokeVertical(e,c,l,u);let d=l+(u-l)/2;e.lineWidth=t.style.lineWidth,e.beginPath(),e.moveTo(i.x,d),e.lineTo(a.x,d),e.stroke(),this.resetLineStyle(e),qh(e,{x:i.x,y:d},{x:a.x,y:d},t.style.color,t.style.lineWidth);let f=kr(t,0,1,n),p=Ar(t,0,1,n),m=p?`${f} bars · ${p}`:`${f} bars`;e.font=N(`label`);let h=dr(e,m),g=sr(),_=Cn((s+c)/2-h/2,d-v_-g,h,g);fr(e,m,_.left,_.top+g/2,t.style.color),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),{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}},b_=class extends J{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.lineCap=`butt`,t.setLineDash(Ln(`dashed`,n.style.lineWidth)),t.beginPath(),t.moveTo(a.x,a.y),t.lineTo(o.x,o.y),t.stroke(),this.resetLineStyle(t);let s=e.j(n.anchors[0].time,r),c=e.j(n.anchors[1].time,r),l=Math.max(0,Math.round(Math.abs(c-s))),u=[Er(n.anchors[0].price,n.anchors[1].price,r),`${l} bars`];t.font=N(`label`),t.textAlign=`center`,t.textBaseline=`bottom`;let d=Math.max(...u.map(e=>t.measureText(e).width)),f=w_((a.x+o.x)/2,(a.y+o.y)/2,d,u.length,r);Mr(t,f.x,f.y,f.width,f.height),t.fillStyle=M().ink;let p=f.x+f.width/2,m=f.y+f.height-C_;for(let e=0;e<u.length;e++)t.fillText(u[e],p,m-(u.length-1-e)*x_);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}},x_=14,S_=6,C_=4;function w_(e,t,n,r,i){let{chartRect:a}=i,o=n+2*S_,s=r*x_+2*C_,c=T_(e-o/2,a.x,a.x+a.width-o),l=T_(t-s+C_,a.y,a.y+a.height-s);if(!er(c,l,c+o,l+s))return{x:c,y:l,width:o,height:s};let u=nr(c,c+o,l);return{x:c,y:u+s<=a.y+a.height?u:l,width:o,height:s}}function T_(e,t,n){return Math.max(t,Math.min(e,n))}var E_=500;function D_(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 O_=class extends J{descriptor={type:`text`,name:`Text`,requiredAnchors:1,text:!0,fill:!0};boxes=new xh;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a={...rh(t.style,{box:!1,border:!1,width:1/0}),maxLines:E_},o=hh(e,D_(t),i.x-8,i.y-6,a);this.boxes.set(t.id,o),_h(e,o,t.style.color,r)}handlePoints(){return[]}hitTest(e,t,n,r){if(t.anchors.length<1)return!1;let i=this.anchorToPixel(t.anchors[0],n);return yh(e,this.boxes.get(t.id)??k_(t,i),r)}textBox(e){return this.boxes.get(e.id)??null}};function k_(e,t){let n=Tn(e.style),r=D_(e).split(`
|
|
4
|
+
`),i=Math.max(...r.map(e=>e.length));return{x:t.x-8,y:t.y-6,width:i*n*.6+16,height:r.length*n*1.3+12}}var A_=class extends J{descriptor={type:`arrow`,name:`Arrow`,requiredAnchors:2,text:!0};render(e,t,n,r){if(this.texts.set(t.id,null),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(),Gh(e,i,a,t.style.color,t.style.lineWidth),this.resetLineStyle(e),this.texts.set(t.id,Nh(e,t.style,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n),n.chartRect)),r&&this.renderAnchorHandles(e,t,n)}texts=new Ah;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},j_=[{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}],M_=4,N_=class extends J{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,f=u.y,p=u.y+u.height;e.font=N(`mark`);for(let{label:n,ratio:r}of j_){let a=c*r,o=d,s=i.y+a*(o-i.x);e.globalAlpha=1,r===1?this.applyLineStyle(e,t.style):this.applyGuideStyle(e,t.style.color),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(o,s),e.stroke();let m=Math.max(f,Math.min(p,s)),h=a===0||m===s?o:i.x+(m-i.y)/a;if(h<u.x||h>u.x+u.width)continue;e.globalAlpha=1,e.fillStyle=Mn(t.style.color);let g=m===s;e.textAlign=g?l>0?`right`:`left`:`center`,e.textBaseline=m<=f+1?`top`:`bottom`;let _=g?h-l*M_:h,v=e.measureText(n).width,y=e.textAlign===`right`?_-v:e.textAlign===`left`?_:_-v/2;F(e,n,_,m<=f+1?nr(y,y+v,m)+M_:m-M_)}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 j_){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}},P_=[0,.25,.333,.5,.667,.75,1].filter(e=>e>0&&e<1),F_=.3,I_=4,L_=2,R_=class extends J{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),this.strokeCrispRect(e,o,c,u,d),e.save(),this.applyGuideStyle(e,t.style.color),e.globalAlpha=F_;for(let t of P_)this.strokeHorizontal(e,o,s,c+d*t),e.lineWidth=1,this.strokeVertical(e,o+u*t,c,l),e.lineWidth=1;this.applyGuideStyle(e,t.style.color,!0),e.beginPath(),e.moveTo(o,c),e.lineTo(s,l),e.moveTo(s,c),e.lineTo(o,l),e.stroke(),e.restore(),this.resetLineStyle(e),this.renderLabels(e,t,{left:o,right:s,top:c,bottom:l,w:u,h:d}),r&&this.renderAnchorHandles(e,t,n)}}renderLabels(e,t,n){let r=M().sizes.mark;e.font=N(`mark`),e.fillStyle=Mn(t.style.color);let i=[...P_].sort((e,t)=>Math.abs(e-.5)-Math.abs(t-.5)),a=[],o=e=>a.every(t=>e.x1+L_<=t.x0||t.x1+L_<=e.x0||e.y1+L_<=t.y0||t.y1+L_<=e.y0);for(let t of i){let i=`${Math.round(t*100)}%`,s=e.measureText(i).width,c=n.top+n.h*t,l={x0:n.left-I_-s,x1:n.left-I_,y0:c-r/2,y1:c+r/2};o(l)&&(a.push(l),e.textAlign=`right`,e.textBaseline=`middle`,F(e,i,l.x1,c));let u=n.left+n.w*t,d={x0:u-s/2,x1:u+s/2,y0:n.bottom+I_,y1:n.bottom+I_+r};o(d)&&(a.push(d),e.textAlign=`center`,e.textBaseline=`top`,F(e,i,u,d.y0))}}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}},z_=6,B_=class extends J{descriptor={type:`anchoredVWAP`,name:`Anchored VWAP`,requiredAnchors:1,priceOnly:!0};dataGetter=null;dataRevision=()=>0;showBands=!0;setDataGetter(e,t=()=>0){this.dataGetter=e,this.dataRevision=t}setShowBands(e){this.showBands=e}handlePoints(t,n){let r=this.dataGetter?.(),i=Math.max(0,Math.round(e.j(t.anchors[0]?.time??0,n)));if(!r||t.anchors.length<1||i>=r.length)return super.handlePoints(t,n);let a=r[i],o=(a.high+a.low+a.close)/3;return[{x:e.w(i,n),y:e.k(o,n)}]}render(t,n,r,i){if(n.anchors.length<1||!this.dataGetter)return;let a=this.dataGetter(),o=Math.max(0,Math.round(e.j(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.w(o+s.length-1,r),c=e.k(i,r);if(a>=f.x&&a<=f.x+f.width){t.fillStyle=n.style.color,t.font=N(`mark`,{weight:600}),t.textBaseline=`middle`;let e=`AVWAP ${wr(i,i,r)}`,o=Cn(a+z_,c,t.measureText(e).width,0);t.textAlign=`left`,F(t,e,o.left,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.w(r+c,i);if(l<a.x-o)continue;if(l>a.x+a.width+o)break;let u=e.k(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.dataRevision(),i=this.vwapCache;if(i&&i.data===e&&i.revision===r&&i.length===e.length&&i.startIdx===t&&i.lastClose===n?.close&&i.lastVolume===(n?.volume??0))return i.result;let a=this.computeVWAPUncached(e,t);return this.vwapCache={data:e,revision:r,length:e.length,startIdx:t,lastClose:n?.close,lastVolume:n?.volume??0,result:a},a}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.j(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.w(o+n-1,r),c=e.k(s[n-1],r),l=e.w(o+n,r),u=e.k(s[n],r);if(this.distanceToLine(t,{x:a,y:c},{x:l,y:u})<=i)return!0}return!1}},V_=`#f2a93b`,H_=40,U_=1/3,W_=.7,G_=.45,K_=.2,q_=.5,J_=.5,Y_=class extends J{descriptor={type:`volumeProfileRange`,name:`Volume Profile (Range)`,requiredAnchors:2,fill:!0,priceOnly:!0};dataGetter=null;dataRevision=()=>0;cached=null;setDataGetter(e,t=()=>0){this.dataGetter=e,this.dataRevision=t,this.cached=null}profile(t,n){if(t.anchors.length<2||!this.dataGetter)return null;let r=this.dataGetter(),i=Math.round(e.j(t.anchors[0].time,n)),a=Math.round(e.j(t.anchors[1].time,n)),o=Math.max(0,Math.min(i,a)),s=Math.min(r.length-1,Math.max(i,a));if(o>=r.length||s<0||o>s)return null;let c=this.dataRevision(),l=this.cached,u=l&&l.data===r&&l.length===r.length&&l.revision===c&&l.start===o&&l.end===s?l.rows:this.rowsOf(r,o,s);return this.cached={data:r,length:r.length,revision:c,start:o,end:s,rows:u},u?{startX:e.w(o,n),endX:e.w(s,n),left:e.w(o,n)-n.barWidth/2,right:e.w(s,n)+n.barWidth/2,top:e.k(u.pMax,n),bottom:e.k(u.pMin,n),pMin:u.pMin,binSize:u.binSize,bins:u.bins,maxBin:u.maxBin,poc:u.poc,valueLow:u.valueLow,valueHigh:u.valueHigh}:null}rowsOf(e,t,n){let r=1/0,i=-1/0;for(let a=t;a<=n;a++)e[a].low<r&&(r=e[a].low),e[a].high>i&&(i=e[a].high);if(!(r<i))return null;let a=(i-r)/H_,o=new Float64Array(H_);for(let i=t;i<=n;i++){let t=e[i],n=Math.max(0,Math.floor((t.low-r)/a)),s=Math.min(H_-1,Math.floor((t.high-r)/a)),c=(t.volume??1)/(s-n+1);for(let e=n;e<=s;e++)o[e]+=c}let s=0,c=0;for(let e=0;e<H_;e++)c+=o[e],o[e]>o[s]&&(s=e);if(o[s]===0)return null;let l=s,u=s,d=o[s];for(;d<c*W_&&(l>0||u<H_-1);){let e=l>0?o[l-1]:-1;(u<H_-1?o[u+1]:-1)>=e?d+=o[++u]:d+=o[--l]}return{start:t,end:n,pMin:r,pMax:i,binSize:a,bins:o,maxBin:o[s],poc:s,valueLow:l,valueHigh:u}}handlePoints(e,t){let n=this.profile(e,t);if(!n)return super.handlePoints(e,t);let r=e.anchors[0].time<=e.anchors[1].time;return[{x:r?n.startX:n.endX,y:n.top},{x:r?n.endX:n.startX,y:n.bottom}]}render(t,n,r,i){let a=this.profile(n,r);if(!a)return;let o=n.style.color,s=Rn(n.style)?n.style.fillColor:V_,c=Math.max(1,(a.right-a.left)*U_);t.save();for(let n=0;n<H_;n++){let i=e.k(a.pMin+(n+1)*a.binSize,r),l=e.k(a.pMin+n*a.binSize,r);t.globalAlpha=n>=a.valueLow&&n<=a.valueHigh?G_:K_,t.fillStyle=n===a.poc?s:o,t.fillRect(a.left,Math.min(i,l),a.bins[n]/a.maxBin*c,Math.max(1,Math.abs(l-i)-J_))}t.restore(),t.save(),this.applyGuideStyle(t,o),t.globalAlpha=q_,this.strokeCrispRect(t,a.left,a.top,a.right-a.left,a.bottom-a.top),t.restore();let l=a.pMin+(a.poc+.5)*a.binSize,u=e.k(l,r);t.save(),t.strokeStyle=s,t.lineWidth=1,t.setLineDash(Ln(`dashed`,1)),this.strokeHorizontal(t,a.left,a.right,u),t.setLineDash([]),t.fillStyle=Mn(s),t.font=N(`mark`),t.textAlign=`left`,t.textBaseline=`bottom`;let d=`POC ${wr(l,l,r)}`;F(t,d,Cn(a.right+4,u-2,t.measureText(d).width,0).left,u-2),t.restore(),i&&this.renderAnchorHandles(t,n,r)}hitTest(e,t,n,r){let i=this.profile(t,n);return i?e.x>=i.left-r&&e.x<=i.right+r&&e.y>=i.top-r&&e.y<=i.bottom+r:!1}},X_=[1,2,3,5,8,13,21,34,55],Z_=.6,Q_=4,$_=class extends J{descriptor={type:`fibTimeZones`,name:`Fibonacci Time Zones`,requiredAnchors:2,options:{levels:{kind:`levels`,label:`Levels`,default:Qm([0,...X_],[89,144])}}};handlePoints(e,t){return this.timeHandles(e,t)}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=N(`label`),t.textBaseline=`top`,t.textAlign=`center`;let c=M().sizes.label,l=[];for(let{value:i,color:u}of this.visibleLevels(n)){this.applyLineStyle(t,{...n.style,color:u??n.style.color});let d=e.M(a.time+o*i,r);if(d<s.x||d>s.x+s.width)continue;t.globalAlpha=i===0||i===1?1:Z_,this.strokeVertical(t,d,s.y,s.y+s.height),t.globalAlpha=1;let f=String(i),p=t.measureText(f).width/2,m=nr(d-p,d+p,s.y)+Q_,h={left:d-p,right:d+p,top:m,bottom:m+c};Nr([h],l)&&(l.push(h),t.fillStyle=Mn(u??n.style.color),F(t,f,d,m))}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.M(a.time+o*s,r);if(Math.abs(t.x-n)<=i)return!0}return!1}},ev=.14,tv=.6,nv=40,rv=2,iv=.1,av=100,ov=0x38d7ea4c68000,sv=2,cv=2,lv=4,uv=6,dv=class extends J{descriptor={type:`riskReward`,name:`Long/Short Position`,priceOnly:!0,requiredAnchors:2,options:{rewardRatio:{kind:`number`,label:`Reward:risk`,default:2,min:iv,max:av,step:.1},accountSize:{kind:`number`,label:`Account size`,default:1e3,min:0,max:ov},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:ov},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),nv),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),d=M();e.fillStyle=(0,t.withAlpha)(d.fall,ev),e.fillRect(o,Math.min(c.y,l.y),s,Math.abs(l.y-c.y)),e.fillStyle=(0,t.withAlpha)(d.rise,ev),e.fillRect(o,Math.min(c.y,u.y),s,Math.abs(u.y-c.y)),e.save();for(let[t,n]of[[l.y,d.fall],[u.y,d.rise]])this.applyGuideStyle(e,n),e.globalAlpha=tv,this.strokeHorizontal(e,o,o+s,t);e.restore(),this.applyLineStyle(e,n.style),e.setLineDash([]),this.strokeHorizontal(e,o,o+s,c.y),this.resetLineStyle(e);let{chartRect:f}=r,p=f.x,m=f.x+f.width;if(this.option(n,`showLabels`)&&o+s>=p&&o<=m){let i=r.pricePrecision??(0,t.autoPricePrecision)(Math.min(a.stop,a.target),Math.max(a.stop,a.target)),s=r.numberLocale??`en-US`,h=this.option(n,`qtyDecimals`),g=e=>a.entry===0?0:(e-a.entry)/a.entry*100,_=a.ratio.toLocaleString(s,{maximumFractionDigits:cv});e.font=N(`label`);let v=e=>(0,t.priceTagText)(e,r,i),y=e=>(0,t.formatPrice)(e,sv,s),b=e=>`${e>=a.entry?`+`:`−`}${Tr(Math.abs(g(e)),r)}%`,x=sr()+2,S=sr()/2,C=e=>{let t=e<c.y,n=e+(t?-1:1)*(S+2),r=t?Math.min(n,c.y-x):Math.max(n,c.y+x);return Math.min(Math.max(r,f.y+S),f.y+f.height-S)},w=({text:t,y:n,start:r})=>{let i=dr(e,t),a=Math.max(p+4,Math.min(Math.max(o+4,r??-1/0),m-4-i)),s=n-S;if(tr(a,s,a+i,s+sr())){let e=(rr(s,s+sr())??a)+lv;e+i<=m-4&&!tr(e,s,e+i,s+sr())?a=e:s=nr(a,a+i,s)+2}return Qn(a,s,a+i,s+sr()),{left:a,top:s}},T=[{text:`${a.isLong?`Long`:`Short`} · Qty ${(0,t.formatPrice)(a.qty,h,s)} · R:R ${_}`,y:c.y,color:n.style.color,start:c.x+Nn(n.style.lineWidth)+uv}];Math.abs(l.y-c.y)>=1&&T.push({text:`Target ${v(a.target)} (${b(a.target)}) · ${y(a.rewardAmount)}`,y:C(u.y),color:d.rise},{text:`Stop ${v(a.stop)} (${b(a.stop)}) · ${y(a.riskAmount)}`,y:C(l.y),color:d.fall});let E=new Map([...T].sort((e,t)=>e.y-t.y).map(e=>[e,w(e)]));for(let t of T){let n=E.get(t);fr(e,t.text,n.left,n.top+S,t.color)}}i&&this.renderHandles(e,n,r)}renderHandles(e,t,n){jp(e,t,this.handles(t,n))}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!==rv){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(av,Math.max(iv,o/a)):iv;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}},fv=class extends J{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 pv(e,t,n){let r=Ar(e,0,1,t),i=kr(e,0,1,t);return[Er(e.anchors[0].price,e.anchors[1].price,t),r?`${i} bars, ${r}`:`${i} bars`,`${n.toFixed(1)}°`]}var mv=class extends J{descriptor={type:`infoLine`,name:`Info Line`,requiredAnchors:2,text:!0};render(e,t,n,r){if(this.texts.set(t.id,null),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=pv(t,n,Lh(i,a)),s=a.y<=i.y;jr(e,o,a.x+(a.x>=i.x?8:-8),a.y+(s?-6:6),a.x>=i.x?`left`:`right`,s),this.texts.set(t.id,Nh(e,t.style,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n),n.chartRect)),r&&this.renderAnchorHandles(e,t,n)}texts=new Ah;textBox(e){return this.texts.bounds(e.id)}hitTest(e,t,n,r){return this.texts.hit(t.id,e,r)||this.hitShape(e,t,n,r)}hitShape(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}},hv=.7,gv=10,_v=[0,.236,.382,.5,.618,.786,1,1.618];function vv(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 yv(e,t,n,r){let i=vv(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 bv=class extends J{descriptor={type:`fibChannel`,name:`Fibonacci Channel`,requiredAnchors:3,options:{levels:{kind:`levels`,label:`Levels`,default:Zm(_v,[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=N(`label`),e.textAlign=`right`,e.textBaseline=`middle`;let s=this.visibleLevels(t);for(let{value:n,color:r}of s){let[s,c]=yv(i,a,o,n);this.applyLineStyle(e,{...t.style,color:r??t.style.color}),e.globalAlpha=n===0||n===1?1:hv,e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(c.x,c.y),e.stroke()}e.globalAlpha=1;let c=M().sizes.label,l=[],u=e=>e===0||e===1;for(let{value:n,color:r}of[...s].sort((e,t)=>Number(u(t.value))-Number(u(e.value)))){let[s,d]=yv(i,a,o,n),f=s.x<=d.x?s:d,p=String(n),m=e.measureText(p).width,h={left:f.x-gv-m,right:f.x-gv,top:f.y-c/2,bottom:f.y+c/2};!Nr([h],l)&&!u(n)||(l.push(h),e.fillStyle=Mn(r??t.style.color),F(e,p,h.right,f.y))}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]=yv(i,a,o,n);if(this.distanceToLine(e,t,s)<=r)return!0}return!1}},xv=.4,Sv=.8,Cv=4,wv=[.25,.382,.5,.618,.75];function Tv(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 Ev(e,t,n=wv){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 Dv=class extends J{descriptor={type:`fibSpeedResistanceFan`,name:`Fib Speed Resistance Fan`,requiredAnchors:2,options:{levels:{kind:`levels`,label:`Levels`,default:Zm(wv,[.236,.786])}}};targets(e,t,n){return Ev(t,n,this.visibleLevels(e).map(e=>e.value))}colorOf(e,t){return this.visibleLevels(e).find(e=>e.value===t)?.color??e.style.color}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.save(),this.applyGuideStyle(e,t.style.color),e.globalAlpha=xv,this.strokeCrispRect(e,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.restore(),e.font=N(`label`);let o=a.x>=i.x,s=a.y>=i.y;for(let r of this.targets(t,i,a)){let a=Tv(i,r.point,n);if(!a)continue;let c=r.kind===`diagonal`?t.style.color:this.colorOf(t,r.level);this.applyLineStyle(e,{...t.style,color:c,lineStyle:r.kind===`time`?`dashed`:t.style.lineStyle}),e.globalAlpha=r.kind===`diagonal`?1:Sv,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),r.kind!==`diagonal`&&(e.globalAlpha=1,e.fillStyle=Mn(c),r.kind===`price`?(e.textAlign=o?`left`:`right`,e.textBaseline=`middle`,F(e,String(r.level),r.point.x+(o?Cv:-Cv),r.point.y)):(e.textAlign=`center`,e.textBaseline=s?`top`:`bottom`,F(e,String(r.level),r.point.x,r.point.y+(s?Cv:-Cv))))}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=Tv(i,o.point,n);if(t&&this.distanceToLine(e,i,t)<=r)return!0}return!1}},Ov=class extends J{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.renderGuides(e,t,i),this.renderExtras(e,t,i,n);let a=this.renderPointLabels(e,t,i);this.renderRatios(e,t,i,[...t_(i,t.style.lineWidth),...a]),r&&this.renderAnchorHandles(e,t,n)}renderExtras(e,t,n,r){}pointFont(){return{font:N(`letter`,{weight:600}),height:M().sizes.letter}}renderTriangles(e,t,n){e.fillStyle=P(t.style);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()}linksIn(e){return this.ratioLinks.filter(t=>Math.max(t.from,t.to,...t.num,...t.den)<e.length)}renderGuides(e,t,n){e.save(),this.applyGuideStyle(e,t.style.color,!0);for(let t of this.linksIn(n))e.beginPath(),e.moveTo(n[t.from].x,n[t.from].y),e.lineTo(n[t.to].x,n[t.to].y),e.stroke();e.restore()}renderRatios(e,t,n,r){let i=[...r];e.fillStyle=Mn(t.style.color);for(let r of this.linksIn(n)){let a=n_(e,Pr(t,r.num,r.den),n[r.from],n[r.to],i);a&&i.push(a)}}renderPointLabels(e,t,n){let{font:r,height:i}=this.pointFont();return e.font=r,Qg(e,t,n,this.pointLabels.map(e=>typeof e==`string`?{text:e}:e),i)}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}},kv=class extends Ov{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]]},Av=class extends Ov{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]}]},jv=class extends Ov{descriptor={type:`headAndShoulders`,name:`Head and Shoulders`,requiredAnchors:7,fill:!0};pointLabels=[{text:``},{text:`Left Shoulder`,short:`LS`},{text:``},{text:`Head`,short:`H`,first:!0},{text:``},{text:`Right Shoulder`,short:`RS`},{text:``}];pointFont(){return{font:N(`label`,{weight:600,prose:!0}),height:M().sizes.label}}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([])}},Mv=class extends Ov{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]}]},Nv=class extends Ov{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]]},Pv=class extends J{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=P(t.style),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}},Fv=.5;function Iv(t,n){let r=n.data;if(!r||r.length===0)return null;let i=Math.round(e.j(t.anchors[0].time,n)),a=Math.round(e.j(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 Lv(e,n){let r=Ar(e,0,1,n),i=kr(e,0,1,n),a=[Er(e.anchors[0].price,e.anchors[1].price,n),r?`${i} bars · ${r}`:`${i} bars`],o=Iv(e,n);return o!==null&&a.push(`Vol ${(0,t.formatVolumeLoc)(o,n.numberLocale??`en-US`)}`),a}var Rv=class extends J{descriptor={type:`dateAndPriceRange`,name:`Date and Price Range`,requiredAnchors:2};render(e,n,r,i){if(n.anchors.length<2)return;let a=this.anchorToPixel(n.anchors[0],r),o=this.anchorToPixel(n.anchors[1],r),s=Math.min(a.x,o.x),c=Math.min(a.y,o.y),l=Math.abs(o.x-a.x),u=Math.abs(o.y-a.y),d=n.anchors[1].price>=n.anchors[0].price,f=M(),p=d?n.style.color:f.fall;e.fillStyle=d?P(n.style):(0,t.withAlpha)(f.fall,cn),e.fillRect(s,c,l,u),e.save(),this.applyGuideStyle(e,p),e.globalAlpha=Fv,this.strokeCrispRect(e,s,c,l,u),e.restore(),this.applyLineStyle(e,{...n.style,color:p});let m=s+l/2,h=c+u/2;e.beginPath(),e.moveTo(m,a.y),e.lineTo(m,o.y),e.moveTo(a.x,h),e.lineTo(o.x,h),e.stroke(),this.resetLineStyle(e),qh(e,{x:m,y:a.y},{x:m,y:o.y},p,n.style.lineWidth),qh(e,{x:a.x,y:h},{x:o.x,y:h},p,n.style.lineWidth),jr(e,Lv(n,r),m,d?c-6:c+u+6,`center`,d),i&&this.renderAnchorHandles(e,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 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}},zv=400,Bv=2;function Vv(e,t,n){let r=Math.abs(t.x-e.x);if(r<Bv)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<zv;e+=r)a.push(e);return a}var Hv=class extends J{descriptor={type:`cyclicLines`,name:`Cyclic Lines`,requiredAnchors:2};handlePoints(e,t){return this.timeHandles(e,t)}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);for(let r of Vv(i,a,n))r<o.x||(this.strokeVertical(e,r,o.y,o.y+o.height),e.lineWidth=t.style.lineWidth);this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:Vv(this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n),n).some(t=>Math.abs(e.x-t)<=r)}},Uv=240;function Wv(e){return Tn(e.style)}function Gv(e){return rh(e.style,{box:!0,border:!0,width:Uv,fill:!0})}function Kv(e,t,n,r){let i=Wv(e),a=Math.max(...t.split(`
|
|
5
|
+
`).map(e=>e.length));return{x:n,y:r,width:Math.min(Uv,a*i*.6)+16,height:i*1.3+12}}var qv=7,Jv=16,Yv=class extends J{descriptor={type:`note`,name:`Note`,requiredAnchors:1,text:!0,fill:!0,options:{showText:{kind:`boolean`,label:`Show text`,default:!0}}};boxes=new xh;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=hh(e,D_(t,`Note`),i.x+qv+6,i.y-Jv-qv,Gv(t));this.boxes.set(t.id,n)}r&&this.renderAnchorHandles(e,t,n)}renderPin(e,t,n){let r=n.y-Jv;e.fillStyle=t.style.color,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-qv*.7,r+qv*.5),e.arc(n.x,r,qv,Math.PI*.8,Math.PI*.2),e.closePath(),e.fill(),e.fillStyle=M().background,e.beginPath(),e.arc(n.x,r,qv*.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 yh(e,{x:i.x-qv,y:i.y-Jv-qv,width:qv*2,height:Jv+qv},r)?!0:this.option(t,`showText`)?yh(e,this.boxes.get(t.id)??Kv(t,D_(t,`Note`),i.x+qv+6,i.y-Jv-qv),r):!1}textBox(e){return this.option(e,`showText`)?this.boxes.get(e.id)??null:null}},Xv=class extends J{descriptor={type:`callout`,name:`Callout`,requiredAnchors:2,text:!0,fill:!0};boxes=new xh;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=D_(t,`Callout`),s=Gv(t),c=Zv(a,mh(e,o,s),n),l=hh(e,o,c.left,c.top,s);this.boxes.set(t.id,l);let u=Qv(l,i);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(u.x,u.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)??Kv(t,D_(t,`Callout`),a.x,a.y);return yh(e,o,r)||this.distanceToLine(e,Qv(o,i),i)<=r}textBox(e){return this.boxes.get(e.id)??null}handlePoints(e,t){let n=super.handlePoints(e,t),r=this.boxes.get(e.id);return r&&n.length>1?[n[0],{x:r.x,y:r.y}]:n}};function Zv(e,t,n){let r=n.chartRect;return e.x>=r.x&&e.x<=r.x+r.width&&e.y>=r.y&&e.y<=r.y+r.height?Cn(e.x,e.y,t.width,t.height):{left:e.x,top:e.y}}function Qv(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 $v=24,ey=18,ty=10,ny=class extends J{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-$v;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+ey,a),e.lineTo(i.x+ey-5,a+ty/2),e.lineTo(i.x+ey,a+ty),e.lineTo(i.x,a+ty),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 yh(e,{x:i.x,y:i.y-$v,width:ey,height:$v},r)}},ry={up:{x:0,y:-1},down:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0}};function iy(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 ay=class extends J{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=ry[this.option(e,`direction`)]??ry.up,i=this.option(e,`size`);return{points:iy(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=sh(Tn(t.style,`label`),t.style.bold,t.style.italic),e.fillStyle=t.style.textColor??t.style.color,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)),_h(e,vh(i),t.style.color,r)}handlePoints(){return[]}hitTest(e,t,n,r){return t.anchors.length<1?!1:yh(e,vh(this.outline(t,n).points),r)}},oy=[`star`,`heart`,`check`,`cross`,`circle`,`triangleUp`,`triangleDown`,`bolt`];function sy(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 cy=class extends J{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`);sy(e,oy.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()),_h(e,{x:i.x-a/2,y:i.y-a/2,width:a,height:a},t.style.color,r)}handlePoints(){return[]}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}},ly=200,uy=36,dy=.4,fy=8,py=.6;function my(e){let t=Math.max(fy,Math.round(e*dy));return{length:t,half:Math.round(t*py)}}function hy(e,t,n){return(r,i,a,o,s,c)=>{let l=i+o,u=a+s,d=i+c+t,f=l-c-t,p=d<=f?Math.max(d,Math.min(e.x,f)):(i+l)/2,m=(t,n,i)=>{r.lineTo(p+n,t),r.lineTo(e.x,e.y),r.lineTo(p+i,t)};r.moveTo(i+c,a),n&&m(a,-t,t),r.arcTo(l,a,l,u,c),r.arcTo(l,u,i,u,c),n||m(u,t,-t),r.arcTo(i,u,i,a,c),r.arcTo(i,a,l,a,c),r.closePath()}}function gy(e){return rh(e.style,{box:!0,border:!0,width:ly,fill:!0})}function _y(e,t,n,r){let i=r.chartRect,a=e.y-n-t.height<i.y,o=Math.max(i.x,e.x-t.width),s=Math.min(i.x+i.width-t.width,e.x),c=e.x-t.width/2;return{x:o<=s?Math.max(o,Math.min(c,s)):c,y:a?e.y+n:e.y-n-t.height,...t,below:a}}function vy(e,t){let n=Tn(e.style),r=t.split(`
|
|
6
|
+
`),i=Math.max(...r.map(e=>e.length));return{width:Math.min(ly,i*n*.6)+16,height:r.length*n*1.3+12}}var yy=class extends J{descriptor={type:`signpost`,name:`Signpost`,requiredAnchors:1,text:!0,fill:!0};boxes=new xh;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=D_(t,`Signpost`),o=gy(t),s=_y(i,mh(e,a,o),uy,n);this.applyLineStyle(e,{...t.style,lineStyle:`solid`}),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x,s.below?i.y+uy:i.y-uy),e.stroke(),this.resetLineStyle(e),this.boxes.set(t.id,hh(e,a,s.x,s.y,o)),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.boxes.get(t.id)??_y(i,vy(t,D_(t,`Signpost`)),uy,n),[o,s]=a.y>i.y?[i.y,i.y+uy]:[i.y-uy,i.y];return Math.abs(e.x-i.x)<=r&&e.y>=o-r&&e.y<=s+r?!0:yh(e,a,r)}textBox(e){return this.boxes.get(e.id)??null}},by=class extends J{descriptor={type:`balloon`,name:`Balloon`,requiredAnchors:1,text:!0,fill:!0};boxes=new xh;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=D_(t,`Comment`),o=gy(t),s=mh(e,a,o),c=my(s.height),l=_y(i,s,c.length,n),u={...o,traceBox:hy(i,c.half,l.below)};this.boxes.set(t.id,hh(e,a,l.x,l.y,u)),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=vy(t,D_(t,`Comment`)),o=this.boxes.get(t.id)??_y(i,a,my(a.height).length,n),s=my(o.height),[c,l]=o.y>i.y?[i.y,i.y+s.length]:[i.y-s.length,i.y];return Math.abs(e.x-i.x)<=s.half+r&&e.y>=c-r&&e.y<=l+r?!0:yh(e,o,r)}textBox(e){return this.boxes.get(e.id)??null}},xy=class extends O_{descriptor={type:`anchoredText`,name:`Anchored Text`,requiredAnchors:1,text:!0,fill:!0,anchoring:`screen`}},Sy=class extends Yv{descriptor={type:`anchoredNote`,name:`Anchored Note`,requiredAnchors:1,text:!0,fill:!0,anchoring:`screen`,options:{showText:{kind:`boolean`,label:`Show text`,default:!0}}}},Cy=14,wy=18,Ty=8,Ey=5,Dy=1.35,Oy=3,ky=3;function Ay(e){return Math.round(e*Dy)+Ey*2}var jy=class extends J{drawn=new xh;descriptor={type:`priceLabel`,name:`Price Label`,requiredAnchors:1,text:!0};text(e,t){return e.style.text||wr(e.anchors[0].price,e.anchors[0].price,t)}box(e,t,n,r){let i=Tn(t.style,`label`),a=this.text(t,r),o=e?e.measureText(a).width:a.length*i*.6,s=Ay(i);return{x:n.x+Cy,y:n.y-wy-s/2,w:Math.ceil(o)+Ty*2,h:s}}render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n);e.font=sh(Tn(t.style,`label`),t.style.bold,t.style.italic);let a=this.box(e,t,i,n);this.drawn.set(t.id,{x:a.x,y:a.y,width:a.w,height:a.h}),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(),this.fillBox(e,a,t.style.color),e.fillStyle=t.style.textColor??zn(t.style.color),e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(this.text(t,n),a.x+Ty,a.y+a.h/2),e.beginPath(),e.arc(i.x,i.y,ky,0,Math.PI*2),e.fillStyle=t.style.color,e.fill(),r&&this.renderAnchorHandles(e,t,n)}fillBox(e,t,n){let r=Math.round(t.x),i=Math.round(t.y);e.fillStyle=n,e.beginPath(),typeof e.roundRect==`function`?e.roundRect(r,i,Math.round(t.w),Math.round(t.h),Oy):e.rect(r,i,Math.round(t.w),Math.round(t.h)),e.fill()}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.drawn.get(t.id),o=a?{...this.box(null,t,i,n),w:a.width}:this.box(null,t,i,n);return e.x>=o.x-r&&e.x<=o.x+o.w+r&&e.y>=o.y-r&&e.y<=o.y+o.h+r}},My=48;function Ny(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 Py(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 Fy(e,t,n,r=En(Number(e.lineWidth)||1)){let i=Math.atan2(n.y-t.y,n.x-t.x);e.save(),e.setLineDash([]),e.lineJoin=`round`,e.lineCap=`round`,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(),e.restore()}function Iy(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 Ly=new WeakMap;function Ry(e){let t=Ly.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);Ly.set(e,t)}return t}var zy=class extends J{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,Ny(e,i),e.globalAlpha=1,e.lineCap=`butt`,e.lineJoin=`miter`,this.resetLineStyle(e),this.renderBounds(e,t,n,r)}renderBounds(e,t,n,r){let i=this.screenBox(t,n),a=this.stroke(t).width/2;_h(e,{x:i.x0-a,y:i.y0-a,width:i.x1-i.x0+a*2,height:i.y1-i.y0+a*2},t.style.color,r)}screenBox(t,n){let{t0:r,t1:i,p0:a,p1:o}=Ry(t.anchors),s=e.k(a,n),c=e.k(o,n);return{x0:e.M(r,n),x1:e.M(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:Up(e,t.anchors.map(e=>this.anchorToPixel(e,n)),i)}},By=class extends zy{descriptor={type:`highlighter`,name:`Highlighter`,requiredAnchors:2,creation:`freehand`};stroke(e){return{width:Math.max(10,e.style.lineWidth*8),alpha:.3}}},Vy=class extends J{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`,Py(e,i),e.stroke(),this.resetLineStyle(e),this.option(t,`arrowEnd`)&&Fy(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:Up(e,t.anchors.map(e=>this.anchorToPixel(e,n)),r)}},Hy=class extends J{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;Py(e,i,a),a&&(e.fillStyle=P(t.style),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 Up(e,i,r,!0)||i.length>=3&&Iy(e,i)}};function Uy(e,t,n,r=My){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 Wy(e,t,n,r=My){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 Gy=class extends J{descriptor={type:`curve`,name:`Curve`,requiredAnchors:3};shape(e,t,n){return Uy(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),Py(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:Up(e,this.points(t,n),r)}},Ky=class extends Gy{descriptor={type:`arc`,name:`Arc`,requiredAnchors:3};shape(e,t,n){return Wy(e,t,n)}},qy=(1+Math.sqrt(5))/2,Jy=64,Yy=2,Xy=6,Zy=-Math.PI/4,Qy=.7,$y=.3,eb=.7,tb=8;function nb(e,t=[]){return{levels:{kind:`levels`,label:`Levels`,default:Zm(e,t)},showLevels:{kind:`boolean`,label:`Show levels`,default:!0}}}var rb=[.236,.382,.5,.618,.786,1];function ib(e){return String(Number(e.toFixed(3)))}function ab(e,t,n,r,i,a=Jy){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 ob(e,t){e.beginPath(),t.forEach((t,n)=>n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)),e.stroke()}function sb(e,t){let n=Math.hypot(t.x-e.x,t.y-e.y)||1;return{x:-(t.y-e.y)/n,y:(t.x-e.x)/n}}var cb=class extends J{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.applyGuideStyle(e,t.style.color,!0),e.globalAlpha=Qy;for(let[t,n]of this.guides(i))ob(e,[t,n]);e.globalAlpha=1,this.applyLineStyle(e,t.style);let a=this.option(t,`showLevels`);e.font=N(`label`),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,ob(e,n.points);a&&this.renderLabels(e,t,o),this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}renderLabels(e,t,n){let r=M().sizes.label,i=[],a=[...n].reverse().sort((e,t)=>Number(t.level.value===1)-Number(e.level.value===1));for(let{level:n,label:o,away:s}of a){let a=ib(n.value),c=e.measureText(a).width,l=s??{x:0,y:-1},u=o.x+l.x*Xy,d=o.y+l.y*Xy,f=l.x<-.3?u-c:l.x>.3?u:u-c/2,p=l.y<-.3?d-r:l.y>.3?d:d-r/2,m={x0:f,x1:f+c,y0:p,y1:p+r};i.some(e=>m.x1+Yy>e.x0&&e.x1+Yy>m.x0&&m.y1+Yy>e.y0&&e.y1+Yy>m.y0)||(i.push(m),e.fillStyle=Mn(n.color??t.style.color),e.textAlign=`left`,e.textBaseline=`top`,F(e,a,m.x0,m.y0))}}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])=>Hp(e,t,n)<=r)?!0:this.shapes(i,this.visibleLevels(t),n,t).some(t=>Up(e,t.points,r))}},lb=class extends cb{descriptor={type:`fibCircles`,name:`Fib Circles`,requiredAnchors:2,options:nb([...rb,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,r={x:n.x+t*Math.cos(Zy),y:n.y+t*Math.sin(Zy)};return{level:e,points:ab(n,t,t,0,Math.PI*2),label:r,away:{x:Math.SQRT1_2,y:-Math.SQRT1_2}}})}},ub=class extends cb{descriptor={type:`fibArcs`,name:`Fib Speed Resistance Arcs`,requiredAnchors:2,options:{...nb(rb),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?ab(i,t,t,0,Math.PI*2):ab(i,t,t,s-Math.PI/2,Math.PI),label:{x:i.x+t*Math.cos(s),y:i.y+t*Math.sin(s)},away:sb(i,a)}})}},db=class extends cb{descriptor={type:`fibWedge`,name:`Fib Wedge`,requiredAnchors:3,options:nb(rb)};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,i=sb(n,r),c=s>0?-1:1;return{level:e,points:ab(n,t,t,o,s,32),label:{x:n.x+t*Math.cos(o),y:n.y+t*Math.sin(o)},away:{x:i.x*c,y:i.y*c}}})}},fb=class extends cb{descriptor={type:`pitchfan`,name:`Pitchfan`,requiredAnchors:3,options:nb([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,away:sb(r,t)}})}},pb=class extends J{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(qy),u=Math.log(i/tb)/Math.log(qy),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*qy**+(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),ob(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:Up(e,this.points(t,n),r)}},mb=class extends J{descriptor={type:`gannSquare`,name:`Gann Square`,requiredAnchors:2,options:{...nb([.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 ab(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.slice(0,6).forEach(([n,r])=>this.strokeSegment(e,n,r,t.style.lineWidth)),this.applyGuideStyle(e,t.style.color),e.globalAlpha=$y,i.slice(6).forEach(([t,n])=>this.strokeSegment(e,t,n,1));let o=this.visibleLevels(t);a.forEach((n,r)=>{this.applyLineStyle(e,{...t.style,color:o[r]?.color??t.style.color}),e.globalAlpha=eb,ob(e,n)}),e.globalAlpha=1,this.resetLineStyle(e),r&&this.renderAnchorHandles(e,t,n)}strokeSegment(e,t,n,r){e.lineWidth=r,Math.abs(t.y-n.y)<.5?this.strokeHorizontal(e,t.x,n.x,t.y):Math.abs(t.x-n.x)<.5?this.strokeVertical(e,t.x,t.y,n.y):ob(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])=>Hp(e,t,n)<=r)}},hb=400,gb=32,_b=3,vb=class extends J{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<hb;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<=gb;i++){let a=Math.PI+Math.PI*i/gb;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=P(t.style),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)}},yb=class extends J{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+=_b)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:Up(e,this.points(t,n),r)}},bb=5,xb=.85,Sb=.08,Cb=500;function wb(t,n,r){let i=r.price>=n.price,a=t.length>0?Math.max(0,Math.floor(e.N(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 Tb=class extends J{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=wb(this.bars(),i,a),l=M(),u=c===`reached`?l.rise:c===`missed`?l.fall:t.style.color,d=Math.hypot(s.x-o.x,s.y-o.y),f=d>bb?{x:s.x-(s.x-o.x)/d*bb,y:s.y-(s.y-o.y)/d*bb}:s;this.applyLineStyle(e,{...t.style,color:u}),e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(f.x,f.y),e.stroke(),this.resetLineStyle(e),e.strokeStyle=u,e.lineWidth=Math.max(1,t.style.lineWidth),e.beginPath(),e.arc(s.x,s.y,bb,0,Math.PI*2),e.stroke();let p=Ar(t,0,1,n);jr(e,[Er(i.price,a.price,n),`${wr(a.price,i.price,n)} · ${kr(t,0,1,n)} bars${p?` · ${p}`:``}`,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:Hp(e,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n))<=r}},Eb=class extends J{descriptor={type:`projection`,name:`Projection`,requiredAnchors:3,fill:!0};target(t,n){let[r,i,a]=t.anchors,o=e.j(i.time,n)-e.j(r.time,n);return{x:e.w(e.j(a.time,n)+o,n),y:e.k(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=P(t.style),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(),Fy(e,r,a);let[o,s,c]=t.anchors,l=c.price+(s.price-o.price);jr(e,[wr(l,c.price,n),Er(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 Hp(e,i[0],i[1])<=r?!0:i.length>=3&&Hp(e,i[2],this.target(t,n))<=r}},Db=class extends J{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.N(Math.min(r.time,i.time),n))),s=Math.min(n.length-1,Math.round(e.N(Math.max(r.time,i.time),n)));if(s<o)return[];let c=n.slice(o,Math.min(s+1,o+Cb));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.j(t.anchors[2].time,n),a=e.w(i,n)-n.barWidth/2,o=e.w(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.k(s,n),u=e.k(c,n);return{x:a,y:Math.min(l,u),width:o-a,height:Math.abs(u-l)}}source(t,n){let r=this.bars();if(r.length===0)return null;let[i,a]=t.anchors,o=Math.max(0,Math.round(e.N(Math.min(i.time,a.time),r))),s=Math.min(r.length-1,Math.round(e.N(Math.max(i.time,a.time),r)));if(s<o)return null;let c=-1/0,l=1/0;for(let e=o;e<=s;e++)r[e].high>c&&(c=r[e].high),r[e].low<l&&(l=r[e].low);let u=e.w(e.j(r[o].time,n),n)-n.barWidth/2,d=e.w(e.j(r[s].time,n),n)+n.barWidth/2,f=e.k(c,n),p=e.k(l,n);return{x:u,y:Math.min(f,p),width:d-u,height:Math.abs(p-f)}}handlePoints(e,t){let n=super.handlePoints(e,t),r=this.source(e,t);if(!r||n.length<2)return n;let[i,a]=e.anchors,o=i.time<=a.time,s=t.barWidth/2,c=r.x+s,l=r.x+r.width-s;return[{x:o?c:l,y:r.y},{x:o?l:c,y:r.y},...n.slice(2)]}render(e,n,r,i){if(n.anchors.length<2)return;let a=this.source(n,r);a&&(e.fillStyle=(0,t.withAlpha)(n.style.color,Sb),e.fillRect(a.x,a.y,a.width,a.height)),n.anchors.length>=3&&this.renderCopy(e,n,r);let o=i&&n.anchors.length>=3?this.box(n,r,this.copied(n)):null;o&&(e.save(),this.applyGuideStyle(e,n.style.color,!0),this.strokeCrispRect(e,o.x,o.y,o.width,o.height),e.restore()),i&&this.renderAnchorHandles(e,n,r)}renderCopy(t,n,r){let i=this.copied(n);if(i.length===0)return;let a=e.j(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=xb,o===`line`)t.beginPath(),i.forEach((n,i)=>{let o=e.w(a+i,r),s=e.k(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=Math.round(e.w(a+s,r))+.5;if(t.lineWidth=1,this.strokeVertical(t,c,e.k(i.high,r),e.k(i.low,r)),o===`highLow`)return;let l=Math.round(e.k(Math.max(i.open,i.close),r)),u=Math.max(1,Math.round(e.k(Math.min(i.open,i.close),r))-l),d=Math.round(c-n),f=Math.max(1,Math.round(n*2));i.close>=i.open?(t.lineWidth=1,this.strokeCrispRect(t,d,l,f,u)):t.fillRect(d,l,f,u)})}t.globalAlpha=1}hitTest(e,t,n,r){if(t.anchors.length<2)return!1;let i=this.source(t,n);if(i&&yh(e,i,r))return!0;let a=t.anchors.length>=3?this.box(t,n,this.copied(t)):null;return a!==null&&yh(e,a,r)}};function Ob(e){e.register(new Zh),e.register(new Qh),e.register(new $h),e.register(new tg),e.register(new ng),e.register(new rg),e.register(new og),e.register(new dg),e.register(new wg),e.register(new Eg),e.register(new Og),e.register(new kg),e.register(new Ag),e.register(new Pg),e.register(new c_),e.register(new g_),e.register(new y_),e.register(new b_),e.register(new O_),e.register(new A_),e.register(new N_),e.register(new R_),e.register(new B_),e.register(new Y_),e.register(new $_),e.register(new dv),e.register(new fv),e.register(new Rh),e.register(new mv),e.register(new bv),e.register(new Dv),e.register(new Fg),e.register(new Ig),e.register(new kv),e.register(new Av),e.register(new jv),e.register(new Pv),e.register(new Rv),e.register(new Hv),e.register(new jy),e.register(new Yv),e.register(new Xv),e.register(new ny),e.register(new ay),e.register(new cy),e.register(new yy),e.register(new by),e.register(new xy),e.register(new Sy),e.register(new zy),e.register(new By),e.register(new Vy),e.register(new Hy),e.register(new Gy),e.register(new Ky),e.register(new lb),e.register(new pb),e.register(new ub),e.register(new db),e.register(new fb),e.register(new mb),e.register(new l_),e.register(new u_),e.register(new d_),e.register(new f_),e.register(new p_),e.register(new Mv),e.register(new Nv),e.register(new vb),e.register(new yb),e.register(new Tb),e.register(new Eb),e.register(new Db)}function X(e,t){let{chartRect:n}=t;return e>=n.y&&e<=n.y+n.height}function kb(e,t){let{chartRect:n}=t;return Math.min(Math.max(e,n.y),n.y+n.height)}function Ab(t,n,r,i,a){let{chartRect:o}=n;t.setLineDash(a),t.strokeStyle=i,t.lineWidth=1,t.beginPath(),e.y(t,o.x,o.x+o.width,Math.round(r)+.5),t.stroke(),t.setLineDash([])}function jb(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 Mb=/\{(side|qty|closedQty|openQty|entry|price|pnl|pnlPct|pnlSign)\}/g;function Nb(e,n){return e.replace(Mb,(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 Pb(e,n,r){let i=10**n,a=Math.round(e*i)/i||0;return`${a>0?`+`:``}${(0,t.formatPrice)(a,n,r)}`}function Fb(e,t,n,r){return(r-t)*n*(e===`buy`?1:-1)}function Ib(e,t){return typeof e==`function`?e(t):Nb(e??`{side} {qty} | P&L: {pnlSign}{pnl}`,t)}function Lb(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 Rb=24,zb=1.75,Bb=[2,2.5],Vb=new Map,Hb=e=>{let t=Vb.get(e);return t||(t=new Path2D(e),Vb.set(e,t)),t};function Ub(e,n,r,i,a,o){if(!(typeof Path2D>`u`)){if(e.save(),e.translate(Math.round(r),Math.round(i)),e.scale(a/Rb,a/Rb),e.strokeStyle=o,e.fillStyle=o,e.lineWidth=Math.max(zb,Rb/a),e.lineCap=`round`,e.lineJoin=`round`,e.setLineDash([]),n.soft){let r=e.globalAlpha;e.globalAlpha=r*t.ICON_SOFT_OPACITY,e.fill(Hb(n.soft)),e.globalAlpha=r}for(let t of n.fills??[])e.fill(Hb(t));n.d&&e.stroke(Hb(n.d)),n.dash&&(e.setLineDash(Bb),e.stroke(Hb(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 Wb=5,Gb=13,Kb=22;function qb(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 Jb(e,t){return`${e.kind===`stamp`?`600 `:``}${t.font.sizeSmall}px ${t.font.family}`}function Yb(e,t,n){return t.kind===`button`?21:(e.font=Jb(t,n),Math.ceil(e.measureText(t.text).width)+Wb*2)}function Xb(e){return Math.round(e)-10}function Zb(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)<Kb&&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 Qb(e,t,n,r,i,a=[],o=0,s=[]){if(t.length===0)return;let{chartRect:c}=n,l=t.map(t=>t.cells.map(t=>Yb(e,t,r))),u=l.map(e=>e.reduce((e,t)=>e+t,0)),d=Zb(t.map((e,t)=>({y:e.y,width:u[t]})),{left:c.x,right:c.x+c.width-o}),f=t.map((e,t)=>t).sort((e,t)=>Number(d[e].fits)-Number(d[t].fits));for(let n of f){let{x:o,fits:f}=d[n],p=Xb(t[n].y);$b(e,t[n],o,p,l[n],u[n],r,f?i:[]),s.push({x:o,y:p,width:u[n],height:21});let m=t[n].grab;if(!f||!m)continue;let h=Math.max(p,c.y),g=Math.min(p+21,c.y+c.height);g>h&&a.push({x:o,y:h,width:u[n],height:g-h,lineY:t[n].y,grab:m})}}function $b(e,t,n,r,i,a,o,s){let c=r+21/2;e.save(),k(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`?(Ub(e,n.icon,l+(u-Gb)/2,r+(21-Gb)/2,Gb,o.text),s.push({x:l,y:r,size:21,action:n.action})):(e.font=Jb(n,o),e.fillStyle=n.kind===`stamp`?ne(t.color):n.color??o.text,e.fillText(n.text,l+Wb,c)),l+=u}),k(e,n+.5,r+.5,a-1,20,o),e.strokeStyle=t.color,e.lineWidth=1,e.stroke(),e.restore()}function ex(e,t){let{chartRect:n}=t,r=n.y+n.height,i=[...e].sort((e,t)=>e.y-t.y),a=te(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 tx(e,n,r,i,a,o){let{chartRect:s}=a,c=s.x+s.width+1;e.fillStyle=i,A(e,c,Math.round(n)-16/2,(a.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,16,o),e.fillStyle=ne(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 nx=[6,4],rx=[2,3],ix=[2,4],ax=.3;function ox(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 sx(e){return{buy:e.orderColors?.buy??`#1fa874`,sell:e.orderColors?.sell??`#e8505b`,profit:e.positionColors?.profit??`#1fa874`,loss:e.positionColors?.loss??`#e8505b`}}function cx(e,t){return t?.orderId===e.id&&t.sourceType===`order`}function lx(e,t){return cx(e,t)?t.currentPrice:e.price}var ux=class{render(e,t,n,r,i,a,o=[]){this.renderLines(e,t,n,i,a),Qb(e,this.tags(t,n,i,a),n,r,o)}renderLines(t,n,r,i,a){let o=sx(i);for(let i of n){let n=e.k(lx(i,a),r),s=i.side===`buy`?o.buy:o.sell;X(n,r)&&Ab(t,r,n,s,nx),cx(i,a)&&(t.globalAlpha=ax,Ab(t,r,e.k(a.startPrice,r),s,ix),t.globalAlpha=1);for(let[n,a]of[[i.stopLoss,o.loss],[i.takeProfit,o.profit]]){let i=n===void 0?NaN:e.k(n,r);X(i,r)&&Ab(t,r,i,a,rx)}}}tags(n,r,i,a){let o=sx(i),s=i.pricePrecision??2,c=[];for(let l of n){let n=lx(l,a),u=e.k(n,r);if(X(u,r)){let e=[{kind:`stamp`,text:String(l.quantity)},{kind:`text`,text:ox(l)}];i.lineButtons?.cancel!==!1&&!cx(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.k(i,r);if(i===void 0||!X(a,r))continue;let u=Fb(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:Pb(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))tx(e,o.y,o.text,o.color,n,r)}axisBadges(n,r,i,a){let o=sx(i),s=[];for(let c of n){let n=lx(c,a),l=e.k(n,r);X(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.k(a.price,r);if(Math.abs(t-n)<=i)return a}return null}},dx=[4,4],fx=[2,4],px=.3,mx=.08,hx=.25,gx=.04,_x=[`stopLoss`,`takeProfit`];function vx(e){return{profit:e.positionColors?.profit??`#1fa874`,loss:e.positionColors?.loss??`#e8505b`,entry:e.positionColors?.entry??`#4c8dff`}}function yx(e,t){let{chartRect:n}=t;return e-21/2>=n.y&&e+21/2<=n.y+n.height}function bx(e){return e.quantity-Math.min(Math.max(e.closedQuantity??0,0),e.quantity)}function xx(e,t,n){return n?.orderId===e.id&&n.sourceType===t?n.currentPrice:e[t]}var Sx=class{render(e,t,n,r,i,a,o=[],s=null){this.renderLines(e,t,n,r,a,s),Qb(e,this.tags(t,n,r,a,s),r,i,o)}renderLines(t,n,r,i,a,o=null){let s=vx(a);for(let c of n){let n=e.k(c.entryPrice,i);Ab(t,i,n,s.entry,[]),r!==null&&this.renderBand(t,c,n,e.k(r,i),r,i,a);for(let n of _x){let r=xx(c,n,o),a=r===void 0?NaN:e.k(r,i),l=n===`stopLoss`?s.loss:s.profit;X(a,i)&&Ab(t,i,a,l,dx);let u=c[n];u!==void 0&&r!==u&&(t.globalAlpha=px,Ab(t,i,e.k(u,i),l,fx),t.globalAlpha=1)}}}renderBand(e,t,n,r,i,a,o){let{chartRect:s}=a,c=vx(o),l=jb(t,i,o.pricePrecision??2),u=Math.min(n,r),d=Math.abs(r-n);e.fillStyle=Lb(l.pnl,o.pnlThresholds,l.pnl>=0?c.profit:c.loss),e.globalAlpha=mx,e.fillRect(s.x,u,s.width,d),l.closedQuantity>0&&t.quantity>0&&(e.fillStyle=c.entry,e.globalAlpha=hx,e.fillRect(s.x,u,Math.max(2,s.width*(l.closedQuantity/t.quantity)*gx)+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 _x){let t=this.stopTag(o,e,n,r,i);t&&a.push(t)}}return a}entryTag(n,r,i,a){let o=e.k(n.entryPrice,i);if(!X(o,i))return null;let s=vx(a),c=n.side===`buy`?`Long`:`Short`,l=[{kind:`stamp`,text:String(bx(n))}];if(r===null)l.push({kind:`text`,text:c});else{let e=a.pricePrecision??2,o=jb(n,r,e,e=>(0,t.priceTagText)(e,i,a.pricePrecision),i.numberLocale);if(a.positionLabel!==void 0)l.push({kind:`text`,text:Ib(a.positionLabel,o)});else{let t=Lb(o.pnl,a.pnlThresholds,o.pnl>=0?s.profit:s.loss);l.push({kind:`text`,text:c},{kind:`text`,text:Pb(o.pnl,e,i.numberLocale),color:t})}}let u=a.lineButtons??{};return yx(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=xx(n,r,o),c=s===void 0?NaN:e.k(s,i);if(s===void 0||!X(c,i))return null;let l=vx(a),u=Fb(n.side,n.entryPrice,bx(n),s),d=[{kind:`stamp`,text:r===`stopLoss`?`SL`:`TP`},{kind:`text`,text:Pb(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&&yx(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))tx(e,a.y,a.text,a.color,n,r)}axisBadges(n,r,i,a=null){let o=vx(i),s=[];for(let c of n){let n=[[xx(c,`stopLoss`,a),o.loss],[xx(c,`takeProfit`,a),o.profit],[c.entryPrice,o.entry]];for(let[a,o]of n){if(a===void 0)continue;let n=e.k(a,r);X(n,r)&&s.push({y:n,text:(0,t.priceTagText)(a,r,i.pricePrecision),color:o})}}return s}},Cx=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.k(n.bids[0].price,r)-e.k(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.k(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.k(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)}}},wx=[`stopLoss`,`takeProfit`],Tx=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.k(n,i);return X(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 wx){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.I(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}},Ex=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=`
|
|
7
7
|
position: absolute;
|
|
8
8
|
left: ${e.x}px;
|
|
9
9
|
top: ${e.y}px;
|
|
@@ -21,6 +21,6 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
|
|
|
21
21
|
cursor: pointer;
|
|
22
22
|
color: ${n?`#1fa874`:`#e8505b`};
|
|
23
23
|
transition: background 0.1s;
|
|
24
|
-
`,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 yx(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 bx(e){let t=Math.abs(e.entry-e.stopLoss);return t===0?0:Math.abs(e.takeProfit-e.entry)/t}var xx=6,Sx=.12,Cx=[6,3],wx=class{draft=null;dragStart=null;dragging=null;defaults;constructor(e={}){this.defaults=e}start(e,t){this.draft=yx(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=xx){if(!this.draft)return null;let i=[`entry`,`sl`,`tp`],a=null,o=r;for(let r of i){let i=e.O(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.F(t.y,n);return this.draft=Ex(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),Wb(e,this.tags(t,n),t,n,[])}renderLines(t,n,r){let i=this.draft;if(!i)return;let{chartRect:a}=n,o=e.O(i.entry,n),s=e.O(i.stopLoss,n),c=e.O(i.takeProfit,n),{profit:l,loss:u}=Tx(r);t.save(),t.globalAlpha=Sx,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,Sb(t,n,o,r.text,Cx),Sb(t,n,c,l,[]),Sb(t,n,s,u,[]),t.restore()}tags(t,n){let r=this.draft;if(!r)return[];let{profit:i,loss:a}=Tx(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.O(r.entry,t),color:n.text,grab:{kind:`bracket`,handle:`entry`},cells:[{kind:`stamp`,text:r.side===`buy`?`Long`:`Short`},{kind:`text`,text:`${bx(r).toFixed(2)}R`}]},{y:e.O(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.O(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=>X(e.y,t))}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))qb(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}=Tx(r),c=[];for(let[l,u]of[[a.takeProfit,o],[a.stopLoss,s],[a.entry,r.text]]){let r=e.O(l,n);X(r,n)&&c.push({y:r,text:(0,t.priceTagText)(l,n,i),color:u})}return c}};function Tx(e){return{profit:e.style?.trading.profit??e.candleUp,loss:e.style?.trading.loss??e.candleDown}}function Ex(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 Dx(e,t,n){return n==null?`limit`:e===`buy`?t<=n?`limit`:`stop`:t>=n?`limit`:`stop`}var Ox=6,kx=[6,3],Ax=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:Dx(this.draft.side,this.draft.price,e),price:this.draft.price,quantity:this.draft.quantity}:null}hitTest(t,n,r=Ox){return this.draft?Math.abs(e.O(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.F(t.y,n))}endDrag(){this.dragging=!1,this.dragStart=null}render(e,t,n,r,i){this.renderLines(e,t,n),Wb(e,this.tags(t,n,r),t,n,[])}renderLines(t,n,r){let i=this.draft;i&&(t.save(),Sb(t,n,e.O(i.price,n),jx(i.side,r),kx),t.restore())}tags(t,n,r){let i=this.draft;if(!i)return[];let a=e.O(i.price,t);if(!X(a,t))return[];let o=Dx(i.side,i.price,r);return[{y:a,color:jx(i.side,n),grab:{kind:`draft`},cells:[{kind:`stamp`,text:String(i.quantity)},{kind:`text`,text:Qb({side:i.side,type:o})}]}]}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))qb(e,i.y,i.text,i.color,t,n)}axisBadges(n,r,i){let a=this.draft;if(!a)return[];let o=e.O(a.price,n);return X(o,n)?[{y:o,text:(0,t.priceTagText)(a.price,n,i),color:jx(a.side,r)}]:[]}};function jx(e,t){return e===`buy`?t.style?.trading.buy??t.candleUp:t.style?.trading.sell??t.candleDown}var Mx=2;function Nx(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 Px(e,t,n=Mx){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 Fx=5,Ix=7,Lx=2;function Rx(e,n){let r=n.data;return r&&r.length>0?e/(0,t.barTimeUnit)(r):e}function zx(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.j(Rx(i.time,r),r),c=e.O(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+Lx:c-Lx,d=l?u+Ix:u-Ix;t.beginPath(),t.moveTo(n,u),t.lineTo(n-Fx,d),t.lineTo(n+Fx,d),t.closePath();let f=l?o:s;!i.reason||i.reason===`order`?(t.fillStyle=f,t.fill()):(t.strokeStyle=f,t.stroke())}}function Bx(e){for(let t in e)if(e[t]!==null)return!0;return!1}function Vx(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];i!==null&&(n[t[r]]=i)}return n}function Hx(e,t){let n=t.style?.trading;return!n||!Bx(n)?e:{...e,orderColors:{...e.orderColors,...Vx({buy:n.buy,sell:n.sell},{buy:`buy`,sell:`sell`})},positionColors:{...e.positionColors,...Vx({profit:n.profit,loss:n.loss,entry:n.entry},{profit:`profit`,loss:`loss`,entry:`entry`})}}}function Ux(e,t){let n=t.style?.markers;return!n||!Bx(n)?e:{...e,...Vx(n,{long:`longColor`,short:`shortColor`,neutral:`neutralColor`})}}function Wx(e,t){let n=t.style?.tradeZones;return!n||!Bx(n)?e:{...e,...Vx(n,{profit:`profitColor`,loss:`lossColor`,active:`activeColor`})}}var Gx=1e3,Kx=class{orders=[];positions=[];depthData=null;currentPrice=null;config;orderRenderer=new nx;positionRenderer=new mx;depthOverlay=new hx;dragHandler;contextMenu=new vx;bracket=new wx;orderDraft=new Ax;buttons=[];tagBoxes=[];tagInset=0;drawnTags=[];grabOffset=0;fills=[];realisedPnl=0;requestRender=null;eventCallback=null;container=null;constructor(e){this.config={...t.DEFAULT_TRADING_CONFIG,...e},this.dragHandler=new _x(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(-(Gx-1)),e],this.realisedPnl+=e.pnl??0,this.requestRender?.()}setFills(e){this.fills=e.slice(-Gx),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&&Px(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:bx(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(zb(this.tagBoxes,t.x,t.y)&&!Px(this.buttons,t))return!0;let i=i=>{if(i===void 0)return!1;let a=e.O(i,n);return X(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=Px(this.buttons,e,n?.button),i=r?null:zb(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:xb(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?Px(this.buttons,e):null;return n&&Nx(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.F(n.y,r);return this.contextMenu.show(n,i,this.container,this.config,e=>(0,t.priceTagText)(e,r,this.config.pricePrecision)),!0}tagRects(){return this.drawnTags}setTagInset(e){this.tagInset=Math.max(0,e)}render(e,t,n){if(this.buttons=[],this.tagBoxes=[],this.drawnTags=[],!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=Hx(this.config,n);this.depthData&&this.depthOverlay.render(e,this.depthData,t,r),r.fillMarks!==!1&&zx(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),Wb(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,this.tagInset,this.drawnTags)}renderAxisBadges(e,t,n,r){if(this.config.enabled){if(r){let{chartRect:i}=t;this.sortedAxisBadges(t,n).forEach((a,o)=>{let s=r[o]??a.y;!Number.isFinite(s)||s-16/2<i.y-.5||s+16/2>i.y+i.height+.5||qb(e,s,a.text,a.color,t,n)});return}for(let r of Kb(this.axisBadges(t,n),t))qb(e,r.at,r.text,r.color,t,n)}}axisBadgeLines(e,n=t.DARK_THEME){return this.config.enabled?this.sortedAxisBadges(e,n).map(e=>e.y):[]}sortedAxisBadges(e,t){return this.axisBadges(e,t).sort((e,t)=>e.y-t.y)}axisBadges(e,t){let n=Hx(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?Kb(this.axisBadges(e,n),e).map(e=>e.at):[]}destroy(){this.contextMenu.destroy()}},qx=class{constructor(e){this.manager=e}render(e,t,n){this.manager.render(e,t,n)}renderAxisBadges(e,t,n,r){this.manager.renderAxisBadges(e,t,n,r)}axisBadgeLines(e,t){return this.manager.axisBadgeLines(e,t)}tagRects(){return this.manager.tagRects()}axisTagYs(e,t){return this.manager.axisTagYs(e,t)}},Jx=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:Xx(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:Yx(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:Yx(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 Yx(e){return e===`buy`?`sell`:`buy`}function Xx(e){switch(e){case`stop`:return`STOP`;case`stopLimit`:return`STOP LIMIT`;default:return`LIMIT`}}var Zx=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()}},Qx=6e4,$x=e=>[e.open,e.high,e.low,e.close].every(Number.isFinite),eS=class extends Zx{currentBar=null;newest=-1/0;builtFromTrades=!1;lastTradeAt=null;timeframe;timeframeMs;dateFrame;bucket={};dateStamps=!1;tickRing;ringHead=0;ringCount=0;ringCapacity;constructor(e,n=1e3){super(),this.timeframe=e,this.timeframeMs=(0,t.timeframeToMs)(e),this.dateFrame=(0,t.timeframeSpansDays)(e),this.ringCapacity=n,this.tickRing=Array(n)}setTimeframe(e){this.timeframe=e,this.timeframeMs=(0,t.timeframeToMs)(e),this.dateFrame=(0,t.timeframeSpansDays)(e),this.reset()}seed(e){this.builtOffTheBuckets()&&(this.currentBar=null,this.newest=-1/0,this.lastTradeAt=null),Number.isFinite(e)&&(this.newest=Math.max(this.newest,(0,t.normalizeBarTime)(e)))}resume(e){if(!$x(e))return;let n=(0,t.normalizeBarTime)(e.time);n<this.newest||(this.newest=n,this.currentBar={time:n,open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume??0,closed:!1,tickCount:0},this.builtFromTrades=!0,this.lastTradeAt=null)}setTimeZone(e,t=!1){this.bucket={timeZone:e??void 0},this.dateStamps=t}processTick(e){let n=(this.ringHead+this.ringCount)%this.ringCapacity;this.tickRing[n]=e,this.ringCount<this.ringCapacity?this.ringCount++:this.ringHead=(this.ringHead+1)%this.ringCapacity;let r=this.barFor(e.time);r!==null&&(this.newest=(0,t.normalizeBarTime)(r),this.lastTradeAt=e.time,!this.currentBar||this.currentBar.time!==r?(this.currentBar&&(this.currentBar.closed=!0,this.emit(`barClose`,this.currentBar)),this.currentBar={time:r,open:e.price,high:e.price,low:e.price,close:e.price,volume:e.volume,closed:!1,tickCount:1},this.builtFromTrades=!0):(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,n){let r=(0,t.normalizeBarTime)(e.time);if(r<this.newest){n&&this.emit(`correction`,{...e});return}if(this.newest=r,this.builtFromTrades=!1,n&&this.currentBar&&(0,t.normalizeBarTime)(this.currentBar.time)===r)this.currentBar={...e,closed:!0,tickCount:this.currentBar.tickCount+1},this.emit(`barClose`,this.currentBar),this.currentBar=null;else if(!n)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.newest=-1/0,this.builtFromTrades=!1,this.lastTradeAt=null,this.ringHead=0,this.ringCount=0}barFor(e){let n=this.alignToTimeframe(e);if((0,t.normalizeBarTime)(n)>=this.newest)return n;if((0,t.normalizeBarTime)(e)<this.instantOf(this.newest))return null;let r=this.currentBar;return r!==null&&(0,t.normalizeBarTime)(r.time)===this.newest?r.time:this.newest}instantOf(e){return!this.dateStamps||!this.dateFrame?e:e-(0,t.offsetAt)(this.bucket.timeZone??0,e)*Qx}builtOffTheBuckets(){let e=this.currentBar;return e===null||!this.builtFromTrades?!1:this.lastTradeAt===null?!this.startsABucket((0,t.normalizeBarTime)(e.time)):this.alignToTimeframe(this.lastTradeAt)!==e.time}startsABucket(e){return this.timeframeMs>0?this.dateStamps&&this.dateFrame?(0,t.timeframeBucketStart)(e,this.timeframe)===e:this.alignToTimeframe(e)===e:!0}alignToTimeframe(e){if(!(this.timeframeMs>0))return e;let n=(0,t.timeframeBucketStart)(e,this.timeframe,this.bucket);return!this.dateStamps||!this.dateFrame?n:n+(0,t.offsetAt)(this.bucket.timeZone??0,n)*Qx}},tS=class extends Zx{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))}},nS=20,rS=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),t===void 0?e!==this.price&&(this.previousClose=this.price??e):this.previousClose=t,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(e,t,n){this.renderLine(e,t,n),this.renderTag(e,t,n)}placed(t,n){let r=n.style?.lastPrice;if(!this.visible||this.price===null||r?.visible===!1)return null;let i=e.O(this.price,t),{chartRect:a}=t;return i<a.y||i>a.y+a.height?null:{y:i,color:this.previousClose===null||this.price>=this.previousClose?r?.up??n.candleUp??`#1fa874`:r?.down??n.candleDown??`#e8505b`}}renderLine(n,r,i){let a=this.placed(r,i);if(!a)return;let{y:o,color:s}=a,{chartRect:c}=r,l=i.style?.lastPrice,u=Date.now()<this.flashUntil,d=l?.width??1;n.setLineDash((0,t.lineDash)(l?.style??`solid`,[4,3],d)),n.strokeStyle=s,n.lineWidth=d,n.globalAlpha=u?1:.7,n.beginPath(),e.y(n,c.x,c.x+c.width,Math.round(o)+.5,d),n.stroke(),n.setLineDash([]),n.globalAlpha=1}renderTag(e,n,r){this.tag=null;let i=this.placed(n,r);if(!i||this.price===null)return;let{y:a,color:o}=i,{chartRect:s}=n,c=s.x+s.width+1,l=this.pricePrecision??(0,t.autoPricePrecision)(n.priceRange.min,n.priceRange.max),u=n.formatPrice?n.formatPrice(this.price):(0,t.formatPrice)(this.price,l,this.locale);e.font=`bold 11px ${r.font.family}`;let d=e.measureText(u).width,f=n.priceAxisWidth??t.PRICE_AXIS_WIDTH,p=Math.min(d+12,f-2);e.fillStyle=o,k(e,c,a-nS/2,p,nS,r),this.tag={x:c,y:a-nS/2,width:p,height:nS,color:o};let m=c-5;e.beginPath(),e.moveTo(m,a),e.lineTo(m+5,a-5),e.lineTo(m+5,a+5),e.closePath(),e.fill(),e.fillStyle=re(o),e.textBaseline=`middle`,e.textAlign=`left`,e.fillText(u,c+5,a)}},iS=1e3,aS=10,oS=1440,sS=5e3,cS=2,lS=864e5,uS=6e4,dS=[`tick`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],fS=new WeakMap;function pS(e){if(e instanceof yS||!e.supportedTimeframes?.length)return e;let t=fS.get(e);return t||(t=new yS(e,e.supportedTimeframes),fS.set(e,t)),t}function mS(e,n,r){if(n.includes(e))return e;let i=(0,t.pickBaseTimeframe)(e,n,{timeZone:r});return i&&Math.ceil((0,t.timeframeToMs)(e)/(0,t.timeframeToMs)(i))<=1440?i:null}function hS(e,n){if((0,t.tickBarCount)(n)!==null)return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`;let r=e.supportedTimeframes;return!r?.length||mS(n,r)!==null}function gS(e,n,r){let i=(0,t.parseTimeframe)(n),a=r!==void 0&&(0,t.timeframeSpansDays)(n)&&e%lS!==0,o=a?e+(0,t.offsetAt)(r,e)*uS:e,s;if(i?.unit===`M`){let e=new Date(o);s=Date.UTC(e.getUTCFullYear(),e.getUTCMonth()+i.count,1)}else s=o+(0,t.timeframeToMs)(n);return a?(0,t.wallToUtc)(s,r):s}function _S(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}function vS(e,t){return _S(e,[...t.values()].sort((e,t)=>e.time-t.time))}var yS=class{name;fetchHistoryBefore;searchSymbols;resolveSymbol;subscribeQuotes;fetchNews;fetchTrades;subscribeTrades;listeners=new Map;unsubscribe=[];live=null;bucket=null;parts=new Map;closedBuckets=new Map;tail=null;generation=0;zones=new Map;resolving=new Map;unanswered=new Map;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=>this.resolveShared(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 dS)this.listen(e,t=>this.emit(e,t.data))}baseFor(e){let t=mS(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.closedBuckets.clear(),this.live=t===e.timeframe?null:{symbol:e.symbol,target:e.timeframe,...this.planFor(e.timeframe,this.keptZone(e.symbol))},this.live&&this.resumeFromHistory(this.live),this.inner.connect({...e,timeframe:this.live?.base??t})}disconnect(){this.generation++,this.inner.disconnect(),this.resetBucket(),this.closedBuckets.clear(),this.live=null}getConnectionState(){return this.inner.getConnectionState()}async fetchHistory(e,t,n=500){if(this.baseFor(t)===t)return this.inner.fetchHistory(e,t,n);let r=this.generation,{plan:i,bars:a}=await this.baseBarsWithZone(e,t,async i=>{let a=this.baseBarsFor(t,i,n),o=await this.inner.fetchHistory(e,i,Math.min(a,iS));return this.extendBack(e,i,o,a,r)});return this.rememberTail(e,t,a,i),this.toTarget(a,t,n,i)}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()}bucketFor(e,t){let n=mS(t,this.baseTimeframes);return n===null||n===t?null:{...this.planFor(t,this.keptZone(e)).bucket}}waitsForZone(e){return typeof this.inner.resolveSymbol==`function`&&(0,t.timeframeFollowsDays)(e)}keptZone(e){return this.zones.get(e)??void 0}renewZone(e){let t=this.unanswered.get(e);if(!t)return;let n=t.zone,r=t.asked!==void 0&&this.resolving.get(e)===t.asked;n===void 0&&r||(this.unanswered.delete(e),n===void 0?this.zones.delete(e):this.zones.set(e,n))}async zoneFor(e){if(this.zones.has(e))return this.keptZone(e);let t,n=new Promise(e=>{t=setTimeout(()=>e(),sS)});try{await Promise.race([this.resolveShared(e),n])}catch{}finally{clearTimeout(t)}return this.zones.has(e)||(this.zones.set(e,null),this.unanswered.set(e,{asked:this.resolving.get(e)})),this.keptZone(e)}resolveShared(e){let t=this.resolving.get(e);if(t)return t;let n=this.inner.resolveSymbol.bind(this.inner),r=Promise.resolve().then(()=>n(e));this.resolving.set(e,r);let i=()=>{this.resolving.get(e)===r&&this.resolving.delete(e)};return r.then(t=>{this.keepZone(e,t),i()},i),r}keepZone(e,n){let r=(0,t.symbolTimeZone)(n),i=r&&(0,t.isValidTimeZone)(r)&&!(0,t.isUtcTimeZone)(r)?r:null,a=this.unanswered.get(e);a?this.unanswered.set(e,{...a,zone:i}):this.zones.has(e)||this.zones.set(e,i)}planFor(e,n){let r=this.baseFor(e),i=n!==void 0&&r!==e&&(0,t.timeframeFollowsDays)(e)?mS(e,this.baseTimeframes,n):null,a=i??r,o=i?n:void 0;return{base:a,zone:o,bucket:{timeZone:o,dates:(0,t.timeframeSpansDays)(a)}}}async historyBefore(e,t,n,r){let i=this.inner.fetchHistoryBefore.bind(this.inner);if(this.baseFor(t)===t)return i(e,t,n,r);let a=this.generation,{plan:o,bars:s}=await this.baseBarsWithZone(e,t,async o=>{let s=this.baseBarsFor(t,o,r),c=await i(e,o,n,Math.min(s,iS));return this.extendBack(e,o,c.filter(e=>e.time<n),s,a,1)});return this.toTarget(s,t,r,o)}async baseBarsWithZone(e,t,n){if(!this.waitsForZone(t)||this.zones.has(e)){let r=this.planFor(t,this.keptZone(e));return{plan:r,bars:await n(r.base)}}let r=this.planFor(t,void 0).base,i=n(r);i.catch(()=>{});let a=this.planFor(t,await this.zoneFor(e));return{plan:a,bars:await(a.base===r?i:n(a.base))}}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,iS));c++;let a=i.filter(e=>e.time<n);if(a.length===0)break;s=a.concat(s)}return s}toTarget(e,n,r,i){if(e.length===0)return[];let a=(0,t.resampleBars)(e,n,i.bucket);return a.length>1&&a[0].time!==e[0].time&&a.shift(),a.length>r?a.slice(a.length-r):a}rememberTail(e,n,r,i){if(r.length===0)return;let a=(0,t.timeframeBucketStart)(r[r.length-1].time,n,i.bucket),o=r.length;for(;o>0&&(0,t.timeframeBucketStart)(r[o-1].time,n,i.bucket)===a;)o--;this.tail={symbol:e,target:n,zone:i.zone,bucket:a,bars:r.slice(o)}}resumeFromHistory(e){let t=this.tail;if(!(!t||t.symbol!==e.symbol||t.target!==e.target||t.zone!==e.zone)){this.bucket=t.bucket;for(let e of t.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,n.bucket);if(this.bucket!==null&&a<this.bucket){i&&this.correctClosed(a,r);return}if(this.bucket!==null&&a>this.bucket){let e=this.composed();e&&this.emit(`bar`,{bar:e,closed:!0}),this.keepClosed(),this.resetBucket()}this.bucket=a,this.parts.set(r.time,r);let o=this.composed();if(!o)return;let s=(0,t.timeframeBucketStart)(gS(r.time,n.base,n.zone),n.target,n.bucket),c=i&&s!==a;this.emit(`bar`,{bar:o,closed:c}),c&&(this.keepClosed(),this.resetBucket(),this.bucket=s)}composed(){return this.bucket===null||this.parts.size===0?null:vS(this.bucket,this.parts)}correctClosed(e,t){let n=this.closedBuckets.get(e);n&&(n.set(t.time,t),this.emit(`bar`,{bar:vS(e,n),closed:!0}))}keepClosed(){if(!(this.bucket===null||this.parts.size===0)){this.closedBuckets.set(this.bucket,this.parts);for(let e of this.closedBuckets.keys()){if(this.closedBuckets.size<=2)break;this.closedBuckets.delete(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)}},bS=1e3,xS=15e3,SS=[`tick`,`bar`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],CS=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)}},wS=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 SS)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,bS)).filter(OS).sort((e,t)=>e.time-t.time),o=new CS(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 CS(n),after:-1/0};this.tick=r,this.stopTrades=this.inner.subscribeTrades(e.symbol,e=>{let t=e.filter(e=>OS(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`),xS)}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)}},TS=new WeakMap;function ES(e){if(e instanceof wS||!DS(e))return e;let t=TS.get(e);return t||(t=new wS(e),TS.set(e,t)),t}function DS(e){return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`}function OS(e){return Number.isFinite(e?.time)&&Number.isFinite(e?.price)&&Number.isFinite(e?.volume)}var kS=Symbol(`tradecanvas.sourceAdapter`),AS=new WeakSet;function jS(e){return AS.has(e)}var MS=(e,t)=>`${e}\u0000${t}`;function NS(e){return typeof e.getBars==`function`&&typeof e.subscribeBars==`function`}function PS(e){if(e.adapter&&e.feed)throw TypeError(`A stream takes an adapter or a feed, not both`);if(e.adapter)return e.adapter;if(e.feed)return LS(e.feed);throw TypeError(`A stream needs an adapter or a feed`)}function FS(e,t,n){for(let r of n){let n=t[r];typeof n==`function`&&(e[r]=n.bind(t))}}var IS=[`resolveSymbol`,`searchSymbols`,`subscribeQuotes`,`fetchNews`,`fetchTrades`,`subscribeTrades`];function LS(e){let t=e[kS];if(t)return t;let n=new RS(e);return AS.add(n),n}var RS=class{name;supportedTimeframes;fetchHistoryBefore;state=`disconnected`;listeners=new Map;unsubscribe=null;requests=new Map;streamed=null;constructor(e){this.feed=e,this.name=e.name,e.supportedTimeframes&&(this.supportedTimeframes=e.supportedTimeframes),e.pagesBack!==!1&&(this.fetchHistoryBefore=(e,t,n,r)=>this.feed.getBars({symbol:e,timeframe:t,countBack:r,before:n,signal:this.signalFor(e,t)})),FS(this,e,IS)}fetchHistory(e,t,n=500){return this.feed.getBars({symbol:e,timeframe:t,countBack:n,signal:this.signalFor(e,t)})}fetchStreamHistory(e,t){return this.streamed=MS(e.symbol,e.timeframe),this.fetchHistory(e.symbol,e.timeframe,t)}connect(e){this.subscribe({symbol:e.symbol,timeframe:e.timeframe})}subscribe(e,t){this.stopSubscription(),this.streamed=MS(e.symbol,e.timeframe);let n=!0,r=!1,i=null;this.unsubscribe=()=>{n=!1,i?.()};let a=e=>{this.setState(e),t?.connection(e)},o=this.feed.subscribeBars(e,{bar:(e,r)=>{n&&(this.emit(`bar`,{bar:e,closed:r}),t?.bar(e,r))},tick:e=>{n&&(this.emit(`tick`,e),t?.tick(e))},connection:e=>{n&&(r=!0,a(e))},symbolInfo:e=>{n&&(this.emit(`symbolInfo`,e),t?.symbolInfo(e))},error:e=>{n&&(this.emit(`error`,{message:e}),t?.error(e))}});if(!n){o();return}i=o,r||a(`connected`)}disconnect(){this.stopSubscription(),this.streamed!==null&&(this.requests.get(this.streamed)?.abort(),this.requests.delete(this.streamed),this.streamed=null),this.state=`disconnected`}getConnectionState(){return this.state}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()}signalFor(e,t){let n=MS(e,t),r=this.requests.get(n);return r||(r=new AbortController,this.requests.set(n,r)),r.signal}stopSubscription(){let e=this.unsubscribe;this.unsubscribe=null,e?.()}setState(e){this.state=e,this.emit(`connectionChange`,e)}emit(e,t){let n={type:e,data:t,timestamp:Date.now()};for(let t of[...this.listeners.get(e)??[]])t(n)}};function zS(e){let t={name:e.name,...e.supportedTimeframes?{supportedTimeframes:e.supportedTimeframes}:{},pagesBack:typeof e.fetchHistoryBefore==`function`,getBars:async({symbol:t,timeframe:n,countBack:r,before:i})=>i===void 0?e.fetchHistory(t,n,r):e.fetchHistoryBefore?e.fetchHistoryBefore(t,n,i,r):[],subscribeBars:(t,n)=>BS(e,t,n),[kS]:e};return FS(t,e,IS),t}function BS(e,t,n){let r=[[`bar`,e=>{let{bar:t,closed:r}=e.data;n.bar(t,r)}],[`tick`,e=>n.tick(e.data)],[`connectionChange`,e=>n.connection(e.data)],[`symbolInfo`,e=>n.symbolInfo(e.data)],[`error`,e=>n.error(e.data?.message??`Adapter error`)]];for(let[t,n]of r)e.on(t,n);return e.connect({symbol:t.symbol,timeframe:t.timeframe}),()=>{for(let[t,n]of r)e.off(t,n);e.disconnect()}}function VS(e){let t=PS(e),n=!jS(t),r=pS(t),i=r instanceof yS?r:null,a=ES(r);return a instanceof RS?new HS(a,i,n):new US(a,i,n)}var HS=class{subscriber=null;constructor(e,t,n){this.adapter=e,this.resampler=t,this.watchSilence=n}listen(e){this.subscriber=e}getBars(e,t){return this.adapter.fetchStreamHistory(e,t)}subscribeBars(e){this.adapter.subscribe(e,this.subscriber??void 0)}unsubscribe(){this.adapter.disconnect()}release(){this.subscriber=null}},US=class{unlisten=[];constructor(e,t,n){this.adapter=e,this.resampler=t,this.watchSilence=n}listen(e){this.hear(`connectionChange`,t=>e.connection(t.data)),this.hear(`tick`,t=>e.tick(t.data)),this.hear(`bar`,t=>{let{bar:n,closed:r}=t.data;e.bar(n,r)}),this.hear(`error`,t=>e.error(t.data?.message??`Adapter error`));try{this.hear(`symbolInfo`,t=>e.symbolInfo(t?.data))}catch{}}getBars(e,t){return this.adapter.fetchHistory(e.symbol,e.timeframe,t)}subscribeBars(e){this.adapter.connect({symbol:e.symbol,timeframe:e.timeframe})}unsubscribe(){this.adapter.disconnect()}release(){for(let e of this.unlisten)e();this.unlisten=[]}hear(e,t){this.adapter.on(e,t),this.unlisten.push(()=>this.adapter.off(e,t))}},WS=2e4,GS=6e4,KS=3e4,qS=500,JS=864e5;function YS(e,n){if(!n)return e;let{time:r,open:i,high:a,low:o,close:s,volume:c}=n;return[...e,{time:(0,t.normalizeBarTime)(r)/(0,t.barTimeUnit)(e),open:i,high:a,low:o,close:s,volume:c}]}function XS(e,n,r){return(0,t.timeframeBucketStart)(e,n,{timeZone:r})===e&&(0,t.timeframeBucketStart)(e,n)!==e}var ZS=class extends Zx{config=null;source=null;aggregator=null;reconnector;priceLine=new rS;state=`disconnected`;lastPrice=null;previousClose=null;sentPreviousClose=null;previousCloseTime=null;heartbeatTimer=null;lastMessageTime=0;connectSeq=0;timeZone=null;historyEnd=null;constructor(){super(),this.reconnector=new tS,this.wireReconnector()}async connect(e){this.disconnect();let n=VS(e);n.resampler?.renewZone(e.symbol),this.config={...t.DEFAULT_STREAM_CONFIG,...e},this.source=n,this.aggregator=new eS(e.timeframe),this.historyEnd=null,this.applyTickZone(),this.reconnector.removeAllListeners(),this.reconnector.stop(),this.reconnector=new tS(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.setPreviousClose(e),this.emit(`barClose`,e)}),this.aggregator.on(`correction`,e=>{(0,t.normalizeBarTime)(e.time)===this.previousCloseTime&&(this.previousClose=e.close),this.emit(`barCorrection`,e)}),n.listen(this.subscriber()),this.reconnector.start(),await this.doConnect()}disconnect(){this.connectSeq++,this.reconnector.stop(),this.stopHeartbeat(),this.source&&=(this.source.release(),this.source.unsubscribe(),null),this.aggregator?.reset(),this.aggregator?.removeAllListeners(),this.aggregator=null,this.config=null,this.historyEnd=null,this.lastPrice=null,this.previousClose=null,this.previousCloseTime=null,this.sentPreviousClose=null,this.setState(`disconnected`)}async switchTo(e,t){!this.config||!this.source||(this.reconnector.stop(),this.source.unsubscribe(),this.reconnector.start(),this.aggregator?.reset(),this.aggregator?.setTimeframe(t),this.lastPrice=null,this.previousClose=null,this.previousCloseTime=null,this.sentPreviousClose=null,(e!==this.config.symbol||t!==this.config.timeframe)&&this.source.resampler?.renewZone(e),this.config.symbol=e,this.config.timeframe=t,await this.doConnect())}getConnectionState(){return this.state}setTimeZone(e){if(e!==null&&!(0,t.isValidTimeZone)(e))throw RangeError(`Unknown time zone: ${e}`);this.timeZone=e,this.applyTickZone()}getConnectionInfo(){return{state:this.state,reconnectAttempt:this.reconnector.getAttempt(),lastMessageTime:this.lastMessageTime}}getLastPrice(){return this.lastPrice}applyTickZone(){let e=this.config;if(!this.aggregator||!e)return;let t=this.historyEnd,n=t!==null&&t%JS===0,r=this.source?.resampler?.bucketFor(e.symbol,e.timeframe);if(r){let e=r.dates===!0&&n;this.aggregator.setTimeZone(r.timeZone??(e?this.timeZone:null),e);return}this.aggregator.setTimeZone(this.tickZone(e.timeframe,t),n)}tickZone(e,n){let r=this.timeZone;return r===null||(0,t.timeframeSpansDays)(e)||n!==null&&XS(n,e,r)?r:null}async doConnect(){if(!this.config||!this.source)return;let e=++this.connectSeq,n={symbol:this.config.symbol,timeframe:this.config.timeframe};this.setState(`connecting`);try{let r=await this.source.getBars(n,this.config.historyLimit??qS);if(e!==this.connectSeq||!this.source)return;let i=r.length>0?r[r.length-1]:null;this.historyEnd=i?(0,t.normalizeBarTime)(i.time):null,this.applyTickZone(),this.seedAggregator(i);let a=this.formingAfter(i);i&&!a&&(this.setPreviousClose(i),this.updatePrice(i.close)),this.emit(`snapshot`,YS(r,a)),this.source.subscribeBars(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.state=`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`})})}subscriber(){return{connection:e=>this.onConnection(e),tick:e=>this.onTick(e),bar:(e,t)=>this.onBar(e,t),error:e=>this.emit(`error`,{message:e??`Adapter error`}),symbolInfo:e=>{e&&typeof e==`object`&&this.emit(`symbolInfo`,e)}}}onConnection(e){this.lastMessageTime=Date.now(),e===`connected`?(this.reconnector.onConnected(),this.setState(`connected`)):(e===`disconnected`||e===`error`)&&this.reconnector.schedule(()=>this.doConnect())}onTick(e){this.lastMessageTime=Date.now(),this.emit(`tick`,e),(e.bid!==void 0||e.ask!==void 0)&&this.emit(`quote`,{bid:e.bid,ask:e.ask}),this.config?.aggregateTicks&&this.aggregator?this.aggregator.processTick(e):this.updatePrice(e.price)}onBar(e,t){this.lastMessageTime=Date.now(),this.aggregator?.processBar(e,t)}setPreviousClose(e){this.previousClose=e.close,this.previousCloseTime=(0,t.normalizeBarTime)(e.time)}seedAggregator(e){this.aggregator&&(this.aggregator.seed(e?e.time:-1/0),e&&this.config?.aggregateTicks&&this.aggregator.resume(e))}formingAfter(e){let n=this.aggregator?.getCurrentBar()??null;return!n||e&&(0,t.normalizeBarTime)(n.time)<=(0,t.normalizeBarTime)(e.time)?null:n}updatePrice(e){e===this.lastPrice&&this.previousClose===this.sentPreviousClose||(this.lastPrice=e,this.sentPreviousClose=this.previousClose,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.source||!this.config||this.state===`connecting`||this.state===`disconnected`||this.state===`connected`&&e===`visible`&&(!this.source.watchSilence||Date.now()-this.lastMessageTime<=WS)||(this.reconnector.stop(),this.source.unsubscribe(),this.reconnector.start(),this.doConnect())}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.source?.watchSilence===!0&&Date.now()-this.lastMessageTime>GS&&this.state===`connected`&&(this.emit(`error`,{message:`Heartbeat timeout`,code:`HEARTBEAT_TIMEOUT`}),this.source?.unsubscribe(),this.reconnector.schedule(()=>this.doConnect()))},KS)}stopHeartbeat(){this.heartbeatTimer&&=(clearInterval(this.heartbeatTimer),null)}dispose(){this.disconnect(),this.removeAllListeners()}},QS=class extends Zx{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 $S(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=tC(e[1]),r=tC(e[2]),i=tC(e[3]),a=tC(e[4]),o=tC(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 eC(e){if(!nC(e))return null;let t=e.t;if(typeof t!=`number`||!Number.isFinite(t))return null;let n=tC(e.o),r=tC(e.h),i=tC(e.l),a=tC(e.c),o=tC(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 tC(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 nC(e){return typeof e==`object`&&!!e}function Z(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:void 0}function rC(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:Z(r.c),open:Z(r.o),high:Z(r.h),low:Z(r.l),volume:Z(r.v),time:Z(r.E)}):null}function iC(e){if(!e||typeof e!=`object`)return null;let n=e;return(0,t.readQuote)({symbol:n.symbol,last:Z(n.lastPrice),change:Z(n.priceChange),changePercent:Z(n.priceChangePercent),open:Z(n.openPrice),high:Z(n.highPrice),low:Z(n.lowPrice),prevClose:Z(n.prevClosePrice),volume:Z(n.volume),bid:Z(n.bidPrice),ask:Z(n.askPrice),time:Z(n.closeTime)})}function aC(e){if(!e||typeof e!=`object`)return null;let t=e,n=Z(t.T),r=Z(t.p),i=Z(t.q);return n!==void 0&&r!==void 0&&i!==void 0?{time:n,price:r,volume:i}:null}var oC=64,sC=(e,t)=>`${e}|${t}`,cC=class{last=new Map;serve(e,t,n){if(!Array.isArray(n)||n.length===0)return;let r=n[n.length-1],i=Number(r?.time);if(!Number.isFinite(i))return;let a=sC(e,t);this.last.delete(a),this.last.set(a,{time:i,close:Number(r?.close??NaN)}),this.last.size>oC&&this.last.delete(this.last.keys().next().value)}lastBar(e,t){return this.last.get(sC(e,t))}},lC=class{newest=-1/0;servedClose=null;served=new cC;serve(e,t,n){this.served.serve(e,t,n)}reset(e,n){let r=this.served.lastBar(e,n);this.newest=r===void 0?-1/0:(0,t.normalizeBarTime)(r.time),this.servedClose=r?.close??null}admit(e,n=!1){let r=(0,t.normalizeBarTime)(e.time);return Number.isFinite(r)?r<this.newest||r===this.newest&&n&&e.close===this.servedClose?!1:(this.servedClose=null,this.newest=r,!0):!0}},uC={"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`},dC=1e3,fC=200,pC=[`USDT`,`USDC`,`FDUSD`,`BTC`,`ETH`,`BNB`,`EUR`,`TRY`,`BRL`,`JPY`];function mC(e){let t=e.currency?pC.indexOf(e.currency):-1;return t<0?0:40-t*3}function hC(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 gC(e){let t=e?.symbols;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=hC(e);t&&n.push(t)}return n}var _C=class{name=`binance`;supportedTimeframes=Object.keys(uC);ws=null;state=`disconnected`;listeners=new Map;config=null;restBase;wsBase;symbolList=null;newestBar=new lC;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.newestBar.reset(e.symbol,e.timeframe),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}async fetchHistory(e,t,n=500){let r=await this.fetchKlines(e,t,n,``);return this.newestBar.serve(e,t,r),r}async searchSymbols(e,n){return(0,t.rankSymbols)(await this.loadSymbols(),e,n?.limit??50,mC)}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?gC(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 gC(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,fC);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(iC).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=rC(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(aC).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=aC(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,dC),`&endTime=${Math.floor(n)-1}`)}async fetchKlines(e,t,n,r){let i=uC[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=$S(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_${uC[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=eC(e);if(!t)return;let{bar:n,closed:r}=t,i=this.newestBar.admit(n,r);this.emitEvent(`bar`,{bar:n,closed:r}),i&&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)}}},vC=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+yC(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+yC(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+yC(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 yC(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t}var bC=class{name;supportedTimeframes;ws=null;state=`disconnected`;config=null;listeners=new Map;opts;newestBar=new lC;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.newestBar.reset(e.symbol,e.timeframe),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){let r=this.opts.fetchHistory(e,t,n??this.opts.defaultHistoryLimit??500);return Promise.resolve(r).then(n=>(this.newestBar.serve(e,t,n),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()}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}if(!r)return;let i=r.bar?this.newestBar.admit(r.bar,r.closed??!1):!1;r.bar&&this.emitEvent(`bar`,{bar:r.bar,closed:r.closed??!1}),r.tick?this.emitEvent(`tick`,r.tick):r.bar&&i&&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)}}},xC=class{name;supportedTimeframes;state=`disconnected`;listeners=new Map;config=null;timer=null;lastBarTime=0;served=new cC;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=this.served.lastBar(e.symbol,e.timeframe)?.time??0,this.state=`connected`,this.emitEvent(`connectionChange`,`connected`),this.startPolling()}disconnect(){this.stopPolling(),this.state=`disconnected`,this.emitEvent(`connectionChange`,`disconnected`)}getConnectionState(){return this.state}async fetchHistory(e,t,n){let r=await this.opts.fetchBars(e,t,n??this.opts.defaultHistoryLimit??500);return this.served.serve(e,t,r),r}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(!(n.time<this.lastBarTime)){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 Q(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 SC(e){return typeof e==`object`&&!!e}var CC={"1m":60,"5m":300,"15m":900,"1h":3600,"6h":21600,"1d":86400};function wC(e){return CC[e]??3600}var TC=class extends xC{constructor(e={}){let t=e.restBase??`https://api.exchange.coinbase.com`;super({name:`coinbase`,supportedTimeframes:Object.keys(CC),intervalMs:e.intervalMs??5e3,pollLimit:2,fetchBars:(e,n)=>EC(t,e,n)})}};async function EC(e,t,n){let r=`${e}/products/${t}/candles?granularity=${wC(n)}`,i=await fetch(r);if(!i.ok)throw Error(`Coinbase REST error: ${i.status}`);return DC(await i.json())}function DC(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=OC(n);e&&t.push(e)}return t.sort((e,t)=>e.time-t.time),t}function OC(e){if(!Array.isArray(e)||e.length<6)return null;let t=Q(e[0]),n=Q(e[1]),r=Q(e[2]),i=Q(e[3]),a=Q(e[4]),o=Q(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 kC={"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 AC(e){return kC[e]??`1`}var jC=class extends bC{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.${AC(e.timeframe)}.${e.symbol}`]}),unsubscribeMessage:e=>({op:`unsubscribe`,args:[`kline.${AC(e.timeframe)}.${e.symbol}`]}),supportedTimeframes:Object.keys(kC),parseMessage:MC,fetchHistory:(e,n,i)=>NC(t,r,e,n,i),fetchHistoryBefore:(e,n,i,a)=>NC(t,r,e,n,a,Math.floor(i)-1)})}};function MC(e){if(!SC(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(!SC(n))return null;let r=Q(n.start),i=Q(n.open),a=Q(n.high),o=Q(n.low),s=Q(n.close),c=Q(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 NC(e,t,n,r,i,a){let o=`${e}/v5/market/kline?category=${t}&symbol=${n}&interval=${AC(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 PC(await s.json())}function PC(e){if(!SC(e)||!SC(e.result))return[];let t=e.result.list;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=FC(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function FC(e){if(!Array.isArray(e)||e.length<6)return null;let t=Q(e[0]),n=Q(e[1]),r=Q(e[2]),i=Q(e[3]),a=Q(e[4]),o=Q(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 IC={"1m":1,"5m":5,"15m":15,"30m":30,"1h":60,"4h":240,"1d":1440,"1w":10080};function LC(e){return IC[e]??1}var RC=class extends bC{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:LC(e.timeframe)}}),unsubscribeMessage:e=>({method:`unsubscribe`,params:{channel:`ohlc`,symbol:[e.symbol],interval:LC(e.timeframe)}}),supportedTimeframes:Object.keys(IC),parseMessage:zC,fetchHistory:(e,n)=>BC(t,e,n)})}};function zC(e){if(!SC(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(!SC(n))return null;let r=Q(n.open),i=Q(n.high),a=Q(n.low),o=Q(n.close),s=Q(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 BC(e,t,n){let r=LC(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 VC(await o.json())}function VC(e){if(!SC(e)||!SC(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=HC(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function HC(e){if(!Array.isArray(e)||e.length<7)return null;let t=Q(e[0]),n=Q(e[1]),r=Q(e[2]),i=Q(e[3]),a=Q(e[4]),o=Q(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 UC=200,WC={"1m":`minutes/1`,"3m":`minutes/3`,"5m":`minutes/5`,"15m":`minutes/15`,"30m":`minutes/30`,"1h":`minutes/60`,"4h":`minutes/240`,"1d":`days`,"1w":`weeks`,"1M":`months`},GC={"1m":`candle.1m`,"3m":`candle.3m`,"5m":`candle.5m`,"15m":`candle.15m`,"30m":`candle.30m`,"1h":`candle.60m`,"4h":`candle.240m`,"1d":`ticker`};function KC(e){return WC[e]??null}function qC(e){return GC[e]??null}var JC=class extends bC{constructor(e={}){let t=e.restBase??`https://api.upbit.com`,n=e.wsUrl??`wss://api.upbit.com/websocket/v1`;super({name:`upbit`,wsUrl:()=>n,socketFactory:e.socketFactory??YC,decode:ZC,subscribeMessage:e=>[{ticket:`tradecanvas`},{type:qC(e.timeframe)??`candle.1m`,codes:[e.symbol]},{format:`DEFAULT`}],supportedTimeframes:Object.keys(GC),parseMessage:QC,fetchHistory:(e,n,r)=>tw(t,e,n,r),fetchHistoryBefore:(e,n,r,i)=>tw(t,e,n,i,r)})}};function YC(e){let t=globalThis.WebSocket;if(!t)throw Error(`No WebSocket implementation available`);let n=new t(e);return n.binaryType=`arraybuffer`,n}var XC=null;function ZC(e){if(typeof e==`string`)return JSON.parse(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return JSON.parse((XC??=new TextDecoder).decode(e))}function QC(e){if(!SC(e)||typeof e.type!=`string`)return null;if(e.type.startsWith(`candle.`)){let t=ew(e,e.candle_date_time_utc,e.candle_acc_trade_volume);return t?{bar:t,closed:!1}:null}if(e.type===`ticker`&&typeof e.trade_date==`string`&&/^\d{8}$/.test(e.trade_date)){let t=e.trade_date,n=ew(e,`${t.slice(0,4)}-${t.slice(4,6)}-${t.slice(6,8)}T00:00:00`,e.acc_trade_volume);return n?{bar:n,closed:!1}:null}return null}function $C(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=SC(n)?ew(n,n.candle_date_time_utc,n.candle_acc_trade_volume):null;e&&t.push(e)}return t.sort((e,t)=>e.time-t.time),t}function ew(e,t,n){let r=typeof t==`string`?Date.parse(`${t}Z`):NaN,i=Q(e.opening_price),a=Q(e.high_price),o=Q(e.low_price),s=Q(e.trade_price),c=Q(n);return!Number.isFinite(r)||i===null||a===null||o===null||s===null||c===null?null:{time:r,open:i,high:a,low:o,close:s,volume:c}}async function tw(e,t,n,r,i){let a=KC(n);if(!a)throw Error(`Upbit has no ${n} candles`);let o=new URLSearchParams({market:t,count:String(Math.min(Math.max(Math.floor(r),1),200))});i!==void 0&&o.set(`to`,new Date(i).toISOString().replace(/\.\d{3}Z$/,`Z`));let s=await fetch(`${e}/v1/candles/${a}?${o}`);if(!s.ok)throw Error(`Upbit REST error: ${s.status}`);return $C(await s.json())}var nw=(e,t)=>`${e}\u0000${t}`,rw=class{name;series=new Map;subscribers=new Map;constructor(e={}){this.name=e.name??`manual`}setBars(e,t,n){let r=n.map(e=>({...e})).sort((e,t)=>e.time-t.time);this.series.set(nw(e,t),r)}pushBar(e,t,n,r=!1){let i=nw(e,t),a=this.series.get(i)??[],o=a[a.length-1],s={...n},c=r;if(!o||s.time>o.time)this.series.set(i,[...a,s]);else{let n=a.findIndex(e=>e.time===s.time);if(n<0)throw RangeError(`ManualFeed: no ${e} ${t} bar at ${s.time} to replace`);n<a.length-1&&(c=!0),this.series.set(i,a.map((e,t)=>t===n?s:e))}for(let e of[...this.subscribers.get(i)??[]])e.bar({...s},c)}async getBars(e){let t=this.series.get(nw(e.symbol,e.timeframe))??[],{before:n}=e,r=n===void 0?t.length:iw(t,n);return t.slice(Math.max(0,r-e.countBack),r).map(e=>({...e}))}subscribeBars(e,t){let n=nw(e.symbol,e.timeframe),r=this.subscribers.get(n);return r||(r=new Set,this.subscribers.set(n,r)),r.add(t),()=>{r.delete(t),r.size===0&&this.subscribers.delete(n)}}};function iw(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].time<t?n=i+1:r=i}return n}var aw={visible:!0,showSymbol:!0,showOHLC:!0,showChange:!0,showVolume:!0,position:`top-left`,fontSize:12,fontFamily:null,ground:!0},ow=class{config={...aw};symbol=``;timeframe=``;hoverBar=null;hoverPrev=null;indicators=[];statusText=null;exchange=``;drawnHeight=null;drawnWidth=0;locale=`en-US`;inset=cw;top=sw;lineGap=lw;pricePrecision=null;reportedHeight=null;resizeListener=null;setResizeListener(e){this.resizeListener=e}forgetHeight(){this.drawnHeight=null,this.reportedHeight=null}reportResize(){let e=this.getHeight();e!==this.reportedHeight&&(this.reportedHeight=e,this.resizeListener?.())}setConfig(e){Object.assign(this.config,e),this.forgetHeight()}getConfig(){return{...this.config}}setPricePrecision(e){this.pricePrecision=e}setLocale(e){this.locale=e}setSymbol(e){e!==this.symbol&&(this.symbol=e,this.forgetHeight())}setTimeframe(e){e!==this.timeframe&&(this.timeframe=e,this.forgetHeight())}setChartType(e){}setHoverBar(e,t=null){this.hoverBar=e,this.hoverPrev=e?t:null}setIndicatorValues(e){this.indicators=e}setStatusText(e){e!==this.statusText&&(this.statusText=e,this.forgetHeight())}setExchange(e){e!==this.exchange&&(this.exchange=e,this.forgetHeight())}title(){return this.config.showSymbol?[(0,t.tickerOf)(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:mw(e,t.value),font:l}))}setSpacing(e){e.inset===this.inset&&e.top===this.top&&e.lineGap===this.lineGap||(this.inset=e.inset,this.top=e.top,this.lineGap=e.lineGap,this.drawnHeight=null)}getInset(){return this.inset}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=this.top;return(this.config.showOHLC||this.title()||this.statusText)&&(t+=e+this.lineGap),this.config.showVolume&&(t+=e+2),t}getWidth(){return!this.config.visible||this.config.position!==`top-left`?0:this.drawnWidth}render(e,n,r,i){if(!this.config.visible)return this.reportResize();if(i.length===0)return;let a=this.hoverBar??i[i.length-1],o=this.hoverBar?this.hoverPrev??a:i.length>1?i[i.length-2]:a,{chartRect:s}=n,c=this.config.fontSize,l=this.config.fontFamily??r.font.family,u=r.style?.legend.text??r.text,d=r.style?.legend.label??r.textSecondary,f=this.config.position===`top-left`,p=f?s.x+this.inset:s.x+s.width-this.inset,m=s.y+this.top;e.textAlign=f?`left`:`right`,e.textBaseline=`top`;let h=0,g=this.titleCells(e,c,l,u,d);if(this.config.showOHLC&&g.push(...this.priceCells(e,n,r,a,o,c,l,u)),g.length>0){e.font=`${c}px ${l}`;let t=e.measureText(` `).width;for(let n of pw(g,t,s.width-2*this.inset)){let i=n.reduce((e,n)=>e+n.labelWidth+n.width+t,-t);h=Math.max(h,i);let a=f?p:p-i;this.drawGround(e,r,a,m,i,c),e.textAlign=`left`;for(let r of n)e.font=r.font,r.label&&(e.fillStyle=d,e.fillText(r.label,a,m),a+=r.labelWidth),e.fillStyle=r.color,e.fillText(r.value,a,m),a+=r.width+t;m+=c+this.lineGap}e.textAlign=f?`left`:`right`}if(this.config.showVolume){e.font=`${c}px ${l}`,e.fillStyle=d;let n=(0,t.formatVolumeLoc)(a.volume,this.locale),i=e.measureText(`Vol ${n}`).width;this.drawGround(e,r,f?p:p-i,m,i,c),e.fillStyle=d,e.fillText(`Vol ${n}`,p,m),h=Math.max(h,i),m+=c+2}if(this.drawnHeight=f?m-s.y:null,this.drawnWidth=f?this.inset+h:0,this.reportResize(),this.indicators.length>0){e.font=`${c}px ${l}`;let t=e.measureText(` `).width,n=this.indicators.map(t=>{let n=`${t.name} ${t.value}`;return{entry:n,color:t.color,width:mw(e,n)}}),i=n.reduce((e,n)=>e+n.width+t,-t),a=f?p:p-i;this.drawGround(e,r,a,m,i,c),e.textAlign=`left`;for(let{entry:r,color:i,width:o}of n)e.fillStyle=i,e.fillText(r,a,m),a+=o+t}}drawGround(e,t,n,r,i,a){!this.config.ground||i<=0||(e.save(),e.globalAlpha=uw,e.fillStyle=t.background,e.fillRect(n-dw,r-fw,i+2*dw,a+this.lineGap),e.restore())}},{legendTop:sw,legendInset:cw,legendLineGap:lw}=t.CHART_SPACING[t.DEFAULT_CHART_DENSITY],uw=.72,dw=3,fw=1;function pw(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 mw(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 hw=class{static toDataURL(e,t){return this.compose(e,t)?.toDataURL(`image/png`)??``}static async toBlob(e,t){let n=this.compose(e,t);return n?new Promise(e=>n.toBlob(e,`image/png`)):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)}static compose(e,t){let n=e.querySelectorAll(`canvas`);if(n.length===0)return null;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}},gw=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()}},_w={solid:null,dashed:[6,4],dotted:[2,3]},vw=6;function yw(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 bw=class{config={visible:!1};cachedBreaksTyped=[];cachedMedianStep=0;cacheValid=!1;lastDataLength=0;firstTime=NaN;lastTime=NaN;tz=null;setConfig(e){Object.assign(this.config,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[];let n=this.lastDataLength,r=this.cacheValid&&e.length>=n&&e[0].time===this.firstTime&&e[n-1].time===this.lastTime;if(r&&e.length===n)return this.cachedBreaksTyped;let i=r?this.cachedBreaksTyped.slice():[],a=(0,t.barTimeUnit)(e),o=r?n:1,s=(0,t.timeParts)(e[o-1].time*a,this.tz);for(let n=o;n<e.length;n++){let r=(0,t.timeParts)(e[n].time*a,this.tz);if(r.year!==s.year)i.push({idx:n,kind:`year`});else if(r.month!==s.month)i.push({idx:n,kind:`month`});else if(r.day!==s.day){let e=new Date(Date.UTC(r.year,r.month-1,r.day)).getUTCDay()===1;i.push({idx:n,kind:e?`week`:`day`})}s=r}return this.lastDataLength=e.length,this.firstTime=e[0].time,this.lastTime=e[e.length-1].time,this.cachedBreaksTyped=i,r||(this.cachedMedianStep=xw(e)),this.cacheValid=!0,i}render(e,t,n,r){this.renderLines(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=_w[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()}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=_w[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 yw(this.marks(e,t,n),vw)}marks(t,n,r){if(!this.config.visible||n.length<2)return[];let i=this.computeBreaksTyped(n);if(i.length===0||this.cachedMedianStep>=1380*60*1e3)return[];let{chartRect:a}=t,o=this.look(r).width,s=[];for(let n of i){let r=e.C(n.idx,t)-(t.barWidth+t.barSpacing)/2;if(r<a.x-1||r>a.x+a.width+1)continue;let i=Math.round(r)+.5,c=.25,l=o,u=3;n.kind===`day`?(c=.22,u=0):n.kind===`week`?(c=.34,u=1):n.kind===`month`?(c=.5,u=2,l=o+.5):(c=.7,l=o+1),s.push({px:i,width:l,alpha:c,rank:u})}return s}invalidateCache(){this.lastDataLength=0,this.cachedBreaksTyped=[],this.cachedMedianStep=0,this.cacheValid=!1}};function xw(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 Sw=864e5;function Cw(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 ww(e,t){let n=((e+t*6e4)%Sw+Sw)%Sw;return Math.floor(n/6e4)}function Tw(e,t,n){return t===n?!0:t<n?e>=t&&e<n:e>=t||e<n}function Ew(e,n){let r=ww(e,n.timeZone?(0,t.zoneOffsetMinutes)(n.timeZone,e):n.tzOffsetMinutes??0);return n.windows&&n.windows.length>0?n.windows.some(e=>Tw(r,e.startMinute,e.endMinute)):Tw(r,n.startMinute,n.endMinute)}var Dw={startMinute:570,endMinute:960,tzOffsetMinutes:-300,timeZone:`America/New_York`},Ow=class{visible=!1;config={...Dw};setVisible(e){this.visible=e}isVisible(){return this.visible}setConfig(e){this.config=Cw(this.config,e)}replaceConfig(e){this.config=Cw(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.C(t,n)-l/2,o=e.C(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=!Ew(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}},kw=[2,3],Aw=16,jw=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(kw),t.lineWidth=1;for(let o of this.levels(i,n)){let i=Math.round(e.O(o.price,n))+.5;i<a.y||i>a.y+a.height||(t.strokeStyle=Mw(o.kind,r),t.beginPath(),e.y(t,a.x,a.x+a.width,i),t.stroke())}t.restore()}renderAxisTags(n,r,i,a,o){let{chartRect:s}=r,c=s.x+s.width+1,l=(r.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,u=(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 d of this.levels(a,r)){let a=e.O(d.price,r);if(a<s.y||a>s.y+s.height)continue;let f=o?.get(d.kind)??a;if(Number.isNaN(f))continue;n.fillStyle=Mw(d.kind,i),k(n,c,f-Aw/2,l,Aw,i),n.fillStyle=i.background;let p=r.formatPrice?.(d.price)??this.priceText?.(d.price)??(0,t.formatPrice)(d.price,u);n.fillText(p,c+5,f)}n.restore()}};function Mw(e,t){switch(e){case`bid`:return t.candleUp;case`ask`:return t.candleDown;default:return t.style?.highLow.color??t.textSecondary}}var Nw=12,Pw=3,Fw=500,Iw=2,Lw=[`movesUp`,`movesDown`];function Rw(e){return e.channel===`price`&&!e.drawingId&&!e.target&&!Lw.includes(e.condition)}function zw(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 Bw=[`crossing`,`crossingUp`,`crossingDown`];function Vw(e,t,n){let r=e<0&&t>=0,i=e>0&&t<=0;return n===`crossingUp`?r:n===`crossingDown`?i:r||i}var Hw=1,Uw=2**31-1,Ww=class extends Zx{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=Gw(t,i,o),c=`tc_alert_${Hw++}`,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(!Bw.includes(t))throw RangeError(`An alert on a drawing takes a crossing condition, not "${t}"`);let a=`tc_alert_${Hw++}`,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(!Rw(r))continue;let i=Math.abs(e.O(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()),Uw);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)=>Vw(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(Lw.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=zw(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,zw(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(Lw.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 zw(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}seedLastValue(e,t){Number.isFinite(t)&&this.lastValues.set(e,t)}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){Bw.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=Kw(e),n=!t.target&&!Lw.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(!Rw(o))continue;let s=e.O(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(),e.y(n,a.x,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-Pw-Nw;d>=a.x&&Fb(n,t.UI_ICONS.bell,d,s-2-Nw,Nw,c)}}};function Gw(e,t,n){let r={},i=Lw.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 Kw(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 qw=16,Jw=3*qw,Yw=1e3/30,Xw=1e-9,Zw=()=>typeof requestAnimationFrame==`function`&&!(typeof document<`u`&&document.hidden),Qw={now:()=>typeof performance<`u`?performance.now():Date.now(),frame:e=>Zw()?{raf:requestAnimationFrame(e)}:{timeout:setTimeout(e,qw)},cancel:e=>{let t=e;t.raf!==void 0&&cancelAnimationFrame(t.raf),t.timeout!==void 0&&clearTimeout(t.timeout)}},$w=class extends Zx{data=[];cursor=-1;timer=null;frameHandle=null;run=0;state=`stopped`;config={speed:1,interval:500};paceMs=null;owedMs=0;constructor(e=Qw){super(),this.clock=e}load(e){this.stop(),this.data=e,this.cursor=-1,this.owedMs=0}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.owedMs=0),this.setPace(r)}if(this.isAtEnd()){this.clearTimer(),this.setState(`paused`);return}this.clearTimer();let t=this.stepMs();if(!(t>0)||!Number.isFinite(t)){this.setState(`paused`);return}this.setState(`playing`),this.config.animate?this.runForming(t):t<qw||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.owedMs=0,this.setState(`stopped`)}seekTo(e){this.data.length!==0&&(this.cursor=this.clamp(e),this.owedMs=0,this.emit(`bar`,{bar:this.data[this.cursor],index:this.cursor,total:this.data.length}))}setSpeed(e){let t=this.getFraction();this.config={...this.config,speed:e},this.paceMs=null;let n=this.stepMs();this.owedMs=n>0&&Number.isFinite(n)?t*n:0,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}}remainingMs(){return this.paceMs===null?null:this.paceMs*Math.max(0,this.data.length-1-this.cursor)}getStepMs(){return this.stepMs()}getFraction(){let e=this.stepMs();return e>0&&Number.isFinite(e)?Math.min(1,this.owedMs/e):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)}stepMs(){return this.paceMs??this.config.interval/this.config.speed}runForming(e){let t=this.run,n=e>=Jw,r=this.clock.now(),i=-1/0,a=r=>{!n||this.isAtEnd()||t!==this.run||this.state!==`playing`||(i=r,this.emit(`phase`,{index:this.cursor+1,fraction:Math.min(1,this.owedMs/e)}))},o=()=>{if(t!==this.run||this.state!==`playing`)return;this.frameHandle=null;let n=this.clock.now();this.owedMs+=Math.min(50,Math.max(0,n-r)),r=n;let s=Math.floor((this.owedMs+Xw)/e);try{s>0?(this.owedMs=Math.max(0,this.owedMs-s*e),this.advance(s),a(n)):n-i+qw/2>=Yw&&a(n)}finally{t===this.run&&this.state===`playing`&&this.frameHandle===null&&(this.frameHandle=this.clock.frame(o))}};a(r),this.frameHandle=this.clock.frame(o)}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))}},eT=64,tT=3,nT=3;function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rT(e){return Array.isArray(e)?e:[]}function iT(e,t){return typeof e==`string`?e:t}function aT(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function oT(e){if(!$(e)||typeof e.id!=`string`||typeof e.type!=`string`||!Array.isArray(e.anchors)||e.anchors.length===0||e.anchors.length>sT||!$(e.style))return null;let n=[];for(let t of e.anchors){if(!$(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:$(e.options)?e.options:void 0,intervals:Ma(e.intervals)??void 0,group:dT(e.group),...Rp(e.name)===void 0?{}:{name:Rp(e.name)},...typeof e.paneId==`string`&&e.paneId.length>0&&e.paneId.length<=cT?{paneId:e.paneId}:{},meta:$(e.meta)?e.meta:void 0}}var sT=5e3,cT=200,lT=64,uT=80;function dT(e){if(!(!$(e)||typeof e.id!=`string`||typeof e.name!=`string`)&&!(e.id===``||e.id.length>lT))return{id:e.id,name:e.name.slice(0,uT)}}function fT(e){return!$(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.type!=`string`||typeof e.price!=`number`||typeof e.quantity!=`number`?null:e}function pT(e){if(!$(e))return;let n={},r=rT(e.colors).filter(e=>typeof e==`string`);r.length>0&&(n.colors=r);let i=rT(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 mT=[`crossingUp`,`crossingDown`,`crossing`,`greaterThan`,`lessThan`,`movesUp`,`movesDown`];function hT(e){if(!$(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=mT.find(t=>t===e.condition)??`crossing`,i=Kw(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:iT(e.channel,`price`),label:typeof e.label==`string`?e.label:void 0,...i,...e.expired===!0?{expired:!0}:{}}}function gT(e){return!$(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.entryPrice!=`number`||typeof e.quantity!=`number`?null:e}var _T=4e3;function vT(e){if(!$(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,eT)]=o)}return r.length>0&&console.warn(`Saved style overrides left out: ${[...new Set(r)].join(`, `)}`),n}function yT(e){if(!$(e))return bT();typeof e.version==`number`&&e.version>nT&&console.warn(`Chart state from a newer version (${e.version}); loading what this version understands.`);let n=$(e.viewport)?e.viewport:{},r=[];for(let n of rT(e.indicators))$(n)&&(typeof n.id!=`string`||typeof n.instanceId!=`string`||$(n.params)&&r.push({id:n.id,instanceId:n.instanceId,params:n.params,position:typeof n.position==`string`?n.position:void 0,style:pT(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:Ma(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,_T):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 rT(e.drawings)){let e=oT(t);e&&i.push(e)}let a=[];for(let t of rT(e.orders)){let e=fT(t);e&&a.push(e)}let o=[];for(let t of rT(e.positions)){let e=gT(t);e&&o.push(e)}let s=[];for(let t of rT(e.alerts)){let e=hT(t);e&&s.push(e)}let c=vT(e.overrides);return{version:typeof e.version==`number`&&Array.isArray(e.indicators)?e.version:1,timestamp:aT(e.timestamp,Date.now()),symbol:typeof e.symbol==`string`?e.symbol:void 0,timeframe:typeof e.timeframe==`string`?e.timeframe:void 0,chartType:iT(e.chartType,`candlestick`),...e.chartTypeOptions===void 0?{}:{chartTypeOptions:(0,t.readChartTypeOptions)(e.chartTypeOptions)},viewport:{barWidth:aT(n.barWidth,8),barSpacing:aT(n.barSpacing,2),offset:aT(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 bT(){return{version:1,timestamp:Date.now(),chartType:`candlestick`,viewport:{barWidth:8,barSpacing:2,offset:0},indicators:[],drawings:[],orders:[],positions:[],alerts:[]}}var xT=class{static capture(e,t){return{version:e.getIndicators?nT: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 yT(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()})}},ST=class{undoStack=[];redoStack=[];maxHistory=50;onChange=null;grouped=null;setOnChange(e){this.onChange=e}push(e){if(this.grouped){this.grouped.push(e);return}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?.()}group(e){if(this.grouped)return e();let t=[];this.grouped=t;try{return e()}finally{this.grouped=null,t.length===1?this.push(t[0]):t.length>1&&this.push({type:`drawingBatch`,before:null,after:null,actions:t})}}last(){return this.grouped?this.grouped[this.grouped.length-1]??null:this.undoStack[this.undoStack.length-1]??null}dropLast(){if(this.grouped){this.grouped.pop();return}this.undoStack.pop()&&(this.redoStack.length=0,this.onChange?.())}replaceLast(e){if(this.grouped){this.grouped.length>0?this.grouped[this.grouped.length-1]=e:this.grouped.push(e);return}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}}},CT=[`Time`,`Open`,`High`,`Low`,`Close`,`Volume`];function wT(e,n){return new Date((0,t.normalizeBarTime)(e,n)).toISOString()}function TT(e){let t=/^[=+\-@\t\r]/.test(e)&&!/^-?\d/.test(e)?`'${e}`:e;return/[",\r\n]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}var ET=15,DT=0x38d7ea4c68000;function OT(e){return e==null||!Number.isFinite(e)?null:Number.isInteger(e)||Math.abs(e)>=DT?e:Number(e.toPrecision(ET))}var kT=e=>{let t=OT(e);return t===null?``:String(t)},AT=class{static toCSV(e,n=[]){let r=[...CT,...n.map(e=>TT(e.name))].join(`,`),i=(0,t.barTimeUnit)(e);return[r,...e.map((e,t)=>[wT(e.time,i),...[e.open,e.high,e.low,e.close,e.volume].map(kT),...n.map(e=>kT(e.values[t]))].join(`,`))].join(`
|
|
25
|
-
`)}static toJSON(e,n=[]){let r=(0,t.barTimeUnit)(e);return JSON.stringify(e.map((e,t)=>{let i={time:wT(e.time,r),open:OT(e.open),high:OT(e.high),low:OT(e.low),close:OT(e.close),volume:OT(e.volume)};for(let e of n)i[e.name]=OT(e.values[t]);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 jT(e,t,n=-1/0){return t===null?e:e.filter(e=>e.time>=n&&e.time<t)}function MT(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 NT=1,PT=3,FT=class extends Zx{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_${NT++}`,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[...jT(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=jT(this.markers,this.revealUntil,this.revealFrom);for(let i=o.length-1;i>=0;i--){let s=o[i],c=e.C(e.M(s.time,r),n),l=e.O(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+PT&&t.y>=d-PT&&t.y<=f+PT)return s}return null}render(t,n,r){let i=this.dataGetter?.(),a=jT(this.markers,this.revealUntil,this.revealFrom);if(!i||i.length===0||a.length===0)return;let{chartRect:o}=n,s=Ux(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.C(e.M(l.time,i),n),u=e.O(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()}},IT=12,LT=2,RT=1,zT=class extends Zx{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_${RT++}`,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[...MT(this.zones,this.revealUntil,this.revealFrom)]}render(e,t,n){let r=this.dataGetter?.(),i=MT(this.zones,this.revealUntil,this.revealFrom);if(!r||r.length===0||i.length===0)return;let{chartRect:a}=t,o=Wx(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.M(r.entryTime,i),u=r.exitTime==null?i.length-1:e.M(r.exitTime,i),d=e.C(l,a),f=e.C(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.O(r.entryPrice,a),g=r.exitPrice==null?e.O(r.entryPrice,a):e.O(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([])),Fb(n,r.direction===`long`?t.UI_ICONS.trendingUp:t.UI_ICONS.trendingDown,p+4,h-3-IT,IT,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+IT+3,h-3),s.showPnl&&!y&&r.pnl!=null){let e=r.pnl>=0?`+`:``,i=e=>(0,t.formatPrice)(e,LT,a.numberLocale??`en-US`),s=r.pnlPercent==null?`${e}${i(r.pnl)}`:`${e}${i(r.pnl)} (${e}${i(r.pnlPercent)}%)`;n.font=`bold 10px ${o.font.family}`,n.fillStyle=x,n.textBaseline=`top`,n.textAlign=`right`;let c=n.measureText(s).width+8,l=m-c-2,u=_+2;n.globalAlpha=.85,n.fillStyle=o.background,k(n,l,u,c,14,o),n.globalAlpha=1,n.fillStyle=x,n.fillText(s,m-4,u+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)}},BT=2,VT=4,HT=10,UT=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.N(t.x,n)),a=e.F(t.y,n);this.startBar=i,this.startPrice=a,this.endBar=i,this.endPrice=a,this.startTime=WT(i,r),this.endTime=this.startTime,this.active=!0}update(t,n,r){if(!this.active)return;let i=Math.round(e.N(t.x,n));this.endBar=i,this.endPrice=e.F(t.y,n),this.endTime=WT(i,r)}end(){this.active=!1}render(n,r,i){if(!this.active)return;let a=e.C(this.startBar,r),o=e.C(this.endBar,r),s=e.O(this.startPrice,r),c=e.O(this.endPrice,r),l=Math.min(a,o),u=Math.max(a,o),d=Math.min(s,c),f=Math.max(s,c),p=u-l,m=f-d,h=this.endPrice>=this.startPrice?i.candleUp:i.candleDown,g=ZT(h,.14);n.save();let{chartRect:_}=r;n.beginPath(),n.rect(_.x,_.y,_.width,_.height),n.clip(),n.fillStyle=g,n.fillRect(l,d,p,m),n.strokeStyle=h,n.lineWidth=1,n.setLineDash([4,3]),n.strokeRect(l+.5,d+.5,p,m),n.setLineDash([]),n.strokeStyle=h,n.lineWidth=1.5,n.beginPath(),n.moveTo(a,s),n.lineTo(o,c),n.stroke(),JT(n,a,s,h),JT(n,o,c,h),n.restore();let v=Math.abs(this.endBar-this.startBar),y=this.endPrice-this.startPrice,b=this.startPrice===0?0:y/this.startPrice*100,x=this.startTime!==null&&this.endTime!==null?qT(Math.abs(this.endTime-this.startTime)):null,S=[],C=y>0?`+`:y<0?`−`:``,w=Math.abs(y),T=(0,t.formatPrice)(Math.abs(b),BT,r.numberLocale??`en-US`);S.push(`${C}${GT(w,r)} (${C}${T}%)`),S.push(`${v} bars${x?` · `+x:``}`),n.save(),YT(n,o,c,S,h,i),n.restore()}};function WT(e,n){return e<0||e>=n.length?null:n[e].time*(0,t.barTimeUnit)(n)}function GT(e,n){return(0,t.priceTagText)(e,n,n.pricePrecision??KT(e))}function KT(e){return e>=1e3?2:e>=1?4:e<=0?VT-1:Math.min(HT,VT-1-Math.floor(Math.log10(e)))}function qT(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 JT(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 YT(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,XT(e,l,u,s,c,6),e.fill(),e.globalAlpha=1,e.strokeStyle=i,e.lineWidth=1,XT(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 XT(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 ZT(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 QT=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()}},eE={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)},tE=class{animations=new Map;frameId=0;running=!1;animate(e,t){this.animations.set(e,{startTime:-1,duration:t.duration,easing:t.easing??eE.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 nE(e){return!e||e===`dark`?t.DARK_THEME:e===`light`?t.LIGHT_THEME:e}var rE=class{canvas;ctx;container;theme;width=0;height=0;dpr=1;frameId=null;resizeObserver;constructor(e,t){this.container=e,this.theme=nE(t),this.canvas=document.createElement(`canvas`),this.canvas.style.width=`100%`,this.canvas.style.height=`100%`,this.canvas.style.display=`block`,s(this.canvas),this.canvas.setAttribute(`role`,`img`),e.appendChild(this.canvas),this.ctx=this.canvas.getContext(`2d`),this.dpr=r(),this.updateSize(),this.resizeObserver=new ResizeObserver(()=>{this.updateSize(),this.requestRender()}),this.resizeObserver.observe(e)}updateSize(){this.dpr=r();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())}))}applyBaseOptions(e){`theme`in e&&(this.theme=nE(e.theme)),e.ariaLabel!==void 0&&this.setLabel(e.ariaLabel)}setLabel(e){this.canvas.setAttribute(`aria-label`,e)}setTheme(e){this.theme=nE(e),this.requestRender()}destroy(){this.frameId!==null&&cancelAnimationFrame(this.frameId),this.resizeObserver.disconnect(),this.canvas.width=0,this.canvas.height=0,this.canvas.remove()}},iE=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 aE(e,n,r,i,a){let{data:o,mode:s=`area`,lineWidth:c=1.5,showLastPoint:l=!1,showMinMax:u=!1}=i;if(o.length<2||n<=0||r<=0)return;let d=i.color??a.lineColor,f=i.fillColor??d,p=n-4,m=r-4,h=1/0,g=-1/0,_=0,v=0;for(let e=0;e<o.length;e++)o[e]<h&&(h=o[e],_=e),o[e]>g&&(g=o[e],v=e);let y=g-h||1,b=e=>2+e/(o.length-1)*p,x=e=>2+m-(e-h)/y*m;if(s===`area`){let n=e.createLinearGradient(0,2,0,r-2);n.addColorStop(0,(0,t.withAlpha)(f,Hd)),n.addColorStop(1,`transparent`),e.beginPath(),e.moveTo(b(0),x(o[0]));for(let t=1;t<o.length;t++)e.lineTo(b(t),x(o[t]));e.lineTo(b(o.length-1),r-2),e.lineTo(b(0),r-2),e.closePath(),e.fillStyle=n,e.fill()}e.beginPath(),e.moveTo(b(0),x(o[0]));for(let t=1;t<o.length;t++)e.lineTo(b(t),x(o[t]));if(e.strokeStyle=d,e.lineWidth=c,e.lineJoin=`round`,e.stroke(),l){let t=i.lastPointColor??d,n=b(o.length-1),r=x(o[o.length-1]);e.beginPath(),e.arc(n,r,3,0,Math.PI*2),e.fillStyle=t,e.fill()}if(u){let t=i.minPointColor??a.candleDown,n=i.maxPointColor??a.candleUp;e.beginPath(),e.arc(b(_),x(h),2.5,0,Math.PI*2),e.fillStyle=t,e.fill(),e.beginPath(),e.arc(b(v),x(g),2.5,0,Math.PI*2),e.fillStyle=n,e.fill()}}var oE=50,sE=60,cE=20,lE=.2,uE=.01;function dE(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 fE(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 pE(e,t){return e.length===1?[e[0],{price:t,cumulativeVolume:e[0].cumulativeVolume}]:e}function mE(e,t){return{left:oE,right:e-sE,top:cE,bottom:t-cE,plotWidth:e-oE-sE,plotHeight:t-cE*2}}function hE(e,t,n,r){e.fillStyle=r,e.fillRect(0,0,t,n)}function gE(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(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 vE(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 yE(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 bE(e){return e.toFixed(2)}function xE(e){return e>=1e6?(e/1e6).toFixed(2)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:e.toFixed(0)}function SE(e,n,r,i,a,o){let{data:s}=i;if(n<=0||r<=0)return;if(s.bids.length===0&&s.asks.length===0){hE(e,n,r,a.background);return}let c=i.bidColor??a.candleUp,l=i.askColor??a.candleDown,u=i.bidFillColor??(0,t.withAlpha)(c,.25),d=i.askFillColor??(0,t.withAlpha)(l,.25),f=i.midPriceLine!==!1,p=i.spreadLabel!==!1,m=i.priceFormat??bE,h=i.volumeFormat??xE,g=dE(s.bids),_=fE(s.asks),v=g.length>0?g[0].price:0,y=_.length>0?_[0].price:0,b=g.length>0&&_.length>0?(v+y)/2:v||y,x=_.length>0&&g.length>0?y-v:0,S=g.length>0?g[g.length-1].price:b,C=_.length>0?_[_.length-1].price:b,w=(Math.max(b-S,C-b)||Math.abs(b)*uE||1)*(1+lE),T=b-w,E=b+w,D=E-T,ee=g.length>0?g[g.length-1].cumulativeVolume:0,O=_.length>0?_[_.length-1].cumulativeVolume:0,k=Math.max(ee,O)||1,A=mE(n,r);hE(e,n,r,a.background),gE(e,A,T,E,k,a,m,h),_E(e,pE(g,T),A,T,D,k,u,c,`bid`),_E(e,pE(_,E),A,T,D,k,d,l,`ask`),f&&g.length>0&&_.length>0&&vE(e,b,x,A,T,D,a,p,m),o&&yE(e,o,g,_,A,T,D,k,a,m,h)}var CE=70,wE=30,TE=20,EE=20,DE=.05,OE=.19;function kE(e,t){return{left:CE,right:e-TE,top:EE,bottom:t-wE,plotWidth:e-CE-TE,plotHeight:t-EE-wE}}function AE(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)*DE||Math.abs(r)*DE||1;return{valMin:n-i,valMax:r+i}}function jE(e,t){let n=-1,r=1/0;for(let i=0;i<e.length;i++){let a=Math.abs(e[i].time-t);a<r&&(r=a,n=i)}return n}function ME(e){let t=[],n=-1/0;for(let r of e)r.value>n&&(n=r.value),t.push(n);return t}function NE(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 PE(e){return Math.abs(e)>=1e6?(e/1e6).toFixed(2)+`M`:Math.abs(e)>=1e3?(e/1e3).toFixed(1)+`K`:e.toFixed(2)}function FE(e,t,n,r){e.fillStyle=r,e.fillRect(0,0,t,n)}function IE(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 LE(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 RE(e,n,r,i,a,o,s,c){if(n.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,h=e.createLinearGradient(0,r.top,0,u);h.addColorStop(0,(0,t.withAlpha)(c,Hd)),h.addColorStop(1,`transparent`),e.save(),e.beginPath(),e.moveTo(p(n[0].time),m(n[0].value));for(let t=1;t<n.length;t++)e.lineTo(p(n[t].time),m(n[t].value));e.lineTo(p(n[n.length-1].time),u),e.lineTo(p(n[0].time),u),e.closePath(),e.fillStyle=h,e.fill(),e.restore()}function zE(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 BE(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=r+i,h=t[t.length-1],g=h.time>m?t[jE(t,m)]??h:h,_=Math.min(n.right,Math.max(u,u+(g.time-r)/i*f)),v=d-(g.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,_+4,v),e.restore()}function VE(e,t,n,r,i,a,o,s,c,l,u,d,f){let{left:p,top:m,bottom:h,plotWidth:g,plotHeight:_}=i,v=t.x;if(v<p||v>i.right)return;e.save(),e.strokeStyle=l.crosshair,e.lineWidth=.5,e.setLineDash([4,4]),e.beginPath(),e.moveTo(v,m),e.lineTo(v,h),e.stroke(),e.restore();let y=n[jE(n,a+(v-p)/g*o)];if(!y)return;let b=[u(y.time),`Value: ${d(y.value)}`],x=r?jE(r,y.time):-1;r&&x>=0&&b.push(`Benchmark: ${d(r[x].value)}`);let S=p+(y.time-a)/o*g,C=h-(y.value-s)/c*_;e.beginPath(),e.arc(S,C,3,0,Math.PI*2),e.fillStyle=f,e.fill(),e.save(),e.font=`${l.font.sizeSmall}px ${l.font.family}`;let w=Math.max(...b.map(t=>e.measureText(t).width))+16,T=b.length*(l.font.sizeSmall+4)+12,E=v+10,D=t.y-T/2;E+w>i.right&&(E=v-w-10),D<m&&(D=m),D+T>h&&(D=h-T),e.fillStyle=l.axisLabelBackground,e.globalAlpha=.9,e.fillRect(E,D,w,T),e.globalAlpha=1,e.fillStyle=l.text,e.textBaseline=`top`,e.textAlign=`left`;for(let t=0;t<b.length;t++)e.fillText(b[t],E+8,D+6+t*(l.font.sizeSmall+4));e.restore()}function HE(e,n,r,i,a,o){let{data:s}=i;if(n<=0||r<=0)return;if(s.length<2){FE(e,n,r,a.background);return}let c=i.lineColor??a.lineColor,l=i.lineWidth??1.5,u=i.drawdown===!0,d=i.drawdownColor??(0,t.withAlpha)(a.candleDown,OE),f=i.fillArea===!0,p=i.benchmark,m=i.benchmarkColor??a.textSecondary,h=i.benchmarkLabel??`Benchmark`,g=i.valueFormat??PE,{valMin:_,valMax:v}=AE(s,p),y=v-_||1,b=s[0].time,x=s[s.length-1].time,S=x-b||1,C=i.timeFormat??NE(S),w=kE(n,r);FE(e,n,r,a.background),IE(e,w,_,v,b,x,a,g,C),u&&zE(e,s,ME(s),w,b,S,_,y,d),f&&RE(e,s,w,b,S,_,y,c),LE(e,s,w,b,S,_,y,c,l),p&&p.length>=2&&(e.save(),e.beginPath(),e.rect(w.left,w.top,w.plotWidth,w.plotHeight),e.clip(),LE(e,p,w,b,S,_,y,m,1),e.restore(),BE(e,p,w,b,S,_,y,h,m,a)),o&&VE(e,o,s,p,w,b,S,_,y,a,C,g,c)}function UE(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 WE(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 GE(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 KE(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){GE(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||WE(u,o)<=WE(s,o))s.push(e[l]),c.push(t[l]),l++;else{GE(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},KE(e.slice(l),t.slice(l),n,r,i);return}}s.length>0&&GE(s,c,n,a,r,i)}function qE(e,t,n){if(e.length===0)return[];let r=e=>e.weight>0&&Number.isFinite(e.weight)?e.weight:0,i=[...e].sort((e,t)=>r(t)-r(e)),a=i.reduce((e,t)=>e+r(t),0);if(a===0)return[];let o=t.width*t.height,s=i.map(e=>r(e)/a*o),c=i.map(e=>e.id),l=[];return KE(s,c,{...t},n,l),l}var JE=2,YE=18;function XE(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=qE(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+JE/2,y:d.y+JE/2+f,width:Math.max(0,d.width-JE),height:Math.max(0,d.height-JE-f)};s.push({name:t,rect:{...d},header:f,value:l>0?u/l:0,count:o.length}),c.push(...qE(o,p,n))}return{groups:s,cells:c}}function ZE(e){return Number.isFinite(e)?(e>=0?`+`:``)+e.toFixed(2)+`%`:``}function QE(e){return e.label}function $E(e,n){let r=n.min??-5,i=n.max??5;if(!Number.isFinite(e))return n.zero;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)}var eD=`#FFFFFF`,tD=`#11151b`;function nD(e,n){let r=/^rgba\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)$/i.exec(e.trim());return Sf(r?(0,t.lerpColor)(n,`rgb(${r[1]},${r[2]},${r[3]})`,Number(r[4])):(0,t.lerpColor)(e,e,0))===tD?tD:eD}function rD(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 iD(e,t,n,r,i,a,o,s,c,l,u,d){if(i<40||a<30)return;let f=n+i/2,p=r+a/2;e.save();let m=d===eD;if(e.shadowColor=m?`rgba(0,0,0,0.6)`:`transparent`,e.shadowBlur=m?2:0,e.fillStyle=d,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,f,c?p-1:p,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,f,s?p+1:p,i-8)}e.restore()}function aD(e,t,n,r,i,a,o,s){let c=[o(t),s(t.value)].filter(e=>e!==``);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,rD(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 oD(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??ZE,h=a.labelFormat??QE,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=$E(n.value,u);rD(e,r,i,a,s,d),e.fillStyle=c,e.fill(),iD(e,n,r,i,a,s,o,f,p,h,m,nD(c,o.background)),t.id===_&&(rD(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&&sD(e,s)):void 0;return cD(e,c,o,m,y),v&&s?aD(e,v.cell,s,t,n,o,h,m):y&&s&&aD(e,{id:``,label:y.name,value:y.value},s,t,n,o,e=>e.label,m),v}function sD(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 cD(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=df(s.name,m,e=>o(e),a);h&&e.fillText(h,t+5,u)}e.restore()}var lD=60,uD=12,dD=24,fD=40,pD=.7,mD=1;function hD(e){return e.type?e.type:e.value<0?`negative`:`positive`}function gD(e){let t=0;return e.map(e=>{let n=hD(e),r=Number.isFinite(e.value)?e.value:0,i=n===`total`||n===`subtotal`?0:t,a=i+r;return t=a,{type:n,value:r,start:i,end:a}})}function _D(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 vD(e,t){return{left:lD,right:e-uD,top:dD,bottom:t-fD,plotWidth:e-lD-uD,plotHeight:t-dD-fD}}function yD(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=gD(e);for(let t=0;t<e.length;t++){let n=e[t],{type:m,value:h,start:g,end:_}=p[t],v=Math.min(g,_),y=Math.max(g,_),b=d-(v-r)/i*f,x=d-(y-r)/i*f,S=Math.min(b,x),C=Math.max(Math.abs(x-b),mD),w=u+t*s,T=w+l;a[t]={label:n.label,value:h,start:g,end:_,type:m,rectX:T,rectY:S,rectW:c,rectH:C,slotX:w,slotW:s},o[t]=_}return{bars:a,cumulatives:o}}function bD(e){if(e.length===0)return{valMin:0,valMax:1};let t=0,n=0;for(let{start:r,end:i}of gD(e))r<t&&(t=r),i<t&&(t=i),r>n&&(n=r),i>n&&(n=i);let r=(n-t||1)*.1;return{valMin:t-r,valMax:n+r}}function xD(e,t,n,r){e.fillStyle=r,e.fillRect(0,0,t,n)}function SD(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 CD(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 wD(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 TD(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 ED(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.textAlign=`right`,e.textBaseline=`middle`;for(let n=0;n<t.length;n++){let r=t[n],o=r.slotX+r.slotW/2;e.save(),e.translate(o,a+4),e.rotate(-Math.PI/4),e.fillText(i(r.label),0,0),e.restore()}}function DD(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 OD(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 kD(e,t,n,r,i,a){let{data:o}=r;if(t<=0||n<=0)return{hitBar:null};if(!o||o.length===0)return xD(e,t,n,i.background),{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??pD,m=r.showValues!==!1,h=r.showDelta!==!1,g=r.valueFormat??_D,_=r.labelFormat??(e=>e),{valMin:v,valMax:y}=bD(o),b=y-v||1,x=vD(t,n),{bars:S,cumulatives:C}=yD(o,x,p,v,b);xD(e,t,n,i.background),SD(e,x,v,y,i,g),wD(e,S,x,v,b,d,f),CD(e,S,{positive:s,negative:c,total:l,subtotal:u}),m&&TD(e,S,C,i,g,h),ED(e,S,x,i,_);let w=a?DD(S,a.x,x):null;return a&&w!==null&&OD(e,S,C,w,a,x,i,g),{hitBar:w}}var AD=Math.PI/180,jD=150,MD=240,ND=90,PD=.14,FD=1.6*AD,ID=.22,LD=8,RD=18,zD=16,BD=6.5,VD=20,HD=5,UD=28;function WD(e,t,n){return e<t?t:e>n?n:e}function GD(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 KD(e){let t=Number.isFinite(e.startAngle)?e.startAngle:jD,n=(Number.isFinite(e.endAngle)?e.endAngle:t+MD)-t;return n<=0&&(n=(n%360+360)%360||360),n=WD(n,ND,360),{start:(t%360+360)%360*AD,sweep:n*AD}}function qD(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 JD(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*BD+12:0}function YD(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}=KD(n),s=a,c=a+o,l=WD(n.thickness??PD,.04,.5),u=qD(s,c),d=Math.max(u.maxY,.18),f=JD(n),p=f>0?zD:0,m=Math.max(1,e-2*LD-2*f),h=Math.max(1,t-2*LD-RD-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+RD+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-LD,E);return{cx:b,cy:x,radius:_,thickness:v,startAngle:s,endAngle:c,min:r,max:i,valueY:w,valueSize:C,textBottom:D}}function XD(e,t){let n=Number.isFinite(e)?WD((e-t.min)/(t.max-t.min),0,1):0;return t.startAngle+(t.endAngle-t.startAngle)*n}function ZD(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 QD(e,t,n){let r=(t??[]).map(t=>({a0:XD(t.from,e),a1:XD(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 $D(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 eO(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 tO(e,t,n,r,i,a){let o=QD(t,n,i),s=o.some(e=>!e.track);o.forEach((n,i)=>{let a=i>0&&!n.track&&!o[i-1].track?FD/2:0,s=i<o.length-1&&!n.track&&!o[i+1].track?FD/2:0,c=n.a0+a,l=n.a1-s;if(n.track){$D(e,t,c,l,n.color);return}e.globalAlpha=ID,$D(e,t,c,l,n.color),e.globalAlpha=1,$D(e,t,c,Math.min(l,r),n.color)}),s||$D(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:ID],[d,f]=u(o[0],c),[p,m]=u(o[o.length-1],l);eO(e,t,t.startAngle,d,f,`start`),eO(e,t,t.endAngle,p,m,`end`)}function nO(e,t,n){let r=t.radius-t.thickness/2;if(r<UD)return;let i=Math.max(4,t.thickness*.45);e.strokeStyle=n,e.lineCap=`butt`;for(let n=0;n<=VD;n++){let a=n%HD===0,o=t.startAngle+(t.endAngle-t.startAngle)*n/VD,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 rO(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 iO(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 aO(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 oO(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=aO(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();aO(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&&aO(e,r,`400`,f,s,c,l)>0&&(e.fillStyle=a.textSecondary,e.fillText(r,t.cx,n))}}function sO(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 cO(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=XD((WD(r.from,t.min,t.max)+WD(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 lO(e,t,n,r,i,a){if(t<=0||n<=0)return;let o=YD(t,n,r),s=Number.isFinite(a),c=s?WD(a,o.min,o.max):o.min,l=XD(c,o),u=s?ZD(c,r.zones):void 0,d=r.pointer===`needle`,f=r.valueFormat??GD,p=u?.color??r.needleColor??i.lineColor;e.save(),e.fillStyle=i.background,e.fillRect(0,0,t,n),tO(e,o,r.zones,l,r.trackColor??i.grid,p),nO(e,o,i.textSecondary),s&&(d?iO(e,o,l,r.needleColor??i.text,i.background):rO(e,o,l,p,i.background)),r.showValue!==!1&&oO(e,o,s?f(c):`—`,r.label,u,i,d),sO(e,o,f,i),r.showZoneLabels===!0&&r.zones?.length&&cO(e,o,r.zones,i),e.restore()}var uO=12,dO=.72,fO=20,pO=.35;function mO(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 hO(e,t){let n=e.colorBySign;return n?n===!0?{positive:t.candleUp,negative:t.candleDown}:n:null}function gO(e,t,n,r,i){let a=e.orientation===`horizontal`,o=e.legend??e.series.length>1?sf(e.series.map((e,t)=>({label:e.name,color:af(t,e.color)})),t-uO*2,i):null,s=uO+(o?o.height+6:0),[c,l]=mO(e),u=$d(c,l,a?Math.max(2,Math.floor(t/110)):5),d=e.valueFormat??K(u),f=Math.max(0,...u.ticks.map(e=>i(d(e),11))),p;if(a){let r=uO+Math.min(t*pO,Math.max(0,...e.categories.map(e=>i(e,11))))+8;p={x:r,y:s,width:Math.max(1,t-r-uO-f/2),height:Math.max(1,n-s-uO-fO)}}else{let e=uO+f+8;p={x:e,y:s,width:Math.max(1,t-e-uO),height:Math.max(1,n-s-uO-fO)}}let m=Math.max(1,e.categories.length),h=a?p.y:p.x,g=(a?p.height:p.width)/m,_=g*dO,v=e.mode===`stacked`,y=v?_:_/Math.max(1,e.series.length),b=e=>a?ef(u,e,p.x,p.width):ef(u,e,p.y,p.height,!0),x=b(0),S=hO(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:af(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:uO}}function _O(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 vO(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 yO(e,n,r,i,a,o,s=gO(i,n,r,a,of(e,a))){let c=of(e,a),l=i.valueFormat??rf,{plot:u,orientation:d}=s,f=d===`horizontal`;e.fillStyle=a.background,e.fillRect(0,0,n,r),s.legend&&cf(e,s.legend,uO,s.legendY,a),uf(e,u,s.scale,f?`horizontal`:`vertical`,a,i.valueFormat??K(s.scale));let p=o&&i.crosshair!==!1?vO(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(),bO(e,i.categories,s,a,c),i.showValues&&xO(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});lf(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}function bO(e,t,n,r,i){let{plot:a}=n;e.save(),e.font=q(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(df(t,a.x-uO-8,i),a.x-8,o)):(e.textAlign=`center`,e.textBaseline=`top`,e.fillText(df(t,n.band*s-4,i),o,a.y+a.height+6))}),e.restore()}function xO(e,t,n,r,i){e.save(),e.font=q(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 SO=12,CO=-Math.PI/2,wO=Math.PI*2,TO=5,EO=1.4,DO=18,OO=new Intl.NumberFormat(void 0,{style:`percent`,maximumFractionDigits:1});function kO(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} ${OO.format(e.value/o)}`,color:af(t,e.color)})),c=e.legend!==!1&&a.length>0,l=c&&t>=n*EO&&a.length*DO<=n-SO*2,u=l?Math.min(t*.4,Math.max(...s.map(e=>i(e.label,11)))+16):t-SO*2,d=c?sf(s,u,i,l):null,f=l?t-u-SO*3:t-SO*2,p=l?n-SO*2:n-SO*3-(d?.height??0),m=Math.max(0,Math.min(f,p)/2-TO),h=SO+f/2,g=SO+p/2,_=e.innerRadius,v=Math.min(.95,Math.max(0,_!==void 0&&Number.isFinite(_)?_:.6)),y=CO,b=a.map((e,t)=>{let n=e.value/o,r=y;return y+=n*wO,{label:e.label,value:e.value,share:n,start:r,end:y,color:af(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-SO:SO,legendY:l?Math.max(SO,g-(d?.height??0)/2):SO*2+p}}function AO(e,t,n){let r=t-e.cx,i=n-e.cy,a=Math.hypot(r,i);if(a<e.inner||a>e.radius+TO)return null;let o=Math.atan2(i,r);for(;o<CO;)o+=wO;return e.slices.find(e=>o>=e.start&&o<e.end)??null}function jO(e,t,n,r,i,a,o=kO(r,t,n,i,of(e,i))){let s=of(e,i),c=r.valueFormat??rf;e.fillStyle=i.background,e.fillRect(0,0,t,n);let l=a&&r.crosshair!==!1?AO(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?TO: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&&MO(e,o,i),NO(e,o,r,i,s),o.legend&&cf(e,o.legend,o.legendX,o.legendY,i),l&&a&&lf(e,[{text:l.label,bold:!0,color:l.color},{text:`${c(l.value)} · ${OO.format(l.share)}`}],a,{x:0,y:0,width:t,height:n},i),o}function MO(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=q(n,11,`600`),e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=`#fff`;for(let n of t.slices){let t=OO.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 NO(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=q(r,o,`600`),e.fillStyle=r.text,e.fillText(df(n.centerValue,a,i,o),t.cx,t.cy+(n.centerLabel?o*.35:0))}n.centerLabel&&(e.font=q(r,11),e.fillStyle=r.textSecondary,e.fillText(df(n.centerLabel,a,i),t.cx,t.cy-(n.centerValue?11*1.1:0))),e.restore()}var PO=12,FO=5,IO=3,LO=18,RO=20,zO=6;function BO(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+zO,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=$d(...p(o,s,n*.8),Math.max(2,Math.floor(n/110))),h=$d(...p(c,l,r*.7),5),g=e.xFormat??K(m),_=e.yFormat??K(h),v=e.legend??e.series.length>1?sf(e.series.map((e,t)=>({label:e.name,color:af(t,e.color)})),n-PO*2,a):null,y=PO+(v?v.height+6:0),b=Math.max(0,...h.ticks.map(e=>a(_(e),11))),x=PO+(e.yLabel?LO:0)+b+8,S=PO+RO+(e.xLabel?LO:0),C=a(g(m.max),11)/2,w={x,y,width:Math.max(1,n-x-PO-C),height:Math.max(1,r-y-S)},T=[];return e.series.forEach((e,n)=>{let r=af(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(IO,d*Math.sqrt(t.size/u)):FO;T.push({px:ef(m,t.x,w.x,w.width),py:ef(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 VO(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+zO&&e<i&&(r=a,i=e)}return r}function HO(e,t,n,r,i,a,o=BO(r,t,n,i,of(e,i))){let{plot:s,xScale:c,yScale:l}=o,u=r.xFormat??K(c),d=r.yFormat??K(l);e.fillStyle=i.background,e.fillRect(0,0,t,n),o.legend&&cf(e,o.legend,PO,PO,i),uf(e,s,l,`vertical`,i,d),uf(e,s,c,`horizontal`,i,u),r.zeroLines!==!1&&UO(e,o,i),WO(e,o,r,i);let f=a&&r.crosshair!==!1?VO(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=q(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??rf)(f.point.x)}`}),o.push({text:`${r.yLabel??`y`}: ${(r.yFormat??rf)(f.point.y)}`}),f.point.size!==void 0&&o.push({text:rf(f.point.size)}),lf(e,o,a,{x:0,y:0,width:t,height:n},i)}return o}function UO(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(ef(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(ef(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 WO(e,t,n,r){let{plot:i}=t;e.save(),e.font=q(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+RO+LO)),n.yLabel&&(e.translate(PO+11/2,i.y+i.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}var GO=1e-9,KO=1e3,qO=e=>{let t=Number(e.toPrecision(12));return t===0?0:t};function JO(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+GO),t=Math.max(e,Math.ceil(i/a-GO)-1)-e+1;if(t<=1e3){let r=Array.from({length:t},(t,n)=>({from:qO((e+n)*a),to:qO((e+n+1)*a),count:0}));for(let i of n)r[Math.min(t-1,Math.floor(i/a+GO)-e)].count++;return r}}let o=t.bins,s=typeof o==`number`&&Number.isFinite(o)&&o>=1?Math.min(KO,Math.floor(o)):Math.min(KO,Math.ceil(Math.log2(n.length))+1),c=(i-r)/s,l=Array.from({length:s},(e,t)=>({from:qO(r+t*c),to:qO(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+GO))].count++;return l}var YO=12,XO=20,ZO=16;function QO(e,n,r){return n.colorBySign?(e.from+e.to)/2<0?r.candleDown:r.candleUp:n.color??t.TC_SERIES_COLORS[0]}function $O(e,t,n,r,i){let a=JO(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=$d(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=$d(0,Math.max(4,u),4),f=e.valueFormat??K(l),p=Math.max(0,...d.ticks.map(e=>i(K(d)(e),11))),m=YO+(c.length>0?ZO:0),h=YO+p+8,g=YO+i(f(l.max),11)/2,_={x:h,y:m,width:Math.max(1,t-h-g),height:Math.max(1,n-m-YO-XO)};return{plot:_,xScale:l,yScale:d,bars:a.map(t=>{let n=ef(l,t.from,_.x,_.width),i=t.to>t.from?ef(l,t.to,_.x,_.width):n+_.width/10,a=ef(d,t.count,_.y,_.height,!0);return{x:n,y:a,width:Math.max(1,i-n),height:_.y+_.height-a,bin:t,color:QO(t,e,r)}}),total:a.reduce((e,t)=>e+t.count,0)}}function ek(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 tk=new Intl.NumberFormat(void 0,{style:`percent`,maximumFractionDigits:1});function nk(e,n,r,i,a,o,s=$O(i,n,r,a,of(e,a))){let c=i.valueFormat??rf,{plot:l}=s;e.fillStyle=a.background,e.fillRect(0,0,n,r),uf(e,l,s.yScale,`vertical`,a,K(s.yScale)),uf(e,l,s.xScale,`horizontal`,a,i.valueFormat??K(s.xScale));let u=o&&i.crosshair!==!1?ek(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(rk(e,s,i,a,c),u&&o){let{bin:t}=u;lf(e,[{text:t.to>t.from?`${c(t.from)} – ${c(t.to)}`:c(t.from),bold:!0,color:u.color},{text:`${rf(t.count)} · ${tk.format(s.total>0?t.count/s.total:0)}`}],o,{x:0,y:0,width:n,height:r},a)}return s}function rk(e,t,n,r,i){let{plot:a}=t;e.save(),e.font=q(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(ef(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 ik=864e5,ak=3,ok=12,sk=16,ck=10,lk=28,uk=6;function dk(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/ik)}function fk(e){return new Date(e*ik).toISOString().slice(0,10)}var pk=e=>((e+4)%7+7)%7;function mk(e,t){let n=e.from===void 0?null:dk(e.from),r=e.to===void 0?null:dk(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*ik).getUTCFullYear()-10+1;return[Math.max(n,Math.round(Date.UTC(i,0,1)/ik)),r]}function hk(e,t,n){let r=[],i=e;for(;i<=t;){let e=new Date(i*ik).getUTCFullYear(),a=Math.min(t,Math.round(Date.UTC(e,11,31)/ik)),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 gk=new Map;function _k(e){let t=e??``,n=gk.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=_k(void 0)}gk.set(t,n)}return n}function vk(e,t,n,r,i){let a=new Map;for(let t of e.data){let e=dk(t.date);e!==null&&Number.isFinite(t.value)&&a.set(e,t)}let o=_k(e.locale),s=e.dateFormat??(e=>o.long.format(new Date(`${e}T00:00:00Z`))),c=e.weekdays===5,l=e=>!c||pk(e)>=1&&pk(e)<=5,u=mk(e,a),d=t-ok*2,f=e.legend===!1?0:28,p=c?5:7,m=c?1:e.weekStart??1,h=e=>(pk(e)-m+7)%7,g=u?hk(u[0],u[1],h):[],_=e=>n-ok*2-f-e*sk-(e-1)*ck;for(;g.length>1&&_(g.length)/(g.length*p)<ak;)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=vf(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)*ik))),w=ok+Math.max(...C.map(e=>i(e,10)),...x?S.map(e=>i(e,11)):[0])+uk,T=Math.max(...g.map(e=>e.weeks)),E=Math.min(lk,(t-w-ok)/T,_(g.length)/(g.length*p));if(!(E>0))return b;let D=E-(E>=6?Math.max(1,Math.round(E*.12)):0),ee=T*E,O=w+Math.max(0,(t-w-ok-ee)/2),k={...b,pitch:E},A=ok;for(let[e,n]of g.entries()){let r=A+sk;x&&k.years.push({label:S[e],x:O-uk,y:A});let s=-1,c=-1/0;for(let e=n.first;e<=n.last;e++){if(!l(e))continue;let u=O+Math.floor((e-n.origin)/7)*E,d=r+h(e)*E,f=a.get(e);k.cells.push({x:u,y:d,size:D,date:fk(e),day:f,color:f&&Number.isFinite(f.value)?yf(f.value,y):null});let p=new Date(e*ik).getUTCMonth();if(p!==s){s=p;let n=o.month.format(new Date(e*ik)),r=u+i(n,10);u>=c&&r<=t&&(k.months.push({label:n,x:u,y:A}),c=r+4)}}if(E>=8){let e=E>=13?1:2;for(let t=0;t<p;t+=e)k.weekdays.push({label:C[t],x:O-uk,y:r+t*E+D/2})}A=r+p*E+ck}return f>0&&(k.bar={x:O,y:A-ck+8,width:Math.min(ee,t-O-ok),height:f-8}),k}function yk(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 bk(e,n,r,i,a,o,s=vk(i,n,r,a,of(e,a))){let c=i.valueFormat??rf;e.fillStyle=a.background,e.fillRect(0,0,n,r);let l=o&&i.crosshair!==!1?yk(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=q(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=q(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&&Cf(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:`–`});lf(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}var xk=12,Sk=6,Ck=72,wk=Math.PI/4,Tk=Math.sin(wk);function Ek(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=Dk(e[r],e[i],r===i);n[r][i]=t,n[i][r]=t}return n}function Dk(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 Ok=e=>e.toFixed(2);function kk(e,t,n,r){return!t||!e?!0:e===`lower`?r<=n:r>=n}function Ak(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)&&kk(e.triangle,s,t,n)&&c.push(r)}let l=vf(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=xk+d+Sk,h=t-m-xk,g=e=>Math.min(Ck,h/o.length,(n-e-xk-p)/a.length),_=xk+11+Sk,v=g(_),y=f>v-4,b=f;if(y&&(b=Math.min(f,n*.33/Tk),_=xk+b*Tk+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*Tk/2)/Tk))),u.grid={x:S,y:_,width:o.length*v,height:a.length*v},u.pitch=v;let C=e.valueFormat??Ok,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)||!kk(e.triangle,s,t,n))continue;let c=yf(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:Sf(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*Tk:v)));for(let e=0;e<a.length;e+=E)u.rowLabels.push({text:df(a[e],d,i),index:e,x:S-Sk,y:_+e*v+x/2});for(let e=0;e<o.length;e+=D)u.columnLabels.push({text:df(o[e],b,i),index:e,x:S+e*v+x/2,y:_-Sk,rotated:y});return p>0&&(u.bar={x:S,y:_+a.length*v+8,width:Math.min(u.grid.width,t-S-xk),height:p-8}),u}function jk(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 Mk(e,t,n,r,i,a,o=Ak(r,t,n,i,of(e,i))){let s=r.valueFormat??Ok;e.fillStyle=i.background,e.fillRect(0,0,t,n);let c=a&&r.crosshair!==!1?jk(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=q(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=q(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(wk),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&&Cf(e,o.bar,o.scale,s,i),c&&a){let{cell:r}=c;lf(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 Nk=12,Pk=18,Fk=20,Ik=10,Lk=.2,Rk=2e3,zk=1e-9;function Bk(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 Vk=(e,t)=>t-e>zk*Math.max(Math.abs(e),Math.abs(t));function Hk(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=Vk(t,n)?(o.volume-a.volume)/(n-t):0,c=Vk(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 Uk(e,n,r,i,a){let o=Bk(e.data,e.period??25,Wk(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&&!Vk(s,c)&&(c=s),o.length>0&&!Vk(l,u)&&(u=l);let d=$d(o.length>0?s:0,o.length>0?c:1,Math.max(2,Math.floor(n/110))),f=$d(o.length>0?l:0,o.length>0?u:1,Math.max(2,Math.floor(r/60))),p=e.priceFormat??K(f),m=e.volumeFormat??K(d),h=Nk+Math.max(0,...f.ticks.map(e=>a(p(e),11)))+8+(e.yLabel?Pk:0),g=Nk+a(m(d.max),11)/2,_=Nk,v=Nk+Fk+(e.xLabel?Pk: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:ef(d,e.volume,y.x,y.width),py:ef(f,e.price,y.y,y.height,!0),alpha:Lk+(1-Lk)*t/b,point:e})),phase:Hk(o),color:e.color??t.TC_SERIES_COLORS[0]}}function Wk(e){let t=e.points??60;return Number.isFinite(t)?Math.min(Rk,Math.max(2,Math.floor(t))):60}function Gk(e,t,n){let r=null,i=Ik*Ik;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 Kk=new Intl.DateTimeFormat(void 0,{year:`numeric`,month:`short`,day:`numeric`});function qk(e,n,r,i,a,o,s=Uk(i,n,r,a,of(e,a))){let{plot:c,points:l,color:u}=s,d=i.timeFormat??(e=>Kk.format(new Date(e))),f=i.priceFormat??rf,p=i.volumeFormat??rf;e.fillStyle=a.background,e.fillRect(0,0,n,r),uf(e,c,s.yScale,`vertical`,a,i.priceFormat??K(s.yScale)),uf(e,c,s.xScale,`horizontal`,a,i.volumeFormat??K(s.xScale)),Jk(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?Gk(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(),lf(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 Jk(e,t,n,r){e.save(),e.font=q(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+Fk+Pk)),n.yLabel&&(e.translate(Nk+4,t.y+t.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}exports.ABCDPatternTool=Sv,exports.ADXIndicator=Es,exports.ALMAIndicator=Oc,exports.ATRIndicator=Ts,exports.AXIS_LABEL_HEIGHT=te,exports.AcceleratorOscillatorIndicator=mc,exports.AccumulationDistributionIndicator=wc,exports.AccumulativeSwingIndexIndicator=yu,exports.AdvanceDeclineIndicator=xu,exports.AlertDragHandler=zd,exports.AlertManager=Ww,exports.AlligatorIndicator=ds,exports.AnchoredNoteTool=my,exports.AnchoredTextTool=py,exports.AnchoredVWAPIndicator=ns,exports.AnchoredVWAPTool=M_,exports.Animator=tE,exports.ArcTool=Ry,exports.AreaRenderer=tt,exports.AroonIndicator=js,exports.ArrowMarkTool=Zv,exports.ArrowTool=S_,exports.AverageDayRangeIndicator=el,exports.AveragePriceIndicator=cl,exports.AwesomeOscillatorIndicator=bs,exports.AxisDragHandler=Rd,exports.BalanceOfPowerIndicator=$s,exports.BalloonTool=fy,exports.BarCountdown=pe,exports.BarRenderer=nt,exports.BarsPatternTool=yb,exports.BaseFinanceChart=rE,exports.BaselineRenderer=at,exports.BinanceAdapter=_C,exports.BollingerBandWidthIndicator=Vc,exports.BollingerBandsIndicator=zo,exports.BollingerPercentBIndicator=Bc,exports.BracketTool=wx,exports.BrushTool=jy,exports.BybitAdapter=jC,exports.CANDLE_PATTERNS=Yl,exports.CCIIndicator=ks,exports.CMFIndicator=Ps,exports.COUNTDOWN_HEIGHT=fe,exports.CROSSHAIR_CURSORS=Ff,exports.CalloutTool=Hv,exports.CandlestickRenderer=ue,exports.CanvasLayer=c,exports.ChaikinOscillatorIndicator=xs,exports.ChaikinVolatilityIndicator=sc,exports.ChandeKrollStopIndicator=Lc,exports.ChandeMomentumIndicator=tc,exports.ChandelierExitIndicator=us,exports.ChartLegend=ow,exports.ChartStateManager=xT,exports.ChopZoneIndicator=Tu,exports.ChoppinessIndexIndicator=Ls,exports.CircleTool=Ev,exports.CoinbaseAdapter=TC,exports.CompareRenderer=Gr,exports.CompareSymbolIndicator=no,exports.CompareSymbolPaneIndicator=ro,exports.ConnorsRSIIndicator=Vs,exports.CoppockIndicator=Us,exports.CorrelationCoefficientIndicator=co,exports.CorrelationLogIndicator=lo,exports.CrossLineTool=iv,exports.CrosshairHandler=Tf,exports.CrosshairTooltip=$f,exports.CurrentPriceLine=rS,exports.CurveTool=Ly,exports.CyclicLinesTool=Pv,exports.CypherPatternTool=Tv,exports.DEFAULT_LEGEND_CONFIG=aw,exports.DEFAULT_MAX_PIXEL_RATIO=n,exports.DEFAULT_MAX_WEBGL_CHARTS=e.t,exports.DEFAULT_SESSION_HOURS=Dw,exports.DEMAIndicator=Ec,exports.DENSE_BAR_WIDTH=e.u,exports.DOUBLE_TAP_MS=md,exports.DOUBLE_TAP_PX=hd,exports.DPRManager=o,exports.DataExporter=AT,exports.DateAndPriceRangeTool=Av,exports.DateRangeTool=d_,exports.DepthHeatmapBuffer=en,exports.DepthHeatmapRenderer=tn,exports.DepthOverlay=hx,exports.DetrendedPriceOscillatorIndicator=Qs,exports.DisparityIndexIndicator=_c,exports.DonchianChannelIndicator=Qo,exports.DrawingBase=J,exports.DrawingManager=Mm,exports.DrawingRenderer=Bm,exports.EMAIndicator=Ro,exports.EaseOfMovementIndicator=ic,exports.Easing=eE,exports.ElderRayIndicator=qs,exports.ElliottCorrectionTool=n_,exports.ElliottDoubleComboTool=i_,exports.ElliottImpulseTool=t_,exports.ElliottTriangleTool=r_,exports.ElliottTripleComboTool=a_,exports.ElliottWaveTool=e_,exports.EllipseTool=xg,exports.Emitter=Zx,exports.EnvelopeIndicator=hs,exports.EquivolumeRenderer=ft,exports.EventBus=dp,exports.ExtendedLineTool=Yh,exports.FibArcsTool=nb,exports.FibChannelTool=fv,exports.FibCirclesTool=tb,exports.FibExtensionTool=vg,exports.FibRetracementTool=gg,exports.FibSpeedResistanceFanTool=yv,exports.FibSpiralTool=ab,exports.FibTimeZonesTool=G_,exports.FibWedgeTool=rb,exports.FinanceCrosshair=iE,exports.FisherTransformIndicator=Zs,exports.FlagTool=Jv,exports.ForceIndexIndicator=Bs,exports.ForecastTool=_b,exports.GROUP_HEADER=YE,exports.GannBoxTool=A_,exports.GannFanTool=T_,exports.GannSquareTool=ob,exports.GridRenderer=e.o,exports.GuppyMMAIndicator=al,exports.HLCAreaRenderer=mt,exports.HammingMAIndicator=fu,exports.HeadAndShouldersTool=Cv,exports.HiLoRenderer=yt,exports.HighlighterTool=My,exports.HistoricalVolatilityIndicator=Uc,exports.HollowCandleRenderer=rt,exports.HorizontalLineTool=Wh,exports.HorizontalRayTool=Gh,exports.HullMAIndicator=as,exports.ICON_GLYPHS=Qv,exports.INDICATOR_CATEGORIES=Fu,exports.INDICATOR_WORKER_MIN_BARS=Do,exports.INTERVAL_LIMITS=Oa,exports.INTERVAL_UNITS=Da,exports.IchimokuIndicator=Jo,exports.IconTool=ey,exports.IndicatorBase=I,exports.IndicatorEngine=Io,exports.IndicatorValueMap=L,exports.IndicatorWorkerClient=qu,exports.IndicatorWorkerHost=Wu,exports.IndicatorWorkerPool=Yu,exports.InfoLineTool=ov,exports.InteractionManager=Td,exports.KAMAIndicator=kc,exports.KEPT_BUCKETS=cS,exports.KSTIndicator=Ws,exports.KagiRenderer=st,exports.KeltnerChannelIndicator=Zo,exports.KeyboardHandler=Hf,exports.KlingerIndicator=Xs,exports.KrakenAdapter=RC,exports.LSMAIndicator=Ac,exports.LayerManager=l,exports.LineRenderer=et,exports.LineWithMarkersRenderer=gt,exports.LinearRegressionChannelIndicator=is,exports.LinearRegressionSlopeIndicator=Qc,exports.MACDIndicator=Cs,exports.MAChannelIndicator=cu,exports.MACrossIndicator=Pc,exports.MADoubleIndicator=gu,exports.MARibbonIndicator=ol,exports.MATripleIndicator=_u,exports.MAX_ALERT_BARS=Fw,exports.MAX_BASE_RATIO=oS,exports.MAX_BASE_REQUESTS=aS,exports.MFIIndicator=As,exports.MIN_ALERT_BARS=Iw,exports.MIN_BAR_UNIT=Le,exports.MIN_BAR_UNIT_LIMIT=Re,exports.MTFMovingAverageIndicator=cs,exports.MajorityRuleIndicator=Su,exports.ManualFeed=rw,exports.MarketProfileRenderer=zt,exports.MassIndexIndicator=ec,exports.McGinleyDynamicIndicator=jc,exports.MeasureOverlay=UT,exports.MeasureTool=f_,exports.MedianPriceIndicator=ll,exports.MockAdapter=vC,exports.ModifiedSchiffPitchforkTool=Og,exports.MomentumIndicator=Hc,exports.NetVolumeIndicator=tl,exports.NoteTool=Vv,exports.OBVIndicator=Ds,exports.OrderDraftTool=Ax,exports.OrderRenderer=nx,exports.PRICE_AXIS_ADD_STRIP=Od,exports.PRICE_SCALE_MARGIN=Ve,exports.PanHandler=Id,exports.PaneResizeHandler=Bd,exports.PaperExecutionAdapter=Jx,exports.ParabolicSARIndicator=Yo,exports.ParallelChannelTool=Qh,exports.PathTool=Ny,exports.PercentagePriceOscillatorIndicator=fc,exports.PeriodLevelsRenderer=Wt,exports.PinnedTooltip=sp,exports.PitchfanTool=ib,exports.PitchforkTool=Eg,exports.PivotMarkersRenderer=Xt,exports.PivotPointsIndicator=es,exports.PointAndFigureRenderer=ut,exports.PollingAdapter=xC,exports.PolylineTool=Py,exports.PositionRenderer=mx,exports.PrettyGoodOscillatorIndicator=yc,exports.PriceAxis=D,exports.PriceAxisAddButton=kd,exports.PriceLabelTool=Cy,exports.PriceLines=jw,exports.PriceOscillatorIndicator=Ou,exports.PriceRangeTool=c_,exports.PriceVolumeTrendIndicator=ac,exports.ProjectionTool=vb,exports.QstickIndicator=vc,exports.RANGE_PRESETS=Ge,exports.ROCIndicator=Ms,exports.RSIIndicator=Ss,exports.RayTool=Jh,exports.ReconnectManager=tS,exports.RectangleTool=bg,exports.RegressionChannelTool=rg,exports.RelativeMomentumIndexIndicator=gc,exports.RelativeVigorIndicator=cc,exports.RelativeVolatilityIndexIndicator=Xc,exports.RenderEngine=Ne,exports.RenderLoop=u,exports.RenkoRenderer=ot,exports.ReplayController=QS,exports.ReplayManager=$w,exports.ResamplingAdapter=yS,exports.ReshapeMemo=Qr,exports.RiskRewardTool=rv,exports.SELECTION_BOX_MIN_SIZE=QT,exports.SMAIndicator=Lo,exports.SMIErgodicIndicator=Du,exports.SMMAIndicator=Dc,exports.SNAPSHOT_VERSION=tT,exports.SYMBOL_INDICATOR_IDS=eo,exports.SYMBOL_ZONE_WAIT_MS=sS,exports.SchaffTrendCycleIndicator=Js,exports.SchiffPitchforkTool=Dg,exports.Screenshot=hw,exports.SelectionBoxOverlay=$T,exports.SessionBreaks=bw,exports.SessionShading=Ow,exports.SessionVWAPIndicator=ls,exports.SignalMarkerManager=FT,exports.SignpostTool=dy,exports.SineLineTool=db,exports.SpreadIndicator=io,exports.StandardErrorBandsIndicator=nl,exports.StandardErrorIndicator=$c,exports.StdDevIndicator=bc,exports.StepLineRenderer=ht,exports.StochasticIndicator=ws,exports.StochasticMomentumIndexIndicator=Yc,exports.StochasticRSIIndicator=lc,exports.StreamManager=ZS,exports.SupertrendIndicator=Xo,exports.SymbolSeriesStore=rn,exports.TEMAIndicator=ys,exports.TOUCH_REACH=pd,exports.TRIXIndicator=nc,exports.TSIIndicator=Ns,exports.TapTracker=gd,exports.TextAnnotationTool=b_,exports.ThreeDrivesTool=wv,exports.TickAggregator=eS,exports.TickBarAdapter=wS,exports.TickBarBuilder=CS,exports.TimeAxis=ld,exports.TimeCyclesTool=ub,exports.TradeZoneManager=zT,exports.TradingContextMenu=vx,exports.TradingDragHandler=_x,exports.TradingManager=Kx,exports.TradingRenderer=qx,exports.TrendAngleTool=Ah,exports.TrendLineTool=Uh,exports.TrendStrengthIndexIndicator=Zc,exports.TriangleTool=Sg,exports.TypicalPriceIndicator=ul,exports.UPBIT_MAX_CANDLES=UC,exports.UlcerIndexIndicator=Kc,exports.UltimateOscillatorIndicator=Rs,exports.UndoRedoManager=ST,exports.UpbitAdapter=JC,exports.VOLUME_HEIGHT_RATIO=bt,exports.VROCIndicator=Tc,exports.VWAPIndicator=Go,exports.VWMAIndicator=ps,exports.VerticalLineTool=qh,exports.Viewport=Ue,exports.VolatilityIndexIndicator=vu,exports.VolatilityOHLCIndicator=ju,exports.VolatilityZeroTrendIndicator=Mu,exports.VolumeCandleRenderer=dt,exports.VolumeDeltaIndicator=Fs,exports.VolumeOscillatorIndicator=Wc,exports.VolumeProfileIndicator=Cc,exports.VolumeProfileRangeTool=V_,exports.VolumeProfileRenderer=wt,exports.VolumeRenderer=xt,exports.VortexIndicator=Is,exports.WMAIndicator=ms,exports.Watermark=gw,exports.WebSocketAdapter=bC,exports.WilliamsADIndicator=oc,exports.WilliamsFractalsIndicator=Ic,exports.WilliamsRIndicator=Os,exports.XABCDPatternTool=xv,exports.ZigZagIndicator=rs,exports.ZoomHandler=Ld,exports.adapterFromFeed=LS,exports.alignAxisTags=me,exports.alignOutput=Ta,exports.arcPoints=Iy,exports.assignSessionLetters=Lt,exports.axisFormat=K,exports.axisTimes=ci,exports.barIndexToTime=e.S,exports.barIndexToX=e.C,exports.barTimeStep=e.w,exports.barTimeStepMs=e.T,exports.barsToColumns=uo,exports.bracketRiskReward=bx,exports.canvasMeasure=of,exports.cappedPixelRatio=r,exports.claimGpuContext=e.n,exports.classifyPivots=Kt,exports.cleanIntervals=Ma,exports.columnsToBars=fo,exports.columnsToOutput=So,exports.computeBarLayout=gO,exports.computeBracketDefaults=yx,exports.computeCalendarLayout=vk,exports.computeCounterClockLayout=Uk,exports.computeDonutLayout=kO,exports.computeHistogramLayout=$O,exports.computeMarketProfile=Ft,exports.computeMatrixLayout=Ak,exports.computePeriodLevels=Ut,exports.computeScatterLayout=BO,exports.computeSessionProfiles=Rt,exports.correlationMatrix=Ek,exports.counterClockPhase=Hk,exports.counterClockPoints=Bk,exports.createIndicatorWorker=Gu,exports.curvePoints=Fy,exports.dayToIso=fk,exports.defaultFormat=rf,exports.describeInputs=Hu,exports.detectCandlePatterns=$l,exports.drawAxisValueLabels=oe,exports.drawIcon=Fb,exports.drawingAxisSpan=Sm,exports.drawnKeys=Gi,exports.feedFromAdapter=zS,exports.fillTag=k,exports.findDominantSwing=Vm,exports.findPivots=qt,exports.forEachPixelColumn=e.d,exports.forecastOutcome=gb,exports.formatTooltipTime=Xf,exports.getIntParam=U,exports.getNumberParam=H,exports.getVisibleData=We,exports.gpuContextsLeft=e.r,exports.hasHistogram=ea,exports.hasTrades=DS,exports.histogramBins=JO,exports.hitBar=_O,exports.hitCategory=vO,exports.hitDay=yk,exports.hitHistogramBar=ek,exports.hitMatrixCell=jk,exports.hitSlice=AO,exports.idleCssCursor=Vf,exports.indicatorCategory=Lu,exports.indicatorValuePrecision=A,exports.indicatorWorkerPool=Xu,exports.inferOrderType=Dx,exports.inputSource=Sa,exports.isCrosshairCursor=If,exports.isDataFeed=NS,exports.isDense=e.f,exports.isInWindow=Tw,exports.isPriceLevelAlert=Rw,exports.isRegularSession=Ew,exports.isSeriesPalette=Pa,exports.isUpTone=Ki,exports.isWorkerResponse=Uu,exports.labelTextColor=re,exports.layoutAxisValueLabels=ae,exports.layoutGroupedTreemap=XE,exports.layoutLegend=sf,exports.layoutSquarifiedTreemap=qE,exports.layoutUniformGrid=UE,exports.lineSourceBars=wa,exports.lineSpace=Np,exports.loadWebGL=Fe,exports.loadWebGLRenderer=Ie,exports.lttbDownsample=Ze,exports.lttbVisibleIndices=$e,exports.mergeSessionHours=Cw,exports.minuteOfDay=ww,exports.nearestCounterClockPoint=Gk,exports.nearestPoint=VO,exports.niceScale=$d,exports.outputToColumns=_o,exports.paneLogRange=Qi,exports.paneValueRange=Zi,exports.parseDay=dk,exports.pastTimeStep=e.E,exports.plotColor=Xi,exports.plotLook=Yi,exports.plotShown=qi,exports.pointAndFigureColumns=yi,exports.priceBucketRow=e.D,exports.priceScaleText=d,exports.priceSourceBars=Ca,exports.priceToY=e.O,exports.priceToYMapper=e.k,exports.rangePresetStart=Xe,exports.readAlertOptions=Kw,exports.readableText=Sf,exports.registerBuiltInDrawingTools=bb,exports.registerBuiltInIndicators=Pu,exports.renderAxisValueLabels=se,exports.renderBarChart=yO,exports.renderCalendar=bk,exports.renderCounterClock=qk,exports.renderDenseBars=e.p,exports.renderDepthChart=SE,exports.renderDonut=jO,exports.renderEquityCurve=HE,exports.renderGauge=lO,exports.renderHeatmap=oD,exports.renderHistogram=nk,exports.renderMatrix=Mk,exports.renderPlots=ta,exports.renderScatter=HO,exports.renderSparkline=aE,exports.renderWaterfall=kD,exports.resolveBarIndex=e.A,exports.resolveColorScale=vf,exports.scaleColor=yf,exports.servesTimeframe=hS,exports.setMaxWebGLCharts=e.i,exports.shownCount=Wk,exports.shownOnInterval=ja,exports.sourceParam=xa,exports.spreadLabels=ne,exports.streamAdapterOf=PS,exports.timeToX=e.j,exports.timestampToBarIndex=e.M,exports.toHeikinAshi=Kr,exports.toKagi=hi,exports.toLineBreak=mi,exports.toPointAndFigure=vi,exports.toRangeBars=Ri,exports.toRenko=li,exports.tpoLetter=It,exports.waveLabel=Xg,exports.whenGpuContextFree=e.a,exports.withResampling=pS,exports.withTickBars=ES,exports.xToBarIndex=e.N,exports.xToTime=e.P,exports.yToPrice=e.F;
|
|
24
|
+
`,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 Dx(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 Ox(e){let t=Math.abs(e.entry-e.stopLoss);return t===0?0:Math.abs(e.takeProfit-e.entry)/t}var kx=6,Ax=.12,jx=[6,3],Mx=class{draft=null;dragStart=null;dragging=null;defaults;constructor(e={}){this.defaults=e}start(e,t){this.draft=Dx(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=kx){if(!this.draft)return null;let i=[`entry`,`sl`,`tp`],a=null,o=r;for(let r of i){let i=e.k(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.I(t.y,n);return this.draft=Px(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),Qb(e,this.tags(t,n),t,n,[])}renderLines(t,n,r){let i=this.draft;if(!i)return;let{chartRect:a}=n,o=e.k(i.entry,n),s=e.k(i.stopLoss,n),c=e.k(i.takeProfit,n),{profit:l,loss:u}=Nx(r);t.save(),t.globalAlpha=Ax,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,Ab(t,n,o,r.text,jx),Ab(t,n,c,l,[]),Ab(t,n,s,u,[]),t.restore()}tags(t,n){let r=this.draft;if(!r)return[];let{profit:i,loss:a}=Nx(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.k(r.entry,t),color:n.text,grab:{kind:`bracket`,handle:`entry`},cells:[{kind:`stamp`,text:r.side===`buy`?`Long`:`Short`},{kind:`text`,text:`${Ox(r).toFixed(2)}R`}]},{y:e.k(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.k(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=>X(e.y,t))}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))tx(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}=Nx(r),c=[];for(let[l,u]of[[a.takeProfit,o],[a.stopLoss,s],[a.entry,r.text]]){let r=e.k(l,n);X(r,n)&&c.push({y:r,text:(0,t.priceTagText)(l,n,i),color:u})}return c}};function Nx(e){return{profit:e.style?.trading.profit??e.candleUp,loss:e.style?.trading.loss??e.candleDown}}function Px(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 Fx(e,t,n){return n==null?`limit`:e===`buy`?t<=n?`limit`:`stop`:t>=n?`limit`:`stop`}var Ix=6,Lx=[6,3],Rx=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:Fx(this.draft.side,this.draft.price,e),price:this.draft.price,quantity:this.draft.quantity}:null}hitTest(t,n,r=Ix){return this.draft?Math.abs(e.k(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.I(t.y,n))}endDrag(){this.dragging=!1,this.dragStart=null}render(e,t,n,r,i){this.renderLines(e,t,n),Qb(e,this.tags(t,n,r),t,n,[])}renderLines(t,n,r){let i=this.draft;i&&(t.save(),Ab(t,n,e.k(i.price,n),zx(i.side,r),Lx),t.restore())}tags(t,n,r){let i=this.draft;if(!i)return[];let a=e.k(i.price,t);if(!X(a,t))return[];let o=Fx(i.side,i.price,r);return[{y:a,color:zx(i.side,n),grab:{kind:`draft`},cells:[{kind:`stamp`,text:String(i.quantity)},{kind:`text`,text:ox({side:i.side,type:o})}]}]}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))tx(e,i.y,i.text,i.color,t,n)}axisBadges(n,r,i){let a=this.draft;if(!a)return[];let o=e.k(a.price,n);return X(o,n)?[{y:o,text:(0,t.priceTagText)(a.price,n,i),color:zx(a.side,r)}]:[]}};function zx(e,t){return e===`buy`?t.style?.trading.buy??t.candleUp:t.style?.trading.sell??t.candleDown}var Bx=2;function Vx(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 Hx(e,t,n=Bx){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 Ux=5,Wx=7,Gx=2;function Kx(e,n){let r=n.data;return r&&r.length>0?e/(0,t.barTimeUnit)(r):e}function qx(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.M(Kx(i.time,r),r),c=e.k(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+Gx:c-Gx,d=l?u+Wx:u-Wx;t.beginPath(),t.moveTo(n,u),t.lineTo(n-Ux,d),t.lineTo(n+Ux,d),t.closePath();let f=l?o:s;!i.reason||i.reason===`order`?(t.fillStyle=f,t.fill()):(t.strokeStyle=f,t.stroke())}}function Jx(e){for(let t in e)if(e[t]!==null)return!0;return!1}function Yx(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];i!==null&&(n[t[r]]=i)}return n}function Xx(e,t){let n=t.style?.trading;return!n||!Jx(n)?e:{...e,orderColors:{...e.orderColors,...Yx({buy:n.buy,sell:n.sell},{buy:`buy`,sell:`sell`})},positionColors:{...e.positionColors,...Yx({profit:n.profit,loss:n.loss,entry:n.entry},{profit:`profit`,loss:`loss`,entry:`entry`})}}}function Zx(e,t){let n=t.style?.markers;return!n||!Jx(n)?e:{...e,...Yx(n,{long:`longColor`,short:`shortColor`,neutral:`neutralColor`})}}function Qx(e,t){let n=t.style?.tradeZones;return!n||!Jx(n)?e:{...e,...Yx(n,{profit:`profitColor`,loss:`lossColor`,active:`activeColor`})}}var $x=1e3,eS=class{orders=[];positions=[];depthData=null;currentPrice=null;config;orderRenderer=new ux;positionRenderer=new Sx;depthOverlay=new Cx;dragHandler;contextMenu=new Ex;bracket=new Mx;orderDraft=new Rx;buttons=[];tagBoxes=[];tagInset=0;drawnTags=[];grabOffset=0;fills=[];realisedPnl=0;requestRender=null;eventCallback=null;container=null;constructor(e){this.config={...t.DEFAULT_TRADING_CONFIG,...e},this.dragHandler=new Tx(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(-($x-1)),e],this.realisedPnl+=e.pnl??0,this.requestRender?.()}setFills(e){this.fills=e.slice(-$x),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&&Hx(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:Ox(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(qb(this.tagBoxes,t.x,t.y)&&!Hx(this.buttons,t))return!0;let i=i=>{if(i===void 0)return!1;let a=e.k(i,n);return X(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=Hx(this.buttons,e,n?.button),i=r?null:qb(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:kb(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?Hx(this.buttons,e):null;return n&&Vx(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.I(n.y,r);return this.contextMenu.show(n,i,this.container,this.config,e=>(0,t.priceTagText)(e,r,this.config.pricePrecision)),!0}tagRects(){return this.drawnTags}setTagInset(e){this.tagInset=Math.max(0,e)}render(e,t,n){if(this.buttons=[],this.tagBoxes=[],this.drawnTags=[],!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=Xx(this.config,n);this.depthData&&this.depthOverlay.render(e,this.depthData,t,r),r.fillMarks!==!1&&qx(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),Qb(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,this.tagInset,this.drawnTags)}renderAxisBadges(e,t,n,r){if(this.config.enabled){if(r){let{chartRect:i}=t;this.sortedAxisBadges(t,n).forEach((a,o)=>{let s=r[o]??a.y;!Number.isFinite(s)||s-16/2<i.y-.5||s+16/2>i.y+i.height+.5||tx(e,s,a.text,a.color,t,n)});return}for(let r of ex(this.axisBadges(t,n),t))tx(e,r.at,r.text,r.color,t,n)}}axisBadgeLines(e,n=t.DARK_THEME){return this.config.enabled?this.sortedAxisBadges(e,n).map(e=>e.y):[]}sortedAxisBadges(e,t){return this.axisBadges(e,t).sort((e,t)=>e.y-t.y)}axisBadges(e,t){let n=Xx(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?ex(this.axisBadges(e,n),e).map(e=>e.at):[]}destroy(){this.contextMenu.destroy()}},tS=class{constructor(e){this.manager=e}render(e,t,n){this.manager.render(e,t,n)}renderAxisBadges(e,t,n,r){this.manager.renderAxisBadges(e,t,n,r)}axisBadgeLines(e,t){return this.manager.axisBadgeLines(e,t)}tagRects(){return this.manager.tagRects()}axisTagYs(e,t){return this.manager.axisTagYs(e,t)}},nS=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:iS(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:rS(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:rS(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 rS(e){return e===`buy`?`sell`:`buy`}function iS(e){switch(e){case`stop`:return`STOP`;case`stopLimit`:return`STOP LIMIT`;default:return`LIMIT`}}var aS=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()}},oS=6e4,sS=e=>[e.open,e.high,e.low,e.close].every(Number.isFinite),cS=class extends aS{currentBar=null;newest=-1/0;builtFromTrades=!1;lastTradeAt=null;timeframe;timeframeMs;dateFrame;bucket={};dateStamps=!1;tickRing;ringHead=0;ringCount=0;ringCapacity;constructor(e,n=1e3){super(),this.timeframe=e,this.timeframeMs=(0,t.timeframeToMs)(e),this.dateFrame=(0,t.timeframeSpansDays)(e),this.ringCapacity=n,this.tickRing=Array(n)}setTimeframe(e){this.timeframe=e,this.timeframeMs=(0,t.timeframeToMs)(e),this.dateFrame=(0,t.timeframeSpansDays)(e),this.reset()}seed(e){this.builtOffTheBuckets()&&(this.currentBar=null,this.newest=-1/0,this.lastTradeAt=null),Number.isFinite(e)&&(this.newest=Math.max(this.newest,(0,t.normalizeBarTime)(e)))}resume(e){if(!sS(e))return;let n=(0,t.normalizeBarTime)(e.time);n<this.newest||(this.newest=n,this.currentBar={time:n,open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume??0,closed:!1,tickCount:0},this.builtFromTrades=!0,this.lastTradeAt=null)}setTimeZone(e,t=!1){this.bucket={timeZone:e??void 0},this.dateStamps=t}processTick(e){let n=(this.ringHead+this.ringCount)%this.ringCapacity;this.tickRing[n]=e,this.ringCount<this.ringCapacity?this.ringCount++:this.ringHead=(this.ringHead+1)%this.ringCapacity;let r=this.barFor(e.time);r!==null&&(this.newest=(0,t.normalizeBarTime)(r),this.lastTradeAt=e.time,!this.currentBar||this.currentBar.time!==r?(this.currentBar&&(this.currentBar.closed=!0,this.emit(`barClose`,this.currentBar)),this.currentBar={time:r,open:e.price,high:e.price,low:e.price,close:e.price,volume:e.volume,closed:!1,tickCount:1},this.builtFromTrades=!0):(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,n){let r=(0,t.normalizeBarTime)(e.time);if(r<this.newest){n&&this.emit(`correction`,{...e});return}if(this.newest=r,this.builtFromTrades=!1,n&&this.currentBar&&(0,t.normalizeBarTime)(this.currentBar.time)===r)this.currentBar={...e,closed:!0,tickCount:this.currentBar.tickCount+1},this.emit(`barClose`,this.currentBar),this.currentBar=null;else if(!n)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.newest=-1/0,this.builtFromTrades=!1,this.lastTradeAt=null,this.ringHead=0,this.ringCount=0}barFor(e){let n=this.alignToTimeframe(e);if((0,t.normalizeBarTime)(n)>=this.newest)return n;if((0,t.normalizeBarTime)(e)<this.instantOf(this.newest))return null;let r=this.currentBar;return r!==null&&(0,t.normalizeBarTime)(r.time)===this.newest?r.time:this.newest}instantOf(e){return!this.dateStamps||!this.dateFrame?e:e-(0,t.offsetAt)(this.bucket.timeZone??0,e)*oS}builtOffTheBuckets(){let e=this.currentBar;return e===null||!this.builtFromTrades?!1:this.lastTradeAt===null?!this.startsABucket((0,t.normalizeBarTime)(e.time)):this.alignToTimeframe(this.lastTradeAt)!==e.time}startsABucket(e){return this.timeframeMs>0?this.dateStamps&&this.dateFrame?(0,t.timeframeBucketStart)(e,this.timeframe)===e:this.alignToTimeframe(e)===e:!0}alignToTimeframe(e){if(!(this.timeframeMs>0))return e;let n=(0,t.timeframeBucketStart)(e,this.timeframe,this.bucket);return!this.dateStamps||!this.dateFrame?n:n+(0,t.offsetAt)(this.bucket.timeZone??0,n)*oS}},lS=class extends aS{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))}},uS=20,dS=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),t===void 0?e!==this.price&&(this.previousClose=this.price??e):this.previousClose=t,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(e,t,n){this.renderLine(e,t,n),this.renderTag(e,t,n)}placed(t,n){let r=n.style?.lastPrice;if(!this.visible||this.price===null||r?.visible===!1)return null;let i=e.k(this.price,t),{chartRect:a}=t;return i<a.y||i>a.y+a.height?null:{y:i,color:this.previousClose===null||this.price>=this.previousClose?r?.up??n.candleUp??`#1fa874`:r?.down??n.candleDown??`#e8505b`}}renderLine(n,r,i){let a=this.placed(r,i);if(!a)return;let{y:o,color:s}=a,{chartRect:c}=r,l=i.style?.lastPrice,u=Date.now()<this.flashUntil,d=l?.width??1;n.setLineDash((0,t.lineDash)(l?.style??`solid`,[4,3],d)),n.strokeStyle=s,n.lineWidth=d,n.globalAlpha=u?1:.7,n.beginPath(),e.y(n,c.x,c.x+c.width,Math.round(o)+.5,d),n.stroke(),n.setLineDash([]),n.globalAlpha=1}renderTag(e,n,r){this.tag=null;let i=this.placed(n,r);if(!i||this.price===null)return;let{y:a,color:o}=i,{chartRect:s}=n,c=s.x+s.width+1,l=this.pricePrecision??(0,t.autoPricePrecision)(n.priceRange.min,n.priceRange.max),u=n.formatPrice?n.formatPrice(this.price):(0,t.formatPrice)(this.price,l,this.locale);e.font=`bold 11px ${r.font.family}`;let d=e.measureText(u).width,f=n.priceAxisWidth??t.PRICE_AXIS_WIDTH,p=Math.min(d+12,f-2);e.fillStyle=o,A(e,c,a-uS/2,p,uS,r),this.tag={x:c,y:a-uS/2,width:p,height:uS,color:o};let m=c-5;e.beginPath(),e.moveTo(m,a),e.lineTo(m+5,a-5),e.lineTo(m+5,a+5),e.closePath(),e.fill(),e.fillStyle=ne(o),e.textBaseline=`middle`,e.textAlign=`left`,e.fillText(u,c+5,a)}},fS=1e3,pS=10,mS=1440,hS=5e3,gS=2,_S=864e5,vS=6e4,yS=[`tick`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],bS=new WeakMap;function xS(e){if(e instanceof DS||!e.supportedTimeframes?.length)return e;let t=bS.get(e);return t||(t=new DS(e,e.supportedTimeframes),bS.set(e,t)),t}function SS(e,n,r){if(n.includes(e))return e;let i=(0,t.pickBaseTimeframe)(e,n,{timeZone:r});return i&&Math.ceil((0,t.timeframeToMs)(e)/(0,t.timeframeToMs)(i))<=1440?i:null}function CS(e,n){if((0,t.tickBarCount)(n)!==null)return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`;let r=e.supportedTimeframes;return!r?.length||SS(n,r)!==null}function wS(e,n,r){let i=(0,t.parseTimeframe)(n),a=r!==void 0&&(0,t.timeframeSpansDays)(n)&&e%_S!==0,o=a?e+(0,t.offsetAt)(r,e)*vS:e,s;if(i?.unit===`M`){let e=new Date(o);s=Date.UTC(e.getUTCFullYear(),e.getUTCMonth()+i.count,1)}else s=o+(0,t.timeframeToMs)(n);return a?(0,t.wallToUtc)(s,r):s}function TS(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}function ES(e,t){return TS(e,[...t.values()].sort((e,t)=>e.time-t.time))}var DS=class{name;fetchHistoryBefore;searchSymbols;resolveSymbol;subscribeQuotes;fetchNews;fetchTrades;subscribeTrades;listeners=new Map;unsubscribe=[];live=null;bucket=null;parts=new Map;closedBuckets=new Map;tail=null;generation=0;zones=new Map;resolving=new Map;unanswered=new Map;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=>this.resolveShared(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 yS)this.listen(e,t=>this.emit(e,t.data))}baseFor(e){let t=SS(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.closedBuckets.clear(),this.live=t===e.timeframe?null:{symbol:e.symbol,target:e.timeframe,...this.planFor(e.timeframe,this.keptZone(e.symbol))},this.live&&this.resumeFromHistory(this.live),this.inner.connect({...e,timeframe:this.live?.base??t})}disconnect(){this.generation++,this.inner.disconnect(),this.resetBucket(),this.closedBuckets.clear(),this.live=null}getConnectionState(){return this.inner.getConnectionState()}async fetchHistory(e,t,n=500){if(this.baseFor(t)===t)return this.inner.fetchHistory(e,t,n);let r=this.generation,{plan:i,bars:a}=await this.baseBarsWithZone(e,t,async i=>{let a=this.baseBarsFor(t,i,n),o=await this.inner.fetchHistory(e,i,Math.min(a,fS));return this.extendBack(e,i,o,a,r)});return this.rememberTail(e,t,a,i),this.toTarget(a,t,n,i)}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()}bucketFor(e,t){let n=SS(t,this.baseTimeframes);return n===null||n===t?null:{...this.planFor(t,this.keptZone(e)).bucket}}waitsForZone(e){return typeof this.inner.resolveSymbol==`function`&&(0,t.timeframeFollowsDays)(e)}keptZone(e){return this.zones.get(e)??void 0}renewZone(e){let t=this.unanswered.get(e);if(!t)return;let n=t.zone,r=t.asked!==void 0&&this.resolving.get(e)===t.asked;n===void 0&&r||(this.unanswered.delete(e),n===void 0?this.zones.delete(e):this.zones.set(e,n))}async zoneFor(e){if(this.zones.has(e))return this.keptZone(e);let t,n=new Promise(e=>{t=setTimeout(()=>e(),hS)});try{await Promise.race([this.resolveShared(e),n])}catch{}finally{clearTimeout(t)}return this.zones.has(e)||(this.zones.set(e,null),this.unanswered.set(e,{asked:this.resolving.get(e)})),this.keptZone(e)}resolveShared(e){let t=this.resolving.get(e);if(t)return t;let n=this.inner.resolveSymbol.bind(this.inner),r=Promise.resolve().then(()=>n(e));this.resolving.set(e,r);let i=()=>{this.resolving.get(e)===r&&this.resolving.delete(e)};return r.then(t=>{this.keepZone(e,t),i()},i),r}keepZone(e,n){let r=(0,t.symbolTimeZone)(n),i=r&&(0,t.isValidTimeZone)(r)&&!(0,t.isUtcTimeZone)(r)?r:null,a=this.unanswered.get(e);a?this.unanswered.set(e,{...a,zone:i}):this.zones.has(e)||this.zones.set(e,i)}planFor(e,n){let r=this.baseFor(e),i=n!==void 0&&r!==e&&(0,t.timeframeFollowsDays)(e)?SS(e,this.baseTimeframes,n):null,a=i??r,o=i?n:void 0;return{base:a,zone:o,bucket:{timeZone:o,dates:(0,t.timeframeSpansDays)(a)}}}async historyBefore(e,t,n,r){let i=this.inner.fetchHistoryBefore.bind(this.inner);if(this.baseFor(t)===t)return i(e,t,n,r);let a=this.generation,{plan:o,bars:s}=await this.baseBarsWithZone(e,t,async o=>{let s=this.baseBarsFor(t,o,r),c=await i(e,o,n,Math.min(s,fS));return this.extendBack(e,o,c.filter(e=>e.time<n),s,a,1)});return this.toTarget(s,t,r,o)}async baseBarsWithZone(e,t,n){if(!this.waitsForZone(t)||this.zones.has(e)){let r=this.planFor(t,this.keptZone(e));return{plan:r,bars:await n(r.base)}}let r=this.planFor(t,void 0).base,i=n(r);i.catch(()=>{});let a=this.planFor(t,await this.zoneFor(e));return{plan:a,bars:await(a.base===r?i:n(a.base))}}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,fS));c++;let a=i.filter(e=>e.time<n);if(a.length===0)break;s=a.concat(s)}return s}toTarget(e,n,r,i){if(e.length===0)return[];let a=(0,t.resampleBars)(e,n,i.bucket);return a.length>1&&a[0].time!==e[0].time&&a.shift(),a.length>r?a.slice(a.length-r):a}rememberTail(e,n,r,i){if(r.length===0)return;let a=(0,t.timeframeBucketStart)(r[r.length-1].time,n,i.bucket),o=r.length;for(;o>0&&(0,t.timeframeBucketStart)(r[o-1].time,n,i.bucket)===a;)o--;this.tail={symbol:e,target:n,zone:i.zone,bucket:a,bars:r.slice(o)}}resumeFromHistory(e){let t=this.tail;if(!(!t||t.symbol!==e.symbol||t.target!==e.target||t.zone!==e.zone)){this.bucket=t.bucket;for(let e of t.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,n.bucket);if(this.bucket!==null&&a<this.bucket){i&&this.correctClosed(a,r);return}if(this.bucket!==null&&a>this.bucket){let e=this.composed();e&&this.emit(`bar`,{bar:e,closed:!0}),this.keepClosed(),this.resetBucket()}this.bucket=a,this.parts.set(r.time,r);let o=this.composed();if(!o)return;let s=(0,t.timeframeBucketStart)(wS(r.time,n.base,n.zone),n.target,n.bucket),c=i&&s!==a;this.emit(`bar`,{bar:o,closed:c}),c&&(this.keepClosed(),this.resetBucket(),this.bucket=s)}composed(){return this.bucket===null||this.parts.size===0?null:ES(this.bucket,this.parts)}correctClosed(e,t){let n=this.closedBuckets.get(e);n&&(n.set(t.time,t),this.emit(`bar`,{bar:ES(e,n),closed:!0}))}keepClosed(){if(!(this.bucket===null||this.parts.size===0)){this.closedBuckets.set(this.bucket,this.parts);for(let e of this.closedBuckets.keys()){if(this.closedBuckets.size<=2)break;this.closedBuckets.delete(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)}},OS=1e3,kS=15e3,AS=[`tick`,`bar`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],jS=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)}},MS=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 AS)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,OS)).filter(IS).sort((e,t)=>e.time-t.time),o=new jS(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 jS(n),after:-1/0};this.tick=r,this.stopTrades=this.inner.subscribeTrades(e.symbol,e=>{let t=e.filter(e=>IS(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`),kS)}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)}},NS=new WeakMap;function PS(e){if(e instanceof MS||!FS(e))return e;let t=NS.get(e);return t||(t=new MS(e),NS.set(e,t)),t}function FS(e){return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`}function IS(e){return Number.isFinite(e?.time)&&Number.isFinite(e?.price)&&Number.isFinite(e?.volume)}var LS=Symbol(`tradecanvas.sourceAdapter`),RS=new WeakSet;function zS(e){return RS.has(e)}var BS=(e,t)=>`${e}\u0000${t}`;function VS(e){return typeof e.getBars==`function`&&typeof e.subscribeBars==`function`}function HS(e){if(e.adapter&&e.feed)throw TypeError(`A stream takes an adapter or a feed, not both`);if(e.adapter)return e.adapter;if(e.feed)return GS(e.feed);throw TypeError(`A stream needs an adapter or a feed`)}function US(e,t,n){for(let r of n){let n=t[r];typeof n==`function`&&(e[r]=n.bind(t))}}var WS=[`resolveSymbol`,`searchSymbols`,`subscribeQuotes`,`fetchNews`,`fetchTrades`,`subscribeTrades`];function GS(e){let t=e[LS];if(t)return t;let n=new KS(e);return RS.add(n),n}var KS=class{name;supportedTimeframes;fetchHistoryBefore;state=`disconnected`;listeners=new Map;unsubscribe=null;requests=new Map;streamed=null;constructor(e){this.feed=e,this.name=e.name,e.supportedTimeframes&&(this.supportedTimeframes=e.supportedTimeframes),e.pagesBack!==!1&&(this.fetchHistoryBefore=(e,t,n,r)=>this.feed.getBars({symbol:e,timeframe:t,countBack:r,before:n,signal:this.signalFor(e,t)})),US(this,e,WS)}fetchHistory(e,t,n=500){return this.feed.getBars({symbol:e,timeframe:t,countBack:n,signal:this.signalFor(e,t)})}fetchStreamHistory(e,t){return this.streamed=BS(e.symbol,e.timeframe),this.fetchHistory(e.symbol,e.timeframe,t)}connect(e){this.subscribe({symbol:e.symbol,timeframe:e.timeframe})}subscribe(e,t){this.stopSubscription(),this.streamed=BS(e.symbol,e.timeframe);let n=!0,r=!1,i=null;this.unsubscribe=()=>{n=!1,i?.()};let a=e=>{this.setState(e),t?.connection(e)},o=this.feed.subscribeBars(e,{bar:(e,r)=>{n&&(this.emit(`bar`,{bar:e,closed:r}),t?.bar(e,r))},tick:e=>{n&&(this.emit(`tick`,e),t?.tick(e))},connection:e=>{n&&(r=!0,a(e))},symbolInfo:e=>{n&&(this.emit(`symbolInfo`,e),t?.symbolInfo(e))},error:e=>{n&&(this.emit(`error`,{message:e}),t?.error(e))}});if(!n){o();return}i=o,r||a(`connected`)}disconnect(){this.stopSubscription(),this.streamed!==null&&(this.requests.get(this.streamed)?.abort(),this.requests.delete(this.streamed),this.streamed=null),this.state=`disconnected`}getConnectionState(){return this.state}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()}signalFor(e,t){let n=BS(e,t),r=this.requests.get(n);return r||(r=new AbortController,this.requests.set(n,r)),r.signal}stopSubscription(){let e=this.unsubscribe;this.unsubscribe=null,e?.()}setState(e){this.state=e,this.emit(`connectionChange`,e)}emit(e,t){let n={type:e,data:t,timestamp:Date.now()};for(let t of[...this.listeners.get(e)??[]])t(n)}};function qS(e){let t={name:e.name,...e.supportedTimeframes?{supportedTimeframes:e.supportedTimeframes}:{},pagesBack:typeof e.fetchHistoryBefore==`function`,getBars:async({symbol:t,timeframe:n,countBack:r,before:i})=>i===void 0?e.fetchHistory(t,n,r):e.fetchHistoryBefore?e.fetchHistoryBefore(t,n,i,r):[],subscribeBars:(t,n)=>JS(e,t,n),[LS]:e};return US(t,e,WS),t}function JS(e,t,n){let r=[[`bar`,e=>{let{bar:t,closed:r}=e.data;n.bar(t,r)}],[`tick`,e=>n.tick(e.data)],[`connectionChange`,e=>n.connection(e.data)],[`symbolInfo`,e=>n.symbolInfo(e.data)],[`error`,e=>n.error(e.data?.message??`Adapter error`)]];for(let[t,n]of r)e.on(t,n);return e.connect({symbol:t.symbol,timeframe:t.timeframe}),()=>{for(let[t,n]of r)e.off(t,n);e.disconnect()}}function YS(e){let t=HS(e),n=!zS(t),r=xS(t),i=r instanceof DS?r:null,a=PS(r);return a instanceof KS?new XS(a,i,n):new ZS(a,i,n)}var XS=class{subscriber=null;constructor(e,t,n){this.adapter=e,this.resampler=t,this.watchSilence=n}listen(e){this.subscriber=e}getBars(e,t){return this.adapter.fetchStreamHistory(e,t)}subscribeBars(e){this.adapter.subscribe(e,this.subscriber??void 0)}unsubscribe(){this.adapter.disconnect()}release(){this.subscriber=null}},ZS=class{unlisten=[];constructor(e,t,n){this.adapter=e,this.resampler=t,this.watchSilence=n}listen(e){this.hear(`connectionChange`,t=>e.connection(t.data)),this.hear(`tick`,t=>e.tick(t.data)),this.hear(`bar`,t=>{let{bar:n,closed:r}=t.data;e.bar(n,r)}),this.hear(`error`,t=>e.error(t.data?.message??`Adapter error`));try{this.hear(`symbolInfo`,t=>e.symbolInfo(t?.data))}catch{}}getBars(e,t){return this.adapter.fetchHistory(e.symbol,e.timeframe,t)}subscribeBars(e){this.adapter.connect({symbol:e.symbol,timeframe:e.timeframe})}unsubscribe(){this.adapter.disconnect()}release(){for(let e of this.unlisten)e();this.unlisten=[]}hear(e,t){this.adapter.on(e,t),this.unlisten.push(()=>this.adapter.off(e,t))}},QS=2e4,$S=6e4,eC=3e4,tC=500,nC=864e5;function rC(e,n){if(!n)return e;let{time:r,open:i,high:a,low:o,close:s,volume:c}=n;return[...e,{time:(0,t.normalizeBarTime)(r)/(0,t.barTimeUnit)(e),open:i,high:a,low:o,close:s,volume:c}]}function iC(e,n,r){return(0,t.timeframeBucketStart)(e,n,{timeZone:r})===e&&(0,t.timeframeBucketStart)(e,n)!==e}var aC=class extends aS{config=null;source=null;aggregator=null;reconnector;priceLine=new dS;state=`disconnected`;lastPrice=null;previousClose=null;sentPreviousClose=null;previousCloseTime=null;heartbeatTimer=null;lastMessageTime=0;connectSeq=0;timeZone=null;historyEnd=null;constructor(){super(),this.reconnector=new lS,this.wireReconnector()}async connect(e){this.disconnect();let n=YS(e);n.resampler?.renewZone(e.symbol),this.config={...t.DEFAULT_STREAM_CONFIG,...e},this.source=n,this.aggregator=new cS(e.timeframe),this.historyEnd=null,this.applyTickZone(),this.reconnector.removeAllListeners(),this.reconnector.stop(),this.reconnector=new lS(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.setPreviousClose(e),this.emit(`barClose`,e)}),this.aggregator.on(`correction`,e=>{(0,t.normalizeBarTime)(e.time)===this.previousCloseTime&&(this.previousClose=e.close),this.emit(`barCorrection`,e)}),n.listen(this.subscriber()),this.reconnector.start(),await this.doConnect()}disconnect(){this.connectSeq++,this.reconnector.stop(),this.stopHeartbeat(),this.source&&=(this.source.release(),this.source.unsubscribe(),null),this.aggregator?.reset(),this.aggregator?.removeAllListeners(),this.aggregator=null,this.config=null,this.historyEnd=null,this.lastPrice=null,this.previousClose=null,this.previousCloseTime=null,this.sentPreviousClose=null,this.setState(`disconnected`)}async switchTo(e,t){!this.config||!this.source||(this.reconnector.stop(),this.source.unsubscribe(),this.reconnector.start(),this.aggregator?.reset(),this.aggregator?.setTimeframe(t),this.lastPrice=null,this.previousClose=null,this.previousCloseTime=null,this.sentPreviousClose=null,(e!==this.config.symbol||t!==this.config.timeframe)&&this.source.resampler?.renewZone(e),this.config.symbol=e,this.config.timeframe=t,await this.doConnect())}getConnectionState(){return this.state}setTimeZone(e){if(e!==null&&!(0,t.isValidTimeZone)(e))throw RangeError(`Unknown time zone: ${e}`);this.timeZone=e,this.applyTickZone()}getConnectionInfo(){return{state:this.state,reconnectAttempt:this.reconnector.getAttempt(),lastMessageTime:this.lastMessageTime}}getLastPrice(){return this.lastPrice}applyTickZone(){let e=this.config;if(!this.aggregator||!e)return;let t=this.historyEnd,n=t!==null&&t%nC===0,r=this.source?.resampler?.bucketFor(e.symbol,e.timeframe);if(r){let e=r.dates===!0&&n;this.aggregator.setTimeZone(r.timeZone??(e?this.timeZone:null),e);return}this.aggregator.setTimeZone(this.tickZone(e.timeframe,t),n)}tickZone(e,n){let r=this.timeZone;return r===null||(0,t.timeframeSpansDays)(e)||n!==null&&iC(n,e,r)?r:null}async doConnect(){if(!this.config||!this.source)return;let e=++this.connectSeq,n={symbol:this.config.symbol,timeframe:this.config.timeframe};this.setState(`connecting`);try{let r=await this.source.getBars(n,this.config.historyLimit??tC);if(e!==this.connectSeq||!this.source)return;let i=r.length>0?r[r.length-1]:null;this.historyEnd=i?(0,t.normalizeBarTime)(i.time):null,this.applyTickZone(),this.seedAggregator(i);let a=this.formingAfter(i);i&&!a&&(this.setPreviousClose(i),this.updatePrice(i.close)),this.emit(`snapshot`,rC(r,a)),this.source.subscribeBars(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.state=`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`})})}subscriber(){return{connection:e=>this.onConnection(e),tick:e=>this.onTick(e),bar:(e,t)=>this.onBar(e,t),error:e=>this.emit(`error`,{message:e??`Adapter error`}),symbolInfo:e=>{e&&typeof e==`object`&&this.emit(`symbolInfo`,e)}}}onConnection(e){this.lastMessageTime=Date.now(),e===`connected`?(this.reconnector.onConnected(),this.setState(`connected`)):(e===`disconnected`||e===`error`)&&this.reconnector.schedule(()=>this.doConnect())}onTick(e){this.lastMessageTime=Date.now(),this.emit(`tick`,e),(e.bid!==void 0||e.ask!==void 0)&&this.emit(`quote`,{bid:e.bid,ask:e.ask}),this.config?.aggregateTicks&&this.aggregator?this.aggregator.processTick(e):this.updatePrice(e.price)}onBar(e,t){this.lastMessageTime=Date.now(),this.aggregator?.processBar(e,t)}setPreviousClose(e){this.previousClose=e.close,this.previousCloseTime=(0,t.normalizeBarTime)(e.time)}seedAggregator(e){this.aggregator&&(this.aggregator.seed(e?e.time:-1/0),e&&this.config?.aggregateTicks&&this.aggregator.resume(e))}formingAfter(e){let n=this.aggregator?.getCurrentBar()??null;return!n||e&&(0,t.normalizeBarTime)(n.time)<=(0,t.normalizeBarTime)(e.time)?null:n}updatePrice(e){e===this.lastPrice&&this.previousClose===this.sentPreviousClose||(this.lastPrice=e,this.sentPreviousClose=this.previousClose,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.source||!this.config||this.state===`connecting`||this.state===`disconnected`||this.state===`connected`&&e===`visible`&&(!this.source.watchSilence||Date.now()-this.lastMessageTime<=QS)||(this.reconnector.stop(),this.source.unsubscribe(),this.reconnector.start(),this.doConnect())}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.source?.watchSilence===!0&&Date.now()-this.lastMessageTime>$S&&this.state===`connected`&&(this.emit(`error`,{message:`Heartbeat timeout`,code:`HEARTBEAT_TIMEOUT`}),this.source?.unsubscribe(),this.reconnector.schedule(()=>this.doConnect()))},eC)}stopHeartbeat(){this.heartbeatTimer&&=(clearInterval(this.heartbeatTimer),null)}dispose(){this.disconnect(),this.removeAllListeners()}},oC=class extends aS{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 sC(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=lC(e[1]),r=lC(e[2]),i=lC(e[3]),a=lC(e[4]),o=lC(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 cC(e){if(!uC(e))return null;let t=e.t;if(typeof t!=`number`||!Number.isFinite(t))return null;let n=lC(e.o),r=lC(e.h),i=lC(e.l),a=lC(e.c),o=lC(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 lC(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 uC(e){return typeof e==`object`&&!!e}function Z(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:void 0}function dC(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:Z(r.c),open:Z(r.o),high:Z(r.h),low:Z(r.l),volume:Z(r.v),time:Z(r.E)}):null}function fC(e){if(!e||typeof e!=`object`)return null;let n=e;return(0,t.readQuote)({symbol:n.symbol,last:Z(n.lastPrice),change:Z(n.priceChange),changePercent:Z(n.priceChangePercent),open:Z(n.openPrice),high:Z(n.highPrice),low:Z(n.lowPrice),prevClose:Z(n.prevClosePrice),volume:Z(n.volume),bid:Z(n.bidPrice),ask:Z(n.askPrice),time:Z(n.closeTime)})}function pC(e){if(!e||typeof e!=`object`)return null;let t=e,n=Z(t.T),r=Z(t.p),i=Z(t.q);return n!==void 0&&r!==void 0&&i!==void 0?{time:n,price:r,volume:i}:null}var mC=64,hC=(e,t)=>`${e}|${t}`,gC=class{last=new Map;serve(e,t,n){if(!Array.isArray(n)||n.length===0)return;let r=n[n.length-1],i=Number(r?.time);if(!Number.isFinite(i))return;let a=hC(e,t);this.last.delete(a),this.last.set(a,{time:i,close:Number(r?.close??NaN)}),this.last.size>mC&&this.last.delete(this.last.keys().next().value)}lastBar(e,t){return this.last.get(hC(e,t))}},_C=class{newest=-1/0;servedClose=null;served=new gC;serve(e,t,n){this.served.serve(e,t,n)}reset(e,n){let r=this.served.lastBar(e,n);this.newest=r===void 0?-1/0:(0,t.normalizeBarTime)(r.time),this.servedClose=r?.close??null}admit(e,n=!1){let r=(0,t.normalizeBarTime)(e.time);return Number.isFinite(r)?r<this.newest||r===this.newest&&n&&e.close===this.servedClose?!1:(this.servedClose=null,this.newest=r,!0):!0}},vC={"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`},yC=1e3,bC=200,xC=[`USDT`,`USDC`,`FDUSD`,`BTC`,`ETH`,`BNB`,`EUR`,`TRY`,`BRL`,`JPY`];function SC(e){let t=e.currency?xC.indexOf(e.currency):-1;return t<0?0:40-t*3}function CC(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 wC(e){let t=e?.symbols;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=CC(e);t&&n.push(t)}return n}var TC=class{name=`binance`;supportedTimeframes=Object.keys(vC);ws=null;state=`disconnected`;listeners=new Map;config=null;restBase;wsBase;symbolList=null;newestBar=new _C;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.newestBar.reset(e.symbol,e.timeframe),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}async fetchHistory(e,t,n=500){let r=await this.fetchKlines(e,t,n,``);return this.newestBar.serve(e,t,r),r}async searchSymbols(e,n){return(0,t.rankSymbols)(await this.loadSymbols(),e,n?.limit??50,SC)}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?wC(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 wC(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,bC);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(fC).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=dC(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(pC).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=pC(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,yC),`&endTime=${Math.floor(n)-1}`)}async fetchKlines(e,t,n,r){let i=vC[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=sC(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_${vC[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=cC(e);if(!t)return;let{bar:n,closed:r}=t,i=this.newestBar.admit(n,r);this.emitEvent(`bar`,{bar:n,closed:r}),i&&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)}}},EC=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+DC(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+DC(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+DC(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 DC(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t}var OC=class{name;supportedTimeframes;ws=null;state=`disconnected`;config=null;listeners=new Map;opts;newestBar=new _C;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.newestBar.reset(e.symbol,e.timeframe),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){let r=this.opts.fetchHistory(e,t,n??this.opts.defaultHistoryLimit??500);return Promise.resolve(r).then(n=>(this.newestBar.serve(e,t,n),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()}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}if(!r)return;let i=r.bar?this.newestBar.admit(r.bar,r.closed??!1):!1;r.bar&&this.emitEvent(`bar`,{bar:r.bar,closed:r.closed??!1}),r.tick?this.emitEvent(`tick`,r.tick):r.bar&&i&&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)}}},kC=class{name;supportedTimeframes;state=`disconnected`;listeners=new Map;config=null;timer=null;lastBarTime=0;served=new gC;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=this.served.lastBar(e.symbol,e.timeframe)?.time??0,this.state=`connected`,this.emitEvent(`connectionChange`,`connected`),this.startPolling()}disconnect(){this.stopPolling(),this.state=`disconnected`,this.emitEvent(`connectionChange`,`disconnected`)}getConnectionState(){return this.state}async fetchHistory(e,t,n){let r=await this.opts.fetchBars(e,t,n??this.opts.defaultHistoryLimit??500);return this.served.serve(e,t,r),r}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(!(n.time<this.lastBarTime)){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 Q(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 AC(e){return typeof e==`object`&&!!e}var jC={"1m":60,"5m":300,"15m":900,"1h":3600,"6h":21600,"1d":86400};function MC(e){return jC[e]??3600}var NC=class extends kC{constructor(e={}){let t=e.restBase??`https://api.exchange.coinbase.com`;super({name:`coinbase`,supportedTimeframes:Object.keys(jC),intervalMs:e.intervalMs??5e3,pollLimit:2,fetchBars:(e,n)=>PC(t,e,n)})}};async function PC(e,t,n){let r=`${e}/products/${t}/candles?granularity=${MC(n)}`,i=await fetch(r);if(!i.ok)throw Error(`Coinbase REST error: ${i.status}`);return FC(await i.json())}function FC(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=IC(n);e&&t.push(e)}return t.sort((e,t)=>e.time-t.time),t}function IC(e){if(!Array.isArray(e)||e.length<6)return null;let t=Q(e[0]),n=Q(e[1]),r=Q(e[2]),i=Q(e[3]),a=Q(e[4]),o=Q(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 LC={"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 RC(e){return LC[e]??`1`}var zC=class extends OC{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.${RC(e.timeframe)}.${e.symbol}`]}),unsubscribeMessage:e=>({op:`unsubscribe`,args:[`kline.${RC(e.timeframe)}.${e.symbol}`]}),supportedTimeframes:Object.keys(LC),parseMessage:BC,fetchHistory:(e,n,i)=>VC(t,r,e,n,i),fetchHistoryBefore:(e,n,i,a)=>VC(t,r,e,n,a,Math.floor(i)-1)})}};function BC(e){if(!AC(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(!AC(n))return null;let r=Q(n.start),i=Q(n.open),a=Q(n.high),o=Q(n.low),s=Q(n.close),c=Q(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 VC(e,t,n,r,i,a){let o=`${e}/v5/market/kline?category=${t}&symbol=${n}&interval=${RC(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 HC(await s.json())}function HC(e){if(!AC(e)||!AC(e.result))return[];let t=e.result.list;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=UC(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function UC(e){if(!Array.isArray(e)||e.length<6)return null;let t=Q(e[0]),n=Q(e[1]),r=Q(e[2]),i=Q(e[3]),a=Q(e[4]),o=Q(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 WC={"1m":1,"5m":5,"15m":15,"30m":30,"1h":60,"4h":240,"1d":1440,"1w":10080};function GC(e){return WC[e]??1}var KC=class extends OC{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:GC(e.timeframe)}}),unsubscribeMessage:e=>({method:`unsubscribe`,params:{channel:`ohlc`,symbol:[e.symbol],interval:GC(e.timeframe)}}),supportedTimeframes:Object.keys(WC),parseMessage:qC,fetchHistory:(e,n)=>JC(t,e,n)})}};function qC(e){if(!AC(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(!AC(n))return null;let r=Q(n.open),i=Q(n.high),a=Q(n.low),o=Q(n.close),s=Q(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 JC(e,t,n){let r=GC(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 YC(await o.json())}function YC(e){if(!AC(e)||!AC(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=XC(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function XC(e){if(!Array.isArray(e)||e.length<7)return null;let t=Q(e[0]),n=Q(e[1]),r=Q(e[2]),i=Q(e[3]),a=Q(e[4]),o=Q(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 ZC=200,QC={"1m":`minutes/1`,"3m":`minutes/3`,"5m":`minutes/5`,"15m":`minutes/15`,"30m":`minutes/30`,"1h":`minutes/60`,"4h":`minutes/240`,"1d":`days`,"1w":`weeks`,"1M":`months`},$C={"1m":`candle.1m`,"3m":`candle.3m`,"5m":`candle.5m`,"15m":`candle.15m`,"30m":`candle.30m`,"1h":`candle.60m`,"4h":`candle.240m`,"1d":`ticker`};function ew(e){return QC[e]??null}function tw(e){return $C[e]??null}var nw=class extends OC{constructor(e={}){let t=e.restBase??`https://api.upbit.com`,n=e.wsUrl??`wss://api.upbit.com/websocket/v1`;super({name:`upbit`,wsUrl:()=>n,socketFactory:e.socketFactory??rw,decode:aw,subscribeMessage:e=>[{ticket:`tradecanvas`},{type:tw(e.timeframe)??`candle.1m`,codes:[e.symbol]},{format:`DEFAULT`}],supportedTimeframes:Object.keys($C),parseMessage:ow,fetchHistory:(e,n,r)=>lw(t,e,n,r),fetchHistoryBefore:(e,n,r,i)=>lw(t,e,n,i,r)})}};function rw(e){let t=globalThis.WebSocket;if(!t)throw Error(`No WebSocket implementation available`);let n=new t(e);return n.binaryType=`arraybuffer`,n}var iw=null;function aw(e){if(typeof e==`string`)return JSON.parse(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return JSON.parse((iw??=new TextDecoder).decode(e))}function ow(e){if(!AC(e)||typeof e.type!=`string`)return null;if(e.type.startsWith(`candle.`)){let t=cw(e,e.candle_date_time_utc,e.candle_acc_trade_volume);return t?{bar:t,closed:!1}:null}if(e.type===`ticker`&&typeof e.trade_date==`string`&&/^\d{8}$/.test(e.trade_date)){let t=e.trade_date,n=cw(e,`${t.slice(0,4)}-${t.slice(4,6)}-${t.slice(6,8)}T00:00:00`,e.acc_trade_volume);return n?{bar:n,closed:!1}:null}return null}function sw(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=AC(n)?cw(n,n.candle_date_time_utc,n.candle_acc_trade_volume):null;e&&t.push(e)}return t.sort((e,t)=>e.time-t.time),t}function cw(e,t,n){let r=typeof t==`string`?Date.parse(`${t}Z`):NaN,i=Q(e.opening_price),a=Q(e.high_price),o=Q(e.low_price),s=Q(e.trade_price),c=Q(n);return!Number.isFinite(r)||i===null||a===null||o===null||s===null||c===null?null:{time:r,open:i,high:a,low:o,close:s,volume:c}}async function lw(e,t,n,r,i){let a=ew(n);if(!a)throw Error(`Upbit has no ${n} candles`);let o=new URLSearchParams({market:t,count:String(Math.min(Math.max(Math.floor(r),1),200))});i!==void 0&&o.set(`to`,new Date(i).toISOString().replace(/\.\d{3}Z$/,`Z`));let s=await fetch(`${e}/v1/candles/${a}?${o}`);if(!s.ok)throw Error(`Upbit REST error: ${s.status}`);return sw(await s.json())}var uw=(e,t)=>`${e}\u0000${t}`,dw=class{name;series=new Map;subscribers=new Map;constructor(e={}){this.name=e.name??`manual`}setBars(e,t,n){let r=n.map(e=>({...e})).sort((e,t)=>e.time-t.time);this.series.set(uw(e,t),r)}pushBar(e,t,n,r=!1){let i=uw(e,t),a=this.series.get(i)??[],o=a[a.length-1],s={...n},c=r;if(!o||s.time>o.time)this.series.set(i,[...a,s]);else{let n=a.findIndex(e=>e.time===s.time);if(n<0)throw RangeError(`ManualFeed: no ${e} ${t} bar at ${s.time} to replace`);n<a.length-1&&(c=!0),this.series.set(i,a.map((e,t)=>t===n?s:e))}for(let e of[...this.subscribers.get(i)??[]])e.bar({...s},c)}async getBars(e){let t=this.series.get(uw(e.symbol,e.timeframe))??[],{before:n}=e,r=n===void 0?t.length:fw(t,n);return t.slice(Math.max(0,r-e.countBack),r).map(e=>({...e}))}subscribeBars(e,t){let n=uw(e.symbol,e.timeframe),r=this.subscribers.get(n);return r||(r=new Set,this.subscribers.set(n,r)),r.add(t),()=>{r.delete(t),r.size===0&&this.subscribers.delete(n)}}};function fw(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].time<t?n=i+1:r=i}return n}var pw={visible:!0,showSymbol:!0,showOHLC:!0,showChange:!0,showVolume:!0,position:`top-left`,fontSize:12,fontFamily:null,ground:!0},mw=class{config={...pw};symbol=``;timeframe=``;hoverBar=null;hoverPrev=null;indicators=[];statusText=null;exchange=``;drawnHeight=null;drawnWidth=0;locale=`en-US`;inset=gw;top=hw;lineGap=_w;pricePrecision=null;reportedHeight=null;resizeListener=null;setResizeListener(e){this.resizeListener=e}forgetHeight(){this.drawnHeight=null,this.reportedHeight=null}reportResize(){let e=this.getHeight();e!==this.reportedHeight&&(this.reportedHeight=e,this.resizeListener?.())}setConfig(e){Object.assign(this.config,e),this.forgetHeight()}getConfig(){return{...this.config}}setPricePrecision(e){this.pricePrecision=e}setLocale(e){this.locale=e}setSymbol(e){e!==this.symbol&&(this.symbol=e,this.forgetHeight())}setTimeframe(e){e!==this.timeframe&&(this.timeframe=e,this.forgetHeight())}setChartType(e){}setHoverBar(e,t=null){this.hoverBar=e,this.hoverPrev=e?t:null}setIndicatorValues(e){this.indicators=e}setStatusText(e){e!==this.statusText&&(this.statusText=e,this.forgetHeight())}setExchange(e){e!==this.exchange&&(this.exchange=e,this.forgetHeight())}title(){return this.config.showSymbol?[(0,t.tickerOf)(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:Sw(e,t.value),font:l}))}setSpacing(e){e.inset===this.inset&&e.top===this.top&&e.lineGap===this.lineGap||(this.inset=e.inset,this.top=e.top,this.lineGap=e.lineGap,this.drawnHeight=null)}getInset(){return this.inset}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=this.top;return(this.config.showOHLC||this.title()||this.statusText)&&(t+=e+this.lineGap),this.config.showVolume&&(t+=e+2),t}getWidth(){return!this.config.visible||this.config.position!==`top-left`?0:this.drawnWidth}render(e,n,r,i){if(!this.config.visible)return this.reportResize();if(i.length===0)return;let a=this.hoverBar??i[i.length-1],o=this.hoverBar?this.hoverPrev??a:i.length>1?i[i.length-2]:a,{chartRect:s}=n,c=this.config.fontSize,l=this.config.fontFamily??r.font.family,u=r.style?.legend.text??r.text,d=r.style?.legend.label??r.textSecondary,f=this.config.position===`top-left`,p=f?s.x+this.inset:s.x+s.width-this.inset,m=s.y+this.top;e.textAlign=f?`left`:`right`,e.textBaseline=`top`;let h=0,g=this.titleCells(e,c,l,u,d);if(this.config.showOHLC&&g.push(...this.priceCells(e,n,r,a,o,c,l,u)),g.length>0){e.font=`${c}px ${l}`;let t=e.measureText(` `).width;for(let n of xw(g,t,s.width-2*this.inset)){let i=n.reduce((e,n)=>e+n.labelWidth+n.width+t,-t);h=Math.max(h,i);let a=f?p:p-i;this.drawGround(e,r,a,m,i,c),e.textAlign=`left`;for(let r of n)e.font=r.font,r.label&&(e.fillStyle=d,e.fillText(r.label,a,m),a+=r.labelWidth),e.fillStyle=r.color,e.fillText(r.value,a,m),a+=r.width+t;m+=c+this.lineGap}e.textAlign=f?`left`:`right`}if(this.config.showVolume){e.font=`${c}px ${l}`,e.fillStyle=d;let n=(0,t.formatVolumeLoc)(a.volume,this.locale),i=e.measureText(`Vol ${n}`).width;this.drawGround(e,r,f?p:p-i,m,i,c),e.fillStyle=d,e.fillText(`Vol ${n}`,p,m),h=Math.max(h,i),m+=c+2}if(this.drawnHeight=f?m-s.y:null,this.drawnWidth=f?this.inset+h:0,this.reportResize(),this.indicators.length>0){e.font=`${c}px ${l}`;let t=e.measureText(` `).width,n=this.indicators.map(t=>{let n=`${t.name} ${t.value}`;return{entry:n,color:t.color,width:Sw(e,n)}}),i=n.reduce((e,n)=>e+n.width+t,-t),a=f?p:p-i;this.drawGround(e,r,a,m,i,c),e.textAlign=`left`;for(let{entry:r,color:i,width:o}of n)e.fillStyle=i,e.fillText(r,a,m),a+=o+t}}drawGround(e,t,n,r,i,a){!this.config.ground||i<=0||(e.save(),e.globalAlpha=vw,e.fillStyle=t.background,e.fillRect(n-yw,r-bw,i+2*yw,a+this.lineGap),e.restore())}},{legendTop:hw,legendInset:gw,legendLineGap:_w}=t.CHART_SPACING[t.DEFAULT_CHART_DENSITY],vw=.72,yw=3,bw=1;function xw(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 Sw(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 Cw=class{static toDataURL(e,t){return this.compose(e,t)?.toDataURL(`image/png`)??``}static async toBlob(e,t){let n=this.compose(e,t);return n?new Promise(e=>n.toBlob(e,`image/png`)):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)}static compose(e,t){let n=e.querySelectorAll(`canvas`);if(n.length===0)return null;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}},ww=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()}},Tw={solid:null,dashed:[6,4],dotted:[2,3]},Ew=6;function Dw(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 Ow=class{config={visible:!1};cachedBreaksTyped=[];cachedMedianStep=0;cacheValid=!1;lastDataLength=0;firstTime=NaN;lastTime=NaN;tz=null;setConfig(e){Object.assign(this.config,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[];let n=this.lastDataLength,r=this.cacheValid&&e.length>=n&&e[0].time===this.firstTime&&e[n-1].time===this.lastTime;if(r&&e.length===n)return this.cachedBreaksTyped;let i=r?this.cachedBreaksTyped.slice():[],a=(0,t.barTimeUnit)(e),o=r?n:1,s=(0,t.timeParts)(e[o-1].time*a,this.tz);for(let n=o;n<e.length;n++){let r=(0,t.timeParts)(e[n].time*a,this.tz);if(r.year!==s.year)i.push({idx:n,kind:`year`});else if(r.month!==s.month)i.push({idx:n,kind:`month`});else if(r.day!==s.day){let e=new Date(Date.UTC(r.year,r.month-1,r.day)).getUTCDay()===1;i.push({idx:n,kind:e?`week`:`day`})}s=r}return this.lastDataLength=e.length,this.firstTime=e[0].time,this.lastTime=e[e.length-1].time,this.cachedBreaksTyped=i,r||(this.cachedMedianStep=kw(e)),this.cacheValid=!0,i}render(e,t,n,r){this.renderLines(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=Tw[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()}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=Tw[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 Dw(this.marks(e,t,n),Ew)}marks(t,n,r){if(!this.config.visible||n.length<2)return[];let i=this.computeBreaksTyped(n);if(i.length===0||this.cachedMedianStep>=1380*60*1e3)return[];let{chartRect:a}=t,o=this.look(r).width,s=[];for(let n of i){let r=e.w(n.idx,t)-(t.barWidth+t.barSpacing)/2;if(r<a.x-1||r>a.x+a.width+1)continue;let i=Math.round(r)+.5,c=.25,l=o,u=3;n.kind===`day`?(c=.22,u=0):n.kind===`week`?(c=.34,u=1):n.kind===`month`?(c=.5,u=2,l=o+.5):(c=.7,l=o+1),s.push({px:i,width:l,alpha:c,rank:u})}return s}invalidateCache(){this.lastDataLength=0,this.cachedBreaksTyped=[],this.cachedMedianStep=0,this.cacheValid=!1}};function kw(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 Aw=864e5;function jw(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 Mw(e,t){let n=((e+t*6e4)%Aw+Aw)%Aw;return Math.floor(n/6e4)}function Nw(e,t,n){return t===n?!0:t<n?e>=t&&e<n:e>=t||e<n}function Pw(e,n){let r=Mw(e,n.timeZone?(0,t.zoneOffsetMinutes)(n.timeZone,e):n.tzOffsetMinutes??0);return n.windows&&n.windows.length>0?n.windows.some(e=>Nw(r,e.startMinute,e.endMinute)):Nw(r,n.startMinute,n.endMinute)}var Fw={startMinute:570,endMinute:960,tzOffsetMinutes:-300,timeZone:`America/New_York`},Iw=class{visible=!1;config={...Fw};setVisible(e){this.visible=e}isVisible(){return this.visible}setConfig(e){this.config=jw(this.config,e)}replaceConfig(e){this.config=jw(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.w(t,n)-l/2,o=e.w(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=!Pw(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}},Lw=[2,3],Rw=16,zw=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(Lw),t.lineWidth=1;for(let o of this.levels(i,n)){let i=Math.round(e.k(o.price,n))+.5;i<a.y||i>a.y+a.height||(t.strokeStyle=Bw(o.kind,r),t.beginPath(),e.y(t,a.x,a.x+a.width,i),t.stroke())}t.restore()}renderAxisTags(n,r,i,a,o){let{chartRect:s}=r,c=s.x+s.width+1,l=(r.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,u=(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 d of this.levels(a,r)){let a=e.k(d.price,r);if(a<s.y||a>s.y+s.height)continue;let f=o?.get(d.kind)??a;if(Number.isNaN(f))continue;n.fillStyle=Bw(d.kind,i),A(n,c,f-Rw/2,l,Rw,i),n.fillStyle=i.background;let p=r.formatPrice?.(d.price)??this.priceText?.(d.price)??(0,t.formatPrice)(d.price,u);n.fillText(p,c+5,f)}n.restore()}};function Bw(e,t){switch(e){case`bid`:return t.candleUp;case`ask`:return t.candleDown;default:return t.style?.highLow.color??t.textSecondary}}var Vw=12,Hw=3,Uw=500,Ww=2,Gw=[`movesUp`,`movesDown`];function Kw(e){return e.channel===`price`&&!e.drawingId&&!e.target&&!Gw.includes(e.condition)}function qw(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 Jw=[`crossing`,`crossingUp`,`crossingDown`];function Yw(e,t,n){let r=e<0&&t>=0,i=e>0&&t<=0;return n===`crossingUp`?r:n===`crossingDown`?i:r||i}var Xw=1,Zw=2**31-1,Qw=class extends aS{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=$w(t,i,o),c=`tc_alert_${Xw++}`,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(!Jw.includes(t))throw RangeError(`An alert on a drawing takes a crossing condition, not "${t}"`);let a=`tc_alert_${Xw++}`,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(!Kw(r))continue;let i=Math.abs(e.k(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()),Zw);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)=>Yw(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(Gw.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=qw(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,qw(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(Gw.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 qw(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}seedLastValue(e,t){Number.isFinite(t)&&this.lastValues.set(e,t)}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){Jw.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=eT(e),n=!t.target&&!Gw.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(!Kw(o))continue;let s=e.k(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(),e.y(n,a.x,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-Hw-Vw;d>=a.x&&Ub(n,t.UI_ICONS.bell,d,s-2-Vw,Vw,c)}}};function $w(e,t,n){let r={},i=Gw.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 eT(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 tT=16,nT=3*tT,rT=1e3/30,iT=1e-9,aT=()=>typeof requestAnimationFrame==`function`&&!(typeof document<`u`&&document.hidden),oT={now:()=>typeof performance<`u`?performance.now():Date.now(),frame:e=>aT()?{raf:requestAnimationFrame(e)}:{timeout:setTimeout(e,tT)},cancel:e=>{let t=e;t.raf!==void 0&&cancelAnimationFrame(t.raf),t.timeout!==void 0&&clearTimeout(t.timeout)}},sT=class extends aS{data=[];cursor=-1;timer=null;frameHandle=null;run=0;state=`stopped`;config={speed:1,interval:500};paceMs=null;owedMs=0;constructor(e=oT){super(),this.clock=e}load(e){this.stop(),this.data=e,this.cursor=-1,this.owedMs=0}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.owedMs=0),this.setPace(r)}if(this.isAtEnd()){this.clearTimer(),this.setState(`paused`);return}this.clearTimer();let t=this.stepMs();if(!(t>0)||!Number.isFinite(t)){this.setState(`paused`);return}this.setState(`playing`),this.config.animate?this.runForming(t):t<tT||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.owedMs=0,this.setState(`stopped`)}seekTo(e){this.data.length!==0&&(this.cursor=this.clamp(e),this.owedMs=0,this.emit(`bar`,{bar:this.data[this.cursor],index:this.cursor,total:this.data.length}))}setSpeed(e){let t=this.getFraction();this.config={...this.config,speed:e},this.paceMs=null;let n=this.stepMs();this.owedMs=n>0&&Number.isFinite(n)?t*n:0,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}}remainingMs(){return this.paceMs===null?null:this.paceMs*Math.max(0,this.data.length-1-this.cursor)}getStepMs(){return this.stepMs()}getFraction(){let e=this.stepMs();return e>0&&Number.isFinite(e)?Math.min(1,this.owedMs/e):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)}stepMs(){return this.paceMs??this.config.interval/this.config.speed}runForming(e){let t=this.run,n=e>=nT,r=this.clock.now(),i=-1/0,a=r=>{!n||this.isAtEnd()||t!==this.run||this.state!==`playing`||(i=r,this.emit(`phase`,{index:this.cursor+1,fraction:Math.min(1,this.owedMs/e)}))},o=()=>{if(t!==this.run||this.state!==`playing`)return;this.frameHandle=null;let n=this.clock.now();this.owedMs+=Math.min(50,Math.max(0,n-r)),r=n;let s=Math.floor((this.owedMs+iT)/e);try{s>0?(this.owedMs=Math.max(0,this.owedMs-s*e),this.advance(s),a(n)):n-i+tT/2>=rT&&a(n)}finally{t===this.run&&this.state===`playing`&&this.frameHandle===null&&(this.frameHandle=this.clock.frame(o))}};a(r),this.frameHandle=this.clock.frame(o)}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))}},cT=64,lT=3,uT=3;function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function dT(e){return Array.isArray(e)?e:[]}function fT(e,t){return typeof e==`string`?e:t}function pT(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function mT(e){if(!$(e)||typeof e.id!=`string`||typeof e.type!=`string`||!Array.isArray(e.anchors)||e.anchors.length===0||e.anchors.length>hT||!$(e.style))return null;let n=[];for(let t of e.anchors){if(!$(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:$(e.options)?e.options:void 0,intervals:Ma(e.intervals)??void 0,group:yT(e.group),...Kp(e.name)===void 0?{}:{name:Kp(e.name)},...typeof e.paneId==`string`&&e.paneId.length>0&&e.paneId.length<=gT?{paneId:e.paneId}:{},meta:$(e.meta)?e.meta:void 0}}var hT=5e3,gT=200,_T=64,vT=80;function yT(e){if(!(!$(e)||typeof e.id!=`string`||typeof e.name!=`string`)&&!(e.id===``||e.id.length>_T))return{id:e.id,name:e.name.slice(0,vT)}}function bT(e){return!$(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.type!=`string`||typeof e.price!=`number`||typeof e.quantity!=`number`?null:e}function xT(e){if(!$(e))return;let n={},r=dT(e.colors).filter(e=>typeof e==`string`);r.length>0&&(n.colors=r);let i=dT(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 ST=[`crossingUp`,`crossingDown`,`crossing`,`greaterThan`,`lessThan`,`movesUp`,`movesDown`];function CT(e){if(!$(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=ST.find(t=>t===e.condition)??`crossing`,i=eT(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:fT(e.channel,`price`),label:typeof e.label==`string`?e.label:void 0,...i,...e.expired===!0?{expired:!0}:{}}}function wT(e){return!$(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.entryPrice!=`number`||typeof e.quantity!=`number`?null:e}var TT=4e3;function ET(e){if(!$(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,cT)]=o)}return r.length>0&&console.warn(`Saved style overrides left out: ${[...new Set(r)].join(`, `)}`),n}function DT(e){if(!$(e))return OT();typeof e.version==`number`&&e.version>uT&&console.warn(`Chart state from a newer version (${e.version}); loading what this version understands.`);let n=$(e.viewport)?e.viewport:{},r=[];for(let n of dT(e.indicators))$(n)&&(typeof n.id!=`string`||typeof n.instanceId!=`string`||$(n.params)&&r.push({id:n.id,instanceId:n.instanceId,params:n.params,position:typeof n.position==`string`?n.position:void 0,style:xT(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:Ma(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,TT):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 dT(e.drawings)){let e=mT(t);e&&i.push(e)}let a=[];for(let t of dT(e.orders)){let e=bT(t);e&&a.push(e)}let o=[];for(let t of dT(e.positions)){let e=wT(t);e&&o.push(e)}let s=[];for(let t of dT(e.alerts)){let e=CT(t);e&&s.push(e)}let c=ET(e.overrides);return{version:typeof e.version==`number`&&Array.isArray(e.indicators)?e.version:1,timestamp:pT(e.timestamp,Date.now()),symbol:typeof e.symbol==`string`?e.symbol:void 0,timeframe:typeof e.timeframe==`string`?e.timeframe:void 0,chartType:fT(e.chartType,`candlestick`),...e.chartTypeOptions===void 0?{}:{chartTypeOptions:(0,t.readChartTypeOptions)(e.chartTypeOptions)},viewport:{barWidth:pT(n.barWidth,8),barSpacing:pT(n.barSpacing,2),offset:pT(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 OT(){return{version:1,timestamp:Date.now(),chartType:`candlestick`,viewport:{barWidth:8,barSpacing:2,offset:0},indicators:[],drawings:[],orders:[],positions:[],alerts:[]}}var kT=class{static capture(e,t){return{version:e.getIndicators?uT: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 DT(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()})}},AT=class{undoStack=[];redoStack=[];maxHistory=50;onChange=null;grouped=null;setOnChange(e){this.onChange=e}push(e){if(this.grouped){this.grouped.push(e);return}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?.()}group(e){if(this.grouped)return e();let t=[];this.grouped=t;try{return e()}finally{this.grouped=null,t.length===1?this.push(t[0]):t.length>1&&this.push({type:`drawingBatch`,before:null,after:null,actions:t})}}last(){return this.grouped?this.grouped[this.grouped.length-1]??null:this.undoStack[this.undoStack.length-1]??null}dropLast(){if(this.grouped){this.grouped.pop();return}this.undoStack.pop()&&(this.redoStack.length=0,this.onChange?.())}replaceLast(e){if(this.grouped){this.grouped.length>0?this.grouped[this.grouped.length-1]=e:this.grouped.push(e);return}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}}},jT=[`Time`,`Open`,`High`,`Low`,`Close`,`Volume`];function MT(e,n){return new Date((0,t.normalizeBarTime)(e,n)).toISOString()}function NT(e){let t=/^[=+\-@\t\r]/.test(e)&&!/^-?\d/.test(e)?`'${e}`:e;return/[",\r\n]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}var PT=15,FT=0x38d7ea4c68000;function IT(e){return e==null||!Number.isFinite(e)?null:Number.isInteger(e)||Math.abs(e)>=FT?e:Number(e.toPrecision(PT))}var LT=e=>{let t=IT(e);return t===null?``:String(t)},RT=class{static toCSV(e,n=[]){let r=[...jT,...n.map(e=>NT(e.name))].join(`,`),i=(0,t.barTimeUnit)(e);return[r,...e.map((e,t)=>[MT(e.time,i),...[e.open,e.high,e.low,e.close,e.volume].map(LT),...n.map(e=>LT(e.values[t]))].join(`,`))].join(`
|
|
25
|
+
`)}static toJSON(e,n=[]){let r=(0,t.barTimeUnit)(e);return JSON.stringify(e.map((e,t)=>{let i={time:MT(e.time,r),open:IT(e.open),high:IT(e.high),low:IT(e.low),close:IT(e.close),volume:IT(e.volume)};for(let e of n)i[e.name]=IT(e.values[t]);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 zT(e,t,n=-1/0){return t===null?e:e.filter(e=>e.time>=n&&e.time<t)}function BT(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 VT=1,HT=3,UT=class extends aS{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_${VT++}`,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[...zT(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=zT(this.markers,this.revealUntil,this.revealFrom);for(let i=o.length-1;i>=0;i--){let s=o[i],c=e.w(e.N(s.time,r),n),l=e.k(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+HT&&t.y>=d-HT&&t.y<=f+HT)return s}return null}render(t,n,r){let i=this.dataGetter?.(),a=zT(this.markers,this.revealUntil,this.revealFrom);if(!i||i.length===0||a.length===0)return;let{chartRect:o}=n,s=Zx(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.w(e.N(l.time,i),n),u=e.k(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()}},WT=12,GT=2,KT=1,qT=class extends aS{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_${KT++}`,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[...BT(this.zones,this.revealUntil,this.revealFrom)]}render(e,t,n){let r=this.dataGetter?.(),i=BT(this.zones,this.revealUntil,this.revealFrom);if(!r||r.length===0||i.length===0)return;let{chartRect:a}=t,o=Qx(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.N(r.entryTime,i),u=r.exitTime==null?i.length-1:e.N(r.exitTime,i),d=e.w(l,a),f=e.w(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.k(r.entryPrice,a),g=r.exitPrice==null?e.k(r.entryPrice,a):e.k(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([])),Ub(n,r.direction===`long`?t.UI_ICONS.trendingUp:t.UI_ICONS.trendingDown,p+4,h-3-WT,WT,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+WT+3,h-3),s.showPnl&&!y&&r.pnl!=null){let e=r.pnl>=0?`+`:``,i=e=>(0,t.formatPrice)(e,GT,a.numberLocale??`en-US`),s=r.pnlPercent==null?`${e}${i(r.pnl)}`:`${e}${i(r.pnl)} (${e}${i(r.pnlPercent)}%)`;n.font=`bold 10px ${o.font.family}`,n.fillStyle=x,n.textBaseline=`top`,n.textAlign=`right`;let c=n.measureText(s).width+8,l=m-c-2,u=_+2;n.globalAlpha=.85,n.fillStyle=o.background,A(n,l,u,c,14,o),n.globalAlpha=1,n.fillStyle=x,n.fillText(s,m-4,u+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)}},JT=2,YT=4,XT=10,ZT=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.P(t.x,n)),a=e.I(t.y,n);this.startBar=i,this.startPrice=a,this.endBar=i,this.endPrice=a,this.startTime=QT(i,r),this.endTime=this.startTime,this.active=!0}update(t,n,r){if(!this.active)return;let i=Math.round(e.P(t.x,n));this.endBar=i,this.endPrice=e.I(t.y,n),this.endTime=QT(i,r)}end(){this.active=!1}render(n,r,i){if(!this.active)return;let a=e.w(this.startBar,r),o=e.w(this.endBar,r),s=e.k(this.startPrice,r),c=e.k(this.endPrice,r),l=Math.min(a,o),u=Math.max(a,o),d=Math.min(s,c),f=Math.max(s,c),p=u-l,m=f-d,h=this.endPrice>=this.startPrice?i.candleUp:i.candleDown,g=aE(h,.14);n.save();let{chartRect:_}=r;n.beginPath(),n.rect(_.x,_.y,_.width,_.height),n.clip(),n.fillStyle=g,n.fillRect(l,d,p,m),n.strokeStyle=h,n.lineWidth=1,n.setLineDash([4,3]),n.strokeRect(l+.5,d+.5,p,m),n.setLineDash([]),n.strokeStyle=h,n.lineWidth=1.5,n.beginPath(),n.moveTo(a,s),n.lineTo(o,c),n.stroke(),nE(n,a,s,h),nE(n,o,c,h),n.restore();let v=Math.abs(this.endBar-this.startBar),y=this.endPrice-this.startPrice,b=this.startPrice===0?0:y/this.startPrice*100,x=this.startTime!==null&&this.endTime!==null?tE(Math.abs(this.endTime-this.startTime)):null,S=[],C=y>0?`+`:y<0?`−`:``,w=Math.abs(y),T=(0,t.formatPrice)(Math.abs(b),JT,r.numberLocale??`en-US`);S.push(`${C}${$T(w,r)} (${C}${T}%)`),S.push(`${v} bars${x?` · `+x:``}`),n.save(),rE(n,o,c,S,h,i),n.restore()}};function QT(e,n){return e<0||e>=n.length?null:n[e].time*(0,t.barTimeUnit)(n)}function $T(e,n){return(0,t.priceTagText)(e,n,n.pricePrecision??eE(e))}function eE(e){return e>=1e3?2:e>=1?4:e<=0?YT-1:Math.min(XT,YT-1-Math.floor(Math.log10(e)))}function tE(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 nE(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 rE(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,iE(e,l,u,s,c,6),e.fill(),e.globalAlpha=1,e.strokeStyle=i,e.lineWidth=1,iE(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 iE(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 aE(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 oE=6,sE=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()}},cE={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)},lE=class{animations=new Map;frameId=0;running=!1;animate(e,t){this.animations.set(e,{startTime:-1,duration:t.duration,easing:t.easing??cE.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 uE(e){return!e||e===`dark`?t.DARK_THEME:e===`light`?t.LIGHT_THEME:e}var dE=class{canvas;ctx;container;theme;width=0;height=0;dpr=1;frameId=null;sizer;constructor(e,t){this.container=e,this.theme=uE(t),this.canvas=document.createElement(`canvas`),this.canvas.style.width=`100%`,this.canvas.style.height=`100%`,this.canvas.style.display=`block`,s(this.canvas),this.canvas.setAttribute(`role`,`img`),e.appendChild(this.canvas),this.ctx=this.canvas.getContext(`2d`),this.sizer=new o(e),this.updateSize(),this.sizer.onResize(()=>{this.updateSize(),this.renderNow()})}updateSize(){this.dpr=this.sizer.getDpr();let e=this.sizer.readContainerSize();if(this.width=e.width,this.height=e.height,this.width<=0||this.height<=0)return;let t=i(e,this.dpr,this.sizer.getDeviceSize());this.canvas.width!==t.width&&(this.canvas.width=t.width),this.canvas.height!==t.height&&(this.canvas.height=t.height)}requestRender(){this.frameId===null&&(this.frameId=requestAnimationFrame(()=>{this.frameId=null,(this.width===0||this.height===0)&&this.updateSize(),this.renderNow()}))}renderNow(){this.width===0||this.height===0||(this.ctx.save(),this.ctx.setTransform(this.canvas.width/this.width,0,0,this.canvas.height/this.height,0,0),this.ctx.clearRect(0,0,this.width,this.height),this.renderChart(this.ctx,this.width,this.height,this.theme),this.ctx.restore())}applyBaseOptions(e){`theme`in e&&(this.theme=uE(e.theme)),e.ariaLabel!==void 0&&this.setLabel(e.ariaLabel)}setLabel(e){this.canvas.setAttribute(`aria-label`,e)}setTheme(e){this.theme=uE(e),this.requestRender()}destroy(){this.frameId!==null&&cancelAnimationFrame(this.frameId),this.sizer.destroy(),this.canvas.width=0,this.canvas.height=0,this.canvas.remove()}},fE=class{pos=null;canvas;onUpdate;handleMove;handleLeave;handleOutside;handleCancel;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=e=>{e.pointerType!==`touch`&&this.clear()},this.handleOutside=t=>{t.composedPath().includes(e)||this.clear()},this.handleCancel=()=>this.clear(),e.addEventListener(`pointermove`,this.handleMove),e.addEventListener(`pointerdown`,this.handleMove),e.addEventListener(`pointerleave`,this.handleLeave),e.addEventListener(`pointercancel`,this.handleCancel),e.ownerDocument.addEventListener(`pointerdown`,this.handleOutside,!0)}clear(){this.pos!==null&&(this.pos=null,this.onUpdate())}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(`pointerdown`,this.handleMove),this.canvas.removeEventListener(`pointerleave`,this.handleLeave),this.canvas.removeEventListener(`pointercancel`,this.handleCancel),this.canvas.ownerDocument.removeEventListener(`pointerdown`,this.handleOutside,!0)}};function pE(e,n,r,i,a){let{data:o,mode:s=`area`,lineWidth:c=1.5,showLastPoint:l=!1,showMinMax:u=!1}=i;if(o.length<2||n<=0||r<=0)return;let d=i.color??a.lineColor,f=i.fillColor??d,p=n-4,m=r-4,h=1/0,g=-1/0,_=0,v=0;for(let e=0;e<o.length;e++)o[e]<h&&(h=o[e],_=e),o[e]>g&&(g=o[e],v=e);let y=g-h||1,b=e=>2+e/(o.length-1)*p,x=e=>2+m-(e-h)/y*m;if(s===`area`){let n=e.createLinearGradient(0,2,0,r-2);n.addColorStop(0,(0,t.withAlpha)(f,Ud)),n.addColorStop(1,`transparent`),e.beginPath(),e.moveTo(b(0),x(o[0]));for(let t=1;t<o.length;t++)e.lineTo(b(t),x(o[t]));e.lineTo(b(o.length-1),r-2),e.lineTo(b(0),r-2),e.closePath(),e.fillStyle=n,e.fill()}e.beginPath(),e.moveTo(b(0),x(o[0]));for(let t=1;t<o.length;t++)e.lineTo(b(t),x(o[t]));if(e.strokeStyle=d,e.lineWidth=c,e.lineJoin=`round`,e.stroke(),l){let t=i.lastPointColor??d,n=b(o.length-1),r=x(o[o.length-1]);e.beginPath(),e.arc(n,r,3,0,Math.PI*2),e.fillStyle=t,e.fill()}if(u){let t=i.minPointColor??a.candleDown,n=i.maxPointColor??a.candleUp;e.beginPath(),e.arc(b(_),x(h),2.5,0,Math.PI*2),e.fillStyle=t,e.fill(),e.beginPath(),e.arc(b(v),x(g),2.5,0,Math.PI*2),e.fillStyle=n,e.fill()}}var mE=.2,hE=.01,gE=24,_E=16,vE=`Spread`;function yE(e,t){let n=e.filter(e=>Number.isFinite(e.price)&&Number.isFinite(e.volume)).sort((e,n)=>t===`bid`?n.price-e.price:e.price-n.price),r=0;return n.map(e=>({price:e.price,cumulativeVolume:r+=e.volume}))}function bE(e,t,n,r){let i=yE(e.data.bids,`bid`),a=yE(e.data.asks,`ask`),o=i[0]?.price,s=a[0]?.price,c=o!==void 0&&s!==void 0,l=c?(o+s)/2:o??s??0,u=i.length>0?i[i.length-1].price:l,d=a.length>0?a[a.length-1].price:l,f=(Math.max(l-u,d-l)||Math.abs(l)*hE||1)*(1+mE),p=ef(0,Math.max(0,...i.map(e=>e.cumulativeVolume),...a.map(e=>e.cumulativeVolume))||1,5),m=e.volumeFormat??K(p),h=12+Math.max(0,...p.ticks.map(e=>r(m(e),11)))+8,g=12+(c&&e.midPriceLine!==!1&&e.spreadLabel!==!1?_E:0);return{plot:{x:h,y:g,width:Math.max(1,t-h-12),height:Math.max(1,n-g-12-20)},volume:p,priceMin:l-f,priceMax:l+f,bids:i,asks:a,mid:c?l:null,spread:c?s-o:0}}function xE(e,t){return e.length===1?[e[0],{price:t,cumulativeVolume:e[0].cumulativeVolume}]:e}function SE(e,t,n){let r=null;for(let i of e){if(n===`bid`?i.price<t:i.price>t)break;r=i}return r}function CE(e,n,r,i,a,o,s){if(n<=0||r<=0)return;e.fillStyle=a.background,e.fillRect(0,0,n,r);let{data:c}=i;if(c.bids.length===0&&c.asks.length===0)return;let l=s??((t,n=11)=>(e.font=q(a,n),e.measureText(t).width)),{plot:u,volume:d,priceMin:f,priceMax:p,bids:m,asks:h,mid:g,spread:_}=bE(i,n,r,l),v=u.y+u.height,y=e=>u.x+(e-f)/(p-f)*u.width,b=e=>G(d,e,u.y,u.height,!0),x=_f([...m,...h].map(e=>e.price)),S=new Intl.NumberFormat(void 0,{minimumFractionDigits:x,maximumFractionDigits:x}),C=i.priceFormat??(e=>S.format(e)),w=i.volumeFormat??rf;vf(e,u,d,`vertical`,a,i.volumeFormat??K(d)),e.save(),e.font=q(a,11),e.fillStyle=a.axisLabel,e.strokeStyle=a.grid,e.textAlign=`center`,e.textBaseline=`top`;let T=l(C(p),11)+gE,E=ef(f,p,Math.max(2,Math.floor(u.width/T))),D=i.priceFormat??K(E);e.font=q(a,11);for(let t of E.ticks)t<f||t>p||(df(e,y(t),u.y,y(t),v),e.fillText(D(t),Math.round(y(t)),v+6));e.restore();let O=(t,n,r)=>{if(t.length===0)return;let i=()=>{for(let n=1;n<t.length;n++)e.lineTo(y(t[n].price),b(t[n-1].cumulativeVolume)),e.lineTo(y(t[n].price),b(t[n].cumulativeVolume))};e.fillStyle=r,e.beginPath(),e.moveTo(y(t[0].price),v),e.lineTo(y(t[0].price),b(t[0].cumulativeVolume)),i(),e.lineTo(y(t[t.length-1].price),v),e.closePath(),e.fill(),e.strokeStyle=n,e.lineWidth=1.5,e.lineJoin=`miter`,e.beginPath(),e.moveTo(y(t[0].price),b(t[0].cumulativeVolume)),i(),e.stroke()},k=i.bidColor??a.candleUp,A=i.askColor??a.candleDown;if(e.save(),e.beginPath(),e.rect(u.x,u.y,u.width,u.height),e.clip(),O(xE(m,f),k,i.bidFillColor??(0,t.withAlpha)(k,.25)),O(xE(h,p),A,i.askFillColor??(0,t.withAlpha)(A,.25)),e.restore(),g!==null&&i.midPriceLine!==!1&&(e.save(),e.strokeStyle=a.textSecondary,e.setLineDash([4,4]),df(e,y(g),u.y,y(g),v),e.setLineDash([]),i.spreadLabel!==!1&&(e.font=q(a,11),e.fillStyle=a.textSecondary,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(`${vE}: ${C(_)}`,Math.round(y(g)),12+_E/2-2)),e.restore()),!o||o.x<u.x||o.x>u.x+u.width)return;let j=f+(o.x-u.x)/u.width*(p-f);e.save(),e.strokeStyle=a.crosshair,e.setLineDash([4,4]),df(e,o.x,u.y,o.x,v),e.restore();let ee=SE(m,j,`bid`),te=SE(h,j,`ask`),ne=[{text:C((ee??te)?.price??j),bold:!0}];ee&&ne.push({text:w(ee.cumulativeVolume),color:k}),te&&ne.push({text:w(te.cumulativeVolume),color:A}),lf(e,ne,o,{x:0,y:0,width:n,height:r},a)}var wE=.19,TE=864e5,EE=80,DE=3,OE=.05,kE=`Benchmark`;function AE(e,t){let n=-1,r=1/0;for(let i=0;i<e.length;i++){let a=Math.abs(e[i].time-t);a<r&&(r=a,n=i)}return n}function jE(e,t){let n=e<TE?{...t>TE?{month:`short`,day:`numeric`}:{},hour:`2-digit`,minute:`2-digit`}:t<365*TE?{month:`short`,day:`numeric`,timeZone:`UTC`}:{month:`short`,year:`numeric`,timeZone:`UTC`},r=new Intl.DateTimeFormat(void 0,n);return e=>r.format(new Date(e))}function ME(e){let t=e<7*TE,n=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,...e>=365*TE?{year:`numeric`}:{},...t?{hour:`2-digit`,minute:`2-digit`}:{timeZone:`UTC`}});return e=>n.format(new Date(e))}function NE(e){for(let t=1;t<e.length;t++)if(e[t].time<e[t-1].time)return[...e].sort((e,t)=>e.time-t.time);return e}function PE(e,t,n,r,i=``){let{data:a,benchmark:o}=e,s=1/0,c=-1/0,l=1/0,u=-1/0;for(let e of a)Number.isFinite(e.value)&&(s=Math.min(s,e.value),c=Math.max(c,e.value)),Number.isFinite(e.time)&&(l=Math.min(l,e.time),u=Math.max(u,e.time));for(let e of o??[])Number.isFinite(e.value)&&(s=Math.min(s,e.value),c=Math.max(c,e.value));let d=s===c?Math.abs(s)*OE||1:0,f=ef(s-d,c+d,5),p=e.valueFormat??K(f),m=Math.max(0,...f.ticks.map(e=>r(p(e),11))),h=o&&o.length>=2?sf([{label:e.benchmarkLabel??kE,color:i}],t-24,r):null,g=12+m+8,_=12+(h?h.height+6:0);return{plot:{x:g,y:_,width:Math.max(1,t-g-12),height:Math.max(1,n-_-12-20)},scale:f,timeMin:l,timeMax:u,legend:h}}function FE(e,t,n,r,i){let{plot:a,timeMin:o,timeMax:s}=t,c=gf(o,s,Math.max(1,Math.floor(a.width/EE))),l=i??jE(c.length>1?c[1]-c[0]:s-o,s-o);e.save(),e.font=q(r,11),e.fillStyle=r.axisLabel,e.strokeStyle=r.grid,e.textAlign=`center`,e.textBaseline=`top`;for(let t of c){let r=a.x+(t-o)/(s-o)*a.width;df(e,r,a.y,r,a.y+a.height);let i=l(t),c=e.measureText(i).width/2;r-c>=0&&r+c<=n&&e.fillText(i,Math.round(r),a.y+a.height+6)}e.restore()}function IE(e,n,r,i,a,o,s){if(n<=0||r<=0||(e.fillStyle=a.background,e.fillRect(0,0,n,r),i.data.length<2))return;let c=NE(i.data),l=i.benchmark&&NE(i.benchmark),u=s??((t,n=11)=>(e.font=q(a,n),e.measureText(t).width)),d=i.lineColor??a.lineColor,f=i.benchmarkColor??a.textSecondary,p=PE(i,n,r,u,f),{plot:m,scale:h,timeMin:g,timeMax:_,legend:v}=p;if(!(_>=g))return;let y=_-g||1,b=e=>m.x+(e-g)/y*m.width,x=e=>G(h,e,m.y,m.height,!0),S=m.y+m.height,C=i.timeFormat??ME(y);vf(e,m,h,`vertical`,a,i.valueFormat??K(h)),FE(e,p,n,a,i.timeFormat),v&&cf(e,v,m.x,12,a);let w=(t,n=e=>t[e].value)=>{e.moveTo(b(t[0].time),x(n(0)));for(let r=1;r<t.length;r++)e.lineTo(b(t[r].time),x(n(r)))};if(e.save(),e.beginPath(),e.rect(m.x,m.y,m.width,m.height),e.clip(),i.drawdown===!0){let n=[],r=-1/0;for(let e of c)n.push(r=Number.isFinite(e.value)?Math.max(r,e.value):r);e.fillStyle=i.drawdownColor??(0,t.withAlpha)(a.candleDown,wE),e.beginPath(),w(c,e=>n[e]);for(let t=c.length-1;t>=0;t--)e.lineTo(b(c[t].time),x(c[t].value));e.closePath(),e.fill()}if(i.fillArea===!0){let n=e.createLinearGradient(0,m.y,0,S);n.addColorStop(0,(0,t.withAlpha)(d,Ud)),n.addColorStop(1,`transparent`),e.fillStyle=n,e.beginPath(),w(c),e.lineTo(b(c[c.length-1].time),S),e.lineTo(b(c[0].time),S),e.closePath(),e.fill()}if(e.lineJoin=`round`,l&&l.length>=2&&(e.strokeStyle=f,e.lineWidth=1,e.beginPath(),w(l),e.stroke()),e.strokeStyle=d,e.lineWidth=i.lineWidth??1.5,e.beginPath(),w(c),e.stroke(),e.restore(),!o||o.x<m.x||o.x>m.x+m.width)return;let T=c[AE(c,g+(o.x-m.x)/m.width*y)];if(!T)return;e.save(),e.strokeStyle=a.crosshair,e.setLineDash([4,4]),df(e,b(T.time),m.y,b(T.time),S),e.restore(),e.fillStyle=d,e.beginPath(),e.arc(b(T.time),x(T.value),DE,0,Math.PI*2),e.fill();let E=i.valueFormat??rf,D=[{text:C(T.time),bold:!0},{text:E(T.value),color:d}],O=l?AE(l,T.time):-1;l&&O>=0&&D.push({text:`${i.benchmarkLabel??kE}: ${E(l[O].value)}`,color:f}),lf(e,D,o,{x:0,y:0,width:n,height:r},a)}function LE(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 RE(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 zE(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 BE(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){zE(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||RE(u,o)<=RE(s,o))s.push(e[l]),c.push(t[l]),l++;else{zE(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},BE(e.slice(l),t.slice(l),n,r,i);return}}s.length>0&&zE(s,c,n,a,r,i)}function VE(e,t,n){if(e.length===0)return[];let r=e=>e.weight>0&&Number.isFinite(e.weight)?e.weight:0,i=[...e].sort((e,t)=>r(t)-r(e)),a=i.reduce((e,t)=>e+r(t),0);if(a===0)return[];let o=t.width*t.height,s=i.map(e=>r(e)/a*o),c=i.map(e=>e.id),l=[];return BE(s,c,{...t},n,l),l}var HE=2,UE=18;function WE(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=VE(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+HE/2,y:d.y+HE/2+f,width:Math.max(0,d.width-HE),height:Math.max(0,d.height-HE-f)};s.push({name:t,rect:{...d},header:f,value:l>0?u/l:0,count:o.length}),c.push(...VE(o,p,n))}return{groups:s,cells:c}}function GE(e){return Number.isFinite(e)?(e>=0?`+`:``)+e.toFixed(2)+`%`:``}function KE(e){return e.label}function qE(e,n){let r=n.min??-5,i=n.max??5;if(!Number.isFinite(e))return n.zero;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)}var JE=`#FFFFFF`,YE=`#11151b`;function XE(e,n){let r=/^rgba\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)$/i.exec(e.trim());return Af(r?(0,t.lerpColor)(n,`rgb(${r[1]},${r[2]},${r[3]})`,Number(r[4])):(0,t.lerpColor)(e,e,0))===YE?YE:JE}function ZE(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 QE(e,t,n,r,i,a,o,s,c,l,u,d){if(i<40||a<30)return;let f=n+i/2,p=r+a/2;e.save();let m=d===JE;if(e.shadowColor=m?`rgba(0,0,0,0.6)`:`transparent`,e.shadowBlur=m?2:0,e.fillStyle=d,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,f,c?p-1:p,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,f,s?p+1:p,i-8)}e.restore()}function $E(e,t,n,r){let i=[{text:n(e),bold:!0}],a=r(e.value);a!==``&&i.push({text:a,color:t});for(let[t,n]of Object.entries(e.meta??{}))i.push({text:t+`: `+String(n)});return i}function eD(e,t,n,r,i,a,o,s,c=[]){if(t<=0||n<=0||(e.fillStyle=o.background,e.fillRect(0,0,t,n),r.length===0||i.length===0))return null;let l=a.colorScale,u=Ef([],o,l),d={negative:u.negative,zero:u.zero,positive:u.positive,min:l?.min,max:l?.max},f=a.cellRadius??4,p=a.showLabels!==!1,m=a.showValues!==!1,h=a.valueFormat??GE,g=a.labelFormat??KE,_=new Map;for(let e of r)_.set(e.id,e);let v=null,y=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){v=e.id;let t=_.get(e.id);t&&(y={cell:t,rect:e});break}}for(let t of i){let n=_.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=qE(n.value,d);ZE(e,r,i,a,s,f),e.fillStyle=c,e.fill(),QE(e,n,r,i,a,s,o,p,m,g,h,XE(c,o.background)),t.id===v&&(ZE(e,r,i,a,s,f),e.strokeStyle=o.text,e.lineWidth=1.5,e.stroke())}let b=s&&!y?c.find(e=>e.header>0&&tD(e,s)):void 0;return nD(e,c,o,h,b),y&&s?lf(e,$E(y.cell,qE(y.cell.value,d),g,h),s,{x:0,y:0,width:t,height:n},o):b&&s&&lf(e,$E({id:``,label:b.name,value:b.value},void 0,e=>e.label,h),s,{x:0,y:0,width:t,height:n},o),y}function tD(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 nD(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=yf(s.name,m,e=>o(e),a);h&&e.fillText(h,t+5,u)}e.restore()}var rD=.7,iD=1,aD=.382,oD=Math.PI/4,sD=4;function cD(e){return e.type?e.type:e.value<0?`negative`:`positive`}function lD(e){let t=0;return e.map(e=>{let n=cD(e),r=Number.isFinite(e.value)?e.value:0,i=n===`total`||n===`subtotal`?0:t,a=i+r;return t=a,{type:n,value:r,start:i,end:a}})}function uD(e,t,n,r){let i=e.data??[],a=lD(i),o=0,s=0;for(let{start:e,end:t}of a)o=Math.min(o,e,t),s=Math.max(s,e,t);let c=(s-o||1)*.1,l=ef(o<0?o-c:0,s>0?s+c:0,5),u=e.valueFormat??K(l),d=12+Math.max(0,...l.ticks.map(e=>r(u(e),11)))+8,f=Math.max(1,t-d-12),p=f/Math.max(1,i.length),m=e.labelFormat??(e=>e),h=Math.max(0,...i.map(e=>r(m(e.label),11))),g=h>p-4,_=g?Math.min(n*aD,Math.ceil((h+11)*Math.sin(oD))+6):20,v={x:d,y:12,width:f,height:Math.max(1,n-24-_)},y=p*Math.min(1,Math.max(.05,e.barWidth??rD)),b=e=>G(l,e,v.y,v.height,!0);return{plot:v,scale:l,bars:a.map((e,t)=>{let n=Math.min(b(e.start),b(e.end)),r=v.x+t*p;return{label:i[t].label,value:e.value,type:e.type,start:e.start,end:e.end,x:r+(p-y)/2,y:n,width:y,height:Math.max(iD,Math.abs(b(e.end)-b(e.start))),slotX:r,slotWidth:p}}),turned:g,labelRoom:_}}function dD(e,t){let{plot:n,bars:r}=e;return r.length===0||t<n.x||t>n.x+n.width?-1:Math.min(r.length-1,Math.floor((t-n.x)/r[0].slotWidth))}function fD(e,t,n,r){let{bars:i,scale:a,plot:o}=t;if(r!==`none`){e.save(),e.strokeStyle=n,e.setLineDash(r===`dashed`?[4,4]:[]);for(let t=0;t<i.length-1;t++){let n=i[t].x+i[t].width,r=i[t+1].x,s=G(a,i[t].end,o.y,o.height,!0);r>n&&df(e,n,s,r,s)}e.restore()}}function pD(e,t,n,r,i){e.save(),e.font=q(n,10),e.fillStyle=n.textSecondary,e.textAlign=`center`;let a=[];for(let n of t.bars){let t=n.type===`positive`||n.type===`negative`?i?`${n.value>=0?`+`:``}${r(n.value)}`:r(n.end):r(n.value),o=e.measureText(t).width,s=n.end<n.start,c=n.x+n.width/2,l={x:c-o/2,y:s?n.y+n.height+sD:n.y-sD-11,width:o,height:11};a.some(e=>l.x<e.x+e.width+2&&e.x<l.x+l.width+2&&l.y<e.y+e.height&&e.y<l.y+l.height)||(a.push(l),e.textBaseline=s?`top`:`bottom`,e.fillText(t,Math.round(c),Math.round(s?l.y:n.y-sD)))}e.restore()}function mD(e,t,n,r,i){let{plot:a,bars:o,turned:s,labelRoom:c}=t;e.save(),e.font=q(n,11),e.fillStyle=n.axisLabel;let l=a.y+a.height+6;if(!s){e.textAlign=`center`,e.textBaseline=`top`;for(let t of o)e.fillText(r(t.label),Math.round(t.slotX+t.slotWidth/2),l);e.restore();return}e.textAlign=`right`,e.textBaseline=`middle`;for(let t of o){let n=t.slotX+t.slotWidth/2,a=Math.min((c-6)/Math.sin(oD)-11,(n-2)/Math.cos(oD)),o=yf(r(t.label),a,i);o&&(e.save(),e.translate(n,l+2),e.rotate(-oD),e.fillText(o,0,0),e.restore())}e.restore()}function hD(e,t,n,r,i,a,o){if(t<=0||n<=0)return{hitBar:null};e.fillStyle=i.background,e.fillRect(0,0,t,n);let s=r.data;if(!s||s.length===0)return{hitBar:null};let c=o??((t,n=11)=>(e.font=q(i,n),e.measureText(t).width)),l=uD(r,t,n,c),{plot:u,scale:d,bars:f}=l,p=r.valueFormat??K(d),m=r.valueFormat??rf,h={positive:r.positiveColor??i.candleUp,negative:r.negativeColor??i.candleDown,total:r.totalColor??i.lineColor,subtotal:r.subtotalColor??i.textSecondary};vf(e,u,d,`vertical`,i,p),fD(e,l,r.connectorColor??i.textSecondary,r.connectorStyle??`dashed`);let g=uf(e);for(let t of f){let n=g.x(t.x)-g.width/2,r=g.x(t.x+t.width)-g.width/2;e.fillStyle=h[t.type],e.fillRect(n,t.y,Math.max(g.width,r-n),t.height)}e.strokeStyle=i.axisLine;let _=G(d,0,u.y,u.height,!0);df(e,u.x,_,u.x+u.width,_),r.showValues!==!1&&pD(e,l,i,m,r.showDelta!==!1),mD(e,l,i,r.labelFormat??(e=>e),c);let v=a?dD(l,a.x):-1;if(a&&v>=0){let r=f[v],o=r.slotX+r.slotWidth/2;e.save(),e.strokeStyle=i.crosshair,e.setLineDash([4,4]),df(e,o,u.y,o,u.y+u.height),e.restore();let s=r.type===`positive`||r.type===`negative`,c=[{text:r.label,bold:!0}];s&&c.push({text:`${r.value>=0?`+`:``}${m(r.value)}`,color:h[r.type]}),c.push({text:s?`= ${m(r.end)}`:m(r.end),color:s?void 0:h[r.type]}),lf(e,c,a,{x:0,y:0,width:t,height:n},i)}return{hitBar:v>=0?v:null}}var gD=Math.PI/180,_D=150,vD=240,yD=90,bD=.14,xD=1.6*gD,SD=.22,CD=8,wD=18,TD=16,ED=6.5,DD=20,OD=5,kD=28;function AD(e,t,n){return e<t?t:e>n?n:e}function jD(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 MD(e){let t=Number.isFinite(e.startAngle)?e.startAngle:_D,n=(Number.isFinite(e.endAngle)?e.endAngle:t+vD)-t;return n<=0&&(n=(n%360+360)%360||360),n=AD(n,yD,360),{start:(t%360+360)%360*gD,sweep:n*gD}}function ND(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 PD(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*ED+12:0}function FD(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}=MD(n),s=a,c=a+o,l=AD(n.thickness??bD,.04,.5),u=ND(s,c),d=Math.max(u.maxY,.18),f=PD(n),p=f>0?TD:0,m=Math.max(1,e-2*CD-2*f),h=Math.max(1,t-2*CD-wD-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+wD+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-CD,E);return{cx:b,cy:x,radius:_,thickness:v,startAngle:s,endAngle:c,min:r,max:i,valueY:w,valueSize:C,textBottom:D}}function ID(e,t){let n=Number.isFinite(e)?AD((e-t.min)/(t.max-t.min),0,1):0;return t.startAngle+(t.endAngle-t.startAngle)*n}function LD(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 RD(e,t,n){let r=(t??[]).map(t=>({a0:ID(t.from,e),a1:ID(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 zD(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 BD(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 VD(e,t,n,r,i,a){let o=RD(t,n,i),s=o.some(e=>!e.track);o.forEach((n,i)=>{let a=i>0&&!n.track&&!o[i-1].track?xD/2:0,s=i<o.length-1&&!n.track&&!o[i+1].track?xD/2:0,c=n.a0+a,l=n.a1-s;if(n.track){zD(e,t,c,l,n.color);return}e.globalAlpha=SD,zD(e,t,c,l,n.color),e.globalAlpha=1,zD(e,t,c,Math.min(l,r),n.color)}),s||zD(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:SD],[d,f]=u(o[0],c),[p,m]=u(o[o.length-1],l);BD(e,t,t.startAngle,d,f,`start`),BD(e,t,t.endAngle,p,m,`end`)}function HD(e,t,n){let r=t.radius-t.thickness/2;if(r<kD)return;let i=Math.max(4,t.thickness*.45);e.strokeStyle=n,e.lineCap=`butt`;for(let n=0;n<=DD;n++){let a=n%OD===0,o=t.startAngle+(t.endAngle-t.startAngle)*n/DD,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 UD(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 WD(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 GD(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 KD(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=GD(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();GD(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&&GD(e,r,`400`,f,s,c,l)>0&&(e.fillStyle=a.textSecondary,e.fillText(r,t.cx,n))}}function qD(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 JD(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=ID((AD(r.from,t.min,t.max)+AD(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 YD(e,t,n,r,i,a){if(t<=0||n<=0)return;let o=FD(t,n,r),s=Number.isFinite(a),c=s?AD(a,o.min,o.max):o.min,l=ID(c,o),u=s?LD(c,r.zones):void 0,d=r.pointer===`needle`,f=r.valueFormat??jD,p=u?.color??r.needleColor??i.lineColor;e.save(),e.fillStyle=i.background,e.fillRect(0,0,t,n),VD(e,o,r.zones,l,r.trackColor??i.grid,p),HD(e,o,i.textSecondary),s&&(d?WD(e,o,l,r.needleColor??i.text,i.background):UD(e,o,l,p,i.background)),r.showValue!==!1&&KD(e,o,s?f(c):`—`,r.label,u,i,d),qD(e,o,f,i),r.showZoneLabels===!0&&r.zones?.length&&JD(e,o,r.zones,i),e.restore()}var XD=12,ZD=.72,QD=20,$D=.35;function eO(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 tO(e,t){let n=e.colorBySign;return n?n===!0?{positive:t.candleUp,negative:t.candleDown}:n:null}function nO(e,t,n,r,i){let a=e.orientation===`horizontal`,o=e.legend??e.series.length>1?sf(e.series.map((e,t)=>({label:e.name,color:af(t,e.color)})),t-XD*2,i):null,s=XD+(o?o.height+6:0),[c,l]=eO(e),u=ef(c,l,a?Math.max(2,Math.floor(t/110)):5),d=e.valueFormat??K(u),f=Math.max(0,...u.ticks.map(e=>i(d(e),11))),p;if(a){let r=XD+Math.min(t*$D,Math.max(0,...e.categories.map(e=>i(e,11))))+8;p={x:r,y:s,width:Math.max(1,t-r-XD-f/2),height:Math.max(1,n-s-XD-QD)}}else{let e=XD+f+8;p={x:e,y:s,width:Math.max(1,t-e-XD),height:Math.max(1,n-s-XD-QD)}}let m=Math.max(1,e.categories.length),h=a?p.y:p.x,g=(a?p.height:p.width)/m,_=g*ZD,v=e.mode===`stacked`,y=v?_:_/Math.max(1,e.series.length),b=e=>a?G(u,e,p.x,p.width):G(u,e,p.y,p.height,!0),x=b(0),S=tO(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:af(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:XD}}function rO(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 iO(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 aO(e,n,r,i,a,o,s=nO(i,n,r,a,of(e,a))){let c=of(e,a),l=i.valueFormat??rf,{plot:u,orientation:d}=s,f=d===`horizontal`;e.fillStyle=a.background,e.fillRect(0,0,n,r),s.legend&&cf(e,s.legend,XD,s.legendY,a),vf(e,u,s.scale,f?`horizontal`:`vertical`,a,i.valueFormat??K(s.scale));let p=o&&i.crosshair!==!1?iO(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(),oO(e,i.categories,s,a,c),i.showValues&&sO(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});lf(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}function oO(e,t,n,r,i){let{plot:a}=n;e.save(),e.font=q(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(yf(t,a.x-XD-8,i),a.x-8,o)):(e.textAlign=`center`,e.textBaseline=`top`,e.fillText(yf(t,n.band*s-4,i),o,a.y+a.height+6))}),e.restore()}function sO(e,t,n,r,i){e.save(),e.font=q(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 cO=12,lO=-Math.PI/2,uO=Math.PI*2,dO=5,fO=1.4,pO=18,mO=new Intl.NumberFormat(void 0,{style:`percent`,maximumFractionDigits:1});function hO(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} ${mO.format(e.value/o)}`,color:af(t,e.color)})),c=e.legend!==!1&&a.length>0,l=c&&t>=n*fO&&a.length*pO<=n-cO*2,u=l?Math.min(t*.4,Math.max(...s.map(e=>i(e.label,11)))+16):t-cO*2,d=c?sf(s,u,i,l):null,f=l?t-u-cO*3:t-cO*2,p=l?n-cO*2:n-cO*3-(d?.height??0),m=Math.max(0,Math.min(f,p)/2-dO),h=cO+f/2,g=cO+p/2,_=e.innerRadius,v=Math.min(.95,Math.max(0,_!==void 0&&Number.isFinite(_)?_:.6)),y=lO,b=a.map((e,t)=>{let n=e.value/o,r=y;return y+=n*uO,{label:e.label,value:e.value,share:n,start:r,end:y,color:af(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-cO:cO,legendY:l?Math.max(cO,g-(d?.height??0)/2):cO*2+p}}function gO(e,t,n){let r=t-e.cx,i=n-e.cy,a=Math.hypot(r,i);if(a<e.inner||a>e.radius+dO)return null;let o=Math.atan2(i,r);for(;o<lO;)o+=uO;return e.slices.find(e=>o>=e.start&&o<e.end)??null}function _O(e,t,n,r,i,a,o=hO(r,t,n,i,of(e,i))){let s=of(e,i),c=r.valueFormat??rf;e.fillStyle=i.background,e.fillRect(0,0,t,n);let l=a&&r.crosshair!==!1?gO(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?dO: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&&vO(e,o,i),yO(e,o,r,i,s),o.legend&&cf(e,o.legend,o.legendX,o.legendY,i),l&&a&&lf(e,[{text:l.label,bold:!0,color:l.color},{text:`${c(l.value)} · ${mO.format(l.share)}`}],a,{x:0,y:0,width:t,height:n},i),o}function vO(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=q(n,11,`600`),e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=`#fff`;for(let n of t.slices){let t=mO.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 yO(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=q(r,o,`600`),e.fillStyle=r.text,e.fillText(yf(n.centerValue,a,i,o),t.cx,t.cy+(n.centerLabel?o*.35:0))}n.centerLabel&&(e.font=q(r,11),e.fillStyle=r.textSecondary,e.fillText(yf(n.centerLabel,a,i),t.cx,t.cy-(n.centerValue?11*1.1:0))),e.restore()}var bO=12,xO=5,SO=3,CO=18,wO=20,TO=6;function EO(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+TO,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=ef(...p(o,s,n*.8),Math.max(2,Math.floor(n/110))),h=ef(...p(c,l,r*.7),5),g=e.xFormat??K(m),_=e.yFormat??K(h),v=e.legend??e.series.length>1?sf(e.series.map((e,t)=>({label:e.name,color:af(t,e.color)})),n-bO*2,a):null,y=bO+(v?v.height+6:0),b=Math.max(0,...h.ticks.map(e=>a(_(e),11))),x=bO+(e.yLabel?CO:0)+b+8,S=bO+wO+(e.xLabel?CO:0),C=a(g(m.max),11)/2,w={x,y,width:Math.max(1,n-x-bO-C),height:Math.max(1,r-y-S)},T=[];return e.series.forEach((e,n)=>{let r=af(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(SO,d*Math.sqrt(t.size/u)):xO;T.push({px:G(m,t.x,w.x,w.width),py:G(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 DO(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+TO&&e<i&&(r=a,i=e)}return r}function OO(e,t,n,r,i,a,o=EO(r,t,n,i,of(e,i))){let{plot:s,xScale:c,yScale:l}=o,u=r.xFormat??K(c),d=r.yFormat??K(l);e.fillStyle=i.background,e.fillRect(0,0,t,n),o.legend&&cf(e,o.legend,bO,bO,i),vf(e,s,l,`vertical`,i,d),vf(e,s,c,`horizontal`,i,u),r.zeroLines!==!1&&kO(e,o,i),AO(e,o,r,i);let f=a&&r.crosshair!==!1?DO(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=q(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??rf)(f.point.x)}`}),o.push({text:`${r.yLabel??`y`}: ${(r.yFormat??rf)(f.point.y)}`}),f.point.size!==void 0&&o.push({text:rf(f.point.size)}),lf(e,o,a,{x:0,y:0,width:t,height:n},i)}return o}function kO(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(G(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(G(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 AO(e,t,n,r){let{plot:i}=t;e.save(),e.font=q(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+wO+CO)),n.yLabel&&(e.translate(bO+11/2,i.y+i.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}var jO=1e-9,MO=1e3,NO=e=>{let t=Number(e.toPrecision(12));return t===0?0:t};function PO(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+jO),t=Math.max(e,Math.ceil(i/a-jO)-1)-e+1;if(t<=1e3){let r=Array.from({length:t},(t,n)=>({from:NO((e+n)*a),to:NO((e+n+1)*a),count:0}));for(let i of n)r[Math.min(t-1,Math.floor(i/a+jO)-e)].count++;return r}}let o=t.bins,s=typeof o==`number`&&Number.isFinite(o)&&o>=1?Math.min(MO,Math.floor(o)):Math.min(MO,Math.ceil(Math.log2(n.length))+1),c=(i-r)/s,l=Array.from({length:s},(e,t)=>({from:NO(r+t*c),to:NO(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+jO))].count++;return l}var FO=12,IO=20,LO=16;function RO(e,n,r){return n.colorBySign?(e.from+e.to)/2<0?r.candleDown:r.candleUp:n.color??t.TC_SERIES_COLORS[0]}function zO(e,t,n,r,i){let a=PO(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=ef(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=ef(0,Math.max(4,u),4),f=e.valueFormat??K(l),p=Math.max(0,...d.ticks.map(e=>i(K(d)(e),11))),m=FO+(c.length>0?LO:0),h=FO+p+8,g=FO+i(f(l.max),11)/2,_={x:h,y:m,width:Math.max(1,t-h-g),height:Math.max(1,n-m-FO-IO)};return{plot:_,xScale:l,yScale:d,bars:a.map(t=>{let n=G(l,t.from,_.x,_.width),i=t.to>t.from?G(l,t.to,_.x,_.width):n+_.width/10,a=G(d,t.count,_.y,_.height,!0);return{x:n,y:a,width:Math.max(1,i-n),height:_.y+_.height-a,bin:t,color:RO(t,e,r)}}),total:a.reduce((e,t)=>e+t.count,0)}}function BO(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 VO=new Intl.NumberFormat(void 0,{style:`percent`,maximumFractionDigits:1});function HO(e,n,r,i,a,o,s=zO(i,n,r,a,of(e,a))){let c=i.valueFormat??rf,{plot:l}=s;e.fillStyle=a.background,e.fillRect(0,0,n,r),vf(e,l,s.yScale,`vertical`,a,K(s.yScale)),vf(e,l,s.xScale,`horizontal`,a,i.valueFormat??K(s.xScale));let u=o&&i.crosshair!==!1?BO(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(UO(e,s,i,a,c),u&&o){let{bin:t}=u;lf(e,[{text:t.to>t.from?`${c(t.from)} – ${c(t.to)}`:c(t.from),bold:!0,color:u.color},{text:`${rf(t.count)} · ${VO.format(s.total>0?t.count/s.total:0)}`}],o,{x:0,y:0,width:n,height:r},a)}return s}function UO(e,t,n,r,i){let{plot:a}=t;e.save(),e.font=q(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(G(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 WO=864e5,GO=3,KO=12,qO=16,JO=10,YO=28,XO=6;function ZO(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/WO)}function QO(e){return new Date(e*WO).toISOString().slice(0,10)}var $O=e=>((e+4)%7+7)%7;function ek(e,t){let n=e.from===void 0?null:ZO(e.from),r=e.to===void 0?null:ZO(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*WO).getUTCFullYear()-10+1;return[Math.max(n,Math.round(Date.UTC(i,0,1)/WO)),r]}function tk(e,t,n){let r=[],i=e;for(;i<=t;){let e=new Date(i*WO).getUTCFullYear(),a=Math.min(t,Math.round(Date.UTC(e,11,31)/WO)),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 nk=new Map;function rk(e){let t=e??``,n=nk.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=rk(void 0)}nk.set(t,n)}return n}function ik(e,t,n,r,i){let a=new Map;for(let t of e.data){let e=ZO(t.date);e!==null&&Number.isFinite(t.value)&&a.set(e,t)}let o=rk(e.locale),s=e.dateFormat??(e=>o.long.format(new Date(`${e}T00:00:00Z`))),c=e.weekdays===5,l=e=>!c||$O(e)>=1&&$O(e)<=5,u=ek(e,a),d=t-KO*2,f=e.legend===!1?0:28,p=c?5:7,m=c?1:e.weekStart??1,h=e=>($O(e)-m+7)%7,g=u?tk(u[0],u[1],h):[],_=e=>n-KO*2-f-e*qO-(e-1)*JO;for(;g.length>1&&_(g.length)/(g.length*p)<GO;)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=Ef(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)*WO))),w=KO+Math.max(...C.map(e=>i(e,10)),...x?S.map(e=>i(e,11)):[0])+XO,T=Math.max(...g.map(e=>e.weeks)),E=Math.min(YO,(t-w-KO)/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-KO-O)/2),A={...b,pitch:E},j=KO;for(let[e,n]of g.entries()){let r=j+qO;x&&A.years.push({label:S[e],x:k-XO,y:j});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:QO(e),day:f,color:f&&Number.isFinite(f.value)?Df(f.value,y):null});let p=new Date(e*WO).getUTCMonth();if(p!==s){s=p;let n=o.month.format(new Date(e*WO)),r=u+i(n,10);u>=c&&r<=t&&(A.months.push({label:n,x:u,y:j}),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-XO,y:r+t*E+D/2})}j=r+p*E+JO}return f>0&&(A.bar={x:k,y:j-JO+8,width:Math.min(O,t-k-KO),height:f-8}),A}function ak(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 ok(e,n,r,i,a,o,s=ik(i,n,r,a,of(e,a))){let c=i.valueFormat??rf;e.fillStyle=a.background,e.fillRect(0,0,n,r);let l=o&&i.crosshair!==!1?ak(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=q(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=q(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&&jf(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:`–`});lf(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}var sk=12,ck=6,lk=72,uk=Math.PI/4,dk=Math.sin(uk);function fk(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=pk(e[r],e[i],r===i);n[r][i]=t,n[i][r]=t}return n}function pk(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 mk=e=>e.toFixed(2);function hk(e,t,n,r){return!t||!e?!0:e===`lower`?r<=n:r>=n}function gk(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)&&hk(e.triangle,s,t,n)&&c.push(r)}let l=Ef(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=sk+d+ck,h=t-m-sk,g=e=>Math.min(lk,h/o.length,(n-e-sk-p)/a.length),_=sk+11+ck,v=g(_),y=f>v-4,b=f;if(y&&(b=Math.min(f,n*.33/dk),_=sk+b*dk+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*dk/2)/dk))),u.grid={x:S,y:_,width:o.length*v,height:a.length*v},u.pitch=v;let C=e.valueFormat??mk,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)||!hk(e.triangle,s,t,n))continue;let c=Df(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:Af(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*dk:v)));for(let e=0;e<a.length;e+=E)u.rowLabels.push({text:yf(a[e],d,i),index:e,x:S-ck,y:_+e*v+x/2});for(let e=0;e<o.length;e+=D)u.columnLabels.push({text:yf(o[e],b,i),index:e,x:S+e*v+x/2,y:_-ck,rotated:y});return p>0&&(u.bar={x:S,y:_+a.length*v+8,width:Math.min(u.grid.width,t-S-sk),height:p-8}),u}function _k(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 vk(e,t,n,r,i,a,o=gk(r,t,n,i,of(e,i))){let s=r.valueFormat??mk;e.fillStyle=i.background,e.fillRect(0,0,t,n);let c=a&&r.crosshair!==!1?_k(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=q(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=q(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(uk),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&&jf(e,o.bar,o.scale,s,i),c&&a){let{cell:r}=c;lf(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 yk=12,bk=18,xk=20,Sk=10,Ck=.2,wk=2e3,Tk=1e-9;function Ek(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 Dk=(e,t)=>t-e>Tk*Math.max(Math.abs(e),Math.abs(t));function Ok(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=Dk(t,n)?(o.volume-a.volume)/(n-t):0,c=Dk(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 kk(e,n,r,i,a){let o=Ek(e.data,e.period??25,Ak(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&&!Dk(s,c)&&(c=s),o.length>0&&!Dk(l,u)&&(u=l);let d=ef(o.length>0?s:0,o.length>0?c:1,Math.max(2,Math.floor(n/110))),f=ef(o.length>0?l:0,o.length>0?u:1,Math.max(2,Math.floor(r/60))),p=e.priceFormat??K(f),m=e.volumeFormat??K(d),h=yk+Math.max(0,...f.ticks.map(e=>a(p(e),11)))+8+(e.yLabel?bk:0),g=yk+a(m(d.max),11)/2,_=yk,v=yk+xk+(e.xLabel?bk: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:G(d,e.volume,y.x,y.width),py:G(f,e.price,y.y,y.height,!0),alpha:Ck+(1-Ck)*t/b,point:e})),phase:Ok(o),color:e.color??t.TC_SERIES_COLORS[0]}}function Ak(e){let t=e.points??60;return Number.isFinite(t)?Math.min(wk,Math.max(2,Math.floor(t))):60}function jk(e,t,n){let r=null,i=Sk*Sk;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 Mk=new Intl.DateTimeFormat(void 0,{year:`numeric`,month:`short`,day:`numeric`});function Nk(e,n,r,i,a,o,s=kk(i,n,r,a,of(e,a))){let{plot:c,points:l,color:u}=s,d=i.timeFormat??(e=>Mk.format(new Date(e))),f=i.priceFormat??rf,p=i.volumeFormat??rf;e.fillStyle=a.background,e.fillRect(0,0,n,r),vf(e,c,s.yScale,`vertical`,a,i.priceFormat??K(s.yScale)),vf(e,c,s.xScale,`horizontal`,a,i.volumeFormat??K(s.xScale)),Pk(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?jk(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(),lf(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 Pk(e,t,n,r){e.save(),e.font=q(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+xk+bk)),n.yLabel&&(e.translate(yk+4,t.y+t.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}exports.ABCDPatternTool=Av,exports.ADXIndicator=Ds,exports.ALMAIndicator=kc,exports.ATRIndicator=Es,exports.AXIS_LABEL_HEIGHT=ee,exports.AcceleratorOscillatorIndicator=hc,exports.AccumulationDistributionIndicator=Tc,exports.AccumulativeSwingIndexIndicator=bu,exports.AdvanceDeclineIndicator=Su,exports.AlertDragHandler=Bd,exports.AlertManager=Qw,exports.AlligatorIndicator=fs,exports.AnchoredNoteTool=Sy,exports.AnchoredTextTool=xy,exports.AnchoredVWAPIndicator=rs,exports.AnchoredVWAPTool=B_,exports.Animator=lE,exports.ArcTool=Ky,exports.AreaRenderer=et,exports.AroonIndicator=Ms,exports.ArrowMarkTool=ay,exports.ArrowTool=A_,exports.AverageDayRangeIndicator=tl,exports.AveragePriceIndicator=ll,exports.AwesomeOscillatorIndicator=xs,exports.AxisDragHandler=zd,exports.BalanceOfPowerIndicator=ec,exports.BalloonTool=by,exports.BarCountdown=fe,exports.BarRenderer=tt,exports.BarsPatternTool=Db,exports.BaseFinanceChart=dE,exports.BaselineRenderer=it,exports.BinanceAdapter=TC,exports.BollingerBandWidthIndicator=Hc,exports.BollingerBandsIndicator=Bo,exports.BollingerPercentBIndicator=Vc,exports.BracketTool=Mx,exports.BrushTool=zy,exports.BybitAdapter=zC,exports.CANDLE_PATTERNS=Xl,exports.CCIIndicator=As,exports.CMFIndicator=Fs,exports.COUNTDOWN_HEIGHT=de,exports.CROSSHAIR_CURSORS=Uf,exports.CalloutTool=Xv,exports.CandlestickRenderer=le,exports.CanvasLayer=c,exports.ChaikinOscillatorIndicator=Ss,exports.ChaikinVolatilityIndicator=cc,exports.ChandeKrollStopIndicator=Rc,exports.ChandeMomentumIndicator=nc,exports.ChandelierExitIndicator=ds,exports.ChartLegend=mw,exports.ChartStateManager=kT,exports.ChopZoneIndicator=Eu,exports.ChoppinessIndexIndicator=Rs,exports.CircleTool=Pv,exports.CoinbaseAdapter=NC,exports.CompareRenderer=Gr,exports.CompareSymbolIndicator=ro,exports.CompareSymbolPaneIndicator=io,exports.ConnorsRSIIndicator=Hs,exports.CoppockIndicator=Ws,exports.CorrelationCoefficientIndicator=lo,exports.CorrelationLogIndicator=uo,exports.CrossLineTool=fv,exports.CrosshairHandler=Nf,exports.CrosshairTooltip=sp,exports.CurrentPriceLine=dS,exports.CurveTool=Gy,exports.CyclicLinesTool=Hv,exports.CypherPatternTool=Nv,exports.DEFAULT_LEGEND_CONFIG=pw,exports.DEFAULT_MAX_PIXEL_RATIO=n,exports.DEFAULT_MAX_WEBGL_CHARTS=e.t,exports.DEFAULT_SESSION_HOURS=Fw,exports.DEMAIndicator=Dc,exports.DENSE_BAR_WIDTH=e.u,exports.DOUBLE_TAP_MS=hd,exports.DOUBLE_TAP_PX=gd,exports.DPRManager=o,exports.DataExporter=RT,exports.DateAndPriceRangeTool=Rv,exports.DateRangeTool=y_,exports.DepthHeatmapBuffer=$t,exports.DepthHeatmapRenderer=en,exports.DepthOverlay=Cx,exports.DetrendedPriceOscillatorIndicator=$s,exports.DisparityIndexIndicator=vc,exports.DonchianChannelIndicator=$o,exports.DrawingBase=J,exports.DrawingManager=Bm,exports.DrawingRenderer=Jm,exports.EMAIndicator=zo,exports.EaseOfMovementIndicator=ac,exports.Easing=cE,exports.ElderRayIndicator=Js,exports.ElliottCorrectionTool=u_,exports.ElliottDoubleComboTool=f_,exports.ElliottImpulseTool=l_,exports.ElliottTriangleTool=d_,exports.ElliottTripleComboTool=p_,exports.ElliottWaveTool=c_,exports.EllipseTool=kg,exports.Emitter=aS,exports.EnvelopeIndicator=gs,exports.EquivolumeRenderer=dt,exports.EventBus=yp,exports.ExtendedLineTool=rg,exports.FibArcsTool=ub,exports.FibChannelTool=bv,exports.FibCirclesTool=lb,exports.FibExtensionTool=Eg,exports.FibRetracementTool=wg,exports.FibSpeedResistanceFanTool=Dv,exports.FibSpiralTool=pb,exports.FibTimeZonesTool=$_,exports.FibWedgeTool=db,exports.FinanceCrosshair=fE,exports.FisherTransformIndicator=Qs,exports.FlagTool=ny,exports.ForceIndexIndicator=Vs,exports.ForecastTool=Tb,exports.GROUP_HEADER=UE,exports.GannBoxTool=R_,exports.GannFanTool=N_,exports.GannSquareTool=mb,exports.GridRenderer=e.o,exports.GuppyMMAIndicator=ol,exports.HLCAreaRenderer=pt,exports.HammingMAIndicator=pu,exports.HeadAndShouldersTool=jv,exports.HiLoRenderer=vt,exports.HighlighterTool=By,exports.HistoricalVolatilityIndicator=Wc,exports.HollowCandleRenderer=nt,exports.HorizontalLineTool=Qh,exports.HorizontalRayTool=$h,exports.HullMAIndicator=os,exports.ICON_GLYPHS=oy,exports.INDICATOR_CATEGORIES=Iu,exports.INDICATOR_WORKER_MIN_BARS=Oo,exports.INTERVAL_LIMITS=Oa,exports.INTERVAL_UNITS=Da,exports.IchimokuIndicator=Yo,exports.IconTool=cy,exports.IndicatorBase=I,exports.IndicatorEngine=Lo,exports.IndicatorValueMap=L,exports.IndicatorWorkerClient=Ju,exports.IndicatorWorkerHost=Gu,exports.IndicatorWorkerPool=Xu,exports.InfoLineTool=mv,exports.InteractionManager=Ed,exports.KAMAIndicator=Ac,exports.KEPT_BUCKETS=gS,exports.KSTIndicator=Gs,exports.KagiRenderer=ot,exports.KeltnerChannelIndicator=Qo,exports.KeyboardHandler=Xf,exports.KlingerIndicator=Zs,exports.KrakenAdapter=KC,exports.LSMAIndicator=jc,exports.LayerManager=l,exports.LineRenderer=$e,exports.LineWithMarkersRenderer=ht,exports.LinearRegressionChannelIndicator=as,exports.LinearRegressionSlopeIndicator=$c,exports.MACDIndicator=ws,exports.MAChannelIndicator=lu,exports.MACrossIndicator=Fc,exports.MADoubleIndicator=_u,exports.MARibbonIndicator=sl,exports.MATripleIndicator=vu,exports.MAX_ALERT_BARS=Uw,exports.MAX_BASE_RATIO=mS,exports.MAX_BASE_REQUESTS=pS,exports.MFIIndicator=js,exports.MIN_ALERT_BARS=Ww,exports.MIN_BAR_UNIT=Ie,exports.MIN_BAR_UNIT_LIMIT=Le,exports.MTFMovingAverageIndicator=ls,exports.MajorityRuleIndicator=Cu,exports.ManualFeed=dw,exports.MarketProfileRenderer=Rt,exports.MassIndexIndicator=tc,exports.McGinleyDynamicIndicator=Mc,exports.MeasureOverlay=ZT,exports.MeasureTool=b_,exports.MedianPriceIndicator=ul,exports.MockAdapter=EC,exports.ModifiedSchiffPitchforkTool=Ig,exports.MomentumIndicator=Uc,exports.NetVolumeIndicator=nl,exports.NoteTool=Yv,exports.OBVIndicator=Os,exports.OrderDraftTool=Rx,exports.OrderRenderer=ux,exports.PRICE_AXIS_ADD_STRIP=kd,exports.PRICE_SCALE_MARGIN=Be,exports.PanHandler=Ld,exports.PaneResizeHandler=Vd,exports.PaperExecutionAdapter=nS,exports.ParabolicSARIndicator=Xo,exports.ParallelChannelTool=og,exports.PathTool=Vy,exports.PercentagePriceOscillatorIndicator=pc,exports.PeriodLevelsRenderer=Ut,exports.PinnedTooltip=hp,exports.PitchfanTool=fb,exports.PitchforkTool=Pg,exports.PivotMarkersRenderer=Yt,exports.PivotPointsIndicator=ts,exports.PointAndFigureRenderer=lt,exports.PollingAdapter=kC,exports.PolylineTool=Hy,exports.PositionRenderer=Sx,exports.PrettyGoodOscillatorIndicator=bc,exports.PriceAxis=D,exports.PriceAxisAddButton=Ad,exports.PriceLabelTool=jy,exports.PriceLines=zw,exports.PriceOscillatorIndicator=ku,exports.PriceRangeTool=g_,exports.PriceVolumeTrendIndicator=oc,exports.ProjectionTool=Eb,exports.QstickIndicator=yc,exports.RANGE_PRESETS=We,exports.ROCIndicator=Ns,exports.RSIIndicator=Cs,exports.RayTool=ng,exports.ReconnectManager=lS,exports.RectangleTool=Og,exports.RegressionChannelTool=dg,exports.RelativeMomentumIndexIndicator=_c,exports.RelativeVigorIndicator=lc,exports.RelativeVolatilityIndexIndicator=Zc,exports.RenderEngine=Me,exports.RenderLoop=u,exports.RenkoRenderer=at,exports.ReplayController=oC,exports.ReplayManager=sT,exports.ResamplingAdapter=DS,exports.ReshapeMemo=Qr,exports.RiskRewardTool=dv,exports.SELECTION_BOX_MIN_SIZE=oE,exports.SMAIndicator=Ro,exports.SMIErgodicIndicator=Ou,exports.SMMAIndicator=Oc,exports.SNAPSHOT_VERSION=lT,exports.SYMBOL_INDICATOR_IDS=to,exports.SYMBOL_ZONE_WAIT_MS=hS,exports.SchaffTrendCycleIndicator=Ys,exports.SchiffPitchforkTool=Fg,exports.Screenshot=Cw,exports.SelectionBoxOverlay=sE,exports.SessionBreaks=Ow,exports.SessionShading=Iw,exports.SessionVWAPIndicator=us,exports.SignalMarkerManager=UT,exports.SignpostTool=yy,exports.SineLineTool=yb,exports.SpreadIndicator=ao,exports.StandardErrorBandsIndicator=rl,exports.StandardErrorIndicator=el,exports.StdDevIndicator=xc,exports.StepLineRenderer=mt,exports.StochasticIndicator=Ts,exports.StochasticMomentumIndexIndicator=Xc,exports.StochasticRSIIndicator=uc,exports.StreamManager=aC,exports.SupertrendIndicator=Zo,exports.SymbolSeriesStore=nn,exports.TEMAIndicator=bs,exports.TOUCH_REACH=md,exports.TRIXIndicator=rc,exports.TSIIndicator=Ps,exports.TapTracker=_d,exports.TextAnnotationTool=O_,exports.ThreeDrivesTool=Mv,exports.TickAggregator=cS,exports.TickBarAdapter=MS,exports.TickBarBuilder=jS,exports.TimeAxis=ud,exports.TimeCyclesTool=vb,exports.TradeZoneManager=qT,exports.TradingContextMenu=Ex,exports.TradingDragHandler=Tx,exports.TradingManager=eS,exports.TradingRenderer=tS,exports.TrendAngleTool=Rh,exports.TrendLineTool=Zh,exports.TrendStrengthIndexIndicator=Qc,exports.TriangleTool=Ag,exports.TypicalPriceIndicator=dl,exports.UPBIT_MAX_CANDLES=ZC,exports.UlcerIndexIndicator=qc,exports.UltimateOscillatorIndicator=zs,exports.UndoRedoManager=AT,exports.UpbitAdapter=nw,exports.VOLUME_HEIGHT_RATIO=yt,exports.VROCIndicator=Ec,exports.VWAPIndicator=Ko,exports.VWMAIndicator=ms,exports.VerticalLineTool=tg,exports.Viewport=He,exports.VolatilityIndexIndicator=yu,exports.VolatilityOHLCIndicator=Mu,exports.VolatilityZeroTrendIndicator=Nu,exports.VolumeCandleRenderer=ut,exports.VolumeDeltaIndicator=Is,exports.VolumeOscillatorIndicator=Gc,exports.VolumeProfileIndicator=wc,exports.VolumeProfileRangeTool=Y_,exports.VolumeProfileRenderer=Ct,exports.VolumeRenderer=bt,exports.VortexIndicator=Ls,exports.WMAIndicator=hs,exports.Watermark=ww,exports.WebSocketAdapter=OC,exports.WilliamsADIndicator=sc,exports.WilliamsFractalsIndicator=Lc,exports.WilliamsRIndicator=ks,exports.XABCDPatternTool=kv,exports.ZigZagIndicator=is,exports.ZoomHandler=Rd,exports.adapterFromFeed=GS,exports.alignAxisTags=pe,exports.alignOutput=Ta,exports.arcPoints=Wy,exports.assignSessionLetters=It,exports.axisFormat=K,exports.axisTimes=ci,exports.barIndexToTime=e.C,exports.barIndexToX=e.w,exports.barTimeStep=e.T,exports.barTimeStepMs=e.E,exports.barsToColumns=fo,exports.bracketRiskReward=Ox,exports.canvasMeasure=of,exports.cappedPixelRatio=r,exports.claimGpuContext=e.n,exports.classifyPivots=Gt,exports.cleanIntervals=Ma,exports.columnsToBars=po,exports.columnsToOutput=Co,exports.computeBarLayout=nO,exports.computeBracketDefaults=Dx,exports.computeCalendarLayout=ik,exports.computeCounterClockLayout=kk,exports.computeDepthLayout=bE,exports.computeDonutLayout=hO,exports.computeEquityLayout=PE,exports.computeHistogramLayout=zO,exports.computeMarketProfile=Pt,exports.computeMatrixLayout=gk,exports.computePeriodLevels=Ht,exports.computeScatterLayout=EO,exports.computeSessionProfiles=Lt,exports.computeWaterfallLayout=uD,exports.correlationMatrix=fk,exports.counterClockPhase=Ok,exports.counterClockPoints=Ek,exports.createIndicatorWorker=Ku,exports.curvePoints=Uy,exports.dayToIso=QO,exports.defaultFormat=rf,exports.describeInputs=Uu,exports.detectCandlePatterns=eu,exports.drawAxisValueLabels=ae,exports.drawIcon=Ub,exports.drawingAxisSpan=Am,exports.drawnKeys=Gi,exports.feedFromAdapter=qS,exports.fillTag=A,exports.findDominantSwing=Ym,exports.findPivots=Kt,exports.forEachPixelColumn=e.d,exports.forecastOutcome=wb,exports.formatTooltipTime=ip,exports.getIntParam=H,exports.getNumberParam=V,exports.getVisibleData=Ue,exports.gpuContextsLeft=e.r,exports.hasHistogram=ea,exports.hasTrades=FS,exports.histogramBins=PO,exports.hitBar=rO,exports.hitCategory=iO,exports.hitDay=ak,exports.hitHistogramBar=BO,exports.hitMatrixCell=_k,exports.hitSlice=gO,exports.hitWaterfallBar=dD,exports.idleCssCursor=Yf,exports.indicatorCategory=Ru,exports.indicatorValuePrecision=j,exports.indicatorWorkerPool=Zu,exports.inferOrderType=Fx,exports.inputSource=Sa,exports.isCrosshairCursor=Wf,exports.isDataFeed=VS,exports.isDense=e.f,exports.isInWindow=Nw,exports.isPriceLevelAlert=Kw,exports.isRegularSession=Pw,exports.isSeriesPalette=Pa,exports.isUpTone=Ki,exports.isWorkerResponse=Wu,exports.labelTextColor=ne,exports.layoutAxisValueLabels=ie,exports.layoutGroupedTreemap=WE,exports.layoutLegend=sf,exports.layoutSquarifiedTreemap=VE,exports.layoutUniformGrid=LE,exports.lineSourceBars=wa,exports.lineSpace=Vp,exports.loadWebGL=Pe,exports.loadWebGLRenderer=Fe,exports.lttbDownsample=Xe,exports.lttbVisibleIndices=Qe,exports.mergeSessionHours=jw,exports.minuteOfDay=Mw,exports.nearestCounterClockPoint=jk,exports.nearestPoint=DO,exports.niceScale=ef,exports.outputToColumns=vo,exports.paneLogRange=Qi,exports.paneValueRange=Zi,exports.parseDay=ZO,exports.pastTimeStep=e.D,exports.plotColor=Xi,exports.plotLook=Yi,exports.plotShown=qi,exports.pointAndFigureColumns=yi,exports.priceBucketRow=e.O,exports.priceScaleText=d,exports.priceSourceBars=Ca,exports.priceToY=e.k,exports.priceToYMapper=e.A,exports.rangePresetStart=Ye,exports.readAlertOptions=eT,exports.readableText=Af,exports.registerBuiltInDrawingTools=Ob,exports.registerBuiltInIndicators=Fu,exports.renderAxisValueLabels=oe,exports.renderBarChart=aO,exports.renderCalendar=ok,exports.renderCounterClock=Nk,exports.renderDenseBars=e.p,exports.renderDepthChart=CE,exports.renderDonut=_O,exports.renderEquityCurve=IE,exports.renderGauge=YD,exports.renderHeatmap=eD,exports.renderHistogram=HO,exports.renderMatrix=vk,exports.renderPlots=ta,exports.renderScatter=OO,exports.renderSparkline=pE,exports.renderWaterfall=hD,exports.resolveBarIndex=e.j,exports.resolveColorScale=Ef,exports.scaleColor=Df,exports.servesTimeframe=CS,exports.setMaxWebGLCharts=e.i,exports.shownCount=Ak,exports.shownOnInterval=ja,exports.sourceParam=xa,exports.spreadLabels=te,exports.streamAdapterOf=HS,exports.timeToX=e.M,exports.timestampToBarIndex=e.N,exports.toHeikinAshi=Kr,exports.toKagi=hi,exports.toLineBreak=mi,exports.toPointAndFigure=vi,exports.toRangeBars=Ri,exports.toRenko=li,exports.tpoLetter=Ft,exports.waveLabel=i_,exports.whenGpuContextFree=e.a,exports.withResampling=xS,exports.withTickBars=PS,exports.xToBarIndex=e.P,exports.xToTime=e.F,exports.yToPrice=e.I;
|
|
26
26
|
//# sourceMappingURL=index.cjs.map
|