@barchart/chart-lib 2.405.0 → 2.405.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- chart-lib/barchart.chart.js +1 -1
- chart-lib/package.json +1 -1
chart-lib/barchart.chart.js
CHANGED
|
@@ -39,4 +39,4 @@ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=
|
|
|
39
39
|
`);if(this.isNew){let{actualWidth:r,actualHeight:i}=this.getTextDimensions(n);t.points[0].update(e.price,e.time);let{x:a,y:o}=t.points[0].point;t.points[1].updateFromPoint({x:a+r,y:o+i}),t.drawn=!1}t.textLines=n,this.textArea.onblur=null,this.getChartParent().removeChild(this.textArea),t.requestRedraw(),this.isNew||t.requestRedraw(),Tj(t,!0,this.isNew?O.Created:O.TextChanged)}getTextDimensions(e){let t=globalThis.getComputedStyle(this.textArea).getPropertyValue(`font-size`),n=parseFloat(t)*e.length,r=0,i=this.anchor.axis.pane.presenter,a=i.view.mainContext;a.save();let{chart:{fontFamily:o}}=i.display;a.font=`${t} ${o}`;for(let t=0;t<e.length;t++){let n=a.measureText(e[t]).width;n>r&&(r=n)}return a.restore(),{actualWidth:r,actualHeight:n}}};function Dk(e){return $().config.tooltipMovement===e}function Ok(){return Dk(`Draggable`)}function kk(){return Dk(`Auto`)}var Ak=B.TOOLTIP_STD_LEGACY_CLASS,jk=B.TOOLTIP_STD_CLASS,Mk=B.TOOLTIP_BUBBLE_CLASS;function Nk(e,t){let n=e.filter(e=>!e.isHidden),r=e=>N(e.val)&&Number.isFinite(e.y),i=n.find(e=>e.isMain)||n[0],a=i?.values.find(e=>[`Close`,`Last`].includes(e.id)&&r(e))?.y??i?.values.find(r)?.y??t,o=n.map(e=>e.values.filter(e=>e.id!==`Change`&&e.y>0&&r(e)).map(e=>e.y)).flat(),[s,c]=o.length>0?[Math.min(...o),Math.max(...o)]:[a,a];return{plots:n,y:a,yMin:s,yMax:c,hasData:n.some(e=>e.values.some(r))}}var Pk=class{view;tooltipElem;leftSide;mode;isDrag=!1;layoutTop=0;canDrag;isToggling;constructor(e){this.view=e,this.tooltipElem=sa(e.el,`div`),ia(this.tooltipElem,{id:`${e.presenter.elementId}-global-tooltip`,class:`${jk} ${Ak}`}),this.leftSide=!0,ra(this.tooltipElem,{visibility:`hidden`,position:`absolute`,cursor:Ok()?`move`:`default`,zIndex:20,top:`${B.TOOLTIP_Y_OFFSET}px`,left:`${B.TOOLTIP_X_OFFSET}px`}),this.setMode(e.presenter.display.tooltip.mode),this.handleMouseMove=this.handleMouseMove.bind(this),this.startDrag=this.startDrag.bind(this),this.stopDrag=this.stopDrag.bind(this),this.view.el.addEventListener(`mousemove`,this.handleMouseMove),this.view.el.addEventListener(`mouseleave`,this.stopDrag),this.tooltipElem.addEventListener(`mousedown`,this.startDrag),this.tooltipElem.addEventListener(`mouseup`,this.stopDrag)}startDrag(){this.isDrag=!0}stopDrag(){this.isDrag=!1}setMode(e){if(this.mode!==e){if(this.mode=e,e===B.TOOLTIP_BUBBLE)this.canDrag=!1,this.tooltipElem.style.transition=`none`,this.tooltipElem.classList.remove(jk,Ak),this.tooltipElem.classList.add(Mk),ra(this.tooltipElem,{pointerEvents:`none`});else if(e===B.TOOLTIP_STD){this.canDrag=Ok(),this.tooltipElem.classList.remove(Mk),this.tooltipElem.classList.add(jk,Ak);let e=B.TOOLTIP_TOGGLE_SIDE_ANIM_MS;this.layoutTop=this.view.xAxis?.contentBounds?.y??0,ra(this.tooltipElem,{pointerEvents:`all`,top:`${this.layoutTop+B.TOOLTIP_Y_OFFSET}px`,left:`${B.TOOLTIP_X_OFFSET}px`,transition:kk()?`left ${e}ms ease-out`:null})}}}show(e,t){let n=this.tooltipElem;if(t){let{width:e,height:r,leftOffset:i,rightOffset:a}=this.view,o=n.getBoundingClientRect(),s=o.width/2,c=n.style,l=r*B.TOOLTIP_BUBBLE_OFFSET,u=t.yMin-o.height-l,d=t.x-s,f=t.yMax+l,p=f+o.height,m=this.view.xAxis?.contentBounds,h=m?.y??0,g=m?m.y+m.height:r,_=u<h?p<g?f:h:u,v=d,y=e-a;v<i?v=i:v+o.width>y&&(v=y-o.width),c.top=`${_}px`,c.left=`${v}px`}n.style.visibility===`hidden`&&(n.style.visibility=`visible`),la(n,e)}hide(){this.tooltipElem.style.visibility=`hidden`}remove(){this.view.el.removeEventListener(`mousemove`,this.handleMouseMove),this.view.el.removeEventListener(`mouseleave`,this.stopDrag),this.tooltipElem.removeEventListener(`mousedown`,this.startDrag),this.tooltipElem.removeEventListener(`mouseup`,this.stopDrag),ta(this.tooltipElem)}reposition(e,t){ra(this.tooltipElem,{left:`${e}px`,top:`${t}px`})}isAutoMove(){return this.mode===B.TOOLTIP_STD&&kk()}handleMouseMove(e){if(this.isDrag&&this.canDrag){let{movementX:t,movementY:n}=e,{top:r,left:i}=this.tooltipElem.style,a=parseInt(r)+n,o=parseInt(i)+t;this.reposition(o,a)}else if(this.isAutoMove()){let t=this.tooltipElem.getBoundingClientRect(),n=this.view.el.getBoundingClientRect(),r=e.pageX,i=B.TOOLTIP_TOGGLE_DISTANCE_TOLERANCE,a=n.width>t.width*2,o=r>t.x&&r<=t.right+i,s=r<t.x&&r>=t.x-i;a&&(o||s)&&this.toggleSide()}}repositionForLayout(){let e=this.view.xAxis?.contentBounds?.y??0;if(this.mode===B.TOOLTIP_STD&&e!==this.layoutTop){let t=parseFloat(this.tooltipElem.style.top),n=Number.isFinite(t)?t:B.TOOLTIP_Y_OFFSET;this.tooltipElem.style.top=`${n+e-this.layoutTop}px`}this.layoutTop=e}repositionAuto(){if(this.isAutoMove()){let e=this.view.presenter.mainPane.getBoundsWithoutScales(),t=parseFloat(this.tooltipElem.style.top),n=e.x+(this.leftSide?B.TOOLTIP_X_OFFSET:e.width-this.tooltipElem.offsetWidth-B.TOOLTIP_X_OFFSET);this.reposition(n,t)}}toggleSide(){this.isToggling||(this.isToggling=!0,setTimeout(()=>this.isToggling=!1,B.TOOLTIP_TOGGLE_SIDE_ANIM_MS),this.leftSide=!this.leftSide,this.repositionAuto())}};function Fk(e){e.showTooltip&&Ik(e,{time:B.ZERO_DATE,offset:B.OFFSCREEN_OFFSET,price:0,lastBarRefresh:void 0,justMain:void 0})}function Ik(e,{time:t,lastBarRefresh:n,justMain:r,offset:i,price:a}){let o=Iv(e,t,i,n,r,a),{mode:s,showMainPlot:c,hideSymbols:l,revealingClose:u}=e.display.tooltip,{includeTimestamp:d,showMainPlot:f,showPlotActions:p}=$().config.tooltipHeaders||{},m=P(f)?f:c,h=P(d)?d:!1,g=P(l)?l:!1,_=P(u)?u:!1,v=P(p)?p:!1,y=t.valueOf()===B.ZERO_DATE.valueOf();switch(s){case B.TOOLTIP_CARDS:r||Rk(e,o,m,!y,h&&!y,!1,g,_,v,e.hasLegend?e.view?.legend?.getLegendElem().clientHeight:0);break;case B.TOOLTIP_BUBBLE:if(!y){let t=Nk(o.panes.find(e=>{let{top:t,left:n,width:r,height:a}=e.bounds;return new Eo(n,t,r,a).contains(i)}).plots,i.y);if(t.hasData){let n=`<div class="bubble-box">${vv({...o,hideSymbols:g,revealingClose:_,plots:t.plots})}</div>`;e.view.tooltip.show(n,{x:i.x,y:t.y,yMin:t.yMin,yMax:t.yMax})}else e.view.tooltip.hide()}Rk(e,o,m,!1,!1,e.hasLegend,g,_,v);break;case B.TOOLTIP_STD:if(!y){let t=vv({...o,hideSymbols:g,revealingClose:_,plots:o.panes.map(e=>e.plots).flat()});e.view.tooltip.show(t)}Rk(e,o,m,!1,!1,e.hasLegend,g,_,v);break;case B.TOOLTIP_EXTERNAL:e.notifyHost(K.CH_TOOLTIPCHANGED,o);break;default:I(`Unknown tooltip mode requested: ${s}`,`warn`);break}}function Lk(e,t,n,r,i,a){ra(e,{position:`absolute`,display:`flex`,"flex-direction":t,"flex-wrap":`wrap`,left:`${n+B.CARDS_X_OFFSET}px`,top:`${i+B.CARDS_Y_OFFSET}px`,maxWidth:`${a-r-B.CARDS_X_OFFSET*2}px`})}function Rk(e,t,n=!1,r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=0){let u=e.view.el,d=yv(e,t,n,r,i,o,s,c);d.some(e=>!P(e.bounds))||d.forEach(({id:t,isMainPane:n,content:r,moveContent:i,bounds:{left:o,right:s,top:c,width:d}},f)=>{if(r!==``&&(!a||!n)){let i=aa(t,u,`div`);Lk(i,n&&hv(e)?`column`:`row`,o,s,c+l,d),oa(i,{"bcharts-card":!0,"bcharts-card-main":n,"bcharts-card-first":f===0}),i.innerHTML=r}let p=na(`#right-${t}`,u);P(p)||(p=document.createElement(`div`),p.id=`right-${t}`,u.appendChild(p),oa(p,`bcharts-card bcharts-card-move`)),ra(p,{position:`absolute`,display:`block`,right:`${s+B.CARDS_X_OFFSET}px`,top:`${c+l+B.CARDS_Y_OFFSET}px`}),p.innerHTML=i})}var zk=null;function Bk(){return zk===null&&(zk=$().config.hostingModel===ae[ae.Application]),zk}var Vk=class extends $O{ap;onLongPress;presenter;panY;snapToSupported=!1;warmUp=!0;preventDefault=!1;lastOffset;lastPanningExtremes;constructor(e,t){super(),this.ap=e,this.onLongPress=t,this.presenter=e.presenter,this.panY=e.axis.isCustomDomain}activated(){}deactivated(){this.cancelLongPress()}startPan(e){this.startLongPress(this.presenter,this.ap,e),this.lastOffset=e,this.lastPanningExtremes=this.ap.axis.yScale.domain();let t=this.ap.presenter;t.enableTooltip(!1),t.view.tooltip.hide(),t.view.drawCrosshair({ap:void 0})}onMouseMove(e){if(e.pinchZoom){this.presenter.resetActiveTool();return}let{point:t,view:n,offset:r}=e;if(t&&t.axis!==this.ap.axis)return;let{x:i,y:a}=r,o=i-this.lastOffset.x,s=Math.abs(o),c=this.lastOffset.y,l=a-c,u=Math.abs(l);s>=1&&this.cancelLongPress();let d=Bk();if(Ie()&&!d&&this.warmUp)return(s>7||u>7)&&(this.warmUp=!1,this.preventDefault=s>u),!1;if(this.preventDefault||!Ie()||d){if(n.xAxis.pan(o),this.panY&&t&&t.axis){u>=1&&this.cancelLongPress();let e=Hk(t.axis,c,a,this.lastPanningExtremes);this.lastPanningExtremes=e,t.axis.yScale.domain(e)}this.lastOffset=r,n.redraw(),t&&t.presenter.view.setCursor(ee.Grabbing)}return d||this.preventDefault}finished(){wj(this.presenter)}onMouseLeave(){this.finished()}onMouseUp(){this.finished()}onMouseDblClick({presenter:e,offset:t,originalEvent:n}){Ie()&&eA(e,t,n)}performLongPress(e,t,n){e.enableTooltip(!0),e.resetActiveTool(),this.onLongPress?this.onLongPress():e.activeTool.startTouchCrosshairMode(e,t,n)}};function Hk(e,t,n,r){let i=(n-t)/e.viewBox.height,[a,o]=r,s=i*(o-a);return[a+s,o+s]}var Uk=null;function Wk(e,t){let n=new DOMParser().parseFromString(e,`image/svg+xml`),r=n.querySelector(`svg`)?.getAttribute(`viewBox`),i=n.querySelector(`path`)?.getAttribute(`d`);if(N(r)&&N(i)){let e=r.split(` `).map(Number);e.length===4&&e.every(Number.isFinite)&&(Uk={path:new Path2D(i),width:e[2],height:e[3],rect:new Eo(0,0,0,0),logoClickable:t})}}var Gk=5,Kk=50;function qk(e,{x:t,y:n,height:r,width:i}){if(!N(Uk))return;let{path:a,width:o,height:s,rect:c}=Uk,l=i/8,u=Math.min(Math.max(Kk,l),o)/o;c.width=o*u,c.height=s*u,c.x=t+Gk,c.y=n+r-c.height-Gk,e.save();let d=getComputedStyle(e.canvas).getPropertyValue(`--widget-logo-fill-color`);e.fillStyle=d.length===0?`rgba(127, 127, 127, 0.6)`:d,e.translate(c.x,c.y),e.scale(u,u),e.fill(a),e.restore()}function Jk(){return N(Uk)&&Uk.logoClickable?Uk.rect:null}var Yk=class extends vk{constructor(e,t){super(e,t)}hitTest(e){if(!this.isVisible)return!1;let t=this.getRect();return t===null?!1:t.contains(e)}draw(e,t){return super.draw(e,t)?(Lo(e,this.getRect()),!0):!1}};function Xk(e,t){return e<t?[e,t]:[t,e]}var Zk={line:{width:1,color:`rgba(127, 127, 127, 0.3)`,dashStyle:`LongDash`},fill:{color:`rgba(127, 127, 127, 0.1)`}},Qk=class extends Ck{snapToSupported=!1;preventDefault=!1;axis;presenter;constructor(){super(lk(`Rectangle`,Yk,null,Zk),!1)}activated(){}deactivated(){P(this.axis,this.annotation)&&this.axis.deleteAnnotation(this.annotation,!1)}onMouseDown(e){let t=super.onMouseDown(e);if(t===!0){let{point:t}=e;this.axis=t.axis,this.presenter=t.presenter}return t}finish(){if(P(this.axis,this.presenter)){wj(this.presenter,{toolChange:O.Executed,annId:`ZoomIn`});let e=this.annotation.points,t=Xk(e[0].price,e[1].price),n=Xk(e[0].time,e[1].time),r=(e,t)=>Math.abs(t(e[0])-t(e[1])),i=r(n,e=>this.axis.toX(e)),a=r(t,e=>this.axis.toY(e)),o=this.presenter.view,s=B.MINIMUM_ZOOM_DIMENSION;if(i>s&&a>s){let e=o.xAxis.xScale;this.axis.isCustomDomain=!0,this.axis.yScale.domain(t),e.wasZoomed=!0,e.scaleBarToFitRange(n,!1),e.domain(n)}o.redraw()}}};function $k(e,t,n=e.isSelected){let r=sk(e);r.offset={x:t.x,y:t.y},r.wasSelected=n,r.canFlip=e.getFlipAnchorIndices()!==null;let i=e.axis.pane.presenter;r.candidates=i.defaultTool.findAnnotationHits(e.axis.toAnnotationPoint(t)).reverse().map(e=>({...sk(e),paneIndex:i.panes.indexOf(e.axis.pane),axisIndex:e.axis.pane.axes.indexOf(e.axis),position:e.axis.findIndex(e),canFlip:e.getFlipAnchorIndices()!==null})),i.annotationManipulation||i.clearSelection(),i.notifyHost(K.CH_ANNNEEDSCONTEXTMENU,r)}function eA(e,t,n){let r={offset:{x:t.x,y:t.y},chart:e.accessor,originalEvent:n};e.notifyHost(K.CH_CHTNEEDSCONTEXTMENU,r)}function tA(e,t,n,r=1,i=-1){let a=(n.y-t.y)/10,o=e.yScale.rangeWithPadding().reverse();return[o[0]+a*r,o[1]+a*i].map(t=>e.yScale.yToPrice(t))}function nA(e,t){return t.x===e.x||t.x===e.x+e.width||t.y===e.y||t.y===e.y+e.height}function rA(){let e=$().config.touchCrosshairTimeoutMillis;return P(e)&&Number.isFinite(e)?e:B.LONG_PRESS_TIMEOUT_MILLIS}var iA=class{resizingPanes=!1;snapToSupported=!1;touchCrosshairMode=!1;notifyZoomChanged;previousTouchTimestamp=null;resizingScale=!1;resizingScaleId=null;lastScaleResizingOffset=null;touchCrosshairTimeout=null;lastResizingOffset=null;splitter;prevZoomingOffset;prevPinchDistance=null;constructor(){this.stopResizingScale(),this.notifyZoomChanged=Ke(K.CH_ZOOMCHANGED,1e3)}startTouchCrosshairMode(e,t,n){this.touchCrosshairMode=!0,this.showCrosshairAndTooltips(e.view,t,n)}activated(){}deactivated(){}findAnnotationHits(e){let t=e.point;if(!t)return[];let n=e.presenter.selectedAnnotation,r=e=>e.hitTest(t)||e===n&&e.points.some(e=>e.hitTest(t));return e.axis.pane.axes.flatMap(e=>e.annotations.filter(e=>!e.computed&&e.isVisible&&r(e)))}findHit(e){if(!e.point)return[];if(e.axis.pane.axes.some(t=>t.plots.some(t=>t.hitTestCustomEvent(e.point))))return B.EVENT_PIN_HIT;let t=e.presenter.selectedAnnotation;if(t?.isVisible&&!t.computed&&t.axis.pane===e.axis.pane){let n=t.points.find(t=>t.hitTest(e.point));if(n)return[t,n];if(e.presenter.annotationManipulation&&t.hitTest(e.point))return[t,void 0]}return[Se(e.presenter.annotationManipulation?this.findAnnotationHits(e):e.axis.annotations.filter(t=>!t.computed&&t.isVisible&&t.hitTest(e.point))),void 0]}restoreSelection(e,t){e.clearSelection();let n=e.allAnnotations.find(e=>e.uid===t);n?.isVisible&&e.setSelection(n)}findPlotHits(e,t){let n=e.axes.map(e=>e.plots).flat().filter(e=>e.isVisible);if(n.length===1){let[t]=n;if(t.isStudy&&e.presenter.isHoverHighlightable(t))return[t]}let r=[];for(let n=e.axes.length-1;n>=0;n--){let i=e.axes[n].plots;for(let n=i.length-1;n>=0;n--){let a=i[n];e.presenter.isHoverHighlightable(a)&&a.isVisible&&a.hasHitTestableCurves&&a.hitTest(t)&&r.push(a)}}return r}stopResizingScale(){this.resizingScale=!1,this.resizingScaleId=null,this.lastScaleResizingOffset=null}resetVerticalAxis(e,t=!0){this.stopResizingScale(),e.isCustomDomain=!1,t&&e.setDomain()}resetHorizontalAxis(e,t=!0){e.view.xAxis.resetZoom(),t&&e.view.setPriceAxesDomains(),this.fireZoomChanged(e)}canVerticalZoom(e){return Qe(e.display.chart.zooming)[0]}canHorizontalZoom(e){return Qe(e.display.chart.zooming)[1]}canRectangleZoom(e){return this.canVerticalZoom(e)&&this.canHorizontalZoom(e)}fireZoomChanged(e){this.notifyZoomChanged({chart:e.accessor})}onMouseDblClick({priceAxis:e,offset:t,presenter:n,view:r}){let i=r.xAxis.contains(t),a=!1;if(P(e))this.resetVerticalAxis(e),a=!0;else if(i)this.resetHorizontalAxis(n),a=!0;else if(Ie()){let e=n.selectedAnnotation;e==null?eA(n,t):$k(e,t)}a&&r.redraw()}onMouseEnter(){this.previousTouchTimestamp=null}computePreviousTouchStartDuration(){if(!Ie())return null;let e=new Date().getTime(),t=P(this.previousTouchTimestamp)?e-this.previousTouchTimestamp:null;return this.previousTouchTimestamp=e,t}onMouseDown(e){let{point:t,button:n,splitter:r,offset:i,priceAxis:a,presenter:o,originalEvent:s}=e,c=window.navigator.platform.toLowerCase().startsWith(`mac`),l=c?D.Meta:D.Control,u=n===E.Right||c&&n===E.Left&&e.getModifier(D.Control);this.touchCrosshairMode&&P(this.touchCrosshairTimeout)&&(clearTimeout(this.touchCrosshairTimeout),this.touchCrosshairTimeout=null);let d=this.computePreviousTouchStartDuration();if(P(d)&&d<B.DOUBLE_CLICK_DURATION_MILLIS)return this.onMouseDblClick(e),!0;if(!u&&this.isLogoLink(i)&&o.notifyHost(K.CH_LOGOCLICKED,{chart:o.accessor}),P(t)&&o.allPlots.some(e=>e.tryHandleCustomEventClick(t.point)))return!0;if(P(r))return this.resizingPanes=!0,this.lastResizingOffset=i,this.splitter=r,o.enableTooltip(!1),!0;if(P(a))return this.canVerticalZoom(o)&&this.startAxisScaling(a,i),!0;if(t!=null){if(e.getModifier(l)&&this.canRectangleZoom(o))return o.activeTool=new Qk,o.activeTool.onMouseDown(e),!0;let[n,r]=this.findHit(t),a=o.annotationManipulation,c=o.selectedAnnotation?.uid,d=n!=null&&c===n.uid,f=()=>this.findAnnotationHits(t).length>1,p;if(a&&n!=null&&(p=()=>{!d&&f()&&this.restoreSelection(o,c),$k(n,i,d)}),a&&u&&n!=null&&!d&&f())return $k(n,i,!1),Ie();if(o.clearSelection(),n!=null&&o.setSelection(n),n==null||n?.locked)return u?(this.hideCrosshairAndTooltips(o.view),n==null?eA(o,i,s):n?.locked&&$k(n,i,d),!0):this.touchCrosshairMode?!0:(o.activeTool=new Vk(t,p),o.activeTool.startPan(i),Bk());let m=r!=null;if(u)return $k(n,i,d),Ie();{if(m&&!r.movable||!m&&!n.canMove(t.point))return!1;let e=m&&n.points.indexOf(r)!==-1,a=n.axis.toAnnotationPoint(i);return o.activeTool=e?new nk(n,r):new tk(n,a,i,p),Ie()}}else this.canHorizontalZoom(o)&&(this.prevZoomingOffset=i);return!1}onContextMenu(e){return!0}isLogoLink(e){let t=Jk();return P(t)&&t.contains(e)}onMouseMove(e){let{point:t,splitter:n,priceAxis:r,view:i,presenter:a,offset:o}=e;if(P(e.pinchZoom)&&e.pinchZoom&&P(e.pinchDistance))return P(this.prevPinchDistance)&&(e.delta=this.prevPinchDistance-e.pinchDistance,this.onWheel(e)),this.prevPinchDistance=e.pinchDistance,Ie();if(n!=null||this.resizingPanes)i.setCursor(ee.ResizeVertical),this.resizingPanes&&this.resizePanes(i,o);else if(P(t)){let[e,n]=this.findHit(t),r=!P(e)&&!P(n)?this.findPlotHits(t.pane,o):[],i=a.setHoverHighlight(r);P(n)?t.presenter.view.setCursor(ee.Crosshair):P(e)?e.isSelected?t.presenter.view.setCursor(ee.Move):t.presenter.view.setCursor(ee.Hand):i?t.presenter.view.setCursor(ee.Crosshair):t.presenter.view.setCursor(ee.Arrow)}else if(P(r))this.canVerticalZoom(a)&&(i.setCursor(ee.ResizeVertical),this.performAxisScaling(i,r,o));else{let e=this.canHorizontalZoom(a);if(!e&&this.prevZoomingOffset&&delete this.prevZoomingOffset,this.prevZoomingOffset&&e){let{x:e}=this.prevZoomingOffset,{x:t}=o,n=e-t;this.applyZoom(i.presenter,-n),this.prevZoomingOffset=o}i.setCursor(e?ee.ResizeHorizontal:ee.Arrow)}return!t||this.resizingPanes?(this.hideCrosshairAndTooltips(i),Ie()):(this.isLogoLink(o)&&i.setCursor(ee.Hand),this.showCrosshairAndTooltips(i,t,o),Ie())}showCrosshairAndTooltips(e,t,n){t.time&&(!Ie()||this.touchCrosshairMode)&&e.drawCrosshair({ap:t,offset:n})&&e.presenter.showTooltip&&Ik(e.presenter,{time:t.time,offset:n,price:t.price,lastBarRefresh:void 0,justMain:void 0})}hideCrosshairAndTooltips(e,t=!1){e.presenter.setHoverHighlight([]),e.drawCrosshair({ap:void 0}),e.tooltip.hide(),e.presenter.hideCards(t),t&&e.tooltip.mode===`cards`&&!e.presenter?.hasLegend&&Fk(e.presenter)}onMouseLeave(e){let{view:t,offset:n}=e;t.presenter.accessor.getPaneBounds()?.every(e=>!e||!e.contains(n)||nA(e,n))&&(this.hideCrosshairAndTooltips(t,!0),this.stopResizeZoom(t.presenter)),t.setCursor(ee.Arrow),this.touchCrosshairMode=!1}stopResizeZoom(e){this.resizingPanes&&(this.resizingPanes=!1,e.enableTooltip(!0),e.onPaneHeightsUpdated()),this.resizingScale&&this.stopResizingScale(),this.prevZoomingOffset&&delete this.prevZoomingOffset}onMouseUp({presenter:e}){if(this.stopResizeZoom(e),Ie()){let t=rA();this.touchCrosshairTimeout=window.setTimeout(()=>{this.hideCrosshairAndTooltips(e.view,!0),this.touchCrosshairMode=!1},t)}}applyZoom(e,t,n=!0){if(!this.canHorizontalZoom(e))return;let r=Math.sign(t)*(Ie()?2:10),i=e.view;i.xAxis.zoom(r)&&(i.setPriceAxesDomains(),i.redraw(),n&&this.fireZoomChanged(e))}onWheel({view:e,presenter:t,getModifier:n,delta:r}){let{scrollBehavior:i}=t.display;return!(Ie()?i!==`none`:i===`wheel`||i===`wheel+shift`&&n(D.Shift))||r===0?!1:(e.drawCrosshair({ap:void 0}),e.tooltip.hide(),e.presenter.hideCards(),this.applyZoom(t,r),!0)}get useKeyboardShortcuts(){return $().config.hostingModel!==ae[ae.Application]}onKeyDown(e){let{key:t,code:n,presenter:r}=e;if(P(r.selectedAnnotation)&&Le(t,n)&&r.deleteAnnotationWithUndo(r.selectedAnnotation),P(r.selectedAnnotation)&&(Re(t,n)?r.clearSelection():ze(t,n)&&r.selectedAnnotation instanceof bk&&r.selectedAnnotation.textEditable&&(r.activeTool=new Ek(null,r.selectedAnnotation),r.activeTool.startEditing())),Be(t,n)||Ve(t,n)){let e=Be(t,n)?1:-1,i=r.view;i.xAxis.pan(e*i.xAxis.xScale.bar.totalWidth),this.hideCrosshairAndTooltips(i),i.redraw()}let i=window.navigator.platform.toLowerCase().startsWith(`mac`)?D.Meta:D.Control;if(e.getModifier(i)&&this.useKeyboardShortcuts){let e=He(t,n),i=We(t,n);return e&&r.undoRedoManager.undo(),i&&r.undoRedoManager.redo(),e||i}Ue(t,n)&&e.getModifier(D.Alt)&&this.resetView(r)}resetView(e){e.allAxes.forEach(e=>this.resetVerticalAxis(e,!1)),this.resetHorizontalAxis(e,!1),e.view.xAxis.goToLatest(!0)}resizePanes(e,t){let n=t.y-this.lastResizingOffset.y;if(n===0)return;let r=e.presenter.panes,[i,a]=this.splitter,o=r.map((e,t)=>{let r=e.getBounds().height;return t===i?r+n:t===a?r-n:r});if(o.some(e=>e<B.MINIMUM_PANE_HEIGHT))return;let s=(e,t)=>e+t,c=o.reduce(s,0),l=r.map(e=>e.height).reduce(s,0),u=e=>Xe(e,4);r.forEach((e,t)=>e.height=u(o[t]/c*l)),this.lastResizingOffset=t,e.recalculateLayout(),e.redraw()}startAxisScaling(e,t){this.resizingScale=!0,this.resizingScaleId=e.id,this.lastScaleResizingOffset=t}performAxisScaling(e,t,n){if(this.resizingScale&&this.resizingScaleId===t.id){let r=Ie()?4:5,i=tA(t,this.lastScaleResizingOffset,n,r,-r);this.lastScaleResizingOffset=n,t.isCustomDomain=!0,t.yScale.domain(i),e.redraw()}}},aA=class extends Sk{factory;maxClicks;clicks=0;snapToSupported=!0;isDrawingAnnotation=!0;constructor(e,t){super(e.annName),this.factory=e,this.maxClicks=t}onMouseMove(e){let{point:t,view:n,offset:r}=e;n.drawCrosshair({ap:t,offset:r})}onMouseDown(e){let{point:t,view:n}=e;if(this.clicks===0){if(t===void 0)return Dj(e),!1;t.axis.pane.presenter.clearSelection(),this.annotation=this.factory(t.axis)}this.applyToPoints(t),this.clicks++,this.clicks===this.maxClicks&&this.annotation!==void 0?(this.annotation.drawn=!1,this.annotation.requestRedraw(),typeof this.annotation.updateOtherPoints==`function`&&this.annotation.updateOtherPoints(n.mainContext),Tj(this.annotation,!0,O.Created)):this.annotation.requestRedraw()}applyToPoints(e){this.annotation.points[this.clicks].update(e.price,e.time)}},oA=class{snapToSupported=!1;constructor(e,t){setTimeout(()=>this.finalize(e,t),10)}finalize(e,t){let n=e(t);t.pane.presenter.clearSelection(),n.drawn=!1,n.requestRedraw(),Tj(n,!0,O.None)}},sA=B.MARKER_ARROW_ANGLE*Math.PI/180/2;function cA(e,t){return lA(e.map(e=>e.point),t)}function lA(e,t,n=B.MARKER_ARROW_LENGTH){return new uA(e,t,n)}var uA=class{vertex;arrowLen;p1;p2;constructor(e,t,n=B.MARKER_ARROW_LENGTH){this.vertex=t,this.arrowLen=n,this.p1=e[0],this.p2=e[1]}hitTest(e){let{anchor:t,p1:n,p2:r}=this.getArrowPoints();return co([t,n],e,B.HIT_TEST_TOLERANCE)||co([t,r],e,B.HIT_TEST_TOLERANCE)}draw(e){let{anchor:t,p1:n,p2:r}=this.getArrowPoints();zo(e,t,n),zo(e,t,r)}getArrowPoints(){let e=so(this.p1,this.p2),t=this.vertex===`start`?0:Math.PI,n=e-sA+t,r=e+sA+t,i=this.vertex===`start`?this.p1:this.p2,a=this.arrowLen*Math.cos(n)+i.x,o=this.arrowLen*Math.sin(n)+i.y,s=this.arrowLen*Math.cos(r)+i.x,c=this.arrowLen*Math.sin(r)+i.y;return{anchor:i,p1:{x:a,y:o},p2:{x:s,y:c}}}},dA=class{hitTest(){return!1}draw(){}},fA=class extends fk{constructor(e,t){super(e,t),this.addPoints(2),this.alignPointsSupported=!0}get extend1(){return this.traits[B.AT_EXTEND_PT_1]}get extend2(){return this.traits[B.AT_EXTEND_PT_2]}get showPercentDiff(){return this.traits[B.AT_SHOW_PERCENTDIFF]}get showBarCount(){return this.traits[B.AT_SHOW_BARCOUNT]}get showRatio(){return this.traits[B.AT_RATIO]}getElements(){let e=this.points[0].point,t=this.points[1].point,n=new uk(e,t,this.extend1,this.extend2,this.axis),r=[];return this.extend1&&r.push(new uk(n.p1,e,!0,!1,this.axis)),r.push(new uk(e,t,!1,!1,this.axis)),this.extend2&&r.push(new uk(t,n.p2,!1,!0,this.axis)),r}formatRatio(e,t){return` (${Xe(e/t,3)})`}formatPercDiff(e,t){let n=(t-e)/e*100;return` (${n>0?`+`:``}${Xe(n,2)}%)`}formatPrice(e){return iv(this.axis,this.priceMap(e))}adornElements(e,t){if(!this.showBarCount&&!this.showPrices&&!this.showPercentDiff&&!this.showRatio)return;let[n,r]=this.points,i=e[+!!this.extend1].getAdornOffset(t);if(this.showBarCount){let e=oo(no(n.point,r.point),i);Fo(t,this.getBarCount(n.time,r.time).toFixed(0),e,T.Right)}let a=this.showRatio?this.formatRatio(n.price,r.price):``,o=`${this.showPrices?this.formatPrice(n.price):``}${a}`.trim();o!==``&&Fo(t,o,oo(n.point,i),T.Right);let s=this.showPercentDiff?this.formatPercDiff(n.price,r.price):``,c=`${this.showPrices?this.formatPrice(r.price):``}${s}`.trim();c!==``&&Fo(t,c,oo(r.point,i),T.Right)}getMarkers(){let e=this.marker;if(!e||e.vertex===`none`)return[];let{vertex:t,kind:n}=e;return(t===`both`?[`start`,`end`]:[t]).map(e=>n===`arrow`?cA(this.points,e):(I(`There is no marker of ${n} kind`,`warn`),new dA))}},pA=class extends fk{constructor(e,t){super(e,t),this.addPoints(1)}get showTimestamps(){return this.traits[B.AT_SHOW_TIMESTAMPS]}getElements(){return[new rk(this.points[0].point,!0,this.axis)]}getTimeScaleAdornments(){return this.showTimestamps?[{time:this.points[0].time,color:this.traits.line.color}]:super.getTimeScaleAdornments()}},mA=class extends fk{constructor(e,t){super(e,t),this.addPoints(1)}getElements(){return[new rk(this.points[0].point,!1,this.axis)]}getPriceScaleAdornments(){return this.showPrices?[{price:this.points[0].price,color:this.traits.line.color}]:super.getPriceScaleAdornments()}},hA=class extends fk{constructor(e,t,n){super(e,t),this.addPoints(2),P(n)&&P(n.points)&&n.points.forEach((e,t)=>this.points[t].update(e.price,e.time))}allPoints(){let[e,t]=this.points;return P(e,e.point,t,t.point)?[e,this.axis.toAnnotationPoint(no(e.point,t.point)),t]:B.EMPTY_ARRAY}line2(){return this.traits[B.AT_LINE_2]}use52WeekPrices(){return this.traits[B.AT_USE_52WEEK_PRICES]}getElements(){let e=this.allPoints();return e===B.EMPTY_ARRAY?B.EMPTY_ARRAY:e.map(e=>new uk({x:-B.OUT_OF_SCREEN,y:e.point.y},{x:B.OUT_OF_SCREEN,y:e.point.y},!1,!1,this.axis))}wasPointMovedByTool(e,t){P(this.use52WeekPrices())&&(this.traits[B.AT_USE_52WEEK_PRICES]=!1)}getStyleForElement(e,t){let n=this.line2();if(t!==1||!P(n))return super.getStyleForElement(e,t);let r=F(this.traits);return r.line=n,hs(r)}getPriceScaleAdornments(){let e=this.allPoints();if(!this.showPrices||e===B.EMPTY_ARRAY)return super.getPriceScaleAdornments();let t=this.traits.line,n=e.map(e=>({price:e.price,color:t.color})),r=this.line2();return P(r)&&(n[1].color=r.color),n}getFlipAnchorIndices(){return null}},gA=5,_A=class extends pk{helper;constructor(e,t,n){super(e,t),this.addPoints(n),this.helper=new ik(e)}get showTrendLine(){return this.traits[B.AT_SHOW_TRENDLINE]}get hasAllPoints(){return P(...this.points.map(e=>e.point))}get line2(){return this.traits[B.AT_LINE_2]}get extendLeft(){return this.traits[B.AT_EXTEND_LEFT]}get extendRight(){return this.traits[B.AT_EXTEND_RIGHT]}get reverse(){return this.traits[B.AT_REVERSE]}get levelsRespectLogScale(){return this.traits[B.AT_LEVELS_RESPECT_LOG_SCALE]}getStyleForElement(e,t){if(e.isTrend){let e=F(this.traits);return e.line=this.line2,hs(e)}return super.getStyleForElement(e,t)}getKeyPoints(){let e=e=>e.map(e=>this.points[e]);return this.isExtended?e(this.reverse?[1,0,2]:[0,1,2]):e(this.reverse?[0,1,0]:[1,0,1])}getElements(){if(!this.hasAllPoints)return[];let[e,t,n]=this.getKeyPoints(),r=t.price-e.price,i=t.price/e.price,a=this.extendLeft,o=this.extendRight,s=this.leftPoint,c=this.rightPoint,l=(e,t,n=!1)=>{let r=new uk(e,t,!n&&a,!n&&o,this.axis);return r.isTrend=n,r},u=this.levelsRespectLogScale&&this.axis.scale===S.Logarithmic,d=this.getColoredElements(({value:e})=>{let t=n.price+r*e,a=n.price*i**+e,o=u?a:t;this.helper.update(o,n.time);let d=this.helper.point.y;return l({x:s.x,y:d},{x:c.x,y:d})});return this.showTrendLine&&(d.push(l(e.point,t.point,!0)),this.isExtended&&d.push(l((this.reverse?e:t).point,n.point,!0))),d}getAdornPointAndAlign(e,t){let n=this.labels,r=(e,t,n)=>({pt:e,align:t,offset:n}),i=this.axis.pane.getBoundsWithoutScales();switch(n){case B.AT_LABELS_LEFT:return this.extendLeft?r({x:i.x,y:e.anchor1.y},T.Left,t):super.getAdornPointAndAlign(e,t);default:case B.AT_LABELS_RIGHT:return this.extendRight?r({x:i.x+i.width,y:e.anchor2.y},T.Right,-t):super.getAdornPointAndAlign(e,t);case B.AT_LABELS_CENTER:return super.getAdornPointAndAlign(e,t)}}getTextRef(){return(e,t,n)=>({ref:t,spacing:gA,offsetY:-5,text:this.formatLevelPrice(n,t.anchor1.y)})}adornElements(e,t){this.adornElementsForColoredFactors(e,(e,t)=>{let n=new Path2D;return e===null?n:(Oo(n,e.p1),n.lineTo(t.p2.x,e.p1.y),ko(n,t.p2),n.lineTo(e.p1.x,t.p2.y),n)},this.getTextRef(),t)}getPriceScaleAdornments(){if(!this.pricesOnScale)return super.getPriceScaleAdornments();let e=this.getElements();if(e.length===0)return super.getPriceScaleAdornments();let t=this.traits.line.color;return this.factors.map((n,r)=>{let i=e[r++].p1,a=this.singleStyle?t:n.line.color;return{price:this.axis.toPrice(i.y),color:a}})}},vA=class extends _A{constructor(e,t){super(e,t,2)}},yA=class extends _A{constructor(e,t){super(e,t,3)}},bA=5,xA=(e,t)=>{let n=new Path2D;return e===null?n:(Oo(n,e.p1),ko(n,e.p2),ko(n,t.p2),n)},SA=class extends pk{constructor(e,t){super(e,t),this.addPoints(2)}get reverse(){return this.traits[B.AT_REVERSE]}getElements(){let[e,t]=this.getScreenPoints(),n=t.y-e.y;return this.getColoredElements(({value:r})=>{let i=this.reverse?e.y+r*n:t.y-r*n;return new uk(e,{x:t.x,y:i},!1,!0,this.axis)})}getTextRef(){let[e,t]=this.getScreenPoints(),n=t.y-e.y,[r,i]=[this.leftPoint,this.rightPoint];return(a,o,s)=>{let c=this.reverse?e.y+s*n:t.y-s*n;return{ref:new uk({x:r.x,y:c},{x:i.x,y:c},!1,!1,this.axis),spacing:bA,offsetY:!0,text:s.toString()}}}adornElements(e,t){this.adornElementsForColoredFactors(e,xA,this.getTextRef(),t)}},CA=class extends SA{constructor(e,t){super(e,t)}};function wA(e,t,n){return new EA(e,t,io(e,t),0,Math.PI,null,n)}function TA(e,t,n,r,i,a){return new EA(e,null,t,n,r,i,a)}var EA=class{center;rim;radius;startAngle;endAngle;antiClockwise;axis;left=null;right=null;scale=null;clip=null;style;constructor(e,t,n,r,i,a,o){this.center=e,this.rim=t,this.radius=n,this.startAngle=r,this.endAngle=i,this.antiClockwise=a,this.axis=o,t!==null&&(this.left={x:this.center.x-this.radius,y:this.center.y},this.right={x:this.center.x+this.radius,y:this.center.y})}get hasScale(){return this.scale!==null}get hasClip(){return this.clip!==null}get hasRim(){return this.rim!==null}applyScale(e){e.translate(this.center.x,this.center.y),e.scale(this.scale.x,this.scale.y),e.translate(-this.center.x,-this.center.y)}inverseScale(e){let t=new DOMPointReadOnly(e.x,e.y),n=this.axis.pane.presenter.view.mouseContext;n.save(),n.resetTransform(),this.applyScale(n);let r=n.getTransform().inverse();return n.restore(),r.transformPoint(t)}hitTest(e){let t=999;if(this.hasRim&&(this.center.y<this.rim.y&&e.y<=this.center.y||this.center.y>=this.rim.y&&e.y>=this.center.y))t=Math.min(io(this.left,e),io(this.right,e));else{let{x:n,y:r}=ao(this.hasScale?this.inverseScale(e):e,this.center);if(!this.hasRim){let{startAngle:e,endAngle:t,antiClockwise:i}=this,a=Math.PI/2;if(e===0&&t===a&&!i&&(n<0||r<0)||e===a&&t===Math.PI&&!i&&(n>0||r<0)||e===-a&&t===Math.PI&&i&&(n>0||r>0)||e===0&&t===-a&&i&&(n<0||r>0))return!1}t=Math.abs(Math.sqrt(n*n+r*r)-this.radius)}return t<=B.HIT_TEST_TOLERANCE}get isAntiClockwise(){return this.hasRim?this.rim.y<=this.center.y:this.antiClockwise}draw(e){e.save(),this.hasClip&&e.clip(this.clip),this.hasScale&&this.applyScale(e),Ro(e,this.center,this.radius,this.startAngle,this.endAngle,this.isAntiClockwise??!1),e.restore()}},DA=(e,t)=>{let n=new Path2D,{center:r}=t;if(Oo(n,r),n.arc(r.x,r.y,t.radius,t.startAngle,t.endAngle,t.isAntiClockwise??!1),e===null)return n;let i=new Path2D,{center:a}=e;return Oo(i,a),i.arc(a.x,a.y,e.radius,e.endAngle,e.startAngle,!e.isAntiClockwise),n.addPath(i),n},OA=class extends pk{constructor(e,t){super(e,t),this.addPoints(2)}getElements(){let[e,t]=this.getScreenPoints();if(!P(e,t))return[];let n=io(e,t),r=ao(t,e),i=r.y/n,a=r.x/n,o=this.getColoredElements(({value:t})=>{let r=n*t,o=i*r,s=a*r;return wA(e,{x:e.x+s,y:e.y+o},this.axis)});if(this.showTrendLine){let n=new uk(e,t,!1,!1,this.axis);n.isTrend=!0,o.unshift(n)}return o}get showTrendLine(){return!0}getTextRef(){return(e,t,n)=>{let{center:r}=t,i=t.isAntiClockwise?-1:1;return{ref:{x:r.x,y:r.y+i*t.radius},spacing:0,offsetY:!0,text:n.toString()}}}adornElements(e,t){this.adornElementsForColoredFactors(e,DA,this.getTextRef(),t)}},kA=class extends OA{constructor(e,t){super(e,t)}getStyleForElement(e,t){if(e.isTrend){let e=F(this.traits);return e.line=this.line2,hs(e)}return super.getStyleForElement(e,t)}get showTrendLine(){return this.traits[B.AT_SHOW_TRENDLINE]}get line2(){return this.traits[B.AT_LINE_2]}},AA=class extends pk{constructor(e,t){super(e,t),this.addPoints(2)}get factorsPropName(){return B.AT_ANGLES}getElements(){let[e,t]=this.getScreenPoints(),{x:n,y:r}=ao(t,e);return this.getColoredElements(({value:i})=>{let a=(t,n)=>new uk(e,{x:t,y:n},!1,!0,this.axis),o=i.charAt(0)!==`1`,s=Number(o?i.charAt(0):i.charAt(2));return o?a(t.x,e.y+r/s):a(e.x+n/s,t.y)})}getTextRef(){return(e,t,n)=>({ref:t.anchor2,spacing:0,offsetY:!0,text:n.toString()})}adornElements(e,t){this.adornElementsForColoredFactors(e,xA,this.getTextRef(),t)}},jA=class extends SA{constructor(e,t){super(e,t),this._factors=[{shown:!0,value:1/3},{shown:!0,value:2/3}]}getElements(){let[e,t]=this.getScreenPoints();return[new uk(e,t,!1,!1,this.axis)].concat(super.getElements())}},MA=class extends OA{constructor(e,t){super(e,t),this._factors=[{shown:!0,value:1/3},{shown:!0,value:2/3}]}},NA=class extends fk{constructor(e,t){super(e,t),this.addPoints(3)}getElements(){let e=this.points[0].point,t=this.points[1].point,n=this.points[2].point,r=(t.x+n.x)/2-e.x,i=(t.y+n.y)/2-e.y,a=[];return a.push(new uk(t,{x:t.x+r,y:t.y+i},!1,!0,this.axis)),a.push(new uk(e,{x:e.x+r,y:e.y+i},!1,!0,this.axis)),a.push(new uk(n,{x:n.x+r,y:n.y+i},!1,!0,this.axis)),a.push(new uk(t,n,!1,!1,this.axis)),a}},PA=class extends vk{constructor(e,t){super(e,t)}getEllipse(){let e=this.getRect();return e===null?null:new Do(e.centerX,e.centerY,e.width/2,e.height/2)}hitTest(e){if(!this.isVisible)return!1;let t=this.getEllipse();return t===null?!1:t.contains(e)}draw(e,t){return super.draw(e,t)?(Io(e,this.getEllipse()),!0):!1}},FA=class extends fk{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[B.AT_EXTEND_PT_1]}get extend2(){return this.traits[B.AT_EXTEND_PT_2]}getLastPoint(){let[e,t,n]=this.points;var r=io(e.point,t.point),i=so(e.point,t.point);return{x:n.point.x+r*Math.cos(i),y:n.point.y+r*Math.sin(i)}}getElements(){let[e,t,n]=this.points;var r=[];if(r.push(new uk(e.point,t.point,this.extend1,this.extend2,this.axis)),P(n?.price)){var i=this.getLastPoint();r.push(new uk(n.point,i,this.extend1,this.extend2,this.axis))}return r}},IA=class extends vk{kind;constructor(e,t,n){super(e,t),this.kind=n,this.adjustFill=!0}hitTest(e){if(!this.isVisible)return!1;let t=this.getRect();return t===null?!1:t.contains(e)}get dimension(){let e=this.kind===`fish_hook`?2:1;return B.DEFAULT_SYMBOL_WIDTH_HEIGHT*e}updateOtherPoints(){this.points[1].price||this.setBottomRight()}setBottomRight(){let e=this.dimension,t=this.axis.pane.presenter.timeline,{price:n,time:r}=this.points[0],i=j(t,r,Number,fv);if(i!==-1){let r=this.axis.pane.presenter.view.xAxis.xScale.bar.totalWidth,a=1;for(;(2*a+1)*r<e;)a++;this.points[0].update(n,t.at(i-a)),this.points[1].update(n,t.at(i+a));let o=oo(this.points[0].point,{x:0,y:-e/2}),s=oo(this.points[1].point,{x:0,y:e/2});this.points[0].updateFromPoint(o),this.points[1].updateFromPoint(s)}}draw(e,t){if(!super.draw(e,t))return!1;let n=this.getRect();return n.width===0&&(n.width=this.dimension),Uo(e,this.kind,n),!0}},LA=class extends pk{helper;constructor(e,t){super(e,t),this.addPoints(2),this.helper=new ik(e)}getElements(){let e=this.axis.pane.presenter.timeline,{price:t,time:n}=this.points[0],r=j(e,n,Number,fv),i=j(e,this.points[1].time,Number,fv),a=i-r;return r===-1||i===-1?[]:this.getColoredElements(({value:n})=>{let i=e.at(r+n*a);return i===null?null:(this.helper.update(t,i),new rk(this.helper.point,!0,this.axis))})}getTextRef(){return(e,t,n)=>({ref:t.anchor,spacing:3,offsetY:!0,text:n.toString()})}adornElements(e,t){let n=this.axis.pane.getBoundsWithoutScales();this.adornElementsForColoredFactors(e,(e,t)=>{let r=new Path2D;if(e===null)return r;let i=t.anchor.x-e.anchor.x;return r.rect(e.anchor.x,n.y,i,n.height),r},this.getTextRef(),t)}getTimeScaleAdornments(){let e=e=>({time:this.points[e].time,color:this.traits.line.color});return[e(0),e(1)]}},RA=class{snapToSupported=!0;isDrawingAnnotation=!0;constructor(){}onMouseMove(e){let{point:t,view:n,offset:r}=e;n.drawCrosshair({ap:t,offset:r})}onMouseDown(e){if(Ie()&&e.originalEvent instanceof TouchEvent)return;let{point:t}=e;if(!t?.axis?.pane?.presenter||!t.time)return;let n=t.axis.pane.presenter,r={chart:n.accessor,axis:t.axis,point:{time:t.time.getTime(),price:t.price}};n.notifyHost(K.CH_ANNPOINTPICKED,r),wj(n,void 0)}},zA=c(o(((e,t)=>{var n=ga(),r=Ca();t.exports=(()=>{function e(e){if(!n.string(e)||e.length!==1)return 0;let t=r.parse(e);return t===null?0:t.baseCode}return e})()}))(),1);function BA(e){let t=e?.minMovement;if(!Number.isFinite(t)||t<=0)return B.MIN_POSITION_PRICE_PRECISION;let[n,r=`0`]=t.toString().toLowerCase().split(`e`),i=(n.includes(`.`)?n.split(`.`)[1].length:0)+Math.max(0,-Number.parseInt(r,10));return Math.max(B.MIN_POSITION_PRICE_PRECISION,i)}function VA(e){if(e?.symbolType===`Forex`)return 10**(0,zA.default)(e.unitCode);let t=e?.pointValue;return Number.isFinite(t)?t:1}function HA(e,t,n){return Xe(n?e/100*t:e,2)}function UA({entryPrice:e,upperPrice:t,lowerPrice:n,isLong:r},i){let a=r?e-n:t-e;return!Number.isFinite(a)||a<=0?NaN:Math.floor(i/a)}function WA(e,t,n){let r=n?e:t,i=n?t:e;return!Number.isFinite(i)||i===0?NaN:Xe(r/i,2)}function GA(e,t,n,r){return Xe((r===`upper`?1:-1)*(n?1:-1)*e*t,2)}function KA(e,t,n,r,i){return Xe(e+(i===`upper`?1:-1)*(r?1:-1)*t*n,2)}function qA(e,t){return Number.isFinite(e)?t?e>0:e<=0:!0}var JA={Open:`Open`,Closed:`Closed`},YA=class extends fk{isLong;twoDecMeta;_dataWindow;_metaData;isHit=!1;constructor(e,t,n){super(e,t),this.isLong=n,this.addPoints(4);let r=(e,t)=>this.points[e].moveDirection=t;r(1,te.Vertical),r(2,te.Vertical),r(3,te.Horizontal),this.twoDecMeta=new Wa(2)}data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}get presenter(){return this.axis.pane.presenter}get metaData(){return this._metaData||=this.presenter.mainPlot.metaData,this._metaData}getDataWindow(e,t,n=!0,r=!0){let i=this.data(G.DateTime),a=j(i,+e,Number),o=j(i,+t,Number),s={refIndex:-1,highestIndex:-1,lowestIndex:-1,highest:null,lowest:null,data:[]},[c,l,u]=[G.High,G.Low,G.Close].map(e=>this.data(e)),d=e=>e-a;for(let e=a;e<=o;e++)n&&s.refIndex===-1&&P(this.entryPrice)&&this.entryPrice>=l[e]&&this.entryPrice<=c[e]&&(s.refIndex=d(e)),(!n||s.refIndex>=0&&d(e)>=s.refIndex)&&((!P(s.highest)||c[e]>s.highest)&&(s.highest=c[e]),(!P(s.lowest)||l[e]<s.lowest)&&(s.lowest=l[e])),n&&s.refIndex!==-1&&(s.highestIndex===-1&&c[e]>this.upperPrice&&(s.highestIndex=d(e)),s.lowestIndex===-1&&l[e]<this.lowerPrice&&(s.lowestIndex=d(e))),r&&s.data.push({high:c[e],low:l[e],close:u[e],time:i[e]});if(r&&s.data&&s.data.length>0){s.state=P(s.highest,s.lowest)&&(this.upperPrice<s.highest||this.lowerPrice>s.lowest)?JA.Closed:JA.Open,s.special=s.highestIndex===-1&&s.lowestIndex===-1||s.highestIndex===s.lowestIndex;let e=Se(s.data);if(s.toPrice=e.close,s.toTime=e.time,s.state===JA.Closed)if(s.special)s.refIndex!==-1&&(s.toTime=s.data[s.refIndex].time,s.toPrice=(this.isLong?this.lowerPrice<s.lowest:this.upperPrice<s.highest)?this.upperPrice:this.lowerPrice);else{let e=s.highestIndex!==-1&&s.lowestIndex!==-1;e&&s.highestIndex<s.lowestIndex||s.lowestIndex===-1?(s.toPrice=this.upperPrice,s.toTime=s.data[s.highestIndex].time):(e&&s.lowestIndex<s.highestIndex||s.highestIndex===-1)&&(s.toPrice=this.lowerPrice,s.toTime=s.data[s.lowestIndex].time)}let t=this.isLong?s.toPrice-this.entryPrice:this.entryPrice-s.toPrice;s.pAndL=this.roundPriceDelta(t)}return s}get dataWindow(){return P(this._dataWindow)||(this._dataWindow=this.getDataWindow(this.entryAnchor.time,this.exitAnchor.time)),this._dataWindow}getVisiblePriceRange(){let e=this.axis.yScale.domain();return e[1]-e[0]}getFutureTimestamp(){let e=this.axis.pane.presenter.timeline,t=j(e,+this.points[0].time,Number,fv);if(!Number.isFinite(t)||t<0)return Date.now();let n=Math.min(e.length-1,t+50),r=e.at(n);return P(r)?r.getTime():Date.now()}get entryPrice(){return this.entryAnchor.price}get entryAnchor(){return this.points[0]}get upperPrice(){return this.upperAnchor.price}get upperAnchor(){return this.points[1]}get lowerPrice(){return this.lowerAnchor.price}get lowerAnchor(){return this.points[2]}get exitAnchor(){return this.points[3]}get accountSize(){return this.traits[B.AT_ACCOUNT_SIZE]}get risk(){return HA(this.traits[B.AT_RISK],this.accountSize,this.traits[B.AT_RISK_IS_PERCENT])}get positionInputs(){return{entryPrice:this.entryPrice,upperPrice:this.upperPrice,lowerPrice:this.lowerPrice,isLong:this.isLong}}get pricePrecision(){return BA(this.metaData)}get pointValue(){return VA(this.metaData)}roundPriceDelta(e){return Xe(e,this.pricePrecision)}formatDollarValue(e){return Number.isFinite(e)?`${e<0?`-`:``}$${this.twoDecMeta.format(Math.abs(e))}`:B.NOT_APPLICABLE}formatRatioValue(e){return Number.isFinite(e)?e.toFixed(2):B.NOT_APPLICABLE}formatQuantityValue(e){return Number.isFinite(e)?`${e}`:B.NOT_APPLICABLE}formatPercentChange(e){return Number.isFinite(e)?`(${Xe(e,2).toFixed(2)}%)`:`(${B.NOT_APPLICABLE})`}get qty(){return UA(this.positionInputs,this.risk)}get upperDiff(){return this.roundPriceDelta(this.upperPrice-this.entryPrice)}get upperAmount(){return KA(this.accountSize,this.qty,this.upperDiff,this.isLong,`upper`)}get upperPandL(){return GA(this.upperDiff,this.pointValue,this.isLong,`upper`)}get isCompact(){return this.traits[B.AT_COMPACT]}get upper(){let e=iv(this.axis,this.priceMap(this.upperPrice)),t=this.formatPercentChange(this.upperDiff/this.entryPrice*100);return this.isCompact,`${e} ${t}`}get upperText(){let e=`${this.formatDollarValue(this.upperPandL)}`,t=`${this.formatDollarValue(this.upperAmount)}`,n=this.isLong?`Target`:`Stop`;return this.isCompact?`${this.upper} ${e}`:`${n}: ${this.upper}, P&L: ${e}, Amount: ${t}`}get lowerDiff(){return this.roundPriceDelta(this.entryPrice-this.lowerPrice)}get lowerAmount(){return KA(this.accountSize,this.qty,this.lowerDiff,this.isLong,`lower`)}get lowerPandL(){return GA(this.lowerDiff,this.pointValue,this.isLong,`lower`)}get lower(){let e=iv(this.axis,this.priceMap(this.lowerPrice)),t=this.formatPercentChange(this.lowerDiff/this.entryPrice*100);return this.isCompact,`${e} ${t}`}get lowerText(){let e=`${this.formatDollarValue(this.lowerPandL)}`,t=`${this.formatDollarValue(this.lowerAmount)}`,n=this.isLong?`Stop`:`Target`;return this.isCompact?`${this.lower} ${e}`:`${n}: ${this.lower}, P&L: ${e}, Amount: ${t}`}get riskReward(){return WA(this.upperDiff,this.lowerDiff,this.isLong)}get state(){return this.dataWindow.state}get pAndL(){return this.dataWindow.pAndL}get pAndLValue(){return this.pAndL*this.pointValue}positionPoints(){let e=this.getVisiblePriceRange()/5,t=this.getFutureTimestamp();this.upperAnchor.update(this.entryPrice+e,this.entryAnchor.time),this.lowerAnchor.update(this.entryPrice-e,this.entryAnchor.time),this.exitAnchor.update(this.entryPrice,t)}get lowerStyle(){return this.fillOnlyStyle(B.AT_FILL2)}get upperStyle(){return this.fillOnlyStyle(B.AT_FILL)}get textStyle(){return this.fillOnlyStyle(B.AT_FILL_TEXT)}get secondaryLineStyle(){return hs({line:{color:this.traits.line.color,dashStyle:`ShortDash`},fill:{color:B.COLOR_TRANSPARENT}})}wasModifiedByTool(){P(this.points[2].price)||this.positionPoints(),this._dataWindow=void 0}wasPointMovedByTool(e,t){let n=this.getVisiblePriceRange()/5e3;if(this.points.indexOf(e)<3){let t=t=>e.update(t,e.time);this.entryAnchor.price>this.upperAnchor.price&&(e===this.entryAnchor?t(this.upperAnchor.price-n):t(this.entryAnchor.price+n)),this.entryAnchor.price<this.lowerAnchor.price&&(e===this.entryAnchor?t(this.lowerAnchor.price+n):t(this.entryAnchor.price-n))}if(e===this.entryAnchor){let t=(t,n,r)=>t.update(n?e.price:t.price,r?e.time:t.time);t(this.exitAnchor,!0,!1),t(this.upperAnchor,!1,!0),t(this.lowerAnchor,!1,!0)}this.wasModifiedByTool()}get isUpperPerPAndL(){return qA(this.dataWindow.pAndL,this.isLong)}getStyleForElement(e,t){return e.style||this.defaultStyle}getElements(){let e=new uk(this.entryAnchor.point,this.exitAnchor.point,!1,!1,this.axis),t=this.exitAnchor.point.x<this.entryAnchor.point.x,n=Math.abs(this.exitAnchor.point.x-this.entryAnchor.point.x),r=(e,t)=>({x:e.x+t,y:e.y}),i=new dk(r(this.upperAnchor.point,t?-n:0),n,Math.abs(this.upperAnchor.point.y-this.entryAnchor.point.y),this.axis);i.style=this.upperStyle;let a=new dk(r(this.entryAnchor.point,t?-n:0),n,Math.abs(this.entryAnchor.point.y-this.lowerAnchor.point.y),this.axis);a.style=this.lowerStyle;let o=[e,i,a],s=this.dataWindow;if(s.refIndex!==-1){let e=s.data[s.refIndex],t=new ik(this.axis,this.entryPrice,e.time),n=new ik(this.axis,s.toPrice,s.toTime),r=new uk(t.point,n.point,!1,!1,this.axis);if(r.style=this.secondaryLineStyle,o.push(r),t.time!==n.time){let e=this.entryPrice<s.toPrice,r=new dk({x:t.point.x,y:Math.min(t.point.y,n.point.y)},n.point.x-t.point.x,Math.abs(n.point.y-t.point.y),this.axis);r.style=e?this.upperStyle:this.lowerStyle,o.push(r)}}return o}hitTest(e){if(!this.isVisible)return!1;let t=this.isHit||!1;return this.isHit=super.hitTest(e),this.isHit!==t&&this.requestRedraw(),this.isHit}get showTextAdornments(){return this.isHit||this.isSelected}getPriceScaleAdornments(){let e=e=>uo(this.traits[e].color);return[{price:this.upperPrice,color:e(B.AT_FILL)},{price:this.entryPrice,color:e(B.AT_LINE)},{price:this.lowerPrice,color:e(B.AT_FILL2)}]}adornElements(e,t){let[n,r,i]=e;if(this.showTextAdornments){let[e,a]=[!0,!1].map(e=>Mo(t,e)),{x:o,y:s,width:c}=r.rect,l={x:o+c/2,y:s+e},u=this.textStyle.fillStyle;Fo(t,this.upperText,l,T.Center,u,uo(this.upperStyle.fillStyle));let{x:d,y:f,width:p,height:m}=i.rect,h={x:d+p/2,y:f+m+Math.abs(a)};Fo(t,this.lowerText,h,T.Center,u,uo(this.lowerStyle.fillStyle));let{p1:g,p2:_}=n,{x:v,y}=g,{x:b}=_,x=this.state||B.NOT_APPLICABLE,S=this.isCompact?`${this.formatDollarValue(this.pAndLValue)}`:`${x} P&L: ${this.formatDollarValue(this.pAndLValue)}, Qty: ${this.formatQuantityValue(this.qty)}`,C=this.isCompact?`${this.formatRatioValue(this.riskReward)}`:`Risk/Reward Ratio: ${this.formatRatioValue(this.riskReward)}`,w=e=>t.measureText(e).width,ee=Math.max(w(S),w(C)),E=Math.abs(b-v)<ee*1.25?y+Math.abs(a)+5:y+e+10,D={x:v+(b-v)/2,y:E},te=uo(this.isUpperPerPAndL?this.upperStyle.fillStyle:this.lowerStyle.fillStyle);Fo(t,[S,C],D,T.Center,u,te)}}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}},XA=class extends mk{markers;display=null;constructor(e,t){super(e,t),this.points=_k(e),this.points[2].visible=!1,this.points[3].visible=!1,this.markers=[new dA]}isPointDrawn(e){return super.isPointDrawn(e)?e.visible:!1}makeLineArrow(e,t,n,r){let i=[no(e,t),no(n,r)];return[this.makeLine(i[0],i[1]),lA(i,`end`,10)]}get rectColor(){return this.traits[B.AT_FILL].color}get textColor(){return this.traits[B.AT_FILL_TEXT].color}getMarkers(){return this.markers}getScreenPoints(){return this.points.slice(2).forEach(e=>e.toPoint()),super.getScreenPoints()}formatDateDifference(e,t){return this.presenter.data.aggregation.isEndOfDay?`${zn(t,e)}d`:Qr(ri({start:e,end:t}),{format:[`days`,`hours`,`minutes`,`seconds`]}).replaceAll(/(days?)|(hours?)|(minutes?)|(seconds?)/g,e=>e[0])}computeState(){}get text(){return this.display===null&&this.computeState(),this.display}getTextCoord(e,t){let n=this.points[0].price<this.points[1].price,r=Mo(t,n,this.text.length),{x:i,y:a,width:o,height:s}=e.rect;return{x:i+o/2,y:a+(n?0:s)+(n?r:Math.abs(r))}}adornElements(e,t){Fo(t,this.text,this.getTextCoord(e[0],t),T.Center,this.textColor,uo(this.rectColor))}getDateDifference(){let[e,t]=this.points.slice(0,2).map(e=>e.time);if(!e||!t)return[`0 bars, `,`Vol ${this.formatter.format(0,G.Volume)}`];let n=Math.min(+e,+t),r=Math.max(+e,+t),i=this.data(G.DateTime);if(!i||i.length===0)return[`0 bars, `,`Vol ${this.formatter.format(0,G.Volume)}`];let a=j(i,+n,Number),o=j(i,+r,Number),s=this.data(G.Volume);if(!Array.isArray(s))return[`0 bars, `,`Vol ${this.formatter.format(0,G.Volume)}`];let c=pe(s.slice(a,o+1)),l=this.formatter.format(c,G.Volume),u=o-a,d=u===0?``:this.formatDateDifference(n,r),f=e<t?``:`-`;return[`${f}${u} bars, ${f}${d}`,`Vol ${l}`]}getPriceDifference(){let[e,t]=this.points.slice(0,2).map(e=>e.price),n=t-e,r=n/e;return[`${this.formatter.format(n,G.Close)} (${this.formatter.format(r,G.PercentChange)})`]}resetComputedState(){this.display=null}onFormatterChanged(){this.resetComputedState()}getFlipAnchorIndices(){return[0,1]}},ZA=class extends XA{getElements(){let[e,t,n,r]=this.getScreenPoints(),i=this.makeLine(e,r),a=this.makeLine(t,n),[o,s]=this.makeLineArrow(e,r,t,n);return this.markers[0]=s,[this.rect,i,a,o]}computeState(){this.display=this.getDateDifference()}},QA=class extends XA{getElements(){let[e,t,n,r]=this.getScreenPoints(),i=this.makeLine(e,n),a=this.makeLine(t,r),[o,s]=this.makeLineArrow(e,n,t,r);return this.markers[0]=s,[this.rect,i,a,o]}computeState(){this.display=this.getPriceDifference()}},$A=class extends XA{get drawBorder(){return this.traits[B.AT_DRAW_BORDER]}getBorderElements(){if(!this.drawBorder)return[];let[e,t,n,r]=this.getScreenPoints();return[this.makeLine(e,r),this.makeLine(t,n),this.makeLine(e,n),this.makeLine(t,r)]}getElements(){let[e,t,n,r]=this.getScreenPoints(),[i,a]=this.makeLineArrow(e,r,t,n),[o,s]=this.makeLineArrow(e,n,t,r);this.markers=[a,s];let c=this.getBorderElements();return[this.rect,i,o].concat(c)}computeState(){this.display=this.getPriceDifference().concat(this.getDateDifference())}},ej=class extends mk{constructor(e,t){super(e,t),this.points=_k(e)}get priceLevels(){return cs(this.traits[B.AT_PRICE_LEVELS])}get timeLevels(){return cs(this.traits[B.AT_TIME_LEVELS])}get showAngles(){return this.traits[B.AT_SHOW_ANGLES]}get reverse(){return this.traits[B.AT_REVERSE]}get showLeftLabels(){return this.traits[B.AT_SHOW_LEFT_LABELS]}get showRightLabels(){return this.traits[B.AT_SHOW_RIGHT_LABELS]}get showTopLabels(){return this.traits[B.AT_SHOW_TOP_LABELS]}get showBottomLabels(){return this.traits[B.AT_SHOW_BOTTOM_LABELS]}getAngles(e,t){let n=this.getScreenPoints(),r=this.lineOnlyStyle(B.AT_LINE_2),i=(e,t)=>e.x===t.x&&e.y===t.y,a=(e,t)=>e.x===t.x||e.y===t.y,o=[];e.concat(t).flatMap(e=>[e.p1,e.p2]).map(e=>{o.some(t=>i(e,t))||o.push(e)});let s=n.map(e=>o.filter(t=>!a(t,e)).map(t=>this.makeLine(e,t))).flat();return s.forEach(e=>e.style=r),s}getElements(){let e=this.getLinesDataAtLevels(this.priceLevels,this.timeLevels),{priceLines:t,timeLines:n}=this.getLineElements(e),r=this.showAngles?this.getAngles(t,n):[];return[...t,...n,...r]}adornElements(e,t){let n=this.singleStyle,r=this.showBackground,i=t.fillStyle,a=jo(t,1)/2,o=e=>Number(e.toFixed(4)).toString(),{x:s,y:c}=B.DEFAULT_ADORN_OFFSET,l=(e,n,r,i,a)=>{let s=oo(e,n);Fo(t,o(r),s,i,a)},u=(e,n)=>{let r=new Path2D;Ao(r,e.p1,n.p2),t.fillStyle=n.style.fillStyle,t.fill(r)},d=null;if(e.forEach(e=>{if(!e._data)return;let{level:t,isPrice:o}=e._data,f=n?i:e.style.strokeStyle,p=d&&r&&!n;o?(this.showLeftLabels&&l(e.p1,{x:s,y:a},t,T.Right,f),this.showRightLabels&&l(e.p2,{x:-s,y:a},t,T.Left,f),p&&u(d,e)):(this.showTopLabels&&l(e.p1,{x:0,y:c},t,T.Center,f),this.showBottomLabels&&l(e.p2,{x:0,y:-c*2},t,T.Center,f),p&&u(d,e)),d=e}),n&&r){let e=this.applyBackgroundOpacity(this.traits.line.color),n=new Path2D,[r,i]=this.getScreenPoints();Ao(n,r,i),t.fillStyle=e,t.fill(n)}}resetComputedState(){this.lines=void 0}updateFrom(e,t,n,r,i){let a=e.reverse!==this.reverse;super.updateFrom(e,t,n,r,i),a&&this.resetComputedState()}getFlipAnchorIndices(){return[0,1]}},tj=e=>e.map(e=>({...e,dimensions:e.value.split(`x`).map(Number)})),nj=5,rj=(e,t)=>Math.abs(e-t)<1e-7,ij=class extends mk{_parsedFans=null;_parsedArcs=null;constructor(e,t){super(e,t),this.points=_k(e),this._parsedFans=this._parsedArcs=null}get levels(){return cs(this.traits[B.AT_LEVELS])}setComputedAndTraits(e,t){let n={...e,computed:t,traits:this.getTraitsFor(e)};return delete n.line,n}get computedLevels(){return this.levels.map(e=>this.setComputedAndTraits(e,e.value/nj))}get showRangesRatio(){return this.traits[B.AT_SHOW_RANGES_RATIO]}get arcs(){return cs(this.traits[B.AT_ARCS])}get fans(){return cs(this.traits[B.AT_FANS])}get reverse(){return this.traits[B.AT_REVERSE]}get parsedFans(){return this._parsedFans===null&&(this._parsedFans=tj(this.fans)),this._parsedFans}get computedFans(){let[,,e,t]=this.getReversedScreenPoints(),{dx:n,dy:r}=this.unit,{signX:i,signY:a}=this.getOrientation();return this.parsedFans.map(o=>{let[s,c]=o.dimensions;return this.setComputedAndTraits(o,s>=c?{x:e.x,y:e.y+c/s*a*nj*r}:{x:t.x+s/c*nj*i*n,y:t.y})})}get parsedArcs(){return this._parsedArcs===null&&(this._parsedArcs=tj(this.arcs)),this._parsedArcs}get computedArcs(){let{dx:e}=this.unit;return this.parsedArcs.map(t=>{let[n,r]=t.dimensions;return this.setComputedAndTraits(t,Math.sqrt(e**2*(n**2+r**2)))})}getReversedScreenPoints(){let[e,t,n,r]=this.getScreenPoints();return this.reverse?[t,e,r,n]:[e,t,n,r]}get unit(){let[e,t]=this.getReversedScreenPoints();return e.x!==t.x&&e.y!==t.y?{dx:Math.abs(t.x-e.x)/nj,dy:Math.abs(t.y-e.y)/nj}:null}get priceBarRatio(){return this.traits[B.AT_PRICE_BAR_RATIO]}set priceBarRatio(e){this.traits[B.AT_PRICE_BAR_RATIO]=e}makeStyledLine(e,t,n){let r=this.makeLine(e,t);return this.singleStyle||(r.style=hs(n)),r}getGridLines(e,t){let n=t.x-e.x,r=t.y-e.y;return this.computedLevels.map(({computed:i,traits:a})=>{let o=e.x+i*n,s=e.y+i*r;return[this.makeStyledLine({x:o,y:e.y},{x:o,y:t.y},a),this.makeStyledLine({x:e.x,y:s},{x:t.x,y:s},a)]}).flat()}getArcs(e){let{flipX:t,flipY:n,signY:r}=this.getOrientation(),{dx:i,dy:a}=this.unit,o=rj(i,a)?null:{x:1,y:a/i},s=this.getClipPath();return this.computedArcs.map(({computed:i,traits:a})=>{let c=TA(e,i,t?r*Math.PI/2:0,t?Math.PI:r*Math.PI/2,n,this.axis);return o!==null&&(c.scale=o),c.clip=s,this.singleStyle||(c.style=hs(a)),c})}getFans(e){return this.computedFans.map(({computed:t,traits:n})=>this.makeStyledLine(e,t,n))}getElements(){if(this.unit===null)return[];let[e,t]=this.getReversedScreenPoints(),n=this.getGridLines(e,t),r=this.getArcs(e),i=this.getFans(e);return[...n,...r,...i]}getOrientation(){let[e,t]=this.getReversedScreenPoints(),n=t.x<e.x,r=t.y<e.y;return{flipX:n,signX:n?-1:1,flipY:r,signY:r?-1:1}}getClipPath(){let[e,t]=this.getReversedScreenPoints(),n=new Path2D;return Ao(n,e,t),n}adornElements(e,t){if(e.length===0)return;let n=(e,n,r)=>{t.fillStyle=r;let i=n.hasScale;i&&(t.save(),n.applyScale(t)),t.fill(e),i&&t.restore()};if(this.showBackground){let r=e.filter(e=>e.radius),i=this.getClipPath();if(t.save(),t.clip(i),this.singleStyle){let e=Se(r);n(DA(null,e),e,this.applyBackgroundOpacity(this.traits.line.color))}else{let e=null;r.forEach(t=>{let r=DA(e,t),i=t.style.fillStyle;n(r,t,i),e=t})}t.restore()}if(this.showRangesRatio&&this.unit!==null){let e=Se(this.computedLevels),n=(this.singleStyle?this:e).traits.line.color,[,r,i,a]=this.getReversedScreenPoints(),{x:o,y:s}=B.DEFAULT_ADORN_OFFSET,{flipX:c,signX:l,signY:u}=this.getOrientation(),d=oo(i,{x:-o*l,y:s*u}),{priceDiff:f,barsDiff:p}=this.getLinesDataAtLevels(null,null),m=c?T.Right:T.Left;Fo(t,p.toFixed(0),d,m,n);let h=oo(a,{x:o*2*l,y:-s*u}),g=c?T.Left:T.Right;Fo(t,this.formatter.format(f,G.Close),h,g,n);let _=oo(r,{x:-o*l,y:-s*u});Fo(t,this.priceBarRatio.toFixed(6),_,m,n)}}resetComputedState(){if(this.lines=void 0,this.points.length===4&&this.unit!==null){let{priceDiff:e,barsDiff:t}=this.getLinesDataAtLevels(null,null);this.priceBarRatio=Math.abs(e/t)}}updateFrom(e,t,n,r,i){if(super.updateFrom(e,t,n,r,i),this._parsedFans=this._parsedArcs=null,!rj(e.priceBarRatio,this.priceBarRatio)){let[t,n,,]=this.points;this.reverse&&([t,n]=[n,t]);let{priceDiff:r,barsDiff:i}=this.getLinesDataAtLevels(null,null);n.update(t.price+Math.sign(r)*e.priceBarRatio*i,n.time),this.resetComputedState()}}getFlipAnchorIndices(){return[0,1]}},aj=5,oj=(e,t)=>{let n=new Path2D;return e===null?n:(Oo(n,e.p1),ko(n,e.p2),ko(n,t.p2),ko(n,t.p1),n)},sj=class extends pk{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[B.AT_EXTEND_PT_1]}get extend2(){return this.traits[B.AT_EXTEND_PT_2]}getElements(){let[e,t,n]=this.getScreenPoints(),{x:r,y:i}=ao(n,e),a=n=>{let[r,i]=[e,t].map(e=>oo(e,n));return new uk(r,i,this.extend1,this.extend2,this.axis)};return this.getColoredElements(({value:e})=>a({x:r*e,y:i*e}))}getTextRef(){return(e,t,n)=>({ref:t,spacing:aj,offsetY:!0,text:this.formatLevelPrice(n,t.anchor1.y)})}adornElements(e,t){this.adornElementsForColoredFactors(e,oj,this.getTextRef(),t)}},cj=class extends fk{levelSize=0;alignLeft=!0;totalVolume=!1;widthPercent=30;useChange=!1;studyPlotId;gotData;boxes=[];periodType=`VisibleScreen`;period=0;valueRangePercent=.7;levelMode=`Count`;usesFinerGrainedAgg=!0;constructor(e,t,n){super(e,t),this.computed=!0,this.studyPlotId=n,this.gotData=!1}setOptions(e){switch(this.levelMode=e.LevelMode,this.levelSize=xt(1,1e3,e.LevelSize),this.alignLeft=e.Position===`Left`,this.totalVolume=e.Volume===`Total`,this.widthPercent=xt(5,100,e.WidthPercent)/100,e.BarColoring){case`OpenToClose`:this.useChange=!1;break;case`CloseToClose`:this.useChange=!0;break;default:{let e=this.presenter.mainPlot?.mainCurve?.attributes;this.useChange=e?.includes(m.ChangeBased)??!1}}N(e.PeriodType)&&(this.periodType=e.PeriodType),this.period=e.Period,this.valueRangePercent=e.ValueRangePercent/100;let t=ne[$()?.config.mode??`Unspecified`];this.usesFinerGrainedAgg=lc(t)}get isCountMode(){return this.levelMode===`Count`}updateLastBox(){if(this.boxes.length>0){let e=this.boxes.pop(),t=this.getDataForRange(e.firstDate,e.lastDate);t&&this.boxes.push(t)}}invalidate(e){switch(this.periodType){case`VisibleScreen`:this.gotData=!1,this.boxes=[];break;case`Bars`:case`Days`:switch(e){case`DataPointAdded`:{let e=this.studySeries.innCont(0)?.getTimeData();if(!P(e))return;let t=e[e.length-1],n=this.boxes.length>0?this.boxes[this.boxes.length-1]:null;if(N(n)&&t.valueOf()<n.lastDate.valueOf())this.updateLastBox();else{let e=this.getDataForRange(t,this.getBoxEndFromStart(t));e&&this.boxes.push(e)}break}case`DataPointChanged`:this.updateLastBox();break;case`NewChunkArrived`:this.gotData=!1;break}break}}getBoxRect(e){switch(this.periodType){case`VisibleScreen`:return this.axis.pane.getBoundsWithoutScales();case`Bars`:case`Days`:{let t=this.axis.pane.presenter.view.xAxis.xScale.bar,n=this.axis.toY(e.min),r=this.axis.toY(e.max),i=this.axis.pane.presenter.view.toX(e.firstDate)-t.width/2,a=0;if(this.periodType===`Days`){let n=e.lastDate,r=this.axis.pane.presenter.view.xAxis.xScale.timeline,o=r.at(r.lastSeriesIndex),s=o.valueOf()<n.valueOf(),c=s?o:n,l=(s?1:-2)*t.width/2;a=this.axis.pane.presenter.view.toX(c)+l-i}else a=this.period*t.width+(this.period-1)*t.spacing;return new Eo(i,r,a,n-r)}default:throw Error(`Unexpected period type for Volume At Price annotation`)}}getElementsForBox(e){let t=this.getBoxRect(e),n=[];if(this.isPeriodic){let e=new dk({x:t.x,y:t.y},t.width,t.height,this.axis);e.style=this.backgroundStyle,n.push(e)}let{x:r,width:i}=t,a=i*this.widthPercent,o=e.bars[e.maxVolumeIndex];return e.bars.forEach((t,s)=>{let{upVolume:c,downVolume:l,totalVolume:u,isValue:d}=t;if(c===0&&l===0)return null;let f=this.axis.toY(e.min+s*e.zone),p=this.axis.toY(e.min+(s+1)*e.zone),m=Math.abs(f-p),h=(e,t,n=0)=>{let a=new dk({x:this.alignLeft?r+n:r+i-e-n,y:p},e,m,this.axis);return a.style=t,a},g=(e,t,n)=>e/t.totalVolume*n,_=this.studyPlot.curves[2].visible,v=_&&d?this.upValueStyle:this.upStyle,y=_&&d?this.downValueStyle:this.downStyle,b=_&&d?this.totalValueStyle:this.totalStyle;if(this.totalVolume){let e=g(u,o,a);n.push(h(e,b))}else{let e=g(l,o,a),t=g(c,o,a);n.push(h(t,v),h(e,y,t))}if(this.studyPlot.curves[1].visible&&s===e.maxVolumeIndex){let e=n[n.length-1].rect,t=this.alignLeft?e.x+e.width:r,a=(p+f)/2,o=this.alignLeft?r+i:e.x;n.push(new uk({x:t,y:a},{x:o,y:a},!1,!1,this.axis))}}),n}get isVisible(){return super.isVisible&&this.studyPlot.isVisible&&this.studyPlot.mainCurve.visible}getElements(){if(this.gotData||this.getData(),!this.gotData||!this.isVisible||this.boxes.length===0)return[];switch(this.periodType){case`VisibleScreen`:{let e=this.boxes[0];return!e||e.bars.length===0?[]:this.getElementsForBox(e)}case`Bars`:case`Days`:{let[e,t]=this.presenter.view.xAxis.xScale.domain()||[];if(!Fn(e)||!Fn(t))return[];let n=this.boxes.findIndex(t=>t.firstDate.getTime()<=e.getTime()&&t.lastDate.getTime()>=e.getTime());n===-1&&(n=0,this.studySeries.loadMoreData());let r=this.boxes.findIndex(e=>e.firstDate.getTime()<=t.getTime()&&e.lastDate.getTime()>=t.getTime());r===-1&&n!==-1&&(r=this.boxes.length-1);let i=[];for(let e=n;e<=r;e++)i.push(...this.getElementsForBox(this.boxes[e]));return i}default:throw Error(`Unexpected period type for Volume At Price annotation`)}}getStyleForElement(e,t){return e.style||super.getStyleForElement(e,t)}get presenter(){return this.axis.pane.presenter}get downStyle(){return this.fillOnlyStyle(B.AT_FILL)}get upStyle(){return this.fillOnlyStyle(B.AT_FILL2)}get totalStyle(){return this.fillOnlyStyle(B.AT_FILL3)}get downValueStyle(){return this.fillOnlyStyle(B.AT_FILL4)}get upValueStyle(){return this.fillOnlyStyle(B.AT_FILL5)}get totalValueStyle(){return this.fillOnlyStyle(B.AT_FILL6)}get backgroundStyle(){return this.fillOnlyStyle(B.AT_FILL7)}get lineStyle(){return this.lineOnlyStyle(B.AT_LINE)}getBoxEndFromStart(e){switch(this.periodType){case`VisibleScreen`:default:return null;case`Days`:return rr(ng(g.Day,this.period)(e),1);case`Bars`:{let t=this.axis.pane.presenter.data.aggregation;return rr(ng(t.unit,t.size*this.period)(e),1)}}}getData(){let e=this.axis.pane.presenter.data.aggregation;if(e.isTick||e.hasSpec&&!XT(e.spec))return;let[t,n]=this.presenter.view.xAxis.xScale.domain()||[];if(!Fn(t)||!Fn(n))return;let r=ng(e.unit,e.size);switch(this.periodType){case`VisibleScreen`:{let e=this.boxes[0];if(!e||e.firstDate!==t||e.lastDate!==n){let e=this.getDataForRange(t,n);e&&(this.boxes[0]=e)}else this.gotData=!0;break}case`Bars`:{let[e,t]=[0,1].map(e=>this.studySeries.innCont(e));if((e?.size??0)<1||(t?.size??0)<1)return;let n=e.getTimeData(),i=0;for(this.boxes=[];i<n.length;){let e=n[i],t=i+this.period,a=rr(t<n.length?n[t]:r(n[n.length-1]),1),o=this.getDataForRange(e,a);o&&this.boxes.push(o),i+=this.period}this.gotData=!0;break}case`Days`:{if(e.isEndOfDay){this.boxes=[],this.gotData=!0;return}let[t,n]=[0,1].map(e=>this.studySeries.innCont(e));if((t?.size??0)<1||(n?.size??0)<1)return;let i=t.getTimeData(),a=t.getData(G.TradingDay),o=e=>{let t=0,n=i[e],r=a[e];for(let o=e;o<i.length;o++)if(bn(i[o],n)>0&&a[o]!==r&&(t+=1,n=i[o],r=a[o],t===this.period))return o;return-1},s=0,c=i[s],l=o(s)-1;for(;(l<0||l===s)&&s<i.length;)s+=1,l=o(s)-1;for(this.boxes=[];s<i.length&&l<i.length&&s<l;){let e=rr(r(i[l]),1),t=this.getDataForRange(c,e);t&&this.boxes.push(t),s=l+1,c=i[s],l=o(s)-1}if(l<0&&s<i.length-1){let e=rr(r(i[i.length-1]),1),t=this.getDataForRange(i[s],e);t&&this.boxes.push(t)}this.gotData=!0;break}}}getBoxAt(e){if(this.boxes.length===0)return null;switch(this.periodType){case`VisibleScreen`:{let t=this.boxes[0];return t.firstDate>e||t.lastDate<e?null:t}case`Bars`:case`Days`:{let t=e.getTime();return this.boxes.find(e=>e.firstDate.getTime()<=t&&e.lastDate.getTime()>=t)||null}}}getValueAt(e,t,n){if(!this.isVisible)return null;let r=this.getBoxAt(t);if(!r)return null;let i=this.getBarIndex(r,n);if(i<0||i>=r.bars.length)return null;let a=r.bars[i];switch(e){case G.UPVOL:return this.totalVolume?null:a.upVolume;case G.DNVOL:return this.totalVolume?null:a.downVolume;case G.TOTVOL:return this.totalVolume?a.totalVolume:null;case G.POC:case G.VAREA:case G.BARBACK:return null;default:throw Error(`Unexpected Volume At Price field`)}}getBarIndex(e,t,n=!1){if(e.bars.length===0||e.zone===0)return-1;let r=Math.floor((t-e.min)/e.zone);return n?Math.min(e.bars.length-1,r):r}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get studySeries(){return this.studyPlot.timeSeries}makeBox(e,t){return{min:Number.MAX_VALUE,max:Number.MIN_VALUE,zone:0,bars:[],maxVolumeIndex:-1,firstDate:e,lastDate:t}}findExtremes(e,t,n,r,i,a){let o=N(i)&&N(a);for(let s=t;s<=n;s++)if(o){let t=i[s];t>e.max&&(e.max=t);let n=a[s];n<e.min&&(e.min=n)}else{let t=r[s];t<e.min&&(e.min=t),t>e.max&&(e.max=t)}}findValueArea(e){if(e.maxVolumeIndex===-1||e.bars.length===0)return;e.bars[e.maxVolumeIndex].isValue=!0;let t=pe(e.bars.map(e=>e.totalVolume))*this.valueRangePercent,n=e.bars[e.maxVolumeIndex].totalVolume,r=e.maxVolumeIndex,i=e.maxVolumeIndex;for(;n<t;){let a=[{dir:`lower`,count:2,startIdx:r-2,endIdx:r-1},{dir:`lower`,count:1,startIdx:r-1,endIdx:r-1},{dir:`upper`,count:2,startIdx:i+1,endIdx:i+2},{dir:`upper`,count:1,startIdx:i+1,endIdx:i+1}].filter(t=>t.startIdx>=0&&t.endIdx<e.bars.length).map(t=>{let r=pe(e.bars.slice(t.startIdx,t.endIdx+1).map(e=>e.totalVolume));return{...t,volume:r,newTotal:n+r}});if(a.length===0)break;let o=(e,t)=>t.newTotal<e.newTotal?t:e,s=(e,t)=>t.volume>e.volume?t:e,c=a.filter(e=>e.newTotal>=t),l=c.length>0?c.reduce(o):a.reduce(s);for(let t=l.startIdx;t<=l.endIdx;t++)e.bars[t].isValue=!0;if(l.dir===`lower`?r=l.startIdx:i=l.endIdx,n=l.newTotal,n>=t)break}}tallyVolume(e,t,n,r,i,a,o){let s=Number.MIN_VALUE,c=!1;for(let l=t;l<=n;l++){let t=i[l],n=this.getBarIndex(e,t,!0);if(n===-1){c=!0;break}let u=o[l],d=this.useChange?a[l]>=0:r[l]<=i[l],f=e.bars[n];d?f.upVolume+=u:f.downVolume+=u,f.totalVolume=f.downVolume+f.upVolume,f.totalVolume>s&&(s=f.totalVolume,e.maxVolumeIndex=n)}c||this.findValueArea(e)}get isPeriodic(){return this.periodType===`Bars`||this.periodType===`Days`}get isVisibleScreen(){return this.periodType===`VisibleScreen`}getDataForRange(e,t){let n=this.makeBox(e,t),r=this.studySeries.innCont(1),i=r?.getTimeData();if(!P(i)||i.length===0)return null;let a=e=>j(i,+e,Number),o=a(e),s=a(t);if(s<0||s>=i.length||o<0||o>=i.length)return null;let c=i[s];if(!P(c)||(c.getTime()>t.getTime()&&--s,s<0)||o>s)return null;if(this.axis.pane.presenter.data.aggregation.unit===g.Day&&this.periodType===`Bars`){let e=r.getData(G.TradingDay),t=e[o];for(;t===e[o]&&o>0;)--o;o+=1;let n=0;for(s=o;s<i.length&&n<this.period;)e[s]!==t&&(n+=1,t=e[s]),s+=1;s-=2}this.isVisibleScreen&&this.usesFinerGrainedAgg&&o<1e3&&this.studySeries.loadMoreData();let l=e=>r.getData(e),[u,d,f,p,m,h]=[`Open`,`High`,`Low`,`Close`,`Change`,`Volume`].map(e=>l(G[e]));this.findExtremes(n,o,s,p,d,f);let _=n.max-n.min,v=e=>({upVolume:0,downVolume:0,isValue:!1,totalVolume:0});if(this.isCountMode)n.zone=_/this.levelSize,n.bars=De(this.levelSize,v);else{let e=(this.presenter.mainPlot?.metaData.minMovement??1)*this.levelSize,t=Math.max(1,Math.ceil(_/e));n.zone=_/t,n.bars=De(t,v)}return this.tallyVolume(n,o,s,u,p,m,h),this.gotData=!0,n}},lj=[`None`,`Absolute`,`Percent`],uj=`#16A34A`,dj=`#DC2626`;function fj(e){return typeof e==`string`&&lj.includes(e)}var pj=class extends fk{studyPlotId;displayMode=`None`;visibleLabelSegments=[];constructor(e,t,n){super(e,t),this.studyPlotId=n}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get studySeries(){return this.studyPlot.timeSeries}setOptions(e){let t=e.ReversalChange;this.displayMode=fj(t)?t:`None`}formatSegmentValue(e,t){return this.displayMode===`Absolute`?this.formatter.format(t-e,G.Close):this.displayMode===`Percent`?e===0?``:this.formatter.format((t-e)/e,G.PercentChange):``}getElements(){if(this.visibleLabelSegments=[],!this.studyPlot.isVisible||!this.studyPlot.mainCurve.visible)return[];let e=this.studySeries.getCurrentState();if(!e)return[];let t=e.confirmedPivots,n=Array.from(t.keys()).sort((e,t)=>e-t);if(n.length===0)return[];let r=this.presenter.mainPlot?.timeSeries?.container;if(!r||r.size<2)return[];let i=r.getTimeData();if(!i)return[];let a=this.presenter.view,[o,s]=a.xAxis.xScale.domain()||[];if(!o||!s)return[];let c=o.getTime(),l=s.getTime(),u=-1,d=-1;for(let e=0;e<n.length;e++){let t=i[n[e]].getTime();if(u===-1&&t>=c&&(u=Math.max(0,e-1)),t<=l)d=e;else if(u!==-1)break}if(u===-1){if(n.length>0&&i[n[0]].getTime()>l)return[];u=n.length-1,d=n.length-1}else d===-1&&(d=u);d=Math.min(n.length-1,d+1);let f=[];for(let e=u;e<d;e++){let r=n[e],o=n[e+1],s=t.get(r),u=t.get(o),d=a.toX(i[r]),p=this.axis.toY(s),m=a.toX(i[o]),h=this.axis.toY(u);f.push(this.makeLine({x:d,y:p},{x:m,y:h}));let g=i[o].getTime();g>=c&&g<=l&&this.visibleLabelSegments.push({fromPrice:s,toPrice:u,toPoint:{x:m,y:h}})}if(P(e.pivotPrice)&&P(e.candPrice)){let t=i[e.pivotIndex].getTime();if(i[e.candIndex].getTime()>=c&&t<=l){let t=a.toX(i[e.pivotIndex]),n=this.axis.toY(e.pivotPrice),r=a.toX(i[e.candIndex]),o=this.axis.toY(e.candPrice);f.push(this.makeLine({x:t,y:n},{x:r,y:o}))}}return f}adornElements(e,t){if(this.displayMode===`None`||this.visibleLabelSegments.length===0)return;let n=Math.abs(Mo(t,!0));this.visibleLabelSegments.forEach(e=>{let r=this.formatSegmentValue(e.fromPrice,e.toPrice);if(r===``)return;let i=e.toPrice>=e.fromPrice;Fo(t,r,{x:e.toPoint.x,y:e.toPoint.y+(i?-n:n)},T.Right,i?uj:dj)})}},mj=[B.AT_LINE,B.AT_LINE_2,B.AT_LINE_3],hj=class extends fk{studyPlotId;constructor(e,t,n){super(e,t),this.studyPlotId=n}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get studySeries(){return this.studyPlot.timeSeries}isCurveVisible(e){return this.studyPlot.curves[e]?.visible??!1}getChannelPrices(){let e=this.studySeries.getCurrentState();if(!e)return null;let{startIndex:t,endIndex:n,slope:r,intercept:i,stdDevWidth:a}=e;if(!N(t)||!N(n)||!N(r)||!N(i)||!N(a)||!Ze(r)||!Ze(i)||!Ze(a))return null;let o=n-t+1;if(o<1)return null;let s=e=>i+r*(e+1),c=s(0),l=s(o-1);return{start:[c+a,c,c-a],end:[l+a,l,l-a]}}makeLines(){if(!this.studyPlot?.isVisible)return null;let e=this.studySeries.getCurrentState(),t=this.getChannelPrices();if(!e||!t)return null;let{startIndex:n,endIndex:r,extendLeft:i,extendRight:a}=e;if(!N(n)||!N(r))return null;let o=this.studyPlot.basePlot?.timeSeries?.container??this.presenter.mainPlot?.timeSeries?.container;if(!o||o.size<2)return null;let s=o.getTimeData();if(!s||s.length<=r)return null;let c=this.presenter.view,[[l,u,d],[f,p,m]]=[t.start,t.end],h=c.toX(s[n]),g=c.toX(s[r]),_=(e,t,n)=>{let r=this.axis.toY(e),o=this.axis.toY(t),s=new uk({x:h,y:r},{x:g,y:o},i,a,this.axis);return s._data={lineIndex:n},s};return[_(l,f,0),_(u,p,1),_(d,m,2)]}getStyleForElement(e,t){let n=mj[e._data?.lineIndex??t],r=this.traits[n];return r?hs({line:r,fill:{color:B.COLOR_TRANSPARENT}}):super.getStyleForElement(e,t)}getElements(){let e=this.makeLines();return e?e.filter((e,t)=>this.isCurveVisible(t)):[]}getPriceScaleAdornments(){let e=this.getChannelPrices();if(!e)return[];let t=[this.traits?.[B.AT_LINE]?.color,this.traits?.[B.AT_LINE_2]?.color,this.traits?.[B.AT_LINE_3]?.color];return e.end.map((e,n)=>({price:e,color:t[n]??this.traits?.line?.color??`#000`}))}getDomainPrices(){let e=this.getChannelPrices();return e?[...e.start,...e.end]:[]}adornElements(e,t){let n=this.makeLines();if(!n||!n.every(e=>P(e.p1,e.p2)))return;let[r,i,a]=n,o=(e,n,r)=>{t.fillStyle=r,t.fill(oj(e,n))};this.isCurveVisible(3)&&o(r,i,this.traits?.[B.AT_FILL]?.color),this.isCurveVisible(4)&&o(i,a,this.traits?.[B.AT_FILL2]?.color)}},gj=class extends fk{studyPlotId;constructor(e,t,n){super(e,t),this.studyPlotId=n,this.computed=!0}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get isVisible(){return this.visible&&(this.studyPlot?.isVisible??!1)}getDomainPrices(){let e=this.studyPlot,t=e?.timeSeries;if(!e||!this.isVisible||!t?.hasData)return[];let n=t.base.getTimeData();return t.getPeriods().flatMap(t=>e.curves.flatMap(e=>{if(!e.visible)return[];let r=this.presenter.view?.xAxis?e.shiftedTimeDomain:null;if(r&&(n[t.endIndex]<r[0]||n[t.startIndex]>r[1]))return[];let i=e.fields[0],a=t.levels[i.id];if(a==null||!Number.isFinite(a))return[];let o=this.axis.priceMap(a);return o!=null&&Number.isFinite(o)?[o]:[]}))}getElements(){let e=this.studyPlot,t=e?.timeSeries,n=this.presenter.view?.xAxis?.xScale;if(!this.isVisible||!e||!t?.hasData||!n?.range())return[];let r=t.base.getTimeData(),[i,a]=n.range(),o=n.bar.totalWidth/2,s=[],c=!1;for(let l of t.getPeriods()){let u=n.timeToIndex(r[l.startIndex]),d=n.timeToIndex(r[l.endIndex]);u==null||d==null||e.curves.forEach((e,r)=>{if(!e.visible)return;let f=n.indexToX(u+e.shift)-o,p=n.indexToX(d+e.shift)+o;if(p<i||f>a)return;t.hasHistoryFor(l.key)||(c=!0);let m=e.fields[0],h=l.levels[m.id];if(h==null||!Number.isFinite(h))return;let g=this.axis.priceMap(h);if(g==null||!Number.isFinite(g))return;let _=e.priceToY(g),v=new uk({x:f,y:_},{x:p,y:_},!1,!1,this.axis);v._data={curveIndex:r,startIndex:l.startIndex,price:h},s.push(v)})}return c&&t.loadMoreData(),s}getStyleForElement(e){let t=this.studyPlot.curves[e._data.curveIndex];return hs({line:{color:t.getColor(e._data.startIndex),width:t.lineWidth,dashStyle:t.dashStyle},fill:{color:B.COLOR_TRANSPARENT}})}adornElements(e,t){let n=this.studyPlot,[r,i]=this.presenter.view.xAxis.xScale.range(),a=Math.abs(Mo(t,!0)),o={};Bv(n,this.presenter,o);for(let s of e){let e=s,{curveIndex:c,startIndex:l,price:u}=s._data,d=n.curves[c],f=n.metaData.format(u,d.fields[0],o),p=Math.max(r,e.p1.x),m=Math.min(i,e.p2.x);t.measureText(f).width+8>m-p||Fo(t,f,{x:p+4,y:e.p1.y-a},T.Left,d.getColor(l))}}};function _j(e){let t=e<0?-1:1,n=Math.abs(e)/Math.SQRT2,r=1/(1+.3275911*n);return .5*(1+t*(1-((((1.061405429*r+-1.453152027)*r+1.421413741)*r+-.284496736)*r+.254829592)*r*Math.exp(-n*n)))}var vj=class extends fk{studyPlotId;periodTarget=0;targetPrice1=0;targetPrice2=0;pricesCount=0;targetDate;computed=!1;anchorPrice=0;sigmaAnnualized=0;unitsPerYear=0;probabilityAbove=0;probabilityBelow=0;probabilityBetween=0;styles=[];constructor(e,t,n){super(e,t),this.studyPlotId=n}makeStyles(){let e=this.lineOnlyStyle(B.AT_LINE),t=this.lineOnlyStyle(B.AT_LINE_2);this.styles=[e,t,t]}containerOf(e){return e?.timeSeries.container}get mainCont(){return this.containerOf(this.presenter.mainPlot)}get studyCont(){return this.containerOf(this.studyPlot)}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get targetPrice(){return this.targetPrice1===0?this.targetPrice2:this.targetPrice1}setOptions(e){if(this.periodTarget=e.PeriodTarget,this.targetPrice1=e.TargetPrice1,this.targetPrice2=e.TargetPrice2,this.pricesCount=(this.targetPrice1===0?0:1)+(this.targetPrice2===0?0:1),this.pricesCount>1&&this.targetPrice1<this.targetPrice2){let e=this.targetPrice1;this.targetPrice1=this.targetPrice2,this.targetPrice2=e}}get haveInput(){return this.periodTarget!==0&&(this.targetPrice1!==0||this.targetPrice2!==0)}get haveData(){return N(this.mainCont)&&!this.mainCont.isEmpty&&this.studySeries.haveVolatility}get studySeries(){return this.studyPlot.timeSeries}getData(){let e=this.presenter.timeline;this.targetDate=e.at(e.lastSeriesIndex+this.periodTarget),this.points=[new ik(this.axis,this.targetPrice,this.targetDate)],this.pricesCount>1&&this.points.push(new ik(this.axis,this.targetPrice2,this.targetDate)),this.unitsPerYear=_O(this.presenter.data.aggregation),this.anchorPrice=this.mainCont.getLastDataPoint(G.Close),this.sigmaAnnualized=this.studySeries.getVolatilityPercent()}computeProbabilities(){let e=this.sigmaAnnualized*Math.sqrt(this.periodTarget/this.unitsPerYear),t=t=>(t-this.anchorPrice)/(this.anchorPrice*e),n=_j(t(this.targetPrice));if(this.pricesCount>1){let e=_j(t(this.targetPrice2));this.probabilityAbove=1-n,this.probabilityBelow=e,this.probabilityBetween=n-e}else this.probabilityBelow=n,this.probabilityAbove=1-this.probabilityBelow;this.computed=!0}compute(){!this.haveInput||!this.haveData||(this.getData(),this.computeProbabilities())}getElements(){if(this.computed||this.compute(),!this.computed||!this.studyPlot.isVisible||!this.studyPlot.mainCurve.visible)return[];let e=[];return e.push(new rk(this.points[0].point,!0,this.axis)),e.push(new rk(this.points[0].point,!1,this.axis)),this.pricesCount>1&&e.push(new rk(this.points[1].point,!1,this.axis)),e}getStyleForElement(e,t){return this.styles.length||this.makeStyles(),this.styles[t]}get hasPoint(){return this.points.length>0}getTimeScaleAdornments(){return this.hasPoint?[{time:this.points[0].time,color:this.traits.line.color}]:[]}getPriceScaleAdornments(){if(!this.hasPoint)return[];let e=[];return e.push({price:this.points[0].price,color:this.traits.line2.color}),this.pricesCount>1&&e.push({price:this.points[1].price,color:this.traits.line2.color}),e}adornElements(e,t){if(this.computed){let[e,n]=[!0,!1].map(e=>Math.abs(Mo(t,e))),r=this.pricesCount>1,i=this.points[0].point,a=r?this.points[1].point:i,o=this.traits.line2.color,s=xo(o),c=jo(t),l=[`Above`,`Below`,`Between`],u=(e,t)=>`${Xe(e*100,2).toFixed(2)}% Probability ${l[t]}`,d=(e,n)=>Fo(t,e,n,T.Right,s,o);if(d(u(this.probabilityAbove,0),{x:i.x-10,y:i.y-e}),r){let e=i.y+(a.y-i.y+c)/2;d(u(this.probabilityBetween,2),{x:i.x-10,y:e})}d(u(this.probabilityBelow,1),{x:a.x-10,y:a.y+n})}}},yj=new iA,bj=e=>Ej(aA,IA,1,e),xj=e=>Ej(aA,xk,1,e),Sj={Default:()=>function(){return yj},Line:()=>Ej(Ck,fA,!1),DateRange:()=>Ej(Ck,ZA,!1),PriceRange:()=>Ej(Ck,QA,!1),DatePriceRange:()=>Ej(Ck,$A,!1),GannBox:()=>Ej(Ck,ej,!1),GannSquare:()=>Ej(Tk,ij),Ray:()=>Ej(Ck,fA,!1),GannLine:()=>Ej(wk,fA,!1),VerticalLine:()=>Ej(aA,pA,1),HorizontalLine:()=>Ej(aA,mA,1),LongPosition:()=>Ej(aA,YA,1,!0),ShortPosition:()=>Ej(aA,YA,1,!1),FiftyPercentLine:function(e,t){return P(e)?Ej(oA,hA,e.axis||t.mainAxis,e):Ej(aA,hA,2)},FibonacciRetracement:()=>Ej(Ck,vA,!1),TrendBasedFibExtension:()=>Ej(Ck,yA,!0),FibonacciFan:()=>Ej(Ck,CA,!1),FibonacciArcs:()=>Ej(Ck,kA,!1),FibonacciChannel:()=>Ej(Ck,sj,!0),GannFan:()=>Ej(Ck,AA,!1),SpeedResistanceFan:()=>Ej(Ck,jA,!1),SpeedResistanceArcs:()=>Ej(Ck,MA,!1),AndrewsPitchfork:()=>Ej(aA,NA,3),Rectangle:()=>Ej(Ck,Yk,!1),Ellipse:()=>Ej(Ck,PA,!1),TrendChannel:()=>Ej(Ck,FA,!0),SymbolArrowUp:()=>bj(`arrow_up`),SymbolArrowDown:()=>bj(`arrow_down`),SymbolArrowRight:()=>bj(`arrow_right`),SymbolArrowLeft:()=>bj(`arrow_left`),SymbolArrowHorizontal:()=>bj(`arrow_horizontal`),SymbolArrowVertical:()=>bj(`arrow_vertical`),SymbolArcDown:()=>bj(`arc_down`),SymbolArcUp:()=>bj(`arc_up`),SymbolThumbsUp:()=>bj(`thumbs_up`),SymbolThumbsDown:()=>bj(`thumbs_down`),SymbolZero:()=>bj(`zero`),SymbolOne:()=>bj(`one`),SymbolTwo:()=>bj(`two`),SymbolThree:()=>bj(`three`),SymbolFour:()=>bj(`four`),SymbolFive:()=>bj(`five`),SymbolSix:()=>bj(`six`),SymbolSeven:()=>bj(`seven`),SymbolEight:()=>bj(`eight`),SymbolNine:()=>bj(`nine`),SymbolQuestion:()=>bj(`question`),SymbolFishHook:()=>bj(`fish_hook`),SymbolLetterB:()=>bj(`letter_b`),SymbolLetterS:()=>bj(`letter_s`),SymbolLetterA:()=>bj(`letter_a`),SymbolLetterC:()=>bj(`letter_c`),SymbolLetterD:()=>bj(`letter_d`),SymbolLetterE:()=>bj(`letter_e`),FibonacciTimeZones:()=>Ej(Ck,LA,!1),Text:()=>Ej(Ek,bk,null),PickPoint:()=>function(){return new RA},ZoomIn:()=>function(){return new Qk},ProfitLoss:xj,RewardRisk:xj,VolumeAtPrice:function(e){return Ej(aA,cj,2,e)},ZigZag:function(e){return Ej(oA,pj,null,e)},ProbabilityCones:function(e){return Ej(aA,vj,2,e)},LinearRegressionChannel:function(e){return Ej(oA,hj,null,e)},PivotPoints:function(e){return Ej(oA,gj,null,e)}};function Cj(e,t=!1,n=null,r=null,i=null){let a=Sj[e];return a=a(r,i),a(e,t,n)}function wj(e,t={}){e.enableTooltip(!0),e.resetActiveTool();let{axis:n,annotation:r,toolChange:i,annId:a}=t;P(n)&&e.onAnnotationsUpdated(n),P(r)&&e.onAnnotationModifiedByTool(r,i),[O.Cancelled,O.Executed,O.TextChanged].includes(i)&&e.onAnnotationDone(a,i)}function Tj(e,t=!0,n=O.None){e.wasModifiedByTool();let r=e.axis,i={axis:r,annotation:e,toolChange:n};wj(r.pane.presenter,t?i:void 0)}function Ej(e,t,n,r){return function(i,a,o){let s=lk(i,t,r,o);return s.annName=i,a?s:new e(s,n)}}function Dj(e){e.button===E.Right&&wj(e.presenter)}function Oj(e,t,n){let r={};r.inputs=dt(e.inputs);let i=r.inputs[B.INPUT_SOURCE],a=N(i)?G[i]:void 0;r.source=G[e.source]??a;let o=e.target!==void 0,s=P(n)?n:e.curves;return r.outFields=Oe(o?[G[e.target]]:s.map(e=>e.fields).flat()),r.target=o?G[e.target]:r.outFields[0],r.aggregation=t,r}function kj(e){return Array.isArray(e.innerSeries)}function Aj(e){return e.query?.symbol===B.PLACEHOLDER_SYMBOL_NAME?!0:kj(e)?e.innerSeries.some(e=>Aj(e)):!1}var jj=class extends XO{model;basePlot;_hasEvents;_params;_shiftFmt;_title;range;shouldMaybePriceMap;annIndex;_canPriceMap;#e(e=3){let t=this.model.inputs||[],n=t.length;if(n===0)return``;let r=``;n>e&&(t=t.slice(0,3),r=`, ...`);let i=this.model.study===`AVWAP`;return t.length===0?``:`(${t.map(e=>i&&e.name===`Anchor`?new Date(e.value).toLocaleString():e.value).join(`, `)}${r})`}get params(){return P(this._params)||(this._params=this.#e()),this._params}get fullParams(){return this.#e(Number.MAX_VALUE)}get shiftFmt(){if([`PC`,`TARGP`].includes(this.model.study))return``;if(!P(this._shiftFmt)){let e=this.curves.map(e=>Number(e.shift)).filter(e=>e!==0);this._shiftFmt=e.length===0?``:`[${e.join(`, `)}]`}return this._shiftFmt}get title(){if(!P(this._title)){let e=this.params,t=this.shiftFmt;this._title=`${this.model.study} ${e} ${t}`.trim()}return this._title}getStandalonePaneTitle(){let e=this.getStandalonePaneBasisTitle();return e?`${this.title} on ${e}`:this.title}getStandalonePaneBasisTitle(){if(this.model?.basis?.kind!==`seasonal`)return null;let e=this.basePlot;if(!e?.isSeasonal)return null;let t=e;if(t.isFutures&&!t.hasComputation){let t=e.metaData?.symbol;if(typeof t==`string`&&t.length>0)return t}return e.title||null}fromModel(e){this.model=e,super.fromModel(this.model)}getMetaData(e){let t=e.meta.decimals;this.metaData=t===void 0?this.basePlot.metaData:new Wa(t),P(e.meta.range)&&(this.range=e.meta.range)}getDetachedScaleMargins(){return this.model?.study===`VOL`&&this.axis?.pane.isMain?B.VOLUME_DETACHED_SCALE_MARGINS:super.getDetachedScaleMargins()}applySpecifics(e){let t=this.model.study,n=V(t);n.meta.shiftable===!0&&this.curves.forEach(t=>{Number.isFinite(e.inputs.Offset)&&(t.shift=e.inputs.Offset)});let r=(e,t,n)=>this.curves[e].zones[t].value=this.model.levels[n].value;switch(t){case`PIVPTS`:{this.customPlotValues=!0;let e=Cj(`PivotPoints`,!0,null,this.id);this.annotations=[e(this.axis,!1)];break}case`ICHCLD`:{let t=e.inputs.Displacement;this.curves[2].shift=-t,this.curves[3].shift=t,this.curves[4].shift=t,this.curves[5].shift=t;break}case`MARIB`:{let t=Math.min(Math.max(0,e.inputs.Count),10);this.curves.forEach((e,n)=>e.visible=e.visible&&n<t);break}case`CRS`:{let t=e.inputs.Display===`PercentChange`;this.axis.comparison=t?x.Percent:x.None;break}case`PERF`:{let t=e.inputs.Anchor===`VisibleStart`;this.axis.comparison=t?x.Percent:x.None;break}case`HV`:e.inputs.Calculation===`Absolute`&&delete n.meta.decimals;break;case`JPI`:case`CTTP`:case`CTTI`:{let t=De(10,e=>(e+1)*.025),n=e=>t.map(t=>_o(t)(e)),r=([e,t])=>[...n(e).reverse(),t,`#6a4a3a`,`#a000c8`,`#ffffff`];this.curves[0].colors=r(this.curves[0].colors),this.curves[1].colors=r(this.curves[1].colors);let i=this.curves[0].colors.length;this.curves[0].colors[i-1]=this.curves[1].colors[t.length],this.curves[1].colors[i-1]=this.curves[0].colors[t.length],this.shouldMaybePriceMap=e.inputs.Height===`Performance`;break}case`RSI`:case`RSIMOD`:case`RSISTO`:case`CCI`:r(0,0,0),r(0,1,2);break;case`STC`:r(0,0,0),r(0,1,1);break;case`RVOL`:case`DPO`:case`COPP`:r(0,0,0);break;case`VOL`:this.setCurveAttributes(0,e.inputs.BarColoring);break;case`MAVOL`:this.setCurveAttributes(1,e.inputs.BarColoring);break;case`VOLAP`:{this.notifyAboutPriceDomains=!0,this.customPlotValues=!0,P(this.annotations)||(this.annotations=[]);let t=this.curves[1],n=this.curves[2],r=Cj(`VolumeAtPrice`,!0,{[B.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[B.AT_FILL]:{color:this.curves[0].colors[0]},[B.AT_FILL2]:{color:this.curves[0].colors[1]},[B.AT_FILL3]:{color:this.curves[0].colors[2]},[B.AT_FILL4]:{color:n.colors[0]},[B.AT_FILL5]:{color:n.colors[1]},[B.AT_FILL6]:{color:n.colors[2]}},this.id)(this.axis,!1);r.setOptions(e.inputs),this.annIndex=this.annotations.push(r)-1;break}case`PVACP`:{this.customPlotValues=!0,P(this.annotations)||(this.annotations=[]);let t=this.curves[1],n=this.curves[2],r=this.curves[3],i=Cj(`VolumeAtPrice`,!0,{[B.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[B.AT_FILL]:{color:this.curves[0].colors[0]},[B.AT_FILL2]:{color:this.curves[0].colors[1]},[B.AT_FILL3]:{color:this.curves[0].colors[2]},[B.AT_FILL4]:{color:n.colors[0]},[B.AT_FILL5]:{color:n.colors[1]},[B.AT_FILL6]:{color:n.colors[2]},[B.AT_FILL7]:{color:r.colors[0]}},this.id)(this.axis,!1);i.setOptions(e.inputs),this.annIndex=this.annotations.push(i)-1;break}case`ZIGZAG`:{this.customPlotValues=!0,P(this.annotations)||(this.annotations=[]);let t=Cj(`ZigZag`,!0,{[B.AT_LINE]:{color:this.curves[0].colors[0],width:this.curves[0].lineWidth,dashStyle:this.curves[0].dashStyle??`Solid`}},this.id)(this.axis,!1);t.setOptions(e.inputs),this.annIndex=this.annotations.push(t)-1;break}case`LINRCHN`:{this.customPlotValues=!0,P(this.annotations)||(this.annotations=[]);let e=this.curves[0],t=this.curves[1],n=this.curves[2],r=this.curves[3],i=this.curves[4],a=Cj(`LinearRegressionChannel`,!0,{[B.AT_LINE]:{color:e.colors[0],width:e.lineWidth,dashStyle:e.dashStyle??`Solid`},[B.AT_LINE_2]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle??`Solid`},[B.AT_LINE_3]:{color:n.colors[0],width:n.lineWidth,dashStyle:n.dashStyle??`Solid`},[B.AT_FILL]:{color:r.colors[0]},[B.AT_FILL2]:{color:i.colors[0]}},this.id)(this.axis,!1);this.annIndex=this.annotations.push(a)-1;break}case`IVRANK`:{let t=G.ImplVolRank1Y;switch(e.inputs.TimeFrame){case`1-Year`:default:break;case`5-Day`:t=G.ImplVolRank5D;break;case`1-Month`:t=G.ImplVolRank1M;break;case`3-Month`:t=G.ImplVolRank3M;break;case`6-Month`:t=G.ImplVolRank6M;break;case`YTD`:t=G.ImplVolRankYTD;break}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case`IVPCTL`:{let t=G.ImplVolPerc1Y;switch(e.inputs.TimeFrame){case`1-Year`:default:break;case`5-Day`:t=G.ImplVolPerc5D;break;case`1-Month`:t=G.ImplVolPerc1M;break;case`3-Month`:t=G.ImplVolPerc3M;break;case`6-Month`:t=G.ImplVolPerc6M;break;case`YTD`:t=G.ImplVolPercYTD;break}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case`OPTIV`:{let t=[G.WeighImplVolHigh,G.WeighImplVol,G.WeighImplVolLow];switch(e.inputs.TimeFrame){case`Implied Volatility`:default:break;case`5-Day Average IV`:t=[G.WeighImplVolHigh5D,G.WeighImplVol5D,G.WeighImplVolLow5D];break;case`1-Month Average IV`:t=[G.WeighImplVolHigh1M,G.WeighImplVol1M,G.WeighImplVolLow1M];break;case`3-Month Average IV`:t=[G.WeighImplVolHigh3M,G.WeighImplVol3M,G.WeighImplVolLow3M];break;case`6-Month Average IV`:t=[G.WeighImplVolHigh6M,G.WeighImplVol6M,G.WeighImplVolLow6M];break;case`1-Year Average IV`:t=[G.WeighImplVolHigh1Y,G.WeighImplVol1Y,G.WeighImplVolLow1Y];break;case`YTD Average IV`:t=[G.WeighImplVolHighYTD,G.WeighImplVolYTD,G.WeighImplVolLowYTD];break}this.curves[0].fields[0]=t[0],this.curves[1].fields[0]=t[1],this.curves[2].fields[0]=t[2],e.outFields=[...t];break}case`PC`:{let t=e.inputs.PeriodForecast-1;this.curves.forEach(e=>e.shift=t),P(this.annotations)||(this.annotations=[]);let n=this.curves[11],r=this.curves[12],i=Cj(`ProbabilityCones`,!0,{[B.AT_LINE]:{color:n.colors[0],width:n.lineWidth,dashStyle:n.dashStyle},[B.AT_LINE_2]:{color:r.colors[0],width:r.lineWidth,dashStyle:r.dashStyle}},this.id)(this.axis,!1);i.setOptions(e.inputs),this.annIndex=this.annotations.push(i)-1;break}case`TARGP`:this.curves.forEach(e=>e.shift=1);break}return n}getValueAt(e,t,n){return this.isVolAP?this.annotations[this.annIndex].getValueAt(e,t,n):super.getValueAt(e,t,n)}getColorOf(e){if(this.isPivotPoints)return this.curves.find(t=>t.fields.includes(e))?.colors[0]??null;if(!this.isVolAP&&!this.isZigZag&&!this.isLinRegChannel)return null;let t=this.curves[0].colors;if(this.isZigZag)return t[0];switch(e){case G.UPVOL:return t[1];case G.DNVOL:return t[0];case G.TOTVOL:return t[2];case G.POC:case G.VAREA:case G.BARBACK:return B.COLOR_TRANSPARENT;case G.LINRUP:return t[0];case G.LINRMID:return this.curves[1].colors[0];case G.LINRLOW:return this.curves[2].colors[0];default:throw Error(`Unexpected Volume At Price field`)}}isEmpty(){return this.isVolAP||this.isZigZag||this.isLinRegChannel||this.isPivotPoints?!1:super.isEmpty()}setCurveAttributes(e,t){let n=t=>this.curves[e].attributes=[m[t]];switch(t){case`LikeMain`:{let t=this.axis.pane.presenter.mainPlot.curves[0].attributes,r=$().config.defaultVolumeBarColoring;P(t)?this.curves[e].attributes=[t[0]]:P(r)?n(r===`OpenToClose`?`OpenVsClose`:`ChangeBased`):n(`OpenVsClose`);break}case`OpenToClose`:n(`OpenVsClose`);break;case`CloseToClose`:n(`ChangeBased`);break;default:throw Error(`Unexpected bar coloring choice: ${t}`)}}get hasEvents(){return!!this._hasEvents&&this.curves.every(e=>e.visible)}get eventsSeries(){return this.timeSeries}doesSeriesEmitEvents(){let e=this.timeSeries.helpers;return e.includes(G.Buy)||e.includes(G.Sell)}getEventFor(e){let t=this.model?.study===`PACROSS`||this.model?.study===`MACROSS`?this.curves[0]?.colors:void 0;switch(e){case G.Buy:return{show:!0,title:`B`,color:t?.[1]??`#03c03c`};case G.Sell:return{show:!0,title:`S`,color:t?.[0]??`#c23b22`};default:return null}}getEventFields(){return this.hasEvents?[G.Buy,G.Sell]:[]}getRefPlot(e){return this.axis?.pane.isMain&&this.basePlot?this.basePlot:super.getRefPlot(e)}#t(){return this.model.basis??{kind:`main`}}#n(e){let t=this.axis.pane.presenter.allPlots.find(t=>t.uid===e.uid&&t.isSeasonal&&t.offset===e.offset);if(P(t))return t;throw Error(`Unable to resolve seasonal basis plot for uid '${e.uid}' and offset '${e.offset}'`)}#r(){let e=this.#t();switch(e.kind){case`main`:return this.axis.pane.presenter.mainPlot;case`seasonal`:return this.#n(e);default:throw Error(`Unknown study basis kind '${e.kind}'`)}}async initialize(){return da.call(this,async()=>{this.basePlot=this.#r(),await this.basePlot.initialize();let e=this.axis.pane.presenter.data.aggregation,t=Oj(this.model,e,this.curves);if(this.basePlot.isSeasonal){let e=this.basePlot.mainCurve.fields[0];P(e)&&(t.source=e)}let n=this.applySpecifics(t);this.getMetaData(n);let r=this.basePlot.timeSeries;r instanceof db&&(r=r.actual),this.timeSeries=ND(this.model.study,t,r),this._hasEvents=this.doesSeriesEmitEvents(),this.timeSeries.useNotifications=!0;let i=this.title;return this.timeSeries.ready().then(e=>{let t=this.basePlot.timeSeries instanceof v_||Aj(this.timeSeries);!e&&!this.timeSeries.hasData&&!t&&!this.timeSeries.computedServerSide&&I(`Unable to calculate study values for ${i}`,`error`)}),!0})}get isJpi(){return[`JPI`,`CTTP`,`CTTI`].includes(this.model.study)}get isVolAP(){return this.model.study===`VOLAP`||this.model.study===`PVACP`}get isZigZag(){return this.model.study===`ZIGZAG`}get isLinRegChannel(){return this.model.study===`LINRCHN`}get isPivotPoints(){return this.model?.study===`PIVPTS`}invalidateAssociatedAnnotations(e){this.isVolAP&&this.annotations[this.annIndex].invalidate(e)}onPriceDomainsUpdated(){this.invalidateAssociatedAnnotations(`PriceDomainsChanged`)}shouldPriceMap(e){return this.isJpi?this.shouldMaybePriceMap?e.id===G.JPIB.id||e.id===G.JPIS.id:!1:super.shouldPriceMap(e)}canPriceMap(e,t){if(!this.isJpi)return super.canPriceMap(e,t);this._canPriceMap=e>0}priceMap(e,t,n){if(!this.isJpi)return super.priceMap(e,t,n);if(t>this.visToIndex)return e;let r=(e,t)=>this.timeSeries.container.getData(e)[t],i=r(G.JPIB,t),a=r(G.JPIS,t);if(i===null&&n.id===G.JPIB.id||a===null&&n.id===G.JPIS.id)return null;let o=0,s=this.visFromIndex,c=this.timeSeries.helpers[0],l=this.timeSeries.helpers[2];for(;s<=t;){let e=r(l,s);o+=e===1?0:r(c,s),s++}return o}},Mj=[G.Open,G.High,G.Low,G.Close,G.Volume],Nj=class extends XO{_expression;exprModel=null;symbols=null;errorText;get title(){return this.expression}get expression(){return this._expression}async parseExpression(){let e=bd(this._expression);if(this.exprModel=null,this.symbols=null,yd(e))this.errorText=e.error;else{let{model:t,clean:n,symbols:r}=e;this.errorText=void 0,this.symbols=r,this.exprModel=t,this._expression=n}}get isValid(){return!P(this.errorText)}#e(e){return{mapper:e=>e.query.symbol,loadMoreData:!0,recompute:d.Minimum,missing:u.UseNext,stretch:e=>!1,fieldMap:new Map(Mj.map(e=>[e,e])),noDataApproach:f.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:e}}getTimeSeries(){let e=this.getInnerSeries(),t=this.axis?.pane.presenter.data?.exprSkipLeadingEmpty??!1,n=new nb(this.exprModel,e,this.#e(t));this.timeSeries=this.wrapIfAdvancedStyle(n);let r=this.title;this.timeSeries.ready().then(e=>{e||I(`Unable to calculate expression: ${r}`,`error`)})}getInnerSeries(){let e=Td(this.exprModel),t=$().getTimeSeriesDataSource();return e.map(e=>{let n=this.makeQuery();return n.symbol=e,t.getTimeSeries(n)})}getRecord(){if(P(this.errorText))return;let e=this.metaData.inner.map(e=>[e.symbol,e.resolved]);this.record=new np(e,F(this.exprModel)),this.record.ready().then(e=>e)}getMetaData(){this.isValid&&(this.metaData=new Ka(this.symbols),this.metaData.ready().then(e=>{e&&(this.getRecord(),this.presenter?.notifyHost(K.MD_CHANGED,{plot:this}))}))}fromModel(e){super.fromModel(e),this._expression=e.expression}async initialize(){return da.call(this,async()=>(await this.parseExpression(),this.isShutDown?!1:(this.getMetaData(),this.getTimeSeries(),!0)))}},Pj=class extends XO{suffix;_forward;offset;errorText;fwdModel=null;outField;roots=null;symbols=[];get title(){return`${this.forward}${this.suffix}`}get forward(){return this._forward}fromModel(e){super.fromModel(e);let t=e;this.offset=t.offset,this._forward=t.forward}async parseForward(){let e=bd(this.forward),t=yd(e);if(t?(this.errorText=e.error,this.fwdModel=null,this._forward=e.text):(this.errorText=void 0,this.fwdModel=e.model,this._forward=e.clean),t)this.roots=null;else{this.offset>0?(this.suffix=` (${le(eg(this.offset),$h(B.FMT_US_DATE_ONLY))(new Date)})`,this.outField=new If(`Close_${this.offset}`,v.Number,b.Forward,`Close (${this.offset})`),this.curves[0].fields[0]=this.outField):(this.suffix=``,this.outField=G.Close);let{yes:t,no:n}=k(e.symbols,e=>Ei(`${e}*1`)),r=(await Promise.all(t.map(e=>Wi(e)))).map(e=>e.map(e=>e.name));this.roots=t.reduce((e,t,n)=>(e[t]=r[n],e),{}),this.symbols=n}}get isValid(){return!P(this.errorText)}getMetaData(){if(this.isValid){let e=Object.values(this.roots).flat();this.metaData=new Ka(e),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(K.MD_CHANGED,{plot:this})})}}getForwardPolicy(e){return{mapper:e=>e.query.root,loadMoreData:!1,recompute:d.Everything,missing:u.UseNext,stretch:e=>!1,fieldMap:new Map([[G.Close,this.outField]]),noDataApproach:f.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1,valueProvider:e}}getTimeSeries(){let e=$().getTimeSeriesDataSource(),t=Object.keys(this.roots),n=this.offset===0?w.Forward:w.HistoricalForward,r=t.map(t=>{let r={seriesKind:n,root:t,offset:this.offset,symbols:this.roots[t],getHashKey:()=>`${n}|${t}|${this.offset}`};return e.getTimeSeries(r)}),i=this.symbols.length>0?new w_(this.symbols):void 0;this.timeSeries=new nb(this.fwdModel,r,this.getForwardPolicy(i)),this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:re.Unspecified};this.presenter?.notifyHost(K.TS_MANYCHANGED,e)}})}async initialize(){return da.call(this,async()=>(await this.parseForward(),this.isShutDown?!1:(this.getMetaData(),this.getTimeSeries(),!0)))}},Fj=e=>e.substring(0,e.lastIndexOf(`::`)),Ij=class extends XO{isAverage;hasComputation;offset;offsets;_seasonal;symbolToOffset;errorText;seaModel=null;isPlain=!1;isFutures=!1;suffix=``;outField;symbols;coreModel;coreHasComputation;refSeasonal;get title(){if(this.isAverage){let e=`YB `;return this.offset<-1&&(e=`${Math.abs(this.offset)}y `),`${e}Average`}return!this.hasComputation&&(this.symbols?.length??0)>0?this.outField.name:`${this.seasonal}${this.suffix}`}get seasonal(){return this._seasonal}fromModel(e){super.fromModel(e);let t=e;this.offset=t.offset,this.offsets=t.offsets,this.isAverage=t.offset<0,this._seasonal=this.refSeasonal=t.seasonal}constructSeasonal(e,t){return wd(Dd(e,e=>this.applyOffset(e,t)))}constructAverage(e,t=null){let n=t===null?null:t.map(e=>this.symbolToOffset[e]),r=n===null,i=this.offsets.filter(e=>r?!0:n.includes(e)).map(t=>`(${this.constructSeasonal(e,t)})`);return`(${i.join(`+`)})/${i.length}`}prepareFields(){let e=this.isPlain?`${this.yearFromOffset(this.offset)}`:`${this.offset}Y`,t=this.isAverage?`Avg`:e;this.suffix=this.offset===0?``:` (${t})`,this.outField=new If(`Close_${t}`,v.Number,b.Seasonal,`Close${this.suffix}`),this.curves[0].fields[0]=this.outField}applyOffset(e,t){return`${this.isPlain?e:Xi(e,-t)}::${t}`}createSymbolToOffsetMapping(e){this.symbolToOffset={},e.forEach(e=>{this.offsets.forEach(t=>{this.symbolToOffset[this.applyOffset(e,t)]=t})})}async parseSeasonal(){let e=bd(this.seasonal,!0),t=yd(e),n=e=>(this.errorText=e,this.seaModel=null,null);if(t)return n(e.error);let{model:r,symbols:i}=e;this.prepareFields();let a=new Map;for(let e of i){let t=Bi(await wi(e));a.set(e,t)}r=Dd(r,e=>a.get(e)),i=Array.from(a.values());let o=i.every(e=>Ei(e)||Oi(e)),s=i.every(e=>Ai(e)),c=i.every(e=>!Ei(e)&&!Ai(e)&&!Oi(e));if(!o&&!s&&!c)return n(`Mixed types of symbols aren't supported yet`);this.isPlain=c,this.isFutures=o,this.createSymbolToOffsetMapping(i),this.coreModel=this.isAverage?r:null,this.coreHasComputation=Ed(r);let{model:l,symbols:u}=bd(this.isAverage?this.constructAverage(r):this.constructSeasonal(r,this.offset),!0);this.seaModel=l,this.hasComputation=Ed(l),this._seasonal=wd(Dd(l,Fj)),this.symbols=u,this.outField.name=this.outField.shortName=this.fixupFieldDescription()}get isValid(){return!P(this.errorText)}getActualSymbols(){return[...new Set(this.symbols.map(Fj))]}fixupFieldDescription(){if(!this.hasComputation&&!this.isAverage){let e=Fj(this.symbols[0]);if(this.isPlain)return`${e} ${new Date().getFullYear()-this.offset}`;if(this.isFutures)return Bi(e,!0)}return this.title}getMetaData(){if(this.isValid){let e=this.getActualSymbols(),t=e.length===1&&!this.hasComputation&&!this.isAverage,n=$().getMetaDataSource();this.metaData=t?n.getMetaData(e[0]):new Ka(e),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(K.MD_CHANGED,{plot:this})})}}getNoDataApproach(){return this.isAverage&&!this.coreHasComputation?f.ModelTransformRequired:this.hasComputation?f.NoAction:f.IgnoreTimelineOnly}get seasonalPolicy(){return{mapper:e=>e.query.surrogate||e.query.symbol,loadMoreData:!1,recompute:d.Everything,missing:this.hasComputation?u.UsePrevious:u.UseNone,stretch:e=>this.shouldStretch(e),fieldMap:new Map([[G.Close,this.outField]]),noDataApproach:this.getNoDataApproach(),modelTransform:(e,t)=>t.length===0?this.seaModel:bd(this.constructAverage(this.coreModel,e)).model,skipLeadingEmpty:!1}}shouldStretch(e){return this.symbolToOffset[e]===0&&(this.isAverage&&this.symbols.length>1||this.offset>0)}shiftYears(e){return En(new Date,-e)}yearFromOffset(e){return ni(this.shiftYears(e))}getCmdtyRange(e){let t=this.shiftYears(e);return[nr(t),tr(t)]}getSeasonalRange(e,t,n){let r=P(e[0],e[1]);return this.isPlain&&!r?this.getCmdtyRange(t):this.isFutures?n!=null&&(n.from!=null||n.to!=null)?[null,null]:[En(e[1]??new Date,-(t+B.SEASONAL_FUTURES_FETCH_YEARS)),null]:this.isPlain&&t>0&&r?e.map(e=>En(e,-t)):e}getTimeSeries(){if(!this.isValid)return;let e=$().getTimeSeriesDataSource(),t=Object.keys(this.symbolToOffset).map(t=>{let n=this.makeQuery();return n.surrogate=t,n.symbol=Fj(t),n.offset=this.symbolToOffset[t],n.cacheMe=!this.isPlain||n.offset===0,n.range=this.getSeasonalRange(n.range,n.offset,n.visibleRange),n.offset>0&&(n.disableStreamingUpdates=!0),e.getTimeSeries(n)}),n=new nb(this.seaModel,t,this.seasonalPolicy);n.seasonalAverageOffset=this.offset,this.timeSeries=n,this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:re.Unspecified};this.presenter?.notifyHost(K.TS_MANYCHANGED,e)}})}async initialize(){return da.call(this,async()=>(await this.parseSeasonal(),this.isShutDown?!1:(this.getMetaData(),this.getTimeSeries(),!0)))}},Lj=[`top`,`bottom`,`right`,`left`],Rj={bottom:`center`,top:`center`,right:`start`,left:`end`},zj=class{lineWidth;arrowLength;position;textAlign;fontSize;fontFamily;padding;strokeColor;textColor;backgroundColor;constructor(e){this.lineWidth=1,this.arrowLength=7,this.position=`bottom`,this.textAlign=`center`,this.fontSize=12,this.fontFamily=`Arial`,this.padding=4,this.strokeColor=`white`,this.textColor=`white`,this.backgroundColor=`black`,e&&this.configure(e)}configure(e){Object.assign(this,e)}draw(e,t,n,r,i,a){let o=P(i);if(a||=this.fontSize+this.padding+this.padding+(o?this.padding:0),!Lj.includes(this.position.toLowerCase())){I(`Can not draw indicator in position [${this.position}]`,`error`);return}e.font=`bold ${this.fontSize}px ${this.fontFamily}`,e.textAlign=Rj[this.position],e.strokeStyle=this.strokeColor,e.fillStyle=uo(this.backgroundColor),e.lineWidth=this.lineWidth;let s=[r,i??``].map(t=>e.measureText(t).width),c=Math.max(...s),l=this.position===`bottom`||this.position===`top`,u=l?0:this.arrowLength,d=Math.round(c+u+this.padding+this.padding),f=Math.round(d/2),p=Math.round(a/2);e.setLineDash([]);let m=t;e.beginPath(),e.moveTo(m,n);let h=n+p,g=n+2*p,_=n-p;if(this.position===`right`){e.lineTo(m,h);let t=m+d;o&&(e.lineTo(m,g),e.lineTo(t,g)),e.lineTo(t,h),e.lineTo(t,_),e.lineTo(m,_)}else if(this.position===`left`){e.lineTo(m,h);let t=m-d;o&&(e.lineTo(m,g),e.lineTo(t,g)),e.lineTo(t,h),e.lineTo(t,_),e.lineTo(m,n-p)}else if(l){let t=this.position===`top`?n-a:n+a,r=m-f,i=m+f;e.lineTo(m,n),e.lineTo(i,n),e.lineTo(i,t),e.lineTo(r,t),e.lineTo(r,n),e.lineTo(m,n)}if(e.closePath(),e.stroke(),e.fill(),e.fillStyle=this.textColor,e.textBaseline=`middle`,l){let t=this.position===`top`?n-a:n;e.fillText(r,m,t+jo(e,1))}else if(this.position===`right`){let t=m+this.arrowLength+this.padding;e.fillText(r,t,n),o&&e.fillText(i,t,n+this.padding+p)}else if(this.position===`left`){let t=m-this.arrowLength-this.padding;e.fillText(r,t,n),o&&e.fillText(i,t,n+this.padding+p)}}},Bj=({y:e,halfHeight:t})=>e-t,Vj=({y:e,halfHeight:t})=>e+t;function Hj(e,t){e.forEach((e,n,r)=>{if(n===0&&e.y-e.halfHeight<t.y)e.y=t.y+e.halfHeight+1;else if(n>0){let i=r[n-1],a=Bj(e),o=Vj(i);a<o&&(e.y=o+1+e.halfHeight),Vj(e)>t.y+t.height&&(e.y=t.y+t.height-e.halfHeight-1)}})}var Uj=4,Wj=({x:e,halfWidth:t})=>e-t-Uj,Gj=({x:e,halfWidth:t})=>e+t+Uj,Kj=(e,t)=>e-1-t-Uj,qj=(e,t)=>e+1+t+Uj;function Jj(e,t){let n=e.length-1;e.forEach((e,r,i)=>{let a=r===0,o=a?null:i[r-1],s=Wj(e),c=a?t.x:Gj(o);if(e.x-e.halfWidth<t.x&&(e.x=qj(t.x,e.halfWidth)),s<c)e.x=qj(c,e.halfWidth+Uj);else{let t=Gj(e),a=r<n?Wj(i[r+1]):2**53-1;if(t>a){let n=Kj(e.x,t-a),r=Kj(e.x,e.halfWidth-2),i=qj(c,o?.halfWidth??0);e.x=Math.max(r,n,i)}}Gj(e)>t.x+t.width&&(e.x=Kj(t.x+t.width,e.halfWidth))})}var Yj=Array.from([,,,,,,],(e,t)=>++t).reverse(),Xj=`8`,Zj=/\d/g;function Qj(e){return e.replace(Zj,Xj)}function $j(e,t){let n=e.timeSeries.container;if(n===null||n.size<1)return[null,-1];let r=n.getLastDataPoint(t),i=n.getData(t),a=i.length-1,o=e.type===C.Study&&[`JPI`,`CTTP`,`CTTI`].includes(e.model.study);return r==null&&!o&&(a=ye(i,e=>e!==null),r=a===-1?null:i[a]),[r,a]}function eM(e){let t=e.plot.timeSeries.container;return t===null||t.size<1?null:e.getColor(t.size-1)}function tM(e){return e.curves.filter(t=>e.isVisible&&t.visible&&(e.type!==C.Study||t.style!==h.Ribbon)).map(t=>{let n=t.pickMainField(),[r,i]=$j(e,n);return{value:r,color:eM(t),field:n,index:i}})}var nM=class{pane;annotationUndoOwner={axis:this};annotations=[];id;isCustomDomain=!1;primary=!1;onTheRight=!0;viewBox;plots=[];comparison;scale;yScale;label=``;crosshairIndicator;ticks;lastUsedOptions;config;_fullDomain;constructor(e){this.pane=e,this.id=bt(),this.ticks=null,this.lastUsedOptions=null;let{chart:{fontSize:t},yAxis:{fontSize:n}}=this.pane.presenter.display,r=n||t||12;this.config={innerTickSize:7,tickPadding:5,indicatorPadding:4,fontWeight:400,fontSize:r},this.crosshairIndicator=new zj({fontSize:this.config.fontSize,arrowLength:this.config.innerTickSize})}makePlot(e){let t=null;switch(C[e.type]){case C.Symbol:t=new ZO;break;case C.Expression:t=new Nj;break;case C.Study:t=new jj;break;case C.IncomeStatement:t=new QO(w.IncomeStatement);break;case C.BalanceSheet:t=new QO(w.BalanceSheet);break;case C.Forward:t=new Pj;break;case C.Seasonal:t=new Ij;break;default:throw Error(`${e.type} isn't supported yet`)}return t.axis=this,t.fromModel(e),t}toPrice(e){let t=this.yScale.yToPrice(e);return this.comparison===x.None?t:this.pane.presenter.mainPlot.priceMap(t,void 0,G.Close,!0)}toTime(e){return this.pane.presenter.view.toTime(e)}toAnnotationPoint(e){let t=this.toPrice(e.y),n=this.toTime(e.x);return new ik(this,t,n||void 0)}toX(e){return this.pane.presenter.view.toX(e)}priceMap(e){return this.comparison===x.None?e:this.pane.presenter.mainPlot.priceMap(e,void 0,G.Close)}toY(e){let t=this.priceMap(e);return this.yScale.priceToY(t)}get plotAnnotations(){let e=[];return this.plots.forEach(t=>{t.isVisible&&t.annotations&&e.push(...t.annotations)}),e}annTimeToX(e){return this.pane.presenter.view.xAxis?.annTimeToX(e)}snapTo(e){let t={x:this.annTimeToX(e.time),y:this.toY(e.price)},n=this.pane.presenter,r=n.activeTool,i=r.annotation;return r.alignPointsMode&&i&&i.alignPointsSupported&&i.points.includes(e)?this.alignPoints(i,e,t):r.snapToSupported&&n.display.yAxis.snapAnnotationsToPrices&&!e.passive&&(e.moveDirection===te.Both||e.moveDirection===te.Vertical)&&this.snapToPrices(e,t),t}snapToPrices(e,t){let n=this.plots.find(e=>e.main);if(n&&n.timeSeries&&n.timeSeries.hasData){let r=n.timeSeries.container,i=j(r.getTimeData(),+e.time,Number),a=[].concat(...n.curves.map(e=>e.fields)).filter(e=>r.hasField(e)).map(e=>{let n=r.getData(e)[i],a=this.toY(n);return{priceSnap:n,ySnap:a,dist:Math.abs(a-t.y)}}).filter(e=>e.dist<=B.SNAP_PROXIMITY_PIXELS).reduce((e,t)=>e===null||t.dist<e.dist?t:e,null);P(a)&&(e.price=a.priceSnap,t.y=a.ySnap,e.time=r.getTimeData()[i],t.x=this.toX(e.time))}}alignPoints(e,t,n){let r=e.points.find(e=>e!==t);if(t!==r&&r&&r.point){let e=r.point,i=(360+-so(e,n)*180/Math.PI)%360,a=45/2,o=i>360-a||i<a||i>180-a&&i<202.5,s=i>90-a&&i<112.5||i>270-a&&i<292.5;if(o)n.y=e.y,t.price=this.toPrice(n.y);else if(s)n.x=e.x,t.time=this.toTime(n.x);else{let r=Math.abs(n.x-e.x),i=e.y>n.y?-1:1;n.y=e.y+r*i,t.price=this.toPrice(n.y)}}}toPoint(e){if(P(this.pane.presenter.view))return this.snapTo(e)}makeAnnotation(e,t=!0){let n=Cj(e.id,!0,e.traits)(this,!1);t&&e.uid&&(n.uid=e.uid);let r=n.activePoints,i=e.points.length-r.length;return i>0&&n.addPoints(i),n.activePoints.forEach((t,n)=>{let r=e.points[n];Ze(r.price)&&Ze(r.time)&&t.update(r.price,r.time)}),n.visible=e.visible,n.locked=e.locked,n}expand(e){let t=[];switch(e.type){case`Forward`:{let n=e.curves,r=e.offsets;delete e.curves,delete e.offsets;for(let i=0;i<n.length;i++){let a=Object.assign({},e);a.curves=[n[i]],a.offset=r[i],t.push(a)}break}case`Seasonal`:{let n=e.curves,r=e.offsets;delete e.curves,delete e.offsets;let i=r.filter(e=>e>=0);for(let a=0;a<n.length;a++){let o=Object.assign({},e);o.curves=[n[a]],o.offset=r[a];let s=o.offset<0;s?o.offsets=o.offset===-1?i:De(Math.abs(o.offset),e=>e+1):o.offsets=[o.offset],(!s||o.offsets.length>1)&&t.push(o)}break}default:t.push(e)}return t}fromModel(e){this.comparison=x[e.comparison??`None`],this.scale=S[e.scale??`Linear`],this.yScale=new jO(this.scale,this),this.label=e.label,this.plots=[].concat(...e.plots.map(e=>this.expand(e))).map(e=>this.makePlot(e));let t=e.annotations||[];this.annotations=t.map(e=>this.makeAnnotation(e));let{chart:{fontFamily:n,backgroundColor:r},yAxis:{textColor:i,crosshair:{color:a},primaryOnTheLeft:o}}=this.pane.presenter.display,s=o??!1;this.onTheRight=this.primary&&!s||!this.primary&&s,this.crosshairIndicator.configure({position:this.onTheRight?`right`:`left`,fontFamily:n,strokeColor:a,textColor:i,backgroundColor:_o(.15)(r)})}findIndex(e){return this.annotations.findIndex(t=>t.uid===e.uid)}addAnnotation(e){let t=this.makeAnnotation(e,!0);if(this.appendAnnotation(t),e.isUndoRedo&&e.position!==void 0){this.annotations.splice(this.findIndex(t),1);let n=xt(0,this.annotations.length,e.position);this.annotations.splice(n,0,t)}t.requestRedraw(),this.fireAnnotationsChanged()}appendAnnotation(e){this.findIndex(e)===-1&&this.annotations.push(e)}fireAnnotationsChanged(e=!1){this.pane.presenter.onAnnotationsUpdated(this,e)}deleteAnnotation(e,t=!0){e.isSelected&&this.pane.presenter.clearSelection();let n=this.findIndex(e);n!==-1&&this.annotations.splice(n,1),t&&this.fireAnnotationsChanged(!e.isSelected)}fliphorizontalAnnotation(e){e.flip(!0),this.fireAnnotationsChanged(!0)}flipverticalAnnotation(e){e.flip(!1),this.fireAnnotationsChanged(!0)}duplicateAnnotation(e){let t=e.axis,n=this.makeAnnotation(e.toModel(),!1);n.drawPoints(null,!0),n.offset({x:B.ANN_DUPLICATE_OFFSET,y:B.ANN_DUPLICATE_OFFSET}),t.appendAnnotation(n),n.requestRedraw(),this.fireAnnotationsChanged()}updateAnnotation(e,t){e.isSelected&&!this.pane.presenter.annotationManipulation&&this.pane.presenter.clearSelection(),El(e.name,t.traits),e.updateFrom(t.traits,t.extras,t.isUndoRedo?null:t.points,t.visible,t.locked),t.isUndoRedo&&P(t.points)&&e.updateActivePoints(t.points),e.isSelected&&!e.isVisible&&this.pane.presenter.clearSelection(),t.isUndoRedo||this.pane.presenter.undoRedoManager.done(ok(e,O.Moved)),e.requestRedraw(),this.fireAnnotationsChanged()}setViewBox(e){this.viewBox=e;let{y:t,height:n}=this.viewBox;this.yScale.range([Math.floor(t),Math.floor(t+n)]),this.plots.forEach(t=>t.setViewBox(e))}get fullDomain(){return P(this._fullDomain)||(this._fullDomain=this.getDataDomain().domain),this._fullDomain}updateFullDomain(e=null){if(e===null&&this.comparison!==x.None)return;let t=this.fullDomain;this._fullDomain=this.getDataDomain([e,e],t).domain}getPlotDataDomain(e,t,n){let r=e.timeSeries;if(!r.hasData)return{domain:null};let i=r.container,a=i.getTimeData(),o=e=>j(a,+e,Number),s=P(t),c=s?o(t):0,l=P(n),u=l?o(n):a.length-1,d=e.curves.map(e=>e.fields).flat().filter(e=>e.id!==G.Change.id),f=P(e.targetFields);f&&d.push(...e.targetFields);let p={},m=t=>{let n=f?e.curves[0]:e.curves.find(e=>e.fields.includes(t));if(!P(n)||n.shift===0)return[c,u];if(!P(p[n.id])){let e=n.shiftedTimeDomain;if(!P(e))return[c,u];p[n.id]=[o(e[0]),o(e[1])]}return p[n.id]},g=t=>{let[n,r]=m(t),a=i.getData(t),o=Math.max(n,0),s=Math.min(a.length-1,r);return a.slice(o,s+1).map((n,r)=>e.priceMapper(n,r,t))},_=e=>Ee(g(e)),v=[null,null],y=e=>e.id,b=new Set(xe(i.fields,d,y).map(y));e.curves.filter(e=>e.visible).map(e=>{let t=e.fields.filter(e=>b.has(e.id));e.isStackedColumn?M(Ee(t.map(e=>g(e)).reduce((e,t)=>t.map((t,n)=>(e[n]||0)+(t||0)),[])),v):t.map(e=>{M(_(e),v)})});let x=(e.annotations||[]).filter(e=>e.isVisible).flatMap(e=>{let t=e.getDomainPrices;return typeof t==`function`?t.call(e):[]}).filter(e=>Ze(e));x.length>0&&M(Ee(x),v);let S=oe.None,C=[h.Column,h.MultiColumn,h.StackedColumn];if(s&&l&&!e.main&&e.curves.some(e=>C.includes(e.style))){let e=v[0]>0,t=v[1]<0;e?(S=oe.Min,v[0]=0):t&&(S=oe.Max,v[1]=0)}return{domain:v,clamped:S}}getDataDomain([e,t]=[null,null],n=[null,null]){let r=F(n),i=!1;for(let n of this.plots.filter(e=>e.isVisible&&e.hasVisibleCurves&&!e.hasDetachedScale)){let{domain:a,clamped:o}=this.getPlotDataDomain(n,e,t);P(a)&&(M(a,r),i||=o!==oe.None)}if(!P(r))return{domain:null};let[a,o]=r;if(!P(a,o))return{domain:null};let s=[Number(a),Number(o)];s[0]===s[1]&&(--s[0],s[1]+=1);let c=oe.None;return i&&(s[0]===0?c=oe.Min:s[1]===0&&(c=oe.Max)),{domain:s,clamped:c}}setDomain(){let e=this.pane.presenter,t=e.view.xAxis.xScale.domain();if(!P(t))return;for(let e of this.plots.filter(e=>e.isVisible&&e.hasVisibleCurves&&e.hasDetachedScale)){let{domain:n}=this.getPlotDataDomain(e,t[0],t[1]);P(n)&&e.yScale.domain(n)}if(this.isCustomDomain)return;let{domain:n,clamped:r}=this.getDataDomain(t);if(this===e.mainAxis&&e.mainPlot?.showPrevious){let t=e.mainPlot.getPreviousValue(),r=rt(e.display,!1,`chart`,`previous`,`forceVisible`);P(t,n)&&r&&(n[0]=Math.min(n[0],t),n[1]=Math.max(n[1],t))}if(this.yScale.domain(n),P(n)){let e=this.getPadding(r);P(e)&&this.yScale.padding(e)}}getInitialPadding(){let e=$i(this.pane.presenter.hostElement),t=na(`#${B.HEADER_SIZE_PLACEHOLDER_ID}`,e);if(!P(t)){t=sa(e,`div`),ra(t,{display:`none`}),ia(t,{id:B.HEADER_SIZE_PLACEHOLDER_ID,class:`bcharts-card bcharts-card-first`});let{lineHeight:n}=getComputedStyle(t);isNaN(Number.parseFloat(n))&&ra(t,{lineHeight:`120%`})}let{paddingTop:n,paddingBottom:r,marginTop:i,lineHeight:a}=getComputedStyle(t),o=this.pane.isMain?i:`0`;return this.pane.presenter.display.tooltip.mode===`cards`?[n,r,o,a].map(Number.parseFloat).reduce((e,t)=>e+t,0)+B.CARDS_Y_OFFSET:Number.parseFloat(o)}getPadding(e){let t=this.pane.presenter,n=this.viewBox?.height;if(n==null)return[0,0];let r=t.display,i=rt(r,null,`yAxis`,`minPaddingPercent`),a=rt(r,null,`yAxis`,`maxPaddingPercent`),o=P(i),s=P(a),c=o||s?0:this.getInitialPadding(),l=o?i:B.PANE_CAP_MIN_PADDING_PERCENT,u=s?a:B.PANE_CAP_MAX_PADDING_PERCENT,d=l*n,f=[s?u*n:Math.max(d,Math.min(u*n,c)),d];e===oe.Max?f[0]=B.PANE_TINY_PADDING_PIXELS:e===oe.Min&&(f[1]=B.PANE_TINY_PADDING_PIXELS);let p=t.mainPlot;return p&&p.hasEvents&&t.view&&(f[0]+=3*t.view.getEventRadius()),f}clearTicks(){this.ticks=null}getTicks(e,t=0){let{height:n}=this.viewBox,r=jo(e,1.3),i={height:n,approxLineHeight:r,domain:this.yScale.domain()};if(P(this.ticks)&&P(i.domain)&&P(this.lastUsedOptions)&&P(this.lastUsedOptions.domain)&&i.height===this.lastUsedOptions.height&&i.approxLineHeight===this.lastUsedOptions.approxLineHeight&&i.domain[0]===this.lastUsedOptions.domain[0]&&i.domain[1]===this.lastUsedOptions.domain[1])return this.ticks;this.lastUsedOptions=i;let a=Math.floor((n+40)/(r+40)),o=this.yScale.getTicks(a),s=rt($().config,null,`overrides`,`yAxis`,`tickProvider`);if(P(s)&&typeof s==`function`&&i.height>0&&P(i.domain)){let e=F(i);e.autoTicks=F(o),o=s(e)}let{innerTickSize:c,tickPadding:l,fontSize:u}=this.config,d=null,f=this.yScale?.checkTicks(),p=f?40/4*3:40;return this.ticks=o.map(n=>{let r=Math.round(this.yScale.priceToY(n)),i=Math.abs(r-(d??r));if(f&&d!==null&&i<p)return null;d=r;let a=iv(this,n),o=e.measureText(a).width,s={x1:0,x2:0,y1:r,y2:r,dy:0,label:a,labelX:0,labelY:r+u*.32};return this.onTheRight?(s.x1=t,s.x2=s.x1+c,s.labelX=s.x2+o+l):(s.x1=t-c,s.x2=s.x1+c,s.labelX=s.x1-l),s}).filter(e=>e!==null),this.ticks}widthNeeded(e){if(!P(this.fullDomain))return B.DEFAULT_PRICE_AXIS_WIDTH;e.save();let{fontWeight:t,fontSize:n}=this.config,{chart:{fontFamily:r}}=this.pane.presenter.display;e.font=`${t} ${n}px ${r}`;let i=Math.max(...this.fullDomain.map(t=>e.measureText(Qj(iv(this,t,!0))).width)),{innerTickSize:a,tickPadding:o}=this.config,s=P(this.label)?jo(e,1.6):0,c=i+a+2*o+s;return e.restore(),c}draw(e){let{chart:{fontFamily:t},yAxis:{gridLines:n,textColor:r,visible:i}}=this.pane.presenter.display;if(!i||!this.viewBox)return;e.save();let{x:a,y:o,width:s,height:c}=this.viewBox,{fontWeight:l,fontSize:u}=this.config;if(To(e,this.viewBox),e.font=`${l} ${u}px ${t}`,e.lineWidth=2,e.strokeStyle=n.color,e.textAlign=`end`,P(this.label)){e.save(),e.fillStyle=go(.4)(r),e.translate(0,0);let t=this.onTheRight?1:-1;e.rotate(t*Math.PI/2),e.textAlign=`center`;let n=jo(e),i=t*(o+c/2);this.onTheRight?e.fillText(this.label,i,-(a+s-n)):e.fillText(this.label,i,a+n),e.restore()}let d=this.onTheRight?a:s;e.setLineDash([]),Bo(e,d,o,o+c);let f=this.getTicks(e,d);this.drawTicks(e,f,r),this.drawPriceAdornments(e),e.restore()}drawTicks(e,t,n){t&&(e.fillStyle=n,t.forEach(t=>{e.fillText(t.label,t.labelX,t.labelY+t.dy)}))}drawCrosshairIndicator(e,t){if(!this.plots.some(e=>e.isVisible&&e.hasVisibleCurves)||!this.pane.presenter.display.yAxis.crosshair.enabled||!Number.isFinite(t)||!this.yScale)return;let n=this.onTheRight?this.viewBox.x:this.viewBox.width,r=this.yScale.yToPrice(t);if(r==null)return;let i=iv(this,r);this.crosshairIndicator.draw(e,n,t,i)}get indicatorHeight(){return this.config.fontSize+this.config.indicatorPadding+this.config.indicatorPadding}drawPriceAdornments(e){let t=this.pane.presenter,{chart:{fontFamily:n,previous:r},yAxis:{showLastValue:i,preventLabelOverlap:a,includePercentChangeWithLastValue:o}}=t.display,s=t.view,c=[],l=(e,t,n,r,i,a)=>{if(t!=null){let s=t;t=e.priceMapper(t,a,i);let l,u=e.is(C.Symbol)||e.is(C.Expression);if(o&&u){let t=e.axis.comparison===x.Percent?x.None:x.Percent;l=e.priceMapper(s,a,i,t)}let d=e.hasDetachedScale?e.metaData.format(t,i):void 0,f=P(l)?1:2;c.push({y:e.priceToY(t),formattedValue:d,value:t,auxValue:l,color:n,halfHeight:Math.round(this.indicatorHeight/f),priority:r})}};this.plots.forEach(e=>{if(!(!e.isVisible||!e.hasVisibleCurves||!e.timeSeries||!e.timeSeries.hasData)){if(i===`All`||i===`Main`&&e.main){let t=e.main?1:3;tM(e).filter(e=>e.value!=null&&e.index!==-1).forEach(n=>l(e,n.value,n.color,t,n.field,n.index))}e.showPrevious&&l(e,e.getPreviousValue(),r.color,2,G.PreviousClose,void 0)}}),this.annotations.concat(this.plotAnnotations).filter(e=>e.isVisible).forEach(e=>{c.push(...e.getPriceScaleAdornments().map(e=>({y:this.toY(e.price),value:this.priceMap(e.price),color:e.color,halfHeight:Math.round(this.indicatorHeight/2),priority:4})))}),c.sort((e,t)=>e.y-t.y),a&&Hj(c,this.viewBox);let u=({y:t,value:r,formattedValue:i,color:a,auxValue:o})=>{let{leftOffset:c,rightOffset:l}=s,u=this.onTheRight?this.pane.viewBox.width-l:c,d=xo(a),f=new zj({position:this.onTheRight?`right`:`left`,fontSize:this.config.fontSize,padding:this.config.indicatorPadding,fontFamily:n,textColor:d,strokeColor:a,backgroundColor:a}),p=i||iv(this,r),m,h=this.comparison===x.Percent;N(o)&&(m=h?rv(this,o):nv(o)),f.draw(e,u,t,p,m)};a?c.forEach(u):Yj.forEach(e=>c.filter(t=>t.priority===e).forEach(u))}};function rM(e){let t=e.map(e=>e.plots).flat().filter(e=>C[e.type]==C.Symbol).map(e=>e.symbol).map(e=>Ki(e)).filter(e=>e!==null).map(e=>e.getFullYear());return t.length==0?null:Math.max(...t)}var iM=Symbol.for(`__dloacip__`),aM=class{presenter;id;axes=[];height=0;alignedToYear=null;viewBox;constructor(e){this.presenter=e,this.id=bt()}fromModel(e){this.height=e.height,e.alignOnExpirations===!0&&(this.alignedToYear=rM(e.axes)),this.axes=e.axes.map((e,t)=>{let n=new nM(this);return n.primary=t===0,n.fromModel(e),n},this)}getBounds(){return this.viewBox}setViewBox(e){this.viewBox=e}drawBackground(e){P(this.viewBox)&&(this.drawAxes(e),e.save(),this.clipToNoScales(e),this.drawGrid(e),e.restore())}draw(e){P(this.viewBox)&&(e.save(),this.clipToNoScales(e),this.drawPrevious(e),this.drawPlots(e),this.drawAnnotations(e),this.drawLogo(e),e.restore())}drawLogo(e){!this.isMain||this.presenter[iM]===!1||qk(e,this.getBoundsWithoutScales())}drawAxes(e){for(let t of this.axes)t.draw(e)}drawPrevious(e){let t=this.presenter.mainPlot;if(t.showPrevious&&this.isMain){let n=t.getPreviousValue();if(n=t.priceMapper(n,void 0,G.PreviousClose),n!=null){let{leftOffset:r,rightOffset:i}=this.presenter.view,a=r,o=this.viewBox.width-i,s=t.axis.yScale.priceToY(n),{color:c,dashStyle:l,lineWidth:u}=this.presenter.display.chart.previous,d=lo(l);e.save(),e.strokeStyle=c,e.lineWidth=u,e.setLineDash(d),Vo(e,s,a,o),e.restore()}}}getBoundsWithoutScales(){let e=this.viewBox.duplicate(),t=this.presenter.view;return e.x=t.leftOffset,e.width-=t.leftOffset+t.rightOffset,e}clipToNoScales(e){To(e,this.getBoundsWithoutScales())}drawAnnotations(e){e.save();try{let{chart:{fontFamily:t},yAxis:{fontSize:n}}=this.presenter.display;e.font=`${n??12}px ${t}`;let r=this.presenter.annotationPreviewUid,i=this.axes.flatMap(e=>e.annotations).find(e=>e.uid===r&&e.isVisible&&!e.computed),a=e=>i!==void 0&&e!==i,o=(t,n)=>{e.save();try{n&&(e.globalAlpha*=B.PLOT_HOVER_DIM_ALPHA),t.draw(e,!0)}finally{e.restore()}};this.axes.forEach(e=>{e.annotations.filter(e=>e.isVisible).forEach(e=>o(e,a(e))),e.plotAnnotations.filter(e=>e.isVisible).forEach(e=>o(e,!1))});let s=this.presenter.selectedAnnotation;this.presenter.annotationManipulation&&s?.axis.pane===this&&s.isVisible&&s.drawPoints(e,!1)}catch(e){throw this.presenter.setAnnotationPreview(),e}finally{e.restore()}}drawGrid(e){let{chart:{fontFamily:t},yAxis:{gridLines:n,visible:r,minorGridLines:i}}=this.presenter.display;if(!r||!n.visible)return;let{lineWidth:a,color:o,dashStyle:s}=n;e.save();let c=!(e=>e.plots.some(e=>e.isVisible&&e.hasVisibleCurves&&!e.hasDetachedScale))(this.axes[0])&&this.axes.length>1,l=this.axes[+!!c],{fontWeight:u,fontSize:d}=l.config;e.font=`${u} ${d}px ${t}`;let f=l.getTicks(e),{leftOffset:p,rightOffset:m}=this.presenter.view,h=p,g=this.viewBox.width-m,_=(t,n,r)=>{e.lineWidth=t,e.strokeStyle=n,e.setLineDash(lo(r)),e.beginPath()};if(_(a,o,s),f.forEach(t=>{e.moveTo(h,t.y1),e.lineTo(g,t.y2)}),e.stroke(),i&&i.visible&&f.length>=2){let{lineWidth:t,color:n,dashStyle:r}=i,a=(f[0].y1-f[1].y1)/5;_(t,n,r),f.forEach(t=>{for(let n=1;n<5;n++){let r=Math.ceil(t.y1+n*a);e.moveTo(h,r),e.lineTo(g,r)}}),e.stroke()}e.restore()}drawYCrosshair(e,t){let{yAxis:{crosshair:{enabled:n,showValue:r,color:i,dashStyle:a}}}=this.presenter.display;if(!n)return;let o=lo(a);e.strokeStyle=i,e.setLineDash(o);let s=this.presenter.view.leftOffset,c=this.viewBox.width-this.presenter.view.rightOffset,l=is();l.prolog(e),Vo(e,l.adjust(t.y),l.adjust(s),l.adjust(c)),l.epilog(e),r&&this.axes.forEach(n=>{n.drawCrosshairIndicator(e,t.y)})}drawNoData(e){e.save(),e.font=`800 14px ${this.presenter.display.chart.fontFamily}`,e.fillStyle=`#f00`,Fo(e,$().config.noDataText||B.NO_DATA_TEXT,{x:this.viewBox.centerX,y:this.viewBox.centerY},T.Center),e.restore()}get isMain(){let e=this.presenter.mainPlot;return this.axes.some(t=>t.plots.includes(e))}drawPlots(e){e.save();let t=this.presenter.mainPlot,n=this.presenter.display.chart.showNoDataText,r=!P(n)||n,i=t=>t.draw(e),a=new Map,o=t=>t.drawEventsTopmost(e,a),s=!0,c=n=>{for(let e of this.axes){for(let r of e.plots){let e=r.isEmpty();s=s&&r.main&&e,r!==t&&!e&&n(r)}e.plots.includes(t)&&!t.isEmpty()&&n(t)}r&&s&&this.drawNoData(e)};c(i),c(o),e.restore()}};function oM(e,t){return{width:e,spacing:t,get totalWidth(){return this.width+this.spacing},offset:0}}var sM=class extends CO{timeline;aggregation;marginBars;bar;resetBar;wasZoomed;fitAllData;constructor(e,t){super(),this.timeline=e,this.aggregation=t;let n=e.presenter.display;this.marginBars=n.xAxis.marginBars||0,this.bar=oM(rt(n,B.DEFAULT_BAR_WIDTH,`chart`,`bar`,`width`),rt(n,B.DEFAULT_BAR_SPACING,`chart`,`bar`,`spacing`)),this._extent=null,this.wasZoomed=!1,this.fitAllData=!1}extent(e){return SO.call(this,`_extent`,e)}get presenter(){return this.timeline.presenter}get display(){return this.presenter.display}scaleBarToFit(){if(this.wasZoomed)return;if(this.fitAllData)return this._domain=null,this.scaleBarToFitDensity(this.timeline.withoutPrologEpilogLength);let e=this.display.xAxis.visibleRange;if(P(e))return this.scaleBarToFitRange([e.from,e.to]);let t=this.display.density;if(Number.isFinite(t))return this.scaleBarToFitDensity(t);let n=this.display.period;if(n===B.YTD_PERIOD)return this.scaleBarToFitYtd();if(Number.isFinite(n))return this.scaleBarToFitPeriod(n)}deriveExtentsFromBarWidth(e){if(!P(this._range)||this.timeline.length===0)return null;let t=this._range[1]-this._range[0],n=t/e.totalWidth,r=Math.ceil(n);e.offset=t-r*e.totalWidth;let i=this.timeline.lastSeriesIndex+this.marginBars,a=this._domain&&this._domain[1];return a&&(i=j(this.timeline,+a,Number,fv)),[i-r+1,i]}adjustDomain(){if(!P(this._range))return;this.scaleBarToFit();let e=this.deriveExtentsFromBarWidth(this.bar);if(P(e))this.extent(e);else return;this.setDomainFromExtent()}xToTime(e){if(!this.ready)return null;let t=this.xToIndex(e);return this.timeline.at(t)}xToIndex(e){if(!this.ready)return null;let t=e-this._range[0]-this.bar.offset,n=Math.floor(t/this.bar.totalWidth);return this._extent[0]+n}timeToIndex(e){return this.ready?(e=typeof e==`number`?e:+e,j(this.timeline,e,Number,fv)):null}indexToX(e){let t=e-this._extent[0];return this.bar.width/2+this.range()[0]+this.bar.offset+t*this.bar.totalWidth}timeToX(e){if(!this.ready)return null;let t=this.timeToIndex(e);return this.indexToX(t)}zoom(e){let t=e,n=t*this.bar.width/100,r=this.bar.width-n,i=this.bar.spacing-t*this.bar.spacing/100;if(r>B.MAXIMUM_BAR_WIDTH||r<B.MINIMUM_BAR_WIDTH)return!1;let a=oM(r,i),o=this.deriveExtentsFromBarWidth(a);return this.isUsableExtent(o)?(this.setBar(r,i),this.adjustDomain(),this.wasZoomed=!0,!0):!1}scaleBarToFitRange(e,t=!0){let n=(e,t,n,r)=>P(e)?j(this.timeline,e,Number,fv,n,r):t,{from:r,to:i}=this.presenter.data.range||{},a=+e[0]===r&&+e[1]===i,{firstSeriesIndex:o,lastSeriesIndex:s}=this.timeline,c=a?o:void 0,l=a?s:void 0,u=[n(e[0],o,c,l),n(e[1],s,c,l)];this.timeline.at(u[1])>e[1]&&(u[1]=Math.max(0,u[1]-1));let d=u[1]-u[0]+1,f=t?this.marginBars:0;u[1]+=f,this.extent(u),this.setDomainFromExtent(),this.scaleBarToFitDensity(d,t)}scaleBarToFitDensity(e,t=!0){let n=Math.max(B.MINIMUM_BARS_VISIBLE,e),r=t&&this.display.xAxis.marginBars||0,i=(this._range[1]-this._range[0])/(n+r);this.setBar(2/3*i,1/3*i,!1)}scaleBarToFitYtd(){let e=this.timeline.at(this.timeline.lastSeriesIndex);e&&this.scaleBarToFitRange([nr(e),e])}scaleBarToFitPeriod(e){let t=this.timeline.lastSeriesIndex,n=this.timeline.at(t),r=n,i=t,a=this.presenter.data.aggregation;if(a.isEndOfDay||a.isIntraday&&e>=B.INTRA_THRESHOLD)for(;i>0&&Bn(n,r)<e;)i--,r=this.timeline.at(i);else if(!a.isTick){let t=Math.floor(e/B.ONE_DAY_MILLIS),r=e=>Gn(e,vn(e)),a=r(n),o=n;for(;i>0;){let e=this.timeline.at(i),n=Nn(e,o);if(t===0){if(r(e)<=a||!n)break}else n||(t--,o=e);i--}}this.scaleBarToFitDensity(t-i+1)}setBar(e,t,n=!0){let[r,i]=yt(e,t,B.MINIMUM_BAR_WIDTH,B.MAXIMUM_BAR_WIDTH);this.bar.width=r,this.bar.spacing=i,this.wasZoomed||(this.resetBar={width:r,spacing:i}),n&&(this.presenter.model.display.chart.bar={width:e,spacing:t})}resetZoom(){P(this.resetBar)?(this.bar.width=this.resetBar.width,this.bar.spacing=this.resetBar.spacing):(this.bar.width=B.DEFAULT_BAR_WIDTH,this.bar.spacing=B.DEFAULT_BAR_SPACING),delete this.presenter.model.display.chart.bar,this.adjustDomain()}isUsableExtent(e){return P(e)&&P(e[0],e[1])&&e[0]>=0&&e[1]<this.timeline.withPrologEpilogLength&&e[1]-e[0]>=B.MINIMUM_BARS_VISIBLE}shiftBars(e,t=null){if(!this._extent)return;let n=this._extent.map(t=>t+e);this.isUsableExtent(n)&&(P(t)&&(this.bar.offset=t),this.extent(n),this.setDomainFromExtent())}setDomainFromExtent(){this.domain(this.extent().map(e=>this.timeline.at(e)))}pan(e){if(!Number.isFinite(e)||e===0)return;let t=e%this.bar.totalWidth,n=this.bar.offset+t,r=Math.sign(e),i=-(e<0?Math.ceil:Math.floor)(e/this.bar.totalWidth);(n>this.bar.totalWidth||n<-this.bar.totalWidth)&&(i+=n>0?-1:1,n-=r*this.bar.totalWidth),this.shiftBars(i,n)}getSeriesThatCouldLoadMoreData(){let e=this.domain();if(!P(e)||!P(e[0]))return[];let t=e[0].getTime();return this.timeline.presenter.allPlots.map(e=>e.timeSeries).filter(e=>{if(!P(e)||!e.hasData||e.container.size===0||e.canLoadMoreData!==!0)return!1;let n=e.container.getTimeData()[0];return P(n)&&t<=n.getTime()})}};function cM(e){return{date:e,priority:1,text:tv(e)}}var lM=class{view;xScale;ticks;lastUsedOptions;wasPanned;panningXAxisAllowed;config;isVisible;crosshairIndicator;contentBounds;axisStrips=[];overrideTickGetter;overrideFormatter;contractParityCache=null;contractParityCacheKey=null;constructor(e){this.view=e,this.xScale=new sM(e.presenter.timeline,e.presenter.data.aggregation),this.ticks=null,this.lastUsedOptions=null,this.wasPanned=!1,this.panningXAxisAllowed=rt(e.presenter.display,!0,`xAxis`,`panning`),this.updateConfigFromModel();let t=e.presenter.renderTo.id,n=rt($().config,null,`overrides`,`xAxis`,`tickProvider`);P(n)&&typeof n==`function`&&(this.overrideTickGetter=se(n,t));let r=rt($().config,null,`overrides`,`xAxis`,`formatter`);P(r)&&typeof r==`function`&&(this.overrideFormatter=se(r,t))}updateConfigFromModel(){let{chart:{fontFamily:e,backgroundColor:t,fontSize:n},xAxis:{textColor:r,visible:i,fontSize:a,crosshair:{color:o}}}=this.view.presenter.display,s=a||n||12;this.config={innerTickSize:5,tickPadding:5,indicatorPadding:5,fontWeight:400,fontSize:s},this.isVisible=i,this.crosshairIndicator=new zj({position:`bottom`,fontSize:this.config.fontSize,fontFamily:e,padding:this.config.indicatorPadding,strokeColor:o,textColor:r,backgroundColor:_o(.15)(t),arrowLength:this.config.innerTickSize})}setDomain(){this.xScale.adjustDomain();let e=this.view.presenter.display.period===B.FIFTY_YEARS_MILLIS;P(this.xScale.extent())&&!e&&this.checkForMoreData()}zoom(e){let t=this.xScale.zoom(e);return this.checkForMoreData(),t}checkForMoreData(){this.xScale.getSeriesThatCouldLoadMoreData().forEach(e=>e.loadMoreData())}shouldScrollIntoView(e){let t=this.xScale.extent();return P(t)?e-this.xScale.timeline.lastSeriesIndex>=0&&e-t[1]<=1:!1}pan(e){this.panningXAxisAllowed&&(this.xScale.pan(e),this.checkForMoreData(),this.view.setPriceAxesDomains(),this.wasPanned=!0)}get wasVisibleRangeChanged(){return this.wasPanned||this.xScale.wasZoomed}resetZoom(){this.xScale.resetZoom()}get barsToLast(){let e=this.xScale.timeline.lastSeriesIndex+this.getMaxCurveOffset(),t=this.xScale.extent();return e-(t?t[1]:e)}canGoToLast(){return this.barsToLast>0}getMaxCurveOffset(){return Math.max(...this.view.presenter.allCurves.map(e=>e.shift))}goToLatest(e=!1){if(this.canGoToLast()||e){let e=this.barsToLast===0?0:this.barsToLast+this.xScale.marginBars+1;this.xScale.shiftBars(e),this.view.setPriceAxesDomains(),this.view.redraw()}}get position(){return this.view.presenter.display.xAxis.position??`bottom`}setViewBox(e,t,n){this.contentBounds=e;let{x:r,y:i,width:a,height:o}=e;this.xScale.range([r,r+a]),this.axisStrips=[],t>0&&this.axisStrips.push({position:`top`,bounds:new Eo(r,i-t,a,t),baseline:i}),n>0&&this.axisStrips.push({position:`bottom`,bounds:new Eo(r,i+o,a,n),baseline:i+o})}contains(e){return this.axisStrips.some(t=>t.bounds.contains(e))}heightNeeded(e){if(!this.isVisible)return 0;let t=this.view.presenter.display.chart.fontFamily,{fontWeight:n,fontSize:r}=this.config;e.save(),e.font=`${n} ${r}px ${t}`;let{innerTickSize:i,tickPadding:a,indicatorPadding:o}=this.config,s=jo(e,1)+i+a+o;return e.restore(),s}getTickGetter(e){if(this.overrideTickGetter)return this.overrideTickGetter;let t=this.view.presenter.display.xAxis.isOrdinal||!1,n=R_(e);return t?cM:e=>n.getTick(e)}getTicks(e){if(P(this.lastUsedOptions)&&((e,t)=>e.unit===t.unit&&e.size===t.size&&e.spec===t.spec)(e.agg,this.lastUsedOptions.agg)&&e.unitWidth===this.lastUsedOptions.unitWidth&&e.barWidth===this.lastUsedOptions.barWidth&&e.extent[0]===this.lastUsedOptions.extent[0]&&e.extent[1]===this.lastUsedOptions.extent[1]&&e.formatString===this.lastUsedOptions.formatString&&e.minTickInterval===this.lastUsedOptions.minTickInterval&&P(this.ticks))return this.ticks;this.lastUsedOptions=e;let t=this.getTickGetter(e),n=Math.max(0,e.extent[0]),r=Math.min(this.xScale.timeline.withPrologEpilogLength-1,e.extent[1]+1);return this.ticks=this.view.presenter.timeline.slice(n,r).map((e,r)=>{if(!P(e)||Number.isNaN(e.getTime()))return null;let i=t(e);return P(i)&&(i.index=n+r),i}).filter(e=>P(e)),this.ticks}normalizeDuration(e){let t=L_(),n=t.Year,r=Object.keys(t);for(let i=0;i<r.length-1;++i){let a=t[r[i]].Multipliers,o=t[r[i+1]].Multipliers;if(e<=(Se(a)+Ce(o))/2){n=t[r[i]];break}}let i=n.Multipliers,a=i.findIndex(t=>e<t),o=a===-1?Se(i):i[a];return n.Period===`P1M`?o*=.9:n.Period===`P1W`&&(o*=.84),o}draw(e){if(!this.isVisible)return;let{xAxis:{gridLines:t,textColor:n,minTickInterval:r,tickPixelInterval:i,format:a,forceTicksVisible:o},chart:{fontFamily:s}}=this.view.presenter.display,{fontWeight:c,fontSize:l,innerTickSize:u,tickPadding:d}=this.config,{x:f,y:p,width:m,height:h}=this.contentBounds,{lineWidth:g,color:_,dashStyle:v}=t,y=lo(v);e.textAlign=`center`,e.textBaseline=`alphabetic`,e.font=`${c} ${l}px ${s}`,e.lineWidth=1,e.strokeStyle=_,e.fillStyle=n,e.setLineDash([]),this.axisStrips.forEach(t=>Vo(e,t.baseline,f,f+m));let b=this.xScale.extent(),x=e=>!P(e)||!P(e[0],e[1]);if(x(b))return;let S=t=>e.measureText(t).width,C=(e,t)=>P(e)?Bn(t,e):B.FIFTY_YEARS_MILLIS,w=i>0?i:120,T=this.xScale.domain();if(x(T))return;let ee=(T[1].getTime()-T[0].getTime())*w*.6/m,E=this.normalizeDuration(ee),D=this.view.presenter.data.aggregation.isEndOfDay,te=(e,t)=>{if(e.date.valueOf()===B.ZERO_DATE.valueOf())return!0;if(C(e.date,t.date)<r)return!1;let n=t.x-e.x,i=t.date.getTime()-e.date.getTime()>=E,a=n>w;return!(e.x+e.textWidth/2>=t.x-t.textWidth/2)&&(a||(D?i:!1))},ne=f+m,re=({text:n,x:r,date:i,forced:a})=>{P(i)&&(this.axisStrips.forEach(({position:t,baseline:i})=>{let o=t===`top`,s=i+(o?-1:1)*u,c=o?s-d:s+d+l*.71;a||Bo(e,r,i,s),e.fillText(n,r,c)}),t.visible&&!a&&(e.save(),e.lineWidth=g,e.setLineDash(y),Bo(e,r,p,p+h),e.restore()))},ie={agg:this.view.presenter.data.aggregation,unitWidth:S(`M`),barWidth:this.xScale.bar.width,extent:b,formatString:a,minTickInterval:r||0,duration:ee},ae=this.getTicks(ie),O=e=>{let{x:t,textWidth:n}=e,r=t;if(o){let i=n/2;r=t-i<f?f+i:t,r=r+i>ne?ne-i:r,e.x=r,e.forced=t!==r}else e.forced=!1},oe={date:B.ZERO_DATE,priority:999,x:-999,text:``,index:-1,textWidth:0};ae.forEach(e=>{e.x=this.xScale.indexToX(e.index),e.textWidth=S(e.text),O(e),te(oe,e)?(re(oe),oe=e):e.priority<oe.priority&&(oe=e)}),re(oe),this.drawTimeTransitions(e),this.drawTimeAdornments(e)}drawTransitionsFor(e,t,n,r,i){let a=this.xScale.domain(),o=this.view.presenter?.mainPlot?.timeSeries.container;if(!N(o))return;let s=o.getTimeData(),c=t===null?s:o.getData(t);if(!P(c))return;let l=j(s,+a[0],Number),u=j(s,+a[1],Number,Te,l);if(l<u){let{y:t,height:a}=this.contentBounds,o=this.view.leftOffset,d=this.contentBounds.x+this.contentBounds.width;if(r.save(),i){r.fillStyle=e.fillColor;let f=c[l],p=Math.max(o,this.xScale.timeToX(s[l]));for(let e=l+1;e<=u;++e){let o=e<c.length?c[e]:null;if(e===u||n(o,f)){let n=e<s.length?s[e]:null,c=N(n)?this.xScale.timeToX(n):d;c=Math.min(c,d),i(f)%2==0&&r.fillRect(p,t,c-p,a),f=o,p=c}}}let f=is();f.prolog(r),r.strokeStyle=e.color,r.lineWidth=e.width,r.setLineDash(lo(e.dashStyle));let p=null;for(let e=l;e<u;++e){let i=c[e];if(n(i,p)){let n=s[e],o=this.xScale.timeToX(n);P(o,p)&&Bo(r,o,t,t+a),p=i}}f.epilog(r),r.restore()}}drawTimeTransitions(e){let t=this.xScale.domain();if(!N(t)||!P(t[0],t[1]))return;let n=this.view.presenter,{xAxis:{contractTransition:r,cycleTransition:i}}=n.display,a=(e,t)=>e!==t;if(r.enabled&&n?.data?.aggregation.isMultiContract){let t=(n?.mainPlot?.timeSeries.container)?.getData(G.Symbol);if(t&&t.length>0){let n=t[0];if(this.contractParityCacheKey!==n||!this.contractParityCache){let e=[...new Set(t)];e.sort((e,t)=>{let n=Ki(e),r=Ki(t);return(n?.getTime()??0)-(r?.getTime()??0)});let r=0;if(this.contractParityCache)for(let t=0;t<e.length;t++){let n=e[t],i=this.contractParityCache.get(n);if(i!==void 0){r=(i-t)%2==0?0:1;break}}this.contractParityCache=new Map,e.forEach((e,t)=>this.contractParityCache.set(e,t+r)),this.contractParityCacheKey=n}this.drawTransitionsFor(r,G.Symbol,a,e,e=>this.contractParityCache.get(e)??0)}}i.enabled&&(n?.data?.aggregation.isIntraday?this.drawTransitionsFor(i,G.TradingDay,a,e,e=>e):n?.data?.aggregation.unit===g.Day?this.drawTransitionsFor(i,null,(e,t)=>!di(e,t),e,e=>e.getMonth()):n?.data?.aggregation.unit===g.Week&&this.drawTransitionsFor(i,null,(e,t)=>!pi(e,t),e,e=>e.getFullYear()))}getAnnXScore(e,t){return[Nn,li,di,pi].map((n,r)=>(4-r)*Number(n(e,t))).reduce((e,t)=>e+t,0)}annTimeToX(e){let t=this.xScale.timeToIndex(e);if(!N(t))return null;let n=this.xScale.timeline.at(t),r=this.xScale.timeToX(e);if(t>0&&n.valueOf()!==e.valueOf()){let i=t-1,a=this.xScale.timeline.at(i),o=this.xScale.indexToX(i);if(!this.view.presenter.display?.xAxis?.isOrdinal){if(a.valueOf()>e.valueOf())return r;let t=this.getAnnXScore(a,e),i=this.getAnnXScore(n,e);return t>i?o:i>t?r:this.view.presenter?.data?.aggregation?.isIntraday?o:r}let s=(e.valueOf()-a.valueOf())/(n.valueOf()-a.valueOf());return o+(r-o)*s}else return r}drawTimeAdornments(e){e.save();let t=this.view.presenter,{chart:{fontFamily:n},xAxis:{preventLabelOverlap:r}}=t.display,i=[],a=t.mainPane?.getBoundsWithoutScales()??new Eo(0,0,0,0);t.allAnnotations.concat(t.plotAnnotations).filter(e=>e.isVisible).forEach(n=>{i.push(...n.getTimeScaleAdornments().map(n=>{let r=this.annTimeToX(n.time);if(r<a.x||r>a.x+a.width)return null;let i=av(t,this.view.presenter?.display?.xAxis?.isOrdinal?n.time:this.xScale.xToTime(r)),o=e.measureText(i).width/2;return{x:r,value:i,color:n.color,halfWidth:o}}).filter(e=>e!=null))}),i.sort((e,t)=>e.x-t.x),r&&Jj(i,this.contentBounds),i.forEach(t=>{let r=xo(t.color),i=new zj({position:`bottom`,fontSize:this.config.fontSize,fontFamily:n,padding:this.config.indicatorPadding,strokeColor:B.COLOR_TRANSPARENT,textColor:r,backgroundColor:t.color,arrowLength:this.config.innerTickSize});this.axisStrips.forEach(({position:n,baseline:r})=>{i.configure({position:n}),i.draw(e,t.x,r+(n===`top`?-1:1),t.value)})}),e.restore()}drawCrosshair(e,{x:t}){if(!Number.isFinite(t))return!1;let n=this.view.presenter,r=n.display.xAxis,{enabled:i,showValue:a,color:o,dashStyle:s,format:c}=r.crosshair,l=this.xScale.xToTime(t);if(!(P(l)&&Fn(l)))return!1;if(!i)return!0;t=this.xScale.timeToX(l);let u=lo(s);e.strokeStyle=o,e.setLineDash(u);let d=is();d.prolog(e);let{y:f,height:p}=this.contentBounds;if(Bo(e,d.adjust(t),f,d.adjust(f+p)),d.epilog(e),!a||!r.visible)return!0;let m=av(n,l,P(r.format)?c:void 0);this.axisStrips.forEach(({position:n,baseline:r,bounds:i})=>{this.crosshairIndicator.configure({position:n}),this.crosshairIndicator.draw(e,t,r+(n===`top`?-1:1),m,void 0,i.height-2)});let{plotHover:h}=n.display.chart;return h&&n.allPlots.filter(e=>e.isVisible&&!n.shouldDimPlot(e)).forEach(n=>n.curves.forEach(n=>n.drawHover(e,l,t))),!0}},uM={mousedown:`onMouseDown`,mousemove:`onMouseMove`,mouseup:`onMouseUp`,dblclick:`onMouseDblClick`,contextmenu:`onContextMenu`,mouseover:`onMouseEnter`,mouseout:`onMouseLeave`,wheel:`onWheel`,touchstart:`onMouseDown`,touchmove:`onMouseMove`,touchend:`onMouseUp`,keydown:`onKeyDown`},dM={Shift:`shiftKey`,Alt:`altKey`,Control:`ctrlKey`,Meta:`metaKey`},fM=e=>e.startsWith(`touch`),pM=class{view;subscriptions=[];constructor(e){this.view=e}init(e){let t=Ie();Object.keys(uM).filter(e=>!fM(e)||t).forEach(t=>{let n=e=>{let n=uM[t];this.notifyActiveTool(n,e)===!0&&e.preventDefault()};e.addEventListener(t,n),this.subscriptions.push(()=>{e.removeEventListener(t,n)})})}shutdown(){this.subscriptions.forEach(e=>e()),this.subscriptions=[]}notifyActiveTool(e,t){let n=this.view.presenter;if(n===void 0||n.activeTool===null)return!1;let r=this.getPayload(t,n),i=n.activeTool,a=!1;return typeof i[e]==`function`&&(a=i[e](r)||!1),a}getPayload(e,t){let n=e instanceof MouseEvent,r=Ie()&&e instanceof TouchEvent;if(n||r){let i={x:0,y:0};if(r&&e.touches.length===1){let t=e.touches[0],{left:n,top:r}=e.target.getBoundingClientRect();i.x=t.clientX-n,i.y=t.clientY-r}else n&&(i.x=e.offsetX,i.y=e.offsetY);let a={button:n?e.which:E.Left,offset:i,view:t.view,presenter:t,originalEvent:e,getModifier:t=>e[dM[D[t]]]};if(e instanceof WheelEvent&&(a.delta=e.shiftKey?e.deltaX:e.deltaY),r&&e.touches.length===2){let t=e.touches[0],n=e.touches[1];a.pinchZoom=!0;let r=t.clientX-n.clientX,i=t.clientY-n.clientY;a.pinchDistance=Math.sqrt(r*r+i*i)}return this.view.splitters.forEach((e,t)=>{e?.contains(i)&&(a.splitter=[t,t+1])}),t.panes.forEach(e=>{let t=e.getBounds();if(P(t)&&t.contains(i)){let t=e.axes.find(e=>e.viewBox?.contains(i));if(t)a.priceAxis=t;else{let t=e.axes.find(e=>e.primary);t&&(a.point=t.toAnnotationPoint(i))}}}),a}else if(e instanceof KeyboardEvent)return{key:e.key??e.keyIdentifier,code:e.keyCode||e.charCode,repeat:e.repeat,presenter:t,getModifier:t=>e.getModifierState(D[t])}}},mM=Pg.concat(G.PercentChange);function hM(e){let t=[],n=new Map;for(let r of e){if(!r.isSeasonal){t.push([r]);continue}let e=n.get(r.uid);e||(e=[],n.set(r.uid,e),t.push(e)),e.push(r)}return t}function gM(e,t){let n=hM(t),r=e.isSeasonal?n.find(t=>t.some(t=>t.uid===e.uid)):void 0,i=[];return r&&i.push(r),n.forEach(e=>{e!==r&&i.push(e)}),i}function _M(e,t){return gM(e,t).flat().filter(t=>t!==e)}var vM=class{view;id;isOptionsChart=!1;constructor(e){this.view=e,this.id=`bc-legend-${bt()}`}getLegendElem(){let e=this.view.el;return aa(this.id,e,`div`)}update(){let e=this.getLegendElem(),t=Rv(this.presenter.mainPane);if(!P(t))return;this.isOptionsChart=this.mainPlot?.title?.startsWith(B.FAKE_SYMBOL_PREFIX)??!1;let{left:n,right:r,top:i,width:a}=t;Lk(e,`row`,n,r,i,a),oa(e,{"bcharts-card":!0,"bcharts-legend":!0});let o=this.mainPlot,s=o.isSeasonal||this.isOptionsChart?this.getFirstColorBadge(o):``,c=this.getPlotTitle(o),l=this.maybeGetQuote();if(o.isSeasonal){e.innerHTML=this.renderSeasonalLegend();return}e.innerHTML=`${this.div(`${s} ${c} `)+this.div(`${l}`)} ${this.maybeGetAdditionalPlots()}`}remove(){ta(this.getLegendElem())}get presenter(){return this.view.presenter}get mainPlot(){return this.presenter.mainPlot}getAttributes(e){return Object.entries(e).map(([e,t])=>t===null?``:`${e} = "${at(Array.isArray(t)?t.join(` `):t)}" `).join(` `)}span(e,t={}){return`<span ${this.getAttributes(t)}>${e}</span>`}div(e){return`<div class="plot" style="flex: 0 0 auto">${e}</div>`}spanAsPlot(e){return`<span class="plot" style="display:inline-flex; align-items:center">${e}</span>`}divAsGroup(e,t=!1){return`<div class="plot-group" style="display:block; flex:0 0 100%;${t?` margin-top:2px;`:``}">${e}</div>`}get meta(){return this.mainPlot.metaData}isSingleSymbolSeasonal(e){return e.isSeasonal&&!e.hasComputation}format(e,t,n){return(n??this.meta).format(e,t)}spanAsName(e){return this.span(it(e),{class:`field-name`})}spanAsValue(e,t=null,n=null){return this.span(it(e),{class:[`field-value`,t],style:n})}getQuoteFromRecord(e){let t=mM.map(t=>e.getValue(t));if(he(t)){let e=t[4],n=`field-${e>0?`up`:e<0?`down`:`same`}-value`;return`${t.slice(0,-1).map((e,t)=>{let r=mM[t],i=this.format(e,r),a=Uv(r);return`${this.spanAsName(a)}${this.spanAsValue(i,n)}`}).join(` `)} ${this.spanAsValue(`(${this.format(Se(t),Se(mM))})`,n)}`}return``}maybeGetQuote(){if(this.mainPlot.isSymbol&&this.mainPlot.timeSeries?.record?.isValid){let e=$().getRecordSource().getRecord(this.mainPlot.timeSeries.record.symbol);return this.getQuoteFromRecord(e)}else if(this.mainPlot.isExpression&&this.mainPlot.record.isValid){let e=this.mainPlot.record;return e.evaluate(),this.getQuoteFromRecord(e)}return``}getTitle(e,t,n,r=e.symbol){let i=t?`value-main`:null,a=`${it(e.name)} (${it(r)})`,o=this.span(a,{"data-plot-uid":n,class:[`value-title`,i]}),s=it(e.exchange);return`${o}${t?` ${this.span(s,{class:`value-subtitle`})}`:``}`}getPlotTitle(e){if(e.isSymbol){let t=Pv(e.title,e.metaData.symbol);return this.getTitle(e.metaData,e.main,e.uid,t)}else if(this.isSingleSymbolSeasonal(e)&&e.offset===0&&(e.symbols?.length??0)>0){let t=$().getMetaDataSource().getMetaData(e.getActualSymbols()[0]);return this.getTitle(t,!0,e.uid)}else{let t=it(Fv(e)??e.title);return this.span(t,{"data-plot-uid":e.uid,class:`value-title`})}}getCondensedSeasonalTitle(e){return!this.isSingleSymbolSeasonal(e)||!e.isPlain||!Ze(e.offset)?null:String(new Date().getFullYear()-e.offset)}getSeasonalFamilyTitle(e,t){if(t)return this.getPlotTitle(e);let n=this.getCondensedSeasonalTitle(e);return n?this.span(n,{"data-plot-uid":e.uid,class:`value-title`}):this.getPlotTitle(e)}renderSeasonalLegend(){let e=this.presenter.mainPane.axes.map(e=>e.plots).flat();return gM(this.mainPlot,e).map((e,t)=>{let n=e.map((e,t)=>{let n=this.getFirstColorBadge(e),r=e.isSeasonal?this.getSeasonalFamilyTitle(e,t===0):this.getPlotTitle(e);return this.spanAsPlot(`${n} ${r}`)}).join(` `);return e[0]?.isSeasonal?this.divAsGroup(n,t>0):n}).join(` `)}getFirstColorBadge(e){return Sv(`rectangle`,e.mainCurve.colors[0])}getLastValues(e){return this.isOptionsChart?``:tM(e).filter(e=>P(e.value)).map(t=>{let n=this.format(t.value,t.field,e.metaData);return this.spanAsValue(n,null,`color:${t.color}`)}).join(` `)}canBeDeleted(e){return e.isStudy||!e.main&&(e.isSymbol||this.isOptionsChart)}maybeGetAdditionalPlots(){let e=this.presenter.mainPane.axes.map(e=>e.plots).flat(),t=_M(this.mainPlot,e),n=this.presenter.display.yAxis.showLastValue;return t.length>0?t.map(e=>{let t=this.getFirstColorBadge(e),r=this.getPlotTitle(e),i=this.canBeDeleted(e)?Mv(e.uid):``,a=n!==`All`&&!e.isSeasonal?this.getLastValues(e):``;return this.div(`${i} ${t} ${r} ${a}`)}).join(` `):``}},yM=class{presenter;splitters=[];canvasContainer=null;mouseCanvas=null;mainCanvas=null;mouseContext;mainContext;leftOffset=0;rightOffset=0;legend;notifyLayoutChanged;el=null;listeners=[];tooltip;width;height;customEventPopup=null;goToLatestButton=null;xAxis;eventCapture;resetZoomAndVisibleRange=!1;constructor(){this.legend=new vM(this),this.draw=this.draw.bind(this),this.notifyLayoutChanged=qe(K.CH_CHTLAYOUTCHANGED,B.LAYOUT_THROTTLE_DELAY)}get canShowLegend(){if(!this.presenter.hasLegend)return!1;let e=this.presenter.display.chart.showLegend;return!(typeof e==`boolean`&&!e)}updateLegend(){this.canShowLegend&&this.legend.update()}removeLegend(){this.legend.remove()}findSvgParentWithClass(e,t){return[e,e.parentElement,e.parentElement.parentElement].find(e=>P(e)&&e.className===t)}onNonToolHandledMouseDown(e){let t=this.presenter,n=e.target;if(typeof n.className==`string`&&n.className.split(` `).includes(`value-title`))t.onCardClicked(n);else{let r=this.findSvgParentWithClass(n,`move-pane`);if(N(r)){t.onMovePaneClicked(r);return}let i=this.findSvgParentWithClass(n,`delete-plot`);if(N(i)){t.deletePlotClicked(i);return}let a=this.findSvgParentWithClass(n,`show-hide-plot`);if(N(a)){t.showHidePlotClicked(a);return}let o=this.findSvgParentWithClass(n,`more-actions`);if(N(o)){t.plotMoreActionsClicked(o,e);return}}}initialize(e){this.presenter=e,this.el=this.presenter.hostElement;let t=new ResizeObserver(e=>{for(let t of e){let{width:e,height:n}=t.contentRect;this.setSize(e,n,!0),P(this.tooltip)&&this.tooltip.repositionAuto()}});t.observe(this.el.parentElement),this.listeners.push(()=>t.unobserve(this.el.parentElement));let n=e=>this.onNonToolHandledMouseDown(e);this.el.addEventListener(`mousedown`,n),this.listeners.push(()=>this.el.removeEventListener(`mousedown`,n)),ra(this.el,{flex:1,display:`flex`,position:`relative`,"flex-direction":`column`,"touch-action":`pan-x pan-y`}),this.tooltip=new Pk(this);let r=$().config.getCustomEventPopup;this.customEventPopup=r?r(this):null;let{clientHeight:i,clientWidth:a}=this.el;this.width=a,this.height=i,this.canvasContainer=sa(this.el,`div`),ia(this.canvasContainer,{class:`chart-canvas-container`}),ra(this.canvasContainer,{flex:1,display:`flex`,"flex-direction":`column`,position:`relative`,height:`100%`}),this.mainCanvas=sa(this.canvasContainer,`canvas`);let o={height:`${i}px`,width:`${a}px`,"z-index":2,position:`absolute`,top:0,left:0};ra(this.mainCanvas,o),this.mouseCanvas=sa(this.canvasContainer,`canvas`),ia(this.mouseCanvas,{tabIndex:0}),o[`z-index`]=3,o.outline=`none`,ra(this.mouseCanvas,o),this.goToLatestButton=sa(this.el,`button`),la(this.goToLatestButton,`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
|
|
40
40
|
<path d="M13.707 17.707l5-5c0.391-0.391 0.391-1.024 0-1.414l-5-5c-0.391-0.391-1.024-0.391-1.414 0s-0.391 1.024 0 1.414l4.293 4.293-4.293 4.293c-0.391 0.391-0.391 1.024 0 1.414s1.024 0.391 1.414 0zM6.707 17.707l5-5c0.391-0.391 0.391-1.024 0-1.414l-5-5c-0.391-0.391-1.024-0.391-1.414 0s-0.391 1.024 0 1.414l4.293 4.293-4.293 4.293c-0.391 0.391-0.391 1.024 0 1.414s1.024 0.391 1.414 0z"></path>
|
|
41
41
|
</svg>`),ra(this.goToLatestButton,{position:`absolute`,right:0,bottom:0,"z-index":3}),ia(this.goToLatestButton,{class:`go-to-latest`}),this.goToLatestButton.onclick=()=>{this.xAxis.goToLatest()},this.listeners.push(()=>{this.goToLatestButton.onclick=null}),this.mainContext=this.mainCanvas.getContext(`2d`),this.mouseContext=this.mouseCanvas.getContext(`2d`),this.splitters=[],this.xAxis=new lM(this),this.eventCapture=new pM(this),this.eventCapture.init(this.mouseCanvas),this.setChartSize(a,i);let s=$i(this.el);P(na(`.${B.SVG_ICONS_DOM_NODE}`,s))||gv(s)}reinitialize(){this.el&&ca(`.bcharts-card`,this.el).forEach(e=>e.remove()),this.customEventPopup?.hide(),this.drawCrosshair({ap:void 0}),this.tooltip.hide(),this.tooltip.setMode(this.presenter.display.tooltip.mode),this.resetZoomAndVisibleRange?this.xAxis=new lM(this):this.xAxis?.updateConfigFromModel(),this.recalculateLayout(),this.redraw()}setSize(e,t,n=!1){this.setChartSize(e,t),this.redraw(n)}setChartSize(e,t){let n={width:`${e}px`,height:`${t}px`};ra(this.el,n),this.width=e,this.height=t;let r=globalThis.devicePixelRatio||1,i={height:this.height*r,width:this.width*r};[this.mainCanvas,this.mouseCanvas].forEach(e=>{ia(e,i),ra(e,n)}),this.mainContext.scale(r,r),this.mouseContext.scale(r,r),this.recalculateLayout(),this.presenter&&Fk(this.presenter)}widthNeeded(e,t){let n=this.presenter.allAxes.filter(e=>e.onTheRight===t&&e.plots.some(e=>e.isVisible&&e.hasVisibleCurves&&!e.hasDetachedScale));return n.length===0?0:Math.max(...n.map(t=>t.widthNeeded(e)))}recalculateLayout(){if(!this.isHostElementVisible)return;this.leftOffset=0,this.rightOffset=0,this.presenter.allAxes.forEach(e=>e.clearTicks()),this.splitters.length=0;let e=this.xAxis.heightNeeded(this.mainContext),t=this.widthNeeded(this.mainContext,!0),n=this.widthNeeded(this.mainContext,!1),r=this.xAxis.position===`bottom`?0:e,i=this.xAxis.position===`top`?0:e,a=Math.max(0,this.height-r-i),o=this.presenter.panes,s=pe(o.map(e=>e.height)),c=r,l=B.PANE_SPLITTER_PERCENT_HEIGHT/100,u=Math.floor(l*a);s*=1+(o.length-1)*l;let d=this.presenter.display?.yAxis?.primaryOnTheLeft??!1;this.presenter.display.yAxis.visible&&(o.some(e=>e.axes.length>1)?(this.leftOffset=n,this.rightOffset=t):d?this.leftOffset=n:this.rightOffset=t),o.forEach((e,n,r)=>{let i=n===r.length-1,o=Math.floor(a*e.height/s),l=new Eo(0,c,this.width,o);e.setViewBox(l);let d=new Eo(this.width-this.rightOffset,c,t,o),f=new Eo(0,c,this.leftOffset,o),p=e=>e.setViewBox(e.onTheRight?d:f);if(p(e.axes[0]),e.axes[1]&&p(e.axes[1]),c+=o,!i){let e=new Eo(this.leftOffset,c,this.width-this.rightOffset-this.leftOffset,u);this.splitters.push(e),c+=u}});let f=new Eo(this.leftOffset,r,this.width-this.rightOffset-this.leftOffset,c-r);this.xAxis.setViewBox(f,r,i),this.tooltip?.repositionForLayout(),ra(this.goToLatestButton,{right:`${t+5}px`,bottom:`${i+5}px`}),this.updateLegend(),this.xAxis.setDomain(),this.setPriceAxesDomains(),this.notifyLayoutChanged({chart:this.presenter.accessor})}setPriceAxesDomains(){this.presenter.allAxes.forEach(e=>{e.setDomain(),e.updateFullDomain()}),this.presenter.priceDomainsUpdated()}draw(){this.mainContext.save(),this.mainContext.miterLimit=1,this.drawBackground(this.mainContext);for(let e of this.presenter.panes)e.drawBackground(this.mainContext);this.xAxis.draw(this.mainContext);for(let e of this.presenter.panes)e.draw(this.mainContext);this.drawSplitters(this.mainContext),this.presenter.title.draw(this.mainContext),this.goToLatestButton.style.display=this.canShowGoToLatestButton()?`block`:`none`,this.mainContext.restore()}canShowGoToLatestButton(){let e=$().config.showGoToLatest,{showGoToLatest:t}=this.presenter.display.chart;return!!(P(e)?e:t)&&this.xAxis.panningXAxisAllowed&&this.xAxis.canGoToLast()}get isHostElementVisible(){return P(this.el)&&P(this.el.offsetParent)}redraw(e=!1){this.isHostElementVisible&&(e?this.draw():$().redraw(this.presenter.hostElement))}drawBackground(e){let t=this.presenter.display.chart.backgroundColor;e.clearRect(0,0,this.width,this.height),e.fillStyle=t,e.fillRect(0,0,this.width,this.height)}drawCrosshair({ap:e,offset:t}){let n=this.mouseContext;return n.clearRect(0,0,this.width,this.height),!e||!t||!this.xAxis||!this.xAxis.drawCrosshair(n,t)?!1:(this.presenter.display.yAxis.visible&&e.axis?.pane&&e.axis.pane.drawYCrosshair(n,t),!0)}drawSplitters(e){let t=this.presenter.display.chart.backgroundColor;e.strokeStyle=ho(t),e.lineWidth=2,this.splitters.forEach(t=>{let{x:n,y:r,width:i,height:a}=t,o=r+a/2;e.beginPath(),e.moveTo(n,o),e.lineTo(n+i,o),e.stroke()})}toTime(e){return this.xAxis.xScale.xToTime(e)}toIndex(e){return this.xAxis.xScale.timeToIndex(e)}toX(e){return this.xAxis.xScale.timeToX(e)}setCursor(e){let t=bM(e);ra(this.el,{cursor:t})}shutdown(){this.listeners.forEach(e=>e()),this.eventCapture&&this.eventCapture.shutdown(),this.tooltip&&this.tooltip.remove(),this.el&&ca(`.bcharts-card`,this.el).forEach(e=>e.remove()),this.canvasContainer.remove()}getEventRadius(){let e=this.xAxis.xScale.bar.width/2;return Math.max(e,B.MIN_EVENT_RADIUS)}};function bM(e){switch(e){case ee.Arrow:default:return`default`;case ee.Crosshair:return`crosshair`;case ee.Hand:return`pointer`;case ee.Move:return`move`;case ee.ResizeVertical:return`ns-resize`;case ee.Grabbing:return`grabbing`;case ee.ResizeHorizontal:return`ew-resize`}}var xM=class{view;popupElement;date;value;visible;_initialized;constructor(e){this.view=e,this.date=null,this.value=null,this.visible=!1,this._initialized=!1}initialize(){this.popupElement=sa(this.view.el,`div`),ia(this.popupElement,{id:`${this.view.presenter.elementId}-custom-event-host`}),ra(this.popupElement,{visibility:`hidden`,position:`absolute`,"z-index":30,top:`0px`,left:`0px`,padding:`5px 10px 10px 10px`,display:`flex`,"flex-direction":`column`,background:`var(--chartPopupElemBg, #999)`,"box-shadow":`0px 2px 10px rgba(0,0,0,.3)`,"border-radius":`4px`,border:`1px solid var(--chartPopupElemBorderColor, #888)`,"max-height":`400px`,overflow:`auto`});let e=sa(this.popupElement,`a`);ia(e,{class:`custom-event-close-button`}),ra(e,{position:`absolute`,right:`10px`,top:`5px`,fill:`var(--text-color,#888)`,cursor:`pointer`}),e.innerHTML=`<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="12px" height="12px"><use xlink:href="#bchart-icon-delete"></use></svg>`,e.addEventListener(`click`,e=>this.hide()),this._initialized=!0}showValue(){}show(e,t,n){this._initialized||this.initialize(),this.date=t,this.value!==n&&(this.value=n,this.showValue()),ra(this.popupElement,{visibility:`visible`,top:`${e.y}px`,left:`${e.x}px`,width:`310px`}),this.visible=!0}hideValue(){}hide(){this.visible&&=(this.hideValue(),ra(this.popupElement,{visibility:`hidden`}),!1)}};function SM(e,t){return U(e,`..axes[${t.axisIndex}]`,e=>(e.annotations=t.annotations,e))}function CM(e){return e.annotations&&e.annotations.length>0}function wM(e,t){CM(e)&&(t.annotations=(t.annotations||[]).concat(e.annotations))}var TM=`..axes{..plots{.type==="Study"}}`;function EM(e){return H(e,`..plots{.type==="Study"}.study`)}function DM(e,t){let n=EM(e),r=EM(t);return n.length===r.length&&_e(n,r)}function OM(e,t,n){let r=t.find(t=>!n.has(t)&&DM(e,t));if(N(r))return r;let[i]=EM(e);return t.find(e=>!n.has(e)&&i===EM(e)[0])}function kM(e,t){let{mainAxis:n}=Wd(e),{mainAxis:r}=Wd(t);wM(n,r);let i=H(e,TM).filter(e=>e!==n),a=H(t,TM).filter(e=>e!==r),o=new Set;return i.forEach(e=>{let t=OM(e,a,o);N(t)&&(o.add(t),wM(e,t))}),t}function AM(e,t){let n=e=>`..panes[${e}]`,r=e;return t.paneHeights.forEach(e=>{r=U(r,n(e.index),t=>(t.height=e.relativeHeight,t))}),r}var jM={ok:!1,change:void 0,toApply:void 0};function MM(e){return e.toolChange===O.Reordered}var NM=class{presenter;paused=null;undoStack=[];redoStack=[];initial=new Map;isPaused=!1;constructor(e){this.presenter=e,this.clear()}clear(e=!1){this.undoStack=[],this.redoStack=[],this.initial=new Map,e&&this.presenter.allAnnotations.forEach(e=>this.initial.set(e.uid,ok(e,O.Moved)))}rebindOwners(e){let t=new Set(this.presenter.panes.flatMap(e=>e.axes)),n=(e,n)=>{e.annotationUndoOwner.axis=n,n&&(n.annotationUndoOwner=e.annotationUndoOwner,t.delete(n))},r=e.flatMap(e=>e.axes);for(let e of[`annotations`,`plots`])r=r.filter(r=>{let i=new Set(r[e].map(e=>e.uid)),a=[...t].filter(t=>t[e].some(e=>i.has(e.uid)));return a.length===1?(n(r,a[0]),!1):!0});for(let e of r){let i=e.pane,a=i.axes.map(e=>e.annotationUndoOwner.axis?.pane),o=new Set(a.filter(e=>e&&this.presenter.panes.includes(e))),s=o.size===1?[...o][0]:void 0,c=s?[...t].filter(e=>e.pane===s):[],l=e.plots.length===0&&e.annotations.length===0,u=r.filter(e=>e.pane===i).length===1;n(e,l&&u&&c.length===1?c[0]:void 0)}}done(e){if(this.isPaused){this.paused=e;return}this.undoStack.push(e),this.redoStack.length=0}undo(){this.undoRedo(this.undoStack,this.redoStack,!0)}pause(){this.isPaused=!0}resume(e){this.isPaused=!1,e&&N(this.paused)&&this.done(this.paused),this.paused=null}redo(){this.undoRedo(this.redoStack,this.undoStack,!1)}delete(e){let t={...e,id:`Delete`};this.presenter.handleAnnotationChange(t)}add(e){let t={annotation:e,id:`Add`};this.presenter.handleAnnotationChange(t)}applyOrder(e,t){let n=this.presenter.allAnnotations.find(t=>t.uid===e.uid)?.axis??e.owner?.axis;if(!n)return;let r=t?e.before:e.after,i=n.annotations.filter(e=>r.includes(e.uid));if(i.length<2)return;i.sort((e,t)=>r.indexOf(e.uid)-r.indexOf(t.uid));let a=0;n.annotations=n.annotations.map(e=>r.includes(e.uid)?i[a++]:e),this.presenter.onAnnotationsUpdated(n),this.presenter.view?.redraw();let o=n.annotations.find(t=>t.uid===e.uid),s=t?O.Undo:O.Redo;o&&this.presenter.onAnnotationModifiedByTool(o,s,!1,!0)}apply(e,t,n=!1){if(!P(e))return!1;if(MM(e))return this.applyOrder(e,n),!0;let r=e;switch(t){case O.None:case O.Undo:case O.Redo:I(`Unexpected tool change ${O[t]} for undo/redo`,`warn`);break;case O.Created:n?this.delete(r):this.add(r);break;case O.Deleted:n?this.add(r):this.delete(r);break;default:{let e={...r,id:`Update`};this.presenter.handleAnnotationChange(e);break}}let i=this.presenter.allAnnotations.find(e=>e.uid===r.uid),a=n?O.Undo:O.Redo;return P(i)&&this.presenter.onAnnotationModifiedByTool(i,a),!0}can(e){let t=e?this.undoStack:this.redoStack;if(t.length<1)return jM;let n=Se(t),r=n.toolChange;if(MM(n)||!(e&&r!==O.Deleted&&r!==O.Created))return{ok:!0,change:r,toApply:n};let i=we(t,e=>e.uid===n.uid&&!MM(e),t.length-2),a=i===-1?null:t[i],o=a===null;return o&&!this.initial.has(n.uid)?jM:{ok:!0,change:r,toApply:o?this.initial.get(n.uid):a}}get canUndo(){return this.can(!0).ok}get canRedo(){return this.can(!1).ok}undoRedo(e,t,n){let{ok:r,change:i,toApply:a}=this.can(n);r&&this.apply(a,i,n)&&t.push(e.pop())}},PM=class{presenter;text=null;align=`center`;verticalAlign=`top`;x=0;y=0;style={color:`#333`,fontSize:18};constructor(e){this.presenter=e}update({style:e,...t}){Object.assign(this,t),Object.assign(this.style,e)}draw(e){if(!this.text)return;let{fontFamily:t}=this.presenter.display.chart,{fontSize:n,color:r,fontWeight:i}=this.style,{x:a,y:o,width:s,height:c}=this.presenter.mainPlot.axis.pane.getBounds(),l=a+this.presenter.view.leftOffset,u=a+s-this.presenter.view.rightOffset,d=l;d=this.align===`center`?s/2:this.align===`right`?u:l;let f=o+n;this.verticalAlign===`middle`?f=o+n+c/2:this.verticalAlign===`bottom`&&(f=o+c),d+=this.x,f+=this.y,e.save(),e.font=`${i||`normal`} ${n}px ${t}`,e.textAlign=this.align,e.textBaseline=`bottom`,e.fillStyle=r,e.fillText(this.text,d,f),e.restore()}};function FM(e){let t=e.offset;return typeof t==`number`?t:void 0}function IM(e,t,n){let r=t.axis,i=r?.pane,a=i?e.panes.indexOf(i):-1,o=i&&r?i.axes.indexOf(r):-1,s=r?r.plots.indexOf(t):-1,c=t.uid??t.id,l=FM(t);return{id:typeof l==`number`&&(t.isSeasonal||t.isForward)?`${c}:${l}`:c,plotUid:c,plotType:C[t.type],plotTitle:Fv(t)??t.title,fieldIds:n.map(({field:e})=>e.id),seasonalOffset:t.isSeasonal?l:void 0,paneIndex:a,axisIndex:o,plotIndex:s,main:t.main}}function LM(e){return e.view?.xAxis?.xScale.extent()??null}function RM(e,t,n){let r=new Map;return t.main&&(r.set(G.DateTime,{field:G.DateTime,shift:0}),e.data.aggregation.isMultiContract&&!t.isExpression&&r.set(G.Symbol,{field:G.Symbol,shift:0})),t.curves.forEach(e=>{e.fields.forEach(t=>{n.includes(t.id)||r.set(t,{field:t,shift:e.shift})})}),Array.from(r.values())}function zM(e,t){let n=t.excludeFields??[],r=e.allPlots.map(t=>{let r=RM(e,t,n);return{plot:t,fields:r,source:IM(e,t,r)}}).filter(({fields:e})=>e.length>0);return t.sourceOrder?r.map((e,t)=>({source:e,index:t})).sort((e,n)=>t.sourceOrder(e.source.source,n.source.source)||e.index-n.index).map(({source:e})=>e):r}function BM(e,t,n){let r=`${t.id}.${n.id}`,i=r,a=2;for(;e.has(i);)i=`${r}.${a++}`;return e.add(i),i}function VM(e){let t=new Set;return e.flatMap(({source:e,fields:n})=>n.map(({field:n})=>({id:BM(t,e,n),name:n.name,fieldId:n.id,source:e})))}function HM(e,t){let n=[0,0];return e.allCurves.forEach(e=>{e.fields.every(e=>t.includes(e.id))||(e.shift<0&&(n[0]=Math.min(n[0],e.shift)),e.shift>0&&(n[1]=Math.max(n[1],e.shift)))}),n}function UM(e,t){return t.some(t=>{if(t.fieldId===G.DateTime.id)return!1;let n=e[t.id];return n!=null&&n!==``})}function WM(e,t,n,r,i,a){let o=e.timeline.at(r),s=n.plot.timeSeries.container,c=s.getTimeData(),l=t[n.plot.id]||0,u=j(c,+o,Number,Te,l),d=+o==+c[u];if(d&&(t[n.plot.id]=u),a===0)return d?s.getData(i)[u]??``:i===G.DateTime?o:``;let f=e.timeline.at(r-a);if(!P(f))return``;let p=j(c,+f,Number,Te,0);return+f==+c[p]?s.getData(i)[p]??``:``}function GM(e={}){let t=this.allPlots,n=t.every(e=>P(e.timeSeries)&&e.timeSeries.hasData),r=this.data.aggregation.isEndOfDay?B.FMT_ISO_DATE_ONLY:B.FMT_EXPORT_ALL_BUT_MILLIS;if(!n||t.length===0)return{columns:[],rows:[],dateFormatHint:r};let i=e.excludeFields??[],a=zM(this,e),o=VM(a),s={},c=this.timeline.lastSeriesIndex,l=Ce(this.mainPlot.timeSeries.container.getTimeData()),u=j(this.timeline,+l,Number,fv),d=HM(this,i),f=e.visibleRange?LM(this):null,p=f?f[0]:u+d[0],m=f?f[1]:c+d[1],h=[];for(let e=p;e<=m;e++){let t={};a.forEach(n=>{n.fields.forEach(({field:r,shift:i})=>{let a=o.find(e=>e.source===n.source&&e.fieldId===r.id);t[a.id]=WM(this,s,n,e,r,i)})}),UM(t,o)&&h.push(t)}return{columns:o,rows:h,dateFormatHint:r}}function KM(e){return`"${e}"`}function qM(e,t,n,r){return e instanceof Date?Yr(e,n.dateFormatHint??B.FMT_EXPORT_ALL_BUT_MILLIS):typeof e==`number`&&P(r.numDecimals)?Xe(e,r.numDecimals)?.toString()??``:e?.toString()??``}function JM(e,t){return t?.source.id===e.source.id?``:KM(`${e.source.plotType}: ${e.source.plotTitle}`)}function YM(e,t={}){if(e.columns.length===0)return`No data to export`;let n=t.excludeHeader??!1,r=[];return n||(r.push(e.columns.map((t,n)=>JM(t,e.columns[n-1]??null)).join(`,`)),r.push(e.columns.map(e=>KM(e.name)).join(`,`))),e.rows.forEach(n=>{let i=e.columns.map(r=>qM(n[r.id],r,e,t));e.columns.some((e,t)=>e.fieldId!==G.DateTime.id&&i[t].length>0)&&r.push(i.join(`,`))}),r.join(`
|
|
42
|
-
`)}function XM(e={}){return YM(GM.call(this,e),e)}function ZM(e={}){let t=this.view.mainCanvas,{width:n,height:r}=t,{width:i,height:a,title:o}=e,s=(e,t)=>{let n=document.createElement(`canvas`);return n.width=e,n.height=t,n.getContext(`2d`)},c=s(n,r),l=globalThis.devicePixelRatio;if(c.drawImage(t,0,0),c.scale(l,l),N(o)){let e=new PM(this);e.update(o),e.draw(c)}let u=this.mainPlot?.timeSeries.container?.getLastDataPoint(G.DateTime);if(N(u)){let{fontFamily:e}=this.display.chart,{fontWeight:n,fontSize:r}=this.mainAxis.config;c.font=`${n} ${r*1.2}px ${e}`,c.textBaseline=`top`;let i=r*1.5,a=getComputedStyle(t),o=a.getPropertyValue(`--app-hc-color`),s=a.getPropertyValue(`--app-color-pl`),l={x:B.CARDS_X_OFFSET,y:B.CARDS_Y_OFFSET},d=Iv(this,u,l,void 0,!1,0),f=`${d.date} ${d.time??``}`.trim(),[p,m]=[1,5],h=(e,t)=>c.measureText(e).width+t,g=(e,t,n,r,i)=>(c.fillStyle=r,c.fillText(e,t,n),h(e,i)),_=(e,t)=>e.type===C[t],v=e=>{let t=e.name;return e.isMain&&_(e,`Symbol`)?t=`${e.description} (${e.name}) [${e.exchange}]`:_(e,`Study`)&&(t=`${e.description} ${e.name.substring(e.name.indexOf(` `))}`),t};d.panes.forEach(e=>{let{top:t,left:n,width:r,right:a}=e.bounds,c=n+r-a-m,u=n+l.x,d=t+l.y;e.plots.some(e=>e.isMain)&&(u+=g(f,u,d,o,m)),e.plots.forEach((e,t)=>{let r=v(e),a=!_(e,`Study`)&&e.values.length>1;if(!e.isMain&&t>0){let t=u+h(r,m);e.values.forEach(e=>{a&&(t+=h(e.abbreviation,p)),t+=h(e.value,m)}),t>=c&&(u=n+l.x,d+=i)}u+=g(r,u,d,o,m),e.values.forEach(e=>{a&&(u+=g(e.abbreviation,u,d,s,p)),u+=g(e.value,u,d,e.color,m)})})})}let d=e=>({width:i??n,height:a??r,data:e.toDataURL(`image/png`)});if(N(i)&&N(a)){let e=s(i,a);return e.drawImage(c.canvas,0,0,i,a),d(e.canvas)}else return d(c.canvas)}function QM(e){if(e!==void 0)return e===B.YTD_PERIOD?e:vt(e)}var $M=Symbol.for(`__ias__`),eN=class{accessor;view;defaultTool;_activeTool;tooltipEnabled=!0;timeline;sentInitialLoadNotification=!1;_hostElement=null;undoRedoManager;title;display;model;data;panes=[];_hasLegend;renderTo;seriesChangedToken=``;metaChangedToken=``;streamingSubscription=null;_previousMask=0;_ohlcMask;selectedAnnotation;annotationPreviewUid;hoverHighlightPlotIds=null;hoverDimPlotIds=null;hoverBasisByDependentPlotId=new Map;hoverDependentsByBasisPlotId=new Map;hoverHighlightablePlotIds=new Set;forceResetVisibleRange=!1;_maxOffset=0;_isShutdown=!1;notifySelectionChanged;notifyRecreated;notifyDefinitionChanged;constructor(e){this.accessor=e,this.defaultTool=Cj(`Default`),this._activeTool=this.defaultTool,this.timeline=new pv(this),this.undoRedoManager=new NM(this),this.title=new PM(this),this.notifySelectionChanged=Ke(K.CH_ANNSELECTIONCHANGED),this.notifyRecreated=Ke(K.CH_RECREATED),this.notifyDefinitionChanged=Ke(K.CH_DEFINITION_CHANGED)}traceChart(e,t={}){Lh(e,{chartId:this.elementId,...t})}getModel(){return this.model}get isEmpty(){return!P(this.model)}notifyHost(e,t){Ge(e,t)}async fromModel(e,t){if(this._isShutdown)return;this.traceChart(`chart:fromModel:start`,{hadModel:P(this.model)}),P(this.model)&&this.allPlots.forEach(e=>e.shutdown()),this.sentInitialLoadNotification=!1,this.clearHoverHighlight(),this.clearHoverHighlightRelations(),this.annotationPreviewUid=void 0,this.clearSelection(),this.model=e;let n=F(e);this.data=n.data,this.data.aggregation=Mu(n.data.aggregation),this.display=n.display,this.display.period=QM(n.display?.period);let r=this.panes;this.panes=n.panes.map(e=>{let t=new aM(this);return t.fromModel(e),t},this),this.undoRedoManager.rebindOwners(r);let i=this.allPlots.map(e=>e.initialize());await Promise.all(i),!this._isShutdown&&(this.rebuildHoverHighlightRelations(),this.traceChart(`chart:fromModel:plots-ready`,{plotCount:this.allPlots.length}),this.timeline.invalidate(),this.checkZoomAndVisibleRange(e,t),P(e,t)&&this.notifyDefinitionChanged({chart:this.accessor}),this.reinitializeView())}checkZoomAndVisibleRange(e,t){if(this.view)if(this.forceResetVisibleRange)this.forceResetVisibleRange=!1,this.view.resetZoomAndVisibleRange=!0,this._maxOffset=0;else{let n=!t||aN(e,t,this);this.view.resetZoomAndVisibleRange=n,n&&(this._maxOffset=0)}}closeView(){P(this.view)&&(this.view.shutdown(),this.view=void 0)}reinitializeView(){this._isShutdown||(P(this.view)?this.view.reinitialize():(this.view=new yM,this.view.initialize(this)),this.notifyRecreated({elementId:this.elementId}))}getCacheableEntities(e){let t={metaData:e.metaData.size,records:e.records.size,timeSeries:e.timeSeries.size};this.isEmpty||this.allPlots.map(t=>t.getCacheableEntities(e)),this.traceChart(`chart:cacheable-entities`,{plotCount:this.allPlots.length,addedMetaData:e.metaData.size-t.metaData,addedRecords:e.records.size-t.records,addedTimeSeries:e.timeSeries.size-t.timeSeries})}get activeTool(){return this._activeTool}set activeTool(e){P(this._activeTool.deactivated)&&this._activeTool.deactivated(this),this._activeTool=e,P(this._activeTool.activated)&&this._activeTool.activated(this),this.notifyHost(K.TL_CHANGED,{chart:this.accessor})}get mainPlot(){return this.allPlots.find(e=>e.main)}get mainAxis(){return this.mainPlot?.axis}get mainPane(){return this.mainAxis?.pane}get allAxes(){let e=[];return this.panes.forEach(t=>{t.axes.forEach(t=>{e.push(t)})}),e}get plotAnnotations(){let e=[];return this.allPlots.forEach(t=>{t.isVisible&&t.annotations?.forEach(t=>{e.push(t)})}),e}get allAnnotations(){let e=[];return this.allAxes.forEach(t=>{t.annotations.forEach(t=>{e.push(t)})}),e}get allPlots(){let e=[];return this.allAxes.forEach(t=>{t.plots.forEach(t=>{e.push(t)})}),e}findAxis(e){return this.allAxes.find(t=>t.id===e)}findPlot(e){return this.allPlots.find(t=>t.id===e)}get allCurves(){let e=[];return this.allPlots.forEach(t=>{t.curves.forEach(t=>{e.push(t)})}),e}findCurve(e){return this.allCurves.find(t=>t.id===e)}get hasStudyBasisFocus(){return this.display?.chart?.studyBasisFocus===!0}get hasHoverHighlight(){return this.hoverHighlightPlotIds!==null||this.hoverDimPlotIds!==null}getStudyBasis(e){return e.isStudy?e.basePlot??null:null}isHoverSourcePlot(e){return e.isSeasonal||e.isSymbol}hasMultipleHoverSourcePlots(){return this.allPlots.filter(e=>e.isVisible&&this.isHoverSourcePlot(e)).length>1}get annotationManipulation(){return $()?.config.annotationManipulation===!0}setAnnotationPreview(e){this.annotationPreviewUid!==e&&(this.annotationPreviewUid=e,this.view?.redraw())}clearHoverHighlight(){this.hoverHighlightPlotIds=null,this.hoverDimPlotIds=null}clearHoverHighlightRelations(){this.hoverBasisByDependentPlotId.clear(),this.hoverDependentsByBasisPlotId.clear(),this.hoverHighlightablePlotIds.clear()}rebuildHoverHighlightRelations(){if(this.clearHoverHighlight(),this.clearHoverHighlightRelations(),this.hasStudyBasisFocus&&this.hasMultipleHoverSourcePlots())for(let e of this.allPlots){if(this.isHoverSourcePlot(e)&&this.hoverHighlightablePlotIds.add(e.id),!e.isStudy)continue;let t=this.getStudyBasis(e);if(!P(t))continue;this.hoverBasisByDependentPlotId.set(e.id,t.id);let n=this.hoverDependentsByBasisPlotId.get(t.id);P(n)||(n=new Set,this.hoverDependentsByBasisPlotId.set(t.id,n)),n.add(e.id),this.hoverHighlightablePlotIds.add(e.id),this.hoverHighlightablePlotIds.add(t.id)}}isHoverHighlightable(e){return this.hasStudyBasisFocus&&P(e)&&this.hoverHighlightablePlotIds.has(e.id)}getRelatedHoverPlotIdsForPlot(e){if(!this.isHoverHighlightable(e))return null;let t=new Set,n=this.hoverBasisByDependentPlotId.get(e.id);if(P(n))return t.add(e.id),t.add(n),t;let r=this.hoverDependentsByBasisPlotId.get(e.id);return P(r)&&r.size>0?(t.add(e.id),r.forEach(e=>t.add(e)),t):(t.add(e.id),t)}getRelatedHoverPlotIds(e){let t=new Set;for(let n of e){let e=this.getRelatedHoverPlotIdsForPlot(n);e!==null&&e.forEach(e=>t.add(e))}return t.size>0?t:null}getHoverDimPlotIds(e){if(!this.hasStudyBasisFocus||e===null)return null;let t=new Set;for(let n of this.hoverHighlightablePlotIds)e.has(n)||t.add(n);return t}sameHoverHighlight(e){let t=this.hoverHighlightPlotIds;if(t===null||e===null)return t===e;if(t.size!==e.size)return!1;for(let n of t)if(!e.has(n))return!1;return!0}setHoverHighlight(e){if(!this.hasStudyBasisFocus)return this.hasHoverHighlight&&(this.clearHoverHighlight(),this.view?.redraw()),!1;let t=this.getRelatedHoverPlotIds(e);return this.sameHoverHighlight(t)?this.hoverHighlightPlotIds!==null:(this.hoverHighlightPlotIds=t,this.hoverDimPlotIds=this.getHoverDimPlotIds(t),this.view?.redraw(),t!==null)}shouldDimPlot(e){return this.hasStudyBasisFocus&&(this.hoverDimPlotIds?.has(e.id)??!1)}fixupDensityForForwards(){let e=this.allPlots.filter(e=>e.isForward).map(e=>e.timeSeries.container?.size??0);e.some(e=>e>0)&&(this.display.density=Math.max(...e))}onSeriesChanged(e,t){if(!this.view||!this.allPlots)return;let n=t.series,r=e=>e.timeSeries===n||e.eventsSeries===n,i=this.allPlots.find(r);if(!P(i))return;let a=P(i)&&i.main,o=!1,s=!1;if(e===K.TS_TIMELINECORRECTION){if(!this.timeline.tryToCorrectLastBar(t.from,t.to))return;o=!0}let c=P(t.index)?n.container.getTimeData()[t.index]:null,l=e===K.TS_EVENTSCHANGED,u=this.view.xAxis,d=u.xScale;if(e===K.TS_MANYCHANGED||l){if(a&&this.data.checkRange)if(P(this.display.xAxis.visibleRange)){let e={id:`Period`,context:{range:this.display.xAxis.visibleRange}};e[$M]=!0,this.accessor.change(e);return}else delete this.data.checkRange;i.isForward&&this.fixupDensityForForwards();let e=this.view.xAxis?.getMaxCurveOffset()??0;i.isStudy&&(e!==this._maxOffset&&(this._maxOffset=e,u.goToLatest(!0)),i.invalidateAssociatedAnnotations(`NewChunkArrived`));let n=P(this.display?.xAxis?.visibleRange);if((i.isSeasonal&&!u.wasVisibleRangeChanged&&!n||this.display?.xAxis?.isOrdinal)&&u.goToLatest(!0),t.part===re.Tail){let e=j(this.timeline,c,Number,fv);u.shouldScrollIntoView(e)&&d.shiftBars(t.count)}this.timeline.invalidate(),this.allPlots.forEach(e=>e.invalidatePriceMappingCache()),o=!0}else if(e===K.TS_DATAPOINTADDED){let e=this.timeline.mergeDateIntoTimeline(c);e!=-1&&u.shouldScrollIntoView(e)?(d.shiftBars(1),o=!0):s=!0,i.isStudy&&i.invalidateAssociatedAnnotations(`DataPointAdded`)}else e===K.TS_DATAPOINTCHANGED&&(s=!0,i.isStudy&&i.invalidateAssociatedAnnotations(`DataPointChanged`));if(!l&&r(this.mainPlot)&&n.hasData&&n.container.size===0&&this.notifyHost(K.CH_NODATAFORMAINSYMBOL,{chart:this.accessor}),o&&this.view.recalculateLayout(),s&&(o&&I(`Performance : redundant call to recompute price domains (layout recalculation took care of this)`,`warn`),this.allAxes.filter(e=>e.plots.includes(i)).forEach(e=>{e.setDomain(),P(c)&&e.updateFullDomain(c)})),!this.sentInitialLoadNotification&&e===K.TS_MANYCHANGED&&this.allPlots.every(e=>e.timeSeries&&e.timeSeries.hasData)){this.sentInitialLoadNotification=!0,this.notifyHost(K.CH_ALL_DATA_PROJECTED,{chart:this.accessor}),Fk(this);let e=this.display.period===B.FIFTY_YEARS_MILLIS;this.mainPlot&&e&&(d.fitAllData=!0,d.adjustDomain())}this.view.redraw()}onMetaChanged(e,t){e===K.MD_CHANGED&&this.view&&this.allPlots&&this.allPlots.find(e=>e.id===t.plot.id)&&(t.plot.main&&this.allAnnotations.forEach(e=>e.onFormatterChanged()),this.view.recalculateLayout(),this.view.redraw())}priceDomainsUpdated(){this.allPlots.forEach(e=>{e.notifyAboutPriceDomains&&e.onPriceDomainsUpdated()})}onScaleDomainChanged(e){let t=this.panes.indexOf(e.pane),n=e.pane.axes.indexOf(e),r={chart:this.accessor,paneIndex:t,axisIndex:n};this.notifyHost(K.CH_AXISSCALECHANGED,r)}get previousMask(){return P(this._previousMask)||(this._previousMask=Hf(G.PreviousClose)),this._previousMask}hasMatch(e,t){return e.some(e=>e.updated&&t)}get hasLegend(){if(!P(this._hasLegend)){let e=ne[$()?.config.mode??`Unspecified`];this._hasLegend=[ne.cmdtyView,ne.EqPlus].includes(e)}return this._hasLegend}onStreamingUpdates(e){P(this.view)&&(this.mainPlot.showPrevious&&this.hasMatch(e,this.previousMask)&&this.view.redraw(),this.hasLegend&&this.hasMatch(e,this.ohlcMask)&&this.view.updateLegend())}get ohlcMask(){return P(this._ohlcMask)||(this._ohlcMask=Hf(G.Open,G.High,G.Low,G.Close,G.PreviousClose)),this._ohlcMask}updateMatches(e,t){if((e&this.ohlcMask)===0)return!1;let n=(e,t)=>N(e)&&e.isValid&&e.hasSymbol(t);return this.mainPlot.isSymbol?n(this.mainPlot.timeSeries.record,t):this.mainPlot.isExpression?n(this.mainPlot.record,t):!1}getStreamingSubscription(){return $().getRecordSource().subject.pipe(Mm(e=>e.filter(e=>this.updateMatches(e.updated,e.data.symbol))),Fm(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}get hostElement(){return this._hostElement}get elementId(){return P(this._hostElement)?this._hostElement.id:null}initialize(e){if(this._hostElement=e instanceof HTMLElement?e:na(`#${e}`),!this._hostElement)throw Error(`There is no element ${e} in the DOM`);this.renderTo=e,this.seriesChangedToken=eb.default.subscribe(K.TS_ALL,this.onSeriesChanged.bind(this)),this.metaChangedToken=eb.default.subscribe(K.MD_ALL,this.onMetaChanged.bind(this)),this.streamingSubscription=this.getStreamingSubscription()}shutdown(){return eb.default.unsubscribe(this.seriesChangedToken),eb.default.unsubscribe(this.metaChangedToken),P(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.allPlots.forEach(e=>e.shutdown()),this.model=void 0,this.closeView(),this.notifyHost(K.CH_SHUTDOWN,{elementId:this.elementId}),this._isShutdown=!0,!0}setSelection(e){this.selectedAnnotation!==e&&(this.selectedAnnotation&&this.clearSelection(),this.selectedAnnotation=e,this.selectedAnnotation.isSelected=!0,this.selectedAnnotation.requestRedraw(),this.notifySelectionChanged({chart:this.accessor}))}clearSelection(){P(this.selectedAnnotation)&&(this.selectedAnnotation.isSelected=!1,this.selectedAnnotation.requestRedraw(),this.selectedAnnotation=void 0),this.notifySelectionChanged({chart:this.accessor})}resetActiveTool(){this.activeTool=this.defaultTool,this.view.setCursor(ee.Arrow)}print(e={}){let t=sa(document.body,`iframe`);t.src=``,t.style.display=`none`,t.onload=()=>{let{title:n}=e,r=ZM.call(this,{title:n}),i=new Image;i.src=r.data,i.style.width=`100%`,t.contentDocument.body.appendChild(i),ua(i).then(()=>{let e=t.contentWindow;t.focus(),e.print(),t.remove()})}}setTitle(e,t=!1){this.title.update(e),P(this.view)&&this.view.redraw(t)}enableTooltip(e){this.tooltipEnabled=e;let t=this.display.tooltip.mode===B.TOOLTIP_CARDS;!e&&t&&this.hideCards()}get showTooltip(){return this.display.tooltip.visible&&this.tooltipEnabled}hideCards(e=!1){let t=this.display.tooltip,n=Ie();!e&&t.visible&&t.mode===B.TOOLTIP_CARDS&&ca(`.bcharts-card`,this.hostElement).forEach(e=>{let t=e.classList.contains(`bcharts-card-move`);n&&t||e.classList.contains(`bcharts-legend`)||(e.style.display=`none`)})}handleAnnotationChange(e){let t=(e,t=!0)=>({id:t?e.name:e.id,uid:e.uid,visible:e.visible});if(e.id===`List`)return this.allAnnotations.map(t);if(e.id===`Cache`)return H(this.model,`..annCache{.annotations}`).map(e=>({symbol:e.symbol,annotations:e.annotations.map(e=>t(e,!1))}));if(e.id===`Add`){let t=e.annotation;return(t.isUndoRedo?t.owner?.axis??this.mainAxis:this.mainAxis)?.addAnnotation(t)}let n=this.allAnnotations.find(t=>t.uid===e.uid);if(n!==void 0){if(e.id===`Delete`&&!e.isUndoRedo)return this.deleteAnnotationWithUndo(n);let t=n.axis,r=t[`${e.id.toLowerCase()}Annotation`];if(typeof r==`function`){r.call(t,n,e);return}}throw Error(`Unknown sub-action ${e.id} for action ${B.ANN_ACTION_ID}`)}deleteAnnotationWithUndo(e){this.undoRedoManager.done(ok(e,O.Deleted)),e.axis.deleteAnnotation(e),this.onAnnotationModifiedByTool(e,O.Deleted,!1)}getPlotInfoFromDom(e){let t=e.attributes.getNamedItem(`data-plot-uid`);if(!t)throw Error(`Unable to resolve plot info: missing data-plot-uid attribute.`);let n=t.value,r=0;for(let e of this.model.panes)for(let t of e.axes)for(let e of t.plots){if(e.uid===n)return{type:e.type,index:r};r++}throw Error(`Unable to resolve plot info: model plot index not found for uid '${n}'.`)}getSimplePlot(e,t){return this.accessor.change({id:`Plot`,context:{id:B.ACTION_GET,type:e,index:t}})[0]}onCardClicked(e){let t=this.getPlotInfoFromDom(e),n=this.getSimplePlot(t.type,t.index),r={chart:this.accessor,plot:n};this.notifyHost(K.CH_CARDPLOTCLICKED,r)}deletePlotClicked(e){let t=this.getPlotInfoFromDom(e),n=this.getSimplePlot(t.type,t.index);this.accessor.change({id:`Plot`,context:{id:`Delete`,type:t.type,index:t.index}});let r={chart:this.accessor,plot:n};this.notifyHost(K.CH_CARDPLOTREMOVED,r)}showHidePlotClicked(e){this.defaultTool.hideCrosshairAndTooltips(this.view,!0);let t=this.getPlotInfoFromDom(e),n=e.attributes.getNamedItem(`data-act`).value===`Show`;this.accessor.change({id:`Plot`,context:{id:`Update`,type:t.type,index:t.index,visible:n}});let r=this.getSimplePlot(t.type,t.index),i={chart:this.accessor,plot:r,visible:n};this.notifyHost(K.CH_CARDPLOTVISIBILITYCHANGED,i)}plotMoreActionsClicked(e,t){let n=this.getPlotInfoFromDom(e),r=this.getSimplePlot(n.type,n.index),i={x:t.clientX,y:t.clientY},a={chart:this.accessor,plot:r,offset:i,originalEvent:t};this.notifyHost(K.CH_PLOTNEEDSCONTEXTMENU,a)}onMovePaneClicked(e){let t=parseInt(e.attributes.getNamedItem(`data-pane`).value),n=e.attributes.getNamedItem(`data-dir`).value===`Down`,r=t+ +!!n,i=t-+!n;setTimeout(()=>{this.accessor.change({id:`MovePane`,context:{from:r,to:i}}),this.notifyHost(K.CH_PANESREORDERED,{chart:this.accessor})})}onAnnotationsUpdated(e,t=!1){let n=this.allAxes.indexOf(e),r=e.annotations.map(e=>e.toModel()),i=SM(this.model,{axisIndex:n,annotations:r});try{this.model=Nf(i,B.CHART_SCHEMA)}catch(e){I(`Cannot update annotation (corrupts definition), error is: ${e.message}`,`error`)}t&&this.view.draw(),this.notifyHost(K.CH_ANNOTATIONCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}onAnnotationModifiedByTool(e,t,n=!0,r=!1){if(t!==O.None){if(n&&t!==O.Undo&&t!==O.Redo){let n=ok(e,t);this.undoRedoManager.done(n)}let i=sk(e);i.toolChange=O[t],(r||t===O.Reordered)&&(i.orderOnly=!0),this.notifyHost(K.CH_ANNMODIFIEDBYTOOL,i)}}onAnnotationDone(e,t){let n={id:e,chart:this.accessor,toolChange:O[t]};this.notifyHost(K.CH_ANNMODIFIEDBYTOOL,n)}onPaneHeightsUpdated(){let e=this.panes.map((e,t)=>({index:t,relativeHeight:e.height}));this.model=AM(this.model,{paneHeights:e}),this.notifyHost(K.CH_PANEHEIGHTSCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}getDataStats(){let e=this.mainPlot.timeSeries.container;if(!P(e)||e.size===0)return null;let t=e.getTimeData(),n=Ce(t),r=Se(t);return P(n,r)?{dataRange:{from:n.getTime(),to:r.getTime()},barCount:e.size}:null}};function tN(e,t){return e?.from===t?.from&&e?.to===t?.to}var nN=[`Renko`,`Range`,`LineBreak`,`Kagi`,`PointAndFigure`];function rN(e,t){for(let n of Object.keys(e))if(e[n]!==t[n])return!0}function iN(e,t){let n=e=>e.curves[0],r=n(e),i=n(t),a=nN.includes(r.style),o=nN.includes(i.style);return a===o?o?!!(r.style!==i.style||t.inputs&&rN(dt(e.inputs),dt(t.inputs))):!1:!0}function aN(e,t,n){let r={id:`Aggregation`,context:{id:`Get`}};if(rN(ju(VP(r,t,n)),ju(VP(r,e,n)))||!tN(e.display?.xAxis?.visibleRange,t.display?.xAxis?.visibleRange)||e.display?.xAxis?.marginBars!==t.display?.xAxis?.marginBars||!tN(e.data?.range,t.data?.range)||e.data?.extendedHours!==t.data?.extendedHours||e.display?.period!==t.display?.period||e.display?.density!==t.display?.density)return!0;let i=Ud(t),a=Ud(e);if(iN(i,a))return!0;let o=(e,t)=>e.type===t,s=e=>{let t=e.toLowerCase();return o(a,e)&&o(i,e)&&i[t]!==a[t]},c=i.type!==a.type,l=s(`Forward`),u=s(`Expression`),d=s(`Symbol`);return c||l||u||d}function oN(e,t,n){if(`paneIndex`in t||`axisIndex`in t)throw Error(`AnnotationManipulation paneIndex and axisIndex are output-only metadata; use uid`);let r=n?.selectedAnnotation?.uid,i=n?.annotationPreviewUid;return e.panes.flatMap((e,n)=>e.axes.flatMap((e,a)=>(e.annotations||[]).map((e,t)=>({uid:e.uid,paneIndex:n,axisIndex:a,position:t,selected:r===e.uid,preview:i===e.uid})).filter(e=>t.uid===void 0||e.uid===t.uid)))}function sN(e,t){return e===`Front`?t-1:e===`Back`?0:xt(0,t-1,e)}function cN(e,t,n){let{uid:r,position:i,selected:a,preview:o}=t;if(t.id!==void 0&&t.id!==`Update`)throw Error(`Invalid AnnotationManipulation sub-action`);if(i!==void 0&&!(i===`Front`||i===`Back`)&&!(Number.isInteger(i)&&i>=0))throw Error(`Annotation position must be Front, Back, or a non-negative integer`);if((i!==void 0||a===!0||o===!0)&&r===void 0)throw Error(`AnnotationManipulation requires uid for position, selection, or preview`);let s=oN(e,t,n),c=r===void 0?void 0:s[0],l=c&&n?.panes[c.paneIndex]?.axes[c.axisIndex],u=l?.annotations.find(e=>e.uid===r),d=u?.isVisible&&!u.computed?u:void 0;if(c&&i!==void 0){let t=e.panes[c.paneIndex].axes[c.axisIndex].annotations,r=sN(i,t.length);if(r!==c.position){let e=t.map(e=>e.uid);if(l&&u&&n){let t=[...e];t.splice(r,0,t.splice(c.position,1)[0]),l.annotations.sort((e,n)=>t.indexOf(e.uid)-t.indexOf(n.uid)),n.undoRedoManager.done({owner:l.annotationUndoOwner,uid:u.uid,toolChange:O.Reordered,before:e,after:t}),n.onAnnotationsUpdated(l),n.onAnnotationModifiedByTool(u,O.Reordered,!1),u.requestRedraw()}else t.splice(r,0,t.splice(c.position,1)[0])}}return n&&o!==void 0&&(o&&d?n.setAnnotationPreview(d.uid):!o&&(r===void 0||n.annotationPreviewUid===r)&&n.setAnnotationPreview()),n&&a!==void 0&&(a&&d?n.setSelection(d):!a&&s.some(e=>e.selected)&&n.clearSelection()),e}function lN(e,t){let[n,r]=Qe(t.crosshair),{color:i,dashStyle:a}=t.horizontal||{},{color:o,dashStyle:s}=t.vertical||{},c=(e,t,n)=>{t&&(e.color=t),n&&(e.dashStyle=n)},l=U(e,`.display.xAxis.crosshair`,e=>(e.enabled=n,c(e,o,s),e));return l=U(l,`.display.yAxis.crosshair`,e=>(e.enabled=r,c(e,i,a),e)),P(t.haloTracking)&&typeof t.haloTracking==`boolean`&&(l=U(l,`.display.chart`,e=>(e.plotHover=t.haloTracking,e))),l}function uN(e,t){return U(e,`.display.tooltip`,e=>(t.visible!=null&&(e.visible=t.visible),t.mode&&(e.mode=t.mode),t.showMainTitle!=null&&(e.showMainTitle=t.showMainTitle),t.mainTitle&&(e.mainTitle=t.mainTitle),e))}function dN(e,t){let n=F(t);return Object.keys(t).forEach(e=>{B.EVENTS.includes(e)||delete n[e];let r=t[e];typeof r==`boolean`?r={show:t[e]}:Object.keys(r).forEach(e=>{B.EVENT_PROPERTIES.includes(e)||delete r[e]}),n[e]=r}),U(e,Hd,e=>(e.type===`Symbol`&&(e.events=e.events||{},Object.keys(n).forEach(t=>{e.events[t]=e.events[t]||{},ct(e.events[t],n[t],!1)})),e))}function fN(e,t){let n=U(e,`..panes{${Hd}}.axes`,e=>(N(t.scale)&&(e.scale=t.scale),e));n=U(n,`.display.xAxis`,e=>(N(t.horizontalAxisPosition)&&(e.position=t.horizontalAxisPosition),N(t.marginBars)&&(e.marginBars=t.marginBars),N(t.nonEodLabelWithDate)&&(e.nonEodLabelWithDate=t.nonEodLabelWithDate),N(t.ordinalName)&&(e.ordinalName=t.ordinalName),N(t.preventHorizontalLabelOverlap)&&(e.preventLabelOverlap=t.preventHorizontalLabelOverlap),e));let r=()=>I(`The 'minPadding' and 'maxPadding' are deprecated (ignored)`,`warn`),i=()=>I(`The 'preventLabelOverlap' is deprecated, please use 'preventVerticalLabelOverlap'`,`warn`);return n=U(n,`.display.yAxis`,e=>{(P(t.minPadding)||P(t.maxPadding))&&r();let n=N(t.preventLabelOverlap)&&!N(t.preventVerticalLabelOverlap);n&&i();let a=n?t.preventLabelOverlap:t.preventVerticalLabelOverlap;return N(a)&&(e.preventLabelOverlap=a),P(t.includePercentChangeWithLastValue)&&(e.includePercentChangeWithLastValue=t.includePercentChangeWithLastValue),P(t.snapAnnotationsToPrices)&&(e.snapAnnotationsToPrices=t.snapAnnotationsToPrices),P(t.primaryOnTheLeft)&&(e.primaryOnTheLeft=t.primaryOnTheLeft),e}),P(t.labels)&&Array.isArray(t.labels)&&t.labels.forEach(e=>{let{axis:t,text:r,index:i,paneIndex:a}=e;P(t,r,i)&&t===`vertical`&&Number.isInteger(i)&&(n=U(n,`..panes[${a??0}]..axes[${i}]`,e=>P(e)?(e.label=r,e):B.NULL_OBJECT))}),N(t.contractTransition)&&(n=U(n,`.display.xAxis`,e=>(lt(e.contractTransition,t.contractTransition),e))),N(t.cycleTransition)&&(n=U(n,`.display.xAxis`,e=>(lt(e.cycleTransition,t.cycleTransition),e))),n}function pN(e,t,n){let r=e;if(P(t.comparisonMode)&&typeof t.comparisonMode==`string`&&nt(x,t.comparisonMode)&&(r=U(r,`..panes{${Hd}}.axes`,e=>(e.comparison=t.comparisonMode,e))),P(t.gridLines)){let[e,n]=Qe(t.gridLines);r=U(r,`.display.xAxis.gridLines`,t=>(t.visible=e,t)),r=U(r,`.display.yAxis.gridLines`,e=>(e.visible=n,e))}if(P(t.minorGridLines)){let[,e]=Qe(t.minorGridLines);r=U(r,`.display.yAxis.minorGridLines`,t=>(t.visible=e,t))}P(t.newPaneHeight)&&typeof t.newPaneHeight==`number`&&(r=U(r,`.display.chart{.newPaneHeight > 0}`,e=>(e.newPaneHeight=t.newPaneHeight,e))),P(t.showNavigator)&&typeof t.showNavigator==`boolean`&&(r=U(r,`.display.scrollbar`,e=>(e.visible=t.showNavigator,e))),P(t.plotHover)&&typeof t.plotHover==`boolean`&&(r=U(r,`.display.chart`,e=>(e.plotHover=t.plotHover,e))),P(t.showLastValue)&&typeof t.showLastValue==`string`&&(r=U(r,`.display.yAxis`,e=>(e.showLastValue=t.showLastValue,e))),P(t.showMinMaxArc)&&typeof t.showMinMaxArc==`boolean`&&(r=U(r,`.display.chart`,e=>(e.showMinMaxArc=t.showMinMaxArc,e))),P(t.showGoToLatest)&&typeof t.showGoToLatest==`boolean`&&(r=U(r,`.display.chart`,e=>(e.showGoToLatest=t.showGoToLatest,e))),P(t.showLegend)&&typeof t.showLegend==`boolean`&&(r=U(r,`.display.chart`,e=>(e.showLegend=t.showLegend,e)),t.showLegend||n.view.removeLegend()),P(t.allAnnotationsLocked)&&typeof t.allAnnotationsLocked==`boolean`&&(r=U(r,`.display`,e=>(e.allAnnotationsLocked=t.allAnnotationsLocked,e))),N(t.hiddenItems)&&PO.includes(t.hiddenItems)&&(r=U(r,`.display`,e=>(e.hiddenItems=t.hiddenItems,e))),P(t.exprSkipLeadingEmpty)&&typeof t.exprSkipLeadingEmpty==`boolean`&&(r=U(r,`.data`,e=>(e.exprSkipLeadingEmpty=t.exprSkipLeadingEmpty,e))),typeof t.useLastTrade==`boolean`&&(r=U(r,`.data`,e=>(e.useLastTrade=t.useLastTrade,e)));let i=[];if(P(t.extendedHours)&&typeof t.extendedHours==`boolean`&&(r=U(r,`.data`,e=>(e.extendedHours=t.extendedHours,e))),P(t.realTimeCboeBzx)&&typeof t.realTimeCboeBzx==`boolean`&&(r=U(r,`.data`,e=>(e.realTimeCboeBzx!==t.realTimeCboeBzx&&i.push(`realTimeCboeBzx`),e.realTimeCboeBzx=t.realTimeCboeBzx,e))),P(t.buildContinuation)&&typeof t.buildContinuation==`boolean`&&(r=U(r,`.data`,e=>(e.buildContinuation=t.buildContinuation,e))),i.length>0){let e={chart:n.accessor,hostPropsChanged:i};n.notifyHost(K.CH_HOST_PROPS_CHANGED,e)}return r}var mN=`MARKED_FOR_DELETION`;function hN(e,t){if(t.plots.length===0)return e;let n=e;for(let e of t.plots){let t=wN(n,e);if(t===void 0)continue;let r=xN(t),i=SN(n,r);P(i)&&(P(e.type)&&i.type!==e.type||(n=U(n,r,e=>(e[mN]=!0,e))))}return n=U(n,`..plots{.${mN} === true}`,e=>B.NULL_OBJECT),n=U(n,`..plots{.type === "Study"}`,e=>{let t=V(e.study);return P(t)&&Vd(n,t,e.basis).eligible?e:B.NULL_OBJECT}),Pf(n)}function gN(e,t,n,r){let i=C[e.type],a={curves:F(e.curves),type:e.type,uid:e.uid};a.precision=e.precision,a.visible=e.visible,a.detachedScale=e.detachedScale;let o=(e,t)=>{P(e[t])?a[t]=e[t].map(e=>F(e)):a[t]=[]},s=(e,t,n=!1)=>{t.main===!0&&(e.main=!0,e.showPrevious=t.showPrevious,n&&t.events!=null&&(e.events=F(t.events)))},c=(e,t=e=>!0)=>{P(r)&&(e.subtitles=r.allPlots.filter(e=>e.type===i).filter(t).map(e=>e.title))};switch(i){case C.Symbol:{a.title=e.symbol;let t=a.curves[0].style,n=t=>{o(e,`inputs`),a.inputs.length===0&&(a.inputs=F(t))};switch(t){case`Renko`:n(B.DEFAULT_RENKO_INPUTS);break;case`Kagi`:n(B.DEFAULT_KAGI_INPUTS);break;case`PointAndFigure`:n(B.DEFAULT_PNF_INPUTS);break;case`LineBreak`:n(B.DEFAULT_LINEBREAK_INPUTS);break;case`Baseline`:n(B.DEFAULT_BASELINE_INPUTS);break}s(a,e,!0);break}case C.Study:{o(e,`inputs`);let r=V(e.study),i=a.inputs,s=e.study===`AVWAP`,c=i.length===0?``:` (${i.map(e=>s&&e.name===`Anchor`?new Date(e.value).toLocaleString():e.value).join(`, `)})`,l=a.curves.map(e=>Number(e.shift)).filter(e=>e>0),u=l.length===0?``:` [${l.join(`, `)}]`;a.title=`${r.id}${c}${u}`,a.studyId=r.id,o(e,`levels`),o(e,`bands`),a.basis=F(e.basis)||{kind:`main`},a.placement=t?n?`overlay`:`withMain`:`standalone`;break}case C.BalanceSheet:case C.IncomeStatement:{let t=G[e.curves[0].fields[0]];a.title=`${t.name} (${e.fundamental.substring(0,1)})`,a.fundamentalId=t.id,a.frequency=e.fundamental;break}case C.Expression:a.title=e.expression,s(a,e);break;case C.Forward:a.title=e.forward,o(e,`offsets`),c(a),s(a,e);break;case C.Seasonal:a.title=e.seasonal,c(a,e=>e.refSeasonal===a.title),o(e,`offsets`),s(a,e);break;default:throw Error(`Unexpected plot type`)}return a}function _N(e,{main:t,type:n,index:r,uid:i},a){let o=`..plots{.main === true}`,s=H(e,`..panes`).map((e,t)=>{let n=H(e,o).length===1;return H(e,`..axes`).map((e,r)=>{let i=H(e,o).length===1;return H(e,`..plots`).map(e=>{let o=gN(e,n,i,a);return o.paneIndex=t,o.axisIndex=r,o})})}).flat(2).map((e,t)=>(e.index=t,e));if(P(i))return s.filter(e=>e.uid===i);if(t)return s.filter(e=>e.main);if(P(n)){let e=s.filter(e=>e.type===n);return P(r)?e.filter(e=>e.index===r):e}else return s}var vN=[`overlay`,`standalone`,`withMain`,`clone`];function yN(e,t,n){t[n]&&(e[n]=t[n])}function bN(e,t){e.type===`Study`&&t.curves?.forEach(e=>delete e.varyColorPerBar),EN(e)?P(t.curves)&&(e.curves=t.curves):jN(e.curves,t.curves);let n=C[t.type],r=e;if(P(t.precision)?r.precision=t.precision:delete r.precision,n===C.Symbol)P(t.symbol)&&(e.symbol=t.symbol);else if(n===C.Study)P(t.basis)&&(e.basis=F(t.basis)),MN(e.inputs,t.inputs,e),[`bands`,`levels`,`detachedScale`].forEach(n=>yN(e,t,n));else if((n===C.BalanceSheet||n===C.IncomeStatement)&&t.frequency)e.fundamental=t.frequency;else if(n===C.Expression){let n=e;P(t.expression)&&(n.expression=t.expression)}else if(n===C.Forward){let n=e;P(t.offsets)&&(n.offsets=t.offsets),P(t.forward)&&(n.forward=t.forward)}else if(n===C.Seasonal){let n=e;P(t.offsets)&&(n.offsets=t.offsets),P(t.seasonal)&&(n.seasonal=t.seasonal),P(t.usesInAverage)&&(r.usesInAverage=t.usesInAverage),cu(n)}}var xN=e=>`..plots[${e}]`;function SN(e,t){let n=H(e,t);return n.length===1?n[0]:null}function CN(e,t){let n=0;for(let r of e.panes)for(let e of r.axes)for(let r of e.plots){if(r.uid===t)return n;n+=1}}function wN(e,t){return P(t.uid)?CN(e,t.uid):t.index}function TN(e){let t=C[e.type];return t===C.Symbol||t===C.Expression}function EN(e){let t=C[e.type];return t===C.Forward||t===C.Seasonal}function DN(e){let t=C[e.type];return t===C.Symbol||t===C.Expression||t===C.Seasonal}function ON(e,t,n){if(P(t))return t;let r=n?.uid;return typeof r==`string`?CN(e,r):void 0}function kN(e,t,n){if(P(t.placement)&&!vN.includes(t.placement))throw Error(`Unknown placement: ${t.placement}`);let r=wN(e,t),i=r===void 0?t.main?Hd:``:xN(r);if(!i)return e;let a=SN(e,i);if(!N(a)||N(t.type)&&a.type!==t.type)return e;let o=ON(e,r,a);if(t.type===C[C.Study]){let n=a,r=V(t.studyId??n.study);if(!N(r))return e;let i=P(t.basis)?t.basis:n.basis,o=Vd(e,r,i);if(!o.eligible)return I(`Cannot update study "${r.meta.title}" because ${o.reason}.`,`error`),e}if(N(t.visible))return a.visible=t.visible,e;if(a.main&&TN(a)){if(t.curves){let n=e=>e.curves[0].style===h[h.Range],[r,i]=[n(a),n(t)];r&&!i?e=tf(e,{unit:`Day`,size:1,spec:`None`}):!r&&i&&(e=tf(e,{unit:`Intraday`,size:100,spec:`PerRange`}))}t.type||=a.type;let n=a;P(t.precision)?n.precision=t.precision:delete n.precision,P(t.showPrevious)&&(e=U(e,Hd,e=>(e.showPrevious=t.showPrevious,e)));let r=t.curves?td(e,t):e;return P(t.oppositeScale)&&DN(a)&&P(o)&&(r=Ld(r,o,+!!t.oppositeScale)),r}else{let s=U(e,i,e=>(bN(e,t),e));if(P(t.oppositeScale)&&DN(a)&&P(o)&&(s=Ld(s,o,+!!t.oppositeScale)),!(t.type===C[C.Study]&&P(t.placement)))return s;let c=P(r)?r:t.index,l=_N(s,{...t,index:c},n).find(e=>e.index===c);if(!P(l))return e;if(t.placement===l.placement)return s;let u=SN(s,i);if(!P(u))return e;s=hN(s,{id:`Delete`,plots:[{uid:u.uid,type:t.type}]});let d=LN(s,t.placement,t.cloneIndex,t.cloneUid);return d!==null&&d.plots.push(u),s}}function AN(e){return e!==void 0}function jN(e,t){if(AN(t)&&t.length===e.length)for(let n=0;n<e.length;++n){let r=t[n],i=e[n];lt(i,r);for(let e of[`shift`,`dashStyle`,`lineSmoothing`,`lineMarker`]){let t=r[e];P(t)&&(i[e]=t)}}}function MN(e,t,n){let r=dt(e),i=dt(t);lt(r,i);let a=ft(i);a.length>0&&(n.inputs=a)}function NN(){return{plots:[]}}function PN(e){let t=e.display.chart.newPaneHeight??1;return{axes:[NN()],height:t}}function FN(e){let t=PN(e);return e.panes.push(t),t}function IN(e,t){let n=N(t.paneIndex)&&t.paneIndex<e.panes.length?e.panes[t.paneIndex]:FN(e),r=n.axes[0];return t.oppositeScale??!1?rP(n,r):r}function LN(e,t,n,r,i){let a=null,{mainPane:o,mainAxis:s}=Wd(e),c=(()=>{if(i?.kind!==`seasonal`)return null;for(let t of e.panes)for(let e of t.axes)for(let n of e.plots){if(n.uid!==i.uid||n.type!==`Seasonal`)continue;let r=n.offsets;if(Array.isArray(r)&&r.includes(i.offset))return{pane:t,axis:e}}return null})();switch(t){case`withMain`:a=c?rP(c.pane,c.axis):rP(o,s);break;case`overlay`:a=c?.axis??s;break;case`standalone`:a=FN(e).axes[0];break;case`clone`:{let t={main:!1,type:C[C.Study]};if(typeof r==`string`&&r.length>0?t.uid=r:typeof n==`number`&&(t.index=n),t.uid||typeof t.index==`number`){let n=_N(e,t).find(e=>e.type===C[C.Study]&&(t.uid?e.uid===t.uid:e.index===t.index));if(!n)break;a=H(e,`..panes[${n.paneIndex}]..axes[${n.axisIndex}]`)[0]}break}}return a}function RN(e,t){let n=V(t.studyId);if(!N(n))return I(`Unknown or unavailable study with the id '${t.studyId}'`,`error`),e;let r=Vd(e,n,t.basis);if(!r.eligible)return I(`Cannot add study "${n.meta.title}" because ${r.reason}.`,`error`),e;let i=t.placement||(n.meta.overlay?`overlay`:`standalone`),a=t.uid??bt();P(t.uid)&&Md(e,a);let o={uid:a,type:`Study`,study:t.studyId,visible:!0};i===`overlay`&&t.studyId===`VOL`&&(o.detachedScale=!0),t.curves!==void 0&&(o.curves=n.defaults.curves),bN(o,t);let s=LN(e,i,t.cloneIndex,t.cloneUid,t.basis);P(s)&&s.plots.push(o);let c=e.data.aggregation;return ef(e,c.unit===`Tick`&&c.spec===`None`)}function zN(e,t){e.panes.push({axes:[{plots:[t]}]})}function BN(e,t){let n=Ud(e);if(n.type!==C[C.Symbol])throw Error(`Cannot add fundamental to the chart whose main plot is not a Symbol plot.`);let r=n.symbol,i=t.uid??bt();P(t.uid)&&Md(e,i);let a={uid:i,curves:[{fields:[t.fundamentalId],lineWidth:2,style:`Line`,varyColorPerBar:!1,visible:!0,colors:[`#888`]}],fundamental:`Quarter`,symbol:r,type:b[G[t.fundamentalId].category],visible:!0};return bN(a,t),zN(e,a),e}var VN=[{fields:[G.Close.id],colors:[`#888`],style:`Line`,lineWidth:2,varyColorPerBar:!1,visible:!0}];function HN(e){return e.type===`Symbol`}function UN(e,t){let n=Ud(e),r=F(HN(n)?n.curves:VN),i=t.uid??bt();P(t.uid)&&Md(e,i);let a={uid:i,curves:r,expression:``,type:`Expression`,visible:!0};return bN(a,t),IN(e,t).plots.push(a),e}function WN(e,t){let n=t.uid??bt();P(t.uid)&&Md(e,n);let r={uid:n,curves:F(VN),offsets:[0],seasonal:``,type:`Seasonal`,visible:!0,main:!1};return bN(r,t),IN(e,t).plots.push(r),e}var GN={attributes:[`OpenVsClose`],colors:[`#b63400`,`#007f3e`,`#1664db`],fields:[`Open`,`High`,`Low`,`Close`,`Change`],style:`Candlestick`,varyColorPerBar:!0,lineWidth:1};function KN(e,t){let n=Ud(e),r=$().getDefaultMultiFieldCurve(),i=P(r)?r:GN,a=n.curves?.length,o=a===t.curves.length&&a===1?(e=>F(e?n.curves:[i]))(HN(n)):t.curves,s=t.uid??bt();P(t.uid)&&Md(e,s);let c={uid:s,curves:o,symbol:``,type:`Symbol`,visible:!0};return bN(c,t),IN(e,t).plots.push(c),e}function qN(e,t){switch(t.type){case`Study`:return RN(e,t);case`IncomeStatement`:case`BalanceSheet`:return BN(e,t);case`Expression`:return UN(e,t);case`Symbol`:return KN(e,t);case`Seasonal`:return WN(e,t);default:throw Error("Unexpected plot type '${type}', not supported currently")}}var JN=0,YN=B.AUTO_COLORS,XN=`Symbol`,ZN=`Expression`,QN=`Seasonal`;function $N(e,t){let n={attributes:[],colors:YN.slice(JN,JN+1),fields:e?[G.Last.id]:[G.Close.id],style:`Line`,dashStyle:`Solid`,varyColorPerBar:!1,lineWidth:2,lineMarker:void 0,lineSmoothing:void 0},r={uid:t.uid??bt(),curves:[n]},{curves:i,oppositeScale:a,...o}=t;return ut(r,o),N(i)&&(r.curves=i.map(e=>{let t=F(e);return ut(t,n),t})),r.main=!1,JN=(JN+1)%YN.length,r}function eP(e){return P(e.symbols)&&(I(`Use of 'symbols' for Compare API is deprecated. Please see docs for the latest version which supports more plot types`,`warn`),e.plots=e.symbols.map(e=>(e.type=XN,e))),e.plots?.some(e=>P(e.leftScale))?(I(`Use of 'leftScale' for Compare API is deprecated. Please use 'oppositeScale'`,`warn`),e.plots.map(e=>{let t=e.leftScale;return delete e.leftScale,{...e,oppositeScale:t}})):e.plots}function tP(e,t){let n=eP(t),r=n.map(e=>e.uid).filter(e=>typeof e==`string`),i=new Set;for(let t of r){if(i.has(t))throw Error(`Plot uid '${t}' is duplicated in the Compare request.`);i.add(t),Md(e,t)}let{yes:a,no:o}=k(n,e=>e.oppositeScale??!1),{mainPane:s,mainAxis:c}=Wd(e);s.alignOnExpirations=t.alignOnExpirations||!1;let l=rP(s,c),u=e=>![XN,ZN,QN].includes(e.type);l.plots=l.plots.filter(u);let d=c.plots.filter(e=>e.main||u(e)),f=e.data.aggregation.unit===`Tick`;JN=0;let p=se($N,f);return c.plots=d.concat(o.map(p)),a.length>0&&(l.plots.push(...a.map(p)),l.comparison=c.comparison,l.scale=c.scale),Pf(e)}var nP=`..plots{(.type === "Symbol" || .type === "Expression" || .type === "Seasonal") && .main !== true}`;function rP(e,t){let n=e.axes.find(e=>e!==t);return P(n)||(n=NN(),e.axes.push(n)),n}function iP(e,t){let n=H(e,nP),r=H(t,nP),i=Math.max(0,4-r.length);if(i===0)return t;let a=n.filter(e=>!r.find(t=>e.symbol===t.symbol)).slice(0,i);if(a.length===0)return t;let{mainPane:o,mainAxis:s}=Wd(t),{mainAxis:c}=Wd(e);return a.forEach(e=>{c.plots.includes(e)?s.plots.push(e):rP(o,s).plots.push(e)}),t}function aP(e,t){let n=e.panes;return n.splice(t.to,0,n.splice(t.from,1)[0]),e}var oP=()=>B.NULL_OBJECT;function sP(e){return U(e,`..axes.annotations`,oP)}function cP(e){return Pf(U(e,`..plots{.type === "Symbol" && .main !== true}`,oP))}function lP(e,t){let n=F(e);if(t.strip.main){let e=Ud(n),t=e.type.toLowerCase();e[t]=B.PLACEHOLDER_SYMBOL_NAME}return t.strip.annotations&&(n=sP(n)),t.strip.compare&&(n=cP(n)),n=U(n,`.data`,e=>(e.range&&(delete e.range,e.checkRange=!0),e)),n}function uP(e,t,n){let r=_N(e,{main:!0},n)[0],i=r.title===B.PLACEHOLDER_SYMBOL_NAME,a=r.type===`Symbol`,o=r.type===`Expression`,s=bd(r.title),c=[];return o&&!yd(s)?c=s.symbols:i||(c=[r.title]),{isTemplate:i,isDefinition:!i,main:{isSymbol:a,isExpression:o,symbols:c,title:i?null:r.title},compare:H(e,nP).map(e=>e.symbol),annotations:H(e,`..annotations`).map(e=>e.id),studies:_N(e,{type:`Study`},n).map(e=>e.title)}}function dP(e,t,n){let r=H(e,`..panes`).map((e,t)=>H(e,`..axes`).map((e,n)=>H(e,`.annotations`).map(e=>({...e,paneIndex:t,axisIndex:n})))).flat(2).map((e,t)=>({...e,index:t}));return P(t.index)&&Number.isFinite(t.index)?t.index<r.length?[r[t.index]]:B.EMPTY_ARRAY:r}function fP(e,t){let n=pP(t.annotation),{mainAxis:r}=Wd(e);return r.annotations??=[],r.annotations.some(e=>e.uid===n.uid)||r.annotations.push(n),e}function pP(e){let t={id:e.id,uid:e.uid,points:(e.points??[]).map(e=>({price:e.price,time:e.time}))};return e.traits!==void 0&&(t.traits=F(e.traits)),e.visible!==void 0&&(t.visible=e.visible),e.locked!==void 0&&(t.locked=e.locked),t}function mP(e,t){let n=H(e,`..axes`);for(let e of n){let n=e.annotations?.find(e=>e.uid===t.uid);if(n){t.traits!==void 0&&(n.traits=F(t.traits)),t.points!==void 0&&(n.points=t.points.map(e=>({price:e.price,time:e.time}))),t.visible!==void 0&&(n.visible=t.visible),t.locked!==void 0&&(n.locked=t.locked);break}}return e}function hP(e,t){let n=H(e,`..axes`);for(let e of n)if(e.annotations?.some(e=>e.uid===t.uid)){e.annotations=e.annotations.filter(e=>e.uid!==t.uid);break}return e}function gP(e,t,n){let r=H(e,`..panes{${Hd}}.axes.comparison`)[0],i=e.display,a=(e,t)=>rt(e,!1,t,`visible`),o=e=>$e(a(i.xAxis,e),a(i.yAxis,e)),s=rt(i.chart,!0,`showLegend`);return{comparison:r,gridLines:o(`gridLines`),minorGridLines:o(`minorGridLines`),newPaneHeight:i.chart.newPaneHeight,showLastValue:i.yAxis.showLastValue,showLegend:s,showMinMaxArc:i.chart.showMinMaxArc,allAnnotationsLocked:i.allAnnotationsLocked,hiddenItems:IO(i),exprSkipLeadingEmpty:e.data?.exprSkipLeadingEmpty??!1,useLastTrade:e.data?.useLastTrade??!1,extendedHours:e.data?.extendedHours??!1,realTimeCboeBzx:e.data?.realTimeCboeBzx??!1,buildContinuation:e.data?.buildContinuation??!1}}function _P(e,t){let n=e,{backgroundColor:r,axis:{gridLinesColor:i,textColor:a,crosshairColor:o,gridLinesStyle:s},fontSize:c}=t,{chart:l,xAxis:u,yAxis:d}=c||{};if((r||l)&&(n=U(e,`.display.chart`,e=>(r&&(e.backgroundColor=r),l&&(e.fontSize=l),e))),i){let e=e=>(e.color=i,e);n=U(n,`.display.xAxis.gridLines`,e),n=U(n,`.display.yAxis.gridLines`,e),n=U(n,`.display.yAxis.minorGridLines`,e)}if(s){let e=e=>(e.dashStyle=s,e);n=U(n,`.display.xAxis.gridLines`,e),n=U(n,`.display.yAxis.gridLines`,e),n=U(n,`.display.yAxis.minorGridLines`,e)}if(a){let e=e=>(e.textColor=a,e);n=U(n,`.display.xAxis`,e),n=U(n,`.display.yAxis`,e)}if(o){let e=e=>(e.color=o,e);n=U(n,`.display.xAxis.crosshair`,e),n=U(n,`.display.yAxis.crosshair`,e)}if(u||d){let e=e=>t=>(t.fontSize=e,t);u&&(n=U(n,`.display.xAxis`,e(u))),d&&(n=U(n,`.display.yAxis`,e(d)))}return n}function vP(e,t,n){let{chart:r,xAxis:i,yAxis:a}=e.display||{},{fontSize:o,backgroundColor:s}=r||{},{fontSize:c,gridLines:l,textColor:u,crosshair:d}=i||{},{color:f,dashStyle:p}=l||{},{fontSize:m}=a||{},{color:h}=d||{};return{backgroundColor:s,axis:{gridLinesColor:f,textColor:u,crosshairColor:h,gridLinesStyle:p},fontSize:{chart:o,xAxis:c,yAxis:m}}}function yP(e,t,n){let{mainAxis:r}=Wd(e),i=H(e,`.display.xAxis`)[0],a=H(e,`.display.yAxis`)[0];return{scale:r.scale,marginBars:i.marginBars??0,horizontalAxisPosition:i.position??`bottom`,preventLabelOverlap:a.preventLabelOverlap,preventVerticalLabelOverlap:a.preventLabelOverlap,preventHorizontalLabelOverlap:i.preventLabelOverlap,snapAnnotationsToPrices:a.snapAnnotationsToPrices,primaryOnTheLeft:a.primaryOnTheLeft??!1,nonEodLabelWithDate:i.nonEodLabelWithDate??!1,includePercentChangeWithLastValue:a.includePercentChangeWithLastValue??!1,ordinalName:i.ordinalName??``,contractTransition:i.contractTransition,cycleTransition:i.cycleTransition}}function bP(e,t,n){let r=t=>H(e,t)[0],i=r(`.display.chart`),a=r(`.display.xAxis.crosshair`),o=r(`.display.yAxis.crosshair`),s=`none`;return a.enabled&&o.enabled?s=`both`:a.enabled?s=`vertical`:o.enabled&&(s=`horizontal`),{crosshair:s,horizontal:{color:o.color,dashStyle:o.dashStyle},vertical:{color:a.color,dashStyle:a.dashStyle},haloTracking:i.plotHover}}function xP(e,t,n){return F(e.data.aggregation)}function SP(e,t){let n=H(e,nP),{mainPane:r,mainAxis:i}=Wd(e),a=[];for(let e of n){let t=!i.plots.includes(e),n=e.type.toLowerCase(),r={curves:F(e.curves),type:e.type,[n]:e[n],oppositeScale:t,leftScale:t};a.push(r)}return{plots:a,alignOnExpirations:r.alignOnExpirations}}function CP(e,t,n){let{paneIndex:r,annotations:i,studies:a}=t||{},o=`..panes${Number.isInteger(r)?`[${r}]`:``}`,s=e,c=e=>B.NULL_OBJECT;return i===!0&&(n.allAnnotations.forEach(e=>n.onAnnotationModifiedByTool(e,O.Deleted,!1)),s=U(s,`${o}..annotations`,c)),a===!0&&(s=U(s,`${o}..plots{.type=="Study"}`,c)),s=Pf(s),s}var wP=`.display.chart.previous`;function TP(e,t,n){return H(e,wP)[0]}function EP(e,t,n){return U(e,wP,e=>(lt(e,t),e))}function DP(e,t,n){let r=[],i=wN(e,t);if(i===void 0||SN(e,xN(i))?.type!==t.type)return r;let a=Pd(e,i);if(a===null)return r;let o=a.pane,s=o===0,c=o===e.panes.length-1,l=e.panes[o].axes.reduce((e,t)=>e+t.plots.length,0)===1;return s||r.push(`ExistingAbove`),l||r.push(`NewAbove`),c||r.push(`ExistingBelow`),l||r.push(`NewBelow`),r}function OP(e,t,n){if(!DP(e,t,n).includes(t.targetPane))return e;let r=wN(e,t);if(r===void 0)return e;let i=Pd(e,r);if(i===null)return e;let a=SN(e,xN(r));e.panes[i.pane].axes[i.axis].plots.splice(i.plot,1);let o=i.pane,s=!0;switch(t.targetPane){case`ExistingAbove`:o--;break;case`NewAbove`:e.panes.splice(o,0,PN(e)),s=!1;break;case`ExistingBelow`:o++;break;case`NewBelow`:o++,s=!1,e.panes.splice(o,0,PN(e));break}let{mainPane:c}=Wd(e),l=e.panes[o]===c;s&&l&&a?.type===`Study`&&a.study===`VOL`&&(a.detachedScale=!0);let u=e.panes[o];u.axes.length<2&&u.axes[0].plots.length>0&&u.axes.push(NN());let d=u.axes.findIndex(e=>e.plots.length===0),f=d===-1?u.axes.length-1:d;u.axes[f].plots.push(a);let p=Id(e,i.pane);return p=Id(p,o),Pf(p)}function kP(e,t,n){return P(t.period)&&t.period&&(delete e.display.period,$d(e),n&&(n.forceResetVisibleRange=!0)),e}function AP(e,t,n){let r=[],i=wN(e,t);if(i===void 0)return r;let a=SN(e,xN(i));if(a?.type!==t.type)return r;let o=Pd(e,i);if(o===null)return r;let s=e.panes[o.pane],c=o.axis===0,l=s.axes.some((e,t)=>e.plots.some((e,n)=>!(t===o.axis&&n===o.plot)&&!e.detachedScale)),u=a.detachedScale===!0;return(c||u)&&r.push(`SecondaryAxis`),(!c||u)&&r.push(`PrimaryAxis`),l&&r.push(`NoAxis`),r}function jP(e,t,n){if(!AP(e,t,n).includes(t.targetAxis))return e;let r=wN(e,t);if(r===void 0)return e;let i=-1;switch(t.targetAxis){case`PrimaryAxis`:i=0;break;case`SecondaryAxis`:i=1;break;case`NoAxis`:return Rd(e,r)}return Ld(e,r,i)}function MP(e,t,n){let r=H(e,`.display.tooltip`)[0];return{visible:r.visible,mode:r.mode,showMainTitle:r.showMainTitle,mainTitle:r.mainTitle}}var NP=`..plots{.type === "Seasonal" && .main === true}`,PP=`..plots{.type === "Seasonal" && .main !== true}`,FP=B.AUTO_COLORS;function IP(e){return JSON.parse(JSON.stringify(e))}function LP(e,t){let n=H(e,NP);if(n.length===0)return e;let r=n[0];if(!r.offsets||r.offsets.length===0)return e;let i=r.offsets,a=H(e,PP);for(let e of a){let t=e.offsets??[],n=e.curves??[],r=new Map;t.length===n.length?t.forEach((e,t)=>{let i=n[t];i&&r.set(e,IP(i))}):n.forEach((e,t)=>{let n=i[t];e&&P(n)&&r.set(n,IP(e))});let a=r.get(0);a?.colors?.[0];let o=i.map((e,t)=>{let n=r.get(e);if(n)return n;let i=FP[t%FP.length];return{...a?IP(a):{},colors:[i],fields:[`Close`],style:`Line`,dashStyle:`Solid`,varyColorPerBar:!1,lineWidth:2}});e.offsets=[...i],e.curves=o}return Pf(e)}var RP={MainPlot:Qd,Aggregation:{Update:tf,Get:xP},Period:{Update:Ku,Delete:kP},Crosshair:{Update:lN,Get:bP},Tooltip:{Update:uN,Get:MP},Events:dN,Scale:{Update:fN,Get:yP},Other:{Update:pN,Get:gP},Plot:{Add:qN,Get:_N,Delete:hN,Update:kN},Compare:{Update:tP,Get:SP},AnnotationManipulation:{Get:oN,Update:cN},Annotation:{Get:dP,Add:fP,Update:mP,Delete:hP},MovePane:aP,Template:lP,Outline:uP,Theme:{Update:_P,Get:vP},Clear:CP,Previous:{Update:EP,Get:TP},MovePlot:{Update:OP,Get:DP},PinPlot:{Update:jP,Get:AP},SeasonalOffsets:{Update:LP}};function zP(e){return typeof e==`function`}function BP(e,t){let n=RP[e];if(zP(n))return n;{let e=t===void 0?void 0:n[t];if(!zP(e)&&(e=n[B.DEFAULT_ACCESSOR_SUBACTION],!zP(e)))throw Error(`Invalid accesor id and/or sub id`);return e}}function VP(e,t,n){return BP(e.id,e.context.id)(t,e.context,n)}function HP(e){return{id:`MainPlot`,context:e}}var UP={id:`SeasonalOffsets`,context:{}};function WP(e){return Array.isArray(e)&&e.some(e=>e?.type===`Seasonal`)}function GP(e){let{id:t,context:n}=e;if(!P(n))return!1;if(t===`Compare`)return WP(n.plots);if(t!==B.ACTION_PLOT)return!1;let r=n.id;return r===`Add`||r===`Update`?n.type===`Seasonal`:r===B.ACTION_DELETE?WP(n.plots):!1}function KP(e){return e.some(GP)?e[e.length-1]?.id!==`SeasonalOffsets`:!1}var qP={keepOldAnnotations:!1,keepNewAnnotations:!0,keepOldCompare:!1,keepNewCompare:!0,keepOldAggregation:!1,keepNewBarWidth:!1},JP=Symbol.for(`__ias__`),YP=class{headless;presenter;_model;constructor(e=!1){this.headless=e,this.presenter=e?null:new eN(this)}get elementId(){return this.headless?null:this.presenter?.elementId??null}get hostElement(){return this.headless?null:this.presenter?.hostElement??null}initialize(e,t=null){if(this.headless){I(`You cannot initialize a headless chart.`,`error`);return}if(this.presenter.initialize(e),N(t)){let e=typeof t==`string`;e?I(`Initializing the chart with symbol name is deprecated. Please use object form instead (see docs for details). This API will be removed in the future.`,`warn`):(t.template&&this.load(t.template),delete t.template);let n=e?{symbol:t}:t;this.change(HP(n))}}shutdown(){if(!this.headless){let e=this.presenter?.shutdown();return this.presenter=null,e}return!1}annotate(e,t=null,n=null){if(!this.headless)if(P(e)){Dl(e,t),El(e,t);let r=Cj(e,!1,t,n,this.presenter);r.isDrawingAnnotation&&this.presenter.view.setCursor(ee.Crosshair),this.presenter.activeTool=r,Ie()||this.presenter.view.mouseCanvas.focus({preventScroll:!0})}else this.presenter.resetActiveTool()}cancelAnnotation(){this.headless||this.presenter.resetActiveTool()}setMainAxisAnnotations(e){let t=this.presenter?.mainAxis;P(t)&&(t.annotations=e.map(e=>t.makeAnnotation(e)),t.fireAnnotationsChanged(),this.presenter.view?.redraw())}toMainAxisPoint(e){let t=this.presenter?.mainAxis;if(!P(t))return null;let n=t.toAnnotationPoint(e);return{price:n.price,time:n.time}}fromMainAxisPoint(e){let t=this.presenter?.mainAxis;if(!P(t))return null;let n=t.toX(new Date(e.time)),r=t.toY(e.price);return!P(n)||!P(r)?null:{x:n,y:r}}zoom(e){!this.headless&&typeof e==`boolean`&&(e?this.annotate(`ZoomIn`):this.presenter.defaultTool.resetView(this.presenter))}getDefaultTemplate(){return bF()}get model(){return(this.headless?this._model:this.presenter.getModel())||bF()}asTemplate(e={main:!0,annotations:!1,compare:!1}){return this.change({id:B.ACTION_TEMPLATE,context:{strip:e}})}change(...e){if(e.length>1&&e.some(e=>e.id===`AnnotationManipulation`))throw Error(`AnnotationManipulation must be executed as a standalone action`);let t={chart:this,actions:e.filter(e=>!e[JP])};t.actions.length>0&&this.presenter?.notifyHost(K.CH_API_ACTIONS_RECEIVED,t);let n=$().config.validateInput,r=e.map(e=>n?Nf(e,B.ACCESSOR_SCHEMA):e);if(r.length===1){let e=r[0];if(e.id===B.ACTION_TEMPLATE||e.context.id===B.ACTION_GET)return VP(e,this.model,this.presenter);if(!this.headless&&e.id===`AnnotationManipulation`){VP(e,this.model,this.presenter);return}else if(!this.headless&&e.id===B.ANN_ACTION_ID)return this.presenter.handleAnnotationChange(e.context)}let{yes:i,no:a}=k(r,e=>e.id===B.ACTION_PLOT&&P(e.context)&&e.context.id===B.ACTION_DELETE),o=F(this.model),s=F(this.model),c=a;i.length>0&&c.push({id:B.ACTION_PLOT,context:{id:B.ACTION_DELETE,plots:i.map(e=>e.context)}}),c.forEach(e=>{if(s=VP(e,s,this.presenter),!P(s))throw Error(`Forgot to return model from accessor`)}),KP(c)&&(s=VP(UP,s,this.presenter)),this.fromModel(s,o)}async fromModel(e,t){let n=Nf(e,B.CHART_SCHEMA);this.headless?this._model=n:await this.presenter?.fromModel(n,t)}async load(e,t){let n={...qP,...t},r=Nf(JSON.parse(e),B.CHART_SCHEMA),i=this.model,a=F(i);if(P(i)){if(r=Gd(i,r,n.keepNewAnnotations),n.keepNewAnnotations||(r=sP(r)),n.keepOldAnnotations&&(r=kM(i,r)),n.keepNewCompare||(r=cP(r)),n.keepOldCompare&&(r=iP(i,r)),n.keepOldAggregation){let e={id:B.ACTION_AGGREGATION,context:i.data.aggregation},t=r.display.density;r=VP(e,r,this.presenter),n.keepNewBarWidth&&P(t)&&(r.display.density=t)}await this.fromModel(r,a),this.clearUndoRedo()}}save(){return JSON.stringify(this.model)}clearUndoRedo(){!this.headless&&this.presenter?.undoRedoManager&&this.presenter.undoRedoManager.clear(!0)}reset(e=!0){let t=bF();if(this.headless)this._model=t;else if(this.presenter.getModel()){let n=this.presenter.mainPlot,r=null,i=n;if(n.isSymbol?r={symbol:i.symbol}:n.isExpression?r={expression:i.expression}:n.isForward?r={forward:i.forward}:n.isSeasonal&&(r={seasonal:i.seasonal}),P(r)){let n=VP({id:`Theme`,context:{id:`Get`}},this.model,this.presenter),i=VP(HP(r),t,this.presenter);e&&(i=VP({id:`Theme`,context:n},i,this.presenter)),this.presenter?.fromModel(i)}}this.clearUndoRedo(),this.presenter?.notifyHost(K.CH_RESET,{elementId:this.elementId})}print(e={}){this.headless||this.presenter.print(e)}getSVGForExport(){I(`Obsolete: please use 'exportImage' method instead.`,`warn`)}setTitle(e){this.headless||this.presenter.setTitle(e)}getPaneBounds(e=!0){if(!this.headless)return this.presenter.panes.map(t=>e?t.getBounds():t.getBoundsWithoutScales())}exportData(e={}){return this.headless?null:XM.call(this.presenter,e)}exportTable(e={}){return this.headless?null:GM.call(this.presenter,e)}exportImage(e={}){return this.headless?null:ZM.call(this.presenter,e)}getDataStats(){return this.presenter.getDataStats()}get canUndo(){return!this.headless&&(this.presenter?.undoRedoManager?.canUndo??!1)}get canRedo(){return!this.headless&&(this.presenter?.undoRedoManager?.canRedo??!1)}undo(){this.canUndo&&this.presenter?.undoRedoManager?.undo()}redo(){this.canRedo&&this.presenter?.undoRedoManager?.redo()}pauseUndoRedo(){this.headless||this.presenter?.undoRedoManager?.pause()}resumeUndoRedo(e){this.headless||this.presenter?.undoRedoManager?.resume(e)}priceToY(e,t=0,n=0){let r=this.presenter;if(this.headless||t<0||n<0||t>r.panes.length)return null;let i=r.panes[t];return n>i.axes.length?null:i.axes[n].toY(e)}yToPrices(e){let t=this.presenter;if(this.headless)return null;for(let[n,r]of t.panes.entries()){let t=r.getBounds();if(P(t)&&e>=t.y&&e<=t.y+t.height)return{pane:n,prices:r.axes.map(t=>t.toPrice(e))}}return{pane:-1,prices:[]}}activate(){this.presenter?.notifyHost(K.CH_DIDBECOMEACTIVE,{chart:this})}};function XP(e){let t=e.split(`.`);if(!t||t.length!==4)return!1;let n=t.map(Number);if(!n.every(e=>Number.isFinite(e)&&e>=0&&e<=255))return!1;let[r,i]=n;return r===10||r===172&&i>=16&&i<=31||r===192&&i===168}function ZP(){let e=globalThis.parent?.location?.hostname||``;return[``,`localhost`,`127.0.0.1`].includes(e)||XP(e)}function QP(){let e=document.domain,t=e.split(`.`),n=`__tld`+new Date().getTime(),r=0;for(;r<t.length-1&&document.cookie.indexOf(`${n}=${n}`)===-1;)e=t.slice(-1-++r).join(`.`),document.cookie=`${n}=${n};domain=${e};`;return document.cookie=`${n}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain=${e};`,e}function $P(e,t){return ot(t),`${e}/?${new URLSearchParams(t).toString()}`}var eF=`aHR0cHM6Ly9iYXJjaGFydHdpZGdldHMud2Vic29sLmJhcmNoYXJ0LmNvbQ==`,tF=`YXV0aGVudGljYXRlQ2hhcnRSZWZlcmVy`;function nF(e,t=``){return $P(atob(eF),{module:atob(tF),secret:t,referer:e})}function rF(e,t){return e+Math.random()*(t-e)}var iF=Function(atob(`Y29uc29sZS5sb2coIlBsZWFzZSBjb250YWN0IEJhcmNoYXJ0IGluIG9yZGVyIHRvIG9idGFpbiB0aGUgbGljZW5zZSBmb3IgdGhlIGNoYXJ0IGNvbXBvbmVudC4iKTsg`)),aF=Function(`f`,atob(`Zi5yZW1vdmVBbGxDaGFydHMoKTsg`)),oF=Function(`m`,atob(`cmV0dXJuIG0gPT09ICJJbnRlcm5hbEZlZWQiIHx8IG0gPT09ICJXaWRnZXQiIHx8IG0gPT09ICJGcmVlV2lkZ2V0IiB8fCBtID09PSAiRGVtb1NpdGUiIHx8IG0gPT09ICJFcVBsdXMiOw==`)),sF=`YXV0aG9yaXplZA==`,cF=`ZGF0YS1lbmRwb2ludA==`,lF=`YWxsb3dDcmVkZW50aWFscw==`;async function uF(e,t){if(t&&!oF(e.mode))return;let n=!1,r=0,i=25;for(;!n&&r<5;){let t=ZP()||e.mode===`FreeWidget`,a=t?e.apiKey:``;try{let i=nF(t?``:QP(),a),o=await fetch(i);if(!o.ok)r++;else{let t=await o.json(),r=t[atob(sF)];e.knownSite=r,r?(e.dataEndpoint=(t[atob(cF)]||``).replace(/\/$/g,``),e.allowCredentials=t[atob(lF)]):(e.dataEndpoint=``,e.allowCredentials=!1),n=!0;break}}catch{}r++,i*=2,await new Promise(e=>setTimeout(e,i))}(!n||!e.knownSite)&&dF()}function dF(){setTimeout(iF,rF(2e3,3e3)),setTimeout(()=>aF($()),rF(4e3,5e3))}var fF={major:2,minor:405,patch:0,prerelease:!1},pF={environment:`Browser`,validateInput:!1,throttleMillis:0,isAlt64:!0,defaultTemplate:`/${B.CHART_DEFINITION}`,cachedAnnotationsCount:0,showResizeHandles:!1,scrollBehavior:`wheel+shift`,bypassSmoothing:!1,showGoToLatest:void 0,tooltipMovement:`Auto`,tooltipHeaders:void 0,touchCrosshairTimeoutMillis:void 0,touchCrosshairDelayMillis:void 0,mode:`Unspecified`,hostingModel:`Page`,overrides:void 0,logo:void 0,logoClickable:void 0,noDataText:void 0,useAllFieldsForComparison:void 0,colorfulAnnotations:!1,annotationManipulation:void 0,baseUrl:{instruments:`/proxies/instruments`,futures:`/proxies/futures`,extras:`/extras`,timeseries:`/proxies/timeseries`,timeseriesNew:`/proxies/new-timeseries`,ondemand:`/proxies/ondemand`,options:`/proxies/core-api`},credentials:void 0,apiKey:void 0,extensions:void 0,defaultVolumeBarColoring:void 0,defaultMainPlotBarColoring:void 0,async fetch(e,t){let n=this.baseUrl[e],r=`${n}${t}`;if(oF(this.mode)&&this.knownSite){let{username:i,password:a}=this.credentials||{},o=P(i,a),s=(e===`timeseries`||e===`timeseriesNew`)&&o&&this.allowCredentials?`&username=${i}&password=${a}`:``;r=`https://${this.dataEndpoint}${n}${t}${s}`}return await(await fetch(r)).text()},getCustomEventPopup:e=>null};async function mF(e,t){let n=$()?.config;if(!n||!n.fetch)throw Error(`You should call initFeed first`);let r=t;return e===`timeseries`?r=`/historical${t}`:e===`options`&&(r=`/options-historical${t}`),await n.fetch.call(n,e,r)}var hF=!1,gF=null;function _F(){let e=fF,t=e.prerelease?`-${e.prerelease.identifier}.${e.prerelease.ordinal}`:``;return`${e.major}.${e.minor}.${e.patch}${t}`}function vF(e){let t=e.extensions?.studyProvider;if(!P(t))return;let n=t.getFields(),r=t.getStudies(),i=F(Xs(B.CHART_SCHEMA)),a=i.definitions,o=a.studyField.enum,s=a.study.enum;for(let e of n)if(o.includes(e.id))throw Error(`Field with id ${e.id} already exists`);for(let e of r)if(s.includes(e.id))throw Error(`Study with id ${e.id} already exists`);o.push(...n.map(e=>e.id)),s.push(...r.map(e=>e.id)),kf(B.CHART_SCHEMA,i),zf(n),tc(r)}function yF(e,t={}){if(hF)throw Error(`You should only call initFeed once during page's lifetime`);hF=!0;let n=Object.assign(pF);return lt(n,t),N(n.logo)&&Wk(n.logo,n.logoClickable??!1),vF(n),gF=new e(n),gF.version=_F(),I(`%cBarchart Chart version ${gF.version}`,`info`,`font-size: larger`),gF.cachesData&&(gF.subject?.subscribe(gF.onPerformInternalGc.bind(gF)),eb.default.subscribe(K.CH_ALL,gF.onChartChanged.bind(gF))),gF}function $(){return gF}function bF(){return F($()?.template)}function xF(){N(gF)&&(gF.shutdown(),hF=!1,gF=null)}function SF(){return new YP(!0)}function CF(e){let t=SF();return t.load(e),t.change({id:`Outline`,context:{id:`Get`}})}function wF(e,t,n,r=null){return new Proxy(e,{get:function(e,i,a){return i===t?function(t){let a=r?t[r]:t;return(n.handlesRequestsFor(a)?n:e)[i](t)}:Reflect.get(e,i,a)}})}var TF=class{config;version;cachesData;timeSeriesSource;metaDataSource;recordSource;charts;pendingRedraw;template;ongoingAnimationCallbackId;_altDataSource;_subject;knowDefaultCurve;defaultOhlcCurve;knowDefaultAggregation;defaultAggregation;knowDefaultPeriod;defaultPeriod;knowDefaultDensity;defaultDensity;id;_mainFeed=null;onBrowserOnline;constructor(e){this.config=e,this.timeSeriesSource=this.metaDataSource=this.recordSource=null,this.charts=new Map,this.pendingRedraw=new Set,this.ongoingAnimationCallbackId=null,this.drawCharts=this.drawCharts.bind(this),this.template=null,this.cachesData=!1,this._altDataSource=null,this._subject=null,this.id=bt(),this.onBrowserOnline=()=>{!this.cachesData||this.isAuxiliary||(this.traceFeed(`refresh:online`),this.refreshCaches())},globalThis.addEventListener?.(`online`,this.onBrowserOnline)}traceFeed(e,t={}){Lh(e,{feedId:this.id,isAuxiliary:this.isAuxiliary,...t})}get subject(){return!this.isAuxiliary&&!N(this._subject)&&(this.traceFeed(`gc:stream:init`,{gcMillis:B.INTERNAL_GC_MILLIS}),this._subject=new em().pipe(Im(B.INTERNAL_GC_MILLIS),Fm(e=>e.length>0))),this._subject}get isAuxiliary(){return window.opener!==null}setAltDataSource(e){this._altDataSource=e,this.timeSeriesSource=wF(this.timeSeriesSource,`getTimeSeries`,e,`symbol`),this.metaDataSource=wF(this.metaDataSource,`getMetaData`,e),this.recordSource=wF(this.recordSource,`getRecord`,e)}replaceDataSources(e){this._altDataSource=e._altDataSource,this.timeSeriesSource=e.timeSeriesSource,this.metaDataSource=e.metaDataSource,this.recordSource=e.recordSource}getAltDataSource(){return this._altDataSource}getTimeSeriesDataSource(){if(!N(this.timeSeriesSource))throw Error(`No time series source defined`);return this.timeSeriesSource}getMetaDataSource(){if(!N(this.metaDataSource))throw Error(`No metadata source defined`);return this.metaDataSource}getRecordSource(){if(!N(this.recordSource))throw Error(`No record source defined`);return this.recordSource}async ready(){return da.call(this,async()=>{let e=this instanceof AF||this instanceof EF||this instanceof NF;await uF(this.config,e);let t=this.config.defaultTemplate;if(!t)throw Error(`Must provide a default template`);return typeof t==`string`&&(t=await(await fetch(t)).json()),this.template=Nf(t,B.CHART_SCHEMA),!0})}getHeadlessChart(){return SF()}fixupRenderTo(e){if(!N(e))return null;if(e instanceof HTMLElement)return e;let t=na(`#${e}`);if(N(t))return t;let n=[...this.charts.keys()].find(t=>t.id===e);return N(n)?n:null}checkChart(e,t){let n=this.fixupRenderTo(e),r=N(n)&&this.charts.has(n);return N(t)&&t!==r&&I(`There is ${t?`no`:`already a`} chart inside the element ${e}`,`error`),n}addChart(e,t=null){let n=this.checkChart(e,!1),r=new YP;return this.charts.set(n,r),r.initialize(e,t),r}removeChart(e){let t=this.checkChart(e,!0);N(t)&&(this.charts.get(t).shutdown(),this.charts.delete(t))}removeAllCharts(){for(let e of this.charts.keys())this.removeChart(e)}getChart(e){let t=this.checkChart(e);return N(t)?this.charts.get(t):null}redraw(e){let t=this.checkChart(e,!0);N(this.ongoingAnimationCallbackId)||(this.ongoingAnimationCallbackId=requestAnimationFrame(this.drawCharts)),N(t)&&this.pendingRedraw.add(t)}drawCharts(){this.ongoingAnimationCallbackId=null,this.pendingRedraw.forEach(e=>{let t=this.getChart(e);if(!N(t?.presenter?.view))return;let n=t.presenter.view;n.isHostElementVisible&&n.draw()}),this.pendingRedraw.clear()}get emptyEntities(){return{metaData:new Set,records:new Set,timeSeries:new Set}}getAllCacheableEntities(e){for(let t of this.charts.values())t.presenter.getCacheableEntities(e)}getCacheableEntities(){let e=this.emptyEntities;return this.getAllCacheableEntities(e),e.timeSeries.forEach(t=>{N(t)&&(N(t.record)&&e.records.add(t.record),N(t.records)&&Object.values(t.records).forEach(t=>e.records.add(t)))}),e}clearCaches(){this.evictUnused(this.emptyEntities)}refreshCaches(){let e=this.getCacheableEntities();this.traceFeed(`refresh:caches`,{metaData:e.metaData.size,records:e.records.size,timeSeries:e.timeSeries.size}),this.getMetaDataSource().refresh?.(),this.getRecordSource().refresh?.(e.records),e.timeSeries.forEach(e=>{e.isCached||e.refresh()}),this.getTimeSeriesDataSource().refresh(),Ge(K.DF_STREAMRECONNECTED,{})}evictUnused(e){this.getMetaDataSource().evictUnused(e.metaData),this.getRecordSource().evictUnused(e.records),this.getTimeSeriesDataSource().evictUnused(e.timeSeries)}onPerformInternalGc(){let e=this.getCacheableEntities();this.traceFeed(`gc:run`,{chartCount:this.charts.size,metaData:e.metaData.size,records:e.records.size,timeSeries:e.timeSeries.size}),this.evictUnused(e)}triggerGc(e=`unknown`){this.traceFeed(`gc:request`,{reason:e}),this.subject?.next()}onChartChanged(e,t){(e===K.CH_RECREATED||e===K.CH_SHUTDOWN)&&(this.isAuxiliary?this._mainFeed?.triggerGc(`${e}:aux:${this.id}`):this.triggerGc(e))}getDefaultMultiFieldCurve(){if(!N(this.template))return null;if(!this.knowDefaultCurve){let e=Ud(this.template);e.curves.length===1&&qu(e.curves[0].style)?this.defaultOhlcCurve=F(e.curves[0]):this.defaultOhlcCurve=null,this.knowDefaultCurve=!0}return this.defaultOhlcCurve}getDefaultAggregation(){return!this.knowDefaultAggregation&&this.template&&(this.defaultAggregation=F(this.template.data.aggregation),this.knowDefaultAggregation=!0),this.defaultAggregation}getDefaultPeriod(){return!this.knowDefaultPeriod&&this.template&&(this.defaultPeriod=this.template.display?.period,this.knowDefaultPeriod=!0),this.defaultPeriod}getDefaultDensity(){return!this.knowDefaultDensity&&this.template&&(this.defaultDensity=this.template.display?.density,this.knowDefaultDensity=!0),this.defaultDensity}shutdown(){globalThis.removeEventListener?.(`online`,this.onBrowserOnline),this.isAuxiliary||this.clearCaches(),this.removeAllCharts()}},EF=class extends TF{constructor(e){super(e),this.timeSeriesSource=new O_(!1),this.metaDataSource=new Ja,this.recordSource=new Vh}},DF=class extends TF{constructor(e){super(e),this.timeSeriesSource=new O_(!0),this.metaDataSource=new Ja,this.recordSource=new Hh}},OF=class extends TF{constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new O_(!0),this.metaDataSource=new Ja,this.recordSource=new Vh}},kF=[`drazen.dotlic@barchart.com`,`princec`,`b.hebert24@barchart.com`],AF=class extends TF{lastStreamingTimestamp=null;_isActivelyStreaming=null;needToResubscribe=!1;_connection;constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new O_(!0),this.metaDataSource=new Ya,this.recordSource=new Uh,this.onEvents=this.onEvents.bind(this),this.onTimestamp=this.onTimestamp.bind(this),this.resetStreamingState()}resetStreamingState(){this.lastStreamingTimestamp=null,this._isActivelyStreaming=null,this.needToResubscribe=!1}get connection(){return this._connection}set connection(e){this._connection=e,N(e)&&this.initializeStreaming()}addChart(e,t=null){return this.needToResubscribe&&this.initializeStreaming(),super.addChart(e,t)}set isActivelyStreaming(e){N(this._isActivelyStreaming)&&!this._isActivelyStreaming&&e&&(this.debug(`need to refresh caches`),this.refreshCaches()),this._isActivelyStreaming=e}get isActivelyStreaming(){return this._isActivelyStreaming}initializeStreaming(){this.resetStreamingState(),this.connection.on(`events`,this.onEvents),this.connection.on(`timestamp`,this.onTimestamp)}onTimestamp(e){this.isActivelyStreaming&&(this.lastStreamingTimestamp=e)}debug(e){this.connection&&kF.includes(this.connection._username)&&I(`[chart] Connection ${e}, last timestamp ${this.lastStreamingTimestamp}`)}onEvents({event:e}){e===B.BC_EVENT_DISCONNECTED||e===B.BC_EVENT_FEED_PAUSED?(this.debug(e),this.isActivelyStreaming=!1):(e===B.BC_EVENT_LOGGED_IN||e===B.BC_EVENT_FEED_RESUMED)&&(this.debug(e),this.isActivelyStreaming=!0)}shutdown(){super.shutdown(),N(this._connection)&&(this.connection.off(`timestamp`,this.onTimestamp),this.connection.off(`events`,this.onEvents),this.resetStreamingState(),this.connection.disconnect(),this.connection=null)}};function jF(e,t){return new MF(e,t)}var MF=class{_client;_subscriptions=new Map;_listeners=new Set;constructor(e,t){this._client=e;let n=e=>e.find(e=>this._subscriptions.has(e))??null;t.onConnected=()=>{this._listeners.forEach(e=>e?.onConnected())},t.onMessageWithMetadata=(e,t)=>{let r=e.marketSnapshot;if(N(r)){let e=n(t);e!==null&&this._listeners.forEach(t=>t.onSnapshot?.(r,e))}let i=e.marketUpdate;if(N(i)){let e=n(t);e!==null&&this._listeners.forEach(t=>t.onUpdate?.(i,e))}},t.onDisconnected=()=>{this._listeners.forEach(e=>e?.onDisconnected())},t.onHeartBeat=e=>{this._listeners.forEach(t=>t.onHeartBeat?.(e))}}addListener(e){this._listeners.add(e)}removeListener(e){this._listeners.delete(e)}async ready(){return N(await this._client.connection)}shutdown(){N(this._client)&&(this._client.dispose(),this._subscriptions.clear(),this._listeners.clear())}subscribeToRealTime(e){if(this._subscriptions.has(e)||!N(this._client))return;let t=this._client.subscribe(1,5,0,[e],null,null,null);this._subscriptions.set(e,t)}unsubscribeFromRealTime(e){if(!this._subscriptions.has(e)||!N(this._client))return;let t=this._subscriptions.get(e);this._client.unsubscribe(t),this._subscriptions.delete(e)}async getInstrument(e){return await(await this._client.connection)?.getInstrument(e)??[]}},NF=class extends TF{_adapter=null;_auxFeeds=[];constructor(e){super(e),this.cachesData=!0,this.isAuxiliary||(this.timeSeriesSource=new O_(!0),this.metaDataSource=new Xa,this.recordSource=new Wh,eb.default.subscribe(K.TS_ALL,this.onTimeSeriesMessage.bind(this)))}onTimeSeriesMessage(e,t){if(!this.isAuxiliary)for(let n of this._auxFeeds)n.notifySeriesMessage(e,t)}notifySeriesMessage(e,t){this.isAuxiliary&&Ge(e,t)}getAdapter(){return this.isAuxiliary?this._mainFeed?._adapter:this._adapter}setAdapter(e){if(this.isAuxiliary)throw Error(`Cannot set adapter on auxiliary feed`);this._adapter=e,this._adapter.addListener(this)}async ready(){if(this.isAuxiliary){let e=await this._mainFeed?.ready()??!1;return e&&(this.template=this._mainFeed.template),e}return await super.ready(),await this._adapter?.ready()??!1}subscribe(e){this.traceFeed(`openfeed:subscribe`,{symbol:e}),this.getAdapter()?.subscribeToRealTime(e)}unsubscribe(e){this.traceFeed(`openfeed:unsubscribe`,{symbol:e}),this.getAdapter()?.unsubscribeFromRealTime(e)}shutdown(){super.shutdown(),this.isAuxiliary?(this._mainFeed?.removeAuxFeed(this),this._mainFeed=null):this._adapter?.shutdown()}onConnected(){this.refreshCaches()}onDisconnected(){}onHeartBeat(){}onUpdate(e,t){this.ofRecordSource.onUpdate(e,t)}onSnapshot(e,t){this.ofRecordSource.onSnapshot(e,t)}get ofRecordSource(){return this.recordSource}replaceDataSources(e){super.replaceDataSources(e),this._mainFeed=e}addAuxFeed(e){e.replaceDataSources(this),this._auxFeeds.push(e),this._adapter?.addListener(e)}removeAuxFeed(e){let t=this._auxFeeds.findIndex(t=>t.id==e.id);t!==-1&&(this._auxFeeds.splice(t,1),this._adapter?.removeListener(e),this.triggerGc(`removeAuxFeed:${e.id}`))}getAllCacheableEntities(e){if(super.getAllCacheableEntities(e),!this.isAuxiliary)for(let t of this._auxFeeds)t.getAllCacheableEntities(e)}},PF=eb.default;export{zu as Aggregation,_ as AggregationSpec,g as AggregationUnit,EF as BarchartSiteDataFeed,TF as BaseDataFeed,Bh as BaseRecordSource,re as ChunkPart,y_ as ContainerWrapperTimeSeries,xM as CustomEventPopup,Kf as EmptyRecord,u as ExpressionMissingBar,f as ExpressionNoDataApproach,d as ExpressionRecompute,nb as ExpressionSeries,If as Field,b as FieldCategory,y as FieldFormat,v as FieldValueType,G as Fields,AF as MarketDataFeed,OF as MiniWidgetDataFeed,gg as OHLCDataPointBuilder,NF as OpenFeed,PF as PubSub,w as SeriesKind,DF as SnapshotDataFeed,J as StudySeries,vg as TimeSeriesContainer,$y as TimeSeriesQuery,K as Topics,jF as adaptOpenFeedClient,sa as appendDOMElement,da as asyncReady,cc as canBeBasedOnSeasonal,Z as convertSeries,YM as convertTableToCsv,ug as dateToOptionValue,Ed as doesExpressionHaveComputation,oc as doesStudyExist,xd as evaluateExpression,wd as formatExpression,Ia as formatPriceWithDecimals,bt as generateUid,ic as getAnnotationTraits,CF as getChartOutline,La as getCombinedMetaData,Td as getExpressionSymbols,$ as getFeed,bo as getLightness,Oj as getStudyOptions,pc as getTaxonomies,Hi as hasOpenInterest,yF as initFeed,iO as linReg,tb as makeExpression,q as makeHelperField,ND as makeStudy,Q as mapSeries,Y as movAvg,X as movExp,RD as movHul,ID as movSmo,LD as movWei,lg as optionValueToDate,bd as parseExpression,Dd as replaceExpressionSymbols,YD as roc,ia as setAttributesDOMElement,xF as shutdownFeed,QD as stdDev,ra as styleDOMElement,WD as trueRange,JD as typical};
|
|
42
|
+
`)}function XM(e={}){return YM(GM.call(this,e),e)}function ZM(e={}){let t=this.view.mainCanvas,{width:n,height:r}=t,{width:i,height:a,title:o}=e,s=(e,t)=>{let n=document.createElement(`canvas`);return n.width=e,n.height=t,n.getContext(`2d`)},c=s(n,r),l=globalThis.devicePixelRatio;if(c.drawImage(t,0,0),c.scale(l,l),N(o)){let e=new PM(this);e.update(o),e.draw(c)}let u=this.mainPlot?.timeSeries.container?.getLastDataPoint(G.DateTime);if(N(u)){let{fontFamily:e}=this.display.chart,{fontWeight:n,fontSize:r}=this.mainAxis.config;c.font=`${n} ${r*1.2}px ${e}`,c.textBaseline=`top`;let i=r*1.5,a=getComputedStyle(t),o=a.getPropertyValue(`--app-hc-color`),s=a.getPropertyValue(`--app-color-pl`),l={x:B.CARDS_X_OFFSET,y:B.CARDS_Y_OFFSET},d=Iv(this,u,l,void 0,!1,0),f=`${d.date} ${d.time??``}`.trim(),[p,m]=[1,5],h=(e,t)=>c.measureText(e).width+t,g=(e,t,n,r,i)=>(c.fillStyle=r,c.fillText(e,t,n),h(e,i)),_=(e,t)=>e.type===C[t],v=e=>{let t=e.name;return e.isMain&&_(e,`Symbol`)?t=`${e.description} (${e.name}) [${e.exchange}]`:_(e,`Study`)&&(t=`${e.description} ${e.name.substring(e.name.indexOf(` `))}`),t};d.panes.forEach(e=>{let{top:t,left:n,width:r,right:a}=e.bounds,c=n+r-a-m,u=n+l.x,d=t+l.y;e.plots.some(e=>e.isMain)&&(u+=g(f,u,d,o,m)),e.plots.forEach((e,t)=>{let r=v(e),a=!_(e,`Study`)&&e.values.length>1;if(!e.isMain&&t>0){let t=u+h(r,m);e.values.forEach(e=>{a&&(t+=h(e.abbreviation,p)),t+=h(e.value,m)}),t>=c&&(u=n+l.x,d+=i)}u+=g(r,u,d,o,m),e.values.forEach(e=>{a&&(u+=g(e.abbreviation,u,d,s,p)),u+=g(e.value,u,d,e.color,m)})})})}let d=e=>({width:i??n,height:a??r,data:e.toDataURL(`image/png`)});if(N(i)&&N(a)){let e=s(i,a);return e.drawImage(c.canvas,0,0,i,a),d(e.canvas)}else return d(c.canvas)}function QM(e){if(e!==void 0)return e===B.YTD_PERIOD?e:vt(e)}var $M=Symbol.for(`__ias__`),eN=class{accessor;view;defaultTool;_activeTool;tooltipEnabled=!0;timeline;sentInitialLoadNotification=!1;_hostElement=null;undoRedoManager;title;display;model;data;panes=[];_hasLegend;renderTo;seriesChangedToken=``;metaChangedToken=``;streamingSubscription=null;_previousMask=0;_ohlcMask;selectedAnnotation;annotationPreviewUid;hoverHighlightPlotIds=null;hoverDimPlotIds=null;hoverBasisByDependentPlotId=new Map;hoverDependentsByBasisPlotId=new Map;hoverHighlightablePlotIds=new Set;forceResetVisibleRange=!1;_maxOffset=0;_isShutdown=!1;notifySelectionChanged;notifyRecreated;notifyDefinitionChanged;constructor(e){this.accessor=e,this.defaultTool=Cj(`Default`),this._activeTool=this.defaultTool,this.timeline=new pv(this),this.undoRedoManager=new NM(this),this.title=new PM(this),this.notifySelectionChanged=Ke(K.CH_ANNSELECTIONCHANGED),this.notifyRecreated=Ke(K.CH_RECREATED),this.notifyDefinitionChanged=Ke(K.CH_DEFINITION_CHANGED)}traceChart(e,t={}){Lh(e,{chartId:this.elementId,...t})}getModel(){return this.model}get isEmpty(){return!P(this.model)}notifyHost(e,t){Ge(e,t)}async fromModel(e,t){if(this._isShutdown)return;this.traceChart(`chart:fromModel:start`,{hadModel:P(this.model)}),P(this.model)&&this.allPlots.forEach(e=>e.shutdown()),this.sentInitialLoadNotification=!1,this.clearHoverHighlight(),this.clearHoverHighlightRelations(),this.annotationPreviewUid=void 0,this.clearSelection(),this.model=e;let n=F(e);this.data=n.data,this.data.aggregation=Mu(n.data.aggregation),this.display=n.display,this.display.period=QM(n.display?.period);let r=this.panes;this.panes=n.panes.map(e=>{let t=new aM(this);return t.fromModel(e),t},this),this.undoRedoManager.rebindOwners(r);let i=this.allPlots.map(e=>e.initialize());await Promise.all(i),!this._isShutdown&&(this.rebuildHoverHighlightRelations(),this.traceChart(`chart:fromModel:plots-ready`,{plotCount:this.allPlots.length}),this.timeline.invalidate(),this.checkZoomAndVisibleRange(e,t),P(e,t)&&this.notifyDefinitionChanged({chart:this.accessor}),this.reinitializeView())}checkZoomAndVisibleRange(e,t){if(this.view)if(this.forceResetVisibleRange)this.forceResetVisibleRange=!1,this.view.resetZoomAndVisibleRange=!0,this._maxOffset=0;else{let n=!t||aN(e,t,this);this.view.resetZoomAndVisibleRange=n,n&&(this._maxOffset=0)}}closeView(){P(this.view)&&(this.view.shutdown(),this.view=void 0)}reinitializeView(){this._isShutdown||(P(this.view)?this.view.reinitialize():(this.view=new yM,this.view.initialize(this)),this.notifyRecreated({elementId:this.elementId}))}getCacheableEntities(e){let t={metaData:e.metaData.size,records:e.records.size,timeSeries:e.timeSeries.size};this.isEmpty||this.allPlots.map(t=>t.getCacheableEntities(e)),this.traceChart(`chart:cacheable-entities`,{plotCount:this.allPlots.length,addedMetaData:e.metaData.size-t.metaData,addedRecords:e.records.size-t.records,addedTimeSeries:e.timeSeries.size-t.timeSeries})}get activeTool(){return this._activeTool}set activeTool(e){P(this._activeTool.deactivated)&&this._activeTool.deactivated(this),this._activeTool=e,P(this._activeTool.activated)&&this._activeTool.activated(this),this.notifyHost(K.TL_CHANGED,{chart:this.accessor})}get mainPlot(){return this.allPlots.find(e=>e.main)}get mainAxis(){return this.mainPlot?.axis}get mainPane(){return this.mainAxis?.pane}get allAxes(){let e=[];return this.panes.forEach(t=>{t.axes.forEach(t=>{e.push(t)})}),e}get plotAnnotations(){let e=[];return this.allPlots.forEach(t=>{t.isVisible&&t.annotations?.forEach(t=>{e.push(t)})}),e}get allAnnotations(){let e=[];return this.allAxes.forEach(t=>{t.annotations.forEach(t=>{e.push(t)})}),e}get allPlots(){let e=[];return this.allAxes.forEach(t=>{t.plots.forEach(t=>{e.push(t)})}),e}findAxis(e){return this.allAxes.find(t=>t.id===e)}findPlot(e){return this.allPlots.find(t=>t.id===e)}get allCurves(){let e=[];return this.allPlots.forEach(t=>{t.curves.forEach(t=>{e.push(t)})}),e}findCurve(e){return this.allCurves.find(t=>t.id===e)}get hasStudyBasisFocus(){return this.display?.chart?.studyBasisFocus===!0}get hasHoverHighlight(){return this.hoverHighlightPlotIds!==null||this.hoverDimPlotIds!==null}getStudyBasis(e){return e.isStudy?e.basePlot??null:null}isHoverSourcePlot(e){return e.isSeasonal||e.isSymbol}hasMultipleHoverSourcePlots(){return this.allPlots.filter(e=>e.isVisible&&this.isHoverSourcePlot(e)).length>1}get annotationManipulation(){return $()?.config.annotationManipulation===!0}setAnnotationPreview(e){this.annotationPreviewUid!==e&&(this.annotationPreviewUid=e,this.view?.redraw())}clearHoverHighlight(){this.hoverHighlightPlotIds=null,this.hoverDimPlotIds=null}clearHoverHighlightRelations(){this.hoverBasisByDependentPlotId.clear(),this.hoverDependentsByBasisPlotId.clear(),this.hoverHighlightablePlotIds.clear()}rebuildHoverHighlightRelations(){if(this.clearHoverHighlight(),this.clearHoverHighlightRelations(),this.hasStudyBasisFocus&&this.hasMultipleHoverSourcePlots())for(let e of this.allPlots){if(this.isHoverSourcePlot(e)&&this.hoverHighlightablePlotIds.add(e.id),!e.isStudy)continue;let t=this.getStudyBasis(e);if(!P(t))continue;this.hoverBasisByDependentPlotId.set(e.id,t.id);let n=this.hoverDependentsByBasisPlotId.get(t.id);P(n)||(n=new Set,this.hoverDependentsByBasisPlotId.set(t.id,n)),n.add(e.id),this.hoverHighlightablePlotIds.add(e.id),this.hoverHighlightablePlotIds.add(t.id)}}isHoverHighlightable(e){return this.hasStudyBasisFocus&&P(e)&&this.hoverHighlightablePlotIds.has(e.id)}getRelatedHoverPlotIdsForPlot(e){if(!this.isHoverHighlightable(e))return null;let t=new Set,n=this.hoverBasisByDependentPlotId.get(e.id);if(P(n))return t.add(e.id),t.add(n),t;let r=this.hoverDependentsByBasisPlotId.get(e.id);return P(r)&&r.size>0?(t.add(e.id),r.forEach(e=>t.add(e)),t):(t.add(e.id),t)}getRelatedHoverPlotIds(e){let t=new Set;for(let n of e){let e=this.getRelatedHoverPlotIdsForPlot(n);e!==null&&e.forEach(e=>t.add(e))}return t.size>0?t:null}getHoverDimPlotIds(e){if(!this.hasStudyBasisFocus||e===null)return null;let t=new Set;for(let n of this.hoverHighlightablePlotIds)e.has(n)||t.add(n);return t}sameHoverHighlight(e){let t=this.hoverHighlightPlotIds;if(t===null||e===null)return t===e;if(t.size!==e.size)return!1;for(let n of t)if(!e.has(n))return!1;return!0}setHoverHighlight(e){if(!this.hasStudyBasisFocus)return this.hasHoverHighlight&&(this.clearHoverHighlight(),this.view?.redraw()),!1;let t=this.getRelatedHoverPlotIds(e);return this.sameHoverHighlight(t)?this.hoverHighlightPlotIds!==null:(this.hoverHighlightPlotIds=t,this.hoverDimPlotIds=this.getHoverDimPlotIds(t),this.view?.redraw(),t!==null)}shouldDimPlot(e){return this.hasStudyBasisFocus&&(this.hoverDimPlotIds?.has(e.id)??!1)}fixupDensityForForwards(){let e=this.allPlots.filter(e=>e.isForward).map(e=>e.timeSeries.container?.size??0);e.some(e=>e>0)&&(this.display.density=Math.max(...e))}onSeriesChanged(e,t){if(!this.view||!this.allPlots)return;let n=t.series,r=e=>e.timeSeries===n||e.eventsSeries===n,i=this.allPlots.find(r);if(!P(i))return;let a=P(i)&&i.main,o=!1,s=!1;if(e===K.TS_TIMELINECORRECTION){if(!this.timeline.tryToCorrectLastBar(t.from,t.to))return;o=!0}let c=P(t.index)?n.container.getTimeData()[t.index]:null,l=e===K.TS_EVENTSCHANGED,u=this.view.xAxis,d=u.xScale;if(e===K.TS_MANYCHANGED||l){if(a&&this.data.checkRange)if(P(this.display.xAxis.visibleRange)){let e={id:`Period`,context:{range:this.display.xAxis.visibleRange}};e[$M]=!0,this.accessor.change(e);return}else delete this.data.checkRange;i.isForward&&this.fixupDensityForForwards();let e=this.view.xAxis?.getMaxCurveOffset()??0;i.isStudy&&(e!==this._maxOffset&&(this._maxOffset=e,u.goToLatest(!0)),i.invalidateAssociatedAnnotations(`NewChunkArrived`));let n=P(this.display?.xAxis?.visibleRange);if((i.isSeasonal&&!u.wasVisibleRangeChanged&&!n||this.display?.xAxis?.isOrdinal)&&u.goToLatest(!0),t.part===re.Tail){let e=j(this.timeline,c,Number,fv);u.shouldScrollIntoView(e)&&d.shiftBars(t.count)}this.timeline.invalidate(),this.allPlots.forEach(e=>e.invalidatePriceMappingCache()),o=!0}else if(e===K.TS_DATAPOINTADDED){let e=this.timeline.mergeDateIntoTimeline(c);e!=-1&&u.shouldScrollIntoView(e)?(d.shiftBars(1),o=!0):s=!0,i.isStudy&&i.invalidateAssociatedAnnotations(`DataPointAdded`)}else e===K.TS_DATAPOINTCHANGED&&(s=!0,i.isStudy&&i.invalidateAssociatedAnnotations(`DataPointChanged`));if(!l&&r(this.mainPlot)&&n.hasData&&n.container.size===0&&this.notifyHost(K.CH_NODATAFORMAINSYMBOL,{chart:this.accessor}),o&&this.view.recalculateLayout(),s&&(o&&I(`Performance : redundant call to recompute price domains (layout recalculation took care of this)`,`warn`),this.allAxes.filter(e=>e.plots.includes(i)).forEach(e=>{e.setDomain(),P(c)&&e.updateFullDomain(c)})),!this.sentInitialLoadNotification&&e===K.TS_MANYCHANGED&&this.allPlots.every(e=>e.timeSeries&&e.timeSeries.hasData)){this.sentInitialLoadNotification=!0,this.notifyHost(K.CH_ALL_DATA_PROJECTED,{chart:this.accessor}),Fk(this);let e=this.display.period===B.FIFTY_YEARS_MILLIS;this.mainPlot&&e&&(d.fitAllData=!0,d.adjustDomain())}this.view.redraw()}onMetaChanged(e,t){e===K.MD_CHANGED&&this.view&&this.allPlots&&this.allPlots.find(e=>e.id===t.plot.id)&&(t.plot.main&&this.allAnnotations.forEach(e=>e.onFormatterChanged()),this.view.recalculateLayout(),this.view.redraw())}priceDomainsUpdated(){this.allPlots.forEach(e=>{e.notifyAboutPriceDomains&&e.onPriceDomainsUpdated()})}onScaleDomainChanged(e){let t=this.panes.indexOf(e.pane),n=e.pane.axes.indexOf(e),r={chart:this.accessor,paneIndex:t,axisIndex:n};this.notifyHost(K.CH_AXISSCALECHANGED,r)}get previousMask(){return P(this._previousMask)||(this._previousMask=Hf(G.PreviousClose)),this._previousMask}hasMatch(e,t){return e.some(e=>e.updated&&t)}get hasLegend(){if(!P(this._hasLegend)){let e=ne[$()?.config.mode??`Unspecified`];this._hasLegend=[ne.cmdtyView,ne.EqPlus].includes(e)}return this._hasLegend}onStreamingUpdates(e){P(this.view)&&(this.mainPlot.showPrevious&&this.hasMatch(e,this.previousMask)&&this.view.redraw(),this.hasLegend&&this.hasMatch(e,this.ohlcMask)&&this.view.updateLegend())}get ohlcMask(){return P(this._ohlcMask)||(this._ohlcMask=Hf(G.Open,G.High,G.Low,G.Close,G.PreviousClose)),this._ohlcMask}updateMatches(e,t){if((e&this.ohlcMask)===0)return!1;let n=(e,t)=>N(e)&&e.isValid&&e.hasSymbol(t);return this.mainPlot.isSymbol?n(this.mainPlot.timeSeries.record,t):this.mainPlot.isExpression?n(this.mainPlot.record,t):!1}getStreamingSubscription(){return $().getRecordSource().subject.pipe(Mm(e=>e.filter(e=>this.updateMatches(e.updated,e.data.symbol))),Fm(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}get hostElement(){return this._hostElement}get elementId(){return P(this._hostElement)?this._hostElement.id:null}initialize(e){if(this._hostElement=e instanceof HTMLElement?e:na(`#${e}`),!this._hostElement)throw Error(`There is no element ${e} in the DOM`);this.renderTo=e,this.seriesChangedToken=eb.default.subscribe(K.TS_ALL,this.onSeriesChanged.bind(this)),this.metaChangedToken=eb.default.subscribe(K.MD_ALL,this.onMetaChanged.bind(this)),this.streamingSubscription=this.getStreamingSubscription()}shutdown(){return eb.default.unsubscribe(this.seriesChangedToken),eb.default.unsubscribe(this.metaChangedToken),P(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.allPlots.forEach(e=>e.shutdown()),this.model=void 0,this.closeView(),this.notifyHost(K.CH_SHUTDOWN,{elementId:this.elementId}),this._isShutdown=!0,!0}setSelection(e){this.selectedAnnotation!==e&&(this.selectedAnnotation&&this.clearSelection(),this.selectedAnnotation=e,this.selectedAnnotation.isSelected=!0,this.selectedAnnotation.requestRedraw(),this.notifySelectionChanged({chart:this.accessor}))}clearSelection(){P(this.selectedAnnotation)&&(this.selectedAnnotation.isSelected=!1,this.selectedAnnotation.requestRedraw(),this.selectedAnnotation=void 0),this.notifySelectionChanged({chart:this.accessor})}resetActiveTool(){this.activeTool=this.defaultTool,this.view.setCursor(ee.Arrow)}print(e={}){let t=sa(document.body,`iframe`);t.src=``,t.style.display=`none`,t.onload=()=>{let{title:n}=e,r=ZM.call(this,{title:n}),i=new Image;i.src=r.data,i.style.width=`100%`,t.contentDocument.body.appendChild(i),ua(i).then(()=>{let e=t.contentWindow;t.focus(),e.print(),t.remove()})}}setTitle(e,t=!1){this.title.update(e),P(this.view)&&this.view.redraw(t)}enableTooltip(e){this.tooltipEnabled=e;let t=this.display.tooltip.mode===B.TOOLTIP_CARDS;!e&&t&&this.hideCards()}get showTooltip(){return this.display.tooltip.visible&&this.tooltipEnabled}hideCards(e=!1){let t=this.display.tooltip,n=Ie();!e&&t.visible&&t.mode===B.TOOLTIP_CARDS&&ca(`.bcharts-card`,this.hostElement).forEach(e=>{let t=e.classList.contains(`bcharts-card-move`);n&&t||e.classList.contains(`bcharts-legend`)||(e.style.display=`none`)})}handleAnnotationChange(e){let t=(e,t=!0)=>({id:t?e.name:e.id,uid:e.uid,visible:e.visible});if(e.id===`List`)return this.allAnnotations.map(t);if(e.id===`Cache`)return H(this.model,`..annCache{.annotations}`).map(e=>({symbol:e.symbol,annotations:e.annotations.map(e=>t(e,!1))}));if(e.id===`Add`){let t=e.annotation;return(t.isUndoRedo?t.owner?.axis??this.mainAxis:this.mainAxis)?.addAnnotation(t)}let n=this.allAnnotations.find(t=>t.uid===e.uid);if(n!==void 0){if(e.id===`Delete`&&!e.isUndoRedo)return this.deleteAnnotationWithUndo(n);let t=n.axis,r=t[`${e.id.toLowerCase()}Annotation`];if(typeof r==`function`){r.call(t,n,e);return}}throw Error(`Unknown sub-action ${e.id} for action ${B.ANN_ACTION_ID}`)}deleteAnnotationWithUndo(e){this.undoRedoManager.done(ok(e,O.Deleted)),e.axis.deleteAnnotation(e),this.onAnnotationModifiedByTool(e,O.Deleted,!1)}getPlotInfoFromDom(e){let t=e.attributes.getNamedItem(`data-plot-uid`);if(!t)throw Error(`Unable to resolve plot info: missing data-plot-uid attribute.`);let n=t.value,r=0;for(let e of this.model.panes)for(let t of e.axes)for(let e of t.plots){if(e.uid===n)return{type:e.type,index:r};r++}throw Error(`Unable to resolve plot info: model plot index not found for uid '${n}'.`)}getSimplePlot(e,t){return this.accessor.change({id:`Plot`,context:{id:B.ACTION_GET,type:e,index:t}})[0]}onCardClicked(e){let t=this.getPlotInfoFromDom(e),n=this.getSimplePlot(t.type,t.index),r={chart:this.accessor,plot:n};this.notifyHost(K.CH_CARDPLOTCLICKED,r)}deletePlotClicked(e){let t=this.getPlotInfoFromDom(e),n=this.getSimplePlot(t.type,t.index);this.accessor.change({id:`Plot`,context:{id:`Delete`,type:t.type,index:t.index}});let r={chart:this.accessor,plot:n};this.notifyHost(K.CH_CARDPLOTREMOVED,r)}showHidePlotClicked(e){this.defaultTool.hideCrosshairAndTooltips(this.view,!0);let t=this.getPlotInfoFromDom(e),n=e.attributes.getNamedItem(`data-act`).value===`Show`;this.accessor.change({id:`Plot`,context:{id:`Update`,type:t.type,index:t.index,visible:n}});let r=this.getSimplePlot(t.type,t.index),i={chart:this.accessor,plot:r,visible:n};this.notifyHost(K.CH_CARDPLOTVISIBILITYCHANGED,i)}plotMoreActionsClicked(e,t){let n=this.getPlotInfoFromDom(e),r=this.getSimplePlot(n.type,n.index),i={x:t.clientX,y:t.clientY},a={chart:this.accessor,plot:r,offset:i,originalEvent:t};this.notifyHost(K.CH_PLOTNEEDSCONTEXTMENU,a)}onMovePaneClicked(e){let t=parseInt(e.attributes.getNamedItem(`data-pane`).value),n=e.attributes.getNamedItem(`data-dir`).value===`Down`,r=t+ +!!n,i=t-+!n;setTimeout(()=>{this.accessor.change({id:`MovePane`,context:{from:r,to:i}}),this.notifyHost(K.CH_PANESREORDERED,{chart:this.accessor})})}onAnnotationsUpdated(e,t=!1){let n=this.allAxes.indexOf(e),r=e.annotations.map(e=>e.toModel()),i=SM(this.model,{axisIndex:n,annotations:r});try{this.model=Nf(i,B.CHART_SCHEMA)}catch(e){I(`Cannot update annotation (corrupts definition), error is: ${e.message}`,`error`)}t&&this.view.draw(),this.notifyHost(K.CH_ANNOTATIONCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}onAnnotationModifiedByTool(e,t,n=!0,r=!1){if(t!==O.None){if(n&&t!==O.Undo&&t!==O.Redo){let n=ok(e,t);this.undoRedoManager.done(n)}let i=sk(e);i.toolChange=O[t],(r||t===O.Reordered)&&(i.orderOnly=!0),this.notifyHost(K.CH_ANNMODIFIEDBYTOOL,i)}}onAnnotationDone(e,t){let n={id:e,chart:this.accessor,toolChange:O[t]};this.notifyHost(K.CH_ANNMODIFIEDBYTOOL,n)}onPaneHeightsUpdated(){let e=this.panes.map((e,t)=>({index:t,relativeHeight:e.height}));this.model=AM(this.model,{paneHeights:e}),this.notifyHost(K.CH_PANEHEIGHTSCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}getDataStats(){let e=this.mainPlot.timeSeries.container;if(!P(e)||e.size===0)return null;let t=e.getTimeData(),n=Ce(t),r=Se(t);return P(n,r)?{dataRange:{from:n.getTime(),to:r.getTime()},barCount:e.size}:null}};function tN(e,t){return e?.from===t?.from&&e?.to===t?.to}var nN=[`Renko`,`Range`,`LineBreak`,`Kagi`,`PointAndFigure`];function rN(e,t){for(let n of Object.keys(e))if(e[n]!==t[n])return!0}function iN(e,t){let n=e=>e.curves[0],r=n(e),i=n(t),a=nN.includes(r.style),o=nN.includes(i.style);return a===o?o?!!(r.style!==i.style||t.inputs&&rN(dt(e.inputs),dt(t.inputs))):!1:!0}function aN(e,t,n){let r={id:`Aggregation`,context:{id:`Get`}};if(rN(ju(VP(r,t,n)),ju(VP(r,e,n)))||!tN(e.display?.xAxis?.visibleRange,t.display?.xAxis?.visibleRange)||e.display?.xAxis?.marginBars!==t.display?.xAxis?.marginBars||!tN(e.data?.range,t.data?.range)||e.data?.extendedHours!==t.data?.extendedHours||e.display?.period!==t.display?.period||e.display?.density!==t.display?.density)return!0;let i=Ud(t),a=Ud(e);if(iN(i,a))return!0;let o=(e,t)=>e.type===t,s=e=>{let t=e.toLowerCase();return o(a,e)&&o(i,e)&&i[t]!==a[t]},c=i.type!==a.type,l=s(`Forward`),u=s(`Expression`),d=s(`Symbol`);return c||l||u||d}function oN(e,t,n){if(`paneIndex`in t||`axisIndex`in t)throw Error(`AnnotationManipulation paneIndex and axisIndex are output-only metadata; use uid`);let r=n?.selectedAnnotation?.uid,i=n?.annotationPreviewUid;return e.panes.flatMap((e,n)=>e.axes.flatMap((e,a)=>(e.annotations||[]).map((e,t)=>({uid:e.uid,paneIndex:n,axisIndex:a,position:t,selected:r===e.uid,preview:i===e.uid})).filter(e=>t.uid===void 0||e.uid===t.uid)))}function sN(e,t){return e===`Front`?t-1:e===`Back`?0:xt(0,t-1,e)}function cN(e,t,n){let{uid:r,position:i,selected:a,preview:o}=t;if(t.id!==void 0&&t.id!==`Update`)throw Error(`Invalid AnnotationManipulation sub-action`);if(i!==void 0&&!(i===`Front`||i===`Back`)&&!(Number.isInteger(i)&&i>=0))throw Error(`Annotation position must be Front, Back, or a non-negative integer`);if((i!==void 0||a===!0||o===!0)&&r===void 0)throw Error(`AnnotationManipulation requires uid for position, selection, or preview`);let s=oN(e,t,n),c=r===void 0?void 0:s[0],l=c&&n?.panes[c.paneIndex]?.axes[c.axisIndex],u=l?.annotations.find(e=>e.uid===r),d=u?.isVisible&&!u.computed?u:void 0;if(c&&i!==void 0){let t=e.panes[c.paneIndex].axes[c.axisIndex].annotations,r=sN(i,t.length);if(r!==c.position){let e=t.map(e=>e.uid);if(l&&u&&n){let t=[...e];t.splice(r,0,t.splice(c.position,1)[0]),l.annotations.sort((e,n)=>t.indexOf(e.uid)-t.indexOf(n.uid)),n.undoRedoManager.done({owner:l.annotationUndoOwner,uid:u.uid,toolChange:O.Reordered,before:e,after:t}),n.onAnnotationsUpdated(l),n.onAnnotationModifiedByTool(u,O.Reordered,!1),u.requestRedraw()}else t.splice(r,0,t.splice(c.position,1)[0])}}return n&&o!==void 0&&(o&&d?n.setAnnotationPreview(d.uid):!o&&(r===void 0||n.annotationPreviewUid===r)&&n.setAnnotationPreview()),n&&a!==void 0&&(a&&d?n.setSelection(d):!a&&s.some(e=>e.selected)&&n.clearSelection()),e}function lN(e,t){let[n,r]=Qe(t.crosshair),{color:i,dashStyle:a}=t.horizontal||{},{color:o,dashStyle:s}=t.vertical||{},c=(e,t,n)=>{t&&(e.color=t),n&&(e.dashStyle=n)},l=U(e,`.display.xAxis.crosshair`,e=>(e.enabled=n,c(e,o,s),e));return l=U(l,`.display.yAxis.crosshair`,e=>(e.enabled=r,c(e,i,a),e)),P(t.haloTracking)&&typeof t.haloTracking==`boolean`&&(l=U(l,`.display.chart`,e=>(e.plotHover=t.haloTracking,e))),l}function uN(e,t){return U(e,`.display.tooltip`,e=>(t.visible!=null&&(e.visible=t.visible),t.mode&&(e.mode=t.mode),t.showMainTitle!=null&&(e.showMainTitle=t.showMainTitle),t.mainTitle&&(e.mainTitle=t.mainTitle),e))}function dN(e,t){let n=F(t);return Object.keys(t).forEach(e=>{B.EVENTS.includes(e)||delete n[e];let r=t[e];typeof r==`boolean`?r={show:t[e]}:Object.keys(r).forEach(e=>{B.EVENT_PROPERTIES.includes(e)||delete r[e]}),n[e]=r}),U(e,Hd,e=>(e.type===`Symbol`&&(e.events=e.events||{},Object.keys(n).forEach(t=>{e.events[t]=e.events[t]||{},ct(e.events[t],n[t],!1)})),e))}function fN(e,t){let n=U(e,`..panes{${Hd}}.axes`,e=>(N(t.scale)&&(e.scale=t.scale),e));n=U(n,`.display.xAxis`,e=>(N(t.horizontalAxisPosition)&&(e.position=t.horizontalAxisPosition),N(t.marginBars)&&(e.marginBars=t.marginBars),N(t.nonEodLabelWithDate)&&(e.nonEodLabelWithDate=t.nonEodLabelWithDate),N(t.ordinalName)&&(e.ordinalName=t.ordinalName),N(t.preventHorizontalLabelOverlap)&&(e.preventLabelOverlap=t.preventHorizontalLabelOverlap),e));let r=()=>I(`The 'minPadding' and 'maxPadding' are deprecated (ignored)`,`warn`),i=()=>I(`The 'preventLabelOverlap' is deprecated, please use 'preventVerticalLabelOverlap'`,`warn`);return n=U(n,`.display.yAxis`,e=>{(P(t.minPadding)||P(t.maxPadding))&&r();let n=N(t.preventLabelOverlap)&&!N(t.preventVerticalLabelOverlap);n&&i();let a=n?t.preventLabelOverlap:t.preventVerticalLabelOverlap;return N(a)&&(e.preventLabelOverlap=a),P(t.includePercentChangeWithLastValue)&&(e.includePercentChangeWithLastValue=t.includePercentChangeWithLastValue),P(t.snapAnnotationsToPrices)&&(e.snapAnnotationsToPrices=t.snapAnnotationsToPrices),P(t.primaryOnTheLeft)&&(e.primaryOnTheLeft=t.primaryOnTheLeft),e}),P(t.labels)&&Array.isArray(t.labels)&&t.labels.forEach(e=>{let{axis:t,text:r,index:i,paneIndex:a}=e;P(t,r,i)&&t===`vertical`&&Number.isInteger(i)&&(n=U(n,`..panes[${a??0}]..axes[${i}]`,e=>P(e)?(e.label=r,e):B.NULL_OBJECT))}),N(t.contractTransition)&&(n=U(n,`.display.xAxis`,e=>(lt(e.contractTransition,t.contractTransition),e))),N(t.cycleTransition)&&(n=U(n,`.display.xAxis`,e=>(lt(e.cycleTransition,t.cycleTransition),e))),n}function pN(e,t,n){let r=e;if(P(t.comparisonMode)&&typeof t.comparisonMode==`string`&&nt(x,t.comparisonMode)&&(r=U(r,`..panes{${Hd}}.axes`,e=>(e.comparison=t.comparisonMode,e))),P(t.gridLines)){let[e,n]=Qe(t.gridLines);r=U(r,`.display.xAxis.gridLines`,t=>(t.visible=e,t)),r=U(r,`.display.yAxis.gridLines`,e=>(e.visible=n,e))}if(P(t.minorGridLines)){let[,e]=Qe(t.minorGridLines);r=U(r,`.display.yAxis.minorGridLines`,t=>(t.visible=e,t))}P(t.newPaneHeight)&&typeof t.newPaneHeight==`number`&&(r=U(r,`.display.chart{.newPaneHeight > 0}`,e=>(e.newPaneHeight=t.newPaneHeight,e))),P(t.showNavigator)&&typeof t.showNavigator==`boolean`&&(r=U(r,`.display.scrollbar`,e=>(e.visible=t.showNavigator,e))),P(t.plotHover)&&typeof t.plotHover==`boolean`&&(r=U(r,`.display.chart`,e=>(e.plotHover=t.plotHover,e))),P(t.showLastValue)&&typeof t.showLastValue==`string`&&(r=U(r,`.display.yAxis`,e=>(e.showLastValue=t.showLastValue,e))),P(t.showMinMaxArc)&&typeof t.showMinMaxArc==`boolean`&&(r=U(r,`.display.chart`,e=>(e.showMinMaxArc=t.showMinMaxArc,e))),P(t.showGoToLatest)&&typeof t.showGoToLatest==`boolean`&&(r=U(r,`.display.chart`,e=>(e.showGoToLatest=t.showGoToLatest,e))),P(t.showLegend)&&typeof t.showLegend==`boolean`&&(r=U(r,`.display.chart`,e=>(e.showLegend=t.showLegend,e)),t.showLegend||n.view.removeLegend()),P(t.allAnnotationsLocked)&&typeof t.allAnnotationsLocked==`boolean`&&(r=U(r,`.display`,e=>(e.allAnnotationsLocked=t.allAnnotationsLocked,e))),N(t.hiddenItems)&&PO.includes(t.hiddenItems)&&(r=U(r,`.display`,e=>(e.hiddenItems=t.hiddenItems,e))),P(t.exprSkipLeadingEmpty)&&typeof t.exprSkipLeadingEmpty==`boolean`&&(r=U(r,`.data`,e=>(e.exprSkipLeadingEmpty=t.exprSkipLeadingEmpty,e))),typeof t.useLastTrade==`boolean`&&(r=U(r,`.data`,e=>(e.useLastTrade=t.useLastTrade,e)));let i=[];if(P(t.extendedHours)&&typeof t.extendedHours==`boolean`&&(r=U(r,`.data`,e=>(e.extendedHours=t.extendedHours,e))),P(t.realTimeCboeBzx)&&typeof t.realTimeCboeBzx==`boolean`&&(r=U(r,`.data`,e=>(e.realTimeCboeBzx!==t.realTimeCboeBzx&&i.push(`realTimeCboeBzx`),e.realTimeCboeBzx=t.realTimeCboeBzx,e))),P(t.buildContinuation)&&typeof t.buildContinuation==`boolean`&&(r=U(r,`.data`,e=>(e.buildContinuation=t.buildContinuation,e))),i.length>0){let e={chart:n.accessor,hostPropsChanged:i};n.notifyHost(K.CH_HOST_PROPS_CHANGED,e)}return r}var mN=`MARKED_FOR_DELETION`;function hN(e,t){if(t.plots.length===0)return e;let n=e;for(let e of t.plots){let t=wN(n,e);if(t===void 0)continue;let r=xN(t),i=SN(n,r);P(i)&&(P(e.type)&&i.type!==e.type||(n=U(n,r,e=>(e[mN]=!0,e))))}return n=U(n,`..plots{.${mN} === true}`,e=>B.NULL_OBJECT),n=U(n,`..plots{.type === "Study"}`,e=>{let t=V(e.study);return P(t)&&Vd(n,t,e.basis).eligible?e:B.NULL_OBJECT}),Pf(n)}function gN(e,t,n,r){let i=C[e.type],a={curves:F(e.curves),type:e.type,uid:e.uid};a.precision=e.precision,a.visible=e.visible,a.detachedScale=e.detachedScale;let o=(e,t)=>{P(e[t])?a[t]=e[t].map(e=>F(e)):a[t]=[]},s=(e,t,n=!1)=>{t.main===!0&&(e.main=!0,e.showPrevious=t.showPrevious,n&&t.events!=null&&(e.events=F(t.events)))},c=(e,t=e=>!0)=>{P(r)&&(e.subtitles=r.allPlots.filter(e=>e.type===i).filter(t).map(e=>e.title))};switch(i){case C.Symbol:{a.title=e.symbol;let t=a.curves[0].style,n=t=>{o(e,`inputs`),a.inputs.length===0&&(a.inputs=F(t))};switch(t){case`Renko`:n(B.DEFAULT_RENKO_INPUTS);break;case`Kagi`:n(B.DEFAULT_KAGI_INPUTS);break;case`PointAndFigure`:n(B.DEFAULT_PNF_INPUTS);break;case`LineBreak`:n(B.DEFAULT_LINEBREAK_INPUTS);break;case`Baseline`:n(B.DEFAULT_BASELINE_INPUTS);break}s(a,e,!0);break}case C.Study:{o(e,`inputs`);let r=V(e.study),i=a.inputs,s=e.study===`AVWAP`,c=i.length===0?``:` (${i.map(e=>s&&e.name===`Anchor`?new Date(e.value).toLocaleString():e.value).join(`, `)})`,l=a.curves.map(e=>Number(e.shift)).filter(e=>e>0),u=l.length===0?``:` [${l.join(`, `)}]`;a.title=`${r.id}${c}${u}`,a.studyId=r.id,o(e,`levels`),o(e,`bands`),a.basis=F(e.basis)||{kind:`main`},a.placement=t?n?`overlay`:`withMain`:`standalone`;break}case C.BalanceSheet:case C.IncomeStatement:{let t=G[e.curves[0].fields[0]];a.title=`${t.name} (${e.fundamental.substring(0,1)})`,a.fundamentalId=t.id,a.frequency=e.fundamental;break}case C.Expression:a.title=e.expression,s(a,e);break;case C.Forward:a.title=e.forward,o(e,`offsets`),c(a),s(a,e);break;case C.Seasonal:a.title=e.seasonal,c(a,e=>e.refSeasonal===a.title),o(e,`offsets`),s(a,e);break;default:throw Error(`Unexpected plot type`)}return a}function _N(e,{main:t,type:n,index:r,uid:i},a){let o=`..plots{.main === true}`,s=H(e,`..panes`).map((e,t)=>{let n=H(e,o).length===1;return H(e,`..axes`).map((e,r)=>{let i=H(e,o).length===1;return H(e,`..plots`).map(e=>{let o=gN(e,n,i,a);return o.paneIndex=t,o.axisIndex=r,o})})}).flat(2).map((e,t)=>(e.index=t,e));if(P(i))return s.filter(e=>e.uid===i);if(t)return s.filter(e=>e.main);if(P(n)){let e=s.filter(e=>e.type===n);return P(r)?e.filter(e=>e.index===r):e}else return s}var vN=[`overlay`,`standalone`,`withMain`,`clone`];function yN(e,t,n){t[n]&&(e[n]=t[n])}function bN(e,t){e.type===`Study`&&t.curves?.forEach(e=>delete e.varyColorPerBar),EN(e)?P(t.curves)&&(e.curves=t.curves):jN(e.curves,t.curves);let n=C[t.type],r=e;if(P(t.precision)?r.precision=t.precision:delete r.precision,n===C.Symbol)P(t.symbol)&&(e.symbol=t.symbol);else if(n===C.Study)P(t.basis)&&(e.basis=F(t.basis)),MN(e.inputs,t.inputs,e),[`bands`,`levels`,`detachedScale`].forEach(n=>yN(e,t,n));else if((n===C.BalanceSheet||n===C.IncomeStatement)&&t.frequency)e.fundamental=t.frequency;else if(n===C.Expression){let n=e;P(t.expression)&&(n.expression=t.expression)}else if(n===C.Forward){let n=e;P(t.offsets)&&(n.offsets=t.offsets),P(t.forward)&&(n.forward=t.forward)}else if(n===C.Seasonal){let n=e;P(t.offsets)&&(n.offsets=t.offsets),P(t.seasonal)&&(n.seasonal=t.seasonal),P(t.usesInAverage)&&(r.usesInAverage=t.usesInAverage),cu(n)}}var xN=e=>`..plots[${e}]`;function SN(e,t){let n=H(e,t);return n.length===1?n[0]:null}function CN(e,t){let n=0;for(let r of e.panes)for(let e of r.axes)for(let r of e.plots){if(r.uid===t)return n;n+=1}}function wN(e,t){return P(t.uid)?CN(e,t.uid):t.index}function TN(e){let t=C[e.type];return t===C.Symbol||t===C.Expression}function EN(e){let t=C[e.type];return t===C.Forward||t===C.Seasonal}function DN(e){let t=C[e.type];return t===C.Symbol||t===C.Expression||t===C.Seasonal}function ON(e,t,n){if(P(t))return t;let r=n?.uid;return typeof r==`string`?CN(e,r):void 0}function kN(e,t,n){if(P(t.placement)&&!vN.includes(t.placement))throw Error(`Unknown placement: ${t.placement}`);let r=wN(e,t),i=r===void 0?t.main?Hd:``:xN(r);if(!i)return e;let a=SN(e,i);if(!N(a)||N(t.type)&&a.type!==t.type)return e;let o=ON(e,r,a);if(t.type===C[C.Study]){let n=a,r=V(t.studyId??n.study);if(!N(r))return e;let i=P(t.basis)?t.basis:n.basis,o=Vd(e,r,i);if(!o.eligible)return I(`Cannot update study "${r.meta.title}" because ${o.reason}.`,`error`),e}if(N(t.visible))return a.visible=t.visible,e;if(a.main&&TN(a)){if(t.curves){let n=e=>e.curves[0].style===h[h.Range],[r,i]=[n(a),n(t)];r&&!i?e=tf(e,{unit:`Day`,size:1,spec:`None`}):!r&&i&&(e=tf(e,{unit:`Intraday`,size:100,spec:`PerRange`}))}t.type||=a.type;let n=a;P(t.precision)?n.precision=t.precision:delete n.precision,P(t.showPrevious)&&(e=U(e,Hd,e=>(e.showPrevious=t.showPrevious,e)));let r=t.curves?td(e,t):e;return P(t.oppositeScale)&&DN(a)&&P(o)&&(r=Ld(r,o,+!!t.oppositeScale)),r}else{let s=U(e,i,e=>(bN(e,t),e));if(P(t.oppositeScale)&&DN(a)&&P(o)&&(s=Ld(s,o,+!!t.oppositeScale)),!(t.type===C[C.Study]&&P(t.placement)))return s;let c=P(r)?r:t.index,l=_N(s,{...t,index:c},n).find(e=>e.index===c);if(!P(l))return e;if(t.placement===l.placement)return s;let u=SN(s,i);if(!P(u))return e;s=hN(s,{id:`Delete`,plots:[{uid:u.uid,type:t.type}]});let d=LN(s,t.placement,t.cloneIndex,t.cloneUid);return d!==null&&d.plots.push(u),s}}function AN(e){return e!==void 0}function jN(e,t){if(AN(t)&&t.length===e.length)for(let n=0;n<e.length;++n){let r=t[n],i=e[n];lt(i,r);for(let e of[`shift`,`dashStyle`,`lineSmoothing`,`lineMarker`]){let t=r[e];P(t)&&(i[e]=t)}}}function MN(e,t,n){let r=dt(e),i=dt(t);lt(r,i);let a=ft(i);a.length>0&&(n.inputs=a)}function NN(){return{plots:[]}}function PN(e){let t=e.display.chart.newPaneHeight??1;return{axes:[NN()],height:t}}function FN(e){let t=PN(e);return e.panes.push(t),t}function IN(e,t){let n=N(t.paneIndex)&&t.paneIndex<e.panes.length?e.panes[t.paneIndex]:FN(e),r=n.axes[0];return t.oppositeScale??!1?rP(n,r):r}function LN(e,t,n,r,i){let a=null,{mainPane:o,mainAxis:s}=Wd(e),c=(()=>{if(i?.kind!==`seasonal`)return null;for(let t of e.panes)for(let e of t.axes)for(let n of e.plots){if(n.uid!==i.uid||n.type!==`Seasonal`)continue;let r=n.offsets;if(Array.isArray(r)&&r.includes(i.offset))return{pane:t,axis:e}}return null})();switch(t){case`withMain`:a=c?rP(c.pane,c.axis):rP(o,s);break;case`overlay`:a=c?.axis??s;break;case`standalone`:a=FN(e).axes[0];break;case`clone`:{let t={main:!1,type:C[C.Study]};if(typeof r==`string`&&r.length>0?t.uid=r:typeof n==`number`&&(t.index=n),t.uid||typeof t.index==`number`){let n=_N(e,t).find(e=>e.type===C[C.Study]&&(t.uid?e.uid===t.uid:e.index===t.index));if(!n)break;a=H(e,`..panes[${n.paneIndex}]..axes[${n.axisIndex}]`)[0]}break}}return a}function RN(e,t){let n=V(t.studyId);if(!N(n))return I(`Unknown or unavailable study with the id '${t.studyId}'`,`error`),e;let r=Vd(e,n,t.basis);if(!r.eligible)return I(`Cannot add study "${n.meta.title}" because ${r.reason}.`,`error`),e;let i=t.placement||(n.meta.overlay?`overlay`:`standalone`),a=t.uid??bt();P(t.uid)&&Md(e,a);let o={uid:a,type:`Study`,study:t.studyId,visible:!0};i===`overlay`&&t.studyId===`VOL`&&(o.detachedScale=!0),t.curves!==void 0&&(o.curves=n.defaults.curves),bN(o,t);let s=LN(e,i,t.cloneIndex,t.cloneUid,t.basis);P(s)&&s.plots.push(o);let c=e.data.aggregation;return ef(e,c.unit===`Tick`&&c.spec===`None`)}function zN(e,t){e.panes.push({axes:[{plots:[t]}]})}function BN(e,t){let n=Ud(e);if(n.type!==C[C.Symbol])throw Error(`Cannot add fundamental to the chart whose main plot is not a Symbol plot.`);let r=n.symbol,i=t.uid??bt();P(t.uid)&&Md(e,i);let a={uid:i,curves:[{fields:[t.fundamentalId],lineWidth:2,style:`Line`,varyColorPerBar:!1,visible:!0,colors:[`#888`]}],fundamental:`Quarter`,symbol:r,type:b[G[t.fundamentalId].category],visible:!0};return bN(a,t),zN(e,a),e}var VN=[{fields:[G.Close.id],colors:[`#888`],style:`Line`,lineWidth:2,varyColorPerBar:!1,visible:!0}];function HN(e){return e.type===`Symbol`}function UN(e,t){let n=Ud(e),r=F(HN(n)?n.curves:VN),i=t.uid??bt();P(t.uid)&&Md(e,i);let a={uid:i,curves:r,expression:``,type:`Expression`,visible:!0};return bN(a,t),IN(e,t).plots.push(a),e}function WN(e,t){let n=t.uid??bt();P(t.uid)&&Md(e,n);let r={uid:n,curves:F(VN),offsets:[0],seasonal:``,type:`Seasonal`,visible:!0,main:!1};return bN(r,t),IN(e,t).plots.push(r),e}var GN={attributes:[`OpenVsClose`],colors:[`#b63400`,`#007f3e`,`#1664db`],fields:[`Open`,`High`,`Low`,`Close`,`Change`],style:`Candlestick`,varyColorPerBar:!0,lineWidth:1};function KN(e,t){let n=Ud(e),r=$().getDefaultMultiFieldCurve(),i=P(r)?r:GN,a=n.curves?.length,o=a===t.curves.length&&a===1?(e=>F(e?n.curves:[i]))(HN(n)):t.curves,s=t.uid??bt();P(t.uid)&&Md(e,s);let c={uid:s,curves:o,symbol:``,type:`Symbol`,visible:!0};return bN(c,t),IN(e,t).plots.push(c),e}function qN(e,t){switch(t.type){case`Study`:return RN(e,t);case`IncomeStatement`:case`BalanceSheet`:return BN(e,t);case`Expression`:return UN(e,t);case`Symbol`:return KN(e,t);case`Seasonal`:return WN(e,t);default:throw Error("Unexpected plot type '${type}', not supported currently")}}var JN=0,YN=B.AUTO_COLORS,XN=`Symbol`,ZN=`Expression`,QN=`Seasonal`;function $N(e,t){let n={attributes:[],colors:YN.slice(JN,JN+1),fields:e?[G.Last.id]:[G.Close.id],style:`Line`,dashStyle:`Solid`,varyColorPerBar:!1,lineWidth:2,lineMarker:void 0,lineSmoothing:void 0},r={uid:t.uid??bt(),curves:[n]},{curves:i,oppositeScale:a,...o}=t;return ut(r,o),N(i)&&(r.curves=i.map(e=>{let t=F(e);return ut(t,n),t})),r.main=!1,JN=(JN+1)%YN.length,r}function eP(e){return P(e.symbols)&&(I(`Use of 'symbols' for Compare API is deprecated. Please see docs for the latest version which supports more plot types`,`warn`),e.plots=e.symbols.map(e=>(e.type=XN,e))),e.plots?.some(e=>P(e.leftScale))?(I(`Use of 'leftScale' for Compare API is deprecated. Please use 'oppositeScale'`,`warn`),e.plots.map(e=>{let t=e.leftScale;return delete e.leftScale,{...e,oppositeScale:t}})):e.plots}function tP(e,t){let n=eP(t),r=n.map(e=>e.uid).filter(e=>typeof e==`string`),i=new Set;for(let t of r){if(i.has(t))throw Error(`Plot uid '${t}' is duplicated in the Compare request.`);i.add(t),Md(e,t)}let{yes:a,no:o}=k(n,e=>e.oppositeScale??!1),{mainPane:s,mainAxis:c}=Wd(e);s.alignOnExpirations=t.alignOnExpirations||!1;let l=rP(s,c),u=e=>![XN,ZN,QN].includes(e.type);l.plots=l.plots.filter(u);let d=c.plots.filter(e=>e.main||u(e)),f=e.data.aggregation.unit===`Tick`;JN=0;let p=se($N,f);return c.plots=d.concat(o.map(p)),a.length>0&&(l.plots.push(...a.map(p)),l.comparison=c.comparison,l.scale=c.scale),Pf(e)}var nP=`..plots{(.type === "Symbol" || .type === "Expression" || .type === "Seasonal") && .main !== true}`;function rP(e,t){let n=e.axes.find(e=>e!==t);return P(n)||(n=NN(),e.axes.push(n)),n}function iP(e,t){let n=H(e,nP),r=H(t,nP),i=Math.max(0,4-r.length);if(i===0)return t;let a=n.filter(e=>!r.find(t=>e.symbol===t.symbol)).slice(0,i);if(a.length===0)return t;let{mainPane:o,mainAxis:s}=Wd(t),{mainAxis:c}=Wd(e);return a.forEach(e=>{c.plots.includes(e)?s.plots.push(e):rP(o,s).plots.push(e)}),t}function aP(e,t){let n=e.panes;return n.splice(t.to,0,n.splice(t.from,1)[0]),e}var oP=()=>B.NULL_OBJECT;function sP(e){return U(e,`..axes.annotations`,oP)}function cP(e){return Pf(U(e,`..plots{.type === "Symbol" && .main !== true}`,oP))}function lP(e,t){let n=F(e);if(t.strip.main){let e=Ud(n),t=e.type.toLowerCase();e[t]=B.PLACEHOLDER_SYMBOL_NAME}return t.strip.annotations&&(n=sP(n)),t.strip.compare&&(n=cP(n)),n=U(n,`.data`,e=>(e.range&&(delete e.range,e.checkRange=!0),e)),n}function uP(e,t,n){let r=_N(e,{main:!0},n)[0],i=r.title===B.PLACEHOLDER_SYMBOL_NAME,a=r.type===`Symbol`,o=r.type===`Expression`,s=bd(r.title),c=[];return o&&!yd(s)?c=s.symbols:i||(c=[r.title]),{isTemplate:i,isDefinition:!i,main:{isSymbol:a,isExpression:o,symbols:c,title:i?null:r.title},compare:H(e,nP).map(e=>e.symbol),annotations:H(e,`..annotations`).map(e=>e.id),studies:_N(e,{type:`Study`},n).map(e=>e.title)}}function dP(e,t,n){let r=H(e,`..panes`).map((e,t)=>H(e,`..axes`).map((e,n)=>H(e,`.annotations`).map(e=>({...e,paneIndex:t,axisIndex:n})))).flat(2).map((e,t)=>({...e,index:t}));return P(t.index)&&Number.isFinite(t.index)?t.index<r.length?[r[t.index]]:B.EMPTY_ARRAY:r}function fP(e,t){let n=pP(t.annotation),{mainAxis:r}=Wd(e);return r.annotations??=[],r.annotations.some(e=>e.uid===n.uid)||r.annotations.push(n),e}function pP(e){let t={id:e.id,uid:e.uid,points:(e.points??[]).map(e=>({price:e.price,time:e.time}))};return e.traits!==void 0&&(t.traits=F(e.traits)),e.visible!==void 0&&(t.visible=e.visible),e.locked!==void 0&&(t.locked=e.locked),t}function mP(e,t){let n=H(e,`..axes`);for(let e of n){let n=e.annotations?.find(e=>e.uid===t.uid);if(n){t.traits!==void 0&&(n.traits=F(t.traits)),t.points!==void 0&&(n.points=t.points.map(e=>({price:e.price,time:e.time}))),t.visible!==void 0&&(n.visible=t.visible),t.locked!==void 0&&(n.locked=t.locked);break}}return e}function hP(e,t){let n=H(e,`..axes`);for(let e of n)if(e.annotations?.some(e=>e.uid===t.uid)){e.annotations=e.annotations.filter(e=>e.uid!==t.uid);break}return e}function gP(e,t,n){let r=H(e,`..panes{${Hd}}.axes.comparison`)[0],i=e.display,a=(e,t)=>rt(e,!1,t,`visible`),o=e=>$e(a(i.xAxis,e),a(i.yAxis,e)),s=rt(i.chart,!0,`showLegend`);return{comparison:r,gridLines:o(`gridLines`),minorGridLines:o(`minorGridLines`),newPaneHeight:i.chart.newPaneHeight,showLastValue:i.yAxis.showLastValue,showLegend:s,showMinMaxArc:i.chart.showMinMaxArc,allAnnotationsLocked:i.allAnnotationsLocked,hiddenItems:IO(i),exprSkipLeadingEmpty:e.data?.exprSkipLeadingEmpty??!1,useLastTrade:e.data?.useLastTrade??!1,extendedHours:e.data?.extendedHours??!1,realTimeCboeBzx:e.data?.realTimeCboeBzx??!1,buildContinuation:e.data?.buildContinuation??!1}}function _P(e,t){let n=e,{backgroundColor:r,axis:{gridLinesColor:i,textColor:a,crosshairColor:o,gridLinesStyle:s},fontSize:c}=t,{chart:l,xAxis:u,yAxis:d}=c||{};if((r||l)&&(n=U(e,`.display.chart`,e=>(r&&(e.backgroundColor=r),l&&(e.fontSize=l),e))),i){let e=e=>(e.color=i,e);n=U(n,`.display.xAxis.gridLines`,e),n=U(n,`.display.yAxis.gridLines`,e),n=U(n,`.display.yAxis.minorGridLines`,e)}if(s){let e=e=>(e.dashStyle=s,e);n=U(n,`.display.xAxis.gridLines`,e),n=U(n,`.display.yAxis.gridLines`,e),n=U(n,`.display.yAxis.minorGridLines`,e)}if(a){let e=e=>(e.textColor=a,e);n=U(n,`.display.xAxis`,e),n=U(n,`.display.yAxis`,e)}if(o){let e=e=>(e.color=o,e);n=U(n,`.display.xAxis.crosshair`,e),n=U(n,`.display.yAxis.crosshair`,e)}if(u||d){let e=e=>t=>(t.fontSize=e,t);u&&(n=U(n,`.display.xAxis`,e(u))),d&&(n=U(n,`.display.yAxis`,e(d)))}return n}function vP(e,t,n){let{chart:r,xAxis:i,yAxis:a}=e.display||{},{fontSize:o,backgroundColor:s}=r||{},{fontSize:c,gridLines:l,textColor:u,crosshair:d}=i||{},{color:f,dashStyle:p}=l||{},{fontSize:m}=a||{},{color:h}=d||{};return{backgroundColor:s,axis:{gridLinesColor:f,textColor:u,crosshairColor:h,gridLinesStyle:p},fontSize:{chart:o,xAxis:c,yAxis:m}}}function yP(e,t,n){let{mainAxis:r}=Wd(e),i=H(e,`.display.xAxis`)[0],a=H(e,`.display.yAxis`)[0];return{scale:r.scale,marginBars:i.marginBars??0,horizontalAxisPosition:i.position??`bottom`,preventLabelOverlap:a.preventLabelOverlap,preventVerticalLabelOverlap:a.preventLabelOverlap,preventHorizontalLabelOverlap:i.preventLabelOverlap,snapAnnotationsToPrices:a.snapAnnotationsToPrices,primaryOnTheLeft:a.primaryOnTheLeft??!1,nonEodLabelWithDate:i.nonEodLabelWithDate??!1,includePercentChangeWithLastValue:a.includePercentChangeWithLastValue??!1,ordinalName:i.ordinalName??``,contractTransition:i.contractTransition,cycleTransition:i.cycleTransition}}function bP(e,t,n){let r=t=>H(e,t)[0],i=r(`.display.chart`),a=r(`.display.xAxis.crosshair`),o=r(`.display.yAxis.crosshair`),s=`none`;return a.enabled&&o.enabled?s=`both`:a.enabled?s=`vertical`:o.enabled&&(s=`horizontal`),{crosshair:s,horizontal:{color:o.color,dashStyle:o.dashStyle},vertical:{color:a.color,dashStyle:a.dashStyle},haloTracking:i.plotHover}}function xP(e,t,n){return F(e.data.aggregation)}function SP(e,t){let n=H(e,nP),{mainPane:r,mainAxis:i}=Wd(e),a=[];for(let e of n){let t=!i.plots.includes(e),n=e.type.toLowerCase(),r={curves:F(e.curves),type:e.type,[n]:e[n],oppositeScale:t,leftScale:t};a.push(r)}return{plots:a,alignOnExpirations:r.alignOnExpirations}}function CP(e,t,n){let{paneIndex:r,annotations:i,studies:a}=t||{},o=`..panes${Number.isInteger(r)?`[${r}]`:``}`,s=e,c=e=>B.NULL_OBJECT;return i===!0&&(n.allAnnotations.forEach(e=>n.onAnnotationModifiedByTool(e,O.Deleted,!1)),s=U(s,`${o}..annotations`,c)),a===!0&&(s=U(s,`${o}..plots{.type=="Study"}`,c)),s=Pf(s),s}var wP=`.display.chart.previous`;function TP(e,t,n){return H(e,wP)[0]}function EP(e,t,n){return U(e,wP,e=>(lt(e,t),e))}function DP(e,t,n){let r=[],i=wN(e,t);if(i===void 0||SN(e,xN(i))?.type!==t.type)return r;let a=Pd(e,i);if(a===null)return r;let o=a.pane,s=o===0,c=o===e.panes.length-1,l=e.panes[o].axes.reduce((e,t)=>e+t.plots.length,0)===1;return s||r.push(`ExistingAbove`),l||r.push(`NewAbove`),c||r.push(`ExistingBelow`),l||r.push(`NewBelow`),r}function OP(e,t,n){if(!DP(e,t,n).includes(t.targetPane))return e;let r=wN(e,t);if(r===void 0)return e;let i=Pd(e,r);if(i===null)return e;let a=SN(e,xN(r));e.panes[i.pane].axes[i.axis].plots.splice(i.plot,1);let o=i.pane,s=!0;switch(t.targetPane){case`ExistingAbove`:o--;break;case`NewAbove`:e.panes.splice(o,0,PN(e)),s=!1;break;case`ExistingBelow`:o++;break;case`NewBelow`:o++,s=!1,e.panes.splice(o,0,PN(e));break}let{mainPane:c}=Wd(e),l=e.panes[o]===c;s&&l&&a?.type===`Study`&&a.study===`VOL`&&(a.detachedScale=!0);let u=e.panes[o];u.axes.length<2&&u.axes[0].plots.length>0&&u.axes.push(NN());let d=u.axes.findIndex(e=>e.plots.length===0),f=d===-1?u.axes.length-1:d;u.axes[f].plots.push(a);let p=Id(e,i.pane);return p=Id(p,o),Pf(p)}function kP(e,t,n){return P(t.period)&&t.period&&(delete e.display.period,$d(e),n&&(n.forceResetVisibleRange=!0)),e}function AP(e,t,n){let r=[],i=wN(e,t);if(i===void 0)return r;let a=SN(e,xN(i));if(a?.type!==t.type)return r;let o=Pd(e,i);if(o===null)return r;let s=e.panes[o.pane],c=o.axis===0,l=s.axes.some((e,t)=>e.plots.some((e,n)=>!(t===o.axis&&n===o.plot)&&!e.detachedScale)),u=a.detachedScale===!0;return(c||u)&&r.push(`SecondaryAxis`),(!c||u)&&r.push(`PrimaryAxis`),l&&r.push(`NoAxis`),r}function jP(e,t,n){if(!AP(e,t,n).includes(t.targetAxis))return e;let r=wN(e,t);if(r===void 0)return e;let i=-1;switch(t.targetAxis){case`PrimaryAxis`:i=0;break;case`SecondaryAxis`:i=1;break;case`NoAxis`:return Rd(e,r)}return Ld(e,r,i)}function MP(e,t,n){let r=H(e,`.display.tooltip`)[0];return{visible:r.visible,mode:r.mode,showMainTitle:r.showMainTitle,mainTitle:r.mainTitle}}var NP=`..plots{.type === "Seasonal" && .main === true}`,PP=`..plots{.type === "Seasonal" && .main !== true}`,FP=B.AUTO_COLORS;function IP(e){return JSON.parse(JSON.stringify(e))}function LP(e,t){let n=H(e,NP);if(n.length===0)return e;let r=n[0];if(!r.offsets||r.offsets.length===0)return e;let i=r.offsets,a=H(e,PP);for(let e of a){let t=e.offsets??[],n=e.curves??[],r=new Map;t.length===n.length?t.forEach((e,t)=>{let i=n[t];i&&r.set(e,IP(i))}):n.forEach((e,t)=>{let n=i[t];e&&P(n)&&r.set(n,IP(e))});let a=r.get(0);a?.colors?.[0];let o=i.map((e,t)=>{let n=r.get(e);if(n)return n;let i=FP[t%FP.length];return{...a?IP(a):{},colors:[i],fields:[`Close`],style:`Line`,dashStyle:`Solid`,varyColorPerBar:!1,lineWidth:2}});e.offsets=[...i],e.curves=o}return Pf(e)}var RP={MainPlot:Qd,Aggregation:{Update:tf,Get:xP},Period:{Update:Ku,Delete:kP},Crosshair:{Update:lN,Get:bP},Tooltip:{Update:uN,Get:MP},Events:dN,Scale:{Update:fN,Get:yP},Other:{Update:pN,Get:gP},Plot:{Add:qN,Get:_N,Delete:hN,Update:kN},Compare:{Update:tP,Get:SP},AnnotationManipulation:{Get:oN,Update:cN},Annotation:{Get:dP,Add:fP,Update:mP,Delete:hP},MovePane:aP,Template:lP,Outline:uP,Theme:{Update:_P,Get:vP},Clear:CP,Previous:{Update:EP,Get:TP},MovePlot:{Update:OP,Get:DP},PinPlot:{Update:jP,Get:AP},SeasonalOffsets:{Update:LP}};function zP(e){return typeof e==`function`}function BP(e,t){let n=RP[e];if(zP(n))return n;{let e=t===void 0?void 0:n[t];if(!zP(e)&&(e=n[B.DEFAULT_ACCESSOR_SUBACTION],!zP(e)))throw Error(`Invalid accesor id and/or sub id`);return e}}function VP(e,t,n){return BP(e.id,e.context.id)(t,e.context,n)}function HP(e){return{id:`MainPlot`,context:e}}var UP={id:`SeasonalOffsets`,context:{}};function WP(e){return Array.isArray(e)&&e.some(e=>e?.type===`Seasonal`)}function GP(e){let{id:t,context:n}=e;if(!P(n))return!1;if(t===`Compare`)return WP(n.plots);if(t!==B.ACTION_PLOT)return!1;let r=n.id;return r===`Add`||r===`Update`?n.type===`Seasonal`:r===B.ACTION_DELETE?WP(n.plots):!1}function KP(e){return e.some(GP)?e[e.length-1]?.id!==`SeasonalOffsets`:!1}var qP={keepOldAnnotations:!1,keepNewAnnotations:!0,keepOldCompare:!1,keepNewCompare:!0,keepOldAggregation:!1,keepNewBarWidth:!1},JP=Symbol.for(`__ias__`),YP=class{headless;presenter;_model;constructor(e=!1){this.headless=e,this.presenter=e?null:new eN(this)}get elementId(){return this.headless?null:this.presenter?.elementId??null}get hostElement(){return this.headless?null:this.presenter?.hostElement??null}initialize(e,t=null){if(this.headless){I(`You cannot initialize a headless chart.`,`error`);return}if(this.presenter.initialize(e),N(t)){let e=typeof t==`string`;e?I(`Initializing the chart with symbol name is deprecated. Please use object form instead (see docs for details). This API will be removed in the future.`,`warn`):(t.template&&this.load(t.template),delete t.template);let n=e?{symbol:t}:t;this.change(HP(n))}}shutdown(){if(!this.headless){let e=this.presenter?.shutdown();return this.presenter=null,e}return!1}annotate(e,t=null,n=null){if(!this.headless)if(P(e)){Dl(e,t),El(e,t);let r=Cj(e,!1,t,n,this.presenter);r.isDrawingAnnotation&&this.presenter.view.setCursor(ee.Crosshair),this.presenter.activeTool=r,Ie()||this.presenter.view.mouseCanvas.focus({preventScroll:!0})}else this.presenter.resetActiveTool()}cancelAnnotation(){this.headless||this.presenter.resetActiveTool()}setMainAxisAnnotations(e){let t=this.presenter?.mainAxis;P(t)&&(t.annotations=e.map(e=>t.makeAnnotation(e)),t.fireAnnotationsChanged(),this.presenter.view?.redraw())}toMainAxisPoint(e){let t=this.presenter?.mainAxis;if(!P(t))return null;let n=t.toAnnotationPoint(e);return{price:n.price,time:n.time}}fromMainAxisPoint(e){let t=this.presenter?.mainAxis;if(!P(t))return null;let n=t.toX(new Date(e.time)),r=t.toY(e.price);return!P(n)||!P(r)?null:{x:n,y:r}}zoom(e){!this.headless&&typeof e==`boolean`&&(e?this.annotate(`ZoomIn`):this.presenter.defaultTool.resetView(this.presenter))}getDefaultTemplate(){return bF()}get model(){return(this.headless?this._model:this.presenter.getModel())||bF()}asTemplate(e={main:!0,annotations:!1,compare:!1}){return this.change({id:B.ACTION_TEMPLATE,context:{strip:e}})}change(...e){if(e.length>1&&e.some(e=>e.id===`AnnotationManipulation`))throw Error(`AnnotationManipulation must be executed as a standalone action`);let t={chart:this,actions:e.filter(e=>!e[JP])};t.actions.length>0&&this.presenter?.notifyHost(K.CH_API_ACTIONS_RECEIVED,t);let n=$().config.validateInput,r=e.map(e=>n?Nf(e,B.ACCESSOR_SCHEMA):e);if(r.length===1){let e=r[0];if(e.id===B.ACTION_TEMPLATE||e.context.id===B.ACTION_GET)return VP(e,this.model,this.presenter);if(!this.headless&&e.id===`AnnotationManipulation`){VP(e,this.model,this.presenter);return}else if(!this.headless&&e.id===B.ANN_ACTION_ID)return this.presenter.handleAnnotationChange(e.context)}let{yes:i,no:a}=k(r,e=>e.id===B.ACTION_PLOT&&P(e.context)&&e.context.id===B.ACTION_DELETE),o=F(this.model),s=F(this.model),c=a;i.length>0&&c.push({id:B.ACTION_PLOT,context:{id:B.ACTION_DELETE,plots:i.map(e=>e.context)}}),c.forEach(e=>{if(s=VP(e,s,this.presenter),!P(s))throw Error(`Forgot to return model from accessor`)}),KP(c)&&(s=VP(UP,s,this.presenter)),this.fromModel(s,o)}async fromModel(e,t){let n=Nf(e,B.CHART_SCHEMA);this.headless?this._model=n:await this.presenter?.fromModel(n,t)}async load(e,t){let n={...qP,...t},r=Nf(JSON.parse(e),B.CHART_SCHEMA),i=this.model,a=F(i);if(P(i)){if(r=Gd(i,r,n.keepNewAnnotations),n.keepNewAnnotations||(r=sP(r)),n.keepOldAnnotations&&(r=kM(i,r)),n.keepNewCompare||(r=cP(r)),n.keepOldCompare&&(r=iP(i,r)),n.keepOldAggregation){let e={id:B.ACTION_AGGREGATION,context:i.data.aggregation},t=r.display.density;r=VP(e,r,this.presenter),n.keepNewBarWidth&&P(t)&&(r.display.density=t)}await this.fromModel(r,a),this.clearUndoRedo()}}save(){return JSON.stringify(this.model)}clearUndoRedo(){!this.headless&&this.presenter?.undoRedoManager&&this.presenter.undoRedoManager.clear(!0)}reset(e=!0){let t=bF();if(this.headless)this._model=t;else if(this.presenter.getModel()){let n=this.presenter.mainPlot,r=null,i=n;if(n.isSymbol?r={symbol:i.symbol}:n.isExpression?r={expression:i.expression}:n.isForward?r={forward:i.forward}:n.isSeasonal&&(r={seasonal:i.seasonal}),P(r)){let n=VP({id:`Theme`,context:{id:`Get`}},this.model,this.presenter),i=VP(HP(r),t,this.presenter);e&&(i=VP({id:`Theme`,context:n},i,this.presenter)),this.presenter?.fromModel(i)}}this.clearUndoRedo(),this.presenter?.notifyHost(K.CH_RESET,{elementId:this.elementId})}print(e={}){this.headless||this.presenter.print(e)}getSVGForExport(){I(`Obsolete: please use 'exportImage' method instead.`,`warn`)}setTitle(e){this.headless||this.presenter.setTitle(e)}getPaneBounds(e=!0){if(!this.headless)return this.presenter.panes.map(t=>e?t.getBounds():t.getBoundsWithoutScales())}exportData(e={}){return this.headless?null:XM.call(this.presenter,e)}exportTable(e={}){return this.headless?null:GM.call(this.presenter,e)}exportImage(e={}){return this.headless?null:ZM.call(this.presenter,e)}getDataStats(){return this.presenter.getDataStats()}get canUndo(){return!this.headless&&(this.presenter?.undoRedoManager?.canUndo??!1)}get canRedo(){return!this.headless&&(this.presenter?.undoRedoManager?.canRedo??!1)}undo(){this.canUndo&&this.presenter?.undoRedoManager?.undo()}redo(){this.canRedo&&this.presenter?.undoRedoManager?.redo()}pauseUndoRedo(){this.headless||this.presenter?.undoRedoManager?.pause()}resumeUndoRedo(e){this.headless||this.presenter?.undoRedoManager?.resume(e)}priceToY(e,t=0,n=0){let r=this.presenter;if(this.headless||t<0||n<0||t>r.panes.length)return null;let i=r.panes[t];return n>i.axes.length?null:i.axes[n].toY(e)}yToPrices(e){let t=this.presenter;if(this.headless)return null;for(let[n,r]of t.panes.entries()){let t=r.getBounds();if(P(t)&&e>=t.y&&e<=t.y+t.height)return{pane:n,prices:r.axes.map(t=>t.toPrice(e))}}return{pane:-1,prices:[]}}activate(){this.presenter?.notifyHost(K.CH_DIDBECOMEACTIVE,{chart:this})}};function XP(e){let t=e.split(`.`);if(!t||t.length!==4)return!1;let n=t.map(Number);if(!n.every(e=>Number.isFinite(e)&&e>=0&&e<=255))return!1;let[r,i]=n;return r===10||r===172&&i>=16&&i<=31||r===192&&i===168}function ZP(){let e=globalThis.parent?.location?.hostname||``;return[``,`localhost`,`127.0.0.1`].includes(e)||XP(e)}function QP(){let e=document.domain,t=e.split(`.`),n=`__tld`+new Date().getTime(),r=0;for(;r<t.length-1&&document.cookie.indexOf(`${n}=${n}`)===-1;)e=t.slice(-1-++r).join(`.`),document.cookie=`${n}=${n};domain=${e};`;return document.cookie=`${n}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain=${e};`,e}function $P(e,t){return ot(t),`${e}/?${new URLSearchParams(t).toString()}`}var eF=`aHR0cHM6Ly9iYXJjaGFydHdpZGdldHMud2Vic29sLmJhcmNoYXJ0LmNvbQ==`,tF=`YXV0aGVudGljYXRlQ2hhcnRSZWZlcmVy`;function nF(e,t=``){return $P(atob(eF),{module:atob(tF),secret:t,referer:e})}function rF(e,t){return e+Math.random()*(t-e)}var iF=Function(atob(`Y29uc29sZS5sb2coIlBsZWFzZSBjb250YWN0IEJhcmNoYXJ0IGluIG9yZGVyIHRvIG9idGFpbiB0aGUgbGljZW5zZSBmb3IgdGhlIGNoYXJ0IGNvbXBvbmVudC4iKTsg`)),aF=Function(`f`,atob(`Zi5yZW1vdmVBbGxDaGFydHMoKTsg`)),oF=Function(`m`,atob(`cmV0dXJuIG0gPT09ICJJbnRlcm5hbEZlZWQiIHx8IG0gPT09ICJXaWRnZXQiIHx8IG0gPT09ICJGcmVlV2lkZ2V0IiB8fCBtID09PSAiRGVtb1NpdGUiIHx8IG0gPT09ICJFcVBsdXMiOw==`)),sF=`YXV0aG9yaXplZA==`,cF=`ZGF0YS1lbmRwb2ludA==`,lF=`YWxsb3dDcmVkZW50aWFscw==`;async function uF(e,t){if(t&&!oF(e.mode))return;let n=!1,r=0,i=25;for(;!n&&r<5;){let t=ZP()||e.mode===`FreeWidget`,a=t?e.apiKey:``;try{let i=nF(t?``:QP(),a),o=await fetch(i);if(!o.ok)r++;else{let t=await o.json(),r=t[atob(sF)];e.knownSite=r,r?(e.dataEndpoint=(t[atob(cF)]||``).replace(/\/$/g,``),e.allowCredentials=t[atob(lF)]):(e.dataEndpoint=``,e.allowCredentials=!1),n=!0;break}}catch{}r++,i*=2,await new Promise(e=>setTimeout(e,i))}(!n||!e.knownSite)&&dF()}function dF(){setTimeout(iF,rF(2e3,3e3)),setTimeout(()=>aF($()),rF(4e3,5e3))}var fF={major:2,minor:405,patch:1,prerelease:!1},pF={environment:`Browser`,validateInput:!1,throttleMillis:0,isAlt64:!0,defaultTemplate:`/${B.CHART_DEFINITION}`,cachedAnnotationsCount:0,showResizeHandles:!1,scrollBehavior:`wheel+shift`,bypassSmoothing:!1,showGoToLatest:void 0,tooltipMovement:`Auto`,tooltipHeaders:void 0,touchCrosshairTimeoutMillis:void 0,touchCrosshairDelayMillis:void 0,mode:`Unspecified`,hostingModel:`Page`,overrides:void 0,logo:void 0,logoClickable:void 0,noDataText:void 0,useAllFieldsForComparison:void 0,colorfulAnnotations:!1,annotationManipulation:void 0,baseUrl:{instruments:`/proxies/instruments`,futures:`/proxies/futures`,extras:`/extras`,timeseries:`/proxies/timeseries`,timeseriesNew:`/proxies/new-timeseries`,ondemand:`/proxies/ondemand`,options:`/proxies/core-api`},credentials:void 0,apiKey:void 0,extensions:void 0,defaultVolumeBarColoring:void 0,defaultMainPlotBarColoring:void 0,async fetch(e,t){let n=this.baseUrl[e],r=`${n}${t}`;if(oF(this.mode)&&this.knownSite){let{username:i,password:a}=this.credentials||{},o=P(i,a),s=(e===`timeseries`||e===`timeseriesNew`)&&o&&this.allowCredentials?`&username=${i}&password=${a}`:``;r=`https://${this.dataEndpoint}${n}${t}${s}`}return await(await fetch(r)).text()},getCustomEventPopup:e=>null};async function mF(e,t){let n=$()?.config;if(!n||!n.fetch)throw Error(`You should call initFeed first`);let r=t;return e===`timeseries`?r=`/historical${t}`:e===`options`&&(r=`/options-historical${t}`),await n.fetch.call(n,e,r)}var hF=!1,gF=null;function _F(){let e=fF,t=e.prerelease?`-${e.prerelease.identifier}.${e.prerelease.ordinal}`:``;return`${e.major}.${e.minor}.${e.patch}${t}`}function vF(e){let t=e.extensions?.studyProvider;if(!P(t))return;let n=t.getFields(),r=t.getStudies(),i=F(Xs(B.CHART_SCHEMA)),a=i.definitions,o=a.studyField.enum,s=a.study.enum;for(let e of n)if(o.includes(e.id))throw Error(`Field with id ${e.id} already exists`);for(let e of r)if(s.includes(e.id))throw Error(`Study with id ${e.id} already exists`);o.push(...n.map(e=>e.id)),s.push(...r.map(e=>e.id)),kf(B.CHART_SCHEMA,i),zf(n),tc(r)}function yF(e,t={}){if(hF)throw Error(`You should only call initFeed once during page's lifetime`);hF=!0;let n=Object.assign(pF);return lt(n,t),N(n.logo)&&Wk(n.logo,n.logoClickable??!1),vF(n),gF=new e(n),gF.version=_F(),I(`%cBarchart Chart version ${gF.version}`,`info`,`font-size: larger`),gF.cachesData&&(gF.subject?.subscribe(gF.onPerformInternalGc.bind(gF)),eb.default.subscribe(K.CH_ALL,gF.onChartChanged.bind(gF))),gF}function $(){return gF}function bF(){return F($()?.template)}function xF(){N(gF)&&(gF.shutdown(),hF=!1,gF=null)}function SF(){return new YP(!0)}function CF(e){let t=SF();return t.load(e),t.change({id:`Outline`,context:{id:`Get`}})}function wF(e,t,n,r=null){return new Proxy(e,{get:function(e,i,a){return i===t?function(t){let a=r?t[r]:t;return(n.handlesRequestsFor(a)?n:e)[i](t)}:Reflect.get(e,i,a)}})}var TF=class{config;version;cachesData;timeSeriesSource;metaDataSource;recordSource;charts;pendingRedraw;template;ongoingAnimationCallbackId;_altDataSource;_subject;knowDefaultCurve;defaultOhlcCurve;knowDefaultAggregation;defaultAggregation;knowDefaultPeriod;defaultPeriod;knowDefaultDensity;defaultDensity;id;_mainFeed=null;onBrowserOnline;constructor(e){this.config=e,this.timeSeriesSource=this.metaDataSource=this.recordSource=null,this.charts=new Map,this.pendingRedraw=new Set,this.ongoingAnimationCallbackId=null,this.drawCharts=this.drawCharts.bind(this),this.template=null,this.cachesData=!1,this._altDataSource=null,this._subject=null,this.id=bt(),this.onBrowserOnline=()=>{!this.cachesData||this.isAuxiliary||(this.traceFeed(`refresh:online`),this.refreshCaches())},globalThis.addEventListener?.(`online`,this.onBrowserOnline)}traceFeed(e,t={}){Lh(e,{feedId:this.id,isAuxiliary:this.isAuxiliary,...t})}get subject(){return!this.isAuxiliary&&!N(this._subject)&&(this.traceFeed(`gc:stream:init`,{gcMillis:B.INTERNAL_GC_MILLIS}),this._subject=new em().pipe(Im(B.INTERNAL_GC_MILLIS),Fm(e=>e.length>0))),this._subject}get isAuxiliary(){return window.opener!==null}setAltDataSource(e){this._altDataSource=e,this.timeSeriesSource=wF(this.timeSeriesSource,`getTimeSeries`,e,`symbol`),this.metaDataSource=wF(this.metaDataSource,`getMetaData`,e),this.recordSource=wF(this.recordSource,`getRecord`,e)}replaceDataSources(e){this._altDataSource=e._altDataSource,this.timeSeriesSource=e.timeSeriesSource,this.metaDataSource=e.metaDataSource,this.recordSource=e.recordSource}getAltDataSource(){return this._altDataSource}getTimeSeriesDataSource(){if(!N(this.timeSeriesSource))throw Error(`No time series source defined`);return this.timeSeriesSource}getMetaDataSource(){if(!N(this.metaDataSource))throw Error(`No metadata source defined`);return this.metaDataSource}getRecordSource(){if(!N(this.recordSource))throw Error(`No record source defined`);return this.recordSource}async ready(){return da.call(this,async()=>{let e=this instanceof AF||this instanceof EF||this instanceof NF;await uF(this.config,e);let t=this.config.defaultTemplate;if(!t)throw Error(`Must provide a default template`);return typeof t==`string`&&(t=await(await fetch(t)).json()),this.template=Nf(t,B.CHART_SCHEMA),!0})}getHeadlessChart(){return SF()}fixupRenderTo(e){if(!N(e))return null;if(e instanceof HTMLElement)return e;let t=na(`#${e}`);if(N(t))return t;let n=[...this.charts.keys()].find(t=>t.id===e);return N(n)?n:null}checkChart(e,t){let n=this.fixupRenderTo(e),r=N(n)&&this.charts.has(n);return N(t)&&t!==r&&I(`There is ${t?`no`:`already a`} chart inside the element ${e}`,`error`),n}addChart(e,t=null){let n=this.checkChart(e,!1),r=new YP;return this.charts.set(n,r),r.initialize(e,t),r}removeChart(e){let t=this.checkChart(e,!0);N(t)&&(this.charts.get(t).shutdown(),this.charts.delete(t))}removeAllCharts(){for(let e of this.charts.keys())this.removeChart(e)}getChart(e){let t=this.checkChart(e);return N(t)?this.charts.get(t):null}redraw(e){let t=this.checkChart(e,!0);N(this.ongoingAnimationCallbackId)||(this.ongoingAnimationCallbackId=requestAnimationFrame(this.drawCharts)),N(t)&&this.pendingRedraw.add(t)}drawCharts(){this.ongoingAnimationCallbackId=null,this.pendingRedraw.forEach(e=>{let t=this.getChart(e);if(!N(t?.presenter?.view))return;let n=t.presenter.view;n.isHostElementVisible&&n.draw()}),this.pendingRedraw.clear()}get emptyEntities(){return{metaData:new Set,records:new Set,timeSeries:new Set}}getAllCacheableEntities(e){for(let t of this.charts.values())t.presenter.getCacheableEntities(e)}getCacheableEntities(){let e=this.emptyEntities;return this.getAllCacheableEntities(e),e.timeSeries.forEach(t=>{N(t)&&(N(t.record)&&e.records.add(t.record),N(t.records)&&Object.values(t.records).forEach(t=>e.records.add(t)))}),e}clearCaches(){this.evictUnused(this.emptyEntities)}refreshCaches(){let e=this.getCacheableEntities();this.traceFeed(`refresh:caches`,{metaData:e.metaData.size,records:e.records.size,timeSeries:e.timeSeries.size}),this.getMetaDataSource().refresh?.(),this.getRecordSource().refresh?.(e.records),e.timeSeries.forEach(e=>{e.isCached||e.refresh()}),this.getTimeSeriesDataSource().refresh(),Ge(K.DF_STREAMRECONNECTED,{})}evictUnused(e){this.getMetaDataSource().evictUnused(e.metaData),this.getRecordSource().evictUnused(e.records),this.getTimeSeriesDataSource().evictUnused(e.timeSeries)}onPerformInternalGc(){let e=this.getCacheableEntities();this.traceFeed(`gc:run`,{chartCount:this.charts.size,metaData:e.metaData.size,records:e.records.size,timeSeries:e.timeSeries.size}),this.evictUnused(e)}triggerGc(e=`unknown`){this.traceFeed(`gc:request`,{reason:e}),this.subject?.next()}onChartChanged(e,t){(e===K.CH_RECREATED||e===K.CH_SHUTDOWN)&&(this.isAuxiliary?this._mainFeed?.triggerGc(`${e}:aux:${this.id}`):this.triggerGc(e))}getDefaultMultiFieldCurve(){if(!N(this.template))return null;if(!this.knowDefaultCurve){let e=Ud(this.template);e.curves.length===1&&qu(e.curves[0].style)?this.defaultOhlcCurve=F(e.curves[0]):this.defaultOhlcCurve=null,this.knowDefaultCurve=!0}return this.defaultOhlcCurve}getDefaultAggregation(){return!this.knowDefaultAggregation&&this.template&&(this.defaultAggregation=F(this.template.data.aggregation),this.knowDefaultAggregation=!0),this.defaultAggregation}getDefaultPeriod(){return!this.knowDefaultPeriod&&this.template&&(this.defaultPeriod=this.template.display?.period,this.knowDefaultPeriod=!0),this.defaultPeriod}getDefaultDensity(){return!this.knowDefaultDensity&&this.template&&(this.defaultDensity=this.template.display?.density,this.knowDefaultDensity=!0),this.defaultDensity}shutdown(){globalThis.removeEventListener?.(`online`,this.onBrowserOnline),this.isAuxiliary||this.clearCaches(),this.removeAllCharts()}},EF=class extends TF{constructor(e){super(e),this.timeSeriesSource=new O_(!1),this.metaDataSource=new Ja,this.recordSource=new Vh}},DF=class extends TF{constructor(e){super(e),this.timeSeriesSource=new O_(!0),this.metaDataSource=new Ja,this.recordSource=new Hh}},OF=class extends TF{constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new O_(!0),this.metaDataSource=new Ja,this.recordSource=new Vh}},kF=[`drazen.dotlic@barchart.com`,`princec`,`b.hebert24@barchart.com`],AF=class extends TF{lastStreamingTimestamp=null;_isActivelyStreaming=null;needToResubscribe=!1;_connection;constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new O_(!0),this.metaDataSource=new Ya,this.recordSource=new Uh,this.onEvents=this.onEvents.bind(this),this.onTimestamp=this.onTimestamp.bind(this),this.resetStreamingState()}resetStreamingState(){this.lastStreamingTimestamp=null,this._isActivelyStreaming=null,this.needToResubscribe=!1}get connection(){return this._connection}set connection(e){this._connection=e,N(e)&&this.initializeStreaming()}addChart(e,t=null){return this.needToResubscribe&&this.initializeStreaming(),super.addChart(e,t)}set isActivelyStreaming(e){N(this._isActivelyStreaming)&&!this._isActivelyStreaming&&e&&(this.debug(`need to refresh caches`),this.refreshCaches()),this._isActivelyStreaming=e}get isActivelyStreaming(){return this._isActivelyStreaming}initializeStreaming(){this.resetStreamingState(),this.connection.on(`events`,this.onEvents),this.connection.on(`timestamp`,this.onTimestamp)}onTimestamp(e){this.isActivelyStreaming&&(this.lastStreamingTimestamp=e)}debug(e){this.connection&&kF.includes(this.connection._username)&&I(`[chart] Connection ${e}, last timestamp ${this.lastStreamingTimestamp}`)}onEvents({event:e}){e===B.BC_EVENT_DISCONNECTED||e===B.BC_EVENT_FEED_PAUSED?(this.debug(e),this.isActivelyStreaming=!1):(e===B.BC_EVENT_LOGGED_IN||e===B.BC_EVENT_FEED_RESUMED)&&(this.debug(e),this.isActivelyStreaming=!0)}shutdown(){super.shutdown(),N(this._connection)&&(this.connection.off(`timestamp`,this.onTimestamp),this.connection.off(`events`,this.onEvents),this.resetStreamingState(),this.connection.disconnect(),this.connection=null)}};function jF(e,t){return new MF(e,t)}var MF=class{_client;_subscriptions=new Map;_listeners=new Set;constructor(e,t){this._client=e;let n=e=>e.find(e=>this._subscriptions.has(e))??null;t.onConnected=()=>{this._listeners.forEach(e=>e?.onConnected())},t.onMessageWithMetadata=(e,t)=>{let r=e.marketSnapshot;if(N(r)){let e=n(t);e!==null&&this._listeners.forEach(t=>t.onSnapshot?.(r,e))}let i=e.marketUpdate;if(N(i)){let e=n(t);e!==null&&this._listeners.forEach(t=>t.onUpdate?.(i,e))}},t.onDisconnected=()=>{this._listeners.forEach(e=>e?.onDisconnected())},t.onHeartBeat=e=>{this._listeners.forEach(t=>t.onHeartBeat?.(e))}}addListener(e){this._listeners.add(e)}removeListener(e){this._listeners.delete(e)}async ready(){return N(await this._client.connection)}shutdown(){N(this._client)&&(this._client.dispose(),this._subscriptions.clear(),this._listeners.clear())}subscribeToRealTime(e){if(this._subscriptions.has(e)||!N(this._client))return;let t=this._client.subscribe(1,5,0,[e],null,null,null);this._subscriptions.set(e,t)}unsubscribeFromRealTime(e){if(!this._subscriptions.has(e)||!N(this._client))return;let t=this._subscriptions.get(e);this._client.unsubscribe(t),this._subscriptions.delete(e)}async getInstrument(e){return await(await this._client.connection)?.getInstrument(e)??[]}},NF=class extends TF{_adapter=null;_auxFeeds=[];constructor(e){super(e),this.cachesData=!0,this.isAuxiliary||(this.timeSeriesSource=new O_(!0),this.metaDataSource=new Xa,this.recordSource=new Wh,eb.default.subscribe(K.TS_ALL,this.onTimeSeriesMessage.bind(this)))}onTimeSeriesMessage(e,t){if(!this.isAuxiliary)for(let n of this._auxFeeds)n.notifySeriesMessage(e,t)}notifySeriesMessage(e,t){this.isAuxiliary&&Ge(e,t)}getAdapter(){return this.isAuxiliary?this._mainFeed?._adapter:this._adapter}setAdapter(e){if(this.isAuxiliary)throw Error(`Cannot set adapter on auxiliary feed`);this._adapter=e,this._adapter.addListener(this)}async ready(){if(this.isAuxiliary){let e=await this._mainFeed?.ready()??!1;return e&&(this.template=this._mainFeed.template),e}return await super.ready(),await this._adapter?.ready()??!1}subscribe(e){this.traceFeed(`openfeed:subscribe`,{symbol:e}),this.getAdapter()?.subscribeToRealTime(e)}unsubscribe(e){this.traceFeed(`openfeed:unsubscribe`,{symbol:e}),this.getAdapter()?.unsubscribeFromRealTime(e)}shutdown(){super.shutdown(),this.isAuxiliary?(this._mainFeed?.removeAuxFeed(this),this._mainFeed=null):this._adapter?.shutdown()}onConnected(){this.refreshCaches()}onDisconnected(){}onHeartBeat(){}onUpdate(e,t){this.ofRecordSource.onUpdate(e,t)}onSnapshot(e,t){this.ofRecordSource.onSnapshot(e,t)}get ofRecordSource(){return this.recordSource}replaceDataSources(e){super.replaceDataSources(e),this._mainFeed=e}addAuxFeed(e){e.replaceDataSources(this),this._auxFeeds.push(e),this._adapter?.addListener(e)}removeAuxFeed(e){let t=this._auxFeeds.findIndex(t=>t.id==e.id);t!==-1&&(this._auxFeeds.splice(t,1),this._adapter?.removeListener(e),this.triggerGc(`removeAuxFeed:${e.id}`))}getAllCacheableEntities(e){if(super.getAllCacheableEntities(e),!this.isAuxiliary)for(let t of this._auxFeeds)t.getAllCacheableEntities(e)}},PF=eb.default;export{zu as Aggregation,_ as AggregationSpec,g as AggregationUnit,EF as BarchartSiteDataFeed,TF as BaseDataFeed,Bh as BaseRecordSource,re as ChunkPart,y_ as ContainerWrapperTimeSeries,xM as CustomEventPopup,Kf as EmptyRecord,u as ExpressionMissingBar,f as ExpressionNoDataApproach,d as ExpressionRecompute,nb as ExpressionSeries,If as Field,b as FieldCategory,y as FieldFormat,v as FieldValueType,G as Fields,AF as MarketDataFeed,OF as MiniWidgetDataFeed,gg as OHLCDataPointBuilder,NF as OpenFeed,PF as PubSub,w as SeriesKind,DF as SnapshotDataFeed,J as StudySeries,vg as TimeSeriesContainer,$y as TimeSeriesQuery,K as Topics,jF as adaptOpenFeedClient,sa as appendDOMElement,da as asyncReady,cc as canBeBasedOnSeasonal,Z as convertSeries,YM as convertTableToCsv,ug as dateToOptionValue,Ed as doesExpressionHaveComputation,oc as doesStudyExist,xd as evaluateExpression,wd as formatExpression,Ia as formatPriceWithDecimals,bt as generateUid,ic as getAnnotationTraits,CF as getChartOutline,La as getCombinedMetaData,Td as getExpressionSymbols,$ as getFeed,bo as getLightness,Oj as getStudyOptions,pc as getTaxonomies,Hi as hasOpenInterest,yF as initFeed,iO as linReg,tb as makeExpression,q as makeHelperField,ND as makeStudy,Q as mapSeries,Y as movAvg,X as movExp,RD as movHul,ID as movSmo,LD as movWei,lg as optionValueToDate,bd as parseExpression,Dd as replaceExpressionSymbols,YD as roc,ia as setAttributesDOMElement,xF as shutdownFeed,QD as stdDev,ra as styleDOMElement,WD as trueRange,JD as typical};
|