@barchart/chart-lib 2.379.0 → 2.379.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 +3 -3
- chart-lib/package.json +1 -1
chart-lib/barchart.chart.js
CHANGED
|
@@ -29,9 +29,9 @@ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=
|
|
|
29
29
|
<td class="field-name">${s}</td>
|
|
30
30
|
<td${o} class="field-value">${c}</td>
|
|
31
31
|
</tr>
|
|
32
|
-
`}function j_(e,t,n=null){return A_(e,t,n,`value-title`)}function M_(e,t,n){let r=typeof n==`string`?at(n):null,i=r===null?``:` style="color: ${r}"`,a=P(e)?it(e):null;return`${a===null?``:`<span class="field-name">${a}</span>`}<span${i} class="field-value">${it(t)}</span>`}function N_(e){return`<a class="delete-plot" data-plot-uid="${at(e)}" title="Delete plot">${T_(`delete`)}</a>`}function P_(e,t){let n=e>0,r=e<t-1;return[`${n?O_(!0,e):``}`,`${r?O_(!1,e):``}`].join(` `).trim()}function F_(e,t){return e.startsWith(z.FAKE_SYMBOL_PREFIX)&&t.length>0?t:e}function I_(e,t,n,r,i,a){let o=L_(e,t);o.offset=n,o.lastBarRefresh=!!r||!1,o.chartId=e.elementId;let s=n=>n.axes.map(e=>e.plots).flat().filter(t=>i?t===e.mainPlot:!0).map(n=>V_(e,t,a,o,n)).filter(e=>e!==null);return o.panes=e.panes.map(e=>({bounds:R_(e),id:e.id,plots:s(e)})),o}function L_(e,t){let n=e.data.aggregation,r=e.display.xAxis,i=r.isOrdinal,a=N(i)&&i,o=a?r.ordinalName??`Value`:`Date`;return{date:a?i_(t):p_(n,t),time:n.isEndOfDay||a?null:m_(n,t,!1),isMultiSymbol:H_(e),isMultiContract:n.isMultiContract,dateFieldName:o}}function R_(e){let t=e.getBounds();if(!P(t))return;let{x:n,y:r,width:i,height:a}=t,{leftOffset:o,rightOffset:s}=e.presenter.view;return{top:r,left:n+o,right:s,bottom:r+a,width:i,height:a}}function z_(e,t,n,r=!1){let i=e.plot,a=i.timeSeries.container,o=i.axis.pane.presenter.timeline,s=Te(o,+n,Number,h_),c=o.at(s-e.shift);if(c===null)return[null,0];let l=a.getTimeData(),u=Te(l,+c,Number);return[!l[u]||l[u].getTime()!==c.getTime()?null:e.dataAt(t,u,!r),u]}function B_(e,t,n){P(e.precision)?n.overridePrecision=e.precision:e.isStudy&&P(t.mainPlot?.precision)&&!P(gs(e.model.study).meta.decimals)&&(n.overridePrecision=t.mainPlot.precision)}function V_(e,t,n,{isMultiContract:r},i){let a=i.isStudy;if(!i.timeSeries.hasData)return null;let o=i.timeSeries.container;i.type,C.Expression;let s=i.axis.comparison!==x.None,c=i.axis.comparison===x.Percent,l=(e,r)=>i.customPlotValues&&r!==W.DateTime?[i.getValueAt(r,t,n),0]:z_(e,r,t,s),u=i,d=a?`${gs(u.model.study).meta.title} ${u.fullParams}`:i.metaData.name||``,f={isMain:i.main,type:i.type,typeName:C[i.type],name:F_(i.title,i.metaData.symbol),description:d,exchange:i.metaData.exchange||``,error:u.errorText,id:i.id,uid:i.uid,visible:i.visible,seasonalOffset:i.isSeasonal?u.offset??void 0:void 0};if(P(u.yearOffset)&&u.yearOffset!=0){let n=e.data.aggregation;f.unalignedDate=p_(n,zr(t,u.yearOffset))}let p=i.curves[0],m=i.type===C.Symbol&&oi(i.title);if(r&&i.type===C.Symbol&&o.hasField(W.Symbol)){let e=t.valueOf()===z.ZERO_DATE.valueOf()?i.timeSeries.container?.getLastDataPoint(W.Symbol):l(p,W.Symbol)[0];P(e)&&e.length>0&&(f.actualSymbol=e,m||(f.name=e))}let g={},_={range:i.axis.yScale.domain(),allDigits:!0};B_(i,e,_);let v=(e,t)=>{let n=(t===W.Change||t===W.PercentChange)&&e>0?`+`:``;return c?n+a_(e):n+i.metaData.format(e,t,_)},y=v_(e),b=new Set;return f.values=i.curves.filter(e=>e.visible).map(e=>(!i.main&&i.isSymbol&&y?Ih:e.fields).map(t=>{if(b.has(t))return null;b.add(t);let[n,r]=l(e,t),o=i.axis.yScale.priceToY(n);g[t.id]=!0;let s=i.customPlotValues?u.getColorOf(t):e.getColor(r,e.style!==h.HollowCandles,t),c=v(n,t).trim();if(P(n)&&t===W.Change){let[t]=l(e,W.PercentChange);P(t)&&(c+=` (${v(t,W.PercentChange)})`)}return{abbreviation:U_(t),shortName:t.shortName,id:t.id,name:t.name,longName:`${t.shortName} ${a?u.params:``}`.trim(),color:wa(s),val:n,y:o,value:c}}).filter(e=>e!==null)).flat(),f.events=i.findEvents(l(p,W.DateTime)).filter(e=>e.field!==W.Custom),f}function H_(e){let t=e.mainPlot.symbol;return e.allPlots.some(e=>e.type===C.Symbol&&e.symbol!==t)}function U_(e){return e.id===W.Change.id?`Δ`:e.id.substring(0,1)}var W_=class{plot;id;fields=[];colors=[];style=h.Line;attributes=[];zones;_shift=0;lineWidth=1;lineMarker;lineSmoothing;dashStyle=`Solid`;varyColorPerBar=!1;visible=!0;_zoneColors;constructor(){this.id=bt(),this.plot=null}get shift(){return this._shift}set shift(e){this._shift=P(e)?e:0}get isOhlc(){return(this.isOhlcStyle||this.isCandle||this.isHlcStyle||this.isElderImpulseSystemStyle||this.isRangeStyle)&&this.fields.includes(W.Close)}get name(){return this.isOhlc?``:this.fields[0].name}get isHeikinAshiStyle(){return this.style===h.HeikinAshi}get isCandle(){return this.style===h.Candlestick||this.style===h.HollowCandles||this.style===h.HeikinAshi}get isHollowCandles(){return this.style===h.HollowCandles}get isElderImpulseSystemStyle(){return this.style===h.ElderImpulseSystem}get isPercentChangeStyle(){return this.style===h.PercentChange}get isOhlcStyle(){return this.style===h.OHLC}get isHlcStyle(){return this.style===h.HLC}get isRangeStyle(){return this.style===h.Range}get isRenko(){return this.style===h.Renko}get isKagi(){return this.style===h.Kagi}get isPointAndFigure(){return this.style===h.PointAndFigure}get isLineBreak(){return this.style===h.LineBreak}get isBaseline(){return this.style===h.Baseline}get isLineLike(){return[h.Line,h.Area,h.Baseline,h.PercentChange].includes(this.style)}get isColumn(){return this.style===h.Column}get isMultiColumn(){return this.style===h.MultiColumn}get isStackedColumn(){return this.style===h.StackedColumn}isFirstVisibleOfStyle(){return this.plot.curves.find(e=>e.visible&&e.style===this.style)===this}fromModel(e){e.attributes&&(this.attributes=e.attributes.map(e=>m[e])),this.colors=e.colors,this.fields=e.fields.map(e=>W[e]),this.style=h[e.style],this.lineWidth=e.lineWidth,this.dashStyle=e.dashStyle,this.lineMarker=e.lineMarker,this.lineSmoothing=e.lineSmoothing,this.varyColorPerBar=e.varyColorPerBar,this.visible=e.visible??!0,e.zones&&(this.zones=e.zones),this.shift=e.shift}get axis(){return this.plot?.axis}get pane(){return this.axis?.pane}get timeSeries(){return this.plot?.timeSeries}get presenter(){return this.pane?.presenter}get view(){return this.presenter?.view}yToPrice(e){return this.yScale.yToPrice(e)}priceToY(e){return this.yScale.priceToY(e)}dataAt(e,t,n=!0){let r=!this.plot.isComparison(x.None),i=e===W.PercentChange,a=e===W.Change,o=i||(!n||r)&&a,s=this.timeSeries.container.hasField(W.Last)?W.Last:W.Close,c=o?s:e,l=(e,t)=>{let n=this.timeSeries.container.getData(e)[t];return e.type===v.Number?this.plot.priceMapper(n,t,e):n},u=l(c,t);if(!o)return u;if(t<=1)return 0;let d=l(c,t-1),f=u-d;return i?d===0?0:f/d:f}timeSeriesAt(e){let t=this.timeSeries.container.getTimeData(),n=t.length;return e<0||e>n-1?null:t[e]}timelineAt(e){return this.presenter.timeline.at(e)}get shiftedTimeDomain(){let e=this.view.xAxis.xScale;return P(e.extent())?this.shift===0?e.domain():e.extent().map(t=>e.timeline.at(t-this.shift)):null}get yScale(){return this.plot?.yScale??this.axis.yScale}getCore(){let e=this.timeSeries;if(!e.hasData||!this.visible)return null;let t=this.view.xAxis.xScale.extent();if(!P(t))return null;let n=this.yScale.domain();return P(n)?{ts:e,extent:t,domain:n,range:this.yScale.range()}:null}drawHover(e,t,n){if(!this.isLineLike||this.getCore()===null)return;let[r,i]=z_(this,this.pickMainField(),t);P(r)&&(e.save(),Ra(e,this.plot.axis.pane.getBoundsWithoutScales()),e.fillStyle=wa(this.getColor(i)),e.beginPath(),lv(e,n,this.priceToY(r),this.lineMarker??`Circle`,1.3333),e.fill(),e.restore())}draw(e){let t=this.getCore();if(t===null)return;let{ts:n,extent:r,domain:i,range:a}=t;e.save(),e.setLineDash([]);let o=n.container.getTimeData(),s=this.shiftedTimeDomain[0],c={bar:this.view.xAxis.xScale.bar,domain:i,range:a,slice:r,start:Te(o,+s,Number)||0},l=P(this.zones);this.isOhlc?av.call(this,e,c):this.isRenko||this.isLineBreak?$_.call(this,e,c):this.style===h.Ribbon?this.varyColorPerBar?yv.call(this,e,c):vv.call(this,e,c,this.colors[0]):this.style===h.Area?l?Y_.call(this,e,c,K_,!0):K_.call(this,e,c,this.colors,!0):this.isColumn||this.isMultiColumn?l?Y_.call(this,e,c,tv,!0):tv.call(this,e,{...c,range:[null,null]}):this.isStackedColumn?ev.call(this,e,c):this.isBaseline?Q_.call(this,e,c):this.style===h.Step?l?Y_.call(this,e,c,rv):rv.call(this,e,c,this.colors[0]):this.isKagi?gv.call(this,e,c):this.isPointAndFigure?_v.call(this,e,c):this.style===h.Dots?nv.call(this,e,c):this.style===h.Line||this.isPercentChangeStyle?l?Y_.call(this,e,c,uv):this.varyColorPerBar?mv.call(this,e,c):uv.call(this,e,c):I(`Drawing of the curve style '${this.style}' is not implemented yet`,`error`),e.restore()}pickMainField(){return this.fields.length===1?this.fields[0]:this.fields.includes(W.Last)?W.Last:this.fields.includes(W.Close)?W.Close:this.fields[0]}get zoneColors(){if(!P(this._zoneColors)){let e=this.colors.slice();this._zoneColors=this.zones.map(t=>e.splice(0,t.colors))}return this._zoneColors}getColorsFromZone(e){let t=this.zones.findIndex(t=>e<t.value);return t===-1&&(t=this.zones.length-1),this.zoneColors[t]}pickAreaStroke(e){return e.length<2?wa(e[0]):e[1]}getComputedColor(e){if(!this.timeSeries.container.hasField(W.BARCOLIX))return null;let t=this.dataAt(W.BARCOLIX,e);return t>=0&&t<this.colors.length?this.colors[t]:null}getColor(e,t=!0,n=null){if(this.varyColorPerBar){let n={};if(this.isOhlc||this.isRenko||this.isLineBreak){let t=this.dataAt(W.Open,e),r=this.dataAt(W.High,e),i=this.dataAt(W.Low,e),a=this.dataAt(W.Close,e),o=this.dataAt(W.Change,e);n.open=t,n.high=r,n.low=i,n.close=a,n.change=o}else if(this.plot.isStudy&&![`VOL`,`MAVOL`].includes(this.plot.model.study)){let t=this.pickMainField(),r=this.dataAt(t,e-1),i=this.dataAt(t,e),a=P(r),o=P(i);a?n.change=o?i-r:-1:n.change=+!!o}else{let t=this.plot.axis.pane.presenter.data.aggregation;(!t.isTick||t.spec!==_.None)&&(n.open=this.dataAt(W.Open,e),n.close=this.dataAt(W.Close,e)),n.change=this.dataAt(W.Change,e)}let r,i=xv(this.style,n,this.colors),a=this.getComputedColor(e);switch(this.style){case h.Candlestick:case h.Renko:case h.LineBreak:case h.Range:case h.HeikinAshi:case h.OHLC:case h.HLC:case h.Column:{if(P(a)){r=a;break}let t=i.useSame?i.isUp:i.isUp||i.isSame,n=i.isSame,o=this.attributes||[],s=this.plot.isStudy&&![`HASMO`,`VOL`,`MAVOL`].includes(this.plot.model.study);(o.includes(m.ChangeBased)||s)&&(t=i.useSame?i.isUpPrev:i.isUpPrev||i.isSamePrev,n=i.isSamePrev),r=this.colors[+!!t],i.useSame&&n&&(r=this.colors[2]),(this.isRenko||this.isLineBreak||this.isRangeStyle)&&this.dataAt(W.Projection,e)===1&&(r=ka(.5,!0)(r));break}case h.ElderImpulseSystem:r=this.colors[this.dataAt(W.BREL,e)];break;case h.HollowCandles:{let e=this.colors[i.isUpPrev||i.isSamePrev?1:0];r=t&&(i.isUp||i.isSame)?z.COLOR_TRANSPARENT:e;break}case h.Line:case h.PercentChange:case h.Ribbon:case h.Kagi:if(P(a)){r=a;break}r=this.colors[0];break;case h.PointAndFigure:{let t=+!!mg(this.dataAt(W.BARKIND,e));r=this.colors[t];break}default:throw Error(`Unexpected style ${h[this.style]} for a curve with varying colors`)}return P(r)||(r=this.colors[0]),r}else if(this.zones){let t=this.pickMainField(),n=this.dataAt(t,e),r=this.getColorsFromZone(n);return this.style===h.Area?this.pickAreaStroke(r):r.length>0?r[0]:this.colors[0]}else return(this.isMultiColumn||this.isStackedColumn)&&P(n)?this.colors[ke(this.colors,this.fields.findIndex(e=>e===n))]:this.colors[0]}};function G_([e,t],n,r){let i=n,a=this.timeSeries.container.size;for(let n=e;n<=t;n++){for(;this.timeSeriesAt(i)<this.timelineAt(n-this.shift)&&i<a;)++i;if(i===a)break;let e=this.timeSeriesAt(i)>this.timelineAt(n-this.shift);r.call(this,i,e)}}function K_(e,t,n,r=!1){uv.call(this,e,t,this.pickAreaStroke(n)),bv.call(this,e,t,n[0],r)}function q_(e,t){let n=P(e),r=P(t),i,a,o=this.pane.getBounds();if(!n)i=this.priceToY(t),a=new za(o.x,i,o.width,o.y+o.height-i);else if(!r)i=this.priceToY(e),a=new za(o.x,o.y,o.width,i-o.y);else{let n=this.priceToY(e),r=this.priceToY(t);i=(n+r)/2,a=new za(o.x,r,o.width,n-r)}return[i,a]}var J_=(e,t)=>{let n=ka(.6)(e),r=Aa(.6)(e),i=t===`linLighten`;return[i?r:n,e,i?n:r]};function Y_(e,t,n,r=!1,i){let a;this.zones.forEach((o,s)=>{let c=o.value,[l,u]=q_.call(this,a,c);e.save(),Ra(e,u),r&&(t.range=[null,l]);let d=this.zoneColors[s];if(o.gradient){let t=J_(d,o.gradient),n=e.createLinearGradient(0,u.y,0,u.y+u.height);n.addColorStop(0,t[0]),n.addColorStop(.5,t[1]),n.addColorStop(1,t[2]),d=n}else P(i)&&(d=i(s,d));n.call(this,e,t,d),e.restore(),a=c})}function X_(e){let{BaseLevel:t}=dt(e);return{baseLevel:Number.isFinite(t)?xt(0,100,t):50}}function Z_(e,t){let{x:n,width:r}=this.pane.getBoundsWithoutScales();e.save(),e.lineWidth=1,e.strokeStyle=`#888`,e.setLineDash(Ca(`dot`)),eo(e,t,n,n+r),e.restore()}function Q_(e,t){let[n,r]=t.range,{baseLevel:i}=X_(this.plot.inputs),a=(n-r)*i/100+r;this.zones[0].value=this.yToPrice(a),Z_.call(this,e,a),Y_.call(this,e,t,K_,!0,(t,i)=>{let o=t===1,s=Ta(i,0),c=e.createLinearGradient(0,o?n:r,0,a);return c.addColorStop(0,i),c.addColorStop(1,s),[c,Ta(i,1)]})}function $_(e,{bar:t,slice:n,start:r}){let i=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;G_.call(this,n,r,(n,r)=>{if(!r){let[r,a]=[W.Open,W.Close].map(e=>this.dataAt(e,n)).map(this.priceToY,this),o=Math.floor(t.totalWidth/2);e.fillStyle=this.getColor(n),e.beginPath(),e.rect(i-o,r,t.totalWidth,a-r),e.fill()}i+=t.totalWidth})}function ev(e,{bar:t,slice:n,start:r}){if(!this.isFirstVisibleOfStyle())return!1;let i=this.view.xAxis.xScale.range()[0]+t.offset,a=vo();a.prolog(e);let o=this.plot.curves.filter(e=>e.isStackedColumn);G_.call(this,n,r,(n,r)=>{if(!r){let r=this.priceToY(0),s=0;o.forEach(o=>{if(!o.visible)return;let c=o.fields[0];if(s+=this.dataAt(c,n),P(s)){let l=this.priceToY(s);e.fillStyle=o.getColor(n,!1,c),e.beginPath(),e.rect(a.adjust(i),a.adjust(l),a.adjust(t.width),a.adjust(r-l)),e.fill(),r=l}})}i+=t.totalWidth}),a.epilog(e)}function tv(e,{bar:t,slice:n,start:r,range:[i,a]}){let o=this.view.xAxis.xScale.range()[0]+t.offset,s=this.isMultiColumn,c=s?this.fields:[this.pickMainField()],l=t.width/(s?c.length:1),u=vo();u.prolog(e),G_.call(this,n,r,(n,r)=>{r||c.forEach((t,r)=>{let i=this.dataAt(t,n);if(P(i)){P(a)||(a=this.priceToY(0));let s=this.priceToY(i);e.fillStyle=this.getColor(n,!1,t),e.beginPath(),e.rect(u.adjust(o+r*l),u.adjust(s),u.adjust(l),u.adjust(a-s)),e.fill()}}),o+=t.totalWidth}),u.epilog(e)}function nv(e,{bar:t,slice:n,start:r}){let i=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;e.fillStyle=this.getColor(0);let a=Math.max(1,this.lineWidth||z.CURVE_STYLE_DOTS_RADIUS),o=Math.PI*2;e.beginPath(),G_.call(this,n,r,(n,r)=>{if(!r){let t=this.pickMainField(),r=this.dataAt(t,n);if(P(r)){let t=this.priceToY(r);e.moveTo(i+a,t),e.arc(i,t,a,0,o)}}i+=t.totalWidth}),e.fill()}function rv(e,{bar:t,slice:n,start:r},i){let a=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,o=vo();o.prolog(e),e.strokeStyle=i,e.lineWidth=this.lineWidth,this.dashStyle&&e.setLineDash(Ca(this.dashStyle)),e.beginPath();let s=!1,c=null;G_.call(this,n,r,(n,r)=>{if(!r){let t=this.pickMainField(),r=this.dataAt(t,n);if(P(r)){let i=this.priceToY(r);if(s)e.lineTo(a,c),e.lineTo(a,i);else{let r=this.dataAt(t,n-1);if(P(r)){let t=this.priceToY(r);e.moveTo(-1,t),e.lineTo(a,t),e.lineTo(a,i)}else e.moveTo(a,i);s=!0}c=i}}a+=t.totalWidth}),e.stroke(),o.epilog(e)}var iv=[W.Open,W.High,W.Low,W.Close];function av(e,{bar:t,slice:n,start:r}){let i=this.presenter.display.chart.showMinMaxArc,a=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,o=vo();o.prolog(e);let s=null,c=null,l=null,u=null,d=t=>{this.isCandle?(this.isHollowCandles?t.outlineColor=this.getColor(t.ix,!1):(this.colors.length>3&&(t.outlineColor=this.colors[3]),this.colors.length>4&&(t.wickColor=this.colors[4])),cv(e,t,this.lineWidth)):(this.isOhlcStyle||this.isHlcStyle||this.isElderImpulseSystemStyle||this.isRangeStyle)&&sv(e,t,this.lineWidth,!this.isHlcStyle)};G_.call(this,n,r,(e,n)=>{if(!n){let n=iv.map(t=>this.dataAt(t,e)),[r,i,f,p]=n;if(P(r,i,f,p)){let m={x:o.adjust(a),adjust:o.adjust,width:t.width,y:[r,i,f,p].map(this.priceToY,this).map(o.adjust),isMin:!1,isMax:!1,ix:e,color:this.getColor(e)},h=Math.min(...n),g=Math.max(...n);(!P(s)||h<s)&&(s=h,l=m),(!P(c)||g>c)&&(c=g,u=m),d(m)}}a+=t.totalWidth}),i&&(P(l)&&(l.isMin=!0,d(l)),P(u)&&(u.isMax=!0,d(u))),o.epilog(e)}function ov(e,t,n,r,i,a,o,s=3){t&&Za(e,{x:r,y:i+s},o,0,Math.PI),n&&Za(e,{x:r,y:a-s},o,0,Math.PI,!0)}function sv(e,{x:t,adjust:n,width:r,y:[i,a,o,s],color:c,isMin:l,isMax:u},d,f){let p=r/2;e.lineWidth=d,e.strokeStyle=c,e.beginPath(),e.moveTo(t,o),e.lineTo(t,a),f&&(e.moveTo(n(t-p),i),e.lineTo(t,i)),e.moveTo(n(t+p),s),e.lineTo(t,s),e.stroke(),ov(e,l,u,t,o,a,p)}function cv(e,{x:t,adjust:n,width:r,y:[i,a,o,s],color:c,outlineColor:l,wickColor:u,isMin:d,isMax:f},p){let m=r/2;e.lineWidth=p,e.fillStyle=c,e.strokeStyle=l||c,e.beginPath(),e.rect(n(t-m),i,r,n(s-i)),e.fill(),e.stroke(),e.strokeStyle=u||l||c,e.beginPath(),e.moveTo(t,Math.min(s,i)),e.lineTo(t,a),e.moveTo(t,Math.max(s,i)),e.lineTo(t,o),e.stroke(),e.strokeStyle=ja(c).a===0?l:c,ov(e,d,f,t,o,a,m)}function lv(e,t,n,r,i=1){let a=z.MARKER_SIZE*i,o=a*1.25;switch(r){case`Circle`:e.moveTo(t+a,n),e.arc(t,n,a,0,Math.PI*2);break;case`Square`:e.rect(t-a,n-a,2*a,2*a);break;case`TriangleUp`:e.moveTo(t-o,n+o),e.lineTo(t+o,n+o),e.lineTo(t,n-o),e.lineTo(t-o,n+o);break;case`TriangleDown`:e.moveTo(t-o,n-o),e.lineTo(t+o,n-o),e.lineTo(t,n+o),e.lineTo(t-o,n-o);break;case`Diamond`:e.moveTo(t,n-o),e.lineTo(t+o,n),e.lineTo(t,n+o),e.lineTo(t-o,n),e.lineTo(t,n-o);break;default:break}}function uv(e,{bar:t,slice:n,start:r},i=null){let a=i||this.getColor(0),o=N(this.lineMarker);o&&(e.fillStyle=a,e.beginPath());let s=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,c=[],l=this.pickMainField();G_.call(this,n,r,(n,r)=>{if(!r){let t=this.dataAt(l,n);if(P(t)){let n=this.priceToY(t);o&&lv(e,s,n,this.lineMarker),c.push({x:s,y:n})}}s+=t.totalWidth}),o&&e.fill(),e.lineWidth=this.lineWidth,this.dashStyle&&e.setLineDash(Ca(this.dashStyle)),N(this.lineSmoothing)?dv(e,c,a,this.lineSmoothing):pv(e,c,a)}function dv(e,t,n,r){if(t.length<2)return;let i=fv(t,r);e.beginPath(),e.strokeStyle=n,e.moveTo(t[0].x,t[0].y);for(let t of i)e.bezierCurveTo(t.cp1x,t.cp1y,t.cp2x,t.cp2y,t.x,t.y);e.stroke()}function fv(e,t){let n=[];for(let r=0;r<e.length-1;r++){let i=e[r-1]||e[r],a=e[r],o=e[r+1],s=e[r+2]||o,c=a.x+(o.x-i.x)/t,l=a.y+(o.y-i.y)/t,u=o.x-(s.x-a.x)/t,d=o.y-(s.y-a.y)/t;n.push({cp1x:c,cp1y:l,cp2x:u,cp2y:d,x:o.x,y:o.y})}return n}function pv(e,t,n){if(t.length>1){e.beginPath(),e.strokeStyle=n;let r=t[0];e.moveTo(r.x,r.y);for(let n=1;n<t.length;n++){let r=t[n];e.lineTo(r.x,r.y)}e.stroke()}}function mv(e,{bar:t,slice:n,start:r}){e.lineWidth=this.lineWidth,e.lineCap=`square`,this.dashStyle&&e.setLineDash(Ca(this.dashStyle));let i=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,a=null,o=null,s=[];G_.call(this,n,r,(n,r)=>{if(!r){let t=this.pickMainField(),r=this.dataAt(t,n);if(P(r)){let t=this.priceToY(r);o=this.getColor(n),a!==o&&(pv(e,s,a),s.length>0&&(s=[s.pop()]),a=o),s.push({x:i,y:t})}}i+=t.totalWidth}),pv(e,s,o)}var hv=[null,null,null,null];function gv(e,{bar:t,slice:n,start:r}){e.lineWidth=Math.max(1,.5*t.width),e.lineJoin=`miter`,e.miterLimit=1.5;let i=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,a=vo();a.prolog(e);let o=null,s=null,c=[];G_.call(this,n,r,(n,r)=>{if(!r){let r=e=>iv.map(t=>this.dataAt(t,e)),[l,u,d,f]=r(n),[,p,m]=n<0?hv:r(n-1);if(P(l,u,d,f)){let r=a.adjust(i),h=a.adjust(i-t.totalWidth),g=[l,u,d,f].map(this.priceToY,this).map(a.adjust),_=a.adjust(this.priceToY(u>p?p:m));s=this.getColor(n);let v=P(o)&&o!==s,y=l===u?1:2,b=l===u?2:1;c.push({x:h,y:g[0]}),c.push({x:r,y:g[y]}),v&&(c.push({x:r,y:_}),pv(e,c,o),c=[]),v&&c.push({x:r,y:_}),c.push({x:r,y:g[b]}),o=s}}i+=t.totalWidth}),pv(e,c,s),a.epilog(e)}function _v(e,{bar:t,slice:n,start:r}){let i=this.view.xAxis.xScale.range()[0],a=t.totalWidth/2,o=i+t.offset+t.width/2,s=vo();s.prolog(e);let c=this.plot.timeSeries.builder.boxSize,l=c/2;G_.call(this,n,r,(n,r)=>{if(!r){let[t,r]=[W.High,W.Low].map(e=>this.dataAt(e,n)),i=this.colors[0],u=this.colors[1],d=this.dataAt(W.BARKIND,n),f=mg(d),p=d===z.BARKIND_XO,m=d===z.BARKIND_OX;if(P(t,r))for(let n=t;n>=r;n-=c){let c=s.adjust(o),[d,h]=[c-a,c+a],[g,_,v]=[n,n-l,n+l].map(e=>this.priceToY(e)),y=n===t&&p||n===r&&m?!f:f;e.beginPath(),y?(e.strokeStyle=u,e.moveTo(d,_),e.lineTo(h,v),e.moveTo(d,v),e.lineTo(h,_)):(e.strokeStyle=i,e.ellipse(c,g,a,_-g,0,0,Math.PI*2)),e.stroke()}}o+=t.totalWidth}),s.epilog(e)}function vv(e,{bar:t,slice:n,start:r},i){e.fillStyle=i;let[a,o]=this.fields,s=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,c=[];if(G_.call(this,n,r,(e,n)=>{if(!n){let t=this.dataAt(a,e),n=this.dataAt(o,e);P(t,n)&&c.push({x:s,upY:this.priceToY(t),downY:this.priceToY(n)})}s+=t.totalWidth}),c.length>0){e.beginPath(),e.moveTo(c[0].x,c[0].upY);for(let t=1;t<c.length;++t)e.lineTo(c[t].x,c[t].upY);let t=c.length-1;e.lineTo(c[t].x,c[t].downY);for(let n=t-1;n>=0;--n)e.lineTo(c[n].x,c[n].downY);e.closePath(),e.fill()}}function yv(e,{bar:t,slice:n,start:r}){let[i,a]=this.fields,o=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,s=[],c=t=>{if(s.length>1){e.beginPath(),e.fillStyle=t,e.moveTo(s[0].x,s[0].upY);for(let t=1;t<s.length;++t)e.lineTo(s[t].x,s[t].upY);let n=s.length-1;e.lineTo(s[n].x,s[n].downY);for(let t=n-1;t>=0;--t)e.lineTo(s[t].x,s[t].downY);e.closePath(),e.fill()}},l=null,u=null;G_.call(this,n,r,(e,n)=>{if(!n){let t=this.dataAt(i,e),n=this.dataAt(a,e);if(P(t,n)){let r=this.priceToY(t),i=this.priceToY(n);u=this.getColor(e),l!==u&&(c(l),s.length>0&&(s=[s.pop()]),l=u),s.push({x:o,upY:r,downY:i})}}o+=t.totalWidth}),c(u)}function bv(e,{bar:t,slice:n,start:r,range:[i,a]},o,s){if(s){let t=e.createLinearGradient(0,i,0,a);t.addColorStop(0,o),t.addColorStop(1,Ta(o,0)),e.fillStyle=t}else e.fillStyle=o;e.beginPath();let c=null,l=this.pickMainField(),u=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,d=!1,f=null;G_.call(this,n,r,(n,r)=>{if(!r){let t=this.dataAt(l,n);if(P(t)){let n=this.priceToY(t);d?e.lineTo(u,n):(e.moveTo(c=u,n),d=!0),f=u}}u+=t.totalWidth}),e.lineTo(f,a),e.lineTo(c,a),e.closePath(),e.fill()}function xv(e,{open:t,close:n,change:r},i){let a=i.length>2&&e!==h.HLC,o=P(t,n),s=o&&n>t,c=o&&n===t,l=r>0,u=r===0;return{useSame:a,isUp:s,isSame:c,isUpPrev:l,isSamePrev:u,isDown:!s&&!c,isDownPrev:!l&&!u}}function Sv(e){let t=e.duplicate(),n=e;return`disableStreamingUpdates`in n&&(t.disableStreamingUpdates=n.disableStreamingUpdates),`surrogate`in n&&(t.surrogate=n.surrogate),t}var Cv=class e{symbol;aggregation;range;seriesKind;cacheMe;barsToFetch;offset;chartId;curveStyle;extendedHours;fields=[];alwaysUseBarsToFetch;inputs=[];splits;padded;constructor(e,t,n=w.Normal,r=[null,null]){this.symbol=e,this.aggregation=t,this.range=r,this.seriesKind=n,this.cacheMe=!1,this.barsToFetch=0,this.offset=0,this.chartId=null,this.curveStyle=null,this.alwaysUseBarsToFetch=!1,this.splits=!0,this.padded=!1}getBuilderKey(){if(!P(this.curveStyle)||!z.SPECIAL_BUILDER_REQUIRED.includes(this.curveStyle))return`Standard`;switch(this.curveStyle){case h.Renko:{let{method:e,period:t,source:n,brickSize:r}=wh(this.inputs);return`Renko;${e===`ATR`?`ATR;${t}`:`${e};${r}`};${n}`}case h.Kagi:{let{method:e,period:t,reversal:n}=og(this.inputs);return`Kagi;${e===`ATR`?`ATR;${t}`:`User;${n}`}`}case h.PointAndFigure:{let{method:e,period:t,reversal:n,boxSize:r,source:i,oneStepBack:a}=hg(this.inputs);return`PointAndFigure;${e===`ATR`?`ATR;${t}`:`User;${r}`};${i};${n};${a}`}case h.LineBreak:{let{lineBreak:e}=cg(this.inputs);return`LineBreak;${e}`}default:return h[this.curveStyle]}}get needsExtraKey(){return[w.Options,w.BalanceSheet,w.IncomeStatement].includes(this.seriesKind)}getExtraKey(){return this.needsExtraKey&&this.fields.length>0?`${this.fields.map(e=>e.id).join(`;`)}`:``}getHashKey(){let e=this.aggregation.getHashKey(),t=this.getBuilderKey(),n=this.getExtraKey(),r=this.extendedHours??!1;return`${this.symbol}|${e}|${r}|${this.range}|${this.seriesKind}|${this.offset}|${t}|${this.splits}|${this.padded}|${n}`}duplicate(){let t=new e(this.symbol,this.aggregation.duplicate(),this.seriesKind,this.range);return t.cacheMe=this.cacheMe,t.barsToFetch=this.barsToFetch,t.alwaysUseBarsToFetch=this.alwaysUseBarsToFetch,t.offset=this.offset,t.chartId=this.chartId,t.curveStyle=this.curveStyle,t.extendedHours=this.extendedHours,t.fields=F(this.fields),t.splits=this.splits,t.padded=this.padded,t}},wv=c(o(((e,t)=>{(function(n,r){var i={};n.PubSub?(i=n.PubSub,console.warn(`PubSub already loaded, using existing version`)):(n.PubSub=i,r(i)),typeof e==`object`?(t!==void 0&&t.exports&&(e=t.exports=i),e.PubSub=i,t.exports=e=i):typeof define==`function`&&define.amd&&define(function(){return i})})(typeof window==`object`&&window||e||global,function(e){var t={},n=-1,r=`*`;function i(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1}function a(e){return function(){throw e}}function o(e,t,n){try{e(t,n)}catch(e){setTimeout(a(e),0)}}function s(e,t,n){e(t,n)}function c(e,n,r,i){var a=t[n],c=i?s:o,l;if(Object.prototype.hasOwnProperty.call(t,n))for(l in a)Object.prototype.hasOwnProperty.call(a,l)&&c(a[l],e,r)}function l(e,t,n){return function(){var i=String(e),a=i.lastIndexOf(`.`);for(c(e,e,t,n);a!==-1;)i=i.substr(0,a),a=i.lastIndexOf(`.`),c(e,i,t,n);c(e,r,t,n)}}function u(e){var n=String(e);return!!(Object.prototype.hasOwnProperty.call(t,n)&&i(t[n]))}function d(e){for(var t=String(e),n=u(t)||u(r),i=t.lastIndexOf(`.`);!n&&i!==-1;)t=t.substr(0,i),i=t.lastIndexOf(`.`),n=u(t);return n}function f(e,t,n,r){e=typeof e==`symbol`?e.toString():e;var i=l(e,t,r);return d(e)?(n===!0?i():setTimeout(i,0),!0):!1}e.publish=function(t,n){return f(t,n,!1,e.immediateExceptions)},e.publishSync=function(t,n){return f(t,n,!0,e.immediateExceptions)},e.subscribe=function(e,r){if(typeof r!=`function`)return!1;e=typeof e==`symbol`?e.toString():e,Object.prototype.hasOwnProperty.call(t,e)||(t[e]={});var i=`uid_`+String(++n);return t[e][i]=r,i},e.subscribeAll=function(t){return e.subscribe(r,t)},e.subscribeOnce=function(t,n){var r=e.subscribe(t,function(){e.unsubscribe(r),n.apply(this,arguments)});return e},e.clearAllSubscriptions=function(){t={}},e.clearSubscriptions=function(e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0&&delete t[n]},e.countSubscriptions=function(e){var n,r,i=0;for(n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0){for(r in t[n])i++;break}return i},e.getSubscriptions=function(e){var n,r=[];for(n in t)Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0&&r.push(n);return r},e.unsubscribe=function(n){var r=typeof n==`string`&&(Object.prototype.hasOwnProperty.call(t,n)||function(e){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0)return!0;return!1}(n)),i=!r&&typeof n==`string`,a=typeof n==`function`,o=!1,s,c,l;if(r){e.clearSubscriptions(n);return}for(s in t)if(Object.prototype.hasOwnProperty.call(t,s)){if(c=t[s],i&&c[n]){delete c[n],o=n;break}if(a)for(l in c)Object.prototype.hasOwnProperty.call(c,l)&&c[l]===n&&(delete c[l],o=!0)}return o}})}))(),1);function Tv(e,t,n){return new Ev(e,t,n)}var Ev=class{calculable=!0;container;innerLookup;policy;exprSymbols;valueSymbols=[];onlyForTimeline;recalcTriggers;crashedComputationReported=!1;isLoading=!1;_sourceFields;_targetFields;basisChangedToken=null;quoteGroupToken=null;constructor(e,t,n){this.exprModel=e,this.innerSeries=t,this.container=null,this.innerLookup=t.reduce((e,t)=>(e[n.mapper(t)]=t,e),{}),this.policy=n,this.exprSymbols=Du(e),this.valueSymbols=this.exprSymbols.filter(e=>this.innerLookup[e]===void 0),this.onlyForTimeline=j(this.symbols,this.exprSymbols),this.recalcTriggers=new Set(t)}refresh(){this.innerSeries.forEach(e=>e.refresh())}get canLoadMoreData(){return this.policy.loadMoreData&&this.innerSeries.some(e=>e.canLoadMoreData)}async loadMoreData(e=!0){if(this.isLoading)return Promise.resolve();this.isLoading=!0;let t=this.innerSeries.filter(e=>e.canLoadMoreData).map(t=>t.loadMoreData(e));await Promise.all(t),this.isLoading=!1}get isExprInError(){return!P(this.exprModel)}get hasData(){return this.container!==null}get sourceFields(){return this._sourceFields||=Array.from(this.policy.fieldMap.keys()),this._sourceFields}get targetFields(){return this._targetFields||=Array.from(this.policy.fieldMap.values()),this._targetFields}async ready(){return Ai.call(this,async()=>{this.basisChangedToken=wv.default.subscribe(G.TS_ALL,this.onBasisChanged.bind(this)),this.quoteGroupToken=wv.default.subscribe(G.RT_QUOTEGROUP,this.onQuoteGroup.bind(this));let e=this.innerSeries.map(e=>e.ready());this.policy.valueProvider!==void 0&&e.push(this.policy.valueProvider.ready());let t=(await Promise.all(e)).every(ue);return t&&this.calculate(),t})}shouldTriggerOurRecalc(e){return this.recalcTriggers.has(e)}onQuoteGroup(e,t){t.source===this.policy.valueProvider&&this.innerSeries.every(e=>P(e.container))&&this.calculateCommon(G.TS_MANYCHANGED)}onBasisChanged(e,t){if(this.policy.recompute===d.Manual||e===G.TS_EVENTSCHANGED||e===G.TS_LOADING||!this.shouldTriggerOurRecalc(t.series)||this.innerSeries.some(e=>!P(e.container)))return;let n=this.policy.mapper(t.series);if(!(e===G.TS_DATAPOINTCHANGED&&this.onlyForTimeline?.includes(n)))switch(this.policy.recompute===d.Everything?G.TS_MANYCHANGED:e){case G.TS_MANYCHANGED:this.calculate();break;case G.TS_DATAPOINTCHANGED:case G.TS_DATAPOINTADDED:this.recalculate(e===G.TS_DATAPOINTADDED);break;case G.TS_TIMELINECORRECTION:case G.TS_QUOTEMARKER:break;default:throw Error(`Unknown time series message, likely forgot to handle it`)}}shutdown(){this.basisChangedToken&&wv.default.unsubscribe(this.basisChangedToken),this.quoteGroupToken&&(wv.default.unsubscribe(this.quoteGroupToken),this.policy.valueProvider?.shutdown())}calculateAt(e){return e.isNull?null:this.sourceFields.map((t,n)=>t===W.Volume?pe(this.exprSymbols.map(t=>e.inn[t].values[n]??0)):Cu(this.exprModel,t=>e.oneValue[t]??e.inn[t]?.values[n]??null))}pickMainField(){let e=null;for(let t of this.policy.fieldMap.values())if(e==null)e=t;else if(t===W.Close){e=t;break}return e}calculateLastChange(){let e=this.container,t=e.size;if(t<=1)return;let n=this.pickMainField(),r=e.getData(n)[t-2],i=e.getData(n)[t-1];P(r,i)&&e.setLastDataPoint(W.Change,i-r)}calculateDataPoint(e,t){let n=this.calculateAt(e);if(n===null)return;e.atLeastOne=!0;let[r,i]=Ee(n,0,3);n[1]=i,n[2]=r,this.targetFields.forEach((e,r)=>{let i=n[r];t?this.container.addDataPoint(e,i):this.container.setLastDataPoint(e,i)}),t&&(this.container.addDataPoint(W.Change,null),this.container.addDataPoint(W.DateTime,new Date(e.timeStamp))),this.calculateLastChange()}notify(e){Ge(e,{series:this,index:this.container.size-1})}fieldValueAt(e,t,n){let r=this.innerLookup[e].container.getData(n);return t<0||t>=r.length?null:r[t]}timeStampAt(e,t){return this.fieldValueAt(e,t,W.DateTime)}timeline(e){return e.container.getData(W.DateTime)}getRangeHelper(){switch(this.policy.missing){case u.UseNext:case u.UseNone:return Math.min;case u.UsePrevious:return Math.max;default:throw Error(`Unknow missing bar policy, likely forgot to implement it.`)}}getRange(){let e=this.getRangeHelper();return{begin:new Date(e(...this.symbols.map(e=>Se(this.timeline(this.innerLookup[e]))))),end:new Date(e(...this.symbols.map(e=>xe(this.timeline(this.innerLookup[e])))))}}getFirstPos(){return this.getPos(this.getRange().begin)}getLastPos(){return this.getPos(this.getRange().end)}findIndex(e,t){let n=this.timeline(this.innerLookup[e]);switch(this.policy.missing){case u.UseNext:case u.UseNone:return n.findIndex(e=>e.valueOf()>=t.valueOf());case u.UsePrevious:return Ce(n,e=>e.valueOf()<=t.valueOf());default:throw Error(`Unknow missing bar policy, likely forgot to implement it.`)}}checkPos(e){let t=Object.keys(e.inn).length;e.isNull=Object.values(e.inn).some(e=>!P(e.timeStamp)&&(!this.policy.stretch(e.symbol)||t===1))}fillPosSymbolAt(e,t,n){e.index=t,e.timeStamp=this.timeStampAt(e.symbol,t);let r=(this.policy.missing===u.UseNone||this.policy.skipLeadingEmpty&&!n.atLeastOne)&&e.timeStamp&&e.timeStamp.valueOf()!==n.timeStamp.valueOf();return e.values=this.sourceFields.map(n=>r?null:this.fieldValueAt(e.symbol,t,n)),e}skippable(e){return this.innerLookup[e].container.isEmpty?this.policy.noDataApproach===f.IgnoreTimelineOnly&&this.onlyForTimeline.includes(e)||this.policy.noDataApproach===f.ModelTransformRequired:!1}get symbols(){let e=Object.keys(this.innerLookup);return P(this.onlyForTimeline)?e.filter(e=>!this.skippable(e)):e}getPos(e){let t={isNull:!0,inn:{},timeStamp:e,atLeastOne:!1,oneValue:{}};return this.symbols.length===0?t:(this.symbols.forEach(n=>{let r=this.findIndex(n,e),i={symbol:n,index:-1,timeStamp:new Date(0),values:[]};t.inn[n]=this.fillPosSymbolAt(i,r,t)}),this.valueSymbols.forEach(e=>{t.oneValue[e]=this.policy.valueProvider?.getValue(e)??null}),this.checkPos(t),t)}getInner(e){return Object.values(e.inn)}moveNext(e){e.isNull||(this.getInner(e).forEach(t=>{for(;P(t.timeStamp)&&t.timeStamp.valueOf()<=e.timeStamp.valueOf();)this.fillPosSymbolAt(t,t.index+1,e)}),this.checkPos(e),e.isNull||(e.timeStamp=new Date(Math.min(...this.getInner(e).filter(e=>e.timeStamp!==null).map(e=>e.timeStamp.valueOf()))),this.policy.missing===u.UsePrevious?this.getInner(e).forEach(t=>{let n=P(t.timeStamp);(n&&t.timeStamp.valueOf()>e.timeStamp.valueOf()||!n&&this.policy.stretch(t.symbol))&&this.fillPosSymbolAt(t,t.index-1,e)}):this.policy.missing===u.UseNone&&this.getInner(e).forEach(t=>this.fillPosSymbolAt(t,t.index,e))))}shouldAdd(e){let t=this.container?.getLastDataPoint(W.DateTime),n=e?.timeStamp;return P(t,n)?t.valueOf()<n.valueOf():!1}calculateCommon(e=null,t=null,n=!0){try{if(t)this.calculateDataPoint(t,n);else if(this.container=this.makeContainer(),!this.isExprInError){let e=this.getFirstPos();for(;!e.isNull;)this.calculateDataPoint(e,!0),this.moveNext(e)}e&&this.notify(e)}catch(e){this.crashedComputationReported||=(I(e,`error`),!0)}}calculate(){let{yes:e,no:t}=A(this.innerSeries,e=>!e.container.isEmpty);if(t.length>0&&this.policy.noDataApproach===f.ModelTransformRequired){let n=e=>e.map(this.policy.mapper),r=this.policy.modelTransform(n(e),n(t));r!==null&&(this.exprModel=r)}this.calculateCommon(G.TS_MANYCHANGED)}recalculate(e){if(this.isExprInError)return;let t=this.getLastPos(),n=this.shouldAdd(t);this.calculateCommon(n?G.TS_DATAPOINTADDED:G.TS_DATAPOINTCHANGED,t,n)}recalculateAt(e,t,n){return this.recalculate(n)}makeContainer(){return new bh([W.DateTime,W.Change].concat(this.targetFields))}getCacheableEntities(e){this.innerSeries.forEach(t=>{t.getCacheableEntities(e)})}};function Dv(e){if(!(e instanceof Ev)||e.innerSeries.length!==1||e.exprSymbols.length!==1||e.valueSymbols.length!==0)return e;let t=e.innerSeries[0],n=t.query;return!P(n)||!nt(n,`surrogate`)?e:t}function Ov(e){let{query:t}=e;return t!==void 0&&`duplicate`in t&&`getBuilderKey`in t}function kv(e,t,n){if(!(e instanceof Ev))return n(e);if(e.valueSymbols.length!==0)return new xg;let r=e.innerSeries.map(n);return new Ev(e.exprModel,r,{...e.policy,fieldMap:new Map([[t,t]])})}function Av(e,t){return kv(e,t,e=>e)}function jv(e,t){let n=Dv(e);if(!Ov(n))return new xg;let r=Sv(n.query);if(r.symbol===z.PLACEHOLDER_SYMBOL_NAME||r.getBuilderKey()!==`Standard`)return new xg(r);{r.barsToFetch!==0&&(r.barsToFetch*=z.SERVER_COMPUTED_STUDY_BAR_MULTIPLIER);let e=t(r);return e.serverComputedSeries=!0,e}}function Mv(e,t,n){return kv(e,t,e=>jv(e,n))}function K(e){return new Ld(e,v.Number,b.Study,e)}var q=class{calcCtx;container;_source;target;inputs;outFields;studyFields={};innerSeries;calculable=!0;useNotifications=!1;initialNotification=!1;computedServerSide=!1;id;usedAsStyle=!1;recalcTriggers=new Set;basisChangedToken=null;_canLoadMoreData=!1;isLoading=!1;query;aggregation;sourceNeedsCompute=!1;allowEmptyValues=!1;constructor(e,...t){this.container=this._source=null,this.inputs=e.inputs,this.setOptions(e),this.innerSeries=t,this.id=bt(),this.addRecalcTrigger(...t)}refresh(){}get canLoadMoreData(){return this._canLoadMoreData}set canLoadMoreData(e){this._canLoadMoreData=e}loadMoreData(e){throw Error(`Should not be called.`)}addInner(...e){this.innerSeries.push(...e),this.addRecalcTrigger(...e)}isCalculable(e){return e.calculable??!1}addRecalcTrigger(...e){for(let t of e)this.isCalculable(t)?t.recalcTriggers.forEach(e=>this.recalcTriggers.add(e)):this.recalcTriggers.add(t)}setOptions(e){ut(this,e),nt(e,`source`)&&(this.source=e.source??null);let t=e.outFields??[e.target];this.studyFields=this.helpers.concat(t).reduce((e,t)=>(e[t.id]=t,e),{})}get helpers(){return z.EMPTY_ARRAY}get hasData(){return this.container!==null}get source(){if(P(this._source))return this._source;let e=P(this.inputs)?this.inputs[z.INPUT_SOURCE]:null;return P(e)?W[e]:null}set source(e){this._source=e}async ready(){return Ai.call(this,async()=>{this.basisChangedToken=this.useNotifications?wv.default.subscribe(G.TS_ALL,this.onBasisChanged.bind(this)):null;let e={tag:bt(),src:null},t=(await Promise.all(this.innerSeries.map(e=>e.ready()))).every(ue);return t&&this.calculate(e),t})}shouldTriggerOurRecalc(e){return this.recalcTriggers.has(e)}onBasisChanged(e,t){if(e===G.TS_EVENTSCHANGED||e===G.TS_LOADING||this.innerSeries.some(e=>!e.hasData)||!this.shouldTriggerOurRecalc(t.series)||this.base===null||this===t.series)return;let n={tag:bt(),src:t.series};switch(e){case G.TS_MANYCHANGED:this.calculate(n);break;case G.TS_DATAPOINTCHANGED:case G.TS_DATAPOINTADDED:{let r=this.innerSeries[this.baseIndex].calculable?this.base.size-1:t.index;this.recalculateAt(n,r,e===G.TS_DATAPOINTADDED);break}case G.TS_TIMELINECORRECTION:case G.TS_QUOTEMARKER:break;default:throw Error(`Unknown time series message, likely forgot to handle it`)}}shutdown(){this.useNotifications&&this.basisChangedToken&&wv.default.unsubscribe(this.basisChangedToken)}get baseIndex(){return 0}get base(){return this.innCont(this.baseIndex)}get period(){return this.inputs?.Period}calculateAt(e){return null}calculateDataPoint(e,t){let n=this.calculateAt(e);n!==null&&Object.keys(n).forEach(e=>{let r=n[e],i=this.studyFields[e];t?this.container.addDataPoint(i,r):this.container.setLastDataPoint(i,r)})}notify(e,t){Ge(e,{series:this,index:t})}calculateCommon(e,t=null,n=-1,r=!0){let i=n===-1,a=i?t=>{(P(e.src)||!P(t.calcCtx))&&t.calculate(e)}:t=>t.recalculateAt(e,n,r);if(!(this.base===null||this.calcCtx&&this.calcCtx.tag===e.tag||this===e.src)){if(this.calcCtx=e,this.innerSeries.filter(e=>this.isCalculable(e)&&!e.usedAsStyle).forEach(e=>a(e)),i&&(this.container=this.makeContainer()),this.calculateAt!==void 0)if(!i)this.calculateDataPoint(n,r);else{let e=this.base.size;for(let t=0;t<e;++t)this.calculateDataPoint(t,!0)}t&&(P(e.src)||this.initialNotification)&&this.notify(t,n)}}calculate(e){this.calculateCommon(e,G.TS_MANYCHANGED,-1,!0)}recalculateAt(e,t,n){this.computedServerSide||(!n&&N(this.container)&&t>this.container.size-1&&(t=this.container.size-1),this.calculateCommon(e,n?G.TS_DATAPOINTADDED:G.TS_DATAPOINTCHANGED,t,n))}baseVal(e,t){return this.base.getData(e)[t]}innCont(e){return this.innerSeries[e].container}innVal(e,t,n){let r=this.innCont(e),i=r.size;return n<0||n>i-1?null:r.getData(t)[n]}innHasData(e){let t=this.innCont(e);return P(t)&&t.size>0}wrap(...e){return e.reduce((e,t)=>(e[t.f.id]=t.g,e),{})}wrapBaseFields(...e){return e.map(this.wrapBaseField,this)}wrapInner(e,t){return{f:e,g:()=>this.innCont(t).getData(e)}}wrapBaseField(e){return this.wrapInner(e,this.baseIndex)}get defaultWrappers(){return this.wrapBaseFields(W.DateTime,W.Symbol)}makeContainer(){let e=this.defaultWrappers.concat(this.getWrappers());return new Sh(Object.keys(this.studyFields).map(e=>this.studyFields[e],this),this.wrap(...e))}getWrappers(){return[]}atLeast(e,t){return e>=t-1}exactly(e,t){return e==t-1}past(e,t,n,r=this.base){let i=r?.getData(n);return Array.isArray(i)?i.slice(e-t+1,e+1):[]}getCacheableEntities(e){this.innerSeries.forEach(t=>{t.getCacheableEntities(e)})}},Nv=class extends q{constructor(e,...t){super(e,...t),this.usedAsStyle=!0}get actual(){return this.innerSeries[0]}get canLoadMoreData(){return this.actual.canLoadMoreData}async loadMoreData(e=!0){return this.actual.loadMoreData(e)}get record(){return this.actual.record}},Pv=class extends Nv{constructor(e,t){super(e,t),this.query=t.query,this.useNotifications=!0}calculateAt(e){let[t,n,r,i]=[W.Open,W.High,W.Low,W.Close].map(t=>this.baseVal(t,e),this),a=null,o=null,s=null,c=null,l=me([t,n,r,i]);if(e<1)a=me([t,i]),o=n,s=r,c=0;else{let[t,i]=[W.Open,W.Close].map(t=>this.container.getData(t)[e-1],this);a=me([t,i]),o=Math.max(n,a,l),s=Math.min(r,a,l),c=l-i}return{[W.Open.id]:a,[W.High.id]:o,[W.Low.id]:s,[W.Close.id]:l,[W.Change.id]:c}}getWrappers(){return this.wrapBaseFields(W.Volume,W.OpenInterest,W.TradingDay)}},Fv=class extends q{constructor(e,t){super(e,t),SE(this)}calculateAt(e){let t=null,n=this.period,[,r]=CE(this);if(this.atLeast(e,n)&&r.hasField(this.source)){let i=this.past(e,n,this.source,r);this.allowEmptyValues?t=me(i.filter(de)):k(i)&&(t=me(i))}return{[this.target.id]:t}}getWrappers(){return this.source===W.Volume?this.wrapBaseFields(W.Volume,W.TradeSize,W.Change,W.Open,W.Close):[]}},Iv=class extends q{multiplier;constructor(e,t,n){super(e,t),this.multiplier=n(this.period),SE(this)}calculateAt(e){let t=null,[n,r]=CE(this);if(this.atLeast(e,2)&&r.hasField(this.source)){let i=this.container.getData(this.target)[e-1];if(i!==null)t=(this.innVal(n,this.source,e)-i)*this.multiplier+i;else{let n=this.period;if(this.atLeast(e,n)){let i=this.past(e,n,this.source,r);this.allowEmptyValues?t=me(i.filter(de)):k(i)&&(t=me(i))}}}return{[this.target.id]:t}}},Lv=class extends Iv{constructor(e,t){super(e,t,e=>2/(e+1))}},Rv=class extends Iv{constructor(e,t){super(e,t,e=>1/e)}},zv=class extends q{constructor(e,t){super(e,t);let n=J(t,this.inputs.Period1,W.High,W.MAHI),r=J(t,this.inputs.Period2,W.Low,W.MALO);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.MAHI,1),this.wrapInner(W.MALO,2)]}},Bv=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,n=W.OpenInterest;return this.base.hasField(n)&&(t=this.baseVal(n,e)),{[n.id]:t}}},Vv=class extends Bv{constructor(e,t){super(e,t)}getWrappers(){return this.wrapBaseFields(W.Volume,W.TradeSize,W.Change,W.Open,W.Close)}},Hv=class extends Bv{constructor(e,t){super(e,Av(t,W.OpenInterest))}getWrappers(){return this.wrapBaseFields(W.TradeSize,W.Change)}},Uv={inField:W.MA,outFields:[W.ENVU,W.ENVD],func:J},Wv={inField:W.EMA,outFields:[W.ENVEXPU,W.ENVEXPD],func:Y},Gv={inField:W.SMA,outFields:[W.ENVSMOU,W.ENVSMOD],func:YT},Kv=class extends q{kind;perc;constructor(e,t,n){super(e,n),this.kind=t,this.perc=this.inputs.Percent/100;let r=t.func(n,this.inputs.Period,e.source);this.addInner(r)}calculateAt(e){let t=null,n=null,r=this.innVal(1,this.kind.inField,e);if(r!==null){let e=r*this.perc;t=r+e,n=r-e}return{[this.kind.outFields[0].id]:t,[this.kind.outFields[1].id]:n}}},qv=class extends Kv{constructor(e,t){super(e,Uv,t)}},Jv=class extends Kv{constructor(e,t){super(e,Wv,t)}},Yv=class extends Kv{constructor(e,t){super(e,Gv,t)}},Xv=class extends q{constructor(e,t){super(e,t);let n=J(t,this.inputs.Period,this.source),r=J(n,this.inputs.Period,W.MA,W.TMA);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.TMA,2)]}},Zv=class extends q{triangle;constructor(e,t){super(e,t);let n=this.period;this.triangle=n*(n+1)/2,SE(this)}weightedAverage(e){let t=e.length;if(t===0)return null;let n=t===this.period?this.triangle:t*(t+1)/2;return e.reduce((e,t,n)=>e+t*(n+1),0)/n}calculateAt(e){let t=null,n=this.period,[,r]=CE(this);if(this.atLeast(e,n)){let i=this.past(e,n,this.source,r);this.allowEmptyValues?t=this.weightedAverage(i.filter(de)):k(i)&&(t=this.weightedAverage(i))}return{[this.target.id]:t}}},Qv=class extends q{constructor(e,t){super(e,t);let n=J(t,this.inputs.Period1,this.source),r=J(t,this.inputs.Period2,this.source),i=Z(this.target,(e,t,n)=>t-n,n,r);this.addInner(i)}getWrappers(){return[this.wrapInner(this.target,1)]}},$v={fields:[W.MACD,W.MACDS,W.MACDH],avgFunc:J,mapFunc:yE,histogramVaryColor:!0},ey={fields:[W.MACD,W.MACDS,W.MACDH],avgFunc:Y,mapFunc:yE,histogramVaryColor:!0},ty={fields:[W.MACD,W.CTLTM,W.CTM],avgFunc:Y,mapFunc:yE,histogramVaryColor:!1},ny={fields:[W.MACD,W.CTLTMF,W.CPMI],avgFunc:Y,mapFunc:yE,histogramVaryColor:!1},ry={fields:[W.PPO,W.PPOS,W.PPOH],avgFunc:Y,mapFunc:bE,histogramVaryColor:!0},iy={fields:[W.PVO,W.PVOS,W.PVOH],avgFunc:Y,mapFunc:bE,histogramVaryColor:!1},ay=class extends q{histogramVaryColor=!1;histogramField;get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=-1;if(this.histogramVaryColor&&e>0){let n=this.container.getData(this.histogramField)[e],r=this.container.getData(this.histogramField)[e-1];if(P(n,r)){let i=n<=0;t=i?1:3,e>0&&(i&&n>r&&(t=0),!i&&n<r&&(t=2))}}return{[W.BARCOLIX.id]:t}}},oy=class extends ay{fields;constructor(e,t,n){super(e,n),this.fields=t.fields,this.histogramVaryColor=t.histogramVaryColor,this.histogramField=this.fields[2];let r=t.avgFunc(n,e.inputs.Period1,e.source,void 0),i=t.avgFunc(n,e.inputs.Period2,e.source,void 0),a=Z(this.fields[0],t.mapFunc,r,i),o=t.avgFunc(a,e.inputs.Period3,a.target,this.fields[1]),s=Z(this.fields[2],yE,a,o);this.addInner(a,o,s)}getWrappers(){return[this.wrapInner(this.fields[0],1),this.wrapInner(this.fields[1],2),this.wrapInner(this.fields[2],3)]}},sy=class extends ay{constructor(e,t){super(e,t),this.histogramVaryColor=!0,this.histogramField=W.MACDVH;let n=DE(e,`EMA`,`Average`),r=n(t,e.inputs.Period1,e.source,void 0),i=n(t,e.inputs.Period2,e.source,void 0),a=iE(t,e.inputs.Period2,e.inputs.Average),o=Z(W.MACDV,(e,t,n,r)=>(t-n)/r*100,r,i,a),s=n(o,e.inputs.Period3,o.target,W.MACDVS),c=Z(W.MACDVH,yE,o,s);this.addInner(o,s,c)}getWrappers(){return[this.wrapInner(W.MACDV,1),this.wrapInner(W.MACDVS,2),this.wrapInner(W.MACDVH,3)]}},cy=class extends oy{constructor(e,t){super(e,$v,t)}},ly=class extends oy{constructor(e,t){super(e,ey,t)}},uy=class extends oy{constructor(e,t){e.inputs={Period1:5,Period2:21,Period3:34},super(e,ty,t)}},dy=class extends oy{constructor(e,t){e.inputs={Period1:3,Period2:5,Period3:8},super(e,ny,t)}},fy=class extends oy{constructor(e,t){super(e,ry,t)}},py=class extends oy{constructor(e,t){super(e,iy,t)}},my=K(`_AVG_GAIN`),hy=K(`_AVG_LOSS`),gy=class extends q{isModified;constructor(e,t){super(e,t),this.isModified=e.inputs.Modified}get helpers(){return[my,hy]}gain(e,t){return t[e]>t[e-1]?t[e]-t[e-1]:0}loss(e,t){return t[e]<t[e-1]?t[e-1]-t[e]:0}calculateAt(e){let t=null,n=null,r=null,i=this.period;if(this.atLeast(e,i+1)){if(this.container.getData(this.target)[e-1]!==null&&!this.isModified){let t=this.container.getData(my)[e-1],a=this.container.getData(hy)[e-1],o=this.past(e,2,this.source),s=this.gain(1,o),c=this.loss(1,o);n=(t*(i-1)+s)/i,r=(a*(i-1)+c)/i}else{let t=this.past(e,i+1,this.source);if(k(t)){let e=he(1,i),a=e.map(e=>this.gain(e,t)),o=e.map(e=>this.loss(e,t));n=me(a),r=me(o)}}n!==null&&r!==null&&(t=100-100/(1+n/r))}return{[my.id]:n,[hy.id]:r,[this.target.id]:t}}},_y=class extends q{constructor(e,t,n){super(e,n);let r=lE(n,this.inputs.Period,this.source,W.RSI,t),i=DE(e,`MA`,`Average`)(r,this.inputs.PeriodAvg,W.RSI,W.RSIAVG);this.addInner(r,i)}getWrappers(){return[this.wrapInner(W.RSI,1),this.wrapInner(W.RSIAVG,2)]}},vy=class extends _y{constructor(e,t){super(e,!1,t)}},yy=class extends _y{constructor(e,t){super(e,!0,t)}},by=class extends q{constructor(e,t){super(e,t);let n=lE(t,this.inputs.Period,this.source),r=this.inputs.Range,i=X(W.STORSI,function(e){let t=null;if(this.atLeast(e,r)){let n=this.past(e,r,W.RSI,this.base),i=Ee(n),a=i[0],o=i[1];t=(xe(n)-a)/(o-a)}return{[W.STORSI.id]:t}},n),a=DE(e,`MA`,`Average`),o=this.inputs.PeriodAvg,s=a(i,o,W.STORSI,W.STORSIAVG);this.addInner(i,s)}getWrappers(){return[this.wrapInner(W.STORSI,1),this.wrapInner(W.STORSIAVG,2)]}},xy=class extends q{constructor(e,t){super(e,t);let n=$T(t,this.inputs.Period1,W.High,W.HH,!0),r=$T(t,this.inputs.Period2,W.Low,W.LL,!1);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.HH,1),this.wrapInner(W.LL,2)]}},Sy=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,[n,r,i]=[W.Close,W.High,W.Low].map(t=>this.baseVal(t,e));return t=(2*n+r+i)/4,{[this.target.id]:t}}},Cy=class extends q{highest;index;constructor(e,t,n,r){super(e,r),this.highest=t,this.index=n}calculateAt(e){let t=null,n=this.inputs.Period;if(this.atLeast(e,n)){let r=this.past(e,n,this.source);k(r)&&(t=this.highest?Math.max(...r):Math.min(...r),this.index&&(t=n-r.indexOf(t)-1))}return{[this.target.id]:t}}},wy=class extends q{toHighest;field;highField;lowField;constructor(e,t,n){super(e,n),this.toHighest=t;let r=P(e.source),i=e.source;this.field=r?i:W.Close,this.highField=r?i:W.High,this.lowField=r?i:W.Low;let a=$T(n,e.inputs.Period,this.highField,W.HH,!0),o=$T(n,e.inputs.Period,this.lowField,W.LL,!1);this.addInner(a,o)}calculateAt(e){let t=null,n=this.baseVal(this.field,e),r=this.innVal(1,W.HH,e),i=this.innVal(2,W.LL,e);if(k([n,r,i])){let e=this.toHighest?r:i,a=r-i;a!==0&&(t=(n-e)/a*100)}return{[this.target.id]:t}}},Ty=class extends wy{constructor(e,t){super(e,!0,t)}},Ey=K(`RawPercK`),Dy=class extends q{kField;constructor(e,t,n,r){super(e,r);let i=eE(r,this.inputs.Period1,t?Ey:n,!1),a=DE(e,`MA`),o=a(i,this.inputs.Period2,i.target,t?n:W.PercD),s=t?a(o,this.inputs.Period3,o.target,W.PercD):o;this.kField=n,t?this.addInner(o,s):this.addInner(i,o)}getWrappers(){return[this.wrapInner(this.kField,1),this.wrapInner(W.PercD,2)]}},Oy=class extends Dy{constructor(e,t){super(e,!1,W.PercK,t)}},ky=class extends Dy{constructor(e,t){super(e,!0,W.PercK,t)}},Ay=class extends Dy{constructor(e,t){e.inputs={Period1:5,Period2:3,Period3:3},super(e,!0,W.CTPI,t)}};function jy(e,t,n,r,i){if(i===null)return null;let a=e*i,o=r+a,s=r-a;switch(t){case W.BOLLBU:return o;case W.BOLLBL:return s;case W.BOLLBW:return(o-s)/r*100;default:return null}}var My=class extends q{kind;constructor(e,t,n){super(e,n),this.kind=t;let r=this.inputs.Period,i=this.source,a=J(n,r,i,W.BOLLBM),o=t===`Modified`,s=dE(o?tE(n,i):n,r,o?W.PCTCHG:i),c=this.inputs.Width,l=e=>ce(jy,c,e),u=Z(W.BOLLBU,l(W.BOLLBU),a,s),d=Z(W.BOLLBL,l(W.BOLLBL),a,s),f=Z(W.BOLLBW,l(W.BOLLBW),a,s),p=DE(e,`MA`,`Average`),m=this.inputs.PeriodAvg,h=p(f,m,W.BOLLBW,W.BOLLBWA);this.addInner(a,s,u,d,f,h)}calculateAt(e){let t=this.innVal(3,W.BOLLBU,e),n=this.innVal(4,W.BOLLBL,e),r=this.innVal(1,W.BOLLBM,e),i=this.innVal(5,W.BOLLBW,e),a=this.innVal(6,W.BOLLBWA,e),o=null,s=this.baseVal(this.source,e);switch(P(t,n,s)&&(o=(s-n)/(t-n)),this.kind){case`Regular`:return{[W.BOLLBU.id]:t,[W.BOLLBL.id]:n,[W.BOLLBM.id]:r};case`Width`:return{[W.BOLLW.id]:t-n};case`Percent`:return{[W.BOLLP.id]:o};case`BandWidth`:return{[W.BOLLBW.id]:i,[W.BOLLBWA.id]:a};case`Modified`:{let t=null,n=null,i=null,a=null,o=this.innVal(2,W.MSD,e);if(P(o)){let e=this.inputs.MultInside,s=this.inputs.MultOutside;t=r+e*o,i=r-e*o,n=r+s*o,a=r-s*o}return{[W.MBBUI.id]:t,[W.MBBLI.id]:i,[W.MBBUO.id]:n,[W.MBBLO.id]:a,[W.MBBM.id]:r}}default:return null}}},Ny=class extends My{constructor(e,t){super(e,`Regular`,t)}},Py=class extends My{constructor(e,t){super(e,`Width`,t)}},Fy=class extends My{constructor(e,t){super(e,`Percent`,t)}},Iy=class extends My{constructor(e,t){super(e,`BandWidth`,t)}},Ly=class extends My{constructor(e,t){super(e,`Modified`,t)}},Ry=class extends q{constructor(e,t){super(e,t);let n=X(W.OBVOL,function(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Volume,e),i=this.baseVal(W.Close,e-1),a=this.container.getData(this.target)[e-1];P(a)||(a=0),t=n>i?a+r:n<i?a-r:a}return{[this.target.id]:t}},t),r=DE(e,`MA`,`Average`),i=this.period,a=r(n,i,W.OBVOL,W.OBVOLAVG);this.addInner(n,a)}getWrappers(){return[this.wrapInner(W.OBVOL,1),this.wrapInner(W.OBVOLAVG,2)]}},zy=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,n=this.baseVal(W.High,e),r=this.baseVal(W.Low,e);if(e>0){let i=this.baseVal(W.Close,e-1);t=Math.max(n-r,Math.abs(n-i),Math.abs(r-i))}else t=n-r;return{[this.target.id]:t}}},By=K(`_ABS_CHG`),Vy=K(`_MA_ABS_CHG`),Hy=K(`_CHG`),Uy=class extends q{constructor(e,t){super(e,t);let n=rE(t,W.TR),r=DE(e,`SMA`)(n,this.inputs.Period,W.TR,this.target),i=J(r,this.inputs.Period2,W.ATR,W.ATRMA);this.addInner(r,i)}getWrappers(){return[this.wrapInner(this.target,1),this.wrapInner(W.ATRMA,2)]}},Wy=class extends q{constructor(e,t){super(e,t);let n=X(By,se((e,t)=>{let n=0;return t>0&&(n=this.baseVal(e,t)-this.baseVal(e,t-1)),{[By.id]:Math.abs(n)}},this.source),t),r=DE(e,`MA`)(n,this.inputs.Period,By,Vy),i=Z(W.ADJATR,(e,t)=>2*t,r);this.addInner(i)}getWrappers(){return[this.wrapInner(W.ADJATR,1)]}},Gy=class extends q{constructor(e,t){super(e,t);let n=X(Hy,e=>{let t=0;return e>0&&(t=this.baseVal(W.Close,e)-this.baseVal(W.Close,e-1)),{[Hy.id]:t}},t),r=kE(e),i=this.inputs.Period,a=this.inputs.Smoothing,o=r(t,i,a),s=Z(this.target,(e,t,n)=>!P(t)||!P(n)?null:t/n,n,o);this.addInner(s)}getWrappers(){return[this.wrapInner(this.target,1)]}},Ky=K(`_PDM`),qy=K(`_MDM`),Jy=K(`_TRS`),Yy=K(`_PDS`),Xy=K(`_MDS`),Zy=K(`_DX`),Qy=class extends q{useEma;adxField;multiplier;constructor(e,t,n,r){super(e,r),this.useEma=t,this.adxField=n,this.multiplier=2/(this.inputs.AdxSmoothing+1);let i=rE(r,W.TR);this.addInner(i)}get helpers(){return[Ky,qy,Jy,Yy,Xy,Zy]}sum(e,t,n,r){let i=null;if(this.atLeast(e-1,r-1)){let a=this.past(e-1,r-1,t,this.container);a.push(n),k(a)&&(i=a.reduce((e,t,n)=>e+t,0))}return i}smooth1(e,t,n,r){let i=null,a=this.inputs.DiLength,o=this.container.getData(n)[e-1];return i=o===null?this.sum(e,t,r,a):o-o/a+r,i}smooth2(e,t,n,r){let i=this.container.getData(n)[e-1],a=this.inputs.AdxSmoothing;if(i!==null)return this.useEma?(r-i)*this.multiplier+i:(i*(a-1)+r)/a;{let n=this.sum(e,t,r,a);if(n!==null)return n/a}return null}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;if(e>0){let u=this.past(e,2,W.High),d=this.past(e,2,W.Low),f=Math.max(u[1]-u[0],0),p=Math.max(d[0]-d[1],0);t=f>p?f:0,n=p>f?p:0;let m=this.container.getData(W.TR)[e];i=this.smooth1(e,Ky,Yy,t),a=this.smooth1(e,qy,Xy,n),r=this.smooth1(e,W.TR,Jy,m),(i>0||a>0)&&r!==0&&(o=i/r*100,s=a/r*100,c=100*Math.abs(o-s)/(o+s),l=this.smooth2(e,Zy,this.adxField,c))}return{[Ky.id]:t,[qy.id]:n,[Jy.id]:r,[Yy.id]:i,[Xy.id]:a,[W.PDI.id]:o,[W.MDI.id]:s,[Zy.id]:c,[this.adxField.id]:l}}getWrappers(){return[this.wrapInner(W.TR,1)]}},$y=class extends Qy{constructor(e,t){super(e,!1,W.ADX,t)}},eb=class extends Qy{constructor(e,t){super(e,!0,W.ADXM,t)}},tb=class extends q{constructor(e,t){super(e,t);let n=uE(t);this.addInner(n)}calculateAt(e){let t=null;return t=(e>0?this.container.getData(this.target)[e-1]:0)+this.innVal(1,W.MFMUL,e),{[this.target.id]:t}}},nb=class extends q{constructor(e,t){super(e,t);let n=X(W.ADWM,function(e){let t=null,n=null;if(e>0){let r=this.baseVal(W.Close,e-1),i=Math.max(r,this.baseVal(W.High,e)),a=Math.min(r,this.baseVal(W.Low,e)),o=this.baseVal(W.Close,e);t=o>r?o-a:o<r?o-i:0,e>1&&(n=(e>2?this.container.getData(W.ADWM)[e-1]:0)+t)}return{[W.ADWM.id]:n}},t),r=J(n,this.inputs.Period,W.ADWM,W.ADWMMA);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.ADWM,1),this.wrapInner(W.ADWMMA,2)]}},rb=class extends q{constructor(e,t){super(e,t);let n=W.ADL,r=oE(t,n),i=Y(r,3,n),a=Y(r,10,n),o=Z(e.target,(e,t,n)=>t-n,i,a);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},ib=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null;return t=me([W.Close,W.High,W.Low].map(t=>this.baseVal(t,e))),{[this.target.id]:t}}},ab=class extends q{calculateAtFunc;constructor(e,t,...n){super(e,...n),this.calculateAtFunc=t}calculateAt(e){let t=this.innerSeries.map((t,n)=>{let r=t,i=r.target;return P(i)||(i=r.container.hasField(W.Close)?W.Close:r.container.fields[0]),this.innVal(n,i,e)}),n=null;return k(t)&&(n=this.calculateAtFunc(e,...t)),{[this.target.id]:n}}};function ob(e,t){let n=this.baseVal(W.High,t),r=this.baseVal(W.Low,t);return{[e.id]:(n+r)/2}}function sb(e,t){let n=this.baseVal(W.High,t),r=this.baseVal(W.Low,t);return{[e.id]:n-r}}var cb=class extends q{calculateAtFunc;constructor(e,t,n){super(e,n),this.calculateAtFunc=t}calculateAt(e){return this.calculateAtFunc.call(this,e)}},lb=K(`_RANGE`),ub=K(`_MOV_RANGE`),db={fields:[W.KCUP,W.KCLOW,W.KCMID],midSeries:e=>sE(e,W.TP),midTarget:W.TP,rangeSeries:e=>X(lb,se(sb,lb),e),rangeTarget:lb,func:`MA`,useMultiplier:!1},fb={fields:[W.KBUP,W.KBLOW,W.KBMID],midSeries:e=>e,midTarget:W.Close,rangeSeries:e=>rE(e,W.TR),rangeTarget:W.TR,func:`EMA`,useMultiplier:!0},pb=class extends q{kind;constructor(e,t,n){super(e,n),this.kind=t;let r=t.midSeries(n),i=DE(e,t.func,`Average`),a=i(r,this.inputs.Period,t.midTarget,t.fields[2]),o=i(t.rangeSeries(n),this.inputs.Period,t.rangeTarget,ub);this.addInner(a,o)}calculateAt(e){let t=this.innVal(1,this.kind.fields[2],e),n=this.innVal(2,ub,e),r=t!==null&&n!==null,i=this.kind.useMultiplier?this.inputs.Multiplier:1;return{[this.kind.fields[0].id]:r?t+n*i:null,[this.kind.fields[1].id]:r?t-n*i:null}}getWrappers(){return[this.wrapInner(this.kind.fields[2],1)]}},mb=class extends pb{constructor(e,t){super(e,db,t)}},hb=class extends pb{constructor(e,t){super(e,fb,t)}},gb=class extends q{isWidth;constructor(e,t,n){super(e,n),this.isWidth=t;let r=$T(n,this.inputs.Period,W.High,W.DONUP,!0),i=$T(n,this.inputs.Period,W.Low,W.DONLOW,!1);this.addInner(r,i)}calculateAt(e){let t=this.innVal(1,W.DONUP,e),n=this.innVal(2,W.DONLOW,e),r=t===null&&n===null;return this.isWidth?{[W.DONW.id]:r?null:t-n}:{[W.DONMID.id]:r?null:(t+n)/2}}getWrappers(){return[this.wrapInner(W.DONUP,1),this.wrapInner(W.DONLOW,2)]}},_b=class extends gb{constructor(e,t){super(e,!1,t)}},vb=class extends gb{constructor(e,t){super(e,!0,t)}},yb=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Volume,e),i=this.baseVal(W.Close,e-1),a=this.container.getData(this.target)[e-1];P(a)||(a=0);let o=(n-i)/i*r;t=a+o}return{[this.target.id]:t}}},bb=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,this.source),r=Y(n,this.inputs.Period,n.target),i=Y(r,this.inputs.Period,r.target),a=cE(i,1,i.target,this.target);this.addInner(a)}getWrappers(){return[this.wrapInner(this.target,1)]}},xb=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,this.source),r=Y(n,this.inputs.Period,n.target),i=Z(W.DEMA,(e,t,n)=>2*t-n,n,r);this.addInner(i)}getWrappers(){return[this.wrapInner(W.DEMA,1)]}},Sb=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period1,this.source),r=Y(t,this.inputs.Period2,this.source),i=Z(W.EOSC,(e,t,n)=>t-n,n,r);this.addInner(i)}getWrappers(){return[this.wrapInner(W.EOSC,1)]}},Cb=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,this.source),r=Y(n,this.inputs.Period,n.target),i=Y(r,this.inputs.Period,r.target),a=Z(W.TEMA,(e,t,n,r)=>3*(t-n)+r,n,r,i);this.addInner(a)}getWrappers(){return[this.wrapInner(W.TEMA,1)]}},wb=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n+1)){let r=this.baseVal(this.source,e-n);r!==null&&r!==0&&(t=(this.baseVal(this.source,e)-r)/r*100)}return{[this.target.id]:t}}},Tb=class extends q{constructor(e,t){super(e,t);let n=sE(t,W.PVPT);this.addInner(n)}calculateAt(e){let t=this.innVal(1,W.PVPT,e),n=this.baseVal(W.High,e),r=this.baseVal(W.Low,e);return{[W.PVPTR.id]:t+n-r,[W.PVPTS.id]:t-n+r}}getWrappers(){return[this.wrapInner(W.PVPT,1)]}},Eb=K(`_HIND`),Db=K(`_LIND`),Ob=class extends q{constructor(e,t,n){super(e,n),this.justWidth=t,this.justWidth=t;let r=this.inputs.Period,i=$T(n,r,W.High,Eb,!0,!0),a=$T(n,r,W.Low,Db,!1,!0);this.addInner(i,a)}calculateAt(e){let t=null,n=null,r=null,i=this.innVal(1,Eb,e),a=this.innVal(2,Db,e);if(i!==null&&a!==null){let e=this.period;t=(e-i)/e*100,n=(e-a)/e*100,r=t-n}return this.justWidth?{[W.ARNOSC.id]:r}:{[W.ARNUP.id]:t,[W.ARNLOW.id]:n}}},kb=class extends Ob{constructor(e,t){super(e,!1,t)}},Ab=class extends Ob{constructor(e,t){super(e,!0,t)}},jb=class extends q{constructor(e,t){super(e,t);let n=e.inputs.Range===`Close`,r=jE(t);if(!n&&r){let e=X(W.TCHNUP,(e,t)=>null,t),n=X(W.TCHNLOW,(e,t)=>null,t);this.addInner(e,n)}else{let r=$T(t,e.inputs.PeriodUpper,n?W.Close:W.High,W.TCHNUP,!0),i=$T(t,e.inputs.PeriodLower,n?W.Close:W.Low,W.TCHNLOW,!1);this.addInner(r,i)}}getWrappers(){return[this.wrapInner(W.TCHNUP,1),this.wrapInner(W.TCHNLOW,2)]}},Mb=class extends q{constructor(e,t){super(e,t);let n=mE(t,e.inputs.Period,e.inputs.Range);this.addInner(n)}calculateAt(e){let t=null,n=this.innVal(1,W.TCHNUP,e),r=this.innVal(1,W.TCHNLOW,e),i=this.inputs.Adjustment,a=this.inputs.Retracement;return a===`Long`?t=P(n)?n-i:null:a===`Short`&&(t=P(r)?r+i:null),{[this.target.id]:t}}},Nb=K(`_MIDPOINT`),Pb=class extends q{constructor(e,t){super(e,t);let n=X(Nb,se(ob,Nb),t),r=YT(n,e.inputs.Period1,Nb,W.ALJAW),i=YT(n,e.inputs.Period2,Nb,W.ALTEETH),a=YT(n,e.inputs.Period3,Nb,W.ALLIPS);this.addInner(r,i,a)}calculateAt(e){return{[W.ALJAW.id]:this.innVal(1,W.ALJAW,e),[W.ALTEETH.id]:this.innVal(2,W.ALTEETH,e),[W.ALLIPS.id]:this.innVal(3,W.ALLIPS,e)}}},Fb=class extends q{constructor(e,t){super(e,t)}calculateAt(e){return{[W.PLTLN.id]:this.inputs.Position}}},Ib=K(`_MIDPOINT`),Lb=class extends q{constructor(e,t){super(e,t);let n=X(Ib,se(ob,Ib),t),r=J(n,this.inputs.Period1,Ib),i=J(n,this.inputs.Period2,Ib),a=Z(W.AWOS,(e,t,n)=>t-n,r,i),o=J(a,this.inputs.Period3,a.target,W.AWOSMA);this.addInner(a,o)}getWrappers(){return[this.wrapInner(W.AWOS,1),this.wrapInner(W.AWOSMA,2)]}},Rb=class extends q{multiplyVol;constructor(e,t,n){super(e,n),this.multiplyVol=t}calculateAt(e){let[t,n,r,i]=[W.High,W.Low,W.Close,W.Volume].map(t=>this.baseVal(t,e)),a=t===n?0:(r-n-(t-r))/(t-n);return this.multiplyVol&&(a*=i),{[this.target.id]:a}}},zb=class extends Rb{constructor(e,t){super(e,!1,t)}},Bb=class extends Rb{constructor(e,t){super(e,!0,t)}},Vb=class extends q{constructor(e,t){super(e,t);let n=uE(t);this.addInner(n)}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,W.Volume),i=this.past(e,n,W.MFMUL,this.innCont(1));if(k(r)&&k(i)){let e=pe(r);e!==0&&(t=pe(i)/e)}}return{[this.target.id]:t}}},Hb=K(`_RANGE`),Ub=class extends q{constructor(e,t){super(e,t);let n=cE(Y(X(Hb,se(sb,Hb),t),this.inputs.Period1,Hb),this.inputs.Period2,W.EMA,this.target);this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}},Wb=class extends q{shift;constructor(e,t){super(e,t);let n=this.inputs.Period;this.shift=Math.floor(n/2)+1;let r=J(t,n,e.source);this.addInner(r)}calculateAt(e){let t=null,n=this.shift,r=this.innVal(1,W.MA,e-n);return r!==null&&(t=this.baseVal(this.source,e)-r),{[this.target.id]:t}}},Gb=K(`_MATP`),Kb=class extends q{constructor(e,t){super(e,t);let n=sE(t),r=J(n,this.inputs.Period,n.target,Gb);this.addInner(n,r)}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,W.TP,this.innCont(1));if(k(r)){let n=this.innVal(2,Gb,e);if(n!==null){let i=r.reduce((e,t,r)=>e+Math.abs(n-t),0)/this.period;t=(this.innVal(1,W.TP,e)-n)/(.015*i)}}}return{[this.target.id]:t}}},qb=class extends q{constructor(e,t){super(e,t);let n=X(W.EMV,function(e){let t=null;if(e>0){let[n,r,i]=[W.High,W.Low,W.Volume].map(t=>this.baseVal(t,e)),[a,o]=[W.High,W.Low].map(t=>this.baseVal(t,e-1));t=((n+r)/2-(a+o)/2)/(i/1e6/(n-r))}return{[this.target.id]:t}},t),r=J(n,this.inputs.Period,W.EMV,W.EMVMA);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.EMV,1),this.wrapInner(W.EMVMA,2)]}},Jb=class extends q{isBull;constructor(e,t,n){super(e,n),this.isBull=t;let r=Y(n,this.inputs.Period,this.source);this.addInner(r)}calculateAt(e){let t=null,n=this.innVal(1,W.EMA,e);return n!==null&&(t=this.isBull?this.baseVal(W.High,e)-n:this.baseVal(W.Low,e)-n),{[this.isBull?W.ERBLPOW.id:W.ERBRPOW.id]:t}}},Yb=class extends Jb{constructor(e,t){super(e,!0,t)}},Xb=class extends Jb{constructor(e,t){super(e,!1,t)}},Zb=K(`_FORCE`),Qb=class extends q{constructor(e,t){super(e,t);let n=Y(X(Zb,function(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Volume,e);t=(n-this.baseVal(W.Close,e-1))*r}return{[this.target.id]:t}},t),this.inputs.Period,Zb,W.FI);this.addInner(n)}getWrappers(){return[this.wrapInner(W.FI,1)]}},$b=K(`_RANGE`),ex=K(`_EMA1`),tx=K(`_EMA2`),nx=K(`_RATIO`),rx=class extends q{constructor(e,t){super(e,t);let n=Y(X($b,se(sb,$b),t),9,$b,ex),r=Z(nx,(e,t,n)=>t/n,n,Y(n,9,ex,tx));this.addInner(r)}calculateAt(e){let t=null;if(this.atLeast(e,25)){let n=this.past(e,25,nx,this.innCont(1));k(n)&&(t=pe(n))}return{[this.target.id]:t}}},ix=class extends q{constructor(e,t){super(e,t);let n=this.inputs.Period,r=X(W.MOM,ce(TE,n,this.source),t),i=J(r,this.inputs.Movement,W.MOM,W.MOMMA);this.addInner(r,i)}getWrappers(){return[this.wrapInner(W.MOM,1),this.wrapInner(W.MOMMA,2)]}},ax=class extends q{constructor(e,t){super(e,t);let n=sE(t);this.addInner(n)}calculateAt(e){let t=null,n=this.period+1;if(this.atLeast(e,n)){let r=this.past(e,n,W.TP,this.innCont(1)),i=this.past(e,n,W.Volume).map(e=>e??0);if(k(r)&&k(i)){let e=0,a=0;for(let t=1;t<n;++t){let n=r[t]*i[t];r[t]>r[t-1]?e+=n:a+=n}t=100-100/(1+e/a)}}return{[this.target.id]:t}}},ox=class extends q{constructor(e,t){super(e,t),SE(this);let n=J(t,this.inputs.Period,this.source);this.addInner(n)}calculateAt(e){let t=null,[n,r]=CE(this),i=this.innVal(n+1,W.MA,e);if(i!==null){let n=this.inputs.Period,a=this.past(e,n,this.source,r);a=a.map(e=>(e-i)*(e-i)),t=Math.sqrt(me(a))}return{[this.target.id]:t}}getWrappers(){let[e]=CE(this);return[this.wrapInner(W.MA,e+1)]}},sx={isNegative:!1,fields:[W.PVI,W.PVIEMA]},cx={isNegative:!0,fields:[W.NVI,W.NVIEMA]},lx=class extends q{kind;constructor(e,t,n){super(e,n),this.kind=t;let r=X(this.kind.fields[0],se(function(e,t){let n=1e3;if(t>0){let r=[W.Close,W.Volume],[i,a]=r.map(e=>this.baseVal(e,t)),[o,s]=r.map(e=>this.baseVal(e,t-1)),c=this.container.getData(this.target)[t-1];n=(e?a<s:a>s)?c*((i-o)/o+1):c}return{[this.target.id]:n}},this.kind.isNegative),n),i=Y(r,this.inputs.Period,this.kind.fields[0],this.kind.fields[1]);this.addInner(r,i)}getWrappers(){return[this.wrapInner(this.kind.fields[0],1),this.wrapInner(this.kind.fields[1],2)]}},ux=class extends lx{constructor(e,t){super(e,cx,t)}},dx=class extends lx{constructor(e,t){super(e,sx,t)}},fx=K(`_LOGPC`),px=class extends q{constructor(e,t){super(e,t);let n=this.source??W.Close,r=Math.sqrt(AE(e.aggregation));if(r===0){let e=X(this.target,(e,t)=>null,t);this.addInner(e)}else{let i=function(e,t){let n=null;if(t>0){let r=this.baseVal(e,t),i=this.baseVal(e,t-1);r!==null&&i!==null&&(n=Math.log(r/i))}return{[fx.id]:n}},a=function(e,t){let n=null,r=this.baseVal(W.MSD,t);return r!==null&&(n=100*r*e),{[W.HV.id]:n}},o=dE(X(fx,se(i,n),t),e.inputs.Period,fx,W.MSD),s=X(W.HV,se(a,r),o);this.addInner(s)}}getWrappers(){return[this.wrapInner(this.target,1)]}},mx=class extends q{noOp;constructor(e,t){super(e,t),this.noOp=this.inputs.Anchor===`VisibleStart`}calculateAt(e){let t=null,n=this.baseVal(this.source,0),r=this.baseVal(this.source,e);return this.noOp?t=r:n!==null&&r!==null&&(t=(r-n)/n*100),{[this.target.id]:t}}},hx=K(`_SWING_INDEX`),gx=class extends q{constructor(e,t){super(e,t)}get helpers(){return[hx]}ohlcVals(e){return[W.Open,W.High,W.Low,W.Close].map(t=>this.baseVal(t,e))}obtainR(e,t,n,r){let i=Math.abs(e-r),a=Math.abs(t-r),o=Math.abs(e-t),s=Math.max(i,a,o),c=.25*Math.abs(r-n);return s===i?i-.5*a+c:s===a?a-.5*i+c:o+c}calculateAt(e){let t=null,n=null;if(e>0){let r=this.container.getData(hx)[e-1];P(r)||(r=0);let[i,a,o,s]=this.ohlcVals(e),[c,l,u,d]=this.ohlcVals(e-1);if(k([i,a,o,s,c,d])){let e=Math.max(Math.abs(a-d),Math.abs(o-d)),l=this.inputs.Limit,u=this.obtainR(a,o,c,d);t=50*((s-d+.5*(s-i)+.25*(d-c))/u)*(e/l),n=r+t}}return{[hx.id]:t,[this.target.id]:n}}},_x=K(`_MIN_CLOSE`),vx=K(`_MAX_CLOSE`),yx=class extends q{constructor(e,t){super(e,t);let n=iE(t,e.inputs.Period);this.addInner(n)}get helpers(){return[vx,_x]}calculateAt(e){let t=null,n=null,r=null,i=null,a=this.innVal(1,W.ATR,e);if(a!==null){let o=this.baseVal(W.Close,e),s=this.baseVal(W.Close,e-1),c=this.period;r=Math.max(...this.past(e,c,W.Close)),i=Math.min(...this.past(e,c,W.Close));let l=a*this.inputs.Constant;if(this.innVal(1,W.ATR,e-1)===null)o>s?t=r-l:n=i+l;else{let[a,s,c,u]=[W.WWVSARU,W.WWVSARD,vx,_x].map(t=>this.container.getData(t)[e-1]);r=c,i=u,a===null?o>s?(r=o,t=o-l):(i=Math.min(o,i),n=i+l):o<a?(i=o,n=o+l):(r=Math.max(o,r),t=r-l)}}return{[vx.id]:r,[_x.id]:i,[W.WWVSARU.id]:t,[W.WWVSARD.id]:n}}},bx=K(`_EP`),xx=K(`_AF`),Sx=K(`_POS`),Cx=1,wx=-1,Tx=class extends q{constructor(e,t){super(e,t)}get helpers(){return[bx,xx,Sx]}hlcVals(e){return[W.High,W.Low,W.Close].map(t=>this.baseVal(t,e))}me(e,t){return this.container.getData(e)[t]}reciprocal(e){return 1/e}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null;if(e>0){let[s,c,l]=this.hlcVals(e),[u,d,f]=this.hlcVals(e-1),p=this.reciprocal(this.inputs.Acceleration),m=this.reciprocal(this.inputs.Limit);if(e===1){a=l>f?Cx:wx;let e=a===Cx;o=e?d:u,r=e?Math.max(s,u):Math.min(c,d),i=p,e?t=o:n=o}else{let[l,f,h,g,_]=[Sx,W.PARSARS,W.PARSARL,bx,xx].map(t=>this.me(t,e-1)),v=l===Cx,y=v?h:f,b=_*Math.abs(g-y);a=v?y+b>c?wx:Cx:y-b<s?Cx:wx;let x=l===a;o=x?v?Math.min(y+b,d,this.baseVal(W.Low,e-2)):Math.max(y-b,u,this.baseVal(W.High,e-2)):g,r=x?v?Math.max(s,g):Math.min(c,g):a===Cx?s:c,i=_,x?(v?r>g:r<g)&&_<m&&(i=_+p):i=p,a===Cx?t=o:n=o}}return{[bx.id]:r,[xx.id]:i,[Sx.id]:a,[W.PARSARS.id]:n,[W.PARSARL.id]:t}}},Ex=class extends q{xSum;xSum2;x2Sum;constructor(e,t){super(e,t);let n=this.period;this.xSum=n*(n+1)/2,this.xSum2=this.xSum*this.xSum,this.x2Sum=n*(n+1)*(2*n+1)/6}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,this.source);if(k(r)){let e=pe(r),i=(n*pe(r.map((e,t)=>e*(t+1)))-this.xSum*e)/(n*this.x2Sum-this.xSum2);t=(e-i*this.xSum)/n+i*n}}return{[this.target.id]:t}}},Dx=K(`_IDY`),Ox=[0,0,0,1,1,1,5,5,2,1,1,0,50,50,0,1,1,1,5,0,0],kx=e=>Array(e).fill(0);function Ax(e,t){return Fx(e,t,10)}function jx(e,t){return Fx(e,t,13)}function Mx(e,t){return Fx(e,t,16)}function Nx(e,t){return Fx(e,t,4)}function Px(e,t){return Fx(e,t,7)}function Fx(e,t,n){let r=e[n-1];return t===0&&(r=e[n]),t<0&&(r=e[n+1]),r}function Ix(e,t,n,r,i){let a=i[18],o=r+1,s=0;for(let n=0;n<a;++n){let n=0,r=0;for(let i=1;i<6;++i){if(o--,e[o]==null)continue;let a=e[o]-t[o];i==1&&(n=r=a),a>n&&(n=a),a<r&&(r=a)}s=s+n-r}return s=s/a*Nx(i,n[r]),s}function Lx(e,t,n,r,i){let a=r,o=Px(i,n[r]),s=0;do a--,e[a]!=null&&s++;while(s<o&&a>0);return t[r]-t[a]}function Rx(e,t,n,r,i,a){let o=n;do o--;while(e[o]==null);return t[n]=t[o],e[n]>i&&t[o]<=0&&(t[n]=t[o]+1),e[n]<r&&t[o]>=0&&(t[n]=t[o]-1),a++,t[n]!==t[o]&&(a=1),a}function zx(e,t,n,r,i,a,o,s,c,l){let u=Ax(i,n[r]),d=jx(i,n[r]),f=Mx(i,n[r]),p=c+l+t[r]-e[r],m=100;i[20]>0&&(m=i[20]);let h=u*s/m;s>d&&(h=u*d/m);let g=l*2,_=e[r]+(p-g)-(p-g)*h,v=e[r]+(p-p*h),y=[a,o];return(s===1||f!==1||_>a)&&(y[0]=_),(s===1||f!==1||v<o)&&(y[1]=v),y}function Bx(e,t,n){let r=0,i=-1,a=0,o=1;for(let s=0;s<n;++s){if(t[s]=0,e[s]==null||(r++,r==21&&(o=2),r==31&&(o=3),a+=e[s]*o,r<40))continue;t[s]=a/70;let c=0,l=i+1;for(let t=l;t<n&&!(e[t]!=null&&(c++,c==1&&(i=t),(c==1||c==21||c==31)&&(a-=e[t]),c==31));++t);}}var Vx=class extends q{haveEnoughData=!1;firstUsefulIndex=0;s3;itr;constructor(e,t){super(e,t),this.s3=this.itr=[];let n=[`VelocityUpTrend`,`VelocitySideTrend`,`VelocityDownTrend`].map(t=>e.inputs[t]||`3`).map(Number);Ox.splice(6,3,...n)}get helpers(){return[Dx]}prepareComputation(){let e=this.base.getData(W.Close),t=0,n=0,r=e.length;for(;n<72&&t<r;)e[t]!=null&&n++,t++;this.haveEnoughData=t<r,this.firstUsefulIndex=t,this.s3=kx(r),this.itr=kx(r),this.haveEnoughData&&Bx(e,this.s3,r)}us(e,t){return this.container.getData(e)[t]}recalculateAt(e,t,n){let r=this.base.getData(W.Close),i=r.length;this.haveEnoughData&&Bx(r,this.s3,i),super.recalculateAt(e,t,n)}calculateAt(e){let t=null,n=null,r=null,i=t=>this.us(t,e-1);if(e===0)this.prepareComputation();else if(this.haveEnoughData&&e>=this.firstUsefulIndex&&this.baseVal(W.Close,e)!==null){let a=i(W.TRSP1),o=i(W.TRSP2);r=i(Dx),a===null&&o===null&&(a=o=this.baseVal(W.Close,this.firstUsefulIndex)),r===null&&(r=1);let s=this.base.getData(W.Close);r=Rx(s,this.itr,e,a,o,r);let c=Lx(s,this.s3,this.itr,e,Ox),l=Ix(s,this.s3,this.itr,e,Ox);[a,o]=zx(s,this.s3,this.itr,e,Ox,a,o,r,c,l),this.itr[e]>=0&&(t=a),this.itr[e]<=0&&(n=o)}return{[Dx.id]:r,[W.TRSP1.id]:t,[W.TRSP2.id]:n}}},Hx=class extends q{constructor(e,t){super(e,t),this.addInner(sE(t))}get helpers(){return[W.BARCOLIX]}getTarget(e){let t=this.baseVal(W.Close,e),n=this.innVal(1,W.TP,e);if(!P(t,n)||!this.atLeast(e,4))return null;let r=this.innVal(1,W.TP,e-3);return r===null?null:t+(n-r)/3}calculateAt(e){let t=null,n=this.getTarget(e);if(n!==null&&e>0){let r=this.container.getData(W.TARGP)?.[e-1];r!==null&&(t=n===r?this.container.getData(W.BARCOLIX)?.[e-1]??1:+(n>r))}return{[W.TARGP.id]:n,[W.BARCOLIX.id]:t}}},Ux=1,Wx=2,Gx=3,Kx={[Ux]:{param:`cot`,func:`parseCotLineChart`,fields:[W.DateTime,W.COTLCCMSP,W.COTLCLGSP,W.COTLCSMSP]},[Wx]:{param:`cotadv`,func:`parseDisaggregated`,fields:[W.DateTime,W.COTDAGPRO,W.COTDAGSPD,W.COTDAGMNM,W.COTDAGOTH]},[Gx]:{param:`cotfin`,func:`parseFinancialTradersReport`,fields:[W.DateTime,W.COTFTRDLI,W.COTFTRASM,W.COTFTRLVF,W.COTFTROTH]}},qx=class extends q{wrappers;constructor(e,t,n){super(e,jv(n,e=>new Jx(t,e))),this.computedServerSide=!0,this.initialNotification=!0,this.wrappers=Kx[t].fields.slice(1).map(e=>this.wrapInner(e,0))}getWrappers(){return this.wrappers}},Jx=class extends yg{kind;constructor(e,t){super(t),this.kind=e}getRetriever(){return new Yx(this.kind)}onStreamingUpdates(e){}},Yx=class extends Uh{kind;constructor(e){super(),this.kind=e}addExtraParams(e){e[Kx[this.kind].param]=`y`}getParser(e){return new Xx(e.symbol,e.aggregation,e.offset,this.kind)}},Xx=class extends Rh{kind;constructor(e,t,n,r){super(e,t,n),this.kind=r}makeContainer(){return new bh(Kx[this.kind].fields)}getParseFunc(){return this.aggregation.isEndOfDay?this[Kx[this.kind].func]:null}parseCotLineChart(e){this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.COTLCCMSP,parseInt(e[2])),this.container.addDataPoint(W.COTLCLGSP,parseInt(e[3])),this.container.addDataPoint(W.COTLCSMSP,parseInt(e[4]))}parseDisaggregated(e){this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.COTDAGPRO,parseInt(e[2])),this.container.addDataPoint(W.COTDAGSPD,parseInt(e[3])),this.container.addDataPoint(W.COTDAGMNM,parseInt(e[4])),this.container.addDataPoint(W.COTDAGOTH,parseInt(e[5]))}parseFinancialTradersReport(e){this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.COTFTRDLI,parseInt(e[2])),this.container.addDataPoint(W.COTFTRASM,parseInt(e[3])),this.container.addDataPoint(W.COTFTRLVF,parseInt(e[4])),this.container.addDataPoint(W.COTFTROTH,parseInt(e[5]))}},Zx=class extends qx{constructor(e,t){super(e,Ux,t)}},Qx=class extends qx{constructor(e,t){super(e,Wx,t)}},$x=class extends qx{constructor(e,t){super(e,Gx,t)}},eS={Day:[W.PreviousHigh,W.PreviousLow,W.PreviousClose],Week:[W.WeekPreviousHigh,W.WeekPreviousLow,W.WeekPreviousClose],Month:[W.MonthPreviousHigh,W.MonthPreviousLow,W.MonthPreviousClose]},tS=class extends q{disabled;record;streamingSubscription;constructor(e,t,n){if(super(e,n),this.disabled=!P(n.query)||!P(n.query.symbol),!this.disabled){let e=n.query.symbol;e.endsWith(`.BZ`)&&(e=e.slice(0,-3)),this.record=$().getRecordSource().getRecord(e),this.record.addFields(...t),this.streamingSubscription=this.getStreamingSubscription()}this.initialNotification=!0}getStreamingSubscription(){return $().getRecordSource().subject.pipe(Pp(e=>{let t=af(G.RT_QUOTE,this.record.symbol);return e.filter(t)}),Lp(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}async ready(){return Ai.call(this,async()=>P(this.record)?await this.record.ready()&&await super.ready():await super.ready(),`asyncReadyWork2`)}onStreamingUpdates(e){if(this.record){let e={tag:bt(),src:null};this.calculate(e)}}shutdown(){super.shutdown(),this.disabled||this.streamingSubscription.unsubscribe()}getValues(e){return eS[e].map(e=>this.record.getValue(e))}},nS=class extends tS{constructor(e,t){super(e,eS[e.inputs.Previous],t)}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null;if(!this.disabled){let e=this.getValues(this.inputs.Previous);if(k(e)){let[c,l,u]=e;t=(c+l+u)/3;let d=2*t;n=d-l,r=d-c;let f=c-l;i=t+f,a=t-f,o=c+2*(t-l),s=l-2*(c-t)}}return{[W.PPTPIV.id]:t,[W.PPTR1.id]:n,[W.PPTR2.id]:i,[W.PPTR3.id]:o,[W.PPTS1.id]:r,[W.PPTS2.id]:a,[W.PPTS3.id]:s}}},rS=class extends tS{constructor(e,t){super(e,eS.Day,t)}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null,c=null;if(!this.disabled){let e=this.getValues(`Day`);if(k(e)){let[l,u,d]=e,f=l-u,[p,m,h,g]=[2,4,6,12].map(e=>1.1/e*f);s=d+p,a=d+m,r=d+h,t=d+g,n=d-g,i=d-h,o=d-m,c=d-p}}return{[W.CPPH4.id]:s,[W.CPPH3.id]:a,[W.CPPH2.id]:r,[W.CPPH1.id]:t,[W.CPPL1.id]:n,[W.CPPL2.id]:i,[W.CPPL3.id]:o,[W.CPPL4.id]:c}}},iS=class extends q{constructor(e,t){super(e,Mv(t,W.IMPVOL,e=>new aS(e))),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return[this.wrapInner(W.IMPVOL,0)]}},aS=class extends yg{constructor(e){super(e)}getRetriever(){return Jr(this.query.symbol)?new lS:new oS}onStreamingUpdates(e){}},oS=class extends Uh{addExtraParams(e){e.impl=`y`}getParser(e){return new cS(e.symbol,e.aggregation,e.offset)}};function sS(){return new bh([W.DateTime,W.IMPVOL])}var cS=class extends Rh{constructor(e,t,n=0){super(e,t,n)}makeContainer(){return sS()}getParseFunc(){return this.parseImpVol}parseImpVol(e){!this.aggregation.isEndOfDay||e.length<9||(this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.IMPVOL,parseFloat(e[8])))}},lS=class extends Gh{emptyContainer(e,t){return sS()}get iterateForward(){return!1}getPageName(){return`getFuturesOptionsHistory`}processRow(e,t,n){n.addDataPoint(W.DateTime,ph(e.date.substring(0,10)));let r=N(e.impliedVolatility);n.addDataPoint(W.IMPVOL,r?e.impliedVolatility*100:null)}},uS=K(`_ABS_CHG`),dS=K(`_DS1_EMA1`),fS=K(`_DS1_EMA2`),pS=K(`_DS2_EMA1`),mS=K(`_DS2_EMA2`),hS=class extends q{constructor(e,t){super(e,t);let n=(e,t,n,r,i,a)=>Y(Y(e,t,n,r),i,r,a),r=X(uS,se((e,t)=>({[e.id]:Math.abs(this.baseVal(W.Change,t))}),uS),t),i=n(t,e.inputs.Period1,W.Change,dS,e.inputs.Period2,fS),a=n(r,e.inputs.Period1,uS,pS,e.inputs.Period2,mS),o=Z(W.TSI,(e,t,n)=>100*t/n,i,a),s=Y(o,e.inputs.Period3,W.TSI,W.TSISIG);this.addInner(o,s)}getWrappers(){return[this.wrapInner(W.TSI,1),this.wrapInner(W.TSISIG,2)]}},gS=class extends q{constructor(e,t){super(e,t);for(let n=1;n<=12;++n){let r=ME(e.inputs,n);this.addInner(Y(t,r,W.Close,e.outFields[n-1]))}}getWrappers(){return he(1,12).map(e=>this.wrapInner(this.outFields[e-1],e))}},_S=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,W.Close);this.addInner(n)}calculateAt(e){let t=null,n=e>0?this.container.getData(this.target)[e-1]:null,r=this.innVal(1,W.EMA,e);if(!N(n))t=r;else{let i=this.baseVal(this.source,e),a=(i/n)**4;t=n+(i-n)/(.6*this.period*a);let o=e=>Math.log10(Math.abs(e-t))>1,s=o(n)||o(r);(!Number.isFinite(t)||s)&&(t=null)}return{[this.target.id]:t}}},vS=K(`_DIFF`),yS=class extends q{constructor(e,t){super(e,t);let n=this.inputs.Period,r=Math.floor(n/2),i=this.allowEmptyValues,a=XT(Z(vS,(e,t,n)=>2*t-n,XT(t,r,this.source,W.WMA,i),XT(t,n,this.source,W.WMA,i)),Math.floor(Math.sqrt(n)),vS,this.target,i);this.addInner(a)}getWrappers(){return[this.wrapInner(this.target,1)]}},bS=K(`_SUM`),xS=class extends q{constructor(e,t){super(e,t);let n=XT(Z(bS,(e,t,n)=>t+n,cE(t,this.inputs.PeriodRocLong),cE(t,this.inputs.PeriodRocShort)),this.inputs.PeriodWma,bS,this.target);this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}},SS=K(`_ABS_CHG`),CS=K(`_HH_LL`),wS=K(`_MULMA`),TS=class extends q{constructor(e,t){super(e,t);let n=e.inputs.TurtleChnField===`Close`,r=e.inputs.Direction===`Long`,i=jE(t);if(!n&&i){let e=X(this.target,(e,t)=>null,t);this.addInner(e)}else{let e=J(X(SS,se((e,t)=>({[SS.id]:t>0?e*Math.abs(this.baseVal(W.Change,t)):null}),this.inputs.FactorATR),t),this.inputs.PeriodAdjATR,SS,W.MA),i=r?W.High:W.Low,a=$T(t,this.inputs.PeriodTurtleChn,n?W.Close:i,CS,r),o=Z(wS,(e,t)=>this.inputs.FactorAdjATR*t,e),s=r?-1:1,c=Z(this.target,(e,t,n)=>t+s*n,a,o);this.addInner(c)}}getWrappers(){return[this.wrapInner(this.target,1)]}},ES=class extends q{state;constructor(e,t){super(e,t),this.resetState()}resetState(){let e=this.inputs.ExtendLines??`None`;this.state={startIndex:null,endIndex:null,slope:null,intercept:null,stdDevWidth:null,extendLeft:e===`Left`||e===`Both`,extendRight:e===`Right`||e===`Both`}}calculateAt(e){let t=this.inputs.Period,n=this.inputs.Width,r=this.source;if(e===this.base.size-1&&this.base.size>=t){this.resetState();let e=t*(t+1)/2,i=e*e,a=t*(t+1)*(2*t+1)/6,o=0,s=0,c=1,l=this.base.size-t;for(let e=0;e<t;++e){let t=this.baseVal(r,l+e);if(!Ze(t))return{};o+=t,s+=c*t,c+=1}let u=(t*s-e*o)/(t*a-i),d=o/t-u*e/t;if(!Ze(u)||!Ze(d))return{};let f=0;for(let e=0;e<t;++e){let t=this.baseVal(r,l+e);if(!Ze(t))return{};let n=t-(d+u*(e+1));f+=n*n}let p=Math.sqrt(f/t);if(!Ze(p))return{};this.state.startIndex=l,this.state.endIndex=this.base.size-1,this.state.slope=u,this.state.intercept=d,this.state.stdDevWidth=n*p}return{}}getCurrentState(){return this.state}},DS=class extends q{computeDone;constructor(e,t){super(e,t,jv(t,e=>{let t=F(e);return t.symbol=ti(e.symbol),P(t.symbol)?new yg(t):new xg(t,!0)})),this.computedServerSide=!0,this.initialNotification=!0,this.computeDone=!1}alignCashTimelineWithUnderlying(){let e=this.innCont(0);if(!P(e)||e.size===0)return;let t=this.innCont(1),n=e.getTimeData(),r=t.getTimeData(),i=t.getData(W.Close),a=Array(n.length).fill(null);if(!(this.innerSeries[1]instanceof xg)){let o=0,s=e.size,c=t.size;for(let e=0;e<s;++e){for(;o<c&&r[o].getTime()<n[e].getTime();)o++;o<c&&r[o].getTime()===n[e].getTime()&&(a[e]=i[o])}}this.container.setData(this.target,a)}calculate(e){this.computeDone||(this.container=this.makeContainer(),this.alignCashTimelineWithUnderlying(),this.computeDone=!0,this.notify(G.TS_MANYCHANGED,-1))}},OS=class extends q{constructor(e,t){let n=pE(t);super(e,t,n)}shouldTriggerOurRecalc(e){return super.shouldTriggerOurRecalc(e)?!0:e===this.innerSeries[1]&&this.innHasData(0)&&this.innHasData(1)}calculateAt(e){let t=(t,n)=>P(this.innCont(t))?this.innVal(t,n,e):null,n=t(0,W.Close),r=t(1,W.CSHO);return{[this.target.id]:P(r)&&P(n)?r-n:null}}},kS=class extends q{computeDone;constructor(e,t){super(e,t,jv(t,e=>{let t=new Cv(e.symbol,new Vl(e.aggregation.unit===g.Year?g.Year:g.Quarter,1),w.BalanceSheet);return t.fields=[W.SharesOutstanding],t.cacheMe=!0,new wg(t)})),this.computedServerSide=!0,this.initialNotification=!0,this.computeDone=!1}alignFundamentalTimelineWithUnderlying(){let e=this.innCont(0);if(!P(e)||e.size===0)return;let t=this.innCont(1);if(!P(t)||t.size===0)return;let n=e.getTimeData(),r=t.getTimeData(),i=t.getData(W.SharesOutstanding),a=e.getData(W.Close),o=Array(n.length),s=0,c=e.size,l=t.size;for(let e=0;e<c;++e){let t=n[e].getTime();for(;s<l-1&&r[s+1].getTime()<=t;)s++;if(s<l&&r[s].getTime()<=t){let t=i[s],n=a[e];o[e]=P(t,n)?t*n:null}}this.container.setData(this.target,o)}calculate(e){this.computeDone||(this.container=this.makeContainer(),this.alignFundamentalTimelineWithUnderlying(),this.computeDone=!0,this.notify(G.TS_MANYCHANGED,-1))}},AS=class extends q{constructor(e,t){super(e,t),SE(this)}calculateAt(e){let t=null,[n]=CE(this);if(e>0){let r=this.innVal(n,this.source,e-1);r!==null&&(t=100*(this.innVal(n,this.source,e)-r)/r)}return{[this.target.id]:t}}},jS=class extends Nv{constructor(e,t){super(e,t),this.query=t.query,this.useNotifications=!0}calculateAt(e){let t=[null,null,null,null,null];if(e>0){let n=(e,t)=>this.baseVal(e,t),r=[W.Open,W.High,W.Low,W.Close],i=r.map(t=>n(t,e));if(k(i)){let a=r.map(t=>n(t,e-1));if(k(a)){t=i.map((e,t)=>100*(e-a[t])/a[t]);let[n,r]=Ee(t);if(t[1]=r,t[2]=n,e>1){let n=this.container.getData(W.Close)[e-1];t[4]=t[3]-n}}}}return{[W.Open.id]:t[0],[W.High.id]:t[1],[W.Low.id]:t[2],[W.Close.id]:t[3],[W.Change.id]:t[4]}}getWrappers(){return this.wrapBaseFields(W.Volume,W.OpenInterest,W.TradingDay)}},MS=K(`_DIST`),NS=K(`_EMA_DIST1`),PS=K(`_EMA_DIST2`),FS=K(`_DIFF`),IS=K(`_EMA_DIFF1`),LS=K(`_EMA_DIFF2`),RS=class extends q{constructor(e,t){super(e,t);let n=$T(t,e.inputs.Period1,W.High,W.HH,!0),r=$T(t,e.inputs.Period1,W.Low,W.LL,!1),i=Y(Y(Z(MS,(e,t,n)=>this.baseVal(W.Close,e)-(t+n)/2,n,r),e.inputs.Period2,MS,NS),e.inputs.Period2,NS,PS),a=Y(Y(Z(FS,(e,t,n)=>t-n,n,r),e.inputs.Period2,FS,IS),e.inputs.Period2,IS,LS),o=Z(W.STOMOMIX,(e,t,n)=>100*t/n,i,a);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},zS=K(`_CHG`),BS=K(`_M1`),VS=K(`_M2`),HS=class extends q{constructor(e,t){super(e,t);let n=X(zS,function(e){let t=W.Close,n=e>0?this.baseVal(t,e)-this.baseVal(t,e-1):0;return{[zS.id]:n}},t),r=(e,t)=>t>=0?t:0,i=(e,t)=>t>=0?0:-t,a=Z(BS,r,n),o=Z(VS,i,n);this.addInner(a,o)}perc(e,t){return 100*e/t}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n+1)){let r=this.past(e,n,BS,this.innCont(1)),i=this.past(e,n,VS,this.innCont(2));if(k(r)&&k(i)){let e=pe(r),n=pe(i);t=this.perc(e-n,e+n)}}return{[W.CHDMOMOSC.id]:t}}},US=class extends q{constructor(e,t){super(e,t);let n=new HS(e,t),r=DE(e,`MA`,`Average`),i=this.inputs.PeriodAvg,a=r(n,i,W.CHDMOMOSC,W.CHDMOMOSCAVG);this.addInner(n,a)}getWrappers(){return[this.wrapInner(W.CHDMOMOSC,1),this.wrapInner(W.CHDMOMOSCAVG,2)]}},WS=K(`_MAX`),GS=K(`_MIN`),KS=K(`_ISUPTREND`),qS=class extends q{constructor(e,t){super(e,t);let n=iE(t,e.inputs.Period);this.addInner(n)}get helpers(){return[WS,GS,KS]}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=1,c=this.baseVal(W.Close,e),l=(e,t)=>P(e)?e:t,u=e=>l(e,0),d=(e,t)=>this.container.getData(e)[t];e>0&&(r=Math.max(u(d(WS,e-1)),c),a=Math.min(u(d(GS,e-1)),c),s=d(KS,e-1));let f=this.inputs.Multiplier,p=this.innVal(1,W.ATR,e);if(P(p)){let l=s===1,u=l?r-f*p:a+f*p,m=d(l?W.VSTOPUP:W.VSTOPLOW,e-1);P(m)||(m=0);let h=l?Math.max(m,u):Math.min(m,u);o=+(c-h>=0);let g=o!=s;n=g?c:r,i=g?c:a,t=g?o===1?n-f*p:i+f*p:h}return{[W.VSTOPUP.id]:o===1?t:null,[W.VSTOPLOW.id]:o===1?null:t,[WS.id]:n,[GS.id]:i,[KS.id]:o}}},JS=K(`_TRENDUP`),YS=K(`_TRENDDOWN`),XS=K(`_TREND`),ZS=class extends q{constructor(e,t){super(e,t);let n=iE(t,e.inputs.Period);this.addInner(n)}get helpers(){return[JS,YS,XS,W.BARCOLIX]}calculateAt(e){let t=0,n=0,r=0,i=null,a=0,o=this.innVal(1,W.ATR,e);if(P(o)){let s=(e,t)=>P(e)?e:t,[c,l,u]=[W.Close,W.High,W.Low].map(t=>this.baseVal(t,e)),d=(l+u)/2,f=this.baseVal(W.Close,e-1),p=this.inputs.Multiplier,m=d-p*o,h=d+p*o,[g,_,v]=[JS,YS,XS].map(t=>this.container.getData(t)[e-1]);t=f>g?Math.max(m,g):m,n=f<_?Math.min(h,_):h,r=c>_?1:c<g?-1:s(v,1);let y=r===1;i=y?t:n,a=+!!y}return{[JS.id]:t,[YS.id]:n,[XS.id]:r,[W.SUPTR.id]:i,[W.BARCOLIX.id]:a}}},QS=class extends q{constructor(e,t){super(e,t);let n=e=>$T(t,e,W.Low,W.LL,!1),r=e=>$T(t,e,W.High,W.HH,!0),i=(e,t,n)=>Z(n,(e,t,n)=>(t+n)/2,e,t),a=(e,t)=>i(n(e),r(e),t),o=a(e.inputs.PeriodConversionLine,W.CONVLN),s=a(e.inputs.PeriodBaseLine,W.BASELN),c=i(o,s,W.LEADSP1),l=a(e.inputs.PeriodLaggingSpan2,W.LEADSP2);this.addInner(o,s,c,l)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=+(this.innVal(3,W.LEADSP1,e)>this.innVal(4,W.LEADSP2,e));return{[W.LAGGSP.id]:this.baseVal(W.Close,e),[W.BARCOLIX.id]:t}}getWrappers(){return[this.wrapInner(W.CONVLN,1),this.wrapInner(W.BASELN,2),this.wrapInner(W.LEADSP1,3),this.wrapInner(W.LEADSP2,4)]}},$S=K(`_CUM_PRICE`),eC=K(`_CUM_VOL`),tC=K(`_PER_CHG`),nC=class extends q{constructor(e,t){super(e,t);let n=this.source,r=X(n,se(wE,n),t);this.addInner(r)}valueAt(e,t){return this.container.getData(e)[t]}dateAt(e){return this.container.getTimeData()[e]}},rC=class extends nC{constructor(e,t){super(e,t)}get helpers(){return[$S,eC,tC]}isSame(e,t){switch(this.inputs.AnchorPeriod){case`Session`:default:return en(e,t);case`Week`:return jr(e,t);case`Month`:return Nr(e,t);case`Quarter`:return Pr(e,t);case`Year`:return Fr(e,t);case`Decade`:return lh(e,t);case`Century`:return uh(e,t)}}findPrevPeriodChange(e){for(let t=e;t>0;t--)if(this.valueAt(tC,t)===1)return t;return 0}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=e>0,s=o?this.dateAt(e-1):z.ZERO_DATE,c=this.dateAt(e),l=o&&this.isSame(s,c),u=l?this.valueAt($S,e-1):0,d=l?this.valueAt(eC,e-1):0,f=this.innVal(0,W.Volume,e),p=u+this.innVal(1,this.source,e)*f,m=d+f;if(t=p/m,l){let o=this.findPrevPeriodChange(e-1),s=this.container.getData(W.VWAP).slice(o,e);s.push(t);let c=me(s),l=s.map(e=>(e-c)*(e-c)),u=Math.sqrt(me(l)),d=this.inputs.Stdev1stMultiplier*u;n=t+d,r=t-d;let f=this.inputs.Stdev2ndMultiplier*u;i=t+f,a=t-f}else n=t,r=t,i=t,a=t;return{[$S.id]:p,[eC.id]:m,[tC.id]:+!l,[W.VWAP.id]:t,[W.VWAPSD1U.id]:n,[W.VWAPSD1L.id]:r,[W.VWAPSD2U.id]:i,[W.VWAPSD2L.id]:a}}},iC=class extends nC{constructor(e,t){super(e,t)}get helpers(){return[$S,eC]}isSameOhlcBar(e,t){let{unit:n,size:r}=this.aggregation;switch(n){case g.Tick:return e===t;case g.Intraday:return Dr(t,Ut(e,r));case g.Day:return Dr(t,jt(e,r));case g.Week:return jr(e,t);case g.Month:return Nr(e,t);case g.Quarter:return Pr(e,t);case g.Year:return Fr(e,t);default:throw Error(`Unexpected aggregation unit ${g[n]}`)}}calculateAt(e){let t=null,n=null,r=null,i=this.inputs.Anchor,a=this.dateAt(e);if(Dr(i,a)||this.isSameOhlcBar(a,i)){let i=e>0,a=i?this.valueAt($S,e-1):0,o=i?this.valueAt(eC,e-1):0,s=this.innVal(0,W.Volume,e);n=a+this.innVal(1,this.source,e)*s,r=o+s,t=n/r}return{[$S.id]:n,[eC.id]:r,[W.AVWAP.id]:t}}},aC=K(`_DIFF`),oC=[aC,W.Buy,W.Sell];function sC(e,t,n,r){let i=null,a=null,o=null;P(n,r)&&(o=n-r);let s=t>0?e.getData(aC)[t-1]:null;return P(o,s)&&(i=o>0&&s<=0?1:null,a=o<0&&s>=0?-1:null),{[aC.id]:o,[W.Buy.id]:i,[W.Sell.id]:a}}var cC=class extends q{constructor(e,t){super(e,t);let n=DE(e,`MA`,`Average`),r=n(t,e.inputs.Period1,this.source,W.MAS),i=n(t,e.inputs.Period2,this.source,W.MAL);this.addInner(r,i)}get helpers(){return oC}calculateAt(e){let t=this.innVal(1,W.MAS,e),n=this.innVal(2,W.MAL,e);return sC(this.container,e,t,n)}getWrappers(){return[this.wrapInner(W.MAS,1),this.wrapInner(W.MAL,2)]}},lC=class extends q{_maIndex;_maTarget;constructor(e,t){super(e,t),SE(this);let n=DE(e,`MA`,`Average`)(t,e.inputs.Period,this.source);this.addInner(n);let[r]=CE(this);this._maIndex=r+1,this._maTarget=n.target}get helpers(){return oC}calculateAt(e){let t=this.innVal(this._maIndex,this._maTarget,e),[,n]=CE(this),r=n.getData(this.source)[e],i=sC(this.container,e,r,t);return i[this.target.id]=t,i}},uC=K(`_PVM`),dC=K(`_NVM`),fC=class extends q{constructor(e,t){super(e,t);let n=function(e){return{[uC.id]:e>0?Math.abs(this.baseVal(W.High,e)-this.baseVal(W.Low,e-1)):null}},r=function(e){return{[dC.id]:e>0?Math.abs(this.baseVal(W.Low,e)-this.baseVal(W.High,e-1)):null}},i=X(uC,n,t),a=X(dC,r,t),o=rE(t,W.TR);this.addInner(i,a,o)}calculateAt(e){let t=null,n=null,r=this.period;if(this.atLeast(e,r)){let i=this.past(e,r,uC,this.innCont(1)),a=this.past(e,r,dC,this.innCont(2)),o=this.past(e,r,W.TR,this.innCont(3));if(k(i)&&k(a)&&k(o)){let e=pe(i),r=pe(a),s=pe(o);t=e/s,n=r/s}}return{[W.PLVI.id]:t,[W.MNVI.id]:n}}},pC=K(`_AVG`),mC=class extends q{isPercent;constructor(e,t){super(e,t);let n=DE(e,`MA`,`Average`),r=this.period,i=n(t,r,this.source,pC);this.isPercent=e.inputs.Distance===`Percentage`,this.addInner(i)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=null,n=null,r=this.innVal(1,pC,e),i=this.baseVal(this.source,e);if(r!=null&&r!==0){t=i-r,this.isPercent&&(t=100*t/r);let a=t<=0;if(n=a?1:3,e>0){let r=this.container.getData(this.target)[e-1];r!==null&&(a&&t>r&&(n=0),!a&&t<r&&(n=2))}}return{[this.target.id]:t,[W.BARCOLIX.id]:n}}},hC=class extends q{constructor(e,t){super(e,t);let n=Y(Y(lE(t,this.inputs.PeriodRsi,this.source,W.RSI),this.inputs.PeriodEma1,W.RSI,W.EMA),this.inputs.PeriodEma2,W.EMA,W.EMA),r=J(n,this.inputs.PeriodMa,W.EMA,W.MA),i=Z(W.DOSCH,(e,t,n)=>t-n,n,r),a=J(i,this.inputs.PeriodSig,W.DOSCH,W.DOSCS);this.addInner(i,a)}getWrappers(){return[this.wrapInner(W.DOSCH,1),this.wrapInner(W.DOSCS,2)]}},gC=class extends q{constructor(e,t){super(e,t);let n=this.inputs.Period,r=this.inputs.Increment,i=Math.min(Math.max(0,this.inputs.Count),10);for(let e=0;e<i;++e){let i=J(t,n+e*r,this.source,this.outFields[e]);this.addInner(i)}}getWrappers(){let e=this.outFields,t=this.inputs.Count;return[this.wrapInner(e[0],1),this.wrapInner(e[1],2),this.wrapInner(e[2],3),this.wrapInner(e[3],4),this.wrapInner(e[4],5),this.wrapInner(e[5],6),this.wrapInner(e[6],7),this.wrapInner(e[7],8),this.wrapInner(e[8],9),this.wrapInner(e[9],10)].slice(0,t)}},_C=K(`_HAO`),vC=K(`_HAH`),yC=K(`_HAL`),bC=K(`_HAC`),xC=class extends q{constructor(e,t){super(e,t);let n=DE(e,`EMA`,`Smoothing1`),r=e.inputs.Period1,i=n(t,r,W.Open),a=n(t,r,W.High),o=n(t,r,W.Low),s=n(t,r,W.Close),c=Z(bC,(e,t,n,r,i)=>(t+n+r+i)/4,i,a,o,s);function l(e,t,n,r){let i=null;if(e>0){let r=this.container.getData(_C)[e-1],a=this.innVal(2,bC,e-1);P(r,a)?i=(r+a)/2:P(t,n)&&(i=(t+n)/2)}return i}let u=Z(_C,l,i,s,c),d=Z(vC,(e,t,n,r)=>P(t,n,r)?Math.max(t,Math.max(n,r)):null,a,u,c),f=Z(yC,(e,t,n,r)=>P(t,n,r)?Math.min(t,Math.min(n,r)):null,o,u,c),p=DE(e,`EMA`,`Smoothing2`),m=e.inputs.Period2,h=p(u,m,_C,W.Open),g=p(d,m,vC,W.High),_=p(f,m,yC,W.Low),v=p(c,m,bC,W.Close),y=X(W.Change,function(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Close,e-1);P(n,r)?t=n-r:P(n)&&!P(r)&&(t=0)}return{[W.Change.id]:t}},v);this.addInner(h,g,_,v,y)}getWrappers(){return[this.wrapInner(W.Open,1),this.wrapInner(W.High,2),this.wrapInner(W.Low,3),this.wrapInner(W.Close,4),this.wrapInner(W.Change,5)]}},SC=K(`_DELTA`),CC=class extends q{constructor(e,t){super(e,t);let n=e.inputs,r=Y(t,n.PeriodEmaKeltner,W.Close),i=iE(t,n.PeriodAtrKeltner);function a(e,t,n,r){return P(n,r)?n+e*r:null}let o=n.MultiplierKeltner,s=Z(W.KCUP,se(a,o),r,i),c=Z(W.KCLOW,se(a,-o),r,i),l=hE(t,n.PeriodBollinger,n.WidthBollinger),u=gE(t,n.PeriodMomentum),d=J(t,n.PeriodMomentum,W.Close);function f(e,t,n,r){let i=null,a=this.innVal(1,W.DONMID,e);return P(a,r)&&(i=t-(a+r)/2),i}let p=_E(Z(SC,f,t,u,d),n.PeriodMomentum,SC,W.TTMSQZOSC);this.addInner(s,c,l,p)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=null,n=null,r=-1,i=this.innVal(1,W.KCUP,e),a=this.innVal(2,W.KCLOW,e),[o,s]=[W.BOLLBU,W.BOLLBL].map(t=>this.innVal(3,t,e));o<i&&s>a?t=0:n=0;let c=this.innVal(4,W.TTMSQZOSC,e),l=e>0?this.innVal(4,W.TTMSQZOSC,e-1):null;if(P(c))if(!P(l))r=2;else{let e=c>=0,t=l<c;r=e?t?3:2:+!!t}return{[W.TTMSQZON.id]:t,[W.TTMSQZOFF.id]:n,[W.BARCOLIX.id]:r}}getWrappers(){return[this.wrapInner(W.TTMSQZOSC,4)]}},wC=e=>{let t=e.unit===g.Month;return{mapper:e=>e.query.symbol,loadMoreData:!1,recompute:d.Manual,missing:t?u.UseNext:u.UsePrevious,stretch:e=>!1,fieldMap:new Map([[W.Close,W.CRS]]),noDataApproach:f.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1}},TC=class extends q{constructor(e,t){if(super(e,t),NE(t)){let n=$().getTimeSeriesDataSource(),r=t.query.duplicate();r.symbol=this.inputs.Symbol.toUpperCase();let i=n.getTimeSeries(r),a=e=>e.query?.symbol,{model:o}=Su(((e,t)=>`{${a(e)}} / {${a(t)}}`)(t,i),!1),s=wC(e.aggregation),c=new Ev(o,[t,i],s),l=DE(e,`MA`,`Average`)(c,this.period,W.CRS,W.CRSAVG);this.addInner(i,c,l),this.canLoadMoreData=!0,this.initialNotification=!0}else{let e=X(W.Close,(e,t)=>null,t),n=X(W.CRS,(e,t)=>null,t),r=X(W.CRSAVG,(e,t)=>null,t);this.addInner(e,n,r),this.canLoadMoreData=!1}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(W.DateTime,2),this.wrapInner(W.CRS,2),this.wrapInner(W.CRSAVG,3)]}},EC=K(`_DIFF`),DC=K(`_RANK`),OC=K(`_CHG`),kC=K(`_AVG`),AC=K(`_HBRAKE_CHG`),jC=K(`_HEIGHT_DELTA`),MC=K(`_ACTION`),NC=K(`_REVERSAL`),PC=200,FC=10,IC=e=>[e>0,e<0],LC=[null,null,null],RC={None:0,Hold:1,Take:2};function zC([e,t],n){let r=null;if(n>0){let t=this.baseVal(e,n-1);P(t)&&(r=this.baseVal(e,n)-t)}return{[t.id]:r}}var BC=class extends q{useHandbrake;constructor(e,t){super(e,t);let n=DE(e,`MA`,`Average`),r=n(t,xt(1,999,this.inputs.FastPeriod),W.Close),i=xt(0,999,this.inputs.SlowPeriod),a=i>0,o=a?n(t,i,W.Close):t,s=Z(EC,a?(e,t,n)=>t-n:(e,t,n)=>n-t,r,o),c=X(OC,se(zC,[W.Close,OC]),t),l=X(DC,function(e){let t=Math.abs(this.baseVal(EC,e)),n=null,r=0,i=0;for(let n=e-1;n>=0&&r<PC;--n){let e=Math.abs(this.baseVal(EC,n));r++,e<t&&i++}return r>0&&(n=Math.floor(i/r*FC)),n===FC&&n--,{[DC.id]:n}},s),u=xt(0,999,this.inputs.HandbrakePeriod);this.useHandbrake=u>0;let d=n(t,u,W.Close,kC),f=X(AC,se(zC,[kC,AC]),d);this.addInner(c,s,l,f)}get helpers(){return[jC,W.BARCOLIX,MC,NC]}getStateAt(e){let t=this.innVal(2,EC,e);return P(t)?IC(t):LC}findPreviousKnownState(e){for(let t=e-1;t>0;t--){let e=this.getStateAt(t);if(e===LC)return LC;let[n,r]=e;if(n||r)return e}return LC}getBuySell(e){let t=this.getStateAt(e);if(t===LC)return LC;let[n,r]=t,i=this.findPreviousKnownState(e),[a,o]=i;if(!n&&!r)return i===LC?LC:[a,o,!1];let s=n!==a||r!==o;return s?[a,o,s]:[n,r,s]}getPrev(e,t){return t>0?this.container.getData(e)[t-1]:null}calculateAt(e){let t=null,n=null,r=0,i=-1,a=RC.None,[o,s,c]=this.getBuySell(e),[l,u]=[NC,MC].map(t=>this.getPrev(t,e)),[d,f]=[0,-1].map(t=>this.innVal(4,AC,e+t));if(i=c?FC:this.innVal(3,DC,e),this.useHandbrake&&P(d,f)){let t=o&&f>0||s&&f<0,n=!o&&d>0||!s&&d<0;c?(i=n?FC:FC+2,a=u):(l===!0||u===RC.Hold)&&(t?(i=this.innVal(3,DC,e),a=RC.Take):(i=n?FC+1:FC+3,a=RC.Hold))}if(P(this.innVal(2,EC,e))){let t=this.innVal(1,OC,e),[n,i]=IC(t),a=Math.abs(t);(o&&n||s&&i)&&(r=a),(o&&i||s&&n)&&(r=-a)}return o?t=1:s&&(n=1),{[W.JPIB.id]:t,[W.JPIS.id]:n,[W.BARCOLIX.id]:i,[jC.id]:r,[MC.id]:a,[NC.id]:c}}},VC=class extends BC{constructor(e,t){e.inputs=dt(B(`JPI`).defaults.inputs.filter(e=>e.name!==`HandbrakePeriod`)),super(e,t)}},HC={FastPeriod:8,SlowPeriod:21,HandbrakePeriod:13,Average:`EMA`,Height:`Fixed`},UC=class extends BC{constructor(e,t){e.inputs=structuredClone(HC),super(e,t)}},WC=e=>{let t=e.unit===g.Month;return{mapper:e=>e.query.symbol,loadMoreData:!1,recompute:d.Manual,missing:t?u.UseNext:u.UsePrevious,stretch:e=>!1,fieldMap:new Map([[W.Close,W.DRS]]),noDataApproach:f.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1}},GC=class extends q{get indexSymbol(){return this.inputs[z.INPUT_SYMBOL]}constructor(e,t){if(super(e,t),NE(t)){let n=$().getTimeSeriesDataSource(),r=t.query.duplicate();r.symbol=this.indexSymbol;let i=n.getTimeSeries(r),{model:a}=Su(`{${t.query.symbol}} / {${i.query.symbol}} * 100`,!1),o=WC(e.aggregation),s=new Ev(a,[t,i],o);this.addInner(i,s),this.canLoadMoreData=!0,this.initialNotification=!0}else{let e=X(W.Close,(e,t)=>null,t),n=X(W.DRS,(e,t)=>null,t);this.addInner(e,n),this.canLoadMoreData=!1}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(W.DateTime,2),this.wrapInner(W.DRS,2)]}},KC=class extends q{get indexSymbol(){return this.inputs[z.INPUT_SYMBOL]}constructor(e,t){super(e,t);let n=fE(t,this.indexSymbol,e.aggregation),r=J(n,this.period,W.DRS);this.addInner(n,r),this.canLoadMoreData=!0,this.initialNotification=!0}calculateAt(e){let t=this.innVal(1,W.DRS,e),n=this.innVal(2,W.MA,e),r=null;return P(t,n)&&n!==0&&(r=(t/n-1)*100),{[W.MRS.id]:r}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},qC=K(`_SMTH_ROC`),JC=K(`_TEN_SMTH_ROC`);function YC(e,t,n,r,i){return new Iv({source:r,target:i,outFields:[i],aggregation:n,inputs:UT(t)},e,e=>2/e)}var XC=class extends q{constructor(e,t){super(e,t);let n=cE(t,1),r=e.aggregation,i=this.inputs.Period1,a=Z(JC,(e,t)=>10*t,YC(n,i,r,W.ROC,qC)),o=this.inputs.Period2,s=YC(a,o,r,JC,W.PMO),c=Y(s,this.inputs.Period3,W.PMO,W.PMOS);this.addInner(s,c)}getWrappers(){return[this.wrapInner(W.PMO,1),this.wrapInner(W.PMOS,2)]}},ZC=K(`_VOL_AVG`),QC=class extends q{constructor(e,t){super(e,t);let n=DE(e,`MA`)(t,this.period,W.Volume,ZC,!0);this.addInner(n)}calculateAt(e){let t=null,n=this.innVal(0,W.Volume,e),r=this.innVal(1,ZC,e);return P(n,r)&&r!==0&&(t=n/r),{[this.target.id]:t}}},$C=e=>Xe(.5**(1/e),6),ew=52,tw=ew/2,nw=ew+1,rw=tw+1,iw=5,aw=tw*iw+1,ow=(()=>{let e=$C(ew-1),t=De(ew,t=>e**+t),n=ew/pe(t);return t.map(e=>e*n)})(),sw=[`Renko`,`Kagi`,`PointAndFigure`,`LineBreak`],cw=class extends q{isDaily;isFeasible=!0;constructor(e,t){super(e,t);let n=Dv(t),r=n.query?.curveStyle;this.isFeasible=!(n instanceof xg)&&(!P(r)||!sw.includes(h[r])),this.isDaily=e.aggregation.unit===g.Day}acceptable(e,t,n,r){return this.isDaily?r===0?!0:!jr(this.baseVal(W.DateTime,t),this.baseVal(W.DateTime,n)):e>0&&n-t>=iw}pluckValues(e){let t=0,n=[],r=e+iw;for(let i=0;t<nw&&e-i>0;i++){let a=e-i,o=this.baseVal(this.source,a);this.acceptable(o,a,r,t)&&(n.push(o),r=a,t++)}return n}calculateAt(e){let t=null;if(this.isFeasible&&e>=aw){let n=1,r=this.pluckValues(e),i=r.length;if(i>=rw)for(let e=0;e<i-1;e++){let t=r[e]/r[e+1]-1;t<0?t=Math.max(t,-.2):t>=0&&(t=Math.min(t,.2)),t=t*ow[e]+1,n*=t}t=100*(n-1)}return{[this.target.id]:t}}},lw=20;function uw(e,t){switch(e){case g.Intraday:return t>=240?3:t>=120?2:1;case g.Day:default:return 5;case g.Week:return 15;case g.Month:return 60;case g.Quarter:case g.Year:return 240}}function dw(e){return e===_.Continue||e===_.Nearest}var fw=class extends q{additionalChunksCounter=1;noData=!1;isPeriodic=!1;constructor(e,t,n){super(e,n,jv(n,e=>{let t=ne[$()?.config.mode??`Unspecified`];if(!bs(t))return n;let r=e.duplicate(),i=e.aggregation;if(i.hasSpec)return dw(i.spec)?n:new xg(r,!0);let a=i.unit===g.Intraday&&i.size<=5,o=uw(i.unit,i.size);r.aggregation=a?new Vl(g.Tick,i.size,_.PerSeconds):new Vl(g.Intraday,o);let s=a?1:3;return r.barsToFetch=Math.min(z.MAX_INTRADAY_BARS,s*e.barsToFetch),new yg(r)})),this.isPeriodic=t,this.noData=this.innerSeries[1]instanceof xg,this.computedServerSide=!0,this.initialNotification=!0}get canLoadMoreData(){return!1}loadMoreData(){let e=this.innerSeries[1];return!this.noData&&this.additionalChunksCounter<lw&&e.canLoadMoreData&&!e.isLoading?(this.additionalChunksCounter+=1,e.loadMoreData()):Promise.resolve()}recalculateAt(e,t,n){if(e.src!==this.innerSeries[0])return;let r=n?G.TS_DATAPOINTADDED:G.TS_DATAPOINTCHANGED;this.notify(r,this.innerSeries[0].container.size-1)}getWrappers(){return[this.wrapInner(W.Change,1),this.wrapInner(W.Open,1),this.wrapInner(W.Close,1)]}},pw=class extends fw{constructor(e,t){super(e,!1,t)}},mw=class extends fw{constructor(e,t){super(e,!0,t)}},hw=class extends q{constructor(e,t){super(e,t);let n=iE(t,e.inputs.Period,e.inputs.Smoothing);this.addInner(n)}calculateAt(e){let t=null,n=this.innVal(1,W.ATR,e),r=this.baseVal(W.Close,e);return P(n,r)&&r>0&&(t=n/r*100),{[W.ATRP.id]:t}}},gw=K(`_DR`),_w=class extends q{constructor(e,t,n){super(e,n);let r=X(gw,e=>{let t=this.baseVal(W.High,e),n=this.baseVal(W.Low,e);return{[gw.id]:P(t,n)?t-n:null}},n),i=DE(e,`MA`)(r,this.inputs.Period,gw,W.ADR);if(t){let e=Z(this.target,(e,t,n)=>!P(t,n)||n===0?null:t/n*100,i,n);this.addInner(e)}else this.addInner(i)}getWrappers(){return[this.wrapInner(this.target,1)]}},vw=class extends _w{constructor(e,t){super(e,!1,t)}},yw=class extends _w{constructor(e,t){super(e,!0,t)}},bw=class extends q{constructor(e,t){super(e,t);let n=this.source,r=X(n,se(wE,n),t),i=cE(r,this.inputs.PeriodRoc1,n),a=cE(r,this.inputs.PeriodRoc2,n),o=cE(r,this.inputs.PeriodRoc3,n),s=cE(r,this.inputs.PeriodRoc4,n),c=J(i,this.inputs.PeriodMa1,W.ROC,W.MA1),l=J(a,this.inputs.PeriodMa2,W.ROC,W.MA2),u=J(o,this.inputs.PeriodMa3,W.ROC,W.MA3),d=J(s,this.inputs.PeriodMa4,W.ROC,W.MA4),f=Z(W.KST,(e,t,n,r,i)=>t+2*n+3*r+4*i,c,l,u,d),p=J(f,this.inputs.PeriodSig,W.KST,W.KSTSIG);this.addInner(f,p)}getWrappers(){return[this.wrapInner(W.KST,1),this.wrapInner(W.KSTSIG,2)]}},xw=K(`_EMA1`),Sw=K(`_EMA2`),Cw=K(`_MACD`),ww=K(`_PCTK`),Tw=K(`_PCTD`),Ew=K(`_PCTK2`),Dw=class extends q{constructor(e,t){super(e,t);let n=Z(Cw,(e,t,n)=>t-n,Y(t,this.inputs.PeriodShort,W.Close,xw),Y(t,this.inputs.PeriodLong,W.Close,Sw)),r=this.inputs.PeriodStoch1,i=this.inputs.PeriodStoch2,a=DE(e,`EMA`),o=a(eE(a(eE(n,r,ww,!1,Cw),i,ww,Tw),r,Ew,!1,Tw),i,Ew,this.target);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},Ow=K(`_EMA1`),kw=K(`_EMA2`),Aw=K(`_CORE`),jw=class extends q{isEmpty=!1;constructor(e,t){if(super(e,t),NE(t)&&e.aggregation?.isEndOfDay){let n=[`$ADVT`,`$DECT`];switch(this.inputs.Source){case`TotalStocks`:default:break;case`NYSEStocks`:n=[`$ADVN`,`$DECN`];break;case`NasdaqStocks`:n=[`$AVDQ`,`$DECQ`];break}let r=this.getSeries(t.query,n[0]),i=this.getSeries(t.query,n[1]),a=this.getTargetSeries(e,r,i);this.addInner(r,i,a),this.canLoadMoreData=!0,this.initialNotification=!0}else{this.isEmpty=!0;let e=X(W.Close,(e,t)=>null,t),n=X(W.Close,(e,t)=>null,t),r=X(this.target,(e,t)=>null,t);this.addInner(e,n,r),this.canLoadMoreData=!1}}get baseIndex(){return+!this.isEmpty}getSeries(e,t){let n=e.duplicate();return n.symbol=t,$().getTimeSeriesDataSource().getTimeSeries(n)}shouldTriggerOurRecalc(e){return super.shouldTriggerOurRecalc(e)?!0:e===this.innerSeries[0]?!1:(e===this.innerSeries[1]||e===this.innerSeries[2])&&this.innHasData(1)&&this.innHasData(2)}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[1].canLoadMoreData||!this.innerSeries[2].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),await this.innerSeries[2].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(this.target,3)]}},Mw=class extends jw{constructor(e,t){super(e,t)}getTargetSeries(e,t,n){let r=(e,t,n)=>t-n,i=Z(Aw,this.inputs.RatioAdjusted===`Yes`?(e,t,n)=>(t-n)/(t+n)*1e3:r,t,n),a=Y(i,this.inputs.Period1,Aw,Ow),o=Y(i,this.inputs.Period2,Aw,kw);return Z(this.target,r,a,o)}},Nw=K(`_INN_HL_ACC_IX`),Pw=new Vl;function Fw(e,t,n){return new Iw({aggregation:Pw,source:null,target:n,outFields:[n],inputs:{...t}},e)}var Iw=class extends q{isWeekly=!1;constructor(e,t){if(super(e,t),t instanceof xg)this.canLoadMoreData=!1;else{let n=this.inputs.Source===`PriceIndex`?`$MADX`:`$FADX`,r=this.getSeries(t.query,n);if(this.addInner(r),this.isWeekly=e.aggregation.unit===g.Week,this.isWeekly){let e=Fw(this.getSeries(t.query,n,Pw),this.inputs,Nw);this.addInner(e)}this.canLoadMoreData=!0,this.initialNotification=!0}}getSeries(e,t,n){let r=e.duplicate();return r.symbol=t,n&&(r.aggregation=n,r.barsToFetch=z.US_TRADING_DAYS_PER_YEAR*15),$().getTimeSeriesDataSource().getTimeSeries(r)}get baseIndex(){return 1}calculateAt(e){if(this.isWeekly)return this.calculateAtWeekly(e);let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,W.Close);k(r)&&(t=pe(r))}return{[this.target.id]:t}}calculateAtWeekly(e){let t=this.container?.size??-1,n=null,r=this.innCont(2);if(t>0&&e===t-1)n=r.getLastDataPoint(Nw);else{let t=this.container.getTimeData()[e],i=r.getTimeData(),a=Te(i,t),o=i[a],s=null;for(;a<r.size&&jr(t,o);)s=a,a+=1,o=i[a];s!==null&&(n=r.getData(Nw)[s])}return{[this.target.id]:n}}shouldTriggerOurRecalc(e){return super.shouldTriggerOurRecalc(e)?!0:e===this.innerSeries[0]?!1:e===this.innerSeries[1]&&this.innHasData(1)}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[1].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},Lw=K(`_RSI1`),Rw=K(`_RSI1_MOM`),zw=K(`_RSI2`),Bw=K(`_RSI2_MA`),Vw=class extends q{constructor(e,t){super(e,t);let n=lE(t,this.inputs.Period1Rsi,W.Close,Lw),r=X(Rw,ce(TE,this.inputs.Period1Mom,Lw),n),i=J(lE(t,this.inputs.Period2Rsi,W.Close,zw),this.inputs.Period2Ma,zw,Bw),a=Z(W.CMBCI,(e,t,n)=>t+n,r,i),o=J(a,this.inputs.PeriodFastMa,W.CMBCI,W.CMBCIF),s=J(a,this.inputs.PeriodSlowMa,W.CMBCI,W.CMBCIS);this.addInner(a,o,s)}getWrappers(){return[this.wrapInner(W.CMBCI,1),this.wrapInner(W.CMBCIF,2),this.wrapInner(W.CMBCIS,3)]}};function Hw(e){return new Zx({source:W.Close,inputs:{},outFields:qT(`COTLC`)},e)}var Uw=class extends q{constructor(e,t){super(e,Hw(t));let n=Number.parseInt(this.inputs.History),r=n===6?52/2:52*n,i=eE(this.innerSeries[0],r,W.COTI,!1,W.COTLCCMSP);this.initialNotification=!0,this.computedServerSide=!0,this.addInner(i)}getWrappers(){return[this.wrapInner(W.COTI,1)]}},Ww=K(`_MUL_ATR`),Gw=class extends q{isLong;constructor(e,t){super(e,t),this.isLong=this.inputs.Direction===`Long`;let n=this.period,r=iE(t,n),i=this.inputs.Multiplier,a=Z(Ww,(e,t)=>t===null?null:i*t,r),o=$T(t,n,W.High,W.HH,!0),s=$T(t,n,W.Low,W.LL,!1);this.addInner(a,o,s)}calculateAt(e){let t=null,n=null,r=this.innVal(1,Ww,e);return r!==null&&(this.isLong?t=this.innVal(2,W.HH,e)-r:n=this.innVal(3,W.LL,e)+r),{[W.CHEXL.id]:t,[W.CHEXS.id]:n}}},Kw=class extends q{constructor(e,t){let n=e.outFields??[],r=e=>{let t=$().getTimeSeriesDataSource();return e.seriesKind=w.Options,e.fields=n,t.getTimeSeries(e)},i=n.length===1?n[0]:void 0,a=i?Mv(t,i,r):jv(t,r);super(e,a),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return this.outFields.map(e=>this.wrapInner(e,0))}},qw=class extends Kw{},Jw=class extends Kw{},Yw=class extends Kw{},Xw=class extends Kw{},Zw=class extends Kw{},Qw=class extends Kw{},$w=class extends Kw{},eT=class extends q{constructor(e,t){super(e,t);let n=iE(t,1),r=this.inputs.Period,i=$T(t,r,W.High,W.HH,!0),a=$T(t,r,W.Low,W.LL,!1);this.addInner(n,i,a)}calculateAt(e){let t=null,n=this.period;if(e>n){let r=this.past(e,n,W.ATR,this.innCont(1));if(k(r)){let i=pe(r)/(this.innVal(2,W.HH,e)-this.innVal(3,W.LL,e));t=100*Math.log10(i)/Math.log10(n)}}return{[this.target.id]:t}}},tT=class extends q{constructor(e,t){super(e,t);let n=DE(e,`MA`,`Average`),r=n(t,e.inputs.Period1,this.source,W.MACLD1),i=n(t,e.inputs.Period2,this.source,W.MACLD2);this.addInner(r,i)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=+(this.innVal(1,W.MACLD1,e)>this.innVal(2,W.MACLD2,e));return{[W.BARCOLIX.id]:t}}getWrappers(){return[this.wrapInner(W.MACLD1,1),this.wrapInner(W.MACLD2,2)]}},nT=K(`_CORE`),rT=class extends jw{constructor(e,t){super(e,t)}getTargetSeries(e,t,n){let r=Z(nT,(e,t,n)=>t/(t+n),t,n);return DE(e,`MA`,`Average`)(r,this.inputs.Period,nT,this.target)}},iT=class extends q{stdDevs;periodForecast;unitsPerYear;constructor(e,t){super(e,t),this.unitsPerYear=AE(e.aggregation),this.stdDevs=this.toInt(`StandardDeviations`),this.periodForecast=this.toInt(`PeriodForecast`);let n=this.getHistVolPeriod();if(n!==null){let r=vE(t,n,e.aggregation);this.addInner(r)}}getHistVolPeriod(){return this.isCustomVolatility?null:Number.parseInt(this.volatilityParam.substring(2))}toInt(e){return Number.parseInt(this.inputs[e])}get volatilityParam(){return this.inputs.Volatility}get isCustomVolatility(){return this.volatilityParam===`Custom`}get haveVolatility(){return this.isCustomVolatility||this.innHasData(1)}getVolatilityPercent(){return(this.isCustomVolatility?this.inputs.VolatilityPercent:this.innCont(1).getLastDataPoint(W.HV))/100}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null;if(this.haveVolatility){let s=this.base.size-this.periodForecast;if(e>=s){let c=this.base.getLastDataPoint(W.Close),l=this.getVolatilityPercent(),u=e-s+1,d=c*l*Math.sqrt(u/this.unitsPerYear);if(t=c+d,n=c-d,this.stdDevs>1){let e=2*d;if(r=c+e,i=c-e,this.stdDevs>2){let e=3*d;a=c+e,o=c-e}}}}return{[W.PCUP1.id]:t,[W.PCDN1.id]:n,[W.PCUP2.id]:r,[W.PCDN2.id]:i,[W.PCUP3.id]:a,[W.PCDN3.id]:o}}recalculateAt(e,t,n){let r={tag:bt(),src:this.innerSeries[0]};n&&this.calculate(r)}},aT=class extends q{constructor(e,t){super(e,jv(t,e=>new oT(e))),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return[this.wrapInner(W.Delta,0),this.wrapInner(W.Gamma,0),this.wrapInner(W.Theta,0),this.wrapInner(W.Vega,0)]}},oT=class extends yg{constructor(e){super(e)}getRetriever(){return Jr(this.query.symbol)?new lT:ei(this.query.symbol)?new uT:new cT}};function sT(){return new bh([W.DateTime,W.Delta,W.Gamma,W.Theta,W.Vega])}var cT=class{supportsChunks;constructor(){this.supportsChunks=!1}async retrieve(e){return sT()}},lT=class extends Gh{emptyContainer(e,t){return sT()}get iterateForward(){return!1}getPageName(){return`getFuturesOptionsHistory`}processRow(e,t,n){n.addDataPoint(W.DateTime,ph(e.date.substring(0,10))),n.addDataPoint(W.Delta,e.delta),n.addDataPoint(W.Gamma,e.gamma),n.addDataPoint(W.Theta,e.theta),n.addDataPoint(W.Vega,e.vega)}},uT=class extends Gh{emptyContainer(e,t){return sT()}addExtraParams(e){e.fields=`delta,gamma,theta,vega`}get iterateForward(){return!0}getPageName(){return`getEquityOptionsHistory`}processRow(e,t,n){n.addDataPoint(W.DateTime,ph(e.date)),n.addDataPoint(W.Delta,e.delta),n.addDataPoint(W.Gamma,e.gamma),n.addDataPoint(W.Theta,e.theta),n.addDataPoint(W.Vega,e.vega)}},dT=K(`_RSI1`),fT=K(`_RSI2`),pT=class extends q{constructor(e,t){super(e,t);let n=lE(t,this.inputs.Period1,this.source,dT),r=lE(t,this.inputs.Period2,this.source,fT),i=Z(W.RSA,(e,t,n)=>(t+n)/2,n,r),a=DE(e,`MA`,`Average`)(i,this.inputs.PeriodAvg,W.RSA,W.RSAAVG);this.addInner(i,a)}getWrappers(){return[this.wrapInner(W.RSA,1),this.wrapInner(W.RSAAVG,2)]}},mT=class extends q{constructor(e,t){super(e,t),SE(this);let n=e.inputs.PeriodRSI,r=e.inputs.PeriodTradeSignal,i=e.inputs.PeriodMarketBase,a=e.inputs.PeriodBB,[o]=CE(this),s=this.innerSeries[o],c=lE(s,n,this.source,W.TDIPRC),l=J(c,r,W.TDIPRC,W.TDITSL),u=J(c,i,W.TDIPRC,W.TDIMBL),d=dE(c,a,W.TDIPRC,W.MSD);this.addInner(c,l,u,d)}calculateAt(e){let t=this.inputs.MultiplierBB,n=+!!this.sourceNeedsCompute,r=this.innVal(1+n,W.TDIPRC,e),i=this.innVal(2+n,W.TDITSL,e),a=this.innVal(3+n,W.TDIMBL,e),o=this.innVal(4+n,W.MSD,e),s=null,c=null;if(P(a,o)){let e=t*o;s=a+e,c=a-e}return{[W.TDIPRC.id]:r,[W.TDITSL.id]:i,[W.TDIMBL.id]:a,[W.TDIUPR.id]:s,[W.TDILWR.id]:c}}},hT=K(`_ANCHR`),gT=class extends q{isLong;isPercent;constructor(e,t){super(e,t);let n=e.inputs.Period,r=e.inputs.Range;this.isLong=e.inputs.Direction===`Long`,this.isPercent=e.inputs.Type===`Percent`;let i=r===`Close`,a=W.Close;i||(a=this.isLong?W.High:W.Low);let o=$T(t,n,a,hT,this.isLong);this.addInner(o)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=null,n=this.innVal(1,hT,e),r=this.inputs.StopValue;if(n!==null){let e=this.isPercent?n*r/100:r;t=this.isLong?n-e:n+e}let i=+!!this.isLong;return{[W.PPS.id]:t,[W.BARCOLIX.id]:i}}},_T=K(`_HH_N`),vT=K(`_LL_N`),yT=K(`_HH_H1`),bT=K(`_LL_H1`),xT=K(`_HH_H2`),ST=K(`_LL_H2`),CT=class extends q{constructor(e,t){super(e,t),SE(this);let n=e.inputs.Period,r=Math.floor(n/2),i=$T(t,n,W.High,_T,!0),a=$T(t,n,W.Low,vT,!1),o=$T(t,r,W.High,yT,!0),s=$T(t,r,W.Low,bT,!1),c=$T(t,r,W.High,xT,!0),l=$T(t,r,W.Low,ST,!1);this.addInner(i,a,o,s,c,l)}calculateAt(e){let t=this.period,n=Math.floor(t/2),[,r]=CE(this),i=r.getData(this.source)[e];if(!this.atLeast(e,t))return{[this.target.id]:i};let a=+!!this.sourceNeedsCompute,o=this.innVal(1+a,_T,e),s=this.innVal(2+a,vT,e),c=this.innVal(3+a,yT,e),l=this.innVal(4+a,bT,e),u=this.innVal(5+a,xT,e-n),d=this.innVal(6+a,ST,e-n);if(!P(o,s,c,l,u,d))return{[this.target.id]:i};let f=(o-s)/t,p=(c-l)/n,m=(u-d)/n,h=0;p>0&&m>0&&f>0&&(h=(Math.log(p+m)-Math.log(f))/Math.log(2));let g=Math.exp(-4.6*(h-1));g=Math.max(.01,Math.min(1,g));let _=e>0?this.container.getData(this.target)[e-1]:i,v=_===null?i:g*i+(1-g)*_;return{[this.target.id]:v}}},wT=K(`_MIDPOINT`),TT=K(`_VALUE`),ET=class extends q{constructor(e,t){super(e,t);let n=e.inputs.Period,r=X(wT,se(ob,wT),t),i=$T(r,n,wT,W.HH,!0),a=$T(r,n,wT,W.LL,!1);this.addInner(r,i,a)}get helpers(){return[TT]}calculateAt(e){let t=this.innVal(1,wT,e),n=this.innVal(2,W.HH,e),r=this.innVal(3,W.LL,e);if(!P(n,r,t))return{[W.FISHER.id]:null,[W.FISHTRG.id]:null,[TT.id]:null};let i=n-r,a=i===0?.5:(t-r)/i,o=t=>this.container.getData(t)[e-1],s=e>0?o(TT):null,c=.66*(a-.5)+.67*(s??0);c>.99?c=.999:c<-.99&&(c=-.999);let l=e>0?o(W.FISHER):null,u=.5*Math.log((1+c)/(1-c))+.5*(l??0);return{[W.FISHER.id]:u,[W.FISHTRG.id]:l,[TT.id]:c}}},DT=class extends q{constructor(e,t){super(e,t),SE(this)}computeMidranks(e){let t=e.length,n=e.map((e,t)=>({v:e,i:t}));n.sort((e,t)=>e.v-t.v);let r=Array(t),i=0;for(;i<t;){let e=i,a=n[i].v;for(;e+1<t&&n[e+1].v===a;)e++;let o=(i+1+(e+1))/2;for(let t=i;t<=e;t++)r[n[t].i]=o;i=e+1}return r}pearsonCorrelation(e){let t=e.length;if(t<2)return null;let n=(t+1)/2,r=0;for(let n=0;n<t;n++)r+=e[n];let i=r/t,a=0,o=0,s=0;for(let r=0;r<t;r++){let t=r+1-n,c=e[r]-i;a+=t*c,o+=t*t,s+=c*c}let c=Math.sqrt(o*s);return c===0?null:a/c}calculateAt(e){let t=null,n=this.period,[,r]=CE(this);if(this.atLeast(e,n)){let i=this.past(e,n,this.source,r);if(i.every(e=>e!==null)){let e=this.computeMidranks(i),n=this.pearsonCorrelation(e);n!==null&&(t=100*n)}}return{[W.RCI.id]:t}}},OT=class extends q{constructor(e,t){super(e,t);let n=this.source,r=new DT({source:n,target:W.RCI,inputs:{Period:e.inputs.Period}},t),i=e.inputs.PeriodSignal,a=DE(e,`MA`,`Smoothing`)(r,i,W.RCI,W.RCISIG);this.addInner(r,a)}getWrappers(){return[this.wrapInner(W.RCI,1),this.wrapInner(W.RCISIG,2)]}},kT=K(`_ATR`),AT=function(e){return e[e.Uninitialized=0]=`Uninitialized`,e[e.UpLeg=1]=`UpLeg`,e[e.DownLeg=-1]=`DownLeg`,e}(AT||{}),jT=class extends q{state;useHighLow;isAtrMode;atrMult;percent;constructor(e,t){if(super(e,t),this.useHighLow=e.inputs.Method===`High/Low`,this.isAtrMode=e.inputs.PercentMode===`ATR`,this.percent=e.inputs.Percent,this.atrMult=e.inputs.MultiplierAtr,this.useHighLow||SE(this),this.isAtrMode){let t=e.inputs.PeriodAtr,[n]=this.useHighLow?[0]:CE(this),r=this.innerSeries[n],i=iE(r,t,`SMA`,kT);this.addInner(i)}this.resetState()}getHigh(e){if(this.useHighLow)return this.baseVal(W.High,e);let[,t]=CE(this);return t.getData(this.source)[e]}getLow(e){if(this.useHighLow)return this.baseVal(W.Low,e);let[,t]=CE(this);return t.getData(this.source)[e]}getAtrDenom(e){if(this.useHighLow)return this.baseVal(W.Close,e);let[,t]=CE(this);return t.getData(this.source)[e]}setPivot(e,t){this.state.pivotPrice=e,this.state.pivotIndex=t}setCandidate(e,t){this.state.candPrice=e,this.state.candIndex=t}getDevPct(e){if(this.isAtrMode){let t=!this.useHighLow&&this.sourceNeedsCompute?1:0,n=this.innVal(1+t,kT,e),r=this.getAtrDenom(e);if(n===null||r===null||r===0)return 0;let i=n/r*100;return this.atrMult*i}return this.percent}pct(e,t){return e===0?0:(t-e)/e*100}resetState(){this.state={mode:AT.Uninitialized,pivotPrice:null,pivotIndex:null,candPrice:null,candIndex:null,confirmedPivots:new Map}}calculateAt(e){let t=this.getHigh(e),n=this.getLow(e),r=this.getDevPct(e);if(t===null||n===null)return{};if(e===0){this.resetState();let n=this.useHighLow?this.baseVal(W.Close,e):t;return this.setPivot(n,e),this.setCandidate(n,e),{}}if(this.state.mode===AT.Uninitialized)this.pct(this.state.pivotPrice,t)>=r?(this.state.mode=AT.UpLeg,this.setCandidate(t,e)):-this.pct(this.state.pivotPrice,n)>=r&&(this.state.mode=AT.DownLeg,this.setCandidate(n,e));else if(this.state.mode===AT.UpLeg){let i=t>=this.state.candPrice;i&&this.setCandidate(t,e);let a=(this.state.candPrice-n)/this.state.candPrice*100;if(!i&&a>=r){let t=this.state.candIndex,r=this.state.candPrice;this.state.confirmedPivots.set(t,r),this.setPivot(r,t),this.setCandidate(n,e),this.state.mode=AT.DownLeg}}else if(this.state.mode===AT.DownLeg){let i=n<=this.state.candPrice;i&&this.setCandidate(n,e);let a=(t-this.state.candPrice)/this.state.candPrice*100;if(!i&&a>=r){let n=this.state.candIndex,r=this.state.candPrice;this.state.confirmedPivots.set(n,r),this.setPivot(r,n),this.setCandidate(t,e),this.state.mode=AT.UpLeg}}return{}}getCurrentState(){return this.state}},MT=class extends q{constructor(e,t){super(e,t);let n=X(W.BOP,function(e){let t=null,[n,r,i,a]=[W.Open,W.High,W.Low,W.Close].map(t=>this.baseVal(t,e));if(P(n,r,i,a)){let e=r-i;t=e===0?0:(a-n)/e}return{[this.target.id]:t}},t),r=DE(e,`MA`,`Average`),i=this.period,a=r(n,i,W.BOP,W.BOPAVG);this.addInner(n,a)}getWrappers(){return[this.wrapInner(W.BOP,1),this.wrapInner(W.BOPAVG,2)]}};function NT(e,t){let n=e.length;if(n<2||t.length!==n)return null;let r=0,i=0,a=0,o=0,s=0;for(let c=0;c<n;c++){let n=e[c],l=t[c];r+=n,i+=l,a+=n*n,o+=l*l,s+=n*l}let c=n*s-r*i,l=Math.sqrt((n*a-r*r)*(n*o-i*i));if(l===0||!Number.isFinite(l))return null;let u=c/l;return Number.isFinite(u)?Math.max(-1,Math.min(1,u)):null}var PT=class extends q{constructor(e,t){if(super(e,t),NE(t)){let e=this.inputs.Symbol?.toUpperCase();if(e){let n=$().getTimeSeriesDataSource(),r=t.query.duplicate();r.symbol=e;let i=n.getTimeSeries(r);this.addInner(i),this.canLoadMoreData=!0,this.initialNotification=!0}}}compareCloseAt(e){let t=this.innCont(1);if(!t||t.isEmpty)return null;let n=this.baseVal(W.DateTime,e);if(n===null)return null;let r=t.getData(W.DateTime),i=t.getData(W.Close);if(r.length===0)return null;let a=n.valueOf(),o=Te(r,a,Number),s=r[o];if(!P(s))return null;let c=s.valueOf()<=a?o:o-1;if(c<0)return null;let l=i[c];return P(l)?l:null}calculateCorrelation(e){let t=this.period;if(!this.atLeast(e,t)||!this.innHasData(1))return null;let n=[],r=[];for(let i=e-t+1;i<=e;i++){let e=this.baseVal(W.Close,i),t=this.compareCloseAt(i);if(!P(e,t))return null;n.push(e),r.push(t)}return NT(n,r)}calculateAt(e){return{[this.target.id]:this.calculateCorrelation(e)}}async loadMoreData(e=!0){if(this.isLoading||this.innerSeries.length<2||!this.innerSeries[1].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},FT=4,IT=4,LT=K(`_RVI_NUM`),RT=K(`_RVI_DEN`),zT=K(`_RVI_NUMAVG`),BT=K(`_RVI_DENAVG`);function VT(e){if(e.length<IT||!k(e))return null;let[t,n,r,i]=e;return(t+2*n+2*r+i)/6}var HT={_TR:zy,_RSI:gy,MA:Fv,MAEXP:Lv,MAHLC:zv,VOL:Vv,MAENV:qv,MAENVEXP:Jv,MAENVSMO:Yv,MATRI:Xv,MAWEI:Zv,MAVOL:Fv,MASMO:Rv,MACD:cy,MACDEXP:ly,MACDV:sy,GMMA:gS,OSCI:Qv,OSCIVOL:Qv,RSI:vy,RSIMOD:yy,RSISTO:by,RSA:pT,WPERCR:Ty,HHLL:xy,WGCL:Sy,STOCHF:Oy,STOCHS:ky,BBANDS:Ny,BWIDTH:Py,BPERC:Fy,OBVOL:Ry,ATR:Uy,ADR:vw,ATRP:hw,ADRP:yw,ADX:$y,ADXMOD:eb,ADL:tb,ADWM:nb,CHAOSC:rb,TP:ib,KELCHN:mb,KELBND:hb,DONCHN:_b,DONWIDTH:vb,PVT:yb,ROC:wb,TRIX:bb,PPMOV:Tb,PIVPTS:nS,CPP:rS,ARNUPDW:kb,ARNOSC:Ab,TCHN:jb,TCHRE:Mb,ALLG:Pb,PLTLN:Fb,AWEOSC:Lb,MFV:Bb,CLV:zb,CHAMF:Vb,CHAVOL:Ub,DPO:Wb,CCI:Kb,EMV:qb,ERBRPOW:Xb,ERBLPOW:Yb,FI:Qb,MI:rx,MOM:ix,MFI:ax,MSD:ox,NVI:ux,PVI:dx,PPO:fy,PVO:py,HV:px,PERF:mx,WASI:gx,WWVOL:yx,PARTP:Tx,MOVLR:Ex,TRSP:Vx,TARGP:Hx,COTLC:Zx,COTDAG:Qx,COTFTR:$x,IMPVOL:iS,CTM:uy,CPMI:dy,DEMA:xb,EOSC:Sb,TEMA:Cb,TSI:hS,ADJATR:Wy,COTR:Gy,MCGD:_S,HMA:yS,COPP:xS,REATRS:TS,LINRCHN:ES,CSHO:DS,CSHB:OS,MKTCAP:kS,CTPI:Ay,PCTCHG:AS,OPINT:Hv,STOMOMIX:RS,CHDMOMOSC:US,VSTOP:qS,SUPTR:ZS,ICHCLD:QS,VWAP:rC,MACROSS:cC,PACROSS:lC,VOIN:fC,DIFA:mC,DOSC:hC,BBANDW:Iy,MARIB:gC,HASMO:xC,TTMSQZ:CC,CRS:TC,JPI:BC,CTTP:VC,CTTI:UC,DRS:GC,MRS:KC,PMO:XC,RVOL:QC,WGALPH:cw,VOLAP:pw,AVWAP:iC,KST:bw,STC:Dw,MCCLO:Mw,NHLAI:Iw,CMBCI:Vw,COTI:Uw,CHEXI:Gw,MBBANDS:Ly,OPTIV:qw,IVRANK:Jw,IVPCTL:Yw,OPTVOLPC:Xw,OPTOIPC:Zw,OPTVOL:Qw,OPTOI:$w,CHOP:eT,MACLD:tT,BTI:rT,FRAMA:CT,FISHER:ET,PC:iT,GREEKS:aT,PVACP:mw,TDI:mT,PPS:gT,RCI:OT,BOP:MT,CORR:PT,RVI:class extends q{constructor(e,t){super(e,t);let n=(e,t)=>function(n){let r=this.past(n,IT,e),i=this.past(n,IT,t),a=null;if(k(r)&&k(i)){let e=r,t=i;a=VT(e.map((e,n)=>e-t[n]))}return{[this.target.id]:a}},r=X(LT,n(W.Close,W.Open),t),i=X(RT,n(W.High,W.Low),t),a=this.period,o=J(r,a,LT,zT),s=J(i,a,RT,BT),c=Z(W.RVI,(e,t,n)=>n===0?null:t/n,o,s),l=X(W.RVISIG,function(e){return{[this.target.id]:VT(this.past(e,FT,W.RVI))}},c);this.addInner(c,l)}getWrappers(){return[this.wrapInner(W.RVI,1),this.wrapInner(W.RVISIG,2)]}},ZIGZAG:jT};function UT(e){return{[z.INPUT_PERIOD]:e}}function WT(e){return{[z.INPUT_SYMBOL]:e}}function GT(e){return{target:e,source:null,inputs:nE}}function KT(e,t,n){if(nt(HT,e))return new HT[e](t,n);let r=$()?.config.extensions?.studyProvider;if(r){let i=r.factory(e,t,n);if(i)return i}throw Error(`Study ${e} has not been implemented yet.`)}function qT(e){return B(e).defaults.curves.reduce((e,t)=>e.concat(t.fields.filter(t=>!e.includes(t))),[]).map(e=>W[e])}function JT(e,t,n,r){return{source:t,target:n,inputs:UT(e),allowEmptyValues:r}}function J(e,t,n,r=W.MA,i=!1){return KT(`MA`,JT(t,n,r,i),e)}function Y(e,t,n,r=W.EMA,i=!1){return KT(`MAEXP`,JT(t,n,r,i),e)}function YT(e,t,n,r=W.SMA,i=!1){return KT(`MASMO`,JT(t,n,r,i),e)}function XT(e,t,n,r=W.WMA,i=!1){return KT(`MAWEI`,JT(t,n,r,i),e)}function ZT(e,t,n,r=W.HMA,i=!1){return KT(`HMA`,JT(t,n,r,i),e)}function QT(e,t,n,r,i=W.Close){return KT(`MACDEXP`,{source:i,inputs:{Period1:t,Period2:n,Period3:r},outFields:[W.MACD,W.MACDS,W.MACDH]},e)}function $T(e,t,n,r,i,a=!1){return new Cy({source:n,target:r,inputs:UT(t)},i,a,e)}function eE(e,t,n,r,i=null){return new wy({source:i,target:n,inputs:UT(t)},r,e)}function tE(e,t,n=W.PCTCHG){return KT(`PCTCHG`,{source:t,target:n,inputs:nE},e)}var nE={};function rE(e,t=W.TR){return KT(`_TR`,GT(t),e)}function iE(e,t,n=`SMA`,r=W.ATR){return KT(`ATR`,{target:r,inputs:{[z.INPUT_PERIOD]:t,[z.INPUT_SMOOTHING]:n},source:null},e)}function aE(e,t,n=`MA`,r=W.Close,i=W.ADJATR){return KT(`ADJATR`,{source:r,target:i,inputs:{[z.INPUT_PERIOD]:t,[z.INPUT_SMOOTHING]:n}},e)}function oE(e,t=W.ADL){return KT(`ADL`,GT(t),e)}function sE(e,t=W.TP){return KT(`TP`,GT(t),e)}function cE(e,t,n=W.Close,r=W.ROC){return KT(`ROC`,{source:n,target:r,inputs:UT(t)},e)}function lE(e,t,n,r=W.RSI,i=!1){return KT(`_RSI`,{source:n,target:r,inputs:{...UT(t),Modified:i}},e)}function uE(e,t=W.MFMUL){return KT(`MFV`,GT(t),e)}function dE(e,t,n,r=W.MSD){return KT(`MSD`,{source:n,target:r,inputs:UT(t)},e)}function fE(e,t,n,r=W.DRS){return KT(`DRS`,{target:r,inputs:WT(t),aggregation:n,source:null},e)}function pE(e,t=W.CSHO){return KT(`CSHO`,GT(t),e)}function mE(e,t,n){let r=`TCHN`;return KT(r,{inputs:{PeriodUpper:t,PeriodLower:t,Range:n},outFields:qT(r),source:null},e)}function hE(e,t,n,r=W.Close){let i=`BBANDS`,a=qT(i);return KT(i,{source:r,inputs:{[z.INPUT_PERIOD]:t,[z.INPUT_WIDTH]:n},outFields:a},e)}function gE(e,t){let n=`DONCHN`,r=qT(n);return KT(n,{inputs:UT(t),outFields:r,source:null},e)}function _E(e,t,n,r=W.MOVLR){return KT(`MOVLR`,{source:n,inputs:UT(t),target:r},e)}function vE(e,t,n,r=W.Close,i=W.HV){return KT(`HV`,{source:r,target:i,aggregation:n,inputs:UT(t)},e)}function X(e,t,n){return new cb(GT(e),t,n)}function Z(e,t,...n){return new ab(GT(e),t,...n)}function yE(e,t,n){return t-n}function bE(e,t,n){return(t-n)/n*100}function xE(e){switch(e.id){case`HL/2`:case`OC/2`:case`HLC/3`:case`OHLC/4`:case`HLCC/4`:return!0;default:return!1}}function SE(e){let t=e.source;if(e.sourceNeedsCompute=xE(t),e.sourceNeedsCompute){let n=X(t,se(wE,t),e.innerSeries[0]);e.addInner(n)}}function CE(e){let t=+!!e.sourceNeedsCompute;return[t,e.innCont(t)]}var wE=function(e,t){let[n,r,i,a]=[W.Open,W.High,W.Low,W.Close].map(e=>this.baseVal(e,t)),o=null,s=e.id;switch(s){case`Open`:o=n;break;case`High`:o=r;break;case`Low`:o=i;break;case`Close`:o=a;break;case`HL/2`:o=(r+i)/2;break;case`OC/2`:o=(n+a)/2;break;case`HLC/3`:o=(r+i+a)/3;break;case`OHLC/4`:o=(n+r+i+a)/4;break;case`HLCC/4`:o=(r+i+a+a)/4;break;default:break}return{[s]:o}},TE=function(e,t,n){let r=null;if(this.atLeast(n,e+1)){let i=this.baseVal(t,n-e);i!==null&&(r=this.baseVal(t,n)-i)}return{[this.target.id]:r}},EE={sma:YT,ma:J,ema:Y,wma:XT,hma:ZT};function DE(e,t,n=`Smoothing`){return EE[(e.inputs[n]??t).toLowerCase()]}var OE={atr:iE,adjatr:aE};function kE(e){return OE[e.inputs.TypeOfATR.toLowerCase()]}function AE(e){switch(e.unit){case g.Day:return 252;case g.Week:return 52;case g.Month:return 12;default:return 0}}function jE(e){let t=[W.High,W.Low];return e instanceof Ev&&be(e.targetFields,t).length!==2}function ME(e,t){return e[`Period${t}`]}function NE(e){return!(e instanceof xg)&&e.query instanceof Cv}var PE=class extends Nv{constructor(e,t){let n=Y(t,13,W.Close),r=QT(t,12,26,9,W.Close);super(e,t,n,r),this.query=t.query,this.useNotifications=!0}calculateAt(e){let t=p.Same,n=this.innVal(1,W.EMA,e),r=this.innVal(1,W.EMA,e-1),i=this.innVal(2,W.MACDH,e),a=this.innVal(2,W.MACDH,e-1);return P(n,r,i,a)&&(n>r&&i>a?t=p.Up:n<r&&i<a&&(t=p.Down)),{[W.BREL.id]:t}}getWrappers(){return this.wrapBaseFields(W.Open,W.High,W.Low,W.Close,W.Change,W.Volume,W.OpenInterest,W.TradingDay)}};function FE(e,t){return P(t)?(this[e]=t,null):this[e]}var IE=class{_domain;_range;_extent;_padding;constructor(){this._domain=this._range=this._extent=null,this._padding=[0,0]}domain(e){return FE.call(this,`_domain`,e)}range(e){return FE.call(this,`_range`,e)}padding(e){return FE.call(this,`_padding`,e)}get ready(){return P(this._domain,this._range)}},LE=1/Math.log2(10),RE=(e,t)=>n=>e*(1-n)+t*n,zE=(e,t)=>(t-=e,t>0?n=>(n-e)/t:e=>ue(isNaN(t)?NaN:.5));function BE(e,t){let n=zE(e[0],e[1]),r=RE(t[0],t[1]);return e=>r(n(e))}function VE(e){return Math.sign(e)*Math.log10(1+Math.abs(e/LE))}function HE(e){return Math.sign(e)*LE*(-1+10**Math.abs(e))}var UE=[[0,1],[1,10],[10,100],[100,1e3],[1e3,1e4],[1e4,1e5]],WE=class extends IE{constructor(e,t){super(),this.scaleType=e,this.axis=t}domain(e){return this.axis&&e&&!ge(e,this._domain)&&this.axis.pane.presenter.onScaleDomainChanged(this.axis),super.domain(e)}yToPrice(e){return this.mapValue(e)}rangeWithPadding(){return[this._range[0]+this._padding[0],this._range[1]-this._padding[1]]}mapValue(e,t=!0){if(!this.ready)return null;let n=ue,r=ue;switch(this.scaleType){case S.Linear:break;case S.Logarithmic:n=VE,r=HE;break;default:throw Error(`Unexpected scale type (neither linear nor log)`)}let i=this._domain.map(n),a=this.rangeWithPadding(),o=t?BE(a,i):BE(i,a),s=e=>a[1]-e+a[0];return(t?r:s)(o((t?s:n)(e)))}priceToY(e){return this.mapValue(e,!1)}getTicks(e){if(!this.ready)return[];let[t,n]=this._range.map(e=>this.mapValue(e,!0));if(t===n&&e>0)return[t];let[r,i]=this._domain;if(this.scaleType===S.Linear||r<0||i>1e5)return GE(t,n,e);let a=this.findLogBand(r),o=this.findLogBand(i),s=e*2;return o-a===0?GE(t,n,s):this.getLogTicks(a,o,s,n<t)}findLogBand(e){return UE.findIndex(([t,n])=>e>=t&&e<n)}getLogTicks(e,t,n,r){let i=[...this._domain],a=[];try{for(let o=e;o<=t;o++){let[s,c]=UE[o];o===e?s=i[0]:o===t&&(c=i[1]),this.domain([s,c]);let[l,u]=this._range.map(e=>this.mapValue(e,!0)),d=GE(l,u,n);a=r?d.concat(a):a.concat(d)}}finally{this.domain(i)}return je(a,r?(e,t)=>e>t:(e,t)=>e<t),a}checkTicks(){return this.scaleType===S.Logarithmic}};function GE(e,t,n){let r,i=-1,a,o,s;if(t=+t,e=+e,n=+n,e===t&&n>0)return[e];if((r=t<e)&&(a=e,e=t,t=a),(s=KE(e,t,n))===0||!isFinite(s))return[];if(s>0)for(e=Math.ceil(e/s),t=Math.floor(t/s),o=Array(a=Math.ceil(t-e+1));++i<a;)o[i]=(e+i)*s;else for(e=Math.floor(e*s),t=Math.ceil(t*s),o=Array(a=Math.ceil(e-t+1));++i<a;)o[i]=(e-i)/s;return r&&o.reverse(),o}function KE(e,t,n){let r=Math.sqrt(50),i=Math.sqrt(10),a=Math.sqrt(2),o=(t-e)/Math.max(0,n),s=Math.floor(Math.log(o)/Math.LN10),c=o/10**s;return s>=0?(c>=r?10:c>=i?5:c>=a?2:1)*10**s:-(10**-s)/(c>=r?10:c>=i?5:c>=a?2:1)}var qE={color:z.COLOR_TRANSPARENT},JE={color:z.COLOR_TRANSPARENT,width:0,dashStyle:`Solid`},YE=[W.Open,W.High,W.Low,W.Close],XE=new Set(YE.map(e=>e.id)),ZE=e=>XE.has(e.id),QE=new za(0,0,0,0),$E=class{axis;id;uid;record;metaData;timeSeries;notifyAboutPriceDomains=!1;customPlotValues=!1;_priceMapFirstIndex;priceMapper;_firstVisibleDate=null;_lastVisibleDate=null;main=!1;curves=[];type=C.Symbol;isShutDown=!1;targetFields=[];detachedScale;yScale=null;levels;bands;annotations;visFromIndex;visToIndex;_eventsData;precision;visible=!0;constructor(){this.axis=null,this.id=bt(),this.uid=this.id,this.record=new Kd(``),this.metaData=new aa,this.timeSeries=new xg,this.priceMapper=this._priceMapper.bind(this),this._priceMapFirstIndex=new Map}get title(){return``}get showPrevious(){return!1}getPreviousValue(){return null}get mainCurve(){return this.curves[0]}get hasEvents(){return!1}findEvents([e,t]){return[]}get eventsSeries(){return null}get hasEventsData(){return this.hasEvents&&P(this.eventsSeries)&&this.eventsSeries.hasData&&this.eventsSeries.container.size>0}getEventFor(e){return null}get isSymbol(){return this.is(C.Symbol)}get isExpression(){return this.is(C.Expression)}get isStudy(){return this.is(C.Study)}get isForward(){return this.is(C.Forward)}get isSeasonal(){return this.is(C.Seasonal)}getValueAt(e,t,n){return null}wrapIfAdvancedStyle(e){let t=e,n=e=>({outFields:e,inputs:{},source:null});return this.mainCurve.isHeikinAshiStyle?t=new Pv(n(Ih.slice()),e):this.mainCurve.isElderImpulseSystemStyle?t=new PE(n(Ih.slice().concat(W.BREL)),e):this.mainCurve.isPercentChangeStyle&&(t=new jS(n(Ih.slice()),e)),t}is(e){return this.type===e}getCacheableEntities(e){this.metaData.getCacheableEntities(e.metaData),this.timeSeries.getCacheableEntities(e.timeSeries)}fromModel(e){this.type=C[e.type];let t=e;this.uid=t.uid,this.main=t.main,t.levels&&(this.levels=t.levels),t.bands&&(this.bands=t.bands),P(t.precision)&&(this.precision=t.precision),this.curves=e.curves.map(e=>{let t=new W_;return t.plot=this,t.fromModel(e),t}),t.detachedScale&&(this.detachedScale=t.detachedScale,this.yScale=new WE(S.Linear,null)),this.visible=t.visible??!0}initialize(){}shutdown(){P(this.timeSeries)&&P(this.timeSeries.shutdown)&&!this.timeSeries.isCached&&this.timeSeries.shutdown(),this.isShutDown=!0}makeQuery(){let e=this.axis.pane.presenter,t=new Cv(null,e.data.aggregation,w.Normal,[pt(rt(e.data,null,`range`,`from`)),pt(rt(e.data,null,`range`,`to`))]);return t.barsToFetch=e.data.maxDataPoints||z.DEFAULT_MAX_RECORDS,t.aggregation.backAdjust&&(t.barsToFetch=4*t.barsToFetch),t.chartId=e.elementId,t.curveStyle=this.curves[0].style,t.visibleRange=rt(e.display,null,`xAxis`,`visibleRange`),t.extendedHours=e.data.extendedHours,t}priceToY(e){return(this.hasDetachedScale?this.yScale:this.axis.yScale).priceToY(e)}get hasDetachedScale(){return P(this.detachedScale,this.yScale)&&this.detachedScale}get hasVisibleCurves(){return this.curves.some(e=>e.visible)}getDetachedScaleMargins(){return z.DEFAULT_DETACHED_SCALE_MARGINS}setViewBox(e){if(!this.hasDetachedScale)return;let{y:t,height:n}=e,{top:r,bottom:i}=this.getDetachedScaleMargins();this.yScale.range([Math.floor(t+r*n),Math.floor(t+n-i*n)])}drawLevels(e){e.save();let t=z.OUT_OF_SCREEN;for(let n of this.levels.filter(e=>e.visible)){let r=this.priceToY(n.value);Oo(e,ko({line:n.line,fill:qE})),Qa(e,{x:-1,y:r},{x:t,y:r})}e.restore()}drawBands(e){e.save();let t=z.OUT_OF_SCREEN;for(let n of this.bands){let r=this.priceToY(n.range.to),i=this.priceToY(n.range.from);Oo(e,ko({fill:n.fill,line:JE})),Xa(e,new za(-1,r,t,i-r),!1)}e.restore()}drawAnnotations(e){e.save(),this.annotations.forEach(t=>t.draw(e,!0)),e.restore()}getEventFields(){return!this.hasEvents||!this.hasEventsData?[]:this.eventsSeries.container.fields.filter(e=>e!==W.DateTime)}getEventsAt(e){let t=this.eventsSeries.container,n=n=>t.getData(n)[e];return this.getEventFields().map(t=>{let r=n(t);if(!P(r))return null;let i=this.getEventFor(t);if(!P(i))return null;let a={field:t,value:r,date:n(W.DateTime),text:i.title,color:i.color};if(t===W.Custom&&r===z.FAKE_CUSTOM_EVENT){let t=e%2==0;return{...a,value:t?`___news`:`___video`,text:t?`N`:`V`}}else return a}).filter(e=>e!=null)}getRefEventField(e,t,n,r){let i=r?.container,a=e.fields[0];t&&(a=e.isOhlc?W.High:n.isTick?W.Last:W.Close);let o=[a,e.fields[0]].filter(N);return N(i)?o.find(e=>i.hasField(e))??a:a}getRefPlot(e){return this.axis.pane.isMain?e.mainPlot:this}drawEvents(e,t){let n=this.axis.pane.presenter,r=n.view.xAxis.xScale,i=r.domain();if(!P(i)||!P(i[0],i[1]))return;let a=(e,t=W.DateTime)=>e.container.getData(t),o=a(this.eventsSeries),s=this.getRefPlot(n),c=s.timeSeries,l=a(c),u=n.data.aggregation,d=s===n.mainPlot,f=a(c,this.getRefEventField(s.mainCurve,d,u,c));if(!Array.isArray(f))return;let{chart:{fontFamily:p}}=this.axis.pane.presenter.display,m=e=>e.valueOf()>=i[0].valueOf()&&e.valueOf()<=i[1].valueOf(),h=o.flatMap((e,i)=>m(e)?this.getEventsAt(i).map(e=>{let i=rh(u,e.date),a=Te(l,+i,Number);if(a<0||a>=f.length)return null;let o=f[a];if(!Ze(o))return null;t.has(a)||t.set(a,-1);let s=t.get(a);t.set(a,++s);let c=r.timeToX(i),d=n.view.getEventRadius(),p=this.axis.yScale.priceToY(o)-s*(d+d+d);return{visible:!0,...e,x:c,y:p,r:d,rect:QE}}).filter(N):[]);e.save();let g=!0;h.forEach(t=>{t.rect=to(e,t,p),this.customEventPopup?.visible&&t.date===this.customEventPopup.date&&(this.showCustomEventPopup(t),g=!1)}),e.restore(),this._eventsData=h,this.customEventPopup?.visible&&g&&this.hideCustomEventPopup()}get customEventPopup(){return this.axis.pane.presenter.view.customEventPopup}hideCustomEventPopup(){this.customEventPopup?.hide()}showCustomEventPopup(e){let{x:t,y:n,r,date:i,value:a}=e;this.customEventPopup?.show({x:t+2*r,y:n-2*r},i,a)}getCustomEventDataAt(e){if(!this._eventsData)return null;let t=this._eventsData.find(t=>t.rect.contains(e));return t?.field===W.Custom?t:null}hitTestCustomEvent(e){return this.getCustomEventDataAt(e)!==null}tryHandleCustomEventClick(e){let t=this.getCustomEventDataAt(e);return P(t)?(this.showCustomEventPopup(t),!0):!1}isEmpty(){let e=this.timeSeries;return P(e)&&e.hasData&&e.container.isEmpty}draw(e){if(this.visible){P(this.levels)&&this.drawLevels(e),P(this.bands)&&this.drawBands(e);for(let t of this.curves)t.draw(e)}}drawTopmost(e,t){this.hasEventsData&&this.drawEvents(e,t)}isComparison(e){return this.axis.comparison===e}invalidatePriceMappingCache(){this._firstVisibleDate=null}_priceMapper(e,t,n,r){if(!P(e)||!this.timeSeries.hasData||!this.shouldPriceMap(n,r))return e;let[i,a]=this.axis.pane.presenter.view.xAxis.xScale.domain()||[];if(!P(i)||!nn(i))return e;if(this._firstVisibleDate!==i){this._firstVisibleDate=i;let e=this.timeSeries.container.getTimeData(),t=t=>Te(e,+t,Number);this.visFromIndex=t(i),this.visToIndex=t(a),this._priceMapFirstIndex.clear()}return this._priceMapFirstIndex.has(n)||this.canPriceMap(t,n),this.priceMap(e,t,n,!1,r)}isOhlcMapping(e){return this.mainCurve.isOhlc&&ZE(e)}getRefPriceMapField(e){return this.isOhlcMapping(e)||e===W.PreviousClose?W.Close:e}dataOf(e){return this.timeSeries.container.getData(e)}canPriceMap(e,t){let n=this.getRefPriceMapField(t),r=this.dataOf(n),i=null,a=this.visFromIndex;for(;i===null&&a<=this.visToIndex;)i=r[a++];this._priceMapFirstIndex.set(n,i===null?NaN:a-1)}priceMap(e,t,n,r=!1,i=x.None){let a=this.getRefPriceMapField(n),o=this._priceMapFirstIndex.get(a);if(!Number.isFinite(o))return e;let s=this.dataOf(a)[o];return this.isComparison(x.Percent)||i===x.Percent?r?s+s*e/100:(e>=s?1:-1)*(Math.abs(e-s)*100)/Math.abs(s):r?s+e:e-s}shouldPriceMap(e,t){return P(t)?t!==x.None:this.isComparison(x.Percent)||this.isComparison(x.Value)}onPriceDomainsUpdated(){}get presenter(){return this.axis?.pane?.presenter}},eD=class extends $E{_symbol;_showPrevious;yearOffset;resolved=null;events;inputs=[];_eventsSeries;compare;tracePlot(e,t={}){zm(e,{chartId:this.axis?.pane?.presenter?.elementId,symbol:this.symbol,...t})}get symbol(){return this._symbol}get title(){return this.symbol}get showPrevious(){return this._showPrevious}getPreviousValue(){if(!P(this.timeSeries)||!P(this.timeSeries.record))return null;let e=this.axis.pane.presenter.display.chart.previous.field;return this.timeSeries.record.getValue(W[e])}getTimeSeries(){let e=$().getTimeSeriesDataSource(),t=this.makeQuery();switch(t.symbol=this.symbol,this.mainCurve.style){case h.Renko:case h.Kagi:case h.PointAndFigure:t.barsToFetch=10100,t.inputs=this.inputs;break;case h.Range:t.barsToFetch=4e3;break;case h.LineBreak:t.inputs=this.inputs;break}let n=this.axis.pane;if(P(n.alignedToYear)){let e=di(this.resolved??t.symbol);e!==null&&(this.yearOffset=n.alignedToYear-e.getFullYear(),t.offset=this.yearOffset)}let r=e.getTimeSeries(t);this.timeSeries=this.wrapIfAdvancedStyle(r),this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:re.Unspecified};this.presenter?.notifyHost(G.TS_MANYCHANGED,e),this.getEvents()}})}getMetaData(){this.metaData=$().getMetaDataSource().getMetaData(this.resolved),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(G.MD_CHANGED,{plot:this})})}getEvents(){if(!this.hasEvents)return;let e=$().getTimeSeriesDataSource(),t={symbol:this.symbol,seriesKind:w.Events,getHashKey:function(){return Object.values(this).filter(e=>typeof e!=`function`).join(`|`)}};z.EVENTS.forEach(e=>{t[e]=rt(this.events,!1,e,`show`)}),this._eventsSeries=e.getTimeSeries(t),this._eventsSeries.ready().then(e=>{e&&this.presenter?.notifyHost(G.TS_EVENTSCHANGED,{series:this.eventsSeries})})}get eventsSeries(){return this._eventsSeries??null}get hasEvents(){return P(this.events)?z.EVENTS.some(e=>rt(this.events,!1,e,`show`)):!1}findEvents(e){if(!this.hasEventsData||e[0]===null||e[1]===null)return[];let t=e[0],n=e[1];if(n>0&&this.axis?.pane?.presenter?.data?.aggregation?.isIntraday){let e=this.timeSeries.container.getTimeData()[n-1];if(this.compare(e,t))return[]}return this.eventsSeries.container.getTimeData().map((e,n)=>this.compare(e,t)?this.getEventsAt(n):[]).flat()}fromModel(e){super.fromModel(e);let t=e;this._showPrevious=t.showPrevious,this.events=t.events,this.inputs=t.inputs||[],this.compare=Fl(this.axis.pane.presenter.data.aggregation),this._symbol=t.symbol}getEventFor(e){let t=this.events[e.id.toLowerCase()];return!P(t)||!t.show?null:t}async initialize(){return Ai.call(this,async()=>(this.tracePlot(`plot:init:start`),this.resolved=await qr(this.symbol),this.isShutDown?(this.tracePlot(`plot:init:aborted`,{resolved:this.resolved}),!1):(this.getMetaData(),this.getTimeSeries(),this.tracePlot(`plot:init:ready`,{resolved:this.resolved}),!0)))}},tD=class extends eD{seriesKind;fundamental;constructor(e){super(),this.seriesKind=e}get showPrevious(){return!1}get title(){return`${this.curves[0].fields[0].name}(${g[this.fundamental].substring(0,1)})`}fromModel(e){this.fundamental=g[e.fundamental],super.fromModel(e)}makeQuery(){let e=new Cv(this.symbol,new Vl(this.fundamental),this.seriesKind);return e.fields=this.curves[0].fields,e}},nD=class{longPressTimeout;constructor(){this.longPressTimeout=null}getTouchCrosshairDelayMillis(){let e=$().config.touchCrosshairDelayMillis;return P(e)&&Number.isFinite(e)?e:z.LONG_PRESS_DELAY_MILLIS}startLongPress(e,t,n){Ie()&&(this.longPressTimeout=setTimeout(()=>this.longPressTriggered(e,t,n),this.getTouchCrosshairDelayMillis()))}longPressTriggered(e,t,n){this.cancelLongPress(),this.performLongPress(e,t,n)}cancelLongPress(){Ie()&&P(this.longPressTimeout)&&(clearTimeout(this.longPressTimeout),this.longPressTimeout=null)}performLongPress(e,t,n){}};function rD(e){return e.locked||e.axis.pane.presenter.display.allAnnotationsLocked}var iD=class extends nD{cursorSet;moved;snapToSupported;constructor(e,t,n){super(),this.annotation=e,this.previous=t,this.cursorSet=!1,this.moved=!1,this.snapToSupported=!1,this.startLongPress(null,t,n)}performLongPress(e,t,n){nO(this.annotation,n)}onMouseMove(e){if(this.cancelLongPress(),this.annotation.axis.pane.presenter.enableTooltip(!1),rD(this.annotation))return;let{point:t,view:n,offset:r}=e;if(!N(t)||t.axis!==this.annotation.axis)return;n.drawCrosshair({ap:t,offset:r}),this.cursorSet||=(this.previous.axis.pane.presenter.view.setCursor(ee.Move),!0);let i=ya(t.point,this.previous.point);this.annotation.offset(i),this.annotation.wasModifiedByTool(),this.annotation.requestRedraw(),this.previous=t,this.moved=!0}onMouseUp(e){this.cancelLongPress(),vk(this.annotation,this.moved,O.Moved)}},aD=class{pointIndex;snapToSupported=!0;moved=!1;alignPointsMode=!1;constructor(e,t){this.annotation=e,this.pointIndex=e.points.indexOf(t)}onMouseMove(e){if(this.alignPointsMode=e.getModifier(D.Shift),this.annotation.axis.pane.presenter.enableTooltip(!1),rD(this.annotation))return;let{point:t,view:n,offset:r}=e;if(n.drawCrosshair({ap:t,offset:r}),P(t)){let e=this.annotation.points[this.pointIndex],n=ya(t.point,e.point);switch(e.moveDirection){case te.Both:e.update(t.price,t.time);break;case te.Horizontal:e.update(e.price,t.time);break;case te.Vertical:e.update(t.price,e.time);break;default:break}this.moved=e.moveDirection!==te.None,this.moved&&this.annotation.wasPointMovedByTool(e,n)}this.annotation.requestRedraw()}onMouseUp(e){vk(this.annotation,this.moved,O.PointMoved)}},oD=class{constructor(e,t,n){this.anchor=e,this.isVertical=t,this.axis=n}hitTest(e){return P(this.anchor)?this.isVertical?Math.abs(e.x-this.anchor.x)<=z.HIT_TEST_TOLERANCE:Math.abs(e.y-this.anchor.y)<=z.HIT_TEST_TOLERANCE:!1}draw(e){let t=z.OUT_OF_SCREEN;this.isVertical?$a(e,this.anchor.x,-t,t):eo(e,this.anchor.y,-t,t)}},sD=class{id;axis;_price;_time;passive=!1;moveDirection=te.Both;visible=!0;point;constructor(e,t,n){this.id=bt(),this.axis=e,t!==void 0&&n!==void 0&&(this.price=t,this.time=n,this.toPoint())}get price(){return this._price}set price(e){this._price=e}get time(){return this._time}set time(e){this._time=e}get movable(){return this.moveDirection!==te.None}get presenter(){return this.pane.presenter}get pane(){return this.axis.pane}toPoint(){let e=this.axis.toPoint(this);P(e)&&Ze(e.x)&&Ze(e.y)&&(this.point=e)}update(e,t){this.price=e,this.time=typeof t==`number`?new Date(t):t,this.toPoint()}updateFromPoint(e){let t=this.axis.toAnnotationPoint(e);this.price=t.price,this.time=t.time,this.point=e}hitTest(e){return this.visible?this.distance(e)<=z.HIT_TEST_TOLERANCE:!1}distance(e){let t=e.x-this.point.x,n=e.y-this.point.y;return Math.abs(Math.sqrt(t*t+n*n)-z.HALF_ANN_POINT_DIMENSION)}draw(e,t){if(P(this.point)){let n=z.HALF_ANN_POINT_DIMENSION;P(t)&&t.locked&&(n*=.6),e.beginPath(),e.ellipse(this.point.x,this.point.y,n,n,0,0,2*Math.PI),e.stroke()}}};function cD(e){return ja(e.fill.color).a===0?e.line.color:e.fill.color}function lD(e,t){return{uid:e.uid,id:e.name,traits:{...e.extractTraits(!0),...e.extractTraits(!1)},extras:{},points:e.extractPoints(),visible:e.visible,locked:e.locked,isUndoRedo:!0,toolChange:t}}function uD(e){return{uid:e.uid,id:e.name,traits:e.extractTraits(!0),extras:e.extractTraits(!1),points:e.extractPoints(),visible:e.visible,locked:e.locked,chart:e.axis.pane.presenter.accessor}}var dD=class{points=[];isSelected=!1;drawn=!0;axis;name;uid;alignPointsSupported=!1;visible=!0;locked=!1;computed=!1;_traits;adjustFill;constructor(e,t){this.axis=e,this.name=t,this.uid=bt()}requestRedraw(){this.axis.pane.presenter.view?.redraw()}prepareDraw(e,t){return this.drawPoints(e,t),this.readyToDraw()}readyToDraw(){return this.activePoints.every(e=>e.point!==void 0)}getPriceScaleAdornments(){return z.EMPTY_ARRAY}getTimeScaleAdornments(){return z.EMPTY_ARRAY}extractTraits(e=!0){let t=F(this.traits),n=ts(this.name);return Object.keys(t).forEach(r=>{let i=n.includes(r);(e&&!i||!e&&i)&&delete t[r]}),e||[`line`,`fill`,`zIndex`].forEach(e=>delete t[e]),t}extractPoints(){return this.activePoints.map(e=>({price:e.price,time:Xe(+e.time,4)}))}offset(e){this.points.filter(e=>e.movable).forEach(t=>{t.updateFromPoint(ba(t.point,e))})}get traits(){return this._traits||=F(this.defaultTraits),this.adjustFill&&=(this._traits.fill.color=cD(this._traits),!1),this._traits}set traits(e){e!==void 0&&ht(this.traits,e)}get activePoints(){return this.points.filter(e=>!e.passive)}get style(){return ko(this.traits)}get defaultTraits(){return Do(this.axis.pane.presenter.display,this.name)}get defaultStyle(){return ko(this.defaultTraits)}get adornStyle(){let e=F(this.defaultTraits);return e.fill.color=this.traits.line.color,e.line.width=0,e.line.color=z.COLOR_TRANSPARENT,ko(e)}get pointsStyle(){let e=F(this.defaultTraits);return e.line.dashStyle=`Solid`,ko(e)}get allowPricesChangeUI(){return this.traits?.allowPricesChangeUI}wasModifiedByTool(){}wasPointMovedByTool(e,t){}isPointDrawn(e){return e.price!==void 0}drawPoints(e,t){this.points.forEach(n=>{let r=this.isPointDrawn(n),i=P(e);t&&(r||!i)&&n.toPoint(),i&&r&&(this.isSelected||this.drawn)&&(Oo(e,this.pointsStyle),n.draw(e,this))})}addPoints(e){for(let t=0;t<e;t++)this.points.push(new sD(this.axis))}toModel(){let e=this.extractPoints();return{id:this.name,uid:this.uid,visible:this.visible,locked:this.locked,points:e,traits:F(this.traits)}}canMove(e){return!0}updatePoints(e){}updateActivePoints(e){let t=this.activePoints;t.length===e.length&&t.forEach((t,n)=>{let r=e[n];t.update(r.price,r.time)})}updateFrom(e,t,n,r,i){typeof r==`boolean`&&(this.visible=r),typeof i==`boolean`&&(this.locked=i);let a=P(e)?F(e):{};P(t)&&ht(a,t),this.traits=a,P(n)&&this.updatePoints(n)}priceMap(e){return this.axis.priceMap(e)}flip(e){let t=this.getFlipAnchorIndices();if(!N(t))return;let n=this.points[t[0]],r=this.points[t[1]];if(e){let e=r.time;r.update(r.price,n.time),n.update(n.price,e)}else{let e=r.price;r.update(n.price,r.time),n.update(e,n.time)}this.wasModifiedByTool()}getFlipAnchorIndices(){return null}};function fD(e,t,n,r){return function(i,a=!0){let o=new t(i,e,n);return a?i.appendAnnotation(o):o.drawn=!1,P(r)&&(o.traits=r),o}}var pD=class{axis;angle;extent;anchor1;anchor2;p1;p2;style;extended;_data;isTrend;constructor(e,t,n,r,i){this.axis=i,P(e,t)&&(this.angle=xa(e,t),this.extent=this.getExtent(e,t),this.anchor1=e,this.anchor2=t,this.p1=n?this.extendPoint(t,-1):e,this.p2=r?this.extendPoint(e,1):t),this.extended=n||r}extendPoint(e,t){return{x:e.x+t*this.extent*Math.cos(this.angle),y:e.y+t*this.extent*Math.sin(this.angle)}}getExtent(e,t){let n=Math.max(Math.abs(e.x),Math.abs(t.x)),r=Math.max(Math.abs(e.y),Math.abs(t.y));return Math.sqrt(n*n+r*r)+z.OUT_OF_SCREEN}hitTest(e){return P(this.p1,this.p2)?Sa([this.p1,this.p2],e,z.HIT_TEST_TOLERANCE):!1}draw(e){P(this.p1,this.p2)&&(Qa(e,this.p1,this.p2),this.extended)}getAdornOffset(e){let t=Ka(e),n=Wa(e,1);return _a(this.p1,this.p2)<0&&(t.y=n+5),t}},mD=class{style;axis;rect;constructor(e,t,n,r){this.axis=r,this.rect=new za(e.x,e.y,t,n)}hitTest(e){return this.rect.contains(e)}draw(e,t){Xa(e,this.rect)}},hD=class extends dD{countCache;constructor(e,t){super(e,t)}draw(e,t){if(this.prepareDraw(e,t)&&!this.getScreenPoints().some(e=>!P(e))&&!this.drawn){let t=this.getElements();Oo(e,this.style),t.forEach((t,n)=>{Oo(e,this.getStyleForElement(t,n)),t.draw(e)}),Oo(e,this.adornStyle),this.adornElements(t,e);let n=this.getMarkers();Oo(e,this.style),n.forEach(t=>{t.draw(e)})}}getBarCount(e,t){if(this.countCache===void 0||this.countCache.time1!==e||this.countCache.time2!==t){let n=this.axis.pane.presenter.view;this.countCache={time1:e,time2:t,barCount:Math.abs(n.toIndex(e)-n.toIndex(t))}}return this.countCache.barCount}getElements(){return[]}get presenter(){return this.axis.pane.presenter}get formatter(){return this.presenter.mainPlot.metaData}data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}getScreenPoints(){return this.points.map(e=>e.point)}getStyleForElement(e,t){return this.style}adornElements(e,t){}hitTestAdornments(e,t){return!1}getTextRef(){return null}hitTest(e){if(!this.drawn&&this.visible){if(this.getScreenPoints().some(e=>!P(e)))return!1;let t=this.getElements(),n=this.getMarkers();return t.some(t=>t.hitTest(e))||n.some(t=>t.hitTest(e))?!0:this.hitTestAdornments(t,e)}return!1}updatePointsFrom(e,t=0){e.forEach((e,n)=>this.points[t+n].update(e.price,e.time))}updatePoints(e){this.allowPricesChangeUI&&this.updatePointsFrom(e)}getMarkers(){return[]}get marker(){return this.traits?.marker}get showPrices(){return this.traits?.showPrices}get singleStyle(){return tt(this.traits?.singleStyle,!0)}get showBackground(){return tt(this.traits?.showBackground,!1)}get backgroundOpacity(){return tt(this.traits?.backgroundOpacity,0)}fillOnlyStyle(e){return ko({line:{color:z.COLOR_TRANSPARENT,dashStyle:`Solid`,width:0},fill:this.traits[e]})}lineOnlyStyle(e){return ko({fill:{color:z.COLOR_TRANSPARENT},line:this.traits[e]})}makeLine(e,t){return new pD(e,t,!1,!1,this.axis)}applyBackgroundOpacity(e){return Ta(wa(e),this.backgroundOpacity)}getTraitsFor(e){let t={fill:{color:z.COLOR_TRANSPARENT},line:{...e.line}};return this.showBackground&&(t.fill.color=this.applyBackgroundOpacity(t.line.color)),t}getFlipAnchorIndices(){return this.points.length===2?[0,1]:null}},gD=class extends hD{_factors;constructor(e,t){super(e,t)}get factorsPropName(){return z.AT_FACTORS}get factors(){return So(this._factors??this.traits[this.factorsPropName])}getStyleForElement(e,t){return e.style??super.getStyleForElement(e,t)}get showLevels(){return this.traits[z.AT_SHOW_LEVELS]}get levelsKind(){return this.traits[z.AT_LEVELS_KIND]}get labels(){return this.traits[z.AT_LABELS]}get isExtended(){return this.points.length===3}isBefore(e,t){return this.points[e].time<this.points[t].time}comparePoints(e,t,n){let r=this.isBefore(e,t);return n||(r=!r),this.points[r?e:t].point}getPoint(e){return this.isExtended?this.comparePoints(1,2,e):this.comparePoints(0,1,e)}get leftPoint(){return this.getPoint(!0)}get rightPoint(){return this.getPoint(!1)}get pricesOnScale(){return this.traits[z.AT_PRICES_ON_SCALE]}formatLevelPrice(e,t){let n=this.levelsKind===z.AT_LEVELS_PERCENTS,r=``;if(this.showLevels&&(r=n?`${(e*100).toFixed(1)}%`:e.toString()),this.showPrices){let e=this.priceMap(this.axis.toPrice(t));r=(r+` (${s_(this.axis,e)})`).trim()}return r}getAdornPointAndAlign(e,t){let n=this.labels,r=e instanceof pD,i=(e,t,n)=>({pt:e,align:t,offset:n});switch(n){case z.AT_LABELS_LEFT:return i(r?e.anchor1:e,T.Right,-t);default:case z.AT_LABELS_RIGHT:return i(r?e.anchor2:e,T.Left,t);case z.AT_LABELS_CENTER:return i(r?ga(e.anchor1,e.anchor2):e,T.Center,0)}}getColoredElements(e){let t=this.singleStyle;return this.factors.map(n=>{let r=e(n);return r===null?null:(t||(r.style=ko(this.getTraitsFor(n))),r._data={factor:n.value},r)}).filter(e=>e!==null)}hitTestAdornments(e,t){let n=this.showLevels,r=this.getTextRef();if(!n||r===null)return!1;let i=this.axis.pane.presenter,a=i.view?.mainContext;if(!a)return!1;let o=null,s=!1;a.save();let{chart:{fontFamily:c},yAxis:{fontSize:l}}=i.display;a.font=`${l??12}px ${c}`;for(let n of e){if(!P(n._data))continue;let{factor:e}=n._data,{ref:i,spacing:c,offsetY:l,text:u}=r(o,n,e),{pt:d,align:f,offset:p}=this.getAdornPointAndAlign(i,c);if(qa(a,u,this.getAdornTextPoint(a,l,d,p),f).contains(t)){s=!0;break}o=n}return a.restore(),s}adornElementsForColoredFactors(e,t,n,r){let i=this.singleStyle,a=this.showBackground,o=this.showLevels,s=this.applyBackgroundOpacity(this.traits.line.color),c=r.fillStyle,l=null;e.forEach(e=>{if(!P(e._data))return;let{factor:u}=e._data;if(a){let n=t(l,e);r.fillStyle=i?s:e.style.fillStyle,r.fill(n)}if(o){let{ref:t,spacing:a,offsetY:o,text:s}=n(l,e,u),{pt:d,align:f,offset:p}=this.getAdornPointAndAlign(t,a);Ja(r,s,this.getAdornTextPoint(r,o,d,p),f,i?c:e.style.strokeStyle)}l=e})}getAdornTextPoint(e,t,n,r){let i=Wa(e,.75);return ba(n,{x:r,y:t===!0?i/2:t})}},_D=class extends hD{lines;constructor(e,t){super(e,t),this.resetComputedState()}get rectStyle(){return this.fillOnlyStyle(z.AT_FILL)}get rect(){let[e,t,,]=this.getScreenPoints(),n=new mD({x:e.x,y:Math.min(e.y,t.y)},t.x-e.x,Math.abs(e.y-t.y),this.axis);return n.style=this.rectStyle,n}get reverse(){return!1}getLinesDataAtLevels(e,t){let[n,r]=this.points;if(this.reverse&&([n,r]=[r,n]),this.lines==null){let i=(e,t=!1)=>n=>({level:n.value,domain:e(n.value),traits:this.getTraitsFor(n),isPrice:t}),a=r.price-n.price,o=i(e=>n.price+e*a,!0),s=e?.map(o)??[],c=this.axis.pane.presenter.timeline,l=Te(c,+n.time,Number,h_),u=Te(c,+r.time,Number,h_)-l,d=i(e=>+c.at(l+Math.floor(e*u)));this.lines={prices:s,times:t?.map(d)||[],barsDiff:u,priceDiff:a}}return this.lines}makeColoredLine(e,t,n){let r=this.makeLine(e,t);return this.singleStyle||(r.style=ko(n.traits)),r._data={level:n.level,isPrice:n.isPrice},r}getLineElements(e){let[t,n]=this.getScreenPoints();return{priceLines:e.prices.map(e=>{let r=this.axis.toY(e.domain);return this.makeColoredLine({x:t.x,y:r},{x:n.x,y:r},e)}),timeLines:e.times.map(e=>{let r=this.presenter.view.toX(e.domain);return this.makeColoredLine({x:r,y:t.y},{x:r,y:n.y},e)})}}getStyleForElement(e,t){return e.style||super.getStyleForElement(e,t)}resetComputedState(){}wasModifiedByTool(){this.resetComputedState()}wasPointMovedByTool(e,t){this.wasModifiedByTool()}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}},vD=class extends sD{constructor(e,t,n){super(e),this.priceRef=t,this.timeRef=n,this.passive=!0}get price(){return this.priceRef.price}get time(){return this.timeRef.time}set price(e){this.priceRef.price=e}set time(e){this.timeRef.time=e}},yD=class{constructor(e){this.points=e}get left(){return Math.min(this.points[0].point.x,this.points[1].point.x)}get top(){return Math.min(this.points[0].point.y,this.points[1].point.y)}get width(){return Math.abs(this.points[1].point.x-this.points[0].point.x)}get height(){return Math.abs(this.points[1].point.y-this.points[0].point.y)}getRect(){return P(this.points[0].point,this.points[1].point)?new za(this.left,this.top,this.width,this.height):null}};function bD(e){let t=new sD(e),n=new sD(e);return[t,n,new vD(e,t,n),new vD(e,n,t)]}var xD=class extends dD{helper;constructor(e,t){super(e,t),this.points=bD(e),this.helper=new yD(this.points)}get left(){return this.helper.left}get top(){return this.helper.top}get width(){return this.helper.width}get height(){return this.helper.height}getRect(){return this.helper.getRect()}draw(e,t){return this.prepareDraw(e,t)?(Oo(e,this.style),!0):!1}updatePoints(e){this.allowPricesChangeUI&&e.length===2&&e.forEach((e,t)=>this.points[t].update(e.price,e.time))}},SD=class{helper;_actualWidth=0;_fontSizeForWidth=0;constructor(e,t,n){this.points=e,this.lines=t,this.axis=n,this.helper=new yD(this.points)}hitTest(e){let t=this.getRect();return N(t)?(t.width=this._actualWidth,t.contains(e)):!1}getRect(){return this.helper.getRect()}get fontSize(){if(this.lines.length===0)return 0;let{height:e}=this.getRect();return Math.floor(e/this.lines.length)}computeActualWidth(e){(this._actualWidth<=0||this._fontSizeForWidth!==this.fontSize)&&(this._actualWidth=Math.max(...this.lines.map(t=>e.measureText(t).width)),this._fontSizeForWidth=this.fontSize)}draw(e){if(this.lines.length===0)return;e.save();let{x:t,y:n}=this.getRect(),{chart:{fontFamily:r}}=this.axis.pane.presenter.display,i=this.fontSize;e.textAlign=`left`,e.textBaseline=`top`,e.font=`${i}px ${r}`,this.lines.forEach((r,a)=>{let o=n+i*a;e.fillText(r,t,o)}),this.computeActualWidth(e),e.restore()}},CD=class extends hD{textEditable;_textAnnElement;constructor(e,t){super(e,t),this.textEditable=!0,this.points=bD(e),this.adjustFill=!0}get textLines(){return this.traits[z.AT_TEXT_LINES]}set textLines(e){this.traits[z.AT_TEXT_LINES]=e,this._textAnnElement=void 0}get textElement(){return!P(this._textAnnElement)&&this.visible&&(this._textAnnElement=new SD(this.points,this.textLines,this.axis)),this._textAnnElement}updateFrom(e,t,n,r,i){super.updateFrom(e,t,n,r,i),this._textAnnElement=void 0}getElements(){return this.visible?[this.textElement]:[]}},wD=class extends CD{constructor(e,t){super(e,t),this.textEditable=!1}canMove(e){return this.visible?this.textElement.hitTest(e):!1}get prices(){return this.traits.prices}get pricesPoints(){let e=this.points[0].time;return this.prices.map(t=>new sD(this.axis,t,e))}updateFrom(e,t,n,r,i){super.updateFrom(e,t,n,r,i),P(e?.textLines)&&(this.textLines=e.textLines)}getElements(){let e=super.getElements(),t=this.pricesPoints.map(e=>new oD(e.point,!1,this.axis));return e.concat(t)}getPriceScaleAdornments(){if(!this.showPrices)return super.getPriceScaleAdornments();let e=this.traits.line;return this.prices.map(t=>({price:t,color:e.color}))}get defaultFont(){let{chart:{fontSize:e,fontFamily:t}}=this.axis.pane.presenter.display;return[e??13,t]}updateOtherPoints(e){let[t,n]=this.defaultFont;e.save(),e.font=`${t}px ${n}`;let r=Math.max(...this.textLines.map(t=>e.measureText(t).width)),{x:i,y:a}=this.points[0].point;this.points[1].updateFromPoint({x:i+r,y:a+this.textLines.length*t}),e.restore()}},TD=class{annotation;constructor(e){this.annId=e}onKeyDown(e){if(this.annId==null)return;let{key:t,code:n,presenter:r}=e;Re(t,n)&&(P(this.annotation)&&(this.annotation.axis.deleteAnnotation(this.annotation,!1),r.view.redraw()),_k(r,{toolChange:O.Cancelled,annId:this.annId}))}},ED=class extends TD{dragged=!1;snapToSupported=!0;isDrawingAnnotation=!0;forceAlignPoints=!1;indices;alignPointsMode=!1;constructor(e,t=!1){super(e.annName),this.factory=e,this.thirdPoint=t,this.indices=t?[0,1,2]:[0,1]}signalChange(){this.annotation.wasModifiedByTool(),this.annotation.requestRedraw()}onMouseDown(e){let{point:t,button:n}=e;if(t===void 0)return;let r=N(this.annotation);if(n===E.Left)if(r){let e=!this.thirdPoint||this.dragged?1:2;this.annotation.points[e].update(t.price,t.time),this.dragged=!1,this.signalChange(),(!this.thirdPoint||e===2)&&this.finish()}else this.dragged=!0,t.axis.pane.presenter.clearSelection(),this.annotation=this.factory(t.axis),this.annotation.drawn=!1,this.indices.forEach(e=>this.annotation.points[e].update(t.price,t.time)),this.signalChange();return!0}onMouseMove(e){let{point:t,view:n,offset:r}=e;return n.drawCrosshair({ap:t,offset:r}),P(this.annotation,t)&&(this.alignPointsMode=this.forceAlignPoints||e.getModifier(D.Shift),this.dragged?(this.annotation.points[1].update(t.price,t.time),this.signalChange()):this.thirdPoint&&!this.dragged&&(this.annotation.points[2].update(t.price,t.time),this.signalChange())),!0}finish(){vk(this.annotation,!0,O.Created)}isAccidentalMouseUp(e){let{point:t}=e,n=this.annotation.points[0].point;return!t?.point||!n?!1:va(t.point,n)<z.HIT_TEST_TOLERANCE}onMouseUp(e){if(this.annotation===void 0){yk(e);return}if(this.isAccidentalMouseUp(e)){this.dragged=!0;return}this.dragged=!1,this.thirdPoint||this.finish()}},DD=class extends ED{constructor(e,t=!1){super(e,t),this.forceAlignPoints=!0}},OD=class extends ED{constructor(e){super(e,!1),this.snapToSupported=!1}onMouseMove(e){let{point:t,view:n,offset:r}=e;if(n.drawCrosshair({ap:t,offset:r}),P(this.annotation)&&this.dragged){let[e,n]=this.annotation.points;n.update(t.price,t.time);let r=ya(n.point,e.point),i=e.point.y+r.x*Math.sign(r.y)*Math.sign(r.x),a=this.annotation.axis.toPrice(i);n.update(a,t.time),this.signalChange()}return!0}},kD=class extends TD{isNew;anchor;clicks=0;snapToSupported=!1;isDrawingAnnotation;textArea;constructor(e,t){super(e?e.annName:null),this.factory=e,this.existing=t,this.isNew=!P(t),this.isNew||(this.anchor=this.existing.points[0]),this.isDrawingAnnotation=this.isNew}getChartParent(){return this.anchor.axis.pane.presenter.view.canvasContainer}styleProps(){if(this.isNew)return{height:100,fontSize:`100%`,color:cD(Do(this.anchor.axis.pane.presenter.display,`Text`))};{let e=this.existing.textElement;return{height:e.getRect().height*1.05,fontSize:`${Math.round(e.fontSize)}px`,color:this.existing.traits[z.AT_FILL].color}}}onMouseDown(e){let{point:t}=e;if(this.isNew)if(this.clicks===0){if(t===void 0){yk(e);return}t.axis.pane.presenter.clearSelection(),this.anchor=t,this.clicks++,this.startEditing()}else this.onEndEditing();else this.onEndEditing()}startEditing(){this.textArea=document.createElement(`textarea`);let{x:e,y:t}=this.anchor.point,n=this.anchor.axis.pane.getBounds(),r=n.x+n.width-this.anchor.point.x,{height:i,fontSize:a,color:o}=this.styleProps();Si(this.textArea,{position:`absolute`,top:`${t}px`,left:`${e}px`,border:`none`,outline:`none`,overflow:`hidden`,height:`${i}px`,width:`${r}px`,resize:`none`,backgroundColor:`rgba(255, 255, 255, 0.05)`,zIndex:`5`,fontSize:a,color:o}),this.getChartParent().appendChild(this.textArea),this.textArea.onblur=this.onEndEditing.bind(this),this.textArea.onkeydown=e=>e.stopImmediatePropagation(),this.isNew||(this.textArea.value=this.existing.textLines.join(`
|
|
32
|
+
`}function j_(e,t,n=null){return A_(e,t,n,`value-title`)}function M_(e,t,n){let r=typeof n==`string`?at(n):null,i=r===null?``:` style="color: ${r}"`,a=P(e)?it(e):null;return`${a===null?``:`<span class="field-name">${a}</span>`}<span${i} class="field-value">${it(t)}</span>`}function N_(e){return`<a class="delete-plot" data-plot-uid="${at(e)}" title="Delete plot">${T_(`delete`)}</a>`}function P_(e,t){let n=e>0,r=e<t-1;return[`${n?O_(!0,e):``}`,`${r?O_(!1,e):``}`].join(` `).trim()}function F_(e,t){return e.startsWith(z.FAKE_SYMBOL_PREFIX)&&t.length>0?t:e}function I_(e,t,n,r,i,a){let o=L_(e,t);o.offset=n,o.lastBarRefresh=!!r||!1,o.chartId=e.elementId;let s=n=>n.axes.map(e=>e.plots).flat().filter(t=>i?t===e.mainPlot:!0).map(n=>V_(e,t,a,o,n)).filter(e=>e!==null);return o.panes=e.panes.map(e=>({bounds:R_(e),id:e.id,plots:s(e)})),o}function L_(e,t){let n=e.data.aggregation,r=e.display.xAxis,i=r.isOrdinal,a=N(i)&&i,o=a?r.ordinalName??`Value`:`Date`;return{date:a?i_(t):p_(n,t),time:n.isEndOfDay||a?null:m_(n,t,!1),isMultiSymbol:H_(e),isMultiContract:n.isMultiContract,dateFieldName:o}}function R_(e){let t=e.getBounds();if(!P(t))return;let{x:n,y:r,width:i,height:a}=t,{leftOffset:o,rightOffset:s}=e.presenter.view;return{top:r,left:n+o,right:s,bottom:r+a,width:i,height:a}}function z_(e,t,n,r=!1){let i=e.plot,a=i.timeSeries.container,o=i.axis.pane.presenter.timeline,s=Te(o,+n,Number,h_),c=o.at(s-e.shift);if(c===null)return[null,0];let l=a.getTimeData(),u=Te(l,+c,Number);return[!l[u]||l[u].getTime()!==c.getTime()?null:e.dataAt(t,u,!r),u]}function B_(e,t,n){P(e.precision)?n.overridePrecision=e.precision:e.isStudy&&P(t.mainPlot?.precision)&&!P(gs(e.model.study).meta.decimals)&&(n.overridePrecision=t.mainPlot.precision)}function V_(e,t,n,{isMultiContract:r},i){let a=i.isStudy;if(!i.timeSeries.hasData)return null;let o=i.timeSeries.container;i.type,C.Expression;let s=i.axis.comparison!==x.None,c=i.axis.comparison===x.Percent,l=(e,r)=>i.customPlotValues&&r!==W.DateTime?[i.getValueAt(r,t,n),0]:z_(e,r,t,s),u=i,d=a?`${gs(u.model.study).meta.title} ${u.fullParams}`:i.metaData.name||``,f={isMain:i.main,type:i.type,typeName:C[i.type],name:F_(i.title,i.metaData.symbol),description:d,exchange:i.metaData.exchange||``,error:u.errorText,id:i.id,uid:i.uid,visible:i.visible,seasonalOffset:i.isSeasonal?u.offset??void 0:void 0};if(P(u.yearOffset)&&u.yearOffset!=0){let n=e.data.aggregation;f.unalignedDate=p_(n,zr(t,u.yearOffset))}let p=i.curves[0],m=i.type===C.Symbol&&oi(i.title);if(r&&i.type===C.Symbol&&o.hasField(W.Symbol)){let e=t.valueOf()===z.ZERO_DATE.valueOf()?i.timeSeries.container?.getLastDataPoint(W.Symbol):l(p,W.Symbol)[0];P(e)&&e.length>0&&(f.actualSymbol=e,m||(f.name=e))}let g={},_={range:i.axis.yScale.domain(),allDigits:!0};B_(i,e,_);let v=(e,t)=>{let n=(t===W.Change||t===W.PercentChange)&&e>0?`+`:``;return c?n+a_(e):n+i.metaData.format(e,t,_)},y=v_(e),b=new Set;return f.values=i.curves.filter(e=>e.visible).map(e=>(!i.main&&i.isSymbol&&y?Ih:e.fields).map(t=>{if(b.has(t))return null;b.add(t);let[n,r]=l(e,t),o=i.axis.yScale.priceToY(n);g[t.id]=!0;let s=i.customPlotValues?u.getColorOf(t):e.getColor(r,e.style!==h.HollowCandles,t),c=v(n,t).trim();if(P(n)&&t===W.Change){let[t]=l(e,W.PercentChange);P(t)&&(c+=` (${v(t,W.PercentChange)})`)}return{abbreviation:U_(t),shortName:t.shortName,id:t.id,name:t.name,longName:`${t.shortName} ${a?u.params:``}`.trim(),color:wa(s),val:n,y:o,value:c}}).filter(e=>e!==null)).flat(),f.events=i.findEvents(l(p,W.DateTime)).filter(e=>e.field!==W.Custom),f}function H_(e){let t=e.mainPlot.symbol;return e.allPlots.some(e=>e.type===C.Symbol&&e.symbol!==t)}function U_(e){return e.id===W.Change.id?`Δ`:e.id.substring(0,1)}var W_=class{plot;id;fields=[];colors=[];style=h.Line;attributes=[];zones;_shift=0;lineWidth=1;lineMarker;lineSmoothing;dashStyle=`Solid`;varyColorPerBar=!1;visible=!0;_zoneColors;constructor(){this.id=bt(),this.plot=null}get shift(){return this._shift}set shift(e){this._shift=P(e)?e:0}get isOhlc(){return(this.isOhlcStyle||this.isCandle||this.isHlcStyle||this.isElderImpulseSystemStyle||this.isRangeStyle)&&this.fields.includes(W.Close)}get name(){return this.isOhlc?``:this.fields[0].name}get isHeikinAshiStyle(){return this.style===h.HeikinAshi}get isCandle(){return this.style===h.Candlestick||this.style===h.HollowCandles||this.style===h.HeikinAshi}get isHollowCandles(){return this.style===h.HollowCandles}get isElderImpulseSystemStyle(){return this.style===h.ElderImpulseSystem}get isPercentChangeStyle(){return this.style===h.PercentChange}get isOhlcStyle(){return this.style===h.OHLC}get isHlcStyle(){return this.style===h.HLC}get isRangeStyle(){return this.style===h.Range}get isRenko(){return this.style===h.Renko}get isKagi(){return this.style===h.Kagi}get isPointAndFigure(){return this.style===h.PointAndFigure}get isLineBreak(){return this.style===h.LineBreak}get isBaseline(){return this.style===h.Baseline}get isLineLike(){return[h.Line,h.Area,h.Baseline,h.PercentChange].includes(this.style)}get isColumn(){return this.style===h.Column}get isMultiColumn(){return this.style===h.MultiColumn}get isStackedColumn(){return this.style===h.StackedColumn}isFirstVisibleOfStyle(){return this.plot.curves.find(e=>e.visible&&e.style===this.style)===this}fromModel(e){e.attributes&&(this.attributes=e.attributes.map(e=>m[e])),this.colors=e.colors,this.fields=e.fields.map(e=>W[e]),this.style=h[e.style],this.lineWidth=e.lineWidth,this.dashStyle=e.dashStyle,this.lineMarker=e.lineMarker,this.lineSmoothing=e.lineSmoothing,this.varyColorPerBar=e.varyColorPerBar,this.visible=e.visible??!0,e.zones&&(this.zones=e.zones),this.shift=e.shift}get axis(){return this.plot?.axis}get pane(){return this.axis?.pane}get timeSeries(){return this.plot?.timeSeries}get presenter(){return this.pane?.presenter}get view(){return this.presenter?.view}yToPrice(e){return this.yScale.yToPrice(e)}priceToY(e){return this.yScale.priceToY(e)}dataAt(e,t,n=!0){let r=!this.plot.isComparison(x.None),i=e===W.PercentChange,a=e===W.Change,o=i||(!n||r)&&a,s=this.timeSeries.container.hasField(W.Last)?W.Last:W.Close,c=o?s:e,l=(e,t)=>{let n=this.timeSeries.container.getData(e)[t];return e.type===v.Number?this.plot.priceMapper(n,t,e):n},u=l(c,t);if(!o)return u;if(t<=1)return 0;let d=l(c,t-1),f=u-d;return i?d===0?0:f/d:f}timeSeriesAt(e){let t=this.timeSeries.container.getTimeData(),n=t.length;return e<0||e>n-1?null:t[e]}timelineAt(e){return this.presenter.timeline.at(e)}get shiftedTimeDomain(){let e=this.view.xAxis.xScale;return P(e.extent())?this.shift===0?e.domain():e.extent().map(t=>e.timeline.at(t-this.shift)):null}get yScale(){return this.plot?.yScale??this.axis.yScale}getCore(){let e=this.timeSeries;if(!e.hasData||!this.visible)return null;let t=this.view.xAxis.xScale.extent();if(!P(t))return null;let n=this.yScale.domain();return P(n)?{ts:e,extent:t,domain:n,range:this.yScale.range()}:null}drawHover(e,t,n){if(!this.isLineLike||this.getCore()===null)return;let[r,i]=z_(this,this.pickMainField(),t);P(r)&&(e.save(),Ra(e,this.plot.axis.pane.getBoundsWithoutScales()),e.fillStyle=wa(this.getColor(i)),e.beginPath(),lv(e,n,this.priceToY(r),this.lineMarker??`Circle`,1.3333),e.fill(),e.restore())}draw(e){let t=this.getCore();if(t===null)return;let{ts:n,extent:r,domain:i,range:a}=t;e.save(),e.setLineDash([]);let o=n.container.getTimeData(),s=this.shiftedTimeDomain[0],c={bar:this.view.xAxis.xScale.bar,domain:i,range:a,slice:r,start:Te(o,+s,Number)||0},l=P(this.zones);this.isOhlc?av.call(this,e,c):this.isRenko||this.isLineBreak?$_.call(this,e,c):this.style===h.Ribbon?this.varyColorPerBar?yv.call(this,e,c):vv.call(this,e,c,this.colors[0]):this.style===h.Area?l?Y_.call(this,e,c,K_,!0):K_.call(this,e,c,this.colors,!0):this.isColumn||this.isMultiColumn?l?Y_.call(this,e,c,tv,!0):tv.call(this,e,{...c,range:[null,null]}):this.isStackedColumn?ev.call(this,e,c):this.isBaseline?Q_.call(this,e,c):this.style===h.Step?l?Y_.call(this,e,c,rv):rv.call(this,e,c,this.colors[0]):this.isKagi?gv.call(this,e,c):this.isPointAndFigure?_v.call(this,e,c):this.style===h.Dots?nv.call(this,e,c):this.style===h.Line||this.isPercentChangeStyle?l?Y_.call(this,e,c,uv):this.varyColorPerBar?mv.call(this,e,c):uv.call(this,e,c):I(`Drawing of the curve style '${this.style}' is not implemented yet`,`error`),e.restore()}pickMainField(){return this.fields.length===1?this.fields[0]:this.fields.includes(W.Last)?W.Last:this.fields.includes(W.Close)?W.Close:this.fields[0]}get zoneColors(){if(!P(this._zoneColors)){let e=this.colors.slice();this._zoneColors=this.zones.map(t=>e.splice(0,t.colors))}return this._zoneColors}getColorsFromZone(e){let t=this.zones.findIndex(t=>e<t.value);return t===-1&&(t=this.zones.length-1),this.zoneColors[t]}pickAreaStroke(e){return e.length<2?wa(e[0]):e[1]}getComputedColor(e){if(!this.timeSeries.container.hasField(W.BARCOLIX))return null;let t=this.dataAt(W.BARCOLIX,e);return t>=0&&t<this.colors.length?this.colors[t]:null}getColor(e,t=!0,n=null){if(this.varyColorPerBar){let n={};if(this.isOhlc||this.isRenko||this.isLineBreak){let t=this.dataAt(W.Open,e),r=this.dataAt(W.High,e),i=this.dataAt(W.Low,e),a=this.dataAt(W.Close,e),o=this.dataAt(W.Change,e);n.open=t,n.high=r,n.low=i,n.close=a,n.change=o}else if(this.plot.isStudy&&![`VOL`,`MAVOL`].includes(this.plot.model.study)){let t=this.pickMainField(),r=this.dataAt(t,e-1),i=this.dataAt(t,e),a=P(r),o=P(i);a?n.change=o?i-r:-1:n.change=+!!o}else{let t=this.plot.axis.pane.presenter.data.aggregation;(!t.isTick||t.spec!==_.None)&&(n.open=this.dataAt(W.Open,e),n.close=this.dataAt(W.Close,e)),n.change=this.dataAt(W.Change,e)}let r,i=xv(this.style,n,this.colors),a=this.getComputedColor(e);switch(this.style){case h.Candlestick:case h.Renko:case h.LineBreak:case h.Range:case h.HeikinAshi:case h.OHLC:case h.HLC:case h.Column:{if(P(a)){r=a;break}let t=i.useSame?i.isUp:i.isUp||i.isSame,n=i.isSame,o=this.attributes||[],s=this.plot.isStudy&&![`HASMO`,`VOL`,`MAVOL`].includes(this.plot.model.study);(o.includes(m.ChangeBased)||s)&&(t=i.useSame?i.isUpPrev:i.isUpPrev||i.isSamePrev,n=i.isSamePrev),r=this.colors[+!!t],i.useSame&&n&&(r=this.colors[2]),(this.isRenko||this.isLineBreak||this.isRangeStyle)&&this.dataAt(W.Projection,e)===1&&(r=ka(.5,!0)(r));break}case h.ElderImpulseSystem:r=this.colors[this.dataAt(W.BREL,e)];break;case h.HollowCandles:{let e=this.colors[i.isUpPrev||i.isSamePrev?1:0];r=t&&(i.isUp||i.isSame)?z.COLOR_TRANSPARENT:e;break}case h.Line:case h.PercentChange:case h.Ribbon:case h.Kagi:if(P(a)){r=a;break}r=this.colors[0];break;case h.PointAndFigure:{let t=+!!mg(this.dataAt(W.BARKIND,e));r=this.colors[t];break}default:throw Error(`Unexpected style ${h[this.style]} for a curve with varying colors`)}return P(r)||(r=this.colors[0]),r}else if(this.zones){let t=this.pickMainField(),n=this.dataAt(t,e),r=this.getColorsFromZone(n);return this.style===h.Area?this.pickAreaStroke(r):r.length>0?r[0]:this.colors[0]}else return(this.isMultiColumn||this.isStackedColumn)&&P(n)?this.colors[ke(this.colors,this.fields.findIndex(e=>e===n))]:this.colors[0]}};function G_([e,t],n,r){let i=n,a=this.timeSeries.container.size;for(let n=e;n<=t;n++){for(;this.timeSeriesAt(i)<this.timelineAt(n-this.shift)&&i<a;)++i;if(i===a)break;let e=this.timeSeriesAt(i)>this.timelineAt(n-this.shift);r.call(this,i,e)}}function K_(e,t,n,r=!1){uv.call(this,e,t,this.pickAreaStroke(n)),bv.call(this,e,t,n[0],r)}function q_(e,t){let n=P(e),r=P(t),i,a,o=this.pane.getBounds();if(!n)i=this.priceToY(t),a=new za(o.x,i,o.width,o.y+o.height-i);else if(!r)i=this.priceToY(e),a=new za(o.x,o.y,o.width,i-o.y);else{let n=this.priceToY(e),r=this.priceToY(t);i=(n+r)/2,a=new za(o.x,r,o.width,n-r)}return[i,a]}var J_=(e,t)=>{let n=ka(.6)(e),r=Aa(.6)(e),i=t===`linLighten`;return[i?r:n,e,i?n:r]};function Y_(e,t,n,r=!1,i){let a;this.zones.forEach((o,s)=>{let c=o.value,[l,u]=q_.call(this,a,c);e.save(),Ra(e,u),r&&(t.range=[null,l]);let d=this.zoneColors[s];if(o.gradient){let t=J_(d,o.gradient),n=e.createLinearGradient(0,u.y,0,u.y+u.height);n.addColorStop(0,t[0]),n.addColorStop(.5,t[1]),n.addColorStop(1,t[2]),d=n}else P(i)&&(d=i(s,d));n.call(this,e,t,d),e.restore(),a=c})}function X_(e){let{BaseLevel:t}=dt(e);return{baseLevel:Number.isFinite(t)?xt(0,100,t):50}}function Z_(e,t){let{x:n,width:r}=this.pane.getBoundsWithoutScales();e.save(),e.lineWidth=1,e.strokeStyle=`#888`,e.setLineDash(Ca(`dot`)),eo(e,t,n,n+r),e.restore()}function Q_(e,t){let[n,r]=t.range,{baseLevel:i}=X_(this.plot.inputs),a=(n-r)*i/100+r;this.zones[0].value=this.yToPrice(a),Z_.call(this,e,a),Y_.call(this,e,t,K_,!0,(t,i)=>{let o=t===1,s=Ta(i,0),c=e.createLinearGradient(0,o?n:r,0,a);return c.addColorStop(0,i),c.addColorStop(1,s),[c,Ta(i,1)]})}function $_(e,{bar:t,slice:n,start:r}){let i=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;G_.call(this,n,r,(n,r)=>{if(!r){let[r,a]=[W.Open,W.Close].map(e=>this.dataAt(e,n)).map(this.priceToY,this),o=Math.floor(t.totalWidth/2);e.fillStyle=this.getColor(n),e.beginPath(),e.rect(i-o,r,t.totalWidth,a-r),e.fill()}i+=t.totalWidth})}function ev(e,{bar:t,slice:n,start:r}){if(!this.isFirstVisibleOfStyle())return!1;let i=this.view.xAxis.xScale.range()[0]+t.offset,a=vo();a.prolog(e);let o=this.plot.curves.filter(e=>e.isStackedColumn);G_.call(this,n,r,(n,r)=>{if(!r){let r=this.priceToY(0),s=0;o.forEach(o=>{if(!o.visible)return;let c=o.fields[0];if(s+=this.dataAt(c,n),P(s)){let l=this.priceToY(s);e.fillStyle=o.getColor(n,!1,c),e.beginPath(),e.rect(a.adjust(i),a.adjust(l),a.adjust(t.width),a.adjust(r-l)),e.fill(),r=l}})}i+=t.totalWidth}),a.epilog(e)}function tv(e,{bar:t,slice:n,start:r,range:[i,a]}){let o=this.view.xAxis.xScale.range()[0]+t.offset,s=this.isMultiColumn,c=s?this.fields:[this.pickMainField()],l=t.width/(s?c.length:1),u=vo();u.prolog(e),G_.call(this,n,r,(n,r)=>{r||c.forEach((t,r)=>{let i=this.dataAt(t,n);if(P(i)){P(a)||(a=this.priceToY(0));let s=this.priceToY(i);e.fillStyle=this.getColor(n,!1,t),e.beginPath(),e.rect(u.adjust(o+r*l),u.adjust(s),u.adjust(l),u.adjust(a-s)),e.fill()}}),o+=t.totalWidth}),u.epilog(e)}function nv(e,{bar:t,slice:n,start:r}){let i=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;e.fillStyle=this.getColor(0);let a=Math.max(1,this.lineWidth||z.CURVE_STYLE_DOTS_RADIUS),o=Math.PI*2;e.beginPath(),G_.call(this,n,r,(n,r)=>{if(!r){let t=this.pickMainField(),r=this.dataAt(t,n);if(P(r)){let t=this.priceToY(r);e.moveTo(i+a,t),e.arc(i,t,a,0,o)}}i+=t.totalWidth}),e.fill()}function rv(e,{bar:t,slice:n,start:r},i){let a=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,o=vo();o.prolog(e),e.strokeStyle=i,e.lineWidth=this.lineWidth,this.dashStyle&&e.setLineDash(Ca(this.dashStyle)),e.beginPath();let s=!1,c=null;G_.call(this,n,r,(n,r)=>{if(!r){let t=this.pickMainField(),r=this.dataAt(t,n);if(P(r)){let i=this.priceToY(r);if(s)e.lineTo(a,c),e.lineTo(a,i);else{let r=this.dataAt(t,n-1);if(P(r)){let t=this.priceToY(r);e.moveTo(-1,t),e.lineTo(a,t),e.lineTo(a,i)}else e.moveTo(a,i);s=!0}c=i}}a+=t.totalWidth}),e.stroke(),o.epilog(e)}var iv=[W.Open,W.High,W.Low,W.Close];function av(e,{bar:t,slice:n,start:r}){let i=this.presenter.display.chart.showMinMaxArc,a=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,o=vo();o.prolog(e);let s=null,c=null,l=null,u=null,d=t=>{this.isCandle?(this.isHollowCandles?t.outlineColor=this.getColor(t.ix,!1):(this.colors.length>3&&(t.outlineColor=this.colors[3]),this.colors.length>4&&(t.wickColor=this.colors[4])),cv(e,t,this.lineWidth)):(this.isOhlcStyle||this.isHlcStyle||this.isElderImpulseSystemStyle||this.isRangeStyle)&&sv(e,t,this.lineWidth,!this.isHlcStyle)};G_.call(this,n,r,(e,n)=>{if(!n){let n=iv.map(t=>this.dataAt(t,e)),[r,i,f,p]=n;if(P(r,i,f,p)){let m={x:o.adjust(a),adjust:o.adjust,width:t.width,y:[r,i,f,p].map(this.priceToY,this).map(o.adjust),isMin:!1,isMax:!1,ix:e,color:this.getColor(e)},h=Math.min(...n),g=Math.max(...n);(!P(s)||h<s)&&(s=h,l=m),(!P(c)||g>c)&&(c=g,u=m),d(m)}}a+=t.totalWidth}),i&&(P(l)&&(l.isMin=!0,d(l)),P(u)&&(u.isMax=!0,d(u))),o.epilog(e)}function ov(e,t,n,r,i,a,o,s=3){t&&Za(e,{x:r,y:i+s},o,0,Math.PI),n&&Za(e,{x:r,y:a-s},o,0,Math.PI,!0)}function sv(e,{x:t,adjust:n,width:r,y:[i,a,o,s],color:c,isMin:l,isMax:u},d,f){let p=r/2;e.lineWidth=d,e.strokeStyle=c,e.beginPath(),e.moveTo(t,o),e.lineTo(t,a),f&&(e.moveTo(n(t-p),i),e.lineTo(t,i)),e.moveTo(n(t+p),s),e.lineTo(t,s),e.stroke(),ov(e,l,u,t,o,a,p)}function cv(e,{x:t,adjust:n,width:r,y:[i,a,o,s],color:c,outlineColor:l,wickColor:u,isMin:d,isMax:f},p){let m=r/2;e.lineWidth=p,e.fillStyle=c,e.strokeStyle=l||c,e.beginPath(),e.rect(n(t-m),i,r,n(s-i)),e.fill(),e.stroke(),e.strokeStyle=u||l||c,e.beginPath(),e.moveTo(t,Math.min(s,i)),e.lineTo(t,a),e.moveTo(t,Math.max(s,i)),e.lineTo(t,o),e.stroke(),e.strokeStyle=ja(c).a===0?l:c,ov(e,d,f,t,o,a,m)}function lv(e,t,n,r,i=1){let a=z.MARKER_SIZE*i,o=a*1.25;switch(r){case`Circle`:e.moveTo(t+a,n),e.arc(t,n,a,0,Math.PI*2);break;case`Square`:e.rect(t-a,n-a,2*a,2*a);break;case`TriangleUp`:e.moveTo(t-o,n+o),e.lineTo(t+o,n+o),e.lineTo(t,n-o),e.lineTo(t-o,n+o);break;case`TriangleDown`:e.moveTo(t-o,n-o),e.lineTo(t+o,n-o),e.lineTo(t,n+o),e.lineTo(t-o,n-o);break;case`Diamond`:e.moveTo(t,n-o),e.lineTo(t+o,n),e.lineTo(t,n+o),e.lineTo(t-o,n),e.lineTo(t,n-o);break;default:break}}function uv(e,{bar:t,slice:n,start:r},i=null){let a=i||this.getColor(0),o=N(this.lineMarker);o&&(e.fillStyle=a,e.beginPath());let s=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,c=[],l=this.pickMainField();G_.call(this,n,r,(n,r)=>{if(!r){let t=this.dataAt(l,n);if(P(t)){let n=this.priceToY(t);o&&lv(e,s,n,this.lineMarker),c.push({x:s,y:n})}}s+=t.totalWidth}),o&&e.fill(),e.lineWidth=this.lineWidth,this.dashStyle&&e.setLineDash(Ca(this.dashStyle)),N(this.lineSmoothing)?dv(e,c,a,this.lineSmoothing):pv(e,c,a)}function dv(e,t,n,r){if(t.length<2)return;let i=fv(t,r);e.beginPath(),e.strokeStyle=n,e.moveTo(t[0].x,t[0].y);for(let t of i)e.bezierCurveTo(t.cp1x,t.cp1y,t.cp2x,t.cp2y,t.x,t.y);e.stroke()}function fv(e,t){let n=[];for(let r=0;r<e.length-1;r++){let i=e[r-1]||e[r],a=e[r],o=e[r+1],s=e[r+2]||o,c=a.x+(o.x-i.x)/t,l=a.y+(o.y-i.y)/t,u=o.x-(s.x-a.x)/t,d=o.y-(s.y-a.y)/t;n.push({cp1x:c,cp1y:l,cp2x:u,cp2y:d,x:o.x,y:o.y})}return n}function pv(e,t,n){if(t.length>1){e.beginPath(),e.strokeStyle=n;let r=t[0];e.moveTo(r.x,r.y);for(let n=1;n<t.length;n++){let r=t[n];e.lineTo(r.x,r.y)}e.stroke()}}function mv(e,{bar:t,slice:n,start:r}){e.lineWidth=this.lineWidth,e.lineCap=`square`,this.dashStyle&&e.setLineDash(Ca(this.dashStyle));let i=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,a=null,o=null,s=[];G_.call(this,n,r,(n,r)=>{if(!r){let t=this.pickMainField(),r=this.dataAt(t,n);if(P(r)){let t=this.priceToY(r);o=this.getColor(n),a!==o&&(pv(e,s,a),s.length>0&&(s=[s.pop()]),a=o),s.push({x:i,y:t})}}i+=t.totalWidth}),pv(e,s,o)}var hv=[null,null,null,null];function gv(e,{bar:t,slice:n,start:r}){e.lineWidth=Math.max(1,.5*t.width),e.lineJoin=`miter`,e.miterLimit=1.5;let i=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,a=vo();a.prolog(e);let o=null,s=null,c=[];G_.call(this,n,r,(n,r)=>{if(!r){let r=e=>iv.map(t=>this.dataAt(t,e)),[l,u,d,f]=r(n),[,p,m]=n<0?hv:r(n-1);if(P(l,u,d,f)){let r=a.adjust(i),h=a.adjust(i-t.totalWidth),g=[l,u,d,f].map(this.priceToY,this).map(a.adjust),_=a.adjust(this.priceToY(u>p?p:m));s=this.getColor(n);let v=P(o)&&o!==s,y=l===u?1:2,b=l===u?2:1;c.push({x:h,y:g[0]}),c.push({x:r,y:g[y]}),v&&(c.push({x:r,y:_}),pv(e,c,o),c=[]),v&&c.push({x:r,y:_}),c.push({x:r,y:g[b]}),o=s}}i+=t.totalWidth}),pv(e,c,s),a.epilog(e)}function _v(e,{bar:t,slice:n,start:r}){let i=this.view.xAxis.xScale.range()[0],a=t.totalWidth/2,o=i+t.offset+t.width/2,s=vo();s.prolog(e);let c=this.plot.timeSeries.builder.boxSize,l=c/2;G_.call(this,n,r,(n,r)=>{if(!r){let[t,r]=[W.High,W.Low].map(e=>this.dataAt(e,n)),i=this.colors[0],u=this.colors[1],d=this.dataAt(W.BARKIND,n),f=mg(d),p=d===z.BARKIND_XO,m=d===z.BARKIND_OX;if(P(t,r))for(let n=t;n>=r;n-=c){let c=s.adjust(o),[d,h]=[c-a,c+a],[g,_,v]=[n,n-l,n+l].map(e=>this.priceToY(e)),y=n===t&&p||n===r&&m?!f:f;e.beginPath(),y?(e.strokeStyle=u,e.moveTo(d,_),e.lineTo(h,v),e.moveTo(d,v),e.lineTo(h,_)):(e.strokeStyle=i,e.ellipse(c,g,a,_-g,0,0,Math.PI*2)),e.stroke()}}o+=t.totalWidth}),s.epilog(e)}function vv(e,{bar:t,slice:n,start:r},i){e.fillStyle=i;let[a,o]=this.fields,s=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,c=[];if(G_.call(this,n,r,(e,n)=>{if(!n){let t=this.dataAt(a,e),n=this.dataAt(o,e);P(t,n)&&c.push({x:s,upY:this.priceToY(t),downY:this.priceToY(n)})}s+=t.totalWidth}),c.length>0){e.beginPath(),e.moveTo(c[0].x,c[0].upY);for(let t=1;t<c.length;++t)e.lineTo(c[t].x,c[t].upY);let t=c.length-1;e.lineTo(c[t].x,c[t].downY);for(let n=t-1;n>=0;--n)e.lineTo(c[n].x,c[n].downY);e.closePath(),e.fill()}}function yv(e,{bar:t,slice:n,start:r}){let[i,a]=this.fields,o=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,s=[],c=t=>{if(s.length>1){e.beginPath(),e.fillStyle=t,e.moveTo(s[0].x,s[0].upY);for(let t=1;t<s.length;++t)e.lineTo(s[t].x,s[t].upY);let n=s.length-1;e.lineTo(s[n].x,s[n].downY);for(let t=n-1;t>=0;--t)e.lineTo(s[t].x,s[t].downY);e.closePath(),e.fill()}},l=null,u=null;G_.call(this,n,r,(e,n)=>{if(!n){let t=this.dataAt(i,e),n=this.dataAt(a,e);if(P(t,n)){let r=this.priceToY(t),i=this.priceToY(n);u=this.getColor(e),l!==u&&(c(l),s.length>0&&(s=[s.pop()]),l=u),s.push({x:o,upY:r,downY:i})}}o+=t.totalWidth}),c(u)}function bv(e,{bar:t,slice:n,start:r,range:[i,a]},o,s){if(s){let t=e.createLinearGradient(0,i,0,a);t.addColorStop(0,o),t.addColorStop(1,Ta(o,0)),e.fillStyle=t}else e.fillStyle=o;e.beginPath();let c=null,l=this.pickMainField(),u=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,d=!1,f=null;G_.call(this,n,r,(n,r)=>{if(!r){let t=this.dataAt(l,n);if(P(t)){let n=this.priceToY(t);d?e.lineTo(u,n):(e.moveTo(c=u,n),d=!0),f=u}}u+=t.totalWidth}),e.lineTo(f,a),e.lineTo(c,a),e.closePath(),e.fill()}function xv(e,{open:t,close:n,change:r},i){let a=i.length>2&&e!==h.HLC,o=P(t,n),s=o&&n>t,c=o&&n===t,l=r>0,u=r===0;return{useSame:a,isUp:s,isSame:c,isUpPrev:l,isSamePrev:u,isDown:!s&&!c,isDownPrev:!l&&!u}}function Sv(e){let t=e.duplicate(),n=e;return`disableStreamingUpdates`in n&&(t.disableStreamingUpdates=n.disableStreamingUpdates),`surrogate`in n&&(t.surrogate=n.surrogate),t}var Cv=class e{symbol;aggregation;range;seriesKind;cacheMe;barsToFetch;offset;chartId;curveStyle;extendedHours;fields=[];alwaysUseBarsToFetch;inputs=[];splits;padded;constructor(e,t,n=w.Normal,r=[null,null]){this.symbol=e,this.aggregation=t,this.range=r,this.seriesKind=n,this.cacheMe=!1,this.barsToFetch=0,this.offset=0,this.chartId=null,this.curveStyle=null,this.alwaysUseBarsToFetch=!1,this.splits=!0,this.padded=!1}getBuilderKey(){if(!P(this.curveStyle)||!z.SPECIAL_BUILDER_REQUIRED.includes(this.curveStyle))return`Standard`;switch(this.curveStyle){case h.Renko:{let{method:e,period:t,source:n,brickSize:r}=wh(this.inputs);return`Renko;${e===`ATR`?`ATR;${t}`:`${e};${r}`};${n}`}case h.Kagi:{let{method:e,period:t,reversal:n}=og(this.inputs);return`Kagi;${e===`ATR`?`ATR;${t}`:`User;${n}`}`}case h.PointAndFigure:{let{method:e,period:t,reversal:n,boxSize:r,source:i,oneStepBack:a}=hg(this.inputs);return`PointAndFigure;${e===`ATR`?`ATR;${t}`:`User;${r}`};${i};${n};${a}`}case h.LineBreak:{let{lineBreak:e}=cg(this.inputs);return`LineBreak;${e}`}default:return h[this.curveStyle]}}get needsExtraKey(){return[w.Options,w.BalanceSheet,w.IncomeStatement].includes(this.seriesKind)}getExtraKey(){return this.needsExtraKey&&this.fields.length>0?`${this.fields.map(e=>e.id).join(`;`)}`:``}getHashKey(){let e=this.aggregation.getHashKey(),t=this.getBuilderKey(),n=this.getExtraKey(),r=this.extendedHours??!1;return`${this.symbol}|${e}|${r}|${this.range}|${this.seriesKind}|${this.offset}|${t}|${this.splits}|${this.padded}|${n}`}duplicate(){let t=new e(this.symbol,this.aggregation.duplicate(),this.seriesKind,this.range);return t.cacheMe=this.cacheMe,t.barsToFetch=this.barsToFetch,t.alwaysUseBarsToFetch=this.alwaysUseBarsToFetch,t.offset=this.offset,t.chartId=this.chartId,t.curveStyle=this.curveStyle,t.extendedHours=this.extendedHours,t.fields=F(this.fields),t.splits=this.splits,t.padded=this.padded,t}},wv=c(o(((e,t)=>{(function(n,r){var i={};n.PubSub?(i=n.PubSub,console.warn(`PubSub already loaded, using existing version`)):(n.PubSub=i,r(i)),typeof e==`object`?(t!==void 0&&t.exports&&(e=t.exports=i),e.PubSub=i,t.exports=e=i):typeof define==`function`&&define.amd&&define(function(){return i})})(typeof window==`object`&&window||e||global,function(e){var t={},n=-1,r=`*`;function i(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1}function a(e){return function(){throw e}}function o(e,t,n){try{e(t,n)}catch(e){setTimeout(a(e),0)}}function s(e,t,n){e(t,n)}function c(e,n,r,i){var a=t[n],c=i?s:o,l;if(Object.prototype.hasOwnProperty.call(t,n))for(l in a)Object.prototype.hasOwnProperty.call(a,l)&&c(a[l],e,r)}function l(e,t,n){return function(){var i=String(e),a=i.lastIndexOf(`.`);for(c(e,e,t,n);a!==-1;)i=i.substr(0,a),a=i.lastIndexOf(`.`),c(e,i,t,n);c(e,r,t,n)}}function u(e){var n=String(e);return!!(Object.prototype.hasOwnProperty.call(t,n)&&i(t[n]))}function d(e){for(var t=String(e),n=u(t)||u(r),i=t.lastIndexOf(`.`);!n&&i!==-1;)t=t.substr(0,i),i=t.lastIndexOf(`.`),n=u(t);return n}function f(e,t,n,r){e=typeof e==`symbol`?e.toString():e;var i=l(e,t,r);return d(e)?(n===!0?i():setTimeout(i,0),!0):!1}e.publish=function(t,n){return f(t,n,!1,e.immediateExceptions)},e.publishSync=function(t,n){return f(t,n,!0,e.immediateExceptions)},e.subscribe=function(e,r){if(typeof r!=`function`)return!1;e=typeof e==`symbol`?e.toString():e,Object.prototype.hasOwnProperty.call(t,e)||(t[e]={});var i=`uid_`+String(++n);return t[e][i]=r,i},e.subscribeAll=function(t){return e.subscribe(r,t)},e.subscribeOnce=function(t,n){var r=e.subscribe(t,function(){e.unsubscribe(r),n.apply(this,arguments)});return e},e.clearAllSubscriptions=function(){t={}},e.clearSubscriptions=function(e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0&&delete t[n]},e.countSubscriptions=function(e){var n,r,i=0;for(n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0){for(r in t[n])i++;break}return i},e.getSubscriptions=function(e){var n,r=[];for(n in t)Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0&&r.push(n);return r},e.unsubscribe=function(n){var r=typeof n==`string`&&(Object.prototype.hasOwnProperty.call(t,n)||function(e){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0)return!0;return!1}(n)),i=!r&&typeof n==`string`,a=typeof n==`function`,o=!1,s,c,l;if(r){e.clearSubscriptions(n);return}for(s in t)if(Object.prototype.hasOwnProperty.call(t,s)){if(c=t[s],i&&c[n]){delete c[n],o=n;break}if(a)for(l in c)Object.prototype.hasOwnProperty.call(c,l)&&c[l]===n&&(delete c[l],o=!0)}return o}})}))(),1);function Tv(e,t,n){return new Ev(e,t,n)}var Ev=class{calculable=!0;container;innerLookup;policy;exprSymbols;valueSymbols=[];onlyForTimeline;recalcTriggers;crashedComputationReported=!1;isLoading=!1;_sourceFields;_targetFields;basisChangedToken=null;quoteGroupToken=null;constructor(e,t,n){this.exprModel=e,this.innerSeries=t,this.container=null,this.innerLookup=t.reduce((e,t)=>(e[n.mapper(t)]=t,e),{}),this.policy=n,this.exprSymbols=Du(e),this.valueSymbols=this.exprSymbols.filter(e=>this.innerLookup[e]===void 0),this.onlyForTimeline=j(this.symbols,this.exprSymbols),this.recalcTriggers=new Set(t)}refresh(){this.innerSeries.forEach(e=>e.refresh())}get canLoadMoreData(){return this.policy.loadMoreData&&this.innerSeries.some(e=>e.canLoadMoreData)}async loadMoreData(e=!0){if(this.isLoading)return Promise.resolve();this.isLoading=!0;let t=this.innerSeries.filter(e=>e.canLoadMoreData).map(t=>t.loadMoreData(e));await Promise.all(t),this.isLoading=!1}get isExprInError(){return!P(this.exprModel)}get hasData(){return this.container!==null}get sourceFields(){return this._sourceFields||=Array.from(this.policy.fieldMap.keys()),this._sourceFields}get targetFields(){return this._targetFields||=Array.from(this.policy.fieldMap.values()),this._targetFields}async ready(){return Ai.call(this,async()=>{this.basisChangedToken=wv.default.subscribe(G.TS_ALL,this.onBasisChanged.bind(this)),this.quoteGroupToken=wv.default.subscribe(G.RT_QUOTEGROUP,this.onQuoteGroup.bind(this));let e=this.innerSeries.map(e=>e.ready());this.policy.valueProvider!==void 0&&e.push(this.policy.valueProvider.ready());let t=(await Promise.all(e)).every(ue);return t&&this.calculate(),t})}shouldTriggerOurRecalc(e){return this.recalcTriggers.has(e)}onQuoteGroup(e,t){t.source===this.policy.valueProvider&&this.innerSeries.every(e=>P(e.container))&&this.calculateCommon(G.TS_MANYCHANGED)}onBasisChanged(e,t){if(this.policy.recompute===d.Manual||e===G.TS_EVENTSCHANGED||e===G.TS_LOADING||!this.shouldTriggerOurRecalc(t.series)||this.innerSeries.some(e=>!P(e.container)))return;let n=this.policy.mapper(t.series);if(!(e===G.TS_DATAPOINTCHANGED&&this.onlyForTimeline?.includes(n)))switch(this.policy.recompute===d.Everything?G.TS_MANYCHANGED:e){case G.TS_MANYCHANGED:this.calculate();break;case G.TS_DATAPOINTCHANGED:case G.TS_DATAPOINTADDED:this.recalculate(e===G.TS_DATAPOINTADDED);break;case G.TS_TIMELINECORRECTION:case G.TS_QUOTEMARKER:break;default:throw Error(`Unknown time series message, likely forgot to handle it`)}}shutdown(){this.basisChangedToken&&wv.default.unsubscribe(this.basisChangedToken),this.quoteGroupToken&&(wv.default.unsubscribe(this.quoteGroupToken),this.policy.valueProvider?.shutdown())}calculateAt(e){return e.isNull?null:this.sourceFields.map((t,n)=>t===W.Volume?pe(this.exprSymbols.map(t=>e.inn[t].values[n]??0)):Cu(this.exprModel,t=>e.oneValue[t]??e.inn[t]?.values[n]??null))}pickMainField(){let e=null;for(let t of this.policy.fieldMap.values())if(e==null)e=t;else if(t===W.Close){e=t;break}return e}calculateLastChange(){let e=this.container,t=e.size;if(t<=1)return;let n=this.pickMainField(),r=e.getData(n)[t-2],i=e.getData(n)[t-1];P(r,i)&&e.setLastDataPoint(W.Change,i-r)}calculateDataPoint(e,t){let n=this.calculateAt(e);if(n===null)return;e.atLeastOne=!0;let[r,i]=Ee(n,0,3);n[1]=i,n[2]=r,this.targetFields.forEach((e,r)=>{let i=n[r];t?this.container.addDataPoint(e,i):this.container.setLastDataPoint(e,i)}),t&&(this.container.addDataPoint(W.Change,null),this.container.addDataPoint(W.DateTime,new Date(e.timeStamp))),this.calculateLastChange()}notify(e){Ge(e,{series:this,index:this.container.size-1})}fieldValueAt(e,t,n){let r=this.innerLookup[e].container.getData(n);return t<0||t>=r.length?null:r[t]}timeStampAt(e,t){return this.fieldValueAt(e,t,W.DateTime)}timeline(e){return e.container.getData(W.DateTime)}getRangeHelper(){switch(this.policy.missing){case u.UseNext:case u.UseNone:return Math.min;case u.UsePrevious:return Math.max;default:throw Error(`Unknow missing bar policy, likely forgot to implement it.`)}}getRange(){let e=this.getRangeHelper();return{begin:new Date(e(...this.symbols.map(e=>Se(this.timeline(this.innerLookup[e]))))),end:new Date(e(...this.symbols.map(e=>xe(this.timeline(this.innerLookup[e])))))}}getFirstPos(){return this.getPos(this.getRange().begin)}getLastPos(){return this.getPos(this.getRange().end)}findIndex(e,t){let n=this.timeline(this.innerLookup[e]);switch(this.policy.missing){case u.UseNext:case u.UseNone:return n.findIndex(e=>e.valueOf()>=t.valueOf());case u.UsePrevious:return Ce(n,e=>e.valueOf()<=t.valueOf());default:throw Error(`Unknow missing bar policy, likely forgot to implement it.`)}}checkPos(e){let t=Object.keys(e.inn).length;e.isNull=Object.values(e.inn).some(e=>!P(e.timeStamp)&&(!this.policy.stretch(e.symbol)||t===1))}fillPosSymbolAt(e,t,n){e.index=t,e.timeStamp=this.timeStampAt(e.symbol,t);let r=(this.policy.missing===u.UseNone||this.policy.skipLeadingEmpty&&!n.atLeastOne)&&e.timeStamp&&e.timeStamp.valueOf()!==n.timeStamp.valueOf();return e.values=this.sourceFields.map(n=>r?null:this.fieldValueAt(e.symbol,t,n)),e}skippable(e){return this.innerLookup[e].container.isEmpty?this.policy.noDataApproach===f.IgnoreTimelineOnly&&this.onlyForTimeline.includes(e)||this.policy.noDataApproach===f.ModelTransformRequired:!1}get symbols(){let e=Object.keys(this.innerLookup);return P(this.onlyForTimeline)?e.filter(e=>!this.skippable(e)):e}getPos(e){let t={isNull:!0,inn:{},timeStamp:e,atLeastOne:!1,oneValue:{}};return this.symbols.length===0?t:(this.symbols.forEach(n=>{let r=this.findIndex(n,e),i={symbol:n,index:-1,timeStamp:new Date(0),values:[]};t.inn[n]=this.fillPosSymbolAt(i,r,t)}),this.valueSymbols.forEach(e=>{t.oneValue[e]=this.policy.valueProvider?.getValue(e)??null}),this.checkPos(t),t)}getInner(e){return Object.values(e.inn)}moveNext(e){e.isNull||(this.getInner(e).forEach(t=>{for(;P(t.timeStamp)&&t.timeStamp.valueOf()<=e.timeStamp.valueOf();)this.fillPosSymbolAt(t,t.index+1,e)}),this.checkPos(e),e.isNull||(e.timeStamp=new Date(Math.min(...this.getInner(e).filter(e=>e.timeStamp!==null).map(e=>e.timeStamp.valueOf()))),this.policy.missing===u.UsePrevious?this.getInner(e).forEach(t=>{let n=P(t.timeStamp);(n&&t.timeStamp.valueOf()>e.timeStamp.valueOf()||!n&&this.policy.stretch(t.symbol))&&this.fillPosSymbolAt(t,t.index-1,e)}):this.policy.missing===u.UseNone&&this.getInner(e).forEach(t=>this.fillPosSymbolAt(t,t.index,e))))}shouldAdd(e){let t=this.container?.getLastDataPoint(W.DateTime),n=e?.timeStamp;return P(t,n)?t.valueOf()<n.valueOf():!1}calculateCommon(e=null,t=null,n=!0){try{if(t)this.calculateDataPoint(t,n);else if(this.container=this.makeContainer(),!this.isExprInError){let e=this.getFirstPos();for(;!e.isNull;)this.calculateDataPoint(e,!0),this.moveNext(e)}e&&this.notify(e)}catch(e){this.crashedComputationReported||=(I(e,`error`),!0)}}calculate(){let{yes:e,no:t}=A(this.innerSeries,e=>!e.container.isEmpty);if(t.length>0&&this.policy.noDataApproach===f.ModelTransformRequired){let n=e=>e.map(this.policy.mapper),r=this.policy.modelTransform(n(e),n(t));r!==null&&(this.exprModel=r)}this.calculateCommon(G.TS_MANYCHANGED)}recalculate(e){if(this.isExprInError)return;let t=this.getLastPos(),n=this.shouldAdd(t);this.calculateCommon(n?G.TS_DATAPOINTADDED:G.TS_DATAPOINTCHANGED,t,n)}recalculateAt(e,t,n){return this.recalculate(n)}makeContainer(){return new bh([W.DateTime,W.Change].concat(this.targetFields))}getCacheableEntities(e){this.innerSeries.forEach(t=>{t.getCacheableEntities(e)})}};function Dv(e){if(!(e instanceof Ev)||e.innerSeries.length!==1||e.exprSymbols.length!==1||e.valueSymbols.length!==0)return e;let t=e.innerSeries[0],n=t.query;return!P(n)||!nt(n,`surrogate`)?e:t}function Ov(e){let{query:t}=e;return t!==void 0&&`duplicate`in t&&`getBuilderKey`in t}function kv(e,t,n){if(!(e instanceof Ev))return n(e);if(e.valueSymbols.length!==0)return new xg;let r=e.innerSeries.map(n);return new Ev(e.exprModel,r,{...e.policy,fieldMap:new Map([[t,t]])})}function Av(e,t){return kv(e,t,e=>e)}function jv(e,t){let n=Dv(e);if(!Ov(n))return new xg;let r=Sv(n.query);if(r.symbol===z.PLACEHOLDER_SYMBOL_NAME||r.getBuilderKey()!==`Standard`)return new xg(r);{r.barsToFetch!==0&&(r.barsToFetch*=z.SERVER_COMPUTED_STUDY_BAR_MULTIPLIER);let e=t(r);return e.serverComputedSeries=!0,e}}function Mv(e,t,n){return kv(e,t,e=>jv(e,n))}function K(e){return new Ld(e,v.Number,b.Study,e)}var q=class{calcCtx;container;_source;target;inputs;outFields;studyFields={};innerSeries;calculable=!0;useNotifications=!1;initialNotification=!1;computedServerSide=!1;id;usedAsStyle=!1;recalcTriggers=new Set;basisChangedToken=null;_canLoadMoreData=!1;isLoading=!1;query;aggregation;sourceNeedsCompute=!1;allowEmptyValues=!1;constructor(e,...t){this.container=this._source=null,this.inputs=e.inputs,this.setOptions(e),this.innerSeries=t,this.id=bt(),this.addRecalcTrigger(...t)}refresh(){}get canLoadMoreData(){return this._canLoadMoreData}set canLoadMoreData(e){this._canLoadMoreData=e}loadMoreData(e){throw Error(`Should not be called.`)}addInner(...e){this.innerSeries.push(...e),this.addRecalcTrigger(...e)}isCalculable(e){return e.calculable??!1}addRecalcTrigger(...e){for(let t of e)this.isCalculable(t)?t.recalcTriggers.forEach(e=>this.recalcTriggers.add(e)):this.recalcTriggers.add(t)}setOptions(e){ut(this,e),nt(e,`source`)&&(this.source=e.source??null);let t=e.outFields??[e.target];this.studyFields=this.helpers.concat(t).reduce((e,t)=>(e[t.id]=t,e),{})}get helpers(){return z.EMPTY_ARRAY}get hasData(){return this.container!==null}get source(){if(P(this._source))return this._source;let e=P(this.inputs)?this.inputs[z.INPUT_SOURCE]:null;return P(e)?W[e]:null}set source(e){this._source=e}async ready(){return Ai.call(this,async()=>{this.basisChangedToken=this.useNotifications?wv.default.subscribe(G.TS_ALL,this.onBasisChanged.bind(this)):null;let e={tag:bt(),src:null},t=(await Promise.all(this.innerSeries.map(e=>e.ready()))).every(ue);return t&&this.calculate(e),t})}shouldTriggerOurRecalc(e){return this.recalcTriggers.has(e)}onBasisChanged(e,t){if(e===G.TS_EVENTSCHANGED||e===G.TS_LOADING||this.innerSeries.some(e=>!e.hasData)||!this.shouldTriggerOurRecalc(t.series)||this.base===null||this===t.series)return;let n={tag:bt(),src:t.series};switch(e){case G.TS_MANYCHANGED:this.calculate(n);break;case G.TS_DATAPOINTCHANGED:case G.TS_DATAPOINTADDED:{let r=this.innerSeries[this.baseIndex].calculable?this.base.size-1:t.index;this.recalculateAt(n,r,e===G.TS_DATAPOINTADDED);break}case G.TS_TIMELINECORRECTION:case G.TS_QUOTEMARKER:break;default:throw Error(`Unknown time series message, likely forgot to handle it`)}}shutdown(){this.useNotifications&&this.basisChangedToken&&wv.default.unsubscribe(this.basisChangedToken)}get baseIndex(){return 0}get base(){return this.innCont(this.baseIndex)}get period(){return this.inputs?.Period}calculateAt(e){return null}calculateDataPoint(e,t){let n=this.calculateAt(e);n!==null&&Object.keys(n).forEach(e=>{let r=n[e],i=this.studyFields[e];t?this.container.addDataPoint(i,r):this.container.setLastDataPoint(i,r)})}notify(e,t){Ge(e,{series:this,index:t})}calculateCommon(e,t=null,n=-1,r=!0){let i=n===-1,a=i?t=>{(P(e.src)||!P(t.calcCtx))&&t.calculate(e)}:t=>t.recalculateAt(e,n,r);if(!(this.base===null||this.calcCtx&&this.calcCtx.tag===e.tag||this===e.src)){if(this.calcCtx=e,this.innerSeries.filter(e=>this.isCalculable(e)&&!e.usedAsStyle).forEach(e=>a(e)),i&&(this.container=this.makeContainer()),this.calculateAt!==void 0)if(!i)this.calculateDataPoint(n,r);else{let e=this.base.size;for(let t=0;t<e;++t)this.calculateDataPoint(t,!0)}t&&(P(e.src)||this.initialNotification)&&this.notify(t,n)}}calculate(e){this.calculateCommon(e,G.TS_MANYCHANGED,-1,!0)}recalculateAt(e,t,n){this.computedServerSide||(!n&&N(this.container)&&t>this.container.size-1&&(t=this.container.size-1),this.calculateCommon(e,n?G.TS_DATAPOINTADDED:G.TS_DATAPOINTCHANGED,t,n))}baseVal(e,t){return this.base.getData(e)[t]}innCont(e){return this.innerSeries[e].container}innVal(e,t,n){let r=this.innCont(e),i=r.size;return n<0||n>i-1?null:r.getData(t)[n]}innHasData(e){let t=this.innCont(e);return P(t)&&t.size>0}wrap(...e){return e.reduce((e,t)=>(e[t.f.id]=t.g,e),{})}wrapBaseFields(...e){return e.map(this.wrapBaseField,this)}wrapInner(e,t){return{f:e,g:()=>this.innCont(t).getData(e)}}wrapBaseField(e){return this.wrapInner(e,this.baseIndex)}get defaultWrappers(){return this.wrapBaseFields(W.DateTime,W.Symbol)}makeContainer(){let e=this.defaultWrappers.concat(this.getWrappers());return new Sh(Object.keys(this.studyFields).map(e=>this.studyFields[e],this),this.wrap(...e))}getWrappers(){return[]}atLeast(e,t){return e>=t-1}exactly(e,t){return e==t-1}past(e,t,n,r=this.base){let i=r?.getData(n);return Array.isArray(i)?i.slice(e-t+1,e+1):[]}getCacheableEntities(e){this.innerSeries.forEach(t=>{t.getCacheableEntities(e)})}},Nv=class extends q{constructor(e,...t){super(e,...t),this.usedAsStyle=!0}get actual(){return this.innerSeries[0]}get canLoadMoreData(){return this.actual.canLoadMoreData}async loadMoreData(e=!0){return this.actual.loadMoreData(e)}get record(){return this.actual.record}},Pv=class extends Nv{constructor(e,t){super(e,t),this.query=t.query,this.useNotifications=!0}calculateAt(e){let[t,n,r,i]=[W.Open,W.High,W.Low,W.Close].map(t=>this.baseVal(t,e),this),a=null,o=null,s=null,c=null,l=me([t,n,r,i]);if(e<1)a=me([t,i]),o=n,s=r,c=0;else{let[t,i]=[W.Open,W.Close].map(t=>this.container.getData(t)[e-1],this);a=me([t,i]),o=Math.max(n,a,l),s=Math.min(r,a,l),c=l-i}return{[W.Open.id]:a,[W.High.id]:o,[W.Low.id]:s,[W.Close.id]:l,[W.Change.id]:c}}getWrappers(){return this.wrapBaseFields(W.Volume,W.OpenInterest,W.TradingDay)}},Fv=class extends q{constructor(e,t){super(e,t),SE(this)}calculateAt(e){let t=null,n=this.period,[,r]=CE(this);if(this.atLeast(e,n)&&r.hasField(this.source)){let i=this.past(e,n,this.source,r);this.allowEmptyValues?t=me(i.filter(de)):k(i)&&(t=me(i))}return{[this.target.id]:t}}getWrappers(){return this.source===W.Volume?this.wrapBaseFields(W.Volume,W.TradeSize,W.Change,W.Open,W.Close):[]}},Iv=class extends q{multiplier;constructor(e,t,n){super(e,t),this.multiplier=n(this.period),SE(this)}calculateAt(e){let t=null,[n,r]=CE(this);if(this.atLeast(e,2)&&r.hasField(this.source)){let i=this.container.getData(this.target)[e-1];if(i!==null)t=(this.innVal(n,this.source,e)-i)*this.multiplier+i;else{let n=this.period;if(this.atLeast(e,n)){let i=this.past(e,n,this.source,r);this.allowEmptyValues?t=me(i.filter(de)):k(i)&&(t=me(i))}}}return{[this.target.id]:t}}},Lv=class extends Iv{constructor(e,t){super(e,t,e=>2/(e+1))}},Rv=class extends Iv{constructor(e,t){super(e,t,e=>1/e)}},zv=class extends q{constructor(e,t){super(e,t);let n=J(t,this.inputs.Period1,W.High,W.MAHI),r=J(t,this.inputs.Period2,W.Low,W.MALO);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.MAHI,1),this.wrapInner(W.MALO,2)]}},Bv=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,n=W.OpenInterest;return this.base.hasField(n)&&(t=this.baseVal(n,e)),{[n.id]:t}}},Vv=class extends Bv{constructor(e,t){super(e,t)}getWrappers(){return this.wrapBaseFields(W.Volume,W.TradeSize,W.Change,W.Open,W.Close)}},Hv=class extends Bv{constructor(e,t){super(e,Av(t,W.OpenInterest))}getWrappers(){return this.wrapBaseFields(W.TradeSize,W.Change)}},Uv={inField:W.MA,outFields:[W.ENVU,W.ENVD],func:J},Wv={inField:W.EMA,outFields:[W.ENVEXPU,W.ENVEXPD],func:Y},Gv={inField:W.SMA,outFields:[W.ENVSMOU,W.ENVSMOD],func:YT},Kv=class extends q{kind;perc;constructor(e,t,n){super(e,n),this.kind=t,this.perc=this.inputs.Percent/100;let r=t.func(n,this.inputs.Period,e.source);this.addInner(r)}calculateAt(e){let t=null,n=null,r=this.innVal(1,this.kind.inField,e);if(r!==null){let e=r*this.perc;t=r+e,n=r-e}return{[this.kind.outFields[0].id]:t,[this.kind.outFields[1].id]:n}}},qv=class extends Kv{constructor(e,t){super(e,Uv,t)}},Jv=class extends Kv{constructor(e,t){super(e,Wv,t)}},Yv=class extends Kv{constructor(e,t){super(e,Gv,t)}},Xv=class extends q{constructor(e,t){super(e,t);let n=J(t,this.inputs.Period,this.source),r=J(n,this.inputs.Period,W.MA,W.TMA);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.TMA,2)]}},Zv=class extends q{triangle;constructor(e,t){super(e,t);let n=this.period;this.triangle=n*(n+1)/2,SE(this)}weightedAverage(e){let t=e.length;if(t===0)return null;let n=t===this.period?this.triangle:t*(t+1)/2;return e.reduce((e,t,n)=>e+t*(n+1),0)/n}calculateAt(e){let t=null,n=this.period,[,r]=CE(this);if(this.atLeast(e,n)){let i=this.past(e,n,this.source,r);this.allowEmptyValues?t=this.weightedAverage(i.filter(de)):k(i)&&(t=this.weightedAverage(i))}return{[this.target.id]:t}}},Qv=class extends q{constructor(e,t){super(e,t);let n=J(t,this.inputs.Period1,this.source),r=J(t,this.inputs.Period2,this.source),i=Z(this.target,(e,t,n)=>t-n,n,r);this.addInner(i)}getWrappers(){return[this.wrapInner(this.target,1)]}},$v={fields:[W.MACD,W.MACDS,W.MACDH],avgFunc:J,mapFunc:yE,histogramVaryColor:!0},ey={fields:[W.MACD,W.MACDS,W.MACDH],avgFunc:Y,mapFunc:yE,histogramVaryColor:!0},ty={fields:[W.MACD,W.CTLTM,W.CTM],avgFunc:Y,mapFunc:yE,histogramVaryColor:!1},ny={fields:[W.MACD,W.CTLTMF,W.CPMI],avgFunc:Y,mapFunc:yE,histogramVaryColor:!1},ry={fields:[W.PPO,W.PPOS,W.PPOH],avgFunc:Y,mapFunc:bE,histogramVaryColor:!0},iy={fields:[W.PVO,W.PVOS,W.PVOH],avgFunc:Y,mapFunc:bE,histogramVaryColor:!1},ay=class extends q{histogramVaryColor=!1;histogramField;get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=-1;if(this.histogramVaryColor&&e>0){let n=this.container.getData(this.histogramField)[e],r=this.container.getData(this.histogramField)[e-1];if(P(n,r)){let i=n<=0;t=i?1:3,e>0&&(i&&n>r&&(t=0),!i&&n<r&&(t=2))}}return{[W.BARCOLIX.id]:t}}},oy=class extends ay{fields;constructor(e,t,n){super(e,n),this.fields=t.fields,this.histogramVaryColor=t.histogramVaryColor,this.histogramField=this.fields[2];let r=t.avgFunc(n,e.inputs.Period1,e.source,void 0),i=t.avgFunc(n,e.inputs.Period2,e.source,void 0),a=Z(this.fields[0],t.mapFunc,r,i),o=t.avgFunc(a,e.inputs.Period3,a.target,this.fields[1]),s=Z(this.fields[2],yE,a,o);this.addInner(a,o,s)}getWrappers(){return[this.wrapInner(this.fields[0],1),this.wrapInner(this.fields[1],2),this.wrapInner(this.fields[2],3)]}},sy=class extends ay{constructor(e,t){super(e,t),this.histogramVaryColor=!0,this.histogramField=W.MACDVH;let n=DE(e,`EMA`,`Average`),r=n(t,e.inputs.Period1,e.source,void 0),i=n(t,e.inputs.Period2,e.source,void 0),a=iE(t,e.inputs.Period2,e.inputs.Average),o=Z(W.MACDV,(e,t,n,r)=>(t-n)/r*100,r,i,a),s=n(o,e.inputs.Period3,o.target,W.MACDVS),c=Z(W.MACDVH,yE,o,s);this.addInner(o,s,c)}getWrappers(){return[this.wrapInner(W.MACDV,1),this.wrapInner(W.MACDVS,2),this.wrapInner(W.MACDVH,3)]}},cy=class extends oy{constructor(e,t){super(e,$v,t)}},ly=class extends oy{constructor(e,t){super(e,ey,t)}},uy=class extends oy{constructor(e,t){e.inputs={Period1:5,Period2:21,Period3:34},super(e,ty,t)}},dy=class extends oy{constructor(e,t){e.inputs={Period1:3,Period2:5,Period3:8},super(e,ny,t)}},fy=class extends oy{constructor(e,t){super(e,ry,t)}},py=class extends oy{constructor(e,t){super(e,iy,t)}},my=K(`_AVG_GAIN`),hy=K(`_AVG_LOSS`),gy=class extends q{isModified;constructor(e,t){super(e,t),this.isModified=e.inputs.Modified}get helpers(){return[my,hy]}gain(e,t){return t[e]>t[e-1]?t[e]-t[e-1]:0}loss(e,t){return t[e]<t[e-1]?t[e-1]-t[e]:0}calculateAt(e){let t=null,n=null,r=null,i=this.period;if(this.atLeast(e,i+1)){if(this.container.getData(this.target)[e-1]!==null&&!this.isModified){let t=this.container.getData(my)[e-1],a=this.container.getData(hy)[e-1],o=this.past(e,2,this.source),s=this.gain(1,o),c=this.loss(1,o);n=(t*(i-1)+s)/i,r=(a*(i-1)+c)/i}else{let t=this.past(e,i+1,this.source);if(k(t)){let e=he(1,i),a=e.map(e=>this.gain(e,t)),o=e.map(e=>this.loss(e,t));n=me(a),r=me(o)}}n!==null&&r!==null&&(t=100-100/(1+n/r))}return{[my.id]:n,[hy.id]:r,[this.target.id]:t}}},_y=class extends q{constructor(e,t,n){super(e,n);let r=lE(n,this.inputs.Period,this.source,W.RSI,t),i=DE(e,`MA`,`Average`)(r,this.inputs.PeriodAvg,W.RSI,W.RSIAVG);this.addInner(r,i)}getWrappers(){return[this.wrapInner(W.RSI,1),this.wrapInner(W.RSIAVG,2)]}},vy=class extends _y{constructor(e,t){super(e,!1,t)}},yy=class extends _y{constructor(e,t){super(e,!0,t)}},by=class extends q{constructor(e,t){super(e,t);let n=lE(t,this.inputs.Period,this.source),r=this.inputs.Range,i=X(W.STORSI,function(e){let t=null;if(this.atLeast(e,r)){let n=this.past(e,r,W.RSI,this.base),i=Ee(n),a=i[0],o=i[1];t=(xe(n)-a)/(o-a)}return{[W.STORSI.id]:t}},n),a=DE(e,`MA`,`Average`),o=this.inputs.PeriodAvg,s=a(i,o,W.STORSI,W.STORSIAVG);this.addInner(i,s)}getWrappers(){return[this.wrapInner(W.STORSI,1),this.wrapInner(W.STORSIAVG,2)]}},xy=class extends q{constructor(e,t){super(e,t);let n=$T(t,this.inputs.Period1,W.High,W.HH,!0),r=$T(t,this.inputs.Period2,W.Low,W.LL,!1);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.HH,1),this.wrapInner(W.LL,2)]}},Sy=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,[n,r,i]=[W.Close,W.High,W.Low].map(t=>this.baseVal(t,e));return t=(2*n+r+i)/4,{[this.target.id]:t}}},Cy=class extends q{highest;index;constructor(e,t,n,r){super(e,r),this.highest=t,this.index=n}calculateAt(e){let t=null,n=this.inputs.Period;if(this.atLeast(e,n)){let r=this.past(e,n,this.source);k(r)&&(t=this.highest?Math.max(...r):Math.min(...r),this.index&&(t=n-r.indexOf(t)-1))}return{[this.target.id]:t}}},wy=class extends q{toHighest;field;highField;lowField;constructor(e,t,n){super(e,n),this.toHighest=t;let r=P(e.source),i=e.source;this.field=r?i:W.Close,this.highField=r?i:W.High,this.lowField=r?i:W.Low;let a=$T(n,e.inputs.Period,this.highField,W.HH,!0),o=$T(n,e.inputs.Period,this.lowField,W.LL,!1);this.addInner(a,o)}calculateAt(e){let t=null,n=this.baseVal(this.field,e),r=this.innVal(1,W.HH,e),i=this.innVal(2,W.LL,e);if(k([n,r,i])){let e=this.toHighest?r:i,a=r-i;a!==0&&(t=(n-e)/a*100)}return{[this.target.id]:t}}},Ty=class extends wy{constructor(e,t){super(e,!0,t)}},Ey=K(`RawPercK`),Dy=class extends q{kField;constructor(e,t,n,r){super(e,r);let i=eE(r,this.inputs.Period1,t?Ey:n,!1),a=DE(e,`MA`),o=a(i,this.inputs.Period2,i.target,t?n:W.PercD),s=t?a(o,this.inputs.Period3,o.target,W.PercD):o;this.kField=n,t?this.addInner(o,s):this.addInner(i,o)}getWrappers(){return[this.wrapInner(this.kField,1),this.wrapInner(W.PercD,2)]}},Oy=class extends Dy{constructor(e,t){super(e,!1,W.PercK,t)}},ky=class extends Dy{constructor(e,t){super(e,!0,W.PercK,t)}},Ay=class extends Dy{constructor(e,t){e.inputs={Period1:5,Period2:3,Period3:3},super(e,!0,W.CTPI,t)}};function jy(e,t,n,r,i){if(i===null)return null;let a=e*i,o=r+a,s=r-a;switch(t){case W.BOLLBU:return o;case W.BOLLBL:return s;case W.BOLLBW:return(o-s)/r*100;default:return null}}var My=class extends q{kind;constructor(e,t,n){super(e,n),this.kind=t,SE(this);let r=this.inputs.Period,i=this.source,a=J(n,r,i,W.BOLLBM),o=t===`Modified`,s=dE(o?tE(n,i):n,r,o?W.PCTCHG:i),c=this.inputs.Width,l=e=>ce(jy,c,e),u=Z(W.BOLLBU,l(W.BOLLBU),a,s),d=Z(W.BOLLBL,l(W.BOLLBL),a,s),f=Z(W.BOLLBW,l(W.BOLLBW),a,s),p=DE(e,`MA`,`Average`),m=this.inputs.PeriodAvg,h=p(f,m,W.BOLLBW,W.BOLLBWA);this.addInner(a,s,u,d,f,h)}calculateAt(e){let t=+!!this.sourceNeedsCompute,n=this.innVal(3+t,W.BOLLBU,e),r=this.innVal(4+t,W.BOLLBL,e),i=this.innVal(1+t,W.BOLLBM,e),a=this.innVal(5+t,W.BOLLBW,e),o=this.innVal(6+t,W.BOLLBWA,e),s=null;switch(this.kind){case`Regular`:return{[W.BOLLBU.id]:n,[W.BOLLBL.id]:r,[W.BOLLBM.id]:i};case`Width`:return{[W.BOLLW.id]:n-r};case`Percent`:if(P(n,r)){let[t]=CE(this),i=this.innVal(t,this.source,e);P(i)&&(s=(i-r)/(n-r))}return{[W.BOLLP.id]:s};case`BandWidth`:return{[W.BOLLBW.id]:a,[W.BOLLBWA.id]:o};case`Modified`:{let n=null,r=null,a=null,o=null,s=this.innVal(2+t,W.MSD,e);if(P(s)){let e=this.inputs.MultInside,t=this.inputs.MultOutside;n=i+e*s,a=i-e*s,r=i+t*s,o=i-t*s}return{[W.MBBUI.id]:n,[W.MBBLI.id]:a,[W.MBBUO.id]:r,[W.MBBLO.id]:o,[W.MBBM.id]:i}}default:return null}}},Ny=class extends My{constructor(e,t){super(e,`Regular`,t)}},Py=class extends My{constructor(e,t){super(e,`Width`,t)}},Fy=class extends My{constructor(e,t){super(e,`Percent`,t)}},Iy=class extends My{constructor(e,t){super(e,`BandWidth`,t)}},Ly=class extends My{constructor(e,t){super(e,`Modified`,t)}},Ry=class extends q{constructor(e,t){super(e,t);let n=X(W.OBVOL,function(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Volume,e),i=this.baseVal(W.Close,e-1),a=this.container.getData(this.target)[e-1];P(a)||(a=0),t=n>i?a+r:n<i?a-r:a}return{[this.target.id]:t}},t),r=DE(e,`MA`,`Average`),i=this.period,a=r(n,i,W.OBVOL,W.OBVOLAVG);this.addInner(n,a)}getWrappers(){return[this.wrapInner(W.OBVOL,1),this.wrapInner(W.OBVOLAVG,2)]}},zy=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,n=this.baseVal(W.High,e),r=this.baseVal(W.Low,e);if(e>0){let i=this.baseVal(W.Close,e-1);t=Math.max(n-r,Math.abs(n-i),Math.abs(r-i))}else t=n-r;return{[this.target.id]:t}}},By=K(`_ABS_CHG`),Vy=K(`_MA_ABS_CHG`),Hy=K(`_CHG`),Uy=class extends q{constructor(e,t){super(e,t);let n=rE(t,W.TR),r=DE(e,`SMA`)(n,this.inputs.Period,W.TR,this.target),i=J(r,this.inputs.Period2,W.ATR,W.ATRMA);this.addInner(r,i)}getWrappers(){return[this.wrapInner(this.target,1),this.wrapInner(W.ATRMA,2)]}},Wy=class extends q{constructor(e,t){super(e,t);let n=X(By,se((e,t)=>{let n=0;return t>0&&(n=this.baseVal(e,t)-this.baseVal(e,t-1)),{[By.id]:Math.abs(n)}},this.source),t),r=DE(e,`MA`)(n,this.inputs.Period,By,Vy),i=Z(W.ADJATR,(e,t)=>2*t,r);this.addInner(i)}getWrappers(){return[this.wrapInner(W.ADJATR,1)]}},Gy=class extends q{constructor(e,t){super(e,t);let n=X(Hy,e=>{let t=0;return e>0&&(t=this.baseVal(W.Close,e)-this.baseVal(W.Close,e-1)),{[Hy.id]:t}},t),r=kE(e),i=this.inputs.Period,a=this.inputs.Smoothing,o=r(t,i,a),s=Z(this.target,(e,t,n)=>!P(t)||!P(n)?null:t/n,n,o);this.addInner(s)}getWrappers(){return[this.wrapInner(this.target,1)]}},Ky=K(`_PDM`),qy=K(`_MDM`),Jy=K(`_TRS`),Yy=K(`_PDS`),Xy=K(`_MDS`),Zy=K(`_DX`),Qy=class extends q{useEma;adxField;multiplier;constructor(e,t,n,r){super(e,r),this.useEma=t,this.adxField=n,this.multiplier=2/(this.inputs.AdxSmoothing+1);let i=rE(r,W.TR);this.addInner(i)}get helpers(){return[Ky,qy,Jy,Yy,Xy,Zy]}sum(e,t,n,r){let i=null;if(this.atLeast(e-1,r-1)){let a=this.past(e-1,r-1,t,this.container);a.push(n),k(a)&&(i=a.reduce((e,t,n)=>e+t,0))}return i}smooth1(e,t,n,r){let i=null,a=this.inputs.DiLength,o=this.container.getData(n)[e-1];return i=o===null?this.sum(e,t,r,a):o-o/a+r,i}smooth2(e,t,n,r){let i=this.container.getData(n)[e-1],a=this.inputs.AdxSmoothing;if(i!==null)return this.useEma?(r-i)*this.multiplier+i:(i*(a-1)+r)/a;{let n=this.sum(e,t,r,a);if(n!==null)return n/a}return null}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;if(e>0){let u=this.past(e,2,W.High),d=this.past(e,2,W.Low),f=Math.max(u[1]-u[0],0),p=Math.max(d[0]-d[1],0);t=f>p?f:0,n=p>f?p:0;let m=this.container.getData(W.TR)[e];i=this.smooth1(e,Ky,Yy,t),a=this.smooth1(e,qy,Xy,n),r=this.smooth1(e,W.TR,Jy,m),(i>0||a>0)&&r!==0&&(o=i/r*100,s=a/r*100,c=100*Math.abs(o-s)/(o+s),l=this.smooth2(e,Zy,this.adxField,c))}return{[Ky.id]:t,[qy.id]:n,[Jy.id]:r,[Yy.id]:i,[Xy.id]:a,[W.PDI.id]:o,[W.MDI.id]:s,[Zy.id]:c,[this.adxField.id]:l}}getWrappers(){return[this.wrapInner(W.TR,1)]}},$y=class extends Qy{constructor(e,t){super(e,!1,W.ADX,t)}},eb=class extends Qy{constructor(e,t){super(e,!0,W.ADXM,t)}},tb=class extends q{constructor(e,t){super(e,t);let n=uE(t);this.addInner(n)}calculateAt(e){let t=null;return t=(e>0?this.container.getData(this.target)[e-1]:0)+this.innVal(1,W.MFMUL,e),{[this.target.id]:t}}},nb=class extends q{constructor(e,t){super(e,t);let n=X(W.ADWM,function(e){let t=null,n=null;if(e>0){let r=this.baseVal(W.Close,e-1),i=Math.max(r,this.baseVal(W.High,e)),a=Math.min(r,this.baseVal(W.Low,e)),o=this.baseVal(W.Close,e);t=o>r?o-a:o<r?o-i:0,e>1&&(n=(e>2?this.container.getData(W.ADWM)[e-1]:0)+t)}return{[W.ADWM.id]:n}},t),r=J(n,this.inputs.Period,W.ADWM,W.ADWMMA);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.ADWM,1),this.wrapInner(W.ADWMMA,2)]}},rb=class extends q{constructor(e,t){super(e,t);let n=W.ADL,r=oE(t,n),i=Y(r,3,n),a=Y(r,10,n),o=Z(e.target,(e,t,n)=>t-n,i,a);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},ib=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null;return t=me([W.Close,W.High,W.Low].map(t=>this.baseVal(t,e))),{[this.target.id]:t}}},ab=class extends q{calculateAtFunc;constructor(e,t,...n){super(e,...n),this.calculateAtFunc=t}calculateAt(e){let t=this.innerSeries.map((t,n)=>{let r=t,i=r.target;return P(i)||(i=r.container.hasField(W.Close)?W.Close:r.container.fields[0]),this.innVal(n,i,e)}),n=null;return k(t)&&(n=this.calculateAtFunc(e,...t)),{[this.target.id]:n}}};function ob(e,t){let n=this.baseVal(W.High,t),r=this.baseVal(W.Low,t);return{[e.id]:(n+r)/2}}function sb(e,t){let n=this.baseVal(W.High,t),r=this.baseVal(W.Low,t);return{[e.id]:n-r}}var cb=class extends q{calculateAtFunc;constructor(e,t,n){super(e,n),this.calculateAtFunc=t}calculateAt(e){return this.calculateAtFunc.call(this,e)}},lb=K(`_RANGE`),ub=K(`_MOV_RANGE`),db={fields:[W.KCUP,W.KCLOW,W.KCMID],midSeries:e=>sE(e,W.TP),midTarget:W.TP,rangeSeries:e=>X(lb,se(sb,lb),e),rangeTarget:lb,func:`MA`,useMultiplier:!1},fb={fields:[W.KBUP,W.KBLOW,W.KBMID],midSeries:e=>e,midTarget:W.Close,rangeSeries:e=>rE(e,W.TR),rangeTarget:W.TR,func:`EMA`,useMultiplier:!0},pb=class extends q{kind;constructor(e,t,n){super(e,n),this.kind=t;let r=t.midSeries(n),i=DE(e,t.func,`Average`),a=i(r,this.inputs.Period,t.midTarget,t.fields[2]),o=i(t.rangeSeries(n),this.inputs.Period,t.rangeTarget,ub);this.addInner(a,o)}calculateAt(e){let t=this.innVal(1,this.kind.fields[2],e),n=this.innVal(2,ub,e),r=t!==null&&n!==null,i=this.kind.useMultiplier?this.inputs.Multiplier:1;return{[this.kind.fields[0].id]:r?t+n*i:null,[this.kind.fields[1].id]:r?t-n*i:null}}getWrappers(){return[this.wrapInner(this.kind.fields[2],1)]}},mb=class extends pb{constructor(e,t){super(e,db,t)}},hb=class extends pb{constructor(e,t){super(e,fb,t)}},gb=class extends q{isWidth;constructor(e,t,n){super(e,n),this.isWidth=t;let r=$T(n,this.inputs.Period,W.High,W.DONUP,!0),i=$T(n,this.inputs.Period,W.Low,W.DONLOW,!1);this.addInner(r,i)}calculateAt(e){let t=this.innVal(1,W.DONUP,e),n=this.innVal(2,W.DONLOW,e),r=t===null&&n===null;return this.isWidth?{[W.DONW.id]:r?null:t-n}:{[W.DONMID.id]:r?null:(t+n)/2}}getWrappers(){return[this.wrapInner(W.DONUP,1),this.wrapInner(W.DONLOW,2)]}},_b=class extends gb{constructor(e,t){super(e,!1,t)}},vb=class extends gb{constructor(e,t){super(e,!0,t)}},yb=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Volume,e),i=this.baseVal(W.Close,e-1),a=this.container.getData(this.target)[e-1];P(a)||(a=0);let o=(n-i)/i*r;t=a+o}return{[this.target.id]:t}}},bb=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,this.source),r=Y(n,this.inputs.Period,n.target),i=Y(r,this.inputs.Period,r.target),a=cE(i,1,i.target,this.target);this.addInner(a)}getWrappers(){return[this.wrapInner(this.target,1)]}},xb=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,this.source),r=Y(n,this.inputs.Period,n.target),i=Z(W.DEMA,(e,t,n)=>2*t-n,n,r);this.addInner(i)}getWrappers(){return[this.wrapInner(W.DEMA,1)]}},Sb=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period1,this.source),r=Y(t,this.inputs.Period2,this.source),i=Z(W.EOSC,(e,t,n)=>t-n,n,r);this.addInner(i)}getWrappers(){return[this.wrapInner(W.EOSC,1)]}},Cb=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,this.source),r=Y(n,this.inputs.Period,n.target),i=Y(r,this.inputs.Period,r.target),a=Z(W.TEMA,(e,t,n,r)=>3*(t-n)+r,n,r,i);this.addInner(a)}getWrappers(){return[this.wrapInner(W.TEMA,1)]}},wb=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n+1)){let r=this.baseVal(this.source,e-n);r!==null&&r!==0&&(t=(this.baseVal(this.source,e)-r)/r*100)}return{[this.target.id]:t}}},Tb=class extends q{constructor(e,t){super(e,t);let n=sE(t,W.PVPT);this.addInner(n)}calculateAt(e){let t=this.innVal(1,W.PVPT,e),n=this.baseVal(W.High,e),r=this.baseVal(W.Low,e);return{[W.PVPTR.id]:t+n-r,[W.PVPTS.id]:t-n+r}}getWrappers(){return[this.wrapInner(W.PVPT,1)]}},Eb=K(`_HIND`),Db=K(`_LIND`),Ob=class extends q{constructor(e,t,n){super(e,n),this.justWidth=t,this.justWidth=t;let r=this.inputs.Period,i=$T(n,r,W.High,Eb,!0,!0),a=$T(n,r,W.Low,Db,!1,!0);this.addInner(i,a)}calculateAt(e){let t=null,n=null,r=null,i=this.innVal(1,Eb,e),a=this.innVal(2,Db,e);if(i!==null&&a!==null){let e=this.period;t=(e-i)/e*100,n=(e-a)/e*100,r=t-n}return this.justWidth?{[W.ARNOSC.id]:r}:{[W.ARNUP.id]:t,[W.ARNLOW.id]:n}}},kb=class extends Ob{constructor(e,t){super(e,!1,t)}},Ab=class extends Ob{constructor(e,t){super(e,!0,t)}},jb=class extends q{constructor(e,t){super(e,t);let n=e.inputs.Range===`Close`,r=jE(t);if(!n&&r){let e=X(W.TCHNUP,(e,t)=>null,t),n=X(W.TCHNLOW,(e,t)=>null,t);this.addInner(e,n)}else{let r=$T(t,e.inputs.PeriodUpper,n?W.Close:W.High,W.TCHNUP,!0),i=$T(t,e.inputs.PeriodLower,n?W.Close:W.Low,W.TCHNLOW,!1);this.addInner(r,i)}}getWrappers(){return[this.wrapInner(W.TCHNUP,1),this.wrapInner(W.TCHNLOW,2)]}},Mb=class extends q{constructor(e,t){super(e,t);let n=mE(t,e.inputs.Period,e.inputs.Range);this.addInner(n)}calculateAt(e){let t=null,n=this.innVal(1,W.TCHNUP,e),r=this.innVal(1,W.TCHNLOW,e),i=this.inputs.Adjustment,a=this.inputs.Retracement;return a===`Long`?t=P(n)?n-i:null:a===`Short`&&(t=P(r)?r+i:null),{[this.target.id]:t}}},Nb=K(`_MIDPOINT`),Pb=class extends q{constructor(e,t){super(e,t);let n=X(Nb,se(ob,Nb),t),r=YT(n,e.inputs.Period1,Nb,W.ALJAW),i=YT(n,e.inputs.Period2,Nb,W.ALTEETH),a=YT(n,e.inputs.Period3,Nb,W.ALLIPS);this.addInner(r,i,a)}calculateAt(e){return{[W.ALJAW.id]:this.innVal(1,W.ALJAW,e),[W.ALTEETH.id]:this.innVal(2,W.ALTEETH,e),[W.ALLIPS.id]:this.innVal(3,W.ALLIPS,e)}}},Fb=class extends q{constructor(e,t){super(e,t)}calculateAt(e){return{[W.PLTLN.id]:this.inputs.Position}}},Ib=K(`_MIDPOINT`),Lb=class extends q{constructor(e,t){super(e,t);let n=X(Ib,se(ob,Ib),t),r=J(n,this.inputs.Period1,Ib),i=J(n,this.inputs.Period2,Ib),a=Z(W.AWOS,(e,t,n)=>t-n,r,i),o=J(a,this.inputs.Period3,a.target,W.AWOSMA);this.addInner(a,o)}getWrappers(){return[this.wrapInner(W.AWOS,1),this.wrapInner(W.AWOSMA,2)]}},Rb=class extends q{multiplyVol;constructor(e,t,n){super(e,n),this.multiplyVol=t}calculateAt(e){let[t,n,r,i]=[W.High,W.Low,W.Close,W.Volume].map(t=>this.baseVal(t,e)),a=t===n?0:(r-n-(t-r))/(t-n);return this.multiplyVol&&(a*=i),{[this.target.id]:a}}},zb=class extends Rb{constructor(e,t){super(e,!1,t)}},Bb=class extends Rb{constructor(e,t){super(e,!0,t)}},Vb=class extends q{constructor(e,t){super(e,t);let n=uE(t);this.addInner(n)}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,W.Volume),i=this.past(e,n,W.MFMUL,this.innCont(1));if(k(r)&&k(i)){let e=pe(r);e!==0&&(t=pe(i)/e)}}return{[this.target.id]:t}}},Hb=K(`_RANGE`),Ub=class extends q{constructor(e,t){super(e,t);let n=cE(Y(X(Hb,se(sb,Hb),t),this.inputs.Period1,Hb),this.inputs.Period2,W.EMA,this.target);this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}},Wb=class extends q{shift;constructor(e,t){super(e,t);let n=this.inputs.Period;this.shift=Math.floor(n/2)+1;let r=J(t,n,e.source);this.addInner(r)}calculateAt(e){let t=null,n=this.shift,r=this.innVal(1,W.MA,e-n);return r!==null&&(t=this.baseVal(this.source,e)-r),{[this.target.id]:t}}},Gb=K(`_MATP`),Kb=class extends q{constructor(e,t){super(e,t);let n=sE(t),r=J(n,this.inputs.Period,n.target,Gb);this.addInner(n,r)}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,W.TP,this.innCont(1));if(k(r)){let n=this.innVal(2,Gb,e);if(n!==null){let i=r.reduce((e,t,r)=>e+Math.abs(n-t),0)/this.period;t=(this.innVal(1,W.TP,e)-n)/(.015*i)}}}return{[this.target.id]:t}}},qb=class extends q{constructor(e,t){super(e,t);let n=X(W.EMV,function(e){let t=null;if(e>0){let[n,r,i]=[W.High,W.Low,W.Volume].map(t=>this.baseVal(t,e)),[a,o]=[W.High,W.Low].map(t=>this.baseVal(t,e-1));t=((n+r)/2-(a+o)/2)/(i/1e6/(n-r))}return{[this.target.id]:t}},t),r=J(n,this.inputs.Period,W.EMV,W.EMVMA);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.EMV,1),this.wrapInner(W.EMVMA,2)]}},Jb=class extends q{isBull;constructor(e,t,n){super(e,n),this.isBull=t;let r=Y(n,this.inputs.Period,this.source);this.addInner(r)}calculateAt(e){let t=null,n=this.innVal(1,W.EMA,e);return n!==null&&(t=this.isBull?this.baseVal(W.High,e)-n:this.baseVal(W.Low,e)-n),{[this.isBull?W.ERBLPOW.id:W.ERBRPOW.id]:t}}},Yb=class extends Jb{constructor(e,t){super(e,!0,t)}},Xb=class extends Jb{constructor(e,t){super(e,!1,t)}},Zb=K(`_FORCE`),Qb=class extends q{constructor(e,t){super(e,t);let n=Y(X(Zb,function(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Volume,e);t=(n-this.baseVal(W.Close,e-1))*r}return{[this.target.id]:t}},t),this.inputs.Period,Zb,W.FI);this.addInner(n)}getWrappers(){return[this.wrapInner(W.FI,1)]}},$b=K(`_RANGE`),ex=K(`_EMA1`),tx=K(`_EMA2`),nx=K(`_RATIO`),rx=class extends q{constructor(e,t){super(e,t);let n=Y(X($b,se(sb,$b),t),9,$b,ex),r=Z(nx,(e,t,n)=>t/n,n,Y(n,9,ex,tx));this.addInner(r)}calculateAt(e){let t=null;if(this.atLeast(e,25)){let n=this.past(e,25,nx,this.innCont(1));k(n)&&(t=pe(n))}return{[this.target.id]:t}}},ix=class extends q{constructor(e,t){super(e,t);let n=this.inputs.Period,r=X(W.MOM,ce(TE,n,this.source),t),i=J(r,this.inputs.Movement,W.MOM,W.MOMMA);this.addInner(r,i)}getWrappers(){return[this.wrapInner(W.MOM,1),this.wrapInner(W.MOMMA,2)]}},ax=class extends q{constructor(e,t){super(e,t);let n=sE(t);this.addInner(n)}calculateAt(e){let t=null,n=this.period+1;if(this.atLeast(e,n)){let r=this.past(e,n,W.TP,this.innCont(1)),i=this.past(e,n,W.Volume).map(e=>e??0);if(k(r)&&k(i)){let e=0,a=0;for(let t=1;t<n;++t){let n=r[t]*i[t];r[t]>r[t-1]?e+=n:a+=n}t=100-100/(1+e/a)}}return{[this.target.id]:t}}},ox=class extends q{constructor(e,t){super(e,t),SE(this);let n=J(t,this.inputs.Period,this.source);this.addInner(n)}calculateAt(e){let t=null,[n,r]=CE(this),i=this.innVal(n+1,W.MA,e);if(i!==null){let n=this.inputs.Period,a=this.past(e,n,this.source,r);a=a.map(e=>(e-i)*(e-i)),t=Math.sqrt(me(a))}return{[this.target.id]:t}}getWrappers(){let[e]=CE(this);return[this.wrapInner(W.MA,e+1)]}},sx={isNegative:!1,fields:[W.PVI,W.PVIEMA]},cx={isNegative:!0,fields:[W.NVI,W.NVIEMA]},lx=class extends q{kind;constructor(e,t,n){super(e,n),this.kind=t;let r=X(this.kind.fields[0],se(function(e,t){let n=1e3;if(t>0){let r=[W.Close,W.Volume],[i,a]=r.map(e=>this.baseVal(e,t)),[o,s]=r.map(e=>this.baseVal(e,t-1)),c=this.container.getData(this.target)[t-1];n=(e?a<s:a>s)?c*((i-o)/o+1):c}return{[this.target.id]:n}},this.kind.isNegative),n),i=Y(r,this.inputs.Period,this.kind.fields[0],this.kind.fields[1]);this.addInner(r,i)}getWrappers(){return[this.wrapInner(this.kind.fields[0],1),this.wrapInner(this.kind.fields[1],2)]}},ux=class extends lx{constructor(e,t){super(e,cx,t)}},dx=class extends lx{constructor(e,t){super(e,sx,t)}},fx=K(`_LOGPC`),px=class extends q{constructor(e,t){super(e,t);let n=this.source??W.Close,r=Math.sqrt(AE(e.aggregation));if(r===0){let e=X(this.target,(e,t)=>null,t);this.addInner(e)}else{let i=function(e,t){let n=null;if(t>0){let r=this.baseVal(e,t),i=this.baseVal(e,t-1);r!==null&&i!==null&&(n=Math.log(r/i))}return{[fx.id]:n}},a=function(e,t){let n=null,r=this.baseVal(W.MSD,t);return r!==null&&(n=100*r*e),{[W.HV.id]:n}},o=dE(X(fx,se(i,n),t),e.inputs.Period,fx,W.MSD),s=X(W.HV,se(a,r),o);this.addInner(s)}}getWrappers(){return[this.wrapInner(this.target,1)]}},mx=class extends q{noOp;constructor(e,t){super(e,t),this.noOp=this.inputs.Anchor===`VisibleStart`}calculateAt(e){let t=null,n=this.baseVal(this.source,0),r=this.baseVal(this.source,e);return this.noOp?t=r:n!==null&&r!==null&&(t=(r-n)/n*100),{[this.target.id]:t}}},hx=K(`_SWING_INDEX`),gx=class extends q{constructor(e,t){super(e,t)}get helpers(){return[hx]}ohlcVals(e){return[W.Open,W.High,W.Low,W.Close].map(t=>this.baseVal(t,e))}obtainR(e,t,n,r){let i=Math.abs(e-r),a=Math.abs(t-r),o=Math.abs(e-t),s=Math.max(i,a,o),c=.25*Math.abs(r-n);return s===i?i-.5*a+c:s===a?a-.5*i+c:o+c}calculateAt(e){let t=null,n=null;if(e>0){let r=this.container.getData(hx)[e-1];P(r)||(r=0);let[i,a,o,s]=this.ohlcVals(e),[c,l,u,d]=this.ohlcVals(e-1);if(k([i,a,o,s,c,d])){let e=Math.max(Math.abs(a-d),Math.abs(o-d)),l=this.inputs.Limit,u=this.obtainR(a,o,c,d);t=50*((s-d+.5*(s-i)+.25*(d-c))/u)*(e/l),n=r+t}}return{[hx.id]:t,[this.target.id]:n}}},_x=K(`_MIN_CLOSE`),vx=K(`_MAX_CLOSE`),yx=class extends q{constructor(e,t){super(e,t);let n=iE(t,e.inputs.Period);this.addInner(n)}get helpers(){return[vx,_x]}calculateAt(e){let t=null,n=null,r=null,i=null,a=this.innVal(1,W.ATR,e);if(a!==null){let o=this.baseVal(W.Close,e),s=this.baseVal(W.Close,e-1),c=this.period;r=Math.max(...this.past(e,c,W.Close)),i=Math.min(...this.past(e,c,W.Close));let l=a*this.inputs.Constant;if(this.innVal(1,W.ATR,e-1)===null)o>s?t=r-l:n=i+l;else{let[a,s,c,u]=[W.WWVSARU,W.WWVSARD,vx,_x].map(t=>this.container.getData(t)[e-1]);r=c,i=u,a===null?o>s?(r=o,t=o-l):(i=Math.min(o,i),n=i+l):o<a?(i=o,n=o+l):(r=Math.max(o,r),t=r-l)}}return{[vx.id]:r,[_x.id]:i,[W.WWVSARU.id]:t,[W.WWVSARD.id]:n}}},bx=K(`_EP`),xx=K(`_AF`),Sx=K(`_POS`),Cx=1,wx=-1,Tx=class extends q{constructor(e,t){super(e,t)}get helpers(){return[bx,xx,Sx]}hlcVals(e){return[W.High,W.Low,W.Close].map(t=>this.baseVal(t,e))}me(e,t){return this.container.getData(e)[t]}reciprocal(e){return 1/e}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null;if(e>0){let[s,c,l]=this.hlcVals(e),[u,d,f]=this.hlcVals(e-1),p=this.reciprocal(this.inputs.Acceleration),m=this.reciprocal(this.inputs.Limit);if(e===1){a=l>f?Cx:wx;let e=a===Cx;o=e?d:u,r=e?Math.max(s,u):Math.min(c,d),i=p,e?t=o:n=o}else{let[l,f,h,g,_]=[Sx,W.PARSARS,W.PARSARL,bx,xx].map(t=>this.me(t,e-1)),v=l===Cx,y=v?h:f,b=_*Math.abs(g-y);a=v?y+b>c?wx:Cx:y-b<s?Cx:wx;let x=l===a;o=x?v?Math.min(y+b,d,this.baseVal(W.Low,e-2)):Math.max(y-b,u,this.baseVal(W.High,e-2)):g,r=x?v?Math.max(s,g):Math.min(c,g):a===Cx?s:c,i=_,x?(v?r>g:r<g)&&_<m&&(i=_+p):i=p,a===Cx?t=o:n=o}}return{[bx.id]:r,[xx.id]:i,[Sx.id]:a,[W.PARSARS.id]:n,[W.PARSARL.id]:t}}},Ex=class extends q{xSum;xSum2;x2Sum;constructor(e,t){super(e,t);let n=this.period;this.xSum=n*(n+1)/2,this.xSum2=this.xSum*this.xSum,this.x2Sum=n*(n+1)*(2*n+1)/6}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,this.source);if(k(r)){let e=pe(r),i=(n*pe(r.map((e,t)=>e*(t+1)))-this.xSum*e)/(n*this.x2Sum-this.xSum2);t=(e-i*this.xSum)/n+i*n}}return{[this.target.id]:t}}},Dx=K(`_IDY`),Ox=[0,0,0,1,1,1,5,5,2,1,1,0,50,50,0,1,1,1,5,0,0],kx=e=>Array(e).fill(0);function Ax(e,t){return Fx(e,t,10)}function jx(e,t){return Fx(e,t,13)}function Mx(e,t){return Fx(e,t,16)}function Nx(e,t){return Fx(e,t,4)}function Px(e,t){return Fx(e,t,7)}function Fx(e,t,n){let r=e[n-1];return t===0&&(r=e[n]),t<0&&(r=e[n+1]),r}function Ix(e,t,n,r,i){let a=i[18],o=r+1,s=0;for(let n=0;n<a;++n){let n=0,r=0;for(let i=1;i<6;++i){if(o--,e[o]==null)continue;let a=e[o]-t[o];i==1&&(n=r=a),a>n&&(n=a),a<r&&(r=a)}s=s+n-r}return s=s/a*Nx(i,n[r]),s}function Lx(e,t,n,r,i){let a=r,o=Px(i,n[r]),s=0;do a--,e[a]!=null&&s++;while(s<o&&a>0);return t[r]-t[a]}function Rx(e,t,n,r,i,a){let o=n;do o--;while(e[o]==null);return t[n]=t[o],e[n]>i&&t[o]<=0&&(t[n]=t[o]+1),e[n]<r&&t[o]>=0&&(t[n]=t[o]-1),a++,t[n]!==t[o]&&(a=1),a}function zx(e,t,n,r,i,a,o,s,c,l){let u=Ax(i,n[r]),d=jx(i,n[r]),f=Mx(i,n[r]),p=c+l+t[r]-e[r],m=100;i[20]>0&&(m=i[20]);let h=u*s/m;s>d&&(h=u*d/m);let g=l*2,_=e[r]+(p-g)-(p-g)*h,v=e[r]+(p-p*h),y=[a,o];return(s===1||f!==1||_>a)&&(y[0]=_),(s===1||f!==1||v<o)&&(y[1]=v),y}function Bx(e,t,n){let r=0,i=-1,a=0,o=1;for(let s=0;s<n;++s){if(t[s]=0,e[s]==null||(r++,r==21&&(o=2),r==31&&(o=3),a+=e[s]*o,r<40))continue;t[s]=a/70;let c=0,l=i+1;for(let t=l;t<n&&!(e[t]!=null&&(c++,c==1&&(i=t),(c==1||c==21||c==31)&&(a-=e[t]),c==31));++t);}}var Vx=class extends q{haveEnoughData=!1;firstUsefulIndex=0;s3;itr;constructor(e,t){super(e,t),this.s3=this.itr=[];let n=[`VelocityUpTrend`,`VelocitySideTrend`,`VelocityDownTrend`].map(t=>e.inputs[t]||`3`).map(Number);Ox.splice(6,3,...n)}get helpers(){return[Dx]}prepareComputation(){let e=this.base.getData(W.Close),t=0,n=0,r=e.length;for(;n<72&&t<r;)e[t]!=null&&n++,t++;this.haveEnoughData=t<r,this.firstUsefulIndex=t,this.s3=kx(r),this.itr=kx(r),this.haveEnoughData&&Bx(e,this.s3,r)}us(e,t){return this.container.getData(e)[t]}recalculateAt(e,t,n){let r=this.base.getData(W.Close),i=r.length;this.haveEnoughData&&Bx(r,this.s3,i),super.recalculateAt(e,t,n)}calculateAt(e){let t=null,n=null,r=null,i=t=>this.us(t,e-1);if(e===0)this.prepareComputation();else if(this.haveEnoughData&&e>=this.firstUsefulIndex&&this.baseVal(W.Close,e)!==null){let a=i(W.TRSP1),o=i(W.TRSP2);r=i(Dx),a===null&&o===null&&(a=o=this.baseVal(W.Close,this.firstUsefulIndex)),r===null&&(r=1);let s=this.base.getData(W.Close);r=Rx(s,this.itr,e,a,o,r);let c=Lx(s,this.s3,this.itr,e,Ox),l=Ix(s,this.s3,this.itr,e,Ox);[a,o]=zx(s,this.s3,this.itr,e,Ox,a,o,r,c,l),this.itr[e]>=0&&(t=a),this.itr[e]<=0&&(n=o)}return{[Dx.id]:r,[W.TRSP1.id]:t,[W.TRSP2.id]:n}}},Hx=class extends q{constructor(e,t){super(e,t),this.addInner(sE(t))}get helpers(){return[W.BARCOLIX]}getTarget(e){let t=this.baseVal(W.Close,e),n=this.innVal(1,W.TP,e);if(!P(t,n)||!this.atLeast(e,4))return null;let r=this.innVal(1,W.TP,e-3);return r===null?null:t+(n-r)/3}calculateAt(e){let t=null,n=this.getTarget(e);if(n!==null&&e>0){let r=this.container.getData(W.TARGP)?.[e-1];r!==null&&(t=n===r?this.container.getData(W.BARCOLIX)?.[e-1]??1:+(n>r))}return{[W.TARGP.id]:n,[W.BARCOLIX.id]:t}}},Ux=1,Wx=2,Gx=3,Kx={[Ux]:{param:`cot`,func:`parseCotLineChart`,fields:[W.DateTime,W.COTLCCMSP,W.COTLCLGSP,W.COTLCSMSP]},[Wx]:{param:`cotadv`,func:`parseDisaggregated`,fields:[W.DateTime,W.COTDAGPRO,W.COTDAGSPD,W.COTDAGMNM,W.COTDAGOTH]},[Gx]:{param:`cotfin`,func:`parseFinancialTradersReport`,fields:[W.DateTime,W.COTFTRDLI,W.COTFTRASM,W.COTFTRLVF,W.COTFTROTH]}},qx=class extends q{wrappers;constructor(e,t,n){super(e,jv(n,e=>new Jx(t,e))),this.computedServerSide=!0,this.initialNotification=!0,this.wrappers=Kx[t].fields.slice(1).map(e=>this.wrapInner(e,0))}getWrappers(){return this.wrappers}},Jx=class extends yg{kind;constructor(e,t){super(t),this.kind=e}getRetriever(){return new Yx(this.kind)}onStreamingUpdates(e){}},Yx=class extends Uh{kind;constructor(e){super(),this.kind=e}addExtraParams(e){e[Kx[this.kind].param]=`y`}getParser(e){return new Xx(e.symbol,e.aggregation,e.offset,this.kind)}},Xx=class extends Rh{kind;constructor(e,t,n,r){super(e,t,n),this.kind=r}makeContainer(){return new bh(Kx[this.kind].fields)}getParseFunc(){return this.aggregation.isEndOfDay?this[Kx[this.kind].func]:null}parseCotLineChart(e){this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.COTLCCMSP,parseInt(e[2])),this.container.addDataPoint(W.COTLCLGSP,parseInt(e[3])),this.container.addDataPoint(W.COTLCSMSP,parseInt(e[4]))}parseDisaggregated(e){this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.COTDAGPRO,parseInt(e[2])),this.container.addDataPoint(W.COTDAGSPD,parseInt(e[3])),this.container.addDataPoint(W.COTDAGMNM,parseInt(e[4])),this.container.addDataPoint(W.COTDAGOTH,parseInt(e[5]))}parseFinancialTradersReport(e){this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.COTFTRDLI,parseInt(e[2])),this.container.addDataPoint(W.COTFTRASM,parseInt(e[3])),this.container.addDataPoint(W.COTFTRLVF,parseInt(e[4])),this.container.addDataPoint(W.COTFTROTH,parseInt(e[5]))}},Zx=class extends qx{constructor(e,t){super(e,Ux,t)}},Qx=class extends qx{constructor(e,t){super(e,Wx,t)}},$x=class extends qx{constructor(e,t){super(e,Gx,t)}},eS={Day:[W.PreviousHigh,W.PreviousLow,W.PreviousClose],Week:[W.WeekPreviousHigh,W.WeekPreviousLow,W.WeekPreviousClose],Month:[W.MonthPreviousHigh,W.MonthPreviousLow,W.MonthPreviousClose]},tS=class extends q{disabled;record;streamingSubscription;constructor(e,t,n){if(super(e,n),this.disabled=!P(n.query)||!P(n.query.symbol),!this.disabled){let e=n.query.symbol;e.endsWith(`.BZ`)&&(e=e.slice(0,-3)),this.record=$().getRecordSource().getRecord(e),this.record.addFields(...t),this.streamingSubscription=this.getStreamingSubscription()}this.initialNotification=!0}getStreamingSubscription(){return $().getRecordSource().subject.pipe(Pp(e=>{let t=af(G.RT_QUOTE,this.record.symbol);return e.filter(t)}),Lp(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}async ready(){return Ai.call(this,async()=>P(this.record)?await this.record.ready()&&await super.ready():await super.ready(),`asyncReadyWork2`)}onStreamingUpdates(e){if(this.record){let e={tag:bt(),src:null};this.calculate(e)}}shutdown(){super.shutdown(),this.disabled||this.streamingSubscription.unsubscribe()}getValues(e){return eS[e].map(e=>this.record.getValue(e))}},nS=class extends tS{constructor(e,t){super(e,eS[e.inputs.Previous],t)}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null;if(!this.disabled){let e=this.getValues(this.inputs.Previous);if(k(e)){let[c,l,u]=e;t=(c+l+u)/3;let d=2*t;n=d-l,r=d-c;let f=c-l;i=t+f,a=t-f,o=c+2*(t-l),s=l-2*(c-t)}}return{[W.PPTPIV.id]:t,[W.PPTR1.id]:n,[W.PPTR2.id]:i,[W.PPTR3.id]:o,[W.PPTS1.id]:r,[W.PPTS2.id]:a,[W.PPTS3.id]:s}}},rS=class extends tS{constructor(e,t){super(e,eS.Day,t)}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null,c=null;if(!this.disabled){let e=this.getValues(`Day`);if(k(e)){let[l,u,d]=e,f=l-u,[p,m,h,g]=[2,4,6,12].map(e=>1.1/e*f);s=d+p,a=d+m,r=d+h,t=d+g,n=d-g,i=d-h,o=d-m,c=d-p}}return{[W.CPPH4.id]:s,[W.CPPH3.id]:a,[W.CPPH2.id]:r,[W.CPPH1.id]:t,[W.CPPL1.id]:n,[W.CPPL2.id]:i,[W.CPPL3.id]:o,[W.CPPL4.id]:c}}},iS=class extends q{constructor(e,t){super(e,Mv(t,W.IMPVOL,e=>new aS(e))),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return[this.wrapInner(W.IMPVOL,0)]}},aS=class extends yg{constructor(e){super(e)}getRetriever(){return Jr(this.query.symbol)?new lS:new oS}onStreamingUpdates(e){}},oS=class extends Uh{addExtraParams(e){e.impl=`y`}getParser(e){return new cS(e.symbol,e.aggregation,e.offset)}};function sS(){return new bh([W.DateTime,W.IMPVOL])}var cS=class extends Rh{constructor(e,t,n=0){super(e,t,n)}makeContainer(){return sS()}getParseFunc(){return this.parseImpVol}parseImpVol(e){!this.aggregation.isEndOfDay||e.length<9||(this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.IMPVOL,parseFloat(e[8])))}},lS=class extends Gh{emptyContainer(e,t){return sS()}get iterateForward(){return!1}getPageName(){return`getFuturesOptionsHistory`}processRow(e,t,n){n.addDataPoint(W.DateTime,ph(e.date.substring(0,10)));let r=N(e.impliedVolatility);n.addDataPoint(W.IMPVOL,r?e.impliedVolatility*100:null)}},uS=K(`_ABS_CHG`),dS=K(`_DS1_EMA1`),fS=K(`_DS1_EMA2`),pS=K(`_DS2_EMA1`),mS=K(`_DS2_EMA2`),hS=class extends q{constructor(e,t){super(e,t);let n=(e,t,n,r,i,a)=>Y(Y(e,t,n,r),i,r,a),r=X(uS,se((e,t)=>({[e.id]:Math.abs(this.baseVal(W.Change,t))}),uS),t),i=n(t,e.inputs.Period1,W.Change,dS,e.inputs.Period2,fS),a=n(r,e.inputs.Period1,uS,pS,e.inputs.Period2,mS),o=Z(W.TSI,(e,t,n)=>100*t/n,i,a),s=Y(o,e.inputs.Period3,W.TSI,W.TSISIG);this.addInner(o,s)}getWrappers(){return[this.wrapInner(W.TSI,1),this.wrapInner(W.TSISIG,2)]}},gS=class extends q{constructor(e,t){super(e,t);for(let n=1;n<=12;++n){let r=ME(e.inputs,n);this.addInner(Y(t,r,W.Close,e.outFields[n-1]))}}getWrappers(){return he(1,12).map(e=>this.wrapInner(this.outFields[e-1],e))}},_S=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,W.Close);this.addInner(n)}calculateAt(e){let t=null,n=e>0?this.container.getData(this.target)[e-1]:null,r=this.innVal(1,W.EMA,e);if(!N(n))t=r;else{let i=this.baseVal(this.source,e),a=(i/n)**4;t=n+(i-n)/(.6*this.period*a);let o=e=>Math.log10(Math.abs(e-t))>1,s=o(n)||o(r);(!Number.isFinite(t)||s)&&(t=null)}return{[this.target.id]:t}}},vS=K(`_DIFF`),yS=class extends q{constructor(e,t){super(e,t);let n=this.inputs.Period,r=Math.floor(n/2),i=this.allowEmptyValues,a=XT(Z(vS,(e,t,n)=>2*t-n,XT(t,r,this.source,W.WMA,i),XT(t,n,this.source,W.WMA,i)),Math.floor(Math.sqrt(n)),vS,this.target,i);this.addInner(a)}getWrappers(){return[this.wrapInner(this.target,1)]}},bS=K(`_SUM`),xS=class extends q{constructor(e,t){super(e,t);let n=XT(Z(bS,(e,t,n)=>t+n,cE(t,this.inputs.PeriodRocLong),cE(t,this.inputs.PeriodRocShort)),this.inputs.PeriodWma,bS,this.target);this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}},SS=K(`_ABS_CHG`),CS=K(`_HH_LL`),wS=K(`_MULMA`),TS=class extends q{constructor(e,t){super(e,t);let n=e.inputs.TurtleChnField===`Close`,r=e.inputs.Direction===`Long`,i=jE(t);if(!n&&i){let e=X(this.target,(e,t)=>null,t);this.addInner(e)}else{let e=J(X(SS,se((e,t)=>({[SS.id]:t>0?e*Math.abs(this.baseVal(W.Change,t)):null}),this.inputs.FactorATR),t),this.inputs.PeriodAdjATR,SS,W.MA),i=r?W.High:W.Low,a=$T(t,this.inputs.PeriodTurtleChn,n?W.Close:i,CS,r),o=Z(wS,(e,t)=>this.inputs.FactorAdjATR*t,e),s=r?-1:1,c=Z(this.target,(e,t,n)=>t+s*n,a,o);this.addInner(c)}}getWrappers(){return[this.wrapInner(this.target,1)]}},ES=class extends q{state;constructor(e,t){super(e,t),this.resetState()}resetState(){let e=this.inputs.ExtendLines??`None`;this.state={startIndex:null,endIndex:null,slope:null,intercept:null,stdDevWidth:null,extendLeft:e===`Left`||e===`Both`,extendRight:e===`Right`||e===`Both`}}calculateAt(e){let t=this.inputs.Period,n=this.inputs.Width,r=this.source;if(e===this.base.size-1&&this.base.size>=t){this.resetState();let e=t*(t+1)/2,i=e*e,a=t*(t+1)*(2*t+1)/6,o=0,s=0,c=1,l=this.base.size-t;for(let e=0;e<t;++e){let t=this.baseVal(r,l+e);if(!Ze(t))return{};o+=t,s+=c*t,c+=1}let u=(t*s-e*o)/(t*a-i),d=o/t-u*e/t;if(!Ze(u)||!Ze(d))return{};let f=0;for(let e=0;e<t;++e){let t=this.baseVal(r,l+e);if(!Ze(t))return{};let n=t-(d+u*(e+1));f+=n*n}let p=Math.sqrt(f/t);if(!Ze(p))return{};this.state.startIndex=l,this.state.endIndex=this.base.size-1,this.state.slope=u,this.state.intercept=d,this.state.stdDevWidth=n*p}return{}}getCurrentState(){return this.state}},DS=class extends q{computeDone;constructor(e,t){super(e,t,jv(t,e=>{let t=F(e);return t.symbol=ti(e.symbol),P(t.symbol)?new yg(t):new xg(t,!0)})),this.computedServerSide=!0,this.initialNotification=!0,this.computeDone=!1}alignCashTimelineWithUnderlying(){let e=this.innCont(0);if(!P(e)||e.size===0)return;let t=this.innCont(1),n=e.getTimeData(),r=t.getTimeData(),i=t.getData(W.Close),a=Array(n.length).fill(null);if(!(this.innerSeries[1]instanceof xg)){let o=0,s=e.size,c=t.size;for(let e=0;e<s;++e){for(;o<c&&r[o].getTime()<n[e].getTime();)o++;o<c&&r[o].getTime()===n[e].getTime()&&(a[e]=i[o])}}this.container.setData(this.target,a)}calculate(e){this.computeDone||(this.container=this.makeContainer(),this.alignCashTimelineWithUnderlying(),this.computeDone=!0,this.notify(G.TS_MANYCHANGED,-1))}},OS=class extends q{constructor(e,t){let n=pE(t);super(e,t,n)}shouldTriggerOurRecalc(e){return super.shouldTriggerOurRecalc(e)?!0:e===this.innerSeries[1]&&this.innHasData(0)&&this.innHasData(1)}calculateAt(e){let t=(t,n)=>P(this.innCont(t))?this.innVal(t,n,e):null,n=t(0,W.Close),r=t(1,W.CSHO);return{[this.target.id]:P(r)&&P(n)?r-n:null}}},kS=class extends q{computeDone;constructor(e,t){super(e,t,jv(t,e=>{let t=new Cv(e.symbol,new Vl(e.aggregation.unit===g.Year?g.Year:g.Quarter,1),w.BalanceSheet);return t.fields=[W.SharesOutstanding],t.cacheMe=!0,new wg(t)})),this.computedServerSide=!0,this.initialNotification=!0,this.computeDone=!1}alignFundamentalTimelineWithUnderlying(){let e=this.innCont(0);if(!P(e)||e.size===0)return;let t=this.innCont(1);if(!P(t)||t.size===0)return;let n=e.getTimeData(),r=t.getTimeData(),i=t.getData(W.SharesOutstanding),a=e.getData(W.Close),o=Array(n.length),s=0,c=e.size,l=t.size;for(let e=0;e<c;++e){let t=n[e].getTime();for(;s<l-1&&r[s+1].getTime()<=t;)s++;if(s<l&&r[s].getTime()<=t){let t=i[s],n=a[e];o[e]=P(t,n)?t*n:null}}this.container.setData(this.target,o)}calculate(e){this.computeDone||(this.container=this.makeContainer(),this.alignFundamentalTimelineWithUnderlying(),this.computeDone=!0,this.notify(G.TS_MANYCHANGED,-1))}},AS=class extends q{constructor(e,t){super(e,t),SE(this)}calculateAt(e){let t=null,[n]=CE(this);if(e>0){let r=this.innVal(n,this.source,e-1);r!==null&&(t=100*(this.innVal(n,this.source,e)-r)/r)}return{[this.target.id]:t}}},jS=class extends Nv{constructor(e,t){super(e,t),this.query=t.query,this.useNotifications=!0}calculateAt(e){let t=[null,null,null,null,null];if(e>0){let n=(e,t)=>this.baseVal(e,t),r=[W.Open,W.High,W.Low,W.Close],i=r.map(t=>n(t,e));if(k(i)){let a=r.map(t=>n(t,e-1));if(k(a)){t=i.map((e,t)=>100*(e-a[t])/a[t]);let[n,r]=Ee(t);if(t[1]=r,t[2]=n,e>1){let n=this.container.getData(W.Close)[e-1];t[4]=t[3]-n}}}}return{[W.Open.id]:t[0],[W.High.id]:t[1],[W.Low.id]:t[2],[W.Close.id]:t[3],[W.Change.id]:t[4]}}getWrappers(){return this.wrapBaseFields(W.Volume,W.OpenInterest,W.TradingDay)}},MS=K(`_DIST`),NS=K(`_EMA_DIST1`),PS=K(`_EMA_DIST2`),FS=K(`_DIFF`),IS=K(`_EMA_DIFF1`),LS=K(`_EMA_DIFF2`),RS=class extends q{constructor(e,t){super(e,t);let n=$T(t,e.inputs.Period1,W.High,W.HH,!0),r=$T(t,e.inputs.Period1,W.Low,W.LL,!1),i=Y(Y(Z(MS,(e,t,n)=>this.baseVal(W.Close,e)-(t+n)/2,n,r),e.inputs.Period2,MS,NS),e.inputs.Period2,NS,PS),a=Y(Y(Z(FS,(e,t,n)=>t-n,n,r),e.inputs.Period2,FS,IS),e.inputs.Period2,IS,LS),o=Z(W.STOMOMIX,(e,t,n)=>100*t/n,i,a);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},zS=K(`_CHG`),BS=K(`_M1`),VS=K(`_M2`),HS=class extends q{constructor(e,t){super(e,t);let n=X(zS,function(e){let t=W.Close,n=e>0?this.baseVal(t,e)-this.baseVal(t,e-1):0;return{[zS.id]:n}},t),r=(e,t)=>t>=0?t:0,i=(e,t)=>t>=0?0:-t,a=Z(BS,r,n),o=Z(VS,i,n);this.addInner(a,o)}perc(e,t){return 100*e/t}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n+1)){let r=this.past(e,n,BS,this.innCont(1)),i=this.past(e,n,VS,this.innCont(2));if(k(r)&&k(i)){let e=pe(r),n=pe(i);t=this.perc(e-n,e+n)}}return{[W.CHDMOMOSC.id]:t}}},US=class extends q{constructor(e,t){super(e,t);let n=new HS(e,t),r=DE(e,`MA`,`Average`),i=this.inputs.PeriodAvg,a=r(n,i,W.CHDMOMOSC,W.CHDMOMOSCAVG);this.addInner(n,a)}getWrappers(){return[this.wrapInner(W.CHDMOMOSC,1),this.wrapInner(W.CHDMOMOSCAVG,2)]}},WS=K(`_MAX`),GS=K(`_MIN`),KS=K(`_ISUPTREND`),qS=class extends q{constructor(e,t){super(e,t);let n=iE(t,e.inputs.Period);this.addInner(n)}get helpers(){return[WS,GS,KS]}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=1,c=this.baseVal(W.Close,e),l=(e,t)=>P(e)?e:t,u=e=>l(e,0),d=(e,t)=>this.container.getData(e)[t];e>0&&(r=Math.max(u(d(WS,e-1)),c),a=Math.min(u(d(GS,e-1)),c),s=d(KS,e-1));let f=this.inputs.Multiplier,p=this.innVal(1,W.ATR,e);if(P(p)){let l=s===1,u=l?r-f*p:a+f*p,m=d(l?W.VSTOPUP:W.VSTOPLOW,e-1);P(m)||(m=0);let h=l?Math.max(m,u):Math.min(m,u);o=+(c-h>=0);let g=o!=s;n=g?c:r,i=g?c:a,t=g?o===1?n-f*p:i+f*p:h}return{[W.VSTOPUP.id]:o===1?t:null,[W.VSTOPLOW.id]:o===1?null:t,[WS.id]:n,[GS.id]:i,[KS.id]:o}}},JS=K(`_TRENDUP`),YS=K(`_TRENDDOWN`),XS=K(`_TREND`),ZS=class extends q{constructor(e,t){super(e,t);let n=iE(t,e.inputs.Period);this.addInner(n)}get helpers(){return[JS,YS,XS,W.BARCOLIX]}calculateAt(e){let t=0,n=0,r=0,i=null,a=0,o=this.innVal(1,W.ATR,e);if(P(o)){let s=(e,t)=>P(e)?e:t,[c,l,u]=[W.Close,W.High,W.Low].map(t=>this.baseVal(t,e)),d=(l+u)/2,f=this.baseVal(W.Close,e-1),p=this.inputs.Multiplier,m=d-p*o,h=d+p*o,[g,_,v]=[JS,YS,XS].map(t=>this.container.getData(t)[e-1]);t=f>g?Math.max(m,g):m,n=f<_?Math.min(h,_):h,r=c>_?1:c<g?-1:s(v,1);let y=r===1;i=y?t:n,a=+!!y}return{[JS.id]:t,[YS.id]:n,[XS.id]:r,[W.SUPTR.id]:i,[W.BARCOLIX.id]:a}}},QS=class extends q{constructor(e,t){super(e,t);let n=e=>$T(t,e,W.Low,W.LL,!1),r=e=>$T(t,e,W.High,W.HH,!0),i=(e,t,n)=>Z(n,(e,t,n)=>(t+n)/2,e,t),a=(e,t)=>i(n(e),r(e),t),o=a(e.inputs.PeriodConversionLine,W.CONVLN),s=a(e.inputs.PeriodBaseLine,W.BASELN),c=i(o,s,W.LEADSP1),l=a(e.inputs.PeriodLaggingSpan2,W.LEADSP2);this.addInner(o,s,c,l)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=+(this.innVal(3,W.LEADSP1,e)>this.innVal(4,W.LEADSP2,e));return{[W.LAGGSP.id]:this.baseVal(W.Close,e),[W.BARCOLIX.id]:t}}getWrappers(){return[this.wrapInner(W.CONVLN,1),this.wrapInner(W.BASELN,2),this.wrapInner(W.LEADSP1,3),this.wrapInner(W.LEADSP2,4)]}},$S=K(`_CUM_PRICE`),eC=K(`_CUM_VOL`),tC=K(`_PER_CHG`),nC=class extends q{constructor(e,t){super(e,t);let n=this.source,r=X(n,se(wE,n),t);this.addInner(r)}valueAt(e,t){return this.container.getData(e)[t]}dateAt(e){return this.container.getTimeData()[e]}},rC=class extends nC{constructor(e,t){super(e,t)}get helpers(){return[$S,eC,tC]}isSame(e,t){switch(this.inputs.AnchorPeriod){case`Session`:default:return en(e,t);case`Week`:return jr(e,t);case`Month`:return Nr(e,t);case`Quarter`:return Pr(e,t);case`Year`:return Fr(e,t);case`Decade`:return lh(e,t);case`Century`:return uh(e,t)}}findPrevPeriodChange(e){for(let t=e;t>0;t--)if(this.valueAt(tC,t)===1)return t;return 0}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=e>0,s=o?this.dateAt(e-1):z.ZERO_DATE,c=this.dateAt(e),l=o&&this.isSame(s,c),u=l?this.valueAt($S,e-1):0,d=l?this.valueAt(eC,e-1):0,f=this.innVal(0,W.Volume,e),p=u+this.innVal(1,this.source,e)*f,m=d+f;if(t=p/m,l){let o=this.findPrevPeriodChange(e-1),s=this.container.getData(W.VWAP).slice(o,e);s.push(t);let c=me(s),l=s.map(e=>(e-c)*(e-c)),u=Math.sqrt(me(l)),d=this.inputs.Stdev1stMultiplier*u;n=t+d,r=t-d;let f=this.inputs.Stdev2ndMultiplier*u;i=t+f,a=t-f}else n=t,r=t,i=t,a=t;return{[$S.id]:p,[eC.id]:m,[tC.id]:+!l,[W.VWAP.id]:t,[W.VWAPSD1U.id]:n,[W.VWAPSD1L.id]:r,[W.VWAPSD2U.id]:i,[W.VWAPSD2L.id]:a}}},iC=class extends nC{constructor(e,t){super(e,t)}get helpers(){return[$S,eC]}isSameOhlcBar(e,t){let{unit:n,size:r}=this.aggregation;switch(n){case g.Tick:return e===t;case g.Intraday:return Dr(t,Ut(e,r));case g.Day:return Dr(t,jt(e,r));case g.Week:return jr(e,t);case g.Month:return Nr(e,t);case g.Quarter:return Pr(e,t);case g.Year:return Fr(e,t);default:throw Error(`Unexpected aggregation unit ${g[n]}`)}}calculateAt(e){let t=null,n=null,r=null,i=this.inputs.Anchor,a=this.dateAt(e);if(Dr(i,a)||this.isSameOhlcBar(a,i)){let i=e>0,a=i?this.valueAt($S,e-1):0,o=i?this.valueAt(eC,e-1):0,s=this.innVal(0,W.Volume,e);n=a+this.innVal(1,this.source,e)*s,r=o+s,t=n/r}return{[$S.id]:n,[eC.id]:r,[W.AVWAP.id]:t}}},aC=K(`_DIFF`),oC=[aC,W.Buy,W.Sell];function sC(e,t,n,r){let i=null,a=null,o=null;P(n,r)&&(o=n-r);let s=t>0?e.getData(aC)[t-1]:null;return P(o,s)&&(i=o>0&&s<=0?1:null,a=o<0&&s>=0?-1:null),{[aC.id]:o,[W.Buy.id]:i,[W.Sell.id]:a}}var cC=class extends q{constructor(e,t){super(e,t);let n=DE(e,`MA`,`Average`),r=n(t,e.inputs.Period1,this.source,W.MAS),i=n(t,e.inputs.Period2,this.source,W.MAL);this.addInner(r,i)}get helpers(){return oC}calculateAt(e){let t=this.innVal(1,W.MAS,e),n=this.innVal(2,W.MAL,e);return sC(this.container,e,t,n)}getWrappers(){return[this.wrapInner(W.MAS,1),this.wrapInner(W.MAL,2)]}},lC=class extends q{_maIndex;_maTarget;constructor(e,t){super(e,t),SE(this);let n=DE(e,`MA`,`Average`)(t,e.inputs.Period,this.source);this.addInner(n);let[r]=CE(this);this._maIndex=r+1,this._maTarget=n.target}get helpers(){return oC}calculateAt(e){let t=this.innVal(this._maIndex,this._maTarget,e),[,n]=CE(this),r=n.getData(this.source)[e],i=sC(this.container,e,r,t);return i[this.target.id]=t,i}},uC=K(`_PVM`),dC=K(`_NVM`),fC=class extends q{constructor(e,t){super(e,t);let n=function(e){return{[uC.id]:e>0?Math.abs(this.baseVal(W.High,e)-this.baseVal(W.Low,e-1)):null}},r=function(e){return{[dC.id]:e>0?Math.abs(this.baseVal(W.Low,e)-this.baseVal(W.High,e-1)):null}},i=X(uC,n,t),a=X(dC,r,t),o=rE(t,W.TR);this.addInner(i,a,o)}calculateAt(e){let t=null,n=null,r=this.period;if(this.atLeast(e,r)){let i=this.past(e,r,uC,this.innCont(1)),a=this.past(e,r,dC,this.innCont(2)),o=this.past(e,r,W.TR,this.innCont(3));if(k(i)&&k(a)&&k(o)){let e=pe(i),r=pe(a),s=pe(o);t=e/s,n=r/s}}return{[W.PLVI.id]:t,[W.MNVI.id]:n}}},pC=K(`_AVG`),mC=class extends q{isPercent;constructor(e,t){super(e,t);let n=DE(e,`MA`,`Average`),r=this.period,i=n(t,r,this.source,pC);this.isPercent=e.inputs.Distance===`Percentage`,this.addInner(i)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=null,n=null,r=this.innVal(1,pC,e),i=this.baseVal(this.source,e);if(r!=null&&r!==0){t=i-r,this.isPercent&&(t=100*t/r);let a=t<=0;if(n=a?1:3,e>0){let r=this.container.getData(this.target)[e-1];r!==null&&(a&&t>r&&(n=0),!a&&t<r&&(n=2))}}return{[this.target.id]:t,[W.BARCOLIX.id]:n}}},hC=class extends q{constructor(e,t){super(e,t);let n=Y(Y(lE(t,this.inputs.PeriodRsi,this.source,W.RSI),this.inputs.PeriodEma1,W.RSI,W.EMA),this.inputs.PeriodEma2,W.EMA,W.EMA),r=J(n,this.inputs.PeriodMa,W.EMA,W.MA),i=Z(W.DOSCH,(e,t,n)=>t-n,n,r),a=J(i,this.inputs.PeriodSig,W.DOSCH,W.DOSCS);this.addInner(i,a)}getWrappers(){return[this.wrapInner(W.DOSCH,1),this.wrapInner(W.DOSCS,2)]}},gC=class extends q{constructor(e,t){super(e,t);let n=this.inputs.Period,r=this.inputs.Increment,i=Math.min(Math.max(0,this.inputs.Count),10);for(let e=0;e<i;++e){let i=J(t,n+e*r,this.source,this.outFields[e]);this.addInner(i)}}getWrappers(){let e=this.outFields,t=this.inputs.Count;return[this.wrapInner(e[0],1),this.wrapInner(e[1],2),this.wrapInner(e[2],3),this.wrapInner(e[3],4),this.wrapInner(e[4],5),this.wrapInner(e[5],6),this.wrapInner(e[6],7),this.wrapInner(e[7],8),this.wrapInner(e[8],9),this.wrapInner(e[9],10)].slice(0,t)}},_C=K(`_HAO`),vC=K(`_HAH`),yC=K(`_HAL`),bC=K(`_HAC`),xC=class extends q{constructor(e,t){super(e,t);let n=DE(e,`EMA`,`Smoothing1`),r=e.inputs.Period1,i=n(t,r,W.Open),a=n(t,r,W.High),o=n(t,r,W.Low),s=n(t,r,W.Close),c=Z(bC,(e,t,n,r,i)=>(t+n+r+i)/4,i,a,o,s);function l(e,t,n,r){let i=null;if(e>0){let r=this.container.getData(_C)[e-1],a=this.innVal(2,bC,e-1);P(r,a)?i=(r+a)/2:P(t,n)&&(i=(t+n)/2)}return i}let u=Z(_C,l,i,s,c),d=Z(vC,(e,t,n,r)=>P(t,n,r)?Math.max(t,Math.max(n,r)):null,a,u,c),f=Z(yC,(e,t,n,r)=>P(t,n,r)?Math.min(t,Math.min(n,r)):null,o,u,c),p=DE(e,`EMA`,`Smoothing2`),m=e.inputs.Period2,h=p(u,m,_C,W.Open),g=p(d,m,vC,W.High),_=p(f,m,yC,W.Low),v=p(c,m,bC,W.Close),y=X(W.Change,function(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Close,e-1);P(n,r)?t=n-r:P(n)&&!P(r)&&(t=0)}return{[W.Change.id]:t}},v);this.addInner(h,g,_,v,y)}getWrappers(){return[this.wrapInner(W.Open,1),this.wrapInner(W.High,2),this.wrapInner(W.Low,3),this.wrapInner(W.Close,4),this.wrapInner(W.Change,5)]}},SC=K(`_DELTA`),CC=class extends q{constructor(e,t){super(e,t);let n=e.inputs,r=Y(t,n.PeriodEmaKeltner,W.Close),i=iE(t,n.PeriodAtrKeltner);function a(e,t,n,r){return P(n,r)?n+e*r:null}let o=n.MultiplierKeltner,s=Z(W.KCUP,se(a,o),r,i),c=Z(W.KCLOW,se(a,-o),r,i),l=hE(t,n.PeriodBollinger,n.WidthBollinger),u=gE(t,n.PeriodMomentum),d=J(t,n.PeriodMomentum,W.Close);function f(e,t,n,r){let i=null,a=this.innVal(1,W.DONMID,e);return P(a,r)&&(i=t-(a+r)/2),i}let p=_E(Z(SC,f,t,u,d),n.PeriodMomentum,SC,W.TTMSQZOSC);this.addInner(s,c,l,p)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=null,n=null,r=-1,i=this.innVal(1,W.KCUP,e),a=this.innVal(2,W.KCLOW,e),[o,s]=[W.BOLLBU,W.BOLLBL].map(t=>this.innVal(3,t,e));o<i&&s>a?t=0:n=0;let c=this.innVal(4,W.TTMSQZOSC,e),l=e>0?this.innVal(4,W.TTMSQZOSC,e-1):null;if(P(c))if(!P(l))r=2;else{let e=c>=0,t=l<c;r=e?t?3:2:+!!t}return{[W.TTMSQZON.id]:t,[W.TTMSQZOFF.id]:n,[W.BARCOLIX.id]:r}}getWrappers(){return[this.wrapInner(W.TTMSQZOSC,4)]}},wC=e=>{let t=e.unit===g.Month;return{mapper:e=>e.query.symbol,loadMoreData:!1,recompute:d.Manual,missing:t?u.UseNext:u.UsePrevious,stretch:e=>!1,fieldMap:new Map([[W.Close,W.CRS]]),noDataApproach:f.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1}},TC=class extends q{constructor(e,t){if(super(e,t),NE(t)){let n=$().getTimeSeriesDataSource(),r=t.query.duplicate();r.symbol=this.inputs.Symbol.toUpperCase();let i=n.getTimeSeries(r),a=e=>e.query?.symbol,{model:o}=Su(((e,t)=>`{${a(e)}} / {${a(t)}}`)(t,i),!1),s=wC(e.aggregation),c=new Ev(o,[t,i],s),l=DE(e,`MA`,`Average`)(c,this.period,W.CRS,W.CRSAVG);this.addInner(i,c,l),this.canLoadMoreData=!0,this.initialNotification=!0}else{let e=X(W.Close,(e,t)=>null,t),n=X(W.CRS,(e,t)=>null,t),r=X(W.CRSAVG,(e,t)=>null,t);this.addInner(e,n,r),this.canLoadMoreData=!1}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(W.DateTime,2),this.wrapInner(W.CRS,2),this.wrapInner(W.CRSAVG,3)]}},EC=K(`_DIFF`),DC=K(`_RANK`),OC=K(`_CHG`),kC=K(`_AVG`),AC=K(`_HBRAKE_CHG`),jC=K(`_HEIGHT_DELTA`),MC=K(`_ACTION`),NC=K(`_REVERSAL`),PC=200,FC=10,IC=e=>[e>0,e<0],LC=[null,null,null],RC={None:0,Hold:1,Take:2};function zC([e,t],n){let r=null;if(n>0){let t=this.baseVal(e,n-1);P(t)&&(r=this.baseVal(e,n)-t)}return{[t.id]:r}}var BC=class extends q{useHandbrake;constructor(e,t){super(e,t);let n=DE(e,`MA`,`Average`),r=n(t,xt(1,999,this.inputs.FastPeriod),W.Close),i=xt(0,999,this.inputs.SlowPeriod),a=i>0,o=a?n(t,i,W.Close):t,s=Z(EC,a?(e,t,n)=>t-n:(e,t,n)=>n-t,r,o),c=X(OC,se(zC,[W.Close,OC]),t),l=X(DC,function(e){let t=Math.abs(this.baseVal(EC,e)),n=null,r=0,i=0;for(let n=e-1;n>=0&&r<PC;--n){let e=Math.abs(this.baseVal(EC,n));r++,e<t&&i++}return r>0&&(n=Math.floor(i/r*FC)),n===FC&&n--,{[DC.id]:n}},s),u=xt(0,999,this.inputs.HandbrakePeriod);this.useHandbrake=u>0;let d=n(t,u,W.Close,kC),f=X(AC,se(zC,[kC,AC]),d);this.addInner(c,s,l,f)}get helpers(){return[jC,W.BARCOLIX,MC,NC]}getStateAt(e){let t=this.innVal(2,EC,e);return P(t)?IC(t):LC}findPreviousKnownState(e){for(let t=e-1;t>0;t--){let e=this.getStateAt(t);if(e===LC)return LC;let[n,r]=e;if(n||r)return e}return LC}getBuySell(e){let t=this.getStateAt(e);if(t===LC)return LC;let[n,r]=t,i=this.findPreviousKnownState(e),[a,o]=i;if(!n&&!r)return i===LC?LC:[a,o,!1];let s=n!==a||r!==o;return s?[a,o,s]:[n,r,s]}getPrev(e,t){return t>0?this.container.getData(e)[t-1]:null}calculateAt(e){let t=null,n=null,r=0,i=-1,a=RC.None,[o,s,c]=this.getBuySell(e),[l,u]=[NC,MC].map(t=>this.getPrev(t,e)),[d,f]=[0,-1].map(t=>this.innVal(4,AC,e+t));if(i=c?FC:this.innVal(3,DC,e),this.useHandbrake&&P(d,f)){let t=o&&f>0||s&&f<0,n=!o&&d>0||!s&&d<0;c?(i=n?FC:FC+2,a=u):(l===!0||u===RC.Hold)&&(t?(i=this.innVal(3,DC,e),a=RC.Take):(i=n?FC+1:FC+3,a=RC.Hold))}if(P(this.innVal(2,EC,e))){let t=this.innVal(1,OC,e),[n,i]=IC(t),a=Math.abs(t);(o&&n||s&&i)&&(r=a),(o&&i||s&&n)&&(r=-a)}return o?t=1:s&&(n=1),{[W.JPIB.id]:t,[W.JPIS.id]:n,[W.BARCOLIX.id]:i,[jC.id]:r,[MC.id]:a,[NC.id]:c}}},VC=class extends BC{constructor(e,t){e.inputs=dt(B(`JPI`).defaults.inputs.filter(e=>e.name!==`HandbrakePeriod`)),super(e,t)}},HC={FastPeriod:8,SlowPeriod:21,HandbrakePeriod:13,Average:`EMA`,Height:`Fixed`},UC=class extends BC{constructor(e,t){e.inputs=structuredClone(HC),super(e,t)}},WC=e=>{let t=e.unit===g.Month;return{mapper:e=>e.query.symbol,loadMoreData:!1,recompute:d.Manual,missing:t?u.UseNext:u.UsePrevious,stretch:e=>!1,fieldMap:new Map([[W.Close,W.DRS]]),noDataApproach:f.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1}},GC=class extends q{get indexSymbol(){return this.inputs[z.INPUT_SYMBOL]}constructor(e,t){if(super(e,t),NE(t)){let n=$().getTimeSeriesDataSource(),r=t.query.duplicate();r.symbol=this.indexSymbol;let i=n.getTimeSeries(r),{model:a}=Su(`{${t.query.symbol}} / {${i.query.symbol}} * 100`,!1),o=WC(e.aggregation),s=new Ev(a,[t,i],o);this.addInner(i,s),this.canLoadMoreData=!0,this.initialNotification=!0}else{let e=X(W.Close,(e,t)=>null,t),n=X(W.DRS,(e,t)=>null,t);this.addInner(e,n),this.canLoadMoreData=!1}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(W.DateTime,2),this.wrapInner(W.DRS,2)]}},KC=class extends q{get indexSymbol(){return this.inputs[z.INPUT_SYMBOL]}constructor(e,t){super(e,t);let n=fE(t,this.indexSymbol,e.aggregation),r=J(n,this.period,W.DRS);this.addInner(n,r),this.canLoadMoreData=!0,this.initialNotification=!0}calculateAt(e){let t=this.innVal(1,W.DRS,e),n=this.innVal(2,W.MA,e),r=null;return P(t,n)&&n!==0&&(r=(t/n-1)*100),{[W.MRS.id]:r}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},qC=K(`_SMTH_ROC`),JC=K(`_TEN_SMTH_ROC`);function YC(e,t,n,r,i){return new Iv({source:r,target:i,outFields:[i],aggregation:n,inputs:UT(t)},e,e=>2/e)}var XC=class extends q{constructor(e,t){super(e,t);let n=cE(t,1),r=e.aggregation,i=this.inputs.Period1,a=Z(JC,(e,t)=>10*t,YC(n,i,r,W.ROC,qC)),o=this.inputs.Period2,s=YC(a,o,r,JC,W.PMO),c=Y(s,this.inputs.Period3,W.PMO,W.PMOS);this.addInner(s,c)}getWrappers(){return[this.wrapInner(W.PMO,1),this.wrapInner(W.PMOS,2)]}},ZC=K(`_VOL_AVG`),QC=class extends q{constructor(e,t){super(e,t);let n=DE(e,`MA`)(t,this.period,W.Volume,ZC,!0);this.addInner(n)}calculateAt(e){let t=null,n=this.innVal(0,W.Volume,e),r=this.innVal(1,ZC,e);return P(n,r)&&r!==0&&(t=n/r),{[this.target.id]:t}}},$C=e=>Xe(.5**(1/e),6),ew=52,tw=ew/2,nw=ew+1,rw=tw+1,iw=5,aw=tw*iw+1,ow=(()=>{let e=$C(ew-1),t=De(ew,t=>e**+t),n=ew/pe(t);return t.map(e=>e*n)})(),sw=[`Renko`,`Kagi`,`PointAndFigure`,`LineBreak`],cw=class extends q{isDaily;isFeasible=!0;constructor(e,t){super(e,t);let n=Dv(t),r=n.query?.curveStyle;this.isFeasible=!(n instanceof xg)&&(!P(r)||!sw.includes(h[r])),this.isDaily=e.aggregation.unit===g.Day}acceptable(e,t,n,r){return this.isDaily?r===0?!0:!jr(this.baseVal(W.DateTime,t),this.baseVal(W.DateTime,n)):e>0&&n-t>=iw}pluckValues(e){let t=0,n=[],r=e+iw;for(let i=0;t<nw&&e-i>0;i++){let a=e-i,o=this.baseVal(this.source,a);this.acceptable(o,a,r,t)&&(n.push(o),r=a,t++)}return n}calculateAt(e){let t=null;if(this.isFeasible&&e>=aw){let n=1,r=this.pluckValues(e),i=r.length;if(i>=rw)for(let e=0;e<i-1;e++){let t=r[e]/r[e+1]-1;t<0?t=Math.max(t,-.2):t>=0&&(t=Math.min(t,.2)),t=t*ow[e]+1,n*=t}t=100*(n-1)}return{[this.target.id]:t}}},lw=20;function uw(e,t){switch(e){case g.Intraday:return t>=240?3:t>=120?2:1;case g.Day:default:return 5;case g.Week:return 15;case g.Month:return 60;case g.Quarter:case g.Year:return 240}}function dw(e){return e===_.Continue||e===_.Nearest}var fw=class extends q{additionalChunksCounter=1;noData=!1;isPeriodic=!1;constructor(e,t,n){super(e,n,jv(n,e=>{let t=ne[$()?.config.mode??`Unspecified`];if(!bs(t))return n;let r=e.duplicate(),i=e.aggregation;if(i.hasSpec)return dw(i.spec)?n:new xg(r,!0);let a=i.unit===g.Intraday&&i.size<=5,o=uw(i.unit,i.size);r.aggregation=a?new Vl(g.Tick,i.size,_.PerSeconds):new Vl(g.Intraday,o);let s=a?1:3;return r.barsToFetch=Math.min(z.MAX_INTRADAY_BARS,s*e.barsToFetch),new yg(r)})),this.isPeriodic=t,this.noData=this.innerSeries[1]instanceof xg,this.computedServerSide=!0,this.initialNotification=!0}get canLoadMoreData(){return!1}loadMoreData(){let e=this.innerSeries[1];return!this.noData&&this.additionalChunksCounter<lw&&e.canLoadMoreData&&!e.isLoading?(this.additionalChunksCounter+=1,e.loadMoreData()):Promise.resolve()}recalculateAt(e,t,n){if(e.src!==this.innerSeries[0])return;let r=n?G.TS_DATAPOINTADDED:G.TS_DATAPOINTCHANGED;this.notify(r,this.innerSeries[0].container.size-1)}getWrappers(){return[this.wrapInner(W.Change,1),this.wrapInner(W.Open,1),this.wrapInner(W.Close,1)]}},pw=class extends fw{constructor(e,t){super(e,!1,t)}},mw=class extends fw{constructor(e,t){super(e,!0,t)}},hw=class extends q{constructor(e,t){super(e,t);let n=iE(t,e.inputs.Period,e.inputs.Smoothing);this.addInner(n)}calculateAt(e){let t=null,n=this.innVal(1,W.ATR,e),r=this.baseVal(W.Close,e);return P(n,r)&&r>0&&(t=n/r*100),{[W.ATRP.id]:t}}},gw=K(`_DR`),_w=class extends q{constructor(e,t,n){super(e,n);let r=X(gw,e=>{let t=this.baseVal(W.High,e),n=this.baseVal(W.Low,e);return{[gw.id]:P(t,n)?t-n:null}},n),i=DE(e,`MA`)(r,this.inputs.Period,gw,W.ADR);if(t){let e=Z(this.target,(e,t,n)=>!P(t,n)||n===0?null:t/n*100,i,n);this.addInner(e)}else this.addInner(i)}getWrappers(){return[this.wrapInner(this.target,1)]}},vw=class extends _w{constructor(e,t){super(e,!1,t)}},yw=class extends _w{constructor(e,t){super(e,!0,t)}},bw=class extends q{constructor(e,t){super(e,t);let n=this.source,r=X(n,se(wE,n),t),i=cE(r,this.inputs.PeriodRoc1,n),a=cE(r,this.inputs.PeriodRoc2,n),o=cE(r,this.inputs.PeriodRoc3,n),s=cE(r,this.inputs.PeriodRoc4,n),c=J(i,this.inputs.PeriodMa1,W.ROC,W.MA1),l=J(a,this.inputs.PeriodMa2,W.ROC,W.MA2),u=J(o,this.inputs.PeriodMa3,W.ROC,W.MA3),d=J(s,this.inputs.PeriodMa4,W.ROC,W.MA4),f=Z(W.KST,(e,t,n,r,i)=>t+2*n+3*r+4*i,c,l,u,d),p=J(f,this.inputs.PeriodSig,W.KST,W.KSTSIG);this.addInner(f,p)}getWrappers(){return[this.wrapInner(W.KST,1),this.wrapInner(W.KSTSIG,2)]}},xw=K(`_EMA1`),Sw=K(`_EMA2`),Cw=K(`_MACD`),ww=K(`_PCTK`),Tw=K(`_PCTD`),Ew=K(`_PCTK2`),Dw=class extends q{constructor(e,t){super(e,t);let n=Z(Cw,(e,t,n)=>t-n,Y(t,this.inputs.PeriodShort,W.Close,xw),Y(t,this.inputs.PeriodLong,W.Close,Sw)),r=this.inputs.PeriodStoch1,i=this.inputs.PeriodStoch2,a=DE(e,`EMA`),o=a(eE(a(eE(n,r,ww,!1,Cw),i,ww,Tw),r,Ew,!1,Tw),i,Ew,this.target);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},Ow=K(`_EMA1`),kw=K(`_EMA2`),Aw=K(`_CORE`),jw=class extends q{isEmpty=!1;constructor(e,t){if(super(e,t),NE(t)&&e.aggregation?.isEndOfDay){let n=[`$ADVT`,`$DECT`];switch(this.inputs.Source){case`TotalStocks`:default:break;case`NYSEStocks`:n=[`$ADVN`,`$DECN`];break;case`NasdaqStocks`:n=[`$AVDQ`,`$DECQ`];break}let r=this.getSeries(t.query,n[0]),i=this.getSeries(t.query,n[1]),a=this.getTargetSeries(e,r,i);this.addInner(r,i,a),this.canLoadMoreData=!0,this.initialNotification=!0}else{this.isEmpty=!0;let e=X(W.Close,(e,t)=>null,t),n=X(W.Close,(e,t)=>null,t),r=X(this.target,(e,t)=>null,t);this.addInner(e,n,r),this.canLoadMoreData=!1}}get baseIndex(){return+!this.isEmpty}getSeries(e,t){let n=e.duplicate();return n.symbol=t,$().getTimeSeriesDataSource().getTimeSeries(n)}shouldTriggerOurRecalc(e){return super.shouldTriggerOurRecalc(e)?!0:e===this.innerSeries[0]?!1:(e===this.innerSeries[1]||e===this.innerSeries[2])&&this.innHasData(1)&&this.innHasData(2)}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[1].canLoadMoreData||!this.innerSeries[2].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),await this.innerSeries[2].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(this.target,3)]}},Mw=class extends jw{constructor(e,t){super(e,t)}getTargetSeries(e,t,n){let r=(e,t,n)=>t-n,i=Z(Aw,this.inputs.RatioAdjusted===`Yes`?(e,t,n)=>(t-n)/(t+n)*1e3:r,t,n),a=Y(i,this.inputs.Period1,Aw,Ow),o=Y(i,this.inputs.Period2,Aw,kw);return Z(this.target,r,a,o)}},Nw=K(`_INN_HL_ACC_IX`),Pw=new Vl;function Fw(e,t,n){return new Iw({aggregation:Pw,source:null,target:n,outFields:[n],inputs:{...t}},e)}var Iw=class extends q{isWeekly=!1;constructor(e,t){if(super(e,t),t instanceof xg)this.canLoadMoreData=!1;else{let n=this.inputs.Source===`PriceIndex`?`$MADX`:`$FADX`,r=this.getSeries(t.query,n);if(this.addInner(r),this.isWeekly=e.aggregation.unit===g.Week,this.isWeekly){let e=Fw(this.getSeries(t.query,n,Pw),this.inputs,Nw);this.addInner(e)}this.canLoadMoreData=!0,this.initialNotification=!0}}getSeries(e,t,n){let r=e.duplicate();return r.symbol=t,n&&(r.aggregation=n,r.barsToFetch=z.US_TRADING_DAYS_PER_YEAR*15),$().getTimeSeriesDataSource().getTimeSeries(r)}get baseIndex(){return 1}calculateAt(e){if(this.isWeekly)return this.calculateAtWeekly(e);let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,W.Close);k(r)&&(t=pe(r))}return{[this.target.id]:t}}calculateAtWeekly(e){let t=this.container?.size??-1,n=null,r=this.innCont(2);if(t>0&&e===t-1)n=r.getLastDataPoint(Nw);else{let t=this.container.getTimeData()[e],i=r.getTimeData(),a=Te(i,t),o=i[a],s=null;for(;a<r.size&&jr(t,o);)s=a,a+=1,o=i[a];s!==null&&(n=r.getData(Nw)[s])}return{[this.target.id]:n}}shouldTriggerOurRecalc(e){return super.shouldTriggerOurRecalc(e)?!0:e===this.innerSeries[0]?!1:e===this.innerSeries[1]&&this.innHasData(1)}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[1].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},Lw=K(`_RSI1`),Rw=K(`_RSI1_MOM`),zw=K(`_RSI2`),Bw=K(`_RSI2_MA`),Vw=class extends q{constructor(e,t){super(e,t);let n=lE(t,this.inputs.Period1Rsi,W.Close,Lw),r=X(Rw,ce(TE,this.inputs.Period1Mom,Lw),n),i=J(lE(t,this.inputs.Period2Rsi,W.Close,zw),this.inputs.Period2Ma,zw,Bw),a=Z(W.CMBCI,(e,t,n)=>t+n,r,i),o=J(a,this.inputs.PeriodFastMa,W.CMBCI,W.CMBCIF),s=J(a,this.inputs.PeriodSlowMa,W.CMBCI,W.CMBCIS);this.addInner(a,o,s)}getWrappers(){return[this.wrapInner(W.CMBCI,1),this.wrapInner(W.CMBCIF,2),this.wrapInner(W.CMBCIS,3)]}};function Hw(e){return new Zx({source:W.Close,inputs:{},outFields:qT(`COTLC`)},e)}var Uw=class extends q{constructor(e,t){super(e,Hw(t));let n=Number.parseInt(this.inputs.History),r=n===6?52/2:52*n,i=eE(this.innerSeries[0],r,W.COTI,!1,W.COTLCCMSP);this.initialNotification=!0,this.computedServerSide=!0,this.addInner(i)}getWrappers(){return[this.wrapInner(W.COTI,1)]}},Ww=K(`_MUL_ATR`),Gw=class extends q{isLong;constructor(e,t){super(e,t),this.isLong=this.inputs.Direction===`Long`;let n=this.period,r=iE(t,n),i=this.inputs.Multiplier,a=Z(Ww,(e,t)=>t===null?null:i*t,r),o=$T(t,n,W.High,W.HH,!0),s=$T(t,n,W.Low,W.LL,!1);this.addInner(a,o,s)}calculateAt(e){let t=null,n=null,r=this.innVal(1,Ww,e);return r!==null&&(this.isLong?t=this.innVal(2,W.HH,e)-r:n=this.innVal(3,W.LL,e)+r),{[W.CHEXL.id]:t,[W.CHEXS.id]:n}}},Kw=class extends q{constructor(e,t){let n=e.outFields??[],r=e=>{let t=$().getTimeSeriesDataSource();return e.seriesKind=w.Options,e.fields=n,t.getTimeSeries(e)},i=n.length===1?n[0]:void 0,a=i?Mv(t,i,r):jv(t,r);super(e,a),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return this.outFields.map(e=>this.wrapInner(e,0))}},qw=class extends Kw{},Jw=class extends Kw{},Yw=class extends Kw{},Xw=class extends Kw{},Zw=class extends Kw{},Qw=class extends Kw{},$w=class extends Kw{},eT=class extends q{constructor(e,t){super(e,t);let n=iE(t,1),r=this.inputs.Period,i=$T(t,r,W.High,W.HH,!0),a=$T(t,r,W.Low,W.LL,!1);this.addInner(n,i,a)}calculateAt(e){let t=null,n=this.period;if(e>n){let r=this.past(e,n,W.ATR,this.innCont(1));if(k(r)){let i=pe(r)/(this.innVal(2,W.HH,e)-this.innVal(3,W.LL,e));t=100*Math.log10(i)/Math.log10(n)}}return{[this.target.id]:t}}},tT=class extends q{constructor(e,t){super(e,t);let n=DE(e,`MA`,`Average`),r=n(t,e.inputs.Period1,this.source,W.MACLD1),i=n(t,e.inputs.Period2,this.source,W.MACLD2);this.addInner(r,i)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=+(this.innVal(1,W.MACLD1,e)>this.innVal(2,W.MACLD2,e));return{[W.BARCOLIX.id]:t}}getWrappers(){return[this.wrapInner(W.MACLD1,1),this.wrapInner(W.MACLD2,2)]}},nT=K(`_CORE`),rT=class extends jw{constructor(e,t){super(e,t)}getTargetSeries(e,t,n){let r=Z(nT,(e,t,n)=>t/(t+n),t,n);return DE(e,`MA`,`Average`)(r,this.inputs.Period,nT,this.target)}},iT=class extends q{stdDevs;periodForecast;unitsPerYear;constructor(e,t){super(e,t),this.unitsPerYear=AE(e.aggregation),this.stdDevs=this.toInt(`StandardDeviations`),this.periodForecast=this.toInt(`PeriodForecast`);let n=this.getHistVolPeriod();if(n!==null){let r=vE(t,n,e.aggregation);this.addInner(r)}}getHistVolPeriod(){return this.isCustomVolatility?null:Number.parseInt(this.volatilityParam.substring(2))}toInt(e){return Number.parseInt(this.inputs[e])}get volatilityParam(){return this.inputs.Volatility}get isCustomVolatility(){return this.volatilityParam===`Custom`}get haveVolatility(){return this.isCustomVolatility||this.innHasData(1)}getVolatilityPercent(){return(this.isCustomVolatility?this.inputs.VolatilityPercent:this.innCont(1).getLastDataPoint(W.HV))/100}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null;if(this.haveVolatility){let s=this.base.size-this.periodForecast;if(e>=s){let c=this.base.getLastDataPoint(W.Close),l=this.getVolatilityPercent(),u=e-s+1,d=c*l*Math.sqrt(u/this.unitsPerYear);if(t=c+d,n=c-d,this.stdDevs>1){let e=2*d;if(r=c+e,i=c-e,this.stdDevs>2){let e=3*d;a=c+e,o=c-e}}}}return{[W.PCUP1.id]:t,[W.PCDN1.id]:n,[W.PCUP2.id]:r,[W.PCDN2.id]:i,[W.PCUP3.id]:a,[W.PCDN3.id]:o}}recalculateAt(e,t,n){let r={tag:bt(),src:this.innerSeries[0]};n&&this.calculate(r)}},aT=class extends q{constructor(e,t){super(e,jv(t,e=>new oT(e))),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return[this.wrapInner(W.Delta,0),this.wrapInner(W.Gamma,0),this.wrapInner(W.Theta,0),this.wrapInner(W.Vega,0)]}},oT=class extends yg{constructor(e){super(e)}getRetriever(){return Jr(this.query.symbol)?new lT:ei(this.query.symbol)?new uT:new cT}};function sT(){return new bh([W.DateTime,W.Delta,W.Gamma,W.Theta,W.Vega])}var cT=class{supportsChunks;constructor(){this.supportsChunks=!1}async retrieve(e){return sT()}},lT=class extends Gh{emptyContainer(e,t){return sT()}get iterateForward(){return!1}getPageName(){return`getFuturesOptionsHistory`}processRow(e,t,n){n.addDataPoint(W.DateTime,ph(e.date.substring(0,10))),n.addDataPoint(W.Delta,e.delta),n.addDataPoint(W.Gamma,e.gamma),n.addDataPoint(W.Theta,e.theta),n.addDataPoint(W.Vega,e.vega)}},uT=class extends Gh{emptyContainer(e,t){return sT()}addExtraParams(e){e.fields=`delta,gamma,theta,vega`}get iterateForward(){return!0}getPageName(){return`getEquityOptionsHistory`}processRow(e,t,n){n.addDataPoint(W.DateTime,ph(e.date)),n.addDataPoint(W.Delta,e.delta),n.addDataPoint(W.Gamma,e.gamma),n.addDataPoint(W.Theta,e.theta),n.addDataPoint(W.Vega,e.vega)}},dT=K(`_RSI1`),fT=K(`_RSI2`),pT=class extends q{constructor(e,t){super(e,t);let n=lE(t,this.inputs.Period1,this.source,dT),r=lE(t,this.inputs.Period2,this.source,fT),i=Z(W.RSA,(e,t,n)=>(t+n)/2,n,r),a=DE(e,`MA`,`Average`)(i,this.inputs.PeriodAvg,W.RSA,W.RSAAVG);this.addInner(i,a)}getWrappers(){return[this.wrapInner(W.RSA,1),this.wrapInner(W.RSAAVG,2)]}},mT=class extends q{constructor(e,t){super(e,t),SE(this);let n=e.inputs.PeriodRSI,r=e.inputs.PeriodTradeSignal,i=e.inputs.PeriodMarketBase,a=e.inputs.PeriodBB,[o]=CE(this),s=this.innerSeries[o],c=lE(s,n,this.source,W.TDIPRC),l=J(c,r,W.TDIPRC,W.TDITSL),u=J(c,i,W.TDIPRC,W.TDIMBL),d=dE(c,a,W.TDIPRC,W.MSD);this.addInner(c,l,u,d)}calculateAt(e){let t=this.inputs.MultiplierBB,n=+!!this.sourceNeedsCompute,r=this.innVal(1+n,W.TDIPRC,e),i=this.innVal(2+n,W.TDITSL,e),a=this.innVal(3+n,W.TDIMBL,e),o=this.innVal(4+n,W.MSD,e),s=null,c=null;if(P(a,o)){let e=t*o;s=a+e,c=a-e}return{[W.TDIPRC.id]:r,[W.TDITSL.id]:i,[W.TDIMBL.id]:a,[W.TDIUPR.id]:s,[W.TDILWR.id]:c}}},hT=K(`_ANCHR`),gT=class extends q{isLong;isPercent;constructor(e,t){super(e,t);let n=e.inputs.Period,r=e.inputs.Range;this.isLong=e.inputs.Direction===`Long`,this.isPercent=e.inputs.Type===`Percent`;let i=r===`Close`,a=W.Close;i||(a=this.isLong?W.High:W.Low);let o=$T(t,n,a,hT,this.isLong);this.addInner(o)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=null,n=this.innVal(1,hT,e),r=this.inputs.StopValue;if(n!==null){let e=this.isPercent?n*r/100:r;t=this.isLong?n-e:n+e}let i=+!!this.isLong;return{[W.PPS.id]:t,[W.BARCOLIX.id]:i}}},_T=K(`_HH_N`),vT=K(`_LL_N`),yT=K(`_HH_H1`),bT=K(`_LL_H1`),xT=K(`_HH_H2`),ST=K(`_LL_H2`),CT=class extends q{constructor(e,t){super(e,t),SE(this);let n=e.inputs.Period,r=Math.floor(n/2),i=$T(t,n,W.High,_T,!0),a=$T(t,n,W.Low,vT,!1),o=$T(t,r,W.High,yT,!0),s=$T(t,r,W.Low,bT,!1),c=$T(t,r,W.High,xT,!0),l=$T(t,r,W.Low,ST,!1);this.addInner(i,a,o,s,c,l)}calculateAt(e){let t=this.period,n=Math.floor(t/2),[,r]=CE(this),i=r.getData(this.source)[e];if(!this.atLeast(e,t))return{[this.target.id]:i};let a=+!!this.sourceNeedsCompute,o=this.innVal(1+a,_T,e),s=this.innVal(2+a,vT,e),c=this.innVal(3+a,yT,e),l=this.innVal(4+a,bT,e),u=this.innVal(5+a,xT,e-n),d=this.innVal(6+a,ST,e-n);if(!P(o,s,c,l,u,d))return{[this.target.id]:i};let f=(o-s)/t,p=(c-l)/n,m=(u-d)/n,h=0;p>0&&m>0&&f>0&&(h=(Math.log(p+m)-Math.log(f))/Math.log(2));let g=Math.exp(-4.6*(h-1));g=Math.max(.01,Math.min(1,g));let _=e>0?this.container.getData(this.target)[e-1]:i,v=_===null?i:g*i+(1-g)*_;return{[this.target.id]:v}}},wT=K(`_MIDPOINT`),TT=K(`_VALUE`),ET=class extends q{constructor(e,t){super(e,t);let n=e.inputs.Period,r=X(wT,se(ob,wT),t),i=$T(r,n,wT,W.HH,!0),a=$T(r,n,wT,W.LL,!1);this.addInner(r,i,a)}get helpers(){return[TT]}calculateAt(e){let t=this.innVal(1,wT,e),n=this.innVal(2,W.HH,e),r=this.innVal(3,W.LL,e);if(!P(n,r,t))return{[W.FISHER.id]:null,[W.FISHTRG.id]:null,[TT.id]:null};let i=n-r,a=i===0?.5:(t-r)/i,o=t=>this.container.getData(t)[e-1],s=e>0?o(TT):null,c=.66*(a-.5)+.67*(s??0);c>.99?c=.999:c<-.99&&(c=-.999);let l=e>0?o(W.FISHER):null,u=.5*Math.log((1+c)/(1-c))+.5*(l??0);return{[W.FISHER.id]:u,[W.FISHTRG.id]:l,[TT.id]:c}}},DT=class extends q{constructor(e,t){super(e,t),SE(this)}computeMidranks(e){let t=e.length,n=e.map((e,t)=>({v:e,i:t}));n.sort((e,t)=>e.v-t.v);let r=Array(t),i=0;for(;i<t;){let e=i,a=n[i].v;for(;e+1<t&&n[e+1].v===a;)e++;let o=(i+1+(e+1))/2;for(let t=i;t<=e;t++)r[n[t].i]=o;i=e+1}return r}pearsonCorrelation(e){let t=e.length;if(t<2)return null;let n=(t+1)/2,r=0;for(let n=0;n<t;n++)r+=e[n];let i=r/t,a=0,o=0,s=0;for(let r=0;r<t;r++){let t=r+1-n,c=e[r]-i;a+=t*c,o+=t*t,s+=c*c}let c=Math.sqrt(o*s);return c===0?null:a/c}calculateAt(e){let t=null,n=this.period,[,r]=CE(this);if(this.atLeast(e,n)){let i=this.past(e,n,this.source,r);if(i.every(e=>e!==null)){let e=this.computeMidranks(i),n=this.pearsonCorrelation(e);n!==null&&(t=100*n)}}return{[W.RCI.id]:t}}},OT=class extends q{constructor(e,t){super(e,t);let n=this.source,r=new DT({source:n,target:W.RCI,inputs:{Period:e.inputs.Period}},t),i=e.inputs.PeriodSignal,a=DE(e,`MA`,`Smoothing`)(r,i,W.RCI,W.RCISIG);this.addInner(r,a)}getWrappers(){return[this.wrapInner(W.RCI,1),this.wrapInner(W.RCISIG,2)]}},kT=K(`_ATR`),AT=function(e){return e[e.Uninitialized=0]=`Uninitialized`,e[e.UpLeg=1]=`UpLeg`,e[e.DownLeg=-1]=`DownLeg`,e}(AT||{}),jT=class extends q{state;useHighLow;isAtrMode;atrMult;percent;constructor(e,t){if(super(e,t),this.useHighLow=e.inputs.Method===`High/Low`,this.isAtrMode=e.inputs.PercentMode===`ATR`,this.percent=e.inputs.Percent,this.atrMult=e.inputs.MultiplierAtr,this.useHighLow||SE(this),this.isAtrMode){let t=e.inputs.PeriodAtr,[n]=this.useHighLow?[0]:CE(this),r=this.innerSeries[n],i=iE(r,t,`SMA`,kT);this.addInner(i)}this.resetState()}getHigh(e){if(this.useHighLow)return this.baseVal(W.High,e);let[,t]=CE(this);return t.getData(this.source)[e]}getLow(e){if(this.useHighLow)return this.baseVal(W.Low,e);let[,t]=CE(this);return t.getData(this.source)[e]}getAtrDenom(e){if(this.useHighLow)return this.baseVal(W.Close,e);let[,t]=CE(this);return t.getData(this.source)[e]}setPivot(e,t){this.state.pivotPrice=e,this.state.pivotIndex=t}setCandidate(e,t){this.state.candPrice=e,this.state.candIndex=t}getDevPct(e){if(this.isAtrMode){let t=!this.useHighLow&&this.sourceNeedsCompute?1:0,n=this.innVal(1+t,kT,e),r=this.getAtrDenom(e);if(n===null||r===null||r===0)return 0;let i=n/r*100;return this.atrMult*i}return this.percent}pct(e,t){return e===0?0:(t-e)/e*100}resetState(){this.state={mode:AT.Uninitialized,pivotPrice:null,pivotIndex:null,candPrice:null,candIndex:null,confirmedPivots:new Map}}calculateAt(e){let t=this.getHigh(e),n=this.getLow(e),r=this.getDevPct(e);if(t===null||n===null)return{};if(e===0){this.resetState();let n=this.useHighLow?this.baseVal(W.Close,e):t;return this.setPivot(n,e),this.setCandidate(n,e),{}}if(this.state.mode===AT.Uninitialized)this.pct(this.state.pivotPrice,t)>=r?(this.state.mode=AT.UpLeg,this.setCandidate(t,e)):-this.pct(this.state.pivotPrice,n)>=r&&(this.state.mode=AT.DownLeg,this.setCandidate(n,e));else if(this.state.mode===AT.UpLeg){let i=t>=this.state.candPrice;i&&this.setCandidate(t,e);let a=(this.state.candPrice-n)/this.state.candPrice*100;if(!i&&a>=r){let t=this.state.candIndex,r=this.state.candPrice;this.state.confirmedPivots.set(t,r),this.setPivot(r,t),this.setCandidate(n,e),this.state.mode=AT.DownLeg}}else if(this.state.mode===AT.DownLeg){let i=n<=this.state.candPrice;i&&this.setCandidate(n,e);let a=(t-this.state.candPrice)/this.state.candPrice*100;if(!i&&a>=r){let n=this.state.candIndex,r=this.state.candPrice;this.state.confirmedPivots.set(n,r),this.setPivot(r,n),this.setCandidate(t,e),this.state.mode=AT.UpLeg}}return{}}getCurrentState(){return this.state}},MT=class extends q{constructor(e,t){super(e,t);let n=X(W.BOP,function(e){let t=null,[n,r,i,a]=[W.Open,W.High,W.Low,W.Close].map(t=>this.baseVal(t,e));if(P(n,r,i,a)){let e=r-i;t=e===0?0:(a-n)/e}return{[this.target.id]:t}},t),r=DE(e,`MA`,`Average`),i=this.period,a=r(n,i,W.BOP,W.BOPAVG);this.addInner(n,a)}getWrappers(){return[this.wrapInner(W.BOP,1),this.wrapInner(W.BOPAVG,2)]}};function NT(e,t){let n=e.length;if(n<2||t.length!==n)return null;let r=0,i=0,a=0,o=0,s=0;for(let c=0;c<n;c++){let n=e[c],l=t[c];r+=n,i+=l,a+=n*n,o+=l*l,s+=n*l}let c=n*s-r*i,l=Math.sqrt((n*a-r*r)*(n*o-i*i));if(l===0||!Number.isFinite(l))return null;let u=c/l;return Number.isFinite(u)?Math.max(-1,Math.min(1,u)):null}var PT=class extends q{constructor(e,t){if(super(e,t),NE(t)){let e=this.inputs.Symbol?.toUpperCase();if(e){let n=$().getTimeSeriesDataSource(),r=t.query.duplicate();r.symbol=e;let i=n.getTimeSeries(r);this.addInner(i),this.canLoadMoreData=!0,this.initialNotification=!0}}}compareCloseAt(e){let t=this.innCont(1);if(!t||t.isEmpty)return null;let n=this.baseVal(W.DateTime,e);if(n===null)return null;let r=t.getData(W.DateTime),i=t.getData(W.Close);if(r.length===0)return null;let a=n.valueOf(),o=Te(r,a,Number),s=r[o];if(!P(s))return null;let c=s.valueOf()<=a?o:o-1;if(c<0)return null;let l=i[c];return P(l)?l:null}calculateCorrelation(e){let t=this.period;if(!this.atLeast(e,t)||!this.innHasData(1))return null;let n=[],r=[];for(let i=e-t+1;i<=e;i++){let e=this.baseVal(W.Close,i),t=this.compareCloseAt(i);if(!P(e,t))return null;n.push(e),r.push(t)}return NT(n,r)}calculateAt(e){return{[this.target.id]:this.calculateCorrelation(e)}}async loadMoreData(e=!0){if(this.isLoading||this.innerSeries.length<2||!this.innerSeries[1].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},FT=4,IT=4,LT=K(`_RVI_NUM`),RT=K(`_RVI_DEN`),zT=K(`_RVI_NUMAVG`),BT=K(`_RVI_DENAVG`);function VT(e){if(e.length<IT||!k(e))return null;let[t,n,r,i]=e;return(t+2*n+2*r+i)/6}var HT={_TR:zy,_RSI:gy,MA:Fv,MAEXP:Lv,MAHLC:zv,VOL:Vv,MAENV:qv,MAENVEXP:Jv,MAENVSMO:Yv,MATRI:Xv,MAWEI:Zv,MAVOL:Fv,MASMO:Rv,MACD:cy,MACDEXP:ly,MACDV:sy,GMMA:gS,OSCI:Qv,OSCIVOL:Qv,RSI:vy,RSIMOD:yy,RSISTO:by,RSA:pT,WPERCR:Ty,HHLL:xy,WGCL:Sy,STOCHF:Oy,STOCHS:ky,BBANDS:Ny,BWIDTH:Py,BPERC:Fy,OBVOL:Ry,ATR:Uy,ADR:vw,ATRP:hw,ADRP:yw,ADX:$y,ADXMOD:eb,ADL:tb,ADWM:nb,CHAOSC:rb,TP:ib,KELCHN:mb,KELBND:hb,DONCHN:_b,DONWIDTH:vb,PVT:yb,ROC:wb,TRIX:bb,PPMOV:Tb,PIVPTS:nS,CPP:rS,ARNUPDW:kb,ARNOSC:Ab,TCHN:jb,TCHRE:Mb,ALLG:Pb,PLTLN:Fb,AWEOSC:Lb,MFV:Bb,CLV:zb,CHAMF:Vb,CHAVOL:Ub,DPO:Wb,CCI:Kb,EMV:qb,ERBRPOW:Xb,ERBLPOW:Yb,FI:Qb,MI:rx,MOM:ix,MFI:ax,MSD:ox,NVI:ux,PVI:dx,PPO:fy,PVO:py,HV:px,PERF:mx,WASI:gx,WWVOL:yx,PARTP:Tx,MOVLR:Ex,TRSP:Vx,TARGP:Hx,COTLC:Zx,COTDAG:Qx,COTFTR:$x,IMPVOL:iS,CTM:uy,CPMI:dy,DEMA:xb,EOSC:Sb,TEMA:Cb,TSI:hS,ADJATR:Wy,COTR:Gy,MCGD:_S,HMA:yS,COPP:xS,REATRS:TS,LINRCHN:ES,CSHO:DS,CSHB:OS,MKTCAP:kS,CTPI:Ay,PCTCHG:AS,OPINT:Hv,STOMOMIX:RS,CHDMOMOSC:US,VSTOP:qS,SUPTR:ZS,ICHCLD:QS,VWAP:rC,MACROSS:cC,PACROSS:lC,VOIN:fC,DIFA:mC,DOSC:hC,BBANDW:Iy,MARIB:gC,HASMO:xC,TTMSQZ:CC,CRS:TC,JPI:BC,CTTP:VC,CTTI:UC,DRS:GC,MRS:KC,PMO:XC,RVOL:QC,WGALPH:cw,VOLAP:pw,AVWAP:iC,KST:bw,STC:Dw,MCCLO:Mw,NHLAI:Iw,CMBCI:Vw,COTI:Uw,CHEXI:Gw,MBBANDS:Ly,OPTIV:qw,IVRANK:Jw,IVPCTL:Yw,OPTVOLPC:Xw,OPTOIPC:Zw,OPTVOL:Qw,OPTOI:$w,CHOP:eT,MACLD:tT,BTI:rT,FRAMA:CT,FISHER:ET,PC:iT,GREEKS:aT,PVACP:mw,TDI:mT,PPS:gT,RCI:OT,BOP:MT,CORR:PT,RVI:class extends q{constructor(e,t){super(e,t);let n=(e,t)=>function(n){let r=this.past(n,IT,e),i=this.past(n,IT,t),a=null;if(k(r)&&k(i)){let e=r,t=i;a=VT(e.map((e,n)=>e-t[n]))}return{[this.target.id]:a}},r=X(LT,n(W.Close,W.Open),t),i=X(RT,n(W.High,W.Low),t),a=this.period,o=J(r,a,LT,zT),s=J(i,a,RT,BT),c=Z(W.RVI,(e,t,n)=>n===0?null:t/n,o,s),l=X(W.RVISIG,function(e){return{[this.target.id]:VT(this.past(e,FT,W.RVI))}},c);this.addInner(c,l)}getWrappers(){return[this.wrapInner(W.RVI,1),this.wrapInner(W.RVISIG,2)]}},ZIGZAG:jT};function UT(e){return{[z.INPUT_PERIOD]:e}}function WT(e){return{[z.INPUT_SYMBOL]:e}}function GT(e){return{target:e,source:null,inputs:nE}}function KT(e,t,n){if(nt(HT,e))return new HT[e](t,n);let r=$()?.config.extensions?.studyProvider;if(r){let i=r.factory(e,t,n);if(i)return i}throw Error(`Study ${e} has not been implemented yet.`)}function qT(e){return B(e).defaults.curves.reduce((e,t)=>e.concat(t.fields.filter(t=>!e.includes(t))),[]).map(e=>W[e])}function JT(e,t,n,r){return{source:t,target:n,inputs:UT(e),allowEmptyValues:r}}function J(e,t,n,r=W.MA,i=!1){return KT(`MA`,JT(t,n,r,i),e)}function Y(e,t,n,r=W.EMA,i=!1){return KT(`MAEXP`,JT(t,n,r,i),e)}function YT(e,t,n,r=W.SMA,i=!1){return KT(`MASMO`,JT(t,n,r,i),e)}function XT(e,t,n,r=W.WMA,i=!1){return KT(`MAWEI`,JT(t,n,r,i),e)}function ZT(e,t,n,r=W.HMA,i=!1){return KT(`HMA`,JT(t,n,r,i),e)}function QT(e,t,n,r,i=W.Close){return KT(`MACDEXP`,{source:i,inputs:{Period1:t,Period2:n,Period3:r},outFields:[W.MACD,W.MACDS,W.MACDH]},e)}function $T(e,t,n,r,i,a=!1){return new Cy({source:n,target:r,inputs:UT(t)},i,a,e)}function eE(e,t,n,r,i=null){return new wy({source:i,target:n,inputs:UT(t)},r,e)}function tE(e,t,n=W.PCTCHG){return KT(`PCTCHG`,{source:t,target:n,inputs:nE},e)}var nE={};function rE(e,t=W.TR){return KT(`_TR`,GT(t),e)}function iE(e,t,n=`SMA`,r=W.ATR){return KT(`ATR`,{target:r,inputs:{[z.INPUT_PERIOD]:t,[z.INPUT_SMOOTHING]:n},source:null},e)}function aE(e,t,n=`MA`,r=W.Close,i=W.ADJATR){return KT(`ADJATR`,{source:r,target:i,inputs:{[z.INPUT_PERIOD]:t,[z.INPUT_SMOOTHING]:n}},e)}function oE(e,t=W.ADL){return KT(`ADL`,GT(t),e)}function sE(e,t=W.TP){return KT(`TP`,GT(t),e)}function cE(e,t,n=W.Close,r=W.ROC){return KT(`ROC`,{source:n,target:r,inputs:UT(t)},e)}function lE(e,t,n,r=W.RSI,i=!1){return KT(`_RSI`,{source:n,target:r,inputs:{...UT(t),Modified:i}},e)}function uE(e,t=W.MFMUL){return KT(`MFV`,GT(t),e)}function dE(e,t,n,r=W.MSD){return KT(`MSD`,{source:n,target:r,inputs:UT(t)},e)}function fE(e,t,n,r=W.DRS){return KT(`DRS`,{target:r,inputs:WT(t),aggregation:n,source:null},e)}function pE(e,t=W.CSHO){return KT(`CSHO`,GT(t),e)}function mE(e,t,n){let r=`TCHN`;return KT(r,{inputs:{PeriodUpper:t,PeriodLower:t,Range:n},outFields:qT(r),source:null},e)}function hE(e,t,n,r=W.Close){let i=`BBANDS`,a=qT(i);return KT(i,{source:r,inputs:{[z.INPUT_PERIOD]:t,[z.INPUT_WIDTH]:n},outFields:a},e)}function gE(e,t){let n=`DONCHN`,r=qT(n);return KT(n,{inputs:UT(t),outFields:r,source:null},e)}function _E(e,t,n,r=W.MOVLR){return KT(`MOVLR`,{source:n,inputs:UT(t),target:r},e)}function vE(e,t,n,r=W.Close,i=W.HV){return KT(`HV`,{source:r,target:i,aggregation:n,inputs:UT(t)},e)}function X(e,t,n){return new cb(GT(e),t,n)}function Z(e,t,...n){return new ab(GT(e),t,...n)}function yE(e,t,n){return t-n}function bE(e,t,n){return(t-n)/n*100}function xE(e){switch(e.id){case`HL/2`:case`OC/2`:case`HLC/3`:case`OHLC/4`:case`HLCC/4`:return!0;default:return!1}}function SE(e){let t=e.source;if(e.sourceNeedsCompute=xE(t),e.sourceNeedsCompute){let n=X(t,se(wE,t),e.innerSeries[0]);e.addInner(n)}}function CE(e){let t=+!!e.sourceNeedsCompute;return[t,e.innCont(t)]}var wE=function(e,t){let[n,r,i,a]=[W.Open,W.High,W.Low,W.Close].map(e=>this.baseVal(e,t)),o=null,s=e.id;switch(s){case`Open`:o=n;break;case`High`:o=r;break;case`Low`:o=i;break;case`Close`:o=a;break;case`HL/2`:o=(r+i)/2;break;case`OC/2`:o=(n+a)/2;break;case`HLC/3`:o=(r+i+a)/3;break;case`OHLC/4`:o=(n+r+i+a)/4;break;case`HLCC/4`:o=(r+i+a+a)/4;break;default:break}return{[s]:o}},TE=function(e,t,n){let r=null;if(this.atLeast(n,e+1)){let i=this.baseVal(t,n-e);i!==null&&(r=this.baseVal(t,n)-i)}return{[this.target.id]:r}},EE={sma:YT,ma:J,ema:Y,wma:XT,hma:ZT};function DE(e,t,n=`Smoothing`){return EE[(e.inputs[n]??t).toLowerCase()]}var OE={atr:iE,adjatr:aE};function kE(e){return OE[e.inputs.TypeOfATR.toLowerCase()]}function AE(e){switch(e.unit){case g.Day:return 252;case g.Week:return 52;case g.Month:return 12;default:return 0}}function jE(e){let t=[W.High,W.Low];return e instanceof Ev&&be(e.targetFields,t).length!==2}function ME(e,t){return e[`Period${t}`]}function NE(e){return!(e instanceof xg)&&e.query instanceof Cv}var PE=class extends Nv{constructor(e,t){let n=Y(t,13,W.Close),r=QT(t,12,26,9,W.Close);super(e,t,n,r),this.query=t.query,this.useNotifications=!0}calculateAt(e){let t=p.Same,n=this.innVal(1,W.EMA,e),r=this.innVal(1,W.EMA,e-1),i=this.innVal(2,W.MACDH,e),a=this.innVal(2,W.MACDH,e-1);return P(n,r,i,a)&&(n>r&&i>a?t=p.Up:n<r&&i<a&&(t=p.Down)),{[W.BREL.id]:t}}getWrappers(){return this.wrapBaseFields(W.Open,W.High,W.Low,W.Close,W.Change,W.Volume,W.OpenInterest,W.TradingDay)}};function FE(e,t){return P(t)?(this[e]=t,null):this[e]}var IE=class{_domain;_range;_extent;_padding;constructor(){this._domain=this._range=this._extent=null,this._padding=[0,0]}domain(e){return FE.call(this,`_domain`,e)}range(e){return FE.call(this,`_range`,e)}padding(e){return FE.call(this,`_padding`,e)}get ready(){return P(this._domain,this._range)}},LE=1/Math.log2(10),RE=(e,t)=>n=>e*(1-n)+t*n,zE=(e,t)=>(t-=e,t>0?n=>(n-e)/t:e=>ue(isNaN(t)?NaN:.5));function BE(e,t){let n=zE(e[0],e[1]),r=RE(t[0],t[1]);return e=>r(n(e))}function VE(e){return Math.sign(e)*Math.log10(1+Math.abs(e/LE))}function HE(e){return Math.sign(e)*LE*(-1+10**Math.abs(e))}var UE=[[0,1],[1,10],[10,100],[100,1e3],[1e3,1e4],[1e4,1e5]],WE=class extends IE{constructor(e,t){super(),this.scaleType=e,this.axis=t}domain(e){return this.axis&&e&&!ge(e,this._domain)&&this.axis.pane.presenter.onScaleDomainChanged(this.axis),super.domain(e)}yToPrice(e){return this.mapValue(e)}rangeWithPadding(){return[this._range[0]+this._padding[0],this._range[1]-this._padding[1]]}mapValue(e,t=!0){if(!this.ready)return null;let n=ue,r=ue;switch(this.scaleType){case S.Linear:break;case S.Logarithmic:n=VE,r=HE;break;default:throw Error(`Unexpected scale type (neither linear nor log)`)}let i=this._domain.map(n),a=this.rangeWithPadding(),o=t?BE(a,i):BE(i,a),s=e=>a[1]-e+a[0];return(t?r:s)(o((t?s:n)(e)))}priceToY(e){return this.mapValue(e,!1)}getTicks(e){if(!this.ready)return[];let[t,n]=this._range.map(e=>this.mapValue(e,!0));if(t===n&&e>0)return[t];let[r,i]=this._domain;if(this.scaleType===S.Linear||r<0||i>1e5)return GE(t,n,e);let a=this.findLogBand(r),o=this.findLogBand(i),s=e*2;return o-a===0?GE(t,n,s):this.getLogTicks(a,o,s,n<t)}findLogBand(e){return UE.findIndex(([t,n])=>e>=t&&e<n)}getLogTicks(e,t,n,r){let i=[...this._domain],a=[];try{for(let o=e;o<=t;o++){let[s,c]=UE[o];o===e?s=i[0]:o===t&&(c=i[1]),this.domain([s,c]);let[l,u]=this._range.map(e=>this.mapValue(e,!0)),d=GE(l,u,n);a=r?d.concat(a):a.concat(d)}}finally{this.domain(i)}return je(a,r?(e,t)=>e>t:(e,t)=>e<t),a}checkTicks(){return this.scaleType===S.Logarithmic}};function GE(e,t,n){let r,i=-1,a,o,s;if(t=+t,e=+e,n=+n,e===t&&n>0)return[e];if((r=t<e)&&(a=e,e=t,t=a),(s=KE(e,t,n))===0||!isFinite(s))return[];if(s>0)for(e=Math.ceil(e/s),t=Math.floor(t/s),o=Array(a=Math.ceil(t-e+1));++i<a;)o[i]=(e+i)*s;else for(e=Math.floor(e*s),t=Math.ceil(t*s),o=Array(a=Math.ceil(e-t+1));++i<a;)o[i]=(e-i)/s;return r&&o.reverse(),o}function KE(e,t,n){let r=Math.sqrt(50),i=Math.sqrt(10),a=Math.sqrt(2),o=(t-e)/Math.max(0,n),s=Math.floor(Math.log(o)/Math.LN10),c=o/10**s;return s>=0?(c>=r?10:c>=i?5:c>=a?2:1)*10**s:-(10**-s)/(c>=r?10:c>=i?5:c>=a?2:1)}var qE={color:z.COLOR_TRANSPARENT},JE={color:z.COLOR_TRANSPARENT,width:0,dashStyle:`Solid`},YE=[W.Open,W.High,W.Low,W.Close],XE=new Set(YE.map(e=>e.id)),ZE=e=>XE.has(e.id),QE=new za(0,0,0,0),$E=class{axis;id;uid;record;metaData;timeSeries;notifyAboutPriceDomains=!1;customPlotValues=!1;_priceMapFirstIndex;priceMapper;_firstVisibleDate=null;_lastVisibleDate=null;main=!1;curves=[];type=C.Symbol;isShutDown=!1;targetFields=[];detachedScale;yScale=null;levels;bands;annotations;visFromIndex;visToIndex;_eventsData;precision;visible=!0;constructor(){this.axis=null,this.id=bt(),this.uid=this.id,this.record=new Kd(``),this.metaData=new aa,this.timeSeries=new xg,this.priceMapper=this._priceMapper.bind(this),this._priceMapFirstIndex=new Map}get title(){return``}get showPrevious(){return!1}getPreviousValue(){return null}get mainCurve(){return this.curves[0]}get hasEvents(){return!1}findEvents([e,t]){return[]}get eventsSeries(){return null}get hasEventsData(){return this.hasEvents&&P(this.eventsSeries)&&this.eventsSeries.hasData&&this.eventsSeries.container.size>0}getEventFor(e){return null}get isSymbol(){return this.is(C.Symbol)}get isExpression(){return this.is(C.Expression)}get isStudy(){return this.is(C.Study)}get isForward(){return this.is(C.Forward)}get isSeasonal(){return this.is(C.Seasonal)}getValueAt(e,t,n){return null}wrapIfAdvancedStyle(e){let t=e,n=e=>({outFields:e,inputs:{},source:null});return this.mainCurve.isHeikinAshiStyle?t=new Pv(n(Ih.slice()),e):this.mainCurve.isElderImpulseSystemStyle?t=new PE(n(Ih.slice().concat(W.BREL)),e):this.mainCurve.isPercentChangeStyle&&(t=new jS(n(Ih.slice()),e)),t}is(e){return this.type===e}getCacheableEntities(e){this.metaData.getCacheableEntities(e.metaData),this.timeSeries.getCacheableEntities(e.timeSeries)}fromModel(e){this.type=C[e.type];let t=e;this.uid=t.uid,this.main=t.main,t.levels&&(this.levels=t.levels),t.bands&&(this.bands=t.bands),P(t.precision)&&(this.precision=t.precision),this.curves=e.curves.map(e=>{let t=new W_;return t.plot=this,t.fromModel(e),t}),t.detachedScale&&(this.detachedScale=t.detachedScale,this.yScale=new WE(S.Linear,null)),this.visible=t.visible??!0}initialize(){}shutdown(){P(this.timeSeries)&&P(this.timeSeries.shutdown)&&!this.timeSeries.isCached&&this.timeSeries.shutdown(),this.isShutDown=!0}makeQuery(){let e=this.axis.pane.presenter,t=new Cv(null,e.data.aggregation,w.Normal,[pt(rt(e.data,null,`range`,`from`)),pt(rt(e.data,null,`range`,`to`))]);return t.barsToFetch=e.data.maxDataPoints||z.DEFAULT_MAX_RECORDS,t.aggregation.backAdjust&&(t.barsToFetch=4*t.barsToFetch),t.chartId=e.elementId,t.curveStyle=this.curves[0].style,t.visibleRange=rt(e.display,null,`xAxis`,`visibleRange`),t.extendedHours=e.data.extendedHours,t}priceToY(e){return(this.hasDetachedScale?this.yScale:this.axis.yScale).priceToY(e)}get hasDetachedScale(){return P(this.detachedScale,this.yScale)&&this.detachedScale}get hasVisibleCurves(){return this.curves.some(e=>e.visible)}getDetachedScaleMargins(){return z.DEFAULT_DETACHED_SCALE_MARGINS}setViewBox(e){if(!this.hasDetachedScale)return;let{y:t,height:n}=e,{top:r,bottom:i}=this.getDetachedScaleMargins();this.yScale.range([Math.floor(t+r*n),Math.floor(t+n-i*n)])}drawLevels(e){e.save();let t=z.OUT_OF_SCREEN;for(let n of this.levels.filter(e=>e.visible)){let r=this.priceToY(n.value);Oo(e,ko({line:n.line,fill:qE})),Qa(e,{x:-1,y:r},{x:t,y:r})}e.restore()}drawBands(e){e.save();let t=z.OUT_OF_SCREEN;for(let n of this.bands){let r=this.priceToY(n.range.to),i=this.priceToY(n.range.from);Oo(e,ko({fill:n.fill,line:JE})),Xa(e,new za(-1,r,t,i-r),!1)}e.restore()}drawAnnotations(e){e.save(),this.annotations.forEach(t=>t.draw(e,!0)),e.restore()}getEventFields(){return!this.hasEvents||!this.hasEventsData?[]:this.eventsSeries.container.fields.filter(e=>e!==W.DateTime)}getEventsAt(e){let t=this.eventsSeries.container,n=n=>t.getData(n)[e];return this.getEventFields().map(t=>{let r=n(t);if(!P(r))return null;let i=this.getEventFor(t);if(!P(i))return null;let a={field:t,value:r,date:n(W.DateTime),text:i.title,color:i.color};if(t===W.Custom&&r===z.FAKE_CUSTOM_EVENT){let t=e%2==0;return{...a,value:t?`___news`:`___video`,text:t?`N`:`V`}}else return a}).filter(e=>e!=null)}getRefEventField(e,t,n,r){let i=r?.container,a=e.fields[0];t&&(a=e.isOhlc?W.High:n.isTick?W.Last:W.Close);let o=[a,e.fields[0]].filter(N);return N(i)?o.find(e=>i.hasField(e))??a:a}getRefPlot(e){return this.axis.pane.isMain?e.mainPlot:this}drawEvents(e,t){let n=this.axis.pane.presenter,r=n.view.xAxis.xScale,i=r.domain();if(!P(i)||!P(i[0],i[1]))return;let a=(e,t=W.DateTime)=>e.container.getData(t),o=a(this.eventsSeries),s=this.getRefPlot(n),c=s.timeSeries,l=a(c),u=n.data.aggregation,d=s===n.mainPlot,f=a(c,this.getRefEventField(s.mainCurve,d,u,c));if(!Array.isArray(f))return;let{chart:{fontFamily:p}}=this.axis.pane.presenter.display,m=e=>e.valueOf()>=i[0].valueOf()&&e.valueOf()<=i[1].valueOf(),h=o.flatMap((e,i)=>m(e)?this.getEventsAt(i).map(e=>{let i=rh(u,e.date),a=Te(l,+i,Number);if(a<0||a>=f.length)return null;let o=f[a];if(!Ze(o))return null;t.has(a)||t.set(a,-1);let s=t.get(a);t.set(a,++s);let c=r.timeToX(i),d=n.view.getEventRadius(),p=this.axis.yScale.priceToY(o)-s*(d+d+d);return{visible:!0,...e,x:c,y:p,r:d,rect:QE}}).filter(N):[]);e.save();let g=!0;h.forEach(t=>{t.rect=to(e,t,p),this.customEventPopup?.visible&&t.date===this.customEventPopup.date&&(this.showCustomEventPopup(t),g=!1)}),e.restore(),this._eventsData=h,this.customEventPopup?.visible&&g&&this.hideCustomEventPopup()}get customEventPopup(){return this.axis.pane.presenter.view.customEventPopup}hideCustomEventPopup(){this.customEventPopup?.hide()}showCustomEventPopup(e){let{x:t,y:n,r,date:i,value:a}=e;this.customEventPopup?.show({x:t+2*r,y:n-2*r},i,a)}getCustomEventDataAt(e){if(!this._eventsData)return null;let t=this._eventsData.find(t=>t.rect.contains(e));return t?.field===W.Custom?t:null}hitTestCustomEvent(e){return this.getCustomEventDataAt(e)!==null}tryHandleCustomEventClick(e){let t=this.getCustomEventDataAt(e);return P(t)?(this.showCustomEventPopup(t),!0):!1}isEmpty(){let e=this.timeSeries;return P(e)&&e.hasData&&e.container.isEmpty}draw(e){if(this.visible){P(this.levels)&&this.drawLevels(e),P(this.bands)&&this.drawBands(e);for(let t of this.curves)t.draw(e)}}drawTopmost(e,t){this.hasEventsData&&this.drawEvents(e,t)}isComparison(e){return this.axis.comparison===e}invalidatePriceMappingCache(){this._firstVisibleDate=null}_priceMapper(e,t,n,r){if(!P(e)||!this.timeSeries.hasData||!this.shouldPriceMap(n,r))return e;let[i,a]=this.axis.pane.presenter.view.xAxis.xScale.domain()||[];if(!P(i)||!nn(i))return e;if(this._firstVisibleDate!==i){this._firstVisibleDate=i;let e=this.timeSeries.container.getTimeData(),t=t=>Te(e,+t,Number);this.visFromIndex=t(i),this.visToIndex=t(a),this._priceMapFirstIndex.clear()}return this._priceMapFirstIndex.has(n)||this.canPriceMap(t,n),this.priceMap(e,t,n,!1,r)}isOhlcMapping(e){return this.mainCurve.isOhlc&&ZE(e)}getRefPriceMapField(e){return this.isOhlcMapping(e)||e===W.PreviousClose?W.Close:e}dataOf(e){return this.timeSeries.container.getData(e)}canPriceMap(e,t){let n=this.getRefPriceMapField(t),r=this.dataOf(n),i=null,a=this.visFromIndex;for(;i===null&&a<=this.visToIndex;)i=r[a++];this._priceMapFirstIndex.set(n,i===null?NaN:a-1)}priceMap(e,t,n,r=!1,i=x.None){let a=this.getRefPriceMapField(n),o=this._priceMapFirstIndex.get(a);if(!Number.isFinite(o))return e;let s=this.dataOf(a)[o];return this.isComparison(x.Percent)||i===x.Percent?r?s+s*e/100:(e>=s?1:-1)*(Math.abs(e-s)*100)/Math.abs(s):r?s+e:e-s}shouldPriceMap(e,t){return P(t)?t!==x.None:this.isComparison(x.Percent)||this.isComparison(x.Value)}onPriceDomainsUpdated(){}get presenter(){return this.axis?.pane?.presenter}},eD=class extends $E{_symbol;_showPrevious;yearOffset;resolved=null;events;inputs=[];_eventsSeries;compare;tracePlot(e,t={}){zm(e,{chartId:this.axis?.pane?.presenter?.elementId,symbol:this.symbol,...t})}get symbol(){return this._symbol}get title(){return this.symbol}get showPrevious(){return this._showPrevious}getPreviousValue(){if(!P(this.timeSeries)||!P(this.timeSeries.record))return null;let e=this.axis.pane.presenter.display.chart.previous.field;return this.timeSeries.record.getValue(W[e])}getTimeSeries(){let e=$().getTimeSeriesDataSource(),t=this.makeQuery();switch(t.symbol=this.symbol,this.mainCurve.style){case h.Renko:case h.Kagi:case h.PointAndFigure:t.barsToFetch=10100,t.inputs=this.inputs;break;case h.Range:t.barsToFetch=4e3;break;case h.LineBreak:t.inputs=this.inputs;break}let n=this.axis.pane;if(P(n.alignedToYear)){let e=di(this.resolved??t.symbol);e!==null&&(this.yearOffset=n.alignedToYear-e.getFullYear(),t.offset=this.yearOffset)}let r=e.getTimeSeries(t);this.timeSeries=this.wrapIfAdvancedStyle(r),this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:re.Unspecified};this.presenter?.notifyHost(G.TS_MANYCHANGED,e),this.getEvents()}})}getMetaData(){this.metaData=$().getMetaDataSource().getMetaData(this.resolved),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(G.MD_CHANGED,{plot:this})})}getEvents(){if(!this.hasEvents)return;let e=$().getTimeSeriesDataSource(),t={symbol:this.symbol,seriesKind:w.Events,getHashKey:function(){return Object.values(this).filter(e=>typeof e!=`function`).join(`|`)}};z.EVENTS.forEach(e=>{t[e]=rt(this.events,!1,e,`show`)}),this._eventsSeries=e.getTimeSeries(t),this._eventsSeries.ready().then(e=>{e&&this.presenter?.notifyHost(G.TS_EVENTSCHANGED,{series:this.eventsSeries})})}get eventsSeries(){return this._eventsSeries??null}get hasEvents(){return P(this.events)?z.EVENTS.some(e=>rt(this.events,!1,e,`show`)):!1}findEvents(e){if(!this.hasEventsData||e[0]===null||e[1]===null)return[];let t=e[0],n=e[1];if(n>0&&this.axis?.pane?.presenter?.data?.aggregation?.isIntraday){let e=this.timeSeries.container.getTimeData()[n-1];if(this.compare(e,t))return[]}return this.eventsSeries.container.getTimeData().map((e,n)=>this.compare(e,t)?this.getEventsAt(n):[]).flat()}fromModel(e){super.fromModel(e);let t=e;this._showPrevious=t.showPrevious,this.events=t.events,this.inputs=t.inputs||[],this.compare=Fl(this.axis.pane.presenter.data.aggregation),this._symbol=t.symbol}getEventFor(e){let t=this.events[e.id.toLowerCase()];return!P(t)||!t.show?null:t}async initialize(){return Ai.call(this,async()=>(this.tracePlot(`plot:init:start`),this.resolved=await qr(this.symbol),this.isShutDown?(this.tracePlot(`plot:init:aborted`,{resolved:this.resolved}),!1):(this.getMetaData(),this.getTimeSeries(),this.tracePlot(`plot:init:ready`,{resolved:this.resolved}),!0)))}},tD=class extends eD{seriesKind;fundamental;constructor(e){super(),this.seriesKind=e}get showPrevious(){return!1}get title(){return`${this.curves[0].fields[0].name}(${g[this.fundamental].substring(0,1)})`}fromModel(e){this.fundamental=g[e.fundamental],super.fromModel(e)}makeQuery(){let e=new Cv(this.symbol,new Vl(this.fundamental),this.seriesKind);return e.fields=this.curves[0].fields,e}},nD=class{longPressTimeout;constructor(){this.longPressTimeout=null}getTouchCrosshairDelayMillis(){let e=$().config.touchCrosshairDelayMillis;return P(e)&&Number.isFinite(e)?e:z.LONG_PRESS_DELAY_MILLIS}startLongPress(e,t,n){Ie()&&(this.longPressTimeout=setTimeout(()=>this.longPressTriggered(e,t,n),this.getTouchCrosshairDelayMillis()))}longPressTriggered(e,t,n){this.cancelLongPress(),this.performLongPress(e,t,n)}cancelLongPress(){Ie()&&P(this.longPressTimeout)&&(clearTimeout(this.longPressTimeout),this.longPressTimeout=null)}performLongPress(e,t,n){}};function rD(e){return e.locked||e.axis.pane.presenter.display.allAnnotationsLocked}var iD=class extends nD{cursorSet;moved;snapToSupported;constructor(e,t,n){super(),this.annotation=e,this.previous=t,this.cursorSet=!1,this.moved=!1,this.snapToSupported=!1,this.startLongPress(null,t,n)}performLongPress(e,t,n){nO(this.annotation,n)}onMouseMove(e){if(this.cancelLongPress(),this.annotation.axis.pane.presenter.enableTooltip(!1),rD(this.annotation))return;let{point:t,view:n,offset:r}=e;if(!N(t)||t.axis!==this.annotation.axis)return;n.drawCrosshair({ap:t,offset:r}),this.cursorSet||=(this.previous.axis.pane.presenter.view.setCursor(ee.Move),!0);let i=ya(t.point,this.previous.point);this.annotation.offset(i),this.annotation.wasModifiedByTool(),this.annotation.requestRedraw(),this.previous=t,this.moved=!0}onMouseUp(e){this.cancelLongPress(),vk(this.annotation,this.moved,O.Moved)}},aD=class{pointIndex;snapToSupported=!0;moved=!1;alignPointsMode=!1;constructor(e,t){this.annotation=e,this.pointIndex=e.points.indexOf(t)}onMouseMove(e){if(this.alignPointsMode=e.getModifier(D.Shift),this.annotation.axis.pane.presenter.enableTooltip(!1),rD(this.annotation))return;let{point:t,view:n,offset:r}=e;if(n.drawCrosshair({ap:t,offset:r}),P(t)){let e=this.annotation.points[this.pointIndex],n=ya(t.point,e.point);switch(e.moveDirection){case te.Both:e.update(t.price,t.time);break;case te.Horizontal:e.update(e.price,t.time);break;case te.Vertical:e.update(t.price,e.time);break;default:break}this.moved=e.moveDirection!==te.None,this.moved&&this.annotation.wasPointMovedByTool(e,n)}this.annotation.requestRedraw()}onMouseUp(e){vk(this.annotation,this.moved,O.PointMoved)}},oD=class{constructor(e,t,n){this.anchor=e,this.isVertical=t,this.axis=n}hitTest(e){return P(this.anchor)?this.isVertical?Math.abs(e.x-this.anchor.x)<=z.HIT_TEST_TOLERANCE:Math.abs(e.y-this.anchor.y)<=z.HIT_TEST_TOLERANCE:!1}draw(e){let t=z.OUT_OF_SCREEN;this.isVertical?$a(e,this.anchor.x,-t,t):eo(e,this.anchor.y,-t,t)}},sD=class{id;axis;_price;_time;passive=!1;moveDirection=te.Both;visible=!0;point;constructor(e,t,n){this.id=bt(),this.axis=e,t!==void 0&&n!==void 0&&(this.price=t,this.time=n,this.toPoint())}get price(){return this._price}set price(e){this._price=e}get time(){return this._time}set time(e){this._time=e}get movable(){return this.moveDirection!==te.None}get presenter(){return this.pane.presenter}get pane(){return this.axis.pane}toPoint(){let e=this.axis.toPoint(this);P(e)&&Ze(e.x)&&Ze(e.y)&&(this.point=e)}update(e,t){this.price=e,this.time=typeof t==`number`?new Date(t):t,this.toPoint()}updateFromPoint(e){let t=this.axis.toAnnotationPoint(e);this.price=t.price,this.time=t.time,this.point=e}hitTest(e){return this.visible?this.distance(e)<=z.HIT_TEST_TOLERANCE:!1}distance(e){let t=e.x-this.point.x,n=e.y-this.point.y;return Math.abs(Math.sqrt(t*t+n*n)-z.HALF_ANN_POINT_DIMENSION)}draw(e,t){if(P(this.point)){let n=z.HALF_ANN_POINT_DIMENSION;P(t)&&t.locked&&(n*=.6),e.beginPath(),e.ellipse(this.point.x,this.point.y,n,n,0,0,2*Math.PI),e.stroke()}}};function cD(e){return ja(e.fill.color).a===0?e.line.color:e.fill.color}function lD(e,t){return{uid:e.uid,id:e.name,traits:{...e.extractTraits(!0),...e.extractTraits(!1)},extras:{},points:e.extractPoints(),visible:e.visible,locked:e.locked,isUndoRedo:!0,toolChange:t}}function uD(e){return{uid:e.uid,id:e.name,traits:e.extractTraits(!0),extras:e.extractTraits(!1),points:e.extractPoints(),visible:e.visible,locked:e.locked,chart:e.axis.pane.presenter.accessor}}var dD=class{points=[];isSelected=!1;drawn=!0;axis;name;uid;alignPointsSupported=!1;visible=!0;locked=!1;computed=!1;_traits;adjustFill;constructor(e,t){this.axis=e,this.name=t,this.uid=bt()}requestRedraw(){this.axis.pane.presenter.view?.redraw()}prepareDraw(e,t){return this.drawPoints(e,t),this.readyToDraw()}readyToDraw(){return this.activePoints.every(e=>e.point!==void 0)}getPriceScaleAdornments(){return z.EMPTY_ARRAY}getTimeScaleAdornments(){return z.EMPTY_ARRAY}extractTraits(e=!0){let t=F(this.traits),n=ts(this.name);return Object.keys(t).forEach(r=>{let i=n.includes(r);(e&&!i||!e&&i)&&delete t[r]}),e||[`line`,`fill`,`zIndex`].forEach(e=>delete t[e]),t}extractPoints(){return this.activePoints.map(e=>({price:e.price,time:Xe(+e.time,4)}))}offset(e){this.points.filter(e=>e.movable).forEach(t=>{t.updateFromPoint(ba(t.point,e))})}get traits(){return this._traits||=F(this.defaultTraits),this.adjustFill&&=(this._traits.fill.color=cD(this._traits),!1),this._traits}set traits(e){e!==void 0&&ht(this.traits,e)}get activePoints(){return this.points.filter(e=>!e.passive)}get style(){return ko(this.traits)}get defaultTraits(){return Do(this.axis.pane.presenter.display,this.name)}get defaultStyle(){return ko(this.defaultTraits)}get adornStyle(){let e=F(this.defaultTraits);return e.fill.color=this.traits.line.color,e.line.width=0,e.line.color=z.COLOR_TRANSPARENT,ko(e)}get pointsStyle(){let e=F(this.defaultTraits);return e.line.dashStyle=`Solid`,ko(e)}get allowPricesChangeUI(){return this.traits?.allowPricesChangeUI}wasModifiedByTool(){}wasPointMovedByTool(e,t){}isPointDrawn(e){return e.price!==void 0}drawPoints(e,t){this.points.forEach(n=>{let r=this.isPointDrawn(n),i=P(e);t&&(r||!i)&&n.toPoint(),i&&r&&(this.isSelected||this.drawn)&&(Oo(e,this.pointsStyle),n.draw(e,this))})}addPoints(e){for(let t=0;t<e;t++)this.points.push(new sD(this.axis))}toModel(){let e=this.extractPoints();return{id:this.name,uid:this.uid,visible:this.visible,locked:this.locked,points:e,traits:F(this.traits)}}canMove(e){return!0}updatePoints(e){}updateActivePoints(e){let t=this.activePoints;t.length===e.length&&t.forEach((t,n)=>{let r=e[n];t.update(r.price,r.time)})}updateFrom(e,t,n,r,i){typeof r==`boolean`&&(this.visible=r),typeof i==`boolean`&&(this.locked=i);let a=P(e)?F(e):{};P(t)&&ht(a,t),this.traits=a,P(n)&&this.updatePoints(n)}priceMap(e){return this.axis.priceMap(e)}flip(e){let t=this.getFlipAnchorIndices();if(!N(t))return;let n=this.points[t[0]],r=this.points[t[1]];if(e){let e=r.time;r.update(r.price,n.time),n.update(n.price,e)}else{let e=r.price;r.update(n.price,r.time),n.update(e,n.time)}this.wasModifiedByTool()}getFlipAnchorIndices(){return null}};function fD(e,t,n,r){return function(i,a=!0){let o=new t(i,e,n);return a?i.appendAnnotation(o):o.drawn=!1,P(r)&&(o.traits=r),o}}var pD=class{axis;angle;extent;anchor1;anchor2;p1;p2;style;extended;_data;isTrend;constructor(e,t,n,r,i){this.axis=i,P(e,t)&&(this.angle=xa(e,t),this.extent=this.getExtent(e,t),this.anchor1=e,this.anchor2=t,this.p1=n?this.extendPoint(t,-1):e,this.p2=r?this.extendPoint(e,1):t),this.extended=n||r}extendPoint(e,t){return{x:e.x+t*this.extent*Math.cos(this.angle),y:e.y+t*this.extent*Math.sin(this.angle)}}getExtent(e,t){let n=Math.max(Math.abs(e.x),Math.abs(t.x)),r=Math.max(Math.abs(e.y),Math.abs(t.y));return Math.sqrt(n*n+r*r)+z.OUT_OF_SCREEN}hitTest(e){return P(this.p1,this.p2)?Sa([this.p1,this.p2],e,z.HIT_TEST_TOLERANCE):!1}draw(e){P(this.p1,this.p2)&&(Qa(e,this.p1,this.p2),this.extended)}getAdornOffset(e){let t=Ka(e),n=Wa(e,1);return _a(this.p1,this.p2)<0&&(t.y=n+5),t}},mD=class{style;axis;rect;constructor(e,t,n,r){this.axis=r,this.rect=new za(e.x,e.y,t,n)}hitTest(e){return this.rect.contains(e)}draw(e,t){Xa(e,this.rect)}},hD=class extends dD{countCache;constructor(e,t){super(e,t)}draw(e,t){if(this.prepareDraw(e,t)&&!this.getScreenPoints().some(e=>!P(e))&&!this.drawn){let t=this.getElements();Oo(e,this.style),t.forEach((t,n)=>{Oo(e,this.getStyleForElement(t,n)),t.draw(e)}),Oo(e,this.adornStyle),this.adornElements(t,e);let n=this.getMarkers();Oo(e,this.style),n.forEach(t=>{t.draw(e)})}}getBarCount(e,t){if(this.countCache===void 0||this.countCache.time1!==e||this.countCache.time2!==t){let n=this.axis.pane.presenter.view;this.countCache={time1:e,time2:t,barCount:Math.abs(n.toIndex(e)-n.toIndex(t))}}return this.countCache.barCount}getElements(){return[]}get presenter(){return this.axis.pane.presenter}get formatter(){return this.presenter.mainPlot.metaData}data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}getScreenPoints(){return this.points.map(e=>e.point)}getStyleForElement(e,t){return this.style}adornElements(e,t){}hitTestAdornments(e,t){return!1}getTextRef(){return null}hitTest(e){if(!this.drawn&&this.visible){if(this.getScreenPoints().some(e=>!P(e)))return!1;let t=this.getElements(),n=this.getMarkers();return t.some(t=>t.hitTest(e))||n.some(t=>t.hitTest(e))?!0:this.hitTestAdornments(t,e)}return!1}updatePointsFrom(e,t=0){e.forEach((e,n)=>this.points[t+n].update(e.price,e.time))}updatePoints(e){this.allowPricesChangeUI&&this.updatePointsFrom(e)}getMarkers(){return[]}get marker(){return this.traits?.marker}get showPrices(){return this.traits?.showPrices}get singleStyle(){return tt(this.traits?.singleStyle,!0)}get showBackground(){return tt(this.traits?.showBackground,!1)}get backgroundOpacity(){return tt(this.traits?.backgroundOpacity,0)}fillOnlyStyle(e){return ko({line:{color:z.COLOR_TRANSPARENT,dashStyle:`Solid`,width:0},fill:this.traits[e]})}lineOnlyStyle(e){return ko({fill:{color:z.COLOR_TRANSPARENT},line:this.traits[e]})}makeLine(e,t){return new pD(e,t,!1,!1,this.axis)}applyBackgroundOpacity(e){return Ta(wa(e),this.backgroundOpacity)}getTraitsFor(e){let t={fill:{color:z.COLOR_TRANSPARENT},line:{...e.line}};return this.showBackground&&(t.fill.color=this.applyBackgroundOpacity(t.line.color)),t}getFlipAnchorIndices(){return this.points.length===2?[0,1]:null}},gD=class extends hD{_factors;constructor(e,t){super(e,t)}get factorsPropName(){return z.AT_FACTORS}get factors(){return So(this._factors??this.traits[this.factorsPropName])}getStyleForElement(e,t){return e.style??super.getStyleForElement(e,t)}get showLevels(){return this.traits[z.AT_SHOW_LEVELS]}get levelsKind(){return this.traits[z.AT_LEVELS_KIND]}get labels(){return this.traits[z.AT_LABELS]}get isExtended(){return this.points.length===3}isBefore(e,t){return this.points[e].time<this.points[t].time}comparePoints(e,t,n){let r=this.isBefore(e,t);return n||(r=!r),this.points[r?e:t].point}getPoint(e){return this.isExtended?this.comparePoints(1,2,e):this.comparePoints(0,1,e)}get leftPoint(){return this.getPoint(!0)}get rightPoint(){return this.getPoint(!1)}get pricesOnScale(){return this.traits[z.AT_PRICES_ON_SCALE]}formatLevelPrice(e,t){let n=this.levelsKind===z.AT_LEVELS_PERCENTS,r=``;if(this.showLevels&&(r=n?`${(e*100).toFixed(1)}%`:e.toString()),this.showPrices){let e=this.priceMap(this.axis.toPrice(t));r=(r+` (${s_(this.axis,e)})`).trim()}return r}getAdornPointAndAlign(e,t){let n=this.labels,r=e instanceof pD,i=(e,t,n)=>({pt:e,align:t,offset:n});switch(n){case z.AT_LABELS_LEFT:return i(r?e.anchor1:e,T.Right,-t);default:case z.AT_LABELS_RIGHT:return i(r?e.anchor2:e,T.Left,t);case z.AT_LABELS_CENTER:return i(r?ga(e.anchor1,e.anchor2):e,T.Center,0)}}getColoredElements(e){let t=this.singleStyle;return this.factors.map(n=>{let r=e(n);return r===null?null:(t||(r.style=ko(this.getTraitsFor(n))),r._data={factor:n.value},r)}).filter(e=>e!==null)}hitTestAdornments(e,t){let n=this.showLevels,r=this.getTextRef();if(!n||r===null)return!1;let i=this.axis.pane.presenter,a=i.view?.mainContext;if(!a)return!1;let o=null,s=!1;a.save();let{chart:{fontFamily:c},yAxis:{fontSize:l}}=i.display;a.font=`${l??12}px ${c}`;for(let n of e){if(!P(n._data))continue;let{factor:e}=n._data,{ref:i,spacing:c,offsetY:l,text:u}=r(o,n,e),{pt:d,align:f,offset:p}=this.getAdornPointAndAlign(i,c);if(qa(a,u,this.getAdornTextPoint(a,l,d,p),f).contains(t)){s=!0;break}o=n}return a.restore(),s}adornElementsForColoredFactors(e,t,n,r){let i=this.singleStyle,a=this.showBackground,o=this.showLevels,s=this.applyBackgroundOpacity(this.traits.line.color),c=r.fillStyle,l=null;e.forEach(e=>{if(!P(e._data))return;let{factor:u}=e._data;if(a){let n=t(l,e);r.fillStyle=i?s:e.style.fillStyle,r.fill(n)}if(o){let{ref:t,spacing:a,offsetY:o,text:s}=n(l,e,u),{pt:d,align:f,offset:p}=this.getAdornPointAndAlign(t,a);Ja(r,s,this.getAdornTextPoint(r,o,d,p),f,i?c:e.style.strokeStyle)}l=e})}getAdornTextPoint(e,t,n,r){let i=Wa(e,.75);return ba(n,{x:r,y:t===!0?i/2:t})}},_D=class extends hD{lines;constructor(e,t){super(e,t),this.resetComputedState()}get rectStyle(){return this.fillOnlyStyle(z.AT_FILL)}get rect(){let[e,t,,]=this.getScreenPoints(),n=new mD({x:e.x,y:Math.min(e.y,t.y)},t.x-e.x,Math.abs(e.y-t.y),this.axis);return n.style=this.rectStyle,n}get reverse(){return!1}getLinesDataAtLevels(e,t){let[n,r]=this.points;if(this.reverse&&([n,r]=[r,n]),this.lines==null){let i=(e,t=!1)=>n=>({level:n.value,domain:e(n.value),traits:this.getTraitsFor(n),isPrice:t}),a=r.price-n.price,o=i(e=>n.price+e*a,!0),s=e?.map(o)??[],c=this.axis.pane.presenter.timeline,l=Te(c,+n.time,Number,h_),u=Te(c,+r.time,Number,h_)-l,d=i(e=>+c.at(l+Math.floor(e*u)));this.lines={prices:s,times:t?.map(d)||[],barsDiff:u,priceDiff:a}}return this.lines}makeColoredLine(e,t,n){let r=this.makeLine(e,t);return this.singleStyle||(r.style=ko(n.traits)),r._data={level:n.level,isPrice:n.isPrice},r}getLineElements(e){let[t,n]=this.getScreenPoints();return{priceLines:e.prices.map(e=>{let r=this.axis.toY(e.domain);return this.makeColoredLine({x:t.x,y:r},{x:n.x,y:r},e)}),timeLines:e.times.map(e=>{let r=this.presenter.view.toX(e.domain);return this.makeColoredLine({x:r,y:t.y},{x:r,y:n.y},e)})}}getStyleForElement(e,t){return e.style||super.getStyleForElement(e,t)}resetComputedState(){}wasModifiedByTool(){this.resetComputedState()}wasPointMovedByTool(e,t){this.wasModifiedByTool()}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}},vD=class extends sD{constructor(e,t,n){super(e),this.priceRef=t,this.timeRef=n,this.passive=!0}get price(){return this.priceRef.price}get time(){return this.timeRef.time}set price(e){this.priceRef.price=e}set time(e){this.timeRef.time=e}},yD=class{constructor(e){this.points=e}get left(){return Math.min(this.points[0].point.x,this.points[1].point.x)}get top(){return Math.min(this.points[0].point.y,this.points[1].point.y)}get width(){return Math.abs(this.points[1].point.x-this.points[0].point.x)}get height(){return Math.abs(this.points[1].point.y-this.points[0].point.y)}getRect(){return P(this.points[0].point,this.points[1].point)?new za(this.left,this.top,this.width,this.height):null}};function bD(e){let t=new sD(e),n=new sD(e);return[t,n,new vD(e,t,n),new vD(e,n,t)]}var xD=class extends dD{helper;constructor(e,t){super(e,t),this.points=bD(e),this.helper=new yD(this.points)}get left(){return this.helper.left}get top(){return this.helper.top}get width(){return this.helper.width}get height(){return this.helper.height}getRect(){return this.helper.getRect()}draw(e,t){return this.prepareDraw(e,t)?(Oo(e,this.style),!0):!1}updatePoints(e){this.allowPricesChangeUI&&e.length===2&&e.forEach((e,t)=>this.points[t].update(e.price,e.time))}},SD=class{helper;_actualWidth=0;_fontSizeForWidth=0;constructor(e,t,n){this.points=e,this.lines=t,this.axis=n,this.helper=new yD(this.points)}hitTest(e){let t=this.getRect();return N(t)?(t.width=this._actualWidth,t.contains(e)):!1}getRect(){return this.helper.getRect()}get fontSize(){if(this.lines.length===0)return 0;let{height:e}=this.getRect();return Math.floor(e/this.lines.length)}computeActualWidth(e){(this._actualWidth<=0||this._fontSizeForWidth!==this.fontSize)&&(this._actualWidth=Math.max(...this.lines.map(t=>e.measureText(t).width)),this._fontSizeForWidth=this.fontSize)}draw(e){if(this.lines.length===0)return;e.save();let{x:t,y:n}=this.getRect(),{chart:{fontFamily:r}}=this.axis.pane.presenter.display,i=this.fontSize;e.textAlign=`left`,e.textBaseline=`top`,e.font=`${i}px ${r}`,this.lines.forEach((r,a)=>{let o=n+i*a;e.fillText(r,t,o)}),this.computeActualWidth(e),e.restore()}},CD=class extends hD{textEditable;_textAnnElement;constructor(e,t){super(e,t),this.textEditable=!0,this.points=bD(e),this.adjustFill=!0}get textLines(){return this.traits[z.AT_TEXT_LINES]}set textLines(e){this.traits[z.AT_TEXT_LINES]=e,this._textAnnElement=void 0}get textElement(){return!P(this._textAnnElement)&&this.visible&&(this._textAnnElement=new SD(this.points,this.textLines,this.axis)),this._textAnnElement}updateFrom(e,t,n,r,i){super.updateFrom(e,t,n,r,i),this._textAnnElement=void 0}getElements(){return this.visible?[this.textElement]:[]}},wD=class extends CD{constructor(e,t){super(e,t),this.textEditable=!1}canMove(e){return this.visible?this.textElement.hitTest(e):!1}get prices(){return this.traits.prices}get pricesPoints(){let e=this.points[0].time;return this.prices.map(t=>new sD(this.axis,t,e))}updateFrom(e,t,n,r,i){super.updateFrom(e,t,n,r,i),P(e?.textLines)&&(this.textLines=e.textLines)}getElements(){let e=super.getElements(),t=this.pricesPoints.map(e=>new oD(e.point,!1,this.axis));return e.concat(t)}getPriceScaleAdornments(){if(!this.showPrices)return super.getPriceScaleAdornments();let e=this.traits.line;return this.prices.map(t=>({price:t,color:e.color}))}get defaultFont(){let{chart:{fontSize:e,fontFamily:t}}=this.axis.pane.presenter.display;return[e??13,t]}updateOtherPoints(e){let[t,n]=this.defaultFont;e.save(),e.font=`${t}px ${n}`;let r=Math.max(...this.textLines.map(t=>e.measureText(t).width)),{x:i,y:a}=this.points[0].point;this.points[1].updateFromPoint({x:i+r,y:a+this.textLines.length*t}),e.restore()}},TD=class{annotation;constructor(e){this.annId=e}onKeyDown(e){if(this.annId==null)return;let{key:t,code:n,presenter:r}=e;Re(t,n)&&(P(this.annotation)&&(this.annotation.axis.deleteAnnotation(this.annotation,!1),r.view.redraw()),_k(r,{toolChange:O.Cancelled,annId:this.annId}))}},ED=class extends TD{dragged=!1;snapToSupported=!0;isDrawingAnnotation=!0;forceAlignPoints=!1;indices;alignPointsMode=!1;constructor(e,t=!1){super(e.annName),this.factory=e,this.thirdPoint=t,this.indices=t?[0,1,2]:[0,1]}signalChange(){this.annotation.wasModifiedByTool(),this.annotation.requestRedraw()}onMouseDown(e){let{point:t,button:n}=e;if(t===void 0)return;let r=N(this.annotation);if(n===E.Left)if(r){let e=!this.thirdPoint||this.dragged?1:2;this.annotation.points[e].update(t.price,t.time),this.dragged=!1,this.signalChange(),(!this.thirdPoint||e===2)&&this.finish()}else this.dragged=!0,t.axis.pane.presenter.clearSelection(),this.annotation=this.factory(t.axis),this.annotation.drawn=!1,this.indices.forEach(e=>this.annotation.points[e].update(t.price,t.time)),this.signalChange();return!0}onMouseMove(e){let{point:t,view:n,offset:r}=e;return n.drawCrosshair({ap:t,offset:r}),P(this.annotation,t)&&(this.alignPointsMode=this.forceAlignPoints||e.getModifier(D.Shift),this.dragged?(this.annotation.points[1].update(t.price,t.time),this.signalChange()):this.thirdPoint&&!this.dragged&&(this.annotation.points[2].update(t.price,t.time),this.signalChange())),!0}finish(){vk(this.annotation,!0,O.Created)}isAccidentalMouseUp(e){let{point:t}=e,n=this.annotation.points[0].point;return!t?.point||!n?!1:va(t.point,n)<z.HIT_TEST_TOLERANCE}onMouseUp(e){if(this.annotation===void 0){yk(e);return}if(this.isAccidentalMouseUp(e)){this.dragged=!0;return}this.dragged=!1,this.thirdPoint||this.finish()}},DD=class extends ED{constructor(e,t=!1){super(e,t),this.forceAlignPoints=!0}},OD=class extends ED{constructor(e){super(e,!1),this.snapToSupported=!1}onMouseMove(e){let{point:t,view:n,offset:r}=e;if(n.drawCrosshair({ap:t,offset:r}),P(this.annotation)&&this.dragged){let[e,n]=this.annotation.points;n.update(t.price,t.time);let r=ya(n.point,e.point),i=e.point.y+r.x*Math.sign(r.y)*Math.sign(r.x),a=this.annotation.axis.toPrice(i);n.update(a,t.time),this.signalChange()}return!0}},kD=class extends TD{isNew;anchor;clicks=0;snapToSupported=!1;isDrawingAnnotation;textArea;constructor(e,t){super(e?e.annName:null),this.factory=e,this.existing=t,this.isNew=!P(t),this.isNew||(this.anchor=this.existing.points[0]),this.isDrawingAnnotation=this.isNew}getChartParent(){return this.anchor.axis.pane.presenter.view.canvasContainer}styleProps(){if(this.isNew)return{height:100,fontSize:`100%`,color:cD(Do(this.anchor.axis.pane.presenter.display,`Text`))};{let e=this.existing.textElement;return{height:e.getRect().height*1.05,fontSize:`${Math.round(e.fontSize)}px`,color:this.existing.traits[z.AT_FILL].color}}}onMouseDown(e){let{point:t}=e;if(this.isNew)if(this.clicks===0){if(t===void 0){yk(e);return}t.axis.pane.presenter.clearSelection(),this.anchor=t,this.clicks++,this.startEditing()}else this.onEndEditing();else this.onEndEditing()}startEditing(){this.textArea=document.createElement(`textarea`);let{x:e,y:t}=this.anchor.point,n=this.anchor.axis.pane.getBounds(),r=n.x+n.width-this.anchor.point.x,{height:i,fontSize:a,color:o}=this.styleProps();Si(this.textArea,{position:`absolute`,top:`${t}px`,left:`${e}px`,border:`none`,outline:`none`,overflow:`hidden`,height:`${i}px`,width:`${r}px`,resize:`none`,backgroundColor:`rgba(255, 255, 255, 0.05)`,zIndex:`5`,fontSize:a,color:o}),this.getChartParent().appendChild(this.textArea),this.textArea.onblur=this.onEndEditing.bind(this),this.textArea.onkeydown=e=>e.stopImmediatePropagation(),this.isNew||(this.textArea.value=this.existing.textLines.join(`
|
|
33
33
|
`),this.existing.textLines=[``],this.existing.requestRedraw()),setTimeout(()=>this.textArea.focus(),100)}onEndEditing(){let e=this.anchor,t=this.isNew?this.factory(e.axis):this.existing,n=this.textArea.value.split(`
|
|
34
|
-
`);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(),vk(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 AD(e){return $().config.tooltipMovement===e}function jD(){return AD(`Draggable`)}function MD(){return AD(`Auto`)}var ND=z.TOOLTIP_STD_LEGACY_CLASS,PD=z.TOOLTIP_STD_CLASS,FD=z.TOOLTIP_BUBBLE_CLASS;function ID(e,t){let n=e.filter(e=>e.visible),r=n.find(e=>e.isMain)||n[0],i=r?.values.find(e=>[`Close`,`Last`].includes(e.id))?.y??r?.values[0]?.y??t,a=n.map(e=>e.values.filter(e=>e.id!==`Change`&&e.y>0).map(e=>e.y)).flat(),[o,s]=a.length>0?[Math.min(...a),Math.max(...a)]:[i,i];return{plots:n,y:i,yMin:o,yMax:s}}var LD=class{tooltipElem;leftSide;mode;isDrag=!1;canDrag;isToggling;constructor(e){this.view=e,this.tooltipElem=Ei(e.el,`div`),Ci(this.tooltipElem,{id:`${e.presenter.elementId}-global-tooltip`,class:`${PD} ${ND}`}),this.leftSide=!0,Si(this.tooltipElem,{visibility:`hidden`,position:`absolute`,cursor:jD()?`move`:`default`,zIndex:20,top:`${z.TOOLTIP_Y_OFFSET}px`,left:`${z.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===z.TOOLTIP_BUBBLE)this.canDrag=!1,this.tooltipElem.style.transition=`none`,this.tooltipElem.classList.remove(PD,ND),this.tooltipElem.classList.add(FD),Si(this.tooltipElem,{pointerEvents:`none`});else if(e===z.TOOLTIP_STD){this.canDrag=jD(),this.tooltipElem.classList.remove(FD),this.tooltipElem.classList.add(PD,ND);let e=z.TOOLTIP_TOGGLE_SIDE_ANIM_MS;Si(this.tooltipElem,{pointerEvents:`all`,top:`${z.TOOLTIP_Y_OFFSET}px`,left:`${z.TOOLTIP_X_OFFSET}px`,transition:MD()?`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*z.TOOLTIP_BUBBLE_OFFSET,u=t.yMin-o.height-l,d=t.x-s,f=t.yMax+l,p=f+o.height,m=u<0?p<r?f:0:u,h=d,g=e-a;h<i?h=i:h+o.width>g&&(h=g-o.width),c.top=`${m}px`,c.left=`${h}px`}n.style.visibility===`hidden`&&(n.style.visibility=`visible`),Oi(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),bi(this.tooltipElem)}reposition(e,t){Si(this.tooltipElem,{left:`${e}px`,top:`${t}px`})}isAutoMove(){return this.mode===z.TOOLTIP_STD&&MD()}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=z.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()}}repositionAuto(){if(this.isAutoMove()){let e=this.view.presenter.mainPane.getBoundsWithoutScales(),t=this.tooltipElem.offsetY,n=e.x+(this.leftSide?z.TOOLTIP_X_OFFSET:e.width-this.tooltipElem.offsetWidth-z.TOOLTIP_X_OFFSET);this.reposition(n,t)}}toggleSide(){this.isToggling||(this.isToggling=!0,setTimeout(()=>this.isToggling=!1,z.TOOLTIP_TOGGLE_SIDE_ANIM_MS),this.leftSide=!this.leftSide,this.repositionAuto())}};function RD(e){e.showTooltip&&zD(e,{time:z.ZERO_DATE,offset:z.OFFSCREEN_OFFSET,price:0,lastBarRefresh:void 0,justMain:void 0})}function zD(e,{time:t,lastBarRefresh:n,justMain:r,offset:i,price:a}){let o=I_(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()===z.ZERO_DATE.valueOf();switch(s){case z.TOOLTIP_CARDS:r||VD(e,o,m,!y,h&&!y,!1,g,_,v,e.hasLegend?e.view?.legend?.getLegendElem().clientHeight:0);break;case z.TOOLTIP_BUBBLE:if(!y){let t=ID(o.panes.find(e=>{let{top:t,left:n,width:r,height:a}=e.bounds;return new za(n,t,r,a).contains(i)}).plots,i.y),n=`<div class="bubble-box">${x_({...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})}VD(e,o,m,!1,!1,e.hasLegend,g,_,v);break;case z.TOOLTIP_STD:if(!y){let t=x_({...o,hideSymbols:g,revealingClose:_,plots:o.panes.map(e=>e.plots).flat()});e.view.tooltip.show(t)}VD(e,o,m,!1,!1,e.hasLegend,g,_,v);break;case z.TOOLTIP_EXTERNAL:e.notifyHost(G.CH_TOOLTIPCHANGED,o);break;default:I(`Unknown tooltip mode requested: ${s}`,`warn`);break}}function BD(e,t,n,r,i,a){Si(e,{position:`absolute`,display:`flex`,"flex-direction":t,"flex-wrap":`wrap`,left:`${n+z.CARDS_X_OFFSET}px`,top:`${i+z.CARDS_Y_OFFSET}px`,maxWidth:`${a-r-z.CARDS_X_OFFSET*2}px`})}function VD(e,t,n=!1,r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=0){let u=e.view.el,d=S_(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=wi(t,u,`div`);BD(i,n&&v_(e)?`column`:`row`,o,s,c+l,d),Ti(i,{"bcharts-card":!0,"bcharts-card-main":n,"bcharts-card-first":f===0}),i.innerHTML=r}let p=xi(`#right-${t}`,u);P(p)||(p=document.createElement(`div`),p.id=`right-${t}`,u.appendChild(p),Ti(p,`bcharts-card bcharts-card-move`)),Si(p,{position:`absolute`,display:`block`,right:`${s+z.CARDS_X_OFFSET}px`,top:`${c+l+z.CARDS_Y_OFFSET}px`}),p.innerHTML=i})}var HD=null;function UD(){return HD===null&&(HD=$().config.hostingModel===ae[ae.Application]),HD}var WD=class extends nD{presenter;panY;snapToSupported=!1;warmUp=!0;preventDefault=!1;lastOffset;lastPanningExtremes;constructor(e){super(),this.ap=e,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=UD();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=GD(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(){_k(this.presenter)}onMouseLeave(){this.finished()}onMouseUp(){this.finished()}onMouseDblClick({presenter:e,offset:t,originalEvent:n}){Ie()&&rO(e,t,n)}performLongPress(e,t,n){e.enableTooltip(!0),e.resetActiveTool(),e.activeTool.startTouchCrosshairMode(e,t,n)}};function GD(e,t,n,r){let i=(n-t)/e.viewBox.height,[a,o]=r,s=i*(o-a);return[a+s,o+s]}var KD=null;function qD(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)&&(KD={path:new Path2D(i),width:e[2],height:e[3],rect:new za(0,0,0,0),logoClickable:t})}}var JD=5,YD=50;function XD(e,{x:t,y:n,height:r,width:i}){if(!N(KD))return;let{path:a,width:o,height:s,rect:c}=KD,l=i/8,u=Math.min(Math.max(YD,l),o)/o;c.width=o*u,c.height=s*u,c.x=t+JD,c.y=n+r-c.height-JD,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 ZD(){return N(KD)&&KD.logoClickable?KD.rect:null}var QD=class extends xD{constructor(e,t){super(e,t)}hitTest(e){if(!this.visible)return!1;let t=this.getRect();return t===null?!1:t.contains(e)}draw(e,t){return super.draw(e,t)?(Xa(e,this.getRect()),!0):!1}};function $D(e,t){return e<t?[e,t]:[t,e]}var eO={line:{width:1,color:`rgba(127, 127, 127, 0.3)`,dashStyle:`LongDash`},fill:{color:`rgba(127, 127, 127, 0.1)`}},tO=class extends ED{snapToSupported=!1;preventDefault=!1;axis;presenter;constructor(){super(fD(`Rectangle`,QD,null,eO),!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)){_k(this.presenter,{toolChange:O.Executed,annId:`ZoomIn`});let e=this.annotation.points,t=$D(e[0].price,e[1].price),n=$D(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=z.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 nO(e,t){let n=uD(e);n.offset={x:t.x,y:t.y},n.canFlip=e.getFlipAnchorIndices()!==null;let r=e.axis.pane.presenter;r.clearSelection(),r.notifyHost(G.CH_ANNNEEDSCONTEXTMENU,n)}function rO(e,t,n){let r={offset:{x:t.x,y:t.y},chart:e.accessor,originalEvent:n};e.notifyHost(G.CH_CHTNEEDSCONTEXTMENU,r)}function iO(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 aO(e,t){return t.x===e.x||t.x===e.x+e.width||t.y===e.y||t.y===e.y+e.height}function oO(){let e=$().config.touchCrosshairTimeoutMillis;return P(e)&&Number.isFinite(e)?e:z.LONG_PRESS_TIMEOUT_MILLIS}var sO=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(G.CH_ZOOMCHANGED,1e3)}startTouchCrosshairMode(e,t,n){this.touchCrosshairMode=!0,this.showCrosshairAndTooltips(e.view,t,n)}activated(){}deactivated(){}findHit(e){if(!e.point)return[];if(e.axis.pane.axes.some(t=>t.plots.some(t=>t.hitTestCustomEvent(e.point))))return z.EVENT_PIN_HIT;let t=e.presenter.selectedAnnotation,n;t!==void 0&&(n=t.points.find(t=>t.hitTest(e.point)));let r=xe(e.axis.annotations.filter(t=>t.computed?null:t.hitTest(e.point)));return n!==void 0&&r==null&&(r=t),[r,n]}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.viewBox.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?rO(n,t):nO(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<z.DOUBLE_CLICK_DURATION_MILLIS)return this.onMouseDblClick(e),!0;if(!u&&this.isLogoLink(i)&&o.notifyHost(G.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 tO,o.activeTool.onMouseDown(e),!0;let[n,r]=this.findHit(t);if(o.clearSelection(),n!=null&&o.setSelection(n),n==null||n?.locked)return u?(this.hideCrosshairAndTooltips(o.view),n==null?rO(o,i,s):n?.locked&&nO(n,i),!0):this.touchCrosshairMode?!0:(o.activeTool=new WD(t),o.activeTool.startPan(i),UD());let a=r!=null;return u?(nO(n,i),Ie()):a&&!r.movable||!a&&!n.canMove(t.point)?!1:(o.activeTool=a&&n.points.indexOf(r)!==-1?new aD(n,r):new iD(n,t,i),Ie())}else this.canHorizontalZoom(o)&&(this.prevZoomingOffset=i);return!1}onContextMenu(e){return!0}isLogoLink(e){let t=ZD();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);P(n)?t.presenter.view.setCursor(ee.Crosshair):P(e)?e.isSelected?t.presenter.view.setCursor(ee.Move):t.presenter.view.setCursor(ee.Hand):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&&zD(e.presenter,{time:t.time,offset:n,price:t.price,lastBarRefresh:void 0,justMain:void 0})}hideCrosshairAndTooltips(e,t=!1){e.drawCrosshair({ap:void 0}),e.tooltip.hide(),e.presenter.hideCards(t),t&&e.tooltip.mode===`cards`&&!e.presenter?.hasLegend&&RD(e.presenter)}onMouseLeave(e){let{view:t,offset:n}=e;t.presenter.accessor.getPaneBounds()?.every(e=>!e||!e.contains(n)||aO(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=oO();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)){let e=r.selectedAnnotation;e.axis.deleteAnnotation(e),r.onAnnotationModifiedByTool(e,O.Deleted)}if(P(r.selectedAnnotation)&&(Re(t,n)?r.clearSelection():ze(t,n)&&r.selectedAnnotation instanceof CD&&r.selectedAnnotation.textEditable&&(r.activeTool=new kD(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<z.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=iO(t,this.lastScaleResizingOffset,n,r,-r);this.lastScaleResizingOffset=n,t.isCustomDomain=!0,t.yScale.domain(i),e.redraw()}}},cO=class extends TD{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 yk(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),vk(this.annotation,!0,O.Created)):this.annotation.requestRedraw()}applyToPoints(e){this.annotation.points[this.clicks].update(e.price,e.time)}},lO=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(),vk(n,!0,O.None)}},uO=z.MARKER_ARROW_ANGLE*Math.PI/180/2;function dO(e,t){return fO(e.map(e=>e.point),t)}function fO(e,t,n=z.MARKER_ARROW_LENGTH){return new pO(e,t,n)}var pO=class{p1;p2;constructor(e,t,n=z.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 Sa([t,n],e,z.HIT_TEST_TOLERANCE)||Sa([t,r],e,z.HIT_TEST_TOLERANCE)}draw(e){let{anchor:t,p1:n,p2:r}=this.getArrowPoints();Qa(e,t,n),Qa(e,t,r)}getArrowPoints(){let e=xa(this.p1,this.p2),t=this.vertex===`start`?0:Math.PI,n=e-uO+t,r=e+uO+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}}}},mO=class{hitTest(){return!1}draw(){}},hO=class extends hD{constructor(e,t){super(e,t),this.addPoints(2),this.alignPointsSupported=!0}get extend1(){return this.traits[z.AT_EXTEND_PT_1]}get extend2(){return this.traits[z.AT_EXTEND_PT_2]}get showPercentDiff(){return this.traits[z.AT_SHOW_PERCENTDIFF]}get showBarCount(){return this.traits[z.AT_SHOW_BARCOUNT]}get showRatio(){return this.traits[z.AT_RATIO]}getElements(){let e=this.points[0].point,t=this.points[1].point,n=new pD(e,t,this.extend1,this.extend2,this.axis),r=[];return this.extend1&&r.push(new pD(n.p1,e,!0,!1,this.axis)),r.push(new pD(e,t,!1,!1,this.axis)),this.extend2&&r.push(new pD(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 s_(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=ba(ga(n.point,r.point),i);Ja(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!==``&&Ja(t,o,ba(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!==``&&Ja(t,c,ba(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`?dO(this.points,e):(I(`There is no marker of ${n} kind`,`warn`),new mO))}},gO=class extends hD{constructor(e,t){super(e,t),this.addPoints(1)}get showTimestamps(){return this.traits[z.AT_SHOW_TIMESTAMPS]}getElements(){return[new oD(this.points[0].point,!0,this.axis)]}getTimeScaleAdornments(){return this.showTimestamps?[{time:this.points[0].time,color:this.traits.line.color}]:super.getTimeScaleAdornments()}},_O=class extends hD{constructor(e,t){super(e,t),this.addPoints(1)}getElements(){return[new oD(this.points[0].point,!1,this.axis)]}getPriceScaleAdornments(){return this.showPrices?[{price:this.points[0].price,color:this.traits.line.color}]:super.getPriceScaleAdornments()}},vO=class extends hD{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(ga(e.point,t.point)),t]:z.EMPTY_ARRAY}line2(){return this.traits[z.AT_LINE_2]}use52WeekPrices(){return this.traits[z.AT_USE_52WEEK_PRICES]}getElements(){let e=this.allPoints();return e===z.EMPTY_ARRAY?z.EMPTY_ARRAY:e.map(e=>new pD({x:-z.OUT_OF_SCREEN,y:e.point.y},{x:z.OUT_OF_SCREEN,y:e.point.y},!1,!1,this.axis))}wasPointMovedByTool(e,t){P(this.use52WeekPrices())&&(this.traits[z.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,ko(r)}getPriceScaleAdornments(){let e=this.allPoints();if(!this.showPrices||e===z.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}},yO=5,bO=class extends gD{helper;constructor(e,t,n){super(e,t),this.addPoints(n),this.helper=new sD(e)}get showTrendLine(){return this.traits[z.AT_SHOW_TRENDLINE]}get hasAllPoints(){return P(...this.points.map(e=>e.point))}get line2(){return this.traits[z.AT_LINE_2]}get extendLeft(){return this.traits[z.AT_EXTEND_LEFT]}get extendRight(){return this.traits[z.AT_EXTEND_RIGHT]}get reverse(){return this.traits[z.AT_REVERSE]}get levelsRespectLogScale(){return this.traits[z.AT_LEVELS_RESPECT_LOG_SCALE]}getStyleForElement(e,t){if(e.isTrend){let e=F(this.traits);return e.line=this.line2,ko(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 pD(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 z.AT_LABELS_LEFT:return this.extendLeft?r({x:i.x,y:e.anchor1.y},T.Left,t):super.getAdornPointAndAlign(e,t);default:case z.AT_LABELS_RIGHT:return this.extendRight?r({x:i.x+i.width,y:e.anchor2.y},T.Right,-t):super.getAdornPointAndAlign(e,t);case z.AT_LABELS_CENTER:return super.getAdornPointAndAlign(e,t)}}getTextRef(){return(e,t,n)=>{let r=this.formatLevelPrice(n,t.anchor1.y);return{ref:t,spacing:yO,offsetY:-yO,text:r}}}adornElements(e,t){this.adornElementsForColoredFactors(e,(e,t)=>{let n=new Path2D;return e===null?n:(Va(n,e.p1),n.lineTo(t.p2.x,e.p1.y),Ha(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}})}},xO=class extends bO{constructor(e,t){super(e,t,2)}},SO=class extends bO{constructor(e,t){super(e,t,3)}},CO=5,wO=(e,t)=>{let n=new Path2D;return e===null?n:(Va(n,e.p1),Ha(n,e.p2),Ha(n,t.p2),n)},TO=class extends gD{constructor(e,t){super(e,t),this.addPoints(2)}get reverse(){return this.traits[z.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 pD(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 pD({x:r.x,y:c},{x:i.x,y:c},!1,!1,this.axis),spacing:CO,offsetY:!0,text:s.toString()}}}adornElements(e,t){this.adornElementsForColoredFactors(e,wO,this.getTextRef(),t)}},EO=class extends TO{constructor(e,t){super(e,t)}};function DO(e,t,n){return new kO(e,t,va(e,t),0,Math.PI,null,n)}function OO(e,t,n,r,i,a){return new kO(e,null,t,n,r,i,a)}var kO=class{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(va(this.left,e),va(this.right,e));else{let{x:n,y:r}=ya(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<=z.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),Za(e,this.center,this.radius,this.startAngle,this.endAngle,this.isAntiClockwise??!1),e.restore()}},AO=(e,t)=>{let n=new Path2D,{center:r}=t;if(Va(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 Va(i,a),i.arc(a.x,a.y,e.radius,e.endAngle,e.startAngle,!e.isAntiClockwise),n.addPath(i),n},jO=class extends gD{constructor(e,t){super(e,t),this.addPoints(2)}getElements(){let[e,t]=this.getScreenPoints();if(!P(e,t))return[];let n=va(e,t),r=ya(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 DO(e,{x:e.x+s,y:e.y+o},this.axis)});if(this.showTrendLine){let n=new pD(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,AO,this.getTextRef(),t)}},MO=class extends jO{constructor(e,t){super(e,t)}getStyleForElement(e,t){if(e.isTrend){let e=F(this.traits);return e.line=this.line2,ko(e)}return super.getStyleForElement(e,t)}get showTrendLine(){return this.traits[z.AT_SHOW_TRENDLINE]}get line2(){return this.traits[z.AT_LINE_2]}},NO=class extends gD{constructor(e,t){super(e,t),this.addPoints(2)}get factorsPropName(){return z.AT_ANGLES}getElements(){let[e,t]=this.getScreenPoints(),{x:n,y:r}=ya(t,e);return this.getColoredElements(({value:i})=>{let a=(t,n)=>new pD(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,wO,this.getTextRef(),t)}},PO=class extends TO{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 pD(e,t,!1,!1,this.axis)].concat(super.getElements())}},FO=class extends jO{constructor(e,t){super(e,t),this._factors=[{shown:!0,value:1/3},{shown:!0,value:2/3}]}},IO=class extends hD{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 pD(t,{x:t.x+r,y:t.y+i},!1,!0,this.axis)),a.push(new pD(e,{x:e.x+r,y:e.y+i},!1,!0,this.axis)),a.push(new pD(n,{x:n.x+r,y:n.y+i},!1,!0,this.axis)),a.push(new pD(t,n,!1,!1,this.axis)),a}},LO=class extends xD{constructor(e,t){super(e,t)}getEllipse(){let e=this.getRect();return e===null?null:new Ba(e.centerX,e.centerY,e.width/2,e.height/2)}hitTest(e){if(!this.visible)return!1;let t=this.getEllipse();return t===null?!1:t.contains(e)}draw(e,t){return super.draw(e,t)?(Ya(e,this.getEllipse()),!0):!1}},RO=class extends hD{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[z.AT_EXTEND_PT_1]}get extend2(){return this.traits[z.AT_EXTEND_PT_2]}getLastPoint(){let[e,t,n]=this.points;var r=va(e.point,t.point),i=xa(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 pD(e.point,t.point,this.extend1,this.extend2,this.axis)),P(n?.price)){var i=this.getLastPoint();r.push(new pD(n.point,i,this.extend1,this.extend2,this.axis))}return r}},zO=class extends xD{constructor(e,t,n){super(e,t),this.kind=n,this.adjustFill=!0}hitTest(e){if(!this.visible)return!1;let t=this.getRect();return t===null?!1:t.contains(e)}get dimension(){let e=this.kind===`fish_hook`?2:1;return z.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=Te(t,r,Number,h_);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=ba(this.points[0].point,{x:0,y:-e/2}),s=ba(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),no(e,this.kind,n),!0}},BO=class extends gD{helper;constructor(e,t){super(e,t),this.addPoints(2),this.helper=new sD(e)}getElements(){let e=this.axis.pane.presenter.timeline,{price:t,time:n}=this.points[0],r=Te(e,n,Number,h_),i=Te(e,this.points[1].time,Number,h_),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 oD(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)]}},VO=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(G.CH_ANNPOINTPICKED,r),_k(n,void 0)}},HO={Open:`Open`,Closed:`Closed`},UO=class extends hD{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 ia(2)}data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}get presenter(){return this.axis.pane.presenter}getDataWindow(e,t,n=!0,r=!0){let i=this.data(W.DateTime),a=Te(i,+e,Number),o=Te(i,+t,Number),s={refIndex:-1,highestIndex:-1,lowestIndex:-1,highest:null,lowest:null,data:[]},[c,l,u]=[W.High,W.Low,W.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)?HO.Closed:HO.Open,s.special=s.highestIndex===-1&&s.lowestIndex===-1||s.highestIndex===s.lowestIndex;let e=xe(s.data);if(s.toPrice=e.close,s.toTime=e.time,s.state===HO.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)}s.pAndL=Xe(this.isLong?s.toPrice-this.entryPrice:this.entryPrice-s.toPrice,2)}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=Te(e,+this.points[0].time,Number,h_);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[z.AT_ACCOUNT_SIZE]}get risk(){let e=this.traits[z.AT_RISK_IS_PERCENT],t=this.traits[z.AT_RISK];return Xe(e?t/100*this.accountSize:t,2)}get pointValue(){return this._metaData||=this.presenter.mainPlot.metaData,this._metaData.pointValue}formatDollarValue(e){return Number.isFinite(e)?`${e<0?`-`:``}$${this.twoDecMeta.format(Math.abs(e))}`:z.NOT_APPLICABLE}get qty(){return Math.floor(this.risk/(this.isLong?this.entryPrice-this.lowerPrice:this.upperPrice-this.entryPrice))}get upperDiff(){return Xe(this.upperPrice-this.entryPrice,2)}get amountMultiplier(){return this.isLong?1:-1}get upperAmount(){return Xe(this.accountSize+this.amountMultiplier*this.qty*this.upperDiff,2)}get upperPandL(){return Xe(this.amountMultiplier*this.upperDiff*this.pointValue,2)}get isCompact(){return this.traits[z.AT_COMPACT]}get upper(){let e=s_(this.axis,this.priceMap(this.upperPrice)),t=`(${Xe(this.upperDiff/this.entryPrice*100,2).toFixed(2)}%)`;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 Xe(this.entryPrice-this.lowerPrice,2)}get lowerAmount(){return Xe(this.accountSize-this.amountMultiplier*this.qty*this.lowerDiff,2)}get lowerPandL(){return Xe(-this.amountMultiplier*this.lowerDiff*this.pointValue,2)}get lower(){let e=s_(this.axis,this.priceMap(this.lowerPrice)),t=`(${Xe(this.lowerDiff/this.entryPrice*100,2).toFixed(2)}%)`;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 Xe(this.isLong?this.upperDiff/this.lowerDiff:this.lowerDiff/this.upperDiff,2)}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(z.AT_FILL2)}get upperStyle(){return this.fillOnlyStyle(z.AT_FILL)}get textStyle(){return this.fillOnlyStyle(z.AT_FILL_TEXT)}get secondaryLineStyle(){return ko({line:{color:this.traits.line.color,dashStyle:`ShortDash`},fill:{color:z.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(){let e=this.dataWindow;return this.isLong?e.pAndL>0:e.pAndL<=0}getStyleForElement(e,t){return e.style||this.defaultStyle}getElements(){let e=new pD(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 mD(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 mD(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 sD(this.axis,this.entryPrice,e.time),n=new sD(this.axis,s.toPrice,s.toTime),r=new pD(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 mD({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.visible)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=>wa(this.traits[e].color);return[{price:this.upperPrice,color:e(z.AT_FILL)},{price:this.entryPrice,color:e(z.AT_LINE)},{price:this.lowerPrice,color:e(z.AT_FILL2)}]}adornElements(e,t){let[n,r,i]=e;if(this.showTextAdornments){let[e,a]=[!0,!1].map(e=>Ga(t,e)),{x:o,y:s,width:c}=r.rect,l={x:o+c/2,y:s+e},u=this.textStyle.fillStyle;Ja(t,this.upperText,l,T.Center,u,wa(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)};Ja(t,this.lowerText,h,T.Center,u,wa(this.lowerStyle.fillStyle));let{p1:g,p2:_}=n,{x:v,y}=g,{x:b}=_,x=this.state||z.NOT_APPLICABLE,S=this.isCompact?`${this.formatDollarValue(this.pAndLValue)}`:`${x} P&L: ${this.formatDollarValue(this.pAndLValue)}, Qty: ${this.qty}`,C=this.isCompact?`${this.riskReward.toFixed(2)}`:`Risk/Reward Ratio: ${this.riskReward.toFixed(2)}`,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=wa(this.isUpperPerPAndL?this.upperStyle.fillStyle:this.lowerStyle.fillStyle);Ja(t,[S,C],D,T.Center,u,te)}}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}},WO=class extends _D{markers;display=null;constructor(e,t){super(e,t),this.points=bD(e),this.points[2].visible=!1,this.points[3].visible=!1,this.markers=[new mO]}isPointDrawn(e){return super.isPointDrawn(e)?e.visible:!1}makeLineArrow(e,t,n,r){let i=[ga(e,t),ga(n,r)];return[this.makeLine(i[0],i[1]),fO(i,`end`,10)]}get rectColor(){return this.traits[z.AT_FILL].color}get textColor(){return this.traits[z.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?`${sn(t,e)}d`:br(Tr({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=Ga(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){Ja(t,this.text,this.getTextCoord(e[0],t),T.Center,this.textColor,wa(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,W.Volume)}`];let n=Math.min(+e,+t),r=Math.max(+e,+t),i=this.data(W.DateTime);if(!i||i.length===0)return[`0 bars, `,`Vol ${this.formatter.format(0,W.Volume)}`];let a=Te(i,+n,Number),o=Te(i,+r,Number),s=this.data(W.Volume);if(!Array.isArray(s))return[`0 bars, `,`Vol ${this.formatter.format(0,W.Volume)}`];let c=pe(s.slice(a,o+1)),l=this.formatter.format(c,W.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,W.Close)} (${this.formatter.format(r,W.PercentChange)})`]}resetComputedState(){this.display=null}getFlipAnchorIndices(){return[0,1]}},GO=class extends WO{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()}},KO=class extends WO{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()}},qO=class extends WO{get drawBorder(){return this.traits[z.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())}},JO=class extends _D{constructor(e,t){super(e,t),this.points=bD(e)}get priceLevels(){return So(this.traits[z.AT_PRICE_LEVELS])}get timeLevels(){return So(this.traits[z.AT_TIME_LEVELS])}get showAngles(){return this.traits[z.AT_SHOW_ANGLES]}get reverse(){return this.traits[z.AT_REVERSE]}get showLeftLabels(){return this.traits[z.AT_SHOW_LEFT_LABELS]}get showRightLabels(){return this.traits[z.AT_SHOW_RIGHT_LABELS]}get showTopLabels(){return this.traits[z.AT_SHOW_TOP_LABELS]}get showBottomLabels(){return this.traits[z.AT_SHOW_BOTTOM_LABELS]}getAngles(e,t){let n=this.getScreenPoints(),r=this.lineOnlyStyle(z.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=Wa(t,1)/2,o=e=>Number(e.toFixed(4)).toString(),{x:s,y:c}=z.DEFAULT_ADORN_OFFSET,l=(e,n,r,i,a)=>{let s=ba(e,n);Ja(t,o(r),s,i,a)},u=(e,n)=>{let r=new Path2D;Ua(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();Ua(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]}},YO=e=>e.map(e=>({...e,dimensions:e.value.split(`x`).map(Number)})),XO=5,ZO=(e,t)=>Math.abs(e-t)<1e-7,QO=class extends _D{_parsedFans=null;_parsedArcs=null;constructor(e,t){super(e,t),this.points=bD(e),this._parsedFans=this._parsedArcs=null}get levels(){return So(this.traits[z.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/XO))}get showRangesRatio(){return this.traits[z.AT_SHOW_RANGES_RATIO]}get arcs(){return So(this.traits[z.AT_ARCS])}get fans(){return So(this.traits[z.AT_FANS])}get reverse(){return this.traits[z.AT_REVERSE]}get parsedFans(){return this._parsedFans===null&&(this._parsedFans=YO(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*XO*r}:{x:t.x+s/c*XO*i*n,y:t.y})})}get parsedArcs(){return this._parsedArcs===null&&(this._parsedArcs=YO(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)/XO,dy:Math.abs(t.y-e.y)/XO}:null}get priceBarRatio(){return this.traits[z.AT_PRICE_BAR_RATIO]}set priceBarRatio(e){this.traits[z.AT_PRICE_BAR_RATIO]=e}makeStyledLine(e,t,n){let r=this.makeLine(e,t);return this.singleStyle||(r.style=ko(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=ZO(i,a)?null:{x:1,y:a/i},s=this.getClipPath();return this.computedArcs.map(({computed:i,traits:a})=>{let c=OO(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=ko(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 Ua(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=xe(r);n(AO(null,e),e,this.applyBackgroundOpacity(this.traits.line.color))}else{let e=null;r.forEach(t=>{let r=AO(e,t),i=t.style.fillStyle;n(r,t,i),e=t})}t.restore()}if(this.showRangesRatio&&this.unit!==null){let e=xe(this.computedLevels),n=(this.singleStyle?this:e).traits.line.color,[,r,i,a]=this.getReversedScreenPoints(),{x:o,y:s}=z.DEFAULT_ADORN_OFFSET,{flipX:c,signX:l,signY:u}=this.getOrientation(),d=ba(i,{x:-o*l,y:s*u}),{priceDiff:f,barsDiff:p}=this.getLinesDataAtLevels(null,null),m=c?T.Right:T.Left;Ja(t,p.toFixed(0),d,m,n);let h=ba(a,{x:o*2*l,y:-s*u}),g=c?T.Left:T.Right;Ja(t,this.formatter.format(f,W.Close),h,g,n);let _=ba(r,{x:-o*l,y:-s*u});Ja(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,!ZO(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]}},$O=5,ek=(e,t)=>{let n=new Path2D;return e===null?n:(Va(n,e.p1),Ha(n,e.p2),Ha(n,t.p2),Ha(n,t.p1),n)},tk=class extends gD{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[z.AT_EXTEND_PT_1]}get extend2(){return this.traits[z.AT_EXTEND_PT_2]}getElements(){let[e,t,n]=this.getScreenPoints(),{x:r,y:i}=ya(n,e),a=n=>{let[r,i]=[e,t].map(e=>ba(e,n));return new pD(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:$O,offsetY:!0,text:this.formatLevelPrice(n,t.anchor1.y)})}adornElements(e,t){this.adornElementsForColoredFactors(e,ek,this.getTextRef(),t)}},nk=class extends hD{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:this.useChange=(this.presenter.mainPlot?.mainCurve?.attributes)?.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=bs(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 za(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 mD({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 mD({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 pD({x:t,y:a},{x:o,y:a},!1,!1,this.axis))}}),n}get isVisible(){return this.studyPlot.visible&&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(!nn(e)||!nn(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(z.AT_FILL)}get upStyle(){return this.fillOnlyStyle(z.AT_FILL2)}get totalStyle(){return this.fillOnlyStyle(z.AT_FILL3)}get downValueStyle(){return this.fillOnlyStyle(z.AT_FILL4)}get upValueStyle(){return this.fillOnlyStyle(z.AT_FILL5)}get totalValueStyle(){return this.fillOnlyStyle(z.AT_FILL6)}get backgroundStyle(){return this.fillOnlyStyle(z.AT_FILL7)}get lineStyle(){return this.lineOnlyStyle(z.AT_LINE)}getBoxEndFromStart(e){switch(this.periodType){case`VisibleScreen`:default:return null;case`Days`:return Tn(ih(g.Day,this.period)(e),1);case`Bars`:{let t=this.axis.pane.presenter.data.aggregation;return Tn(ih(t.unit,t.size*this.period)(e),1)}}}getData(){let e=this.axis.pane.presenter.data.aggregation;if(e.isTick||e.hasSpec&&!dw(e.spec))return;let[t,n]=this.presenter.view.xAxis.xScale.domain()||[];if(!nn(t)||!nn(n))return;let r=ih(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=Tn(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(W.TradingDay),o=e=>{let t=0,n=i[e],r=a[e];for(let o=e;o<i.length;o++)if(Vt(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=Tn(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=Tn(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 W.UPVOL:return this.totalVolume?null:a.upVolume;case W.DNVOL:return this.totalVolume?null:a.downVolume;case W.TOTVOL:return this.totalVolume?a.totalVolume:null;case W.POC:case W.VAREA:case W.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=>Te(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(W.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(W[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}},rk=[`None`,`Absolute`,`Percent`],ik=`#16A34A`,ak=`#DC2626`;function ok(e){return typeof e==`string`&&rk.includes(e)}var sk=class extends hD{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=ok(t)?t:`None`}formatSegmentValue(e,t){return this.displayMode===`Absolute`?this.formatter.format(t-e,W.Close):this.displayMode===`Percent`?e===0?``:this.formatter.format((t-e)/e,W.PercentChange):``}getElements(){if(this.visibleLabelSegments=[],!this.studyPlot.visible||!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(Ga(t,!0));this.visibleLabelSegments.forEach(e=>{let r=this.formatSegmentValue(e.fromPrice,e.toPrice);if(r===``)return;let i=e.toPrice>=e.fromPrice;Ja(t,r,{x:e.toPoint.x,y:e.toPoint.y+(i?-n:n)},T.Right,i?ik:ak)})}},ck=[z.AT_LINE,z.AT_LINE_2,z.AT_LINE_3],lk=class extends hD{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?.visible)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 pD({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=ck[e._data?.lineIndex??t],r=this.traits[n];return r?ko({line:r,fill:{color:z.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?.[z.AT_LINE]?.color,this.traits?.[z.AT_LINE_2]?.color,this.traits?.[z.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(ek(e,n))};this.isCurveVisible(3)&&o(r,i,this.traits?.[z.AT_FILL]?.color),this.isCurveVisible(4)&&o(i,a,this.traits?.[z.AT_FILL2]?.color)}};function uk(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 dk=class extends hD{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(z.AT_LINE),t=this.lineOnlyStyle(z.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 sD(this.axis,this.targetPrice,this.targetDate)],this.pricesCount>1&&this.points.push(new sD(this.axis,this.targetPrice2,this.targetDate)),this.unitsPerYear=AE(this.presenter.data.aggregation),this.anchorPrice=this.mainCont.getLastDataPoint(W.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=uk(t(this.targetPrice));if(this.pricesCount>1){let e=uk(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.mainCurve.visible)return[];let e=[];return e.push(new oD(this.points[0].point,!0,this.axis)),e.push(new oD(this.points[0].point,!1,this.axis)),this.pricesCount>1&&e.push(new oD(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(Ga(t,e))),r=this.pricesCount>1,i=this.points[0].point,a=r?this.points[1].point:i,o=this.traits.line2.color,s=Pa(o),c=Wa(t),l=[`Above`,`Below`,`Between`],u=(e,t)=>`${Xe(e*100,2).toFixed(2)}% Probability ${l[t]}`,d=(e,n)=>Ja(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})}}},fk=new sO,pk=e=>Q(cO,zO,1,e),mk=e=>Q(cO,wD,1,e),hk={Default:()=>function(){return fk},Line:()=>Q(ED,hO,!1),DateRange:()=>Q(ED,GO,!1),PriceRange:()=>Q(ED,KO,!1),DatePriceRange:()=>Q(ED,qO,!1),GannBox:()=>Q(ED,JO,!1),GannSquare:()=>Q(OD,QO),Ray:()=>Q(ED,hO,!1),GannLine:()=>Q(DD,hO,!1),VerticalLine:()=>Q(cO,gO,1),HorizontalLine:()=>Q(cO,_O,1),LongPosition:()=>Q(cO,UO,1,!0),ShortPosition:()=>Q(cO,UO,1,!1),FiftyPercentLine:function(e,t){return P(e)?Q(lO,vO,e.axis||t.mainAxis,e):Q(cO,vO,2)},FibonacciRetracement:()=>Q(ED,xO,!1),TrendBasedFibExtension:()=>Q(ED,SO,!0),FibonacciFan:()=>Q(ED,EO,!1),FibonacciArcs:()=>Q(ED,MO,!1),FibonacciChannel:()=>Q(ED,tk,!0),GannFan:()=>Q(ED,NO,!1),SpeedResistanceFan:()=>Q(ED,PO,!1),SpeedResistanceArcs:()=>Q(ED,FO,!1),AndrewsPitchfork:()=>Q(cO,IO,3),Rectangle:()=>Q(ED,QD,!1),Ellipse:()=>Q(ED,LO,!1),TrendChannel:()=>Q(ED,RO,!0),SymbolArrowUp:()=>pk(`arrow_up`),SymbolArrowDown:()=>pk(`arrow_down`),SymbolArrowRight:()=>pk(`arrow_right`),SymbolArrowLeft:()=>pk(`arrow_left`),SymbolArrowHorizontal:()=>pk(`arrow_horizontal`),SymbolArrowVertical:()=>pk(`arrow_vertical`),SymbolArcDown:()=>pk(`arc_down`),SymbolArcUp:()=>pk(`arc_up`),SymbolThumbsUp:()=>pk(`thumbs_up`),SymbolThumbsDown:()=>pk(`thumbs_down`),SymbolZero:()=>pk(`zero`),SymbolOne:()=>pk(`one`),SymbolTwo:()=>pk(`two`),SymbolThree:()=>pk(`three`),SymbolFour:()=>pk(`four`),SymbolFive:()=>pk(`five`),SymbolSix:()=>pk(`six`),SymbolSeven:()=>pk(`seven`),SymbolEight:()=>pk(`eight`),SymbolNine:()=>pk(`nine`),SymbolQuestion:()=>pk(`question`),SymbolFishHook:()=>pk(`fish_hook`),SymbolBuy:()=>pk(`buy`),SymbolSell:()=>pk(`sell`),FibonacciTimeZones:()=>Q(ED,BO,!1),Text:()=>Q(kD,CD,null),PickPoint:()=>function(){return new VO},ZoomIn:()=>function(){return new tO},ProfitLoss:mk,RewardRisk:mk,VolumeAtPrice:function(e){return Q(cO,nk,2,e)},ZigZag:function(e){return Q(lO,sk,null,e)},ProbabilityCones:function(e){return Q(cO,dk,2,e)},LinearRegressionChannel:function(e){return Q(lO,lk,null,e)}};function gk(e,t=!1,n=null,r=null,i=null){let a=hk[e];return a=a(r,i),a(e,t,n)}function _k(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 vk(e,t=!0,n=O.None){e.wasModifiedByTool();let r=e.axis,i={axis:r,annotation:e,toolChange:n};_k(r.pane.presenter,t?i:void 0)}function Q(e,t,n,r){return function(i,a,o){let s=fD(i,t,r,o);return s.annName=i,a?s:new e(s,n)}}function yk(e){e.button===E.Right&&_k(e.presenter)}function bk(e,t,n){let r={};r.inputs=dt(e.inputs);let i=r.inputs[z.INPUT_SOURCE],a=N(i)?W[i]:void 0,o=W[e.source];r.source=a??o;let s=e.target!==void 0,c=P(n)?n:e.curves;return r.outFields=Oe(s?[W[e.target]]:c.map(e=>e.fields).flat()),r.target=s?W[e.target]:r.outFields[0],r.aggregation=t,r}function xk(e){return Array.isArray(e.innerSeries)}function Sk(e){return e.query?.symbol===z.PLACEHOLDER_SYMBOL_NAME?!0:xk(e)?e.innerSeries.some(e=>Sk(e)):!1}var Ck=class extends $E{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}fromModel(e){this.model=e,super.fromModel(this.model)}getMetaData(){let e=B(this.model.study),t=e.meta.decimals;this.metaData=t===void 0?this.basePlot.metaData:new ia(t),P(e.meta.range)&&(this.range=e.meta.range)}getDetachedScaleMargins(){return this.model?.study===`VOL`&&this.axis?.pane.isMain?z.VOLUME_DETACHED_SCALE_MARGINS:super.getDetachedScaleMargins()}applySpecifics(e){let t=this.model.study;B(t).meta.shiftable===!0&&this.curves.forEach(t=>{Number.isFinite(e.inputs.Offset)&&(t.shift=e.inputs.Offset)});let n=(e,t,n)=>this.curves[e].zones[t].value=this.model.levels[n].value;switch(t){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`JPI`:case`CTTP`:case`CTTI`:{let t=De(10,e=>(e+1)*.025),n=e=>t.map(t=>Aa(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`:n(0,0,0),n(0,1,2);break;case`STC`:n(0,0,0),n(0,1,1);break;case`RVOL`:case`DPO`:case`COPP`:n(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=gk(`VolumeAtPrice`,!0,{[z.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[z.AT_FILL]:{color:this.curves[0].colors[0]},[z.AT_FILL2]:{color:this.curves[0].colors[1]},[z.AT_FILL3]:{color:this.curves[0].colors[2]},[z.AT_FILL4]:{color:n.colors[0]},[z.AT_FILL5]:{color:n.colors[1]},[z.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=gk(`VolumeAtPrice`,!0,{[z.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[z.AT_FILL]:{color:this.curves[0].colors[0]},[z.AT_FILL2]:{color:this.curves[0].colors[1]},[z.AT_FILL3]:{color:this.curves[0].colors[2]},[z.AT_FILL4]:{color:n.colors[0]},[z.AT_FILL5]:{color:n.colors[1]},[z.AT_FILL6]:{color:n.colors[2]},[z.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=gk(`ZigZag`,!0,{[z.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=gk(`LinearRegressionChannel`,!0,{[z.AT_LINE]:{color:e.colors[0],width:e.lineWidth,dashStyle:e.dashStyle??`Solid`},[z.AT_LINE_2]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle??`Solid`},[z.AT_LINE_3]:{color:n.colors[0],width:n.lineWidth,dashStyle:n.dashStyle??`Solid`},[z.AT_FILL]:{color:r.colors[0]},[z.AT_FILL2]:{color:i.colors[0]}},this.id)(this.axis,!1);this.annIndex=this.annotations.push(a)-1;break}case`IVRANK`:{let t=W.ImplVolRank1Y;switch(e.inputs.TimeFrame){case`1-Year`:default:break;case`5-Day`:t=W.ImplVolRank5D;break;case`1-Month`:t=W.ImplVolRank1M;break;case`3-Month`:t=W.ImplVolRank3M;break;case`6-Month`:t=W.ImplVolRank6M;break;case`YTD`:t=W.ImplVolRankYTD;break}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case`IVPCTL`:{let t=W.ImplVolPerc1Y;switch(e.inputs.TimeFrame){case`1-Year`:default:break;case`5-Day`:t=W.ImplVolPerc5D;break;case`1-Month`:t=W.ImplVolPerc1M;break;case`3-Month`:t=W.ImplVolPerc3M;break;case`6-Month`:t=W.ImplVolPerc6M;break;case`YTD`:t=W.ImplVolPercYTD;break}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case`OPTIV`:{let t=[W.WeighImplVolHigh,W.WeighImplVol,W.WeighImplVolLow];switch(e.inputs.TimeFrame){case`1-Day`:default:break;case`5-Day`:t=[W.WeighImplVolHigh5D,W.WeighImplVol5D,W.WeighImplVolLow5D];break;case`1-Month`:t=[W.WeighImplVolHigh1M,W.WeighImplVol1M,W.WeighImplVolLow1M];break;case`3-Month`:t=[W.WeighImplVolHigh3M,W.WeighImplVol3M,W.WeighImplVolLow3M];break;case`6-Month`:t=[W.WeighImplVolHigh6M,W.WeighImplVol6M,W.WeighImplVolLow6M];break;case`1-Year`:t=[W.WeighImplVolHigh1Y,W.WeighImplVol1Y,W.WeighImplVolLow1Y];break;case`YTD`:t=[W.WeighImplVolHighYTD,W.WeighImplVolYTD,W.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=gk(`ProbabilityCones`,!0,{[z.AT_LINE]:{color:n.colors[0],width:n.lineWidth,dashStyle:n.dashStyle},[z.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}}getValueAt(e,t,n){return this.isVolAP?this.annotations[this.annIndex].getValueAt(e,t,n):super.getValueAt(e,t,n)}getColorOf(e){if(!this.isVolAP&&!this.isZigZag&&!this.isLinRegChannel)return null;let t=this.curves[0].colors;if(this.isZigZag)return t[0];switch(e){case W.UPVOL:return t[1];case W.DNVOL:return t[0];case W.TOTVOL:return t[2];case W.POC:case W.VAREA:case W.BARBACK:return z.COLOR_TRANSPARENT;case W.LINRUP:return t[0];case W.LINRMID:return this.curves[1].colors[0];case W.LINRLOW:return this.curves[2].colors[0];default:throw Error(`Unexpected Volume At Price field`)}}isEmpty(){return this.isVolAP||this.isZigZag||this.isLinRegChannel?!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}get eventsSeries(){return this.timeSeries}doesSeriesEmitEvents(){let e=this.timeSeries.helpers;return e.includes(W.Buy)||e.includes(W.Sell)}getEventFor(e){switch(e){case W.Buy:return{show:!0,title:`B`,color:`#03c03c`};case W.Sell:return{show:!0,title:`S`,color:`#c23b22`};default:return null}}getEventFields(){return this.hasEvents?[W.Buy,W.Sell]:[]}#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 Ai.call(this,async()=>{this.basePlot=this.#r(),await this.basePlot.initialize(),this.getMetaData();let e=this.axis.pane.presenter.data.aggregation,t=bk(this.model,e,this.curves);if(this.basePlot.isSeasonal){let e=this.basePlot.mainCurve.fields[0];P(e)&&(t.source=e)}this.applySpecifics(t);let n=this.basePlot.timeSeries;n instanceof Pv&&(n=n.actual),this.timeSeries=KT(this.model.study,t,n),this._hasEvents=this.doesSeriesEmitEvents(),this.timeSeries.useNotifications=!0;let r=this.title;return this.timeSeries.ready().then(e=>{let t=this.basePlot.timeSeries instanceof xg||Sk(this.timeSeries);!e&&!this.timeSeries.hasData&&!t&&!this.timeSeries.computedServerSide&&I(`Unable to calculate study values for ${r}`,`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`}invalidateAssociatedAnnotations(e){this.isVolAP&&this.annotations[this.annIndex].invalidate(e)}onPriceDomainsUpdated(){this.invalidateAssociatedAnnotations(`PriceDomainsChanged`)}shouldPriceMap(e){return this.isJpi?this.shouldMaybePriceMap?e.id===W.JPIB.id||e.id===W.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(W.JPIB,t),a=r(W.JPIS,t);if(i===null&&n.id===W.JPIB.id||a===null&&n.id===W.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}},wk=[W.Open,W.High,W.Low,W.Close,W.Volume],Tk=class extends $E{_expression;exprModel=null;symbols=null;errorText;get title(){return this.expression}get expression(){return this._expression}async parseExpression(){let e=Su(this._expression);if(this.exprModel=null,this.symbols=null,xu(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(wk.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 Ev(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=Du(this.exprModel),t=$().getTimeSeriesDataSource();return e.map(e=>{let n=this.makeQuery();return n.symbol=e,t.getTimeSeries(n)})}getRecord(){P(this.errorText)||(this.record=new rf(this.metaData.inner.map(e=>[e.symbol,e.resolved]),F(this.exprModel)),this.record.ready().then(e=>e))}getMetaData(){this.isValid&&(this.metaData=new oa(this.symbols),this.metaData.ready().then(e=>{e&&(this.getRecord(),this.presenter?.notifyHost(G.MD_CHANGED,{plot:this}))}))}fromModel(e){super.fromModel(e),this._expression=e.expression}async initialize(){return Ai.call(this,async()=>(await this.parseExpression(),this.isShutDown?!1:(this.getMetaData(),this.getTimeSeries(),!0)))}},Ek=class extends $E{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=Su(this.forward),t=xu(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(nh(this.offset),th(z.FMT_US_DATE_ONLY))(new Date)})`,this.outField=new Ld(`Close_${this.offset}`,v.Number,b.Forward,`Close (${this.offset})`),this.curves[0].fields[0]=this.outField):(this.suffix=``,this.outField=W.Close);let{yes:t,no:n}=A(e.symbols,e=>Yr(`${e}*1`)),r=(await Promise.all(t.map(e=>li(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(){this.isValid&&(this.metaData=new oa(Object.values(this.roots).flat()),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(G.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([[W.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 Dg(this.symbols):void 0;this.timeSeries=new Ev(this.fwdModel,r,this.getForwardPolicy(i)),this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:re.Unspecified};this.presenter?.notifyHost(G.TS_MANYCHANGED,e)}})}async initialize(){return Ai.call(this,async()=>(await this.parseForward(),this.isShutDown?!1:(this.getMetaData(),this.getTimeSeries(),!0)))}},Dk=e=>e.substring(0,e.lastIndexOf(`::`)),Ok=class extends $E{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 Eu(ku(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 Ld(`Close_${t}`,v.Number,b.Seasonal,`Close${this.suffix}`),this.curves[0].fields[0]=this.outField}applyOffset(e,t){return`${this.isPlain?e:hi(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=Su(this.seasonal,!0),t=xu(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=ai(await qr(e));a.set(e,t)}r=ku(r,e=>a.get(e)),i=Array.from(a.values());let o=i.every(e=>Yr(e)||Zr(e)),s=i.every(e=>$r(e)),c=i.every(e=>!Yr(e)&&!$r(e)&&!Zr(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=Ou(r);let{model:l,symbols:u}=Su(this.isAverage?this.constructAverage(r):this.constructSeasonal(r,this.offset),!0);this.seaModel=l,this.hasComputation=Ou(l),this._seasonal=Eu(ku(l,Dk)),this.symbols=u,this.outField.name=this.outField.shortName=this.fixupFieldDescription()}get isValid(){return!P(this.errorText)}getActualSymbols(){return[...new Set(this.symbols.map(Dk))]}fixupFieldDescription(){if(!this.hasComputation&&!this.isAverage){let e=Dk(this.symbols[0]);if(this.isPlain)return`${e} ${new Date().getFullYear()-this.offset}`;if(this.isFutures)return ai(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 oa(e),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(G.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([[W.Close,this.outField]]),noDataApproach:this.getNoDataApproach(),modelTransform:(e,t)=>t.length===0?this.seaModel:Su(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 qt(new Date,-e)}yearFromOffset(e){return wr(this.shiftYears(e))}getCmdtyRange(e){let t=this.shiftYears(e);return[wn(t),Cn(t)]}getSeasonalRange(e,t){let n=P(e[0],e[1]);return this.isPlain&&!n?this.getCmdtyRange(t):this.isFutures?[null,null]:this.isPlain&&t>0&&n?e.map(e=>qt(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=Dk(t),n.offset=this.symbolToOffset[t],n.cacheMe=!this.isPlain||n.offset===0,n.range=this.getSeasonalRange(n.range,n.offset),n.offset>0&&(n.disableStreamingUpdates=!0),e.getTimeSeries(n)});this.timeSeries=new Ev(this.seaModel,t,this.seasonalPolicy),this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:re.Unspecified};this.presenter?.notifyHost(G.TS_MANYCHANGED,e)}})}async initialize(){return Ai.call(this,async()=>(await this.parseSeasonal(),this.isShutDown?!1:(this.getMetaData(),this.getTimeSeries(),!0)))}},kk=[`bottom`,`right`,`left`],Ak={bottom:`center`,right:`start`,left:`end`},jk=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),!kk.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=Ak[this.position],e.strokeStyle=this.strokeColor,e.fillStyle=wa(this.backgroundColor),e.lineWidth=this.lineWidth;let s=[r,i??``].map(t=>e.measureText(t).width),c=Math.max(...s),l=this.position===`bottom`?0:this.arrowLength,u=Math.round(c+l+this.padding+this.padding),d=Math.round(u/2),f=Math.round(a/2);e.setLineDash([]);let p=t;e.beginPath(),e.moveTo(p,n);let m=n+f,h=n+2*f,g=n-f;if(this.position===`right`){e.lineTo(p,m);let t=p+u;o&&(e.lineTo(p,h),e.lineTo(t,h)),e.lineTo(t,m),e.lineTo(t,g),e.lineTo(p,g)}else if(this.position===`left`){e.lineTo(p,m);let t=p-u;o&&(e.lineTo(p,h),e.lineTo(t,h)),e.lineTo(t,m),e.lineTo(t,g),e.lineTo(p,n-f)}else if(this.position===`bottom`){let t=p-d,r=p+d;e.lineTo(p,n),e.lineTo(r,n),e.lineTo(r,n+a),e.lineTo(t,n+a),e.lineTo(t,n),e.lineTo(p,n)}if(e.closePath(),e.stroke(),e.fill(),e.fillStyle=this.textColor,e.textBaseline=`middle`,this.position===`bottom`)e.fillText(r,p,n+Wa(e,1));else if(this.position===`right`){let t=p+this.arrowLength+this.padding;e.fillText(r,t,n),o&&e.fillText(i,t,n+this.padding+f)}else if(this.position===`left`){let t=p-this.arrowLength-this.padding;e.fillText(r,t,n),o&&e.fillText(i,t,n+this.padding+f)}}},Mk=({y:e,halfHeight:t})=>e-t,Nk=({y:e,halfHeight:t})=>e+t;function Pk(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=Mk(e),o=Nk(i);a<o&&(e.y=o+1+e.halfHeight),Nk(e)>t.y+t.height&&(e.y=t.y+t.height-e.halfHeight-1)}})}var Fk=4,Ik=({x:e,halfWidth:t})=>e-t-Fk,Lk=({x:e,halfWidth:t})=>e+t+Fk,Rk=(e,t)=>e-1-t-Fk,zk=(e,t)=>e+1+t+Fk;function Bk(e,t){let n=e.length-1;e.forEach((e,r,i)=>{let a=r===0,o=a?null:i[r-1],s=Ik(e),c=a?t.x:Lk(o);if(e.x-e.halfWidth<t.x&&(e.x=zk(t.x,e.halfWidth)),s<c)e.x=zk(c,e.halfWidth+Fk);else{let t=Lk(e),a=r<n?Ik(i[r+1]):2**53-1;if(t>a){let n=Rk(e.x,t-a),r=Rk(e.x,e.halfWidth-2),i=zk(c,o?.halfWidth??0);e.x=Math.max(r,n,i)}}Lk(e)>t.x+t.width&&(e.x=Rk(t.x+t.width,e.halfWidth))})}var Vk=Array.from([,,,,,,],(e,t)=>++t).reverse();function Hk(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=ve(i,e=>e!==null),r=a===-1?null:i[a]),[r,a]}function Uk(e){let t=e.plot.timeSeries.container;return t===null||t.size<1?null:e.getColor(t.size-1)}function Wk(e){return e.curves.filter(t=>e.visible&&t.visible&&(e.type!==C.Study||t.style!==h.Ribbon)).map(t=>{let n=t.pickMainField(),[r,i]=Hk(e,n);return{value:r,color:Uk(t),field:n,index:i}})}var Gk=class{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;this.config={innerTickSize:7,tickPadding:5,indicatorPadding:4,fontWeight:400,fontSize:n||t||12},this.crosshairIndicator=new jk({fontSize:this.config.fontSize,arrowLength:this.config.innerTickSize})}makePlot(e){let t=null;switch(C[e.type]){case C.Symbol:t=new eD;break;case C.Expression:t=new Tk;break;case C.Study:t=new Ck;break;case C.IncomeStatement:t=new tD(w.IncomeStatement);break;case C.BalanceSheet:t=new tD(w.BalanceSheet);break;case C.Forward:t=new Ek;break;case C.Seasonal:t=new Ok;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,W.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 sD(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,W.Close)}toY(e){let t=this.priceMap(e);return this.yScale.priceToY(t)}get plotAnnotations(){let e=[];return this.plots.forEach(t=>{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=Te(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<=z.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+-xa(e,n)*180/Math.PI)%360,a=45/2,o=i>360-a||i<a||i>180-a&&i<180+a,s=i>90-a&&i<90+a||i>270-a&&i<270+a;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=gk(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 WE(this.scale,this),this.label=e.label,this.plots=[].concat(...e.plots.map(e=>this.expand(e))).map(e=>this.makePlot(e)),this.annotations=(e.annotations||[]).map(e=>this.makeAnnotation(e));let{chart:{fontFamily:t,backgroundColor:n},yAxis:{textColor:r,crosshair:{color:i},primaryOnTheLeft:a}}=this.pane.presenter.display,o=a??!1;this.onTheRight=this.primary&&!o||!this.primary&&o,this.crosshairIndicator.configure({position:this.onTheRight?`right`:`left`,fontFamily:t,strokeColor:i,textColor:r,backgroundColor:Aa(.15)(n)})}findIndex(e){return this.annotations.findIndex(t=>t.uid===e.uid)}addAnnotation(e){let t=this.makeAnnotation(e,!0);this.appendAnnotation(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:z.ANN_DUPLICATE_OFFSET,y:z.ANN_DUPLICATE_OFFSET}),t.appendAnnotation(n),n.requestRedraw(),this.fireAnnotationsChanged()}updateAnnotation(e,t){e.isSelected&&this.pane.presenter.clearSelection(),Lc(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),t.isUndoRedo||this.pane.presenter.undoRedoManager.done(lD(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=>Te(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!==W.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(be(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.visible!==!1).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.visible&&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.visible&&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=vi(this.pane.presenter.hostElement),t=xi(`#${z.HEADER_SIZE_PLACEHOLDER_ID}`,e);if(!P(t)){t=Ei(e,`div`),Si(t,{display:`none`}),Ci(t,{id:z.HEADER_SIZE_PLACEHOLDER_ID,class:`bcharts-card bcharts-card-first`});let{lineHeight:n}=getComputedStyle(t);isNaN(Number.parseFloat(n))&&Si(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)+z.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:z.PANE_CAP_MIN_PADDING_PERCENT,u=s?a:z.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]=z.PANE_TINY_PADDING_PIXELS:e===oe.Min&&(f[1]=z.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=Wa(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=s_(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 z.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(s_(this,t,!0)).width)),{innerTickSize:a,tickPadding:o}=this.config,s=P(this.label)?Wa(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(Ra(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=ka(.4)(r),e.translate(0,0);let t=this.onTheRight?1:-1;e.rotate(t*Math.PI/2),e.textAlign=`center`;let n=Wa(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([]),$a(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.visible&&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=s_(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.visible||!e.hasVisibleCurves||!e.timeSeries||!e.timeSeries.hasData)){if(i===`All`||i===`Main`&&e.main){let t=e.main?1:3;Wk(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,W.PreviousClose,void 0)}}),this.annotations.concat(this.plotAnnotations).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&&Pk(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=Pa(a),f=new jk({position:this.onTheRight?`right`:`left`,fontSize:this.config.fontSize,padding:this.config.indicatorPadding,fontFamily:n,textColor:d,strokeColor:a,backgroundColor:a}),p=i||s_(this,r),m,h=this.comparison===x.Percent;N(o)&&(m=h?o_(this,o):a_(o)),f.draw(e,u,t,p,m)};a?c.forEach(u):Vk.forEach(e=>c.filter(t=>t.priority===e).forEach(u))}};function Kk(e){let t=e.map(e=>e.plots).flat().filter(e=>C[e.type]==C.Symbol).map(e=>e.symbol).map(e=>di(e)).filter(e=>e!==null).map(e=>e.getFullYear());return t.length==0?null:Math.max(...t)}var qk=Symbol.for(`__dloacip__`),Jk=class{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=Kk(e.axes)),this.axes=e.axes.map((e,t)=>{let n=new Gk(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[qk]===!1||XD(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,W.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=Ca(l);e.save(),e.strokeStyle=c,e.lineWidth=u,e.setLineDash(d),eo(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){Ra(e,this.getBoundsWithoutScales())}drawAnnotations(e){e.save();let{chart:{fontFamily:t},yAxis:{fontSize:n}}=this.presenter.display;e.font=`${n??12}px ${t}`;let r=t=>t.draw(e,!0);this.axes.forEach(e=>{e.annotations.forEach(r),e.plotAnnotations.forEach(r)}),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.visible&&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(Ca(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=Ca(a);e.strokeStyle=i,e.setLineDash(o);let s=this.presenter.view.leftOffset,c=this.viewBox.width-this.presenter.view.rightOffset,l=vo();l.prolog(e),eo(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`,Ja(e,$().config.noDataText||z.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.drawTopmost(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 Yk(e,t){return{width:e,spacing:t,get totalWidth(){return this.width+this.spacing},offset:0}}var Xk=class extends IE{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=Yk(rt(n,z.DEFAULT_BAR_WIDTH,`chart`,`bar`,`width`),rt(n,z.DEFAULT_BAR_SPACING,`chart`,`bar`,`spacing`)),this._extent=null,this.wasZoomed=!1,this.fitAllData=!1}extent(e){return FE.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(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=Te(this.timeline,+a,Number,h_)),[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=e-this._range[0]-this.bar.offset,n=Math.floor(t/this.bar.totalWidth),r=this._extent[0]+n;return this.timeline.at(r)}timeToIndex(e){return this.ready?(e=typeof e==`number`?e:+e,Te(this.timeline,e,Number,h_)):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>z.MAXIMUM_BAR_WIDTH||r<z.MINIMUM_BAR_WIDTH)return!1;let a=Yk(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)?Te(this.timeline,e,Number,h_,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(z.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)}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>=z.INTRA_THRESHOLD)for(;i>0&&cn(n,r)<e;)i--,r=this.timeline.at(i);else if(!a.isTick){let t=Math.floor(e/z.ONE_DAY_MILLIS),r=e=>pn(e,zt(e)),a=r(n),o=n;for(;i>0;){let e=this.timeline.at(i),n=en(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,z.MINIMUM_BAR_WIDTH,z.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=z.DEFAULT_BAR_WIDTH,this.bar.spacing=z.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]>=z.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 Zk(e){return{date:e,priority:1,text:i_(e)}}var Qk=class{xScale;ticks;lastUsedOptions;wasPanned;panningXAxisAllowed;config;isVisible;crosshairIndicator;viewBox;overrideTickGetter;overrideFormatter;contractParityCache=null;contractParityCacheKey=null;constructor(e){this.view=e,this.xScale=new Xk(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;this.config={innerTickSize:5,tickPadding:5,indicatorPadding:5,fontWeight:400,fontSize:a||n||12},this.isVisible=i,this.crosshairIndicator=new jk({position:`bottom`,fontSize:this.config.fontSize,fontFamily:e,padding:this.config.indicatorPadding,strokeColor:o,textColor:r,backgroundColor:Aa(.15)(t),arrowLength:this.config.innerTickSize})}setDomain(){this.xScale.adjustDomain();let e=this.view.presenter.display.period===z.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()}}setViewBox(e){this.viewBox=e;let{x:t,width:n}=this.viewBox;this.xScale.range([t,t+n])}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=Wa(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=Vg(e);return t?Zk: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=Bg(),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<=(xe(a)+Se(o))/2){n=t[r[i]];break}}let i=n.Multipliers,a=i.findIndex(t=>e<t),o=a===-1?xe(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}=this.viewBox,{lineWidth:h,color:g,dashStyle:_}=t,v=Ca(_);e.textAlign=`center`,e.font=`${c} ${l}px ${s}`,e.lineWidth=1,e.strokeStyle=g,e.fillStyle=n,e.setLineDash([]),eo(e,p,f,f+m);let y=this.xScale.extent(),b=e=>!P(e)||!P(e[0],e[1]);if(b(y))return;let x=t=>e.measureText(t).width,S=(e,t)=>P(e)?cn(t,e):z.FIFTY_YEARS_MILLIS,C=i>0?i:120,w=this.xScale.domain();if(b(w))return;let T=(w[1].getTime()-w[0].getTime())*C*.6/m,ee=this.normalizeDuration(T),E=this.view.presenter.data.aggregation.isEndOfDay,D=(e,t)=>{if(e.date.valueOf()===z.ZERO_DATE.valueOf())return!0;if(S(e.date,t.date)<r)return!1;let n=t.x-e.x,i=t.date.getTime()-e.date.getTime()>=ee,a=n>C;return!(e.x+e.textWidth/2>=t.x-t.textWidth/2)&&(a||(E?i:!1))},te=f+m,ne=({text:n,x:r,date:i,forced:a})=>{P(i)&&(a||$a(e,r,p,p+u),e.fillText(n,r,p+u+d+l*.71),t.visible&&!a&&(e.save(),e.lineWidth=h,e.setLineDash(v),$a(e,r,0,p),e.restore()))},re={agg:this.view.presenter.data.aggregation,unitWidth:x(`M`),barWidth:this.xScale.bar.width,extent:y,formatString:a,minTickInterval:r||0,duration:T},ie=this.getTicks(re),ae=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>te?te-i:r,e.x=r,e.forced=t!==r}else e.forced=!1},O={date:z.ZERO_DATE,priority:999,x:-999,text:``,index:-1,textWidth:0};ie.forEach(e=>{e.x=this.xScale.indexToX(e.index),e.textWidth=x(e.text),ae(e),D(O,e)?(ne(O),O=e):e.priority<O.priority&&(O=e)}),ne(O),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=Te(s,+a[0],Number),u=Te(s,+a[1],Number,we,l);if(l<u){let t=this.viewBox.y,a=this.view.leftOffset,o=this.viewBox.x+this.viewBox.width;if(r.save(),i){r.fillStyle=e.fillColor;let d=c[l],f=Math.max(a,this.xScale.timeToX(s[l]));for(let e=l+1;e<=u;++e){let a=e<c.length?c[e]:null;if(e===u||n(a,d)){let n=e<s.length?s[e]:null,c=N(n)?this.xScale.timeToX(n):o;c=Math.min(c,o),i(d)%2==0&&r.fillRect(f,0,c-f,t),d=a,f=c}}}let d=vo();d.prolog(r),r.strokeStyle=e.color,r.lineWidth=e.width,r.setLineDash(Ca(e.dashStyle));let f=null;for(let e=l;e<u;++e){let i=c[e];if(n(i,f)){let n=s[e],a=this.xScale.timeToX(n);P(a,f)&&$a(r,a,0,t),f=i}}d.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(W.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=di(e),r=di(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,W.Symbol,a,e,e=>this.contractParityCache.get(e)??0)}}i.enabled&&(n?.data?.aggregation.isIntraday?this.drawTransitionsFor(i,W.TradingDay,a,e,e=>e):n?.data?.aggregation.unit===g.Day?this.drawTransitionsFor(i,null,(e,t)=>!Nr(e,t),e,e=>e.getMonth()):n?.data?.aggregation.unit===g.Week&&this.drawTransitionsFor(i,null,(e,t)=>!Fr(e,t),e,e=>e.getFullYear()))}getAnnXScore(e,t){return[en,jr,Nr,Fr].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 za(0,0,0,0);t.allAnnotations.concat(t.plotAnnotations).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=c_(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&&Bk(i,this.viewBox),i.forEach(t=>{let r=Pa(t.color);new jk({position:`bottom`,fontSize:this.config.fontSize,fontFamily:n,padding:this.config.indicatorPadding,strokeColor:z.COLOR_TRANSPARENT,textColor:r,backgroundColor:t.color,arrowLength:this.config.innerTickSize}).draw(e,t.x,this.viewBox.y+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)&&nn(l)))return!1;if(!i)return!0;t=this.xScale.timeToX(l);let u=Ca(s);e.strokeStyle=o,e.setLineDash(u);let d=vo();if(d.prolog(e),$a(e,d.adjust(t),0,d.adjust(this.viewBox.y)),d.epilog(e),!a||!r.visible)return!0;let f=c_(n,l,P(r.format)?c:void 0);this.crosshairIndicator.draw(e,t,this.viewBox.y+1,f,void 0,this.viewBox.height-2);let{plotHover:p}=n.display.chart;return p&&n.allPlots.filter(e=>e.visible).forEach(n=>n.curves.forEach(n=>n.drawHover(e,l,t))),!0}},$k={mousedown:`onMouseDown`,mousemove:`onMouseMove`,mouseup:`onMouseUp`,dblclick:`onMouseDblClick`,contextmenu:`onContextMenu`,mouseover:`onMouseEnter`,mouseout:`onMouseLeave`,wheel:`onWheel`,touchstart:`onMouseDown`,touchmove:`onMouseMove`,touchend:`onMouseUp`,keydown:`onKeyDown`},eA={Shift:`shiftKey`,Alt:`altKey`,Control:`ctrlKey`,Meta:`metaKey`},tA=e=>e.startsWith(`touch`),nA=class{subscriptions=[];constructor(e){this.view=e}init(e){let t=Ie();Object.keys($k).filter(e=>!tA(e)||t).forEach(t=>{let n=e=>{let n=$k[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[eA[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])}}},rA=Ih.concat(W.PercentChange);function iA(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 aA(e,t){let n=iA(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 oA(e,t){return aA(e,t).flat().filter(t=>t!==e)}var sA=class{id;isOptionsChart=!1;constructor(e){this.view=e,this.id=`bc-legend-${bt()}`}getLegendElem(){let e=this.view.el;return wi(this.id,e,`div`)}update(){let e=this.getLegendElem(),t=R_(this.presenter.mainPane);if(!P(t))return;this.isOptionsChart=this.mainPlot?.title?.startsWith(z.FAKE_SYMBOL_PREFIX)??!1;let{left:n,right:r,top:i,width:a}=t;BD(e,`row`,n,r,i,a),Ti(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(){bi(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=rA.map(t=>e.getValue(t));if(k(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=rA[t],i=this.format(e,r),a=U_(r);return`${this.spanAsName(a)}${this.spanAsValue(i,n)}`}).join(` `)} ${this.spanAsValue(`(${this.format(xe(t),xe(rA))})`,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=F_(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(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 aA(this.mainPlot,e).map((e,t)=>{let n=e.map((e,t)=>{let n=this.getFirstColorBadge(e),r=this.getSeasonalFamilyTitle(e,t===0);return this.spanAsPlot(`${n} ${r}`)}).join(` `);return this.divAsGroup(n,t>0)}).join(` `)}getFirstColorBadge(e){return T_(`rectangle`,e.mainCurve.colors[0])}getLastValues(e){return this.isOptionsChart?``:Wk(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&&this.isOptionsChart}maybeGetAdditionalPlots(){let e=this.presenter.mainPane.axes.map(e=>e.plots).flat(),t=oA(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)?N_(e.uid):``,a=n!==`All`&&!e.isSeasonal?this.getLastValues(e):``;return this.div(`${i} ${t} ${r} ${a}`)}).join(` `):``}},cA=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 sA(this),this.draw=this.draw.bind(this),this.notifyLayoutChanged=qe(G.CH_CHTLAYOUTCHANGED,z.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)),Si(this.el,{flex:1,display:`flex`,position:`relative`,"flex-direction":`column`,"touch-action":`pan-x pan-y`}),this.tooltip=new LD(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=Ei(this.el,`div`),Ci(this.canvasContainer,{class:`chart-canvas-container`}),Si(this.canvasContainer,{flex:1,display:`flex`,"flex-direction":`column`,position:`relative`,height:`100%`}),this.mainCanvas=Ei(this.canvasContainer,`canvas`);let o={height:`${i}px`,width:`${a}px`,"z-index":2,position:`absolute`,top:0,left:0};Si(this.mainCanvas,o),this.mouseCanvas=Ei(this.canvasContainer,`canvas`),Ci(this.mouseCanvas,{tabIndex:0}),o[`z-index`]=3,o.outline=`none`,Si(this.mouseCanvas,o),this.goToLatestButton=Ei(this.el,`button`),Oi(this.goToLatestButton,`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
|
|
34
|
+
`);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(),vk(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 AD(e){return $().config.tooltipMovement===e}function jD(){return AD(`Draggable`)}function MD(){return AD(`Auto`)}var ND=z.TOOLTIP_STD_LEGACY_CLASS,PD=z.TOOLTIP_STD_CLASS,FD=z.TOOLTIP_BUBBLE_CLASS;function ID(e,t){let n=e.filter(e=>e.visible),r=n.find(e=>e.isMain)||n[0],i=r?.values.find(e=>[`Close`,`Last`].includes(e.id))?.y??r?.values[0]?.y??t,a=n.map(e=>e.values.filter(e=>e.id!==`Change`&&e.y>0).map(e=>e.y)).flat(),[o,s]=a.length>0?[Math.min(...a),Math.max(...a)]:[i,i];return{plots:n,y:i,yMin:o,yMax:s}}var LD=class{tooltipElem;leftSide;mode;isDrag=!1;canDrag;isToggling;constructor(e){this.view=e,this.tooltipElem=Ei(e.el,`div`),Ci(this.tooltipElem,{id:`${e.presenter.elementId}-global-tooltip`,class:`${PD} ${ND}`}),this.leftSide=!0,Si(this.tooltipElem,{visibility:`hidden`,position:`absolute`,cursor:jD()?`move`:`default`,zIndex:20,top:`${z.TOOLTIP_Y_OFFSET}px`,left:`${z.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===z.TOOLTIP_BUBBLE)this.canDrag=!1,this.tooltipElem.style.transition=`none`,this.tooltipElem.classList.remove(PD,ND),this.tooltipElem.classList.add(FD),Si(this.tooltipElem,{pointerEvents:`none`});else if(e===z.TOOLTIP_STD){this.canDrag=jD(),this.tooltipElem.classList.remove(FD),this.tooltipElem.classList.add(PD,ND);let e=z.TOOLTIP_TOGGLE_SIDE_ANIM_MS;Si(this.tooltipElem,{pointerEvents:`all`,top:`${z.TOOLTIP_Y_OFFSET}px`,left:`${z.TOOLTIP_X_OFFSET}px`,transition:MD()?`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*z.TOOLTIP_BUBBLE_OFFSET,u=t.yMin-o.height-l,d=t.x-s,f=t.yMax+l,p=f+o.height,m=u<0?p<r?f:0:u,h=d,g=e-a;h<i?h=i:h+o.width>g&&(h=g-o.width),c.top=`${m}px`,c.left=`${h}px`}n.style.visibility===`hidden`&&(n.style.visibility=`visible`),Oi(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),bi(this.tooltipElem)}reposition(e,t){Si(this.tooltipElem,{left:`${e}px`,top:`${t}px`})}isAutoMove(){return this.mode===z.TOOLTIP_STD&&MD()}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=z.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()}}repositionAuto(){if(this.isAutoMove()){let e=this.view.presenter.mainPane.getBoundsWithoutScales(),t=this.tooltipElem.offsetY,n=e.x+(this.leftSide?z.TOOLTIP_X_OFFSET:e.width-this.tooltipElem.offsetWidth-z.TOOLTIP_X_OFFSET);this.reposition(n,t)}}toggleSide(){this.isToggling||(this.isToggling=!0,setTimeout(()=>this.isToggling=!1,z.TOOLTIP_TOGGLE_SIDE_ANIM_MS),this.leftSide=!this.leftSide,this.repositionAuto())}};function RD(e){e.showTooltip&&zD(e,{time:z.ZERO_DATE,offset:z.OFFSCREEN_OFFSET,price:0,lastBarRefresh:void 0,justMain:void 0})}function zD(e,{time:t,lastBarRefresh:n,justMain:r,offset:i,price:a}){let o=I_(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()===z.ZERO_DATE.valueOf();switch(s){case z.TOOLTIP_CARDS:r||VD(e,o,m,!y,h&&!y,!1,g,_,v,e.hasLegend?e.view?.legend?.getLegendElem().clientHeight:0);break;case z.TOOLTIP_BUBBLE:if(!y){let t=ID(o.panes.find(e=>{let{top:t,left:n,width:r,height:a}=e.bounds;return new za(n,t,r,a).contains(i)}).plots,i.y),n=`<div class="bubble-box">${x_({...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})}VD(e,o,m,!1,!1,e.hasLegend,g,_,v);break;case z.TOOLTIP_STD:if(!y){let t=x_({...o,hideSymbols:g,revealingClose:_,plots:o.panes.map(e=>e.plots).flat()});e.view.tooltip.show(t)}VD(e,o,m,!1,!1,e.hasLegend,g,_,v);break;case z.TOOLTIP_EXTERNAL:e.notifyHost(G.CH_TOOLTIPCHANGED,o);break;default:I(`Unknown tooltip mode requested: ${s}`,`warn`);break}}function BD(e,t,n,r,i,a){Si(e,{position:`absolute`,display:`flex`,"flex-direction":t,"flex-wrap":`wrap`,left:`${n+z.CARDS_X_OFFSET}px`,top:`${i+z.CARDS_Y_OFFSET}px`,maxWidth:`${a-r-z.CARDS_X_OFFSET*2}px`})}function VD(e,t,n=!1,r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=0){let u=e.view.el,d=S_(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=wi(t,u,`div`);BD(i,n&&v_(e)?`column`:`row`,o,s,c+l,d),Ti(i,{"bcharts-card":!0,"bcharts-card-main":n,"bcharts-card-first":f===0}),i.innerHTML=r}let p=xi(`#right-${t}`,u);P(p)||(p=document.createElement(`div`),p.id=`right-${t}`,u.appendChild(p),Ti(p,`bcharts-card bcharts-card-move`)),Si(p,{position:`absolute`,display:`block`,right:`${s+z.CARDS_X_OFFSET}px`,top:`${c+l+z.CARDS_Y_OFFSET}px`}),p.innerHTML=i})}var HD=null;function UD(){return HD===null&&(HD=$().config.hostingModel===ae[ae.Application]),HD}var WD=class extends nD{presenter;panY;snapToSupported=!1;warmUp=!0;preventDefault=!1;lastOffset;lastPanningExtremes;constructor(e){super(),this.ap=e,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=UD();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=GD(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(){_k(this.presenter)}onMouseLeave(){this.finished()}onMouseUp(){this.finished()}onMouseDblClick({presenter:e,offset:t,originalEvent:n}){Ie()&&rO(e,t,n)}performLongPress(e,t,n){e.enableTooltip(!0),e.resetActiveTool(),e.activeTool.startTouchCrosshairMode(e,t,n)}};function GD(e,t,n,r){let i=(n-t)/e.viewBox.height,[a,o]=r,s=i*(o-a);return[a+s,o+s]}var KD=null;function qD(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)&&(KD={path:new Path2D(i),width:e[2],height:e[3],rect:new za(0,0,0,0),logoClickable:t})}}var JD=5,YD=50;function XD(e,{x:t,y:n,height:r,width:i}){if(!N(KD))return;let{path:a,width:o,height:s,rect:c}=KD,l=i/8,u=Math.min(Math.max(YD,l),o)/o;c.width=o*u,c.height=s*u,c.x=t+JD,c.y=n+r-c.height-JD,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 ZD(){return N(KD)&&KD.logoClickable?KD.rect:null}var QD=class extends xD{constructor(e,t){super(e,t)}hitTest(e){if(!this.visible)return!1;let t=this.getRect();return t===null?!1:t.contains(e)}draw(e,t){return super.draw(e,t)?(Xa(e,this.getRect()),!0):!1}};function $D(e,t){return e<t?[e,t]:[t,e]}var eO={line:{width:1,color:`rgba(127, 127, 127, 0.3)`,dashStyle:`LongDash`},fill:{color:`rgba(127, 127, 127, 0.1)`}},tO=class extends ED{snapToSupported=!1;preventDefault=!1;axis;presenter;constructor(){super(fD(`Rectangle`,QD,null,eO),!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)){_k(this.presenter,{toolChange:O.Executed,annId:`ZoomIn`});let e=this.annotation.points,t=$D(e[0].price,e[1].price),n=$D(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=z.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 nO(e,t){let n=uD(e);n.offset={x:t.x,y:t.y},n.canFlip=e.getFlipAnchorIndices()!==null;let r=e.axis.pane.presenter;r.clearSelection(),r.notifyHost(G.CH_ANNNEEDSCONTEXTMENU,n)}function rO(e,t,n){let r={offset:{x:t.x,y:t.y},chart:e.accessor,originalEvent:n};e.notifyHost(G.CH_CHTNEEDSCONTEXTMENU,r)}function iO(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 aO(e,t){return t.x===e.x||t.x===e.x+e.width||t.y===e.y||t.y===e.y+e.height}function oO(){let e=$().config.touchCrosshairTimeoutMillis;return P(e)&&Number.isFinite(e)?e:z.LONG_PRESS_TIMEOUT_MILLIS}var sO=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(G.CH_ZOOMCHANGED,1e3)}startTouchCrosshairMode(e,t,n){this.touchCrosshairMode=!0,this.showCrosshairAndTooltips(e.view,t,n)}activated(){}deactivated(){}findHit(e){if(!e.point)return[];if(e.axis.pane.axes.some(t=>t.plots.some(t=>t.hitTestCustomEvent(e.point))))return z.EVENT_PIN_HIT;let t=e.presenter.selectedAnnotation,n;t!==void 0&&(n=t.points.find(t=>t.hitTest(e.point)));let r=xe(e.axis.annotations.filter(t=>t.computed?null:t.hitTest(e.point)));return n!==void 0&&r==null&&(r=t),[r,n]}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.viewBox.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?rO(n,t):nO(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<z.DOUBLE_CLICK_DURATION_MILLIS)return this.onMouseDblClick(e),!0;if(!u&&this.isLogoLink(i)&&o.notifyHost(G.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 tO,o.activeTool.onMouseDown(e),!0;let[n,r]=this.findHit(t);if(o.clearSelection(),n!=null&&o.setSelection(n),n==null||n?.locked)return u?(this.hideCrosshairAndTooltips(o.view),n==null?rO(o,i,s):n?.locked&&nO(n,i),!0):this.touchCrosshairMode?!0:(o.activeTool=new WD(t),o.activeTool.startPan(i),UD());let a=r!=null;return u?(nO(n,i),Ie()):a&&!r.movable||!a&&!n.canMove(t.point)?!1:(o.activeTool=a&&n.points.indexOf(r)!==-1?new aD(n,r):new iD(n,t,i),Ie())}else this.canHorizontalZoom(o)&&(this.prevZoomingOffset=i);return!1}onContextMenu(e){return!0}isLogoLink(e){let t=ZD();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);P(n)?t.presenter.view.setCursor(ee.Crosshair):P(e)?e.isSelected?t.presenter.view.setCursor(ee.Move):t.presenter.view.setCursor(ee.Hand):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&&zD(e.presenter,{time:t.time,offset:n,price:t.price,lastBarRefresh:void 0,justMain:void 0})}hideCrosshairAndTooltips(e,t=!1){e.drawCrosshair({ap:void 0}),e.tooltip.hide(),e.presenter.hideCards(t),t&&e.tooltip.mode===`cards`&&!e.presenter?.hasLegend&&RD(e.presenter)}onMouseLeave(e){let{view:t,offset:n}=e;t.presenter.accessor.getPaneBounds()?.every(e=>!e||!e.contains(n)||aO(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=oO();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)){let e=r.selectedAnnotation;e.axis.deleteAnnotation(e),r.onAnnotationModifiedByTool(e,O.Deleted)}if(P(r.selectedAnnotation)&&(Re(t,n)?r.clearSelection():ze(t,n)&&r.selectedAnnotation instanceof CD&&r.selectedAnnotation.textEditable&&(r.activeTool=new kD(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<z.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=iO(t,this.lastScaleResizingOffset,n,r,-r);this.lastScaleResizingOffset=n,t.isCustomDomain=!0,t.yScale.domain(i),e.redraw()}}},cO=class extends TD{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 yk(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),vk(this.annotation,!0,O.Created)):this.annotation.requestRedraw()}applyToPoints(e){this.annotation.points[this.clicks].update(e.price,e.time)}},lO=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(),vk(n,!0,O.None)}},uO=z.MARKER_ARROW_ANGLE*Math.PI/180/2;function dO(e,t){return fO(e.map(e=>e.point),t)}function fO(e,t,n=z.MARKER_ARROW_LENGTH){return new pO(e,t,n)}var pO=class{p1;p2;constructor(e,t,n=z.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 Sa([t,n],e,z.HIT_TEST_TOLERANCE)||Sa([t,r],e,z.HIT_TEST_TOLERANCE)}draw(e){let{anchor:t,p1:n,p2:r}=this.getArrowPoints();Qa(e,t,n),Qa(e,t,r)}getArrowPoints(){let e=xa(this.p1,this.p2),t=this.vertex===`start`?0:Math.PI,n=e-uO+t,r=e+uO+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}}}},mO=class{hitTest(){return!1}draw(){}},hO=class extends hD{constructor(e,t){super(e,t),this.addPoints(2),this.alignPointsSupported=!0}get extend1(){return this.traits[z.AT_EXTEND_PT_1]}get extend2(){return this.traits[z.AT_EXTEND_PT_2]}get showPercentDiff(){return this.traits[z.AT_SHOW_PERCENTDIFF]}get showBarCount(){return this.traits[z.AT_SHOW_BARCOUNT]}get showRatio(){return this.traits[z.AT_RATIO]}getElements(){let e=this.points[0].point,t=this.points[1].point,n=new pD(e,t,this.extend1,this.extend2,this.axis),r=[];return this.extend1&&r.push(new pD(n.p1,e,!0,!1,this.axis)),r.push(new pD(e,t,!1,!1,this.axis)),this.extend2&&r.push(new pD(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 s_(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=ba(ga(n.point,r.point),i);Ja(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!==``&&Ja(t,o,ba(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!==``&&Ja(t,c,ba(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`?dO(this.points,e):(I(`There is no marker of ${n} kind`,`warn`),new mO))}},gO=class extends hD{constructor(e,t){super(e,t),this.addPoints(1)}get showTimestamps(){return this.traits[z.AT_SHOW_TIMESTAMPS]}getElements(){return[new oD(this.points[0].point,!0,this.axis)]}getTimeScaleAdornments(){return this.showTimestamps?[{time:this.points[0].time,color:this.traits.line.color}]:super.getTimeScaleAdornments()}},_O=class extends hD{constructor(e,t){super(e,t),this.addPoints(1)}getElements(){return[new oD(this.points[0].point,!1,this.axis)]}getPriceScaleAdornments(){return this.showPrices?[{price:this.points[0].price,color:this.traits.line.color}]:super.getPriceScaleAdornments()}},vO=class extends hD{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(ga(e.point,t.point)),t]:z.EMPTY_ARRAY}line2(){return this.traits[z.AT_LINE_2]}use52WeekPrices(){return this.traits[z.AT_USE_52WEEK_PRICES]}getElements(){let e=this.allPoints();return e===z.EMPTY_ARRAY?z.EMPTY_ARRAY:e.map(e=>new pD({x:-z.OUT_OF_SCREEN,y:e.point.y},{x:z.OUT_OF_SCREEN,y:e.point.y},!1,!1,this.axis))}wasPointMovedByTool(e,t){P(this.use52WeekPrices())&&(this.traits[z.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,ko(r)}getPriceScaleAdornments(){let e=this.allPoints();if(!this.showPrices||e===z.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}},yO=5,bO=class extends gD{helper;constructor(e,t,n){super(e,t),this.addPoints(n),this.helper=new sD(e)}get showTrendLine(){return this.traits[z.AT_SHOW_TRENDLINE]}get hasAllPoints(){return P(...this.points.map(e=>e.point))}get line2(){return this.traits[z.AT_LINE_2]}get extendLeft(){return this.traits[z.AT_EXTEND_LEFT]}get extendRight(){return this.traits[z.AT_EXTEND_RIGHT]}get reverse(){return this.traits[z.AT_REVERSE]}get levelsRespectLogScale(){return this.traits[z.AT_LEVELS_RESPECT_LOG_SCALE]}getStyleForElement(e,t){if(e.isTrend){let e=F(this.traits);return e.line=this.line2,ko(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 pD(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 z.AT_LABELS_LEFT:return this.extendLeft?r({x:i.x,y:e.anchor1.y},T.Left,t):super.getAdornPointAndAlign(e,t);default:case z.AT_LABELS_RIGHT:return this.extendRight?r({x:i.x+i.width,y:e.anchor2.y},T.Right,-t):super.getAdornPointAndAlign(e,t);case z.AT_LABELS_CENTER:return super.getAdornPointAndAlign(e,t)}}getTextRef(){return(e,t,n)=>{let r=this.formatLevelPrice(n,t.anchor1.y);return{ref:t,spacing:yO,offsetY:-yO,text:r}}}adornElements(e,t){this.adornElementsForColoredFactors(e,(e,t)=>{let n=new Path2D;return e===null?n:(Va(n,e.p1),n.lineTo(t.p2.x,e.p1.y),Ha(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}})}},xO=class extends bO{constructor(e,t){super(e,t,2)}},SO=class extends bO{constructor(e,t){super(e,t,3)}},CO=5,wO=(e,t)=>{let n=new Path2D;return e===null?n:(Va(n,e.p1),Ha(n,e.p2),Ha(n,t.p2),n)},TO=class extends gD{constructor(e,t){super(e,t),this.addPoints(2)}get reverse(){return this.traits[z.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 pD(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 pD({x:r.x,y:c},{x:i.x,y:c},!1,!1,this.axis),spacing:CO,offsetY:!0,text:s.toString()}}}adornElements(e,t){this.adornElementsForColoredFactors(e,wO,this.getTextRef(),t)}},EO=class extends TO{constructor(e,t){super(e,t)}};function DO(e,t,n){return new kO(e,t,va(e,t),0,Math.PI,null,n)}function OO(e,t,n,r,i,a){return new kO(e,null,t,n,r,i,a)}var kO=class{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(va(this.left,e),va(this.right,e));else{let{x:n,y:r}=ya(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<=z.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),Za(e,this.center,this.radius,this.startAngle,this.endAngle,this.isAntiClockwise??!1),e.restore()}},AO=(e,t)=>{let n=new Path2D,{center:r}=t;if(Va(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 Va(i,a),i.arc(a.x,a.y,e.radius,e.endAngle,e.startAngle,!e.isAntiClockwise),n.addPath(i),n},jO=class extends gD{constructor(e,t){super(e,t),this.addPoints(2)}getElements(){let[e,t]=this.getScreenPoints();if(!P(e,t))return[];let n=va(e,t),r=ya(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 DO(e,{x:e.x+s,y:e.y+o},this.axis)});if(this.showTrendLine){let n=new pD(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,AO,this.getTextRef(),t)}},MO=class extends jO{constructor(e,t){super(e,t)}getStyleForElement(e,t){if(e.isTrend){let e=F(this.traits);return e.line=this.line2,ko(e)}return super.getStyleForElement(e,t)}get showTrendLine(){return this.traits[z.AT_SHOW_TRENDLINE]}get line2(){return this.traits[z.AT_LINE_2]}},NO=class extends gD{constructor(e,t){super(e,t),this.addPoints(2)}get factorsPropName(){return z.AT_ANGLES}getElements(){let[e,t]=this.getScreenPoints(),{x:n,y:r}=ya(t,e);return this.getColoredElements(({value:i})=>{let a=(t,n)=>new pD(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,wO,this.getTextRef(),t)}},PO=class extends TO{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 pD(e,t,!1,!1,this.axis)].concat(super.getElements())}},FO=class extends jO{constructor(e,t){super(e,t),this._factors=[{shown:!0,value:1/3},{shown:!0,value:2/3}]}},IO=class extends hD{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 pD(t,{x:t.x+r,y:t.y+i},!1,!0,this.axis)),a.push(new pD(e,{x:e.x+r,y:e.y+i},!1,!0,this.axis)),a.push(new pD(n,{x:n.x+r,y:n.y+i},!1,!0,this.axis)),a.push(new pD(t,n,!1,!1,this.axis)),a}},LO=class extends xD{constructor(e,t){super(e,t)}getEllipse(){let e=this.getRect();return e===null?null:new Ba(e.centerX,e.centerY,e.width/2,e.height/2)}hitTest(e){if(!this.visible)return!1;let t=this.getEllipse();return t===null?!1:t.contains(e)}draw(e,t){return super.draw(e,t)?(Ya(e,this.getEllipse()),!0):!1}},RO=class extends hD{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[z.AT_EXTEND_PT_1]}get extend2(){return this.traits[z.AT_EXTEND_PT_2]}getLastPoint(){let[e,t,n]=this.points;var r=va(e.point,t.point),i=xa(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 pD(e.point,t.point,this.extend1,this.extend2,this.axis)),P(n?.price)){var i=this.getLastPoint();r.push(new pD(n.point,i,this.extend1,this.extend2,this.axis))}return r}},zO=class extends xD{constructor(e,t,n){super(e,t),this.kind=n,this.adjustFill=!0}hitTest(e){if(!this.visible)return!1;let t=this.getRect();return t===null?!1:t.contains(e)}get dimension(){let e=this.kind===`fish_hook`?2:1;return z.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=Te(t,r,Number,h_);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=ba(this.points[0].point,{x:0,y:-e/2}),s=ba(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),no(e,this.kind,n),!0}},BO=class extends gD{helper;constructor(e,t){super(e,t),this.addPoints(2),this.helper=new sD(e)}getElements(){let e=this.axis.pane.presenter.timeline,{price:t,time:n}=this.points[0],r=Te(e,n,Number,h_),i=Te(e,this.points[1].time,Number,h_),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 oD(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)]}},VO=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(G.CH_ANNPOINTPICKED,r),_k(n,void 0)}},HO={Open:`Open`,Closed:`Closed`},UO=class extends hD{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 ia(2)}data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}get presenter(){return this.axis.pane.presenter}getDataWindow(e,t,n=!0,r=!0){let i=this.data(W.DateTime),a=Te(i,+e,Number),o=Te(i,+t,Number),s={refIndex:-1,highestIndex:-1,lowestIndex:-1,highest:null,lowest:null,data:[]},[c,l,u]=[W.High,W.Low,W.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)?HO.Closed:HO.Open,s.special=s.highestIndex===-1&&s.lowestIndex===-1||s.highestIndex===s.lowestIndex;let e=xe(s.data);if(s.toPrice=e.close,s.toTime=e.time,s.state===HO.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)}s.pAndL=Xe(this.isLong?s.toPrice-this.entryPrice:this.entryPrice-s.toPrice,2)}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=Te(e,+this.points[0].time,Number,h_);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[z.AT_ACCOUNT_SIZE]}get risk(){let e=this.traits[z.AT_RISK_IS_PERCENT],t=this.traits[z.AT_RISK];return Xe(e?t/100*this.accountSize:t,2)}get pointValue(){return this._metaData||=this.presenter.mainPlot.metaData,this._metaData.pointValue}formatDollarValue(e){return Number.isFinite(e)?`${e<0?`-`:``}$${this.twoDecMeta.format(Math.abs(e))}`:z.NOT_APPLICABLE}get qty(){return Math.floor(this.risk/(this.isLong?this.entryPrice-this.lowerPrice:this.upperPrice-this.entryPrice))}get upperDiff(){return Xe(this.upperPrice-this.entryPrice,2)}get amountMultiplier(){return this.isLong?1:-1}get upperAmount(){return Xe(this.accountSize+this.amountMultiplier*this.qty*this.upperDiff,2)}get upperPandL(){return Xe(this.amountMultiplier*this.upperDiff*this.pointValue,2)}get isCompact(){return this.traits[z.AT_COMPACT]}get upper(){let e=s_(this.axis,this.priceMap(this.upperPrice)),t=`(${Xe(this.upperDiff/this.entryPrice*100,2).toFixed(2)}%)`;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 Xe(this.entryPrice-this.lowerPrice,2)}get lowerAmount(){return Xe(this.accountSize-this.amountMultiplier*this.qty*this.lowerDiff,2)}get lowerPandL(){return Xe(-this.amountMultiplier*this.lowerDiff*this.pointValue,2)}get lower(){let e=s_(this.axis,this.priceMap(this.lowerPrice)),t=`(${Xe(this.lowerDiff/this.entryPrice*100,2).toFixed(2)}%)`;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 Xe(this.isLong?this.upperDiff/this.lowerDiff:this.lowerDiff/this.upperDiff,2)}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(z.AT_FILL2)}get upperStyle(){return this.fillOnlyStyle(z.AT_FILL)}get textStyle(){return this.fillOnlyStyle(z.AT_FILL_TEXT)}get secondaryLineStyle(){return ko({line:{color:this.traits.line.color,dashStyle:`ShortDash`},fill:{color:z.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(){let e=this.dataWindow;return this.isLong?e.pAndL>0:e.pAndL<=0}getStyleForElement(e,t){return e.style||this.defaultStyle}getElements(){let e=new pD(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 mD(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 mD(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 sD(this.axis,this.entryPrice,e.time),n=new sD(this.axis,s.toPrice,s.toTime),r=new pD(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 mD({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.visible)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=>wa(this.traits[e].color);return[{price:this.upperPrice,color:e(z.AT_FILL)},{price:this.entryPrice,color:e(z.AT_LINE)},{price:this.lowerPrice,color:e(z.AT_FILL2)}]}adornElements(e,t){let[n,r,i]=e;if(this.showTextAdornments){let[e,a]=[!0,!1].map(e=>Ga(t,e)),{x:o,y:s,width:c}=r.rect,l={x:o+c/2,y:s+e},u=this.textStyle.fillStyle;Ja(t,this.upperText,l,T.Center,u,wa(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)};Ja(t,this.lowerText,h,T.Center,u,wa(this.lowerStyle.fillStyle));let{p1:g,p2:_}=n,{x:v,y}=g,{x:b}=_,x=this.state||z.NOT_APPLICABLE,S=this.isCompact?`${this.formatDollarValue(this.pAndLValue)}`:`${x} P&L: ${this.formatDollarValue(this.pAndLValue)}, Qty: ${this.qty}`,C=this.isCompact?`${this.riskReward.toFixed(2)}`:`Risk/Reward Ratio: ${this.riskReward.toFixed(2)}`,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=wa(this.isUpperPerPAndL?this.upperStyle.fillStyle:this.lowerStyle.fillStyle);Ja(t,[S,C],D,T.Center,u,te)}}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}},WO=class extends _D{markers;display=null;constructor(e,t){super(e,t),this.points=bD(e),this.points[2].visible=!1,this.points[3].visible=!1,this.markers=[new mO]}isPointDrawn(e){return super.isPointDrawn(e)?e.visible:!1}makeLineArrow(e,t,n,r){let i=[ga(e,t),ga(n,r)];return[this.makeLine(i[0],i[1]),fO(i,`end`,10)]}get rectColor(){return this.traits[z.AT_FILL].color}get textColor(){return this.traits[z.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?`${sn(t,e)}d`:br(Tr({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=Ga(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){Ja(t,this.text,this.getTextCoord(e[0],t),T.Center,this.textColor,wa(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,W.Volume)}`];let n=Math.min(+e,+t),r=Math.max(+e,+t),i=this.data(W.DateTime);if(!i||i.length===0)return[`0 bars, `,`Vol ${this.formatter.format(0,W.Volume)}`];let a=Te(i,+n,Number),o=Te(i,+r,Number),s=this.data(W.Volume);if(!Array.isArray(s))return[`0 bars, `,`Vol ${this.formatter.format(0,W.Volume)}`];let c=pe(s.slice(a,o+1)),l=this.formatter.format(c,W.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,W.Close)} (${this.formatter.format(r,W.PercentChange)})`]}resetComputedState(){this.display=null}getFlipAnchorIndices(){return[0,1]}},GO=class extends WO{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()}},KO=class extends WO{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()}},qO=class extends WO{get drawBorder(){return this.traits[z.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())}},JO=class extends _D{constructor(e,t){super(e,t),this.points=bD(e)}get priceLevels(){return So(this.traits[z.AT_PRICE_LEVELS])}get timeLevels(){return So(this.traits[z.AT_TIME_LEVELS])}get showAngles(){return this.traits[z.AT_SHOW_ANGLES]}get reverse(){return this.traits[z.AT_REVERSE]}get showLeftLabels(){return this.traits[z.AT_SHOW_LEFT_LABELS]}get showRightLabels(){return this.traits[z.AT_SHOW_RIGHT_LABELS]}get showTopLabels(){return this.traits[z.AT_SHOW_TOP_LABELS]}get showBottomLabels(){return this.traits[z.AT_SHOW_BOTTOM_LABELS]}getAngles(e,t){let n=this.getScreenPoints(),r=this.lineOnlyStyle(z.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=Wa(t,1)/2,o=e=>Number(e.toFixed(4)).toString(),{x:s,y:c}=z.DEFAULT_ADORN_OFFSET,l=(e,n,r,i,a)=>{let s=ba(e,n);Ja(t,o(r),s,i,a)},u=(e,n)=>{let r=new Path2D;Ua(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();Ua(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]}},YO=e=>e.map(e=>({...e,dimensions:e.value.split(`x`).map(Number)})),XO=5,ZO=(e,t)=>Math.abs(e-t)<1e-7,QO=class extends _D{_parsedFans=null;_parsedArcs=null;constructor(e,t){super(e,t),this.points=bD(e),this._parsedFans=this._parsedArcs=null}get levels(){return So(this.traits[z.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/XO))}get showRangesRatio(){return this.traits[z.AT_SHOW_RANGES_RATIO]}get arcs(){return So(this.traits[z.AT_ARCS])}get fans(){return So(this.traits[z.AT_FANS])}get reverse(){return this.traits[z.AT_REVERSE]}get parsedFans(){return this._parsedFans===null&&(this._parsedFans=YO(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*XO*r}:{x:t.x+s/c*XO*i*n,y:t.y})})}get parsedArcs(){return this._parsedArcs===null&&(this._parsedArcs=YO(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)/XO,dy:Math.abs(t.y-e.y)/XO}:null}get priceBarRatio(){return this.traits[z.AT_PRICE_BAR_RATIO]}set priceBarRatio(e){this.traits[z.AT_PRICE_BAR_RATIO]=e}makeStyledLine(e,t,n){let r=this.makeLine(e,t);return this.singleStyle||(r.style=ko(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=ZO(i,a)?null:{x:1,y:a/i},s=this.getClipPath();return this.computedArcs.map(({computed:i,traits:a})=>{let c=OO(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=ko(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 Ua(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=xe(r);n(AO(null,e),e,this.applyBackgroundOpacity(this.traits.line.color))}else{let e=null;r.forEach(t=>{let r=AO(e,t),i=t.style.fillStyle;n(r,t,i),e=t})}t.restore()}if(this.showRangesRatio&&this.unit!==null){let e=xe(this.computedLevels),n=(this.singleStyle?this:e).traits.line.color,[,r,i,a]=this.getReversedScreenPoints(),{x:o,y:s}=z.DEFAULT_ADORN_OFFSET,{flipX:c,signX:l,signY:u}=this.getOrientation(),d=ba(i,{x:-o*l,y:s*u}),{priceDiff:f,barsDiff:p}=this.getLinesDataAtLevels(null,null),m=c?T.Right:T.Left;Ja(t,p.toFixed(0),d,m,n);let h=ba(a,{x:o*2*l,y:-s*u}),g=c?T.Left:T.Right;Ja(t,this.formatter.format(f,W.Close),h,g,n);let _=ba(r,{x:-o*l,y:-s*u});Ja(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,!ZO(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]}},$O=5,ek=(e,t)=>{let n=new Path2D;return e===null?n:(Va(n,e.p1),Ha(n,e.p2),Ha(n,t.p2),Ha(n,t.p1),n)},tk=class extends gD{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[z.AT_EXTEND_PT_1]}get extend2(){return this.traits[z.AT_EXTEND_PT_2]}getElements(){let[e,t,n]=this.getScreenPoints(),{x:r,y:i}=ya(n,e),a=n=>{let[r,i]=[e,t].map(e=>ba(e,n));return new pD(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:$O,offsetY:!0,text:this.formatLevelPrice(n,t.anchor1.y)})}adornElements(e,t){this.adornElementsForColoredFactors(e,ek,this.getTextRef(),t)}},nk=class extends hD{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:this.useChange=(this.presenter.mainPlot?.mainCurve?.attributes)?.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=bs(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 za(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 mD({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 mD({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 pD({x:t,y:a},{x:o,y:a},!1,!1,this.axis))}}),n}get isVisible(){return this.studyPlot.visible&&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(!nn(e)||!nn(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(z.AT_FILL)}get upStyle(){return this.fillOnlyStyle(z.AT_FILL2)}get totalStyle(){return this.fillOnlyStyle(z.AT_FILL3)}get downValueStyle(){return this.fillOnlyStyle(z.AT_FILL4)}get upValueStyle(){return this.fillOnlyStyle(z.AT_FILL5)}get totalValueStyle(){return this.fillOnlyStyle(z.AT_FILL6)}get backgroundStyle(){return this.fillOnlyStyle(z.AT_FILL7)}get lineStyle(){return this.lineOnlyStyle(z.AT_LINE)}getBoxEndFromStart(e){switch(this.periodType){case`VisibleScreen`:default:return null;case`Days`:return Tn(ih(g.Day,this.period)(e),1);case`Bars`:{let t=this.axis.pane.presenter.data.aggregation;return Tn(ih(t.unit,t.size*this.period)(e),1)}}}getData(){let e=this.axis.pane.presenter.data.aggregation;if(e.isTick||e.hasSpec&&!dw(e.spec))return;let[t,n]=this.presenter.view.xAxis.xScale.domain()||[];if(!nn(t)||!nn(n))return;let r=ih(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=Tn(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(W.TradingDay),o=e=>{let t=0,n=i[e],r=a[e];for(let o=e;o<i.length;o++)if(Vt(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=Tn(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=Tn(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 W.UPVOL:return this.totalVolume?null:a.upVolume;case W.DNVOL:return this.totalVolume?null:a.downVolume;case W.TOTVOL:return this.totalVolume?a.totalVolume:null;case W.POC:case W.VAREA:case W.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=>Te(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(W.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(W[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}},rk=[`None`,`Absolute`,`Percent`],ik=`#16A34A`,ak=`#DC2626`;function ok(e){return typeof e==`string`&&rk.includes(e)}var sk=class extends hD{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=ok(t)?t:`None`}formatSegmentValue(e,t){return this.displayMode===`Absolute`?this.formatter.format(t-e,W.Close):this.displayMode===`Percent`?e===0?``:this.formatter.format((t-e)/e,W.PercentChange):``}getElements(){if(this.visibleLabelSegments=[],!this.studyPlot.visible||!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(Ga(t,!0));this.visibleLabelSegments.forEach(e=>{let r=this.formatSegmentValue(e.fromPrice,e.toPrice);if(r===``)return;let i=e.toPrice>=e.fromPrice;Ja(t,r,{x:e.toPoint.x,y:e.toPoint.y+(i?-n:n)},T.Right,i?ik:ak)})}},ck=[z.AT_LINE,z.AT_LINE_2,z.AT_LINE_3],lk=class extends hD{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?.visible)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 pD({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=ck[e._data?.lineIndex??t],r=this.traits[n];return r?ko({line:r,fill:{color:z.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?.[z.AT_LINE]?.color,this.traits?.[z.AT_LINE_2]?.color,this.traits?.[z.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(ek(e,n))};this.isCurveVisible(3)&&o(r,i,this.traits?.[z.AT_FILL]?.color),this.isCurveVisible(4)&&o(i,a,this.traits?.[z.AT_FILL2]?.color)}};function uk(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 dk=class extends hD{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(z.AT_LINE),t=this.lineOnlyStyle(z.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 sD(this.axis,this.targetPrice,this.targetDate)],this.pricesCount>1&&this.points.push(new sD(this.axis,this.targetPrice2,this.targetDate)),this.unitsPerYear=AE(this.presenter.data.aggregation),this.anchorPrice=this.mainCont.getLastDataPoint(W.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=uk(t(this.targetPrice));if(this.pricesCount>1){let e=uk(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.mainCurve.visible)return[];let e=[];return e.push(new oD(this.points[0].point,!0,this.axis)),e.push(new oD(this.points[0].point,!1,this.axis)),this.pricesCount>1&&e.push(new oD(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(Ga(t,e))),r=this.pricesCount>1,i=this.points[0].point,a=r?this.points[1].point:i,o=this.traits.line2.color,s=Pa(o),c=Wa(t),l=[`Above`,`Below`,`Between`],u=(e,t)=>`${Xe(e*100,2).toFixed(2)}% Probability ${l[t]}`,d=(e,n)=>Ja(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})}}},fk=new sO,pk=e=>Q(cO,zO,1,e),mk=e=>Q(cO,wD,1,e),hk={Default:()=>function(){return fk},Line:()=>Q(ED,hO,!1),DateRange:()=>Q(ED,GO,!1),PriceRange:()=>Q(ED,KO,!1),DatePriceRange:()=>Q(ED,qO,!1),GannBox:()=>Q(ED,JO,!1),GannSquare:()=>Q(OD,QO),Ray:()=>Q(ED,hO,!1),GannLine:()=>Q(DD,hO,!1),VerticalLine:()=>Q(cO,gO,1),HorizontalLine:()=>Q(cO,_O,1),LongPosition:()=>Q(cO,UO,1,!0),ShortPosition:()=>Q(cO,UO,1,!1),FiftyPercentLine:function(e,t){return P(e)?Q(lO,vO,e.axis||t.mainAxis,e):Q(cO,vO,2)},FibonacciRetracement:()=>Q(ED,xO,!1),TrendBasedFibExtension:()=>Q(ED,SO,!0),FibonacciFan:()=>Q(ED,EO,!1),FibonacciArcs:()=>Q(ED,MO,!1),FibonacciChannel:()=>Q(ED,tk,!0),GannFan:()=>Q(ED,NO,!1),SpeedResistanceFan:()=>Q(ED,PO,!1),SpeedResistanceArcs:()=>Q(ED,FO,!1),AndrewsPitchfork:()=>Q(cO,IO,3),Rectangle:()=>Q(ED,QD,!1),Ellipse:()=>Q(ED,LO,!1),TrendChannel:()=>Q(ED,RO,!0),SymbolArrowUp:()=>pk(`arrow_up`),SymbolArrowDown:()=>pk(`arrow_down`),SymbolArrowRight:()=>pk(`arrow_right`),SymbolArrowLeft:()=>pk(`arrow_left`),SymbolArrowHorizontal:()=>pk(`arrow_horizontal`),SymbolArrowVertical:()=>pk(`arrow_vertical`),SymbolArcDown:()=>pk(`arc_down`),SymbolArcUp:()=>pk(`arc_up`),SymbolThumbsUp:()=>pk(`thumbs_up`),SymbolThumbsDown:()=>pk(`thumbs_down`),SymbolZero:()=>pk(`zero`),SymbolOne:()=>pk(`one`),SymbolTwo:()=>pk(`two`),SymbolThree:()=>pk(`three`),SymbolFour:()=>pk(`four`),SymbolFive:()=>pk(`five`),SymbolSix:()=>pk(`six`),SymbolSeven:()=>pk(`seven`),SymbolEight:()=>pk(`eight`),SymbolNine:()=>pk(`nine`),SymbolQuestion:()=>pk(`question`),SymbolFishHook:()=>pk(`fish_hook`),SymbolBuy:()=>pk(`buy`),SymbolSell:()=>pk(`sell`),FibonacciTimeZones:()=>Q(ED,BO,!1),Text:()=>Q(kD,CD,null),PickPoint:()=>function(){return new VO},ZoomIn:()=>function(){return new tO},ProfitLoss:mk,RewardRisk:mk,VolumeAtPrice:function(e){return Q(cO,nk,2,e)},ZigZag:function(e){return Q(lO,sk,null,e)},ProbabilityCones:function(e){return Q(cO,dk,2,e)},LinearRegressionChannel:function(e){return Q(lO,lk,null,e)}};function gk(e,t=!1,n=null,r=null,i=null){let a=hk[e];return a=a(r,i),a(e,t,n)}function _k(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 vk(e,t=!0,n=O.None){e.wasModifiedByTool();let r=e.axis,i={axis:r,annotation:e,toolChange:n};_k(r.pane.presenter,t?i:void 0)}function Q(e,t,n,r){return function(i,a,o){let s=fD(i,t,r,o);return s.annName=i,a?s:new e(s,n)}}function yk(e){e.button===E.Right&&_k(e.presenter)}function bk(e,t,n){let r={};r.inputs=dt(e.inputs);let i=r.inputs[z.INPUT_SOURCE],a=N(i)?W[i]:void 0;r.source=W[e.source]??a;let o=e.target!==void 0,s=P(n)?n:e.curves;return r.outFields=Oe(o?[W[e.target]]:s.map(e=>e.fields).flat()),r.target=o?W[e.target]:r.outFields[0],r.aggregation=t,r}function xk(e){return Array.isArray(e.innerSeries)}function Sk(e){return e.query?.symbol===z.PLACEHOLDER_SYMBOL_NAME?!0:xk(e)?e.innerSeries.some(e=>Sk(e)):!1}var Ck=class extends $E{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}fromModel(e){this.model=e,super.fromModel(this.model)}getMetaData(){let e=B(this.model.study),t=e.meta.decimals;this.metaData=t===void 0?this.basePlot.metaData:new ia(t),P(e.meta.range)&&(this.range=e.meta.range)}getDetachedScaleMargins(){return this.model?.study===`VOL`&&this.axis?.pane.isMain?z.VOLUME_DETACHED_SCALE_MARGINS:super.getDetachedScaleMargins()}applySpecifics(e){let t=this.model.study;B(t).meta.shiftable===!0&&this.curves.forEach(t=>{Number.isFinite(e.inputs.Offset)&&(t.shift=e.inputs.Offset)});let n=(e,t,n)=>this.curves[e].zones[t].value=this.model.levels[n].value;switch(t){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`JPI`:case`CTTP`:case`CTTI`:{let t=De(10,e=>(e+1)*.025),n=e=>t.map(t=>Aa(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`:n(0,0,0),n(0,1,2);break;case`STC`:n(0,0,0),n(0,1,1);break;case`RVOL`:case`DPO`:case`COPP`:n(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=gk(`VolumeAtPrice`,!0,{[z.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[z.AT_FILL]:{color:this.curves[0].colors[0]},[z.AT_FILL2]:{color:this.curves[0].colors[1]},[z.AT_FILL3]:{color:this.curves[0].colors[2]},[z.AT_FILL4]:{color:n.colors[0]},[z.AT_FILL5]:{color:n.colors[1]},[z.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=gk(`VolumeAtPrice`,!0,{[z.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[z.AT_FILL]:{color:this.curves[0].colors[0]},[z.AT_FILL2]:{color:this.curves[0].colors[1]},[z.AT_FILL3]:{color:this.curves[0].colors[2]},[z.AT_FILL4]:{color:n.colors[0]},[z.AT_FILL5]:{color:n.colors[1]},[z.AT_FILL6]:{color:n.colors[2]},[z.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=gk(`ZigZag`,!0,{[z.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=gk(`LinearRegressionChannel`,!0,{[z.AT_LINE]:{color:e.colors[0],width:e.lineWidth,dashStyle:e.dashStyle??`Solid`},[z.AT_LINE_2]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle??`Solid`},[z.AT_LINE_3]:{color:n.colors[0],width:n.lineWidth,dashStyle:n.dashStyle??`Solid`},[z.AT_FILL]:{color:r.colors[0]},[z.AT_FILL2]:{color:i.colors[0]}},this.id)(this.axis,!1);this.annIndex=this.annotations.push(a)-1;break}case`IVRANK`:{let t=W.ImplVolRank1Y;switch(e.inputs.TimeFrame){case`1-Year`:default:break;case`5-Day`:t=W.ImplVolRank5D;break;case`1-Month`:t=W.ImplVolRank1M;break;case`3-Month`:t=W.ImplVolRank3M;break;case`6-Month`:t=W.ImplVolRank6M;break;case`YTD`:t=W.ImplVolRankYTD;break}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case`IVPCTL`:{let t=W.ImplVolPerc1Y;switch(e.inputs.TimeFrame){case`1-Year`:default:break;case`5-Day`:t=W.ImplVolPerc5D;break;case`1-Month`:t=W.ImplVolPerc1M;break;case`3-Month`:t=W.ImplVolPerc3M;break;case`6-Month`:t=W.ImplVolPerc6M;break;case`YTD`:t=W.ImplVolPercYTD;break}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case`OPTIV`:{let t=[W.WeighImplVolHigh,W.WeighImplVol,W.WeighImplVolLow];switch(e.inputs.TimeFrame){case`1-Day`:default:break;case`5-Day`:t=[W.WeighImplVolHigh5D,W.WeighImplVol5D,W.WeighImplVolLow5D];break;case`1-Month`:t=[W.WeighImplVolHigh1M,W.WeighImplVol1M,W.WeighImplVolLow1M];break;case`3-Month`:t=[W.WeighImplVolHigh3M,W.WeighImplVol3M,W.WeighImplVolLow3M];break;case`6-Month`:t=[W.WeighImplVolHigh6M,W.WeighImplVol6M,W.WeighImplVolLow6M];break;case`1-Year`:t=[W.WeighImplVolHigh1Y,W.WeighImplVol1Y,W.WeighImplVolLow1Y];break;case`YTD`:t=[W.WeighImplVolHighYTD,W.WeighImplVolYTD,W.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=gk(`ProbabilityCones`,!0,{[z.AT_LINE]:{color:n.colors[0],width:n.lineWidth,dashStyle:n.dashStyle},[z.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}}getValueAt(e,t,n){return this.isVolAP?this.annotations[this.annIndex].getValueAt(e,t,n):super.getValueAt(e,t,n)}getColorOf(e){if(!this.isVolAP&&!this.isZigZag&&!this.isLinRegChannel)return null;let t=this.curves[0].colors;if(this.isZigZag)return t[0];switch(e){case W.UPVOL:return t[1];case W.DNVOL:return t[0];case W.TOTVOL:return t[2];case W.POC:case W.VAREA:case W.BARBACK:return z.COLOR_TRANSPARENT;case W.LINRUP:return t[0];case W.LINRMID:return this.curves[1].colors[0];case W.LINRLOW:return this.curves[2].colors[0];default:throw Error(`Unexpected Volume At Price field`)}}isEmpty(){return this.isVolAP||this.isZigZag||this.isLinRegChannel?!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}get eventsSeries(){return this.timeSeries}doesSeriesEmitEvents(){let e=this.timeSeries.helpers;return e.includes(W.Buy)||e.includes(W.Sell)}getEventFor(e){switch(e){case W.Buy:return{show:!0,title:`B`,color:`#03c03c`};case W.Sell:return{show:!0,title:`S`,color:`#c23b22`};default:return null}}getEventFields(){return this.hasEvents?[W.Buy,W.Sell]:[]}#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 Ai.call(this,async()=>{this.basePlot=this.#r(),await this.basePlot.initialize(),this.getMetaData();let e=this.axis.pane.presenter.data.aggregation,t=bk(this.model,e,this.curves);if(this.basePlot.isSeasonal){let e=this.basePlot.mainCurve.fields[0];P(e)&&(t.source=e)}this.applySpecifics(t);let n=this.basePlot.timeSeries;n instanceof Pv&&(n=n.actual),this.timeSeries=KT(this.model.study,t,n),this._hasEvents=this.doesSeriesEmitEvents(),this.timeSeries.useNotifications=!0;let r=this.title;return this.timeSeries.ready().then(e=>{let t=this.basePlot.timeSeries instanceof xg||Sk(this.timeSeries);!e&&!this.timeSeries.hasData&&!t&&!this.timeSeries.computedServerSide&&I(`Unable to calculate study values for ${r}`,`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`}invalidateAssociatedAnnotations(e){this.isVolAP&&this.annotations[this.annIndex].invalidate(e)}onPriceDomainsUpdated(){this.invalidateAssociatedAnnotations(`PriceDomainsChanged`)}shouldPriceMap(e){return this.isJpi?this.shouldMaybePriceMap?e.id===W.JPIB.id||e.id===W.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(W.JPIB,t),a=r(W.JPIS,t);if(i===null&&n.id===W.JPIB.id||a===null&&n.id===W.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}},wk=[W.Open,W.High,W.Low,W.Close,W.Volume],Tk=class extends $E{_expression;exprModel=null;symbols=null;errorText;get title(){return this.expression}get expression(){return this._expression}async parseExpression(){let e=Su(this._expression);if(this.exprModel=null,this.symbols=null,xu(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(wk.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 Ev(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=Du(this.exprModel),t=$().getTimeSeriesDataSource();return e.map(e=>{let n=this.makeQuery();return n.symbol=e,t.getTimeSeries(n)})}getRecord(){P(this.errorText)||(this.record=new rf(this.metaData.inner.map(e=>[e.symbol,e.resolved]),F(this.exprModel)),this.record.ready().then(e=>e))}getMetaData(){this.isValid&&(this.metaData=new oa(this.symbols),this.metaData.ready().then(e=>{e&&(this.getRecord(),this.presenter?.notifyHost(G.MD_CHANGED,{plot:this}))}))}fromModel(e){super.fromModel(e),this._expression=e.expression}async initialize(){return Ai.call(this,async()=>(await this.parseExpression(),this.isShutDown?!1:(this.getMetaData(),this.getTimeSeries(),!0)))}},Ek=class extends $E{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=Su(this.forward),t=xu(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(nh(this.offset),th(z.FMT_US_DATE_ONLY))(new Date)})`,this.outField=new Ld(`Close_${this.offset}`,v.Number,b.Forward,`Close (${this.offset})`),this.curves[0].fields[0]=this.outField):(this.suffix=``,this.outField=W.Close);let{yes:t,no:n}=A(e.symbols,e=>Yr(`${e}*1`)),r=(await Promise.all(t.map(e=>li(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(){this.isValid&&(this.metaData=new oa(Object.values(this.roots).flat()),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(G.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([[W.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 Dg(this.symbols):void 0;this.timeSeries=new Ev(this.fwdModel,r,this.getForwardPolicy(i)),this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:re.Unspecified};this.presenter?.notifyHost(G.TS_MANYCHANGED,e)}})}async initialize(){return Ai.call(this,async()=>(await this.parseForward(),this.isShutDown?!1:(this.getMetaData(),this.getTimeSeries(),!0)))}},Dk=e=>e.substring(0,e.lastIndexOf(`::`)),Ok=class extends $E{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 Eu(ku(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 Ld(`Close_${t}`,v.Number,b.Seasonal,`Close${this.suffix}`),this.curves[0].fields[0]=this.outField}applyOffset(e,t){return`${this.isPlain?e:hi(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=Su(this.seasonal,!0),t=xu(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=ai(await qr(e));a.set(e,t)}r=ku(r,e=>a.get(e)),i=Array.from(a.values());let o=i.every(e=>Yr(e)||Zr(e)),s=i.every(e=>$r(e)),c=i.every(e=>!Yr(e)&&!$r(e)&&!Zr(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=Ou(r);let{model:l,symbols:u}=Su(this.isAverage?this.constructAverage(r):this.constructSeasonal(r,this.offset),!0);this.seaModel=l,this.hasComputation=Ou(l),this._seasonal=Eu(ku(l,Dk)),this.symbols=u,this.outField.name=this.outField.shortName=this.fixupFieldDescription()}get isValid(){return!P(this.errorText)}getActualSymbols(){return[...new Set(this.symbols.map(Dk))]}fixupFieldDescription(){if(!this.hasComputation&&!this.isAverage){let e=Dk(this.symbols[0]);if(this.isPlain)return`${e} ${new Date().getFullYear()-this.offset}`;if(this.isFutures)return ai(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 oa(e),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(G.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([[W.Close,this.outField]]),noDataApproach:this.getNoDataApproach(),modelTransform:(e,t)=>t.length===0?this.seaModel:Su(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 qt(new Date,-e)}yearFromOffset(e){return wr(this.shiftYears(e))}getCmdtyRange(e){let t=this.shiftYears(e);return[wn(t),Cn(t)]}getSeasonalRange(e,t){let n=P(e[0],e[1]);return this.isPlain&&!n?this.getCmdtyRange(t):this.isFutures?[null,null]:this.isPlain&&t>0&&n?e.map(e=>qt(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=Dk(t),n.offset=this.symbolToOffset[t],n.cacheMe=!this.isPlain||n.offset===0,n.range=this.getSeasonalRange(n.range,n.offset),n.offset>0&&(n.disableStreamingUpdates=!0),e.getTimeSeries(n)});this.timeSeries=new Ev(this.seaModel,t,this.seasonalPolicy),this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:re.Unspecified};this.presenter?.notifyHost(G.TS_MANYCHANGED,e)}})}async initialize(){return Ai.call(this,async()=>(await this.parseSeasonal(),this.isShutDown?!1:(this.getMetaData(),this.getTimeSeries(),!0)))}},kk=[`bottom`,`right`,`left`],Ak={bottom:`center`,right:`start`,left:`end`},jk=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),!kk.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=Ak[this.position],e.strokeStyle=this.strokeColor,e.fillStyle=wa(this.backgroundColor),e.lineWidth=this.lineWidth;let s=[r,i??``].map(t=>e.measureText(t).width),c=Math.max(...s),l=this.position===`bottom`?0:this.arrowLength,u=Math.round(c+l+this.padding+this.padding),d=Math.round(u/2),f=Math.round(a/2);e.setLineDash([]);let p=t;e.beginPath(),e.moveTo(p,n);let m=n+f,h=n+2*f,g=n-f;if(this.position===`right`){e.lineTo(p,m);let t=p+u;o&&(e.lineTo(p,h),e.lineTo(t,h)),e.lineTo(t,m),e.lineTo(t,g),e.lineTo(p,g)}else if(this.position===`left`){e.lineTo(p,m);let t=p-u;o&&(e.lineTo(p,h),e.lineTo(t,h)),e.lineTo(t,m),e.lineTo(t,g),e.lineTo(p,n-f)}else if(this.position===`bottom`){let t=p-d,r=p+d;e.lineTo(p,n),e.lineTo(r,n),e.lineTo(r,n+a),e.lineTo(t,n+a),e.lineTo(t,n),e.lineTo(p,n)}if(e.closePath(),e.stroke(),e.fill(),e.fillStyle=this.textColor,e.textBaseline=`middle`,this.position===`bottom`)e.fillText(r,p,n+Wa(e,1));else if(this.position===`right`){let t=p+this.arrowLength+this.padding;e.fillText(r,t,n),o&&e.fillText(i,t,n+this.padding+f)}else if(this.position===`left`){let t=p-this.arrowLength-this.padding;e.fillText(r,t,n),o&&e.fillText(i,t,n+this.padding+f)}}},Mk=({y:e,halfHeight:t})=>e-t,Nk=({y:e,halfHeight:t})=>e+t;function Pk(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=Mk(e),o=Nk(i);a<o&&(e.y=o+1+e.halfHeight),Nk(e)>t.y+t.height&&(e.y=t.y+t.height-e.halfHeight-1)}})}var Fk=4,Ik=({x:e,halfWidth:t})=>e-t-Fk,Lk=({x:e,halfWidth:t})=>e+t+Fk,Rk=(e,t)=>e-1-t-Fk,zk=(e,t)=>e+1+t+Fk;function Bk(e,t){let n=e.length-1;e.forEach((e,r,i)=>{let a=r===0,o=a?null:i[r-1],s=Ik(e),c=a?t.x:Lk(o);if(e.x-e.halfWidth<t.x&&(e.x=zk(t.x,e.halfWidth)),s<c)e.x=zk(c,e.halfWidth+Fk);else{let t=Lk(e),a=r<n?Ik(i[r+1]):2**53-1;if(t>a){let n=Rk(e.x,t-a),r=Rk(e.x,e.halfWidth-2),i=zk(c,o?.halfWidth??0);e.x=Math.max(r,n,i)}}Lk(e)>t.x+t.width&&(e.x=Rk(t.x+t.width,e.halfWidth))})}var Vk=Array.from([,,,,,,],(e,t)=>++t).reverse();function Hk(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=ve(i,e=>e!==null),r=a===-1?null:i[a]),[r,a]}function Uk(e){let t=e.plot.timeSeries.container;return t===null||t.size<1?null:e.getColor(t.size-1)}function Wk(e){return e.curves.filter(t=>e.visible&&t.visible&&(e.type!==C.Study||t.style!==h.Ribbon)).map(t=>{let n=t.pickMainField(),[r,i]=Hk(e,n);return{value:r,color:Uk(t),field:n,index:i}})}var Gk=class{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;this.config={innerTickSize:7,tickPadding:5,indicatorPadding:4,fontWeight:400,fontSize:n||t||12},this.crosshairIndicator=new jk({fontSize:this.config.fontSize,arrowLength:this.config.innerTickSize})}makePlot(e){let t=null;switch(C[e.type]){case C.Symbol:t=new eD;break;case C.Expression:t=new Tk;break;case C.Study:t=new Ck;break;case C.IncomeStatement:t=new tD(w.IncomeStatement);break;case C.BalanceSheet:t=new tD(w.BalanceSheet);break;case C.Forward:t=new Ek;break;case C.Seasonal:t=new Ok;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,W.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 sD(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,W.Close)}toY(e){let t=this.priceMap(e);return this.yScale.priceToY(t)}get plotAnnotations(){let e=[];return this.plots.forEach(t=>{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=Te(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<=z.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+-xa(e,n)*180/Math.PI)%360,a=45/2,o=i>360-a||i<a||i>180-a&&i<180+a,s=i>90-a&&i<90+a||i>270-a&&i<270+a;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=gk(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 WE(this.scale,this),this.label=e.label,this.plots=[].concat(...e.plots.map(e=>this.expand(e))).map(e=>this.makePlot(e)),this.annotations=(e.annotations||[]).map(e=>this.makeAnnotation(e));let{chart:{fontFamily:t,backgroundColor:n},yAxis:{textColor:r,crosshair:{color:i},primaryOnTheLeft:a}}=this.pane.presenter.display,o=a??!1;this.onTheRight=this.primary&&!o||!this.primary&&o,this.crosshairIndicator.configure({position:this.onTheRight?`right`:`left`,fontFamily:t,strokeColor:i,textColor:r,backgroundColor:Aa(.15)(n)})}findIndex(e){return this.annotations.findIndex(t=>t.uid===e.uid)}addAnnotation(e){let t=this.makeAnnotation(e,!0);this.appendAnnotation(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:z.ANN_DUPLICATE_OFFSET,y:z.ANN_DUPLICATE_OFFSET}),t.appendAnnotation(n),n.requestRedraw(),this.fireAnnotationsChanged()}updateAnnotation(e,t){e.isSelected&&this.pane.presenter.clearSelection(),Lc(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),t.isUndoRedo||this.pane.presenter.undoRedoManager.done(lD(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=>Te(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!==W.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(be(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.visible!==!1).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.visible&&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.visible&&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=vi(this.pane.presenter.hostElement),t=xi(`#${z.HEADER_SIZE_PLACEHOLDER_ID}`,e);if(!P(t)){t=Ei(e,`div`),Si(t,{display:`none`}),Ci(t,{id:z.HEADER_SIZE_PLACEHOLDER_ID,class:`bcharts-card bcharts-card-first`});let{lineHeight:n}=getComputedStyle(t);isNaN(Number.parseFloat(n))&&Si(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)+z.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:z.PANE_CAP_MIN_PADDING_PERCENT,u=s?a:z.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]=z.PANE_TINY_PADDING_PIXELS:e===oe.Min&&(f[1]=z.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=Wa(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=s_(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 z.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(s_(this,t,!0)).width)),{innerTickSize:a,tickPadding:o}=this.config,s=P(this.label)?Wa(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(Ra(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=ka(.4)(r),e.translate(0,0);let t=this.onTheRight?1:-1;e.rotate(t*Math.PI/2),e.textAlign=`center`;let n=Wa(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([]),$a(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.visible&&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=s_(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.visible||!e.hasVisibleCurves||!e.timeSeries||!e.timeSeries.hasData)){if(i===`All`||i===`Main`&&e.main){let t=e.main?1:3;Wk(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,W.PreviousClose,void 0)}}),this.annotations.concat(this.plotAnnotations).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&&Pk(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=Pa(a),f=new jk({position:this.onTheRight?`right`:`left`,fontSize:this.config.fontSize,padding:this.config.indicatorPadding,fontFamily:n,textColor:d,strokeColor:a,backgroundColor:a}),p=i||s_(this,r),m,h=this.comparison===x.Percent;N(o)&&(m=h?o_(this,o):a_(o)),f.draw(e,u,t,p,m)};a?c.forEach(u):Vk.forEach(e=>c.filter(t=>t.priority===e).forEach(u))}};function Kk(e){let t=e.map(e=>e.plots).flat().filter(e=>C[e.type]==C.Symbol).map(e=>e.symbol).map(e=>di(e)).filter(e=>e!==null).map(e=>e.getFullYear());return t.length==0?null:Math.max(...t)}var qk=Symbol.for(`__dloacip__`),Jk=class{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=Kk(e.axes)),this.axes=e.axes.map((e,t)=>{let n=new Gk(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[qk]===!1||XD(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,W.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=Ca(l);e.save(),e.strokeStyle=c,e.lineWidth=u,e.setLineDash(d),eo(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){Ra(e,this.getBoundsWithoutScales())}drawAnnotations(e){e.save();let{chart:{fontFamily:t},yAxis:{fontSize:n}}=this.presenter.display;e.font=`${n??12}px ${t}`;let r=t=>t.draw(e,!0);this.axes.forEach(e=>{e.annotations.forEach(r),e.plotAnnotations.forEach(r)}),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.visible&&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(Ca(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=Ca(a);e.strokeStyle=i,e.setLineDash(o);let s=this.presenter.view.leftOffset,c=this.viewBox.width-this.presenter.view.rightOffset,l=vo();l.prolog(e),eo(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`,Ja(e,$().config.noDataText||z.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.drawTopmost(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 Yk(e,t){return{width:e,spacing:t,get totalWidth(){return this.width+this.spacing},offset:0}}var Xk=class extends IE{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=Yk(rt(n,z.DEFAULT_BAR_WIDTH,`chart`,`bar`,`width`),rt(n,z.DEFAULT_BAR_SPACING,`chart`,`bar`,`spacing`)),this._extent=null,this.wasZoomed=!1,this.fitAllData=!1}extent(e){return FE.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(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=Te(this.timeline,+a,Number,h_)),[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=e-this._range[0]-this.bar.offset,n=Math.floor(t/this.bar.totalWidth),r=this._extent[0]+n;return this.timeline.at(r)}timeToIndex(e){return this.ready?(e=typeof e==`number`?e:+e,Te(this.timeline,e,Number,h_)):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>z.MAXIMUM_BAR_WIDTH||r<z.MINIMUM_BAR_WIDTH)return!1;let a=Yk(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)?Te(this.timeline,e,Number,h_,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(z.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)}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>=z.INTRA_THRESHOLD)for(;i>0&&cn(n,r)<e;)i--,r=this.timeline.at(i);else if(!a.isTick){let t=Math.floor(e/z.ONE_DAY_MILLIS),r=e=>pn(e,zt(e)),a=r(n),o=n;for(;i>0;){let e=this.timeline.at(i),n=en(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,z.MINIMUM_BAR_WIDTH,z.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=z.DEFAULT_BAR_WIDTH,this.bar.spacing=z.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]>=z.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 Zk(e){return{date:e,priority:1,text:i_(e)}}var Qk=class{xScale;ticks;lastUsedOptions;wasPanned;panningXAxisAllowed;config;isVisible;crosshairIndicator;viewBox;overrideTickGetter;overrideFormatter;contractParityCache=null;contractParityCacheKey=null;constructor(e){this.view=e,this.xScale=new Xk(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;this.config={innerTickSize:5,tickPadding:5,indicatorPadding:5,fontWeight:400,fontSize:a||n||12},this.isVisible=i,this.crosshairIndicator=new jk({position:`bottom`,fontSize:this.config.fontSize,fontFamily:e,padding:this.config.indicatorPadding,strokeColor:o,textColor:r,backgroundColor:Aa(.15)(t),arrowLength:this.config.innerTickSize})}setDomain(){this.xScale.adjustDomain();let e=this.view.presenter.display.period===z.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()}}setViewBox(e){this.viewBox=e;let{x:t,width:n}=this.viewBox;this.xScale.range([t,t+n])}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=Wa(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=Vg(e);return t?Zk: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=Bg(),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<=(xe(a)+Se(o))/2){n=t[r[i]];break}}let i=n.Multipliers,a=i.findIndex(t=>e<t),o=a===-1?xe(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}=this.viewBox,{lineWidth:h,color:g,dashStyle:_}=t,v=Ca(_);e.textAlign=`center`,e.font=`${c} ${l}px ${s}`,e.lineWidth=1,e.strokeStyle=g,e.fillStyle=n,e.setLineDash([]),eo(e,p,f,f+m);let y=this.xScale.extent(),b=e=>!P(e)||!P(e[0],e[1]);if(b(y))return;let x=t=>e.measureText(t).width,S=(e,t)=>P(e)?cn(t,e):z.FIFTY_YEARS_MILLIS,C=i>0?i:120,w=this.xScale.domain();if(b(w))return;let T=(w[1].getTime()-w[0].getTime())*C*.6/m,ee=this.normalizeDuration(T),E=this.view.presenter.data.aggregation.isEndOfDay,D=(e,t)=>{if(e.date.valueOf()===z.ZERO_DATE.valueOf())return!0;if(S(e.date,t.date)<r)return!1;let n=t.x-e.x,i=t.date.getTime()-e.date.getTime()>=ee,a=n>C;return!(e.x+e.textWidth/2>=t.x-t.textWidth/2)&&(a||(E?i:!1))},te=f+m,ne=({text:n,x:r,date:i,forced:a})=>{P(i)&&(a||$a(e,r,p,p+u),e.fillText(n,r,p+u+d+l*.71),t.visible&&!a&&(e.save(),e.lineWidth=h,e.setLineDash(v),$a(e,r,0,p),e.restore()))},re={agg:this.view.presenter.data.aggregation,unitWidth:x(`M`),barWidth:this.xScale.bar.width,extent:y,formatString:a,minTickInterval:r||0,duration:T},ie=this.getTicks(re),ae=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>te?te-i:r,e.x=r,e.forced=t!==r}else e.forced=!1},O={date:z.ZERO_DATE,priority:999,x:-999,text:``,index:-1,textWidth:0};ie.forEach(e=>{e.x=this.xScale.indexToX(e.index),e.textWidth=x(e.text),ae(e),D(O,e)?(ne(O),O=e):e.priority<O.priority&&(O=e)}),ne(O),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=Te(s,+a[0],Number),u=Te(s,+a[1],Number,we,l);if(l<u){let t=this.viewBox.y,a=this.view.leftOffset,o=this.viewBox.x+this.viewBox.width;if(r.save(),i){r.fillStyle=e.fillColor;let d=c[l],f=Math.max(a,this.xScale.timeToX(s[l]));for(let e=l+1;e<=u;++e){let a=e<c.length?c[e]:null;if(e===u||n(a,d)){let n=e<s.length?s[e]:null,c=N(n)?this.xScale.timeToX(n):o;c=Math.min(c,o),i(d)%2==0&&r.fillRect(f,0,c-f,t),d=a,f=c}}}let d=vo();d.prolog(r),r.strokeStyle=e.color,r.lineWidth=e.width,r.setLineDash(Ca(e.dashStyle));let f=null;for(let e=l;e<u;++e){let i=c[e];if(n(i,f)){let n=s[e],a=this.xScale.timeToX(n);P(a,f)&&$a(r,a,0,t),f=i}}d.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(W.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=di(e),r=di(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,W.Symbol,a,e,e=>this.contractParityCache.get(e)??0)}}i.enabled&&(n?.data?.aggregation.isIntraday?this.drawTransitionsFor(i,W.TradingDay,a,e,e=>e):n?.data?.aggregation.unit===g.Day?this.drawTransitionsFor(i,null,(e,t)=>!Nr(e,t),e,e=>e.getMonth()):n?.data?.aggregation.unit===g.Week&&this.drawTransitionsFor(i,null,(e,t)=>!Fr(e,t),e,e=>e.getFullYear()))}getAnnXScore(e,t){return[en,jr,Nr,Fr].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 za(0,0,0,0);t.allAnnotations.concat(t.plotAnnotations).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=c_(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&&Bk(i,this.viewBox),i.forEach(t=>{let r=Pa(t.color);new jk({position:`bottom`,fontSize:this.config.fontSize,fontFamily:n,padding:this.config.indicatorPadding,strokeColor:z.COLOR_TRANSPARENT,textColor:r,backgroundColor:t.color,arrowLength:this.config.innerTickSize}).draw(e,t.x,this.viewBox.y+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)&&nn(l)))return!1;if(!i)return!0;t=this.xScale.timeToX(l);let u=Ca(s);e.strokeStyle=o,e.setLineDash(u);let d=vo();if(d.prolog(e),$a(e,d.adjust(t),0,d.adjust(this.viewBox.y)),d.epilog(e),!a||!r.visible)return!0;let f=c_(n,l,P(r.format)?c:void 0);this.crosshairIndicator.draw(e,t,this.viewBox.y+1,f,void 0,this.viewBox.height-2);let{plotHover:p}=n.display.chart;return p&&n.allPlots.filter(e=>e.visible).forEach(n=>n.curves.forEach(n=>n.drawHover(e,l,t))),!0}},$k={mousedown:`onMouseDown`,mousemove:`onMouseMove`,mouseup:`onMouseUp`,dblclick:`onMouseDblClick`,contextmenu:`onContextMenu`,mouseover:`onMouseEnter`,mouseout:`onMouseLeave`,wheel:`onWheel`,touchstart:`onMouseDown`,touchmove:`onMouseMove`,touchend:`onMouseUp`,keydown:`onKeyDown`},eA={Shift:`shiftKey`,Alt:`altKey`,Control:`ctrlKey`,Meta:`metaKey`},tA=e=>e.startsWith(`touch`),nA=class{subscriptions=[];constructor(e){this.view=e}init(e){let t=Ie();Object.keys($k).filter(e=>!tA(e)||t).forEach(t=>{let n=e=>{let n=$k[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[eA[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])}}},rA=Ih.concat(W.PercentChange);function iA(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 aA(e,t){let n=iA(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 oA(e,t){return aA(e,t).flat().filter(t=>t!==e)}var sA=class{id;isOptionsChart=!1;constructor(e){this.view=e,this.id=`bc-legend-${bt()}`}getLegendElem(){let e=this.view.el;return wi(this.id,e,`div`)}update(){let e=this.getLegendElem(),t=R_(this.presenter.mainPane);if(!P(t))return;this.isOptionsChart=this.mainPlot?.title?.startsWith(z.FAKE_SYMBOL_PREFIX)??!1;let{left:n,right:r,top:i,width:a}=t;BD(e,`row`,n,r,i,a),Ti(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(){bi(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=rA.map(t=>e.getValue(t));if(k(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=rA[t],i=this.format(e,r),a=U_(r);return`${this.spanAsName(a)}${this.spanAsValue(i,n)}`}).join(` `)} ${this.spanAsValue(`(${this.format(xe(t),xe(rA))})`,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=F_(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(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 aA(this.mainPlot,e).map((e,t)=>{let n=e.map((e,t)=>{let n=this.getFirstColorBadge(e),r=this.getSeasonalFamilyTitle(e,t===0);return this.spanAsPlot(`${n} ${r}`)}).join(` `);return this.divAsGroup(n,t>0)}).join(` `)}getFirstColorBadge(e){return T_(`rectangle`,e.mainCurve.colors[0])}getLastValues(e){return this.isOptionsChart?``:Wk(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&&this.isOptionsChart}maybeGetAdditionalPlots(){let e=this.presenter.mainPane.axes.map(e=>e.plots).flat(),t=oA(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)?N_(e.uid):``,a=n!==`All`&&!e.isSeasonal?this.getLastValues(e):``;return this.div(`${i} ${t} ${r} ${a}`)}).join(` `):``}},cA=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 sA(this),this.draw=this.draw.bind(this),this.notifyLayoutChanged=qe(G.CH_CHTLAYOUTCHANGED,z.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)),Si(this.el,{flex:1,display:`flex`,position:`relative`,"flex-direction":`column`,"touch-action":`pan-x pan-y`}),this.tooltip=new LD(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=Ei(this.el,`div`),Ci(this.canvasContainer,{class:`chart-canvas-container`}),Si(this.canvasContainer,{flex:1,display:`flex`,"flex-direction":`column`,position:`relative`,height:`100%`}),this.mainCanvas=Ei(this.canvasContainer,`canvas`);let o={height:`${i}px`,width:`${a}px`,"z-index":2,position:`absolute`,top:0,left:0};Si(this.mainCanvas,o),this.mouseCanvas=Ei(this.canvasContainer,`canvas`),Ci(this.mouseCanvas,{tabIndex:0}),o[`z-index`]=3,o.outline=`none`,Si(this.mouseCanvas,o),this.goToLatestButton=Ei(this.el,`button`),Oi(this.goToLatestButton,`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
|
|
35
35
|
<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>
|
|
36
36
|
</svg>`),Si(this.goToLatestButton,{position:`absolute`,right:0,bottom:0,"z-index":3}),Ci(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 Qk(this),this.eventCapture=new nA(this),this.eventCapture.init(this.mouseCanvas),this.setChartSize(a,i);let s=vi(this.el);P(xi(`.${z.SVG_ICONS_DOM_NODE}`,s))||y_(s)}reinitialize(){this.el&&Di(`.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 Qk(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`};Si(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=>{Ci(e,i),Si(e,n)}),this.mainContext.scale(r,r),this.mouseContext.scale(r,r),this.recalculateLayout(),this.presenter&&RD(this.presenter)}widthNeeded(e,t){let n=this.presenter.allAxes.filter(e=>e.onTheRight===t&&e.plots.some(e=>e.visible&&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.height-e,i=this.presenter.panes,a=pe(i.map(e=>e.height)),o=0,s=z.PANE_SPLITTER_PERCENT_HEIGHT/100,c=Math.floor(s*r);a*=1+(i.length-1)*s;let l=this.presenter.display?.yAxis?.primaryOnTheLeft??!1;this.presenter.display.yAxis.visible&&(i.some(e=>e.axes.length>1)?(this.leftOffset=n,this.rightOffset=t):l?this.leftOffset=n:this.rightOffset=t),i.forEach((e,n,i)=>{let s=n===i.length-1,l=Math.floor(r*e.height/a),u=new za(0,o,this.width,l);e.setViewBox(u);let d=new za(this.width-this.rightOffset,o,t,l),f=new za(0,o,this.leftOffset,l),p=e=>e.setViewBox(e.onTheRight?d:f);if(p(e.axes[0]),e.axes[1]&&p(e.axes[1]),o+=l,!s){let e=new za(this.leftOffset,o,this.width-this.rightOffset-this.leftOffset,c);this.splitters.push(e),o+=c}});let u=new za(this.leftOffset,o,this.width-this.rightOffset-this.leftOffset,e);this.xAxis.setViewBox(u),Si(this.goToLatestButton,{right:`${t+5}px`,bottom:`${e+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=Oa(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=lA(e);Si(this.el,{cursor:t})}shutdown(){this.listeners.forEach(e=>e()),this.eventCapture&&this.eventCapture.shutdown(),this.tooltip&&this.tooltip.remove(),this.el&&Di(`.bcharts-card`,this.el).forEach(e=>e.remove()),this.canvasContainer.remove()}getEventRadius(){let e=this.xAxis.xScale.bar.width/2;return Math.max(e,z.MIN_EVENT_RADIUS)}};function lA(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 uA=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=Ei(this.view.el,`div`),Ci(this.popupElement,{id:`${this.view.presenter.elementId}-custom-event-host`}),Si(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=Ei(this.popupElement,`a`);Ci(e,{class:`custom-event-close-button`}),Si(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()),Si(this.popupElement,{visibility:`visible`,top:`${e.y}px`,left:`${e.x}px`,width:`310px`}),this.visible=!0}hideValue(){}hide(){this.visible&&=(this.hideValue(),Si(this.popupElement,{visibility:`hidden`}),!1)}};function dA(e,t){return H(e,`..axes[${t.axisIndex}]`,e=>(e.annotations=t.annotations,e))}function fA(e){return e.annotations&&e.annotations.length>0}function pA(e,t){fA(e)&&(t.annotations=(t.annotations||[]).concat(e.annotations))}var mA=`..axes{..plots{.type==="Study"}}`;function hA(e,t){let{mainAxis:n}=Ku(e),{mainAxis:r}=Ku(t);pA(n,r);let i=e=>V(e,`..plots{.type==="Study"}.study`)[0],a=V(e,mA).filter(e=>e!==n),o=V(t,mA).filter(e=>e!==r);return a.forEach(e=>{let t=i(e),n=o.find(e=>t===i(e));P(n)&&pA(e,n)}),t}function gA(e,t){let n=e=>`..panes[${e}]`,r=e;return t.paneHeights.forEach(e=>{r=H(r,n(e.index),t=>(t.height=e.relativeHeight,t))}),r}var _A={ok:!1,change:void 0,toApply:void 0},vA=class{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,lD(e,O.Moved)))}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)}apply(e,t,n){if(!P(e))return!1;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(e):this.add(e);break;case O.Deleted:n?this.add(e):this.delete(e);break;default:{let t={...e,id:`Update`};this.presenter.handleAnnotationChange(t);break}}let r=this.presenter.allAnnotations.find(t=>t.uid===e.uid),i=n?O.Undo:O.Redo;return P(r)&&this.presenter.onAnnotationModifiedByTool(r,i),!0}can(e){let t=e?this.undoStack:this.redoStack;if(t.length<1)return _A;let n=xe(t),r=n.toolChange;if(!(e&&r!==O.Deleted&&r!==O.Created))return{ok:!0,change:r,toApply:n};let i=Ce(t,e=>e.uid===n.uid,t.length-2),a=i===-1?null:t[i],o=a===null;return o&&!this.initial.has(n.uid)?_A:{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);if(!r)return;let o=e.pop();this.apply(a,i,n),t.push(o)}},yA=class{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 bA(e={}){let t=this.allPlots;if(!t.every(e=>P(e.timeSeries)&&e.timeSeries.hasData))return`No data to export`;let n=e.excludeHeader??!1,r=e.numDecimals??null,i=e.excludeFields??[],a=e=>{let t=new Map;return e.main&&(t.set(W.DateTime,0),this.data.aggregation.isMultiContract&&!e.isExpression&&t.set(W.Symbol,0)),e.curves.forEach(e=>{e.fields.forEach(n=>{i.includes(n.id)||t.set(n,e.shift)})}),Array.from(t)},o=e=>`"${C[e.type]}: ${e.title}"`,s=this.data.aggregation.isEndOfDay?z.FMT_ISO_DATE_ONLY:z.FMT_EXPORT_ALL_BUT_MILLIS,c=e=>P(r,e)?Xe(e,r):e,l=(e,t)=>e===W.DateTime?_r(t,s):c(t)?.toString()??``,u={},d=this.timeline.lastSeriesIndex,f=Se(this.mainPlot.timeSeries.container.getTimeData()),p=Te(this.timeline,+f,Number,h_),m=(e,t)=>{let n=this.timeline.at(e),r=t.timeSeries.container,i=r.getTimeData(),o=u[t.id]||0,c=Te(i,+n,Number,we,o),d=+n==+i[c];return d&&(u[t.id]=c),a(t).map(([t,a])=>{if(a===0)return d?l(t,r.getData(t)[c]):t===W.DateTime?_r(n,s):``;{let n=this.timeline.at(e-a),o=Te(i,+n,Number,we,0);return+n==+i[o]?l(t,r.getData(t)[o]):``}})},h=e=>{let n=t.map(e).flat();return n.slice(1).every(e=>e.length===0)?null:n.join(`,`)},g=[];n||(g.push(h(e=>{let t=Array(a(e).length).fill(``);return t[0]=o(e),t})),g.push(h(e=>a(e).map(([e,t])=>`"${e.name}"`))));let _=[0,0];this.allCurves.forEach(e=>{e.fields.every(e=>i.includes(e.id))||(e.shift<0&&(_[0]=Math.min(_[0],e.shift)),e.shift>0&&(_[1]=Math.max(_[1],e.shift)))});for(let e=p+_[0];e<=d+_[1];e++){let t=h(se(m,e));t!==null&&g.push(t)}return g.join(`
|
|
37
|
-
`)}function xA(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 yA(this);e.update(o),e.draw(c)}let u=this.mainPlot?.timeSeries.container?.getLastDataPoint(W.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:z.CARDS_X_OFFSET,y:z.CARDS_Y_OFFSET},d=I_(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)}var SA=Symbol.for(`__ias__`),CA=class{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;forceResetVisibleRange=!1;_maxOffset=0;_isShutdown=!1;notifySelectionChanged;notifyRecreated;notifyDefinitionChanged;constructor(e){this.accessor=e,this.defaultTool=gk(`Default`),this._activeTool=this.defaultTool,this.timeline=new g_(this),this.undoRedoManager=new vA(this),this.title=new yA(this),this.notifySelectionChanged=Ke(G.CH_ANNSELECTIONCHANGED),this.notifyRecreated=Ke(G.CH_RECREATED),this.notifyDefinitionChanged=Ke(G.CH_DEFINITION_CHANGED)}traceChart(e,t={}){zm(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.clearSelection(),this.model=e;let n=F(e);this.data=n.data,this.data.aggregation=Pl(n.data.aggregation),this.display=n.display,P(this.display.period)&&(this.display.period=vt(this.display.period)),this.panes=n.panes.map(e=>{let t=new Jk(this);return t.fromModel(e),t},this);let r=this.allPlots.map(e=>e.initialize());await Promise.all(r),this.traceChart(`chart:fromModel:plots-ready`,{plotCount:this.allPlots.length}),!this._isShutdown&&(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||OA(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 cA,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(G.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.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)}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===G.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===G.TS_EVENTSCHANGED,u=this.view.xAxis,d=u.xScale;if(e===G.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[SA]=!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=Te(this.timeline,c,Number,h_);u.shouldScrollIntoView(e)&&d.shiftBars(t.count)}this.timeline.invalidate(),this.allPlots.forEach(e=>e.invalidatePriceMappingCache()),o=!0}else if(e===G.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===G.TS_DATAPOINTCHANGED&&(s=!0,i.isStudy&&i.invalidateAssociatedAnnotations(`DataPointChanged`));if(!l&&r(this.mainPlot)&&n.hasData&&n.container.size===0&&this.notifyHost(G.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===G.TS_MANYCHANGED&&this.allPlots.every(e=>e.timeSeries&&e.timeSeries.hasData)){this.sentInitialLoadNotification=!0,this.notifyHost(G.CH_ALL_DATA_PROJECTED,{chart:this.accessor}),RD(this);let e=this.display.period===z.FIFTY_YEARS_MILLIS;this.mainPlot&&e&&(d.fitAllData=!0,d.adjustDomain())}this.view.redraw()}onMetaChanged(e,t){e===G.MD_CHANGED&&this.view&&this.allPlots&&this.allPlots.find(e=>e.id===t.plot.id)&&(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(G.CH_AXISSCALECHANGED,r)}get previousMask(){return P(this._previousMask)||(this._previousMask=Ud(W.PreviousClose)),this._previousMask}hasMatch(e,t){return e.some(e=>e.updated&&t)}get hasLegend(){return P(this._hasLegend)||(this._hasLegend=$().config.mode===ne[ne.cmdtyView]),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=Ud(W.Open,W.High,W.Low,W.Close,W.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(Pp(e=>e.filter(e=>this.updateMatches(e.updated,e.data.symbol))),Lp(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:xi(`#${e}`),!this._hostElement)throw Error(`There is no element ${e} in the DOM`);this.renderTo=e,this.seriesChangedToken=wv.default.subscribe(G.TS_ALL,this.onSeriesChanged.bind(this)),this.metaChangedToken=wv.default.subscribe(G.MD_ALL,this.onMetaChanged.bind(this)),this.streamingSubscription=this.getStreamingSubscription()}shutdown(){return wv.default.unsubscribe(this.seriesChangedToken),wv.default.unsubscribe(this.metaChangedToken),P(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.allPlots.forEach(e=>e.shutdown()),this.model=void 0,this.closeView(),this.notifyHost(G.CH_SHUTDOWN,{elementId:this.elementId}),this._isShutdown=!0,!0}setSelection(e){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=Ei(document.body,`iframe`);t.src=``,t.style.display=`none`,t.onload=()=>{let{title:n}=e,r=xA.call(this,{title:n}),i=new Image;i.src=r.data,i.style.width=`100%`,t.contentDocument.body.appendChild(i),ki(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===z.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===z.TOOLTIP_CARDS&&Di(`.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 V(this.model,`..annCache{.annotations}`).map(e=>({symbol:e.symbol,annotations:e.annotations.map(e=>t(e,!1))}));if(e.id===`Add`)return this.mainAxis.addAnnotation(e.annotation);let n=this.allAnnotations.find(t=>t.uid===e.uid);if(n!==void 0){let t=n.axis,r=t[`${e.id.toLowerCase()}Annotation`];if(typeof r==`function`){r.call(t,n,e),e.id===`Delete`&&!e.isUndoRedo&&this.onAnnotationModifiedByTool(n,O.Deleted);return}}throw Error(`Unknown sub-action ${e.id} for action ${z.ANN_ACTION_ID}`)}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:z.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(G.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(G.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(G.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(G.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(G.CH_PANESREORDERED,{chart:this.accessor})})}onAnnotationsUpdated(e,t=!1){let n=this.allAxes.indexOf(e),r=e.annotations.map(e=>e.toModel()),i=dA(this.model,{axisIndex:n,annotations:r});try{this.model=Pd(i,z.CHART_SCHEMA)}catch(e){I(`Cannot update annotation (corrupts definition), error is: ${e.message}`,`error`)}t&&this.view.draw(),this.notifyHost(G.CH_ANNOTATIONCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}onAnnotationModifiedByTool(e,t,n=!0){if(t!==O.None){if(n&&t!==O.Undo&&t!==O.Redo){let n=lD(e,t);this.undoRedoManager.done(n)}let r=uD(e);r.toolChange=O[t],this.notifyHost(G.CH_ANNMODIFIEDBYTOOL,r)}}onAnnotationDone(e,t){let n={id:e,chart:this.accessor,toolChange:O[t]};this.notifyHost(G.CH_ANNMODIFIEDBYTOOL,n)}onPaneHeightsUpdated(){let e=this.panes.map((e,t)=>({index:t,relativeHeight:e.height}));this.model=gA(this.model,{paneHeights:e}),this.notifyHost(G.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=Se(t),r=xe(t);return P(n,r)?{dataRange:{from:n.getTime(),to:r.getTime()},barCount:e.size}:null}};function wA(e,t){return e?.from===t?.from&&e?.to===t?.to}var TA=[`Renko`,`Range`,`LineBreak`,`Kagi`,`PointAndFigure`];function EA(e,t){for(let n of Object.keys(e))if(e[n]!==t[n])return!0}function DA(e,t){let n=e=>e.curves[0],r=n(e),i=n(t),a=TA.includes(r.style),o=TA.includes(i.style);return a===o?o?!!(r.style!==i.style||t.inputs&&EA(dt(e.inputs),dt(t.inputs))):!1:!0}function OA(e,t,n){let r={id:`Aggregation`,context:{id:`Get`}};if(EA(Nl(rM(r,t,n)),Nl(rM(r,e,n)))||!wA(e.display?.xAxis?.visibleRange,t.display?.xAxis?.visibleRange)||e.display?.xAxis?.marginBars!==t.display?.xAxis?.marginBars||!wA(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=Gu(t),a=Gu(e);if(DA(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 kA(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=H(e,`.display.xAxis.crosshair`,e=>(e.enabled=n,c(e,o,s),e));return l=H(l,`.display.yAxis.crosshair`,e=>(e.enabled=r,c(e,i,a),e)),P(t.haloTracking)&&typeof t.haloTracking==`boolean`&&(l=H(l,`.display.chart`,e=>(e.plotHover=t.haloTracking,e))),l}function AA(e,t){return H(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 jA(e,t){let n=F(t);return Object.keys(t).forEach(e=>{z.EVENTS.includes(e)||delete n[e];let r=t[e];typeof r==`boolean`?r={show:t[e]}:Object.keys(r).forEach(e=>{z.EVENT_PROPERTIES.includes(e)||delete r[e]}),n[e]=r}),H(e,Wu,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 MA(e,t){let n=H(e,`..panes{${Wu}}.axes`,e=>(N(t.scale)&&(e.scale=t.scale),e));n=H(n,`.display.xAxis`,e=>(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=H(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=H(n,`..panes[${a??0}]..axes[${i}]`,e=>P(e)?(e.label=r,e):z.NULL_OBJECT))}),N(t.contractTransition)&&(n=H(n,`.display.xAxis`,e=>(lt(e.contractTransition,t.contractTransition),e))),N(t.cycleTransition)&&(n=H(n,`.display.xAxis`,e=>(lt(e.cycleTransition,t.cycleTransition),e))),n}function NA(e,t,n){let r=e;if(P(t.comparisonMode)&&typeof t.comparisonMode==`string`&&nt(x,t.comparisonMode)&&(r=H(r,`..panes{${Wu}}.axes`,e=>(e.comparison=t.comparisonMode,e))),P(t.gridLines)){let[e,n]=Qe(t.gridLines);r=H(r,`.display.xAxis.gridLines`,t=>(t.visible=e,t)),r=H(r,`.display.yAxis.gridLines`,e=>(e.visible=n,e))}if(P(t.minorGridLines)){let[,e]=Qe(t.minorGridLines);r=H(r,`.display.yAxis.minorGridLines`,t=>(t.visible=e,t))}P(t.newPaneHeight)&&typeof t.newPaneHeight==`number`&&(r=H(r,`.display.chart{.newPaneHeight > 0}`,e=>(e.newPaneHeight=t.newPaneHeight,e))),P(t.showNavigator)&&typeof t.showNavigator==`boolean`&&(r=H(r,`.display.scrollbar`,e=>(e.visible=t.showNavigator,e))),P(t.plotHover)&&typeof t.plotHover==`boolean`&&(r=H(r,`.display.chart`,e=>(e.plotHover=t.plotHover,e))),P(t.showLastValue)&&typeof t.showLastValue==`string`&&(r=H(r,`.display.yAxis`,e=>(e.showLastValue=t.showLastValue,e))),P(t.showMinMaxArc)&&typeof t.showMinMaxArc==`boolean`&&(r=H(r,`.display.chart`,e=>(e.showMinMaxArc=t.showMinMaxArc,e))),P(t.showGoToLatest)&&typeof t.showGoToLatest==`boolean`&&(r=H(r,`.display.chart`,e=>(e.showGoToLatest=t.showGoToLatest,e))),P(t.showLegend)&&typeof t.showLegend==`boolean`&&(r=H(r,`.display.chart`,e=>(e.showLegend=t.showLegend,e)),t.showLegend||n.view.removeLegend()),P(t.allAnnotationsLocked)&&typeof t.allAnnotationsLocked==`boolean`&&(r=H(r,`.display`,e=>(e.allAnnotationsLocked=t.allAnnotationsLocked,e))),P(t.exprSkipLeadingEmpty)&&typeof t.exprSkipLeadingEmpty==`boolean`&&(r=H(r,`.data`,e=>(e.exprSkipLeadingEmpty=t.exprSkipLeadingEmpty,e)));let i=[];if(P(t.extendedHours)&&typeof t.extendedHours==`boolean`&&(r=H(r,`.data`,e=>(e.extendedHours=t.extendedHours,e))),P(t.realTimeCboeBzx)&&typeof t.realTimeCboeBzx==`boolean`&&(r=H(r,`.data`,e=>(e.realTimeCboeBzx!==t.realTimeCboeBzx&&i.push(`realTimeCboeBzx`),e.realTimeCboeBzx=t.realTimeCboeBzx,e))),P(t.buildContinuation)&&typeof t.buildContinuation==`boolean`&&(r=H(r,`.data`,e=>(e.buildContinuation=t.buildContinuation,e))),i.length>0){let e={chart:n.accessor,hostPropsChanged:i};n.notifyHost(G.CH_HOST_PROPS_CHANGED,e)}return r}var PA=`MARKED_FOR_DELETION`;function FA(e,t){if(t.plots.length===0)return e;let n=e;for(let e of t.plots){let t=WA(n,e);if(t===void 0)continue;let r=VA(t),i=HA(n,r);P(i)&&(P(e.type)&&i.type!==e.type||(n=H(n,r,e=>(e[PA]=!0,e))))}return n=H(n,`..plots{.${PA} === true}`,e=>z.NULL_OBJECT),n=H(n,`..plots{.type === "Study"}`,e=>{let t=B(e.study);return P(t)&&Uu(n,t,e.basis).eligible?e:z.NULL_OBJECT}),Fd(n)}function IA(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(z.DEFAULT_RENKO_INPUTS);break;case`Kagi`:n(z.DEFAULT_KAGI_INPUTS);break;case`PointAndFigure`:n(z.DEFAULT_PNF_INPUTS);break;case`LineBreak`:n(z.DEFAULT_LINEBREAK_INPUTS);break;case`Baseline`:n(z.DEFAULT_BASELINE_INPUTS);break}s(a,e,!0);break}case C.Study:{o(e,`inputs`);let r=B(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=W[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 LA(e,{main:t,type:n,index:r,uid:i},a){let o=`..plots{.main === true}`,s=V(e,`..panes`).map((e,t)=>{let n=V(e,o).length===1;return V(e,`..axes`).map((e,r)=>{let i=V(e,o).length===1;return V(e,`..plots`).map(e=>{let o=IA(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 RA=[`overlay`,`standalone`,`withMain`,`clone`];function zA(e,t,n){t[n]&&(e[n]=t[n])}function BA(e,t){e.type===`Study`&&t.curves?.forEach(e=>delete e.varyColorPerBar),KA(e)?P(t.curves)&&(e.curves=t.curves):ZA(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)),QA(e.inputs,t.inputs,e),[`bands`,`levels`,`detachedScale`].forEach(n=>zA(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),vl(n)}}var VA=e=>`..plots[${e}]`;function HA(e,t){let n=V(e,t);return n.length===1?n[0]:null}function UA(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 WA(e,t){return P(t.uid)?UA(e,t.uid):t.index}function GA(e){let t=C[e.type];return t===C.Symbol||t===C.Expression}function KA(e){let t=C[e.type];return t===C.Forward||t===C.Seasonal}function qA(e){let t=C[e.type];return t===C.Symbol||t===C.Expression||t===C.Seasonal}function JA(e,t,n){if(P(t))return t;let r=n?.uid;return typeof r==`string`?UA(e,r):void 0}function YA(e,t,n){if(P(t.placement)&&!RA.includes(t.placement))throw Error(`Unknown placement: ${t.placement}`);let r=WA(e,t),i=r===void 0?t.main?Wu:``:VA(r);if(!i)return e;let a=HA(e,i);if(!N(a)||N(t.type)&&a.type!==t.type)return e;let o=JA(e,r,a);if(t.type===C[C.Study]){let n=a,r=B(t.studyId??n.study);if(!N(r))return e;let i=P(t.basis)?t.basis:n.basis,o=Uu(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&&GA(a)){if(t.curves){let n=e=>e.curves[0].style===h[h.Range],[r,i]=[n(a),n(t)];r&&!i?e=rd(e,{unit:`Day`,size:1,spec:`None`}):!r&&i&&(e=rd(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=H(e,Wu,e=>(e.showPrevious=t.showPrevious,e)));let r=t.curves?ru(e,t):e;return P(t.oppositeScale)&&qA(a)&&P(o)&&(r=zu(r,o,+!!t.oppositeScale)),r}else{let s=H(e,i,e=>(BA(e,t),e));if(P(t.oppositeScale)&&qA(a)&&P(o)&&(s=zu(s,o,+!!t.oppositeScale)),!(t.type===C[C.Study]&&P(t.placement)))return s;let c=P(r)?r:t.index,l=LA(s,{...t,index:c},n).find(e=>e.index===c);if(!P(l))return e;if(t.placement===l.placement)return s;let u=HA(s,i);if(!P(u))return e;s=FA(s,{id:`Delete`,plots:[{uid:u.uid,type:t.type}]});let d=rj(s,t.placement,t.cloneIndex,t.cloneUid);return d!==null&&d.plots.push(u),s}}function XA(e){return e!==void 0}function ZA(e,t){if(XA(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 QA(e,t,n){let r=dt(e),i=dt(t);lt(r,i);let a=ft(i);a.length>0&&(n.inputs=a)}function $A(){return{plots:[]}}function ej(e){let t=e.display.chart.newPaneHeight??1;return{axes:[$A()],height:t}}function tj(e){let t=ej(e);return e.panes.push(t),t}function nj(e,t){let n=N(t.paneIndex)&&t.paneIndex<e.panes.length?e.panes[t.paneIndex]:tj(e),r=n.axes[0];return t.oppositeScale??!1?Cj(n,r):r}function rj(e,t,n,r,i){let a=null,{mainPane:o,mainAxis:s}=Ku(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?Cj(c.pane,c.axis):Cj(o,s);break;case`overlay`:a=c?.axis??s;break;case`standalone`:a=tj(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=LA(e,t).find(e=>e.type===C[C.Study]&&(t.uid?e.uid===t.uid:e.index===t.index));if(!n)break;a=V(e,`..panes[${n.paneIndex}]..axes[${n.axisIndex}]`)[0]}break}}return a}function ij(e,t){let n=B(t.studyId);if(!N(n))return I(`Unknown or unavailable study with the id '${t.studyId}'`,`error`),e;let r=Uu(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)&&Pu(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),BA(o,t);let s=rj(e,i,t.cloneIndex,t.cloneUid,t.basis);P(s)&&s.plots.push(o);let c=e.data.aggregation;return nd(e,c.unit===`Tick`&&c.spec===`None`)}function aj(e,t){e.panes.push({axes:[{plots:[t]}]})}function oj(e,t){let n=Gu(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)&&Pu(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[W[t.fundamentalId].category],visible:!0};return BA(a,t),aj(e,a),e}var sj=[{fields:[W.Close.id],colors:[`#888`],style:`Line`,lineWidth:2,varyColorPerBar:!1,visible:!0}];function cj(e){return e.type===`Symbol`}function lj(e,t){let n=Gu(e),r=F(cj(n)?n.curves:sj),i=t.uid??bt();P(t.uid)&&Pu(e,i);let a={uid:i,curves:r,expression:``,type:`Expression`,visible:!0};return BA(a,t),nj(e,t).plots.push(a),e}function uj(e,t){let n=t.uid??bt();P(t.uid)&&Pu(e,n);let r={uid:n,curves:F(sj),offsets:[0],seasonal:``,type:`Seasonal`,visible:!0,main:!1};return BA(r,t),nj(e,t).plots.push(r),e}var dj={attributes:[`OpenVsClose`],colors:[`#b63400`,`#007f3e`,`#1664db`],fields:[`Open`,`High`,`Low`,`Close`,`Change`],style:`Candlestick`,varyColorPerBar:!0,lineWidth:1};function fj(e,t){let n=Gu(e),r=$().getDefaultMultiFieldCurve(),i=P(r)?r:dj,a=n.curves?.length,o=a===t.curves.length&&a===1?(e=>F(e?n.curves:[i]))(cj(n)):t.curves,s=t.uid??bt();P(t.uid)&&Pu(e,s);let c={uid:s,curves:o,symbol:``,type:`Symbol`,visible:!0};return BA(c,t),nj(e,t).plots.push(c),e}function pj(e,t){switch(t.type){case`Study`:return ij(e,t);case`IncomeStatement`:case`BalanceSheet`:return oj(e,t);case`Expression`:return lj(e,t);case`Symbol`:return fj(e,t);case`Seasonal`:return uj(e,t);default:throw Error("Unexpected plot type '${type}', not supported currently")}}var mj=0,hj=z.AUTO_COLORS,gj=`Symbol`,_j=`Expression`,vj=`Seasonal`;function yj(e,t){let n={attributes:[],colors:hj.slice(mj,mj+1),fields:e?[W.Last.id]:[W.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,mj=(mj+1)%hj.length,r}function bj(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=gj,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 xj(e,t){let n=bj(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),Pu(e,t)}let{yes:a,no:o}=A(n,e=>e.oppositeScale??!1),{mainPane:s,mainAxis:c}=Ku(e);s.alignOnExpirations=t.alignOnExpirations||!1;let l=Cj(s,c),u=e=>![gj,_j,vj].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`;mj=0;let p=se(yj,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),Fd(e)}var Sj=`..plots{(.type === "Symbol" || .type === "Expression" || .type === "Seasonal") && .main !== true}`;function Cj(e,t){let n=e.axes.find(e=>e!==t);return P(n)||(n=$A(),e.axes.push(n)),n}function wj(e,t){let n=V(e,Sj),r=V(t,Sj),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}=Ku(t),{mainAxis:c}=Ku(e);return a.forEach(e=>{c.plots.includes(e)?s.plots.push(e):Cj(o,s).plots.push(e)}),t}function Tj(e,t){let n=e.panes;return n.splice(t.to,0,n.splice(t.from,1)[0]),e}var Ej=()=>z.NULL_OBJECT;function Dj(e){return H(e,`..axes.annotations`,Ej)}function Oj(e){return Fd(H(e,`..plots{.type === "Symbol" && .main !== true}`,Ej))}function kj(e,t){let n=F(e);if(t.strip.main){let e=Gu(n),t=e.type.toLowerCase();e[t]=z.PLACEHOLDER_SYMBOL_NAME}return t.strip.annotations&&(n=Dj(n)),t.strip.compare&&(n=Oj(n)),n=H(n,`.data`,e=>(e.range&&(delete e.range,e.checkRange=!0),e)),n}function Aj(e,t,n){let r=LA(e,{main:!0},n)[0],i=r.title===z.PLACEHOLDER_SYMBOL_NAME,a=r.type===`Symbol`,o=r.type===`Expression`,s=Su(r.title),c=[];return o&&!xu(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:V(e,Sj).map(e=>e.symbol),annotations:V(e,`..annotations`).map(e=>e.id),studies:LA(e,{type:`Study`},n).map(e=>e.title)}}function jj(e,t,n){let r=V(e,`..panes`).map((e,t)=>V(e,`..axes`).map((e,n)=>V(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]]:z.EMPTY_ARRAY:r}function Mj(e,t,n){let r=V(e,`..panes{${Wu}}.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,exprSkipLeadingEmpty:e.data?.exprSkipLeadingEmpty??!1,extendedHours:e.data?.extendedHours??!1,realTimeCboeBzx:e.data?.realTimeCboeBzx??!1,buildContinuation:e.data?.buildContinuation??!1}}function Nj(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=H(e,`.display.chart`,e=>(r&&(e.backgroundColor=r),l&&(e.fontSize=l),e))),i){let e=e=>(e.color=i,e);n=H(n,`.display.xAxis.gridLines`,e),n=H(n,`.display.yAxis.gridLines`,e),n=H(n,`.display.yAxis.minorGridLines`,e)}if(s){let e=e=>(e.dashStyle=s,e);n=H(n,`.display.xAxis.gridLines`,e),n=H(n,`.display.yAxis.gridLines`,e),n=H(n,`.display.yAxis.minorGridLines`,e)}if(a){let e=e=>(e.textColor=a,e);n=H(n,`.display.xAxis`,e),n=H(n,`.display.yAxis`,e)}if(o){let e=e=>(e.color=o,e);n=H(n,`.display.xAxis.crosshair`,e),n=H(n,`.display.yAxis.crosshair`,e)}if(u||d){let e=e=>t=>(t.fontSize=e,t);u&&(n=H(n,`.display.xAxis`,e(u))),d&&(n=H(n,`.display.yAxis`,e(d)))}return n}function Pj(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 Fj(e,t,n){let{mainAxis:r}=Ku(e),i=V(e,`.display.xAxis`)[0],a=V(e,`.display.yAxis`)[0];return{scale:r.scale,marginBars:i.marginBars??0,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 Ij(e,t,n){let r=t=>V(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 Lj(e,t,n){return F(e.data.aggregation)}function Rj(e,t){let n=V(e,Sj),{mainPane:r,mainAxis:i}=Ku(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 zj(e,t,n){let{paneIndex:r,annotations:i,studies:a}=t||{},o=`..panes${Number.isInteger(r)?`[${r}]`:``}`,s=e,c=e=>z.NULL_OBJECT;return i===!0&&(n.allAnnotations.forEach(e=>n.onAnnotationModifiedByTool(e,O.Deleted,!1)),s=H(s,`${o}..annotations`,c)),a===!0&&(s=H(s,`${o}..plots{.type=="Study"}`,c)),s=Fd(s),s}var Bj=`.display.chart.previous`;function Vj(e,t,n){return V(e,Bj)[0]}function Hj(e,t,n){return H(e,Bj,e=>(lt(e,t),e))}function Uj(e,t,n){let r=[],i=WA(e,t);if(i===void 0||HA(e,VA(i))?.type!==t.type)return r;let a=Iu(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 Wj(e,t,n){if(!Uj(e,t,n).includes(t.targetPane))return e;let r=WA(e,t);if(r===void 0)return e;let i=Iu(e,r);if(i===null)return e;let a=HA(e,VA(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,ej(e)),s=!1;break;case`ExistingBelow`:o++;break;case`NewBelow`:o++,s=!1,e.panes.splice(o,0,ej(e));break}let{mainPane:c}=Ku(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($A());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=Ru(e,i.pane);return p=Ru(p,o),Fd(p)}function Gj(e,t,n){return P(t.period)&&t.period&&(delete e.display.period,td(e),n&&(n.forceResetVisibleRange=!0)),e}function Kj(e,t,n){let r=[],i=WA(e,t);if(i===void 0)return r;let a=HA(e,VA(i));if(a?.type!==t.type)return r;let o=Iu(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 qj(e,t,n){if(!Kj(e,t,n).includes(t.targetAxis))return e;let r=WA(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 Bu(e,r)}return zu(e,r,i)}function Jj(e,t,n){let r=V(e,`.display.tooltip`)[0];return{visible:r.visible,mode:r.mode,showMainTitle:r.showMainTitle,mainTitle:r.mainTitle}}var Yj=`..plots{.type === "Seasonal" && .main === true}`,Xj=`..plots{.type === "Seasonal" && .main !== true}`,Zj=z.AUTO_COLORS;function Qj(e){return JSON.parse(JSON.stringify(e))}function $j(e,t){let n=V(e,Yj);if(n.length===0)return e;let r=n[0];if(!r.offsets||r.offsets.length===0)return e;let i=r.offsets,a=V(e,Xj);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,Qj(i))}):n.forEach((e,t)=>{let n=i[t];e&&P(n)&&r.set(n,Qj(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=Zj[t%Zj.length];return{...a?Qj(a):{},colors:[i],fields:[`Close`],style:`Line`,dashStyle:`Solid`,varyColorPerBar:!1,lineWidth:2}});e.offsets=[...i],e.curves=o}return Fd(e)}var eM={MainPlot:ed,Aggregation:{Update:rd,Get:Lj},Period:{Update:Jl,Delete:Gj},Crosshair:{Update:kA,Get:Ij},Tooltip:{Update:AA,Get:Jj},Events:jA,Scale:{Update:MA,Get:Fj},Other:{Update:NA,Get:Mj},Plot:{Add:pj,Get:LA,Delete:FA,Update:YA},Compare:{Update:xj,Get:Rj},Annotation:{Get:jj},MovePane:Tj,Template:kj,Outline:Aj,Theme:{Update:Nj,Get:Pj},Clear:zj,Previous:{Update:Hj,Get:Vj},MovePlot:{Update:Wj,Get:Uj},PinPlot:{Update:qj,Get:Kj},SeasonalOffsets:{Update:$j}};function tM(e){return typeof e==`function`}function nM(e,t){let n=eM[e];if(tM(n))return n;{let e=t===void 0?void 0:n[t];if(!tM(e)&&(e=n[z.DEFAULT_ACCESSOR_SUBACTION],!tM(e)))throw Error(`Invalid accesor id and/or sub id`);return e}}function rM(e,t,n){return nM(e.id,e.context.id)(t,e.context,n)}function iM(e){return{id:`MainPlot`,context:e}}var aM={id:`SeasonalOffsets`,context:{}};function oM(e){return Array.isArray(e)&&e.some(e=>e?.type===`Seasonal`)}function sM(e){let{id:t,context:n}=e;if(!P(n))return!1;if(t===`Compare`)return oM(n.plots);if(t!==z.ACTION_PLOT)return!1;let r=n.id;return r===`Add`||r===`Update`?n.type===`Seasonal`:r===z.ACTION_DELETE?oM(n.plots):!1}function cM(e){return e.some(sM)?e[e.length-1]?.id!==`SeasonalOffsets`:!1}var lM={keepOldAnnotations:!1,keepNewAnnotations:!0,keepOldCompare:!1,keepNewCompare:!0,keepOldAggregation:!1,keepNewBarWidth:!1},uM=Symbol.for(`__ias__`),dM=class{presenter;_model;constructor(e=!1){this.headless=e,this.presenter=e?null:new CA(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(iM(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)){Rc(e,t),Lc(e,t);let r=gk(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()}zoom(e){!this.headless&&typeof e==`boolean`&&(e?this.annotate(`ZoomIn`):this.presenter.defaultTool.resetView(this.presenter))}getDefaultTemplate(){return IM()}get model(){return(this.headless?this._model:this.presenter.getModel())||IM()}asTemplate(e={main:!0,annotations:!1,compare:!1}){return this.change({id:z.ACTION_TEMPLATE,context:{strip:e}})}change(...e){let t={chart:this,actions:e.filter(e=>!e[uM])};t.actions.length>0&&this.presenter?.notifyHost(G.CH_API_ACTIONS_RECEIVED,t);let n=$().config.validateInput,r=e.map(e=>n?Pd(e,z.ACCESSOR_SCHEMA):e);if(r.length===1){let e=r[0];if(e.id===z.ACTION_TEMPLATE||e.context.id===z.ACTION_GET)return rM(e,this.model,this.presenter);if(!this.headless&&e.id===z.ANN_ACTION_ID)return this.presenter.handleAnnotationChange(e.context)}let{yes:i,no:a}=A(r,e=>e.id===z.ACTION_PLOT&&P(e.context)&&e.context.id===z.ACTION_DELETE),o=F(this.model),s=F(this.model),c=a;i.length>0&&c.push({id:z.ACTION_PLOT,context:{id:z.ACTION_DELETE,plots:i.map(e=>e.context)}}),c.forEach(e=>{if(s=rM(e,s,this.presenter),!P(s))throw Error(`Forgot to return model from accessor`)}),cM(c)&&(s=rM(aM,s,this.presenter)),this.fromModel(s,o)}async fromModel(e,t){let n=Pd(e,z.CHART_SCHEMA);this.headless?this._model=n:await this.presenter?.fromModel(n,t)}async load(e,t){let n={...lM,...t},r=Pd(JSON.parse(e),z.CHART_SCHEMA),i=this.model,a=F(i);if(P(i)){if(r=qu(i,r,n.keepNewAnnotations),n.keepNewAnnotations||(r=Dj(r)),n.keepOldAnnotations&&(r=hA(i,r)),n.keepNewCompare||(r=Oj(r)),n.keepOldCompare&&(r=wj(i,r)),n.keepOldAggregation){let e={id:z.ACTION_AGGREGATION,context:i.data.aggregation},t=r.display.density;r=rM(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=IM();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=rM({id:`Theme`,context:{id:`Get`}},this.model,this.presenter),i=rM(iM(r),t,this.presenter);e&&(i=rM({id:`Theme`,context:n},i,this.presenter)),this.presenter?.fromModel(i)}}this.clearUndoRedo(),this.presenter?.notifyHost(G.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:bA.call(this.presenter,e)}exportImage(e={}){return this.headless?null:xA.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(G.CH_DIDBECOMEACTIVE,{chart:this})}};function fM(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 pM(){let e=globalThis.parent?.location?.hostname||``;return[``,`localhost`,`127.0.0.1`].includes(e)||fM(e)}function mM(){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 hM(e,t){return ot(t),`${e}/?${new URLSearchParams(t).toString()}`}var gM=`aHR0cHM6Ly9iYXJjaGFydHdpZGdldHMud2Vic29sLmJhcmNoYXJ0LmNvbQ==`,_M=`YXV0aGVudGljYXRlQ2hhcnRSZWZlcmVy`;function vM(e,t=``){return hM(atob(gM),{module:atob(_M),secret:t,referer:e})}function yM(e,t){return e+Math.random()*(t-e)}var bM=Function(atob(`Y29uc29sZS5sb2coIlBsZWFzZSBjb250YWN0IEJhcmNoYXJ0IGluIG9yZGVyIHRvIG9idGFpbiB0aGUgbGljZW5zZSBmb3IgdGhlIGNoYXJ0IGNvbXBvbmVudC4iKTsg`)),xM=Function(`f`,atob(`Zi5yZW1vdmVBbGxDaGFydHMoKTsg`)),SM=Function(`m`,atob(`cmV0dXJuIG0gPT09ICJJbnRlcm5hbEZlZWQiIHx8IG0gPT09ICJXaWRnZXQiIHx8IG0gPT09ICJGcmVlV2lkZ2V0IiB8fCBtID09PSAiRGVtb1NpdGUiOw==`)),CM=`YXV0aG9yaXplZA==`,wM=`ZGF0YS1lbmRwb2ludA==`,TM=`YWxsb3dDcmVkZW50aWFscw==`;async function EM(e,t){if(t&&!SM(e.mode))return;let n=!1,r=0,i=25;for(;!n&&r<5;){let t=pM()||e.mode===`FreeWidget`,a=t?e.apiKey:``;try{let i=vM(t?``:mM(),a),o=await fetch(i);if(!o.ok)r++;else{let t=await o.json(),r=t[atob(CM)];e.knownSite=r,r?(e.dataEndpoint=(t[atob(wM)]||``).replace(/\/$/g,``),e.allowCredentials=t[atob(TM)]):(e.dataEndpoint=``,e.allowCredentials=!1),n=!0;break}}catch{}r++,i*=2,await new Promise(e=>setTimeout(e,i))}(!n||!e.knownSite)&&DM()}function DM(){setTimeout(bM,yM(2e3,3e3)),setTimeout(()=>xM($()),yM(4e3,5e3))}var OM={major:2,minor:379,patch:0,prerelease:!1},kM={environment:`Browser`,validateInput:!1,throttleMillis:0,isAlt64:!0,defaultTemplate:`/${z.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,baseUrl:{instruments:`/proxies/instruments`,futures:`/proxies/futures`,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(SM(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 AM(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 jM=!1,MM=null;function NM(){let e=OM,t=e.prerelease?`-${e.prerelease.identifier}.${e.prerelease.ordinal}`:``;return`${e.major}.${e.minor}.${e.patch}${t}`}function PM(e){let t=e.extensions?.studyProvider;if(!P(t))return;let n=t.getFields(),r=t.getStudies(),i=F(ss(z.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)),Ad(z.CHART_SCHEMA,i),Bd(n),fs(r)}function FM(e,t={}){if(jM)throw Error(`You should only call initFeed once during page's lifetime`);jM=!0;let n=Object.assign(kM);return lt(n,t),N(n.logo)&&qD(n.logo,n.logoClickable??!1),PM(n),MM=new e(n),MM.version=NM(),I(`%cBarchart Chart version ${MM.version}`,`info`,`font-size: larger`),MM.cachesData&&(MM.subject?.subscribe(MM.onPerformInternalGc.bind(MM)),wv.default.subscribe(G.CH_ALL,MM.onChartChanged.bind(MM))),MM}function $(){return MM}function IM(){return F($()?.template)}function LM(){N(MM)&&(MM.shutdown(),jM=!1,MM=null)}function RM(){return new dM(!0)}function zM(e){let t=RM();return t.load(e),t.change({id:`Outline`,context:{id:`Get`}})}function BM(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 VM=class{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={}){zm(e,{feedId:this.id,isAuxiliary:this.isAuxiliary,...t})}get subject(){return!this.isAuxiliary&&!N(this._subject)&&(this.traceFeed(`gc:stream:init`,{gcMillis:z.INTERNAL_GC_MILLIS}),this._subject=new np().pipe(Rp(z.INTERNAL_GC_MILLIS),Lp(e=>e.length>0))),this._subject}get isAuxiliary(){return window.opener!==null}setAltDataSource(e){this._altDataSource=e,this.timeSeriesSource=BM(this.timeSeriesSource,`getTimeSeries`,e,`symbol`),this.metaDataSource=BM(this.metaDataSource,`getMetaData`,e),this.recordSource=BM(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 Ai.call(this,async()=>{let e=this instanceof KM||this instanceof HM||this instanceof YM;await EM(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=Pd(t,z.CHART_SCHEMA),!0})}getHeadlessChart(){return RM()}fixupRenderTo(e){if(!N(e))return null;if(e instanceof HTMLElement)return e;let t=xi(`#${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 dM;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(G.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===G.CH_RECREATED||e===G.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=Gu(this.template);e.curves.length===1&&Yl(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()}},HM=class extends VM{constructor(e){super(e),this.timeSeriesSource=new jg(!1),this.metaDataSource=new ca,this.recordSource=new Um}},UM=class extends VM{constructor(e){super(e),this.timeSeriesSource=new jg(!0),this.metaDataSource=new ca,this.recordSource=new Wm}},WM=class extends VM{constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new jg(!0),this.metaDataSource=new ca,this.recordSource=new Um}},GM=[`drazen.dotlic@barchart.com`,`princec`,`b.hebert24@barchart.com`],KM=class extends VM{lastStreamingTimestamp=null;_isActivelyStreaming=null;needToResubscribe=!1;_connection;constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new jg(!0),this.metaDataSource=new la,this.recordSource=new Gm,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&&GM.includes(this.connection._username)&&I(`[chart] Connection ${e}, last timestamp ${this.lastStreamingTimestamp}`)}onEvents({event:e}){e===z.BC_EVENT_DISCONNECTED||e===z.BC_EVENT_FEED_PAUSED?(this.debug(e),this.isActivelyStreaming=!1):(e===z.BC_EVENT_LOGGED_IN||e===z.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 qM(e,t){return new JM(e,t)}var JM=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)??[]}},YM=class extends VM{_adapter=null;_auxFeeds=[];constructor(e){super(e),this.cachesData=!0,this.isAuxiliary||(this.timeSeriesSource=new jg(!0),this.metaDataSource=new ua,this.recordSource=new Km,wv.default.subscribe(G.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)}},XM=wv.default;export{Vl as Aggregation,_ as AggregationSpec,g as AggregationUnit,HM as BarchartSiteDataFeed,VM as BaseDataFeed,Hm as BaseRecordSource,re as ChunkPart,Sg as ContainerWrapperTimeSeries,uA as CustomEventPopup,qd as EmptyRecord,u as ExpressionMissingBar,f as ExpressionNoDataApproach,d as ExpressionRecompute,Ev as ExpressionSeries,Ld as Field,b as FieldCategory,y as FieldFormat,v as FieldValueType,W as Fields,KM as MarketDataFeed,WM as MiniWidgetDataFeed,vh as OHLCDataPointBuilder,YM as OpenFeed,XM as PubSub,w as SeriesKind,UM as SnapshotDataFeed,q as StudySeries,bh as TimeSeriesContainer,Cv as TimeSeriesQuery,G as Topics,qM as adaptOpenFeedClient,Ei as appendDOMElement,Ai as asyncReady,X as convertSeries,Ou as doesExpressionHaveComputation,_s as doesStudyExist,Cu as evaluateExpression,Eu as formatExpression,Xi as formatPriceWithDecimals,bt as generateUid,hs as getAnnotationTraits,zM as getChartOutline,Zi as getCombinedMetaData,Du as getExpressionSymbols,$ as getFeed,Na as getLightness,bk as getStudyOptions,ws as getTaxonomies,si as hasOpenInterest,FM as initFeed,_E as linReg,Tv as makeExpression,K as makeHelperField,KT as makeStudy,Z as mapSeries,J as movAvg,Y as movExp,ZT as movHul,YT as movSmo,XT as movWei,dh as optionValueToDate,Su as parseExpression,ku as replaceExpressionSymbols,cE as roc,Ci as setAttributesDOMElement,LM as shutdownFeed,dE as stdDev,Si as styleDOMElement,rE as trueRange,sE as typical};
|
|
37
|
+
`)}function xA(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 yA(this);e.update(o),e.draw(c)}let u=this.mainPlot?.timeSeries.container?.getLastDataPoint(W.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:z.CARDS_X_OFFSET,y:z.CARDS_Y_OFFSET},d=I_(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)}var SA=Symbol.for(`__ias__`),CA=class{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;forceResetVisibleRange=!1;_maxOffset=0;_isShutdown=!1;notifySelectionChanged;notifyRecreated;notifyDefinitionChanged;constructor(e){this.accessor=e,this.defaultTool=gk(`Default`),this._activeTool=this.defaultTool,this.timeline=new g_(this),this.undoRedoManager=new vA(this),this.title=new yA(this),this.notifySelectionChanged=Ke(G.CH_ANNSELECTIONCHANGED),this.notifyRecreated=Ke(G.CH_RECREATED),this.notifyDefinitionChanged=Ke(G.CH_DEFINITION_CHANGED)}traceChart(e,t={}){zm(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.clearSelection(),this.model=e;let n=F(e);this.data=n.data,this.data.aggregation=Pl(n.data.aggregation),this.display=n.display,P(this.display.period)&&(this.display.period=vt(this.display.period)),this.panes=n.panes.map(e=>{let t=new Jk(this);return t.fromModel(e),t},this);let r=this.allPlots.map(e=>e.initialize());await Promise.all(r),this.traceChart(`chart:fromModel:plots-ready`,{plotCount:this.allPlots.length}),!this._isShutdown&&(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||OA(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 cA,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(G.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.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)}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===G.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===G.TS_EVENTSCHANGED,u=this.view.xAxis,d=u.xScale;if(e===G.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[SA]=!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=Te(this.timeline,c,Number,h_);u.shouldScrollIntoView(e)&&d.shiftBars(t.count)}this.timeline.invalidate(),this.allPlots.forEach(e=>e.invalidatePriceMappingCache()),o=!0}else if(e===G.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===G.TS_DATAPOINTCHANGED&&(s=!0,i.isStudy&&i.invalidateAssociatedAnnotations(`DataPointChanged`));if(!l&&r(this.mainPlot)&&n.hasData&&n.container.size===0&&this.notifyHost(G.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===G.TS_MANYCHANGED&&this.allPlots.every(e=>e.timeSeries&&e.timeSeries.hasData)){this.sentInitialLoadNotification=!0,this.notifyHost(G.CH_ALL_DATA_PROJECTED,{chart:this.accessor}),RD(this);let e=this.display.period===z.FIFTY_YEARS_MILLIS;this.mainPlot&&e&&(d.fitAllData=!0,d.adjustDomain())}this.view.redraw()}onMetaChanged(e,t){e===G.MD_CHANGED&&this.view&&this.allPlots&&this.allPlots.find(e=>e.id===t.plot.id)&&(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(G.CH_AXISSCALECHANGED,r)}get previousMask(){return P(this._previousMask)||(this._previousMask=Ud(W.PreviousClose)),this._previousMask}hasMatch(e,t){return e.some(e=>e.updated&&t)}get hasLegend(){return P(this._hasLegend)||(this._hasLegend=$().config.mode===ne[ne.cmdtyView]),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=Ud(W.Open,W.High,W.Low,W.Close,W.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(Pp(e=>e.filter(e=>this.updateMatches(e.updated,e.data.symbol))),Lp(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:xi(`#${e}`),!this._hostElement)throw Error(`There is no element ${e} in the DOM`);this.renderTo=e,this.seriesChangedToken=wv.default.subscribe(G.TS_ALL,this.onSeriesChanged.bind(this)),this.metaChangedToken=wv.default.subscribe(G.MD_ALL,this.onMetaChanged.bind(this)),this.streamingSubscription=this.getStreamingSubscription()}shutdown(){return wv.default.unsubscribe(this.seriesChangedToken),wv.default.unsubscribe(this.metaChangedToken),P(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.allPlots.forEach(e=>e.shutdown()),this.model=void 0,this.closeView(),this.notifyHost(G.CH_SHUTDOWN,{elementId:this.elementId}),this._isShutdown=!0,!0}setSelection(e){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=Ei(document.body,`iframe`);t.src=``,t.style.display=`none`,t.onload=()=>{let{title:n}=e,r=xA.call(this,{title:n}),i=new Image;i.src=r.data,i.style.width=`100%`,t.contentDocument.body.appendChild(i),ki(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===z.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===z.TOOLTIP_CARDS&&Di(`.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 V(this.model,`..annCache{.annotations}`).map(e=>({symbol:e.symbol,annotations:e.annotations.map(e=>t(e,!1))}));if(e.id===`Add`)return this.mainAxis.addAnnotation(e.annotation);let n=this.allAnnotations.find(t=>t.uid===e.uid);if(n!==void 0){let t=n.axis,r=t[`${e.id.toLowerCase()}Annotation`];if(typeof r==`function`){r.call(t,n,e),e.id===`Delete`&&!e.isUndoRedo&&this.onAnnotationModifiedByTool(n,O.Deleted);return}}throw Error(`Unknown sub-action ${e.id} for action ${z.ANN_ACTION_ID}`)}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:z.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(G.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(G.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(G.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(G.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(G.CH_PANESREORDERED,{chart:this.accessor})})}onAnnotationsUpdated(e,t=!1){let n=this.allAxes.indexOf(e),r=e.annotations.map(e=>e.toModel()),i=dA(this.model,{axisIndex:n,annotations:r});try{this.model=Pd(i,z.CHART_SCHEMA)}catch(e){I(`Cannot update annotation (corrupts definition), error is: ${e.message}`,`error`)}t&&this.view.draw(),this.notifyHost(G.CH_ANNOTATIONCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}onAnnotationModifiedByTool(e,t,n=!0){if(t!==O.None){if(n&&t!==O.Undo&&t!==O.Redo){let n=lD(e,t);this.undoRedoManager.done(n)}let r=uD(e);r.toolChange=O[t],this.notifyHost(G.CH_ANNMODIFIEDBYTOOL,r)}}onAnnotationDone(e,t){let n={id:e,chart:this.accessor,toolChange:O[t]};this.notifyHost(G.CH_ANNMODIFIEDBYTOOL,n)}onPaneHeightsUpdated(){let e=this.panes.map((e,t)=>({index:t,relativeHeight:e.height}));this.model=gA(this.model,{paneHeights:e}),this.notifyHost(G.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=Se(t),r=xe(t);return P(n,r)?{dataRange:{from:n.getTime(),to:r.getTime()},barCount:e.size}:null}};function wA(e,t){return e?.from===t?.from&&e?.to===t?.to}var TA=[`Renko`,`Range`,`LineBreak`,`Kagi`,`PointAndFigure`];function EA(e,t){for(let n of Object.keys(e))if(e[n]!==t[n])return!0}function DA(e,t){let n=e=>e.curves[0],r=n(e),i=n(t),a=TA.includes(r.style),o=TA.includes(i.style);return a===o?o?!!(r.style!==i.style||t.inputs&&EA(dt(e.inputs),dt(t.inputs))):!1:!0}function OA(e,t,n){let r={id:`Aggregation`,context:{id:`Get`}};if(EA(Nl(rM(r,t,n)),Nl(rM(r,e,n)))||!wA(e.display?.xAxis?.visibleRange,t.display?.xAxis?.visibleRange)||e.display?.xAxis?.marginBars!==t.display?.xAxis?.marginBars||!wA(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=Gu(t),a=Gu(e);if(DA(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 kA(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=H(e,`.display.xAxis.crosshair`,e=>(e.enabled=n,c(e,o,s),e));return l=H(l,`.display.yAxis.crosshair`,e=>(e.enabled=r,c(e,i,a),e)),P(t.haloTracking)&&typeof t.haloTracking==`boolean`&&(l=H(l,`.display.chart`,e=>(e.plotHover=t.haloTracking,e))),l}function AA(e,t){return H(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 jA(e,t){let n=F(t);return Object.keys(t).forEach(e=>{z.EVENTS.includes(e)||delete n[e];let r=t[e];typeof r==`boolean`?r={show:t[e]}:Object.keys(r).forEach(e=>{z.EVENT_PROPERTIES.includes(e)||delete r[e]}),n[e]=r}),H(e,Wu,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 MA(e,t){let n=H(e,`..panes{${Wu}}.axes`,e=>(N(t.scale)&&(e.scale=t.scale),e));n=H(n,`.display.xAxis`,e=>(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=H(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=H(n,`..panes[${a??0}]..axes[${i}]`,e=>P(e)?(e.label=r,e):z.NULL_OBJECT))}),N(t.contractTransition)&&(n=H(n,`.display.xAxis`,e=>(lt(e.contractTransition,t.contractTransition),e))),N(t.cycleTransition)&&(n=H(n,`.display.xAxis`,e=>(lt(e.cycleTransition,t.cycleTransition),e))),n}function NA(e,t,n){let r=e;if(P(t.comparisonMode)&&typeof t.comparisonMode==`string`&&nt(x,t.comparisonMode)&&(r=H(r,`..panes{${Wu}}.axes`,e=>(e.comparison=t.comparisonMode,e))),P(t.gridLines)){let[e,n]=Qe(t.gridLines);r=H(r,`.display.xAxis.gridLines`,t=>(t.visible=e,t)),r=H(r,`.display.yAxis.gridLines`,e=>(e.visible=n,e))}if(P(t.minorGridLines)){let[,e]=Qe(t.minorGridLines);r=H(r,`.display.yAxis.minorGridLines`,t=>(t.visible=e,t))}P(t.newPaneHeight)&&typeof t.newPaneHeight==`number`&&(r=H(r,`.display.chart{.newPaneHeight > 0}`,e=>(e.newPaneHeight=t.newPaneHeight,e))),P(t.showNavigator)&&typeof t.showNavigator==`boolean`&&(r=H(r,`.display.scrollbar`,e=>(e.visible=t.showNavigator,e))),P(t.plotHover)&&typeof t.plotHover==`boolean`&&(r=H(r,`.display.chart`,e=>(e.plotHover=t.plotHover,e))),P(t.showLastValue)&&typeof t.showLastValue==`string`&&(r=H(r,`.display.yAxis`,e=>(e.showLastValue=t.showLastValue,e))),P(t.showMinMaxArc)&&typeof t.showMinMaxArc==`boolean`&&(r=H(r,`.display.chart`,e=>(e.showMinMaxArc=t.showMinMaxArc,e))),P(t.showGoToLatest)&&typeof t.showGoToLatest==`boolean`&&(r=H(r,`.display.chart`,e=>(e.showGoToLatest=t.showGoToLatest,e))),P(t.showLegend)&&typeof t.showLegend==`boolean`&&(r=H(r,`.display.chart`,e=>(e.showLegend=t.showLegend,e)),t.showLegend||n.view.removeLegend()),P(t.allAnnotationsLocked)&&typeof t.allAnnotationsLocked==`boolean`&&(r=H(r,`.display`,e=>(e.allAnnotationsLocked=t.allAnnotationsLocked,e))),P(t.exprSkipLeadingEmpty)&&typeof t.exprSkipLeadingEmpty==`boolean`&&(r=H(r,`.data`,e=>(e.exprSkipLeadingEmpty=t.exprSkipLeadingEmpty,e)));let i=[];if(P(t.extendedHours)&&typeof t.extendedHours==`boolean`&&(r=H(r,`.data`,e=>(e.extendedHours=t.extendedHours,e))),P(t.realTimeCboeBzx)&&typeof t.realTimeCboeBzx==`boolean`&&(r=H(r,`.data`,e=>(e.realTimeCboeBzx!==t.realTimeCboeBzx&&i.push(`realTimeCboeBzx`),e.realTimeCboeBzx=t.realTimeCboeBzx,e))),P(t.buildContinuation)&&typeof t.buildContinuation==`boolean`&&(r=H(r,`.data`,e=>(e.buildContinuation=t.buildContinuation,e))),i.length>0){let e={chart:n.accessor,hostPropsChanged:i};n.notifyHost(G.CH_HOST_PROPS_CHANGED,e)}return r}var PA=`MARKED_FOR_DELETION`;function FA(e,t){if(t.plots.length===0)return e;let n=e;for(let e of t.plots){let t=WA(n,e);if(t===void 0)continue;let r=VA(t),i=HA(n,r);P(i)&&(P(e.type)&&i.type!==e.type||(n=H(n,r,e=>(e[PA]=!0,e))))}return n=H(n,`..plots{.${PA} === true}`,e=>z.NULL_OBJECT),n=H(n,`..plots{.type === "Study"}`,e=>{let t=B(e.study);return P(t)&&Uu(n,t,e.basis).eligible?e:z.NULL_OBJECT}),Fd(n)}function IA(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(z.DEFAULT_RENKO_INPUTS);break;case`Kagi`:n(z.DEFAULT_KAGI_INPUTS);break;case`PointAndFigure`:n(z.DEFAULT_PNF_INPUTS);break;case`LineBreak`:n(z.DEFAULT_LINEBREAK_INPUTS);break;case`Baseline`:n(z.DEFAULT_BASELINE_INPUTS);break}s(a,e,!0);break}case C.Study:{o(e,`inputs`);let r=B(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=W[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 LA(e,{main:t,type:n,index:r,uid:i},a){let o=`..plots{.main === true}`,s=V(e,`..panes`).map((e,t)=>{let n=V(e,o).length===1;return V(e,`..axes`).map((e,r)=>{let i=V(e,o).length===1;return V(e,`..plots`).map(e=>{let o=IA(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 RA=[`overlay`,`standalone`,`withMain`,`clone`];function zA(e,t,n){t[n]&&(e[n]=t[n])}function BA(e,t){e.type===`Study`&&t.curves?.forEach(e=>delete e.varyColorPerBar),KA(e)?P(t.curves)&&(e.curves=t.curves):ZA(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)),QA(e.inputs,t.inputs,e),[`bands`,`levels`,`detachedScale`].forEach(n=>zA(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),vl(n)}}var VA=e=>`..plots[${e}]`;function HA(e,t){let n=V(e,t);return n.length===1?n[0]:null}function UA(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 WA(e,t){return P(t.uid)?UA(e,t.uid):t.index}function GA(e){let t=C[e.type];return t===C.Symbol||t===C.Expression}function KA(e){let t=C[e.type];return t===C.Forward||t===C.Seasonal}function qA(e){let t=C[e.type];return t===C.Symbol||t===C.Expression||t===C.Seasonal}function JA(e,t,n){if(P(t))return t;let r=n?.uid;return typeof r==`string`?UA(e,r):void 0}function YA(e,t,n){if(P(t.placement)&&!RA.includes(t.placement))throw Error(`Unknown placement: ${t.placement}`);let r=WA(e,t),i=r===void 0?t.main?Wu:``:VA(r);if(!i)return e;let a=HA(e,i);if(!N(a)||N(t.type)&&a.type!==t.type)return e;let o=JA(e,r,a);if(t.type===C[C.Study]){let n=a,r=B(t.studyId??n.study);if(!N(r))return e;let i=P(t.basis)?t.basis:n.basis,o=Uu(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&&GA(a)){if(t.curves){let n=e=>e.curves[0].style===h[h.Range],[r,i]=[n(a),n(t)];r&&!i?e=rd(e,{unit:`Day`,size:1,spec:`None`}):!r&&i&&(e=rd(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=H(e,Wu,e=>(e.showPrevious=t.showPrevious,e)));let r=t.curves?ru(e,t):e;return P(t.oppositeScale)&&qA(a)&&P(o)&&(r=zu(r,o,+!!t.oppositeScale)),r}else{let s=H(e,i,e=>(BA(e,t),e));if(P(t.oppositeScale)&&qA(a)&&P(o)&&(s=zu(s,o,+!!t.oppositeScale)),!(t.type===C[C.Study]&&P(t.placement)))return s;let c=P(r)?r:t.index,l=LA(s,{...t,index:c},n).find(e=>e.index===c);if(!P(l))return e;if(t.placement===l.placement)return s;let u=HA(s,i);if(!P(u))return e;s=FA(s,{id:`Delete`,plots:[{uid:u.uid,type:t.type}]});let d=rj(s,t.placement,t.cloneIndex,t.cloneUid);return d!==null&&d.plots.push(u),s}}function XA(e){return e!==void 0}function ZA(e,t){if(XA(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 QA(e,t,n){let r=dt(e),i=dt(t);lt(r,i);let a=ft(i);a.length>0&&(n.inputs=a)}function $A(){return{plots:[]}}function ej(e){let t=e.display.chart.newPaneHeight??1;return{axes:[$A()],height:t}}function tj(e){let t=ej(e);return e.panes.push(t),t}function nj(e,t){let n=N(t.paneIndex)&&t.paneIndex<e.panes.length?e.panes[t.paneIndex]:tj(e),r=n.axes[0];return t.oppositeScale??!1?Cj(n,r):r}function rj(e,t,n,r,i){let a=null,{mainPane:o,mainAxis:s}=Ku(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?Cj(c.pane,c.axis):Cj(o,s);break;case`overlay`:a=c?.axis??s;break;case`standalone`:a=tj(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=LA(e,t).find(e=>e.type===C[C.Study]&&(t.uid?e.uid===t.uid:e.index===t.index));if(!n)break;a=V(e,`..panes[${n.paneIndex}]..axes[${n.axisIndex}]`)[0]}break}}return a}function ij(e,t){let n=B(t.studyId);if(!N(n))return I(`Unknown or unavailable study with the id '${t.studyId}'`,`error`),e;let r=Uu(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)&&Pu(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),BA(o,t);let s=rj(e,i,t.cloneIndex,t.cloneUid,t.basis);P(s)&&s.plots.push(o);let c=e.data.aggregation;return nd(e,c.unit===`Tick`&&c.spec===`None`)}function aj(e,t){e.panes.push({axes:[{plots:[t]}]})}function oj(e,t){let n=Gu(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)&&Pu(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[W[t.fundamentalId].category],visible:!0};return BA(a,t),aj(e,a),e}var sj=[{fields:[W.Close.id],colors:[`#888`],style:`Line`,lineWidth:2,varyColorPerBar:!1,visible:!0}];function cj(e){return e.type===`Symbol`}function lj(e,t){let n=Gu(e),r=F(cj(n)?n.curves:sj),i=t.uid??bt();P(t.uid)&&Pu(e,i);let a={uid:i,curves:r,expression:``,type:`Expression`,visible:!0};return BA(a,t),nj(e,t).plots.push(a),e}function uj(e,t){let n=t.uid??bt();P(t.uid)&&Pu(e,n);let r={uid:n,curves:F(sj),offsets:[0],seasonal:``,type:`Seasonal`,visible:!0,main:!1};return BA(r,t),nj(e,t).plots.push(r),e}var dj={attributes:[`OpenVsClose`],colors:[`#b63400`,`#007f3e`,`#1664db`],fields:[`Open`,`High`,`Low`,`Close`,`Change`],style:`Candlestick`,varyColorPerBar:!0,lineWidth:1};function fj(e,t){let n=Gu(e),r=$().getDefaultMultiFieldCurve(),i=P(r)?r:dj,a=n.curves?.length,o=a===t.curves.length&&a===1?(e=>F(e?n.curves:[i]))(cj(n)):t.curves,s=t.uid??bt();P(t.uid)&&Pu(e,s);let c={uid:s,curves:o,symbol:``,type:`Symbol`,visible:!0};return BA(c,t),nj(e,t).plots.push(c),e}function pj(e,t){switch(t.type){case`Study`:return ij(e,t);case`IncomeStatement`:case`BalanceSheet`:return oj(e,t);case`Expression`:return lj(e,t);case`Symbol`:return fj(e,t);case`Seasonal`:return uj(e,t);default:throw Error("Unexpected plot type '${type}', not supported currently")}}var mj=0,hj=z.AUTO_COLORS,gj=`Symbol`,_j=`Expression`,vj=`Seasonal`;function yj(e,t){let n={attributes:[],colors:hj.slice(mj,mj+1),fields:e?[W.Last.id]:[W.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,mj=(mj+1)%hj.length,r}function bj(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=gj,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 xj(e,t){let n=bj(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),Pu(e,t)}let{yes:a,no:o}=A(n,e=>e.oppositeScale??!1),{mainPane:s,mainAxis:c}=Ku(e);s.alignOnExpirations=t.alignOnExpirations||!1;let l=Cj(s,c),u=e=>![gj,_j,vj].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`;mj=0;let p=se(yj,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),Fd(e)}var Sj=`..plots{(.type === "Symbol" || .type === "Expression" || .type === "Seasonal") && .main !== true}`;function Cj(e,t){let n=e.axes.find(e=>e!==t);return P(n)||(n=$A(),e.axes.push(n)),n}function wj(e,t){let n=V(e,Sj),r=V(t,Sj),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}=Ku(t),{mainAxis:c}=Ku(e);return a.forEach(e=>{c.plots.includes(e)?s.plots.push(e):Cj(o,s).plots.push(e)}),t}function Tj(e,t){let n=e.panes;return n.splice(t.to,0,n.splice(t.from,1)[0]),e}var Ej=()=>z.NULL_OBJECT;function Dj(e){return H(e,`..axes.annotations`,Ej)}function Oj(e){return Fd(H(e,`..plots{.type === "Symbol" && .main !== true}`,Ej))}function kj(e,t){let n=F(e);if(t.strip.main){let e=Gu(n),t=e.type.toLowerCase();e[t]=z.PLACEHOLDER_SYMBOL_NAME}return t.strip.annotations&&(n=Dj(n)),t.strip.compare&&(n=Oj(n)),n=H(n,`.data`,e=>(e.range&&(delete e.range,e.checkRange=!0),e)),n}function Aj(e,t,n){let r=LA(e,{main:!0},n)[0],i=r.title===z.PLACEHOLDER_SYMBOL_NAME,a=r.type===`Symbol`,o=r.type===`Expression`,s=Su(r.title),c=[];return o&&!xu(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:V(e,Sj).map(e=>e.symbol),annotations:V(e,`..annotations`).map(e=>e.id),studies:LA(e,{type:`Study`},n).map(e=>e.title)}}function jj(e,t,n){let r=V(e,`..panes`).map((e,t)=>V(e,`..axes`).map((e,n)=>V(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]]:z.EMPTY_ARRAY:r}function Mj(e,t,n){let r=V(e,`..panes{${Wu}}.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,exprSkipLeadingEmpty:e.data?.exprSkipLeadingEmpty??!1,extendedHours:e.data?.extendedHours??!1,realTimeCboeBzx:e.data?.realTimeCboeBzx??!1,buildContinuation:e.data?.buildContinuation??!1}}function Nj(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=H(e,`.display.chart`,e=>(r&&(e.backgroundColor=r),l&&(e.fontSize=l),e))),i){let e=e=>(e.color=i,e);n=H(n,`.display.xAxis.gridLines`,e),n=H(n,`.display.yAxis.gridLines`,e),n=H(n,`.display.yAxis.minorGridLines`,e)}if(s){let e=e=>(e.dashStyle=s,e);n=H(n,`.display.xAxis.gridLines`,e),n=H(n,`.display.yAxis.gridLines`,e),n=H(n,`.display.yAxis.minorGridLines`,e)}if(a){let e=e=>(e.textColor=a,e);n=H(n,`.display.xAxis`,e),n=H(n,`.display.yAxis`,e)}if(o){let e=e=>(e.color=o,e);n=H(n,`.display.xAxis.crosshair`,e),n=H(n,`.display.yAxis.crosshair`,e)}if(u||d){let e=e=>t=>(t.fontSize=e,t);u&&(n=H(n,`.display.xAxis`,e(u))),d&&(n=H(n,`.display.yAxis`,e(d)))}return n}function Pj(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 Fj(e,t,n){let{mainAxis:r}=Ku(e),i=V(e,`.display.xAxis`)[0],a=V(e,`.display.yAxis`)[0];return{scale:r.scale,marginBars:i.marginBars??0,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 Ij(e,t,n){let r=t=>V(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 Lj(e,t,n){return F(e.data.aggregation)}function Rj(e,t){let n=V(e,Sj),{mainPane:r,mainAxis:i}=Ku(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 zj(e,t,n){let{paneIndex:r,annotations:i,studies:a}=t||{},o=`..panes${Number.isInteger(r)?`[${r}]`:``}`,s=e,c=e=>z.NULL_OBJECT;return i===!0&&(n.allAnnotations.forEach(e=>n.onAnnotationModifiedByTool(e,O.Deleted,!1)),s=H(s,`${o}..annotations`,c)),a===!0&&(s=H(s,`${o}..plots{.type=="Study"}`,c)),s=Fd(s),s}var Bj=`.display.chart.previous`;function Vj(e,t,n){return V(e,Bj)[0]}function Hj(e,t,n){return H(e,Bj,e=>(lt(e,t),e))}function Uj(e,t,n){let r=[],i=WA(e,t);if(i===void 0||HA(e,VA(i))?.type!==t.type)return r;let a=Iu(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 Wj(e,t,n){if(!Uj(e,t,n).includes(t.targetPane))return e;let r=WA(e,t);if(r===void 0)return e;let i=Iu(e,r);if(i===null)return e;let a=HA(e,VA(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,ej(e)),s=!1;break;case`ExistingBelow`:o++;break;case`NewBelow`:o++,s=!1,e.panes.splice(o,0,ej(e));break}let{mainPane:c}=Ku(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($A());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=Ru(e,i.pane);return p=Ru(p,o),Fd(p)}function Gj(e,t,n){return P(t.period)&&t.period&&(delete e.display.period,td(e),n&&(n.forceResetVisibleRange=!0)),e}function Kj(e,t,n){let r=[],i=WA(e,t);if(i===void 0)return r;let a=HA(e,VA(i));if(a?.type!==t.type)return r;let o=Iu(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 qj(e,t,n){if(!Kj(e,t,n).includes(t.targetAxis))return e;let r=WA(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 Bu(e,r)}return zu(e,r,i)}function Jj(e,t,n){let r=V(e,`.display.tooltip`)[0];return{visible:r.visible,mode:r.mode,showMainTitle:r.showMainTitle,mainTitle:r.mainTitle}}var Yj=`..plots{.type === "Seasonal" && .main === true}`,Xj=`..plots{.type === "Seasonal" && .main !== true}`,Zj=z.AUTO_COLORS;function Qj(e){return JSON.parse(JSON.stringify(e))}function $j(e,t){let n=V(e,Yj);if(n.length===0)return e;let r=n[0];if(!r.offsets||r.offsets.length===0)return e;let i=r.offsets,a=V(e,Xj);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,Qj(i))}):n.forEach((e,t)=>{let n=i[t];e&&P(n)&&r.set(n,Qj(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=Zj[t%Zj.length];return{...a?Qj(a):{},colors:[i],fields:[`Close`],style:`Line`,dashStyle:`Solid`,varyColorPerBar:!1,lineWidth:2}});e.offsets=[...i],e.curves=o}return Fd(e)}var eM={MainPlot:ed,Aggregation:{Update:rd,Get:Lj},Period:{Update:Jl,Delete:Gj},Crosshair:{Update:kA,Get:Ij},Tooltip:{Update:AA,Get:Jj},Events:jA,Scale:{Update:MA,Get:Fj},Other:{Update:NA,Get:Mj},Plot:{Add:pj,Get:LA,Delete:FA,Update:YA},Compare:{Update:xj,Get:Rj},Annotation:{Get:jj},MovePane:Tj,Template:kj,Outline:Aj,Theme:{Update:Nj,Get:Pj},Clear:zj,Previous:{Update:Hj,Get:Vj},MovePlot:{Update:Wj,Get:Uj},PinPlot:{Update:qj,Get:Kj},SeasonalOffsets:{Update:$j}};function tM(e){return typeof e==`function`}function nM(e,t){let n=eM[e];if(tM(n))return n;{let e=t===void 0?void 0:n[t];if(!tM(e)&&(e=n[z.DEFAULT_ACCESSOR_SUBACTION],!tM(e)))throw Error(`Invalid accesor id and/or sub id`);return e}}function rM(e,t,n){return nM(e.id,e.context.id)(t,e.context,n)}function iM(e){return{id:`MainPlot`,context:e}}var aM={id:`SeasonalOffsets`,context:{}};function oM(e){return Array.isArray(e)&&e.some(e=>e?.type===`Seasonal`)}function sM(e){let{id:t,context:n}=e;if(!P(n))return!1;if(t===`Compare`)return oM(n.plots);if(t!==z.ACTION_PLOT)return!1;let r=n.id;return r===`Add`||r===`Update`?n.type===`Seasonal`:r===z.ACTION_DELETE?oM(n.plots):!1}function cM(e){return e.some(sM)?e[e.length-1]?.id!==`SeasonalOffsets`:!1}var lM={keepOldAnnotations:!1,keepNewAnnotations:!0,keepOldCompare:!1,keepNewCompare:!0,keepOldAggregation:!1,keepNewBarWidth:!1},uM=Symbol.for(`__ias__`),dM=class{presenter;_model;constructor(e=!1){this.headless=e,this.presenter=e?null:new CA(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(iM(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)){Rc(e,t),Lc(e,t);let r=gk(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()}zoom(e){!this.headless&&typeof e==`boolean`&&(e?this.annotate(`ZoomIn`):this.presenter.defaultTool.resetView(this.presenter))}getDefaultTemplate(){return IM()}get model(){return(this.headless?this._model:this.presenter.getModel())||IM()}asTemplate(e={main:!0,annotations:!1,compare:!1}){return this.change({id:z.ACTION_TEMPLATE,context:{strip:e}})}change(...e){let t={chart:this,actions:e.filter(e=>!e[uM])};t.actions.length>0&&this.presenter?.notifyHost(G.CH_API_ACTIONS_RECEIVED,t);let n=$().config.validateInput,r=e.map(e=>n?Pd(e,z.ACCESSOR_SCHEMA):e);if(r.length===1){let e=r[0];if(e.id===z.ACTION_TEMPLATE||e.context.id===z.ACTION_GET)return rM(e,this.model,this.presenter);if(!this.headless&&e.id===z.ANN_ACTION_ID)return this.presenter.handleAnnotationChange(e.context)}let{yes:i,no:a}=A(r,e=>e.id===z.ACTION_PLOT&&P(e.context)&&e.context.id===z.ACTION_DELETE),o=F(this.model),s=F(this.model),c=a;i.length>0&&c.push({id:z.ACTION_PLOT,context:{id:z.ACTION_DELETE,plots:i.map(e=>e.context)}}),c.forEach(e=>{if(s=rM(e,s,this.presenter),!P(s))throw Error(`Forgot to return model from accessor`)}),cM(c)&&(s=rM(aM,s,this.presenter)),this.fromModel(s,o)}async fromModel(e,t){let n=Pd(e,z.CHART_SCHEMA);this.headless?this._model=n:await this.presenter?.fromModel(n,t)}async load(e,t){let n={...lM,...t},r=Pd(JSON.parse(e),z.CHART_SCHEMA),i=this.model,a=F(i);if(P(i)){if(r=qu(i,r,n.keepNewAnnotations),n.keepNewAnnotations||(r=Dj(r)),n.keepOldAnnotations&&(r=hA(i,r)),n.keepNewCompare||(r=Oj(r)),n.keepOldCompare&&(r=wj(i,r)),n.keepOldAggregation){let e={id:z.ACTION_AGGREGATION,context:i.data.aggregation},t=r.display.density;r=rM(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=IM();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=rM({id:`Theme`,context:{id:`Get`}},this.model,this.presenter),i=rM(iM(r),t,this.presenter);e&&(i=rM({id:`Theme`,context:n},i,this.presenter)),this.presenter?.fromModel(i)}}this.clearUndoRedo(),this.presenter?.notifyHost(G.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:bA.call(this.presenter,e)}exportImage(e={}){return this.headless?null:xA.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(G.CH_DIDBECOMEACTIVE,{chart:this})}};function fM(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 pM(){let e=globalThis.parent?.location?.hostname||``;return[``,`localhost`,`127.0.0.1`].includes(e)||fM(e)}function mM(){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 hM(e,t){return ot(t),`${e}/?${new URLSearchParams(t).toString()}`}var gM=`aHR0cHM6Ly9iYXJjaGFydHdpZGdldHMud2Vic29sLmJhcmNoYXJ0LmNvbQ==`,_M=`YXV0aGVudGljYXRlQ2hhcnRSZWZlcmVy`;function vM(e,t=``){return hM(atob(gM),{module:atob(_M),secret:t,referer:e})}function yM(e,t){return e+Math.random()*(t-e)}var bM=Function(atob(`Y29uc29sZS5sb2coIlBsZWFzZSBjb250YWN0IEJhcmNoYXJ0IGluIG9yZGVyIHRvIG9idGFpbiB0aGUgbGljZW5zZSBmb3IgdGhlIGNoYXJ0IGNvbXBvbmVudC4iKTsg`)),xM=Function(`f`,atob(`Zi5yZW1vdmVBbGxDaGFydHMoKTsg`)),SM=Function(`m`,atob(`cmV0dXJuIG0gPT09ICJJbnRlcm5hbEZlZWQiIHx8IG0gPT09ICJXaWRnZXQiIHx8IG0gPT09ICJGcmVlV2lkZ2V0IiB8fCBtID09PSAiRGVtb1NpdGUiOw==`)),CM=`YXV0aG9yaXplZA==`,wM=`ZGF0YS1lbmRwb2ludA==`,TM=`YWxsb3dDcmVkZW50aWFscw==`;async function EM(e,t){if(t&&!SM(e.mode))return;let n=!1,r=0,i=25;for(;!n&&r<5;){let t=pM()||e.mode===`FreeWidget`,a=t?e.apiKey:``;try{let i=vM(t?``:mM(),a),o=await fetch(i);if(!o.ok)r++;else{let t=await o.json(),r=t[atob(CM)];e.knownSite=r,r?(e.dataEndpoint=(t[atob(wM)]||``).replace(/\/$/g,``),e.allowCredentials=t[atob(TM)]):(e.dataEndpoint=``,e.allowCredentials=!1),n=!0;break}}catch{}r++,i*=2,await new Promise(e=>setTimeout(e,i))}(!n||!e.knownSite)&&DM()}function DM(){setTimeout(bM,yM(2e3,3e3)),setTimeout(()=>xM($()),yM(4e3,5e3))}var OM={major:2,minor:379,patch:1,prerelease:!1},kM={environment:`Browser`,validateInput:!1,throttleMillis:0,isAlt64:!0,defaultTemplate:`/${z.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,baseUrl:{instruments:`/proxies/instruments`,futures:`/proxies/futures`,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(SM(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 AM(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 jM=!1,MM=null;function NM(){let e=OM,t=e.prerelease?`-${e.prerelease.identifier}.${e.prerelease.ordinal}`:``;return`${e.major}.${e.minor}.${e.patch}${t}`}function PM(e){let t=e.extensions?.studyProvider;if(!P(t))return;let n=t.getFields(),r=t.getStudies(),i=F(ss(z.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)),Ad(z.CHART_SCHEMA,i),Bd(n),fs(r)}function FM(e,t={}){if(jM)throw Error(`You should only call initFeed once during page's lifetime`);jM=!0;let n=Object.assign(kM);return lt(n,t),N(n.logo)&&qD(n.logo,n.logoClickable??!1),PM(n),MM=new e(n),MM.version=NM(),I(`%cBarchart Chart version ${MM.version}`,`info`,`font-size: larger`),MM.cachesData&&(MM.subject?.subscribe(MM.onPerformInternalGc.bind(MM)),wv.default.subscribe(G.CH_ALL,MM.onChartChanged.bind(MM))),MM}function $(){return MM}function IM(){return F($()?.template)}function LM(){N(MM)&&(MM.shutdown(),jM=!1,MM=null)}function RM(){return new dM(!0)}function zM(e){let t=RM();return t.load(e),t.change({id:`Outline`,context:{id:`Get`}})}function BM(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 VM=class{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={}){zm(e,{feedId:this.id,isAuxiliary:this.isAuxiliary,...t})}get subject(){return!this.isAuxiliary&&!N(this._subject)&&(this.traceFeed(`gc:stream:init`,{gcMillis:z.INTERNAL_GC_MILLIS}),this._subject=new np().pipe(Rp(z.INTERNAL_GC_MILLIS),Lp(e=>e.length>0))),this._subject}get isAuxiliary(){return window.opener!==null}setAltDataSource(e){this._altDataSource=e,this.timeSeriesSource=BM(this.timeSeriesSource,`getTimeSeries`,e,`symbol`),this.metaDataSource=BM(this.metaDataSource,`getMetaData`,e),this.recordSource=BM(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 Ai.call(this,async()=>{let e=this instanceof KM||this instanceof HM||this instanceof YM;await EM(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=Pd(t,z.CHART_SCHEMA),!0})}getHeadlessChart(){return RM()}fixupRenderTo(e){if(!N(e))return null;if(e instanceof HTMLElement)return e;let t=xi(`#${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 dM;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(G.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===G.CH_RECREATED||e===G.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=Gu(this.template);e.curves.length===1&&Yl(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()}},HM=class extends VM{constructor(e){super(e),this.timeSeriesSource=new jg(!1),this.metaDataSource=new ca,this.recordSource=new Um}},UM=class extends VM{constructor(e){super(e),this.timeSeriesSource=new jg(!0),this.metaDataSource=new ca,this.recordSource=new Wm}},WM=class extends VM{constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new jg(!0),this.metaDataSource=new ca,this.recordSource=new Um}},GM=[`drazen.dotlic@barchart.com`,`princec`,`b.hebert24@barchart.com`],KM=class extends VM{lastStreamingTimestamp=null;_isActivelyStreaming=null;needToResubscribe=!1;_connection;constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new jg(!0),this.metaDataSource=new la,this.recordSource=new Gm,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&&GM.includes(this.connection._username)&&I(`[chart] Connection ${e}, last timestamp ${this.lastStreamingTimestamp}`)}onEvents({event:e}){e===z.BC_EVENT_DISCONNECTED||e===z.BC_EVENT_FEED_PAUSED?(this.debug(e),this.isActivelyStreaming=!1):(e===z.BC_EVENT_LOGGED_IN||e===z.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 qM(e,t){return new JM(e,t)}var JM=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)??[]}},YM=class extends VM{_adapter=null;_auxFeeds=[];constructor(e){super(e),this.cachesData=!0,this.isAuxiliary||(this.timeSeriesSource=new jg(!0),this.metaDataSource=new ua,this.recordSource=new Km,wv.default.subscribe(G.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)}},XM=wv.default;export{Vl as Aggregation,_ as AggregationSpec,g as AggregationUnit,HM as BarchartSiteDataFeed,VM as BaseDataFeed,Hm as BaseRecordSource,re as ChunkPart,Sg as ContainerWrapperTimeSeries,uA as CustomEventPopup,qd as EmptyRecord,u as ExpressionMissingBar,f as ExpressionNoDataApproach,d as ExpressionRecompute,Ev as ExpressionSeries,Ld as Field,b as FieldCategory,y as FieldFormat,v as FieldValueType,W as Fields,KM as MarketDataFeed,WM as MiniWidgetDataFeed,vh as OHLCDataPointBuilder,YM as OpenFeed,XM as PubSub,w as SeriesKind,UM as SnapshotDataFeed,q as StudySeries,bh as TimeSeriesContainer,Cv as TimeSeriesQuery,G as Topics,qM as adaptOpenFeedClient,Ei as appendDOMElement,Ai as asyncReady,X as convertSeries,Ou as doesExpressionHaveComputation,_s as doesStudyExist,Cu as evaluateExpression,Eu as formatExpression,Xi as formatPriceWithDecimals,bt as generateUid,hs as getAnnotationTraits,zM as getChartOutline,Zi as getCombinedMetaData,Du as getExpressionSymbols,$ as getFeed,Na as getLightness,bk as getStudyOptions,ws as getTaxonomies,si as hasOpenInterest,FM as initFeed,_E as linReg,Tv as makeExpression,K as makeHelperField,KT as makeStudy,Z as mapSeries,J as movAvg,Y as movExp,ZT as movHul,YT as movSmo,XT as movWei,dh as optionValueToDate,Su as parseExpression,ku as replaceExpressionSymbols,cE as roc,Ci as setAttributesDOMElement,LM as shutdownFeed,dE as stdDev,Si as styleDOMElement,rE as trueRange,sE as typical};
|