@tradecanvas/core 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3,7 +3,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
3
3
  `).slice(0,Bh):[]}function qh(e,t){let n=wn(t);return e.font=Sh(n,t.bold,t.italic),e.fillStyle=t.textColor??t.color,n*zh}function Jh(e,t,n,r,i){let a=Kh(t);if(a.length===0)return null;let o=i?Uh(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`?Rh:f===`right`?-Rh:0;e.save();let h=qh(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`?-Lh-(a.length-1-n)*h:g===`bottom`?Lh+n*h:(n-(a.length-1)/2)*h;if(F(e,t,m,r),Math.abs(d)<Hh){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);Zn(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`?-Lh-v:g===`bottom`?Lh:-v/2,width:_,height:v}}function Yh(e,t,n){let r=Kh(t);if(r.length===0)return null;e.save();let i=qh(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 Xh=28,Zh=48;function Qh(e,t){return Math.atan2(e.y-t.y,t.x-e.x)*180/Math.PI}var $h=class extends Y{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=Qh(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*Zh,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,Xh,Math.min(l,c),Math.max(l,c)),e.stroke(),e.globalAlpha=1,e.font=N(`label`),e.fillStyle=jn(t.style.color),e.textAlign=s>0?`left`:`right`,e.textBaseline=`middle`,F(e,`${o.toFixed(1)}°`,i.x+s*(Xh+6),i.y+(o>=0?-8:8)),this.texts.set(t.id,Jh(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 Gh;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}},eg=3.5,tg=1.5,ng=8,rg=[{value:`normal`,label:`Normal`},{value:`arrow`,label:`Arrow`}],ig={leftEnd:{kind:`choice`,label:`Left end`,default:`normal`,choices:rg},rightEnd:{kind:`choice`,label:`Right end`,default:`normal`,choices:rg}},ag={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 og(e,t,n,r,i=1){let a=Tn(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 sg=1.5;function cg(e,t,n,r,i=1){Math.hypot(n.x-t.x,n.y-t.y)<Tn(i)*sg||og(e,t,n,r,i)}function lg(e,t,n,r){let[i,a]=t;i.x===a.x&&i.y===a.y||(r(`leftEnd`)===`arrow`&&og(e,a,i,n,Number(e.lineWidth)||1),r(`rightEnd`)===`arrow`&&og(e,i,a,n,Number(e.lineWidth)||1))}function ug(e,t,n,r,i){let a=[];i(`showPriceRange`)&&a.push(Tr(e.anchors[0].price,e.anchors[1].price,t)),i(`showBarsRange`)&&a.push(`${Or(e,0,1,t)} bars`);let o=i(`showDateRange`)?kr(e,0,1,t):null;return o&&a.push(o),i(`showAngle`)&&a.push(`${Qh(n,r).toFixed(1)}°`),a}function dg(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(eg,Mn(t.style.lineWidth)-1),0,Math.PI*2),e.fillStyle=Hn(),e.fill(),e.strokeStyle=t.style.color,e.lineWidth=tg,e.setLineDash([]),e.stroke()),!a&&!o(`alwaysShowStats`))return;let c=ug(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`){Ar(e,c,s.x,s.y-ng,`center`,!0);return}let[f,p]=d===`left`?[l,u]:[u,l],m=f.y<=p.y;Ar(e,c,d===`left`?f.x-ng:f.x+ng,f.y+(m?-ng:ng),d===`left`?`right`:`left`,m)}var fg=class extends Y{descriptor={type:`trendLine`,name:`Trend Line`,requiredAnchors:2,text:!0,options:{...lh(),...ig,...ag}};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);lg(e,[i,a],t.style.color,o),dg(e,t,n,[this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n)],r,o),this.texts.set(t.id,Jh(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`),Xp(n));return r===null?null:[r]}texts=new Gh;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}},pg=class extends Y{descriptor={type:`horizontalLine`,name:`Horizontal Line`,requiredAnchors:1,text:!0,options:dh,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,Jh(t,n.style,{x:o.x,y:a},{x:o.x+o.width,y:a})),this.option(n,`showPrice`)&&(t.fillStyle=jn(n.style.color),ir(t,Cr(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 Gh;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}},mg=class extends Y{descriptor={type:`horizontalRay`,name:`Horizontal Ray`,requiredAnchors:1,text:!0,options:dh,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,Jh(e,t.style,i,{x:o.x+o.width,y:a},o)),this.option(t,`showPrice`)){e.fillStyle=jn(t.style.color);let r=i.x+Mn(t.style.lineWidth);ir(e,Cr(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 Gh;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}},hg=4,gg=class extends Y{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-hg*2-or():o;if(this.texts.set(t.id,Jh(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;dr(e,s,i.x-n/2,o-hg-or()/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 Gh;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}},_g=class extends Y{descriptor={type:`ray`,name:`Ray`,requiredAnchors:2,text:!0,options:ag};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),dg(e,t,n,[i,a],r,this.optionsOf(t)),this.texts.set(t.id,Jh(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,Xp(n));return r===null?null:[r]}texts=new Gh;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}},vg=class extends Y{descriptor={type:`extendedLine`,name:`Extended Line`,requiredAnchors:2,text:!0,options:ag};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),dg(e,t,n,[i,a],r,this.optionsOf(t)),this.texts.set(t.id,Jh(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,Xp(n));return r===null?null:[r]}texts=new Gh;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}},yg=.7,bg=.5,xg=class extends Y{descriptor={type:`parallelChannel`,name:`Parallel Channel`,requiredAnchors:3,fill:!0,options:{...lh(),middleLine:{kind:`boolean`,label:`Middle line`,default:!0,savedDefault:!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)<bg,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(In(`dashed`,t.style.lineWidth)),e.lineCap=`butt`,e.globalAlpha=yg,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=Xp(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,wg=64;function Tg(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 Eg=class extends Y{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>=wg&&this.fits.clear(),l=Tg(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(In(`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)}},Dg=1,Og=.06,kg=3,Ag=6,jg=.8;function Mg(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:Dg,o)}%`,l=a(n);return r&&i?`${c} (${l})`:r?c:i?l:``}function Ng(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=Og,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:jg;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=Mg(e.value,i,a.showLevels,a.showPrices,e=>Cr(e,e,r),r.numberLocale);if(!s)continue;let f=t.measureText(s).width;if(t.fillStyle=jn(e.color??n.style.color),t.textBaseline=`top`,a.labelsOutside){let n=a.labelPosition===`right`,i=n?a.x1+Ag:a.x0-Ag-f,c=r.chartRect;if(i>=c.x&&i+f<=c.x+c.width){let n={left:i,right:i+f,top:o-l/2,bottom:o+l/2};if(!Mr([n],u)&&!d(e.value))continue;u.push(n),t.textAlign=`left`,F(t,s,n.left,n.top);continue}t.textAlign=n?`right`:`left`}let p=a.labelPosition===`right`?c-f:c,m={left:p,right:p+f,top:o-kg-l,bottom:o-kg},h={left:p,right:p+f,top:o+kg,bottom:o+kg+l},g=tr(p,p+f,o+kg)+kg,_={left:p,right:p+f,top:g,bottom:g+l},v=Mr([m,h,_],u)??(d(e.value)?_:null);v&&(u.push(v),F(t,s,c,v.top))}t.globalAlpha=1}var Pg=[5,4],Fg=.8;function Ig(e,t,n){t.length<2||(e.save(),e.strokeStyle=n,e.lineWidth=1,e.globalAlpha=Fg,e.setLineDash(Pg),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 Lg(e){return e.map(({level:e,price:t})=>({level:{...e,color:void 0},price:t}))}function Rg(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 zg=sh([0,.236,.382,.5,.618,.786,1],[1.272,1.414,1.618,2.618,3.618,4.236]),Bg=class extends Y{descriptor={type:`fibRetracement`,name:`Fibonacci Retracement`,requiredAnchors:2,fill:!0,options:{levels:{kind:`levels`,label:`Levels`,default:zg},...uh,reversed:{kind:`boolean`,label:`Reverse`,default:!1,savedDefault:!0,invertedAlias:`reverse`},...ph,...fh,background:{kind:`boolean`,label:`Background`,default:!0}}};levels(e){let t=this.option(e,`reversed`),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`)&&Ig(e,t.anchors.slice(0,2).map(e=>this.anchorToPixel(e,n)),t.style.color),Ng(e,t,n,this.option(t,`oneColor`)?Lg(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`),labelsOutside:!this.option(t,this.option(t,`labelPosition`)===`right`?`extendRight`:`extendLeft`),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 Rg(e,n,this.levels(t),i,a,r)}},Vg=sh([0,.618,1,1.618,2,2.618,3.618,4.236],[.382,.5,.786,1.272,1.414]),Hg=class extends Y{descriptor={type:`fibExtension`,name:`Fibonacci Extension`,requiredAnchors:3,fill:!0,options:{levels:{kind:`levels`,label:`Levels`,default:Vg},...uh,...ph,...fh,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`)&&Ig(e,t.anchors.slice(0,3).map(e=>this.anchorToPixel(e,n)),t.style.color),Ng(e,t,n,this.option(t,`oneColor`)?Lg(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`),labelsOutside:!this.option(t,this.option(t,`labelPosition`)===`right`?`extendRight`:`extendLeft`),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 Rg(e,n,this.levels(t),i,a,r)}},Ug=new Set([4,5,6,7]),Wg=class extends Y{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,Yh(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){Bp(e,t,this.handlePoints(t,n),{sides:Ug})}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 Gh;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}},Gg=class extends Y{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}},Kg=class extends Y{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 qg(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 Jg(e,t,n){return{x:e.x+t.x*n,y:e.y+t.y*n}}function Yg(e,t){let{origin:n,b:r,c:i,dir:a}=e,o=[n,r,i].map(e=>[e,Jg(e,a,qg(e,a,t))]);return[[r,i],...o]}var Xg=class extends Y{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 Yg(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(qg(i,o,r),qg(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=Jg(a,o,s),l=Jg(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:Yg(this.fork(t,n),n.chartRect).some(([t,n])=>this.distanceToLine(e,t,n)<=r)}},Zg=class extends Xg{descriptor={type:`schiffPitchfork`,name:`Schiff Pitchfork`,requiredAnchors:3,fill:!0};origin(e,t){return{x:e.x,y:(e.y+t.y)/2}}},Qg=class extends Xg{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}}},$g=5,e_=3,t_=1.25,n_=1.5,r_=[.5,.38,.62,.26,.74,.15,.85],i_=8,a_=3;function o_(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 s_(e){return Mn(e)+$g}function c_(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 l_(e,t,n,r,i){let a=o_(e,t),o=c_(e[t],a,n,r,i);return Sn(o.left,o.top,n,r).top===o.top?o:c_(e[t],a===`above`?`below`:`above`,n,r,i)}function u_(e,t){return e.left<t.right&&t.left<e.right&&e.top<t.bottom&&t.top<e.bottom}function d_(e,t,n,r){let i=e.measureText(t).width;if(!n)return{width:i,height:r};let a=2*f_(i,r);return{width:a,height:a}}function f_(e,t){return Math.max(e,t)/2+e_}function p_(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=d_(e,s,!!n.ring,r);return{text:s,ring:!!n.ring,first:!!n.first,box:l_(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=>u_(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=>!u_(t.box,e.box))&&l.push(e);return s.filter(e=>l.includes(e))}function m_(e,t,n,r,i){let a=p_(e,n,r,i,s_(t.style.lineWidth)),o=jn(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&&h_(e,r,i,(n.box.right-n.box.left)/2,t.style.color),e.fillStyle=o,F(e,n.text,r,i),g_(n.box)}return a.map(e=>e.box)}function h_(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=t_,e.setLineDash([]),e.stroke(),e.restore()}function g_(e){_n(e.left,e.top,e.right-e.left,e.bottom-e.top),Zn(e.left,e.top,e.right,e.bottom)}function __(e,t){let n=Mn(t)+n_;return e.map(e=>({left:e.x-n,right:e.x+n,top:e.y-n,bottom:e.y+n}))}function v_(e,t,n,r,i){e.font=N(`mark`);let a=e.measureText(t).width,o=M().sizes.mark,s=o+a_,c=[0,s,-s].flatMap(e=>r_.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-i_,right:e.right+i_})),u=Mr(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),g_(d),d}var y_=[`0`,`i`,`ii`,`iii`,`iv`,`v`];function b_(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?y_[Number(e)]??e:e.toLowerCase();default:return e}}function x_(e,t){return t===`primary`?{text:e,ring:!0}:{text:b_(e,t)}}var S_={degree:{kind:`choice`,label:`Degree`,default:`minor`,choices:[{value:`primary`,label:`Primary`},{value:`intermediate`,label:`Intermediate`},{value:`minor`,label:`Minor`},{value:`minute`,label:`Minute`}]}},C_=class extends Y{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}),m_(e,t,i,this.labels.map(e=>x_(e,a)),M().sizes.letter),r&&this.renderAnchorHandles(e,t,n)}hitTest(e,t,n,r){return t.anchors.length<2?!1:Qp(e,t.anchors.map(e=>this.anchorToPixel(e,n)),r)}},w_=class extends C_{descriptor={type:`elliottWave`,name:`Elliott Wave`,requiredAnchors:8,options:S_};labels=[`1`,`2`,`3`,`4`,`5`,`A`,`B`,`C`]},T_=class extends C_{descriptor={type:`elliottImpulse`,name:`Elliott Impulse Wave`,requiredAnchors:6,options:S_};labels=[`0`,`1`,`2`,`3`,`4`,`5`]},E_=class extends C_{descriptor={type:`elliottCorrection`,name:`Elliott Correction Wave`,requiredAnchors:4,options:S_};labels=[`0`,`A`,`B`,`C`]},D_=class extends C_{descriptor={type:`elliottTriangle`,name:`Elliott Triangle Wave`,requiredAnchors:6,options:S_};labels=[`0`,`A`,`B`,`C`,`D`,`E`]},O_=class extends C_{descriptor={type:`elliottDoubleCombo`,name:`Elliott Double Combo Wave`,requiredAnchors:4,options:S_};labels=[`0`,`W`,`X`,`Y`]},k_=class extends C_{descriptor={type:`elliottTripleCombo`,name:`Elliott Triple Combo Wave`,requiredAnchors:6,options:S_};labels=[`0`,`W`,`X`,`Y`,`X`,`Z`]},A_=.6,j_=6,M_=class extends Y{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,sn),e.fillRect(s,l,c,u),e.save(),this.applyGuideStyle(e,p),e.globalAlpha=A_,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),cg(e,{x:m,y:a.y},{x:m,y:o.y},p,n.style.lineWidth),e.font=N(`label`);let h=Tr(n.anchors[0].price,n.anchors[1].price,r),g=ur(e,h),_=or(),v=f?l-j_-_:l+u+j_,y=Sn(m-g/2,v,g,_);dr(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}},N_=.08,P_=6,F_=class extends Y{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,N_),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),cg(e,{x:i.x,y:d},{x:a.x,y:d},t.style.color,t.style.lineWidth);let f=Or(t,0,1,n),p=kr(t,0,1,n),m=p?`${f} bars · ${p}`:`${f} bars`;e.font=N(`label`);let h=ur(e,m),g=or(),_=Sn((s+c)/2-h/2,d-P_-g,h,g);dr(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}},I_=class extends Y{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(In(`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=[Tr(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=B_((a.x+o.x)/2,(a.y+o.y)/2,d,u.length,r);jr(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-z_;for(let e=0;e<u.length;e++)t.fillText(u[e],p,m-(u.length-1-e)*L_);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}},L_=14,R_=6,z_=4;function B_(e,t,n,r,i){let{chartRect:a}=i,o=n+2*R_,s=r*L_+2*z_,c=V_(e-o/2,a.x,a.x+a.width-o),l=V_(t-s+z_,a.y,a.y+a.height-s);if(!$n(c,l,c+o,l+s))return{x:c,y:l,width:o,height:s};let u=tr(c,c+o,l);return{x:c,y:u+s<=a.y+a.height?u:l,width:o,height:s}}function V_(e,t,n){return Math.max(t,Math.min(e,n))}var H_=500;function U_(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 W_=class extends Y{descriptor={type:`text`,name:`Text`,requiredAnchors:1,text:!0,fill:!0};boxes=new Ih;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a={...mh(t.style,{box:!1,border:!1,width:1/0}),maxLines:H_},o=Ah(e,U_(t),i.x-8,i.y-6,a);this.boxes.set(t.id,o),Mh(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 Ph(e,this.boxes.get(t.id)??G_(t,i),r)}textBox(e){return this.boxes.get(e.id)??null}};function G_(e,t){let n=wn(e.style),r=U_(e).split(`
4
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 K_=class extends Y{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(),og(e,i,a,t.style.color,t.style.lineWidth),this.resetLineStyle(e),this.texts.set(t.id,Jh(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 Gh;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}},q_=[{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}],J_=4,Y_=class extends Y{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 q_){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=jn(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*J_:h,v=e.measureText(n).width,y=e.textAlign===`right`?_-v:e.textAlign===`left`?_:_-v/2;F(e,n,_,m<=f+1?tr(y,y+v,m)+J_:m-J_)}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 q_){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}},X_=[0,.25,.333,.5,.667,.75,1].filter(e=>e>0&&e<1),Z_=.3,Q_=4,$_=2,ev=class extends Y{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=Z_;for(let t of X_)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=jn(t.style.color);let i=[...X_].sort((e,t)=>Math.abs(e-.5)-Math.abs(t-.5)),a=[],o=e=>a.every(t=>e.x1+$_<=t.x0||t.x1+$_<=e.x0||e.y1+$_<=t.y0||t.y1+$_<=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-Q_-s,x1:n.left-Q_,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+Q_,y1:n.bottom+Q_+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}},tv=6,nv=class extends Y{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 ${Cr(i,i,r)}`,o=Sn(a+tv,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}},rv=`#f2a93b`,iv=40,av=1/3,ov=.7,sv=.45,cv=.2,lv=.5,uv=.5,dv=class extends Y{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)/iv,o=new Float64Array(iv);for(let i=t;i<=n;i++){let t=e[i],n=Math.max(0,Math.floor((t.low-r)/a)),s=Math.min(iv-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<iv;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*ov&&(l>0||u<iv-1);){let e=l>0?o[l-1]:-1;(u<iv-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=Ln(n.style)?n.style.fillColor:rv,c=Math.max(1,(a.right-a.left)*av);t.save();for(let n=0;n<iv;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?sv:cv,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)-uv))}t.restore(),t.save(),this.applyGuideStyle(t,o),t.globalAlpha=lv,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(In(`dashed`,1)),this.strokeHorizontal(t,a.left,a.right,u),t.setLineDash([]),t.fillStyle=jn(s),t.font=N(`mark`),t.textAlign=`left`,t.textBaseline=`bottom`;let d=`POC ${Cr(l,l,r)}`;F(t,d,Sn(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}},fv=[1,2,3,5,8,13,21,34,55],pv=.6,mv=4,hv=class extends Y{descriptor={type:`fibTimeZones`,name:`Fibonacci Time Zones`,requiredAnchors:2,options:{levels:{kind:`levels`,label:`Levels`,default:ch([0,...fv],[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:pv,this.strokeVertical(t,d,s.y,s.y+s.height),t.globalAlpha=1;let f=String(i),p=t.measureText(f).width/2,m=tr(d-p,d+p,s.y)+mv,h={left:d-p,right:d+p,top:m,bottom:m+c};Mr([h],l)&&(l.push(h),t.fillStyle=jn(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}},gv=.14,_v=.6,vv=40,yv=2,bv=.1,xv=100,Sv=0x38d7ea4c68000,Cv=2,wv=2,Tv=4,Ev=6,Dv=class extends Y{descriptor={type:`riskReward`,name:`Long/Short Position`,priceOnly:!0,requiredAnchors:2,options:{rewardRatio:{kind:`number`,label:`Reward:risk`,default:2,min:bv,max:xv,step:.1},accountSize:{kind:`number`,label:`Account size`,default:1e3,min:0,max:Sv},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:Sv},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),vv),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,gv),e.fillRect(o,Math.min(c.y,l.y),s,Math.abs(l.y-c.y)),e.fillStyle=(0,t.withAlpha)(d.rise,gv),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=_v,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:wv});e.font=N(`label`);let v=e=>(0,t.priceTagText)(e,r,i),y=e=>(0,t.formatPrice)(e,Cv,s),b=e=>`${e>=a.entry?`+`:`−`}${wr(Math.abs(g(e)),r)}%`,x=or()+2,S=or()/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=ur(e,t),a=Math.max(p+4,Math.min(Math.max(o+4,r??-1/0),m-4-i)),s=n-S;if(er(a,s,a+i,s+or())){let e=(nr(s,s+or())??a)+Tv;e+i<=m-4&&!er(e,s,e+i,s+or())?a=e:s=tr(a,a+i,s)+2}return Zn(a,s,a+i,s+or()),{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+Mn(n.style.lineWidth)+Ev}];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);dr(e,t.text,n.left,n.top+S,t.color)}}i&&this.renderHandles(e,n,r)}renderHandles(e,t,n){Bp(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!==yv){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(xv,Math.max(bv,o/a)):bv;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}},Ov=class extends Y{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 kv(e,t,n){let r=kr(e,0,1,t),i=Or(e,0,1,t);return[Tr(e.anchors[0].price,e.anchors[1].price,t),r?`${i} bars, ${r}`:`${i} bars`,`${n.toFixed(1)}°`]}var Av=class extends Y{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=kv(t,n,Qh(i,a)),s=a.y<=i.y;Ar(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,Jh(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 Gh;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}},jv=.7,Mv=10,Nv=[0,.236,.382,.5,.618,.786,1,1.618];function Pv(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 Fv(e,t,n,r){let i=Pv(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 Iv=class extends Y{descriptor={type:`fibChannel`,name:`Fibonacci Channel`,requiredAnchors:3,options:{levels:{kind:`levels`,label:`Levels`,default:sh(Nv,[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]=Fv(i,a,o,n);this.applyLineStyle(e,{...t.style,color:r??t.style.color}),e.globalAlpha=n===0||n===1?1:jv,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]=Fv(i,a,o,n),f=s.x<=d.x?s:d,p=String(n),m=e.measureText(p).width,h={left:f.x-Mv-m,right:f.x-Mv,top:f.y-c/2,bottom:f.y+c/2};!Mr([h],l)&&!u(n)||(l.push(h),e.fillStyle=jn(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]=Fv(i,a,o,n);if(this.distanceToLine(e,t,s)<=r)return!0}return!1}},Lv=.4,Rv=.8,zv=4,Bv=[.25,.382,.5,.618,.75];function Vv(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 Hv(e,t,n=Bv){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 Uv=class extends Y{descriptor={type:`fibSpeedResistanceFan`,name:`Fib Speed Resistance Fan`,requiredAnchors:2,options:{levels:{kind:`levels`,label:`Levels`,default:sh(Bv,[.236,.786])}}};targets(e,t,n){return Hv(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=Lv,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=Vv(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:Rv,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(a.x,a.y),e.stroke(),r.kind!==`diagonal`&&(e.globalAlpha=1,e.fillStyle=jn(c),r.kind===`price`?(e.textAlign=o?`left`:`right`,e.textBaseline=`middle`,F(e,String(r.level),r.point.x+(o?zv:-zv),r.point.y)):(e.textAlign=`center`,e.textBaseline=s?`top`:`bottom`,F(e,String(r.level),r.point.x,r.point.y+(s?zv:-zv))))}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=Vv(i,o.point,n);if(t&&this.distanceToLine(e,i,t)<=r)return!0}return!1}},Wv=class extends Y{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,[...__(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=jn(t.style.color);for(let r of this.linksIn(n)){let a=v_(e,Nr(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,m_(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}},Gv=class extends Wv{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]]},Kv=class extends Wv{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]}]},qv=class extends Wv{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([])}},Jv=class extends Wv{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]}]},Yv=class extends Wv{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]]},Xv=class extends Y{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}},Zv=.5;function Qv(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 $v(e,n){let r=kr(e,0,1,n),i=Or(e,0,1,n),a=[Tr(e.anchors[0].price,e.anchors[1].price,n),r?`${i} bars · ${r}`:`${i} bars`],o=Qv(e,n);return o!==null&&a.push(`Vol ${(0,t.formatVolumeLoc)(o,n.numberLocale??`en-US`)}`),a}var ey=class extends Y{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,sn),e.fillRect(s,c,l,u),e.save(),this.applyGuideStyle(e,p),e.globalAlpha=Zv,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),cg(e,{x:m,y:a.y},{x:m,y:o.y},p,n.style.lineWidth),cg(e,{x:a.x,y:h},{x:o.x,y:h},p,n.style.lineWidth),Ar(e,$v(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}},ty=400,ny=2;function ry(e,t,n){let r=Math.abs(t.x-e.x);if(r<ny)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<ty;e+=r)a.push(e);return a}var iy=class extends Y{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 ry(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:ry(this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n),n).some(t=>Math.abs(e.x-t)<=r)}},ay=240;function oy(e){return wn(e.style)}function sy(e){return{...mh(e.style,{box:!0,border:!0,width:ay,fill:!0,solid:!0}),radius:6}}function cy(e,t,n,r){let i=oy(e),a=Math.max(...t.split(`
5
5
  `).map(e=>e.length));return{x:n,y:r,width:Math.min(ay,a*i*.6)+16,height:i*1.3+12}}var ly=7,uy=16,dy=class extends Y{descriptor={type:`note`,name:`Note`,requiredAnchors:1,text:!0,fill:!0,options:{showText:{kind:`boolean`,label:`Show text`,default:!0}}};boxes=new Ih;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=Ah(e,U_(t,`Note`),i.x+ly+6,i.y-uy-ly,sy(t));this.boxes.set(t.id,n)}r&&this.renderAnchorHandles(e,t,n)}renderPin(e,t,n){let r=n.y-uy;e.fillStyle=t.style.color,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-ly*.7,r+ly*.5),e.arc(n.x,r,ly,Math.PI*.8,Math.PI*.2),e.closePath(),e.fill(),e.fillStyle=M().background,e.beginPath(),e.arc(n.x,r,ly*.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 Ph(e,{x:i.x-ly,y:i.y-uy-ly,width:ly*2,height:uy+ly},r)?!0:this.option(t,`showText`)?Ph(e,this.boxes.get(t.id)??cy(t,U_(t,`Note`),i.x+ly+6,i.y-uy-ly),r):!1}textBox(e){return this.option(e,`showText`)?this.boxes.get(e.id)??null:null}},fy=class extends Y{descriptor={type:`callout`,name:`Callout`,requiredAnchors:2,text:!0,fill:!0};boxes=new Ih;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n);if(t.anchors.length<2){e.fillStyle=t.style.color,e.beginPath(),e.arc(i.x,i.y,3,0,Math.PI*2),e.fill();return}let a=this.anchorToPixel(t.anchors[1],n),o=U_(t,`Callout`),s=sy(t),c=py(a,kh(e,o,s),n),l=Ah(e,o,c.left,c.top,{...s,traceBox:_h(i,8)});!s.fill&&!s.stroke&&this.strokeBareTail(e,t,l,i),this.boxes.set(t.id,l),r&&this.renderAnchorHandles(e,t,n)}strokeBareTail(e,t,n,r){let i=my(n,r);this.applyLineStyle(e,t.style),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(r.x,r.y),e.stroke(),this.resetLineStyle(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=this.boxes.get(t.id)??cy(t,U_(t,`Callout`),a.x,a.y);if(Ph(e,o,r))return!0;let s=gh(o,i,8,6);return s!==null&&vh(e,s.first,i,s.second,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 py(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?Sn(e.x,e.y,t.width,t.height):{left:e.x,top:e.y}}function my(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 hy=24,gy=18,_y=10,vy=class extends Y{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-hy;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+gy,a),e.lineTo(i.x+gy-5,a+_y/2),e.lineTo(i.x+gy,a+_y),e.lineTo(i.x,a+_y),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 Ph(e,{x:i.x,y:i.y-hy,width:gy,height:hy},r)}},yy={up:{x:0,y:-1},down:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0}};function by(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 xy=class extends Y{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=yy[this.option(e,`direction`)]??yy.up,i=this.option(e,`size`);return{points:by(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(wn(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)),Mh(e,Nh(i),t.style.color,r)}handlePoints(){return[]}hitTest(e,t,n,r){return t.anchors.length<1?!1:Ph(e,Nh(this.outline(t,n).points),r)}},Sy=[`star`,`heart`,`check`,`cross`,`circle`,`triangleUp`,`triangleDown`,`bolt`];function Cy(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 wy=class extends Y{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`);Cy(e,Sy.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()),Mh(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}},Ty=200,Ey=36,Dy=.4,Oy=8,ky=.6;function Ay(e){let t=Math.max(Oy,Math.round(e*Dy));return{length:t,half:Math.round(t*ky)}}function jy(e){return{...mh(e.style,{box:!0,border:!0,width:Ty,fill:!0,solid:!0}),radius:6}}function My(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 Ny(e,t){let n=wn(e.style),r=t.split(`
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 Py=class extends Y{descriptor={type:`signpost`,name:`Signpost`,requiredAnchors:1,text:!0,fill:!0};boxes=new Ih;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=U_(t,`Signpost`),o=jy(t),s=My(i,kh(e,a,o),Ey,n);this.applyLineStyle(e,{...t.style,lineStyle:`solid`}),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x,s.below?i.y+Ey:i.y-Ey),e.stroke(),this.resetLineStyle(e),this.boxes.set(t.id,Ah(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)??My(i,Ny(t,U_(t,`Signpost`)),Ey,n),[o,s]=a.y>i.y?[i.y,i.y+Ey]:[i.y-Ey,i.y];return Math.abs(e.x-i.x)<=r&&e.y>=o-r&&e.y<=s+r?!0:Ph(e,a,r)}textBox(e){return this.boxes.get(e.id)??null}},Fy=class extends Y{descriptor={type:`balloon`,name:`Balloon`,requiredAnchors:1,text:!0,fill:!0};boxes=new Ih;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=U_(t,`Comment`),o=jy(t),s=kh(e,a,o),c=Ay(s.height),l=My(i,s,c.length,n),u={...o,traceBox:_h(i,c.half)};this.boxes.set(t.id,Ah(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=Ny(t,U_(t,`Comment`)),o=this.boxes.get(t.id)??My(i,a,Ay(a.height).length,n),s=Ay(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:Ph(e,o,r)}textBox(e){return this.boxes.get(e.id)??null}},Iy=class extends W_{descriptor={type:`anchoredText`,name:`Anchored Text`,requiredAnchors:1,text:!0,fill:!0,anchoring:`screen`}},Ly=class extends dy{descriptor={type:`anchoredNote`,name:`Anchored Note`,requiredAnchors:1,text:!0,fill:!0,anchoring:`screen`,options:{showText:{kind:`boolean`,label:`Show text`,default:!0}}}},Ry=14,zy=18,By=8,Vy=5,Hy=1.35,Uy=3,Wy=3;function Gy(e){return Math.round(e*Hy)+Vy*2}var Ky=class extends Y{drawn=new Ih;descriptor={type:`priceLabel`,name:`Price Label`,requiredAnchors:1,text:!0};text(e,t){return e.style.text||Cr(e.anchors[0].price,e.anchors[0].price,t)}box(e,t,n,r){let i=wn(t.style,`label`),a=this.text(t,r),o=e?e.measureText(a).width:a.length*i*.6,s=Gy(i);return{x:n.x+Ry,y:n.y-zy-s/2,w:Math.ceil(o)+By*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(wn(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??Rn(t.style.color),e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(this.text(t,n),a.x+By,a.y+a.h/2),e.beginPath(),e.arc(i.x,i.y,Wy,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),Uy):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}},qy=48;function Jy(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 Yy(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 Xy(e,t,n,r=Tn(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 Zy(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 Qy=new WeakMap;function $y(e){let t=Qy.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);Qy.set(e,t)}return t}var eb=class extends Y{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,Jy(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;Mh(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}=$y(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:Qp(e,t.anchors.map(e=>this.anchorToPixel(e,n)),i)}},tb=class extends eb{descriptor={type:`highlighter`,name:`Highlighter`,requiredAnchors:2,creation:`freehand`};stroke(e){return{width:Math.max(10,e.style.lineWidth*8),alpha:.3}}},nb=class extends Y{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`,Yy(e,i),e.stroke(),this.resetLineStyle(e),this.option(t,`arrowEnd`)&&Xy(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:Qp(e,t.anchors.map(e=>this.anchorToPixel(e,n)),r)}},rb=class extends Y{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;Yy(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 Qp(e,i,r,!0)||i.length>=3&&Zy(e,i)}};function ib(e,t,n,r=qy){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 ab(e,t,n,r=qy){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 ob=class extends Y{descriptor={type:`curve`,name:`Curve`,requiredAnchors:3};shape(e,t,n){return ib(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),Yy(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:Qp(e,this.points(t,n),r)}},sb=class extends ob{descriptor={type:`arc`,name:`Arc`,requiredAnchors:3};shape(e,t,n){return ab(e,t,n)}},cb=(1+Math.sqrt(5))/2,lb=64,ub=2,db=6,fb=-Math.PI/4,pb=.7,mb=.3,hb=.7,gb=8;function _b(e,t=[]){return{levels:{kind:`levels`,label:`Levels`,default:sh(e,t)},showLevels:{kind:`boolean`,label:`Show levels`,default:!0}}}var vb=[.236,.382,.5,.618,.786,1];function yb(e){return String(Number(e.toFixed(3)))}function bb(e,t,n,r,i,a=lb){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 xb(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 Y{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=pb;for(let[t,n]of this.guides(i))xb(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,xb(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=yb(n.value),c=e.measureText(a).width,l=s??{x:0,y:-1},u=o.x+l.x*db,d=o.y+l.y*db,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+ub>e.x0&&e.x1+ub>m.x0&&m.y1+ub>e.y0&&e.y1+ub>m.y0)||(i.push(m),e.fillStyle=jn(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])=>Zp(e,t,n)<=r)?!0:this.shapes(i,this.visibleLevels(t),n,t).some(t=>Qp(e,t.points,r))}},wb=class extends Cb{descriptor={type:`fibCircles`,name:`Fib Circles`,requiredAnchors:2,options:_b([...vb,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(fb),y:n.y+t*Math.sin(fb)};return{level:e,points:bb(n,t,t,0,Math.PI*2),label:r,away:{x:Math.SQRT1_2,y:-Math.SQRT1_2}}})}},Tb=class extends Cb{descriptor={type:`fibArcs`,name:`Fib Speed Resistance Arcs`,requiredAnchors:2,options:{..._b(vb),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?bb(i,t,t,0,Math.PI*2):bb(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)}})}},Eb=class extends Cb{descriptor={type:`fibWedge`,name:`Fib Wedge`,requiredAnchors:3,options:_b(vb)};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:bb(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}}})}},Db=class extends Cb{descriptor={type:`pitchfan`,name:`Pitchfan`,requiredAnchors:3,options:_b([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)}})}},Ob=class extends Y{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(cb),u=Math.log(i/gb)/Math.log(cb),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*cb**+(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),xb(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:Qp(e,this.points(t,n),r)}},kb=class extends Y{descriptor={type:`gannSquare`,name:`Gann Square`,requiredAnchors:2,options:{..._b([.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 bb(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=mb,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=hb,xb(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):xb(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])=>Zp(e,t,n)<=r)}},Ab=400,jb=32,Mb=3,Nb=class extends Y{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<Ab;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<=jb;i++){let a=Math.PI+Math.PI*i/jb;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)}},Pb=class extends Y{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+=Mb)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:Qp(e,this.points(t,n),r)}},Fb=5,Ib=.85,Lb=.08,Rb=500;function zb(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 Bb=class extends Y{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=zb(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>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=kr(t,0,1,n);Ar(e,[Tr(i.price,a.price,n),`${Cr(a.price,i.price,n)} · ${Or(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:Zp(e,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n))<=r}},Vb=class extends Y{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(),Xy(e,r,a);let[o,s,c]=t.anchors,l=c.price+(s.price-o.price);Ar(e,[Cr(l,c.price,n),Tr(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 Zp(e,i[0],i[1])<=r?!0:i.length>=3&&Zp(e,i[2],this.target(t,n))<=r}},Hb=class extends Y{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+Rb));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,Lb),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=Ib,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&&Ph(e,i,r))return!0;let a=t.anchors.length>=3?this.box(t,n,this.copied(t)):null;return a!==null&&Ph(e,a,r)}};function Ub(e){e.register(new fg),e.register(new pg),e.register(new mg),e.register(new gg),e.register(new _g),e.register(new vg),e.register(new xg),e.register(new Eg),e.register(new Bg),e.register(new Hg),e.register(new Wg),e.register(new Gg),e.register(new Kg),e.register(new Xg),e.register(new w_),e.register(new M_),e.register(new F_),e.register(new I_),e.register(new W_),e.register(new K_),e.register(new Y_),e.register(new ev),e.register(new nv),e.register(new dv),e.register(new hv),e.register(new Dv),e.register(new Ov),e.register(new $h),e.register(new Av),e.register(new Iv),e.register(new Uv),e.register(new Zg),e.register(new Qg),e.register(new Gv),e.register(new Kv),e.register(new qv),e.register(new Xv),e.register(new ey),e.register(new iy),e.register(new Ky),e.register(new dy),e.register(new fy),e.register(new vy),e.register(new xy),e.register(new wy),e.register(new Py),e.register(new Fy),e.register(new Iy),e.register(new Ly),e.register(new eb),e.register(new tb),e.register(new nb),e.register(new rb),e.register(new ob),e.register(new sb),e.register(new wb),e.register(new Ob),e.register(new Tb),e.register(new Eb),e.register(new Db),e.register(new kb),e.register(new T_),e.register(new E_),e.register(new D_),e.register(new O_),e.register(new k_),e.register(new Jv),e.register(new Yv),e.register(new Nb),e.register(new Pb),e.register(new Bb),e.register(new Vb),e.register(new Hb)}function Z(e,t){let{chartRect:n}=t;return e>=n.y&&e<=n.y+n.height}function Wb(e,t){let{chartRect:n}=t;return Math.min(Math.max(e,n.y),n.y+n.height)}function Gb(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 Kb(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 qb=/\{(side|qty|closedQty|openQty|entry|price|pnl|pnlPct|pnlSign)\}/g;function Jb(e,n){return e.replace(qb,(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 Yb(e,n,r){let i=10**n,a=Math.round(e*i)/i||0;return`${a>0?`+`:``}${(0,t.formatPrice)(a,n,r)}`}var Xb=2,Zb=2,Qb=2;function $b(e,n,r){if(r!==void 0)return r;let i=Math.abs(e),a=Math.abs(n),o=Math.round(i*10**Xb)>0;if(!(i>0)||!Number.isFinite(i)||o||!(a>0&&a<1))return Xb;let s=(0,t.smallValueDecimals)(i,Zb);return s<=(0,t.smallValueDecimals)(a)+Qb?s:Xb}function ex(e,t,n,r){return(r-t)*n*(e===`buy`?1:-1)}function tx(e,t){return typeof e==`function`?e(t):Jb(e??`{side} {qty} | P&L: {pnlSign}{pnl}`,t)}function nx(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 rx=24,ix=1.75,ax=[2,2.5],ox=new Map,sx=e=>{let t=ox.get(e);return t||(t=new Path2D(e),ox.set(e,t)),t};function cx(e,n,r,i,a,o){if(!(typeof Path2D>`u`)){if(e.save(),e.translate(Math.round(r),Math.round(i)),e.scale(a/rx,a/rx),e.strokeStyle=o,e.fillStyle=o,e.lineWidth=Math.max(ix,rx/a),e.lineCap=`round`,e.lineJoin=`round`,e.setLineDash([]),n.soft){let r=e.globalAlpha;e.globalAlpha=r*t.ICON_SOFT_OPACITY,e.fill(sx(n.soft)),e.globalAlpha=r}for(let t of n.fills??[])e.fill(sx(t));n.d&&e.stroke(sx(n.d)),n.dash&&(e.setLineDash(ax),e.stroke(sx(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 lx=5,ux=13,dx=22;function fx(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 px(e,t){return`${e.kind===`stamp`?`600 `:``}${t.font.sizeSmall}px ${t.font.family}`}function mx(e,t,n){return t.kind===`button`?21:(e.font=px(t,n),Math.ceil(e.measureText(t.text).width)+lx*2)}function hx(e){return Math.round(e)-10}function gx(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)<dx&&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 _x(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=>mx(e,t,r))),u=l.map(e=>e.reduce((e,t)=>e+t,0)),d=gx(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=hx(t[n].y);vx(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 vx(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`?(cx(e,n.icon,l+(u-ux)/2,r+(21-ux)/2,ux,o.text),s.push({x:l,y:r,size:21,action:n.action})):(e.font=px(n,o),e.fillStyle=n.kind===`stamp`?ne(t.color):n.color??o.text,e.fillText(n.text,l+lx,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 yx(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 bx(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+7,Math.round(n))}var xx=[6,4],Sx=[2,3],Cx=[2,4],wx=.3;function Tx(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 Ex(e){return{buy:e.orderColors?.buy??`#1fa874`,sell:e.orderColors?.sell??`#e8505b`,profit:e.positionColors?.profit??`#1fa874`,loss:e.positionColors?.loss??`#e8505b`}}function Dx(e,t){return t?.orderId===e.id&&t.sourceType===`order`}function Ox(e,t){return Dx(e,t)?t.currentPrice:e.price}var kx=class{render(e,t,n,r,i,a,o=[]){this.renderLines(e,t,n,i,a),_x(e,this.tags(t,n,i,a),n,r,o)}renderLines(t,n,r,i,a){let o=Ex(i);for(let i of n){let n=e.k(Ox(i,a),r),s=i.side===`buy`?o.buy:o.sell;Z(n,r)&&Gb(t,r,n,s,xx),Dx(i,a)&&(t.globalAlpha=wx,Gb(t,r,e.k(a.startPrice,r),s,Cx),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);Z(i,r)&&Gb(t,r,i,a,Sx)}}}tags(n,r,i,a){let o=Ex(i),s=[];for(let c of n){let n=Ox(c,a),l=e.k(n,r);if(Z(l,r)){let e=[{kind:`stamp`,text:String(c.quantity)},{kind:`text`,text:Tx(c)}];i.lineButtons?.cancel!==!1&&!Dx(c,a)&&e.push({kind:`button`,icon:t.UI_ICONS.x,action:{type:`cancelOrder`,orderId:c.id}});let n=c.draggable===!1?void 0:{kind:`order`,orderId:c.id};s.push({y:l,color:c.side===`buy`?o.buy:o.sell,cells:e,grab:n})}for(let t of[`stopLoss`,`takeProfit`]){let a=c[t],l=a===void 0?NaN:e.k(a,r);if(a===void 0||!Z(l,r))continue;let u=ex(c.side,n,c.quantity,a);s.push({y:l,color:t===`stopLoss`?o.loss:o.profit,cells:[{kind:`stamp`,text:t===`stopLoss`?`SL`:`TP`},{kind:`text`,text:Yb(u,$b(u,n,i.pricePrecision),r.numberLocale),color:u>=0?o.profit:o.loss}]})}}return s}renderAxisBadges(e,t,n,r,i,a){for(let o of this.axisBadges(t,n,i,a))bx(e,o.y,o.text,o.color,n,r)}axisBadges(n,r,i,a){let o=Ex(i),s=[];for(let c of n){let n=Ox(c,a),l=e.k(n,r);Z(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}},Ax=[4,4],jx=[2,4],Mx=.3,Nx=.08,Px=.25,Fx=.04,Ix=[`stopLoss`,`takeProfit`];function Lx(e){return{profit:e.positionColors?.profit??`#1fa874`,loss:e.positionColors?.loss??`#e8505b`,entry:e.positionColors?.entry??`#4c8dff`}}function Rx(e,t){let{chartRect:n}=t;return e-21/2>=n.y&&e+21/2<=n.y+n.height}function zx(e){return e.quantity-Math.min(Math.max(e.closedQuantity??0,0),e.quantity)}function Bx(e,t,n){return n?.orderId===e.id&&n.sourceType===t?n.currentPrice:e[t]}var Vx=class{render(e,t,n,r,i,a,o=[],s=null){this.renderLines(e,t,n,r,a,s),_x(e,this.tags(t,n,r,a,s),r,i,o)}renderLines(t,n,r,i,a,o=null){let s=Lx(a);for(let c of n){let n=e.k(c.entryPrice,i);Gb(t,i,n,s.entry,[]),r!==null&&this.renderBand(t,c,n,e.k(r,i),r,i,a);for(let n of Ix){let r=Bx(c,n,o),a=r===void 0?NaN:e.k(r,i),l=n===`stopLoss`?s.loss:s.profit;Z(a,i)&&Gb(t,i,a,l,Ax);let u=c[n];u!==void 0&&r!==u&&(t.globalAlpha=Mx,Gb(t,i,e.k(u,i),l,jx),t.globalAlpha=1)}}}renderBand(e,t,n,r,i,a,o){let{chartRect:s}=a,c=Lx(o),l=Kb(t,i,o.pricePrecision??2),u=Math.min(n,r),d=Math.abs(r-n);e.fillStyle=nx(l.pnl,o.pnlThresholds,l.pnl>=0?c.profit:c.loss),e.globalAlpha=Nx,e.fillRect(s.x,u,s.width,d),l.closedQuantity>0&&t.quantity>0&&(e.fillStyle=c.entry,e.globalAlpha=Px,e.fillRect(s.x,u,Math.max(2,s.width*(l.closedQuantity/t.quantity)*Fx)+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 Ix){let s=this.stopTag(o,e,n,r,i,t);s&&a.push(s)}}return a}entryTag(n,r,i,a){let o=e.k(n.entryPrice,i);if(!Z(o,i))return null;let s=Lx(a),c=n.side===`buy`?`Long`:`Short`,l=[{kind:`stamp`,text:String(zx(n))}];if(r===null)l.push({kind:`text`,text:c});else{let e=Kb(n,r,a.pricePrecision??2,e=>(0,t.priceTagText)(e,i,a.pricePrecision),i.numberLocale);if(a.positionLabel!==void 0)l.push({kind:`text`,text:tx(a.positionLabel,e)});else{let t=nx(e.pnl,a.pnlThresholds,e.pnl>=0?s.profit:s.loss);l.push({kind:`text`,text:c},{kind:`text`,text:Yb(e.pnl,$b(e.pnl,r,a.pricePrecision),i.numberLocale),color:t})}}let u=a.lineButtons??{};return Rx(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,s=null){let c=Bx(n,r,o),l=c===void 0?NaN:e.k(c,i);if(c===void 0||!Z(l,i))return null;let u=Lx(a),d=ex(n.side,n.entryPrice,zx(n),c),f=typeof n.trailingStop==`number`&&n.trailingStop>0,p=[{kind:`stamp`,text:r===`takeProfit`?`TP`:f?`TSL`:`SL`},{kind:`text`,text:Yb(d,$b(d,n.entryPrice,a.pricePrecision),i.numberLocale),color:d>=0?u.profit:u.loss}],m=o?.orderId===n.id&&o.sourceType===r;if(r===`stopLoss`&&a.lineButtons?.trailStop!==!1&&Rx(l,i)&&!m){let e=n.side===`buy`,r=s===null?NaN:e?s-c:c-s,i=f?null:r>0?r:void 0;i!==void 0&&p.push({kind:`button`,icon:e?t.UI_ICONS.trendingUp:t.UI_ICONS.trendingDown,action:{type:`trailStop`,positionId:n.id,distance:i}})}return a.lineButtons?.removeStops!==!1&&Rx(l,i)&&!m&&p.push({kind:`button`,icon:t.UI_ICONS.x,action:{type:`removeStop`,positionId:n.id,which:r}}),{y:l,color:r===`stopLoss`?u.loss:u.profit,cells:p,grab:{kind:`stop`,positionId:n.id,which:r}}}renderAxisBadges(e,t,n,r,i){for(let a of this.axisBadges(t,n,i))bx(e,a.y,a.text,a.color,n,r)}axisBadges(n,r,i,a=null){let o=Lx(i),s=[];for(let c of n){let n=[[Bx(c,`stopLoss`,a),o.loss],[Bx(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);Z(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.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)}}},Ux=[`stopLoss`,`takeProfit`],Wx=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 Z(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 Ux){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}},Gx=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=`
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 Py=class extends Y{descriptor={type:`signpost`,name:`Signpost`,requiredAnchors:1,text:!0,fill:!0};boxes=new Ih;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=U_(t,`Signpost`),o=jy(t),s=My(i,kh(e,a,o),Ey,n);this.applyLineStyle(e,{...t.style,lineStyle:`solid`}),e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x,s.below?i.y+Ey:i.y-Ey),e.stroke(),this.resetLineStyle(e),this.boxes.set(t.id,Ah(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)??My(i,Ny(t,U_(t,`Signpost`)),Ey,n),[o,s]=a.y>i.y?[i.y,i.y+Ey]:[i.y-Ey,i.y];return Math.abs(e.x-i.x)<=r&&e.y>=o-r&&e.y<=s+r?!0:Ph(e,a,r)}textBox(e){return this.boxes.get(e.id)??null}},Fy=class extends Y{descriptor={type:`balloon`,name:`Balloon`,requiredAnchors:1,text:!0,fill:!0};boxes=new Ih;render(e,t,n,r){if(t.anchors.length<1)return;let i=this.anchorToPixel(t.anchors[0],n),a=U_(t,`Comment`),o=jy(t),s=kh(e,a,o),c=Ay(s.height),l=My(i,s,c.length,n),u={...o,traceBox:_h(i,c.half)};this.boxes.set(t.id,Ah(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=Ny(t,U_(t,`Comment`)),o=this.boxes.get(t.id)??My(i,a,Ay(a.height).length,n),s=Ay(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:Ph(e,o,r)}textBox(e){return this.boxes.get(e.id)??null}},Iy=class extends W_{descriptor={type:`anchoredText`,name:`Anchored Text`,requiredAnchors:1,text:!0,fill:!0,anchoring:`screen`}},Ly=class extends dy{descriptor={type:`anchoredNote`,name:`Anchored Note`,requiredAnchors:1,text:!0,fill:!0,anchoring:`screen`,options:{showText:{kind:`boolean`,label:`Show text`,default:!0}}}},Ry=14,zy=18,By=8,Vy=5,Hy=1.35,Uy=3,Wy=3;function Gy(e){return Math.round(e*Hy)+Vy*2}var Ky=class extends Y{drawn=new Ih;descriptor={type:`priceLabel`,name:`Price Label`,requiredAnchors:1,text:!0};text(e,t){return e.style.text||Cr(e.anchors[0].price,e.anchors[0].price,t)}box(e,t,n,r){let i=wn(t.style,`label`),a=this.text(t,r),o=e?e.measureText(a).width:a.length*i*.6,s=Gy(i);return{x:n.x+Ry,y:n.y-zy-s/2,w:Math.ceil(o)+By*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(wn(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??Rn(t.style.color),e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(this.text(t,n),a.x+By,a.y+a.h/2),e.beginPath(),e.arc(i.x,i.y,Wy,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),Uy):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}},qy=48;function Jy(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 Yy(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 Xy(e,t,n,r=Tn(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 Zy(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 Qy=new WeakMap;function $y(e){let t=Qy.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);Qy.set(e,t)}return t}var eb=class extends Y{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,Jy(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;Mh(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}=$y(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:Qp(e,t.anchors.map(e=>this.anchorToPixel(e,n)),i)}},tb=class extends eb{descriptor={type:`highlighter`,name:`Highlighter`,requiredAnchors:2,creation:`freehand`};stroke(e){return{width:Math.max(10,e.style.lineWidth*8),alpha:.3}}},nb=class extends Y{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`,Yy(e,i),e.stroke(),this.resetLineStyle(e),this.option(t,`arrowEnd`)&&Xy(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:Qp(e,t.anchors.map(e=>this.anchorToPixel(e,n)),r)}},rb=class extends Y{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;Yy(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 Qp(e,i,r,!0)||i.length>=3&&Zy(e,i)}};function ib(e,t,n,r=qy){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 ab(e,t,n,r=qy){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 ob=class extends Y{descriptor={type:`curve`,name:`Curve`,requiredAnchors:3};shape(e,t,n){return ib(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),Yy(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:Qp(e,this.points(t,n),r)}},sb=class extends ob{descriptor={type:`arc`,name:`Arc`,requiredAnchors:3};shape(e,t,n){return ab(e,t,n)}},cb=(1+Math.sqrt(5))/2,lb=64,ub=2,db=6,fb=-Math.PI/4,pb=.7,mb=.3,hb=.7,gb=8;function _b(e,t=[]){return{levels:{kind:`levels`,label:`Levels`,default:sh(e,t)},showLevels:{kind:`boolean`,label:`Show levels`,default:!0}}}var vb=[.236,.382,.5,.618,.786,1];function yb(e){return String(Number(e.toFixed(3)))}function bb(e,t,n,r,i,a=lb){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 xb(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 Y{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=pb;for(let[t,n]of this.guides(i))xb(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,xb(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=yb(n.value),c=e.measureText(a).width,l=s??{x:0,y:-1},u=o.x+l.x*db,d=o.y+l.y*db,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+ub>e.x0&&e.x1+ub>m.x0&&m.y1+ub>e.y0&&e.y1+ub>m.y0)||(i.push(m),e.fillStyle=jn(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])=>Zp(e,t,n)<=r)?!0:this.shapes(i,this.visibleLevels(t),n,t).some(t=>Qp(e,t.points,r))}},wb=class extends Cb{descriptor={type:`fibCircles`,name:`Fib Circles`,requiredAnchors:2,options:_b([...vb,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(fb),y:n.y+t*Math.sin(fb)};return{level:e,points:bb(n,t,t,0,Math.PI*2),label:r,away:{x:Math.SQRT1_2,y:-Math.SQRT1_2}}})}},Tb=class extends Cb{descriptor={type:`fibArcs`,name:`Fib Speed Resistance Arcs`,requiredAnchors:2,options:{..._b(vb),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?bb(i,t,t,0,Math.PI*2):bb(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)}})}},Eb=class extends Cb{descriptor={type:`fibWedge`,name:`Fib Wedge`,requiredAnchors:3,options:_b(vb)};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:bb(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}}})}},Db=class extends Cb{descriptor={type:`pitchfan`,name:`Pitchfan`,requiredAnchors:3,options:_b([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)}})}},Ob=class extends Y{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(cb),u=Math.log(i/gb)/Math.log(cb),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*cb**+(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),xb(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:Qp(e,this.points(t,n),r)}},kb=class extends Y{descriptor={type:`gannSquare`,name:`Gann Square`,requiredAnchors:2,options:{..._b([.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 bb(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=mb,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=hb,xb(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):xb(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])=>Zp(e,t,n)<=r)}},Ab=400,jb=32,Mb=3,Nb=class extends Y{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<Ab;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<=jb;i++){let a=Math.PI+Math.PI*i/jb;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)}},Pb=class extends Y{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+=Mb)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:Qp(e,this.points(t,n),r)}},Fb=5,Ib=.85,Lb=.08,Rb=500;function zb(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 Bb=class extends Y{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=zb(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>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=kr(t,0,1,n);Ar(e,[Tr(i.price,a.price,n),`${Cr(a.price,i.price,n)} · ${Or(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:Zp(e,this.anchorToPixel(t.anchors[0],n),this.anchorToPixel(t.anchors[1],n))<=r}},Vb=class extends Y{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(),Xy(e,r,a);let[o,s,c]=t.anchors,l=c.price+(s.price-o.price);Ar(e,[Cr(l,c.price,n),Tr(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 Zp(e,i[0],i[1])<=r?!0:i.length>=3&&Zp(e,i[2],this.target(t,n))<=r}},Hb=class extends Y{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+Rb));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,Lb),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=Ib,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&&Ph(e,i,r))return!0;let a=t.anchors.length>=3?this.box(t,n,this.copied(t)):null;return a!==null&&Ph(e,a,r)}};function Ub(e){e.register(new fg),e.register(new pg),e.register(new mg),e.register(new gg),e.register(new _g),e.register(new vg),e.register(new xg),e.register(new Eg),e.register(new Bg),e.register(new Hg),e.register(new Wg),e.register(new Gg),e.register(new Kg),e.register(new Xg),e.register(new w_),e.register(new M_),e.register(new F_),e.register(new I_),e.register(new W_),e.register(new K_),e.register(new Y_),e.register(new ev),e.register(new nv),e.register(new dv),e.register(new hv),e.register(new Dv),e.register(new Ov),e.register(new $h),e.register(new Av),e.register(new Iv),e.register(new Uv),e.register(new Zg),e.register(new Qg),e.register(new Gv),e.register(new Kv),e.register(new qv),e.register(new Xv),e.register(new ey),e.register(new iy),e.register(new Ky),e.register(new dy),e.register(new fy),e.register(new vy),e.register(new xy),e.register(new wy),e.register(new Py),e.register(new Fy),e.register(new Iy),e.register(new Ly),e.register(new eb),e.register(new tb),e.register(new nb),e.register(new rb),e.register(new ob),e.register(new sb),e.register(new wb),e.register(new Ob),e.register(new Tb),e.register(new Eb),e.register(new Db),e.register(new kb),e.register(new T_),e.register(new E_),e.register(new D_),e.register(new O_),e.register(new k_),e.register(new Jv),e.register(new Yv),e.register(new Nb),e.register(new Pb),e.register(new Bb),e.register(new Vb),e.register(new Hb)}function Z(e,t){let{chartRect:n}=t;return e>=n.y&&e<=n.y+n.height}function Wb(e,t){let{chartRect:n}=t;return Math.min(Math.max(e,n.y),n.y+n.height)}function Gb(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 Kb(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 qb=/\{(side|qty|closedQty|openQty|entry|price|pnl|pnlPct|pnlSign)\}/g;function Jb(e,n){return e.replace(qb,(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 Yb(e,n,r){let i=10**n,a=Math.round(e*i)/i||0;return`${a>0?`+`:``}${(0,t.formatPrice)(a,n,r)}`}var Xb=2,Zb=2,Qb=2;function $b(e,n,r){if(r!==void 0)return r;let i=Math.abs(e),a=Math.abs(n),o=Math.round(i*10**Xb)>0;if(!(i>0)||!Number.isFinite(i)||o||!(a>0&&a<1))return Xb;let s=(0,t.smallValueDecimals)(i,Zb);return s<=(0,t.smallValueDecimals)(a)+Qb?s:Xb}function ex(e,t,n,r){return(r-t)*n*(e===`buy`?1:-1)}function tx(e,t){return typeof e==`function`?e(t):Jb(e??`{side} {qty} | P&L: {pnlSign}{pnl}`,t)}function nx(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 rx=24,ix=1.75,ax=[2,2.5],ox=new Map,sx=e=>{let t=ox.get(e);return t||(t=new Path2D(e),ox.set(e,t)),t};function cx(e,n,r,i,a,o){if(!(typeof Path2D>`u`)){if(e.save(),e.translate(Math.round(r),Math.round(i)),e.scale(a/rx,a/rx),e.strokeStyle=o,e.fillStyle=o,e.lineWidth=Math.max(ix,rx/a),e.lineCap=`round`,e.lineJoin=`round`,e.setLineDash([]),n.soft){let r=e.globalAlpha;e.globalAlpha=r*t.ICON_SOFT_OPACITY,e.fill(sx(n.soft)),e.globalAlpha=r}for(let t of n.fills??[])e.fill(sx(t));n.d&&e.stroke(sx(n.d)),n.dash&&(e.setLineDash(ax),e.stroke(sx(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 lx=5,ux=13,dx=22;function fx(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 px(e,t){return`${e.kind===`stamp`?`600 `:``}${t.font.sizeSmall}px ${t.font.family}`}function mx(e,t,n){return t.kind===`button`?21:(e.font=px(t,n),Math.ceil(e.measureText(t.text).width)+lx*2)}function hx(e){return Math.round(e)-10}function gx(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)<dx&&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 _x(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=>mx(e,t,r))),u=l.map(e=>e.reduce((e,t)=>e+t,0)),d=gx(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=hx(t[n].y);vx(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 vx(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`?(n.active&&e.fillRect(l,r,u,21),cx(e,n.icon,l+(u-ux)/2,r+(21-ux)/2,ux,n.active?ne(t.color):o.text),s.push({x:l,y:r,size:21,action:n.action})):(e.font=px(n,o),e.fillStyle=n.kind===`stamp`?ne(t.color):n.color??o.text,e.fillText(n.text,l+lx,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 yx(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 bx(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+7,Math.round(n))}var xx=[6,4],Sx=[2,3],Cx=[2,4],wx=.3;function Tx(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 Ex(e){return{buy:e.orderColors?.buy??`#1fa874`,sell:e.orderColors?.sell??`#e8505b`,profit:e.positionColors?.profit??`#1fa874`,loss:e.positionColors?.loss??`#e8505b`}}function Dx(e,t){return t?.orderId===e.id&&t.sourceType===`order`}function Ox(e,t){return Dx(e,t)?t.currentPrice:e.price}var kx=class{render(e,t,n,r,i,a,o=[]){this.renderLines(e,t,n,i,a),_x(e,this.tags(t,n,i,a),n,r,o)}renderLines(t,n,r,i,a){let o=Ex(i);for(let i of n){let n=e.k(Ox(i,a),r),s=i.side===`buy`?o.buy:o.sell;Z(n,r)&&Gb(t,r,n,s,xx),Dx(i,a)&&(t.globalAlpha=wx,Gb(t,r,e.k(a.startPrice,r),s,Cx),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);Z(i,r)&&Gb(t,r,i,a,Sx)}}}tags(n,r,i,a){let o=Ex(i),s=[];for(let c of n){let n=Ox(c,a),l=e.k(n,r);if(Z(l,r)){let e=[{kind:`stamp`,text:String(c.quantity)},{kind:`text`,text:Tx(c)}];i.lineButtons?.cancel!==!1&&!Dx(c,a)&&e.push({kind:`button`,icon:t.UI_ICONS.x,action:{type:`cancelOrder`,orderId:c.id}});let n=c.draggable===!1?void 0:{kind:`order`,orderId:c.id};s.push({y:l,color:c.side===`buy`?o.buy:o.sell,cells:e,grab:n})}for(let t of[`stopLoss`,`takeProfit`]){let a=c[t],l=a===void 0?NaN:e.k(a,r);if(a===void 0||!Z(l,r))continue;let u=ex(c.side,n,c.quantity,a);s.push({y:l,color:t===`stopLoss`?o.loss:o.profit,cells:[{kind:`stamp`,text:t===`takeProfit`?`TP`:typeof c.trailingStop==`number`&&c.trailingStop>0?`TSL`:`SL`},{kind:`text`,text:Yb(u,$b(u,n,i.pricePrecision),r.numberLocale),color:u>=0?o.profit:o.loss}]})}}return s}renderAxisBadges(e,t,n,r,i,a){for(let o of this.axisBadges(t,n,i,a))bx(e,o.y,o.text,o.color,n,r)}axisBadges(n,r,i,a){let o=Ex(i),s=[];for(let c of n){let n=Ox(c,a),l=e.k(n,r);Z(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}},Ax=[4,4],jx=[2,4],Mx=.3,Nx=.08,Px=.25,Fx=.04,Ix=[`stopLoss`,`takeProfit`];function Lx(e){return{profit:e.positionColors?.profit??`#1fa874`,loss:e.positionColors?.loss??`#e8505b`,entry:e.positionColors?.entry??`#4c8dff`}}function Rx(e,t){let{chartRect:n}=t;return e-21/2>=n.y&&e+21/2<=n.y+n.height}function zx(e){return e.quantity-Math.min(Math.max(e.closedQuantity??0,0),e.quantity)}function Bx(e,t,n){return n?.orderId===e.id&&n.sourceType===t?n.currentPrice:e[t]}var Vx=class{render(e,t,n,r,i,a,o=[],s=null){this.renderLines(e,t,n,r,a,s),_x(e,this.tags(t,n,r,a,s),r,i,o)}renderLines(t,n,r,i,a,o=null){let s=Lx(a);for(let c of n){let n=e.k(c.entryPrice,i);Gb(t,i,n,s.entry,[]),r!==null&&this.renderBand(t,c,n,e.k(r,i),r,i,a);for(let n of Ix){let r=Bx(c,n,o),a=r===void 0?NaN:e.k(r,i),l=n===`stopLoss`?s.loss:s.profit;Z(a,i)&&Gb(t,i,a,l,Ax);let u=c[n];u!==void 0&&r!==u&&(t.globalAlpha=Mx,Gb(t,i,e.k(u,i),l,jx),t.globalAlpha=1)}}}renderBand(e,t,n,r,i,a,o){let{chartRect:s}=a,c=Lx(o),l=Kb(t,i,o.pricePrecision??2),u=Math.min(n,r),d=Math.abs(r-n);e.fillStyle=nx(l.pnl,o.pnlThresholds,l.pnl>=0?c.profit:c.loss),e.globalAlpha=Nx,e.fillRect(s.x,u,s.width,d),l.closedQuantity>0&&t.quantity>0&&(e.fillStyle=c.entry,e.globalAlpha=Px,e.fillRect(s.x,u,Math.max(2,s.width*(l.closedQuantity/t.quantity)*Fx)+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 Ix){let s=this.stopTag(o,e,n,r,i,t);s&&a.push(s)}}return a}entryTag(n,r,i,a){let o=e.k(n.entryPrice,i);if(!Z(o,i))return null;let s=Lx(a),c=n.side===`buy`?`Long`:`Short`,l=[{kind:`stamp`,text:String(zx(n))}];if(r===null)l.push({kind:`text`,text:c});else{let e=Kb(n,r,a.pricePrecision??2,e=>(0,t.priceTagText)(e,i,a.pricePrecision),i.numberLocale);if(a.positionLabel!==void 0)l.push({kind:`text`,text:tx(a.positionLabel,e)});else{let t=nx(e.pnl,a.pnlThresholds,e.pnl>=0?s.profit:s.loss);l.push({kind:`text`,text:c},{kind:`text`,text:Yb(e.pnl,$b(e.pnl,r,a.pricePrecision),i.numberLocale),color:t})}}let u=a.lineButtons??{};return Rx(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,s=null){let c=Bx(n,r,o),l=c===void 0?NaN:e.k(c,i);if(c===void 0||!Z(l,i))return null;let u=Lx(a),d=ex(n.side,n.entryPrice,zx(n),c),f=typeof n.trailingStop==`number`&&n.trailingStop>0,p=[{kind:`stamp`,text:r===`takeProfit`?`TP`:f?`TSL`:`SL`},{kind:`text`,text:Yb(d,$b(d,n.entryPrice,a.pricePrecision),i.numberLocale),color:d>=0?u.profit:u.loss}],m=o?.orderId===n.id&&o.sourceType===r;if(r===`stopLoss`&&a.lineButtons?.trailStop!==!1&&Rx(l,i)&&!m){let e=n.side===`buy`,r=s===null?NaN:e?s-c:c-s,i=f?null:r>0?r:void 0;i!==void 0&&p.push({kind:`button`,icon:e?t.UI_ICONS.trendingUp:t.UI_ICONS.trendingDown,action:{type:`trailStop`,positionId:n.id,distance:i},active:f})}return a.lineButtons?.removeStops!==!1&&Rx(l,i)&&!m&&p.push({kind:`button`,icon:t.UI_ICONS.x,action:{type:`removeStop`,positionId:n.id,which:r}}),{y:l,color:r===`stopLoss`?u.loss:u.profit,cells:p,grab:{kind:`stop`,positionId:n.id,which:r}}}renderAxisBadges(e,t,n,r,i){for(let a of this.axisBadges(t,n,i))bx(e,a.y,a.text,a.color,n,r)}axisBadges(n,r,i,a=null){let o=Lx(i),s=[];for(let c of n){let n=[[Bx(c,`stopLoss`,a),o.loss],[Bx(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);Z(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.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)}}},Ux=[`stopLoss`,`takeProfit`],Wx=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 Z(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 Ux){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}},Gx=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 Kx(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 qx(e){let t=Math.abs(e.entry-e.stopLoss);return t===0?0:Math.abs(e.takeProfit-e.entry)/t}var Jx=6,Yx=.12,Xx=[6,3],Zx=class{draft=null;dragStart=null;dragging=null;defaults;constructor(e={}){this.defaults=e}start(e,t){this.draft=Kx(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=Jx){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=$x(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),_x(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}=Qx(r);t.save(),t.globalAlpha=Yx,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,Gb(t,n,o,r.text,Xx),Gb(t,n,c,l,[]),Gb(t,n,s,u,[]),t.restore()}tags(t,n){let r=this.draft;if(!r)return[];let{profit:i,loss:a}=Qx(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:`${qx(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=>Z(e.y,t))}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))bx(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}=Qx(r),c=[];for(let[l,u]of[[a.takeProfit,o],[a.stopLoss,s],[a.entry,r.text]]){let r=e.k(l,n);Z(r,n)&&c.push({y:r,text:(0,t.priceTagText)(l,n,i),color:u})}return c}};function Qx(e){return{profit:e.style?.trading.profit??e.candleUp,loss:e.style?.trading.loss??e.candleDown}}function $x(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 eS(e,t,n){return n==null?`limit`:e===`buy`?t<=n?`limit`:`stop`:t>=n?`limit`:`stop`}var tS=6,nS=[6,3],rS=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:eS(this.draft.side,this.draft.price,e),price:this.draft.price,quantity:this.draft.quantity}:null}hitTest(t,n,r=tS){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),_x(e,this.tags(t,n,r),t,n,[])}renderLines(t,n,r){let i=this.draft;i&&(t.save(),Gb(t,n,e.k(i.price,n),iS(i.side,r),nS),t.restore())}tags(t,n,r){let i=this.draft;if(!i)return[];let a=e.k(i.price,t);if(!Z(a,t))return[];let o=eS(i.side,i.price,r);return[{y:a,color:iS(i.side,n),grab:{kind:`draft`},cells:[{kind:`stamp`,text:String(i.quantity)},{kind:`text`,text:Tx({side:i.side,type:o})}]}]}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))bx(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 Z(o,n)?[{y:o,text:(0,t.priceTagText)(a.price,n,i),color:iS(a.side,r)}]:[]}};function iS(e,t){return e===`buy`?t.style?.trading.buy??t.candleUp:t.style?.trading.sell??t.candleDown}var aS=2;function oS(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 sS(e,t,n=aS){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 cS=5,lS=7,uS=2;function dS(e,n){let r=n.data;return r&&r.length>0?e/(0,t.barTimeUnit)(r):e}function fS(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(dS(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+uS:c-uS,d=l?u+lS:u-lS;t.beginPath(),t.moveTo(n,u),t.lineTo(n-cS,d),t.lineTo(n+cS,d),t.closePath();let f=l?o:s;!i.reason||i.reason===`order`?(t.fillStyle=f,t.fill()):(t.strokeStyle=f,t.stroke())}}function pS(e){for(let t in e)if(e[t]!==null)return!0;return!1}function mS(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];i!==null&&(n[t[r]]=i)}return n}function hS(e,t){let n=t.style?.trading;return!n||!pS(n)?e:{...e,orderColors:{...e.orderColors,...mS({buy:n.buy,sell:n.sell},{buy:`buy`,sell:`sell`})},positionColors:{...e.positionColors,...mS({profit:n.profit,loss:n.loss,entry:n.entry},{profit:`profit`,loss:`loss`,entry:`entry`})}}}function gS(e,t){let n=t.style?.markers;return!n||!pS(n)?e:{...e,...mS(n,{long:`longColor`,short:`shortColor`,neutral:`neutralColor`})}}function _S(e,t){let n=t.style?.tradeZones;return!n||!pS(n)?e:{...e,...mS(n,{profit:`profitColor`,loss:`lossColor`,active:`activeColor`})}}var vS=1e3,yS=class{orders=[];positions=[];depthData=null;currentPrice=null;config;orderRenderer=new kx;positionRenderer=new Vx;depthOverlay=new Hx;dragHandler;contextMenu=new Gx;bracket=new Zx;orderDraft=new rS;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 Wx(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(-(vS-1)),e],this.realisedPnl+=e.pnl??0,this.requestRender?.()}setFills(e){this.fills=e.slice(-vS),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&&sS(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;case`trailStop`:this.eventCallback?.(`positionModify`,{positionId:e.positionId,trailingStop:e.distance});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:qx(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(fx(this.tagBoxes,t.x,t.y)&&!sS(this.buttons,t))return!0;let i=i=>{if(i===void 0)return!1;let a=e.k(i,n);return Z(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=sS(this.buttons,e,n?.button),i=r?null:fx(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:Wb(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?sS(this.buttons,e):null;return n&&oS(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=hS(this.config,n);this.depthData&&this.depthOverlay.render(e,this.depthData,t,r),r.fillMarks!==!1&&fS(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),_x(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||bx(e,s,a.text,a.color,t,n)});return}for(let r of yx(this.axisBadges(t,n),t))bx(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=hS(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?yx(this.axisBadges(e,n),e).map(e=>e.at):[]}destroy(){this.contextMenu.destroy()}},bS=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)}};function xS(e,t){let n=e.trailingStop;if(n===void 0||!(n>0)||!Number.isFinite(t)||!(t>0))return e;let r=e.side===`buy`,i=r?t-n:t+n,a=e.stopLoss;return a!==void 0&&(r?i<=a:i>=a)?e:{...e,stopLoss:i}}var SS=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:wS(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=>{if(n.id!==e.positionId)return n;let r={...n,stopLoss:t(e.stopLoss,n.stopLoss),takeProfit:t(e.takeProfit,n.takeProfit)};return e.trailingStop===null?delete r.trailingStop:e.trailingStop!==void 0&&Number.isFinite(e.trailingStop)&&e.trailingStop>0&&(r.trailingStop=e.trailingStop),e.stopLoss===null&&delete r.trailingStop,typeof e.stopLoss==`number`?r:xS(r,this.markPrice)}),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:CS(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:CS(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}trailStops(){let e=!1;return this.positions=this.positions.map(t=>{let n=xS(t,this.markPrice);return n!==t&&(e=!0),n}),e}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)}this.trailStops()&&(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 CS(e){return e===`buy`?`sell`:`buy`}function wS(e){switch(e){case`stop`:return`STOP`;case`stopLimit`:return`STOP LIMIT`;default:return`LIMIT`}}var TS=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()}},ES=6e4,DS=e=>[e.open,e.high,e.low,e.close].every(Number.isFinite),OS=class extends TS{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(!DS(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)*ES}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)*ES}},kS=class extends TS{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))}},AS=20,jS=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??`dotted`,[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=(n.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2;e.fillStyle=o,A(e,c,a-AS/2,d,AS,r),this.tag={x:c,y:a-AS/2,width:d,height:AS,color:o},e.fillStyle=ne(o),e.textBaseline=`middle`,e.textAlign=`left`,e.fillText(u,c+7,a)}},MS=1e3,NS=10,PS=1440,FS=5e3,IS=2,LS=864e5,RS=6e4,zS=[`tick`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],BS=new WeakMap;function VS(e){if(e instanceof qS||!e.supportedTimeframes?.length)return e;let t=BS.get(e);return t||(t=new qS(e,e.supportedTimeframes),BS.set(e,t)),t}function HS(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 US(e,n){if((0,t.tickBarCount)(n)!==null)return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`;let r=e.supportedTimeframes;return!r?.length||HS(n,r)!==null}function WS(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)*RS: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 GS(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 KS(e,t){return GS(e,[...t.values()].sort((e,t)=>e.time-t.time))}var qS=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 zS)this.listen(e,t=>this.emit(e,t.data))}baseFor(e){let t=HS(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,MS));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=HS(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(),FS)});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)?HS(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,MS));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,MS));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:KS(this.bucket,this.parts)}correctClosed(e,t){let n=this.closedBuckets.get(e);n&&(n.set(t.time,t),this.emit(`bar`,{bar:KS(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)}},JS=1e3,YS=15e3,XS=[`tick`,`bar`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],ZS=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)}},QS=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 XS)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,JS)).filter(nC).sort((e,t)=>e.time-t.time),o=new ZS(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 ZS(n),after:-1/0};this.tick=r,this.stopTrades=this.inner.subscribeTrades(e.symbol,e=>{let t=e.filter(e=>nC(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`),YS)}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)}},$S=new WeakMap;function eC(e){if(e instanceof QS||!tC(e))return e;let t=$S.get(e);return t||(t=new QS(e),$S.set(e,t)),t}function tC(e){return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`}function nC(e){return Number.isFinite(e?.time)&&Number.isFinite(e?.price)&&Number.isFinite(e?.volume)}var rC=Symbol(`tradecanvas.sourceAdapter`),iC=new WeakSet;function aC(e){return iC.has(e)}var oC=(e,t)=>`${e}\u0000${t}`;function sC(e){return typeof e.getBars==`function`&&typeof e.subscribeBars==`function`}function cC(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 dC(e.feed);throw TypeError(`A stream needs an adapter or a feed`)}function lC(e,t,n){for(let r of n){let n=t[r];typeof n==`function`&&(e[r]=n.bind(t))}}var uC=[`resolveSymbol`,`searchSymbols`,`subscribeQuotes`,`fetchNews`,`fetchTrades`,`subscribeTrades`];function dC(e){let t=e[rC];if(t)return t;let n=new fC(e);return iC.add(n),n}var fC=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)})),lC(this,e,uC)}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=oC(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=oC(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=oC(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 pC(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)=>mC(e,t,n),[rC]:e};return lC(t,e,uC),t}function mC(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 hC(e){let t=cC(e),n=!aC(t),r=VS(t),i=r instanceof qS?r:null,a=eC(r);return a instanceof fC?new gC(a,i,n):new _C(a,i,n)}var gC=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}},_C=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))}},vC=2e4,yC=6e4,bC=3e4,xC=500,SC=864e5;function CC(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 wC(e,n,r){return(0,t.timeframeBucketStart)(e,n,{timeZone:r})===e&&(0,t.timeframeBucketStart)(e,n)!==e}var TC=class extends TS{config=null;source=null;aggregator=null;reconnector;priceLine=new jS;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 kS,this.wireReconnector()}async connect(e){this.disconnect();let n=hC(e);n.resampler?.renewZone(e.symbol),this.config={...t.DEFAULT_STREAM_CONFIG,...e},this.source=n,this.aggregator=new OS(e.timeframe),this.historyEnd=null,this.applyTickZone(),this.reconnector.removeAllListeners(),this.reconnector.stop(),this.reconnector=new kS(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%SC===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&&wC(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??xC);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`,CC(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<=vC)||(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>yC&&this.state===`connected`&&(this.emit(`error`,{message:`Heartbeat timeout`,code:`HEARTBEAT_TIMEOUT`}),this.source?.unsubscribe(),this.reconnector.schedule(()=>this.doConnect()))},bC)}stopHeartbeat(){this.heartbeatTimer&&=(clearInterval(this.heartbeatTimer),null)}dispose(){this.disconnect(),this.removeAllListeners()}},EC=class extends TS{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 DC(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=kC(e[1]),r=kC(e[2]),i=kC(e[3]),a=kC(e[4]),o=kC(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 OC(e){if(!AC(e))return null;let t=e.t;if(typeof t!=`number`||!Number.isFinite(t))return null;let n=kC(e.o),r=kC(e.h),i=kC(e.l),a=kC(e.c),o=kC(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 kC(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}function Q(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:void 0}function jC(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:Q(r.c),open:Q(r.o),high:Q(r.h),low:Q(r.l),volume:Q(r.v),time:Q(r.E)}):null}function MC(e){if(!e||typeof e!=`object`)return null;let n=e;return(0,t.readQuote)({symbol:n.symbol,last:Q(n.lastPrice),change:Q(n.priceChange),changePercent:Q(n.priceChangePercent),open:Q(n.openPrice),high:Q(n.highPrice),low:Q(n.lowPrice),prevClose:Q(n.prevClosePrice),volume:Q(n.volume),bid:Q(n.bidPrice),ask:Q(n.askPrice),time:Q(n.closeTime)})}function NC(e){if(!e||typeof e!=`object`)return null;let t=e,n=Q(t.T),r=Q(t.p),i=Q(t.q);return n!==void 0&&r!==void 0&&i!==void 0?{time:n,price:r,volume:i}:null}var PC=64,FC=(e,t)=>`${e}|${t}`,IC=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=FC(e,t);this.last.delete(a),this.last.set(a,{time:i,close:Number(r?.close??NaN)}),this.last.size>PC&&this.last.delete(this.last.keys().next().value)}lastBar(e,t){return this.last.get(FC(e,t))}},LC=class{newest=-1/0;servedClose=null;served=new IC;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}},RC={"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`},zC=1e3,BC=200,VC=[`USDT`,`USDC`,`FDUSD`,`BTC`,`ETH`,`BNB`,`EUR`,`TRY`,`BRL`,`JPY`];function HC(e){let t=e.currency?VC.indexOf(e.currency):-1;return t<0?0:40-t*3}function UC(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=UC(e);t&&n.push(t)}return n}var GC=class{name=`binance`;supportedTimeframes=Object.keys(RC);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,HC)}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(MC).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=jC(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(NC).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=NC(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,zC),`&endTime=${Math.floor(n)-1}`)}async fetchKlines(e,t,n,r){let i=RC[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=DC(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_${RC[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=OC(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)}}},KC=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+qC(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+qC(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+qC(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 qC(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t}var JC=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)}}},YC=class{name;supportedTimeframes;state=`disconnected`;listeners=new Map;config=null;timer=null;lastBarTime=0;served=new IC;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 $(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 XC(e){return typeof e==`object`&&!!e}var ZC={"1m":60,"5m":300,"15m":900,"1h":3600,"6h":21600,"1d":86400};function QC(e){return ZC[e]??3600}var $C=class extends YC{constructor(e={}){let t=e.restBase??`https://api.exchange.coinbase.com`;super({name:`coinbase`,supportedTimeframes:Object.keys(ZC),intervalMs:e.intervalMs??5e3,pollLimit:2,fetchBars:(e,n)=>ew(t,e,n)})}};async function ew(e,t,n){let r=`${e}/products/${t}/candles?granularity=${QC(n)}`,i=await fetch(r);if(!i.ok)throw Error(`Coinbase REST error: ${i.status}`);return tw(await i.json())}function tw(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=nw(n);e&&t.push(e)}return t.sort((e,t)=>e.time-t.time),t}function nw(e){if(!Array.isArray(e)||e.length<6)return null;let t=$(e[0]),n=$(e[1]),r=$(e[2]),i=$(e[3]),a=$(e[4]),o=$(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 rw={"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 iw(e){return rw[e]??`1`}var aw=class extends JC{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.${iw(e.timeframe)}.${e.symbol}`]}),unsubscribeMessage:e=>({op:`unsubscribe`,args:[`kline.${iw(e.timeframe)}.${e.symbol}`]}),supportedTimeframes:Object.keys(rw),parseMessage:ow,fetchHistory:(e,n,i)=>sw(t,r,e,n,i),fetchHistoryBefore:(e,n,i,a)=>sw(t,r,e,n,a,Math.floor(i)-1)})}};function ow(e){if(!XC(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(!XC(n))return null;let r=$(n.start),i=$(n.open),a=$(n.high),o=$(n.low),s=$(n.close),c=$(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 sw(e,t,n,r,i,a){let o=`${e}/v5/market/kline?category=${t}&symbol=${n}&interval=${iw(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 cw(await s.json())}function cw(e){if(!XC(e)||!XC(e.result))return[];let t=e.result.list;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=lw(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function lw(e){if(!Array.isArray(e)||e.length<6)return null;let t=$(e[0]),n=$(e[1]),r=$(e[2]),i=$(e[3]),a=$(e[4]),o=$(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 uw={"1m":1,"5m":5,"15m":15,"30m":30,"1h":60,"4h":240,"1d":1440,"1w":10080};function dw(e){return uw[e]??1}var fw=class extends JC{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:dw(e.timeframe)}}),unsubscribeMessage:e=>({method:`unsubscribe`,params:{channel:`ohlc`,symbol:[e.symbol],interval:dw(e.timeframe)}}),supportedTimeframes:Object.keys(uw),parseMessage:pw,fetchHistory:(e,n)=>mw(t,e,n)})}};function pw(e){if(!XC(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(!XC(n))return null;let r=$(n.open),i=$(n.high),a=$(n.low),o=$(n.close),s=$(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 mw(e,t,n){let r=dw(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 hw(await o.json())}function hw(e){if(!XC(e)||!XC(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=gw(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function gw(e){if(!Array.isArray(e)||e.length<7)return null;let t=$(e[0]),n=$(e[1]),r=$(e[2]),i=$(e[3]),a=$(e[4]),o=$(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 _w=200,vw={"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`},yw={"1m":`candle.1m`,"3m":`candle.3m`,"5m":`candle.5m`,"15m":`candle.15m`,"30m":`candle.30m`,"1h":`candle.60m`,"4h":`candle.240m`,"1d":`ticker`};function bw(e){return vw[e]??null}function xw(e){return yw[e]??null}var Sw=class extends JC{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??Cw,decode:Tw,subscribeMessage:e=>[{ticket:`tradecanvas`},{type:xw(e.timeframe)??`candle.1m`,codes:[e.symbol]},{format:`DEFAULT`}],supportedTimeframes:Object.keys(yw),parseMessage:Ew,fetchHistory:(e,n,r)=>kw(t,e,n,r),fetchHistoryBefore:(e,n,r,i)=>kw(t,e,n,i,r)})}};function Cw(e){let t=globalThis.WebSocket;if(!t)throw Error(`No WebSocket implementation available`);let n=new t(e);return n.binaryType=`arraybuffer`,n}var ww=null;function Tw(e){if(typeof e==`string`)return JSON.parse(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return JSON.parse((ww??=new TextDecoder).decode(e))}function Ew(e){if(!XC(e)||typeof e.type!=`string`)return null;if(e.type.startsWith(`candle.`)){let t=Ow(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=Ow(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 Dw(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=XC(n)?Ow(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 Ow(e,t,n){let r=typeof t==`string`?Date.parse(`${t}Z`):NaN,i=$(e.opening_price),a=$(e.high_price),o=$(e.low_price),s=$(e.trade_price),c=$(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 kw(e,t,n,r,i){let a=bw(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 Dw(await s.json())}var Aw=(e,t)=>`${e}\u0000${t}`,jw=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(Aw(e,t),r)}pushBar(e,t,n,r=!1){let i=Aw(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(Aw(e.symbol,e.timeframe))??[],{before:n}=e,r=n===void 0?t.length:Mw(t,n);return t.slice(Math.max(0,r-e.countBack),r).map(e=>({...e}))}subscribeBars(e,t){let n=Aw(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 Mw(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 Nw={visible:!0,showSymbol:!0,showOHLC:!0,showChange:!0,showVolume:!0,position:`top-left`,fontSize:12,fontFamily:null,ground:!0},Pw=class{config={...Nw};symbol=``;timeframe=``;hoverBar=null;hoverPrev=null;indicators=[];statusText=null;exchange=``;drawnHeight=null;drawnWidth=0;locale=`en-US`;inset=Iw;top=Fw;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:Hw(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 Vw(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:Hw(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=Rw,e.fillStyle=t.background,e.fillRect(n-zw,r-Bw,i+2*zw,a+this.lineGap),e.restore())}},{legendTop:Fw,legendInset:Iw,legendLineGap:Lw}=t.CHART_SPACING[t.DEFAULT_CHART_DENSITY],Rw=.72,zw=3,Bw=1;function Vw(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 Hw(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 Uw=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()}},Gw={solid:null,dashed:[6,4],dotted:[2,3]},Kw=6;function qw(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 Jw=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=Yw(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=Gw[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=Gw[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 qw(this.marks(e,t,n),Kw)}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 Yw(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 Xw=864e5;function Zw(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 Qw(e,t){let n=((e+t*6e4)%Xw+Xw)%Xw;return Math.floor(n/6e4)}function $w(e,t,n){return t===n?!0:t<n?e>=t&&e<n:e>=t||e<n}function eT(e,n){let r=Qw(e,n.timeZone?(0,t.zoneOffsetMinutes)(n.timeZone,e):n.tzOffsetMinutes??0);return n.windows&&n.windows.length>0?n.windows.some(e=>$w(r,e.startMinute,e.endMinute)):$w(r,n.startMinute,n.endMinute)}var tT={startMinute:570,endMinute:960,tzOffsetMinutes:-300,timeZone:`America/New_York`},nT=class{visible=!1;config={...tT};setVisible(e){this.visible=e}isVisible(){return this.visible}setConfig(e){this.config=Zw(this.config,e)}replaceConfig(e){this.config=Zw(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=!eT(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}},rT=[2,3],iT=16,aT=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(rT),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=oT(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=oT(d.kind,i),A(n,c,f-iT/2,l,iT,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+7,f)}n.restore()}};function oT(e,t){switch(e){case`bid`:return t.candleUp;case`ask`:return t.candleDown;default:return t.style?.highLow.color??t.textSecondary}}var sT=12,cT=3,lT=500,uT=2,dT=[`movesUp`,`movesDown`];function fT(e){return e.channel===`price`&&!e.drawingId&&!e.target&&!dT.includes(e.condition)}function pT(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 mT=[`crossing`,`crossingUp`,`crossingDown`];function hT(e,t,n){let r=e<0&&t>=0,i=e>0&&t<=0;return n===`crossingUp`?r:n===`crossingDown`?i:r||i}var gT=1,_T=2**31-1,vT=class extends TS{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=yT(t,i,o),c=`tc_alert_${gT++}`,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(!mT.includes(t))throw RangeError(`An alert on a drawing takes a crossing condition, not "${t}"`);let a=`tc_alert_${gT++}`,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(!fT(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()),_T);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)=>hT(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(dT.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=pT(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,pT(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(dT.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 pT(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){mT.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=bT(e),n=!t.target&&!dT.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(!fT(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-cT-sT;d>=a.x&&cx(n,t.UI_ICONS.bell,d,s-2-sT,sT,c)}}};function yT(e,t,n){let r={},i=dT.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 bT(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 xT=16,ST=3*xT,CT=1e3/30,wT=1e-9,TT=()=>typeof requestAnimationFrame==`function`&&!(typeof document<`u`&&document.hidden),ET={now:()=>typeof performance<`u`?performance.now():Date.now(),frame:e=>TT()?{raf:requestAnimationFrame(e)}:{timeout:setTimeout(e,xT)},cancel:e=>{let t=e;t.raf!==void 0&&cancelAnimationFrame(t.raf),t.timeout!==void 0&&clearTimeout(t.timeout)}},DT=class extends TS{data=[];cursor=-1;timer=null;frameHandle=null;run=0;state=`stopped`;config={speed:1,interval:500};paceMs=null;owedMs=0;constructor(e=ET){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<xT||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>=ST,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+wT)/e);try{s>0?(this.owedMs=Math.max(0,this.owedMs-s*e),this.advance(s),a(n)):n-i+xT/2>=CT&&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))}},OT=64,kT=3,AT=3;function jT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function MT(e){return Array.isArray(e)?e:[]}function NT(e,t){return typeof e==`string`?e:t}function PT(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function FT(e){if(!jT(e)||typeof e.id!=`string`||typeof e.type!=`string`||!Array.isArray(e.anchors)||e.anchors.length===0||e.anchors.length>IT||!jT(e.style))return null;let n=[];for(let t of e.anchors){if(!jT(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:jT(e.options)?e.options:void 0,intervals:ja(e.intervals)??void 0,group:BT(e.group),...tm(e.name)===void 0?{}:{name:tm(e.name)},...typeof e.paneId==`string`&&e.paneId.length>0&&e.paneId.length<=LT?{paneId:e.paneId}:{},meta:jT(e.meta)?e.meta:void 0}}var IT=5e3,LT=200,RT=64,zT=80;function BT(e){if(!(!jT(e)||typeof e.id!=`string`||typeof e.name!=`string`)&&!(e.id===``||e.id.length>RT))return{id:e.id,name:e.name.slice(0,zT)}}function VT(e){return!jT(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.type!=`string`||typeof e.price!=`number`||typeof e.quantity!=`number`?null:e}function HT(e){if(!jT(e))return;let n={},r=MT(e.colors).filter(e=>typeof e==`string`);r.length>0&&(n.colors=r);let i=MT(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 UT=[`crossingUp`,`crossingDown`,`crossing`,`greaterThan`,`lessThan`,`movesUp`,`movesDown`];function WT(e){if(!jT(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=UT.find(t=>t===e.condition)??`crossing`,i=bT(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:NT(e.channel,`price`),label:typeof e.label==`string`?e.label:void 0,...i,...e.expired===!0?{expired:!0}:{}}}function GT(e){return!jT(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.entryPrice!=`number`||typeof e.quantity!=`number`?null:e}var KT=4e3;function qT(e){if(!jT(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,OT)]=o)}return r.length>0&&console.warn(`Saved style overrides left out: ${[...new Set(r)].join(`, `)}`),n}function JT(e){if(!jT(e))return YT();typeof e.version==`number`&&e.version>AT&&console.warn(`Chart state from a newer version (${e.version}); loading what this version understands.`);let n=jT(e.viewport)?e.viewport:{},r=[];for(let n of MT(e.indicators))jT(n)&&(typeof n.id!=`string`||typeof n.instanceId!=`string`||jT(n.params)&&r.push({id:n.id,instanceId:n.instanceId,params:n.params,position:typeof n.position==`string`?n.position:void 0,style:HT(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:ja(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,KT):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 MT(e.drawings)){let e=FT(t);e&&i.push(e)}let a=[];for(let t of MT(e.orders)){let e=VT(t);e&&a.push(e)}let o=[];for(let t of MT(e.positions)){let e=GT(t);e&&o.push(e)}let s=[];for(let t of MT(e.alerts)){let e=WT(t);e&&s.push(e)}let c=qT(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:NT(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 YT(){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?AT: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 JT(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()})}},ZT=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}}},QT=[`Time`,`Open`,`High`,`Low`,`Close`,`Volume`];function $T(e,n){return new Date((0,t.normalizeBarTime)(e,n)).toISOString()}function eE(e){let t=/^[=+\-@\t\r]/.test(e)&&!/^-?\d/.test(e)?`'${e}`:e;return/[",\r\n]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}var tE=15,nE=0x38d7ea4c68000;function rE(e){return e==null||!Number.isFinite(e)?null:Number.isInteger(e)||Math.abs(e)>=nE?e:Number(e.toPrecision(tE))}var iE=e=>{let t=rE(e);return t===null?``:String(t)},aE=class{static toCSV(e,n=[]){let r=[...QT,...n.map(e=>eE(e.name))].join(`,`),i=(0,t.barTimeUnit)(e);return[r,...e.map((e,t)=>[$T(e.time,i),...[e.open,e.high,e.low,e.close,e.volume].map(iE),...n.map(e=>iE(e.values[t]))].join(`,`))].join(`
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 Kx(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 qx(e){let t=Math.abs(e.entry-e.stopLoss);return t===0?0:Math.abs(e.takeProfit-e.entry)/t}var Jx=6,Yx=.12,Xx=[6,3],Zx=class{draft=null;dragStart=null;dragging=null;defaults;constructor(e={}){this.defaults=e}start(e,t){this.draft=Kx(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=Jx){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=$x(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),_x(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}=Qx(r);t.save(),t.globalAlpha=Yx,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,Gb(t,n,o,r.text,Xx),Gb(t,n,c,l,[]),Gb(t,n,s,u,[]),t.restore()}tags(t,n){let r=this.draft;if(!r)return[];let{profit:i,loss:a}=Qx(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:`${qx(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=>Z(e.y,t))}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))bx(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}=Qx(r),c=[];for(let[l,u]of[[a.takeProfit,o],[a.stopLoss,s],[a.entry,r.text]]){let r=e.k(l,n);Z(r,n)&&c.push({y:r,text:(0,t.priceTagText)(l,n,i),color:u})}return c}};function Qx(e){return{profit:e.style?.trading.profit??e.candleUp,loss:e.style?.trading.loss??e.candleDown}}function $x(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 eS(e,t,n){return n==null?`limit`:e===`buy`?t<=n?`limit`:`stop`:t>=n?`limit`:`stop`}var tS=6,nS=[6,3],rS=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:eS(this.draft.side,this.draft.price,e),price:this.draft.price,quantity:this.draft.quantity}:null}hitTest(t,n,r=tS){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),_x(e,this.tags(t,n,r),t,n,[])}renderLines(t,n,r){let i=this.draft;i&&(t.save(),Gb(t,n,e.k(i.price,n),iS(i.side,r),nS),t.restore())}tags(t,n,r){let i=this.draft;if(!i)return[];let a=e.k(i.price,t);if(!Z(a,t))return[];let o=eS(i.side,i.price,r);return[{y:a,color:iS(i.side,n),grab:{kind:`draft`},cells:[{kind:`stamp`,text:String(i.quantity)},{kind:`text`,text:Tx({side:i.side,type:o})}]}]}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))bx(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 Z(o,n)?[{y:o,text:(0,t.priceTagText)(a.price,n,i),color:iS(a.side,r)}]:[]}};function iS(e,t){return e===`buy`?t.style?.trading.buy??t.candleUp:t.style?.trading.sell??t.candleDown}var aS=2;function oS(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 sS(e,t,n=aS){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 cS=5,lS=7,uS=2;function dS(e,n){let r=n.data;return r&&r.length>0?e/(0,t.barTimeUnit)(r):e}function fS(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(dS(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+uS:c-uS,d=l?u+lS:u-lS;t.beginPath(),t.moveTo(n,u),t.lineTo(n-cS,d),t.lineTo(n+cS,d),t.closePath();let f=l?o:s;!i.reason||i.reason===`order`?(t.fillStyle=f,t.fill()):(t.strokeStyle=f,t.stroke())}}function pS(e){for(let t in e)if(e[t]!==null)return!0;return!1}function mS(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];i!==null&&(n[t[r]]=i)}return n}function hS(e,t){let n=t.style?.trading;return!n||!pS(n)?e:{...e,orderColors:{...e.orderColors,...mS({buy:n.buy,sell:n.sell},{buy:`buy`,sell:`sell`})},positionColors:{...e.positionColors,...mS({profit:n.profit,loss:n.loss,entry:n.entry},{profit:`profit`,loss:`loss`,entry:`entry`})}}}function gS(e,t){let n=t.style?.markers;return!n||!pS(n)?e:{...e,...mS(n,{long:`longColor`,short:`shortColor`,neutral:`neutralColor`})}}function _S(e,t){let n=t.style?.tradeZones;return!n||!pS(n)?e:{...e,...mS(n,{profit:`profitColor`,loss:`lossColor`,active:`activeColor`})}}var vS=1e3,yS=class{orders=[];positions=[];depthData=null;currentPrice=null;config;orderRenderer=new kx;positionRenderer=new Vx;depthOverlay=new Hx;dragHandler;contextMenu=new Gx;bracket=new Zx;orderDraft=new rS;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 Wx(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(-(vS-1)),e],this.realisedPnl+=e.pnl??0,this.requestRender?.()}setFills(e){this.fills=e.slice(-vS),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&&sS(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;case`trailStop`:this.eventCallback?.(`positionModify`,{positionId:e.positionId,trailingStop:e.distance});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:qx(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(fx(this.tagBoxes,t.x,t.y)&&!sS(this.buttons,t))return!0;let i=i=>{if(i===void 0)return!1;let a=e.k(i,n);return Z(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=sS(this.buttons,e,n?.button),i=r?null:fx(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:Wb(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?sS(this.buttons,e):null;return n&&oS(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=hS(this.config,n);this.depthData&&this.depthOverlay.render(e,this.depthData,t,r),r.fillMarks!==!1&&fS(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),_x(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||bx(e,s,a.text,a.color,t,n)});return}for(let r of yx(this.axisBadges(t,n),t))bx(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=hS(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?yx(this.axisBadges(e,n),e).map(e=>e.at):[]}destroy(){this.contextMenu.destroy()}},bS=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)}};function xS(e,t){let n=e.trailingStop;if(n===void 0||!(n>0)||!Number.isFinite(t)||!(t>0))return e;let r=e.side===`buy`,i=r?t-n:t+n,a=e.stopLoss;return a!==void 0&&(r?i<=a:i>=a)?e:{...e,stopLoss:i}}var SS=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:wS(e.type),draggable:!0,stopLoss:e.stopLoss,takeProfit:e.takeProfit,timeInForce:e.timeInForce};return e.trailingStop!==void 0&&Number.isFinite(e.trailingStop)&&e.trailingStop>0&&(t.trailingStop=e.trailingStop),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=>{if(n.id!==e.positionId)return n;let r={...n,stopLoss:t(e.stopLoss,n.stopLoss),takeProfit:t(e.takeProfit,n.takeProfit)};return e.trailingStop===null?delete r.trailingStop:e.trailingStop!==void 0&&Number.isFinite(e.trailingStop)&&e.trailingStop>0&&(r.trailingStop=e.trailingStop),e.stopLoss===null&&delete r.trailingStop,typeof e.stopLoss==`number`?r:xS(r,this.markPrice)}),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:CS(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};e.trailingStop!==void 0&&(n.trailingStop=e.trailingStop),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:CS(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}trailStops(){let e=!1;return this.positions=this.positions.map(t=>{let n=xS(t,this.markPrice);return n!==t&&(e=!0),n}),e}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)}this.trailStops()&&(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 CS(e){return e===`buy`?`sell`:`buy`}function wS(e){switch(e){case`stop`:return`STOP`;case`stopLimit`:return`STOP LIMIT`;default:return`LIMIT`}}var TS=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()}},ES=6e4,DS=e=>[e.open,e.high,e.low,e.close].every(Number.isFinite),OS=class extends TS{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(!DS(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)*ES}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)*ES}},kS=class extends TS{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))}},AS=20,jS=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??`dotted`,[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=(n.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2;e.fillStyle=o,A(e,c,a-AS/2,d,AS,r),this.tag={x:c,y:a-AS/2,width:d,height:AS,color:o},e.fillStyle=ne(o),e.textBaseline=`middle`,e.textAlign=`left`,e.fillText(u,c+7,a)}},MS=1e3,NS=10,PS=1440,FS=5e3,IS=2,LS=864e5,RS=6e4,zS=[`tick`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],BS=new WeakMap;function VS(e){if(e instanceof qS||!e.supportedTimeframes?.length)return e;let t=BS.get(e);return t||(t=new qS(e,e.supportedTimeframes),BS.set(e,t)),t}function HS(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 US(e,n){if((0,t.tickBarCount)(n)!==null)return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`;let r=e.supportedTimeframes;return!r?.length||HS(n,r)!==null}function WS(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)*RS: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 GS(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 KS(e,t){return GS(e,[...t.values()].sort((e,t)=>e.time-t.time))}var qS=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 zS)this.listen(e,t=>this.emit(e,t.data))}baseFor(e){let t=HS(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,MS));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=HS(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(),FS)});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)?HS(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,MS));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,MS));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:KS(this.bucket,this.parts)}correctClosed(e,t){let n=this.closedBuckets.get(e);n&&(n.set(t.time,t),this.emit(`bar`,{bar:KS(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)}},JS=1e3,YS=15e3,XS=[`tick`,`bar`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],ZS=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)}},QS=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 XS)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,JS)).filter(nC).sort((e,t)=>e.time-t.time),o=new ZS(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 ZS(n),after:-1/0};this.tick=r,this.stopTrades=this.inner.subscribeTrades(e.symbol,e=>{let t=e.filter(e=>nC(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`),YS)}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)}},$S=new WeakMap;function eC(e){if(e instanceof QS||!tC(e))return e;let t=$S.get(e);return t||(t=new QS(e),$S.set(e,t)),t}function tC(e){return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`}function nC(e){return Number.isFinite(e?.time)&&Number.isFinite(e?.price)&&Number.isFinite(e?.volume)}var rC=Symbol(`tradecanvas.sourceAdapter`),iC=new WeakSet;function aC(e){return iC.has(e)}var oC=(e,t)=>`${e}\u0000${t}`;function sC(e){return typeof e.getBars==`function`&&typeof e.subscribeBars==`function`}function cC(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 dC(e.feed);throw TypeError(`A stream needs an adapter or a feed`)}function lC(e,t,n){for(let r of n){let n=t[r];typeof n==`function`&&(e[r]=n.bind(t))}}var uC=[`resolveSymbol`,`searchSymbols`,`subscribeQuotes`,`fetchNews`,`fetchTrades`,`subscribeTrades`];function dC(e){let t=e[rC];if(t)return t;let n=new fC(e);return iC.add(n),n}var fC=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)})),lC(this,e,uC)}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=oC(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=oC(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=oC(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 pC(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)=>mC(e,t,n),[rC]:e};return lC(t,e,uC),t}function mC(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 hC(e){let t=cC(e),n=!aC(t),r=VS(t),i=r instanceof qS?r:null,a=eC(r);return a instanceof fC?new gC(a,i,n):new _C(a,i,n)}var gC=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}},_C=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))}},vC=2e4,yC=6e4,bC=3e4,xC=500,SC=864e5;function CC(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 wC(e,n,r){return(0,t.timeframeBucketStart)(e,n,{timeZone:r})===e&&(0,t.timeframeBucketStart)(e,n)!==e}var TC=class extends TS{config=null;source=null;aggregator=null;reconnector;priceLine=new jS;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 kS,this.wireReconnector()}async connect(e){this.disconnect();let n=hC(e);n.resampler?.renewZone(e.symbol),this.config={...t.DEFAULT_STREAM_CONFIG,...e},this.source=n,this.aggregator=new OS(e.timeframe),this.historyEnd=null,this.applyTickZone(),this.reconnector.removeAllListeners(),this.reconnector.stop(),this.reconnector=new kS(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%SC===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&&wC(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??xC);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`,CC(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<=vC)||(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>yC&&this.state===`connected`&&(this.emit(`error`,{message:`Heartbeat timeout`,code:`HEARTBEAT_TIMEOUT`}),this.source?.unsubscribe(),this.reconnector.schedule(()=>this.doConnect()))},bC)}stopHeartbeat(){this.heartbeatTimer&&=(clearInterval(this.heartbeatTimer),null)}dispose(){this.disconnect(),this.removeAllListeners()}},EC=class extends TS{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 DC(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=kC(e[1]),r=kC(e[2]),i=kC(e[3]),a=kC(e[4]),o=kC(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 OC(e){if(!AC(e))return null;let t=e.t;if(typeof t!=`number`||!Number.isFinite(t))return null;let n=kC(e.o),r=kC(e.h),i=kC(e.l),a=kC(e.c),o=kC(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 kC(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}function Q(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:void 0}function jC(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:Q(r.c),open:Q(r.o),high:Q(r.h),low:Q(r.l),volume:Q(r.v),time:Q(r.E)}):null}function MC(e){if(!e||typeof e!=`object`)return null;let n=e;return(0,t.readQuote)({symbol:n.symbol,last:Q(n.lastPrice),change:Q(n.priceChange),changePercent:Q(n.priceChangePercent),open:Q(n.openPrice),high:Q(n.highPrice),low:Q(n.lowPrice),prevClose:Q(n.prevClosePrice),volume:Q(n.volume),bid:Q(n.bidPrice),ask:Q(n.askPrice),time:Q(n.closeTime)})}function NC(e){if(!e||typeof e!=`object`)return null;let t=e,n=Q(t.T),r=Q(t.p),i=Q(t.q);return n!==void 0&&r!==void 0&&i!==void 0?{time:n,price:r,volume:i}:null}var PC=64,FC=(e,t)=>`${e}|${t}`,IC=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=FC(e,t);this.last.delete(a),this.last.set(a,{time:i,close:Number(r?.close??NaN)}),this.last.size>PC&&this.last.delete(this.last.keys().next().value)}lastBar(e,t){return this.last.get(FC(e,t))}},LC=class{newest=-1/0;servedClose=null;served=new IC;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}},RC={"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`},zC=1e3,BC=200,VC=[`USDT`,`USDC`,`FDUSD`,`BTC`,`ETH`,`BNB`,`EUR`,`TRY`,`BRL`,`JPY`];function HC(e){let t=e.currency?VC.indexOf(e.currency):-1;return t<0?0:40-t*3}function UC(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=UC(e);t&&n.push(t)}return n}var GC=class{name=`binance`;supportedTimeframes=Object.keys(RC);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,HC)}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(MC).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=jC(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(NC).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=NC(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,zC),`&endTime=${Math.floor(n)-1}`)}async fetchKlines(e,t,n,r){let i=RC[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=DC(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_${RC[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=OC(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)}}},KC=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+qC(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+qC(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+qC(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 qC(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t}var JC=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)}}},YC=class{name;supportedTimeframes;state=`disconnected`;listeners=new Map;config=null;timer=null;lastBarTime=0;served=new IC;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 $(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 XC(e){return typeof e==`object`&&!!e}var ZC={"1m":60,"5m":300,"15m":900,"1h":3600,"6h":21600,"1d":86400};function QC(e){return ZC[e]??3600}var $C=class extends YC{constructor(e={}){let t=e.restBase??`https://api.exchange.coinbase.com`;super({name:`coinbase`,supportedTimeframes:Object.keys(ZC),intervalMs:e.intervalMs??5e3,pollLimit:2,fetchBars:(e,n)=>ew(t,e,n)})}};async function ew(e,t,n){let r=`${e}/products/${t}/candles?granularity=${QC(n)}`,i=await fetch(r);if(!i.ok)throw Error(`Coinbase REST error: ${i.status}`);return tw(await i.json())}function tw(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=nw(n);e&&t.push(e)}return t.sort((e,t)=>e.time-t.time),t}function nw(e){if(!Array.isArray(e)||e.length<6)return null;let t=$(e[0]),n=$(e[1]),r=$(e[2]),i=$(e[3]),a=$(e[4]),o=$(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 rw={"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 iw(e){return rw[e]??`1`}var aw=class extends JC{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.${iw(e.timeframe)}.${e.symbol}`]}),unsubscribeMessage:e=>({op:`unsubscribe`,args:[`kline.${iw(e.timeframe)}.${e.symbol}`]}),supportedTimeframes:Object.keys(rw),parseMessage:ow,fetchHistory:(e,n,i)=>sw(t,r,e,n,i),fetchHistoryBefore:(e,n,i,a)=>sw(t,r,e,n,a,Math.floor(i)-1)})}};function ow(e){if(!XC(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(!XC(n))return null;let r=$(n.start),i=$(n.open),a=$(n.high),o=$(n.low),s=$(n.close),c=$(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 sw(e,t,n,r,i,a){let o=`${e}/v5/market/kline?category=${t}&symbol=${n}&interval=${iw(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 cw(await s.json())}function cw(e){if(!XC(e)||!XC(e.result))return[];let t=e.result.list;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=lw(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function lw(e){if(!Array.isArray(e)||e.length<6)return null;let t=$(e[0]),n=$(e[1]),r=$(e[2]),i=$(e[3]),a=$(e[4]),o=$(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 uw={"1m":1,"5m":5,"15m":15,"30m":30,"1h":60,"4h":240,"1d":1440,"1w":10080};function dw(e){return uw[e]??1}var fw=class extends JC{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:dw(e.timeframe)}}),unsubscribeMessage:e=>({method:`unsubscribe`,params:{channel:`ohlc`,symbol:[e.symbol],interval:dw(e.timeframe)}}),supportedTimeframes:Object.keys(uw),parseMessage:pw,fetchHistory:(e,n)=>mw(t,e,n)})}};function pw(e){if(!XC(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(!XC(n))return null;let r=$(n.open),i=$(n.high),a=$(n.low),o=$(n.close),s=$(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 mw(e,t,n){let r=dw(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 hw(await o.json())}function hw(e){if(!XC(e)||!XC(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=gw(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function gw(e){if(!Array.isArray(e)||e.length<7)return null;let t=$(e[0]),n=$(e[1]),r=$(e[2]),i=$(e[3]),a=$(e[4]),o=$(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 _w=200,vw={"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`},yw={"1m":`candle.1m`,"3m":`candle.3m`,"5m":`candle.5m`,"15m":`candle.15m`,"30m":`candle.30m`,"1h":`candle.60m`,"4h":`candle.240m`,"1d":`ticker`};function bw(e){return vw[e]??null}function xw(e){return yw[e]??null}var Sw=class extends JC{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??Cw,decode:Tw,subscribeMessage:e=>[{ticket:`tradecanvas`},{type:xw(e.timeframe)??`candle.1m`,codes:[e.symbol]},{format:`DEFAULT`}],supportedTimeframes:Object.keys(yw),parseMessage:Ew,fetchHistory:(e,n,r)=>kw(t,e,n,r),fetchHistoryBefore:(e,n,r,i)=>kw(t,e,n,i,r)})}};function Cw(e){let t=globalThis.WebSocket;if(!t)throw Error(`No WebSocket implementation available`);let n=new t(e);return n.binaryType=`arraybuffer`,n}var ww=null;function Tw(e){if(typeof e==`string`)return JSON.parse(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return JSON.parse((ww??=new TextDecoder).decode(e))}function Ew(e){if(!XC(e)||typeof e.type!=`string`)return null;if(e.type.startsWith(`candle.`)){let t=Ow(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=Ow(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 Dw(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=XC(n)?Ow(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 Ow(e,t,n){let r=typeof t==`string`?Date.parse(`${t}Z`):NaN,i=$(e.opening_price),a=$(e.high_price),o=$(e.low_price),s=$(e.trade_price),c=$(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 kw(e,t,n,r,i){let a=bw(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 Dw(await s.json())}var Aw=(e,t)=>`${e}\u0000${t}`,jw=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(Aw(e,t),r)}pushBar(e,t,n,r=!1){let i=Aw(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(Aw(e.symbol,e.timeframe))??[],{before:n}=e,r=n===void 0?t.length:Mw(t,n);return t.slice(Math.max(0,r-e.countBack),r).map(e=>({...e}))}subscribeBars(e,t){let n=Aw(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 Mw(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 Nw={visible:!0,showSymbol:!0,showOHLC:!0,showChange:!0,showVolume:!0,position:`top-left`,fontSize:12,fontFamily:null,ground:!0},Pw=class{config={...Nw};symbol=``;timeframe=``;hoverBar=null;hoverPrev=null;indicators=[];statusText=null;exchange=``;drawnHeight=null;drawnWidth=0;locale=`en-US`;inset=Iw;top=Fw;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:Hw(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 Vw(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:Hw(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=Rw,e.fillStyle=t.background,e.fillRect(n-zw,r-Bw,i+2*zw,a+this.lineGap),e.restore())}},{legendTop:Fw,legendInset:Iw,legendLineGap:Lw}=t.CHART_SPACING[t.DEFAULT_CHART_DENSITY],Rw=.72,zw=3,Bw=1;function Vw(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 Hw(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 Uw=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()}},Gw={solid:null,dashed:[6,4],dotted:[2,3]},Kw=6;function qw(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 Jw=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=Yw(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=Gw[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=Gw[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 qw(this.marks(e,t,n),Kw)}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 Yw(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 Xw=864e5;function Zw(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 Qw(e,t){let n=((e+t*6e4)%Xw+Xw)%Xw;return Math.floor(n/6e4)}function $w(e,t,n){return t===n?!0:t<n?e>=t&&e<n:e>=t||e<n}function eT(e,n){let r=Qw(e,n.timeZone?(0,t.zoneOffsetMinutes)(n.timeZone,e):n.tzOffsetMinutes??0);return n.windows&&n.windows.length>0?n.windows.some(e=>$w(r,e.startMinute,e.endMinute)):$w(r,n.startMinute,n.endMinute)}var tT={startMinute:570,endMinute:960,tzOffsetMinutes:-300,timeZone:`America/New_York`},nT=class{visible=!1;config={...tT};setVisible(e){this.visible=e}isVisible(){return this.visible}setConfig(e){this.config=Zw(this.config,e)}replaceConfig(e){this.config=Zw(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=!eT(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}},rT=[2,3],iT=16,aT=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(rT),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=oT(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=oT(d.kind,i),A(n,c,f-iT/2,l,iT,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+7,f)}n.restore()}};function oT(e,t){switch(e){case`bid`:return t.candleUp;case`ask`:return t.candleDown;default:return t.style?.highLow.color??t.textSecondary}}var sT=12,cT=3,lT=500,uT=2,dT=[`movesUp`,`movesDown`];function fT(e){return e.channel===`price`&&!e.drawingId&&!e.target&&!dT.includes(e.condition)}function pT(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 mT=[`crossing`,`crossingUp`,`crossingDown`];function hT(e,t,n){let r=e<0&&t>=0,i=e>0&&t<=0;return n===`crossingUp`?r:n===`crossingDown`?i:r||i}var gT=1,_T=2**31-1,vT=class extends TS{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=yT(t,i,o),c=`tc_alert_${gT++}`,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(!mT.includes(t))throw RangeError(`An alert on a drawing takes a crossing condition, not "${t}"`);let a=`tc_alert_${gT++}`,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(!fT(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()),_T);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)=>hT(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(dT.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=pT(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,pT(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(dT.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 pT(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){mT.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=bT(e),n=!t.target&&!dT.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(!fT(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-cT-sT;d>=a.x&&cx(n,t.UI_ICONS.bell,d,s-2-sT,sT,c)}}};function yT(e,t,n){let r={},i=dT.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 bT(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 xT=16,ST=3*xT,CT=1e3/30,wT=1e-9,TT=()=>typeof requestAnimationFrame==`function`&&!(typeof document<`u`&&document.hidden),ET={now:()=>typeof performance<`u`?performance.now():Date.now(),frame:e=>TT()?{raf:requestAnimationFrame(e)}:{timeout:setTimeout(e,xT)},cancel:e=>{let t=e;t.raf!==void 0&&cancelAnimationFrame(t.raf),t.timeout!==void 0&&clearTimeout(t.timeout)}},DT=class extends TS{data=[];cursor=-1;timer=null;frameHandle=null;run=0;state=`stopped`;config={speed:1,interval:500};paceMs=null;owedMs=0;constructor(e=ET){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<xT||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>=ST,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+wT)/e);try{s>0?(this.owedMs=Math.max(0,this.owedMs-s*e),this.advance(s),a(n)):n-i+xT/2>=CT&&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))}},OT=64,kT=3,AT=3;function jT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function MT(e){return Array.isArray(e)?e:[]}function NT(e,t){return typeof e==`string`?e:t}function PT(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function FT(e){if(!jT(e)||typeof e.id!=`string`||typeof e.type!=`string`||!Array.isArray(e.anchors)||e.anchors.length===0||e.anchors.length>IT||!jT(e.style))return null;let n=[];for(let t of e.anchors){if(!jT(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:jT(e.options)?e.options:void 0,intervals:ja(e.intervals)??void 0,group:BT(e.group),...tm(e.name)===void 0?{}:{name:tm(e.name)},...typeof e.paneId==`string`&&e.paneId.length>0&&e.paneId.length<=LT?{paneId:e.paneId}:{},meta:jT(e.meta)?e.meta:void 0}}var IT=5e3,LT=200,RT=64,zT=80;function BT(e){if(!(!jT(e)||typeof e.id!=`string`||typeof e.name!=`string`)&&!(e.id===``||e.id.length>RT))return{id:e.id,name:e.name.slice(0,zT)}}function VT(e){return!jT(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.type!=`string`||typeof e.price!=`number`||typeof e.quantity!=`number`?null:e}function HT(e){if(!jT(e))return;let n={},r=MT(e.colors).filter(e=>typeof e==`string`);r.length>0&&(n.colors=r);let i=MT(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 UT=[`crossingUp`,`crossingDown`,`crossing`,`greaterThan`,`lessThan`,`movesUp`,`movesDown`];function WT(e){if(!jT(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=UT.find(t=>t===e.condition)??`crossing`,i=bT(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:NT(e.channel,`price`),label:typeof e.label==`string`?e.label:void 0,...i,...e.expired===!0?{expired:!0}:{}}}function GT(e){return!jT(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.entryPrice!=`number`||typeof e.quantity!=`number`?null:e}var KT=4e3;function qT(e){if(!jT(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,OT)]=o)}return r.length>0&&console.warn(`Saved style overrides left out: ${[...new Set(r)].join(`, `)}`),n}function JT(e){if(!jT(e))return YT();typeof e.version==`number`&&e.version>AT&&console.warn(`Chart state from a newer version (${e.version}); loading what this version understands.`);let n=jT(e.viewport)?e.viewport:{},r=[];for(let n of MT(e.indicators))jT(n)&&(typeof n.id!=`string`||typeof n.instanceId!=`string`||jT(n.params)&&r.push({id:n.id,instanceId:n.instanceId,params:n.params,position:typeof n.position==`string`?n.position:void 0,style:HT(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:ja(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,KT):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 MT(e.drawings)){let e=FT(t);e&&i.push(e)}let a=[];for(let t of MT(e.orders)){let e=VT(t);e&&a.push(e)}let o=[];for(let t of MT(e.positions)){let e=GT(t);e&&o.push(e)}let s=[];for(let t of MT(e.alerts)){let e=WT(t);e&&s.push(e)}let c=qT(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:NT(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 YT(){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?AT: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 JT(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()})}},ZT=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}}},QT=[`Time`,`Open`,`High`,`Low`,`Close`,`Volume`];function $T(e,n){return new Date((0,t.normalizeBarTime)(e,n)).toISOString()}function eE(e){let t=/^[=+\-@\t\r]/.test(e)&&!/^-?\d/.test(e)?`'${e}`:e;return/[",\r\n]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}var tE=15,nE=0x38d7ea4c68000;function rE(e){return e==null||!Number.isFinite(e)?null:Number.isInteger(e)||Math.abs(e)>=nE?e:Number(e.toPrecision(tE))}var iE=e=>{let t=rE(e);return t===null?``:String(t)},aE=class{static toCSV(e,n=[]){let r=[...QT,...n.map(e=>eE(e.name))].join(`,`),i=(0,t.barTimeUnit)(e);return[r,...e.map((e,t)=>[$T(e.time,i),...[e.open,e.high,e.low,e.close,e.volume].map(iE),...n.map(e=>iE(e.values[t]))].join(`,`))].join(`
25
25
  `)}static toJSON(e,n=[]){let r=(0,t.barTimeUnit)(e);return JSON.stringify(e.map((e,t)=>{let i={time:$T(e.time,r),open:rE(e.open),high:rE(e.high),low:rE(e.low),close:rE(e.close),volume:rE(e.volume)};for(let e of n)i[e.name]=rE(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 oE(e,t,n=-1/0){return t===null?e:e.filter(e=>e.time>=n&&e.time<t)}function sE(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 cE=1,lE=3,uE=class extends TS{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_${cE++}`,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[...oE(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=oE(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+lE&&t.y>=d-lE&&t.y<=f+lE)return s}return null}render(t,n,r){let i=this.dataGetter?.(),a=oE(this.markers,this.revealUntil,this.revealFrom);if(!i||i.length===0||a.length===0)return;let{chartRect:o}=n,s=gS(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()}},dE=12,fE=2,pE=1,mE=class extends TS{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_${pE++}`,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[...sE(this.zones,this.revealUntil,this.revealFrom)]}render(e,t,n){let r=this.dataGetter?.(),i=sE(this.zones,this.revealUntil,this.revealFrom);if(!r||r.length===0||i.length===0)return;let{chartRect:a}=t,o=_S(this.style,n);e.save(),e.beginPath(),e.rect(a.x,a.y,a.width,a.height),e.clip();for(let a of i)this.renderZone(e,a,r,t,n,o);e.restore()}renderZone(n,r,i,a,o,s){let{chartRect:c}=a,l=e.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([])),cx(n,r.direction===`long`?t.UI_ICONS.trendingUp:t.UI_ICONS.trendingDown,p+4,h-3-dE,dE,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+dE+3,h-3),s.showPnl&&!y&&r.pnl!=null){let e=r.pnl>=0?`+`:``,i=e=>(0,t.formatPrice)(e,fE,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)}},hE=2,gE=4,_E=t.MAX_PRICE_DECIMALS,vE=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=yE(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=yE(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=EE(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(),CE(n,a,s,h),CE(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?SE(Math.abs(this.endTime-this.startTime)):null,S=[],C=y>0?`+`:y<0?`−`:``,w=Math.abs(y),T=(0,t.formatPrice)(Math.abs(b),hE,r.numberLocale??`en-US`);S.push(`${C}${bE(w,r)} (${C}${T}%)`),S.push(`${v} bars${x?` · `+x:``}`),n.save(),wE(n,o,c,S,h,i),n.restore()}};function yE(e,n){return e<0||e>=n.length?null:n[e].time*(0,t.barTimeUnit)(n)}function bE(e,n){return(0,t.priceTagText)(e,n,n.pricePrecision??xE(e))}function xE(e){return e>=1e3?2:e>=1?4:e<=0?gE-1:Math.min(_E,gE-1-Math.floor(Math.log10(e)))}function SE(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 CE(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 wE(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,TE(e,l,u,s,c,6),e.fill(),e.globalAlpha=1,e.strokeStyle=i,e.lineWidth=1,TE(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 TE(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 EE(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 DE=6,OE=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()}},kE={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)},AE=class{animations=new Map;frameId=0;running=!1;animate(e,t){this.animations.set(e,{startTime:-1,duration:t.duration,easing:t.easing??kE.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 jE(e){return!e||e===`dark`?t.DARK_THEME:e===`light`?t.LIGHT_THEME:e}function ME(e,t){let n=jE(e),r=Object.fromEntries(Object.entries(t??{}).filter(([,e])=>e!==void 0));return{...n,font:{...n.font,...r}}}var NE=class{canvas;ctx;container;theme;width=0;height=0;dpr=1;frameId=null;sizer;themeGiven;fontGiven;constructor(e,t,n){this.container=e,this.themeGiven=t,this.fontGiven=n,this.theme=ME(t,n),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.themeGiven=e.theme),`font`in e&&(this.fontGiven=e.font),(`theme`in e||`font`in e)&&(this.theme=ME(this.themeGiven,this.fontGiven)),e.ariaLabel!==void 0&&this.setLabel(e.ariaLabel)}setLabel(e){this.canvas.setAttribute(`aria-label`,e)}setTheme(e){this.themeGiven=e,this.theme=ME(e,this.fontGiven),this.requestRender()}destroy(){this.frameId!==null&&cancelAnimationFrame(this.frameId),this.sizer.destroy(),this.canvas.width=0,this.canvas.height=0,this.canvas.remove()}},PE=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 FE(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 IE=.2,LE=.01,RE=24,zE=16,BE=`Spread`;function VE(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 HE(e,t,n,r){let i=VE(e.data.bids,`bid`),a=VE(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)*LE||1)*(1+IE),p=$d(0,Math.max(0,...i.map(e=>e.cumulativeVolume),...a.map(e=>e.cumulativeVolume))||1,5),m=e.volumeFormat??q(p,e.locale),h=12+Math.max(0,...p.ticks.map(e=>r(m(e),11)))+8,g=12+(c&&e.midPriceLine!==!1&&e.spreadLabel!==!1?zE: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 UE(e,t){return e.length===1?[e[0],{price:t,cumulativeVolume:e[0].cumulativeVolume}]:e}function WE(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 GE(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=J(a,n),e.measureText(t).width)),{plot:u,volume:d,priceMin:f,priceMax:p,bids:m,asks:h,mid:g,spread:_}=HE(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=wf([...m,...h].map(e=>e.price)),S=i.priceFormat??sf(i.locale,x),C=i.volumeFormat??K(i.locale);Tf(e,u,d,`vertical`,a,i.volumeFormat??q(d,i.locale)),e.save(),e.font=J(a,11),e.fillStyle=a.axisLabel,e.strokeStyle=a.grid,e.textAlign=`center`,e.textBaseline=`top`;let w=l(S(p),11)+RE,T=$d(f,p,Math.max(2,Math.floor(u.width/w))),E=i.priceFormat??q(T,i.locale);e.font=J(a,11);for(let t of T.ticks)t<f||t>p||(gf(e,y(t),u.y,y(t),v),e.fillText(E(t),Math.round(y(t)),v+6));e.restore();let D=(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()},O=i.bidColor??a.candleUp,k=i.askColor??a.candleDown;if(e.save(),e.beginPath(),e.rect(u.x,u.y,u.width,u.height),e.clip(),D(UE(m,f),O,i.bidFillColor??(0,t.withAlpha)(O,.25)),D(UE(h,p),k,i.askFillColor??(0,t.withAlpha)(k,.25)),e.restore(),g!==null&&i.midPriceLine!==!1&&(e.save(),e.strokeStyle=a.textSecondary,e.setLineDash([4,4]),gf(e,y(g),u.y,y(g),v),e.setLineDash([]),i.spreadLabel!==!1&&(e.font=J(a,11),e.fillStyle=a.textSecondary,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(`${typeof i.spreadLabel==`string`?i.spreadLabel:BE}: ${S(_)}`,Math.round(y(g)),12+zE/2-2)),e.restore()),!o||o.x<u.x||o.x>u.x+u.width)return;let A=f+(o.x-u.x)/u.width*(p-f);e.save(),e.strokeStyle=a.crosshair,e.setLineDash([4,4]),gf(e,o.x,u.y,o.x,v),e.restore();let j=WE(m,A,`bid`),ee=WE(h,A,`ask`),te=[{text:S((j??ee)?.price??A),bold:!0}];j&&te.push({text:C(j.cumulativeVolume),color:O}),ee&&te.push({text:C(ee.cumulativeVolume),color:k}),mf(e,te,o,{x:0,y:0,width:n,height:r},a)}var KE=.19,qE=864e5,JE=80,YE=3,XE=.05,ZE=`Benchmark`;function QE(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 $E(e,t,n){return of(n,e<qE?{...t>qE?{month:`short`,day:`numeric`}:{},hour:`2-digit`,minute:`2-digit`}:e>=28*qE?{month:`short`,...t>=365*qE?{year:`numeric`}:{},timeZone:`UTC`}:{month:`short`,day:`numeric`,timeZone:`UTC`})}function eD(e,t){let n=e<7*qE;return of(t,{month:`short`,day:`numeric`,...e>=365*qE?{year:`numeric`}:{},...n?{hour:`2-digit`,minute:`2-digit`}:{timeZone:`UTC`}})}function tD(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 nD(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)*XE||1:0,f=$d(s-d,c+d,5),p=e.valueFormat??q(f,e.locale),m=Math.max(0,...f.ticks.map(e=>r(p(e),11))),h=o&&o.length>=2?ff([{label:e.benchmarkLabel??ZE,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 rD(e,t,n,r,i,a){let{plot:o,timeMin:s,timeMax:c}=t,l=Cf(s,c,Math.max(1,Math.floor(o.width/JE))),u=i??$E(l.length>1?l[1]-l[0]:c-s,c-s,a);e.save(),e.font=J(r,11),e.fillStyle=r.axisLabel,e.strokeStyle=r.grid,e.textAlign=`center`,e.textBaseline=`top`;for(let t of l){let r=o.x+(t-s)/(c-s)*o.width;gf(e,r,o.y,r,o.y+o.height);let i=u(t),a=e.measureText(i).width/2;r-a>=0&&r+a<=n&&e.fillText(i,Math.round(r),o.y+o.height+6)}e.restore()}function iD(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=tD(i.data),l=i.benchmark&&tD(i.benchmark),u=s??((t,n=11)=>(e.font=J(a,n),e.measureText(t).width)),d=i.lineColor??a.lineColor,f=i.benchmarkColor??a.textSecondary,p=nD(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??eD(y,i.locale);Tf(e,m,h,`vertical`,a,i.valueFormat??q(h,i.locale)),rD(e,p,n,a,i.timeFormat,i.locale),v&&pf(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,KE),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,Hd)),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[QE(c,g+(o.x-m.x)/m.width*y)];if(!T)return;e.save(),e.strokeStyle=a.crosshair,e.setLineDash([4,4]),gf(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),YE,0,Math.PI*2),e.fill();let E=i.valueFormat??K(i.locale),D=[{text:C(T.time),bold:!0},{text:E(T.value),color:d}],O=l?QE(l,T.time):-1;l&&O>=0&&D.push({text:`${i.benchmarkLabel??ZE}: ${E(l[O].value)}`,color:f}),mf(e,D,o,{x:0,y:0,width:n,height:r},a)}function aD(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 oD(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 sD(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 cD(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){sD(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||oD(u,o)<=oD(s,o))s.push(e[l]),c.push(t[l]),l++;else{sD(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},cD(e.slice(l),t.slice(l),n,r,i);return}}s.length>0&&sD(s,c,n,a,r,i)}function lD(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 cD(s,c,{...t},n,l),l}var uD=2,dD=18;function fD(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=lD(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+uD/2,y:d.y+uD/2+f,width:Math.max(0,d.width-uD),height:Math.max(0,d.height-uD-f)};s.push({name:t,rect:{...d},header:f,value:l>0?u/l:0,count:o.length}),c.push(...lD(o,p,n))}return{groups:s,cells:c}}function pD(e){return Number.isFinite(e)?(e>=0?`+`:``)+e.toFixed(2)+`%`:``}function mD(e){return e.label}function hD(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 gD=`#FFFFFF`,_D=`#11151b`;function vD(e,n){let r=/^rgba\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)$/i.exec(e.trim());return Lf(r?(0,t.lerpColor)(n,`rgb(${r[1]},${r[2]},${r[3]})`,Number(r[4])):(0,t.lerpColor)(e,e,0))===_D?_D:gD}function yD(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 bD(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===gD;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 xD(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 SD(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=Nf([],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??pD,g=a.labelFormat??mD,_=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=hD(n.value,d);yD(e,r,i,a,s,f),e.fillStyle=c,e.fill(),bD(e,n,r,i,a,s,o,p,m,g,h,vD(c,o.background)),t.id===v&&(yD(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&&CD(e,s)):void 0;return wD(e,c,o,h,b),y&&s?mf(e,xD(y.cell,hD(y.cell.value,d),g,h),s,{x:0,y:0,width:t,height:n},o):b&&s&&mf(e,xD({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 CD(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 wD(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=Ef(s.name,m,e=>o(e),a);h&&e.fillText(h,t+5,u)}e.restore()}var TD=.7,ED=1,DD=.382,OD=Math.PI/4,kD=4;function AD(e){return e.type?e.type:e.value<0?`negative`:`positive`}function jD(e){let t=0;return e.map(e=>{let n=AD(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 MD(e,t,n,r){let i=e.data??[],a=jD(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=$d(o<0?o-c:0,s>0?s+c:0,5),u=e.valueFormat??q(l,e.locale),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*DD,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??TD)),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(ED,Math.abs(b(e.end)-b(e.start))),slotX:r,slotWidth:p}}),turned:g,labelRoom:_}}function ND(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 PD(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&&gf(e,n,s,r,s)}e.restore()}}function FD(e,t,n,r,i){e.save(),e.font=J(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+kD:n.y-kD-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-kD)))}e.restore()}function ID(e,t,n,r,i){let{plot:a,bars:o,turned:s,labelRoom:c}=t;e.save(),e.font=J(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=Ef(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 LD(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=J(i,n),e.measureText(t).width)),l=MD(r,t,n,c),{plot:u,scale:d,bars:f}=l,p=r.valueFormat??q(d,r.locale),m=r.valueFormat??K(r.locale),h={positive:r.positiveColor??i.candleUp,negative:r.negativeColor??i.candleDown,total:r.totalColor??i.lineColor,subtotal:r.subtotalColor??i.textSecondary};Tf(e,u,d,`vertical`,i,p),PD(e,l,r.connectorColor??i.textSecondary,r.connectorStyle??`dashed`);let g=hf(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);gf(e,u.x,_,u.x+u.width,_),r.showValues!==!1&&FD(e,l,i,m,r.showDelta!==!1),ID(e,l,i,r.labelFormat??(e=>e),c);let v=a?ND(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]),gf(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]}),mf(e,c,a,{x:0,y:0,width:t,height:n},i)}return{hitBar:v>=0?v:null}}var RD=Math.PI/180,zD=150,BD=240,VD=90,HD=.14,UD=1.6*RD,WD=.22,GD=8,KD=18,qD=16,JD=6.5,YD=20,XD=5,ZD=28;function QD(e,t,n){return e<t?t:e>n?n:e}function $D(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 eO(e){let t=Number.isFinite(e.startAngle)?e.startAngle:zD,n=(Number.isFinite(e.endAngle)?e.endAngle:t+BD)-t;return n<=0&&(n=(n%360+360)%360||360),n=QD(n,VD,360),{start:(t%360+360)%360*RD,sweep:n*RD}}function tO(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 nO(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*JD+12:0}function rO(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}=eO(n),s=a,c=a+o,l=QD(n.thickness??HD,.04,.5),u=tO(s,c),d=Math.max(u.maxY,.18),f=nO(n),p=f>0?qD:0,m=Math.max(1,e-2*GD-2*f),h=Math.max(1,t-2*GD-KD-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+KD+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-GD,E);return{cx:b,cy:x,radius:_,thickness:v,startAngle:s,endAngle:c,min:r,max:i,valueY:w,valueSize:C,textBottom:D}}function iO(e,t){let n=Number.isFinite(e)?QD((e-t.min)/(t.max-t.min),0,1):0;return t.startAngle+(t.endAngle-t.startAngle)*n}function aO(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 oO(e,t,n){let r=(t??[]).map(t=>({a0:iO(t.from,e),a1:iO(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 sO(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 cO(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 lO(e,t,n,r,i,a){let o=oO(t,n,i),s=o.some(e=>!e.track);o.forEach((n,i)=>{let a=i>0&&!n.track&&!o[i-1].track?UD/2:0,s=i<o.length-1&&!n.track&&!o[i+1].track?UD/2:0,c=n.a0+a,l=n.a1-s;if(n.track){sO(e,t,c,l,n.color);return}e.globalAlpha=WD,sO(e,t,c,l,n.color),e.globalAlpha=1,sO(e,t,c,Math.min(l,r),n.color)}),s||sO(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:WD],[d,f]=u(o[0],c),[p,m]=u(o[o.length-1],l);cO(e,t,t.startAngle,d,f,`start`),cO(e,t,t.endAngle,p,m,`end`)}function uO(e,t,n){let r=t.radius-t.thickness/2;if(r<ZD)return;let i=Math.max(4,t.thickness*.45);e.strokeStyle=n,e.lineCap=`butt`;for(let n=0;n<=YD;n++){let a=n%XD===0,o=t.startAngle+(t.endAngle-t.startAngle)*n/YD,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 dO(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 fO(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 pO(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 mO(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=pO(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();pO(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&&pO(e,r,`400`,f,s,c,l)>0&&(e.fillStyle=a.textSecondary,e.fillText(r,t.cx,n))}}function hO(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 gO(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=iO((QD(r.from,t.min,t.max)+QD(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 _O(e,t,n,r,i,a){if(t<=0||n<=0)return;let o=rO(t,n,r),s=Number.isFinite(a),c=s?QD(a,o.min,o.max):o.min,l=iO(c,o),u=s?aO(c,r.zones):void 0,d=r.pointer===`needle`,f=r.valueFormat??$D,p=u?.color??r.needleColor??i.lineColor;e.save(),e.fillStyle=i.background,e.fillRect(0,0,t,n),lO(e,o,r.zones,l,r.trackColor??i.grid,p),uO(e,o,i.textSecondary),s&&(d?fO(e,o,l,r.needleColor??i.text,i.background):dO(e,o,l,p,i.background)),r.showValue!==!1&&mO(e,o,s?f(c):`—`,r.label,u,i,d),hO(e,o,f,i),r.showZoneLabels===!0&&r.zones?.length&&gO(e,o,r.zones,i),e.restore()}var vO=12,yO=.72,bO=20,xO=.35;function SO(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 CO(e,t){let n=e.colorBySign;return n?n===!0?{positive:t.candleUp,negative:t.candleDown}:n:null}function wO(e,t,n,r,i){let a=e.orientation===`horizontal`,o=e.legend??e.series.length>1?ff(e.series.map((e,t)=>({label:e.name,color:uf(t,e.color)})),t-vO*2,i):null,s=vO+(o?o.height+6:0),[c,l]=SO(e),u=$d(c,l,a?Math.max(2,Math.floor(t/110)):5),d=e.valueFormat??q(u,e.locale),f=Math.max(0,...u.ticks.map(e=>i(d(e),11))),p;if(a){let r=vO+Math.min(t*xO,Math.max(0,...e.categories.map(e=>i(e,11))))+8;p={x:r,y:s,width:Math.max(1,t-r-vO-f/2),height:Math.max(1,n-s-vO-bO)}}else{let e=vO+f+8;p={x:e,y:s,width:Math.max(1,t-e-vO),height:Math.max(1,n-s-vO-bO)}}let m=Math.max(1,e.categories.length),h=a?p.y:p.x,g=(a?p.height:p.width)/m,_=g*yO,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=CO(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:uf(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:vO}}function TO(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 EO(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 DO(e,n,r,i,a,o,s=wO(i,n,r,a,df(e,a))){let c=df(e,a),l=i.valueFormat??K(i.locale),{plot:u,orientation:d}=s,f=d===`horizontal`;e.fillStyle=a.background,e.fillRect(0,0,n,r),s.legend&&pf(e,s.legend,vO,s.legendY,a),Tf(e,u,s.scale,f?`horizontal`:`vertical`,a,i.valueFormat??q(s.scale,i.locale));let p=o&&i.crosshair!==!1?EO(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&&kO(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});mf(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=J(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(Ef(t,a.x-vO-8,i),a.x-8,o)):(e.textAlign=`center`,e.textBaseline=`top`,e.fillText(Ef(t,n.band*s-4,i),o,a.y+a.height+6))}),e.restore()}function kO(e,t,n,r,i){e.save(),e.font=J(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 AO=12,jO=-Math.PI/2,MO=Math.PI*2,NO=5,PO=1.4,FO=18;function IO(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((t,n)=>({label:`${t.label} ${af(e.locale)(t.value/o)}`,color:uf(n,t.color)})),c=e.legend!==!1&&a.length>0,l=c&&t>=n*PO&&a.length*FO<=n-AO*2,u=l?Math.min(t*.4,Math.max(...s.map(e=>i(e.label,11)))+16):t-AO*2,d=c?ff(s,u,i,l):null,f=l?t-u-AO*3:t-AO*2,p=l?n-AO*2:n-AO*3-(d?.height??0),m=Math.max(0,Math.min(f,p)/2-NO),h=AO+f/2,g=AO+p/2,_=e.innerRadius,v=Math.min(.95,Math.max(0,_!==void 0&&Number.isFinite(_)?_:.6)),y=jO,b=a.map((e,t)=>{let n=e.value/o,r=y;return y+=n*MO,{label:e.label,value:e.value,share:n,start:r,end:y,color:uf(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-AO:AO,legendY:l?Math.max(AO,g-(d?.height??0)/2):AO*2+p}}function LO(e,t,n){let r=t-e.cx,i=n-e.cy,a=Math.hypot(r,i);if(a<e.inner||a>e.radius+NO)return null;let o=Math.atan2(i,r);for(;o<jO;)o+=MO;return e.slices.find(e=>o>=e.start&&o<e.end)??null}function RO(e,t,n,r,i,a,o=IO(r,t,n,i,df(e,i))){let s=df(e,i),c=r.valueFormat??K(r.locale);e.fillStyle=i.background,e.fillRect(0,0,t,n);let l=a&&r.crosshair!==!1?LO(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?NO: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&&zO(e,o,i,r.locale),BO(e,o,r,i,s),o.legend&&pf(e,o.legend,o.legendX,o.legendY,i),l&&a&&mf(e,[{text:l.label,bold:!0,color:l.color},{text:`${c(l.value)} · ${af(r.locale)(l.share)}`}],a,{x:0,y:0,width:t,height:n},i),o}function zO(e,t,n,r){let{cx:i,cy:a,radius:o,inner:s}=t,c=s>0?(o+s)/2:o*.62;e.save(),e.font=J(n,11,`600`),e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=`#fff`;for(let n of t.slices){let t=af(r)(n.share);if((n.end-n.start)*c<e.measureText(t).width+8||s>0&&o-s<15)continue;let l=(n.start+n.end)/2;e.fillText(t,i+Math.cos(l)*c,a+Math.sin(l)*c)}e.restore()}function BO(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=J(r,o,`600`),e.fillStyle=r.text,e.fillText(Ef(n.centerValue,a,i,o),t.cx,t.cy+(n.centerLabel?o*.35:0))}n.centerLabel&&(e.font=J(r,11),e.fillStyle=r.textSecondary,e.fillText(Ef(n.centerLabel,a,i),t.cx,t.cy-(n.centerValue?11*1.1:0))),e.restore()}var VO=12,HO=5,UO=3,WO=18,GO=20,KO=6;function qO(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+KO,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??q(m,e.locale),_=e.yFormat??q(h,e.locale),v=e.legend??e.series.length>1?ff(e.series.map((e,t)=>({label:e.name,color:uf(t,e.color)})),n-VO*2,a):null,y=VO+(v?v.height+6:0),b=Math.max(0,...h.ticks.map(e=>a(_(e),11))),x=VO+(e.yLabel?WO:0)+b+8,S=VO+GO+(e.xLabel?WO:0),C=a(g(m.max),11)/2,w={x,y,width:Math.max(1,n-x-VO-C),height:Math.max(1,r-y-S)},T=[];return e.series.forEach((e,n)=>{let r=uf(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(UO,d*Math.sqrt(t.size/u)):HO;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 JO(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+KO&&e<i&&(r=a,i=e)}return r}function YO(e,t,n,r,i,a,o=qO(r,t,n,i,df(e,i))){let{plot:s,xScale:c,yScale:l}=o,u=r.xFormat??q(c,r.locale),d=r.yFormat??q(l,r.locale);e.fillStyle=i.background,e.fillRect(0,0,t,n),o.legend&&pf(e,o.legend,VO,VO,i),Tf(e,s,l,`vertical`,i,d),Tf(e,s,c,`horizontal`,i,u),r.zeroLines!==!1&&XO(e,o,i),ZO(e,o,r,i);let f=a&&r.crosshair!==!1?JO(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=J(i,10),e.fillStyle=i.textSecondary,e.textAlign=`left`,e.textBaseline=`middle`;for(let t of o.points)t.label&&e.fillText(t.label,t.px+t.r+4,t.py);e.restore()}if(f&&a){let o=[{text:f.label??f.series,bold:!0,color:f.color}];f.label&&r.series.length>1&&o.push({text:f.series}),o.push({text:`${r.xLabel??`x`}: ${(r.xFormat??K(r.locale))(f.point.x)}`}),o.push({text:`${r.yLabel??`y`}: ${(r.yFormat??K(r.locale))(f.point.y)}`}),f.point.size!==void 0&&o.push({text:K(r.locale)(f.point.size)}),mf(e,o,a,{x:0,y:0,width:t,height:n},i)}return o}function XO(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 ZO(e,t,n,r){let{plot:i}=t;e.save(),e.font=J(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+GO+WO)),n.yLabel&&(e.translate(VO+11/2,i.y+i.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}var QO=1e-9,$O=1e3,ek=e=>{let t=Number(e.toPrecision(12));return t===0?0:t};function tk(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+QO),t=Math.max(e,Math.ceil(i/a-QO)-1)-e+1;if(t<=1e3){let r=Array.from({length:t},(t,n)=>({from:ek((e+n)*a),to:ek((e+n+1)*a),count:0}));for(let i of n)r[Math.min(t-1,Math.floor(i/a+QO)-e)].count++;return r}}let o=t.bins,s=typeof o==`number`&&Number.isFinite(o)&&o>=1?Math.min($O,Math.floor(o)):Math.min($O,Math.ceil(Math.log2(n.length))+1),c=(i-r)/s,l=Array.from({length:s},(e,t)=>({from:ek(r+t*c),to:ek(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+QO))].count++;return l}var nk=12,rk=20,ik=16;function ak(e,n,r){return n.colorBySign?(e.from+e.to)/2<0?r.candleDown:r.candleUp:n.color??t.TC_SERIES_COLORS[0]}function ok(e,t,n,r,i){let a=tk(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??q(l,e.locale),p=Math.max(0,...d.ticks.map(t=>i(q(d,e.locale)(t),11))),m=nk+(c.length>0?ik:0),h=nk+p+8,g=nk+i(f(l.max),11)/2,_={x:h,y:m,width:Math.max(1,t-h-g),height:Math.max(1,n-m-nk-rk)};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:ak(t,e,r)}}),total:a.reduce((e,t)=>e+t.count,0)}}function sk(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}function ck(e,n,r,i,a,o,s=ok(i,n,r,a,df(e,a))){let c=i.valueFormat??K(i.locale),{plot:l}=s;e.fillStyle=a.background,e.fillRect(0,0,n,r),Tf(e,l,s.yScale,`vertical`,a,q(s.yScale,i.locale)),Tf(e,l,s.xScale,`horizontal`,a,i.valueFormat??q(s.xScale,i.locale));let u=o&&i.crosshair!==!1?sk(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(lk(e,s,i,a,c),u&&o){let{bin:t}=u;mf(e,[{text:t.to>t.from?`${c(t.from)} – ${c(t.to)}`:c(t.from),bold:!0,color:u.color},{text:`${K(i.locale)(t.count)} · ${af(i.locale)(s.total>0?t.count/s.total:0)}`}],o,{x:0,y:0,width:n,height:r},a)}return s}function lk(e,t,n,r,i){let{plot:a}=t;e.save(),e.font=J(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 uk=864e5,dk=3,fk=12,pk=16,mk=10,hk=28,gk=6;function _k(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/uk)}function vk(e){return new Date(e*uk).toISOString().slice(0,10)}var yk=e=>((e+4)%7+7)%7;function bk(e,t){let n=e.from===void 0?null:_k(e.from),r=e.to===void 0?null:_k(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*uk).getUTCFullYear()-10+1;return[Math.max(n,Math.round(Date.UTC(i,0,1)/uk)),r]}function xk(e,t,n){let r=[],i=e;for(;i<=t;){let e=new Date(i*uk).getUTCFullYear(),a=Math.min(t,Math.round(Date.UTC(e,11,31)/uk)),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 Sk=new Map;function Ck(e){let t=e??``,n=Sk.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=Ck(void 0)}Sk.set(t,n)}return n}function wk(e,t,n,r,i){let a=new Map;for(let t of e.data){let e=_k(t.date);e!==null&&Number.isFinite(t.value)&&a.set(e,t)}let o=Ck(e.locale),s=e.dateFormat??(e=>o.long.format(new Date(`${e}T00:00:00Z`))),c=e.weekdays===5,l=e=>!c||yk(e)>=1&&yk(e)<=5,u=bk(e,a),d=t-fk*2,f=e.legend===!1?0:28,p=c?5:7,m=c?1:e.weekStart??1,h=e=>(yk(e)-m+7)%7,g=u?xk(u[0],u[1],h):[],_=e=>n-fk*2-f-e*pk-(e-1)*mk;for(;g.length>1&&_(g.length)/(g.length*p)<dk;)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=Nf(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)*uk))),w=fk+Math.max(...C.map(e=>i(e,10)),...x?S.map(e=>i(e,11)):[0])+gk,T=Math.max(...g.map(e=>e.weeks)),E=Math.min(hk,(t-w-fk)/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-fk-O)/2),A={...b,pitch:E},j=fk;for(let[e,n]of g.entries()){let r=j+pk;x&&A.years.push({label:S[e],x:k-gk,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:vk(e),day:f,color:f&&Number.isFinite(f.value)?Pf(f.value,y):null});let p=new Date(e*uk).getUTCMonth();if(p!==s){s=p;let n=o.month.format(new Date(e*uk)),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-gk,y:r+t*E+D/2})}j=r+p*E+mk}return f>0&&(A.bar={x:k,y:j-mk+8,width:Math.min(O,t-k-fk),height:f-8}),A}function Tk(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 Ek(e,n,r,i,a,o,s=wk(i,n,r,a,df(e,a))){let c=i.valueFormat??K(i.locale);e.fillStyle=a.background,e.fillRect(0,0,n,r);let l=o&&i.crosshair!==!1?Tk(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=J(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=J(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&&Rf(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:`–`});mf(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}var Dk=12,Ok=6,kk=72,Ak=Math.PI/4,jk=Math.sin(Ak);function Mk(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=Nk(e[r],e[i],r===i);n[r][i]=t,n[i][r]=t}return n}function Nk(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 Pk=e=>e.toFixed(2);function Fk(e,t,n,r){return!t||!e?!0:e===`lower`?r<=n:r>=n}function Ik(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)&&Fk(e.triangle,s,t,n)&&c.push(r)}let l=Nf(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=Dk+d+Ok,h=t-m-Dk,g=e=>Math.min(kk,h/o.length,(n-e-Dk-p)/a.length),_=Dk+11+Ok,v=g(_),y=f>v-4,b=f;if(y&&(b=Math.min(f,n*.33/jk),_=Dk+b*jk+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*jk/2)/jk))),u.grid={x:S,y:_,width:o.length*v,height:a.length*v},u.pitch=v;let C=e.valueFormat??Pk,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)||!Fk(e.triangle,s,t,n))continue;let c=Pf(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:Lf(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*jk:v)));for(let e=0;e<a.length;e+=E)u.rowLabels.push({text:Ef(a[e],d,i),index:e,x:S-Ok,y:_+e*v+x/2});for(let e=0;e<o.length;e+=D)u.columnLabels.push({text:Ef(o[e],b,i),index:e,x:S+e*v+x/2,y:_-Ok,rotated:y});return p>0&&(u.bar={x:S,y:_+a.length*v+8,width:Math.min(u.grid.width,t-S-Dk),height:p-8}),u}function Lk(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 Rk(e,t,n,r,i,a,o=Ik(r,t,n,i,df(e,i))){let s=r.valueFormat??Pk;e.fillStyle=i.background,e.fillRect(0,0,t,n);let c=a&&r.crosshair!==!1?Lk(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=J(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=J(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(Ak),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&&Rf(e,o.bar,o.scale,s,i),c&&a){let{cell:r}=c;mf(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 zk=12,Bk=18,Vk=20,Hk=10,Uk=.2,Wk=2e3,Gk=1e-9;function Kk(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 qk=(e,t)=>t-e>Gk*Math.max(Math.abs(e),Math.abs(t));function Jk(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=qk(t,n)?(o.volume-a.volume)/(n-t):0,c=qk(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 Yk(e,n,r,i,a){let o=Kk(e.data,e.period??25,Xk(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&&!qk(s,c)&&(c=s),o.length>0&&!qk(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??q(f,e.locale),m=e.volumeFormat??q(d,e.locale),h=zk+Math.max(0,...f.ticks.map(e=>a(p(e),11)))+8+(e.yLabel?Bk:0),g=zk+a(m(d.max),11)/2,_=zk,v=zk+Vk+(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:Uk+(1-Uk)*t/b,point:e})),phase:Jk(o),color:e.color??t.TC_SERIES_COLORS[0]}}function Xk(e){let t=e.points??60;return Number.isFinite(t)?Math.min(Wk,Math.max(2,Math.floor(t))):60}function Zk(e,t,n){let r=null,i=Hk*Hk;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}function Qk(e,n,r,i,a,o,s=Yk(i,n,r,a,df(e,a))){let{plot:c,points:l,color:u}=s,d=i.timeFormat??of(i.locale,{year:`numeric`,month:`short`,day:`numeric`}),f=i.priceFormat??K(i.locale),p=i.volumeFormat??K(i.locale);e.fillStyle=a.background,e.fillRect(0,0,n,r),Tf(e,c,s.yScale,`vertical`,a,i.priceFormat??q(s.yScale,i.locale)),Tf(e,c,s.xScale,`horizontal`,a,i.volumeFormat??q(s.xScale,i.locale)),$k(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?Zk(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(),mf(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 $k(e,t,n,r){e.save(),e.font=J(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+Vk+Bk)),n.yLabel&&(e.translate(zk+4,t.y+t.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}exports.ABCDPatternTool=Kv,exports.ADXIndicator=Es,exports.ALMAIndicator=Oc,exports.ATRIndicator=Ts,exports.AXIS_LABEL_HEIGHT=ee,exports.AcceleratorOscillatorIndicator=mc,exports.AccumulationDistributionIndicator=wc,exports.AccumulativeSwingIndexIndicator=yu,exports.AdvanceDeclineIndicator=xu,exports.AlertDragHandler=zd,exports.AlertManager=vT,exports.AlligatorIndicator=ds,exports.AnchoredNoteTool=Ly,exports.AnchoredTextTool=Iy,exports.AnchoredVWAPIndicator=ns,exports.AnchoredVWAPTool=nv,exports.Animator=AE,exports.ArcTool=sb,exports.AreaRenderer=$e,exports.AroonIndicator=js,exports.ArrowMarkTool=xy,exports.ArrowTool=K_,exports.AverageDayRangeIndicator=el,exports.AveragePriceIndicator=cl,exports.AwesomeOscillatorIndicator=bs,exports.AxisDragHandler=Rd,exports.BalanceOfPowerIndicator=$s,exports.BalloonTool=Fy,exports.BarCountdown=fe,exports.BarRenderer=et,exports.BarsPatternTool=Hb,exports.BaseFinanceChart=NE,exports.BaselineRenderer=rt,exports.BinanceAdapter=GC,exports.BollingerBandWidthIndicator=Vc,exports.BollingerBandsIndicator=zo,exports.BollingerPercentBIndicator=Bc,exports.BracketTool=Zx,exports.BrushTool=eb,exports.BybitAdapter=aw,exports.CANDLE_PATTERNS=Yl,exports.CCIIndicator=ks,exports.CMFIndicator=Ps,exports.COUNTDOWN_HEIGHT=de,exports.CROSSHAIR_CURSORS=Qf,exports.CalloutTool=fy,exports.CandlestickRenderer=le,exports.CanvasLayer=c,exports.ChaikinOscillatorIndicator=xs,exports.ChaikinVolatilityIndicator=sc,exports.ChandeKrollStopIndicator=Lc,exports.ChandeMomentumIndicator=tc,exports.ChandelierExitIndicator=us,exports.ChartLegend=Pw,exports.ChartStateManager=XT,exports.ChopZoneIndicator=Tu,exports.ChoppinessIndexIndicator=Ls,exports.CircleTool=Xv,exports.CoinbaseAdapter=$C,exports.CompareRenderer=Wr,exports.CompareSymbolIndicator=no,exports.CompareSymbolPaneIndicator=ro,exports.ConnorsRSIIndicator=Vs,exports.CoppockIndicator=Us,exports.CorrelationCoefficientIndicator=co,exports.CorrelationLogIndicator=lo,exports.CrossLineTool=Ov,exports.CrosshairHandler=Hf,exports.CrosshairTooltip=gp,exports.CurrentPriceLine=jS,exports.CurveTool=ob,exports.CyclicLinesTool=iy,exports.CypherPatternTool=Yv,exports.DEFAULT_LEGEND_CONFIG=Nw,exports.DEFAULT_MAX_PIXEL_RATIO=n,exports.DEFAULT_MAX_WEBGL_CHARTS=e.t,exports.DEFAULT_SESSION_HOURS=tT,exports.DEMAIndicator=Ec,exports.DENSE_BAR_WIDTH=e.u,exports.DOUBLE_TAP_MS=md,exports.DOUBLE_TAP_PX=hd,exports.DPRManager=o,exports.DataExporter=aE,exports.DateAndPriceRangeTool=ey,exports.DateRangeTool=F_,exports.DepthHeatmapBuffer=Qt,exports.DepthHeatmapRenderer=$t,exports.DepthOverlay=Hx,exports.DetrendedPriceOscillatorIndicator=Qs,exports.DisparityIndexIndicator=_c,exports.DonchianChannelIndicator=Qo,exports.DrawingBase=Y,exports.DrawingManager=Xm,exports.DrawingRenderer=ih,exports.EMAIndicator=Ro,exports.EaseOfMovementIndicator=ic,exports.Easing=kE,exports.ElderRayIndicator=qs,exports.ElliottCorrectionTool=E_,exports.ElliottDoubleComboTool=O_,exports.ElliottImpulseTool=T_,exports.ElliottTriangleTool=D_,exports.ElliottTripleComboTool=k_,exports.ElliottWaveTool=w_,exports.EllipseTool=Gg,exports.Emitter=TS,exports.EnvelopeIndicator=hs,exports.EquivolumeRenderer=ut,exports.EventBus=Op,exports.ExtendedLineTool=vg,exports.FibArcsTool=Tb,exports.FibChannelTool=Iv,exports.FibCirclesTool=wb,exports.FibExtensionTool=Hg,exports.FibRetracementTool=Bg,exports.FibSpeedResistanceFanTool=Uv,exports.FibSpiralTool=Ob,exports.FibTimeZonesTool=hv,exports.FibWedgeTool=Eb,exports.FinanceCrosshair=PE,exports.FisherTransformIndicator=Zs,exports.FlagTool=vy,exports.ForceIndexIndicator=Bs,exports.ForecastTool=Bb,exports.GROUP_HEADER=dD,exports.GannBoxTool=ev,exports.GannFanTool=Y_,exports.GannSquareTool=kb,exports.GridRenderer=e.o,exports.GuppyMMAIndicator=al,exports.HLCAreaRenderer=ft,exports.HammingMAIndicator=fu,exports.HeadAndShouldersTool=qv,exports.HiLoRenderer=_t,exports.HighlighterTool=tb,exports.HistoricalVolatilityIndicator=Uc,exports.HollowCandleRenderer=tt,exports.HorizontalLineTool=pg,exports.HorizontalRayTool=mg,exports.HullMAIndicator=as,exports.ICON_GLYPHS=Sy,exports.INDICATOR_CATEGORIES=Fu,exports.INDICATOR_WORKER_MIN_BARS=Do,exports.INTERVAL_LIMITS=Da,exports.INTERVAL_UNITS=Ea,exports.IchimokuIndicator=Jo,exports.IconTool=wy,exports.IndicatorBase=I,exports.IndicatorEngine=Io,exports.IndicatorValueMap=L,exports.IndicatorWorkerClient=qu,exports.IndicatorWorkerHost=Wu,exports.IndicatorWorkerPool=Yu,exports.InfoLineTool=Av,exports.InteractionManager=Td,exports.KAMAIndicator=kc,exports.KEPT_BUCKETS=IS,exports.KSTIndicator=Ws,exports.KagiRenderer=at,exports.KeltnerChannelIndicator=Zo,exports.KeyboardHandler=ap,exports.KlingerIndicator=Xs,exports.KrakenAdapter=fw,exports.LSMAIndicator=Ac,exports.LayerManager=l,exports.LineRenderer=Qe,exports.LineWithMarkersRenderer=mt,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=lT,exports.MAX_BASE_RATIO=PS,exports.MAX_BASE_REQUESTS=NS,exports.MFIIndicator=As,exports.MIN_ALERT_BARS=uT,exports.MIN_BAR_UNIT=Fe,exports.MIN_BAR_UNIT_LIMIT=Ie,exports.MTFMovingAverageIndicator=cs,exports.MajorityRuleIndicator=Su,exports.ManualFeed=jw,exports.MarketProfileRenderer=Lt,exports.MassIndexIndicator=ec,exports.McGinleyDynamicIndicator=jc,exports.MeasureOverlay=vE,exports.MeasureTool=I_,exports.MedianPriceIndicator=ll,exports.MockAdapter=KC,exports.ModifiedSchiffPitchforkTool=Qg,exports.MomentumIndicator=Hc,exports.NetVolumeIndicator=tl,exports.NoteTool=dy,exports.OBVIndicator=Ds,exports.OrderDraftTool=rS,exports.OrderRenderer=kx,exports.PRICE_AXIS_ADD_STRIP=Od,exports.PRICE_SCALE_MARGIN=ze,exports.PanHandler=Id,exports.PaneResizeHandler=Bd,exports.PaperExecutionAdapter=SS,exports.ParabolicSARIndicator=Yo,exports.ParallelChannelTool=xg,exports.PathTool=nb,exports.PercentagePriceOscillatorIndicator=fc,exports.PeriodLevelsRenderer=Ht,exports.PinnedTooltip=wp,exports.PitchfanTool=Db,exports.PitchforkTool=Xg,exports.PivotMarkersRenderer=Jt,exports.PivotPointsIndicator=es,exports.PointAndFigureRenderer=ct,exports.PollingAdapter=YC,exports.PolylineTool=rb,exports.PositionRenderer=Vx,exports.PrettyGoodOscillatorIndicator=yc,exports.PriceAxis=D,exports.PriceAxisAddButton=kd,exports.PriceLabelTool=Ky,exports.PriceLines=aT,exports.PriceOscillatorIndicator=Ou,exports.PriceRangeTool=M_,exports.PriceVolumeTrendIndicator=ac,exports.ProjectionTool=Vb,exports.QstickIndicator=vc,exports.RANGE_PRESETS=Ue,exports.ROCIndicator=Ms,exports.RSIIndicator=Ss,exports.RayTool=_g,exports.ReconnectManager=kS,exports.RectangleTool=Wg,exports.RegressionChannelTool=Eg,exports.RelativeMomentumIndexIndicator=gc,exports.RelativeVigorIndicator=cc,exports.RelativeVolatilityIndexIndicator=Xc,exports.RenderEngine=je,exports.RenderLoop=u,exports.RenkoRenderer=it,exports.ReplayController=EC,exports.ReplayManager=DT,exports.ResamplingAdapter=qS,exports.ReshapeMemo=Zr,exports.RiskRewardTool=Dv,exports.SELECTION_BOX_MIN_SIZE=DE,exports.SMAIndicator=Lo,exports.SMIErgodicIndicator=Du,exports.SMMAIndicator=Dc,exports.SNAPSHOT_VERSION=kT,exports.SYMBOL_INDICATOR_IDS=eo,exports.SYMBOL_ZONE_WAIT_MS=FS,exports.SchaffTrendCycleIndicator=Js,exports.SchiffPitchforkTool=Zg,exports.Screenshot=Uw,exports.SelectionBoxOverlay=OE,exports.SessionBreaks=Jw,exports.SessionShading=nT,exports.SessionVWAPIndicator=ls,exports.SignalMarkerManager=uE,exports.SignpostTool=Py,exports.SineLineTool=Pb,exports.SpreadIndicator=io,exports.StandardErrorBandsIndicator=nl,exports.StandardErrorIndicator=$c,exports.StdDevIndicator=bc,exports.StepLineRenderer=pt,exports.StochasticIndicator=ws,exports.StochasticMomentumIndexIndicator=Yc,exports.StochasticRSIIndicator=lc,exports.StreamManager=TC,exports.SupertrendIndicator=Xo,exports.SymbolSeriesStore=tn,exports.TEMAIndicator=ys,exports.TOUCH_REACH=pd,exports.TRIXIndicator=nc,exports.TSIIndicator=Ns,exports.TapTracker=gd,exports.TextAnnotationTool=W_,exports.ThreeDrivesTool=Jv,exports.TickAggregator=OS,exports.TickBarAdapter=QS,exports.TickBarBuilder=ZS,exports.TimeAxis=ld,exports.TimeCyclesTool=Nb,exports.TradeZoneManager=mE,exports.TradingContextMenu=Gx,exports.TradingDragHandler=Wx,exports.TradingManager=yS,exports.TradingRenderer=bS,exports.TrendAngleTool=$h,exports.TrendLineTool=fg,exports.TrendStrengthIndexIndicator=Zc,exports.TriangleTool=Kg,exports.TypicalPriceIndicator=ul,exports.UPBIT_MAX_CANDLES=_w,exports.UlcerIndexIndicator=Kc,exports.UltimateOscillatorIndicator=Rs,exports.UndoRedoManager=ZT,exports.UpbitAdapter=Sw,exports.VOLUME_HEIGHT_RATIO=vt,exports.VROCIndicator=Tc,exports.VWAPIndicator=Go,exports.VWMAIndicator=ps,exports.VerticalLineTool=gg,exports.Viewport=Ve,exports.VolatilityIndexIndicator=vu,exports.VolatilityOHLCIndicator=ju,exports.VolatilityZeroTrendIndicator=Mu,exports.VolumeCandleRenderer=lt,exports.VolumeDeltaIndicator=Fs,exports.VolumeOscillatorIndicator=Wc,exports.VolumeProfileIndicator=Cc,exports.VolumeProfileRangeTool=dv,exports.VolumeProfileRenderer=St,exports.VolumeRenderer=yt,exports.VortexIndicator=Is,exports.WMAIndicator=ms,exports.Watermark=Ww,exports.WebSocketAdapter=JC,exports.WilliamsADIndicator=oc,exports.WilliamsFractalsIndicator=Ic,exports.WilliamsRIndicator=Os,exports.XABCDPatternTool=Gv,exports.ZigZagIndicator=rs,exports.ZoomHandler=Ld,exports.adapterFromFeed=dC,exports.alignAxisTags=pe,exports.alignOutput=wa,exports.arcPoints=ab,exports.assignSessionLetters=Ft,exports.axisFormat=q,exports.axisTimes=si,exports.barIndexToTime=e.C,exports.barIndexToX=e.w,exports.barTimeStep=e.T,exports.barTimeStepMs=e.E,exports.barsToColumns=uo,exports.bracketRiskReward=qx,exports.canvasMeasure=df,exports.cappedPixelRatio=r,exports.claimGpuContext=e.n,exports.classifyPivots=Wt,exports.cleanIntervals=ja,exports.columnsToBars=fo,exports.columnsToOutput=So,exports.computeBarLayout=wO,exports.computeBracketDefaults=Kx,exports.computeCalendarLayout=wk,exports.computeCounterClockLayout=Yk,exports.computeDepthLayout=HE,exports.computeDonutLayout=IO,exports.computeEquityLayout=nD,exports.computeHistogramLayout=ok,exports.computeMarketProfile=Nt,exports.computeMatrixLayout=Ik,exports.computePeriodLevels=Vt,exports.computeScatterLayout=qO,exports.computeSessionProfiles=It,exports.computeWaterfallLayout=MD,exports.correlationMatrix=Mk,exports.counterClockPhase=Jk,exports.counterClockPoints=Kk,exports.createIndicatorWorker=Gu,exports.curvePoints=ib,exports.dayToIso=vk,exports.defaultFormat=cf,exports.describeInputs=Hu,exports.detectCandlePatterns=$l,exports.drawAxisValueLabels=ae,exports.drawIcon=cx,exports.drawingAxisSpan=Bm,exports.drawnKeys=Wi,exports.feedFromAdapter=pC,exports.fillTag=A,exports.financeTheme=ME,exports.findDominantSwing=ah,exports.findPivots=Gt,exports.forEachPixelColumn=e.d,exports.forecastOutcome=zb,exports.formatTooltipTime=pp,exports.getIntParam=H,exports.getNumberParam=V,exports.getVisibleData=He,exports.gpuContextsLeft=e.r,exports.hasHistogram=$i,exports.hasTrades=tC,exports.histogramBins=tk,exports.hitBar=TO,exports.hitCategory=EO,exports.hitDay=Tk,exports.hitHistogramBar=sk,exports.hitMatrixCell=Lk,exports.hitSlice=LO,exports.hitWaterfallBar=ND,exports.idleCssCursor=ip,exports.indicatorCategory=Lu,exports.indicatorValuePrecision=j,exports.indicatorWorkerPool=Xu,exports.inferOrderType=eS,exports.inputSource=xa,exports.isCrosshairCursor=$f,exports.isDataFeed=sC,exports.isDense=e.f,exports.isInWindow=$w,exports.isPriceLevelAlert=fT,exports.isRegularSession=eT,exports.isSeriesPalette=Na,exports.isUpTone=Gi,exports.isWorkerResponse=Uu,exports.labelTextColor=ne,exports.layoutAxisValueLabels=ie,exports.layoutGroupedTreemap=fD,exports.layoutLegend=ff,exports.layoutSquarifiedTreemap=lD,exports.layoutUniformGrid=aD,exports.lineSourceBars=Ca,exports.lineSpace=Xp,exports.loadWebGL=Ne,exports.loadWebGLRenderer=Pe,exports.lttbDownsample=Ye,exports.lttbVisibleIndices=Ze,exports.mergeSessionHours=Zw,exports.minuteOfDay=Qw,exports.nearestCounterClockPoint=Zk,exports.nearestPoint=JO,exports.niceScale=$d,exports.numberFormat=K,exports.outputToColumns=_o,exports.paneLogRange=Zi,exports.paneValueRange=Xi,exports.parseDay=_k,exports.pastTimeStep=e.D,exports.percentFormat=af,exports.plotColor=Yi,exports.plotLook=Ji,exports.plotShown=Ki,exports.pointAndFigureColumns=vi,exports.priceBucketRow=e.O,exports.priceScaleText=d,exports.priceSourceBars=Sa,exports.priceToY=e.k,exports.priceToYMapper=e.A,exports.rangePresetStart=Je,exports.readAlertOptions=bT,exports.readableText=Lf,exports.registerBuiltInDrawingTools=Ub,exports.registerBuiltInIndicators=Pu,exports.renderAxisValueLabels=oe,exports.renderBarChart=DO,exports.renderCalendar=Ek,exports.renderCounterClock=Qk,exports.renderDenseBars=e.p,exports.renderDepthChart=GE,exports.renderDonut=RO,exports.renderEquityCurve=iD,exports.renderGauge=_O,exports.renderHeatmap=SD,exports.renderHistogram=ck,exports.renderMatrix=Rk,exports.renderPlots=ea,exports.renderScatter=YO,exports.renderSparkline=FE,exports.renderWaterfall=LD,exports.resolveBarIndex=e.j,exports.resolveColorScale=Nf,exports.scaleColor=Pf,exports.servesTimeframe=US,exports.setMaxWebGLCharts=e.i,exports.shownCount=Xk,exports.shownOnInterval=Aa,exports.sourceParam=ba,exports.spreadLabels=te,exports.streamAdapterOf=cC,exports.timeToX=e.M,exports.timestampToBarIndex=e.N,exports.toHeikinAshi=Gr,exports.toKagi=mi,exports.toLineBreak=pi,exports.toPointAndFigure=_i,exports.toRangeBars=Li,exports.toRenko=ci,exports.tpoLetter=Pt,exports.waveLabel=b_,exports.whenGpuContextFree=e.a,exports.withResampling=VS,exports.withTickBars=eC,exports.xToBarIndex=e.P,exports.xToTime=e.F,exports.yToPrice=e.I;
26
26
  //# sourceMappingURL=index.cjs.map