openalgo-charts 2.5.2 → 2.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -24
- package/dist/draw/index.d.ts +182 -24
- package/dist/index.d.ts +2711 -1899
- package/dist/indicators/index.d.ts +437 -46
- package/dist/openalgo-charts.draw.mjs +1 -1
- package/dist/openalgo-charts.draw.mjs.map +1 -1
- package/dist/openalgo-charts.indicators.mjs +1 -1
- package/dist/openalgo-charts.indicators.mjs.map +1 -1
- package/dist/openalgo-charts.mjs +1 -1
- package/dist/openalgo-charts.mjs.map +1 -1
- package/dist/openalgo-charts.standalone.js +1 -1
- package/dist/openalgo-charts.standalone.js.map +1 -1
- package/dist/openalgo-charts.widget.mjs +1 -1
- package/dist/openalgo-charts.widget.mjs.map +1 -1
- package/dist/openalgo-charts.workspace.mjs +1 -1
- package/dist/openalgo-charts.workspace.mjs.map +1 -1
- package/dist/webgl/index.d.ts +2 -2
- package/dist/widget/index.d.ts +484 -18
- package/dist/workspace/index.d.ts +42 -7
- package/package.json +2 -1
package/dist/openalgo-charts.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e="2.5.2";function t(){return e}const i={None:0,Cursor:1,Light:2,Full:3};class r{constructor(e=i.None){Object.defineProperty(this,"_globalLevel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_panes",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_timeScaleOps",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this._globalLevel=e}get globalLevel(){return this._globalLevel}invalidateGlobal(e){e>this._globalLevel&&(this._globalLevel=e)}invalidatePane(e,t){var i,r;this._panes.set(e,(i=this._panes.get(e),r=t,void 0===i?{...r}:{level:Math.max(i.level,r.level),autoScale:i.autoScale||r.autoScale}))}paneInvalidation(e){return this._panes.get(e)}panes(){return this._panes}addTimeScaleOp(e){this._timeScaleOps.push(e)}timeScaleOps(){return this._timeScaleOps}isEmpty(){return this._globalLevel===i.None&&0===this._panes.size&&0===this._timeScaleOps.length}merge(e){this.invalidateGlobal(e._globalLevel);for(const[t,i]of e._panes)this.invalidatePane(t,i);e._timeScaleOps.length>0&&(this._timeScaleOps=this._timeScaleOps.concat(e._timeScaleOps))}}const s=()=>{};class n{constructor(e,t,i){if(Object.defineProperty(this,"_onFrame",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schedule",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_cancel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_handle",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._onFrame=e,t)this._schedule=t,this._cancel=i??s;else{const e="function"==typeof requestAnimationFrame?{schedule:e=>requestAnimationFrame(e),cancel:e=>cancelAnimationFrame(e)}:{schedule:e=>setTimeout(e,16),cancel:e=>clearTimeout(e)};this._schedule=e.schedule,this._cancel=e.cancel}}get scheduled(){return null!==this._handle}requestFrame(){if(null!==this._handle)return;this._handle=-1;const e=this._schedule(()=>{this._handle=null,this._onFrame()});null!==this._handle&&(this._handle=e)}stop(){null!==this._handle&&(this._cancel(this._handle),this._handle=null)}}function o(e,t,i){return{width:Math.round(e*i),height:Math.round(t*i)}}function a(e,t){return Math.round(e*t)/t}class l{constructor(e,t){Object.defineProperty(this,"element",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ctx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_mediaWidth",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_mediaHeight",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_dpr",{enumerable:!0,configurable:!0,writable:!0,value:1}),this.element=e.createElement("canvas");const i=this.element.getContext("2d");if(null===i)throw new Error("openalgo-charts: 2D canvas context is not available");this.ctx=i;const r=this.element.style;r.position="absolute",r.top="0",r.left="0",r.width="100%",r.height="100%",r.zIndex=String(t)}get mediaWidth(){return this._mediaWidth}get mediaHeight(){return this._mediaHeight}get pixelRatio(){return this._dpr}resize(e,t,i){if(e===this._mediaWidth&&t===this._mediaHeight&&i===this._dpr)return;this._mediaWidth=e,this._mediaHeight=t,this._dpr=i;const r=o(e,t,i);this.element.width=r.width,this.element.height=r.height,this.element.style.width=`${e}px`,this.element.style.height=`${t}px`}clearBitmap(){this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.element.width,this.element.height)}}function h(e,t,i){return e<t?t:e>i?i:e}function c(e,t,i){return e+(t-e)*i}function d(e,t){return t<=0?e:Math.round(e/t)*t}function u(e){const t=Math.floor(Math.log10(e)),i=e/Math.pow(10,t);for(const e of[1,2,2.5,5])if(e>i*(1+1e-9))return e*Math.pow(10,t);return 10*Math.pow(10,t)}function p(e,t,i){const r=Math.ceil(e/i)*i,s=Math.floor(t/i)*i;return Math.round((s-r)/i)+1}function _(e,t,i=6){if(!isFinite(e)||!isFinite(t)||t<=e)return[Number.isFinite(e)?e:0];let r=function(e){if(e<=0)return 0;const t=Math.floor(Math.log10(e)),i=e/Math.pow(10,t);let r;return r=i<1.5?1:i<3?2:i<7?5:10,r*Math.pow(10,t)}((t-e)/Math.max(1,i-1));if(!(r>0))return[e];for(let s=0;s<20&&p(e,t,r)>i;s++)r=u(r);const s=Math.ceil(e/r)*r,n=Math.floor(t/r)*r,o=[],a=Math.round((n-s)/r)+1;for(let e=0;e<a&&e<1e3;e++){const t=s+e*r;o.push(Math.abs(t)<r/1e6?0:t)}return o}function b(e){return e<=0||!isFinite(e)?2:e>=1?0:Math.min(8,Math.ceil(-Math.log10(e)))}function f(e){return"percentage"===e||"indexed-to-100"===e}const m={marginTop:.1,marginBottom:.1,minMove:0,minPrecision:0,mode:"linear",inverted:!1};function g(e,t,i,r){if(!isFinite(e)||!isFinite(t))return{min:0,max:1};if(t<=e){const i=Math.abs(t)>0?.05*Math.abs(t):.5;return{min:e-i,max:t+i}}const s=(t-e)/Math.max(1-i-r,.01);return{min:e-s*r,max:t+s*i}}class v{constructor(e={}){Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_height",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_min",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_max",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"_autoScale",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_scaled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_baseline",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_fixedRange",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_priceFormatter",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._options={...m,...e}}get options(){return this._options}setOptions(e){this._options={...this._options,...e},f(this._options.mode)||(this._baseline=null)}setHeight(e){this._height=e}get height(){return this._height}setPriceRange(e){this._min=e.min,this._max=e.max,this._scaled=!0}get scaled(){return this._scaled}setBaseline(e){this._baseline=e}get baseline(){return this._baseline}priceRange(){return{min:this._min,max:this._max}}get autoScale(){return this._autoScale}setAutoScale(e){e&&null!==this._fixedRange?this.setPriceRange(this._fixedRange):this._autoScale=e}setFixedRange(e){this._fixedRange=null===e?null:{...e},null!==e&&(this._autoScale=!1,this.setPriceRange(e))}get fixedRange(){return null===this._fixedRange?null:{...this._fixedRange}}reset(){this._autoScale&&(this._min=0,this._max=1,this._scaled=!1,this._baseline=null)}scaleAroundCenter(e){const t=(this._min+this._max)/2,i=(this._max-this._min)/2*e;this._min=t-i,this._max=t+i,this._autoScale=!1}scaleAtY(e,t){if(!this._scaled||this._height<=0||!Number.isFinite(t)||t<=0)return;const i=this._t(this._min),r=this._t(this._max),s=this._t(this.yToPrice(e)),n=this._tInv(s+(i-s)*t),o=this._tInv(s+(r-s)*t);Number.isFinite(n)&&Number.isFinite(o)&&o>n&&(this.setPriceRange({min:n,max:o}),this._autoScale=!1)}panByPixels(e){if(this._height<=0||0===e)return;const t=this._t(this._min),i=this._t(this._max),r=i-t;if(!(r>0))return;const s=r*((this._options.inverted?-e:e)/this._height);this._min=this._tInv(t+s),this._max=this._tInv(i+s),this._autoScale=!1}autoscale(e,t,i=1){if(null!==this._fixedRange)return this.setPriceRange(this._fixedRange),!1;const r=g(e,t,this._options.marginTop,this._options.marginBottom),s=this._t(this._min),n=this._t(this._max),o=this._t(r.min),a=this._t(r.max),l=n-s,c=a-o,d=Math.max(Math.abs((o-s)/l),Math.abs((a-n)/l))*this._height;if(!this._scaled||i>=1||!Number.isFinite(i)||!(l>0)||!(c>0)||d<.1)return this.setPriceRange(r),!1;const u=h(i,0,1),p=(1-u)/l+u/c,_=((1-u)*s/l+u*o/c)/p;return this.setPriceRange({min:this._tInv(_),max:this._tInv(_+1/p)}),!0}_rebase(){const e=this._options.mode;if("percentage"!==e&&"indexed-to-100"!==e)return null;const t=this._baseline;return null!==t&&isFinite(t)&&t>0?t:null}_t(e){if("logarithmic"===this._options.mode)return Math.log10(Math.max(1e-10,e));const t=this._rebase();if(null===t)return e;const i=e/t*100;return"percentage"===this._options.mode?i-100:i}_tInv(e){if("logarithmic"===this._options.mode)return Math.pow(10,e);const t=this._rebase();return null===t?e:("percentage"===this._options.mode?e+100:e)*t/100}priceToY(e){const t=this._t(this._min),i=this._t(this._max)-t;if(i<=0)return this._height/2;const r=(this._t(e)-t)/i;return this._options.inverted?this._height*r:this._height*(1-r)}yToPrice(e){const t=this._t(this._min),i=this._t(this._max)-t,r=this._options.inverted?e/this._height:1-e/this._height;return this._tInv(t+r*i)}precision(){if(null!==this._rebase())return Math.max(2,b((this._t(this._max)-this._t(this._min))/100));if(this._options.minMove>0)return b(this._options.minMove);const e=b((this._max-this._min)/100),t=Math.max(Math.abs(this._min),Math.abs(this._max));return!Number.isFinite(t)||t>=1e4?e:Math.max(this._options.minPrecision,e)}ticks(e=6){return null===this._rebase()?_(this._min,this._max,e):_(this._t(this._min),this._t(this._max),e).map(e=>this._tInv(e))}snapToTick(e){const t=this._options.minMove;return t<=0?e:Math.round(e/t)*t}setPriceFormatter(e){this._priceFormatter=e}format(e){if(null!==this._rebase()){const t=this.precision(),i=this._t(e);if("indexed-to-100"===this._options.mode)return i.toFixed(t);const r=Number(i.toFixed(t));return`${r>0?"+":""}${(0===r?0:i).toFixed(t)}%`}return null!==this._priceFormatter?this._priceFormatter(e):e.toFixed(this.precision())}clampY(e){return h(e,0,this._height)}}const y={barSpacing:8,minBarSpacing:1,maxBarSpacing:80,rightOffset:4};class w{constructor(e={}){Object.defineProperty(this,"_barSpacing",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_rightOffset",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_minBarSpacing",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_maxBarSpacing",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_width",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_baseIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_onChange",{enumerable:!0,configurable:!0,writable:!0,value:null});const t={...y,...e};this._barSpacing=t.barSpacing,this._rightOffset=t.rightOffset,this._minBarSpacing=t.minBarSpacing,this._maxBarSpacing=t.maxBarSpacing}setWidth(e){this._width=e}get width(){return this._width}get barSpacing(){return this._barSpacing}setBarSpacing(e){this._barSpacing=this.constrainBarSpacing(e)}constrainBarSpacing(e){return h(e,this._minBarSpacing,this._maxBarSpacing)}get rightOffset(){return this._rightOffset}setRightOffset(e){this._rightOffset=e}setBaseIndex(e){this._baseIndex=e}_rightEdgeIndex(){return this._baseIndex+this._rightOffset}indexToX(e){return this._width-(this._rightEdgeIndex()-e)*this._barSpacing}xToIndex(e){return this._rightEdgeIndex()-(this._width-e)/this._barSpacing}visibleRange(){const e=this._rightEdgeIndex();return{from:e-this._width/this._barSpacing,to:e}}getVisibleLogicalRange(){return this.visibleRange()}setVisibleLogicalRange(e){if(this._width<=0)return;const t=e.to-e.from;t>0&&(this.setBarSpacing(this._width/t),this._rightOffset=e.to-this._baseIndex,this._onChange?.())}setChangeHandler(e){this._onChange=e}scrollByPixels(e){this._rightOffset-=e/this._barSpacing}zoomAtX(e,t){const i=this.xToIndex(e),r=this._barSpacing;if(this.setBarSpacing(r*t),this._barSpacing===r)return;const s=i+(this._width-e)/this._barSpacing;this._rightOffset=s-this._baseIndex}fitContent(e){if(e<=0||this._width<=0)return;this._baseIndex=e-1,this._rightOffset=y.rightOffset;const t=this._width/(e+this._rightOffset);this.setBarSpacing(t)}}const x=[];class P{constructor(){Object.defineProperty(this,"_series",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_sortedTimes",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_indexByTime",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_nextId",{enumerable:!0,configurable:!0,writable:!0,value:1})}createSeries(){const e=this._nextId++;return this._series.set(e,{bars:[]}),e}removeSeries(e){this._series.delete(e),this._rebuild()}setSeriesData(e,t){const i=this._series.get(e);if(void 0===i)throw new Error(`openalgo-charts: unknown series ${e}`);i.bars=function(e){const t=e.slice().sort((e,t)=>e.time-t.time);let i=0;for(let e=0;e<t.length;e++)i>0&&t[e].time===t[i-1].time?t[i-1]=t[e]:t[i++]=t[e];return t.length=i,t}(t),this._rebuild()}addBars(e,t){const i=this._series.get(e);if(void 0===i)throw new Error(`openalgo-charts: unknown series ${e}`);if(0===t.length)return;const r=new Map;for(const e of i.bars)r.set(e.time,e);for(const e of t)r.set(e.time,e);i.bars=Array.from(r.values()).sort((e,t)=>e.time-t.time),this._rebuild()}update(e,t){const i=this._series.get(e);if(void 0===i)throw new Error(`openalgo-charts: unknown series ${e}`);const r=i.bars,s=r[r.length-1];if(void 0===s||t.time>s.time){r.push(t);const e=this._sortedTimes.length,i=e>0?this._sortedTimes[e-1]:void 0;return void 0===i||t.time>i?(this._appendTime(t.time),"append"):this._indexByTime.has(t.time)?"replace":(this._rebuild(),"insert")}if(t.time===s.time)return r[r.length-1]=t,"replace";const n=r.findIndex(e=>e.time===t.time);return n>=0?(r[n]=t,"replace"):(this.addBars(e,[t]),"insert")}_appendTime(e){this._indexByTime.has(e)||(this._indexByTime.set(e,this._sortedTimes.length),this._sortedTimes.push(e))}get length(){return this._sortedTimes.length}get baseIndex(){return this._sortedTimes.length-1}indexToTime(e){return this._sortedTimes[e]}timeToIndex(e){return this._indexByTime.get(e)}indexToTimeFloat(e){const t=this._sortedTimes,i=t.length;if(0===i)return NaN;if(1===i)return t[0];if(e<=0)return t[0]+e*(t[1]-t[0]);if(e>=i-1)return t[i-1]+(e-(i-1))*(t[i-1]-t[i-2]);const r=Math.floor(e);return t[r]+(e-r)*(t[r+1]-t[r])}timeToIndexFloat(e){const t=this._sortedTimes,i=t.length;if(0===i)return NaN;if(1===i)return 0;if(e<=t[0]){const i=t[1]-t[0];return i>0?(e-t[0])/i:0}if(e>=t[i-1]){const r=t[i-1]-t[i-2];return r>0?i-1+(e-t[i-1])/r:i-1}let r=0,s=i-1;for(;r<s;){const i=r+s+1>>1;t[i]<=e?r=i:s=i-1}const n=t[r+1]-t[r];return n>0?r+(e-t[r])/n:r}seriesBars(e){return this._series.get(e)?.bars??x}indexedBars(e){const t=this._series.get(e);if(void 0===t)return[];const i=[];for(const e of t.bars){const t=this._indexByTime.get(e.time);void 0!==t&&i.push({index:t,bar:e})}return i}visibleBars(e,t,i){const r=this._series.get(e);if(void 0===r)return[];const s=r.bars,n=Math.max(0,Math.floor(t)),o=Math.min(this.baseIndex,Math.ceil(i));if(o<n||0===s.length)return[];const a=this._sortedTimes[n],l=this._sortedTimes[o];if(void 0===a||void 0===l)return[];let h=0,c=s.length;for(;h<c;){const e=h+c>>1;s[e].time<a?h=e+1:c=e}const d=[];for(let e=h;e<s.length;e++){const t=s[e].time;if(t>l)break;const i=this._indexByTime.get(t);void 0!==i&&d.push({index:i,bar:s[e]})}return d}lastIndexedBar(e){const t=this._series.get(e);if(void 0===t||0===t.bars.length)return null;const i=t.bars[t.bars.length-1],r=this._indexByTime.get(i.time);return void 0===r?null:{index:r,bar:i}}_rebuild(){const e=new Set;for(const t of this._series.values())for(const i of t.bars)e.add(i.time);this._sortedTimes=Array.from(e).sort((e,t)=>e-t),this._indexByTime.clear();for(let e=0;e<this._sortedTimes.length;e++)this._indexByTime.set(this._sortedTimes[e],e)}}function S(e,t){return"dashed"===e?[4*t,4*t]:"dotted"===e?[1*t,3*t]:[]}function O(e,t,i){const r=S(e.gridStyle,i);return{color:e.grid,lineWidth:t?.lineWidth??1,dash:r,vert:{color:t?.vertColor??e.grid,dash:void 0===t?.vertStyle?r:S(t.vertStyle,i)},horz:{color:t?.horzColor??e.grid,dash:void 0===t?.horzStyle?r:S(t.horzStyle,i)}}}function k(e,t,i,r,s,n,o,l){if(0!==t.length){e.strokeStyle=r?.color??s.color,e.setLineDash(r?.dash??s.dash??[]),e.beginPath();for(const r of t){const t=Math.round(a(r,n)*n);i?(e.moveTo(t,0),e.lineTo(t,l)):(e.moveTo(0,t),e.lineTo(o,t))}e.stroke()}}const M=10,T=14;function C(e,t){const i=void 0===t?.fontSize?e.axisFontSize??11:h(Math.round(t.fontSize),10,14);return{textColor:t?.textColor??e.axisText,lineColor:t?.lineColor??e.axisLine,font:`${i}px system-ui, sans-serif`}}function I(e){const t={};return void 0!==e?.top&&(t.marginTop=h(e.top,0,49)/100),void 0!==e?.bottom&&(t.marginBottom=h(e.bottom,0,49)/100),t}const j={upColor:"#26a69a",downColor:"#ef5350",borderUpColor:"#26a69a",borderDownColor:"#ef5350",wickUpColor:"#26a69a",wickDownColor:"#ef5350",borderVisible:!0,wickVisible:!0};function A(e,t){const i=Math.floor(e*t*.8);let r=Math.max(1,i);if(r>=2){r%2!=Math.max(1,Math.floor(t))%2&&(r-=1)}return Math.max(1,r)}function L(e,t,i){return i.wickVisible?!0===i.hollow||!1===i.bodyVisible||e>t||i.borderVisible&&e>=3||i.upColor!==i.wickUpColor||i.downColor!==i.wickDownColor?"full":"wick":"full"}function z(e,t,i,r=1){const s=A(t,i),n=Math.max(1,Math.floor(i)),o=Math.round(e*i),a=Math.max(.05,Math.min(1,r)),l=1===a?s:Math.max(1,Math.round(s*a));return{cx:o,bodyX:o-Math.floor(l/2),bodyW:l,wickX:o-Math.floor(n/2),wickW:n}}function F(e,t,i,r,s,n=j){const o=A(r,s),a=Math.max(1,Math.floor(s)),l=n.widthScale?null:L(o,a,n);for(let o=0;o<t.length;o++){const{x:h,bar:c}=t[o],d=o>0?t[o-1].bar.close:t[o].prevClose,u=!0===n.colorByPreviousClose&&void 0!==d&&Number.isFinite(d)?c.close>=d:c.close>=c.open,p=Math.round(i(c.open)*s),_=Math.round(i(c.close)*s),b=Math.round(i(c.high)*s),f=Math.round(i(c.low)*s),m=z(h,r,s,n.widthScale?n.widthScale(c):1),g=m.cx,v=m.bodyW,y=g-m.bodyX,w=c.color,x=w??(u?n.upColor:n.downColor),P=c.wickColor??w??(u?n.wickUpColor:n.wickDownColor),S=c.borderColor??w??(u?n.borderUpColor:n.borderDownColor);if(n.wickVisible&&(e.fillStyle=P,e.fillRect(m.wickX,b,m.wickW,Math.max(1,f-b))),"wick"===(l??L(v,a,n))&&P===x)continue;const O=Math.min(p,_),k=Math.max(1,Math.abs(_-p));if(n.hollow&&u)e.strokeStyle=n.borderVisible?S:x,e.lineWidth=Math.max(1,a),e.strokeRect(g-y+.5,O+.5,v-1,k-1);else{const t=!1!==n.bodyVisible;t&&(e.fillStyle=x,e.fillRect(g-y,O,v,k)),n.borderVisible&&(!t||v>=3)&&(e.strokeStyle=S,e.lineWidth=1,e.strokeRect(g-y+.5,O+.5,v-1,k-1))}}}function B(e,t,i){const r=e.bar;return{cx:Math.round(e.x*i),yOpen:Math.round(t(r.open)*i),yClose:Math.round(t(r.close)*i),yHigh:Math.round(t(r.high)*i),yLow:Math.round(t(r.low)*i),up:r.close>=r.open}}function $(e,t,i,r,s,n,o=!1){const a=Math.max(1,Math.floor(A(r,s)/2)),l=Math.max(1,Math.floor(s));e.save();for(let r=0;r<t.length;r++){const h=t[r],c=B(h,i,s),d=r>0?t[r-1].bar.close:h.prevClose,u=!0===n.colorByPreviousClose&&void 0!==d&&Number.isFinite(d)?h.bar.close>=d:c.up;e.fillStyle=h.bar.color??(u?n.upColor??"#26a69a":n.downColor??"#ef5350"),e.fillRect(c.cx-Math.floor(l/2),c.yHigh,l,Math.max(1,c.yLow-c.yHigh)),o||(e.fillRect(c.cx-a,c.yOpen,a,l),e.fillRect(c.cx,c.yClose,a,l))}e.restore()}function N(e){const t=e.trim();if(t.startsWith("#")){const e=t.slice(1);if(3===e.length||4===e.length){const[t,i,r,s]=[...e].map(e=>parseInt(e+e,16));return[t,i,r].some(Number.isNaN)?null:{r:t,g:i,b:r,a:4===e.length?s/255:1}}if(6===e.length||8===e.length){const t=parseInt(e.slice(0,6),16);if(Number.isNaN(t))return null;const i=8===e.length?parseInt(e.slice(6,8),16)/255:1;return{r:t>>16&255,g:t>>8&255,b:255&t,a:Number.isNaN(i)?1:i}}return null}const i=/^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*(?:,\s*([\d.]+)\s*)?\)$/i.exec(t);return null===i?null:{r:Number(i[1]),g:Number(i[2]),b:Number(i[3]),a:void 0===i[4]?1:Number(i[4])}}function D(e){return function(e){const t=N(e);if(null===t)return.5;const i=e=>{const t=e/255;return t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)};return.2126*i(t.r)+.7152*i(t.g)+.0722*i(t.b)}(e)>.45?"#10131a":"#ffffff"}function R(e,t){const i=N(e);return null===i?e:`rgba(${i.r},${i.g},${i.b},${t})`}function E(e){if("transparent"===e.trim().toLowerCase())return!0;const t=N(e);return null!==t&&t.a<=0}function W(e,t){const i=N(e);if(null===i)return e;const r=t>=0?255:0,s=Math.min(1,Math.abs(t)),n=e=>Math.round(e+(r-e)*s);return`rgba(${n(i.r)},${n(i.g)},${n(i.b)},${i.a})`}function q(e,t,i,r,s,n){const o=e.roundRect;"function"==typeof o?o.call(e,t,i,r,s,Math.max(0,Math.min(n,r/2,s/2))):e.rect(t,i,r,s)}const H=new WeakMap;function V(e,t,i,r){let s=H.get(e);void 0===s&&(s=new Map,H.set(e,s));const n=`${Math.round(t)}|${i}|${r}`;let o=s.get(n);return void 0===o&&(o=e.createLinearGradient(0,0,0,t),o.addColorStop(0,i),o.addColorStop(1,r),s.set(n,o)),o}function G(e,t,i,r,s){const n=N(r),o=N(s);if(null===n||null===o)return r;const a=(e-t)/(i-t),l=a>0?a<1?a:1:0;return`rgba(${Math.round(n.r+(o.r-n.r)*l)},${Math.round(n.g+(o.g-n.g)*l)},${Math.round(n.b+(o.b-n.b)*l)},${n.a+(o.a-n.a)*l})`}function U(e,t,i=e=>e.close){return e.map(e=>({x:e.x,y:t(i(e.bar))}))}function Y(e,t,i,r){if(0===t.length)return;const s=e.strokeStyle;let n,o;e.beginPath();let a=!1;for(let l=0;l<t.length;l++){const h=t[l];if(!Number.isFinite(h.x)||!Number.isFinite(h.y)){n=void 0;continue}if(void 0===n){e.moveTo(h.x*i,h.y*i),n=h;continue}const c=void 0===r?o:r[l];c!==o&&(a&&(e.stroke(),e.beginPath(),e.moveTo(n.x*i,n.y*i),a=!1),e.strokeStyle=c??s,o=c),e.lineTo(h.x*i,h.y*i),n=h,a=!0}e.stroke()}function K(e,t,i,r,s){const n=U(t,i),o=s.step?function(e){if(0===e.length)return[];const t=[{...e[0]}];for(let i=1;i<e.length;i++)t.push({x:e[i].x,y:e[i-1].y}),t.push({x:e[i].x,y:e[i].y});return t}(n):n,a=function(e,t){let i=!1;for(const t of e)if(void 0!==t.bar.color){i=!0;break}if(!i)return;const r=[];for(const i of e)t&&r.length>0&&r.push(i.bar.color),r.push(i.bar.color);return r}(t,!0===s.step);e.save(),e.strokeStyle=s.color??"#4f8cff",e.lineWidth=Math.max(1,(s.lineWidth??1.5)*r),e.lineJoin="round",e.lineCap="round";const l="dashed"===s.lineStyle?[6*r,4*r]:"dotted"===s.lineStyle?[1*r,3*r]:[];if(e.setLineDash(l),s.markersOnly||Y(e,o,r,a),e.setLineDash([]),s.markers||s.markersOnly){const i=(s.markerRadius??2)*r,o=s.color??"#4f8cff";e.fillStyle=o;for(let s=0;s<n.length;s++){const l=n[s];Number.isFinite(l.x)&&Number.isFinite(l.y)&&(void 0!==a&&(e.fillStyle=t[s].bar.color??o),e.beginPath(),e.arc(l.x*r,l.y*r,i,0,2*Math.PI),e.fill())}}e.restore()}const X={color:"#3a4666",base:0};function J(e,t,i={}){return{...j,upColor:e.upColor??t.upColor,downColor:e.downColor??t.downColor,borderUpColor:e.borderUpColor??t.upColor,borderDownColor:e.borderDownColor??t.downColor,wickUpColor:e.wickUpColor??t.wickUpColor,wickDownColor:e.wickDownColor??t.wickDownColor,borderVisible:e.borderVisible??j.borderVisible,bodyVisible:e.bodyVisible??!0,wickVisible:e.wickVisible??j.wickVisible,colorByPreviousClose:e.colorByPreviousClose,...i}}const Z=e=>({min:e.low,max:e.high}),Q=e=>({min:e.close,max:e.close}),ee=(e,t)=>{const i=t.base??0;return{min:Math.min(i,e.close),max:Math.max(i,e.close)}},te=new Map,ie=new Set(["point-figure","kagi"]);function re(e,t){te.set(e,t)}function se(e){const t=te.get(e);if(void 0===t){if(ie.has(e))throw new Error(`openalgo-charts: series type "${e}" needs the transform tier — import 'openalgo-charts/transform' first`);throw new Error(`openalgo-charts: unknown series type "${e}"`)}return t}function ne(){return Array.from(te.keys())}const oe=(e,t)=>({...e,upColor:e.upColor??t.upColor,downColor:e.downColor??t.downColor});function ae(e,t,i=.5,r=1){const s=e*t;if(s<=0)return 1;const n=i*Math.max(1,r);return s>=n?1:Math.max(1,Math.ceil(n/s))}function le(e){const t=e[0];let i=t.high,r=t.low,s=t.volume??0,n=void 0!==t.volume,o=t.oi;for(let t=1;t<e.length;t++){const a=e[t];a.high>i&&(i=a.high),a.low<r&&(r=a.low),void 0!==a.volume&&(s+=a.volume,n=!0),void 0!==a.oi&&(o=a.oi)}const a={time:t.time,open:t.open,high:i,low:r,close:e[e.length-1].close};return n&&(a.volume=s),void 0!==o&&(a.oi=o),a}function he(e,t){if(t<=1)return e.slice();const i=[];for(let r=0;r<e.length;r+=t)i.push(le(e.slice(r,r+t)));return i}function ce(e,t){if(t<=1)return e.map(e=>({x:e.x,bar:e.bar}));const i=[];for(let r=0;r<e.length;r+=t){const s=e.slice(r,r+t),n=s.reduce((e,t)=>e+t.x,0)/s.length;i.push({x:n,bar:le(s.map(e=>e.bar))})}return i}re("candlestick",{defaultStyle:{},isPriceSeries:!0,draw:(e,t,i,r,s,n,o)=>F(e,t,i,r,s,J(n,o.theme)),extents:Z}),re("hollow-candle",{defaultStyle:{},isPriceSeries:!0,draw:(e,t,i,r,s,n,o)=>F(e,t,i,r,s,J(n,o.theme,{hollow:!0})),extents:Z}),re("volume-candle",{defaultStyle:{},isPriceSeries:!0,draw:(e,t,i,r,s,n,o)=>{const a=o.maxVolume;F(e,t,i,r,s,J(n,o.theme,{widthScale:e=>a>0?(e.volume??0)/a:1}))},extents:Z}),re("bar",{defaultStyle:{},isPriceSeries:!0,draw:(e,t,i,r,s,n,o)=>$(e,t,i,r,s,oe(n,o.theme)),extents:Z}),re("high-low",{defaultStyle:{},isPriceSeries:!0,draw:(e,t,i,r,s,n,o)=>$(e,t,i,r,s,oe(n,o.theme),!0),extents:Z}),re("line",{defaultStyle:{lineWidth:1.5},isPriceSeries:!0,draw:(e,t,i,r,s,n,o)=>K(e,t,i,s,{...n,color:n.color??o.theme.lineColor}),extents:Q}),re("line-markers",{defaultStyle:{lineWidth:1.5,markers:!0},isPriceSeries:!0,draw:(e,t,i,r,s,n,o)=>K(e,t,i,s,{...n,color:n.color??o.theme.lineColor,markers:!0}),extents:Q}),re("step",{defaultStyle:{lineWidth:1.5,step:!0},isPriceSeries:!0,draw:(e,t,i,r,s,n,o)=>K(e,t,i,s,{...n,color:n.color??o.theme.lineColor,step:!0}),extents:Q}),re("area",{defaultStyle:{lineWidth:1.5},isPriceSeries:!0,draw:(e,t,i,r,s,n,o)=>function(e,t,i,r,s,n){const o=U(t,i);if(0===o.length)return;const a=s*r;e.save(),e.beginPath(),e.moveTo(o[0].x*r,a);for(const t of o)e.lineTo(t.x*r,t.y*r);e.lineTo(o[o.length-1].x*r,a),e.closePath(),e.fillStyle=V(e,a,n.areaTopColor??"rgba(79,140,255,0.40)",n.areaBottomColor??"rgba(79,140,255,0.00)"),e.fill(),e.restore(),K(e,t,i,r,{color:n.color??"#4f8cff",lineWidth:n.lineWidth??1.5,lineStyle:n.lineStyle})}(e,t,i,s,o.plotHeight,{...n,color:n.color??o.theme.lineColor,areaTopColor:n.areaTopColor??o.theme.areaTopColor,areaBottomColor:n.areaBottomColor??o.theme.areaBottomColor}),extents:Q}),re("hlc-area",{defaultStyle:{lineWidth:1.5},isPriceSeries:!0,draw:(e,t,i,r,s,n,o)=>function(e,t,i,r,s){if(0===t.length)return;const n=U(t,i,e=>e.high),o=U(t,i,e=>e.low);e.save(),e.beginPath(),e.moveTo(n[0].x*r,n[0].y*r);for(const t of n)e.lineTo(t.x*r,t.y*r);for(let t=o.length-1;t>=0;t--)e.lineTo(o[t].x*r,o[t].y*r);e.closePath(),e.fillStyle=s.areaTopColor??"rgba(79,140,255,0.15)",e.fill(),e.restore();for(const[t,i]of[[s.highColor,n],[s.lowColor,o]])void 0!==t&&(e.save(),e.strokeStyle=t,e.lineWidth=Math.max(1,Math.round((s.lineWidth??1.5)*r)),Y(e,i,r),e.restore());K(e,t,i,r,{color:s.closeColor??"#4f8cff",lineWidth:s.lineWidth??1.5})}(e,t,i,s,{...n,closeColor:n.closeColor??o.theme.lineColor}),extents:Z}),re("baseline",{defaultStyle:{baseValue:0,lineWidth:1.5},isPriceSeries:!0,draw:(e,t,i,r,s,n,o)=>function(e,t,i,r,s){const n=i(s.baseValue??0)*r,o=U(t,i);if(0===o.length)return;const a=o[0].x*r,l=o[o.length-1].x*r,h=()=>{e.beginPath(),e.moveTo(a,n);for(const t of o)e.lineTo(t.x*r,t.y*r);e.lineTo(l,n),e.closePath()},c=s.areaTopColor??"rgba(38,166,154,0.20)",d=s.areaBottomColor??"rgba(239,83,80,0.20)",u=1e5;e.save(),e.beginPath(),e.rect(a,n-u,l-a,u),e.clip(),h(),e.fillStyle=V(e,n,c,"rgba(0,0,0,0)"),e.fill(),e.restore(),e.save(),e.beginPath(),e.rect(a,n,l-a,u),e.clip(),h(),e.fillStyle=d,e.fill(),e.restore(),e.save();for(let t=1;t<o.length;t++){const i=o[t-1],a=o[t],l=(i.y+a.y)/2<=n/r;e.strokeStyle=l?s.topColor??"#26a69a":s.bottomColor??"#ef5350",e.lineWidth=Math.max(1,Math.round((s.lineWidth??1.5)*r)),e.beginPath(),e.moveTo(i.x*r,i.y*r),e.lineTo(a.x*r,a.y*r),e.stroke()}e.restore()}(e,t,i,s,{...n,topColor:n.topColor??o.theme.baselineTopLine,bottomColor:n.bottomColor??o.theme.baselineBottomLine,areaTopColor:n.areaTopColor??o.theme.baselineTopFill,areaBottomColor:n.areaBottomColor??o.theme.baselineBottomFill}),extents:(e,t)=>{const i=t.baseValue??0;return{min:Math.min(i,e.close),max:Math.max(i,e.close)}}}),re("column",{defaultStyle:{base:0},isPriceSeries:!1,draw:(e,t,i,r,s,n,o)=>function(e,t,i,r,s,n){const o=A(r,s),a=Math.floor(o/2),l=Math.round(i(n.base??0)*s);e.save();for(const r of t){const t=B(r,i,s);e.fillStyle=r.bar.color??n.color??(t.up?n.upColor??"#26a69a":n.downColor??"#ef5350");const h=Math.min(l,t.yClose);e.fillRect(t.cx-a,h,o,Math.max(1,Math.abs(l-t.yClose)))}e.restore()}(e,t,i,r,s,oe(n,o.theme)),extents:ee}),re("histogram",{defaultStyle:{base:0,color:"#3a4666"},isPriceSeries:!1,draw:(e,t,i,r,s,n)=>{!function(e,t,i,r,s,n=X){const o=A(r,s),a=Math.floor(o/2),l=Math.round(i(n.base)*s);let h="";for(const{x:r,bar:c}of t){const t=c.color??n.color;t!==h&&(e.fillStyle=t,h=t);const d=Math.round(r*s),u=Math.round(i(c.close)*s),p=Math.min(l,u),_=Math.max(1,Math.abs(l-u));e.fillRect(d-a,p,o,_)}}(e,t,i,r,s,{color:n.color??"#3a4666",base:n.base??0})},extents:ee});const de=19800;function ue(e){return Math.floor(e/1e3)}function pe(e){const t=e.trim(),i=/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?/.exec(t);if(null===i)throw new Error(`openalgo-charts: unparseable IST time string "${e}"`);const r=Number(i[1]),s=Number(i[2]),n=Number(i[3]),o=void 0!==i[4]?Number(i[4]):0,a=void 0!==i[5]?Number(i[5]):0,l=void 0!==i[6]?Number(i[6]):0,h=Date.UTC(r,s-1,n,o,a,l);return Math.floor(h/1e3)-de}function _e(e){const t=new Date(1e3*(e+de));return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),weekday:t.getUTCDay()}}const be=e=>e<10?`0${e}`:String(e);function fe(e){const t=_e(e);return`${be(t.hour)}:${be(t.minute)}`}function me(e){const t=_e(e);return`${be(t.hour)}:${be(t.minute)}:${be(t.second)}`}function ge(e){const t=_e(e);return`${t.year}-${be(t.month)}-${be(t.day)}`}const ve=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ye(e){const t=_e(e);return`${be(t.day)} ${ve[t.month-1]}`}const we=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function xe(e){const t=_e(e);let i=`${we[t.weekday]} ${be(t.day)} ${ve[t.month-1]} '${String(t.year).slice(-2)}`;return 0===t.hour&&0===t.minute&&0===t.second||(i+=` ${be(t.hour)}:${be(t.minute)}`,0!==t.second&&(i+=`:${be(t.second)}`)),i}function Pe(e,t){const i=_e(e),r=_e(t);return i.year!==r.year||i.month!==r.month||i.day!==r.day}const Se="Asia/Kolkata",Oe=new Map,ke={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function Me(e){let t=Oe.get(e);if(void 0===t){let i;try{i=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",weekday:"short"})}catch{throw new Error(`openalgo-charts: unknown IANA time zone "${e}"`)}t={format:i,parts:new Map,lastSecond:Number.NaN,lastParts:null},Oe.set(e,t)}return t}function Te(e){if(Oe.has(e))return!0;try{return Me(e),!0}catch{return!1}}function Ce(e,t){const i=Me(t);if(e===i.lastSecond&&null!==i.lastParts)return i.lastParts;let r=i.parts.get(e);return void 0===r&&(r=function(e,t){let i=1970,r=1,s=1,n=0,o=0,a=0,l=4;for(const h of e.formatToParts(new Date(1e3*t)))switch(h.type){case"year":i=Number(h.value);break;case"month":r=Number(h.value);break;case"day":s=Number(h.value);break;case"hour":n=Number(h.value)%24;break;case"minute":o=Number(h.value);break;case"second":a=Number(h.value);break;case"weekday":l=ke[h.value]??0}return{year:i,month:r,day:s,hour:n,minute:o,second:a,weekday:l,dayIndex:Math.floor(Date.UTC(i,r-1,s)/864e5)}}(i.format,e),i.parts.size>=4096&&i.parts.clear(),i.parts.set(e,r)),i.lastSecond=e,i.lastParts=r,r}function Ie(e,t=Se){const i=Ce(e,t);return{year:i.year,month:i.month,day:i.day,hour:i.hour,minute:i.minute,second:i.second,weekday:i.weekday}}function je(e,t=Se){return Ce(e,t).dayIndex}function Ae(e,t=Se){return Math.floor((Ce(e,t).dayIndex+3)/7)}function Le(e,t=Se){const i=Ce(e,t);return Math.floor(Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second)/1e3)-e}function ze(e,t,i=Se){return Ce(e,i).dayIndex!==Ce(t,i).dayIndex}function Fe(e,t,i=Se){return Math.floor((Ce(e,i).dayIndex+3)/7)!==Math.floor((Ce(t,i).dayIndex+3)/7)}function Be(e,t,i=Se){const r=Ce(e,i),s=Ce(t,i);return r.year!==s.year||r.month!==s.month}function $e(e,t,i=Se){const r=Ce(e,i),s=Ce(t,i);return r.year!==s.year||Math.floor((r.month-1)/3)!==Math.floor((s.month-1)/3)}function Ne(e,t,i=Se){return Ce(e,i).year!==Ce(t,i).year}function De(e,t,i,r=Se){switch(i){case"week":return Fe(e,t,r);case"month":return Be(e,t,r);case"quarter":return $e(e,t,r);case"year":return Ne(e,t,r);default:return ze(e,t,r)}}function Re(e,t=Se){const i=e.trim(),r=/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?/.exec(i);if(null===r)throw new Error(`openalgo-charts: unparseable time string "${e}"`);return Ee(Number(r[1]),Number(r[2]),Number(r[3]),void 0!==r[4]?Number(r[4]):0,void 0!==r[5]?Number(r[5]):0,void 0!==r[6]?Number(r[6]):0,t)}function Ee(e,t,i,r=0,s=0,n=0,o=Se){const a=Math.floor(Date.UTC(e,t-1,i,r,s,n)/1e3),l=a-Le(a,o);return a-Le(l,o)}function We(e,t=Se){const i=Ce(e,t);return Ee(i.year,i.month,i.day,0,0,0,t)}function qe(e,t=Se){const i=Ce(e,t),r=(i.weekday+6)%7,s=new Date(Date.UTC(i.year,i.month-1,i.day-r));return Ee(s.getUTCFullYear(),s.getUTCMonth()+1,s.getUTCDate(),0,0,0,t)}function He(e,t=Se){const i=Ce(e,t);return Ee(i.year,i.month,1,0,0,0,t)}function Ve(e,t=Se){const i=Ce(e,t);return`${be(i.hour)}:${be(i.minute)}`}function Ge(e,t=Se){const i=Ce(e,t);return`${be(i.hour)}:${be(i.minute)}:${be(i.second)}`}function Ue(e,t=Se){const i=Ce(e,t);return`${be(i.day)} ${ve[i.month-1]}`}function Ye(e,t=Se){const i=Ce(e,t);return`${i.year}-${be(i.month)}-${be(i.day)}`}function Ke(e,t=Se){const i=Ce(e,t);let r=`${we[i.weekday]} ${be(i.day)} ${ve[i.month-1]} '${String(i.year).slice(-2)}`;return 0===i.hour&&0===i.minute&&0===i.second||(r+=` ${be(i.hour)}:${be(i.minute)}`,0!==i.second&&(r+=`:${be(i.second)}`)),r}function Xe(e){const t=function(e){const t=[];for(let i=1;i<e.length;i++){const r=e[i]-e[i-1];r>0&&t.push(r)}return 0===t.length?0:(t.sort((e,t)=>e-t),t[t.length>>1])}(e);if(t<=0||t>=86400)return null;const i=Math.max(4*t,14400),r=[];for(let t=1;t<e.length;t++)e[t]-e[t-1]>=i&&r.push(t);if(0===r.length)return null;const s=[e[0],...r.map(t=>e[t])],n=[];for(let e=1;e<s.length;e++)n.push(s[e]-s[e-1]);return n.sort((e,t)=>e-t),n[n.length>>1]>129600?null:r}function Je(e,t=Se){const i=new Array(e.length).fill(!1),r=Xe(e);if(null===r){const r=t===Se?Pe:(e,i)=>ze(e,i,t);for(let t=1;t<e.length;t++)i[t]=r(e[t-1],e[t]);return i}for(const e of r)i[e]=!0;return i}function Ze(e,t){const i=new Array(e.length).fill(!1),r=Xe(e);if(null===r){for(let r=1;r<e.length;r++)i[r]=t(e[r-1],e[r]);return i}let s=e[0];for(const n of r)t(s,e[n])&&(i[n]=!0),s=e[n];return i}const Qe=/^\s*(\d{2})(\d{2})\s*-\s*(\d{2})(\d{2})(?:\s*:\s*([1-7]+))?\s*$/;function et(e,t){const i=Number(e),r=Number(t);return i>23||r>59?-1:60*i+r}function tt(e){const t=Qe.exec(e);if(null===t)return null;const i=et(t[1],t[2]),r=et(t[3],t[4]);return i<0||r<0?null:void 0===t[5]?{start:i,end:r}:{start:i,end:r,days:[...t[5]].map(Number)}}function it(e,t){const i=60*e.hour+e.minute,r=t.end<=t.start,s=i<t.end;if(!(r?i>=t.start||s:i>=t.start&&s))return!1;if(void 0===t.days)return!0;const n=r&&s?(e.weekday+6)%7:e.weekday;return t.days.includes(n+1)}function rt(e,t,i=Se){return it(Ce(e,i),t)}function st(e,t,i=Se){const r=new Array(e.length).fill(!1),s="string"==typeof t?tt(t):t;if(null===s)return r;for(let t=0;t<e.length;t++)r[t]=it(Ce(e[t],i),s);return r}const nt={textColor:"#8b91a7",lineColor:"#2a3046",font:"11px system-ui, sans-serif"};function ot(e){return!Number.isFinite(e)||e<=0?2:Math.max(2,Math.min(30,Math.round(e/32)))}const at=90,lt=30,ht=10;function ct(e,t=0){const i=new Array(e.length).fill(!1),r=e.map((e,t)=>t);r.sort((t,i)=>e[i].priority-e[t].priority||t-i);const s=[];for(const n of r){const r=e[n];if(!Number.isFinite(r.y)||!Number.isFinite(r.height))continue;let o=!0;for(const e of s)if(Math.abs(e.y-r.y)<(e.height+r.height)/2+t){o=!1;break}o&&(i[n]=!0,s.push(r))}return i}function dt(e,t,i,r){if(void 0===r||0===r.length)return null;return ct([...e.map(e=>({y:Math.round(t.priceToY(e)*i),height:16*i,priority:ht})),...r],2*i).slice(0,e.length)}function ut(e,t,i,r){const s=r?"timeWithSeconds":"time";if(i===Se){const i=_e(e),r=_e(t);return i.year!==r.year?"year":i.month!==r.month?"month":i.day!==r.day?"day":s}return Ne(e,t,i)?"year":Be(e,t,i)?"month":ze(e,t,i)?"day":s}function pt(e,t,i){const r=[];for(let s=e;s<=t;s+=i)r.push(s);return r}function _t(e,t=64){const i=e.baseIndex,r=[];let s;for(let n=Math.max(0,i-t);n<=i;n++){const t=e.indexToTime(n);void 0!==t&&(void 0!==s&&t-s>0&&r.push(t-s),s=t)}return 0===r.length?0:(r.sort((e,t)=>e-t),r[r.length>>1])}const bt=e=>e<10?`0${e}`:String(e);function ft(e,t=!1){return(t?28:16)*e}function mt(e,t,i,r,s,n,o,a){const l=e.measureText(n).width;e.fillStyle=o,e.fillRect(t+1,i-r/2,l+2*s,r),e.fillStyle=a,e.fillText(n,t+1+s,i)}function gt(e,t,i,r,s,n,o=nt){if(!Number.isFinite(i))return;const a=Math.round(t.priceToY(i)*n);a<0||a>s.plotHeight*n||(e.save(),e.font=wt(o.font,n),e.textAlign="left",e.textBaseline="middle",mt(e,Math.round(s.plotWidth*n),a,ft(n),6*n,t.format(i),r,D(r)),e.restore())}function vt(e,t,i,r,s,n,o=nt,a={up:"#26a69a",down:"#ef5350",text:"#0d0e12"},l=!0,h=!0,c){if(!l&&!h)return;const d=Math.round(t.priceToY(i)*n);if(d<0||d>s.plotHeight*n)return;const u=r?a.up:a.down,p=Math.round(s.plotWidth*n);if(e.save(),l&&(e.strokeStyle=u,e.lineWidth=Math.max(1,Math.round(n)),e.setLineDash([3*n,3*n]),e.beginPath(),e.moveTo(0,d+.5),e.lineTo(p,d+.5),e.stroke(),e.setLineDash([])),h){const r=t.format(i),s=void 0!==c&&!0===c.visible,l=wt(o.font,n);e.font=l;const h=6*n,_=ft(n,s);if(e.textAlign="left",e.textBaseline="middle",s){const t=function(e){if(null===e||!Number.isFinite(e))return"--:--:--";const t=Math.max(0,Math.ceil(e));return`${bt(Math.floor(t/3600))}:${bt(Math.floor(t%3600/60))}:${bt(t%60)}`}(function(e,t,i){if(!Number.isFinite(t)||t<=0)return null;if(!Number.isFinite(e)||!Number.isFinite(i))return null;const r=i-e;return r<0?t-r:t-r%t}(c.lastBarTime,c.intervalSec,c.now())),i=wt(o.font,.9*n),s=e.measureText(r).width;e.font=i;const b=e.measureText(t).width;e.fillStyle=u,e.fillRect(p+1,d-_/2,Math.max(s,b)+2*h,_),e.fillStyle=a.text,e.font=l,e.fillText(r,p+1+h,d-_/4),e.font=i,e.fillText(t,p+1+h,d+_/4)}else mt(e,p,d,_,h,r,u,a.text)}e.restore()}function yt(e,t,i,r,s=nt){if(!0!==r.visible)return;if(t.timeAxisHeight<=0||t.priceAxisWidth<=0)return;const n=r.now();if(!Number.isFinite(n))return;const o=Math.floor(n),a=void 0!==r.timezone&&r.timezone!==Se&&Te(r.timezone)?r.timezone:Se,l=a===Se,h=l?me(o):Ge(o,a),c=l?de:Le(o,a),d=Math.round((t.plotWidth+t.priceAxisWidth/2)*i),u=Math.round(t.plotHeight*i),p=t.timeAxisHeight*i,_=!1!==r.showOffset&&t.timeAxisHeight>=20;e.save(),e.fillStyle=s.textColor,e.textAlign="center",e.textBaseline="middle",e.font=wt(s.font,i),_?(e.fillText(h,d,u+.3*p),e.font=wt(s.font,.82*i),e.fillText(function(e){const t=Math.round(e/60);if(0===t)return"UTC";const i=Math.abs(t),r=i%60;return`UTC${t<0?"-":"+"}${Math.floor(i/60)}${0===r?"":`:${bt(r)}`}`}(c),d,u+.74*p)):e.fillText(h,d,u+p/2),e.restore()}function wt(e,t){return e.replace(/(^|[^\d.])(\d{1,5}(?:\.\d{1,4})?)px/,(e,i,r)=>`${i}${Number(r)*t}px`)}function xt(e,t,i){return{color:t?.color??e.crosshair,width:t?.width??e.crosshairWidth??1,dash:S(t?.style??e.crosshairStyle??"dashed",i)}}function Pt(e,t,i,r,s,n,o,a=1,l=[4*n,4*n]){if(e.save(),e.strokeStyle=o,e.lineWidth=Math.max(1,a),e.setLineDash(l),t>=0&&t<=r){const i=Math.round(t*n)+.5;e.beginPath(),e.moveTo(i,0),e.lineTo(i,Math.round(s*n)),e.stroke()}if(null!==i&&i>=0&&i<=s){const t=Math.round(i*n)+.5;e.beginPath(),e.moveTo(0,t),e.lineTo(Math.round(r*n),t),e.stroke()}e.setLineDash([]),e.restore()}function St(e){const t={top:2,normal:1,bottom:0};let i=null;for(const r of e)null!==r&&(null===i||r.distance<i.distance||r.distance===i.distance&&t[r.zOrder]>t[i.zOrder])&&(i=r);return i}function Ot(e){return"canvas2d"===e.kind||void 0===e.device?null:e.device.lost?"context-lost":e.device.available?null:"unavailable"}const kt=new Map;function Mt(e,t){kt.set(e,t)}function Tt(e){return"canvas2d"!==e&&kt.delete(e)}function Ct(){return Array.from(kt.keys())}function It(e="canvas2d"){const t=kt.get("canvas2d");if(void 0===t)throw new Error("openalgo-charts: no canvas2d render backend is registered");if("auto"===e){const e=kt.get("webgl2");return void 0===e?t:()=>e()??t()}const i=kt.get(e);if(void 0===i)throw new Error(`openalgo-charts: render backend "${e}" is not registered; import the tier that provides it first`);return"canvas2d"===e?i:()=>i()??t()}function jt(e="canvas2d"){const t=It(e)();if(null===t)throw new Error("openalgo-charts: the canvas2d render backend factory returned null");return t}class At{constructor(){Object.defineProperty(this,"kind",{enumerable:!0,configurable:!0,writable:!0,value:"canvas2d"}),Object.defineProperty(this,"_canvas",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_ctx",{enumerable:!0,configurable:!0,writable:!0,value:null})}mount(e,t){if(this._canvas=e,this._ctx=t??e.getContext("2d"),null===this._ctx)throw new Error("openalgo-charts: 2D canvas context is not available")}resize(e,t,i){}beginFrame(e){e&&null!==this._ctx&&null!==this._canvas&&(this._ctx.setTransform(1,0,0,1,0,0),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height))}drawSeries(e,t,i,r,s,n,o){null!==this._ctx&&e.draw(this._ctx,t,i,r,s,n,o)}endFrame(){}overlay2d(){return this._ctx}destroy(){this._ctx=null,this._canvas=null}}function Lt(e,t){if("string"==typeof e.color)return e.color;const i=t?e.upColor:e.downColor;return"string"==typeof i?i:"string"==typeof e.closeColor?e.closeColor:void 0}Mt("canvas2d",()=>new At);class zt{constructor(e,t=new At){Object.defineProperty(this,"element",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"base",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"top",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_backend",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_rightScale",{enumerable:!0,configurable:!0,writable:!0,value:new v}),Object.defineProperty(this,"_leftScale",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_overlayScales",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_ratioLocks",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"weight",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"_series",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_primitives",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_width",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_height",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.element=e.createElement("div"),this.element.style.position="relative",this.element.style.width="100%",this.element.style.flex="1 1 auto",this.element.style.overflow="hidden",this.element.style.borderTopStyle="solid",this.element.style.borderTopWidth="0px",this.element.style.boxSizing="border-box",this.base=new l(e,0),this.top=new l(e,1),this.element.appendChild(this.base.element),this.element.appendChild(this.top.element),this._backend=t,t.mount(this.base.element,this.base.ctx)}get backend(){return this._backend}setBackend(e){e!==this._backend&&(this._backend.destroy(),this._backend=e,e.mount(this.base.element,this.base.ctx),this._width>0&&this._height>0&&e.resize(this._width,this._height,this.base.pixelRatio))}get backendDegradation(){return Ot(this._backend)}get priceScale(){return this._rightScale}addSeries(e){this._scaleFor(e.scaleId),this._series.push(e)}_scaleFor(e){if("left"===e)return this._leftScale??(this._leftScale=new v);if(""===e||e.startsWith("overlay:")){let t=this._overlayScales.get(e);return t||(t=new v,this._overlayScales.set(e,t)),t}return this._rightScale}scaleFor(e){return this._scaleFor(e)}usesScale(e){return this._series.some(t=>t.scaleId===e)}moveSeriesScale(e,t){if(e===t||!this.usesScale(e)||this.usesScale(t))return!1;const i=this._scaleFor(e),r=this._scaleFor(t);"left"===t?(this._leftScale=i,this._rightScale=r):(this._rightScale=i,this._leftScale=r);for(const i of this._series)i.scaleId===e&&(i.scaleId=t);r.setFixedRange(null),r.setAutoScale(!0),r.reset();const s=this._ratioLocks.get(e);return void 0!==s&&(this._ratioLocks.delete(e),this._ratioLocks.set(t,s)),!0}ratioLocked(e){return this._ratioLocks.has(e)}setRatioLock(e,t,i,r){if(!t)return this._ratioLocks.delete(e),!0;const s=this._scaleFor(e);return!!(s.scaled&&i>0&&r>0)&&(s.setAutoScale(!1),this._ratioLocks.set(e,{barSpacing:i,height:r}),!0)}clearRatioLocks(){this._ratioLocks.clear()}scaleOf(e){return this._scaleFor(e.scaleId)}scales(){const e=[this.priceScale];return null!==this._leftScale&&e.push(this._leftScale),e.push(...this._overlayScales.values()),e}axisScales(){const e=[this.priceScale];return null!==this._leftScale&&e.push(this._leftScale),e}hasLeftScale(){return null!==this._leftScale&&this._series.some(e=>"left"===e.scaleId)}removeSeries(e){const t=this._series.indexOf(e);return!(t<0)&&(this._series.splice(t,1),this._series.some(t=>t.scaleId===e.scaleId)||(this._scaleFor(e.scaleId).reset(),""!==e.scaleId&&this._overlayScales.delete(e.scaleId)&&this._ratioLocks.delete(e.scaleId)),!0)}series(){return this._series}primitives(){return this._primitives}addPrimitive(e,t){this._primitives.push(e),e.attached?.(t)}hasPrimitive(e){return this._primitives.includes(e)}removePrimitive(e){const t=this._primitives.indexOf(e);return!(t<0)&&(this._primitives.splice(t,1),e.detached?.(),!0)}destroy(){for(const e of this._primitives)e.detached?.();this._primitives.length=0,this._backend.destroy(),this.element.remove()}_primitiveContext(e){const t=this._layout(e);return{timeScale:e.timeScale,priceScale:this.priceScale,readoutPriceScale:this._readoutScale(),dataLayer:e.dataLayer,plotWidth:t.plotWidth,plotHeight:t.plotHeight,priceAxisWidth:e.priceAxisWidth,dpr:e.dpr,theme:e.theme,hoverId:e.hoverId??null,dragId:e.dragId??null,bars:()=>{for(const t of this._series)if(se(t.type).isPriceSeries)return e.dataLayer.seriesBars(t.dataId);return[]}}}hitTestPrimitives(e,t,i){const r=this._primitiveContext(i);return St(this._primitives.map(i=>i.hitTest?i.hitTest(e,t,r):null))}resize(e,t,i){this._width=e,this._height=t,this.base.resize(e,t,i),this.top.resize(e,t,i),this._backend.resize(e,t,i)}setLayoutSize(e,t){this._width=e,this._height=t}setScaleHeights(e){this.priceScale.setHeight(e),this._leftScale?.setHeight(e);for(const t of this._overlayScales.values())t.setHeight(e)}_layout(e){const t=e.leftAxisWidth??0;return{plotWidth:Math.max(0,this._width-e.priceAxisWidth-t),plotHeight:Math.max(0,this._height-(e.showTimeAxis?e.timeAxisHeight:0)),priceAxisWidth:e.priceAxisWidth,timeAxisHeight:e.showTimeAxis?e.timeAxisHeight:0,plotLeft:t}}autoscale(e,t=1){let i=!1;const r=this._layout(e),s=e.timeScale.visibleRange();i=this._autoscaleScale(this.priceScale,e=>"right"===e.scaleId,!0,e,r.plotHeight,s,t)||i,this._leftScale&&(i=this._autoscaleScale(this._leftScale,e=>"left"===e.scaleId,!1,e,r.plotHeight,s,t)||i);for(const[n,o]of this._overlayScales)i=this._autoscaleScale(o,e=>e.scaleId===n,!1,e,r.plotHeight,s,t)||i;this._ratioLocks.size>0&&this._applyRatioLocks(e.timeScale.barSpacing,r.plotHeight);for(const e of this._primitives)e.afterAutoscale?.();return i}_autoscaleScale(e,t,i,r,s,n,o){e.setHeight(s);const a=e.options.mode;if("percentage"!==a&&"indexed-to-100"!==a||e.setBaseline(this._firstVisibleValue(t,r,n)),!e.autoScale)return!1;let l=1/0,h=-1/0;for(const e of this._series){if(!1===e.style.visible||!t(e))continue;const i=se(e.type),s=e.style.barOffset??0;for(const t of r.dataLayer.visibleBars(e.dataId,n.from-s,n.to-s)){const r=i.extents(t.bar,e.style);r.min<l&&(l=r.min),r.max>h&&(h=r.max)}}if(i)for(const e of this._primitives){const t=e.autoscaleInfo?.();t&&(t.min<l&&(l=t.min),t.max>h&&(h=t.max))}return l<=h&&e.autoscale(l,h,o)}_applyRatioLocks(e,t){if(e>0&&t>0)for(const[i,r]of this._ratioLocks){const s=t/e/(r.height/r.barSpacing);if(r.barSpacing=e,r.height=t,!isFinite(s)||s<=0||Math.abs(s-1)<1e-9)continue;const n=this._scaleFor(i);n.scaled&&this._scaleSpan(n,s)}}_scaleSpan(e,t){const i=e.height;if(!(i>0))return;const r=i/2*t,s=e.yToPrice(i/2-r),n=e.yToPrice(i/2+r);isFinite(s)&&isFinite(n)&&s!==n&&e.setPriceRange({min:Math.min(s,n),max:Math.max(s,n)})}_firstVisibleValue(e,t,i){for(const r of this._series)if(!1!==r.style.visible&&e(r))for(const e of t.dataLayer.visibleBars(r.dataId,i.from,i.to))if(isFinite(e.bar.close))return e.bar.close;return null}paintBase(e,t){const i=this._layout(e),r=e.dpr,s=t??this._backend.overlay2d()??this.base.ctx;void 0===t&&this._backend.beginFrame(!0);const n=C(e.theme,e.canvasOptions?.scales);!1!==e.paintBackground&&"transparent"!==e.theme.background&&(s.fillStyle=e.theme.background,s.fillRect(0,0,Math.round(this._width*r),Math.round(this._height*r))),this._leftScale&&i.plotLeft>0&&this._leftScale.scaled&&function(e,t,i,r,s,n=nt,o){const a=t.ticks(ot(r)),l=dt(a,t,s,o),h=Math.round(i*s);e.save(),e.strokeStyle=n.lineColor,e.fillStyle=n.textColor,e.font=wt(n.font,s),e.textAlign="right",e.textBaseline="middle",e.lineWidth=1,e.beginPath(),e.moveTo(h-.5,0),e.lineTo(h-.5,Math.round(r*s)),e.stroke();for(let i=0;i<a.length;i++){if(null!==l&&!l[i])continue;const n=a[i],o=Math.round(t.priceToY(n)*s);o<0||o>r*s||e.fillText(t.format(n),h-6*s,o)}e.restore()}(s,this._leftScale,i.plotLeft,i.plotHeight,r,n),s.save(),i.plotLeft>0&&s.translate(Math.round(i.plotLeft*r),0);const o=e.canvasOptions?.grid,a=function(e,t,i){const r=Math.max(1,i.spacing),s=[];if(!1!==i.vertLines)for(let t=r;t<e;t+=r)s.push(t);const n=[];if(!1!==i.horzLines)for(let e=r;e<t;e+=r)n.push(e);return{verticals:s,horizontals:n}}(i.plotWidth,i.plotHeight,{...o,spacing:o?.spacing??60,vertLines:e.showVertGrid,horzLines:e.showHorzGrid});(a.verticals.length>0||a.horizontals.length>0)&&function(e,t,i,r,s,n){e.save(),e.lineWidth=Math.max(1,Math.round(n.lineWidth*s));const o=Math.round(i*s),a=Math.round(r*s);k(e,t.verticals,!0,n.vert,n,s,o,a),k(e,t.horizontals,!1,n.horz,n,s,o,a),e.setLineDash([]),e.restore()}(s,a,i.plotWidth,i.plotHeight,r,O(e.theme,o,r)),s.save(),s.beginPath(),s.rect(0,0,Math.round(i.plotWidth*r),Math.round(i.plotHeight*r)),s.clip();const l=this._primitiveContext(e);for(const e of this._primitives)"bottom"===e.zOrder()&&e.draw(s,l);const h=e.timeScale.visibleRange(),c=this._readoutScale();let d=null;const u=[],p=e.conflate?ae(e.timeScale.barSpacing,r,.5,e.conflationFactor):1;for(const n of this._series){if(!1===n.style.visible)continue;const o=this._scaleFor(n.scaleId),a=e=>o.priceToY(e),l=se(n.type),_=n.style.barOffset??0,b=e.dataLayer.visibleBars(n.dataId,h.from-_,h.to-_);let f=b.map(t=>({x:e.timeScale.indexToX(t.index+_),bar:t.bar}));if(p>1&&(f=ce(f,p)),!0===n.style.colorByPreviousClose&&f.length>0){const t=e.dataLayer.visibleBars(n.dataId,b[0].index-1,b[0].index-1);t.length>0&&(f[0].prevClose=t[0].bar.close)}let m=0;for(const e of f)(e.bar.volume??0)>m&&(m=e.bar.volume??0);const g={plotHeight:i.plotHeight,maxVolume:m,theme:e.theme};if(void 0===t?this._backend.drawSeries(l,f,a,e.timeScale.barSpacing,r,n.style,g):l.draw(s,f,a,e.timeScale.barSpacing,r,n.style,g),o===c){const t=e.dataLayer.lastIndexedBar(n.dataId);if(null!==t&&l.isPriceSeries&&null===d)d={close:t.bar.close,up:t.bar.close>=t.bar.open,showLine:!1!==n.style.priceLineVisible,showTag:!1!==n.style.lastValueVisible};else if(null!==t&&!1!==n.style.lastValueVisible){const e=Lt(n.style,t.bar.close>=t.bar.open);void 0!==e&&Number.isFinite(t.bar.close)&&u.push({price:t.bar.close,color:e})}}}void 0===t&&this._backend.endFrame(),s.restore();const _=null!==d&&d.showTag&&c===this._rightScale,b=!0===e.barCountdown?.visible,f=e=>e>=0&&e<=i.plotHeight*r,m=[];if(null!==d&&_){const e=Math.round(c.priceToY(d.close)*r);f(e)&&m.push({y:e,height:ft(r,b),priority:at})}const g=m.length,v=c===this._rightScale;if(v)for(const e of u){const t=Math.round(c.priceToY(e.price)*r);m.push({y:t,height:f(t)?ft(r):NaN,priority:lt})}const y=m.length>0?ct(m,2*r):[],w=m.length>0?m.filter((e,t)=>y[t]):void 0;if(this.priceScale.scaled&&function(e,t,i,r,s=nt,n){const o=t.ticks(ot(i.plotHeight)),a=dt(o,t,r,n),l=Math.round(i.plotWidth*r);e.save(),e.strokeStyle=s.lineColor,e.fillStyle=s.textColor,e.font=wt(s.font,r),e.textAlign="left",e.textBaseline="middle",e.lineWidth=1,e.beginPath(),e.moveTo(l+.5,0),e.lineTo(l+.5,Math.round(i.plotHeight*r)),e.stroke();for(let s=0;s<o.length;s++){if(null!==a&&!a[s])continue;const n=o[s],h=Math.round(t.priceToY(n)*r);h<0||h>i.plotHeight*r||e.fillText(t.format(n),l+6*r,h)}e.restore()}(s,this.priceScale,i,r,n,w),v)for(let e=0;e<u.length;e++)y[g+e]&>(s,c,u[e].price,u[e].color,i,r,n);null!==d&&vt(s,c,d.close,d.up,i,r,n,{up:e.theme.lastPriceUp,down:e.theme.lastPriceDown,text:e.theme.lastPriceText},d.showLine,_,e.barCountdown);for(const e of this._primitives)"normal"===e.zOrder()&&e.draw(s,l);e.showTimeAxis&&(!function(e,t,i,r,s,n=nt,o,a){const l=t.visibleRange(),h=Math.max(0,Math.floor(l.from)),c=Math.min(i.baseIndex,Math.ceil(l.to));if(c<h)return;const d=Math.max(1,Math.round(80/Math.max(1,t.barSpacing))),u=Math.round(r.plotHeight*s);let p=Number.POSITIVE_INFINITY;{let e=i.indexToTime(h);for(let t=h+1;t<=c;t++){const r=i.indexToTime(t);if(void 0!==r&&void 0!==e){const t=r-e;t>0&&t<p&&(p=t)}void 0!==r&&(e=r)}}const _=p*d,b=Number.isFinite(_)&&_<60,f=void 0!==a&&a!==Se&&Te(a)?a:Se,m=f===Se,g=m?Pe:(e,t)=>ze(e,t,f),v=m?ye:e=>Ue(e,f),y=m?fe:e=>Ve(e,f),w=m?me:e=>Ge(e,f);e.save(),e.fillStyle=n.textColor,e.strokeStyle=n.lineColor,e.font=wt(n.font,s),e.textAlign="center",e.textBaseline="top",e.lineWidth=1,e.beginPath(),e.moveTo(0,u+.5),e.lineTo(Math.round(r.plotWidth*s),u+.5),e.stroke();const x=new Set;{let e=i.indexToTime(h);for(let t=h+1;t<=c;t++){const r=i.indexToTime(t);void 0!==r&&(void 0!==e&&g(e,r)&&x.add(t),e=r)}}const P=[...new Set([...pt(h,c,d),...x])].sort((e,t)=>e-t),S=[];let O;for(const n of P){const a=i.indexToTime(n);if(void 0===a)continue;const l=Math.round(t.indexToX(n)*s);if(l<0||l>r.plotWidth*s){O=a;continue}let h;h=o?o(a,void 0===O?"day":ut(O,a,f,b)):void 0===O||g(O,a)?v(a):b?w(a):y(a),S.push({x:l,text:h,half:e.measureText(h).width/2,boundary:x.has(n)}),O=a}const k=4*s,M=[],T=e=>M.every(t=>e.x+e.half+k<=t.x-t.half||e.x-e.half-k>=t.x+t.half);for(const e of S)e.boundary&&T(e)&&M.push(e);for(const e of S)!e.boundary&&T(e)&&M.push(e);M.sort((e,t)=>e.x-t.x);for(const t of M)e.fillText(t.text,t.x,u+4*s);e.restore()}(s,e.timeScale,e.dataLayer,i,r,n,e.timeFormatter,e.timezone),void 0!==e.sessionClock&&yt(s,i,r,e.sessionClock,n)),s.restore()}paintTop(e,t,i){void 0===i&&this.top.clearBitmap();const r=this._layout(t),s=i??this.top.ctx,n=t.dpr;s.save(),r.plotLeft>0&&s.translate(Math.round(r.plotLeft*n),0);const o=this._primitiveContext(t);for(const e of this._primitives)"top"===e.zOrder()&&e.draw(s,o);if(null!==e){const i=xt(t.theme,t.canvasOptions?.crosshair,n);Pt(s,e.x,e.yLocal,r.plotWidth,r.plotHeight,n,i.color,i.width,i.dash);const o=t.theme.crosshairLabelBackground??i.color,a=!1!==t.theme.crosshairLabelVisible;if(a&&null!==e.yLocal){const i=this._readoutScale(),a=i.format(i.yToPrice(e.yLocal));!function(e,t,i,r,s,n,o){e.save(),e.font=11*s+"px system-ui, sans-serif";const a=6*s,l=16*s,h=e.measureText(t).width;e.fillStyle=n,e.textBaseline="middle",e.fillRect(i+1,r-l/2,h+2*a,l),e.fillStyle=o,e.textAlign="left",e.fillText(t,i+1+a,r),e.restore()}(s,a,i===this._leftScale&&r.plotLeft>0?-this._tagWidth(s,a,n):r.plotWidth*n,e.yLocal*n,n,o,t.theme.lastPriceText)}if(a&&e.showTimeTag&&e.x>=0&&e.x<=r.plotWidth){const i=Math.round(t.timeScale.xToIndex(e.x)),a=t.dataLayer.indexToTime(i);if(void 0!==a){!function(e,t,i,r,s,n,o=nt){e.save(),e.font=wt(o.font,s);const a=7*s,l=18*s,h=e.measureText(t).width+2*a,c=Math.max(0,i-h/2),d=r+1*s,u=(n.radius??4)*s;e.beginPath(),q(e,c,d,h,l,u),void 0!==n.backplate&&(e.fillStyle=n.backplate,e.fill()),e.fillStyle=n.background,e.fill(),void 0!==n.border&&(e.strokeStyle=n.border,e.lineWidth=Math.max(1,Math.round(s)),e.stroke()),e.fillStyle=n.textColor,e.textAlign="center",e.textBaseline="middle",e.fillText(t,c+h/2,d+l/2),e.restore()}(s,t.timeFormatter?t.timeFormatter(a):Ke(a,t.timezone??Se),e.x*n,r.plotHeight*n,n,{background:o,textColor:t.theme.lastPriceText,backplate:t.theme.background},C(t.theme,t.canvasOptions?.scales))}}}s.restore()}_readoutScale(){for(const e of this._series)if(!1!==e.style.visible&&se(e.type).isPriceSeries)return this._scaleFor(e.scaleId);return this._rightScale}readoutScale(){return this._readoutScale()}priceToY(e){return this._readoutScale().priceToY(e)}_tagWidth(e,t,i){e.save(),e.font=11*i+"px system-ui, sans-serif";const r=e.measureText(t).width+12*i+1;return e.restore(),r}yToPrice(e){return this._readoutScale().yToPrice(e)}}const Ft={background:"#0d0e12",grid:"#161a26",axisText:"#8b91a7",axisLine:"#2a3046",paneSeparator:"#1e2334",crosshair:"#6b7280",upColor:"#26a69a",downColor:"#ef5350",wickUpColor:"#26a69a",wickDownColor:"#ef5350",lineColor:"#4f8cff",areaTopColor:"rgba(79,140,255,0.40)",areaBottomColor:"rgba(79,140,255,0.00)",baselineTopLine:"#26a69a",baselineTopFill:"rgba(38,166,154,0.20)",baselineBottomLine:"#ef5350",baselineBottomFill:"rgba(239,83,80,0.20)",lastPriceUp:"#26a69a",lastPriceDown:"#ef5350",lastPriceText:"#0d0e12",buy:"#26a69a",sell:"#ef5350",profit:"#26a69a",loss:"#ef5350"},Bt={background:"#ffffff",grid:"#eef1f6",axisText:"#5b6472",axisLine:"#d4dae3",paneSeparator:"#e6eaf0",crosshair:"#9aa3b2",upColor:"#089981",downColor:"#e0473e",wickUpColor:"#089981",wickDownColor:"#e0473e",lineColor:"#2962ff",areaTopColor:"rgba(41,98,255,0.30)",areaBottomColor:"rgba(41,98,255,0.00)",baselineTopLine:"#089981",baselineTopFill:"rgba(8,153,129,0.18)",baselineBottomLine:"#e0473e",baselineBottomFill:"rgba(224,71,62,0.18)",lastPriceUp:"#089981",lastPriceDown:"#e0473e",lastPriceText:"#ffffff",buy:"#089981",sell:"#e0473e",profit:"#089981",loss:"#e0473e"},$t=Bt;class Nt{constructor(e,t,i,r,s){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"x0",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"y0",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"x1",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"y1",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"stops",{enumerable:!0,configurable:!0,writable:!0,value:[]})}addColorStop(e,t){this.stops.push({offset:e,color:t})}toString(){return`url(#${this.id})`}}const Dt=2*Math.PI;function Rt(e){if(!Number.isFinite(e))return"0";const t=Math.round(100*e)/100;return String(0===t?0:t)}function Et(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Wt(e){return/[ .,:;'|!iIljtfr[\]()-]/.test(e)?.3:/[mwMW@%]/.test(e)?.9:/[A-Z]/.test(e)?.68:.55}function qt(e){const t=e.trim().split(/\s+/);let i=null,r=null,s=10,n=0;for(;n<t.length;n++){const e=t[n],o=/^(\d+(?:\.\d+)?)(px|pt)(?:\/\S+)?$/.exec(e);if(null!==o){s=parseFloat(o[1])*("pt"===o[2]?4/3:1),n++;break}"italic"===e||"oblique"===e?r=e:/^(\d{3}|bold|bolder|lighter)$/.test(e)&&(i=e)}return{size:s,family:t.slice(n).join(" ")||"sans-serif",weight:i,style:r}}const Ht={top:"text-before-edge",hanging:"hanging",middle:"central",ideographic:"ideographic",bottom:"text-after-edge"},Vt={center:"middle",right:"end",end:"end"};class Gt{constructor(e,t,i={}){Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"fillStyle",{enumerable:!0,configurable:!0,writable:!0,value:"#000"}),Object.defineProperty(this,"strokeStyle",{enumerable:!0,configurable:!0,writable:!0,value:"#000"}),Object.defineProperty(this,"lineWidth",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"lineCap",{enumerable:!0,configurable:!0,writable:!0,value:"butt"}),Object.defineProperty(this,"lineJoin",{enumerable:!0,configurable:!0,writable:!0,value:"miter"}),Object.defineProperty(this,"miterLimit",{enumerable:!0,configurable:!0,writable:!0,value:10}),Object.defineProperty(this,"globalAlpha",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"font",{enumerable:!0,configurable:!0,writable:!0,value:"10px sans-serif"}),Object.defineProperty(this,"textAlign",{enumerable:!0,configurable:!0,writable:!0,value:"start"}),Object.defineProperty(this,"textBaseline",{enumerable:!0,configurable:!0,writable:!0,value:"alphabetic"}),Object.defineProperty(this,"shadowColor",{enumerable:!0,configurable:!0,writable:!0,value:"rgba(0, 0, 0, 0)"}),Object.defineProperty(this,"shadowBlur",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"shadowOffsetX",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"shadowOffsetY",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"globalCompositeOperation",{enumerable:!0,configurable:!0,writable:!0,value:"source-over"}),Object.defineProperty(this,"imageSmoothingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"canvas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"unsupported",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_out",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_frames",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_gradients",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_clips",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_rootOpen",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_path",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"_hasPoint",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_dash",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_ids",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_strict",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_background",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_fontCache",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._strict=!0===i.strict,this._background=i.background}asCanvasContext(){return this}save(){this._frames.push({kind:"save",open:0,state:this._snapshot()})}restore(){let e=this._frames.length-1;for(;e>=0&&"save"!==this._frames[e].kind;)e--;if(!(e<0)){if(e!==this._frames.length-1&&this._strict)throw new Error("SvgContext: restore() reached across an open pushGroup()");this._closeTo(e)}}pushGroup(e,t={}){let i="<g";for(const t in e)i+=` ${t}="${Et(String(e[t]))}"`;const{translate:r,clip:s}=t;if(void 0!==r&&(i+=` transform="translate(${Rt(r.x)} ${Rt(r.y)})"`),void 0!==s){i+=` clip-path="url(#${this._clipId(`<rect x="${Rt(s.x)}" y="${Rt(s.y)}" width="${Rt(s.width)}" height="${Rt(s.height)}"/>`)})"`}this._out.push(i+">"),this._frames.push({kind:"group",open:1,state:null})}popGroup(){let e=this._frames.length-1;for(;e>=0&&"group"!==this._frames[e].kind;)e--;if(e<0){if(this._strict)throw new Error("SvgContext: popGroup() without a pushGroup()")}else{if(e!==this._frames.length-1&&this._strict)throw new Error("SvgContext: popGroup() reached across an open save()");this._closeTo(e)}}translate(e,t){0===e&&0===t||this._openGroup(`transform="translate(${Rt(e)} ${Rt(t)})"`)}scale(e,t){1===e&&1===t||this._openGroup(`transform="scale(${Rt(e)} ${Rt(t)})"`)}rotate(e){0!==e&&this._openGroup(`transform="rotate(${Rt(180*e/Math.PI)})"`)}setLineDash(e){this._dash=e.slice()}getLineDash(){return this._dash.slice()}beginPath(){this._path="",this._hasPoint=!1}closePath(){""!==this._path&&(this._path+="Z")}moveTo(e,t){this._path+=`M${Rt(e)} ${Rt(t)}`,this._hasPoint=!0}lineTo(e,t){this._path+=`${this._hasPoint?"L":"M"}${Rt(e)} ${Rt(t)}`,this._hasPoint=!0}quadraticCurveTo(e,t,i,r){this._hasPoint||this.moveTo(e,t),this._path+=`Q${Rt(e)} ${Rt(t)} ${Rt(i)} ${Rt(r)}`}bezierCurveTo(e,t,i,r,s,n){this._hasPoint||this.moveTo(e,t),this._path+=`C${Rt(e)} ${Rt(t)} ${Rt(i)} ${Rt(r)} ${Rt(s)} ${Rt(n)}`}rect(e,t,i,r){this._path+=`M${Rt(e)} ${Rt(t)}h${Rt(i)}v${Rt(r)}h${Rt(-i)}Z`,this._hasPoint=!0}roundRect(e,t,i,r,s=0){const n=Array.isArray(s)?s:[s];let[o,a,l,h]=[n[0]??0,n[1]??n[0]??0,n[2]??n[0]??0,n[3]??n[1]??n[0]??0];const c=Math.min(1,i/Math.max(1e-9,o+a,h+l),r/Math.max(1e-9,o+h,a+l));o*=c,a*=c,l*=c,h*=c;const d=(e,t,i)=>e>0?`A${Rt(e)} ${Rt(e)} 0 0 1 ${Rt(t)} ${Rt(i)}`:"";this._path+=`M${Rt(e+o)} ${Rt(t)}H${Rt(e+i-a)}${d(a,e+i,t+a)}V${Rt(t+r-l)}${d(l,e+i-l,t+r)}H${Rt(e+h)}${d(h,e,t+r-h)}V${Rt(t+o)}${d(o,e+o,t)}Z`,this._hasPoint=!0}arc(e,t,i,r,s,n=!1){this.ellipse(e,t,i,i,0,r,s,n)}ellipse(e,t,i,r,s,n,o,a=!1){const l=Math.cos(s),h=Math.sin(s),c=s=>{const n=i*Math.cos(s),o=r*Math.sin(s);return[e+n*l-o*h,t+n*h+o*l]};let d,u=!1;a?(u=n-o>=Dt,d=-((n-o)%Dt+Dt)%Dt):(u=o-n>=Dt,d=((o-n)%Dt+Dt)%Dt);const[p,_]=c(n);this._path+=`${this._hasPoint?"L":"M"}${Rt(p)} ${Rt(_)}`,this._hasPoint=!0;const b=Rt(180*s/Math.PI),f=(e,t,s)=>{const[n,o]=c(e);this._path+=`A${Rt(i)} ${Rt(r)} ${b} ${t?1:0} ${s?1:0} ${Rt(n)} ${Rt(o)}`};if(u){const e=a?-Math.PI:Math.PI;f(n+e,!1,!a),f(n+2*e,!1,!a)}else 0!==d&&f(n+d,Math.abs(d)>Math.PI,d>0)}fill(e,t){if("object"==typeof e)return void this._unsupported("fill(Path2D)");if(""===this._path)return;const i=this._paint(this.fillStyle);null!==i&&this._out.push(`<path d="${this._path}" fill="${i}"${"evenodd"===e?' fill-rule="evenodd"':""}${this._opacity()}/>`)}stroke(e){if(void 0!==e)return void this._unsupported("stroke(Path2D)");if(""===this._path)return;const t=this._strokeAttrs();null!==t&&this._out.push(`<path d="${this._path}" fill="none"${t}${this._opacity()}/>`)}clip(e){if("object"==typeof e)return void this._unsupported("clip(Path2D)");if(""===this._path)return;const t=this._clipId(`<path d="${this._path}"${"evenodd"===e?' clip-rule="evenodd"':""}/>`);this._openGroup(`clip-path="url(#${t})"`)}fillRect(e,t,i,r){const s=this._paint(this.fillStyle);null!==s&&this._rect(e,t,i,r,` fill="${s}"`)}strokeRect(e,t,i,r){const s=this._strokeAttrs();null!==s&&this._rect(e,t,i,r,` fill="none"${s}`)}clearRect(e,t,i,r){void 0!==this._background&&this._rect(e,t,i,r,` fill="${Et(this._background)}"`)}fillText(e,t,i){if(""===e)return;const r=this._paint(this.fillStyle);if(null===r)return;const s=this._font();let n=` font-family="${Et(s.family)}" font-size="${Rt(s.size)}"`;null!==s.weight&&(n+=` font-weight="${s.weight}"`),null!==s.style&&(n+=` font-style="${s.style}"`);const o=Vt[this.textAlign];void 0!==o&&(n+=` text-anchor="${o}"`);const a=Ht[this.textBaseline];void 0!==a&&(n+=` dominant-baseline="${a}"`),this._out.push(`<text x="${Rt(t)}" y="${Rt(i)}"${n} fill="${r}"${this._opacity()}>${Et(e)}</text>`)}measureText(e){const t=this._font();let i=0;for(const t of e)i+=Wt(t);const r=null!==t.weight&&("bold"===t.weight||"bolder"===t.weight||parseInt(t.weight,10)>=600),s=i*t.size*(r?1.05:1);return{width:s,actualBoundingBoxLeft:0,actualBoundingBoxRight:s,actualBoundingBoxAscent:.8*t.size,actualBoundingBoxDescent:.2*t.size,fontBoundingBoxAscent:.8*t.size,fontBoundingBoxDescent:.2*t.size}}createLinearGradient(e,t,i,r){const s=new Nt("g"+ ++this._ids,e,t,i,r);return this._gradients.push(s),s}drawImage(e,...t){const i=this._imageHref(e);if(null===i)return void this._unsupported("drawImage");const r=e,s=r.naturalWidth??("number"==typeof r.width?r.width:0),n=r.naturalHeight??("number"==typeof r.height?r.height:0),o=this._opacity();if(t.length>=8){const[e,r,a,l,h,c,d,u]=t;return void this._out.push(`<svg x="${Rt(h)}" y="${Rt(c)}" width="${Rt(d)}" height="${Rt(u)}" viewBox="${Rt(e)} ${Rt(r)} ${Rt(a)} ${Rt(l)}" preserveAspectRatio="none"><image href="${Et(i)}" width="${Rt(s)}" height="${Rt(n)}" preserveAspectRatio="none"${o}/></svg>`)}const[a,l]=t,h=t.length>=4?t[2]:s,c=t.length>=4?t[3]:n;this._out.push(`<image href="${Et(i)}" x="${Rt(a)}" y="${Rt(l)}" width="${Rt(h)}" height="${Rt(c)}" preserveAspectRatio="none"${o}/>`)}setTransform(){this._unsupported("setTransform")}resetTransform(){this._unsupported("resetTransform")}getTransform(){this._unsupported("getTransform")}createRadialGradient(){this._unsupported("createRadialGradient")}createConicGradient(){this._unsupported("createConicGradient")}createPattern(){return this._unsupported("createPattern"),null}getImageData(){this._unsupported("getImageData")}putImageData(){this._unsupported("putImageData")}createImageData(){this._unsupported("createImageData")}strokeText(){this._unsupported("strokeText")}drawFocusIfNeeded(){this._unsupported("drawFocusIfNeeded")}isPointInPath(){return this._unsupported("isPointInPath"),!1}isPointInStroke(){return this._unsupported("isPointInStroke"),!1}toString(){const e=Rt(this.width),t=Rt(this.height);let i="";for(const e of this._clips)i+=e;for(const e of this._gradients){i+=`<linearGradient id="${e.id}" gradientUnits="userSpaceOnUse" x1="${Rt(e.x0)}" y1="${Rt(e.y0)}" x2="${Rt(e.x1)}" y2="${Rt(e.y1)}">`;for(const t of e.stops)i+=`<stop offset="${Rt(t.offset)}" stop-color="${Et(t.color)}"/>`;i+="</linearGradient>"}let r="";for(let e=this._frames.length-1;e>=0;e--)r+="</g>".repeat(this._frames[e].open);return r+="</g>".repeat(this._rootOpen),`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}" xml:space="preserve">`+(""===i?"":`<defs>${i}</defs>`)+this._out.join("")+r+"</svg>"}_snapshot(){return{fillStyle:this.fillStyle,strokeStyle:this.strokeStyle,lineWidth:this.lineWidth,lineCap:this.lineCap,lineJoin:this.lineJoin,miterLimit:this.miterLimit,globalAlpha:this.globalAlpha,font:this.font,textAlign:this.textAlign,textBaseline:this.textBaseline,dash:this._dash.slice()}}_apply(e){this.fillStyle=e.fillStyle,this.strokeStyle=e.strokeStyle,this.lineWidth=e.lineWidth,this.lineCap=e.lineCap,this.lineJoin=e.lineJoin,this.miterLimit=e.miterLimit,this.globalAlpha=e.globalAlpha,this.font=e.font,this.textAlign=e.textAlign,this.textBaseline=e.textBaseline,this._dash=e.dash}_closeTo(e){for(;this._frames.length>e;){const e=this._frames.pop();this._out.push("</g>".repeat(e.open)),null!==e.state&&this._apply(e.state)}}_openGroup(e){this._out.push(`<g ${e}>`);const t=this._frames[this._frames.length-1];void 0!==t?t.open++:this._rootOpen++}_clipId(e){const t="c"+ ++this._ids;return this._clips.push(`<clipPath id="${t}">${e}</clipPath>`),t}_rect(e,t,i,r,s){0!==i&&0!==r&&(i<0&&(e+=i,i=-i),r<0&&(t+=r,r=-r),this._out.push(`<rect x="${Rt(e)}" y="${Rt(t)}" width="${Rt(i)}" height="${Rt(r)}"${s}${this._opacity()}/>`))}_paint(e){return this.globalAlpha<=0?null:"string"!=typeof e?e instanceof Nt?e.toString():null:"transparent"===e?null:Et(e)}_strokeAttrs(){if(!(this.lineWidth>0))return null;const e=this._paint(this.strokeStyle);if(null===e)return null;let t=` stroke="${e}" stroke-width="${Rt(this.lineWidth)}"`;return"butt"!==this.lineCap&&(t+=` stroke-linecap="${this.lineCap}"`),"miter"!==this.lineJoin&&(t+=` stroke-linejoin="${this.lineJoin}"`),this._dash.some(e=>e>0)&&(t+=` stroke-dasharray="${this._dash.map(Rt).join(" ")}"`),t}_opacity(){return this.globalAlpha<1?` opacity="${Rt(this.globalAlpha)}"`:""}_font(){return null!==this._fontCache&&this._fontCache.font===this.font||(this._fontCache={font:this.font,parsed:qt(this.font)}),this._fontCache.parsed}_imageHref(e){const t=e;if("string"==typeof t.src&&""!==t.src)return t.src;if("function"==typeof t.toDataURL)try{return t.toDataURL.call(e)}catch{return null}return null}_unsupported(e){if(this._strict)throw new Error(`SvgContext: ${e} has no SVG form and cannot be exported`);this.unsupported.includes(e)||this.unsupported.push(e)}}const Ut=[{label:"Solid",value:"solid"},{label:"Dashed",value:"dashed"},{label:"Dotted",value:"dotted"}];function Yt(e){return{color:e.colorKey??`${e.key}:color`,width:`${e.key}:width`,lineStyle:`${e.key}:lineStyle`,opacity:`${e.key}:opacity`,type:`${e.key}:type`}}function Kt(e){const t=[];for(const i of e.plots){const r=Yt(i),s=e.inputs.find(e=>e.key===i.colorKey),n="string"==typeof s?.default?s.default:i.style?.color??"#4f8cff";t.push({key:r.color,type:"color",label:i.title,default:n,group:i.title}),t.push({key:r.opacity,type:"number",label:"Opacity",default:100,min:0,max:100,step:1,group:i.title}),t.push({key:r.width,type:"number",label:"Thickness",default:i.style?.lineWidth??1.5,min:.5,max:8,step:.5,group:i.title}),t.push({key:r.lineStyle,type:"select",label:"Line style",default:i.style?.lineStyle??"solid",options:Ut,group:i.title}),t.push({key:r.type,type:"select",label:"Plot style",default:i.type,options:Xt,group:i.title})}return t}const Xt=[{label:"Line",value:"line"},{label:"Line with markers",value:"line-markers"},{label:"Step line",value:"step"},{label:"Area",value:"area"},{label:"Histogram",value:"histogram"},{label:"Columns",value:"column"}],Jt=[{label:"Close",value:"close"},{label:"Open",value:"open"},{label:"High",value:"high"},{label:"Low",value:"low"},{label:"HL2",value:"hl2"},{label:"HLC3",value:"hlc3"},{label:"OHLC4",value:"ohlc4"}];class Zt extends Error{constructor(e){super(e),this.name="IndicatorInputError"}}const Qt=new Map;function ei(e){Qt.set(e.id,e)}function ti(e){const t=Qt.get(e);if(void 0===t)throw new Error(`openalgo-charts: unknown indicator "${e}" — did you import 'openalgo-charts/indicators'?`);return t}function ii(e){return Qt.has(e)}function ri(){return Array.from(Qt.values())}function si(e){const t={};for(const i of e.inputs)t[i.key]=i.default;return t}function ni(e,t){switch(t){case"open":return e.open;case"high":return e.high;case"low":return e.low;case"hl2":return(e.high+e.low)/2;case"hlc3":return(e.high+e.low+e.close)/3;case"ohlc4":return(e.open+e.high+e.low+e.close)/4;case"volume":return e.volume??0;default:return e.close}}function oi(e,t){const i=new Array(e.length);for(let r=0;r<e.length;r++)i[r]=ni(e[r],t);return i}class ai{constructor(e){Object.defineProperty(this,"_points",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_visible",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this._opts={opacity:.12,...e}}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"bottom"}autoscaleInfo(){return null}setPoints(e){this._points=e.slice(),this._host?.requestUpdate()}setOptions(e){this._opts={...this._opts,...e},this._host?.requestUpdate()}setVisible(e){this._visible=e,this._host?.requestUpdate()}draw(e,t){if(!this._visible||this._points.length<2)return;const i=t.dpr,r=e=>t.timeScale.indexToX(e)*i,s=e=>t.priceScale.priceToY(e)*i,n=this._opts.gradient;let o=0,a=1;if(void 0!==n){let e=n.topValue,t=n.bottomValue;if(void 0===e||void 0===t){let i=1/0,r=-1/0;const s=e=>{null!==e&&Number.isFinite(e)&&(e<i&&(i=e),e>r&&(r=e))};for(const e of this._points)s(e.a),s(e.b);e??(e=r),t??(t=i)}o=s(e),a=s(t)-o||1}e.save(),e.globalAlpha=this._opts.opacity??.12;let l=null;const h=()=>{if(null!==l&&l.xs.length>=2){e.beginPath(),e.moveTo(l.xs[0],l.top[0]);for(let t=1;t<l.xs.length;t++)e.lineTo(l.xs[t],l.top[t]);for(let t=l.xs.length-1;t>=0;t--)e.lineTo(l.xs[t],l.bot[t]);e.closePath(),void 0===n||void 0!==l.color?(e.fillStyle=l.color??(l.up?this._opts.colorUp:this._opts.colorDown),e.fill()):(e.save(),e.translate(0,o),e.fillStyle=V(e,a,n.topColor,n.bottomColor),e.fill(),e.restore())}l=null};for(let e=0;e<this._points.length;e++){const t=this._points[e];if(null===t.a||null===t.b||!Number.isFinite(t.a)||!Number.isFinite(t.b)){h();continue}const i=t.a>=t.b,n=r(t.index),o=s(t.a),a=s(t.b);if(null===l||l.up!==i||l.color===t.color){if(null!==l&&l.up!==i){const n=this._points[e-1];if(void 0!==n&&null!==n.a&&null!==n.b){const e=n.a-n.b,o=t.a-t.b,a=e===o?0:e/(e-o),c=r(n.index+(t.index-n.index)*a),d=s(n.a+(t.a-n.a)*a);l.xs.push(c),l.top.push(d),l.bot.push(d),h(),l={up:i,color:t.color,xs:[c],top:[d],bot:[d]}}else h()}null===l&&(l={up:i,color:t.color,xs:[],top:[],bot:[]}),l.xs.push(n),l.top.push(o),l.bot.push(a)}else l.xs.push(n),l.top.push(o),l.bot.push(a),h(),l={up:i,color:t.color,xs:[n],top:[o],bot:[a]}}h(),e.restore()}}function li(e,t){return"dashed"===e?[6*t,4*t]:"dotted"===e?[1*t,3*t]:[]}function hi(e,t,i,r,s,n,o,a){const l=11*t;e.font=`${l}px ui-sans-serif, system-ui, sans-serif`,e.textBaseline="middle",e.textAlign="left";const h=s.split("\n");let c=0;for(const t of h)c=Math.max(c,e.measureText(t).width);const d=5*t,u=3*t,p=1.35*l,_=c+2*d,b=p*h.length+2*u,f="center"===a?i-_/2:"right"===a?i-_:i,m=r-b/2;e.beginPath(),q(e,f,m,_,b,3*t),e.fillStyle=n,e.fill(),e.fillStyle=o??D(n);for(let t=0;t<h.length;t++)e.fillText(h[t],f+d,m+u+p*(t+.5));return{x:f,y:m,w:_,h:b}}class ci{constructor(){Object.defineProperty(this,"_items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_visible",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_hits",{enumerable:!0,configurable:!0,writable:!0,value:[]})}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"normal"}autoscaleInfo(){return null}setItems(e){this._items=e,this._host?.requestUpdate()}setVisible(e){this._visible=e,this._host?.requestUpdate()}draw(e,t){if(this._hits=[],!this._visible||0===this._items.length)return;const i=t.dpr,r=t.plotWidth*i,s=t.plotHeight*i,n=t.theme.axisText,o=200*i,a=e=>t.timeScale.indexToX(t.dataLayer.timeToIndexFloat(e.time))*i,l=e=>t.priceScale.priceToY(e.price)*i,h=(e,t,i,n)=>Math.max(e,i)<0||Math.min(e,i)>r||Math.max(t,n)<0||Math.min(t,n)>s;e.save(),e.lineJoin="round",e.lineCap="round";for(const t of this._items){if("label"===t.kind){const h=a(t.at),c=l(t.at);if(h<-o||h>r+o||c<-o||c>s+o)continue;const d=hi(e,i,h,c,t.text,t.color??n,t.textColor,t.align??"center");this._recordHit(t,d,i);continue}const c=t.color??n;if(e.lineWidth=Math.max(1,Math.round((t.lineWidth??1)*i)),"polyline"===t.kind){const i=t.points;if(i.length<2)continue;const r=new Array(i.length),s=new Array(i.length);let n=1/0,o=-1/0,d=1/0,u=-1/0;for(let e=0;e<i.length;e++){const t=a(i[e]),h=l(i[e]);r[e]=t,s[e]=h,t<n&&(n=t),t>o&&(o=t),h<d&&(d=h),h>u&&(u=h)}if(h(n,d,o,u))continue;e.beginPath(),e.moveTo(r[0],s[0]);for(let t=1;t<i.length;t++)e.lineTo(r[t],s[t]);!0===t.closed&&e.closePath(),void 0!==t.fillColor&&(e.globalAlpha=t.opacity??.12,e.fillStyle=t.fillColor,e.fill(),e.globalAlpha=1),e.setLineDash([]),e.strokeStyle=c,e.stroke();continue}let d=a(t.from),u=l(t.from),p=a(t.to),_=l(t.to);if("box"===t.kind){if(h(d,u,p,_))continue;const r=Math.min(d,p),s=Math.min(u,_),n=Math.abs(p-d),o=Math.abs(_-u);void 0!==t.fillColor&&(e.globalAlpha=t.opacity??.12,e.fillStyle=t.fillColor,e.fillRect(r,s,n,o),e.globalAlpha=1),e.setLineDash([]),e.strokeStyle=c,e.strokeRect(r,s,n,o),this._recordHit(t,{x:r,y:s,w:n,h:o},i),void 0!==t.text&&""!==t.text&&hi(e,i,r+n/2,s+o/2,t.text,c,t.textColor,"center");continue}if(!0===t.extendLeft||!0===t.extendRight){const e=p-d;if(0===e)u=0,_=s;else{const i=(_-u)/e,s=d<=p;!0===t.extendLeft&&(s?(u-=i*d,d=0):(_-=i*p,p=0)),!0===t.extendRight&&(s?(_+=i*(r-p),p=r):(u+=i*(r-d),d=r))}}h(d,u,p,_)||(e.setLineDash(li(t.lineStyle,i)),e.strokeStyle=c,e.beginPath(),e.moveTo(d,u),e.lineTo(p,_),e.stroke())}e.setLineDash([]),this._drawTooltip(e,t,i,r,s,n),e.restore()}_recordHit(e,t,i){const r=e.id??e.tooltip;void 0!==r&&this._hits.push({id:r,tooltip:e.tooltip,x:t.x/i,y:t.y/i,w:t.w/i,h:t.h/i})}_drawTooltip(e,t,i,r,s,n){const o=t.hoverId;if(null==o)return;const a=this._hits.find(e=>e.id===o&&void 0!==e.tooltip);if(void 0===a?.tooltip)return;const l=8*i,h=11*i*1.35*a.tooltip.split("\n").length+6*i,c=a.y*i-l-h>=0?a.y*i-l-h/2:(a.y+a.h)*i+l+h/2,d=Math.min(Math.max((a.x+a.w/2)*i,0),r);c<-h||c>s+h||hi(e,i,d,c,a.tooltip,n,void 0,"center")}hitTest(e,t){for(let i=this._hits.length-1;i>=0;i--){const r=this._hits[i];if(e>=r.x&&e<=r.x+r.w&&t>=r.y&&t<=r.y+r.h)return{externalId:r.id,zOrder:"normal",distance:0,cursor:void 0===r.tooltip?"pointer":"default"}}return null}}class di{constructor(){Object.defineProperty(this,"_colors",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_anchor",{enumerable:!0,configurable:!0,writable:!0,value:NaN}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_visible",{enumerable:!0,configurable:!0,writable:!0,value:!0})}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"bottom"}autoscaleInfo(){return null}setColors(e,t){this._colors=e,this._anchor=t.length>0?t[0].time:NaN,this._host?.requestUpdate()}setVisible(e){this._visible=e,this._host?.requestUpdate()}draw(e,t){const i=this._colors,r=i.length;if(!this._visible||0===r)return;const s=Math.round(t.dataLayer.timeToIndexFloat(this._anchor)),n=t.timeScale.visibleRange(),o=Math.max(0,Math.floor(n.from-s)),a=Math.min(r-1,Math.ceil(n.to-s)),l=t.dpr,h=t.plotWidth*l,c=t.plotHeight*l,d=e=>Math.min(h,Math.max(0,Math.round(t.timeScale.indexToX(s+e-.5)*l)));e.save();for(let t=o,r=o;t<=a;t++){const s=i[t];if(!(t<a&&i[t+1]===s)){if(s){const i=d(r);e.fillStyle=s,e.fillRect(i,0,d(t+1)-i,c)}r=t+1}}e.restore()}}function ui(e){const t={};for(const i of Kt(e))t[i.key]=i.default;return t}function pi(e,t){if(void 0!==t&&t>0)return e.toFixed(b(t));const i=Math.abs(e);return i>=1e9?`${(e/1e9).toFixed(2)}B`:i>=1e6?`${(e/1e6).toFixed(2)}M`:i>=1e3?e.toFixed(0):i>=1?e.toFixed(2):e.toPrecision(3)}let _i=1;class bi{constructor(e,t,i={},r,s,n){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"indicatorId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"paneIndex",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_d",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ownPane",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_zoned",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_series",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_plotTypes",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_fills",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_levels",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_levelSig",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"_values",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_barCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_firstTime",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastTime",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_removed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_store",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_detach",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_lifetime",{enumerable:!0,configurable:!0,writable:!0,value:new AbortController}),Object.defineProperty(this,"_dataStatus",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dataRetry",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dataListeners",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_legend",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_markers",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_markerSeries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_table",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_draws",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_background",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_alertTime",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_live",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_visible",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_constructed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_calcFailed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._host=e,this._d=t,this.indicatorId=t.id,this.name=t.name;let o=s;if(void 0===o)do{o=`${t.id}-${_i++}`}while(n?.has(o));this.id=o,this._settings={...si(t),...ui(t),...i},void 0!==r?(this.paneIndex=r,this._ownPane=!1):"onchart"===t.placement?(this.paneIndex=0,this._ownPane=!1):(this.paneIndex=e.nextPaneIndex(),this._ownPane=!0);for(const i of t.plots){const t=this._plotType(i);this._plotTypes.set(i.key,t),this._series.set(i.key,e.addIndicatorSeries(t,this._plotPane(i),this._plotStyle(i),i.priceScaleId,i.priceFormat))}for(const i of t.fills??[]){const t=new ai({colorUp:this._fillColor(i,!0),colorDown:this._fillColor(i,!1),opacity:i.opacity??.12});this._fills.push(t),e.addIndicatorFill(t,!0===i.overlay?0:this.paneIndex)}this._legend=e.addIndicatorLegend({id:`indicator:${this.id}`,title:t.name,params:this._paramSummary(),color:this._legendColor(),row:e.legendRowsOn(this.paneIndex),paneIndex:this.paneIndex,hasSource:!0===t.hasSource}),this._applyRange(),this.recompute(),this._constructed=!0,this._attach()}_plotPane(e){return!0===e.overlay?0:this.paneIndex}_paramSummary(){const e=[];for(const t of this._d.inputs){if("color"===t.type||"boolean"===t.type)continue;const i=this._settings[t.key];null!=i&&""!==i&&e.push(String(i))}return e.join(" ")}_legendColor(){for(const e of this._d.plots){const t=e.colorKey;if(void 0!==t&&"string"==typeof this._settings[t])return this._settings[t];if("string"==typeof e.style?.color)return e.style.color}}visible(){return this._visible}setVisible(e){if(this._removed||e===this._visible)return;this._visible=e;for(const t of this._d.plots)this._series.get(t.key)?.applyOptions({visible:e&&!1!==t.style?.visible});for(const t of this._fills)t.setVisible(e);const t=this._host.sourceBars();this._applyLevels(t,this._descriptorSettings()),this._syncMarkers(t),this._syncTable(t),this._syncBarColors(t),this._draws?.setVisible(e),this._background?.setVisible(e),this._legend?.setOptions({hidden:!e}),this._host.emit?.("objects:change",{})}shiftPane(e){this.paneIndex+=e}legend(){return this._legend}updateLegendValues(e){if(null===this._legend)return;const t=this._barCount,i=void 0===e||e<0||e>=t?t-1:e;if(i<0)return void this._legend.setValues([]);const r=[];for(const e of this._d.plots){const t=this._values[e.ohlc?.close??e.key]?.[i-(e.offset??0)];if(null==t||!Number.isFinite(t))continue;const s=this._plotPane(e),n=this._plotColor(e);if(void 0!==n&&E(n))continue;const o=this._host.formatPrice?.(s,t)??pi(t,this._host.tickSize?.(s));r.push({text:o,color:n})}this._legend.setValues(r)}_fillColor(e,t){const i=t?e.colorUpKey:e.colorDownKey,r=void 0!==i?this._settings[i]:void 0;if("string"==typeof r)return r;return(t?e.colorUp:e.colorDown)??(t?"#26a69a":"#ef5350")}_syncFills(){const e=this._d.fills??[];for(let t=0;t<e.length;t++){const i=this._fills[t];if(void 0===i)continue;const r=e[t],s=this._values[r.between[0]],n=this._values[r.between[1]];if(i.setOptions({colorUp:this._fillColor(r,!0),colorDown:this._fillColor(r,!1),opacity:r.opacity??.12}),void 0===s||void 0===n){i.setPoints([]);continue}const o=this._d.plots.find(e=>e.key===r.between[0])?.offset??0,a=[];for(let e=0;e<this._barCount;e++)a.push({index:e+o,a:s[e]??null,b:n[e]??null});i.setPoints(a)}}_syncMarkers(e){if(void 0===this._d.markers)return;const t=this._visible?this._d.markers({bars:e,values:this._values,settings:this._descriptorSettings()}):[],i=this._host.primarySeries?.()??void 0,r=("price"===this._d.markerAnchor&&0===this.paneIndex?i:void 0)??this._series.get(this._d.plots[0]?.key??"");if(null!==this._markers&&r!==this._markerSeries&&(this._host.removeIndicatorMarkers(this._markers),this._markers=null),null===this._markers){if(0===t.length)return;if(void 0===r)return;this._markerSeries=r,this._markers=r.createMarkers(()=>{const e=this._host.primarySeries?.();return 0===this.paneIndex&&null!=e&&r.priceScale()===e.priceScale()?this._host.sourceBars():[]})}this._markers.setMarkers(t)}_syncTable(e){if(void 0===this._d.table)return;const t=this._visible?this._d.table({bars:e,values:this._values,settings:this._descriptorSettings()}):null,i=t?.rows??[];if(null===this._table){if(0===i.length)return;this._table=this._host.addIndicatorTable(this.paneIndex)}void 0!==t?.options&&this._table.setOptions(t.options),this._table.setRows(i)}_syncDraws(e){if(void 0===this._d.draws)return;const t=this._d.draws({bars:e,values:this._values,settings:this._descriptorSettings()});if(null===this._draws){if(0===t.length||void 0===this._host.addIndicatorPrimitive)return;this._draws=new ci,this._draws.setVisible(this._visible),this._host.addIndicatorPrimitive(this._draws,this.paneIndex)}this._draws.setItems(t)}_syncBackground(e){if(void 0===this._d.background)return;const t=this._d.background({bars:e,values:this._values,settings:this._descriptorSettings()});if(null===this._background){if(0===t.length||void 0===this._host.addIndicatorPrimitive)return;this._background=new di,this._background.setVisible(this._visible),this._host.addIndicatorPrimitive(this._background,this.paneIndex)}this._background.setColors(t,e)}_syncBarColors(e){if(void 0===this._d.barColors)return;const t=this._visible?this._d.barColors({bars:e,values:this._values,settings:this._descriptorSettings()}):null;this._host.setBarColors?.(t,this.id)}_syncAlerts(e,t,i){const r=this._d.alerts,s=e.length;if(void 0===r||0===s)return;const n=this._alertTime;if(this._alertTime=e[s-1].time,!i)return;let o=s;for(;o>0&&e[o-1].time>n;)o--;for(let i=o;i<s;i++)for(const s of r){const r={bars:e,values:this._values,settings:t,index:i};s.when(r)&&this._host.emit?.("indicator:alert",{indicatorId:this.indicatorId,instanceId:this.id,alertId:s.id,title:s.title,message:"function"==typeof s.message?s.message(r):s.message??s.title,time:e[i].time,index:i})}}_calcContext(e,t){const i=e.length,r=()=>this._host.now?.()??Date.now()/1e3,s=i>1?e[i-1].time-e[i-2].time:0;return{barState:{isNew:t,isConfirmed:0===i||s<=0||r()>=e[i-1].time+s,isRealtime:this._live,lastIndex:i-1},symbol:this._host.symbol?.(),interval:this._host.interval?.(),timezone:this._host.timezone?.()??Se,now:r,tickSize:this._host.tickSize?.(0)||void 0}}_plotType(e){const t=this._settings[Yt(e).type];return"string"==typeof t&&""!==t?t:e.type}_plotColor(e){const t=this._settings[Yt(e).color];return"string"==typeof t?t:"string"==typeof e.style?.color?e.style.color:void 0}_plotStyle(e){const t=Yt(e),i={...e.style??{},title:e.title,visible:this._visible&&!1!==e.style?.visible},r=this._plotColor(e),s=(n=this._settings[t.opacity],o=100,"number"==typeof n&&Number.isFinite(n)?n:o);var n,o;void 0!==r&&(i.color=s>=100?r:R(r,s/100));const a=this._settings[t.width];"number"==typeof a&&a>0&&(i.lineWidth=a);const l=this._settings[t.lineStyle];return"string"==typeof l&&(i.lineStyle=l),void 0!==e.offset&&0!==e.offset&&(i.barOffset=e.offset),i}_attach(){this._dataRetry=null;const e=this._d.attach?.({dataContext:()=>this._host.dataContext?.(),subscribeDataChanges:e=>this._host.subscribeDataChanges?.(e)??(()=>{}),signal:this._lifetime.signal,setDataStatus:e=>this._publishStatus(e),setDataRetry:e=>{this._removed||(this._dataRetry=e)},requestBars:e=>{const t=this._host.requestBars;return void 0===t?Promise.reject(new Error("openalgo-charts: this chart has no bars provider; call chart.setBarsProvider(...) to serve other instruments")):t({...e,signal:e.signal??this._lifetime.signal})},settings:()=>this._descriptorSettings(),bars:()=>this._host.sourceBars(),requestRecompute:()=>{this._removed||(this._barCount=0,this.recompute())},store:this._store,symbol:()=>this._host.symbol?.(),interval:()=>this._host.interval?.(),timezone:()=>this._host.timezone?.()??Se,now:()=>this._host.now?.()??Date.now()/1e3,paneIndex:()=>this.paneIndex,addPrimitive:e=>{this._host.addIndicatorPrimitive?.(e,this.paneIndex)},removePrimitive:e=>{this._host.removeIndicatorPrimitive?.(e)},emit:(e,t)=>{this._host.emit?.(e,t)}});this._detach="function"==typeof e?e:null}_publishStatus(e){if(this._removed)return;const t=this._dataStatus;if(t?.state!==e.state||"error"===e.state&&("error"!==t.state||t.error!==e.error)){this._dataStatus=Object.freeze({...e});for(const e of this._dataListeners)e(this._dataStatus);this._host.emit?.("indicator:data-status",{id:this.id,indicatorId:this.indicatorId,status:this._dataStatus})}}dataStatus(){return this._dataStatus}subscribeDataStatus(e){return this._removed?()=>{}:(this._dataListeners.add(e),null!==this._dataStatus&&e(this._dataStatus),()=>{this._dataListeners.delete(e)})}retryData(){this._removed||this._dataRetry?.()}settings(){return{...this._settings}}_descriptorSettings(){const e=this._host.timezone?.()??Se;if(e===Se)return this._settings;const t=this._zoned;if(null!==t&&t.zone===e&&t.base===this._settings)return t.merged;const i={...this._settings,timezone:e};return this._zoned={zone:e,base:this._settings,merged:i},i}series(e){return this._series.get(e)}values(){return this._host.flushIndicators?.(),this._values}setSettings(e){if(!this._removed){this._settings={...this._settings,...e};for(const e of this._d.plots){const t=this._plotType(e);t===this._plotTypes.get(e.key)?this._series.get(e.key)?.applyOptions(this._plotStyle(e)):(this._series.get(e.key)?.remove(),this._series.set(e.key,this._host.addIndicatorSeries(t,this._plotPane(e),this._plotStyle(e),e.priceScaleId,e.priceFormat)),this._plotTypes.set(e.key,t))}this._legend?.setOptions({params:this._paramSummary(),color:this._legendColor()}),this._applyRange(),this._values={},this._barCount=0,this.recompute(),this._detach?.(),this._attach(),this._host.emit?.("objects:change",{})}}recompute(){if(!this._removed)if(this._constructed){try{this._recompute()}catch(e){return this._calcFailed=!0,void this._publishStatus({state:"error",error:e})}this._calcFailed&&(this._calcFailed=!1,this._publishStatus({state:"ready"}))}else this._recompute()}_recompute(){const e=this._host.sourceBars(),t=e.length,i=this._descriptorSettings();let r=null;const s=this._barCount>0&&t===this._barCount+1&&e[t-2].time===this._lastTime&&e[0].time===this._firstTime,n=t>0&&this._barCount>0&&e[0].time===this._firstTime&&(t===this._barCount&&e[t-1].time===this._lastTime||s);n&&(this._live=!0);const o=this._calcContext(e,s);if(n&&void 0!==this._d.calcTail){const s=this._barCount-1,n=this._d.calcTail(e,i,s,this._values,this._store,o);null!==n&&(r=function(e,t,i,r){const s={};for(const n of Object.keys(t)){const o=e[n],a=t[n];if(void 0===o||void 0===a)return null;if(a.length!==r-i)return null;const l=new Array(r);for(let e=0;e<i;e++)l[e]=o[e]??null;for(let e=i;e<r;e++)l[e]=a[e-i]??null;s[n]=l}return s}(this._values,n,s,t))}null===r&&(r=this._d.calc(e,i,this._store,o)),this._values=r,this._barCount=t,this._firstTime=t>0?e[0].time:0,this._lastTime=t>0?e[t-1].time:0;for(const s of this._d.plots){const n=this._series.get(s.key);if(void 0===n)continue;if(void 0!==s.ohlc){n.setData(this._ohlcPoints(s,s.ohlc,r,e,i));continue}const o=r[s.key];if(void 0===o){n.setData([]);continue}const a=s.colorBy,l=s.colorParts,h=new Array(t);for(let s=0;s<t;s++){const t=o[s],n=null==t?NaN:t,c={time:e[s].time,value:n};if(Number.isFinite(n)){const e=l?.({value:n,index:s,values:r,settings:i})?.body??a?.({value:n,index:s,values:r,settings:i});void 0!==e&&(c.color=e)}h[s]=c}n.setData(h)}this._syncFills(),this._syncMarkers(e),this._syncTable(e),this._syncDraws(e),this._syncBackground(e),this._syncBarColors(e),this._applyLevels(e,i),this._syncAlerts(e,i,n),this.updateLegendValues(this._host.legendIndex?.())}_ohlcPoints(e,t,i,r,s){const n=r.length,o=[t.open,t.high,t.low,t.close].map(t=>{const r=i[t];if(void 0===r||r.length!==n)throw new Error(`openalgo-charts: ${this.indicatorId} plot "${e.key}" ohlc column "${t}" must be ${n} values`);return r}),a=e.colorBy,l=e.colorParts,h=new Array(n);for(let e=0;e<n;e++){const t=o[3][e],n=null===t?NaN:t,c={time:r[e].time,open:o[0][e]??NaN,high:o[1][e]??NaN,low:o[2][e]??NaN,close:n};if(Number.isFinite(n)){const t=a?.({value:n,index:e,values:i,settings:s});void 0!==t&&(c.color=t);const r=l?.({value:n,index:e,values:i,settings:s});void 0!==r&&(void 0!==r.body&&(c.color=r.body),void 0!==r.wick&&(c.wickColor=r.wick),void 0!==r.border&&(c.borderColor=r.border))}h[e]=c}return h}_applyLevels(e,t){if(void 0===this._d.levels)return;const i={...t,settings:t,bars:e,values:this._values},r=this._visible?this._d.levels(i):[];let s="";for(const e of r)s+=`${e.price}|${e.color??""}|${e.title??""}|${e.dashed??""}|${e.lineWidth??""}|${e.lineStyle??""};`;if(s===this._levelSig)return;this._levelSig=s;for(const e of this._levels)this._host.removeIndicatorLevel(e);this._levels=[];let n=0;for(const e of r){const t=e.lineStyle??(!1===e.dashed?"solid":"dashed");this._levels.push(this._host.addIndicatorLevel({price:e.price,color:e.color??"#8892a6",dashed:"dashed"===t,lineWidth:e.lineWidth??1,lineStyle:t,label:e.title??"",id:`${this.id}:level:${n++}`},this.paneIndex))}}_applyRange(){this._ownPane&&this._host.setPaneRange(this.paneIndex,this._d.range?.(this._descriptorSettings())??null)}remove(){if(!this._removed){this._removed=!0,this._lifetime.abort(),this._dataRetry=null,this._dataListeners.clear();try{this._detach?.()}catch{}this._detach=null,null!==this._legend&&(this._host.removeIndicatorLegend(this._legend),this._legend=null);for(const e of this._levels)this._host.removeIndicatorLevel(e);this._levels=[];for(const e of this._series.values())e.remove();this._series.clear();for(const e of this._fills)this._host.removeIndicatorFill(e);this._fills.length=0,null!==this._markers&&(this._host.removeIndicatorMarkers(this._markers),this._markers=null),null!==this._table&&(this._host.removeIndicatorTable(this._table),this._table=null),null!==this._draws&&(this._host.removeIndicatorPrimitive?.(this._draws),this._draws=null),null!==this._background&&(this._host.removeIndicatorPrimitive?.(this._background),this._background=null),void 0!==this._d.barColors&&this._host.setBarColors?.(null,this.id),this._ownPane&&this._host.setPaneRange(this.paneIndex,null),this._host.indicatorRemoved?.(this.id)}}}const fi=["crossing","crossingUp","crossingDown","greaterThan","lessThan","enteringRange","leavingRange"];function mi(e,t,i,r,s,n=r,o=s){if(!Number.isFinite(i))return!1;if("greaterThan"===e)return i>r;if("lessThan"===e)return i<r;if(void 0===t||!Number.isFinite(t))return!1;const a=t<=n&&i>r,l=t>=n&&i<r;if("crossing"===e)return a||l;if("crossingUp"===e)return a;if("crossingDown"===e)return l;const h=t>=n&&t<=o,c=i>=r&&i<=s;return"enteringRange"===e?!h&&c:h&&!c}function gi(e,t,i,r,s,n,o=s,a=n){if(![t,i,r].every(Number.isFinite))return;const l=t<=o&&r>s,h=t>=o&&i<s;switch(e){case"crossing":return l||h?s:void 0;case"crossingUp":return l?s:void 0;case"crossingDown":return h?s:void 0;case"greaterThan":return r>s?r:void 0;case"lessThan":return i<s?i:void 0;case"enteringRange":return t<o&&r>=s?s:t>a&&i<=n?n:void 0;case"leavingRange":if(t<o||t>a)return;return i<s?s:r>n?n:void 0;case"matches":return}}const vi=e=>"string"==typeof e&&e.trim().length>0;function yi(e){if(!vi(e.id))throw new Error("Alert id must be nonempty");const t=e.source;if(!t||!["price","indicator","barCondition","drawing"].includes(t.kind))throw new Error("Unknown alert source");if("barCondition"===t.kind&&!vi(t.id))throw new Error("Invalid bar condition id");if(!("indicator"!==t.kind||vi(t.instanceId)&&vi(t.plotKey)))throw new Error("Invalid indicator source");if(!("drawing"!==t.kind||vi(t.drawingId)&&(void 0===t.level||vi(t.level))&&(void 0===t.input||t.input&&vi(t.input.instanceId)&&vi(t.input.plotKey))))throw new Error("Invalid drawing source");if("barCondition"===t.kind?"matches"!==e.condition:!fi.includes(e.condition))throw new Error("Invalid source condition");if("price"===t.kind||"indicator"===t.kind){const i="price"===t.kind?t.price:t.value,r="price"===t.kind?t.upperPrice:t.upperValue;if(!Number.isFinite(i)||void 0!==r&&!Number.isFinite(r))throw new Error("Alert bounds must be finite");if(("enteringRange"===e.condition||"leavingRange"===e.condition)&&(void 0===r||r<i))throw new Error("Alert range requires ordered finite bounds")}if("onBarClose"!==e.policy&&"onTouch"!==e.policy)throw new Error("Unknown alert policy");if("once"!==e.repeat&&"everyTime"!==e.repeat)throw new Error("Unknown alert repeat");if(!["armed","triggered","disabled","expired"].includes(e.state))throw new Error("Unknown alert state");if(!Number.isFinite(e.cooldownSeconds)||e.cooldownSeconds<0)throw new Error("Invalid alert cooldown");if("string"!=typeof e.title||void 0!==e.message&&"string"!=typeof e.message)throw new Error("Alert title and message must be text");const i=xi(e.scope);for(const e of["symbol","exchange","interval"])if(void 0!==i[e]&&"string"!=typeof i[e])throw new Error("Invalid alert scope");for(const t of["expiresAt","lastTriggeredAt","lastTriggeredTime","lastClosedTime","lastTouchedTime"])if(void 0!==e[t]&&!Number.isFinite(e[t]))throw new Error(`Invalid alert ${t}`)}function wi(e){return{...e,source:"drawing"===e.source.kind?{...e.source,...e.source.input?{input:{...e.source.input}}:{}}:{...e.source},scope:{...e.scope}}}function xi(e){if(null===e||"object"!=typeof e||Array.isArray(e)||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw new Error("Alert document needs plain JSON records");for(const t of Reflect.ownKeys(e)){const i=Object.getOwnPropertyDescriptor(e,t);if("string"!=typeof t||!("value"in i)||!i.enumerable)throw new Error("Alert document needs JSON data properties")}return e}function Pi(e){if(!Array.isArray(e)||e.length>1e5||Reflect.ownKeys(e).length!==e.length+1)throw new Error("Alert document array is not JSON data");return Array.from({length:e.length},(t,i)=>{const r=Object.getOwnPropertyDescriptor(e,String(i));if(!r||!("value"in r))throw new Error("Alert document array needs JSON data values");return r.value})}function Si(e){const t=new Set;let i=0,r=0;const s=(e,n)=>{if(++i>1e5||n>32)throw new Error("Alert payload exceeds JSON limits");if(null===e||"boolean"==typeof e)return e;if("string"==typeof e){if(r+=e.length,r>5242880)throw new Error("Alert payload exceeds JSON size limit");return e}if("number"==typeof e&&Number.isFinite(e))return e;if("object"!=typeof e)throw new Error("Alert payload must be finite JSON data");if(t.has(e))throw new Error("Alert payload contains a cycle");let o;if(t.add(e),Array.isArray(e))o=Pi(e).map(e=>s(e,n+1));else{const t=xi(e),i={};for(const e of Object.keys(t)){if(r+=e.length,r>5242880)throw new Error("Alert payload exceeds JSON size limit");Object.defineProperty(i,e,{value:s(t[e],n+1),enumerable:!0,writable:!0,configurable:!0})}o=i}return t.delete(e),o};return s(e,0)}function Oi(e){if("string"==typeof e){if(e.length>5242880)throw new Error("Alert document exceeds JSON size limit");e=JSON.parse(e)}const t=Array.isArray(e)?{version:1,alerts:e}:xi(e);if(1!==t.version||!Array.isArray(t.alerts)||t.alerts.length>1e4)throw new Error("Unsupported alert document");const i=new Set,r=Pi(t.alerts).map(e=>{const t=xi(e),r=xi(t.source);void 0!==r.input&&xi(r.input);const s=(e,i)=>void 0===t[e]?i:t[e],n=xi(s("scope",{})),o={id:t.id,source:{...r},condition:s("condition","barCondition"===r.kind?"matches":"crossing"),policy:s("policy","onBarClose"),repeat:s("repeat","once"),state:s("state","armed"),title:s("title","Chart alert"),cooldownSeconds:s("cooldownSeconds",0),scope:Si(Object.fromEntries(Object.entries(n).filter(([,e])=>void 0!==e)))};for(const e of["message","expiresAt","lastTriggeredAt","lastTriggeredTime","lastClosedTime","lastTouchedTime"])void 0!==t[e]&&Object.assign(o,{[e]:t[e]});if(yi(o),i.has(o.id))throw new Error(`Duplicate alert id: ${o.id}`);return i.add(o.id),o.source=Si(Object.fromEntries(Object.entries(o.source).filter(([,e])=>void 0!==e))),void 0!==t.payload&&(o.payload=Si(t.payload)),o});return{version:1,alerts:r}}const ki=1;function Mi(e){return!("open"in e)&&!("value"in e)}function Ti(e){if("open"in e)return e;if("value"in e){const t=e.value,i={time:e.time,open:t,high:t,low:t,close:t};return void 0!==e.color&&(i.color=e.color),i}return{time:e.time,open:NaN,high:NaN,low:NaN,close:NaN}}const Ci={friction:.0055,minSpeed:.02,triggerSpeed:.08};class Ii{constructor(e,t={}){Object.defineProperty(this,"_v0",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_k",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_minSpeed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_duration",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const i={...Ci,...t};this._v0=e,this._k=i.friction,this._minSpeed=i.minSpeed;const r=Math.abs(this._v0)>0?this._minSpeed/Math.abs(this._v0):1;this._duration=r>=1?0:-Math.log(r)/this._k}static shouldAnimate(e,t={}){const i=t.triggerSpeed??Ci.triggerSpeed;return Math.abs(e)>=i}distanceAt(e){const t=Math.min(Math.max(0,e),this._duration);return this._v0/this._k*(1-Math.exp(-this._k*t))}get durationMs(){return this._duration}finished(e){return e>=this._duration}}const ji={tau:55,stopFraction:.995,minLogStep:.02};class Ai{constructor(e,t={}){Object.defineProperty(this,"_base",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_target",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_epoch",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_tau",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_duration",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const i={...ji,...t};this._target=e,this._tau=i.tau,this._duration=-Math.log(1-i.stopFraction)*i.tau}static leadFraction(e={}){const t=e.tau??ji.tau;return 1-Math.exp(-16.666666666666668/t)}static shouldAnimate(e,t={}){const i=t.minLogStep??ji.minLogStep;return Math.abs(e)>=i}add(e,t,i){this._base=t,this._target+=e,this._epoch=i}appliedAt(e){const t=e-this._epoch;return t<=0?this._base:t>=this._duration?this._target:this._base+(this._target-this._base)*(1-Math.exp(-t/this._tau))}get totalLogFactor(){return this._target}get durationMs(){return this._duration}finished(e){return e-this._epoch>=this._duration}}function Li(e){return Math.max(-2,Math.min(2,-e*Math.log(1.1)/100))}const zi=["Mod","Ctrl","Meta","Alt","Shift"],Fi=new Set(zi),Bi=new Set(["Shift","Control","Alt","Meta","OS","ShiftLeft","ShiftRight","ControlLeft","ControlRight","AltLeft","AltRight","MetaLeft","MetaRight","OSLeft","OSRight"]);function $i(){return"undefined"!=typeof navigator&&/mac|iphone|ipad/i.test(navigator.platform||navigator.userAgent||"")}function Ni(e){const t=e.split("+").map(e=>e.trim()).filter(e=>e.length>0);if(0===t.length)return null;const i=t[t.length-1];if(!/^[A-Za-z0-9]+$/.test(i)||Fi.has(i))return null;const r=[];for(const e of t.slice(0,-1)){if(!Fi.has(e))return null;r.includes(e)||r.push(e)}return r.sort((e,t)=>zi.indexOf(e)-zi.indexOf(t)),{mods:r,key:i}}function Di(e){const t=Ni(e);return null===t?"":[...t.mods,t.key].join("+")}function Ri(e){return""!==Di(e)}const Ei={ArrowLeft:"←",ArrowRight:"→",ArrowUp:"↑",ArrowDown:"↓",Equal:"=",Minus:"-",NumpadAdd:"+",NumpadSubtract:"-",Escape:"Esc",Space:"Space"};function Wi(e,t=$i()){const i=Ni(e);if(null===i)return"";const r=t?{Mod:"⌘",Ctrl:"⌃",Meta:"⌘",Alt:"⌥",Shift:"⇧"}:{Mod:"Ctrl",Ctrl:"Ctrl",Meta:"Win",Alt:"Alt",Shift:"Shift"};var s;return[...i.mods.map(e=>r[e]),(s=i.key,void 0!==Ei[s]?Ei[s]:/^Key[A-Z]$/.test(s)?s.slice(3):/^Digit[0-9]$/.test(s)?s.slice(5):s)].join(t?" ":" + ")}function qi(e,t=$i()){const i=e.code??e.key??"";if(""===i||Bi.has(i))return"";const r=[];return(t?e.metaKey:e.ctrlKey)&&r.push("Mod"),t&&e.ctrlKey&&r.push("Ctrl"),!t&&e.metaKey&&r.push("Meta"),e.altKey&&r.push("Alt"),e.shiftKey&&r.push("Shift"),Di([...r,i].join("+"))}const Hi=new Set(["Mod+KeyW","Mod+KeyT","Mod+KeyN","Mod+KeyQ","Mod+KeyR","Mod+KeyL","Mod+Shift+KeyT","Mod+Shift+KeyN","Mod+Shift+KeyW"]);function Vi(e){return Hi.has(Di(e))}const Gi=[{command:"panLeft",label:"Pan left",combos:["ArrowLeft"]},{command:"panRight",label:"Pan right",combos:["ArrowRight"]},{command:"panLeftFast",label:"Pan left (fast)",combos:["Mod+ArrowLeft"]},{command:"panRightFast",label:"Pan right (fast)",combos:["Mod+ArrowRight"]},{command:"panUp",label:"Pan up",combos:["ArrowUp"]},{command:"panDown",label:"Pan down",combos:["ArrowDown"]},{command:"zoomIn",label:"Zoom in",combos:["Equal","Shift+Equal","NumpadAdd"]},{command:"zoomOut",label:"Zoom out",combos:["Minus","NumpadSubtract"]},{command:"resetScale",label:"Reset scale",combos:["Home","Digit0"]},{command:"fitContent",label:"Fit content",combos:["Alt+KeyF"]},{command:"screenshot",label:"Screenshot (PNG)",combos:["Alt+Shift+KeyS"]},{command:"toggleGridVert",label:"Toggle vertical grid",combos:["Alt+KeyV"]},{command:"toggleGridHorz",label:"Toggle horizontal grid",combos:["Alt+KeyH"]},{command:"toggleCrosshairMagnet",label:"Toggle crosshair magnet",combos:["Alt+KeyM"]}],Ui={panLeftFast:["Alt+ArrowLeft"],panRightFast:["Alt+ArrowRight"],screenshot:["Mod+Shift+KeyS"]},Yi=new Set(Gi.map(e=>e.command)),Ki=e=>Array.isArray(e)?e:[e];class Xi{constructor(e={}){Object.defineProperty(this,"scope",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isMac",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_persist",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_storageKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_preset",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_overrides",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_disabled",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_custom",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_entries",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_reverse",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),this.scope=e.scope??"hover",this._isMac=e.isMac??$i(),this._persist=e.persist??!1,this._storageKey=e.storageKey??"openalgo-charts:shortcuts",this._preset=e.preset??"default";const t=e=>{for(const[t,i]of Object.entries(e??{})){if(null===i){this._disabled.add(t);continue}const e=Ki(i).map(Di).filter(e=>""!==e&&!Vi(e));this._overrides[t]=e}};t(e.overrides);for(const t of e.disabledCommands??[])this._disabled.add(t);for(const t of e.customShortcuts??[])this._custom.set(t.command,t);const i=this._load();if(null!==i){void 0!==i.preset&&(this._preset=i.preset),t(i.overrides);for(const e of i.disabled??[])this._disabled.add(e)}this._rebuild()}_presetCombos(e){return"alt"===this._preset?Ui[e]:void 0}_effectiveCombos(e,t){return this._disabled.has(e)?[]:void 0!==this._overrides[e]?this._overrides[e]:this._presetCombos(e)??t}_rebuild(){this._entries=new Map;for(const e of Gi)this._entries.set(e.command,{command:e.command,label:e.label,combos:this._effectiveCombos(e.command,e.combos)});for(const e of this._custom.values())this._entries.set(e.command,{command:e.command,label:e.label??e.command,combos:this._effectiveCombos(e.command,Ki(e.combos).map(Di).filter(e=>""!==e))});this._reverse=new Map;for(const e of this._entries.values())for(const t of e.combos)this._reverse.has(t)||this._reverse.set(t,e.command)}resolve(e){const t=qi(e,this._isMac);return""===t?null:this._reverse.get(t)??null}handleKey(e){return this._reverse.get(Di(e))??null}runCustom(e){const t=this._custom.get(e);return void 0!==t&&(t.onTrigger(),this.emitTrigger(e),!0)}emitTrigger(e,t=""){const i={command:e,combo:t,isCustom:this._custom.has(e)};for(const e of this._listeners)e(i)}on(e){return this._listeners.add(e),()=>this._listeners.delete(e)}setBinding(e,t){const i=Ki(t).map(Di).filter(e=>""!==e&&!Vi(e));return 0!==i.length&&(this._overrides[e]=i,this._disabled.delete(e),this._after(),!0)}disable(e){this._disabled.add(e),delete this._overrides[e],this._after()}resetBinding(e){delete this._overrides[e],this._disabled.delete(e),this._after()}resetAll(){this._overrides={},this._disabled.clear(),this._after()}setPreset(e){this._preset=e,this._after()}addCustom(e){this._custom.set(e.command,e),this._after()}list(){return[...this._entries.values()].map(e=>({command:e.command,label:e.label,combos:e.combos,isCustom:this._custom.has(e.command),isDisabled:this._disabled.has(e.command)}))}state(){return{preset:this._preset,overrides:this._overrides,disabled:[...this._disabled]}}_after(){this._rebuild(),this._save()}_save(){if(this._persist&&"undefined"!=typeof localStorage)try{localStorage.setItem(this._storageKey,JSON.stringify(this.state()))}catch{}}_load(){if(!this._persist||"undefined"==typeof localStorage)return null;try{const e=localStorage.getItem(this._storageKey);return null===e?null:JSON.parse(e)}catch{return null}}static shouldIgnore(e){const t=e;if(null==t)return!1;if(!0===t.isContentEditable)return!0;const i=(t.tagName??"").toUpperCase();return"INPUT"===i||"TEXTAREA"===i||"SELECT"===i}}class Ji{constructor(e){Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_ghostPrice",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_group",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._opts=e}attached(e){this._host=e}detached(){this._host=null}get price(){return this._opts.price}setPrice(e){this._opts.price=e,this._host?.requestUpdate()}setLeftLabel(e){this._opts.leftLabel=e,this._host?.requestUpdate()}setOptions(e){this._opts={...this._opts,...e},this._host?.requestUpdate()}setDragGhost(e){this._ghostPrice=e,this._host?.requestUpdate()}options(){return this._opts}zOrder(){return"normal"}autoscaleInfo(){return{min:this._opts.price,max:this._opts.price}}draw(e,t){this._group=null;const i=Math.round(t.priceScale.priceToY(this._opts.price)*t.dpr)+.5;if(i<0||i>t.plotHeight*t.dpr)return;const r=t.dpr,s=this._opts.lineWidth??1,n=Math.round(t.plotWidth*r),o=Math.max(0,Math.min(1,this._opts.extentFromRight??1)),a=Math.round(t.plotWidth*(1-o)*r),l=this._opts.color,h=void 0!==this._opts.cursor||!0===this._opts.closeButton,c=t.dragId===this._opts.id,d=h&&!c&&(t.hoverId===this._opts.id||t.hoverId===`${this._opts.id}::close`),u=t.hoverId===`${this._opts.id}::close`;if(e.save(),null!==this._ghostPrice&&c){const i=Math.round(t.priceScale.priceToY(this._ghostPrice)*r)+.5;i>=0&&i<=t.plotHeight*r&&(e.strokeStyle=R(l,.35),e.lineWidth=Math.max(1,Math.round(r)),e.setLineDash([2*r,3*r]),e.beginPath(),e.moveTo(a,i),e.lineTo(n,i),e.stroke(),e.setLineDash([]))}c&&(e.strokeStyle=R(l,.18),e.lineWidth=Math.max(5*r,Math.round(s*r)+4*r),e.beginPath(),e.moveTo(a,i),e.lineTo(n,i),e.stroke()),e.strokeStyle=d||c?W(l,.1):l;const p=Math.max(1,Math.round(s*r));e.lineWidth=d||c?p+Math.round(r):p,e.setLineDash(S(this._opts.lineStyle??(!0===this._opts.dashed?"dashed":"solid"),r)),e.beginPath(),e.moveTo(a,i),e.lineTo(n,i),e.stroke(),e.setLineDash([]),e.font=`500 ${11*r}px system-ui, sans-serif`,e.textBaseline="middle",e.textAlign="left";const _=18*r,b=6*r,f=3*r,m=c||d?W(l,.12):l,g=this._opts.label??t.priceScale.format(this._opts.price);e.fillStyle=m,e.fillRect(n+1,i-_/2,e.measureText(g).width+2*b,_),e.fillStyle=D(l),e.fillText(g,n+1+b,i);if(void 0!==this._opts.badge||void 0!==this._opts.qty||void 0!==this._opts.leftLabel&&""!==this._opts.leftLabel||!0===this._opts.closeButton){const s="transparent"===t.theme.background,n=s?R(l,.14):t.theme.background,h=s?t.theme.axisText:D(t.theme.background),p=R(t.theme.axisText,d||c?.75:.5),m=[];void 0!==this._opts.badge&&m.push({text:this._opts.badge,fill:c?W(l,.2):d?W(l,.12):l,textColor:D(l),border:W(l,-.25)}),void 0!==this._opts.qty&&m.push({text:String(this._opts.qty),fill:n,textColor:h,border:p}),void 0!==this._opts.leftLabel&&""!==this._opts.leftLabel&&m.push({text:this._opts.leftLabel,fill:n,textColor:h,border:p}),!0===this._opts.closeButton&&m.push({close:!0,fill:u?l:n,textColor:u?D(l):h,border:u?l:p}),this._group=function(e,t,i,r,s){const{height:n,padX:o,radius:a,gap:l,dpr:h}=s,c=r.map(t=>!0===t.close?20*h:e.measureText(t.text??"").width+2*o),d=c.reduce((e,t)=>e+t,0)+l*Math.max(0,r.length-1);void 0!==s.backplate&&(e.beginPath(),q(e,t,i-n/2,d,n,a),e.fillStyle=s.backplate,e.fill());let u=Number.POSITIVE_INFINITY,p=t;for(let t=0;t<r.length;t++){const s=r[t],d=c[t];if(e.beginPath(),q(e,p,i-n/2,d,n,a),e.fillStyle=s.fill,e.fill(),void 0!==s.border&&(e.strokeStyle=s.border,e.lineWidth=Math.max(1,Math.round(h)),e.stroke()),!0===s.close){u=p,e.strokeStyle=s.textColor,e.lineWidth=Math.max(1,Math.round(1.4*h));const t=p+d/2,r=3.5*h;e.beginPath(),e.moveTo(t-r,i-r),e.lineTo(t+r,i+r),e.moveTo(t+r,i-r),e.lineTo(t-r,i+r),e.stroke()}else e.fillStyle=s.textColor,e.textAlign="left",e.textBaseline="middle",e.fillText(s.text??"",p+o,i);p+=d+l}return{x0:t/h,x1:(p-l)/h,closeX0:u/h}}(e,a+(1===o?6*r:0),i,m,{height:_,padX:b,radius:f,gap:2*r,backplate:s?void 0:t.theme.background,dpr:r})}e.restore()}hitTest(e,t,i){if(e<0||e>i.plotWidth)return null;const r=i.priceScale.priceToY(this._opts.price),s=Math.abs(t-r),n=this._group;return null!==n&&s<=10&&e>=n.x0&&e<=n.x1?this._opts.closeButton&&e>=n.closeX0?{externalId:`${this._opts.id}::close`,zOrder:"normal",distance:s,cursor:"pointer"}:{externalId:this._opts.id,zOrder:"normal",distance:s,cursor:this._opts.cursor}:s>4?null:{externalId:this._opts.id,zOrder:"normal",distance:s,cursor:this._opts.cursor}}}const Zi={long:"#2f6df6",short:"#ef5350",order:"#3b82f6",tp:"#26a69a",sl:"#ef5350",buy:"#26a69a",sell:"#ef5350"},Qi="::close";function er(e,t){const i=e.length;if(0===i)return;let r=0,s=i-1;for(;r<s;){const i=r+s+1>>1,n=e.indexToTime(i);void 0!==n&&n<=t?r=i:s=i-1}const n=e.indexToTime(r);if(void 0!==n){if(r+1<i){const i=e.indexToTime(r+1);if(void 0!==i&&Math.abs(i-t)<Math.abs(n-t))return r+1}return r}}function tr(e,t,i,r,s,n){const o=5*n;e.fillStyle=s,e.beginPath(),"buy"===r?(e.moveTo(t,i-1.5*o),e.lineTo(t-o,i),e.lineTo(t+o,i)):(e.moveTo(t,i+1.5*o),e.lineTo(t-o,i),e.lineTo(t+o,i)),e.closePath(),e.fill()}function ir(e,t,i,r,s,n){const o=9*n;e.fillStyle=r,e.beginPath(),e.arc(t,i,o,0,2*Math.PI),e.fill(),""!==s&&(e.fillStyle=D(r),e.font=`500 ${9*n}px system-ui, sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillText(s,t,i+.5*n))}function rr(e,t,i,r,s,n){const o=String(r);e.font=`500 ${9*n}px system-ui, sans-serif`;const a=e.measureText(o).width+10*n,l=15*n;e.fillStyle=s,e.beginPath(),q(e,Math.round(t-a/2),Math.round(i-l/2),Math.round(a),Math.round(l),3*n),e.fill(),e.fillStyle=D(s),e.textAlign="center",e.textBaseline="middle",e.fillText(o,t,i+.5*n)}class sr{constructor(e){Object.defineProperty(this,"_trades",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_colors",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._colors=e}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"top"}autoscaleInfo(){return null}setTrades(e){this._trades=e,this._host?.requestUpdate()}setColors(e){this._colors=e,this._host?.requestUpdate()}draw(e,t){if(0===this._trades.length)return;const i=t.dpr,r=new Map;e.save();for(const s of this._trades){const n=er(t.dataLayer,Math.floor(s.timestamp/1e3));if(void 0===n)continue;const o=Math.round(t.timeScale.indexToX(n)*i),a=s.color??("buy"===s.side?this._colors.buy:this._colors.sell),l=s.variant??"chevron";if("count"===l){const e=`${n}:${s.side}`;let t=r.get(e);void 0===t&&(t={index:n,sumPS:0,sumS:0,n:0,color:a},r.set(e,t)),t.sumPS+=s.price*s.size,t.sumS+=s.size,t.n+=1;continue}const h=Math.round(t.priceScale.priceToY(s.price)*i);"bubble"===l?ir(e,o,h,a,s.label??("buy"===s.side?"B":"S"),i):tr(e,o,h,s.side,a,i)}for(const s of r.values()){const r=s.sumS>0?s.sumPS/s.sumS:0;rr(e,Math.round(t.timeScale.indexToX(s.index)*i),Math.round(t.priceScale.priceToY(r)*i),s.n,s.color,i)}e.restore()}}class nr{constructor(e){Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_positions",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_orders",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_trades",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_dragPrev",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_colors",{enumerable:!0,configurable:!0,writable:!0,value:{...Zi}}),Object.defineProperty(this,"_markers",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._host=e,e.subscribeClick(e=>this._onClick(e)),e.subscribeDrag((e,t)=>this._onDrag(e,t),(e,t)=>this._onDragEnd(e,t))}on(e,t){let i=this._listeners.get(e);return void 0===i&&(i=new Set,this._listeners.set(e,i)),i.add(t),()=>{this._listeners.get(e)?.delete(t)}}off(e,t){this._listeners.get(e)?.delete(t)}_emit(e,t){const i=this._listeners.get(e);if(void 0!==i)for(const e of i)e(t);this._host.emit?.(e,t)}setSettings(e){void 0!==e.longColor&&(this._colors.long=e.longColor),void 0!==e.shortColor&&(this._colors.short=e.shortColor),void 0!==e.orderColor&&(this._colors.order=e.orderColor),void 0!==e.tpColor&&(this._colors.tp=e.tpColor),void 0!==e.slColor&&(this._colors.sl=e.slColor),void 0!==e.buyColor&&(this._colors.buy=e.buyColor),void 0!==e.sellColor&&(this._colors.sell=e.sellColor),this.setPositions(this.getPositions()),this.setOrders(this.getOrders()),this._markers?.setColors(this._colors)}getSettings(){return{...this._colors}}setPositions(e){this._sync(this._positions,e,"pos")}setOrders(e){this._sync(this._orders,e,"ord")}setTrades(e){this._trades.clear();for(const t of e)this._trades.set(t.id,t);this._renderTrades()}addTrade(e){this._trades.set(e.id,e),this._renderTrades()}upsertOrder(e){const t=this.getOrders().filter(t=>t.id!==e.id);t.push(e),this.setOrders(t)}removeOrder(e){const t=this.getOrders().filter(t=>t.id!==e&&t.parentId!==e);this.setOrders(t)}syncState(e){void 0!==e.positions&&this.setPositions(e.positions),void 0!==e.orders&&this.setOrders(e.orders),void 0!==e.trades&&this.setTrades(e.trades)}updatePositionPnl(e,t,i,r){const s=this._positions.get(e);void 0!==s&&(void 0!==i&&(s.entity.pnlText=i),void 0!==r&&(s.entity.pnlPercent=r),s.line.setLeftLabel(this._positionPill(s.entity)))}getPositions(){return[...this._positions.values()].map(e=>e.entity)}getOrders(){return[...this._orders.values()].map(e=>e.entity)}getTrades(){return[...this._trades.values()]}clear(){for(const e of this._positions.values())this._host.removePrimitive(e.line);for(const e of this._orders.values())this._host.removePrimitive(e.line);this._positions.clear(),this._orders.clear(),this._trades.clear(),null!==this._markers&&(this._host.removePrimitive(this._markers),this._markers=null)}_renderTrades(){null===this._markers&&(this._markers=new sr(this._colors),this._host.addPrimitive(this._markers)),this._markers.setTrades(this.getTrades())}_sync(e,t,i){const r=new Set;for(const s of t){r.add(s.id);const t="pos"===i?this._positionOpts(s):this._orderOpts(s),n=this._sig(t),o=e.get(s.id);if(void 0!==o&&o.sig===n)o.entity=s,o.line.setPrice(t.price),void 0!==t.leftLabel&&o.line.setLeftLabel(t.leftLabel);else{void 0!==o&&this._host.removePrimitive(o.line);const i=new Ji(t);this._host.addPrimitive(i),e.set(s.id,{entity:s,line:i,sig:n})}}for(const[t,i]of e)r.has(t)||(this._host.removePrimitive(i.line),e.delete(t))}_sig(e){return`${e.color}|${e.dashed}|${!0===e.closeButton}|${e.cursor??""}|${void 0!==e.leftLabel}|${e.badge??""}|${e.qty??""}`}_positionPill(e){return void 0===e.pnlText?"":`${e.pnlText}${void 0!==e.pnlPercent?` (${e.pnlPercent})`:""}`}_positionOpts(e){const t="line-only"===e.variant;return{price:e.entryPrice,color:e.color??("long"===e.side?this._colors.long:this._colors.short),lineWidth:2,dashed:!1,id:`pos:${e.id}`,badge:t?void 0:e.side.toUpperCase(),qty:t?void 0:e.size,leftLabel:t?void 0:this._positionPill(e),closeButton:!t&&!0!==e.readOnly,extentFromRight:.3}}_orderOpts(e){const t="line-only"===e.variant,i=!t&&(e.draggable??!0!==e.readOnly),r=e.color??("tp"===e.bracketRole?this._colors.tp:"sl"===e.bracketRole?this._colors.sl:this._colors.order);return{price:e.price,color:r,lineWidth:e.lineWidth??1,dashed:"solid"!==(e.lineStyle??"solid"),id:`ord:${e.id}`,badge:t?void 0:(e.bracketRole??e.side).toUpperCase(),qty:t?void 0:e.size,leftLabel:t||void 0!==e.bracketRole?void 0:e.type.replace("_"," ").toUpperCase(),closeButton:!t&&!0!==e.readOnly,extentFromRight:.3,cursor:i?"ns-resize":void 0}}_onClick(e){if(e.endsWith(Qi)){const t=e.slice(0,-7);if(t.startsWith("ord:")){const e=t.slice(4);this._orders.has(e)&&this._emit("trading:order_cancel",{orderId:e})}else if(t.startsWith("pos:")){const e=t.slice(4);this._positions.has(e)&&this._emit("trading:position_close",{positionId:e})}return}if(e.startsWith("ord:")){const t=this._orders.get(e.slice(4));void 0!==t&&this._emit("trading:order_click",{order:t.entity})}else if(e.startsWith("pos:")){const t=this._positions.get(e.slice(4));void 0!==t&&this._emit("trading:position_click",{position:t.entity})}}_onDrag(e,t){if(!e.startsWith("ord:"))return;const i=this._orders.get(e.slice(4));if(void 0===i)return;const r=e.slice(4);this._dragPrev.has(r)||(this._dragPrev.set(r,i.entity.price),i.line.setDragGhost(i.entity.price)),i.line.setPrice(t)}_onDragEnd(e,t){if(!e.startsWith("ord:"))return;const i=e.slice(4),r=this._orders.get(i);if(void 0===r)return;const s=this._dragPrev.get(i)??r.entity.price;this._dragPrev.delete(i),r.line.setDragGhost(null),r.entity.price=t,r.line.setPrice(t),void 0!==r.entity.bracketRole?this._emit("trading:bracket_modify",{parentId:r.entity.parentId,bracketRole:r.entity.bracketRole,newPrice:t}):this._emit("trading:order_modify",{orderId:i,newPrice:t,previousPrice:s})}}function or(e,t){return{dist:Math.hypot(e.x-t.x,e.y-t.y),cx:(e.x+t.x)/2,cy:(e.y+t.y)/2}}const ar=new WeakMap;function lr(e,t,i){ar.get(e)?.();let r=null;const s=s=>{null!==r&&(r(),r=null,ar.get(e)===n&&ar.delete(e),e.emit("pick:end",{kind:t,value:s}),null!==s&&i(s))},n=()=>s(null);return r=e.on("click",i=>{const r=i;let n="price"===t?r.price:r.time;if(null!==n&&Number.isFinite(n)){if("time"===t){const t=e.dataLayer;n=t.indexToTime(Math.round(t.timeToIndexFloat(n)))??n}s(n)}}),ar.set(e,n),e.emit("pick:start",{kind:t}),n}const hr={tiny:6,small:9,medium:12,big:16};function cr(e){return hr[e]}function dr(e,t){return Math.max(4,Math.min(hr[e],Math.floor(t)))}function ur(e,t,i,r,s,n){const o=s/2;switch(e.fillStyle=n,e.strokeStyle=n,e.beginPath(),t){case"arrowUp":case"triangleUp":e.moveTo(i,r-o),e.lineTo(i+o,r+o),e.lineTo(i-o,r+o),e.closePath(),e.fill();break;case"arrowDown":case"triangleDown":e.moveTo(i,r+o),e.lineTo(i+o,r-o),e.lineTo(i-o,r-o),e.closePath(),e.fill();break;case"circle":e.arc(i,r,o,0,2*Math.PI),e.fill();break;case"square":e.fillRect(i-o,r-o,s,s);break;case"diamond":e.moveTo(i,r-o),e.lineTo(i+o,r),e.lineTo(i,r+o),e.lineTo(i-o,r),e.closePath(),e.fill();break;case"flag":e.fillRect(i-1,r-o,Math.max(1,s/8),s),e.fillRect(i,r-o,o,.8*o);break;case"cross":{const t=Math.max(1,Math.round(s/6));e.fillRect(i-o,r-Math.floor(t/2),s,t),e.fillRect(i-Math.floor(t/2),r-o,t,s);break}case"xcross":e.lineWidth=Math.max(1,Math.round(s/6)),e.moveTo(i-o,r-o),e.lineTo(i+o,r+o),e.moveTo(i+o,r-o),e.lineTo(i-o,r+o),e.stroke()}}function pr(e,t,i,r,s,n,o){e.font=`600 ${o}px system-ui, sans-serif`;const a=.5*o,l=s.indexOf("\n")<0?void 0:s.split("\n");let h=e.measureText(void 0===l?s:l[0]).width;if(void 0!==l)for(let t=1;t<l.length;t++)h=Math.max(h,e.measureText(l[t]).width);const c=1.35*o,d=h+2*a,u=o+.64*o+(void 0===l?0:c*(l.length-1)),p=.42*o,_=t?r+p:r-p-u;e.fillStyle=n,e.beginPath(),q(e,i-d/2,_,d,u,Math.min(.3*o,u/2)),e.fill();const b=t?_+1:_+u-1;if(e.beginPath(),e.moveTo(i,r),e.lineTo(i-p,b),e.lineTo(i+p,b),e.closePath(),e.fill(),e.fillStyle=D(n),e.textAlign="center",e.textBaseline="middle",void 0===l)return void e.fillText(s,i,_+u/2);const f=_+u/2-c*(l.length-1)/2;for(let t=0;t<l.length;t++)e.fillText(l[t],i,f+c*t)}class _r{constructor(e,t,i){Object.defineProperty(this,"_seriesId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_fallbackBars",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_priceScale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_markers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_lastPositions",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this._seriesId=e,this._fallbackBars=t,this._priceScale=i}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"normal"}setMarkers(e){this._markers=e.slice().sort((e,t)=>e.time-t.time),this._host?.requestUpdate()}draw(e,t){if(this._lastPositions=[],0===this._markers.length)return;const i=new Map;if(void 0!==this._fallbackBars)for(const e of this._fallbackBars())i.set(e.time,e);for(const{bar:e}of t.dataLayer.indexedBars(this._seriesId))Number.isFinite(e.close)&&i.set(e.time,e);const r=this._priceScale?.()??t.priceScale,s=t.timeScale.visibleRange(),n=new Map;e.save();for(const o of this._markers){const a=t.dataLayer.timeToIndex(o.time);if(void 0===a||a<s.from-1||a>s.to+1)continue;const l=i.get(o.time),h=dr(o.size,t.timeScale.barSpacing)*t.dpr,c=t.timeScale.indexToX(a)*t.dpr,d=n.get(o.time)??0,u=(h+4*t.dpr)*d;let p;if("paneTop"===o.position)p=h/2+4*t.dpr+u;else if("paneBottom"===o.position)p=t.plotHeight*t.dpr-h/2-4*t.dpr-u;else if("atPrice"===o.position&&void 0!==o.price)p=r.priceToY(o.price)*t.dpr;else if(void 0!==l&&"aboveBar"===o.position)p=r.priceToY(l.high)*t.dpr-h-u;else if(void 0!==l&&"belowBar"===o.position)p=r.priceToY(l.low)*t.dpr+h+u;else{if(void 0===l)continue;p=r.priceToY((l.open+l.close)/2)*t.dpr}if(Number.isFinite(p))if(n.set(o.time,d+1),"labelUp"!==o.shape&&"labelDown"!==o.shape){if(ur(e,o.shape,c,p,h,o.color),void 0!==o.text){const i=Math.max(9,cr(o.size))*t.dpr;e.fillStyle=o.color,e.font=`${i}px system-ui, sans-serif`,e.textAlign="center";const r="belowBar"===o.position||"paneTop"===o.position;e.textBaseline=r?"top":"bottom";const s=r?p+h:p-h;if(o.text.indexOf("\n")<0)e.fillText(o.text,c,s);else{const t=o.text.split("\n"),n=1.35*i;for(let i=0;i<t.length;i++)e.fillText(t[r?i:t.length-1-i],c,r?s+n*i:s-n*i)}}void 0!==o.id&&this._lastPositions.push({id:o.id,x:c/t.dpr,y:p/t.dpr})}else void 0!==o.text&&pr(e,"labelUp"===o.shape,c,p,o.text,o.color,Math.max(9,cr(o.size))*t.dpr),void 0!==o.id&&this._lastPositions.push({id:o.id,x:c/t.dpr,y:p/t.dpr})}e.restore()}hitTest(e,t){let i=null;for(const r of this._lastPositions){const s=Math.hypot(r.x-e,r.y-t);s<=8&&(null===i||s<i.distance)&&(i={externalId:r.id,zOrder:"normal",distance:s,cursor:"pointer"})}return i}}const br={earnings:"#f0a020",dividend:"#26a69a",split:"#4f8cff",news:"#9aa0b4"};function fr(e){return{...e,..."object"==typeof e.details&&null!==e.details?{details:{...e.details,...e.details.fields?{fields:e.details.fields.map(e=>({...e}))}:{}}}:{}}}class mr{constructor(e={}){Object.defineProperty(this,"_entries",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_groups",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:{clustering:!1,clusterRadius:18}}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_positions",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_hits",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_providedIds",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_duplicateIds",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_width",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_height",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.setOptions(e)}attached(e){this._host=e}detached(){this._host=null,this._invalidate()}zOrder(){return"normal"}setEvents(e){const t=e.map(e=>{if(!Number.isFinite(e.time))throw new Error("openalgo-charts: event time must be finite");return fr(e)}).sort((e,t)=>e.time-t.time),i=new Map;this._entries=t.map(e=>{const t=void 0===e.id?JSON.stringify([e.time,e.type,e.label,e.group??null]):JSON.stringify(e.id),r=i.get(t)??0;return i.set(t,r+1),{event:e,key:`${t}:${r}`}}),this._providedIds=new Set(t.flatMap(e=>void 0===e.id?[]:[e.id])),this._duplicateIds=new Set([...this._providedIds].filter(e=>(i.get(JSON.stringify(e))??0)>1)),this._invalidate()}events(){return this._entries.map(e=>fr(e.event))}setGroups(e){const t=new Map;for(const i of e){if(!i.id||t.has(i.id))throw new Error("openalgo-charts: event group IDs must be nonempty and unique");t.set(i.id,{...i})}const i=new Set;for(const e of t.keys()){const r=new Set;let s=e;for(;void 0!==s&&!i.has(s);){if(r.has(s))throw new Error("openalgo-charts: event group cycle");const e=t.get(s);if(void 0===e)throw new Error("openalgo-charts: event group parent is missing");r.add(s),s=e.parentId}for(const e of r)i.add(e)}this._groups=t,this._invalidate()}groups(){return Array.from(this._groups.values(),e=>({...e}))}setGroupVisible(e,t){const i=this._groups.get(e);if(void 0===i)throw new Error(`openalgo-charts: unknown event group ${e}`);i.visible=t,this._invalidate()}isGroupVisible(e){let t=this._groups.get(e);for(;void 0!==t;){if(!1===t.visible)return!1;t=void 0===t.parentId?void 0:this._groups.get(t.parentId)}return!0}setOptions(e){const t=e.clusterRadius??this._options.clusterRadius;if(!Number.isFinite(t)||t<1||t>200)throw new Error("openalgo-charts: event clusterRadius must be from 1 to 200");this._options={clustering:e.clustering??this._options.clustering,clusterRadius:t},this._invalidate()}options(){return{...this._options}}detailsForHit(e){const t=this._hits.get(e);return void 0===t?null:{id:t.id,cluster:t.entries.length>1,events:t.entries.map(e=>fr(e.event))}}draw(e,t){if(this._positions=[],this._hits.clear(),this._width=t.plotWidth,this._height=t.plotHeight,!(0!==this._entries.length&&t.dpr>0&&Number.isFinite(t.dpr)&&t.plotWidth>0&&t.plotHeight>0))return;const i=[];for(const e of this._entries){if(void 0!==e.event.group&&!this.isGroupVisible(e.event.group))continue;const r=t.dataLayer.timeToIndexFloat(e.event.time),s=t.timeScale.indexToX(r);if(!Number.isFinite(s))continue;const n=i[i.length-1];this._options.clustering&&void 0!==n&&s-n.firstX<=this._options.clusterRadius?(n.entries.push(e),n.x+=(s-n.x)/n.entries.length):i.push({x:s,firstX:s,entries:[e]})}const r=t.plotHeight-8-4;e.save(),e.beginPath(),e.rect(0,0,t.plotWidth*t.dpr,t.plotHeight*t.dpr),e.clip(),e.textAlign="center",e.textBaseline="middle",e.font=10*t.dpr+"px system-ui, sans-serif";for(const s of i){if(s.x+8<0||s.x-8>t.plotWidth||r+8<0)continue;const i=s.entries[0].event,n=s.entries.length>1;let o=i.id;if(n||void 0===o||this._duplicateIds.has(o))for(o=`${n?"event-cluster:":"event:"}${JSON.stringify(s.entries.map(e=>e.key).sort())}`;this._providedIds.has(o);)o=":"+o;e.fillStyle=i.color??br[i.type]??"#9aa0b4",e.beginPath(),e.arc(s.x*t.dpr,r*t.dpr,8*t.dpr,0,2*Math.PI),e.fill(),e.fillStyle="#0d0e12";const a=n?s.entries.length>99?"99+":String(s.entries.length):i.label.slice(0,2);e.fillText(a,s.x*t.dpr,r*t.dpr);const l={id:o,x:s.x,y:r,r:8,entries:s.entries};this._positions.push(l),this._hits.set(o,l)}e.restore()}hitTest(e,t){if(e<0||t<0||e>this._width||t>this._height)return null;let i=null;for(const r of this._positions){const s=Math.hypot(r.x-e,r.y-t);s<=r.r&&(null===i||s<=i.distance)&&(i={externalId:r.id,zOrder:"normal",distance:s,cursor:"pointer"})}return i}_invalidate(){this._positions=[],this._hits.clear(),this._host?.requestUpdate()}}const gr="ui-sans-serif, system-ui, sans-serif",vr={},yr={};function wr(e){const t=e.iconSize;return"number"==typeof t&&Number.isFinite(t)?Math.max(12,Math.min(28,t)):16}function xr(e){return Math.max(18,wr(e)+2)}const Pr=e=>e.parts.reduce((e,t)=>e+t.w+t.gap,0);function Sr(e,t,i){return"ohlc"===t?!1!==e.chartValues:"change"===t?!1!==e.barChange:"volume"===t?!1!==e.volume:"openInterest"===t?!0===e.openInterest&&!1!==i:!1!==e.lastValueLabel}const Or=["hide","settings","close"];function kr(e,t,i,r,s,n,o){const a=.36*s*n,l=Math.max(1,Math.round(1.4*s*n/16));switch(e.save(),e.strokeStyle=e.fillStyle,e.lineWidth=l,e.lineCap="round",e.lineJoin="round",e.beginPath(),t){case"up":e.moveTo(i,r+a),e.lineTo(i,r-a),e.moveTo(i-.62*a,r-.35*a),e.lineTo(i,r-a),e.lineTo(i+.62*a,r-.35*a);break;case"down":e.moveTo(i,r-a),e.lineTo(i,r+a),e.moveTo(i-.62*a,r+.35*a),e.lineTo(i,r+a),e.lineTo(i+.62*a,r+.35*a);break;case"hide":e.moveTo(i-a,r),e.quadraticCurveTo(i,r-1.15*a,i+a,r),e.quadraticCurveTo(i,r+1.15*a,i-a,r),e.stroke(),e.beginPath(),e.arc(i,r,.34*a,0,2*Math.PI),!0===o.hidden&&(e.moveTo(i-a,r+.85*a),e.lineTo(i+a,r-.85*a));break;case"maximize":!0===o.maximized?(e.moveTo(i-a,r-.25*a),e.lineTo(i-.25*a,r-.25*a),e.lineTo(i-.25*a,r-a),e.moveTo(i+a,r+.25*a),e.lineTo(i+.25*a,r+.25*a),e.lineTo(i+.25*a,r+a)):(e.moveTo(i-a,r-.4*a),e.lineTo(i-a,r-a),e.lineTo(i-.4*a,r-a),e.moveTo(i+.4*a,r-a),e.lineTo(i+a,r-a),e.lineTo(i+a,r-.4*a),e.moveTo(i+a,r+.4*a),e.lineTo(i+a,r+a),e.lineTo(i+.4*a,r+a),e.moveTo(i-.4*a,r+a),e.lineTo(i-a,r+a),e.lineTo(i-a,r+.4*a));break;case"settings":e.arc(i,r,.46*a,0,2*Math.PI);for(let t=0;t<8;t++){const s=t*Math.PI/4,n=Math.cos(s),o=Math.sin(s);e.moveTo(i+n*a*.68,r+o*a*.68),e.lineTo(i+n*a,r+o*a)}break;case"source":{const t=.62*a,s=.34*a,n=.28*a;for(const o of[-1,1]){const l=i+o*t;e.moveTo(l-o*s,r-a),e.quadraticCurveTo(l,r-a,l,r-.55*a),e.lineTo(l,r-.2*a),e.quadraticCurveTo(l,r,l+o*n,r),e.quadraticCurveTo(l,r,l,r+.2*a),e.lineTo(l,r+.55*a),e.quadraticCurveTo(l,r+a,l-o*s,r+a)}break}case"close":e.moveTo(i-.8*a,r-.55*a),e.lineTo(i+.8*a,r-.55*a),e.moveTo(i-.3*a,r-.55*a),e.lineTo(i-.3*a,r-.85*a),e.lineTo(i+.3*a,r-.85*a),e.lineTo(i+.3*a,r-.55*a),e.moveTo(i-.6*a,r-.55*a),e.lineTo(i-.45*a,r+.85*a),e.lineTo(i+.45*a,r+.85*a),e.lineTo(i+.6*a,r-.55*a)}e.stroke(),e.restore()}class Mr{constructor(e){Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_values",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_buttons",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_width",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_plotWidth",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_plotHeight",{enumerable:!0,configurable:!0,writable:!0,value:0}),this._opts={font:11,left:8,top:6,row:0,...e}}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"top"}autoscaleInfo(){return null}setValue(e,t){this.setValues(""===e?[]:[{text:e,color:t}])}setValues(e){e.length===this._values.length&&e.every((e,t)=>e.text===this._values[t].text&&e.label===this._values[t].label&&e.color===this._values[t].color&&e.field===this._values[t].field&&e.priority===this._values[t].priority)||(this._values=e.map(e=>({...e})),this._host?.requestUpdate())}setOptions(e){const t=this._opts.statusLine;this._opts={...this._opts,...e},void 0!==e.statusLine&&(this._opts.statusLine={...t,...e.statusLine}),this._host?.requestUpdate()}_status(){const e=this._opts.status;return void 0===e?yr:("function"==typeof e?e():e)??yr}options(){return this._opts}draw(e,t){const i=this._opts,r=t.dpr,s=(i.font??11)*r,n=wr(i),o=xr(i),a=((i.top??6)+(i.row??0)*o)*r,l=a+o*r/2,h=(i.left??8)*r;let c=h;const d=!0===i.hidden,u=i.statusLine??vr,p=this._status(),_=R(t.theme.axisText,.55);this._plotWidth=Math.max(0,t.plotWidth),this._plotHeight=Math.max(0,t.plotHeight);const b=Math.max(0,(this._plotWidth-4)*r-h),f="string"==typeof t.hoverId&&t.hoverId.startsWith(`${i.id}::`),m=Math.max(0,Math.floor((b/r-6)/(n+2))),g=f&&m>0?(i.actions??Or).slice(-m):[],v=g.length?(g.length*(n+2)+6)*r:0;e.save(),e.beginPath(),e.rect(0,0,this._plotWidth*r,t.plotHeight*r),e.clip(),e.textBaseline="middle",e.textAlign="left",e.globalAlpha=d?.45:1;const y=[],w=(t,i,n,o)=>(e.font=`${n?"600 ":""}${s}px ${gr}`,{k:"text",text:t,color:i,bold:n,w:e.measureText(t).width,gap:o*r}),x=(e,t,i=1)=>{const r=[];void 0!==e.label&&""!==e.label&&r.push(w(e.label,_,!1,3)),r.push(w(e.text,e.color??t,!1,6)),y.push({parts:r,priority:Number.isFinite(e.priority)?e.priority:i,reading:i>0})};let P;if(void 0!==p.logo&&!1!==u.logo&&y.push({parts:[{k:"logo",img:p.logo,w:12*r,gap:5*r}],priority:-1}),void 0!==i.color&&y.push({parts:[{k:"dot",color:i.color,w:6*r,gap:5*r}],priority:-1}),!1!==u.title){const e=u.titleMode??"symbol",r="description"===e?p.description:"ticker"===e?p.ticker:void 0;P=w(r??i.title,t.theme.axisText,!0,6),y.push({parts:[P],priority:0})}void 0!==i.params&&""!==i.params&&y.push({parts:[w(i.params,_,!1,6)],priority:-3}),void 0!==p.marketStatus&&!1!==u.marketStatus&&x(p.marketStatus,_,-4);const S=i.valueColor??i.color??t.theme.axisText;for(const e of this._values)Sr(u,e.field,i.hasOpenInterest)&&x(e,S);void 0!==p.lastDayChange&&!1!==u.lastDayChange&&x(p.lastDayChange,S,-2),e.font=`600 ${s}px ${gr}`;const O=function(e,t,i,r){if(t.reduce((e,t)=>e+Pr(t),0)<=r)return t.flatMap(e=>e.parts);const s=t.filter(e=>!e.parts.includes(i)).sort((e,t)=>t.priority-e.priority);if("text"===i?.k){const t=s.find(e=>e.reading),n=t?Pr(t):0,o=n<=.75*r?n:0,a=Math.max(0,r-o-i.gap);if(i.w>a){const t=Array.from(i.text);let r=0,s=t.length;for(;r<s;){const i=Math.ceil((r+s)/2);e.measureText(t.slice(0,i).join("")+"...").width<=a?r=i:s=i-1}i.text=e.measureText("...").width<=a?t.slice(0,r).join("")+"...":"",i.w=e.measureText(i.text).width,i.text||(i.gap=0)}r-=i.w+i.gap}const n=new Set;for(const e of s){const t=Pr(e);t<=r&&(n.add(e),r-=t)}return t.filter(e=>e.parts.includes(i)||n.has(e)).flatMap(e=>e.parts)}(e,y,P,Math.max(0,b-v)),k=O[O.length-1];if(!0===u.background&&void 0!==k){const i=4*r,s=O.reduce((e,t)=>e+t.w+t.gap,0)-k.gap+2*i;e.globalAlpha=1,e.fillStyle=R(u.backgroundColor??t.theme.background,u.backgroundOpacity??.8),e.beginPath(),e.roundRect(h-i,l-o/2*r,s,o*r,4*r),e.fill(),e.globalAlpha=d?.45:1}for(const t of O)"text"===t.k?(e.font=`${t.bold?"600 ":""}${s}px ${gr}`,e.fillStyle=t.color,e.fillText(t.text,c,l)):"dot"===t.k?(e.fillStyle=t.color,e.beginPath(),e.arc(c+3*r,l,3*r,0,2*Math.PI),e.fill()):e.drawImage(t.img,c,l-t.w/2,t.w,t.w),c+=t.w+t.gap;if(this._buttons=[],g.length>0){const s=(g.length*(n+2)+6)*r;e.globalAlpha=1,e.fillStyle=R(t.theme.background,.82),e.beginPath(),e.roundRect(c-3*r,l-o/2*r,s,o*r,5*r),e.fill(),c+=2*r;for(const s of g){const o=`${i.id}::${s}`,h=c;this._buttons.push({id:o,x:h/r,y:a/r});const u=t.hoverId===o;u&&(e.fillStyle=R(t.theme.axisText,.16),e.beginPath(),e.roundRect(h,l-n/2*r,n*r,n*r,4*r),e.fill()),e.globalAlpha=d?.5:u?1:.75,e.fillStyle="close"===s&&u?"#ff6b6b":t.theme.axisText,kr(e,s,h+n/2*r,l,n,r,i),e.globalAlpha=1,c+=(n+2)*r}}this._width=c/r,e.restore()}hitTest(e,t){if(e<0||e>=this._plotWidth||t<0||t>=this._plotHeight)return null;const i=this._opts,r=xr(i),s=(i.top??6)+(i.row??0)*r;if(t<s||t>s+r)return null;const n=wr(i);for(const t of this._buttons)if(e>=t.x&&e<=t.x+n)return{externalId:t.id,zOrder:"top",distance:0,cursor:"pointer"};const o=Math.max(this._width,(i.left??8)+40)+130;return e>=(i.left??8)-4&&e<=o?{externalId:`${i.id}::row`,zOrder:"top",distance:0,cursor:"default"}:null}}const Tr={position:"bottom-right",margin:8,cellWidth:64,cellHeight:18,fontSize:11,borderWidth:1};function Cr(e,t,i){return Math.min(Math.round(e*i),Math.floor(.62*t))}const Ir=28;function jr(e,t,i,r,s,n){const[o,a]=e.split("-");return{x:"left"===a?t:"right"===a?s-i-t:(s-i)/2,y:"top"===o?t:"bottom"===o?n-r-t:(n-r)/2}}class Ar{constructor(e={}){Object.defineProperty(this,"_rows",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_rect",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._opts={...Tr,...e}}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"top"}options(){return this._opts}setOptions(e){this._opts={...this._opts,...e},this._host?.requestUpdate()}setRows(e){this._rows=e,this._host?.requestUpdate()}rows(){return this._rows}draw(e,t){this._rect=null;const i=this._rows;if(0===i.length)return;const r=this._opts,s=t.dpr;let n=0;for(const e of i)e.length>n&&(n=e.length);if(0===n)return;const o=i.map((e,t)=>{const i=r.rowWeights?.[t];return"number"==typeof i&&i>0?i:1}),a=o.reduce((e,t)=>e+t,0);let l=r.cellHeight,h=l*a;void 0!==r.heightPercent&&r.heightPercent>0&&(h=t.plotHeight*r.heightPercent/100,l=h/a);const c=[];for(let e=0,t=0;e<i.length;e++)c.push(t),t+=l*o[e];const d=o.map(e=>Math.round(l*e*s));e.save();const u=function(e,t){const i=[];let r=0;for(let s=0;s<t;s++)i.push(r),r+="number"==typeof e?e:e[s]??e[e.length-1]??0;return{x:i,total:r}}("auto"===r.cellWidth?function(e,t,i,r,s,n){const o=[];for(let a=0;a<i;a++){let i=0;for(let o=0;o<t.length;o++){const l=t[o][a];if(void 0===l||""===l.text)continue;const h=l.fontSize??s.fontSize,c="auto"===h?Math.round(11*n):Cr(h,r[o],n);e.font=`${!0===l.bold?"600 ":""}${c}px system-ui, sans-serif`;const d=e.measureText(l.text).width/n;d>i&&(i=d)}o.push(Math.max(i+10,Ir))}return o}(e,i,n,d,r,s):r.cellWidth,n);let p=u.x,_=u.total;if(void 0!==r.widthPercent&&r.widthPercent>0&&_>0){const e=t.plotWidth*r.widthPercent/100,i=e/_;p=p.map(e=>e*i),_=e}const b=jr(r.position,r.margin,_,h,t.plotWidth,t.plotHeight);this._rect={x:b.x,y:b.y,w:_,h:h};const f=e=>Math.round(e*s),m=f(b.x),g=f(b.y);void 0!==r.background&&(e.fillStyle=r.background,e.fillRect(m,g,f(_),f(h))),e.textBaseline="middle";for(let n=0;n<i.length;n++){const o=i[n],a=g+f(c[n]),l=d[n];for(let i=0;i<o.length;i++){const n=o[i],h=m+f(p[i]),c=f((p[i+1]??_)-p[i]);if(void 0!==n.bgColor&&(e.fillStyle=n.bgColor,e.fillRect(h,a,c,l)),void 0!==r.borderColor&&r.borderWidth>0&&(e.strokeStyle=r.borderColor,e.lineWidth=Math.max(1,f(r.borderWidth)),e.strokeRect(h,a,c,l)),""===n.text)continue;const d=f(4);e.save(),e.beginPath(),e.rect(h,a,c,l),e.clip();const u=!0===n.bold?"600 ":"",b=Math.floor(.62*l);let g;if(void 0===n.fontSize&&"auto"===r.fontSize){const t=f(6);g=Math.max(t,b),e.font=`${u}${g}px system-ui, sans-serif`;const i=c-2*d;for(;g>t&&e.measureText(n.text).width>i;)g-=Math.max(1,f(1)),e.font=`${u}${g}px system-ui, sans-serif`}else g=Cr(n.fontSize??("auto"===r.fontSize?11:r.fontSize),l,s);e.font=`${u}${g}px system-ui, sans-serif`,e.fillStyle=n.textColor??(void 0!==n.bgColor?D(n.bgColor):t.theme.axisText);const v=n.align??"center";e.textAlign=v;const y="left"===v?h+d:"right"===v?h+c-d:h+c/2;e.fillText(n.text,y,a+l/2),e.restore()}}e.restore()}hitTest(e,t){const i=this._rect;return void 0===this._opts.id||null===i||e<i.x||e>i.x+i.w||t<i.y||t>i.y+i.h?null:{externalId:this._opts.id,zOrder:"top",distance:0,cursor:"default"}}}const Lr={zoomOut:"Zoom out",zoomIn:"Zoom in",resetScale:"Reset view",panLeftBar:"Move left",panRightBar:"Move right"},zr={id:"timenav",buttons:["zoomOut","zoomIn",null,"resetScale",null,"panLeftBar","panRightBar"],size:26,gap:4,groupGap:16,bottomMargin:10,revealHeight:64,fadeSeconds:.12,labels:Lr,hints:{},showTooltip:!0,font:11,radius:6,zOrder:"top"};class Fr{constructor(e={},t){Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_boxes",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_pointer",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_opacity",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastFrameMs",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_revealTop",{enumerable:!0,configurable:!0,writable:!0,value:1/0}),this._opts={...zr,...e,labels:{...zr.labels,...e.labels}},this._now=t??(()=>"undefined"!=typeof performance?performance.now():0)}attached(e){this._host=e}detached(){this._host=null}zOrder(){return this._opts.zOrder??"top"}options(){return this._opts}setOptions(e){this._opts={...this._opts,...e,labels:{...this._opts.labels,...e.labels}},this._host?.requestUpdate()}setPointer(e){const t=this._pointer;this._pointer=e,(null===t!=(null===e)||this._opacity>0||this._targetOpacity()>0)&&this._host?.requestUpdate()}_revealed(){return null!==this._pointer&&this._pointer.y>=this._revealTop}_targetOpacity(){return this._revealed()?1:0}animating(){return Math.abs(this._targetOpacity()-this._opacity)>.001}draw(e,t){const i=this._opts,r=t.dpr;this._revealTop=Math.max(0,t.plotHeight-i.revealHeight);const s=this._targetOpacity(),n=this._now(),o=null===this._lastFrameMs?0:Math.max(0,(n-this._lastFrameMs)/1e3);if(this._lastFrameMs=n,i.fadeSeconds<=0||o<=0)i.fadeSeconds<=0&&(this._opacity=s);else{const e=o/i.fadeSeconds;this._opacity+=Math.sign(s-this._opacity)*Math.min(e,Math.abs(s-this._opacity))}if(this._opacity<=.001)return this._boxes=[],void(this._opacity=0);const a=i.size;let l=0;for(let e=0;e<i.buttons.length;e++){null!==i.buttons[e]?(l+=a,e<i.buttons.length-1&&null!==i.buttons[e+1]&&(l+=i.gap)):l+=i.groupGap}const h=(t.plotWidth-l)/2,c=t.plotHeight-i.bottomMargin-a;this._boxes=[];let d=h;for(let e=0;e<i.buttons.length;e++){const t=i.buttons[e];null!==t?(this._boxes.push({action:t,x:d,y:c,w:a,h:a}),d+=a,e<i.buttons.length-1&&null!==i.buttons[e+1]&&(d+=i.gap)):d+=i.groupGap}const u=this._hoveredAction();e.save(),e.globalAlpha=this._opacity;for(const i of this._boxes)this._button(e,i,i.action===u,t,r);i.showTooltip&&null!==u&&this._tooltip(e,u,t,r),e.restore()}_hoveredAction(){const e=this._pointer;if(null===e)return null;for(const t of this._boxes)if(e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h)return t.action;return null}_button(e,t,i,r,s){const n=this._opts,o=t.x*s,a=t.y*s,l=t.w*s,h=t.h*s,c=Math.min(n.radius*s,l/2,h/2);e.beginPath(),e.roundRect(o,a,l,h,c),e.fillStyle=Br(r.theme.background,r.theme.axisText,i?.28:.12),e.fill(),e.strokeStyle=Nr(r.theme.axisLine,i?1:.8),e.lineWidth=Math.max(1,Math.round(s)),e.stroke(),e.strokeStyle=r.theme.axisText,e.fillStyle=r.theme.axisText,e.lineWidth=Math.max(1,Math.round(1.5*s)),e.lineCap="round",e.lineJoin="round";const d=o+l/2,u=a+h/2,p=.22*Math.min(l,h);switch(e.beginPath(),t.action){case"zoomOut":e.moveTo(d-p,u),e.lineTo(d+p,u);break;case"zoomIn":e.moveTo(d-p,u),e.lineTo(d+p,u),e.moveTo(d,u-p),e.lineTo(d,u+p);break;case"resetScale":{const t=p*Math.SQRT1_2;e.arc(d,u,p,.75*-Math.PI,.75*Math.PI),e.moveTo(d-t,u-2*t),e.lineTo(d-t,u-t),e.lineTo(d,u-t);break}case"panLeftBar":e.moveTo(d+.55*p,u-p),e.lineTo(d-.5*p,u),e.lineTo(d+.55*p,u+p);break;case"panRightBar":e.moveTo(d-.55*p,u-p),e.lineTo(d+.5*p,u),e.lineTo(d-.55*p,u+p)}e.stroke()}_tooltip(e,t,i,r){const s=this._opts,n=this._boxes.find(e=>e.action===t);if(void 0===n)return;const o=s.labels[t]??Lr[t],a=s.hints[t];e.font=s.font*r+"px ui-sans-serif, system-ui, sans-serif",e.textBaseline="middle",e.textAlign="left";const l=7*r,h=8*r,c=e.measureText(o).width,d=2*l+c+(void 0===a?0:e.measureText(a).width+h+8*r),u=22*r;let p=(n.x+n.w/2)*r-d/2;p=Math.max(2*r,Math.min(p,i.plotWidth*r-d-2*r));const _=n.y*r-u-6*r;if(e.beginPath(),e.roundRect(p,_,d,u,5*r),e.fillStyle=Br(i.theme.background,i.theme.axisText,.22),e.fill(),e.strokeStyle=Nr(i.theme.axisLine,.9),e.lineWidth=Math.max(1,Math.round(r)),e.stroke(),e.fillStyle=i.theme.axisText,e.fillText(o,p+l,_+u/2),void 0!==a){const t=p+l+c+h,s=e.measureText(a).width+8*r;e.beginPath(),e.roundRect(t-4*r,_+4*r,s,u-8*r,3*r),e.fillStyle=Br(i.theme.background,i.theme.axisText,.42),e.fill(),e.fillStyle=i.theme.axisText,e.fillText(a,t,_+u/2)}}hitTest(e,t){if(this._opacity<.5)return null;for(const i of this._boxes)if(e>=i.x&&e<=i.x+i.w&&t>=i.y&&t<=i.y+i.h)return{externalId:`${this._opts.id}::${i.action}`,zOrder:"top",distance:0,cursor:"pointer"};return null}}function Br(e,t,i){const r=$r(e),s=$r(t);if(null===r||null===s)return e;const n=i<0?0:i>1?1:i;return`rgb(${Math.round(r[0]+(s[0]-r[0])*n)},${Math.round(r[1]+(s[1]-r[1])*n)},${Math.round(r[2]+(s[2]-r[2])*n)})`}function $r(e){if(e.startsWith("#")){const t=e.slice(1),i=3===t.length?t.split("").map(e=>e+e).join(""):t,r=parseInt(i.slice(0,6),16);return Number.isNaN(r)?null:[r>>16&255,r>>8&255,255&r]}const t=/^rgba?\(([^)]+)\)$/.exec(e);if(null===t)return null;const i=t[1].split(",").map(e=>parseFloat(e));return[i[0],i[1],i[2]]}function Nr(e,t){if(e.startsWith("#")){const i=e.slice(1),r=3===i.length?i.split("").map(e=>e+e).join(""):i,s=parseInt(r.slice(0,6),16);return Number.isNaN(s)?e:`rgba(${s>>16&255},${s>>8&255},${255&s},${t})`}const i=/^rgba?\(([^)]+)\)$/.exec(e);if(null===i)return e;const r=i[1].split(",").map(e=>e.trim());return`rgba(${r[0]},${r[1]},${r[2]},${t})`}function Dr(e){return void 0===e?{x:7,y:4}:"number"==typeof e?{x:e,y:e}:{x:e.x,y:e.y}}function Rr(e,t,i,r,s,n){const o=s-t-i,a=n-t-r;switch(e){case"top-left":return{x:t,y:t,w:i,h:r};case"top-right":return{x:o,y:t,w:i,h:r};case"bottom-left":return{x:t,y:a,w:i,h:r};case"center":return{x:(s-i)/2,y:(n-r)/2,w:i,h:r};default:return{x:o,y:a,w:i,h:r}}}class Er{constructor(e={}){Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_reveal",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastFrameMs",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_labelW",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:"undefined"!=typeof performance?()=>performance.now():()=>0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_img",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_ready",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_autoHeight",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tintCanvas",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_tintKey",{enumerable:!0,configurable:!0,writable:!0,value:""}),this._autoHeight=void 0===e.height,this._opts={position:e.position??"bottom-right",margin:e.margin??12,height:e.height??28,opacity:e.opacity??.7,zOrder:e.zOrder??"top",src:e.src,image:e.image,tint:e.tint,label:e.label,id:e.id??"watermark",revealSeconds:e.revealSeconds??.18,labelColor:e.labelColor,fontSize:e.fontSize??12,background:e.background,borderColor:e.borderColor,radius:e.radius??6,padding:Dr(e.padding),href:e.href,utmMedium:e.utmMedium??"oac-link",utmCampaign:e.utmCampaign??"oac-chart"},e.image&&(this._img=e.image,this._ready=!0)}attached(e){if(this._host=e,!this._ready&&this._opts.src&&"undefined"!=typeof Image){const e=new Image;e.onload=()=>{this._img=e,this._ready=!0,this._host?.requestUpdate()},e.decoding="async",e.src=this._opts.src}}detached(){this._host=null}zOrder(){return this._opts.zOrder}autoscaleInfo(){return null}setOptions(e){const{padding:t,...i}=e;this._opts={...this._opts,...i},void 0!==t&&(this._opts.padding=Dr(t)),void 0!==e.height&&(this._autoHeight=!1),void 0===e.label&&void 0===e.fontSize||(this._labelW=0),this._tintCanvas=null,e.image?(this._img=e.image,this._ready=!0):void 0!==e.src&&(this._ready=!1,this._img=null,this.attached(this._host)),this._host?.requestUpdate()}_rect(e){if(!(this._builtin()||this._ready&&null!==this._img))return null;const t=this._img?.naturalWidth??this._img?.width??1,i=this._img?.naturalHeight??this._img?.height??1;if(!t||!i)return null;const r=this._opts,s=Math.max(0,r.margin,r.padding.x,r.padding.y),n=e.plotWidth-2*s,o=e.plotHeight-2*s;if(n<=0||o<=0)return null;const a=this._builtin()&&this._autoHeight&&e.plotWidth<480?24:r.height,l=Math.max(0,Math.min(a,o,n*i/t));if(!Number.isFinite(l)||l<=0)return null;const h=l*(t/i),c=Math.min(n,h+this._labelW*this._reveal);return{...Rr(r.position,s,c,l,e.plotWidth,e.plotHeight),logoW:h}}_builtin(){return void 0===this._opts.src&&void 0===this._opts.image}href(){const e=this._opts.href;if(void 0===e||e.includes("?"))return e;const t="undefined"!=typeof location?location:void 0,i=[`utm_medium=${encodeURIComponent(this._opts.utmMedium)}`,`utm_campaign=${encodeURIComponent(this._opts.utmCampaign)}`];return t?.host&&i.push(`utm_source=${t.host}${t.pathname}`),`${e}${e.includes("?")?"&":"?"}${i.join("&")}`}hitTest(e,t,i){if(void 0===this._opts.label&&void 0===this._opts.href)return null;const r=this._rect(i);if(null===r)return null;const s=Math.max(this._opts.padding.x,4,(44-r.w)/2),n=Math.max(this._opts.padding.y,4,(44-r.h)/2),o=Math.min(i.plotWidth,r.w+2*s),a=Math.min(i.plotHeight,r.h+2*n),l=Math.max(0,Math.min(i.plotWidth-o,r.x-s)),h=Math.max(0,Math.min(i.plotHeight-a,r.y-n));return e>=l&&e<=l+o&&t>=h&&t<=h+a?{externalId:this._opts.id,zOrder:this._opts.zOrder,distance:0,cursor:void 0!==this._opts.href?"pointer":"default"}:null}draw(e,t){if(!(this._builtin()||this._ready&&null!==this._img))return;const i=this._opts,r=t.dpr;void 0!==i.label&&0===this._labelW&&(e.save(),e.font=`600 ${i.fontSize*r}px system-ui, sans-serif`,this._labelW=e.measureText(i.label).width/r+8,e.restore()),this._advanceReveal(t);const s=this._rect(t);if(null===s)return;const n=Math.round(s.x*r),o=Math.round(s.y*r),a=Math.round(s.logoW*r),l=Math.round(s.h*r);e.save();const h=i.padding,c=Math.round((s.x-h.x)*r),d=Math.round((s.y-h.y)*r),u=Math.round((s.x+s.w+h.x)*r)-c,p=Math.round((s.y+s.h+h.y)*r)-d,_=t.theme,b=i.background??(_?R(_.background,.82):"none"),f=i.borderColor??_?.axisLine??"none";"none"!==b&&(e.beginPath(),q(e,c,d,u,p,Math.round(i.radius*r)),e.fillStyle=b,e.fill(),"none"!==f&&(e.strokeStyle=f,e.lineWidth=Math.max(1,Math.round(r)),e.stroke())),e.globalAlpha=Math.max(0,Math.min(1,i.opacity));const m=this._ink(t),g=void 0!==i.label?m:i.tint;if(this._builtin())e.fillStyle=m,function(e,t,i,r){e.save(),e.translate(t,i),e.scale(r/397,r/397),e.translate(-315.1,-217.65),e.beginPath(),e.moveTo(367.5,255.5),e.bezierCurveTo(371.3,251.3,374.8,247.3,378.7,242.8),e.bezierCurveTo(398.1,262.7,416.4,281.4,435.2,300.6),e.bezierCurveTo(461.6,273.7,487.4,247.4,513.6,220.6),e.bezierCurveTo(540.7,247.4,566.9,273.2,592.9,298.9),e.bezierCurveTo(611.4,280.3,629.8,262,648.4,243.3),e.bezierCurveTo(654.6,249.9,660.3,256.1,665.9,262.2),e.bezierCurveTo(648.3,280.2,630.3,298.7,612.5,316.9),e.bezierCurveTo(645.6,350.8,679,384.9,712.1,418.6),e.bezierCurveTo(684.7,446.7,656.7,475.5,628.4,504.5),e.bezierCurveTo(647.5,523.2,667.4,542.7,686.8,561.8),e.bezierCurveTo(680.8,568.3,675,574.7,668.8,581.5),e.bezierCurveTo(648.3,561.4,628.3,541.7,608.1,521.8),e.bezierCurveTo(577.2,551.9,546.6,581.7,516,611.7),e.bezierCurveTo(488.3,584.7,461,558,433.6,531.3),e.bezierCurveTo(415.9,548.5,398.2,565.6,380.1,583.1),e.bezierCurveTo(374.3,576.6,368.7,570.4,363.5,564.6),e.bezierCurveTo(379.4,548,396.1,530.5,412.9,512.9),e.bezierCurveTo(380.7,481.9,348,450.4,315.1,418.7),e.bezierCurveTo(349.2,385,383,351.6,416.6,318.3),e.bezierCurveTo(398.1,299.3,379.8,280.6,360.9,261.3),e.bezierCurveTo(362.8,259.7,365,257.7,367.5,255.5),e.moveTo(540.5,406),e.bezierCurveTo(552,417.1,563.4,428.1,575,439.2),e.bezierCurveTo(588.1,426.5,601.7,413.3,615.9,399.5),e.bezierCurveTo(621.9,406.1,627.8,412.6,633.8,419.2),e.bezierCurveTo(620.3,431.7,606.4,444.8,592.9,457.3),e.bezierCurveTo(600,464.3,606.9,471.2,613.8,478.1),e.bezierCurveTo(633.5,458.1,653.4,437.7,673.2,417.5),e.bezierCurveTo(620.7,365.5,567.7,313.2,514.8,260.8),e.bezierCurveTo(494.6,280.6,474.6,300.2,454.3,320),e.bezierCurveTo(461.7,327,468.8,333.8,477.5,342.1),e.bezierCurveTo(489.4,329.1,501.6,315.8,514.3,301.9),e.bezierCurveTo(521,308.7,526.7,314.6,531.9,319.9),e.bezierCurveTo(519.2,333.3,506.8,346.5,494.7,359.4),e.bezierCurveTo(509.5,374.4,524.7,390,540.5,406),e.moveTo(575.3,514.8),e.bezierCurveTo(581.4,508.6,587.6,502.3,593.4,496.4),e.bezierCurveTo(586.7,489.5,580.1,482.5,573.2,475.3),e.bezierCurveTo(557.6,490.1,542.3,504.7,526.9,519.3),e.bezierCurveTo(520.9,513.3,515.2,507.5,509.4,501.6),e.bezierCurveTo(524.7,487,540,472.3,555.6,457.4),e.bezierCurveTo(528.5,430.5,501.6,403.8,474.5,377),e.bezierCurveTo(461.3,389.6,448,402.3,434.6,415.2),e.bezierCurveTo(455,435.2,475.1,454.9,494.9,474.3),e.bezierCurveTo(482.1,487.6,469.4,500.8,456.5,514.1),e.bezierCurveTo(476.3,533.2,496.5,552.7,516.8,572.4),e.bezierCurveTo(536.3,553.1,555.6,534.2,575.3,514.8),e.moveTo(413.2,474.3),e.bezierCurveTo(420.1,481,427,487.7,434.6,495.1),e.bezierCurveTo(441.3,487.6,447.8,480.3,453.9,473.5),e.bezierCurveTo(435.5,454.7,416.3,435.1,397.1,415.5),e.bezierCurveTo(416.9,396.5,436.7,377.7,456.9,358.4),e.bezierCurveTo(449.8,351.8,442.7,345.3,435.6,338.7),e.bezierCurveTo(409,364.8,381.8,391.4,354.7,418),e.bezierCurveTo(374.3,436.9,393.4,455.4,413.2,474.3),e.closePath(),e.fill(),e.restore()}(e,n,o,l);else{const t=g?this._tinted(e,a,l,g):this._img;g&&t?e.drawImage(t,n,o):this._img&&e.drawImage(this._img,n,o,a,l)}if(void 0!==i.label&&this._reveal>.001){const t=(s.w-s.logoW)*r;e.beginPath(),e.rect(n+a,o,t,l),e.clip(),e.globalAlpha=this._reveal,e.font=`600 ${Math.round(i.fontSize*r)}px system-ui, -apple-system, sans-serif`,e.textBaseline="middle",e.textAlign="left",e.fillStyle=m,e.fillText(i.label,Math.round(n+a+6*r),Math.round(o+l/2))}e.restore()}_ink(e){const t=this._opts,i=e.theme;return t.labelColor??t.tint??i?.axisText??"#9aa3b2"}_advanceReveal(e){if(void 0===this._opts.label)return;const t=e.hoverId===this._opts.id?1:0,i=this._now(),r=null===this._lastFrameMs?0:Math.max(0,(i-this._lastFrameMs)/1e3);this._lastFrameMs=i;const s=this._opts.revealSeconds;if(s<=0)this._reveal=t;else if(this._reveal!==t){const e=r/s;this._reveal+=Math.sign(t-this._reveal)*Math.min(e,Math.abs(t-this._reveal))}Math.abs(t-this._reveal)>.001?this._host?.requestUpdate():this._reveal=t}_tinted(e,t,i,r){const s=`${t}x${i}:${r}`;if(this._tintCanvas&&this._tintKey===s)return this._tintCanvas;const n=e.canvas,o=n?.ownerDocument;let a=null;if(o&&"function"==typeof o.createElement&&(a=o.createElement("canvas")),!a)return null;a.width=t,a.height=i;const l=a.getContext("2d");return l&&null!==this._img?(l.clearRect(0,0,t,i),l.drawImage(this._img,0,0,t,i),l.globalCompositeOperation="source-in",l.fillStyle=r,l.fillRect(0,0,t,i),this._tintCanvas=a,this._tintKey=s,a):null}}const Wr='600 {size}px system-ui, -apple-system, "Segoe UI", sans-serif';class qr{constructor(e){Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._opts={text:e.text,fontSize:e.fontSize??64,opacity:e.opacity??.08,zOrder:e.zOrder??"bottom",id:e.id??"text-watermark",color:e.color,font:e.font}}zOrder(){return this._opts.zOrder}attached(e){this._host=e}detached(){this._host=null}autoscaleInfo(){return null}hitTest(){return null}setOptions(e){this._opts={...this._opts,...e},this._host?.requestUpdate()}draw(e,t){const i=this._opts;if(""===i.text)return;const r=t.dpr,s=t.plotWidth*r,n=t.plotHeight*r;if(s<=0||n<=0)return;e.save(),e.beginPath(),e.rect(0,0,s,n),e.clip(),e.globalAlpha=i.opacity,e.fillStyle=i.color??"#9aa4b2",e.textAlign="center",e.textBaseline="middle";const o=Math.min(i.fontSize*r,.8*n),a=(i.font??Wr).replace("{size}",String(Math.round(o)));e.font=a;const l=e.measureText(i.text).width,h=.8*s;if(l>h&&l>0){const t=Math.max(.1,o*(h/l));e.font=(i.font??Wr).replace("{size}",String(t))}e.fillText(i.text,s/2,n/2),e.restore()}}const Hr=["#f5a623","#26a69a","#ab47bc","#ef5350","#26c6da","#8bc34a","#ff7043","#5c6bc0"];function Vr(e){if(!Te(e))throw new Error(`openalgo-charts: unknown IANA time zone "${e}"`);return e}function Gr(e){const t=Math.abs(e);return t>=1e9?(e/1e9).toFixed(2)+"B":t>=1e6?(e/1e6).toFixed(2)+"M":t>=1e3?(e/1e3).toFixed(2)+"K":String(Math.round(e))}function Ur(e){const t=e.pointerType;return{modifiers:{shift:!0===e.shiftKey,alt:!0===e.altKey,ctrl:!0===e.ctrlKey,meta:!0===e.metaKey},pointerType:"touch"===t||"pen"===t?t:"mouse",pressure:Yr(e)}}function Yr(e){const t=e.pressure;return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):0!==(e.buttons??0)?.5:0}const Kr=["linear","logarithmic","percentage","indexed-to-100"];function Xr(){return"undefined"!=typeof window&&window.devicePixelRatio?window.devicePixelRatio:1}class Jr{constructor(e,t={}){Object.defineProperty(this,"_container",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_doc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pixelRatio",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_theme",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_panes",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_loop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_raf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_remeasureHandle",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dataLayer",{enumerable:!0,configurable:!0,writable:!0,value:new P}),Object.defineProperty(this,"_timeScale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_priceAxisWidth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timeAxisHeight",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pending",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_resizeObserver",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_width",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_height",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_hasFitContent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_crosshairMode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_crosshairSnapToBar",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_shortcuts",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_trading",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pointerInside",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_keyTarget",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_conflate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_conflationFactor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_backendFactory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_rendererKind",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_requestedRenderer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_gridVert",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_gridHorz",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_canvas",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_statusLine",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_legendIconSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_axisChrome",{enumerable:!0,configurable:!0,writable:!0,value:{sessionClock:!1,barCountdown:!1}}),Object.defineProperty(this,"_sessionClockForm",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_wallClock",{enumerable:!0,configurable:!0,writable:!0,value:()=>Date.now()/1e3}),Object.defineProperty(this,"_tradingSettings",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_events",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_eventMarkers",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_eventPane",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_eventVisible",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_cursorPane",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_cursor",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dragging",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_navigation",{enumerable:!0,configurable:!0,writable:!0,value:{mousePan:"both",defaultVisibleBars:0}}),Object.defineProperty(this,"_dragStartX",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_dragStartY",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastDragY",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_endedPointers",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_pointers",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_pinch",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pinchPane",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_liveRegion",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dragStartOffset",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastDragX",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastDragT",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_dragVelocity",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_kineticHandle",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_kineticEpoch",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_zoomHandle",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_zoomGlide",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_zoomGlideStart",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_zoomGlideApplied",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_animZoom",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_animAutoscale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_autoscaleTime",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_autoscaleFrames",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_navigationEpoch",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_zoomAnchor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_doubleClick",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_firstDataId",{enumerable:!0,configurable:!0,writable:!0,value:{value:null}}),Object.defineProperty(this,"_primary",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_seriesRecords",{enumerable:!0,configurable:!0,writable:!0,value:new WeakMap}),Object.defineProperty(this,"_indicators",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_dataContext",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_barsProvider",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_recomputing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_indicatorsDirty",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_barColorOwner",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_barColors",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_barColorBase",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_barColorAnchor",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_drawingState",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_alertState",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_maximizedPane",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_legends",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_firstPaneIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_historyLoader",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_loadingHistory",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_clickCb",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_crosshairCb",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_readoutTime",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pointerMoved",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_placementMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_legendOffset",{enumerable:!0,configurable:!0,writable:!0,value:{top:6,left:8}}),Object.defineProperty(this,"_downPane",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_downX",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_downLocalY",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_downPressure",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_dragId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dragCancelOnEscape",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_hoverId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_hoverOnBase",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_overlayFrozen",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_dragCb",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dragEndCb",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_axisDrag",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_axisDragScale",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dragMoved",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_dragFrom",{enumerable:!0,configurable:!0,writable:!0,value:{time:0,price:0}}),Object.defineProperty(this,"_paneResize",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_axisStartCoord",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_axisStartMin",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_axisStartMax",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_axisStartSpacing",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_priceFormatter",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_priceScaleOptions",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pricePanes",{enumerable:!0,configurable:!0,writable:!0,value:new WeakSet}),Object.defineProperty(this,"_timeFormatter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timezone",{enumerable:!0,configurable:!0,writable:!0,value:Se}),Object.defineProperty(this,"_leftAxisWidth",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_rightAxisWidth",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_timeNav",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_timeNavPane",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"_branding",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_brandingOptions",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_brandingPress",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_watermark",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_watermarkOptions",{enumerable:!0,configurable:!0,writable:!0,value:{visible:!1,text:"",color:"#9aa4b2",opacity:.08,fontSize:64}}),Object.defineProperty(this,"_listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_anchored",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_onPointerEnter",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this._pointerInside=!0}}),Object.defineProperty(this,"_onContextMenu",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(e.defaultPrevented)return;const t=this._localPoint(e),i=this._panes[t.pane];if(void 0===i)return;const r=this._listeners.get("contextmenu");if(void 0!==r&&r.size>0)this.emit("contextmenu",this._contextMenuEvent(e,t));else{this._cursor=null,this._cursorPane=null;try{const e=i.top.ctx;e.save(),e.globalCompositeOperation="destination-over",e.drawImage(i.base.element,0,0),e.restore(),this._overlayFrozen=!0}catch{}}}}),Object.defineProperty(this,"_onPointerDown",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(this._unfreezeOverlay(),("mouse"===e.pointerType||"pen"===e.pointerType)&&0!==e.button)return;this._endedPointers.delete(e.pointerId),this._stopKinetic(),this._stopZoomGlide();const t=this._localPoint(e);this._pointers.set(e.pointerId,{x:t.x,y:t.y,pane:t.pane});try{this._container.setPointerCapture?.(e.pointerId)}catch{}if(this._pointers.size>=2)return void this._beginPinch();this._downPane=t.pane,this._downX=t.x,this._downLocalY=t.localY,this._downPressure=Yr(e);const r=this._dividerAt(t.y);if(null!==r){const e=this._paneLayout();return this._paneResize={index:r,startY:t.y,aWeight:this._panes[r].weight,bWeight:this._panes[r+1].weight,aHeight:e[r].height,bHeight:e[r+1].height},void(this._dragging=!1)}const s=Math.max(0,this._width-this._rightAxisWidth),n=this._leftAxisWidth>0&&t.x<this._leftAxisWidth,o=t.x>=s||n,a=t.pane===this._bottomPaneIndex()&&t.localY>=t.paneHeight-this._timeAxisHeight;if(o){this._axisDrag="price",this._axisDragScale=n?this._panes[t.pane].scaleFor("left"):this._panes[t.pane].priceScale,this._axisStartCoord=t.localY;const e=this._axisDragScale.priceRange();return this._axisStartMin=e.min,this._axisStartMax=e.max,void(this._dragging=!1)}if(a)return this._axisDrag="time",this._axisStartCoord=t.x,this._axisStartSpacing=this._timeScale.barSpacing,void(this._dragging=!1);if(null!==this._branding&&this._brandingHit(t.pane,t.x,t.localY))return this._brandingPress={pointerId:e.pointerId,mark:this._branding,moved:!1},this._dragging=!1,void(this._pointerMoved=!1);if(this._placementMode)return this._dragging=!1,void(this._pointerMoved=!1);const l=this._panes[t.pane]?.hitTestPrimitives(t.x-this._leftAxisWidth,t.localY,this._renderContext(t.pane===this._bottomPaneIndex()));if(l&&(!0===l.draggable||"ns-resize"===l.cursor&&null!==this._dragCb)){this._dragId=l.externalId,this._dragCancelOnEscape=!0===l.cancelOnEscape,this._dragMoved=!1,this._ensureScaled(t.pane),this._dragFrom={time:this._xToTime(t.x),price:this._panes[t.pane].yToPrice(t.localY)},this._setHover(l),this._cursor=null,this._cursorPane=null,this._readoutTime=null,this.invalidate(e=>e.invalidateGlobal(i.Cursor)),this._dragging=!1,this._pointerMoved=!1;const r={id:l.externalId,...this._dragFrom,paneIndex:this._downPane,point:{x:t.x,y:t.localY},...Ur(e)};return void this.emit("drag:start",r)}this._dragging=!0,this._setHover(l??null),this._pointerMoved=!1,this._dragStartX=t.x,this._dragStartY=t.y,this._lastDragY=t.y,this._dragStartOffset=this._timeScale.rightOffset,this._lastDragX=t.x,this._lastDragT=this._now(),this._dragVelocity=0}}),Object.defineProperty(this,"_onPointerMove",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(this._unfreezeOverlay(),this._pointers.size>0&&!this._pointers.has(e.pointerId))return;if(("mouse"===e.pointerType||"pen"===e.pointerType)&&!(1&e.buttons)&&(this._dragging||null!==this._dragId||null!==this._axisDrag||null!==this._brandingPress))return null!==this._brandingPress&&(this._brandingPress.moved=!0),this._onPointerUp(e),void this._endedPointers.add(e.pointerId);const t=this._localPoint(e);if(this._pointers.has(e.pointerId)&&this._pointers.set(e.pointerId,{x:t.x,y:t.y,pane:t.pane}),null===this._pinch)if(null===this._brandingPress){if("price"===this._axisDrag){const e=t.localY-this._axisStartCoord,r=Math.exp(.005*e),s=(this._axisStartMin+this._axisStartMax)/2,n=(this._axisStartMax-this._axisStartMin)/2*r,o=this._axisDragScale??this._panes[this._downPane].priceScale;return o.setPriceRange({min:s-n,max:s+n}),o.setAutoScale(!1),void this.invalidate(e=>e.invalidatePane(this._downPane,{level:i.Light,autoScale:!1}))}if(null!==this._paneResize){const e=this._paneResize,r=e.aHeight+e.bHeight,s=e.aWeight+e.bWeight,n=Math.min(24,r/4),o=Math.max(n,Math.min(r-n,e.aHeight+(t.y-e.startY)));return this._panes[e.index].weight=o/r*s,this._panes[e.index+1].weight=s-this._panes[e.index].weight,this._relayout(),void this.invalidate(e=>e.invalidateGlobal(i.Full))}if("time"===this._axisDrag){this._beginAutoscaleMotion();const e=t.x-this._axisStartCoord;return this._timeScale.setBarSpacing(this._axisStartSpacing*Math.exp(.005*-e)),this.invalidate(e=>e.invalidateGlobal(i.Full)),void this._emitViewport("zoom")}if(this._placementMode&&this._pointers.size>0&&(Math.abs(t.x-this._downX)>3||Math.abs(t.localY-this._downLocalY)>3)&&(this._pointerMoved=!0),null!==this._dragId){const i=t.y-(this._paneLayout()[this._downPane]?.top??0);(Math.abs(t.x-this._downX)>3||Math.abs(i-this._downLocalY)>3)&&(this._dragMoved=!0);const r=this._panes[this._downPane].yToPrice(i),s=this._xToTime(t.x);this._dragCb?.(this._dragId,r,s);const n={id:this._dragId,price:r,time:s,paneIndex:this._downPane,fromPrice:this._dragFrom.price,fromTime:this._dragFrom.time,point:{x:t.x,y:i},samples:this._dragSamples(e),...Ur(e)};return void this.emit("drag",n)}if(this._dragging){this._beginAutoscaleMotion();const r=t.x-this._dragStartX;(Math.abs(r)>3||Math.abs(t.y-this._dragStartY)>3)&&(this._pointerMoved=!0),this._pointerMoved&&null!==this._hoverId&&this._setHover(null),this._timeScale.setRightOffset(this._dragStartOffset-r/this._timeScale.barSpacing),"touch"!==e.pointerType&&"both"!==this._navigation.mousePan||this._panes[this._downPane]?.priceScale.panByPixels(t.y-this._lastDragY),this._lastDragY=t.y;const s=this._now(),n=s-this._lastDragT;if(n>0){const e=(t.x-this._lastDragX)/n,i=Math.exp(-n/50);this._dragVelocity=this._dragVelocity*i+e*(1-i)}return this._lastDragX=t.x,this._lastDragT=s,this._maybeLoadHistory(),this.invalidate(e=>e.invalidateGlobal(i.Full)),void this._emitViewport("pan")}this._updateCursor(t.pane,t.x,t.localY,t.y,e)}else(Math.abs(t.x-this._downX)>3||Math.abs(t.localY-this._downLocalY)>3||t.pane!==this._downPane||"mouse"===e.pointerType&&!(1&e.buttons))&&(this._brandingPress.moved=!0);else this._updatePinch()}}),Object.defineProperty(this,"_onPointerUp",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(this._pointers.size>0&&!this._pointers.has(e.pointerId))return;try{this._container.releasePointerCapture?.(e.pointerId)}catch{}if(this._endedPointers.has(e.pointerId))return void this._endedPointers.delete(e.pointerId);if(this._pointers.delete(e.pointerId),this._brandingPress?.pointerId===e.pointerId){const t=this._brandingPress;this._brandingPress=null;const i=this._localPoint(e);if(!t.moved&&t.mark===this._branding&&i.pane===this._downPane&&Math.abs(i.x-this._downX)<=3&&Math.abs(i.localY-this._downLocalY)<=3&&this._brandingHit(i.pane,i.x,i.localY)){const e=t.mark.href();e&&/^https?:\/\//i.test(e)&&this._doc.defaultView?.open(e,"_blank","noopener,noreferrer")}return void this._endedPointers.add(e.pointerId)}if(null!==this._pinch)return void(0===this._pointers.size&&(this._pinch=null,this._dragging=!1));if(null!==this._paneResize)return this._paneResize=null,void this.emit("paneResized",{paneIndex:this._downPane});if(null!==this._axisDrag)return this._axisDrag=null,void(this._axisDragScale=null);if(null!==this._dragId){const t=this._localPoint(e),r=t.y-(this._paneLayout()[this._downPane]?.top??0),s=this._panes[this._downPane].yToPrice(r),n=this._xToTime(t.x);this._dragEndCb?.(this._dragId,s,n);const o={id:this._dragId,price:s,time:n,paneIndex:this._downPane,point:{x:t.x,y:r},...Ur(e)};if(this.emit("drag:end",o),!this._dragMoved){const t=this._dragId;this._clickCb?.(t);const i={id:t,price:s,time:n,paneIndex:this._downPane,point:{x:this._downX,y:this._downLocalY},...this._clickInfo(e)};this.emit("click",i)}this._dragId=null;const a="touch"===e.pointerType?null:this._panes[t.pane]?.hitTestPrimitives(t.x-this._leftAxisWidth,t.localY,this._renderContext(t.pane===this._bottomPaneIndex()))??null;return this._setHover(a),void this.invalidate(e=>e.invalidateGlobal(i.Light))}const t=this._dragging;if(this._dragging=!1,this._placementMode&&this._pointerMoved){t&&this._setHover(null);const i=this._localPoint(e);this._ensureScaled(this._downPane);const r=this._clickInfo(e),s={id:null,price:this._panes[this._downPane]?.yToPrice(this._downLocalY)??null,time:this._xToTime(this._downX),paneIndex:this._downPane,point:{x:this._downX,y:this._downLocalY},...r};this.emit("click",s);const n={id:null,price:this._panes[this._downPane]?.yToPrice(i.localY)??null,time:this._xToTime(i.x),paneIndex:this._downPane,point:{x:i.x,y:i.localY},viaDrag:!0,...r};return void this.emit("click",n)}if(!this._pointerMoved){const i=this._downPane===this._bottomPaneIndex(),r=this._panes[this._downPane]?.hitTestPrimitives(this._downX-this._leftAxisWidth,this._downLocalY,this._renderContext(i));if(t&&this._setHover("touch"===e.pointerType?null:r??null),r&&this._handleLegendAction(r.externalId))return;r&&this._clickCb?.(r.externalId),this._ensureScaled(this._downPane);const s={id:r?.externalId??null,price:this._panes[this._downPane]?.yToPrice(this._downLocalY)??null,time:this._xToTime(this._downX),paneIndex:this._downPane,point:{x:this._downX,y:this._downLocalY},...this._clickInfo(e)};return void this.emit("click",s)}t&&this._setHover(null),"touch"===e.pointerType&&"pointercancel"!==e.type&&Ii.shouldAnimate(this._dragVelocity)&&this._startKinetic(this._dragVelocity)}}),Object.defineProperty(this,"_onPointerUpNative",{enumerable:!0,configurable:!0,writable:!0,value:e=>{("mouse"!==e.pointerType&&"pen"!==e.pointerType||0===e.button)&&this._onPointerUp(e)}}),Object.defineProperty(this,"_onPointerCancel",{enumerable:!0,configurable:!0,writable:!0,value:e=>{this._cancelPrimitiveDrag("pointercancel"),this._dragging&&(this._pointerMoved=!0),this._brandingPress?.pointerId===e.pointerId&&(this._brandingPress.moved=!0),this._onPointerUp(e)}}),Object.defineProperty(this,"_onLostPointerCapture",{enumerable:!0,configurable:!0,writable:!0,value:e=>{this._dragging&&this._pointers.has(e.pointerId)&&(this._dragging=!1,this._pointerMoved=!0,this._pointers.delete(e.pointerId),this._endedPointers.add(e.pointerId),this._setHover(null))}}),Object.defineProperty(this,"_onPointerLeave",{enumerable:!0,configurable:!0,writable:!0,value:()=>{if(this._pointerInside=!1,this._feedTimeNav(null),null===this._dragId&&this._setHover(null),null!==this._cursor){this._cursor=null,this._cursorPane=null,this.invalidate(e=>e.invalidateGlobal(i.Cursor));for(const e of this._indicators)e.updateLegendValues();const e={time:null,index:null,price:null,bar:null,point:null,paneIndex:null};this._crosshairCb?.(e),this.emit("crosshair:move",e)}}}),Object.defineProperty(this,"_onWheel",{enumerable:!0,configurable:!0,writable:!0,value:e=>{const t=function(e,t,i){const r=e.deltaMode,s=e.deltaX??0,n=e.deltaY??0;return{x:Number.isFinite(s)?s*(1===r?16:2===r?t:1):0,y:Number.isFinite(n)?n*(1===r?16:2===r?i:1):0}}(e,this._width,this._height);if(0===t.x&&0===t.y)return;this._unfreezeOverlay(),e.preventDefault(),this._stopKinetic();const r=this._localPoint(e),s=this._leftAxisWidth>0&&r.x<this._leftAxisWidth,n=this._rightAxisWidth>0&&r.x>=this._width-this._rightAxisWidth;if(s||n){if(0===t.y)return;this._stopZoomGlide();return this._panes[r.pane].scaleFor(this._axisScaleId(r.pane,s?"left":"right")).scaleAtY(r.localY,Math.exp(-Li(t.y))),void this.invalidate(e=>e.invalidateGlobal(i.Full))}if(!e.ctrlKey&&!e.metaKey&&(e.shiftKey||Math.abs(t.x)>Math.abs(t.y)))return this._stopZoomGlide(),this._beginAutoscaleMotion(),this._timeScale.scrollByPixels(-(e.shiftKey&&0===t.x?t.y:t.x)),this._maybeLoadHistory(),this.invalidate(e=>e.invalidateGlobal(i.Full)),void this._emitViewport("pan");if(0===t.y)return;const o="right"!==this._zoomAnchor||e.ctrlKey||e.metaKey?Math.max(0,Math.min(this._timeScale.width,r.x-this._leftAxisWidth)):this._timeScale.width,a=null===this._zoomGlide?0:this._zoomGlide.totalLogFactor-this._zoomGlideApplied,l=this._timeScale.barSpacing,h=this._timeScale.constrainBarSpacing(l*Math.exp(a+Li(t.y))),c=Math.log(h/l);if(this._stopZoomGlide(),0===c)return;if(!this._animZoom||!Ai.shouldAnimate(c))return void this._applyZoom(o,c);const d=c*Ai.leadFraction(),u=this._navigationEpoch;this._applyZoom(o,d),this._destroyed||u!==this._navigationEpoch||this._startZoomGlide(o,c-d)}}),Object.defineProperty(this,"_onDblClick",{enumerable:!0,configurable:!0,writable:!0,value:e=>{const t=this._localPoint(e);if(this._brandingHit(t.pane,t.x,t.localY))return;const i={paneIndex:t.pane,x:t.x,y:t.y,handled:!1};this.emit("dblclick",i),this._placementMode||i.handled||("reset"===this._doubleClick?this.resetScale():"maximize"===this._doubleClick&&this.maximizePane(t.pane))}}),Object.defineProperty(this,"_onKeyDown",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(this._unfreezeOverlay(),"Escape"===e.key&&this._dragCancelOnEscape&&null!==this._dragId&&!Xi.shouldIgnore(e.target)){this._cancelPrimitiveDrag("escape"),this._dragId=null,this._dragging=!1,this._pointerMoved=!0;for(const e of this._pointers.keys())this._endedPointers.add(e);return this._pointers.clear(),this._setHover(null),this.invalidate(e=>e.invalidateGlobal(i.Light)),void e.preventDefault()}const t=this._shortcuts;if(null===t||Xi.shouldIgnore(e.target)||!this._shortcutsActive())return;const r=t.resolve(e);if(null===r)return;let s=this._runShortcut(r);s||(s=t.runCustom(r)),s&&(e.preventDefault(),t.emitTrigger(r),this._maybeLoadHistory(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._updateAccessibleSummary())}}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._timeScale=new w(t.timeScale),this._container=e,this._doc=t.document??e.ownerDocument,this._pixelRatio=t.pixelRatio??Xr,this._theme=t.theme??$t,this._priceAxisWidth=t.priceAxisWidth??56,this._rightAxisWidth=this._priceAxisWidth,void 0!==t.legendOffset?.top&&(this._legendOffset.top=t.legendOffset.top),void 0!==t.legendOffset?.left&&(this._legendOffset.left=t.legendOffset.left),this._timeAxisHeight=t.timeAxisHeight??22,this._crosshairMode=t.crosshairMode??"normal",this._crosshairSnapToBar=!0===t.crosshairSnapToBar,Object.assign(this._axisChrome,t.axisChrome),"object"==typeof t.axisChrome?.sessionClock&&(this._sessionClockForm={...t.axisChrome.sessionClock}),void 0!==t.axisChrome?.clock&&(this._wallClock=t.axisChrome.clock);const r=t.shortcuts;this._shortcuts=!1===r?null:r instanceof Xi?r:new Xi(r??{}),this._now=t.now??(()=>"undefined"!=typeof performance?performance.now():0),this._animZoom=t.animZoom??!0,this._barsProvider=t.barsProvider??null,this._animAutoscale=t.animAutoscale??this._animZoom,this._zoomAnchor=t.zoomAnchor??"cursor",this._doubleClick=t.doubleClick??"reset",this._conflate=t.conflate??!1,this._conflationFactor=t.conflationFactor??1,this._backendFactory=t.renderBackend??It(t.renderer??"canvas2d"),this._requestedRenderer=void 0===t.renderBackend?t.renderer??"canvas2d":null,this._priceFormatter=t.priceFormatter??null,this._priceScaleOptions=t.priceScale??null,this._timeFormatter=t.timeFormatter,void 0!==t.timezone&&(this._timezone=Vr(t.timezone)),this._gridVert=t.grid?.vertLines??!0,this._gridHorz=t.grid?.horzLines??!0,Object.assign(this._canvas,t.canvas),t.grid&&(this._canvas.grid={...this._canvas.grid,...t.grid}),Object.assign(this._statusLine,t.statusLine),"number"==typeof t.legendIconSize&&Number.isFinite(t.legendIconSize)&&(this._legendIconSize=t.legendIconSize);const s=I(this._canvas.margins);void 0===s.marginTop&&void 0===s.marginBottom||(this._priceScaleOptions={...this._priceScaleOptions,...s}),this._patchNavigation(t.navigation??{});const o=t.timeNavigator??!0;!1!==o&&(this._timeNav=new Fr({...!0===o?{}:o,hints:this._navHints(!0===o?void 0:o)},this._now));const a="function"==typeof getComputedStyle?getComputedStyle(e).position:e.style.position;a&&"static"!==a||(e.style.position="relative"),e.style.display="flex",e.style.flexDirection="column",e.style.background=this._theme.background,e.style.touchAction="none",e.getAttribute("role")||e.setAttribute("role","application"),e.setAttribute("aria-label",t.ariaLabel??"Interactive financial chart"),e.hasAttribute("tabindex")||(e.tabIndex=0);const l=this._doc.createElement("div");l.setAttribute("aria-live","polite");const h=l.style;var c;h.position="absolute",h.width="1px",h.height="1px",h.overflow="hidden",h.clip="rect(0 0 0 0)",h.whiteSpace="nowrap",h.border="0",h.padding="0",h.margin="-1px",e.appendChild(l),this._liveRegion=l,this._raf=(c=t.raf)?{schedule:c.schedule,cancel:c.cancel??(()=>{})}:"function"==typeof requestAnimationFrame?{schedule:e=>requestAnimationFrame(e),cancel:e=>cancelAnimationFrame(e)}:{schedule:e=>setTimeout(e,16),cancel:e=>clearTimeout(e)},this._loop=new n(()=>this._onFrame(),this._raf.schedule,this._raf.cancel),this._addPane(),this.setBranding(t.branding??!0),this.setWatermarkOptions(t.watermark??!1),this._observeSize(),this._attachInput(),this._timeScale.setChangeHandler(()=>{this._stopNavigationMotion(),this.invalidate(e=>e.invalidateGlobal(i.Full))}),this.applySize(e.clientWidth,e.clientHeight),this._remeasureHandle=this._raf.schedule(()=>{this._remeasureHandle=null,this._remeasure()}),"function"==typeof queueMicrotask&&queueMicrotask(()=>this.emit("ready",{}))}setHistoryLoader(e){this._historyLoader=e}historyLoadComplete(){this._loadingHistory=!1}get dataLayer(){return this._dataLayer}primaryBars(){const e=this._firstDataId.value;return null===e?[]:this._dataLayer.seriesBars(e)}get timeScale(){return this._timeScale}setVisibleLogicalRange(e){this._stopNavigationMotion();const t=this._timeScale.visibleRange();this._timeScale.setVisibleLogicalRange(e),this._emitViewportIfMoved(t)}getVisibleLogicalRange(){return this._timeScale.visibleRange()}fitContent(){if(this._stopNavigationMotion(),this._dataLayer.length<=0)return;const e=this._timeScale.visibleRange();this._timeScale.fitContent(this._dataLayer.length),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._emitViewportIfMoved(e)}navigationOptions(){return{...this._navigation}}setNavigationOptions(e){const t=this._navigation.defaultVisibleBars;this._patchNavigation(e),t!==this._navigation.defaultVisibleBars&&this.resetScale()}_patchNavigation(e){"horizontal"!==e.mousePan&&"both"!==e.mousePan||(this._navigation.mousePan=e.mousePan);const t=e.defaultVisibleBars;"number"==typeof t&&Number.isFinite(t)&&t>=0&&(this._navigation.defaultVisibleBars=Math.min(1e5,Math.floor(t)))}_fitDefaultView(){const e=this._dataLayer.length;if(e<=0||!(this._timeScale.width>0))return!1;if(this._timeScale.fitContent(e),this._navigation.defaultVisibleBars>0){const t=Math.min(e,this._navigation.defaultVisibleBars);this._timeScale.setBarSpacing(this._timeScale.width/(t+this._timeScale.rightOffset))}return!0}get shortcuts(){return this._shortcuts}get trading(){return null===this._trading&&(this._trading=new nr(this),this._trading.setSettings(this._tradingSettings)),this._trading}hasTrading(){return null!==this._trading}tradingSettings(){if(null!==this._trading)return this._trading.getSettings();const e={...Zi};for(const[t,i]of Object.entries(this._tradingSettings))"string"==typeof i&&(e[t.slice(0,-5)]=i);return e}setTradingSettings(e){Object.assign(this._tradingSettings,e),this._trading?.setSettings(e)}addSeries(e,t={}){return this._createSeries(e,t,!0)}_createSeries(e,t,r){const s=this._dataLayer.createSeries(),n=t.paneIndex??0;this._ensurePane(n);const o=function(e,t,i,r="right"){return{dataId:e,type:t,style:{...se(t).defaultStyle,...i},scaleId:r}}(s,e,t.style,t.priceScaleId??"right");r&&se(e).isPriceSeries&&this._claimPricePane(this._panes[n]);const a=r&&null===this._firstDataId.value&&se(e).isPriceSeries;a&&(this._firstDataId.value=s,this._firstPaneIndex=n),this._panes[n].addSeries(o),this._recomputeAxisColumns();const l=this._panes[n],h=l.scaleOf(o);if(t.priceFormat){const e=t.priceFormat;if("custom"===e.type)h.setPriceFormatter(e.formatter);else if("volume"===e.type)h.setPriceFormatter(Gr);else if("percent"===e.type){const t=e.precision??2;h.setPriceFormatter(e=>`${e.toFixed(t)}%`)}else{const t=e.minMove??(void 0!==e.precision?Math.pow(10,-e.precision):void 0);void 0!==t&&h.setOptions({minMove:t})}}void 0!==o.style.precision&&this._applyPrecision(h,o.style.precision);const c={setData:e=>this._setData(s,e.map(Ti)),prependData:e=>this._prependData(s,e.map(Ti)),update:e=>this._updateBar(s,Ti(e)),getData:()=>this._dataLayer.indexedBars(s).map(e=>e.bar),applyOptions:e=>{Object.assign(o.style,e),"precision"in e&&this._applyPrecision(l.scaleOf(o),e.precision),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._primary?.record===o&&this.emit("objects:change",{})},remove:()=>{const e=this._primary?.record===o;l.removeSeries(o),this._dataLayer.removeSeries(s),this._firstDataId.value===s&&(this._firstDataId.value=null),this._primary?.record===o&&(this._primary=null),this._timeScale.setBaseIndex(this._dataLayer.baseIndex),this._recomputeAxisColumns(),this.invalidate(e=>e.invalidateGlobal(i.Full)),e&&(this.emit("data:update",{kind:"reset"}),this.emit("objects:change",{}))},priceScale:()=>l.scaleOf(o),createMarkers:e=>{const t=new _r(s,e,()=>l.scaleOf(o));return this._addPrimitive(this._panes.indexOf(l),t),t}};return a&&(this._primary={api:c,record:o},this.emit("objects:change",{})),this._seriesRecords.set(c,o),c}primarySeries(){return this._primary?.api??null}primarySeriesInfo(){const e=this._primary;return null===e?null:{type:e.record.type,style:e.record.style}}_applyPrecision(e,t){if(void 0===t||!isFinite(t))return void e.setPriceFormatter(this._priceFormatter);const i=h(Math.round(t),0,8);e.setPriceFormatter(e=>e.toFixed(i))}addPriceLine(e,t=0){const i=new Ji(e);return this._addPrimitive(t,i),i}addEventMarkers(e=0,t={}){const i=new mr(t);return this._addPrimitive(e,i),i}setEvents(e,t=0){const i=this._ensureEventMarkers();i.setEvents(e),this._events=i.events(),t!==this._eventPane&&(this.removePrimitive(i),this._addPrimitive(t,i)),this._eventPane=t,this._syncEvents()}eventMarkers(){return this._eventMarkers}setEventMarkerOptions(e){this._ensureEventMarkers().setOptions(e)}setEventGroups(e){this._ensureEventMarkers().setGroups(e),this.emit("events:change",void 0)}setEventGroupVisible(e,t){this._ensureEventMarkers().setGroupVisible(e,t),this.emit("events:change",void 0)}setEventOptions(e){Object.assign(this._eventVisible,e),this._syncEvents()}eventOptions(){return{...this._eventVisible}}_ensureEventMarkers(){return null===this._eventMarkers&&(this._eventMarkers=new mr,this._addPrimitive(this._eventPane,this._eventMarkers),this.on("click",e=>{const t=e;if(!t.id||t.viaDrag||t.paneIndex!==this._eventPane)return;const i=this._eventMarkers?.detailsForHit(t.id);i&&this.emit("event:click",{...i,point:{x:t.point.x,y:t.point.y+(this._paneLayout()[t.paneIndex]?.top??0)},paneIndex:t.paneIndex})})),this._eventMarkers}_syncEvents(){if(null===this._eventMarkers&&0===this._events.length)return;const e=this._eventVisible;this._ensureEventMarkers().setEvents(this._events.filter(t=>!1!==e[t.type])),this.emit("events:change",void 0)}addIndicator(e,t={},i={}){const r=ti(e),s=new bi(this._indicatorHost(),r,this._distinctColors(r,t),i.paneIndex,void 0,new Set(this._indicators.map(e=>e.id)));return this._indicators.push(s),this.emit("objects:change",{}),s}_distinctColors(e,t){const i=this._indicators.filter(t=>t.indicatorId===e.id).length;if(0===i)return t;const r={...t},s=e.plots;for(let e=0;e<s.length;e++){const t=Yt(s[e]).color;void 0===r[t]&&(r[t]=Hr[(i*s.length+e)%Hr.length])}return r}indicators(){return this._flushIndicators(),this._indicators}removeIndicator(e){const t=this._indicators.find(t=>t.id===e);return void 0!==t&&(t.remove(),!0)}_forgetIndicator(e){const t=this._indicators.findIndex(t=>t.id===e);if(t<0)return;const{indicatorId:i,paneIndex:r}=this._indicators[t];this._indicators.splice(t,1),this.emit("indicatorRemoved",{instanceId:e,indicatorId:i,paneIndex:r}),r>0&&0===this._panes[r]?.series().length&&this.removePane(r)}getDataContext(){return this._dataContext}get hasOpenInterest(){return this._dataContext?.hasOpenInterest}setDataContext(e){if(this._dataContext?.symbol===e?.symbol&&this._dataContext?.exchange===e?.exchange&&this._dataContext?.hasOpenInterest===e?.hasOpenInterest&&this._dataContext?.interval===e?.interval&&!!this._dataContext==!!e)return;const t=this._dataContext?.symbol!==e?.symbol||this._dataContext?.exchange!==e?.exchange;this._dataContext=e?Object.freeze({...e}):void 0,t&&this._events.length&&(this._events=[],this._syncEvents());for(const e of this._legends)e.legend.setOptions({hasOpenInterest:this.hasOpenInterest});this._syncWatermark(),this.emit("data:context",this._dataContext)}setBarsProvider(e){this._barsProvider=e}hasBarsProvider(){return null!==this._barsProvider}setBranding(e){null!==this._branding&&this.removePrimitive(this._branding),this._branding=null,this._brandingOptions=!1!==e&&{position:"bottom-left",margin:14,opacity:1,padding:8,label:"Chart by OpenAlgo",href:"https://openalgo.in",id:"chart-branding",...!0===e?{}:e},!1!==this._brandingOptions&&("object"==typeof this._brandingOptions.padding&&(this._brandingOptions.padding={...this._brandingOptions.padding}),this._branding=new Er(this._brandingOptions),this.addPrimitive(this._branding,{anchor:"chart-bottom"})),this.invalidate(e=>e.invalidateGlobal(i.Light)),this.emit("branding:changed",this.brandingOptions())}brandingOptions(){const e=this._brandingOptions;return!1!==e&&{...e,..."object"==typeof e.padding?{padding:{...e.padding}}:{}}}setWatermarkOptions(e){const t="boolean"==typeof e?{visible:e}:e;if(null===t||"object"!=typeof t)return;const i=this._watermarkOptions;"boolean"==typeof t.visible&&(i.visible=t.visible);for(const e of["text","color","font","id"])"string"==typeof t[e]&&(i[e]=t[e]);"number"==typeof t.opacity&&Number.isFinite(t.opacity)&&(i.opacity=Math.max(0,Math.min(1,t.opacity))),"number"==typeof t.fontSize&&Number.isFinite(t.fontSize)&&(i.fontSize=Math.max(10,Math.min(200,t.fontSize))),"bottom"!==t.zOrder&&"normal"!==t.zOrder&&"top"!==t.zOrder||(i.zOrder=t.zOrder),this._syncWatermark()}watermarkOptions(){return{...this._watermarkOptions}}_syncWatermark(){const e=this._watermarkOptions;if(!e.visible)return null!==this._watermark&&this.removePrimitive(this._watermark),void(this._watermark=null);const t=e.text?.trim()?e.text:[this._dataContext?.symbol,this._dataContext?.interval].filter(Boolean).join(" ");null===this._watermark?(this._watermark=new qr({...e,text:t}),this.addPrimitive(this._watermark,{anchor:"chart-top"})):this._watermark.setOptions({...e,text:t}),this.invalidate(e=>e.invalidateGlobal(i.Light))}_indicatorHost(){return{legendIndex:()=>this._readoutIndex(),indicatorRemoved:e=>this._forgetIndicator(e),flushIndicators:()=>this._flushIndicators(),formatPrice:(e,t)=>this._panes[e]?.priceScale.format(t),addIndicatorLegend:e=>{const t=0===e.row&&e.paneIndex>0?["hide","settings","up","down","maximize","close"]:["hide","settings","close"];!0===e.hasSource&&t.splice(t.indexOf("settings")+1,0,"source");const i=new Mr({...e,actions:t});return this._addPrimitive(e.paneIndex,i),i},removeIndicatorLegend:e=>{this.removePrimitive(e),this._restackLegends()},legendRowsOn:e=>this._legends.filter(t=>t.paneIndex===e).length,primarySeries:()=>this.primarySeries(),addIndicatorSeries:(e,t,i,r,s)=>this._createSeries(e,{paneIndex:t,style:i,priceScaleId:r,priceFormat:s},!1),addIndicatorLevel:(e,t)=>{const i={price:e.price,color:e.color,lineWidth:e.lineWidth,dashed:e.dashed,lineStyle:e.lineStyle,leftLabel:e.label,id:e.id};return this.addPriceLine(i,t)},removeIndicatorLevel:e=>this.removePrimitive(e),addIndicatorFill:(e,t)=>this._addPrimitive(t,e),removeIndicatorFill:e=>this.removePrimitive(e),removeIndicatorMarkers:e=>this.removePrimitive(e),addIndicatorPrimitive:(e,t)=>this._addPrimitive(t,e),removeIndicatorPrimitive:e=>this.removePrimitive(e),addIndicatorTable:e=>{const t=new Ar;return this._addPrimitive(e,t),t},removeIndicatorTable:e=>this.removePrimitive(e),sourceBars:()=>null===this._firstDataId.value?[]:this._dataLayer.seriesBars(this._firstDataId.value),nextPaneIndex:()=>this._panes.length,timezone:()=>this._timezone,now:()=>this._wallClock(),symbol:()=>this._dataContext?.symbol,interval:()=>this._dataContext?.interval,dataContext:()=>this._dataContext,requestBars:e=>{const t=this._barsProvider;return null===t?Promise.reject(new Error("openalgo-charts: this chart has no bars provider; call chart.setBarsProvider(...) to serve other instruments")):t(e)},subscribeDataChanges:e=>{const t=this.on("data:context",()=>e("context")),i=this.on("data:range",()=>e("range"));return()=>{t(),i()}},tickSize:e=>{const t=this._panes[e]??this._panes[0],i=t?.priceScale.options.minMove??0;return i>0?i:void 0},setBarColors:(e,t)=>this._setBarColors(e,t),emit:(e,t)=>this.emit(e,t),setPaneRange:(e,t)=>{const i=this._panes[e];void 0!==i&&(i.priceScale.setFixedRange(t),null===t&&i.priceScale.setAutoScale(!0))}}}_setBarColors(e,t){if(null===e){if(this._barColorOwner!==t)return;this._barColorOwner=null}else this._barColorOwner=t;this._barColors=e,this._applyBarColors()}_applyBarColors(){const e=this._firstDataId.value;if(null===e)return;const t=this._dataLayer.seriesBars(e),r=t.length,s=this._barColorBase;(r<s.length||s.length>0&&t[0].time!==this._barColorAnchor)&&(s.length=0),0===s.length&&(this._barColorAnchor=r>0?t[0].time:0);for(let e=s.length;e<r;e++)s[e]=t[e].color;const n=this._barColors,o=new Array(r);let a=!1;for(let e=0;e<r;e++){const i=t[e],r=n?.[e]??s[e];r!==i.color?(o[e]={...i,color:r},a=!0):o[e]=i}a&&(this._dataLayer.setSeriesData(e,o),this.invalidate(e=>e.invalidateGlobal(i.Light)))}_invalidateIndicators(){this.emit("data:range",{}),0!==this._indicators.length&&(this._indicatorsDirty=!0,this._loop.requestFrame())}_flushIndicators(){if(this._indicatorsDirty)if(this._recomputing||0===this._indicators.length)this._indicatorsDirty=!1;else{this._indicatorsDirty=!1,this._recomputing=!0;try{for(const e of this._indicators)e.recompute()}finally{this._recomputing=!1}}}subscribeClick(e){this._clickCb=e}subscribeCrosshairMove(e){this._crosshairCb=e}setLinkedCrosshairIndex(e){if(this.isDestroyed||null!==this._cursor)return;const t=null===e?null:this._dataLayer.indexToTime(e)??null;if(t===this._readoutTime)return;this._readoutTime=t;for(const t of this._indicators)t.updateLegendValues(e??void 0);const i=null===e||null===this._firstDataId.value?null:this._dataLayer.visibleBars(this._firstDataId.value,e,e)[0]?.bar??null;this._crosshairCb?.({source:"linked",time:t,index:e,bar:i,price:null,point:null,paneIndex:null})}_readoutIndex(){return null===this._readoutTime?void 0:this._dataLayer.timeToIndex(this._readoutTime)}subscribeDrag(e,t){this._dragCb=e,this._dragEndCb=t??null}_ensureScaled(e){const t=this._panes[e];void 0===t||t.readoutScale().scaled||t.autoscale(this._renderContext(e===this._bottomPaneIndex()))}_xToTime(e){return this._dataLayer.indexToTimeFloat(this._timeScale.xToIndex(e-this._leftAxisWidth))}timeToCoordinate(e){return this._timeScale.indexToX(this._dataLayer.timeToIndexFloat(e))+this._leftAxisWidth}coordinateToTime(e){return this._xToTime(e)}on(e,t){let i=this._listeners.get(e);return void 0===i&&(i=new Set,this._listeners.set(e,i)),i.add(t),()=>this.off(e,t)}once(e,t){const i=r=>{this.off(e,i),t(r)};return this.on(e,i)}off(e,t){void 0!==t?this._listeners.get(e)?.delete(t):this._listeners.delete(e)}emit(e,t){const i=this._listeners.get(e);if(void 0!==i)for(const e of[...i])try{e(t)}catch{}}_emitViewport(e){if(void 0===this._listeners.get(e))return;const t=this._timeScale.visibleRange();this.emit(e,{from:this._dataLayer.indexToTime(Math.round(t.from))??null,to:this._dataLayer.indexToTime(Math.round(t.to))??null,logicalFrom:t.from,logicalTo:t.to})}_emitViewportIfMoved(e){const t=this._timeScale.visibleRange();if(t.from===e.from&&t.to===e.to)return;const i=Math.abs(t.to-t.from-(e.to-e.from))>1e-9;this._emitViewport(i?"zoom":"pan")}addPrimitive(e,t=0){"number"!=typeof t?(this._anchored.push({primitive:e,anchor:t.anchor}),this._addPrimitive(this._anchorTarget(t.anchor),e)):this._addPrimitive(t,e)}_anchorTarget(e){return"chart-bottom"===e?this._bottomPaneIndex():this._topPaneIndex()}_rehomeAnchored(){if(0!==this._anchored.length)for(const e of this._anchored){const t=this._anchorTarget(e.anchor),i=this._panes.findIndex(t=>t.hasPrimitive(e.primitive));if(i===t)continue;i>=0&&this._panes[i].removePrimitive(e.primitive);const r=this._legends.findIndex(t=>t.legend===e.primitive);r>=0&&this._legends.splice(r,1),this._addPrimitive(t,e.primitive)}}priceToCoordinate(e,t=0){this._ensureScaled(t);const i=this._panes[t];if(void 0===i)return null;return(this._paneLayout()[t]?.top??0)+i.priceToY(e)}coordinateToPrice(e,t=0){this._ensureScaled(t);const i=this._panes[t];if(void 0===i)return null;const r=this._paneLayout()[t]?.top??0;return i.yToPrice(e-r)}setGridOptions(e){void 0!==e.vertLines&&(this._gridVert=e.vertLines),void 0!==e.horzLines&&(this._gridHorz=e.horzLines),this._canvas.grid={...this._canvas.grid,...e},this.invalidate(e=>e.invalidateGlobal(i.Full))}gridOptions(){return{...this._canvas.grid,vertLines:this._gridVert,horzLines:this._gridHorz}}setCanvasOptions(e){e.grid&&this.setGridOptions(e.grid),e.crosshair&&(this._canvas.crosshair={...this._canvas.crosshair,...e.crosshair}),e.scales&&(this._canvas.scales={...this._canvas.scales,...e.scales}),e.margins&&(this._canvas.margins={...this._canvas.margins,...e.margins},this.setPriceScaleOptions(I(this._canvas.margins),"axes")),this.invalidate(e=>e.invalidateGlobal(i.Full))}canvasOptions(){return{...this._canvas}}setPriceScaleOptions(e,t="primary"){this._priceScaleOptions={...this._priceScaleOptions,...e};for(const i of this._panes){const r="all"===t?i.scales():"axes"===t?i.axisScales():[i.priceScale],s=this._scalePatchFor(i,e);for(const e of r)e.setOptions(s)}this.invalidate(e=>e.invalidateGlobal(i.Full))}_scalePatchFor(e,t){if(void 0===t.minMove||this._pricePanes.has(e))return t;const i={...t};return delete i.minMove,i.minPrecision=2,i}_claimPricePane(e){if(this._pricePanes.has(e))return;this._pricePanes.add(e);const t=this._priceScaleOptions?.minMove;for(const i of e.axisScales())i.setOptions(void 0!==t?{minMove:t,minPrecision:0}:{minPrecision:0})}priceScaleOptions(){return{...this._panes[0].priceScale.options}}setAutoScale(e){for(const t of this._panes)e&&t.setRatioLock("right",!1,0,0),t.priceScale.setAutoScale(e);this.invalidate(e=>e.invalidateGlobal(i.Full))}priceAxisState(e=0,t="right"){const i=this._panes[e];if(void 0===i)return null;const r=i.scaleFor(t),s="left"===t?"left":"right",n="left"===s?"right":"left";return{paneIndex:e,scaleId:t,side:s,active:i.usesScale(t),autoFit:r.autoScale,inverted:r.options.inverted,mode:r.options.mode,scaled:r.scaled,lockRatio:i.ratioLocked(t),movable:("right"===t||"left"===t)&&i.usesScale(t)&&!i.usesScale(n)}}setPriceAxisOptions(e,t,r){const s=this._panes[e];void 0!==s&&(s.scaleFor(t).setOptions(r),this.invalidate(e=>e.invalidateGlobal(i.Full)))}setPriceAxisAutoFit(e,t,r){const s=this._panes[e];void 0!==s&&(r&&s.setRatioLock(t,!1,0,0),s.scaleFor(t).setAutoScale(r),this.invalidate(e=>e.invalidateGlobal(i.Full)))}setPriceAxisLockRatio(e,t,r){const s=this._panes[e];if(void 0===s)return!1;r&&this._ensureScaledFor(e,t);const n=s.setRatioLock(t,r,this._timeScale.barSpacing,s.scaleFor(t).height);return this.invalidate(e=>e.invalidateGlobal(i.Full)),n}movePriceAxis(e,t,r){const s=this._panes[e];if(void 0===s||!s.moveSeriesScale(t,r))return!1;const n=s.scaleFor(t);return this._priceScaleOptions&&n.setOptions(this._scalePatchFor(s,this._priceScaleOptions)),n.setPriceFormatter(this._priceFormatter),this._recomputeAxisColumns(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this.emit("priceAxisMoved",{paneIndex:e,from:t,to:r}),!0}_ensureScaledFor(e,t){const i=this._panes[e];void 0===i||i.scaleFor(t).scaled||i.autoscale(this._renderContext(e===this._bottomPaneIndex()))}setStatusLineOptions(e){Object.assign(this._statusLine,e);for(const e of this._legends)e.legend.setOptions({statusLine:this._statusLine});this.invalidate(e=>e.invalidateGlobal(i.Full))}statusLineOptions(){return{...this._statusLine}}setLegendIconSize(e){if(Number.isFinite(e)){this._legendIconSize=e;for(const t of this._legends)t.legend.setOptions({iconSize:e});this.invalidate(e=>e.invalidateGlobal(i.Full))}}legendIconSize(){return this._legendIconSize}setAxisChromeOptions(e){void 0!==e.sessionClock&&("object"==typeof e.sessionClock&&(this._sessionClockForm={...e.sessionClock}),this._axisChrome.sessionClock=!0===e.sessionClock?this._sessionClockForm??!0:e.sessionClock),void 0!==e.barCountdown&&(this._axisChrome.barCountdown=e.barCountdown),void 0!==e.clock&&(this._axisChrome.clock=e.clock,this._wallClock=e.clock),this.invalidate(e=>e.invalidateGlobal(i.Full))}axisChromeOptions(){return{...this._axisChrome}}crosshairMode(){return this._crosshairMode}crosshairSnapToBar(){return this._crosshairSnapToBar}theme(){return this._theme}takeScreenshot(){const e=this._pixelRatio(),t=this._doc.createElement("canvas");t.width=Math.max(1,Math.round(this._width*e)),t.height=Math.max(1,Math.round(this._height*e));const i=t.getContext("2d");if(null===i)return t;i.fillStyle=this._theme.background,i.fillRect(0,0,t.width,t.height);const r=this._paneLayout();for(let t=0;t<this._panes.length;t++){if(this._layoutWeight(t)<=0)continue;const s=Math.round((r[t]?.top??0)*e);for(const e of[this._panes[t].base,this._panes[t].top])e.element.width>0&&e.element.height>0&&i.drawImage(e.element,0,s)}return t}exportSVG(e={}){if(void 0!==e.dpr&&1!==e.dpr)throw new RangeError("exportSVG: dpr must be 1, SVG has no device pixels");const t=Math.max(1,Math.round(e.width??this._width)),r=Math.max(1,Math.round(e.height??this._height)),s=!1!==e.background,n=new Gt(t,r,{background:s?this._theme.background:void 0}),o=n.asCanvasContext();this._flushIndicators();const a=this._width,l=this._height,h=t!==a||r!==l;h&&(this._width=t,this._height=r,this._relayout(!0));try{s&&"transparent"!==this._theme.background&&(n.fillStyle=this._theme.background,n.fillRect(0,0,t,r));const e=this._paneLayout(),i=this._topPaneIndex(),a=this._bottomPaneIndex();for(let r=0;r<this._panes.length;r++){if(this._layoutWeight(r)<=0)continue;const l=this._panes[r],h={...this._renderContext(r===a),dpr:1,hoverId:null,dragId:null,paintBackground:s},c=r===i,d=e[r].top+(c?0:1),u=e[r].height-(c?0:1);c||(n.fillStyle=this._theme.paneSeparator,n.fillRect(0,e[r].top,t,1)),n.pushGroup({"data-pane":r},{translate:{x:0,y:d},clip:{x:0,y:0,width:t,height:u}}),l.autoscale(h),l.paintBase(h,o),l.paintTop(null,h,o),n.popGroup()}}finally{h&&(this._width=a,this._height=l,this._relayout(!0),this.invalidate(e=>e.invalidateGlobal(i.Full)))}return n.toString()}_addPrimitive(e,t){this._ensurePane(e);const r={requestUpdate:()=>this.invalidate(r=>r.invalidatePane(e,{level:"top"===t.zOrder()?i.Cursor:i.Light,autoScale:!1}))};if(this._panes[e].addPrimitive(t,r),t instanceof Mr){if(this._legends.push({legend:t,paneIndex:e}),t.setOptions({hasOpenInterest:this.hasOpenInterest}),Object.keys(this._statusLine).length>0){const e=t.options().statusLine;t.setOptions({statusLine:{...this._statusLine,...e}})}void 0!==this._legendIconSize&&t.setOptions({iconSize:this._legendIconSize}),this._restackLegends()}this.invalidate(t=>t.invalidatePane(e,{level:i.Light,autoScale:!1}))}removePrimitive(e){const t=this._anchored.findIndex(t=>t.primitive===e);t>=0&&this._anchored.splice(t,1);const r=this._legends.findIndex(t=>t.legend===e);r>=0&&this._legends.splice(r,1);for(let t=0;t<this._panes.length;t++)if(this._panes[t].removePrimitive(e))return r>=0&&this._restackLegends(),void this.invalidate(e=>e.invalidatePane(t,{level:i.Light,autoScale:!1}))}_restackLegends(){const e=new Map;for(const t of this._legends){const i=e.get(t.paneIndex)??0;t.legend.setOptions({row:i}),e.set(t.paneIndex,i+1)}this._syncLegendOffsets()}_syncLegendOffsets(){const e=this._paneLayout();for(const t of this._legends){if(!t.legend.options().id.startsWith("indicator:"))continue;const i=(e[t.paneIndex]?.top??Number.POSITIVE_INFINITY)<=12;t.legend.setOptions(i?{top:this._legendOffset.top,left:this._legendOffset.left}:{top:6,left:8})}}tradeHost(e=0){return{addPrimitive:t=>this._addPrimitive(e,t),removePrimitive:e=>this.removePrimitive(e)}}_updateBar(e,t){const r=this._timeScale.rightOffset>=0,s=this._dataLayer.update(e,t);this._timeScale.setBaseIndex(this._dataLayer.baseIndex),"append"!==s||r||this._timeScale.setRightOffset(this._timeScale.rightOffset-1),e===this._firstDataId.value&&this._invalidateIndicators(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._updateAccessibleSummary(),e===this._firstDataId.value&&this.emit("data:update",{kind:"update",time:t.time})}_ensurePane(e){const t=[];for(;this._panes.length<=e;)this._addPane(0===this._panes.length?1:.32),t.push(this._panes.length-1);if(0!==t.length){this._relayout(),this._rehomeAnchored();for(const e of t)this.emit("paneAdded",{paneIndex:e})}}_setData(e,t){e===this._firstDataId.value&&this._stopNavigationMotion(),this._dataLayer.setSeriesData(e,t),e===this._firstDataId.value&&(this._invalidateIndicators(),this._flushIndicators()),this._timeScale.setBaseIndex(this._dataLayer.baseIndex),!this._hasFitContent&&this._dataLayer.length>0&&(this._timeScale.setWidth(Math.max(0,this._width-this._rightAxisWidth-this._leftAxisWidth)),this._hasFitContent=this._fitDefaultView()),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._updateAccessibleSummary(),e===this._firstDataId.value&&this.emit("data:update",{kind:"reset"})}_prependData(e,t){this._dataLayer.addBars(e,t),this._timeScale.setBaseIndex(this._dataLayer.baseIndex),e===this._firstDataId.value&&this._invalidateIndicators(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._updateAccessibleSummary(),e===this._firstDataId.value&&this.emit("data:update",{kind:"prepend"})}get rendererKind(){return this._rendererKind??"canvas2d"}get renderer(){return this.rendererKind}_newBackend(){const e=this._backendFactory()??It("canvas2d")();if(null===e)throw new Error("openalgo-charts: the canvas2d render backend factory returned null");return null===this._rendererKind&&(this._rendererKind=e.kind,null!==this._requestedRenderer&&"auto"!==this._requestedRenderer&&e.kind!==this._requestedRenderer&&console.warn(`openalgo-charts: render backend "${this._requestedRenderer}" is unavailable on this device; using "${e.kind}"`)),e}_fallbackToCanvas2d(e){const t=this.rendererKind;this._backendFactory=It("canvas2d");for(const e of this._panes)e.setBackend(this._newBackend());this._rendererKind="canvas2d";const r={from:t,to:"canvas2d",reason:e};this.emit("renderer:fallback",r),this.invalidate(e=>e.invalidateGlobal(i.Full))}_addPane(e=1){const t=new zt(this._doc,this._newBackend());if(t.weight=e,0===this._panes.length)this._pricePanes.add(t);else for(const e of t.scales())e.setOptions({minPrecision:2});return t.priceScale.setPriceFormatter(this._priceFormatter),this._priceScaleOptions&&t.priceScale.setOptions(this._scalePatchFor(t,this._priceScaleOptions)),this._panes.push(t),this._container.appendChild(t.element),t}setPriceFormatter(e){this._priceFormatter=e;for(const t of this._panes)t.priceScale.setPriceFormatter(e);for(const e of this._panes)for(const t of e.series())void 0!==t.style.precision&&this._applyPrecision(e.scaleOf(t),t.style.precision);this.invalidate(e=>e.invalidateGlobal(i.Full))}setTimeFormatter(e){this._timeFormatter=e,this.invalidate(e=>e.invalidateGlobal(i.Full))}timezone(){return this._timezone}setTimezone(e){const t=Vr(e);t!==this._timezone&&(this._timezone=t,this._invalidateIndicators(),this.invalidate(e=>e.invalidateGlobal(i.Full)))}setPlacementMode(e){this._placementMode=e}beginPick(e,t){return lr(this,e,t)}setTheme(e){this._theme=e,this._container.style.background=e.background,this.invalidate(e=>e.invalidateGlobal(i.Full))}applyOptions(e){e.theme&&this.setTheme(e.theme),e.grid&&this.setGridOptions(e.grid),e.canvas&&this.setCanvasOptions(e.canvas),e.statusLine&&this.setStatusLineOptions(e.statusLine),void 0!==e.legendIconSize&&this.setLegendIconSize(e.legendIconSize),e.priceScale&&this.setPriceScaleOptions(e.priceScale),void 0!==e.priceFormatter&&this.setPriceFormatter(e.priceFormatter),"timeFormatter"in e&&this.setTimeFormatter(e.timeFormatter),void 0!==e.timezone&&this.setTimezone(e.timezone),e.crosshairMode&&(this._crosshairMode=e.crosshairMode),"boolean"==typeof e.crosshairSnapToBar&&(this._crosshairSnapToBar=e.crosshairSnapToBar,this.invalidate(e=>e.invalidateGlobal(i.Cursor)))}panes(){return this._panes}getState(){const e=this._panes.map(e=>{const t=e.priceScale,i=t.options,r={weight:e.weight,priceScale:{marginTop:i.marginTop,marginBottom:i.marginBottom,minMove:i.minMove,mode:i.mode,inverted:i.inverted,autoScale:t.autoScale}};return t.autoScale||(r.priceScale.range={...t.priceRange()}),r}),t=[];this._panes.forEach((e,i)=>{for(const r of e.series()){const e=Object.fromEntries(Object.entries(r.style).filter(([,e])=>void 0!==e));t.push({type:r.type,style:e,paneIndex:i,priceScaleId:r.scaleId})}});const i={version:1,timezone:this._timezone,viewport:{...this.getVisibleLogicalRange()},barSpacing:this._timeScale.barSpacing,navigation:this.navigationOptions(),grid:this.gridOptions(),canvas:this.canvasOptions(),statusLine:this.statusLineOptions(),watermark:this.watermarkOptions(),trading:{...this._tradingSettings},axisChrome:{sessionClock:this._axisChrome.sessionClock,barCountdown:this._axisChrome.barCountdown},events:this.eventOptions(),crosshairMode:this._crosshairMode,crosshairSnapToBar:this._crosshairSnapToBar,panes:e,series:t,indicators:this._indicators.map(e=>({indicatorId:e.indicatorId,instanceId:e.id,settings:e.settings(),paneIndex:e.paneIndex,visible:e.visible()}))};return void 0!==this._drawingState&&(i.drawings=this._drawingState),void 0!==this._alertState&&(i.alerts=Oi(this._alertState)),i}restoreState(e){const t=e;if(null===t||"object"!=typeof t||"number"!=typeof t.version)return{applied:!1,series:[],indicators:0,reason:"not a chart state object"};if(t.version>1)return{applied:!1,series:[],indicators:0,reason:`state version ${t.version} is newer than 1`};let i;const r=new Set;try{if(void 0!==t.alerts&&(i=Oi(t.alerts)),void 0!==t.indicators){if(!Array.isArray(t.indicators))throw new Error("Invalid indicator list");for(const e of t.indicators)if(void 0!==e.instanceId){if("string"!=typeof e.instanceId||!e.instanceId.trim()||r.has(e.instanceId))throw new Error("Invalid or duplicate indicator instance id");r.add(e.instanceId)}}}catch(e){return{applied:!1,series:[],indicators:0,reason:e instanceof Error?e.message:"Invalid saved alerts or identities"}}this.emit("state:restore:start",{});try{return this._restoreState(t,i,r)}finally{this.emit("state:restore:end",{})}}_restoreState(e,t,r){e.grid&&this.setGridOptions(e.grid),e.canvas&&this.setCanvasOptions(e.canvas),e.statusLine&&this.setStatusLineOptions(e.statusLine),e.watermark&&this.setWatermarkOptions(e.watermark),e.trading&&this.setTradingSettings(e.trading),e.axisChrome&&this.setAxisChromeOptions(e.axisChrome),e.navigation&&"object"==typeof e.navigation&&this._patchNavigation(e.navigation),e.events&&this.setEventOptions(e.events),e.crosshairMode&&(this._crosshairMode=e.crosshairMode),"boolean"==typeof e.crosshairSnapToBar&&(this._crosshairSnapToBar=e.crosshairSnapToBar),"string"==typeof e.timezone&&Te(e.timezone)&&this.setTimezone(e.timezone),e.panes&&(e.panes.forEach((e,t)=>{this._ensurePane(t),this._panes[t].weight=e.weight}),this._relayout());let s=0;if(e.indicators){for(const e of this._indicators.splice(0))e.remove();const t=new Set;for(const i of e.indicators){if(!ii(i.indicatorId))continue;const e=ti(i.indicatorId),n=new bi(this._indicatorHost(),e,i.settings,i.paneIndex,i.instanceId,r);r.add(n.id),this._indicators.push(n),!1===i.visible&&n.setVisible(!1),s+=1,i.paneIndex>0&&!t.has(i.paneIndex)&&(t.add(i.paneIndex),this._panes[i.paneIndex]?.priceScale.setFixedRange(e.range?.(i.settings)??null))}}e.panes&&e.panes.forEach((e,t)=>{const i=this._panes[t];if(void 0===i)return;const r=i.priceScale;r.setOptions(this._scalePatchFor(i,{marginTop:e.priceScale.marginTop,marginBottom:e.priceScale.marginBottom,minMove:e.priceScale.minMove,mode:e.priceScale.mode,inverted:e.priceScale.inverted})),r.setAutoScale(e.priceScale.autoScale),!e.priceScale.autoScale&&e.priceScale.range&&r.setPriceRange(e.priceScale.range)});for(let e=this._panes.length-1;e>0;e--)0===this._panes[e].series().length&&this.removePane(e);return this._drawingState=e.drawings,this._alertState=t,void 0!==e.barSpacing&&this._timeScale.setBarSpacing(e.barSpacing),e.viewport&&this._dataLayer.length>0&&this.setVisibleLogicalRange(e.viewport),this.invalidate(e=>e.invalidateGlobal(i.Full)),this.emit("drawings:restore",e.drawings??[]),this.emit("alerts:restore",t??{version:1,alerts:[]}),this.emit("objects:change",{}),{applied:!0,series:e.series??[],indicators:s}}drawingState(){return this._drawingState}setDrawingState(e){this._drawingState=e,this.emit("objects:change",{})}snapPrice(e,t){if(!Number.isFinite(t))return t;const i=this._panes[e]?.priceScale.options.minMove??0;return i>0?d(t,i):t}alertState(){return void 0===this._alertState?void 0:Oi(this._alertState)}setAlertState(e){if(void 0!==e){if(1!==e.version)throw new Error("Unsupported alert document");for(const t of e.alerts)yi(t)}this._alertState=void 0===e?void 0:{version:1,alerts:e.alerts.map(wi)}}invalidate(e){null===this._pending&&(this._pending=new r),e(this._pending),this._loop.requestFrame()}_remeasure(){if(0===this._panes.length)return;const e=this._container.clientWidth,t=this._container.clientHeight;e>0&&t>0&&this.applySize(e,t)}applySize(e,t){e===this._width&&t===this._height||(this._width=e,this._height=t,this._relayout(),this._hasFitContent||(this._hasFitContent=this._fitDefaultView()),this.invalidate(e=>e.invalidateGlobal(i.Full)),this.emit("resize",{width:e,height:t}))}_relayout(e=!1){if(e){const e=this._weightTotal(),t=this._bottomPaneIndex();return this._panes.forEach((i,r)=>{const s=this._height*this._layoutWeight(r)/e;i.setLayoutSize(this._width,s),i.setScaleHeights(Math.max(0,s-(r===t?this._timeAxisHeight:0)))}),void this._timeScale.setWidth(Math.max(0,this._width-this._rightAxisWidth-this._leftAxisWidth))}this._syncTimeNavPane(),this._syncLegendOffsets();const t=this._pixelRatio(),i=this._weightTotal(),r=this._topPaneIndex(),s=this._bottomPaneIndex();this._panes.forEach((e,n)=>{const o=this._layoutWeight(n),a=this._height*o/i;e.element.style.display=o>0?"":"none",e.element.style.flex=`0 0 ${a}px`;const l=n===r;e.element.style.borderTopWidth=l?"0px":"1px",e.element.style.borderTopColor=l?"transparent":this._theme.paneSeparator,e.resize(this._width,a,t);const h=n===s;e.setScaleHeights(Math.max(0,a-(h?this._timeAxisHeight:0)))}),this._timeScale.setWidth(Math.max(0,this._width-this._rightAxisWidth-this._leftAxisWidth))}_recomputeAxisColumns(){const e=this._panes.some(e=>e.hasLeftScale()),t=this._panes.some(e=>e.usesScale("right")),r=e?this._priceAxisWidth:0,s=t||!e?this._priceAxisWidth:0;r===this._leftAxisWidth&&s===this._rightAxisWidth||(this._leftAxisWidth=r,this._rightAxisWidth=s,this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full)))}_layoutWeight(e){const t=this._panes[e];return void 0===t?0:null===this._maximizedPane?t.weight:e===this._maximizedPane?1:0}_topPaneIndex(){for(let e=0;e<this._panes.length;e++)if(this._layoutWeight(e)>0)return e;return 0}_bottomPaneIndex(){for(let e=this._panes.length-1;e>=0;e--)if(this._layoutWeight(e)>0)return e;return this._panes.length-1}_weightTotal(){let e=0;for(let t=0;t<this._panes.length;t++)e+=this._layoutWeight(t);return e<=0?1:e}_dividerAt(e){const t=this._paneLayout();for(let i=0;i<t.length-1;i++){const r=t[i].top+t[i].height;if(Math.abs(e-r)<=Jr.DIVIDER_GRAB)return i}return null}setPaneWeight(e,t){const r=this._panes[e];void 0!==r&&(r.weight=Math.max(.05,t),this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full)))}paneWeight(e){return this._panes[e]?.weight??0}removePane(e){if(e<=0||e>=this._panes.length)return!1;this._eventPane===e&&null!==this._eventMarkers?(this.removePrimitive(this._eventMarkers),this._eventPane=0,this._addPrimitive(0,this._eventMarkers),this.emit("events:change",void 0)):this._eventPane>e&&(this._eventPane-=1);for(let t=this._indicators.length-1;t>=0;t--){if(this._indicators[t].paneIndex!==e)continue;const[i]=this._indicators.splice(t,1);i.remove()}const t=this._panes[e];for(const e of[...t.series()])t.removeSeries(e),this._dataLayer.removeSeries(e.dataId),this._firstDataId.value===e.dataId&&(this._firstDataId.value=null);t.destroy(),this._panes.splice(e,1),null!==this._maximizedPane&&(this._maximizedPane===e?this._maximizedPane=null:this._maximizedPane>e&&(this._maximizedPane-=1));for(const t of this._indicators)t.paneIndex>e&&t.shiftPane(-1);return this._timeScale.setBaseIndex(this._dataLayer.baseIndex),this._recomputeAxisColumns(),this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._rehomeAnchored(),this.emit("paneRemoved",{paneIndex:e}),!0}movePane(e,t){const r=e+t;if(e<=0||r<=0||e>=this._panes.length||r>=this._panes.length)return!1;const s=this._panes;[s[e],s[r]]=[s[r],s[e]],this._eventPane===e?this._eventPane=r:this._eventPane===r&&(this._eventPane=e),null!==this._eventMarkers&&this.emit("events:change",void 0),this._maximizedPane===e?this._maximizedPane=r:this._maximizedPane===r&&(this._maximizedPane=e);for(const i of this._indicators)i.paneIndex===e?i.shiftPane(t):i.paneIndex===r&&i.shiftPane(-t);for(const e of s)this._container.appendChild(e.element);return this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._rehomeAnchored(),this.emit("paneMoved",{from:e,to:r}),!0}maximizePane(e){return!(e<0||e>=this._panes.length)&&(this._maximizedPane=this._maximizedPane===e?null:e,this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._rehomeAnchored(),this.emit("paneMaximized",{paneIndex:this._maximizedPane}),!0)}maximizedPane(){return this._maximizedPane}_handleLegendAction(e){const t=e.lastIndexOf("::");if(t<0)return!1;const r=e.slice(t+2);if(null!==this._timeNav&&e.startsWith(`${this._timeNav.options().id}::`))return this._runShortcut(r)&&this.invalidate(e=>e.invalidateGlobal(i.Full)),!0;if("row"===r&&!e.startsWith("indicator:"))return!0;if(!e.startsWith("indicator:"))return!1;const s=e.slice(10,t);if("row"===r)return!0;const n=this._indicators.find(e=>e.id===s);if(void 0===n)return!1;const o=n.paneIndex;switch(r){case"close":return this.removeIndicator(s),!0;case"hide":return n.setVisible(!n.visible()),!0;case"up":return this.movePane(o,-1),!0;case"down":return this.movePane(o,1),!0;case"maximize":return this.maximizePane(o),!0;case"settings":return this.emit("indicatorSettings",{instanceId:s,indicatorId:n.indicatorId,paneIndex:o}),!0;case"source":return this.emit("indicatorSource",{instanceId:s,indicatorId:n.indicatorId,paneIndex:o}),!0;default:return!1}}_paneLayout(){const e=this._weightTotal(),t=[];let i=0;for(let r=0;r<this._panes.length;r++){const s=this._height*this._layoutWeight(r)/e;t.push({top:i,height:s}),i+=s}return t}_navHints(e){if(void 0!==e?.hints)return e.hints;if(null===this._shortcuts)return{};const t={};for(const e of this._shortcuts.list()){if("zoomIn"!==e.command&&"zoomOut"!==e.command&&"resetScale"!==e.command)continue;const i=e.combos[0];void 0!==i&&(t[e.command]=Qr(i))}return t}_syncTimeNavPane(){if(null===this._timeNav)return;const e=this._bottomPaneIndex();e===this._timeNavPane||e<0||(this._timeNavPane>=0&&this._panes[this._timeNavPane]?.removePrimitive(this._timeNav),this._addPrimitive(e,this._timeNav),this._timeNavPane=e)}_feedTimeNav(e){const t=this._timeNav;null!==t&&(t.setPointer(e),t.animating()&&this.invalidate(e=>e.invalidateGlobal(i.Light)))}_renderContext(e){return{timeScale:this._timeScale,dataLayer:this._dataLayer,dpr:this._pixelRatio(),priceAxisWidth:this._rightAxisWidth,timeAxisHeight:this._timeAxisHeight,showTimeAxis:e,conflate:this._conflate,conflationFactor:this._conflationFactor,theme:this._theme,showVertGrid:this._gridVert,showHorzGrid:this._gridHorz,canvasOptions:this._canvas,timeFormatter:this._timeFormatter,timezone:this._timezone,leftAxisWidth:this._leftAxisWidth,hoverId:this._hoverId,dragId:this._dragId,sessionClock:this._sessionClockOptions(),barCountdown:this._barCountdownOptions()}}_sessionClockOptions(){const e=this._axisChrome.sessionClock;if(void 0!==e&&!1!==e)return{visible:!0,now:this._wallClock,timezone:this._timezone,showOffset:!0===e?void 0:e.showOffset}}_barCountdownOptions(){if(!0!==this._axisChrome.barCountdown)return;const e=this._dataLayer.indexToTime(this._dataLayer.baseIndex);return void 0!==e?{visible:!0,now:this._wallClock,lastBarTime:e,intervalSec:_t(this._dataLayer)}:void 0}_observeSize(){"undefined"!=typeof ResizeObserver&&(this._resizeObserver=new ResizeObserver(e=>{const t=e[0];t&&this.applySize(t.contentRect.width,t.contentRect.height)}),this._resizeObserver.observe(this._container))}_onFrame(){this._flushIndicators();const e=this._pending;if(this._pending=null,null===e||e.isEmpty())return;const t=e.globalLevel;let r=!1;const s=this._now(),n=null===this._autoscaleTime||++this._autoscaleFrames>=90?1:1-Math.exp(-Math.max(1,s-this._autoscaleTime)/80);null!==this._autoscaleTime&&(this._autoscaleTime=s);let o=this._cursor?.x??0;const a=this._firstDataId.value??this._panes[0]?.series()[0]?.dataId;if(null!==this._cursor&&this._crosshairSnapToBar&&void 0!==a){const e=Math.round(this._timeScale.xToIndex(o));this._dataLayer.visibleBars(a,e,e).length>0&&(o=this._timeScale.indexToX(e))}for(let s=0;s<this._panes.length;s++){const a=this._panes[s],l=e.paneInvalidation(s),h=Math.max(t,l?.level??i.None),c=s===this._bottomPaneIndex(),d=this._renderContext(c);if((h>=i.Full||l?.autoScale||null!==this._autoscaleTime)&&(r=a.autoscale(d,n)||r),h>=i.Light&&a.paintBase(d),h>=i.Cursor&&!this._overlayFrozen){const e=null===this._cursor?null:{x:o,yLocal:s===this._cursorPane?this._cursor.y:null,showTimeTag:c};a.paintTop(e,d)}}if(r?this.invalidate(e=>e.invalidateGlobal(i.Light)):this._autoscaleTime=null,null!==this._rendererKind&&"canvas2d"!==this._rendererKind)for(const e of this._panes){const t=e.backendDegradation;if(null!==t){this._fallbackToCanvas2d(t);break}}}_attachInput(){if("undefined"==typeof window)return;const e=this._container;e.addEventListener("pointerdown",this._onPointerDown),e.addEventListener("pointermove",this._onPointerMove),e.addEventListener("pointerup",this._onPointerUpNative),e.addEventListener("pointercancel",this._onPointerCancel),e.addEventListener("lostpointercapture",this._onLostPointerCapture),e.addEventListener("pointerleave",this._onPointerLeave),e.addEventListener("wheel",this._onWheel,{passive:!1}),e.addEventListener("dblclick",this._onDblClick),e.addEventListener("pointerenter",this._onPointerEnter),e.addEventListener("contextmenu",this._onContextMenu);const t="function"==typeof this._doc.addEventListener?this._doc:e;t.addEventListener("keydown",this._onKeyDown),this._keyTarget=t}_contextMenuEvent(e,t){const i=t.x-this._leftAxisWidth,r=i>=0&&t.x<this._width-this._rightAxisWidth,s=r?Math.round(this._timeScale.xToIndex(i)):null;return r&&this._ensureScaled(t.pane),{paneIndex:t.pane,point:{x:t.x,y:t.y},price:r?this._panes[t.pane].yToPrice(t.localY):null,time:null===s?null:this._dataLayer.indexToTime(s)??null,index:s,target:this._contextTarget(t,i,r,s),preventDefault:()=>e.preventDefault()}}_contextTarget(e,t,i,r){const s=e.pane===this._bottomPaneIndex(),n=e.x>=this._width-this._rightAxisWidth;if(s&&e.localY>=e.paneHeight-this._timeAxisHeight&&!n)return{kind:"time-scale",id:null};if(!i){const t=n?"right":"left";return{kind:"price-scale",id:null,side:t,scaleId:this._axisScaleId(e.pane,t)}}const o=this._panes[e.pane]?.hitTestPrimitives(t,e.localY,this._renderContext(s));if(null!=o){const e=o.externalId;if(e.startsWith("draw:"))return{kind:"drawing",id:e};if(e.startsWith("indicator:")){const t=e.lastIndexOf("::"),i=e.slice(10,t<0?void 0:t);return{kind:"indicator",id:e,instanceId:i}}return e.endsWith("::row")?{kind:"legend",id:e}:{kind:"primitive",id:e}}const a=null===r?null:this._seriesAt(e.pane,r,e.localY);if(null===a)return{kind:"empty",id:null};for(const e of this._indicators)for(const t of ti(e.indicatorId).plots){const i=e.series(t.key);if(i&&this._seriesRecords.get(i)===a)return{kind:"indicator",id:`indicator:${e.id}`,instanceId:e.id,plotKey:t.key}}return{kind:"series",id:null,seriesType:a.type}}_axisScaleId(e,t){const i=this._panes[e];return void 0===i||i.usesScale(t)?t:i.usesScale("")?"":t}_seriesAt(e,t,i){const r=this._panes[e];if(void 0===r)return null;const s=r.series();for(let e=s.length-1;e>=0;e--){const n=s[e];if(!1===n.style.visible)continue;const o=this._dataLayer.visibleBars(n.dataId,t,t);if(0===o.length)continue;const a=se(n.type).extents(o[0].bar,n.style);if(!isFinite(a.min)||!isFinite(a.max))continue;const l=r.scaleOf(n),h=l.priceToY(a.max),c=l.priceToY(a.min);if(i>=Math.min(h,c)-3&&i<=Math.max(h,c)+3)return n}return null}_unfreezeOverlay(){this._overlayFrozen&&(this._overlayFrozen=!1,this.invalidate(e=>e.invalidateGlobal(i.Cursor)))}_localPoint(e){const t=this._container.getBoundingClientRect();return this._project(e.clientX-t.left,e.clientY-t.top,this._paneLayout())}_project(e,t,i){let r=0;for(let e=0;e<i.length;e++)t>=i[e].top&&(r=e);const s=i[r]??{top:0,height:this._height};return{x:e,y:t,pane:r,localY:t-s.top,paneHeight:s.height}}_dragSamples(e){const t="function"==typeof e.getCoalescedEvents?e.getCoalescedEvents():[],i=t.length>0?t:[e],r=this._container.getBoundingClientRect(),s=this._paneLayout(),n=[];for(const e of i){const t=this._project(e.clientX-r.left,e.clientY-r.top,s);n.push({x:t.x,y:null===this._dragId?t.localY:t.y-(s[this._downPane]?.top??0),pressure:Yr(e)})}return n}_clickInfo(e){const t=Ur(e);return t.pressure=this._downPressure,{...t,shiftKey:t.modifiers.shift,ctrlKey:t.modifiers.ctrl,metaKey:t.modifiers.meta}}_brandingHit(e,t,i){const r=this._panes[e];if(null===this._branding||!r?.hasPrimitive(this._branding))return!1;const s=e===this._bottomPaneIndex();return null!==this._branding.hitTest(t-this._leftAxisWidth,i,{timeScale:this._timeScale,priceScale:r.priceScale,dataLayer:this._dataLayer,plotWidth:this._width-this._leftAxisWidth-this._rightAxisWidth,plotHeight:(this._paneLayout()[e]?.height??0)-(s?this._timeAxisHeight:0),priceAxisWidth:this._rightAxisWidth,dpr:this._pixelRatio(),theme:this._theme})}_applyZoom(e,t){this._beginAutoscaleMotion(),this._timeScale.zoomAtX(e,Math.exp(t)),this._maybeLoadHistory(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._emitViewport("zoom")}_startZoomGlide(e,t){const i=new Ai(t);this._zoomGlide=i,this._zoomGlideStart=this._now(),this._zoomGlideApplied=0;let r=0;const s=()=>{if(this._zoomGlide!==i||this._destroyed)return;const t=this._now()-this._zoomGlideStart,n=i.appliedAt(t),o=n-this._zoomGlideApplied;if(this._zoomGlideApplied=n,0!==o&&this._applyZoom(e,o),this._zoomGlide===i&&!this._destroyed)if(!i.finished(t)&&++r<600)this._zoomHandle=this._raf.schedule(s);else{const t=i.totalLogFactor-this._zoomGlideApplied;0!==t&&this._applyZoom(e,t),this._zoomHandle=null,this._zoomGlide=null}};this._zoomHandle=this._raf.schedule(s)}_beginAutoscaleMotion(){this._animAutoscale&&null===this._autoscaleTime&&(this._autoscaleTime=this._now()-16,this._autoscaleFrames=0)}_stopNavigationMotion(){this._navigationEpoch++,this._stopZoomGlide(),this._stopKinetic(),this._autoscaleTime=null}_stopZoomGlide(){null!==this._zoomHandle&&(this._raf.cancel(this._zoomHandle),this._zoomHandle=null),this._zoomGlide=null}resetScale(){this._stopNavigationMotion();const e=this._timeScale.visibleRange();this._hasFitContent=this._fitDefaultView();for(const e of this._panes){e.clearRatioLocks();for(const t of e.scales())t.setAutoScale(!0)}this.invalidate(e=>e.invalidateGlobal(i.Full)),this._emitViewportIfMoved(e)}_beginPinch(){this._cancelPrimitiveDrag("pinch"),this._brandingPress=null;const e=[...this._pointers.values()];this._pinch=or(e[0],e[1]),this._pinchPane=e[0].pane,this._dragging=!1,this._axisDrag=null,this._axisDragScale=null,this._dragId=null,this._pointerMoved=!0,this._setHover(null)}_updatePinch(){const e=[...this._pointers.values()];if(e.length<2||null===this._pinch)return;const t=or(e[0],e[1]),r=function(e,t){return{factor:e.dist>0?t.dist/e.dist:1,dx:t.cx-e.cx,dy:t.cy-e.cy}}(this._pinch,t);this._beginAutoscaleMotion(),1!==r.factor&&this._timeScale.zoomAtX(t.cx,r.factor),this._timeScale.setRightOffset(this._timeScale.rightOffset-r.dx/this._timeScale.barSpacing),this._panes[this._pinchPane]?.priceScale.panByPixels(r.dy),this._pinch=t,this._maybeLoadHistory(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._emitViewport(1!==r.factor?"zoom":"pan")}_cancelPrimitiveDrag(e){null!==this._dragId&&(this._dragMoved=!0,this.emit("drag:cancel",{id:this._dragId,paneIndex:this._downPane,reason:e}))}_shortcutsActive(){if(null===this._shortcuts)return!1;if("global"===this._shortcuts.scope||this._pointerInside)return!0;const e=this._doc.activeElement;return null!==e&&(e===this._container||!0===this._container.contains?.(e))}_runShortcut(e){const t=this._timeScale,i=e=>{this._stopZoomGlide(),this._beginAutoscaleMotion();const i=t.visibleRange();return t.setRightOffset(t.rightOffset+e),this._emitViewportIfMoved(i),!0},r=e=>{this._stopZoomGlide(),this._beginAutoscaleMotion();const i=t.visibleRange();return t.zoomAtX(this._width/2,e),this._emitViewportIfMoved(i),!0};switch(e){case"panLeftBar":return i(-1);case"panRightBar":return i(1);case"panLeft":return i(-2);case"panRight":return i(2);case"panLeftFast":return i(-10);case"panRightFast":return i(10);case"panUp":return this._panes[0]?.priceScale.panByPixels(20),!0;case"panDown":return this._panes[0]?.priceScale.panByPixels(-20),!0;case"zoomIn":return r(1.1);case"zoomOut":return r(1/1.1);case"resetScale":return this.resetScale(),!0;case"fitContent":return this.fitContent(),!0;case"screenshot":return this.downloadScreenshot(),!0;case"toggleGridVert":return this.setGridOptions({vertLines:!this._gridVert}),!0;case"toggleGridHorz":return this.setGridOptions({horzLines:!this._gridHorz}),!0;case"toggleCrosshairMagnet":return this._crosshairMode="magnet"===this._crosshairMode?"normal":"magnet",!0;default:return!1}}downloadScreenshot(e="chart.png"){try{const t=this.takeScreenshot(),i=this._doc.createElement("a");i.href=t.toDataURL("image/png"),i.download=e,i.click()}catch{}}_updateAccessibleSummary(){if(null===this._liveRegion)return;const e=this._dataLayer.length;let t=`${e} bar${1===e?"":"s"}`;if(null!==this._firstDataId.value&&void 0!==this._panes[0]){const e=this._dataLayer.lastIndexedBar(this._firstDataId.value);null!==e&&(t+=`, latest price ${this._panes[0].priceScale.format(e.bar.close)}`)}this._liveRegion.textContent=`Financial chart, ${t}`}_setHover(e){const t=e?.externalId??null;if(this._container.style.cursor=this._dragging&&"pointer"!==e?.cursor?"grabbing":e?.cursor??"",t===this._hoverId)return;const r=null!==e&&"top"!==e.zOrder,s=r||this._hoverOnBase?i.Light:i.Cursor;this._hoverId=t,this._hoverOnBase=r,this.invalidate(e=>e.invalidateGlobal(s)),this.emit("hover",{id:t})}_updateCursor(e,t,r,s,n){const o=this._width-this._rightAxisWidth,a=t-this._leftAxisWidth,l=Math.max(0,o-this._leftAxisWidth);if(a<0||a>l)return void this._onPointerLeave();const h=this._panes[e],c=h.hitTestPrimitives(a,r,this._renderContext(e===this._bottomPaneIndex()))??null;if(null===c&&null!==this._dividerAt(s))return this._setHover(null),void(this._container.style.cursor="row-resize");this._setHover(c),this._feedTimeNav(e!==this._bottomPaneIndex()||this._brandingHit(e,t,r)?null:{x:a,y:r});let d=r;const u=Math.round(this._timeScale.xToIndex(a));let p=null;if(null!==this._firstDataId.value){const t=this._dataLayer.visibleBars(this._firstDataId.value,u,u);if(t.length>0&&(p=t[0].bar,"magnet"===this._crosshairMode&&e===this._firstPaneIndex)){const e=function(e,t){const i=[t.open,t.high,t.low,t.close];let r=i[0],s=Math.abs(e-r);for(let t=1;t<i.length;t++){const n=Math.abs(e-i[t]);n<s&&(s=n,r=i[t])}return r}(h.yToPrice(r),p);d=h.priceToY(e)}}this._cursorPane=e,this._cursor={x:a,y:d},this._readoutTime=p?.time??null;for(const e of this._indicators)e.updateLegendValues(u);if(this.invalidate(e=>e.invalidateGlobal(i.Cursor)),null!==this._crosshairCb||void 0!==this._listeners.get("crosshair:move")){const i={time:this._dataLayer.indexToTime(u)??null,index:u,price:h.yToPrice(r),bar:p,point:{x:t,y:s},paneIndex:e,pressed:this._pointers.size>0,...Ur(n),...this._pointers.size>0?{samples:this._dragSamples(n)}:{}};this._crosshairCb?.(i),this.emit("crosshair:move",i)}}_maybeLoadHistory(){if(null===this._historyLoader||this._loadingHistory)return;const e=this._timeScale.visibleRange();e.from<10&&(this._loadingHistory=!0,this.emit("lazy-load",{from:this._dataLayer.indexToTime(Math.round(e.from))??null,to:this._dataLayer.indexToTime(Math.round(e.to))??null,direction:"backward"}),this._historyLoader())}_startKinetic(e){this._stopKinetic();const t=this._kineticEpoch,r=new Ii(e);if(r.durationMs<=0)return;const s=this._now();let n=0,o=0;const a=()=>{if(t!==this._kineticEpoch||this._destroyed)return;const e=this._now()-s,l=r.distanceAt(e),h=l-n;n=l,this._beginAutoscaleMotion(),this._timeScale.setRightOffset(this._timeScale.rightOffset-h/this._timeScale.barSpacing),this._maybeLoadHistory(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._emitViewport("pan"),t!==this._kineticEpoch||this._destroyed||(!r.finished(e)&&++o<600?this._kineticHandle=this._raf.schedule(a):this._kineticHandle=null)};this._kineticHandle=this._raf.schedule(a)}_stopKinetic(){this._kineticEpoch++,null!==this._kineticHandle&&(this._raf.cancel(this._kineticHandle),this._kineticHandle=null)}get isDestroyed(){return this._destroyed}destroy(){if(!this._destroyed){this._loop.stop(),null!==this._remeasureHandle&&(this._raf.cancel(this._remeasureHandle),this._remeasureHandle=null),this._stopNavigationMotion();for(const e of this._indicators.splice(0))e.remove();if(this._resizeObserver?.disconnect(),this._resizeObserver=null,"undefined"!=typeof window){const e=this._container;e.removeEventListener("pointerdown",this._onPointerDown),e.removeEventListener("pointermove",this._onPointerMove),e.removeEventListener("pointerup",this._onPointerUpNative),e.removeEventListener("pointercancel",this._onPointerCancel),e.removeEventListener("lostpointercapture",this._onLostPointerCapture),e.removeEventListener("pointerleave",this._onPointerLeave),e.removeEventListener("wheel",this._onWheel),e.removeEventListener("dblclick",this._onDblClick),e.removeEventListener("pointerenter",this._onPointerEnter),e.removeEventListener("contextmenu",this._onContextMenu),this._keyTarget?.removeEventListener("keydown",this._onKeyDown),this._keyTarget=null}this._liveRegion?.remove(),this._liveRegion=null,this._container.style.cursor="",this._pointers.clear();for(const e of this._panes)e.destroy();this._panes.length=0,this._destroyed=!0,this.emit("destroy",{}),this._listeners.clear()}}}function Zr(e,t={}){return new Jr(e,t)}function Qr(e){const t={Equal:"+",Minus:"-",NumpadAdd:"+",NumpadSubtract:"-",ArrowLeft:"<",ArrowRight:">",ArrowUp:"^",ArrowDown:"v"};return e.split("+").map(e=>e.trim()).map(e=>"Mod"===e?"Ctrl":t[e]??e.replace(/^(Key|Digit)/,"")).join(" + ")}Object.defineProperty(Jr,"DIVIDER_GRAB",{enumerable:!0,configurable:!0,writable:!0,value:4});const es=new WeakMap,ts=new WeakMap;function is(e){return es.get(e)}function rs(e){return es.has(e)}function ss(e,t){t?es.set(e,t):es.delete(e);for(const t of ts.get(e)??[])t()}const ns={bars:0,matched:0,gaps:0,dropped:0};function os(e,t){const i=new Map;for(const e of t){const t=Ti(e);isFinite(t.close)?i.set(t.time,t):i.delete(t.time)}const r=[];let s=0;for(const t of e){const e=i.get(t.time);void 0!==e?(r.push(e),s++):r.push({time:t.time})}return{items:r,alignment:{bars:r.length,matched:s,gaps:r.length-s,dropped:i.size-s}}}class as{constructor(e,t={}){Object.defineProperty(this,"_chart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_mode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_baseline",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_panes",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_items",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_alignedAt",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"_realigning",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_nextScale",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_syncing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_alignedPrimary",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_primaryLength",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"_primaryFirst",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_primaryLast",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_off",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._chart=e,this._mode=t.mode??"percentage",this._baseline=t.baseline??"first-visible",this._off.push(function(e,t){let i=ts.get(e);return i||(i=new Set,ts.set(e,i)),i.add(t),()=>{i.delete(t),i.size||ts.delete(e)}}(e,()=>this.realign())),e.on&&(this._off.push(e.on("data:update",()=>{this._needsAlignment()&&this.realign()})),this._off.push(e.on("destroy",()=>this._dispose())))}add(e){if(this._destroyed)throw new Error("openalgo-charts: comparison controller is destroyed");if(null===this._chart.primarySeries())throw new Error("openalgo-charts: a comparison needs a primary series to align against");const t=e.paneIndex??0,i={...e.style};void 0===i.color&&void 0!==e.color&&(i.color=e.color);const r=this._panes.get(t),s=this._scaleIdFor(t),n=this._chart.addSeries(e.type??"line",{paneIndex:t,style:i,priceScaleId:s}),o=r??this._openPane(t);o.count++;const a={series:n,entry:o,scale:n.priceScale(),savedScaleMode:n.priceScale().options.mode,savedInverted:n.priceScale().options.inverted,appliedInverted:null,scaleId:s,type:e.type??"line",style:i,items:[],values:new Map,suppressed:!1,bars:e.bars,alignment:ns,removed:!1};"none"!==this._mode&&a.scale.setOptions({mode:this._mode});const l={symbol:e.symbol,series:n,paneIndex:t,priceScale:()=>a.scale,alignment:()=>a.alignment,barAt:e=>{const t=a.values.get(e);return!a.removed&&!a.suppressed&&t&&Number.isFinite(t.close)?t:null},setBars:e=>{a.removed||(a.bars=e,this._align(a,this._primaryBars()))},remove:()=>{this.remove(l)},list:()=>this.list()};return this._items.set(l,a),this._align(a,this._primaryBars()),this._rememberAlignment(),l}remove(e){const t=this._items.get(e);if(void 0===t||t.removed)return!1;this._restoreScale(t),t.removed=!0,this._items.delete(e);const i=t.entry;return--i.count<=0&&this._closePane(i),t.series.remove(),!0}list(){return Array.from(this._items.keys())}clear(){for(const e of this.list())this.remove(e)}setMode(e){if(e!==this._mode){this._mode=e,this._syncing=!0;try{for(const e of this._panes.values())this._restoreMode(e),this._applyMode(e);for(const e of this._items.values())this._setSuppressed(e,!1)}finally{this._syncing=!1}this._repaint()}}get mode(){return this._mode}setBaseline(e){if(e!==this._baseline){this._baseline=e,this._syncing=!0;try{for(const e of this._items.values())this._setSuppressed(e,!1)}finally{this._syncing=!1}this._repaint()}}get baseline(){return this._baseline}baselineTime(e=0){const t=this._panes.get(e);return"common"===this._baseline&&"none"!==this._mode&&t&&t.primary.options.mode===t.applied?this._commonAnchor(t,this._visiblePrimary())?.time??null:null}realign(){if(this._realigning||this._destroyed||!this._items.size)return;this._realigning=!0;const e=this._syncing;this._syncing=!0;try{const e=this._primaryBars();for(const t of this._items.values())this._align(t,e);this._rememberAlignment()}finally{this._realigning=!1,this._syncing=e}e||this._repaint()}sync(){if(!this._syncing){this._syncing=!0;try{this._needsAlignment()&&this.realign();for(const e of this._panes.values())this._mirror(e)}finally{this._syncing=!1}}}destroy(){this._destroyed||(this.clear(),this._dispose())}_dispose(){if(!this._destroyed){this._destroyed=!0;for(const e of this._off.splice(0))e();for(const e of this._items.values())e.removed=!0,e.bars=[],e.items=[],e.values.clear();this._items.clear(),this._panes.clear(),this._alignedPrimary=null,ls.delete(this._chart)}}_needsAlignment(){if(this._destroyed||!this._items.size)return!1;const e=this._chart.primaryBars?.();return this._chart.dataLayer.length!==this._alignedAt||Boolean(e&&(e!==this._alignedPrimary||e.length!==this._primaryLength||e[0]?.time!==this._primaryFirst||e[e.length-1]?.time!==this._primaryLast))}_rememberAlignment(){this._alignedAt=this._chart.dataLayer.length,this._alignedPrimary=this._chart.primaryBars?.()??null,this._primaryLength=this._alignedPrimary?.length??-1,this._primaryFirst=this._alignedPrimary?.[0]?.time,this._primaryLast=this._alignedPrimary?.[this._primaryLength-1]?.time}_scaleIdFor(e){const t=this._chart.panes()[e],i=e=>t?.series().some(t=>t.scaleId===e)??!1;if(!this._panes.has(e)){if(!i(""))return"";if(!i("left"))return"left"}let r;do{r="overlay:comparison-"+ ++this._nextScale}while(i(r));return r}_openPane(e){const t=this._chart.panes()[e].priceScale,i={paneIndex:e,primary:t,savedPrimaryMode:t.options.mode,applied:null,sync:{zOrder:()=>"bottom",draw:()=>{},afterAutoscale:()=>{this.sync()}},count:0};return this._panes.set(e,i),this._applyMode(i),this._chart.addPrimitive(i.sync,e),i}_closePane(e){this._restoreMode(e),this._chart.removePrimitive(e.sync),this._panes.delete(e.paneIndex)}_applyMode(e){if("none"!==this._mode){e.applied=this._mode,e.primary.setOptions({mode:this._mode});for(const t of this._items.values())t.entry===e&&t.scale.setOptions({mode:this._mode})}}_restoreScale(e){null!==e.entry.applied&&e.scale.options.mode===e.entry.applied&&e.scale.setOptions({mode:e.savedScaleMode}),null!==e.appliedInverted&&e.scale.options.inverted===e.appliedInverted&&e.scale.setOptions({inverted:e.savedInverted}),e.appliedInverted=null}_restoreMode(e){const t=e.applied;if(null!==t){for(const t of this._items.values())t.entry===e&&this._restoreScale(t);e.applied=null,e.primary.options.mode===t&&e.primary.setOptions({mode:e.savedPrimaryMode})}}_mirror(e){if(null===e.applied)return;const t=Array.from(this._items.values()).filter(t=>t.entry===e);if(e.primary.options.mode!==e.applied){for(const e of t)this._setSuppressed(e,!1);return}if("common"===this._baseline&&e.primary.options.mode===e.applied){const i=this._visiblePrimary(),r=this._commonAnchor(e,i);for(const e of t){const t=r&&e.values.get(r.time)?.close;this._setSuppressed(e,!t||!Number.isFinite(t)||t<=0)}if(null===r)return;e.primary.setBaseline(r.close);const s=e.primary.priceRange();for(const n of t){const t=n.values.get(r.time)?.close;if(n.scale.setBaseline(t&&t>0?t:null),!e.primary.autoScale||!t||t<=0||!this._visible(n))continue;const o=se(n.type),a=this._record(n)?.style??n.style;let l=1/0,h=-1/0;for(const e of i){const t=n.values.get(e.time);if(!t)continue;const i=o.extents(t,a);Number.isFinite(i.min)&&Number.isFinite(i.max)&&(l=Math.min(l,i.min),h=Math.max(h,i.max))}if(!(l<=h))continue;const c=g(l,h,e.primary.options.marginTop,e.primary.options.marginBottom),d=r.close/t;s.min=Math.min(s.min,c.min*d),s.max=Math.max(s.max,c.max*d)}e.primary.autoScale&&e.primary.setPriceRange(s)}const i=e.primary.baseline;if(null===i||!Number.isFinite(i)||i<=0||!e.primary.scaled)return;const r=e.primary.priceRange();for(const t of this._items.values()){if(t.entry!==e)continue;const s=t.scale.baseline;if(null===s||!Number.isFinite(s)||s<=0)continue;const n=s/i;t.appliedInverted=e.primary.options.inverted,t.scale.setOptions({inverted:t.appliedInverted}),t.scale.setPriceRange({min:r.min*n,max:r.max*n})}}_primaryBars(){return this._chart.primaryBars?.()??this._chart.primarySeries()?.getData()??[]}_record(e){return this._chart.panes()[e.entry.paneIndex]?.series().find(t=>t.scaleId===e.scaleId)}_visible(e){return!1!==this._record(e)?.style?.visible}_visiblePrimary(){const e=this._primaryBars(),t=this._chart.getVisibleLogicalRange?.();if(!t)return e;const i=Math.max(0,Math.floor(t.from)),r=Math.min(this._chart.dataLayer.length-1,Math.ceil(t.to));if(i>r)return[];const s=this._chart.dataLayer.indexToTime?.(i)??e[i]?.time,n=this._chart.dataLayer.indexToTime?.(r)??e[r]?.time;if(void 0===s||void 0===n)return[];let o=0,a=e.length;for(;o<a;){const t=o+a>>>1;e[t].time<s?o=t+1:a=t}let l=o;for(;l<e.length&&e[l].time<=n;)l++;return e.slice(o,l)}_commonAnchor(e,t){const i=Array.from(this._items.values()).filter(t=>t.entry===e&&this._visible(t));return i.length?t.find(e=>Number.isFinite(e.close)&&e.close>0&&i.every(t=>{const i=t.values.get(e.time)?.close;return void 0!==i&&Number.isFinite(i)&&i>0}))??null:null}_setSuppressed(e,t){t!==e.suppressed&&(e.suppressed=t,this._write(e))}_write(e){e.series.setData(e.suppressed?e.items.map(e=>({time:e.time})):e.items)}_align(e,t){const i=is(this._chart),r=os(i?t.filter(e=>e.time<=i.time):t,i?.forming?e.bars.filter(e=>e.time!==i.time):e.bars);e.alignment=r.alignment,e.items=r.items,e.values=new Map(r.items.map(e=>{const t=Ti(e);return[t.time,t]})),this._write(e)}_repaint(){for(const e of this._items.values())e.series.applyOptions({})}}const ls=new WeakMap;function hs(e,t){let i=ls.get(e);return void 0===i&&(i=new as(e,t),ls.set(e,i)),i}function cs(e,t){return hs(e).add(t)}const ds=["time","open","high","low","close","volume","oi"],us=e=>"number"==typeof e&&Number.isFinite(e)?String(e):"",ps=e=>/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e;function _s(e,t={}){const i=e.primaryBars(),r=!1===t.indicators?[]:e.indicators().flatMap(e=>{const t=e.values();return ti(e.indicatorId).plots.map(i=>({name:`indicator:${e.id}:${i.key}`,values:t[i.key]}))}),s=t.comparisons??function(e){return ls.get(e)?.list()??[]}(e),n=[[...ds,...r.map(e=>e.name),...s.map((e,t)=>`comparison:${t+1}:${e.symbol}:close`)].map(ps).join(",")];for(let e=0;e<i.length;e++){const t=i[e];n.push([...ds.map(e=>us(t[e])),...r.map(t=>us(t.values?.[e])),...s.map(e=>us(e.barAt(t.time)?.close))].join(","))}return n.join("\r\n")+"\r\n"}const bs=Object.freeze([]),fs=(e,t)=>e.length===t.length&&e.every((e,i)=>{const r=t[i];return e.id===r.id&&e.name===r.name&&e.kind===r.kind&&e.paneIndex===r.paneIndex&&e.visible===r.visible&&e.locked===r.locked&&e.selected===r.selected&&e.dataStatus?.state===r.dataStatus?.state&&("error"!==e.dataStatus?.state||"error"===r.dataStatus?.state&&e.dataStatus.error===r.dataStatus.error)&&Object.keys(e.capabilities).every(t=>e.capabilities[t]===r.capabilities[t])});class ms{constructor(e,t={}){if(Object.defineProperty(this,"_chart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_off",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_providers",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_entries",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_rows",{enumerable:!0,configurable:!0,writable:!0,value:bs}),Object.defineProperty(this,"_selected",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_refreshing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_pending",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._chart=e,this._options=t,e.isDestroyed)return void(this._destroyed=!0);for(const t of["objects:change","indicatorRemoved","paneRemoved","paneMoved","data:context","indicator:data-status","drawing:change","drawing:select"])this._off.push(e.on(t,()=>this.refresh()));let i=e.dataLayer.length>0;this._off.push(e.on("data:range",()=>{const t=e.dataLayer.length>0;t!==i&&(i=t,this.refresh())})),this._off.push(e.on("destroy",()=>this.destroy())),this.refresh()}list(){return this._refreshing||this.refresh(),this._rows}get(e){return this._refreshing||this.refresh(),this._entries.get(e)?.row}subscribe(e){this.refresh(),this._destroyed||this._listeners.add(e);try{e(this._rows)}catch{}return()=>{this._listeners.delete(e)}}register(e){if(this._destroyed)return()=>{};if("string"!=typeof e.id||""===e.id.trim())throw new Error("An object provider needs an id");const t="custom:"+e.id;if(this._providers.has(t))throw new Error("Object provider already registered: "+e.id);const i={provider:e};this._providers.set(t,i);try{i.off=e.subscribe?.(()=>this.refresh())}catch(e){throw this._providers.get(t)===i&&this._providers.delete(t),this.refresh(),e}if(this._destroyed||this._providers.get(t)!==i){try{i.off?.()}catch{}return()=>{}}return this.refresh(),()=>{if(this._providers.get(t)===i){this._providers.delete(t);try{i.off?.()}catch{}this.refresh()}}}refresh(){if(!this._destroyed)if(this._refreshing)this._pending=!0;else{this._refreshing=!0;try{do{this._pending=!1;const e=this._read();if(this._destroyed)break;this._entries=e,null===this._selected||e.has(this._selected)||(this._selected=null);const t=Object.freeze([...e.values()].map(e=>e.row));if(!fs(t,this._rows)){this._rows=t;for(const e of[...this._listeners]){if(this._destroyed)break;try{e(t)}catch{}}}}while(this._pending&&!this._destroyed)}finally{this._refreshing=!1}}}select(e,t=!1){if(this._destroyed)return!1;if(null===e)return this._selected=null,this._options.drawings?.select(null),this.refresh(),!0;const i=this.get(e);if(!i?.capabilities.select)return!1;try{return this._selected="drawing"===i.kind?null:e,e.startsWith("drawing:")?this._options.drawings?.select(i.sourceId,t):(this._options.drawings?.select(null),this._entries.get(e)?.actions.select?.()),this.refresh(),!0}catch{return this.refresh(),!1}}setVisible(e,t){return this._act(e,"visibility",e=>e.setVisible(t))}setLocked(e,t){return this._act(e,"lock",e=>e.setLocked(t))}remove(e){return this._act(e,"remove",e=>e.remove())}openSettings(e){return this._act(e,"settings",e=>e.openSettings())}focus(e){return this._act(e,"focus",e=>e.focus())}_act(e,t,i){const r=this.get(e);if(this._destroyed||!r?.capabilities[t])return!1;try{return i(this._entries.get(e).actions),this.refresh(),!0}catch{return this.refresh(),!1}}_read(){const e=new Map,t=this._options.drawings,i=t?.selection()??[];i.length>0&&(this._selected=null);const r=(t,i,r,s)=>{const n=Object.freeze({select:"function"==typeof s.select,visibility:"function"==typeof s.setVisible,lock:"function"==typeof s.setLocked,remove:"function"==typeof s.remove,settings:"function"==typeof s.openSettings,focus:"function"==typeof s.focus}),o=Object.freeze({id:t,sourceId:i,kind:r.kind,name:r.name,paneIndex:r.paneIndex??0,visible:!1!==r.visible,locked:r.locked,selected:!0===r.selected||this._selected===t,dataStatus:r.dataStatus?Object.freeze({...r.dataStatus}):void 0,capabilities:n});e.set(t,{row:o,actions:s})},s=e=>this._options.onSettings?{openSettings:()=>{const t=this.get(e);t&&this._options.onSettings(t)}}:{},n=this._chart;if(null!==n.primarySeries()){const e=n.getDataContext();r("source:primary","primary",{kind:"source",name:e?.symbol||"Price",visible:!1!==n.primarySeriesInfo()?.style.visible},s("source:primary"))}for(const e of n.indicators()){const t="indicator:"+e.id;r(t,e.id,{kind:"indicator",name:e.name,paneIndex:e.paneIndex,visible:e.visible(),dataStatus:e.dataStatus()??void 0},{select:()=>{},setVisible:t=>e.setVisible(t),remove:()=>{n.removeIndicator(e.id)},...s(t)})}if(t)for(const e of t.drawings()){const o="drawing:"+e.id,a=n.dataLayer.length>0&&e.points.length>0&&e.points.every(e=>Number.isFinite(e.time)&&Number.isFinite(e.price))&&void 0!==n.panes()[e.paneIndex];r(o,e.id,{kind:"drawing",name:e.tool.replace(/-/g," ").replace(/^./,e=>e.toUpperCase()),paneIndex:e.paneIndex,visible:!1!==e.visible,locked:!0===e.locked,selected:i.includes(e.id)},{select:()=>t.select(e.id),setVisible:i=>t.update(e.id,{visible:i}),setLocked:i=>t.update(e.id,{locked:i}),remove:()=>{t.remove(e.id)},...a?{focus:()=>this._focusDrawing(e)}:{},...s(o)})}for(const[e,{provider:t}]of this._providers)try{const i=t.get();if(!i||"string"!=typeof i.name||!["source","indicator","drawing","profile"].includes(i.kind))continue;r(e,t.id,i,t)}catch{}return e}_focusDrawing(e){const t=this._chart,i=e.points.map(e=>t.dataLayer.timeToIndexFloat(e.time));if(!i.every(Number.isFinite))return;const r=Math.min(...i),s=Math.max(...i),n=t.getVisibleLogicalRange(),o=Math.max(n.to-n.from,1.2*(s-r),10),a=t.panes()[e.paneIndex].readoutScale(),l=e.points.map(e=>e.price),h=Math.min(...l),c=Math.max(...l),d=Math.max(.15*(c-h),.001*Math.abs(c),a.options.minMove);a.setAutoScale(!1),a.setPriceRange({min:h-d,max:c+d});const u=t.maximizedPane();null!==u&&u!==e.paneIndex&&t.maximizePane(u),t.setVisibleLogicalRange({from:(r+s-o)/2,to:(r+s+o)/2})}destroy(){if(this._destroyed)return;this._destroyed=!0;for(const e of this._off.splice(0))e();const e=[...this._providers.values()];this._providers.clear(),this._entries.clear(),this._rows=bs,this._selected=null;for(const{off:t}of e)try{t?.()}catch{}const t=[...this._listeners];this._listeners.clear();for(const e of t)try{e(bs)}catch{}}}const gs=new Set([..."precision priceLineVisible lastValueVisible colorByPreviousClose upColor downColor bodyVisible borderUpColor borderDownColor borderVisible wickUpColor wickDownColor wickVisible topColor bottomColor closeColor color lineWidth lineStyle areaTopColor areaBottomColor".split(" ").map(e=>`symbol.${e}`),..."titleMode title logo marketStatus chartValues barChange volume openInterest lastDayChange lastValueLabel background backgroundColor backgroundOpacity".split(" ").map(e=>`statusLine.${e}`),..."visible color opacity fontSize".split(" ").map(e=>`watermark.${e}`),..."mode autoScale inverted".split(" ").map(e=>`scales.${e}`),"axisChrome.sessionClock","axisChrome.barCountdown",..."grid.vertLines grid.vertColor grid.vertStyle grid.horzLines grid.horzColor grid.horzStyle grid.lineWidth grid.spacing crosshairMode crosshairSnapToBar crosshair.color crosshair.style crosshair.width scales.textColor scales.fontSize scales.lineColor margins.top margins.bottom".split(" ").map(e=>`canvas.${e}`)]);function vs(e){const t={};for(const[i,r]of Object.entries(e))gs.has(i)&&("string"==typeof r||"boolean"==typeof r||"number"==typeof r&&Number.isFinite(r))&&(t[i]=r);return t}function ys(e,t,i,r,s,n){return{input:{key:e,type:"boolean",label:t,default:r,group:i},fields:[{key:e,read:s,write:(e,t)=>n(e,!0===t)}]}}function ws(e,t,i,r,s,n){return{input:{key:e,type:"color",label:t,default:r,group:i},fields:[{key:e,read:s,write:(e,t)=>n(e,String(t))}]}}function xs(e,t,i,r,s,n,o){return{input:{key:e,type:"number",label:t,default:r,min:s.min,max:s.max,step:s.step,group:i},fields:[{key:e,read:n,write:(e,t)=>o(e,Number(t))}]}}function Ps(e,t,i,r,s,n,o,a){return{input:{key:e,type:"select",label:t,default:r,options:s,group:i,tooltip:a},fields:[{key:e,read:n,write:(e,t)=>o(e,String(t))}]}}function Ss(e,t,i,r,s,n){const o={key:e,type:"colorPair",label:t,group:i,up:{key:r.key,label:r.label,default:r.def},down:{key:s.key,label:s.label,default:s.def}},a=[{key:r.key,read:r.get,write:(e,t)=>r.set(e,String(t))},{key:s.key,read:s.get,write:(e,t)=>s.set(e,String(t))}];return void 0!==n&&(o.enabled={key:n.key,default:n.def},a.unshift({key:n.key,read:n.get,write:(e,t)=>n.set(e,!0===t)})),{input:o,fields:a}}const Os=[{label:"Solid",value:"solid"},{label:"Dashed",value:"dashed"},{label:"Dotted",value:"dotted"}],ks=[{label:"Default",value:"default"},...Array.from({length:9},(e,t)=>({label:String(t),value:String(t)}))],Ms=e=>e.primarySeriesInfo()?.style??{},Ts=(e,t)=>{e.primarySeries()?.applyOptions(t)},Cs=(e,t,i)=>Ts(e,{[t]:i});function Is(e,t,i,r,s,n){const o=e=>({key:`symbol.${e.key}`,label:e.label,def:e.def,get:t=>Ms(t)[e.key]??e.def,set:(t,i)=>Cs(t,e.key,i)}),a=void 0===n?void 0:{key:`symbol.${n.key}`,def:!0,get:e=>!1!==Ms(e)[n.key],set:(e,t)=>Cs(e,n.key,t)};return Ss(e,t,i,o(r),o(s),a)}const js=e=>Math.round(1e3*e)/10;const As=e=>ys("symbol.colorByPreviousClose","Color from previous close",e,!1,e=>!0===Ms(e).colorByPreviousClose,(e,t)=>Ts(e,{colorByPreviousClose:t}));function Ls(e){const t=e.theme(),i=e.primarySeriesInfo()?.type,r=[];if(void 0===i)return[];if("candlestick"===i||"hollow-candle"===i||"volume-candle"===i)r.push(Is("symbol.body","Body","Candles",{key:"upColor",label:"Up",def:t.upColor},{key:"downColor",label:"Down",def:t.downColor},{key:"bodyVisible"}),Is("symbol.borders","Borders","Candles",{key:"borderUpColor",label:"Up",def:t.upColor},{key:"borderDownColor",label:"Down",def:t.downColor},{key:"borderVisible"}),Is("symbol.wick","Wick","Candles",{key:"wickUpColor",label:"Up",def:t.wickUpColor},{key:"wickDownColor",label:"Down",def:t.wickDownColor},{key:"wickVisible"}),As("Candles"));else if("bar"===i||"high-low"===i||"column"===i){const e="column"===i?"Columns":"Bars";r.push(Is("symbol.body","column"===i?"Columns":"Bars",e,{key:"upColor",label:"Up",def:t.upColor},{key:"downColor",label:"Down",def:t.downColor})),"column"!==i&&r.push(As(e))}else"baseline"===i?r.push(Is("symbol.baseline","Line","Baseline",{key:"topColor",label:"Above",def:t.baselineTopLine},{key:"bottomColor",label:"Below",def:t.baselineBottomLine})):"hlc-area"===i?r.push(ws("symbol.closeColor","Close line","Line",t.lineColor,e=>Ms(e).closeColor??t.lineColor,(e,t)=>Ts(e,{closeColor:t}))):r.push(ws("symbol.color","Line","Line",t.lineColor,e=>Ms(e).color??t.lineColor,(e,t)=>Ts(e,{color:t}))),"histogram"!==i&&r.push(xs("symbol.lineWidth","Thickness","Line",1.5,{min:.5,max:8,step:.5},e=>Ms(e).lineWidth??1.5,(e,t)=>Ts(e,{lineWidth:t}))),"line"!==i&&"line-markers"!==i&&"step"!==i||r.push(Ps("symbol.lineStyle","Line style","Line","solid",Os,e=>Ms(e).lineStyle??"solid",(e,t)=>Ts(e,{lineStyle:t}))),"area"===i?r.push(Is("symbol.fill","Fill","Line",{key:"areaTopColor",label:"Top",def:t.areaTopColor},{key:"areaBottomColor",label:"Bottom",def:t.areaBottomColor})):"baseline"===i?r.push(Is("symbol.fill","Fill","Baseline",{key:"areaTopColor",label:"Above",def:t.baselineTopFill},{key:"areaBottomColor",label:"Below",def:t.baselineBottomFill})):"hlc-area"===i&&r.push(ws("symbol.areaTopColor","Band","Line",t.areaTopColor,e=>Ms(e).areaTopColor??t.areaTopColor,(e,t)=>Ts(e,{areaTopColor:t})));return[...r,Ps("symbol.precision","Precision","Values","default",ks,e=>{const t=Ms(e).precision;return void 0===t?"default":String(t)},(e,t)=>Ts(e,{precision:"default"===t?void 0:Number(t)})),ys("symbol.priceLineVisible","Price line","Values",!0,e=>!1!==Ms(e).priceLineVisible,(e,t)=>Ts(e,{priceLineVisible:t})),ys("symbol.lastValueVisible","Last value label","Values",!0,e=>!1!==Ms(e).lastValueVisible,(e,t)=>Ts(e,{lastValueVisible:t}))]}const zs=[{label:"Symbol",value:"symbol"},{label:"Description",value:"description"},{label:"Ticker",value:"ticker"}];function Fs(e,t,i){return ys(`statusLine.${e}`,t,i,!0,t=>!1!==t.statusLineOptions()[e],(t,i)=>t.setStatusLineOptions({[e]:i}))}function Bs(e){const t=e.theme();return[Fs("logo","Logo","Show"),Fs("title","Title","Show"),Ps("statusLine.titleMode","Title shows","Show","symbol",zs,e=>e.statusLineOptions().titleMode??"symbol",(e,t)=>e.setStatusLineOptions({titleMode:t})),Fs("marketStatus","Session state","Show"),Fs("chartValues","Open, high, low, close","Show"),Fs("barChange","Bar change","Show"),Fs("volume","Volume","Show"),ys("statusLine.openInterest","Open interest","Show",!1,e=>!0===e.statusLineOptions().openInterest,(e,t)=>e.setStatusLineOptions({openInterest:t})),Fs("lastDayChange","Change since previous close","Show"),Fs("lastValueLabel","Indicator values","Show"),ys("statusLine.background","Background","Background",!1,e=>!0===e.statusLineOptions().background,(e,t)=>e.setStatusLineOptions({background:t})),ws("statusLine.backgroundColor","Color","Background",t.background,e=>e.statusLineOptions().backgroundColor??t.background,(e,t)=>e.setStatusLineOptions({backgroundColor:t})),xs("statusLine.backgroundOpacity","Opacity","Background",.8,{min:0,max:1,step:.05},e=>e.statusLineOptions().backgroundOpacity??.8,(e,t)=>e.setStatusLineOptions({backgroundOpacity:t}))]}const $s=[{label:"Regular",value:"linear"},{label:"Logarithmic",value:"logarithmic"},{label:"Percent",value:"percentage"},{label:"Indexed to 100",value:"indexed-to-100"}],Ns=["UTC","Europe/London","Europe/Berlin","Europe/Moscow","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Hong_Kong","Asia/Tokyo","Australia/Sydney","America/Sao_Paulo","America/New_York","America/Chicago","America/Los_Angeles"];function Ds(e){const t=e.timezone();return(Ns.includes(t)?Ns:[...Ns,t]).map(e=>({label:e,value:e}))}function Rs(e){const t=[Ps("navigation.mousePan","Mouse drag","Navigation","both",[{label:"Horizontal only",value:"horizontal"},{label:"Time and price",value:"both"}],e=>e.navigationOptions().mousePan,(e,t)=>e.setNavigationOptions({mousePan:t})),xs("navigation.defaultVisibleBars","Default visible bars (0 = all)","Navigation",0,{min:0,max:1e5,step:1},e=>e.navigationOptions().defaultVisibleBars,(e,t)=>e.setNavigationOptions({defaultVisibleBars:t})),Ps("scales.mode","Scale","Price scale","linear",$s,e=>e.priceScaleOptions().mode,(e,t)=>e.setPriceScaleOptions({mode:t}),"Regular plots the price. Logarithmic gives equal space to equal percentage moves. Percent and Indexed to 100 both rebase to the left edge of the visible range, the first as a change from it, the second as a level starting at 100."),ys("scales.autoScale","Auto (fits data to screen)","Price scale",!0,e=>e.panes()[0].priceScale.autoScale,(e,t)=>e.setAutoScale(t)),ys("scales.inverted","Invert scale","Price scale",!1,e=>e.priceScaleOptions().inverted,(e,t)=>e.setPriceScaleOptions({inverted:t})),Ps("time.timezone","Timezone","Time axis",Se,Ds(e),e=>e.timezone(),(e,t)=>{Te(t)&&e.setTimezone(t)},"The calendar the axis and crosshair label in, and the one every session-anchored study resets on. Changing it moves VWAP and pivot values, not only the labels."),ys("axisChrome.sessionClock","Corner clock","Axis chrome",!1,e=>void 0!==e.axisChromeOptions().sessionClock&&!1!==e.axisChromeOptions().sessionClock,(e,t)=>e.setAxisChromeOptions({sessionClock:t}))];return function(e){const t=e.primarySeriesInfo()?.type;return void 0!==t&&se(t).isPriceSeries}(e)&&t.push(ys("axisChrome.barCountdown","Countdown to bar close","Axis chrome",!1,e=>!0===e.axisChromeOptions().barCountdown,(e,t)=>e.setAxisChromeOptions({barCountdown:t}))),t}const Es=[{label:"Cross",value:"normal"},{label:"Magnet",value:"magnet"}];function Ws(e){const t=e.theme(),i=e=>e.gridOptions(),r=e=>e.canvasOptions().crosshair??{},s=e=>e.canvasOptions().scales??{};return[ys("watermark.visible","Show watermark","Watermark",!1,e=>e.watermarkOptions().visible??!1,(e,t)=>e.setWatermarkOptions({visible:t})),{input:{key:"watermark.text",type:"text",label:"Text (blank uses symbol and interval)",group:"Watermark",default:""},fields:[{key:"watermark.text",read:e=>e.watermarkOptions().text??"",write:(e,t)=>e.setWatermarkOptions({text:String(t)})}]},ws("watermark.color","Color","Watermark","#9aa4b2",e=>e.watermarkOptions().color??"#9aa4b2",(e,t)=>e.setWatermarkOptions({color:t})),xs("watermark.opacity","Opacity","Watermark",.08,{min:0,max:1,step:.01},e=>e.watermarkOptions().opacity??.08,(e,t)=>e.setWatermarkOptions({opacity:t})),xs("watermark.fontSize","Text size","Watermark",64,{min:10,max:200,step:1},e=>e.watermarkOptions().fontSize??64,(e,t)=>e.setWatermarkOptions({fontSize:t})),ys("canvas.grid.vertLines","Vert grid lines","Grid",!0,e=>e.gridOptions().vertLines,(e,t)=>e.setGridOptions({vertLines:t})),ws("canvas.grid.vertColor","Vert color","Grid",t.grid,e=>i(e)?.vertColor??t.grid,(e,t)=>e.setGridOptions({vertColor:t})),Ps("canvas.grid.vertStyle","Vert style","Grid",t.gridStyle??"solid",Os,e=>i(e)?.vertStyle??t.gridStyle??"solid",(e,t)=>e.setGridOptions({vertStyle:t})),ys("canvas.grid.horzLines","Horz grid lines","Grid",!0,e=>e.gridOptions().horzLines,(e,t)=>e.setGridOptions({horzLines:t})),ws("canvas.grid.horzColor","Horz color","Grid",t.grid,e=>i(e)?.horzColor??t.grid,(e,t)=>e.setGridOptions({horzColor:t})),Ps("canvas.grid.horzStyle","Horz style","Grid",t.gridStyle??"solid",Os,e=>i(e)?.horzStyle??t.gridStyle??"solid",(e,t)=>e.setGridOptions({horzStyle:t})),xs("canvas.grid.lineWidth","Width","Grid",1,{min:1,max:4,step:1},e=>i(e)?.lineWidth??1,(e,t)=>e.setGridOptions({lineWidth:t})),xs("canvas.grid.spacing","Spacing","Grid",60,{min:20,max:200,step:10},e=>i(e)?.spacing??60,(e,t)=>e.setGridOptions({spacing:t})),Ps("canvas.crosshairMode","Mode","Crosshair","normal",Es,e=>e.crosshairMode(),(e,t)=>e.applyOptions({crosshairMode:"magnet"===t?"magnet":"normal"})),ys("canvas.crosshairSnapToBar","Snap to candle center","Crosshair",!1,e=>e.crosshairSnapToBar(),(e,t)=>e.applyOptions({crosshairSnapToBar:t})),ws("canvas.crosshair.color","Color","Crosshair",t.crosshair,e=>r(e).color??t.crosshair,(e,t)=>e.setCanvasOptions({crosshair:{color:t}})),Ps("canvas.crosshair.style","Style","Crosshair",t.crosshairStyle??"dashed",Os,e=>r(e).style??t.crosshairStyle??"dashed",(e,t)=>e.setCanvasOptions({crosshair:{style:t}})),xs("canvas.crosshair.width","Width","Crosshair",1,{min:1,max:4,step:1},e=>r(e).width??t.crosshairWidth??1,(e,t)=>e.setCanvasOptions({crosshair:{width:t}})),ws("canvas.scales.textColor","Text color","Scale text",t.axisText,e=>s(e).textColor??t.axisText,(e,t)=>e.setCanvasOptions({scales:{textColor:t}})),xs("canvas.scales.fontSize","Text size","Scale text",t.axisFontSize??11,{min:10,max:14,step:1},e=>s(e).fontSize??t.axisFontSize??11,(e,t)=>e.setCanvasOptions({scales:{fontSize:t}})),ws("canvas.scales.lineColor","Lines color","Scale text",t.axisLine,e=>s(e).lineColor??t.axisLine,(e,t)=>e.setCanvasOptions({scales:{lineColor:t}})),xs("canvas.margins.top","Top margin %","Plot margins",10,{min:0,max:49,step:1},e=>js(e.priceScaleOptions().marginTop),(e,t)=>e.setCanvasOptions({margins:{top:t}})),xs("canvas.margins.bottom","Bottom margin %","Plot margins",10,{min:0,max:49,step:1},e=>js(e.priceScaleOptions().marginBottom),(e,t)=>e.setCanvasOptions({margins:{bottom:t}}))]}function qs(e){const t=(t,i,r)=>function(e,t,i,r){return{key:`trading.${t}`,label:r,def:e.tradingSettings()[i],get:e=>e.tradingSettings()[i],set:(e,i)=>e.setTradingSettings({[t]:i})}}(e,t,i,r);return[Ss("trading.positions","Position","Positions",t("longColor","long","Long"),t("shortColor","short","Short")),ws("trading.orderColor","Order","Orders",e.tradingSettings().order,e=>e.tradingSettings().order,(e,t)=>e.setTradingSettings({orderColor:t})),Ss("trading.bracket","Bracket","Orders",t("tpColor","tp","Take profit"),t("slColor","sl","Stop loss")),Ss("trading.executions","Execution","Executions",t("buyColor","buy","Buy"),t("sellColor","sell","Sell"))]}function Hs(e){return[{id:"price",label:"Price",controls:Ls(e)},{id:"readout",label:"Readout",controls:Bs(e)},{id:"axes",label:"Axes",controls:Rs(e)},{id:"appearance",label:"Appearance",controls:Ws(e)},{id:"trading",label:"Trading",controls:qs(e)}]}function Vs(e){return Hs(e).map(e=>({id:e.id,label:e.label,inputs:e.controls.map(e=>e.input)}))}function Gs(e){const t={};for(const i of Hs(e))for(const r of i.controls)for(const i of r.fields)t[i.key]=i.read(e);return t}function Us(e,t){const i=new Map,r={};for(const t of Hs(e))for(const e of t.controls)for(const t of e.fields)i.set(t.key,t);for(const s of Object.keys(t)){const n=t[s];if(void 0===n)continue;const o=i.get(s);o&&(o.write(e,n),r[s]=o.read(e))}const s=vs(r);Object.keys(s).length&&e.emit("style:change",s)}function Ys(e,t){return e.map((i,r)=>{const s=i.time,n=t(i,r),o=e[r+1]?.time;if(!Number.isFinite(s)||!Number.isFinite(n)||n<s||r>0&&s<=e[r-1].time||void 0!==o&&n>o)throw new Error("openalgo-charts: replay time must be finite, ordered and within its candle interval");return n})}class Ks{constructor(e,t,i){if(Object.defineProperty(this,"points",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"ends",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.ends=Ys(e,i.barEndTime),t.length&&!i.subBarEndTime)throw new Error("openalgo-charts: replay timing needs subBarEndTime");const r=t.length?Ys(t,i.subBarEndTime):[];let s=0;for(let i=0;i<e.length;i++){const n=e[i],o=this.ends[i],a=this.points.length;for(;s<t.length&&t[s].time<n.time;)s++;let l,h=n.time,c=!1;for(;s<t.length&&t[s].time<o;){const e=t[s],a=r[s++];if((e.time!==h||a>o)&&(c=!0),c)continue;if(h=a,l?(l.high=Math.max(l.high,e.high),l.low=Math.min(l.low,e.low),l.close=e.close,l.volume=(l.volume??0)+(e.volume??0),void 0!==e.oi&&(l.oi=e.oi)):l={...e,time:n.time},a>=o)continue;const d=this.points[this.points.length-1];d?.index===i&&d.time===a?d.bar={...l}:this.points.push({time:a,index:i,subIndex:0,subSteps:0,bar:{...l}})}this.points.push({time:o,index:i,subIndex:0,subSteps:0,bar:n});const d=this.points.length-a;this.steps[i]=d;for(let e=a;e<this.points.length;e++)this.points[e].subIndex=e-a,this.points[e].subSteps=d}}at(e){let t=0,i=this.points.length;for(;t<i;){const r=t+i>>>1;this.points[r].time<=e?t=r+1:i=r}return t-1}}const Xs=(e,t)=>{const i=setInterval(e,t);return()=>clearInterval(i)};function Js(e,t){let i=0,r=e.length;for(;i<r;){const s=i+r>>1;e[s].time<=t?i=s+1:r=s}return i}function Zs(e,t,i,r){const s=e[t];let n=s.high,o=s.low,a=s.volume??0,l=s.oi;for(let r=t+1;r<=i;r++){const t=e[r];t.high>n&&(n=t.high),t.low<o&&(o=t.low),a+=t.volume??0,void 0!==t.oi&&(l=t.oi)}return{time:r,open:s.open,high:n,low:o,close:e[i].close,volume:a,...void 0===l?{}:{oi:l}}}class Qs{constructor(e,t={}){Object.defineProperty(this,"_chart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_series",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_bars",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_restore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_view",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_onFrame",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schedule",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_barMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_startIndex",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timeline",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_startTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_time",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pointIndex",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"_subBars",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subCount",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_intra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_speed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_index",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sub",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_playing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_active",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_cancel",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_interval",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastAdvance",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_tick",{enumerable:!0,configurable:!0,writable:!0,value:()=>{if(!this._playing)return;const e=this._now();let t=Math.floor((e-this._lastAdvance)/this._interval);t<=0||(t>10?(t=10,this._lastAdvance=e):this._lastAdvance+=t*this._interval,this._advance(t),this._atEnd()&&this._end())}}),this._chart=e;const i=t.series,r=void 0===i?[]:"setData"in i?[i]:[...i];if(0===r.length){const t=e.primarySeries?.()??null;if(null===t)throw new Error("openalgo-charts: replay needs a series to drive (pass options.series)");r.push(t)}this._series=r,this._restore=r.map(e=>e.getData()),this._bars=t.bars??this._restore[0],this._view={barSpacing:e.timeScale.barSpacing,rightOffset:e.timeScale.rightOffset},this._subBars=t.subBars??[],this._intra=this._subBars.length>0&&this._bars.length>0;const s=this._buildBuckets();if(this._subStart=s.start,this._subCount=s.count,this._startIndex=h(Math.floor(t.startIndex??0),0,Math.max(0,this._bars.length-1)),this._index=this._startIndex,this._timeline=t.timing?new Ks(this._bars,this._subBars,t.timing):null,!(void 0===t.startTime||this._timeline&&Number.isFinite(t.startTime)))throw new Error("openalgo-charts: replay start time must be finite and requires timing");this._startTime=t.startTime??this._timeline?.ends[this._startIndex]??null,this._time=this._startTime,this._timeline&&(this._index=-1);const n=t.barMs??1e3;this._barMs=n>0?n:1e3;const o=t.speed??1;this._speed=o>0?o:1,this._onFrame=t.onFrame??null,this._now=t.now??(()=>"undefined"!=typeof performance?performance.now():0),this._schedule=t.scheduler??Xs,!1!==t.autoStart&&(this._timeline?null!==this._startTime&&this.seekTime(this._startTime):this._apply(this._startIndex,this._steps(this._startIndex)-1))}_buildBuckets(){const e=this._bars.length,t=new Int32Array(e),i=new Int32Array(e);if(!this._intra)return{start:t,count:i};const r=this._subBars;let s=-1;for(let n=0;n<r.length;n++){const o=r[n].time;for(;s+1<e&&this._bars[s+1].time<=o;)s++,t[s]=n;s>=0&&i[s]++}return{start:t,count:i}}_steps(e){return this._timeline?this._timeline.steps[e]??1:this._intra?Math.max(1,this._subCount[e]):1}seek(e){if(this._timeline){const t=this._timeline.ends[h(Math.floor(e),0,Math.max(0,this._bars.length-1))];return void(void 0!==t&&this.seekTime(t))}this._apply(e,this._steps(h(Math.floor(e),0,Math.max(0,this._bars.length-1)))-1)}seekTime(e){if(!this._timeline)throw new Error("openalgo-charts: replay seekTime requires timing");if(!Number.isFinite(e))throw new Error("openalgo-charts: replay time must be finite");const t=this._timeline.at(e);if(this._time=e,this._active&&t===this._pointIndex)return;const i=!this._active,r=this._timeline.points[t];this._active=!0,this._pointIndex=t,this._index=r?.index??-1,this._sub=r?.subIndex??0;const s=this._bars.slice(0,this._index+1);r&&(s[this._index]=r.bar),this._write(s,!!r&&r.subIndex<r.subSteps-1,i)}time(){return this._timeline?this._time:this.state().bar?.time??null}timePoints(){if(!this._timeline)throw new Error("openalgo-charts: replay timePoints requires timing");return this._timeline.points.map(e=>e.time)}step(e=1){this._advance(e)}stepBack(e=1){this._advance(-e)}_advance(e){if(this._timeline){if(!Number.isFinite(e))throw new Error("openalgo-charts: replay step must be finite");const t=Math.trunc(e);if(0===t||t<0&&this._pointIndex<0)return;const i=h(this._pointIndex+t,0,this._timeline.points.length-1),r=this._timeline.points[i];return void(r&&this.seekTime(r.time))}if(!this._intra)return void this._apply(this._index+e,0);let t=this._index,i=this._sub;const r=this._bars.length-1;for(let s=0;s<Math.abs(e);s++)if(e>0)if(i+1<this._steps(t))i++;else{if(!(t<r))break;t++,i=0}else if(i>0)i--;else{if(!(t>0))break;t--,i=this._steps(t)-1}this._apply(t,i)}play(e={}){const t=e.speed;void 0!==t&&t>0&&(this._speed=t),0!==this._bars.length&&(this._timeline?null!==this._time&&this.seekTime(this._time):this._apply(this._index,this._sub),this._atEnd()?this._end():(this._stopTimer(),this._interval=this._barMs/this._speed,this._lastAdvance=this._now(),this._playing=!0,this._cancel=this._schedule(this._tick,this._interval),this._chart.emit("replay:play",this.state())))}pause(){this._playing&&(this._playing=!1,this._stopTimer(),this._chart.emit("replay:pause",this.state()))}stop(){if(this._playing=!1,this._stopTimer(),!this._active)return;if(this._active=!1,this._index=this._startIndex,this._sub=0,this._timeline){this._time=this._startTime,this._pointIndex=null===this._time?-1:this._timeline.at(this._time);const e=this._timeline.points[this._pointIndex];this._index=e?.index??-1,this._sub=e?.subIndex??0}ss(this._chart);for(let e=0;e<this._series.length;e++)this._series[e].setData(this._restore[e]);const e=this._chart.timeScale;e.setBarSpacing(this._view.barSpacing),e.setRightOffset(this._view.rightOffset),this._chart.emit("replay:stop",this.state())}state(){const e=this._bars.length,t=0===e?1:this._steps(this._index);let i=null;if(this._timeline)i=this._timeline.points[this._pointIndex]?.bar??null;else if(e>0&&(i=this._bars[this._index],this._intra&&this._sub<t-1&&this._subCount[this._index]>0)){const e=this._subStart[this._index];i=Zs(this._subBars,e,e+this._sub,i.time)}return{index:this._index,total:e,playing:this._playing,speed:this._speed,bar:i,subIndex:this._sub,subSteps:t}}_apply(e,t=0){const i=this._bars.length;if(0===i)return;const r=h(Math.floor(e),0,i-1),s=this._steps(r),n=h(Math.floor(t),0,s-1);if(this._active&&r===this._index&&n===this._sub)return;const o=!this._active;this._active=!0,this._index=r,this._sub=n;const a=this._bars.slice(0,r+1);if(this._intra&&n<s-1&&this._subCount[r]>0){const e=this._subStart[r];a[r]=Zs(this._subBars,e,e+n,this._bars[r].time)}const l=this._intra&&n<s-1;this._write(a,l,o)}_write(e,t,i){const r=e[e.length-1]?.time??Number.NEGATIVE_INFINITY;ss(this._chart,{time:r,forming:t}),this._series[0].setData(e);const s=t?e[e.length-2]?.time??Number.NEGATIVE_INFINITY:r;for(let e=1;e<this._series.length;e++){const t=this._restore[e];this._series[e].setData(t.slice(0,Js(t,s)))}i&&this._chart.emit("replay:start",this.state());const n=this.state();this._onFrame?.(n),this._chart.emit("replay:frame",n)}_atEnd(){if(this._timeline)return this._pointIndex>=this._timeline.points.length-1;const e=this._bars.length-1;return this._index>=e&&this._sub>=this._steps(e)-1}_end(){this.pause(),this._chart.emit("replay:end",this.state())}_stopTimer(){this._cancel?.(),this._cancel=null}}class en extends Qs{constructor(e,t,i){super(e,{...t,autoStart:!1}),Object.defineProperty(this,"_transport",{enumerable:!0,configurable:!0,writable:!0,value:i})}state(){return{...super.state(),...this._transport()}}}const tn=new WeakMap,rn=e=>new Error("openalgo-charts: replay group "+e);function sn(e,t){if(!Number.isFinite(e))throw rn(t+" must be finite")}function nn(e,t){if(sn(e,t),e<=0)throw rn(t+" must be positive")}function on(e,t){if(null===t)return-1;let i=0,r=e.length;for(;i<r;){const s=i+r>>>1;e[s]<=t?i=s+1:r=s}return i-1}class an{constructor(e,t={}){if(Object.defineProperty(this,"_members",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_activeIds",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_times",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_scope",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_focusedId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_time",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_startTime",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_active",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_playing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_busy",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_closing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_revision",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_speed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_barMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_scheduler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_onChange",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_cancel",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_clockRevision",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastAdvance",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_pending",{enumerable:!0,configurable:!0,writable:!0,value:[]}),!e.length)throw rn("needs at least one member");this._scope=t.scope??"focused",this._focusedId=t.focusedId??e[0].id,this._speed=t.speed??1,this._barMs=t.barMs??1e3,nn(this._speed,"speed"),nn(this._barMs,"barMs"),nn(this._barMs/this._speed,"clock interval"),void 0!==t.startTime&&sn(t.startTime,"start time"),this._now=t.now??(()=>performance.now()),this._scheduler=t.scheduler??((e,t)=>{const i=setInterval(e,Math.min(2147483647,Math.max(1,t)));return()=>clearInterval(i)}),this._onChange=t.onChange;const i=new Set,r=new Set;for(const t of e){if("string"!=typeof t.id||!t.id.trim()||i.has(t.id))throw rn("member id must be unique and nonempty");if(r.has(t.chart))throw rn("cannot drive the same chart twice");if(tn.has(t.chart))throw rn("chart already has a replay group owner");if(t.chart.isDestroyed)throw rn("cannot own a destroyed chart");if(is(t.chart))throw rn("chart already has active replay");if("function"!=typeof t.options?.timing?.barEndTime)throw rn("member needs explicit timing");i.add(t.id),r.add(t.chart)}this._validateScope(this._scope,this._focusedId,i);for(const t of e){const e={id:t.id,chart:t.chart,options:{...t.options,timing:{...t.options.timing}}};this._members.push({...e,controller:this._prepare(e),dead:!1})}this._execute(()=>{for(const e of this._members)tn.set(e.chart,this),e.dispose=e.chart.on?.("destroy",()=>this._chartGone(e));this._rebuildTimes(),this._startTime=t.startTime??this._times[0]??null,this._apply(this._startTime)})}state(){return{active:this._active,destroyed:this._destroyed,scope:this._scope,focusedId:this._focusedId,time:this._time,index:on(this._times,this._time),total:this._times.length,playing:this._playing,speed:this._speed,members:this._members.map(e=>({id:e.id,active:this._activeIds.has(e.id),state:e.controller.state()}))}}seekTime(e){if(sn(e,"time"),this._check(),this._active&&e===this._time)return;const t=this._prepareEntering();this._execute(()=>{this._install(t),this._apply(e)})}seek(e){sn(e,"index"),this._check();const t=this._prepareEntering();this._execute(()=>{this._install(t);const i=this._times[Math.max(0,Math.min(this._times.length-1,Math.floor(e)))];void 0===i||this._active&&this._time===i||this._apply(i)})}step(e=1){this._move(e)}stepBack(e=1){this._move(-e)}_move(e){sn(e,"step"),this._check();const t=Math.trunc(e);if(!t)return;const i=this._prepareEntering();this._execute(()=>{this._install(i);const e=on(this._times,this._time);if(t<0&&e<0)return;const r=this._times[Math.max(0,Math.min(this._times.length-1,e+t))];void 0===r||this._active&&this._time===r||this._apply(r)})}setScope(e,t=this._focusedId){if(this._check(),this._validateScope(e,t,new Set(this._members.map(e=>e.id))),e===this._scope&&t===this._focusedId)return;const i=this._prepareEntering(e,t);this._execute(()=>{this._scope=e,this._focusedId=t,this._install(i)||this._rebuildTimes(),this._apply(this._time??this._times[0]??null)})}play(e={}){const t=e.speed??this._speed;nn(t,"speed"),nn(this._barMs/t,"clock interval"),this._check();const i=this._prepareEntering();this._execute(()=>{if(this._install(i),this._active||this._apply(this._startTime??this._times[0]??null),!this._active||this._destroyed)return;if(this._speed=t,this._atEnd())return this._emit("replay:end"),void this._notify();this._clearClock(),this._lastAdvance=this._now(),sn(this._lastAdvance,"clock"),this._playing=!0;const e=++this._clockRevision,r=this._scheduler(()=>{e===this._clockRevision&&this._tick()},this._barMs/this._speed);this._playing&&!this._destroyed&&e===this._clockRevision?this._cancel=r:r(),this._emit("replay:play"),this._notify()})}pause(){this._check(),this._playing&&this._execute(()=>{this._clearClock(),this._emit("replay:pause"),this._notify()})}stop(){this._destroyed||this._closing||!this._active||this._execute(()=>{this._cleanup(!1),this._notify()})}destroy(){this._destroyed||this._closing||this._execute(()=>{this._cleanup(!0),this._notify()})}_validateScope(e,t,i){if("all"!==e&&"focused"!==e)throw rn("scope must be focused or all");if(!i.has(t))throw rn("focus must name a member")}_prepare(e){const t=e.options.onFrame;return new en(e.chart,{...e.options,onFrame:t?e=>this._pending.push({callback:t,state:e}):void 0},()=>({playing:this._playing&&this._activeIds.has(e.id),speed:this._speed}))}_prepareEntering(e=this._scope,t=this._focusedId){const i=new Map;for(const r of this._members)if(("all"===e||r.id===t)&&!this._activeIds.has(r.id)){if(r.dead||r.chart.isDestroyed)throw rn("cannot enter a destroyed chart");if(is(r.chart))throw rn("chart already has active replay");i.set(r,this._prepare(r))}return i}_install(e){if(!e.size)return!1;for(const[t,i]of e)t.controller=i;return this._rebuildTimes(),!0}_wanted(e){return"all"===this._scope||e.id===this._focusedId}_rebuildTimes(){const e=new Set;for(const t of this._members)if(this._wanted(t))for(const i of t.controller.timePoints())e.add(i);this._times=[...e].sort((e,t)=>e-t)}_check(){if(this._destroyed)throw rn("has been destroyed");if(this._busy)throw rn("cannot change transport during a member frame");if(this._members.some(e=>this._activeIds.has(e.id)&&e.chart.isDestroyed))throw this.destroy(),rn("active chart was destroyed")}_apply(e){const t=++this._revision,i=this._activeIds;this._busy=!0,this._pending=[],this._time=e,this._active=!0,this._activeIds=new Set(this._members.filter(e=>this._wanted(e)).map(e=>e.id));try{for(const e of this._members){if(t!==this._revision)return;i.has(e.id)&&!this._activeIds.has(e.id)&&e.controller.stop()}for(const i of this._members){if(t!==this._revision)return;this._activeIds.has(i.id)&&i.controller.seekTime(e??0)}}finally{this._busy=!1}const r=this._pending;this._pending=[];for(const e of r){if(t!==this._revision)return;e.callback(e.state)}t===this._revision&&(this._playing&&this._atEnd()?(this._clearClock(),this._emit("replay:pause"),this._emit("replay:end")):this._playing&&this._emit("replay:play",e=>!i.has(e.id)),t===this._revision&&this._notify())}_atEnd(){return!this._times.length||on(this._times,this._time)>=this._times.length-1}_tick(){this._playing&&this._execute(()=>{const e=this._now();sn(e,"clock");const t=this._barMs/this._speed;if(e<this._lastAdvance)return void(this._lastAdvance=e);let i=Math.floor((e-this._lastAdvance)/t);i<=0||(i>10?(i=10,this._lastAdvance=e):this._lastAdvance+=i*t,this._move(i))})}_clearClock(){this._playing=!1,this._clockRevision++;const e=this._cancel;this._cancel=null,e?.()}_emit(e,t=()=>!0){const i=this._revision;for(const r of this._members){if(i!==this._revision)return;this._activeIds.has(r.id)&&t(r)&&r.chart.emit(e,r.controller.state())}}_notify(){this._onChange?.(this.state())}_execute(e){try{e()}catch(e){try{this._cleanup(!0)}catch{}throw e}}_chartGone(e){e.dead=!0,this._closing||this._destroyed||(this._activeIds.has(e.id)||e.id===this._focusedId?this.destroy():this._execute(()=>{const t=this._busy;t||this._revision++,e.dispose?.(),tn.delete(e.chart),this._members=this._members.filter(t=>t!==e),this._rebuildTimes(),t||this._notify()}))}_cleanup(e){if(this._closing)return;this._closing=!0,this._revision++;const t=this._activeIds;let i;this._activeIds=new Set,this._active=!1,this._pending=[];const r=e=>{try{e()}catch(e){i??(i=e)}};r(()=>this._clearClock());for(const e of this._members)t.has(e.id)&&(e.dead||e.chart.isDestroyed?r(()=>ss(e.chart)):r(()=>e.controller.stop()));e||(e=void 0!==i||this._members.some(e=>e.dead&&(t.has(e.id)||e.id===this._focusedId)));for(const t of this._members)(e||t.dead)&&(r(()=>t.dispose?.()),tn.get(t.chart)===this&&tn.delete(t.chart));if(this._time=this._startTime,e?(this._destroyed=!0,this._members=[],this._times=[]):(this._members=this._members.filter(e=>!e.dead),this._rebuildTimes()),this._closing=!1,void 0!==i)throw i}}const ln=.55;class hn{constructor(){Object.defineProperty(this,"_index",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null})}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"top"}index(){return this._index}setIndex(e){e!==this._index&&(this._index=e,this._host?.requestUpdate())}draw(e,t){const i=this._index;if(null===i)return;const r=xt(t.theme,void 0,t.dpr);Pt(e,t.timeScale.indexToX(i),null,t.plotWidth,t.plotHeight,t.dpr,R(r.color,.55),r.width,r.dash)}}function cn(e,t,i="nearest"){if(!Number.isFinite(t)||0===e.length)return null;const r=e.indexToTime(0),s=e.indexToTime(e.length-1);if(void 0===r||void 0===s)return null;if(t<r||t>s)return null;const n=e.timeToIndex(t);if(void 0!==n)return n;if("hide"===i)return null;const o=Math.floor(e.timeToIndexFloat(t));return void 0===e.indexToTime(o)?null:Math.max(0,Math.min(o,e.length-1))}function dn(e,t,i){if(0===e.length||t.length<2)return null;const r=e.indexToTimeFloat(i.from),s=e.indexToTimeFloat(i.to);if(!Number.isFinite(r)||!Number.isFinite(s)||s<=r)return null;const n=t.timeToIndexFloat(r),o=t.timeToIndexFloat(s);return!Number.isFinite(n)||!Number.isFinite(o)||o<=n?null:{from:n,to:o}}const un={crosshair:!0,viewport:!0,symbol:!1,interval:!1,appearance:!1,whenMissing:"nearest"};function pn(e){return!0!==e.isDestroyed&&e.panes().length>0}function _n(e){return"string"==typeof e&&e.trim().length>0}class bn{constructor(e={}){Object.defineProperty(this,"_members",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_broadcasting",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_symbol",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_interval",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._options={...un,...e}}options(){return{...this._options}}setOptions(e){const t=this._options;if(this._options={...t,...e},t.crosshair&&!this._options.crosshair)for(const e of this._members)this._detachCrosshairs(e);!t.symbol&&this._options.symbol&&this._convergeSymbol(),!t.interval&&this._options.interval&&this._convergeInterval()}members(){return this._prune(),this._members.map(e=>e.chart)}has(e){return null!==this._find(e)}symbol(){return this._symbol}interval(){return this._interval}crosshairIndex(e){return this._find(e)?.crosshairs[0]?.index()??null}add(e,t={}){if(this._destroyed||!pn(e))return;const i=this._find(e);if(null!==i)return void 0!==t.symbol&&(i.symbol=t.symbol),void 0!==t.onSymbol&&(i.onSymbol=t.onSymbol),_n(t.interval)&&(i.interval=t.interval),void 0!==t.onInterval&&(i.onInterval=t.onInterval),void 0!==t.appearance&&(i.appearance=t.appearance),void(this._options.interval&&this._convergeInterval());const r={chart:e,appearance:t.appearance??null,symbol:t.symbol??null,onSymbol:t.onSymbol??null,interval:_n(t.interval)?t.interval:null,onInterval:t.onInterval??null,unsubscribe:[],crosshairs:[]};r.unsubscribe.push(e.on("crosshair:move",e=>this._onCrosshair(r,e)),e.on("pan",()=>this._onViewport(r)),e.on("zoom",()=>this._onViewport(r)),e.on("symbol",e=>this._onSymbolEvent(r,e)),e.on("style:change",()=>this.syncAppearance(e)),e.on("interval",e=>{const t="string"==typeof e?e:e?.interval;_n(t)&&this._applyInterval(r,t)}),e.on("destroy",()=>this._prune())),this._members.push(r),null===this._symbol&&null!==r.symbol&&(this._symbol=r.symbol),this._options.symbol&&this._convergeSymbol(),null===this._interval&&null!==r.interval&&(this._interval=r.interval),this._options.interval&&this._convergeInterval()}remove(e){const t=this._members.findIndex(t=>t.chart===e);t<0||(this._release(this._members[t]),this._members.splice(t,1))}setSymbol(e,t){const i=this._find(e);null!==i&&this._applySymbol(i,t)}setInterval(e,t){const i=this._find(e);null!==i&&_n(t)&&this._applyInterval(i,t)}syncAppearance(e){if(this._destroyed||this._broadcasting||!this._options.appearance||!pn(e))return;const t=this._find(e);if(null===t?.appearance||null===t)return;const i=vs(t.appearance.read());0!==Object.keys(i).length&&this._broadcast(t,e=>e.appearance?.apply({...i}))}destroy(){this._destroyed=!0;for(const e of this._members)this._release(e);this._members.length=0,this._symbol=null,this._interval=null}_onCrosshair(e,t){if(!this._options.crosshair)return;const i=t?.time??null;this._broadcast(e,e=>{const t=null===i?null:cn(e.chart.dataLayer,i,this._options.whenMissing);this._setCrosshair(e,t)},e=>{this._setCrosshair(e,null)})}_onViewport(e){if(!this._options.viewport)return;if(!pn(e.chart))return void this._prune();const t=e.chart.getVisibleLogicalRange(),i=e.chart.dataLayer;this._broadcast(e,e=>{const r=dn(i,e.chart.dataLayer,t);null!==r&&e.chart.setVisibleLogicalRange(r)})}_onSymbolEvent(e,t){const i="string"==typeof t?t:t?.symbol;"string"==typeof i&&0!==i.length&&this._applySymbol(e,i)}_applySymbol(e,t){e.symbol=t,this._symbol=t,this._options.symbol&&this._broadcast(e,e=>{e.symbol!==t&&(e.symbol=t,e.onSymbol?.(t,e.chart))})}_convergeSymbol(){const e=this._symbol;null!==e&&this._options.symbol&&this._broadcast(null,t=>{t.symbol!==e&&(t.symbol=e,t.onSymbol?.(e,t.chart))})}_applyInterval(e,t){this._broadcasting||this._destroyed||!pn(e.chart)||(e.interval=t,this._interval=t,this._options.interval&&this._broadcast(e,e=>this._followInterval(e,t)))}_followInterval(e,t){e.interval!==t&&null!==e.onInterval&&!1!==e.onInterval(t,e.chart)&&(e.interval=t)}_convergeInterval(){const e=this._interval;null!==e&&this._options.interval&&this._broadcast(null,t=>this._followInterval(t,e))}_broadcast(e,t,i){if(!this._broadcasting){this._broadcasting=!0;try{this._prune(),null!==e&&this._members.includes(e)&&i?.(e);for(const i of[...this._members])i!==e&&this._members.includes(i)&&pn(i.chart)&&t(i)}finally{this._broadcasting=!1}}}_prune(){for(let e=this._members.length-1;e>=0;e--)pn(this._members[e].chart)||this._members.splice(e,1)}_find(e){return this._members.find(t=>t.chart===e)??null}_release(e){for(const t of e.unsubscribe)t();e.unsubscribe.length=0,this._detachCrosshairs(e)}_setCrosshair(e,t){if(!pn(e.chart))return;const i=null===t?e.crosshairs.length:e.chart.panes().length;for(;e.crosshairs.length>i;){const t=e.crosshairs.pop();void 0!==t&&e.chart.removePrimitive(t)}for(;e.crosshairs.length<i;){const t=new hn;e.chart.addPrimitive(t,e.crosshairs.length),e.crosshairs.push(t)}for(const i of e.crosshairs)i.setIndex(t);e.chart.setLinkedCrosshairIndex?.(t)}_detachCrosshairs(e){if(pn(e.chart)){for(const t of e.crosshairs)e.chart.removePrimitive(t);e.chart.setLinkedCrosshairIndex?.(null)}e.crosshairs.length=0}}function fn(e={}){return new bn(e)}const mn={intervalSec:60,volumeMode:"ltq-sum",lateTickPolicy:"foldIntoBar",sessionAnchorSec:0};class gn{constructor(e={}){Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_current",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_cumAtBarStart",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastCum",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_hasCum",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_streamed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_provisional",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._opts={...mn,...e}}seed(e,t){this._current={...e},this._hasCum=!1,this._streamed=!1,this._provisional=!1,void 0!==t&&(this._lastCum=t,this._cumAtBarStart=t-(e.volume??0),this._hasCum=!0)}current(){return null===this._current?null:{...this._current}}isProvisional(){return null!==this._current&&this._provisional}reconcile(e){const t=this._current;if(null===t||e.time!==t.time)return null;const i=void 0===t.volume&&void 0===e.volume?void 0:Math.max(t.volume??0,e.volume??0),r={...t,open:this._provisional?e.open:t.open,high:Math.max(t.high,e.high),low:Math.min(t.low,e.low),volume:i};return"day-delta"===this._opts.volumeMode&&this._hasCum&&void 0!==i&&(this._cumAtBarStart=this._lastCum-i),this._current=r,this._provisional=!1,{...r}}bucketStart(e){const t=this._opts.sessionAnchorSec,i=this._opts.intervalSec;return t+Math.floor((e-t)/i)*i}onTick(e){const t=this.bucketStart(e.time);if(null!==this._current&&t<this._current.time)return"dropOlderThanPrevBar"===this._opts.lateTickPolicy?null:(this._foldInto(this._current,e),this._streamed=!0,{bar:{...this._current},isNew:!1,provisional:this._provisional});if(null===this._current||t>this._current.time){const i=null===this._current||!this._streamed,r=this._volumeForNewBar(e),s={time:t,open:e.price,high:e.price,low:e.price,close:e.price,volume:r};return void 0!==e.oi&&Number.isFinite(e.oi)&&(s.oi=e.oi),this._current=s,this._streamed=!0,this._provisional=i,{bar:{...s},isNew:!0,provisional:i}}return this._foldInto(this._current,e),this._streamed=!0,{bar:{...this._current},isNew:!1,provisional:this._provisional}}_foldInto(e,t){t.price>e.high&&(e.high=t.price),t.price<e.low&&(e.low=t.price),e.close=t.price,e.volume=this._volumeForSameBar(e,t),void 0!==t.oi&&Number.isFinite(t.oi)?e.oi=t.oi:delete e.oi}_volumeForNewBar(e){if("ltq-sum"===this._opts.volumeMode)return e.ltq??0;const t=e.cumDayVolume??0;return this._hasCum?t<this._lastCum?this._cumAtBarStart=0:this._cumAtBarStart=this._lastCum:this._cumAtBarStart=t,this._lastCum=t,this._hasCum=!0,Math.max(0,t-this._cumAtBarStart)}_volumeForSameBar(e,t){if("ltq-sum"===this._opts.volumeMode)return(e.volume??0)+(t.ltq??0);const i=t.cumDayVolume??0;return this._hasCum||(this._cumAtBarStart=i-(e.volume??0),this._hasCum=!0),this._lastCum=i,Math.max(0,i-this._cumAtBarStart)}}const vn=["previousClose","sessionHigh","sessionLow","lastPrice","preMarketOpen","preMarketClose","postMarketOpen","postMarketClose","bid","ask"];const yn={previousClose:{line:!0,label:!0,lineStyle:"dashed"},sessionHigh:{line:!1,label:!1,lineStyle:"dashed"},sessionLow:{line:!1,label:!1,lineStyle:"dashed"},lastPrice:{line:!1,label:!1,lineStyle:"dashed"},preMarketOpen:{line:!1,label:!1,lineStyle:"dotted"},preMarketClose:{line:!1,label:!1,lineStyle:"dotted"},postMarketOpen:{line:!1,label:!1,lineStyle:"dotted"},postMarketClose:{line:!1,label:!1,lineStyle:"dotted"},bid:{line:!1,label:!1,lineStyle:"dotted"},ask:{line:!1,label:!1,lineStyle:"dotted"}};function wn(e){return"number"==typeof e&&Number.isFinite(e)?e:null}const xn=new WeakMap;function Pn(e){const t={previousClose:null,sessionHigh:null,sessionLow:null,lastPrice:null,preMarketOpen:null,preMarketClose:null,postMarketOpen:null,postMarketClose:null,bid:null,ask:null},i=e.quote;null!=i&&(t.bid=wn(i.bid),t.ask=wn(i.ask));const r=e.bars,s=r.length;if(0===s)return t;t.lastPrice=wn(r[s-1].close);const n=function(e,t){const i=e.length;if(void 0===t||!Number.isFinite(t))return i-1;if(t>=e[i-1].time)return i-1;if(t<e[0].time)return-1;let r=0,s=i-1;for(;r<s;){const i=r+s+1>>1;e[i].time<=t?r=i:s=i-1}return r}(r,e.anchorTime);if(n<0)return t;const o=function(e,t){const i=e.length;if(0===i)return[];const r=e[0].time,s=e[i-1].time,n=xn.get(e);if(void 0!==n&&n.len===i&&n.first===r&&n.last===s&&n.zone===t)return n.starts;const o=new Array(i);for(let t=0;t<i;t++)o[t]=e[t].time;const a=Je(o,t),l=[0];for(let e=1;e<i;e++)a[e]&&l.push(e);return xn.set(e,{len:i,first:r,last:s,zone:t,starts:l}),l}(r,e.timezone??Se),a=function(e,t){let i=0,r=e.length-1;for(;i<r;){const s=i+r+1>>1;e[s]<=t?i=s:r=s-1}return i}(o,n),l=o[a],h=a+1<o.length?o[a+1]-1:s-1;let c=-1/0,d=1/0;for(let e=l;e<=h;e++){const t=r[e];Number.isFinite(t.high)&&t.high>c&&(c=t.high),Number.isFinite(t.low)&&t.low<d&&(d=t.low)}if(c>-1/0&&(t.sessionHigh=c),d<1/0&&(t.sessionLow=d),a>0){const e=o[a-1];for(let i=l-1;i>=e;i--){const e=wn(r[i].close);if(null!==e){t.previousClose=e;break}}}const u=e.marketPhase;if(null!=u)for(let e=l;e<=h;e++){const i=r[e],s=u(i);if("pre"===s){null===t.preMarketOpen&&(t.preMarketOpen=wn(i.open));const e=wn(i.close);null!==e&&(t.preMarketClose=e)}else if("post"===s){null===t.postMarketOpen&&(t.postMarketOpen=wn(i.open));const e=wn(i.close);null!==e&&(t.postMarketClose=e)}}return t}function Sn(e,t,i){switch(e){case"sessionHigh":return t.upColor;case"sessionLow":return t.downColor;case"bid":return t.buy;case"ask":return t.sell;case"lastPrice":return i?t.lastPriceUp:t.lastPriceDown;default:return t.crosshair}}function On(e){return{line:!1!==e.priceLineVisible,label:!1!==e.lastValueVisible}}function kn(e){return{priceLineVisible:e.line,lastValueVisible:e.label}}class Mn{constructor(e={}){Object.defineProperty(this,"_levels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timezone",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_phase",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_quote",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_values",{enumerable:!0,configurable:!0,writable:!0,value:{previousClose:null,sessionHigh:null,sessionLow:null,lastPrice:null,preMarketOpen:null,preMarketClose:null,postMarketOpen:null,postMarketClose:null,bid:null,ask:null}}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._levels={...yn};for(const t of vn){const i=e.levels?.[t];void 0!==i&&(this._levels[t]={...yn[t],...i})}this._timezone=e.timezone??Se,this._phase=e.marketPhase??null,this._quote=e.quote??null}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"normal"}level(e){return this._levels[e]}setLevel(e,t){this._levels[e]={...this._levels[e],...t},this._host?.requestUpdate()}setOptions(e){for(const t of vn){const i=e.levels?.[t];void 0!==i&&(this._levels[t]={...this._levels[t],...i})}void 0!==e.timezone&&(this._timezone=e.timezone),void 0!==e.marketPhase&&(this._phase=e.marketPhase),void 0!==e.quote&&(this._quote=e.quote),this._host?.requestUpdate()}setQuote(e){this._quote=e,this._host?.requestUpdate()}values(){return this._values}available(e){return null!==this._values[e]}draw(e,t){const i=t.bars?.()??[],r=t.dataLayer.indexToTimeFloat(t.timeScale.visibleRange().to);this._values=Pn({bars:i,anchorTime:r,timezone:this._timezone,marketPhase:this._phase,quote:"function"==typeof this._quote?this._quote()??null:this._quote});const s=t.dpr,n=Math.round(t.plotWidth*s),o=t.plotHeight*s,a=i.length>0?i[i.length-1]:null,l=null!==a&&a.close>=a.open;e.save(),e.font=`500 ${11*s}px system-ui, sans-serif`,e.textBaseline="middle",e.textAlign="left";for(const i of vn){const r=this._levels[i];if(!r.line&&!r.label)continue;const a=this._values[i];if(null===a)continue;const h=Math.round(t.priceScale.priceToY(a)*s)+.5;if(h<0||h>o)continue;const c=r.color??Sn(i,t.theme,l);if(r.line){const i=Math.max(0,Math.min(1,r.extentFromRight??1)),o=Math.round(t.plotWidth*(1-i)*s);e.strokeStyle=c,e.lineWidth=Math.max(1,Math.round((r.lineWidth??1)*s)),e.setLineDash(S(r.lineStyle,s)),e.beginPath(),e.moveTo(o,h),e.lineTo(n,h),e.stroke(),e.setLineDash([])}if(r.label){const i=r.text??t.priceScale.format(a),o=6*s,l=16*s;e.fillStyle=c,e.fillRect(n+1,h-l/2,e.measureText(i).width+2*o,l),e.fillStyle=D(c),e.fillText(i,n+1+o,h)}}e.restore()}}class Tn{constructor(e){Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._opts={index:e.index,color:e.color??"rgba(12,14,20,0.62)",lineColor:e.lineColor??"#3b82f6",lineWidth:e.lineWidth??1,lineVisible:e.lineVisible??!0,zOrder:e.zOrder??"top",id:e.id??"replay-shade"}}zOrder(){return this._opts.zOrder}autoscaleInfo(){return null}hitTest(){return null}setOptions(e){this._opts={...this._opts,...e}}draw(e,t){const i=this._opts;if(null===i.index)return;const r=t.dpr,s=t.plotWidth*r,n=t.plotHeight*r;if(s<=0||n<=0)return;const o=t.timeScale.barSpacing*r/2,a=Math.round(t.timeScale.indexToX(i.index)*r+o);if(a>=s)return;const l=Math.max(0,a);e.save(),e.fillStyle=i.color,e.fillRect(l,0,s-l,n),i.lineVisible&&a>=0&&(e.strokeStyle=i.lineColor,e.lineWidth=Math.max(1,Math.round(i.lineWidth*r)),e.beginPath(),e.moveTo(a+.5,0),e.lineTo(a+.5,n),e.stroke()),e.restore()}}class Cn{constructor(e={}){Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_position",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_mx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_my",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_scale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_btnW",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_qtyW",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_h",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_buyLabel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sellLabel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_showPrices",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_qty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_buyColor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sellColor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_bid",{enumerable:!0,configurable:!0,writable:!0,value:NaN}),Object.defineProperty(this,"_ask",{enumerable:!0,configurable:!0,writable:!0,value:NaN}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_sellRect",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_buyRect",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_qtyRect",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._id=e.id??"trade",this._position=e.position??"top-left";const t=e.margin??12;this._mx="number"==typeof t?t:t.x,this._my="number"==typeof t?t:t.y,this._buyLabel=e.buyLabel??"BUY",this._sellLabel=e.sellLabel??"SELL",this._showPrices=e.showPrices??!0,this._scale=Math.max(.6,Math.min(1.5,e.scale??1)),this._btnW=74*this._scale,this._qtyW=40*this._scale,this._h=42*this._scale,this._qty=void 0!==e.qty?String(e.qty):"",this._buyColor=e.buyColor,this._sellColor=e.sellColor}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"top"}autoscaleInfo(){return null}setPrices(e,t){this._bid=e,this._ask=t,this._host?.requestUpdate()}setMark(e){this.setPrices(e,e)}setQty(e){this._qty=String(e),this._host?.requestUpdate()}setColors(e,t){this._buyColor=e,this._sellColor=t,this._host?.requestUpdate()}_origin(e,t){const i=2*this._btnW+this._qtyW+2,r=this._mx,s=e-this._mx-i,n=this._my,o=t-this._my-this._h;switch(this._position){case"top-right":return{x:s,y:n,w:i};case"bottom-left":return{x:r,y:o,w:i};case"bottom-right":return{x:s,y:o,w:i};case"center":return{x:(e-i)/2,y:(t-this._h)/2,w:i};default:return{x:r,y:n,w:i}}}draw(e,t){this._sellRect=this._buyRect=this._qtyRect=null;const i=t.dpr,r=this._origin(t.plotWidth,t.plotHeight),s=this._sellColor??t.theme.sell,n=this._buyColor??t.theme.buy;this._sellRect={x:r.x,y:r.y,w:this._btnW,h:this._h},this._qtyRect={x:r.x+this._btnW+1,y:r.y,w:this._qtyW,h:this._h},this._buyRect={x:r.x+this._btnW+this._qtyW+2,y:r.y,w:this._btnW,h:this._h},e.save(),e.shadowColor="rgba(0,0,0,0.35)",e.shadowBlur=8*i,e.shadowOffsetY=2*i;const o=(e,i)=>null!==e&&t.hoverId===`${this._id}:${i}`;this._drawButton(e,this._sellRect,i,o(this._sellRect,"sell")?W(s,.12):s,this._sellLabel,this._showPrices?this._fmt(t,this._bid):"","left");const a="transparent"===t.theme.background?W(s,-.6):t.theme.grid;this._drawChip(e,this._qtyRect,i,a,this._qty||"—",t.theme.axisText),this._drawButton(e,this._buyRect,i,o(this._buyRect,"buy")?W(n,.12):n,this._buyLabel,this._showPrices?this._fmt(t,this._ask):"","right"),e.restore()}_fmt(e,t){return Number.isNaN(t)?"":e.priceScale.format(t)}_drawButton(e,t,i,r,s,n,o){const a=7*this._scale*i;e.beginPath(),this._roundedSide(e,t.x*i,t.y*i,t.w*i,t.h*i,a,o),e.fillStyle=r,e.fill();const l=D(r);e.textAlign="center";const h=(t.x+t.w/2)*i;""!==n?(e.fillStyle=l,e.font=10*this._scale*i+"px system-ui, sans-serif",e.textBaseline="alphabetic",e.fillText(n,h,(t.y+t.h*(18/42))*i),e.font=`700 ${12*this._scale*i}px system-ui, sans-serif`,e.fillText(s,h,(t.y+t.h*(33/42))*i)):(e.fillStyle=l,e.font=`700 ${13*this._scale*i}px system-ui, sans-serif`,e.textBaseline="middle",e.fillText(s,h,(t.y+t.h/2)*i))}_drawChip(e,t,i,r,s,n){e.beginPath(),e.rect(t.x*i,t.y*i,t.w*i,t.h*i),e.fillStyle=r,e.fill(),e.fillStyle=n,e.font=`600 ${13*this._scale*i}px system-ui, sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillText(s,(t.x+t.w/2)*i,(t.y+t.h/2)*i)}_roundedSide(e,t,i,r,s,n,o){const a=e;if("function"==typeof a.roundRect){const e="left"===o?[n,0,0,n]:[0,n,n,0];a.roundRect(t,i,r,s,e)}else q(e,t,i,r,s,n)}hitTest(e,t,i){const r=i=>null!==i&&e>=i.x&&e<=i.x+i.w&&t>=i.y&&t<=i.y+i.h;return r(this._buyRect)?{externalId:`${this._id}:buy`,zOrder:"top",distance:0,cursor:"pointer"}:r(this._sellRect)?{externalId:`${this._id}:sell`,zOrder:"top",distance:0,cursor:"pointer"}:r(this._qtyRect)?{externalId:`${this._id}:qty`,zOrder:"top",distance:0,cursor:"pointer"}:null}}function In(e,t){if(t<=0)throw new Error("openalgo-charts: EMA period must be > 0");const i=[];if(0===e.length)return i;const r=2/(t+1);let s=e[0];i.push(s);for(let t=1;t<e.length;t++)s=e[t]*r+s*(1-r),i.push(s);return i}function jn(e,t){const i=In(e.map(e=>e.close),t);return e.map((e,t)=>({time:e.time,open:i[t],high:i[t],low:i[t],close:i[t]}))}function An(e,t=14){if(t<=0)throw new Error("openalgo-charts: RSI period must be > 0");const i=e.length,r=new Array(i).fill(NaN);if(i<=t)return r;let s=0,n=0;for(let i=1;i<=t;i++){const t=e[i]-e[i-1];t>=0?s+=t:n-=t}let o=s/t,a=n/t;r[t]=0===a?100:100-100/(1+o/a);for(let s=t+1;s<i;s++){const i=e[s]-e[s-1];o=(o*(t-1)+(i>0?i:0))/t,a=(a*(t-1)+(i<0?-i:0))/t,r[s]=0===a?100:100-100/(1+o/a)}return r}function Ln(e,t=14){const i=An(e.map(e=>e.close),t);return e.map((e,t)=>({time:e.time,open:i[t],high:i[t],low:i[t],close:i[t]}))}function zn(e,t,i){const r=e.length,s=new Array(r);if(0===r)return s;s[0]=e[0]-t[0];for(let n=1;n<r;n++){const r=e[n]-t[n],o=Math.abs(e[n]-i[n-1]),a=Math.abs(t[n]-i[n-1]);s[n]=Math.max(r,o,a)}return s}function Fn(e,t,i,r=14){if(r<=0)throw new Error("openalgo-charts: ATR period must be > 0");const s=zn(e,t,i),n=s.length,o=new Array(n).fill(NaN);if(n<r)return o;let a=0;for(let e=0;e<r;e++)a+=s[e];let l=a/r;o[r-1]=l;for(let e=r;e<n;e++)l=(l*(r-1)+s[e])/r,o[e]=l;return o}function Bn(e,t=10,i=3){const r=e.length,s=e.map(()=>({value:NaN,direction:1})),n=e.map(e=>e.high),o=e.map(e=>e.low),a=e.map(e=>e.close),l=Fn(n,o,a,t);let h=NaN,c=NaN,d=NaN,u=!1;for(let e=0;e<r;e++){if(!Number.isFinite(l[e]))continue;const t=(n[e]+o[e])/2,r=t+i*l[e],p=t-i*l[e],_=u?r<h||a[e-1]>h?r:h:r,b=u?p>c||a[e-1]<c?p:c:p;let f,m;u&&d!==h?a[e]>=b?(f=b,m=-1):(f=_,m=1):a[e]<=_?(f=_,m=1):(f=b,m=-1),s[e]={value:f,direction:m},h=_,c=b,d=f,u=!0}return s}function $n(e,t=10,i=3){const r=Bn(e,t,i),s=(e,t)=>({time:e,open:t,high:t,low:t,close:t}),n=[],o=[];for(let t=0;t<e.length;t++){const i=r[t],a=Number.isFinite(i.value);n.push(s(e[t].time,a&&-1===i.direction?i.value:NaN)),o.push(s(e[t].time,a&&1===i.direction?i.value:NaN))}return{up:n,down:o}}class Nn extends Error{constructor(e){super(`openalgo-charts: unknown interval "${e}". Register it with registerInterval() or use a built-in token (1s, 1m, 5m, 1h, D, W).`),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="UnknownIntervalError",this.code=e}}const Dn=/^(\d*)\s*([smhdw])$/i,Rn={s:1,m:60,h:3600,d:86400,w:604800};const En=new Map;function Wn(e){return e.trim().toLowerCase()}function qn(e){const t=Wn(e.code);if(""===t)throw new Error("openalgo-charts: interval code must not be empty");return function(e){if("interval"===e.mode&&!(e.seconds>0))throw new Error("openalgo-charts: interval bucketing needs seconds > 0");if("ticks"===e.mode&&!(e.count>=1))throw new Error("openalgo-charts: tick bucketing needs count >= 1");if("volume"===e.mode&&!(e.perBar>0))throw new Error("openalgo-charts: volume bucketing needs perBar > 0");if("calendar"===e.mode&&void 0!==e.count&&!(e.count>=1))throw new Error("openalgo-charts: calendar bucketing needs count >= 1")}(e.bucketing),En.set(t,e),()=>{En.get(t)===e&&En.delete(t)}}function Hn(e){return En.delete(Wn(e))}function Vn(){return Array.from(En.values())}function Gn(e){const t=e.trim(),i=En.get(t.toLowerCase());if(void 0!==i)return i;const r=function(e){if(/^\d*\s*M$/.test(e))return null;const t=Dn.exec(e);return null===t?null:{mode:"interval",seconds:(""===t[1]?1:Number(t[1]))*Rn[t[2].toLowerCase()]}}(t);return null===r?null:{code:t,bucketing:r}}function Un(e){return null!==Gn(e)}function Yn(e){const t=Gn(e);if(null===t)throw new Nn(e);return t}function Kn(e){return"interval"===e.mode||"calendar"===e.mode}const Xn={month:1,quarter:3,year:12};function Jn(e){return Xn[e.unit]*Math.max(1,Math.floor(e.count??1))}function Zn(e,t){return e.timezone??t??Se}function Qn(e,t,i){const r=Ie(t,i),s=Jn(e);return Math.floor((12*r.year+(r.month-1))/s)*s}function eo(e,t){return Ee(Math.floor(e/12),e%12+1,1,0,0,0,t)}function to(e,t,i){if("interval"===e.mode){const i=e.anchorSec??0;return i+Math.floor((t-i)/e.seconds)*e.seconds}if("calendar"!==e.mode)return t;const r=Zn(e,i);return eo(Qn(e,t,r),r)}function io(e,t,i){if("interval"===e.mode)return to(e,t)+e.seconds;if("calendar"!==e.mode)return null;const r=Zn(e,i);return eo(Qn(e,t,r)+Jn(e),r)}function ro(e){const t=Gn(e);if(null===t)return null;const i=t.bucketing;if("ticks"===i.mode)return{multiplier:i.count,unit:"tick"};if("volume"===i.mode)return{multiplier:i.perBar,unit:"other"};if("calendar"===i.mode)return{multiplier:Jn(i),unit:"M"};const r=i.seconds;return r%604800==0?{multiplier:r/604800,unit:"W"}:r%86400==0?{multiplier:r/86400,unit:"D"}:r%3600==0?{multiplier:r/3600,unit:"h"}:r%60==0?{multiplier:r/60,unit:"m"}:{multiplier:r,unit:"s"}}function so(e){const t=Gn(e)?.bucketing;return void 0!==t&&"interval"===t.mode?t.seconds:0}function no(e){const t=so(e);return t>0&&t%60!=0}function oo(e){const t=so(e);return t>0&&t<86400}function ao(e){return 86400===so(e)}function lo(e){return"ticks"===Gn(e)?.bucketing.mode}function ho(e){throw new Error(`Invalid instrument: ${e}`)}function co(e){return e&&"object"==typeof e&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e))?Object.values(Object.getOwnPropertyDescriptors(e)).some(e=>!("value"in e))?ho("accessors are not metadata"):e:ho("expected a plain object")}function uo(e,t){return"string"!=typeof e||!e.trim()||e.length>200||Array.from(e).some(e=>e.charCodeAt(0)<32)?ho(t):e}function po(e,t){return"number"!=typeof e||!Number.isFinite(e)||e<=0?ho(t):e}function _o(e,t){return!Array.isArray(e)||e.length>t?ho("invalid list"):e.map(e=>uo(e,"invalid list item"))}function bo(e){const t=_o(e,16);return t.some(e=>!tt(e))?ho("invalid session"):Object.freeze(t)}function fo(e){return e.toISOString().slice(0,10)}function mo(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return ho("invalid exception date");const t=new Date(e+"T00:00:00Z");return Number.isFinite(t.getTime())&&fo(t)===e?t:ho("invalid exception date")}function go(e,t,i){const r=new Date(e.getTime()+6e4*t),s=r.getUTCFullYear(),n=r.getUTCMonth()+1,o=r.getUTCDate(),a=r.getUTCHours(),l=r.getUTCMinutes(),h=Ee(s,n,o,a,l,0,i),c=Ie(h,i);return c.year!==s||c.month!==n||c.day!==o||c.hour!==a||c.minute!==l?ho("session boundary is absent in this timezone"):h}class vo{constructor(e){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sessions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_exceptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=function(e){const t=co(e),i=co(t.calendar),r=uo(t.timezone,"timezone");if(!Te(r))return ho("unknown timezone");const s=po(t.priceTick,"price tick"),n=t.pricePrecision;if("number"!=typeof n||!Number.isInteger(n)||n<0||n>12)return ho("price precision must be 0..12");const o=s*10**n;if(!Number.isFinite(o)||o<1||Math.abs(o-Math.round(o))>8*Number.EPSILON*Math.max(1,o))return ho("price precision cannot represent the tick");const a=_o(t.intervals,128);if(!a.length||new Set(a).size!==a.length)return ho("intervals must be nonempty and unique");for(const e of a){const t=Gn(e)?.bucketing;if(!t||"interval"===t.mode&&(!Number.isFinite(t.seconds)||t.seconds<=0))return ho(`unsupported interval ${e}`)}const l={};if(void 0!==i.exceptions){const e=co(i.exceptions);if(Object.keys(e).length>3660)return ho("too many session exceptions");for(const[t,i]of Object.entries(e))mo(t),l[t]=bo(i)}return void 0!==t.hasOpenInterest&&"boolean"!=typeof t.hasOpenInterest?ho("invalid OI capability"):Object.freeze({symbol:uo(t.symbol,"symbol"),exchange:uo(t.exchange,"exchange"),timezone:r,priceTick:s,pricePrecision:n,quantityStep:po(t.quantityStep,"quantity step"),intervals:Object.freeze(a),calendar:Object.freeze({sessions:bo(i.sessions),exceptions:Object.freeze(l)}),...void 0===t.hasOpenInterest?{}:{hasOpenInterest:t.hasOpenInterest}})}(e),this._sessions=this.metadata.calendar.sessions.map(e=>tt(e)),this._exceptions=new Map(Object.entries(this.metadata.calendar.exceptions??{}).map(([e,t])=>[e,t.map(e=>tt(e))]))}supportsInterval(e){return this.metadata.intervals.includes(e)}formatPrice(e){return Number.isFinite(e)?e.toFixed(this.metadata.pricePrecision):""}sessionAt(e){if(!Number.isFinite(e)||!Number.isFinite(new Date(1e3*e).getTime()))return ho("invalid timestamp");const t=Ie(e,this.metadata.timezone);let i=null;for(const r of[0,-1]){const s=new Date(Date.UTC(t.year,t.month-1,t.day+r)),n=fo(s);for(const t of this._exceptions.get(n)??this._sessions){if(t.days&&!t.days.includes(s.getUTCDay()+1))continue;if(-1===r&&t.end>t.start)continue;const o=go(s,t.start,this.metadata.timezone),a=go(s,t.end+(t.end<=t.start?1440:0),this.metadata.timezone);if(!(e<o||e>=a)){if(i)return ho("overlapping active sessions");i={date:n,open:o,close:a}}}}return i}applyTo(e,t){if(!this.supportsInterval(t))return ho(`unsupported interval ${t}`);if(e.isDestroyed)return ho("chart is destroyed");const i=e.primarySeries();if(!i)return ho("chart needs a primary series");const r=e.getDataContext(),s=this.metadata;if(r&&(r.symbol!==s.symbol||r.exchange!==s.exchange||r.interval!==t)&&e.primaryBars().length)return ho("clear previous source bars before applying metadata");e.setTimezone(s.timezone),e.setPriceScaleOptions({minMove:s.priceTick}),i.priceScale().setOptions({minMove:s.priceTick}),i.priceScale().setPriceFormatter(e=>this.formatPrice(e)),e.setDataContext({symbol:s.symbol,exchange:s.exchange,interval:t,hasOpenInterest:s.hasOpenInterest})}}function yo(e,t){if(void 0===e)return{supported:!0};try{const i="function"==typeof e?e(Object.freeze({...t})):e;if(!i||"object"!=typeof i||Array.isArray(i)||"then"in i)return{supported:!1,reason:"Trading capabilities are unavailable"};const r=i[t.operation];if(!1===r)return{supported:!1,reason:`Trading operation ${t.operation} is not supported`};if(void 0!==r&&!0!==r)return{supported:!1,reason:`Support for trading operation ${t.operation} is unknown`};if("place"===t.operation){if(void 0!==i.orderTypes){if(!Array.isArray(i.orderTypes)||void 0===t.type)return{supported:!1,reason:"Supported order types are unavailable for this request"};if(!i.orderTypes.includes(t.type))return{supported:!1,reason:`Order type ${t.type} is not supported`}}if(void 0!==i.modes){if(!Array.isArray(i.modes)||void 0===t.mode)return{supported:!1,reason:"Supported trading modes are unavailable for this request"};if(!i.modes.includes(t.mode))return{supported:!1,reason:`Trading mode ${t.mode} is not supported`}}}return{supported:!0}}catch{return{supported:!1,reason:"Trading capabilities are unavailable"}}}class wo extends Error{constructor(e,t){super(t),Object.defineProperty(this,"preflight",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TradingCapabilityError",this.operation=e}}function xo(e,t){const i=yo(e,t);if(!i.supported)throw new wo(t.operation,i.reason)}function Po(e,t){const i=new Error(t);return i.name=e,i}function So(e){if(!Number.isFinite(e)||e<=0)throw new RangeError("History timeout must be positive and finite");return e}function Oo(e,t){if(e.signal?.aborted)return Promise.reject(Po("AbortError","History request cancelled"));const i=So(e.timeoutMs??15e3);return new Promise((r,s)=>{const n=new AbortController;let o=!1;const a=(t,i)=>{o||(o=!0,clearTimeout(h),e.signal?.removeEventListener("abort",l),t?r(i):(n.abort(),s(i)))},l=()=>a(!1,Po("AbortError","History request cancelled")),h=setTimeout(()=>a(!1,Po("TimeoutError","History request timed out")),i);e.signal?.addEventListener("abort",l,{once:!0});try{t(n.signal).then(e=>a(!0,e),e=>a(!1,e))}catch(e){a(!1,e)}})}function ko(e){const t=e=>e.map(e=>{if(null===e||"object"!=typeof e)throw new TypeError("Invalid history bar");return{...e}});return Array.isArray(e)?t(e):{...e,bars:t(e.bars)}}class Mo{constructor(e,t={}){if(Object.defineProperty(this,"_feed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_max",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_jobs",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_active",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_draining",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._feed=e,this._max=t.maxConcurrent??4,!Number.isInteger(this._max)||this._max<1)throw new RangeError("History concurrency must be a positive integer");this._timeout=So(t.timeoutMs??15e3)}getBars(e,t=0){return this._request(e,!1,t)}getBarsPage(e,t=0){return this._feed.getBarsPage?this._request(e,!0,t):Promise.reject(new Error("This feed does not support history pages"))}_request(e,t,i){if(e.signal?.aborted)return Promise.reject(Po("AbortError","History request cancelled"));if(!Number.isFinite(i))return Promise.reject(new RangeError("History priority must be finite"));let r;try{r=So(e.timeoutMs??this._timeout)}catch(e){return Promise.reject(e)}const s=JSON.stringify([t,e.symbol,e.exchange,e.interval,e.from,e.to,e.countBack,!0===e.noCache,"before"in e?e.before:null]);let n=this._jobs.get(s);n||(n={key:s,req:{...e,signal:void 0,timeoutMs:2147483647},page:t,priority:i,controller:new AbortController,consumers:new Set,running:!1,done:!1},this._jobs.set(s,n));const o=n;o.priority=Math.max(o.priority,i);const a=new Promise((t,i)=>{const s=e=>{o.consumers.delete(l)&&(l.cleanup(),i(e),0===o.consumers.size&&(this._remove(o),o.controller.abort(),this._drain()))},n=()=>s(Po("AbortError","History request cancelled")),a=setTimeout(()=>s(Po("TimeoutError","History request timed out")),r),l={resolve:t,reject:i,cleanup:()=>{clearTimeout(a),e.signal?.removeEventListener("abort",n)}};o.consumers.add(l),e.signal?.addEventListener("abort",n,{once:!0})});return this._drain(),a}_remove(e){e.done||(e.done=!0,this._jobs.get(e.key)===e&&this._jobs.delete(e.key),e.running&&this._active--)}_finish(e,t,i){if(e.done)return;let r;if(t)try{if(e.page===Array.isArray(i))throw new TypeError("Invalid history result shape");r=ko(i)}catch(e){t=!1,i=e}this._remove(e);for(const s of e.consumers)s.cleanup(),t?s.resolve(ko(r)):s.reject(i);e.consumers.clear(),this._drain()}_drain(){if(!this._draining){this._draining=!0;try{for(;this._active<this._max;){let e;for(const t of this._jobs.values())t.running||e&&!(t.priority>e.priority)||(e=t);if(!e)return;const t=e;t.running=!0,this._active++;const i={...t.req,signal:t.controller.signal};try{(t.page?this._feed.getBarsPage(i):this._feed.getBars(i)).then(e=>this._finish(t,!0,e),e=>this._finish(t,!1,e))}catch(e){this._finish(t,!1,e)}}}finally{this._draining=!1}}}}const To=new WeakMap;function Co(e){let t=To.get(e);return t||(t=new Mo(e),To.set(e,t)),t}const Io={delayMs:2500,retries:2,retryDelayMs:5e3};function jo(e){return e instanceof Error?e:new Error(String(e??"History request failed"))}function Ao(e,t){if(!Number.isFinite(e)||e<=0)throw new RangeError(`${t} must be positive and finite`);return e}function Lo(e){const t=new Map;for(const i of e){if(![i.time,i.open,i.high,i.low,i.close].every(Number.isFinite)||i.high<Math.max(i.open,i.close,i.low)||i.low>Math.min(i.open,i.close)||void 0!==i.volume&&(!Number.isFinite(i.volume)||i.volume<0))throw new Error("History contains an invalid candle");t.set(i.time,{...i})}return[...t.values()].sort((e,t)=>e.time-t.time)}function zo(...e){return Lo(e.flat())}class Fo{constructor(e,t={}){Object.defineProperty(this,"_feed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pool",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:{request:null,bars:[],status:"idle",historyStatus:"idle",hasMore:null,reason:"state",paused:!1}}),Object.defineProperty(this,"_bars",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_scope",{enumerable:!0,configurable:!0,writable:!0,value:new AbortController}),Object.defineProperty(this,"_refreshAbort",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pageAbort",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_loadWork",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pageWork",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_unsubscribe",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_stream",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_generation",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_refreshId",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_before",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_buffer",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_poll",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_visible",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_seconds",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_provisionalTime",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_repairTimer",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_repairRetries",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_pendingRepair",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_barClose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._feed=e,this._pool=t.requestPool??Co(e),this._options={pageSize:500,maxEmptyPages:4,maxBars:1e5,pollIntervalMs:0,...t};for(const e of["pageSize","maxEmptyPages","maxBars"]){const t=Ao(this._options[e],e);if(!Number.isInteger(t))throw new RangeError(`${e} must be an integer`)}if(void 0!==t.pageWindowSec&&Ao(t.pageWindowSec,"pageWindowSec"),void 0!==t.timeoutMs&&Ao(t.timeoutMs,"timeoutMs"),!Number.isFinite(this._options.pollIntervalMs)||this._options.pollIntervalMs<0)throw new RangeError("pollIntervalMs must be nonnegative");if(void 0!==t.refreshWindowBars&&!Number.isInteger(Ao(t.refreshWindowBars,"refreshWindowBars")))throw new RangeError("refreshWindowBars must be an integer");const i=t.refreshOnBarClose;if(this._barClose=i?{...Io,...!0===i?{}:i}:null,this._barClose){for(const e of["delayMs","retries","retryDelayMs"]){const t=this._barClose[e];if(!Number.isFinite(t)||t<0)throw new RangeError(`refreshOnBarClose.${e} must be nonnegative`)}if(!Number.isInteger(this._barClose.retries))throw new RangeError("refreshOnBarClose.retries must be an integer")}}getState(){return this._state}bars(){return this._bars}subscribe(e){return this._destroyed?()=>{}:(this._listeners.add(e),()=>{this._listeners.delete(e)})}load(e){if(this._destroyed)return Promise.resolve([]);const t=++this._generation;if(this._cancel(),!this._current(t))return this._loadWork??Promise.resolve(this._bars);this._scope=new AbortController,this._bars=[],this._before=void 0,this._provisionalTime=null;const i=Gn(e.interval);this._seconds="interval"===i?.bucketing.mode?i.bucketing.seconds:null;const r={...e,signal:void 0,timeoutMs:e.timeoutMs??this._options.timeoutMs};let s;this._state={request:r,bars:[],status:"loading",historyStatus:"idle",hasMore:null,reason:"load",paused:!1};const n=new Promise(e=>{s=e});return this._loadWork=n,this._publish("load"),this._load(r,e.signal,t).then(s),n.then(()=>{this._loadWork===n&&(this._loadWork=null)}),n}async _load(e,t,i){if(!this._current(i))return this._bars;const r=this._scope,s=()=>r.abort();t?.addEventListener("abort",s,{once:!0}),t?.aborted&&r.abort();try{let t;if(!e.noCache&&this._feed.getCachedBars)try{const i=await Oo({signal:r.signal,timeoutMs:Math.min(e.timeoutMs??500,500)},t=>this._feed.getCachedBars({...e,signal:t}));t=i?Lo(i):void 0}catch{}if(!this._current(i))return this._bars;if(r.signal.aborted)throw r.signal.reason;t?.length&&(this._bars=t,this._publish("cache",{status:"refreshing"}));const s=t?.length&&void 0!==e.from&&t[0].time<=e.from?Math.max(e.from,t[Math.max(0,t.length-2)].time):e.from,n=await this._pool.getBars({...e,from:s,signal:r.signal,noCache:e.noCache||!!this._feed.getCachedBars},10);if(!this._current(i))return this._bars;this._bars=this._replaceWindow(Lo(n),s,e.to),this._limit(),this._before=this._bars[0]?.time??e.from,this._publish("load",{status:this._bars.length?"ready":"empty",error:void 0}),this._startStream(i),this._current(i)&&this._schedulePoll()}catch(e){this._current(i)&&this._publish("state",{status:r.signal.aborted?"idle":this._bars.length?"stale":"error",error:r.signal.aborted?void 0:jo(e)})}finally{t?.removeEventListener("abort",s)}return this._bars}refresh(){return this._refresh()}async _refresh(e){if(this._destroyed||!this._state.request)return this._bars;if(this._loadWork)return this._loadWork;const t=this._generation,i=++this._refreshId,r=this._refreshAbort;if(this._refreshAbort=null,r?.abort(),!this._current(t)||i!==this._refreshId)return this._bars;const s=new AbortController;this._refreshAbort=s,this._clearPoll(),this._buffer??(this._buffer=new Map);const n=this._state.request,o=Math.max(n.to??0,(this._options.now??(()=>Date.now()/1e3))()),a=void 0!==n.from&&void 0!==n.to?n.to-n.from:void 0,l=this._bars[this._bars.length-1];let h=void 0===a?n.from:o-a;void 0!==this._options.refreshWindowBars&&null!==this._seconds&&l&&(h=l.time-this._options.refreshWindowBars*this._seconds,void 0!==e?.from&&(h=Math.min(h,e.from))),this._publish("state",{status:"refreshing",error:void 0});try{const r=await this._pool.getBars({...n,from:h,to:o,noCache:!0,signal:s.signal},5);if(!this._current(t)||i!==this._refreshId)return this._bars;if(0===r.length&&this._bars.length)throw new Error("History refresh returned no bars");const a=Lo(r);let c=-1/0;for(const e of a)e.time>c&&(c=e.time);const d=a.length?Math.min(o,c):o,u=this._replaceWindow(a,h,d),p=new Map(u.map(e=>[e.time,e])),_=l&&l.time===c?p.get(l.time):void 0;l&&_&&p.set(l.time,{..._,high:Math.max(_.high,l.high),low:Math.min(_.low,l.low),volume:void 0===_.volume&&void 0===l.volume?void 0:Math.max(_.volume??0,l.volume??0)}),null!==this._provisionalTime&&p.has(this._provisionalTime)&&this._provisionalTime<=d&&(this._provisionalTime=null);for(const e of this._buffer?.values()??[]){const t=p.get(e.time);p.set(e.time,t?{...t,high:Math.max(t.high,e.high),low:Math.min(t.low,e.low),close:e.close,volume:void 0===t.volume&&void 0===e.volume?void 0:Math.max(t.volume??0,e.volume??0),oi:e.oi}:e)}this._bars=Lo([...p.values()]),this._buffer=null,this._limit(),this._publish("refresh",{status:this._bars.length?"ready":"empty",error:void 0}),this._startStream(t),void 0!==e?.expect&&c<e.expect&&this._barClose&&this._repairRetries<this._barClose.retries&&(this._repairRetries++,this._scheduleRepair({expect:e.expect},this._barClose.retryDelayMs))}catch(e){if(!this._current(t)||i!==this._refreshId||s.signal.aborted)return this._bars;this._limit(),this._publish("refresh",{status:this._bars.length?"stale":"error",error:jo(e)})}finally{if(this._current(t)&&i===this._refreshId){this._refreshAbort=null,this._schedulePoll();const e=this._pendingRepair;this._pendingRepair=null,e&&this._refresh(e)}}return this._bars}pushBar(e,t){if(this._destroyed||!this._state.request)return;let i;try{i=Lo([e])[0]}catch(e){return void this._publish("state",{status:this._bars.length?"stale":"error",error:jo(e)})}const r=this._bars[this._bars.length-1];if(r&&i.time<r.time)return;const s=!0===t?.provisional,n=!r||i.time>r.time;if(n?s&&(this._provisionalTime=i.time):s&&this._provisionalTime!==i.time&&(i={...i,open:r.open,high:Math.max(r.high,i.high),low:Math.min(r.low,i.low),volume:void 0===r.volume&&void 0===i.volume?void 0:Math.max(r.volume??0,i.volume??0)}),this._buffer)for(this._buffer.set(i.time,i);this._buffer.size>this._options.maxBars;)this._buffer.delete(this._buffer.keys().next().value);const o=this._bars.slice();r?.time===i.time?o[o.length-1]={...i,volume:i.volume??r.volume}:o.push(i),this._bars=o,this._limit(),this._buffer||this._publish("live",{status:"stale"===this._state.status?"stale":"ready"}),n&&this._onNewBucket(r?.time,i.time)}_onNewBucket(e,t){this._options.refreshOnGap&&null!==this._seconds&&void 0!==e&&t-e>this._seconds?this._requestRepair({from:e}):this._barClose&&(this._repairRetries=0,this._scheduleRepair({expect:e},this._barClose.delayMs))}_scheduleRepair(e,t){this._clearRepairTimer(),!this._destroyed&&this._visible&&(this._repairTimer=setTimeout(()=>{this._repairTimer=null,this._requestRepair(e)},t))}_requestRepair(e){if(!this._destroyed&&this._visible&&this._state.request&&!this._loadWork){if(this._refreshAbort){const t=this._pendingRepair;return void(this._pendingRepair={from:void 0===t?.from?e.from:void 0===e.from?t.from:Math.min(t.from,e.from),expect:void 0===t?.expect?e.expect:void 0===e.expect?t.expect:Math.max(t.expect,e.expect)})}this._refresh(e)}}_clearRepairTimer(){null!==this._repairTimer&&clearTimeout(this._repairTimer),this._repairTimer=null}loadMore(){if(this._pageWork)return this._pageWork;if(this._destroyed||!this._state.request||this._loadWork||this._state.paused||!1===this._state.hasMore)return Promise.resolve(this._bars);if(this._bars.length>=this._options.maxBars)return this._publish("state",{historyStatus:"limited"}),Promise.resolve(this._bars);const e=this._generation;let t;const i=new Promise(e=>{t=e});return this._pageWork=i,this._loadMore(e).then(t),i.then(()=>{this._pageWork===i&&(this._pageWork=null)}),i}async _loadMore(e){const t=this._state.request,i=this._options.pageWindowSec??Math.max(1,(t.to??0)-(t.from??0)||86400),r=new AbortController;this._pageAbort=r,this._publish("state",{historyStatus:"loading",historyError:void 0});try{for(let s=0;s<this._options.maxEmptyPages;s++){const s=this._before??this._bars[0]?.time??t.from;if(void 0===s)throw new Error("Older history needs a starting time");const n={...t,from:s-i,to:s-1e-6,before:s,countBack:this._options.pageSize,signal:r.signal},o=this._feed.getBarsPage?await this._pool.getBarsPage(n):{bars:await this._pool.getBars(n),hasMore:void 0,nextBefore:void 0};if(!this._current(e)||r.signal.aborted)return this._bars;const a=Lo(o.bars).filter(e=>e.time<s),l=o.nextBefore??a[0]?.time??s-i;if(!Number.isFinite(l)||l>=s)throw new Error("History page did not advance its cursor");if(this._before=l,a.length){const e=new Set(this._bars.map(e=>e.time)),t=a.filter(t=>!e.has(t.time)),i=Math.max(0,this._options.maxBars-this._bars.length);this._bars=zo(i?t.slice(-i):[],this._bars);const r=t.length>i||this._bars.length>=this._options.maxBars;return this._publish("prepend",{hasMore:t.length>i||(o.hasMore??null),historyStatus:r?"limited":!1===o.hasMore?"exhausted":"idle"}),this._bars}if(!1===o.hasMore)return this._publish("state",{hasMore:!1,historyStatus:"exhausted"}),this._bars}this._publish("state",{hasMore:null,historyStatus:"idle"})}catch(t){this._current(e)&&!r.signal.aborted&&this._publish("state",{historyStatus:"error",historyError:jo(t)})}finally{this._pageAbort===r&&(this._pageAbort=null)}return this._bars}setPaused(e){this._destroyed||e===this._state.paused||(this._state={...this._state,paused:e},this._publish(e?"state":"resume"))}setVisible(e){this._destroyed||e===this._visible||(this._visible=e,e?this.refresh():(this._clearPoll(),this._clearRepairTimer(),this._pendingRepair=null))}destroy(){this._destroyed||(this._destroyed=!0,this._generation++,this._cancel(),this._listeners.clear())}_current(e){return!this._destroyed&&e===this._generation}_replaceWindow(e,t,i){return void 0===t||void 0===i?e:zo(this._bars.filter(e=>e.time<t||e.time>i),e)}_limit(){this._bars.length>this._options.maxBars&&(this._bars=this._bars.slice(-this._options.maxBars))}_publish(e,t={}){if(this._destroyed)return;this._state={...this._state,...t,reason:e,bars:this._state.paused||this._buffer?this._state.bars:this._bars};const i=this._state;for(const e of[...this._listeners]){if(this._destroyed||this._state!==i)break;try{e(i)}catch{}}}_startStream(e){if(!this._current(e))return;const t=this._stream,i=++this._stream,r=this._unsubscribe;if(this._unsubscribe=null,this._feed.subscribeBars)try{const t=this._feed.subscribeBars(this._state.request,(t,r)=>{this._current(e)&&i===this._stream&&this.pushBar(t,r)},{seedFrom:this._bars[this._bars.length-1],onResync:()=>{this._current(e)&&i===this._stream&&this.refresh()}});this._current(e)&&i===this._stream?this._unsubscribe=t:this._release(t),this._release(r)}catch(s){this._current(e)&&i===this._stream?(this._stream=t,this._unsubscribe=r,this._buffer??(this._buffer=new Map),this._publish("state",{status:this._bars.length?"stale":"error",error:jo(s)})):this._release(r)}else this._release(r)}_release(e){try{e?.()}catch{}}_clearPoll(){null!==this._poll&&clearTimeout(this._poll),this._poll=null}_schedulePoll(){this._clearPoll(),!this._destroyed&&this._visible&&this._options.pollIntervalMs>0&&(this._poll=setTimeout(()=>{this._poll=null,this.refresh()},this._options.pollIntervalMs))}_cancel(){const e=this._scope,t=this._refreshAbort,i=this._pageAbort,r=this._unsubscribe;this._refreshAbort=null,this._pageAbort=null,this._loadWork=null,this._pageWork=null,this._buffer=null,this._pendingRepair=null,this._stream++,this._unsubscribe=null,this._clearPoll(),this._clearRepairTimer(),e.abort(),t?.abort(),i?.abort(),this._release(r)}}function Bo(e){if("number"==typeof e)return e>1e12?ue(e):Math.floor(e);const t=Number(e);if(""!==e.trim()&&!Number.isNaN(t)&&!/[-T :]/.test(e.trim()))return t>1e12?ue(t):Math.floor(t);if(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(e.trim())){const t=Date.parse(e.trim().replace(" ","T"));if(Number.isFinite(t))return ue(t)}return pe(e)}function $o(e,t){if("error"===e.status)throw new Error(e.message??"OpenAlgo history request failed");const i=e.data??[],r=[];for(const e of i){const i=e.timestamp??e.time;void 0!==i&&r.push({time:Bo(i),open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume,...!1!==t&&Number.isFinite(e.oi)?{oi:e.oi}:{}})}return r.sort((e,t)=>e.time-t.time)}class No{constructor(e){Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_fetch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._config=e;const t=e.fetchImpl??("undefined"!=typeof fetch?fetch.bind(globalThis):void 0);if(void 0===t)throw new Error("openalgo-charts: no fetch available; pass config.fetchImpl");this._fetch=t}async getBars(e){const t=this._config.hasOpenInterest?.(e),{from:i,to:r}=e;if(void 0===i||void 0===r)throw new Error("openalgo-charts: getBars requires `from` and `to` (UTC seconds): OpenAlgo history needs a date range");return Oo(e,async s=>{const n=await this._fetch(`${this._config.baseUrl}/api/v1/history`,{method:"POST",signal:s,headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this._config.apiKey,symbol:e.symbol,exchange:e.exchange,interval:{"1d":"D","1D":"D","1w":"W","1W":"W","1M":"M",MN:"M"}[e.interval]??e.interval,start_date:ge(i),end_date:ge(r)})});if(!n.ok)throw new Error(`openalgo-charts: history request failed (${n.status})`);return $o(await n.json(),t)})}}const Do={LTP:1,Quote:2,Depth:3};function Ro(){return JSON.stringify({action:"subscribe_orders"})}function Eo(e,t,i,r){const s={action:"subscribe",symbol:t,exchange:i,mode:Do[e]};return"Depth"===e&&void 0!==r&&(s.depth=r,s.depth_level=r),JSON.stringify(s)}function Wo(e,t,i){return JSON.stringify({action:"unsubscribe",symbol:t,exchange:i,mode:Do[e]})}function qo(e){if("string"==typeof e&&/^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(e.trim())&&(e=Number(e)),"number"==typeof e)return Number.isFinite(e)&&e>0?e>1e12?ue(e):Math.floor(e):0;if("string"==typeof e&&""!==e.trim()){const t=Date.parse(e);if(Number.isFinite(t)&&t>0)return Math.floor(t/1e3)}return 0}function Ho(e){for(const t of[e.last_trade_time,e.ltt,e.exchange_timestamp,e.timestamp]){const e=qo(t);if(e>0)return e}return 0}function Vo(e){if("string"!=typeof e)return null;const t=e.split(".");if(2!==t.length)return null;const[i,r]=t;return""===i||""===r?null:{symbol:i,exchange:r}}function Go(e){if("object"!=typeof e||null===e)return null;const t=e,i="string"==typeof t.type?t.type.toLowerCase():"",r="string"==typeof t.status?t.status.toLowerCase():"",s="success"===r||"ok"===r||"authenticated"===r;return"auth"===i||"authenticate"===i||"auth_response"===i?s?"ok":"failed":"error"===i||"error"===r?"failed":""===i&&s&&"string"==typeof t.message&&/auth/i.test(t.message)?"ok":null}function Uo(e){if("object"!=typeof e||null===e)return;const t=e,i=e=>{if(void 0!==e)for(const t of["seq","sequence","sequence_number"]){const i=e[t];if("number"==typeof i&&Number.isFinite(i))return i}};return i(t)??i(t.data)}function Yo(e,t,i=Math.random){const r=Math.min(t.maxDelayMs,t.baseDelayMs*2**e);return!1===t.jitter?r:Math.floor(r/2+i()*(r/2))}function Ko(e){if("object"!=typeof e||null===e)return null;const t=e,i=t.data??t,r=Vo(t.topic),s=i.symbol||t.symbol||r?.symbol||"",n=i.exchange||t.exchange||r?.exchange||"";if(i.depth&&(i.depth.buy||i.depth.sell)){const e=(i.depth.buy??[]).map(e=>({price:e.price,qty:e.quantity})),t=(i.depth.sell??[]).map(e=>({price:e.price,qty:e.quantity})),r=i.ltp??i.last_price??e[0]?.price??0,o=Ho(i);return{kind:"depth",symbol:s,exchange:n,depth:{bids:e,asks:t,ltp:r,...Number.isFinite(o)&&o>0?{timeSec:o}:{}}}}const o=i.ltp??i.last_price;return"number"==typeof o?{kind:"ltp",event:{symbol:s,exchange:n,ltp:o,ltq:i.last_trade_quantity??i.ltq,volume:i.volume,timeSec:Ho(i)}}:null}class Xo{constructor(e){Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_factory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sock",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_phase",{enumerable:!0,configurable:!0,writable:!0,value:"idle"}),Object.defineProperty(this,"_epoch",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_ltpCbs",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_depthCbs",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_stateCbs",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_controlCbs",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_orderCbs",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_ordersSubscribed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_subs",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_seq",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_userClosed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_fatal",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_everAuthed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_attempts",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_reconnectTimer",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_authTimer",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_liveTimer",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_rc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_auth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_hbTimeoutMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_hbProbeMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._config=e;const t=e.socketFactory??(e=>new WebSocket(e));this._factory=t;const i=e.reconnect??{};this._rc={enabled:i.enabled??!0,baseDelayMs:i.baseDelayMs??1e3,maxDelayMs:i.maxDelayMs??3e4,maxAttempts:i.maxAttempts??1/0,jitter:i.jitter??!0,random:i.random??Math.random};const r=e.auth??{};this._auth={requireAck:r.requireAck??!0,ackTimeoutMs:r.ackTimeoutMs??5e3},this._hbTimeoutMs=e.heartbeat?.timeoutMs??45e3,this._hbProbeMs=e.heartbeat?.probeMs??5e3}connect(){null===this._sock&&(this._userClosed=!1,this._fatal=!1,this._attempts=0,null!==this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._openSocket())}isReady(){return"ready"===this._phase}_openSocket(){if(null!==this._sock)return;this._phase="connecting",this._emitState("connecting");const e=this._factory(this._config.url),t=++this._epoch;e.onmessage=e=>{t===this._epoch&&this._dispatch(e.data)},e.onopen=()=>{t===this._epoch&&this._onOpen()},e.onclose=()=>{t===this._epoch&&this._onClose()},e.onerror=()=>{t===this._epoch&&this._emitState("error")},this._sock=e,1===e.readyState&&this._onOpen()}onState(e){return this._stateCbs.add(e),()=>this._stateCbs.delete(e)}onControl(e){return this._controlCbs.add(e),()=>this._controlCbs.delete(e)}_emitState(e){for(const t of this._stateCbs)t(e)}_emitControl(e){for(const t of this._controlCbs)t(e)}_warn(e,t){const i={type:"client_warning",code:e,message:t};this._emitControl(i)}_later(e,t){const i=setTimeout(e,t);return i.unref?.(),i}_onOpen(){if("connecting"===this._phase){var e;if(this._phase="authenticating",this._sock?.send((e=this._config.apiKey,JSON.stringify({action:"authenticate",api_key:e}))),!this._auth.requireAck)return this._warn("AUTH_UNACKNOWLEDGED","proceeding without an auth acknowledgement (auth.requireAck is false)"),void this._onAuthenticated();this._authTimer=this._later(()=>this._failConnection("AUTH_TIMEOUT",`no auth acknowledgement within ${this._auth.ackTimeoutMs}ms`),this._auth.ackTimeoutMs)}}_onAuthenticated(){if("authenticating"===this._phase){this._clearTimer("auth"),this._phase="ready",this._attempts=0,this._armLiveness();for(const e of Array.from(this._subs.values()))this._sock?.send(Eo(e.mode,e.symbol,e.exchange,e.depthLevel));this._ordersSubscribed&&this._sock?.send(Ro()),this._everAuthed&&(this._seq.clear(),this._warn("STREAM_RESYNC","reconnected: ticks were missed and the forming bar is stale, refetch it")),this._everAuthed=!0,this._emitState("open")}}_onAuthFailed(e){const t="object"==typeof e&&null!==e&&"string"==typeof e.message?e.message:"authentication refused";this._fatal=!0,this._warn("AUTH_FAILED",t),this._emitState("error"),this._dropSocket(),this._clearTimer("auth"),this._clearTimer("live"),this._phase="fatal",this._emitState("closed")}_failConnection(e,t){this._warn(e,t),this._emitState("error"),this._dropSocket(),this._clearTimer("auth"),this._clearTimer("live"),this._phase="idle",this._emitState("closed"),this._maybeReconnect()}_onClose(){this._sock=null,this._clearTimer("auth"),this._clearTimer("live"),this._phase=this._userClosed?"closed":"idle",this._emitState("closed"),this._maybeReconnect()}_maybeReconnect(){if(this._userClosed||this._fatal||!this._rc.enabled)return;if(this._attempts>=this._rc.maxAttempts)return void("fatal"!==this._phase&&(this._phase="fatal",this._warn("RECONNECT_ABANDONED",`gave up after ${this._attempts} attempts; call connect() to retry`)));const e=Yo(this._attempts++,this._rc,this._rc.random);this._phase="backoff",this._emitState("reconnecting"),this._reconnectTimer=this._later(()=>{this._reconnectTimer=null,this._sock=null,this._openSocket()},e)}_sendGated(e){"ready"===this._phase&&null!==this._sock&&this._sock.send(e)}_armLiveness(){this._hbTimeoutMs<=0||"ready"!==this._phase||(this._clearTimer("live"),this._liveTimer=this._later(()=>this._probeLiveness(),this._hbTimeoutMs))}_probeLiveness(){"ready"===this._phase&&null!==this._sock&&(this._sock.send(JSON.stringify({action:"ping"})),this._liveTimer=this._later(()=>this._failConnection("HEARTBEAT_DEAD",`no answer to a liveness ping within ${this._hbProbeMs}ms`),this._hbProbeMs))}_clearTimer(e){const t="auth"===e?this._authTimer:"live"===e?this._liveTimer:this._reconnectTimer;null!==t&&clearTimeout(t),"auth"===e?this._authTimer=null:"live"===e?this._liveTimer=null:this._reconnectTimer=null}_dropSocket(){const e=this._sock;if(this._sock=null,this._epoch++,null!==e)try{e.close()}catch{}}onLtp(e){return this._ltpCbs.add(e),()=>this._ltpCbs.delete(e)}onDepth(e){return this._depthCbs.add(e),()=>this._depthCbs.delete(e)}subscribe(e,t,i,r){this._subs.set(`${e}:${t}:${i}`,{mode:e,symbol:t,exchange:i,depthLevel:r}),this._sendGated(Eo(e,t,i,r))}unsubscribe(e,t,i){this._subs.delete(`${e}:${t}:${i}`),this._sendGated(Wo(e,t,i))}onOrderUpdate(e){return this._orderCbs.add(e),()=>this._orderCbs.delete(e)}subscribeOrders(){this._ordersSubscribed=!0,this._sendGated(Ro())}unsubscribeOrders(){this._ordersSubscribed=!1,this._sendGated(JSON.stringify({action:"unsubscribe_orders"}))}close(){this._userClosed=!0,this._clearTimer("reconnect"),this._clearTimer("auth"),this._clearTimer("live"),this._dropSocket(),this._subs.clear(),this._ordersSubscribed=!1,this._seq.clear(),this._attempts=0,this._everAuthed=!1,this._fatal=!1,this._phase="closed",this._emitState("closed")}_sequenceOk(e,t){const i=Uo(t);if(void 0===i)return!0;const r=this._seq.get(e);return!(void 0!==r&&i<=r)&&(void 0!==r&&i>r+1&&this._warn("SEQUENCE_GAP",`${e}: ${i-r-1} frame(s) missing, the forming bar is suspect`),this._seq.set(e,i),!0)}_dispatch(e){let t;try{t=JSON.parse(e)}catch{t=e}if(this._armLiveness(),function(e){return"ping"===e||"object"==typeof e&&null!==e&&"ping"===e.type}(t))return void this._sock?.send(JSON.stringify({action:"pong"}));if("authenticating"===this._phase){const e=Go(t);if(null!==e)return this._emitControl(t),void("ok"===e?this._onAuthenticated():this._onAuthFailed(t))}const i=function(e){if("object"!=typeof e||null===e)return null;const t=e;if("order_update"!==t.type)return null;const i=e=>{if("number"==typeof e)return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isNaN(t)?0:t}return 0},r=e=>"string"==typeof e?e:"",s=i(t.trigger_price);return{orderId:r(t.orderid),symbol:r(t.symbol),exchange:r(t.exchange),action:"SELL"===t.action?"SELL":"BUY",quantity:i(t.quantity),price:i(t.price),triggerPrice:s>0?s:void 0,pricetype:""===r(t.pricetype)?"LIMIT":r(t.pricetype),product:r(t.product),status:r(t.order_status).toLowerCase(),filledQuantity:i(t.filled_quantity),pendingQuantity:i(t.pending_quantity),averagePrice:i(t.average_price),rejectionReason:r(t.rejection_reason),mode:r(t.mode)}}(t);if(null!==i){if(!this._sequenceOk("orders",t))return;for(const e of this._orderCbs)e(i);return}const r=Ko(t);if(null===r)return void("object"==typeof t&&null!==t&&this._emitControl(t));const s=t.topic;if("ltp"===r.kind){if(!this._sequenceOk(s??`ltp:${r.event.symbol}.${r.event.exchange}`,t))return;for(const e of this._ltpCbs)e(r.event)}else{if(!this._sequenceOk(s??`depth:${r.symbol}.${r.exchange}`,t))return;for(const e of this._depthCbs)e(r.symbol,r.exchange,r.depth)}}}function Jo(e,t){if(!Number.isFinite(e))return{ok:!1,code:"QTY_INVALID",reason:"quantity must be a finite number"};if(e<=0)return{ok:!1,code:"QTY_INVALID",reason:"quantity must be positive"};const i=t.lotSize??(!0===t.allowFractionalQty?void 0:1);return void 0!==i&&function(e,t){if(!Number.isFinite(t)||t<=0)return!1;const i=e/t,r=Math.round(i);if(!Number.isSafeInteger(r)||r<1)return!0;if(r*t===e)return!1;const s=Math.min(1e-7,8*Number.EPSILON*Math.max(1,Math.abs(i)));return Math.abs(i-r)>s}(e,i)?{ok:!1,code:"QTY_STEP",reason:void 0!==t.lotSize?`quantity ${e} is not a multiple of lot size ${t.lotSize}`:`quantity ${e} must be a whole number`}:void 0!==t.freezeQty&&e>t.freezeQty?{ok:!1,code:"QTY_FREEZE_LIMIT",reason:`quantity ${e} exceeds freeze limit ${t.freezeQty}`}:{ok:!0}}function Zo(e){return Object.assign(new Error(e),{preflight:!0})}class Qo{constructor(e){Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_fetch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_strategy",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_defaultProduct",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ctx",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_claimed",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_verifyMode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_modeCacheMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_mode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_modeAt",{enumerable:!0,configurable:!0,writable:!0,value:0}),this._config=e,this._strategy=e.strategy??"openalgo-charts",this._defaultProduct=e.defaultProduct??"MIS",this._verifyMode=e.verifyMode??"auto",this._modeCacheMs=e.modeCacheMs??5e3,this._now=e.now??Date.now;const t=e.fetchImpl??("undefined"!=typeof fetch?fetch.bind(globalThis):void 0);if(void 0===t)throw new Error("openalgo-charts: no fetch available; pass config.fetchImpl");this._fetch=t}async _post(e,t){const i=await this._fetch(`${this._config.baseUrl}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this._config.apiKey,...t})});if(!i.ok){let t="";try{const e=await i.json();"string"==typeof e.message&&""!==e.message&&(t=`: ${e.message}`)}catch{}throw new Error(`openalgo-charts: ${e} failed (${i.status})${t}`)}const r=await i.json(),s=da(r);return void 0!==s&&(this._mode=s,this._modeAt=this._now()),r}async getServerMode(e=this._modeCacheMs){const t=this._freshMode(e);if(void 0!==t)return t;const i=da(await this._post("/api/v1/analyzer/",{}));if(void 0===i)throw new Error("openalgo-charts: /api/v1/analyzer/ returned no readable mode");return i}serverMode(e=this._modeCacheMs){return this._freshMode(e)}_freshMode(e){if(void 0!==this._mode)return this._now()-this._modeAt<=e?this._mode:void 0}async _assertMode(e){if("off"===this._verifyMode)return;if("live"!==e&&"analyzer"!==e)return;let t=this._freshMode(this._modeCacheMs);if(void 0===t&&("always"===this._verifyMode||"analyzer"===e))try{t=await this.getServerMode()}catch(e){throw Zo(`openalgo-charts: cannot confirm the server mode, no order was sent (${String(e.message??e)})`)}if(void 0!==t&&t!==e)throw Zo(`openalgo-charts: refusing to place, caller expects ${e} mode but the OpenAlgo server is in ${t} mode`)}_assertQuantity(e){const t=e.exchange??"NSE",i=this._config.constraints?.(e.symbol,t)??{},r=Jo(e.qty,i);if(!r.ok)throw Zo(`openalgo-charts: ${e.symbol} ${t}: ${r.reason}`)}_claimToken(e){if(void 0===e||!0===this._config.disableIdempotency)return;const t=this._claimed.get(e);if(void 0!==t)throw Zo("ambiguous"===t?`openalgo-charts: clientToken ${e} may already be live at the broker; check the order book before retrying`:`openalgo-charts: duplicate clientToken ${e}`);return this._claimed.set(e,"inflight"),e}get capabilities(){return this._config.capabilities}async place(e){const t={...e},i={operation:"place",symbol:t.symbol,exchange:t.exchange??"NSE",type:t.type,mode:t.mode};xo(this.capabilities,i),await this._assertMode(t.mode),xo(this.capabilities,i),this._assertQuantity(t);const r=this._claimToken(t.clientToken),s={symbol:t.symbol,exchange:t.exchange??"NSE",action:t.side,pricetype:t.type,product:t.product??this._defaultProduct,quantity:t.qty,price:t.price??0,triggerPrice:t.triggerPrice??0};let n;try{n=await this._post("/api/v1/placeorder",{strategy:this._strategy,symbol:s.symbol,action:s.action,exchange:s.exchange,pricetype:s.pricetype,product:s.product,quantity:t.qty,price:t.price??0,trigger_price:t.triggerPrice??0,disclosed_quantity:0})}catch(e){throw void 0!==r&&this._claimed.set(r,"ambiguous"),e}const o=n.orderid??n.order_id;if(void 0===o)throw new Error("openalgo-charts: placeorder returned no orderid");return void 0!==r&&this._claimed.set(r,"sent"),this._ctx.set(o,s),{orderId:o}}tokenState(e){return this._claimed.get(e)??"unknown"}releaseToken(e){this._claimed.delete(e)}async modify(e,t){const i={...t},r=this._ctx.get(e);if(xo(this.capabilities,{operation:"modify",orderId:e,symbol:r?.symbol,exchange:r?.exchange,type:r?.pricetype}),void 0===r)throw Zo(`openalgo-charts: cannot modify ${e}, unknown order context (place it or load the order book first)`);void 0!==i.qty&&(r.quantity=i.qty),void 0!==i.price&&(r.price=i.price),void 0!==i.triggerPrice&&(r.triggerPrice=i.triggerPrice),await this._post("/api/v1/modifyorder",{orderid:e,strategy:this._strategy,symbol:r.symbol,action:r.action,exchange:r.exchange,pricetype:r.pricetype,product:r.product,quantity:r.quantity,price:r.price,trigger_price:r.triggerPrice,disclosed_quantity:0})}async cancel(e){const t=this._ctx.get(e);xo(this.capabilities,{operation:"cancel",orderId:e,symbol:t?.symbol,exchange:t?.exchange,type:t?.pricetype}),await this._post("/api/v1/cancelorder",{orderid:e,strategy:this._strategy})}async getOrderBook(){const e=await this._post("/api/v1/orderbook",{}),t=Array.isArray(e.data)?e.data:e.data?.orders??[],i=[],r=[];for(let e=0;e<t.length;e++){const s=t[e],n=la(s,`orders[${e}]`);if(!n.ok){r.push({issue:n.issue,raw:s});continue}i.push(n.order);const o=ta(s.exchange),a=ta(s.product);void 0!==o&&void 0!==a&&this._ctx.set(n.order.id,{symbol:n.order.symbol,exchange:o,action:n.order.side,pricetype:n.order.type,product:a,quantity:n.order.qty,price:n.order.price,triggerPrice:n.order.triggerPrice??0})}return r.length>0&&this._config.onDecodeIssue?.({orders:i,quarantined:r}),{orders:i,quarantined:r}}async getOrders(){return(await this.getOrderBook()).orders}async getPositions(){return((await this._post("/api/v1/positionbook",{})).data??[]).map(ca)}}function ea(e){const t="number"==typeof e?e:"string"==typeof e&&""!==e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function ta(e){return"string"==typeof e&&""!==e.trim()?e.trim():void 0}const ia="a non-empty string",ra="a finite number",sa="a number of 0 or more";function na(e,t,i,r){return{ok:!1,issue:{path:e,code:t,expected:i,got:("string"==typeof r?r:String(r)).slice(0,64)}}}const oa={open:"working",pending:"pending",trigger_pending:"working","trigger pending":"working",complete:"filled",cancelled:"cancelled",rejected:"rejected"};function aa(e){return oa[e.trim().toLowerCase()]??"unknown"}function la(e,t="order"){const i=ta(e.orderid);if(void 0===i)return na(`${t}.orderid`,"MISSING",ia,e.orderid);const r=ta(e.symbol);if(void 0===r)return na(`${t}.symbol`,"MISSING",ia,e.symbol);const s=ta(e.action)?.toUpperCase();if("BUY"!==s&&"SELL"!==s)return na(`${t}.action`,"UNKNOWN_ENUM","BUY or SELL",e.action);const n=ta(e.pricetype)?.toUpperCase();if("MARKET"!==n&&"LIMIT"!==n&&"SL"!==n&&"SL-M"!==n)return na(`${t}.pricetype`,"UNKNOWN_ENUM","MARKET, LIMIT, SL or SL-M",e.pricetype);const o=ea(e.quantity);if(void 0===o)return na(`${t}.quantity`,void 0===e.quantity?"MISSING":"NON_FINITE",ra,e.quantity);if(o<0)return na(`${t}.quantity`,"RANGE",sa,e.quantity);const a=void 0===e.filled_quantity?0:ea(e.filled_quantity);if(void 0===a)return na(`${t}.filled_quantity`,"NON_FINITE",ra,e.filled_quantity);const l=void 0===e.price?0:ea(e.price);if(void 0===l)return na(`${t}.price`,"NON_FINITE",ra,e.price);if(l<0)return na(`${t}.price`,"RANGE",sa,e.price);const h=void 0===e.trigger_price?0:ea(e.trigger_price);if(void 0===h)return na(`${t}.trigger_price`,"NON_FINITE",ra,e.trigger_price);const c=ta(e.order_status)??"",d=oa[c.toLowerCase()],u={id:i,symbol:r,side:s,type:n,qty:o,filledQty:a,price:l,triggerPrice:h>0?h:void 0,status:d??"unknown"};return void 0===d&&(u.rawStatus=c),{ok:!0,order:u}}function ha(e){const t=la(e);return t.ok?t.order:{id:ta(e.orderid)??"",symbol:ta(e.symbol)??"",side:ta(e.action)??"",type:ta(e.pricetype)??"",qty:ea(e.quantity)??0,filledQty:ea(e.filled_quantity)??0,price:ea(e.price)??0,status:"unknown",rawStatus:ta(e.order_status)??""}}function ca(e){return{symbol:e.symbol??"",netQty:ea(e.quantity)??0,avgPrice:ea(e.average_price)??0}}function da(e){if("object"!=typeof e||null===e)return;const t=e,i=t.mode??t.data?.mode;if("analyze"===i)return"analyzer";if("live"===i)return"live";const r=t.data?.analyze_mode;return"boolean"==typeof r?r?"analyzer":"live":void 0}class ua{constructor(e,t={}){Object.defineProperty(this,"_tf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_zone",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_cur",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_count",{enumerable:!0,configurable:!0,writable:!0,value:0}),this._tf=e,this._zone=t.timezone}current(){return null===this._cur?null:{...this._cur}}seed(e){Kn(this._tf)&&(this._cur={...e},this._count=0)}onTick(e){const t=null===this._cur;let i=t;if(t||null===this._cur||(i="interval"===this._tf.mode||"calendar"===this._tf.mode?to(this._tf,e.time,this._zone)!==this._cur.time:"ticks"===this._tf.mode?this._count>=this._tf.count:(this._cur.volume??0)>=this._tf.perBar),i){const t=to(this._tf,e.time,this._zone);return this._cur={time:t,open:e.price,high:e.price,low:e.price,close:e.price,volume:e.qty},void 0!==e.oi&&Number.isFinite(e.oi)&&(this._cur.oi=e.oi),this._count=1,{bar:{...this._cur},isNew:!0}}const r=this._cur;return e.price>r.high&&(r.high=e.price),e.price<r.low&&(r.low=e.price),r.close=e.price,r.volume=(r.volume??0)+e.qty,void 0!==e.oi&&Number.isFinite(e.oi)?r.oi=e.oi:delete r.oi,this._count+=1,{bar:{...r},isNew:!1}}}function pa(e){const{bucketing:t}=Yn(e);if("interval"!==t.mode)throw new Error(`openalgo-charts: interval "${e}" is ${t.mode}-bucketed and has no fixed length. Use resolveInterval() and bucketStartOf() instead of intervalToSeconds().`);return t.seconds}class _a{constructor(e){Object.defineProperty(this,"_rest",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_volumeMode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timezone",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_depthLevel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tickMode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subs",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),this._rest=new No(e),this._ws=new Xo({url:e.wsUrl,apiKey:e.apiKey,socketFactory:e.socketFactory,reconnect:e.reconnect,auth:e.auth,heartbeat:e.heartbeat}),this._volumeMode=e.volumeMode??"ltq-sum",this._timezone=e.timezone,this._depthLevel=e.depthLevel,this._tickMode="day-delta"===this._volumeMode?"Quote":"LTP",this._ws.connect()}_acquire(e,t,i,r){const s=`${e}:${t}:${i}`,n=this._subs.get(s);void 0===n?(this._subs.set(s,{count:1,level:r}),this._ws.subscribe(e,t,i,r)):(n.count+=1,void 0!==r&&(void 0===n.level||r>n.level)&&(n.level=r,this._ws.subscribe(e,t,i,r)));let o=!1;return()=>{if(o)return;o=!0;const r=this._subs.get(s);void 0!==r&&(r.count-=1,r.count>0||(this._subs.delete(s),this._ws.unsubscribe(e,t,i)))}}getBars(e){return this._rest.getBars(e)}subscribeBars(e,t,i){const{bucketing:r}=Yn(e.interval),s="interval"===r.mode?this._candleReader(r,t,i):this._aggregatorReader(r,t,i),n=this._ws.onLtp(t=>{t.symbol===e.symbol&&(t.exchange&&e.exchange&&t.exchange!==e.exchange||s(t))}),o=i?.onResync?this._ws.onControl(e=>{"client_warning"===e.type&&"STREAM_RESYNC"===e.code&&i.onResync?.()}):void 0,a=this._acquire(this._tickMode,e.symbol,e.exchange);return()=>{n(),o?.(),a()}}static _tickTime(e){return e.timeSec&&e.timeSec>0?e.timeSec:Math.floor(Date.now()/1e3)}_candleReader(e,t,i){const r=new gn({intervalSec:e.seconds,sessionAnchorSec:e.anchorSec??0,volumeMode:this._volumeMode});return i?.seedFrom&&r.seed(i.seedFrom,i.cumDayVolumeSoFar),e=>{const i=r.onTick({time:_a._tickTime(e),price:e.ltp,ltq:e.ltq,cumDayVolume:e.volume});null!==i&&t(i.bar,i.provisional?{provisional:!0}:void 0)}}_aggregatorReader(e,t,i){const r=new ua(e,{timezone:this._timezone});i?.seedFrom&&Kn(e)&&r.seed(i.seedFrom);const s=function(e,t){if("ltq-sum"===e)return e=>e.ltq??0;let i=t??null;return e=>{const t=e.volume??0,r=null===i?0:t<i?t:t-i;return i=t,Math.max(0,r)}}(this._volumeMode,i?.cumDayVolumeSoFar);return e=>{const i=r.onTick({time:_a._tickTime(e),price:e.ltp,qty:s(e)});t(i.bar)}}subscribeDepth(e,t,i){const r=this._ws.onDepth((i,r,s)=>{i===e.symbol&&(r&&e.exchange&&r!==e.exchange||t(s))}),s=this._acquire("Depth",e.symbol,e.exchange,i?.depthLevel??this._depthLevel);return()=>{r(),s()}}close(){this._subs.clear(),this._ws.close()}}const ba=(e,t)=>{const i=setInterval(e,t);return()=>clearInterval(i)};class fa{constructor(e=60,t=ba){Object.defineProperty(this,"intervalSec",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schedule",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.intervalSec=e,this._schedule=t}async getBars(e){return ma(e.from??17e8,500,this.intervalSec)}subscribeBars(e,t,i){let r=i?.seedFrom?.time??e.from??17e8,s=i?.seedFrom?.close??100,n=19088743;const o=()=>(n^=n<<13,n>>>=0,n^=n>>17,n^=n<<5,n>>>=0,n/4294967295);return this._schedule(()=>{r+=this.intervalSec;const e=s,i=Math.max(1,e+2*(o()-.5)),n=Math.max(e,i)+o(),a=Math.max(.01,Math.min(e,i)-o());t({time:r,open:e,high:n,low:a,close:i,volume:Math.round(1e3+9e3*o())}),s=i},i?.tickMs??1e3)}}function ma(e,t,i){const r=[];let s=100,n=2654435769;const o=()=>(n^=n<<13,n>>>=0,n^=n>>17,n^=n<<5,n>>>=0,n/4294967295);for(let n=0;n<t;n++){const t=2*(o()-.5),a=s,l=Math.max(1,a+t),h=Math.max(a,l)+o(),c=Math.min(a,l)-o();r.push({time:e+n*i,open:a,high:h,low:c,close:l,volume:Math.round(1e3+9e3*o())}),s=l}return r}const ga=1;function va(e,t,i){const r=Gn(e);if(null===r)return null;const s=r.bucketing;return"interval"===s.mode?t+s.seconds:io(s,t,i)}function ya(e){return`${e.symbol}|${e.exchange}|${e.interval}`}function wa(e){const t=new Array(e.length);for(let i=0;i<e.length;i++)t[i]={...e[i]};return t}function xa(e){e?.throwIfAborted()}class Pa{constructor(e,t={}){Object.defineProperty(this,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_backing",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_memory",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_tombstones",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_writes",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_ttlMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_max",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_maxBars",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_barCloses",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_index",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_tick",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_hits",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_misses",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_evictions",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"subscribeBars",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscribeDepth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"getBarsPage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.source=e,this._backing=t.storage,this._ttlMs=t.ttlMs??3e5,this._max=t.max??24,this._maxBars=t.maxBars??25e4,this._now=t.now??(()=>Date.now());const i=t.timezone;this._barCloses=t.barCloses??((e,t)=>va(e,t,i)),"function"==typeof e.subscribeBars&&(this.subscribeBars=(t,i,...r)=>e.subscribeBars(t,i,...r)),"function"==typeof e.subscribeDepth&&(this.subscribeDepth=(t,i,...r)=>e.subscribeDepth(t,i,...r)),"function"==typeof e.getBarsPage&&(this.getBarsPage=t=>e.getBarsPage(t))}async getBars(e){if(xa(e.signal),void 0===e.from||void 0===e.to){const t=await this.source.getBars(e);return xa(e.signal),t}const t=ya(e);if(!0!==e.noCache){const i=await this._lookup(t,e.interval,e.from,e.to);if(xa(e.signal),void 0!==i)return this._hits++,i;this._misses++}xa(e.signal);const i=await this.source.getBars(e);return xa(e.signal),await this._put(t,e.from,e.to,e.interval,i,e.signal),xa(e.signal),i}async getCachedBars(e){if(xa(e.signal),!0===e.noCache||void 0===e.from||void 0===e.to)return;const t=ya(e),i=await this._readEntry(t,e.interval);if(xa(e.signal),void 0===i)return;if(this._now()-i.storedAt>this._ttlMs)return await this._drop(t),void xa(e.signal);const r=this._slice(i,e.from,e.to);return 0!==r.length?(this._remember(t,i),await this._evict(),xa(e.signal),r):void 0}async invalidate(e){if(void 0===e)return this.clear();const t=ya(e);await this._drop(t)}async clear(){const e=new Set([...this._memory.keys(),...this._tombstones]);this._memory.clear(),this._index.clear();for(const t of e)await this._deleteBacking(t)}stats(){let e=0;for(const t of this._index.values())e+=t.bars;return{entries:this._index.size,bars:e,hits:this._hits,misses:this._misses,evictions:this._evictions}}async _lookup(e,t,i,r){const s=await this._readEntry(e,t);if(void 0===s)return;const n=this._now();if(n-s.storedAt>this._ttlMs)return void await this._drop(e);if(i<s.from)return;const o=Math.floor(n/1e3);return r>s.to&&o>=s.nextClose?void 0:(this._remember(e,s),await this._evict(),this._slice(s,i,r))}_slice(e,t,i){const r=[];for(const s of e.bars)if(!(s.time<t)){if(s.time>i)break;r.push({...s})}return r}async _put(e,t,i,r,s,n){const o=this._now(),a=Math.floor(o/1e3),l=s.filter(e=>e.time>=t&&e.time<=i);let h=l.length;for(;h>0;){const e=this._barCloses(r,l[h-1].time);if(null!==e&&e<=a)break;h--}if(0===h)return;if(h>this._maxBars)return;const c=wa(l.slice(0,h)),d=c[c.length-1],u=this._barCloses(r,d.time),p=this._barCloses(r,u)??u,_={version:1,bars:c,from:t,to:Math.min(i,u-1),storedAt:o,nextClose:p};if(!this._validEntry(_,r,o))return;xa(n);const b=Symbol(e);if(this._writes.set(e,b),this._remember(e,_),await this._writeBacking(e,_),this._writes.get(e)!==b)return await this._restoreLatestBacking(e),void xa(n);!0===n?.aborted&&(this._memory.delete(e),this._index.delete(e),this._writes.delete(e),await this._deleteBacking(e),xa(n)),await this._evict(),!0===n?.aborted&&this._writes.get(e)===b&&(this._memory.delete(e),this._index.delete(e),this._writes.delete(e),await this._deleteBacking(e),xa(n)),this._writes.get(e)===b&&this._writes.delete(e)}async _drop(e){this._memory.delete(e),this._index.delete(e),await this._deleteBacking(e)}async _evict(){for(;;){let e,t=0;for(const e of this._index.values())t+=e.bars;if(this._index.size<=this._max&&t<=this._maxBars)return;let i=1/0;for(const[t,r]of this._index)r.lastUsed<i&&(i=r.lastUsed,e=t);if(void 0===e)return;this._evictions++,await this._drop(e)}}_remember(e,t){const i=this._cloneEntry(t);this._memory.set(e,i),this._index.set(e,{lastUsed:++this._tick,bars:i.bars.length})}async _readEntry(e,t){const i=this._memory.get(e);if(void 0===this._backing||this._tombstones.has(e))return i;let r;try{r=await this._backing.get(e)}catch{return i}if(void 0===r)return i;const s=this._now();if(!this._validEntry(r,t,s))return await this._deleteBacking(e),i;const n=this._cloneEntry(r);return void 0!==i&&i.storedAt>=n.storedAt?i:n}_validEntry(e,t,i){if("object"!=typeof e||null===e)return!1;const r=e;if(void 0!==r.version&&1!==r.version)return!1;if(!Number.isFinite(r.from)||!Number.isInteger(r.from))return!1;if(!Number.isFinite(r.to)||!Number.isInteger(r.to))return!1;if(!Number.isFinite(r.storedAt)||r.storedAt<0||r.storedAt>i)return!1;if(!Number.isFinite(r.nextClose)||!Number.isInteger(r.nextClose))return!1;if(r.from>r.to||r.nextClose<=r.to)return!1;if(!Array.isArray(r.bars)||0===r.bars.length)return!1;if(r.bars.length>this._maxBars||this._max<1)return!1;const s=Math.floor(i/1e3);let n=-1/0,o=null;for(const e of r.bars){if(!this._validBar(e)||e.time<=n)return!1;if(e.time<r.from||e.time>r.to)return!1;if(o=this._barCloses(t,e.time),null===o||o>s)return!1;n=e.time}const a=this._barCloses(t,o)??o;return r.nextClose===a}_validBar(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Number.isInteger(t.time)&&(!![t.open,t.high,t.low,t.close].every(Number.isFinite)&&(!(void 0!==t.volume&&!Number.isFinite(t.volume))&&(!(void 0!==t.oi&&!Number.isFinite(t.oi))&&(void 0===t.color||"string"==typeof t.color))))}_cloneEntry(e){const t={bars:wa(e.bars),from:e.from,to:e.to,storedAt:e.storedAt,nextClose:e.nextClose};return void 0!==e.version&&(t.version=e.version),t}async _writeBacking(e,t){if(void 0!==this._backing)try{await this._backing.set(e,this._cloneEntry(t)),this._tombstones.delete(e)}catch{this._tombstones.add(e)}}async _deleteBacking(e){if(void 0!==this._backing)try{await this._backing.delete(e),this._tombstones.delete(e)}catch{this._tombstones.add(e)}}async _restoreLatestBacking(e){const t=this._memory.get(e);void 0===t?await this._deleteBacking(e):await this._writeBacking(e,t)}}function Sa(e,t){return new Pa(e,t)}let Oa;function ka(){if(!Oa){Oa=new Map([{id:"bullish",title:"Bullish bar",when:({bars:e,index:t})=>e[t].close>e[t].open},{id:"bearish",title:"Bearish bar",when:({bars:e,index:t})=>e[t].close<e[t].open},{id:"inside",title:"Inside bar",when:({bars:e,index:t})=>t>0&&e[t].high<e[t-1].high&&e[t].low>e[t-1].low},{id:"outside",title:"Outside bar",when:({bars:e,index:t})=>t>0&&e[t].high>e[t-1].high&&e[t].low<e[t-1].low},{id:"gap-up",title:"Gap up",when:({bars:e,index:t})=>t>0&&e[t].low>e[t-1].high},{id:"gap-down",title:"Gap down",when:({bars:e,index:t})=>t>0&&e[t].high<e[t-1].low}].map(e=>[e.id,Object.freeze(e)]))}return Oa}function Ma(e){if("string"!=typeof e.id||!e.id.trim()||"string"!=typeof e.title||!e.title.trim()||"function"!=typeof e.when)throw new Error("Invalid bar condition");if(ka().has(e.id))throw new Error(`Bar condition id already registered: ${e.id}`);ka().set(e.id,Object.freeze({...e}))}function Ta(e){return ka().delete(e)}function Ca(e){return ka().get(e)}function Ia(){return[...ka().values()]}const ja={armed:"#3b82f6",triggered:"#22c55e",disabled:"#64748b",expired:"#d97706"};function Aa(e,t){return t?"Paused":"armed"===e?"Alert":e[0].toUpperCase()+e.slice(1)}class La extends Ji{constructor(){super(...arguments),Object.defineProperty(this,"_movable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_committedPrice",{enumerable:!0,configurable:!0,writable:!0,value:this.price}),Object.defineProperty(this,"_context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_resolveScale",{enumerable:!0,configurable:!0,writable:!0,value:e=>e.priceScale}),Object.defineProperty(this,"_canAutoscale",{enumerable:!0,configurable:!0,writable:!0,value:()=>!0})}bind(e,t,i,r){this._movable=e,this._committedPrice=t,this._resolveScale=i,this._canAutoscale=r}zOrder(){return"top"}autoscaleInfo(){return this._canAutoscale()?this._context&&this._resolveScale(this._context)!==this._context.priceScale?null:{min:this._committedPrice,max:this._committedPrice}:null}draw(e,t){this._context=t;const i=this._resolveScale(t);e.save(),i!==t.priceScale&&(e.beginPath(),e.rect(0,0,t.plotWidth*t.dpr,t.plotHeight*t.dpr),e.clip()),super.draw(e,{...t,priceScale:i}),e.restore()}hitTest(e,t,i){this._context=i;const r=this._movable?super.hitTest(e,t,{...i,priceScale:this._resolveScale(i)}):null;return r?{...r,zOrder:"top",draggable:!0,cancelOnEscape:!0}:null}coordinateToPrice(e){return this._context?this._resolveScale(this._context).yToPrice(e):void 0}}function za(e){const t=/^alert:(.+):(\d+)$/.exec(e);if(null===t)return null;const i=Number(t[2]);return 0===i||1===i?{id:t[1],index:i}:null}class Fa{constructor(e){Object.defineProperty(this,"_chart",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_lines",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}update(e,t,i,r){if(!this._chart.addPrimitive||!this._chart.removePrimitive)return;if(!t)return void this.remove(e.id);const s=void 0===t.upperPrice?[t.price]:[t.price,t.upperPrice],n=function(e){return"price"===e.source.kind||"indicator"===e.source.kind}(e)&&"armed"===e.state&&!i,{source:o}=e,a=()=>"indicator"===o.kind?this._chart.indicators?.().find(e=>e.id===o.instanceId)?.series(o.plotKey)?.priceScale():"price"===o.kind?this._chart.primarySeries?.()?.priceScale():void 0,l=e=>"indicator"===o.kind?a()??e.priceScale:"price"===o.kind?e.readoutPriceScale??e.priceScale:e.priceScale,h=()=>{const e=this._chart.panes?.()[t.paneIndex]?.priceScale;return void 0===e||(a()??e)===e};let c=this._lines.get(e.id);!c||c.pane===t.paneIndex&&c.lines.length===s.length||(this.remove(e.id),c=void 0),c||(c={pane:t.paneIndex,lines:[]},this._lines.set(e.id,c));for(let o=0;o<s.length;o++){const a={price:s[o],color:ja[e.state],lineStyle:"armed"===e.state?"dashed":"dotted",badge:Aa(e.state,i),leftLabel:e.title+(void 0===r?"":` (${r})`)+(2===s.length?0===o?" (lower)":" (upper)":""),cursor:n?"ns-resize":void 0},d=c.lines[o];if(d){d.bind(n,s[o],l,h);const e=d.options();Object.entries(a).some(([t,i])=>e[t]!==i)&&d.setOptions(a)}else{const i=new La({...a,id:`alert:${e.id}:${o}`});i.bind(n,s[o],l,h),c.lines.push(i),this._chart.addPrimitive(i,t.paneIndex)}}}preview(e,t){const i=za(e);i&&this._lines.get(i.id)?.lines[i.index]?.setPrice(t)}coordinateToPrice(e,t){const i=za(e);return i?this._lines.get(i.id)?.lines[i.index]?.coordinateToPrice(t):void 0}remove(e){const t=this._lines.get(e);if(t){this._lines.delete(e);for(const e of t.lines)this._chart.removePrimitive?.(e)}}destroy(){for(const e of this._lines.keys())this.remove(e)}}const Ba=new WeakSet;let $a=1;const Na=e=>{const t=e.getDataContext();return{symbol:t?.symbol,exchange:t?.exchange,interval:t?.interval}},Da=(e,t)=>e.symbol===t.symbol&&e.exchange===t.exchange,Ra=(e,t)=>Da(e,t)&&e.interval===t.interval;class Ea{constructor(e,t={}){if(Object.defineProperty(this,"_chart",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_records",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_hovered",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_off",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_drawings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_spentLines",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_visuals",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timerAt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_paused",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_restoring",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_replay",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_revision",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_drag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Ba.has(e))throw new Error("An alert controller already owns this chart");this._now=t.now??(()=>Date.now()/1e3),this._drawings=t.drawings,this._spentLines=t.spentLines??"show",this._visuals=!1===t.visuals?void 0:new Fa(e),Ba.add(e),this._off=[e.on("data:update",e=>this._onData(e)),e.on("data:context",()=>this._seedAll()),e.on("objects:change",()=>this._onObjects()),e.on("paneMoved",()=>this._onObjects()),e.on("state:restore:start",()=>{this._hovered=void 0,this._cancelDrag(),this._restoring=!0,this._revision++}),e.on("state:restore:end",()=>{this._restoring=!1,this._seedAll()}),e.on("alerts:restore",e=>this.fromJSON(e)),e.on("replay:start",()=>{this._replay=!0,this._seedAll()}),e.on("replay:stop",()=>{this._replay=!1,this._seedAll()}),e.on("destroy",()=>this.destroy()),e.on("drag:start",e=>this._startDrag(e)),e.on("hover",e=>{const t=e?.id,i="string"==typeof t?za(t):null;this._hovered=null!==i&&this._records.has(i.id)?i.id:void 0}),e.on("drag",e=>this._onDrag(e,!1)),e.on("drag:end",e=>this._onDrag(e,!0)),e.on("drag:cancel",e=>{e.id===this._drag?.externalId&&this._cancelDrag()})];try{const t=e.alertState?.();void 0!==t&&this.fromJSON(t)}catch(e){throw this.destroy(),e}}_dragAvailability(e,t){const i=e.alert.source;return this._destroyed||this._restoring||"armed"!==e.alert.state||this._records.get(e.alert.id)!==e||"price"!==i.kind&&"indicator"!==i.kind||0!==t&&(1!==t||void 0===("price"===i.kind?i.upperPrice:i.upperValue))?{available:!1}:this.availability(e.alert.id)}hovered(){const e=void 0===this._hovered?void 0:this._records.get(this._hovered);return e&&this._dragAvailability(e,0).available?e.alert.id:void 0}_dragPrice(e,t,i){const r=e.point?.y,s=("number"==typeof r&&Number.isFinite(r)?this._visuals?.coordinateToPrice(t,r):void 0)??e.price;if("number"!=typeof s||!Number.isFinite(s))return;const n=za(t),o=n&&this._records.get(n.id)?.alert.source,a="price"===o?.kind?this._chart.primarySeries?.()?.priceScale():"indicator"===o?.kind?this._chart.indicators?.().find(e=>e.id===o.instanceId)?.series(o.plotKey)?.priceScale():void 0,l=i??e.paneIndex,h=a?d(s,a.options.minMove):"number"==typeof l?this._chart.snapPrice?.(l,s)??s:s;let c=Number.isFinite(h)?h:s;if(n&&("price"===o?.kind||"indicator"===o?.kind)){const e=0===n.index?"price"===o.kind?o.upperPrice:o.upperValue:"price"===o.kind?o.price:o.value;if(void 0!==e&&(0===n.index?c>e:c<e)){c=e;const t=a?.options.minMove??0;if(t>0){c=d(e,t);const i=Number.EPSILON*Math.max(1,Math.abs(e))*4;Math.abs(c-e)<=i?c=e:(0===n.index?c>e:c<e)&&(c=d(e+(0===n.index?-t:t),t))}else if(!a&&"number"==typeof l&&this._chart.snapPrice&&(c=this._chart.snapPrice(l,e),!Number.isFinite(c)||(0===n.index?c>e:c<e)))return}}return c}_startDrag(e){if(this._cancelDrag(),"string"!=typeof e.id)return;const t=za(e.id),i=t&&this._records.get(t.id);if(!t||!i)return;const r=this._dragAvailability(i,t.index),s=this._dragPrice(e,e.id,r.paneIndex);!r.available||void 0===r.paneIndex||void 0===s||void 0!==e.paneIndex&&e.paneIndex!==r.paneIndex||(this._drag={externalId:e.id,record:i,index:t.index,paneIndex:r.paneIndex,startPrice:s,startY:"number"==typeof e.point?.y?e.point.y:void 0,moved:!1})}_cancelDrag(e){const t=this._drag;if(!t||void 0!==e&&t.record.alert.id!==e)return;this._drag=void 0;const i=this._records.get(t.record.alert.id);i&&this._syncVisual(i)}_onDrag(e,t){this._expireDue();const i=this._drag;if(!i||e.id!==i.externalId)return;const r=this._dragAvailability(i.record,i.index);if(!r.available||r.paneIndex!==i.paneIndex||void 0!==e.paneIndex&&e.paneIndex!==i.paneIndex)return void this._cancelDrag();const s=this._dragPrice(e,i.externalId,i.paneIndex);if(void 0===s)return void(t&&this._cancelDrag());const n=e.point?.y;i.moved||(i.moved=void 0!==i.startY&&"number"==typeof n?n!==i.startY:s!==i.startPrice);const o=i.record.alert.source;if("price"!==o.kind&&"indicator"!==o.kind)return void this._cancelDrag();const a="price"===o.kind?o.price:o.value,l="price"===o.kind?o.upperPrice:o.upperValue,h=0===i.index?Math.min(s,l??1/0):Math.max(s,a);if(!t)return void(i.moved&&this._visuals?.preview(i.externalId,h));if(this._cancelDrag(),!i.moved||h===(0===i.index?a:l))return;const c="price"===o.kind?{...o,...0===i.index?{price:h}:{upperPrice:h}}:{...o,...0===i.index?{value:h}:{upperValue:h}};this.update(i.record.alert.id,{source:c}),this._chart.emit("alerts:changed",{id:i.record.alert.id,reason:"dragged"})}add(e){this._assertAlive();let t=e.id;if(void 0===t)do{t="alert-"+$a++}while(this._records.has(t));if(this._records.has(t))throw new Error(`Duplicate alert id: ${t}`);const i={...e,id:t,source:{...e.source},condition:e.condition??("barCondition"===e.source.kind?"matches":"crossing"),policy:e.policy??"onBarClose",repeat:e.repeat??"once",state:e.state??"armed",title:e.title??"Chart alert",cooldownSeconds:e.cooldownSeconds??0,scope:Na(this._chart)};yi(i),i.source=wi(i).source,"armed"===i.state&&void 0!==i.expiresAt&&this._now()>=i.expiresAt&&(i.state="expired");const r={alert:i};return this._seed(r),this._records.set(t,r),this._syncVisual(r),this._scheduleExpiry(),this._saveState(),this._chart.emit("alert:created",{alert:wi(i)}),wi(i)}update(e,t){this._assertAlive();const i=this._records.get(e);if(!i)return;const r={...i.alert,...t,id:e,source:{...t.source??i.alert.source}};yi(r),r.source=wi(r).source,this._cancelDrag(e),"armed"===r.state&&void 0!==r.expiresAt&&this._now()>=r.expiresAt&&(r.state="expired");const s={...i,alert:r};return this._seed(s),this._records.set(e,s),this._syncVisual(s),this._scheduleExpiry(),this._saveState(),this._chart.emit("alert:updated",{alert:wi(r)}),wi(r)}remove(e){return this._remove(e,"removed")}_remove(e,t){const i=this._records.get(e);return!!i&&(this._cancelDrag(e),this._records.delete(e),this._hovered===e&&(this._hovered=void 0),this._visuals?.remove(e),this._scheduleExpiry(),this._saveState(),this._chart.emit("alert:removed",{alert:wi(i.alert),reason:t}),!0)}list(){return[...this._records.values()].map(e=>wi(e.alert))}toJSON(){return Oi({version:1,alerts:this.list()})}fromJSON(e){this._assertAlive();const t=Oi(e),i=new Map,r=[];for(const e of t.alerts){const t=e.source;let s;"drawing"===t.kind&&this._drawings&&null==this._drawings.get(t.drawingId)&&(s="drawing-missing");const n="indicator"===t.kind?t:"drawing"===t.kind?t.input:void 0;if(!s&&n&&this._chart.indicators){const e=this._chart.indicators().find(e=>e.id===n.instanceId);e?e.series(n.plotKey)||(s="plot-missing"):s="indicator-missing"}if(s){r.push({alert:e,reason:s});continue}if("armed"===e.state&&void 0!==e.expiresAt&&this._now()>=e.expiresAt&&(e.state="expired"),void 0!==e.lastTriggeredTime){const t="onTouch"===e.policy?"lastTouchedTime":"lastClosedTime";e[t]=Math.max(e[t]??-1/0,e.lastTriggeredTime)}const o={alert:e};this._seed(o),i.set(e.id,o)}this._cancelDrag(),this._revision++,this._visuals?.destroy(),this._hovered=void 0,this._records.clear();for(const[e,t]of i)this._records.set(e,t),this._syncVisual(t);this._scheduleExpiry(),this._saveState();for(const e of r){if(this._destroyed)break;this._chart.emit("alert:removed",{...e,alert:wi(e.alert)})}this._destroyed||this._chart.emit("alerts:restored",{alerts:this.list()})}_saveState(){this._destroyed||this._chart.setAlertState?.({version:1,alerts:this.list()})}availability(e){const t=this._records.get(e);if(!t)return{available:!1,reason:"Alert is unavailable"};if(this._paused||this._replay)return{available:!1,reason:"Alerts are paused"};const i=Na(this._chart);if(!Da(t.alert.scope,i))return{available:!1,reason:"Instrument context differs"};if(t.alert.scope.interval!==i.interval)return{available:!1,reason:`Switch to ${t.alert.scope.interval??"the original timeframe"} to evaluate this alert`};const{source:r}=t.alert,s=this._chart.primaryBars();if("drawing"===r.kind){const e=this._drawings?.alertInfo(r.drawingId);if(!e?.available)return{available:!1,reason:e?.reason??"Drawing provider is unavailable"};if(0!==e.paneIndex&&!r.input)return{available:!1,reason:"Select an input plot for this drawing pane"};const i=this._drawingValue(t.alert,s[s.length-1]?.time);return i?{available:!0,paneIndex:i.paneIndex}:{available:!1,reason:"Drawing level, time, input plot or condition is unavailable",paneIndex:e.paneIndex}}if("indicator"===r.kind){const e=this._plot(r);return e.values?Number.isFinite(e.values[s.length-1])?{available:!0,paneIndex:e.paneIndex}:{available:!1,reason:"Plot value is unavailable",paneIndex:e.paneIndex}:{available:!1,reason:e.reason}}return"barCondition"!==r.kind||Ca(r.id)?s.length?{available:!0,paneIndex:0}:{available:!1,reason:"Source data is unavailable"}:{available:!1,reason:"Bar condition is unavailable"}}enable(e){return this.update(e,{state:"armed"})}disable(e){return this.update(e,{state:"disabled"})}setPaused(e){this._assertAlive(),this._paused!==e&&(this._paused=e,this._seedAll())}destroy(){if(!this._destroyed){this._destroyed=!0,this._drag=void 0,this._revision++;for(const e of this._off)e();this._clearTimer(),this._visuals?.destroy(),this._hovered=void 0,this._records.clear(),Ba.delete(this._chart)}}_assertAlive(){if(this._destroyed)throw new Error("Alert controller is destroyed")}_seed(e){if(!Ra(e.alert.scope,Na(this._chart)))return e.tail=void 0,e.value=void 0,void(e.plotPane=void 0);const t=this._chart.primaryBars(),i=t[t.length-1];if(e.tail=i?{...i}:void 0,"indicator"===e.alert.source.kind){const i=this._plot(e.alert.source);e.value=this._reading(i.values,t.length-1),e.plotPane=i.paneIndex}else"drawing"===e.alert.source.kind&&e.alert.source.input&&(e.value=this._reading(this._plot(e.alert.source.input).values,t.length-1));const r=t[t.length-2]?.time;void 0!==r&&(e.alert.lastClosedTime=Math.max(e.alert.lastClosedTime??-1/0,r))}_seedAll(){this._cancelDrag(),this._revision++;for(const e of this._records.values())this._seed(e),this._syncVisual(e);this._restoring||(this._saveState(),!this._destroyed&&this._records.size&&this._chart.emit("alerts:checkpoint",{}))}_onObjects(){if(this._destroyed||this._restoring)return;this._cancelDrag();const e=++this._revision;for(const t of[...this._records.values()]){if(this._destroyed||this._revision!==e)break;const i=t.alert.source;"drawing"===i.kind&&this._drawings&&null==this._drawings.get(i.drawingId)?this._remove(t.alert.id,"drawing-removed"):"indicator"!==i.kind&&"drawing"!==i.kind||(this._seed(t),this._syncVisual(t))}}_syncVisual(e){if(!this._visuals)return;const{alert:t}=e,{source:i}=t;if("hide"===this._spentLines&&("triggered"===t.state||"expired"===t.state))return void this._visuals.update(t,void 0,!0);const r=Na(this._chart),s=Ra(t.scope,r);let n;if("price"===i.kind&&Da(t.scope,r)&&(n={price:i.price,upperPrice:i.upperPrice,paneIndex:0}),s&&("indicator"===i.kind&&void 0!==e.plotPane&&(n={price:i.value,upperPrice:i.upperValue,paneIndex:e.plotPane}),"drawing"===i.kind)){const e=this._chart.primaryBars();n=this._drawingValue(t,e[e.length-1]?.time)}this._visuals.update(t,n,this._paused||this._replay||!s&&"armed"===t.state,s?void 0:t.scope.interval??"original timeframe")}_onData(e){if(this._destroyed||this._restoring)return;const t=++this._revision;if(this._expireDue(),this._drag&&!this._dragAvailability(this._drag.record,this._drag.index).available&&this._cancelDrag(),this._destroyed||t!==this._revision)return;if(this._paused||this._replay)return;if("update"!==e.kind)return void this._seedAll();const i=this._chart.primaryBars(),r=i[i.length-1];if(!r||e.time!==r.time)return;const s=Na(this._chart);let n=!1;for(const e of[...this._records.values()]){if(this._destroyed||t!==this._revision)break;if(this._records.get(e.alert.id)!==e)continue;if(!Ra(e.alert.scope,s))continue;const o=e.tail;if(e.tail={...r},"drawing"===e.alert.source.kind&&o?.time!==r.time&&this._syncVisual(e),this._destroyed||t!==this._revision)break;if("armed"!==e.alert.state||!o)continue;const{alert:a}=e;if("onBarClose"===a.policy){const s=i.length-2,l=i[s];if(r.time<=o.time||!l||l.time!==o.time||void 0!==a.lastClosedTime&&l.time<=a.lastClosedTime)continue;a.lastClosedTime=l.time,n=!0;const h=this._closedMatch(e,i,s);void 0!==h&&t===this._revision&&this._records.get(a.id)===e&&this._trigger(e,l,s,h)}else{if(r.time<o.time||void 0!==a.lastTouchedTime&&r.time<=a.lastTouchedTime)continue;const s=this._touchMatch(e,i,o);void 0!==s&&t===this._revision&&this._records.get(a.id)===e&&(a.lastTouchedTime=r.time,n=!0,this._trigger(e,r,i.length-1,s))}}n&&(this._saveState(),this._destroyed||this._chart.emit("alerts:checkpoint",{}))}_plot(e){const t=this._chart.indicators?.().find(t=>t.id===e.instanceId);if(!t)return{reason:"Indicator instance is unavailable"};if(!t.series(e.plotKey))return{reason:"Indicator plot is unavailable"};const i=t.values()[e.plotKey],r=t.indicatorId&&ii(t.indicatorId)&&ti(t.indicatorId).plots.some(t=>t.key===e.plotKey&&t.overlay);return i?{values:i,paneIndex:r?0:t.paneIndex}:{reason:"Indicator plot is unavailable"}}_reading(e,t){const i=e?.[t];return"number"==typeof i&&Number.isFinite(i)?i:void 0}_closedMatch(e,t,i){const{source:r,condition:s}=e.alert;if("barCondition"===r.kind)return this._barMatch(e,t,i)?t[i].close:void 0;if("drawing"===r.kind){const n=this._drawingValue(e.alert,t[i].time),o=this._drawingValue(e.alert,t[i-1]?.time),a=r.input?this._plot(r.input).values:void 0,l=r.input?this._reading(a,i):t[i].close,h=r.input?this._reading(a,i-1):t[i-1]?.close;if(!n||void 0===l)return;return mi(s,o?h:void 0,l,n.price,n.upperPrice,o?.price,o?.upperPrice)?l:void 0}if("price"===r.kind)return mi(s,t[i-1]?.close,t[i].close,r.price,r.upperPrice)?t[i].close:void 0;const n=this._plot(r).values,o=this._reading(n,i);return void 0!==o&&mi(s,this._reading(n,i-1),o,r.value,r.upperValue)?o:void 0}_touchMatch(e,t,i){const{source:r,condition:s}=e.alert,n=t.length-1,o=t[n];if("barCondition"===r.kind)return this._barMatch(e,t,n)?o.close:void 0;if("drawing"===r.kind)return this._drawingTouch(e,r,t,i);if("indicator"===r.kind){const t=this._plot(r).values,a=this._reading(t,n),l=o.time>i.time?this._reading(t,n-1):e.value;if(e.value=a,void 0===a||a===l&&o.time===i.time)return;return mi(s,l,a,r.value,r.upperValue)?a:void 0}const a=o.time>i.time;if(!(a||o.close!==i.close||o.high>i.high||o.low<i.low))return;const l=Math.max(i.close,o.close,a||o.high>i.high?o.high:-1/0),h=Math.min(i.close,o.close,a||o.low<i.low?o.low:1/0);return gi(s,i.close,h,l,r.price,r.upperPrice)}_barMatch(e,t,i){const r=e.alert.source;if("barCondition"!==r.kind||e.errorTime===t[i].time)return!1;const s=Ca(r.id);if(!s)return!1;try{return!0===s.when({bars:t.slice(0,i+1),index:i})}catch(r){return e.errorTime=t[i].time,this._chart.emit("alert:error",{alert:wi(e.alert),error:r}),!1}}_drawingValue(e,t){const i=e.source;if("drawing"!==i.kind||void 0===t)return;const r=this._drawings?.valueAt(i.drawingId,t,i.level);if(!r||0!==r.paneIndex&&!i.input)return;if(i.input&&this._plot(i.input).paneIndex!==r.paneIndex)return;return("enteringRange"===e.condition||"leavingRange"===e.condition)===(void 0!==r.upperPrice)?r:void 0}_drawingTouch(e,t,i,r){const s=i[i.length-1],n=this._drawingValue(e.alert,s.time),o=this._drawingValue(e.alert,r.time);if(t.input){const a=this._plot(t.input).values,l=this._reading(a,i.length-1),h=s.time>r.time?this._reading(a,i.length-2):e.value;if(e.value=l,!n||void 0===l||l===h&&s.time===r.time)return;return mi(e.alert.condition,o?h:void 0,l,n.price,n.upperPrice,o?.price,o?.upperPrice)?l:void 0}if(!n||!o)return;const a=s.time>r.time;if(!a&&s.close===r.close&&s.high<=r.high&&s.low>=r.low)return;const l=Math.max(r.close,s.close,a||s.high>r.high?s.high:-1/0),h=Math.min(r.close,s.close,a||s.low<r.low?s.low:1/0);return gi(e.alert.condition,r.close,h,l,n.price,n.upperPrice,o.price,o.upperPrice)}_trigger(e,t,i,r){const{alert:s}=e,n=this._now();if(void 0!==s.expiresAt&&n>=s.expiresAt)return void this._expireDue();if(void 0!==s.lastTriggeredAt&&n-s.lastTriggeredAt<s.cooldownSeconds)return;this._cancelDrag(s.id),s.lastTriggeredAt=n,s.lastTriggeredTime=t.time,"once"===s.repeat&&(s.state="triggered"),this._syncVisual(e),this._scheduleExpiry(),this._saveState();const o={alertId:s.id,title:s.title,message:s.message,time:t.time,index:i,price:r,alert:wi(s)};this._chart.emit("alert:triggered",o)}_expireDue(){const e=this._now(),t=[];for(const i of this._records.values()){const{alert:r}=i;"armed"===r.state&&void 0!==r.expiresAt&&e>=r.expiresAt&&(this._cancelDrag(r.id),r.state="expired",this._syncVisual(i),t.push(i))}this._scheduleExpiry(),t.length&&this._saveState();for(const e of t){if(this._destroyed)break;this._records.get(e.alert.id)===e&&this._chart.emit("alert:expired",{alert:wi(e.alert)})}}_clearTimer(){void 0!==this._timer&&clearTimeout(this._timer),this._timer=void 0,this._timerAt=void 0}_scheduleExpiry(){if(this._destroyed)return;let e;for(const{alert:t}of this._records.values())"armed"===t.state&&void 0!==t.expiresAt&&(e=Math.min(e??1/0,t.expiresAt));e!==this._timerAt&&(this._clearTimer(),void 0!==e&&(this._timerAt=e,this._timer=setTimeout(()=>{this._timer=void 0,this._timerAt=void 0,this._destroyed||this._expireDue()},Math.max(1,Math.min(2147483647,1e3*(e-this._now())))),this._timer.unref?.()))}}const Wa={crossing:"Crossing",crossingUp:"Crossing up",crossingDown:"Crossing down",greaterThan:"Above",lessThan:"Below",enteringRange:"Entering range",leavingRange:"Leaving range",matches:"Matches"},qa=["crossing","crossingUp","crossingDown","greaterThan","lessThan"],Ha=["enteringRange","leavingRange"];function Va(e,t){const i="barCondition"===e.kind?["matches"]:"drawing"===e.kind?"band"===e.level?Ha:qa:[...qa,...Ha],r=t&&i.includes(t)?t:i[0],s=Ha.includes(r),n=[{key:"title",type:"text",label:"Name",default:"Chart alert"},{key:"condition",type:"select",label:"Condition",default:r,options:i.map(e=>({value:e,label:Wa[e]}))}];if("price"===e.kind||"indicator"===e.kind){const t="price"===e.kind;n.push({key:t?"price":"value",type:"number",label:s?"Lower bound":"Threshold",default:t?e.price:e.value,step:.01}),s&&n.push({key:t?"upperPrice":"upperValue",type:"number",label:"Upper bound",default:t?e.upperPrice??e.price:e.upperValue??e.value,step:.01})}return n.push({key:"policy",type:"select",label:"Evaluate",default:"onBarClose",options:[{value:"onBarClose",label:"Bar close"},{value:"onTouch",label:"Intrabar touch"}]},{key:"repeat",type:"select",label:"Repeat",default:"once",options:[{value:"once",label:"Once"},{value:"everyTime",label:"Every match"}]},{key:"cooldownSeconds",type:"number",label:"Cooldown (seconds)",default:0,min:0,step:1},{key:"expiresAt",type:"text",label:"Expires",default:"",tooltip:"Leave empty for no expiry."},{key:"message",type:"text",label:"Message",default:""},{key:"enabled",type:"boolean",label:"Enabled",default:!0}),n}export{Ui as ALT_PRESET,Ea as AlertController,ga as BAR_CACHE_VERSION,Yi as BUILTIN_COMMANDS,Pa as BarCache,Cn as BuySellButtons,ki as CHART_STATE_VERSION,gn as CandleBuilder,At as Canvas2dBackend,Jr as Chart,ms as ChartObjects,Ar as ChartTable,as as ComparisonController,mn as DEFAULT_CANDLE_BUILDER_OPTIONS,j as DEFAULT_CANDLE_STYLE,Tr as DEFAULT_CHART_TABLE_OPTIONS,X as DEFAULT_HISTOGRAM_STYLE,Gi as DEFAULT_KEYMAP,m as DEFAULT_PRICE_SCALE_OPTIONS,$t as DEFAULT_THEME,Se as DEFAULT_TIMEZONE,zr as DEFAULT_TIME_NAVIGATOR_OPTIONS,y as DEFAULT_TIME_SCALE_OPTIONS,Zi as DEFAULT_TRADING_COLORS,ji as DEFAULT_ZOOM_GLIDE_OPTIONS,Fo as DataLoadingController,mr as EventMarkers,fa as FakeDataFeed,Mo as HistoryRequestPool,Ut as INDICATOR_LINE_STYLES,Xt as INDICATOR_PLOT_STYLES,Jt as INDICATOR_SOURCES,de as IST_OFFSET_SECONDS,di as IndicatorBackground,ci as IndicatorDrawings,ai as IndicatorFill,Zt as IndicatorInputError,vo as Instrument,i as InvalidationLevel,ln as LINK_CROSSHAIR_ALPHA,hn as LinkCrosshair,bn as LinkGroup,Er as LogoWatermark,No as OpenAlgoDataFeed,_a as OpenAlgoLiveDataFeed,Qo as OpenAlgoTradeFeed,Xo as OpenAlgoWsFeed,vn as PRICE_LEVEL_KINDS,Kr as PRICE_SCALE_MODES,zt as Pane,Mr as PaneLegend,Mn as PriceLevels,Ji as PriceLine,v as PriceScale,Qs as ReplayController,an as ReplayGroup,Tn as ReplayShade,T as SCALE_FONT_MAX,M as SCALE_FONT_MIN,_r as SeriesMarkers,Xi as ShortcutManager,Gt as SvgContext,Nt as SvgLinearGradient,qr as TextWatermark,ua as TickBarAggregator,Fr as TimeNavigator,w as TimeScale,sr as TradeMarkersPrimitive,wo as TradingCapabilityError,nr as TradingController,Nn as UnknownIntervalError,e as VERSION,Ai as ZoomGlide,cs as addComparison,Va as alertSettingsSchema,os as alignToPrimary,Us as applyChartSettings,xo as assertTradingCapability,Fn as atr,g as autoscaleRange,Ot as backendDegradation,Yo as backoffDelayMs,ya as barCacheKey,va as barCloseSec,lr as beginPick,St as bestHit,o as bitmapSize,to as bucketStartOf,Ze as calendarPeriodFlags,z as candleGeometry,L as candleTier,Vs as chartSettingsSchema,yo as checkTradingCapability,h as clamp,Go as classifyAuthAck,Gr as compactVolume,hs as comparisonController,Pn as computePriceLevels,he as conflateBars,ce as conflateItems,ae as conflationGroupSize,Zr as createChart,fn as createLinkGroup,jt as createRenderBackend,Ft as darkTheme,S as dashPattern,la as decodeOrder,pr as drawLabel,ur as drawShape,dr as effectiveMarkerPx,In as ema,jn as emaSeries,ue as epochMsToUtcSeconds,qi as eventToCombo,_s as exportChartDataCsv,vs as filterLinkAppearance,cn as followerIndex,dn as followerRange,Wi as formatCombo,xe as formatIstCrosshairLabel,ye as formatIstDate,fe as formatIstTime,me as formatIstTimeSeconds,Eo as formatSubscribe,Wo as formatUnsubscribe,Ke as formatZonedCrosshairLabel,Ue as formatZonedDate,Ve as formatZonedTime,Ge as formatZonedTimeSeconds,G as fromGradient,ma as generateBars,Ca as getBarCondition,se as getChartType,ti as getIndicator,ii as hasIndicator,rt as inSessionAt,si as indicatorDefaults,Kt as indicatorStyleInputs,ro as intervalParts,pa as intervalToSeconds,ao as isDailyInterval,oo as isIntradayInterval,Un as isKnownInterval,Pe as isNewIstDay,ze as isNewZonedDay,Be as isNewZonedMonth,De as isNewZonedPeriod,$e as isNewZonedQuarter,Fe as isNewZonedWeek,Ne as isNewZonedYear,f as isRebasing,rs as isReplaying,Vi as isReservedCombo,no as isSecondsInterval,lo as isTickInterval,Kn as isTimeBucketed,Ri as isValidCombo,Te as isValidTimezone,Mi as isWhitespace,pe as istStringToUtcSeconds,On as lastPriceLevelFromSeriesStyle,c as lerp,Bt as lightTheme,$o as mapHistoryResponse,ha as mapOrder,aa as mapOrderStatus,ca as mapPosition,cr as markerSizePx,le as mergeBars,io as nextBucketStart,_ as niceTicks,Di as normalizeCombo,A as optimalBarWidth,Oi as parseAlertsDocument,Ni as parseCombo,Ko as parseMessage,tt as parseSessionSpec,Vo as parseTopic,Yt as plotStyleKeys,b as precisionForStep,Gs as readChartSettings,Uo as readSequence,Ma as registerBarCondition,re as registerChartType,ei as registerIndicator,qn as registerInterval,Mt as registerRenderBackend,Ia as registeredBarConditions,ne as registeredChartTypes,ri as registeredIndicators,Vn as registeredIntervals,Ct as registeredRenderBackends,xt as resolveCrosshairStyle,O as resolveGridStyle,Yn as resolveInterval,I as resolvePlotMargins,It as resolveRenderBackend,C as resolveScaleStyle,d as roundToTick,Bo as rowTimeToUtcSeconds,An as rsi,Ln as rsiSeries,kn as seriesStyleForLastPriceLevel,st as sessionFlags,Je as sessionStartFlags,Xe as sessionStartIndices,Co as sharedHistoryRequests,a as snapToDevicePixel,ni as sourceValue,oi as sourceValues,We as startOfZonedDay,He as startOfZonedMonth,qe as startOfZonedWeek,Bn as supertrend,$n as supertrendSeries,jr as tableOrigin,Ti as toBar,zn as trueRange,Gn as tryResolveInterval,Ta as unregisterBarCondition,Hn as unregisterInterval,Tt as unregisterRenderBackend,ge as utcSecondsToIstDateString,_e as utcSecondsToIstParts,Ye as utcSecondsToZonedDateString,Ie as utcSecondsToZonedParts,t as version,V as verticalGradient,Rr as watermarkRect,R as withAlpha,Sa as withBarCache,Le as zoneOffsetSeconds,je as zonedDayIndex,Re as zonedStringToUtcSeconds,Ee as zonedWallClockToUtcSeconds,Ae as zonedWeekIndex};
|
|
1
|
+
const e="2.5.4";function t(){return e}const i={None:0,Cursor:1,Light:2,Full:3};class s{constructor(e=i.None){Object.defineProperty(this,"_globalLevel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_panes",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_timeScaleOps",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this._globalLevel=e}get globalLevel(){return this._globalLevel}invalidateGlobal(e){e>this._globalLevel&&(this._globalLevel=e)}invalidatePane(e,t){var i,s;this._panes.set(e,(i=this._panes.get(e),s=t,void 0===i?{...s}:{level:Math.max(i.level,s.level),autoScale:i.autoScale||s.autoScale}))}paneInvalidation(e){return this._panes.get(e)}panes(){return this._panes}addTimeScaleOp(e){this._timeScaleOps.push(e)}timeScaleOps(){return this._timeScaleOps}isEmpty(){return this._globalLevel===i.None&&0===this._panes.size&&0===this._timeScaleOps.length}merge(e){this.invalidateGlobal(e._globalLevel);for(const[t,i]of e._panes)this.invalidatePane(t,i);e._timeScaleOps.length>0&&(this._timeScaleOps=this._timeScaleOps.concat(e._timeScaleOps))}}const r=()=>{};class n{constructor(e,t,i){if(Object.defineProperty(this,"_onFrame",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schedule",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_cancel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_handle",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._onFrame=e,t)this._schedule=t,this._cancel=i??r;else{const e="function"==typeof requestAnimationFrame?{schedule:e=>requestAnimationFrame(e),cancel:e=>cancelAnimationFrame(e)}:{schedule:e=>setTimeout(e,16),cancel:e=>clearTimeout(e)};this._schedule=e.schedule,this._cancel=e.cancel}}get scheduled(){return null!==this._handle}requestFrame(){if(null!==this._handle)return;this._handle=-1;const e=this._schedule(()=>{this._handle=null,this._onFrame()});null!==this._handle&&(this._handle=e)}stop(){null!==this._handle&&(this._cancel(this._handle),this._handle=null)}}function o(e,t,i){return{width:Math.round(e*i),height:Math.round(t*i)}}function a(e,t){return Math.round(e*t)/t}class l{constructor(e,t){Object.defineProperty(this,"element",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ctx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_mediaWidth",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_mediaHeight",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_dpr",{enumerable:!0,configurable:!0,writable:!0,value:1}),this.element=e.createElement("canvas");const i=this.element.getContext("2d");if(null===i)throw new Error("openalgo-charts: 2D canvas context is not available");this.ctx=i;const s=this.element.style;s.position="absolute",s.top="0",s.left="0",s.width="100%",s.height="100%",s.zIndex=String(t)}get mediaWidth(){return this._mediaWidth}get mediaHeight(){return this._mediaHeight}get pixelRatio(){return this._dpr}resize(e,t,i){if(e===this._mediaWidth&&t===this._mediaHeight&&i===this._dpr)return;this._mediaWidth=e,this._mediaHeight=t,this._dpr=i;const s=o(e,t,i);this.element.width=s.width,this.element.height=s.height,this.element.style.width=`${e}px`,this.element.style.height=`${t}px`}clearBitmap(){this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.element.width,this.element.height)}}function h(e,t,i){return e<t?t:e>i?i:e}function c(e,t,i){return e+(t-e)*i}function d(e,t){return t<=0?e:Math.round(e/t)*t}function u(e){const t=Math.floor(Math.log10(e)),i=e/Math.pow(10,t);for(const e of[1,2,2.5,5])if(e>i*(1+1e-9))return e*Math.pow(10,t);return 10*Math.pow(10,t)}function p(e,t,i){const s=Math.ceil(e/i)*i,r=Math.floor(t/i)*i;return Math.round((r-s)/i)+1}function _(e,t,i=6){if(!isFinite(e)||!isFinite(t)||t<=e)return[Number.isFinite(e)?e:0];let s=function(e){if(e<=0)return 0;const t=Math.floor(Math.log10(e)),i=e/Math.pow(10,t);let s;return s=i<1.5?1:i<3?2:i<7?5:10,s*Math.pow(10,t)}((t-e)/Math.max(1,i-1));if(!(s>0))return[e];for(let r=0;r<20&&p(e,t,s)>i;r++)s=u(s);const r=Math.ceil(e/s)*s,n=Math.floor(t/s)*s,o=[],a=Math.round((n-r)/s)+1;for(let e=0;e<a&&e<1e3;e++){const t=r+e*s;o.push(Math.abs(t)<s/1e6?0:t)}return o}function f(e){return e<=0||!isFinite(e)?2:e>=1?0:Math.min(8,Math.ceil(-Math.log10(e)))}function m(e){return"percentage"===e||"indexed-to-100"===e}const b={marginTop:.1,marginBottom:.1,minMove:0,minPrecision:0,mode:"linear",inverted:!1};function g(e,t,i,s){if(!isFinite(e)||!isFinite(t))return{min:0,max:1};if(t<=e){const i=Math.abs(t)>0?.05*Math.abs(t):.5;return{min:e-i,max:t+i}}const r=(t-e)/Math.max(1-i-s,.01);return{min:e-r*s,max:t+r*i}}class v{constructor(e={}){Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_height",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_min",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_max",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"_autoScale",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_scaled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_baseline",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_fixedRange",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_fixedRangeOwner",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_manualRangeOverride",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_priceFormatter",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._options={...b,...e}}get options(){return this._options}setOptions(e){this._options={...this._options,...e},m(this._options.mode)||(this._baseline=null)}setHeight(e){this._height=e}get height(){return this._height}setPriceRange(e){this._manualRangeOverride=!0,this._writePriceRange(e)}setComputedRange(e){this._writePriceRange(e)}_writePriceRange(e){this._min=e.min,this._max=e.max,this._scaled=!0}get scaled(){return this._scaled}setBaseline(e){this._baseline=e}get baseline(){return this._baseline}priceRange(){return{min:this._min,max:this._max}}get autoScale(){return this._autoScale}setAutoScale(e){this._manualRangeOverride=!e,e&&null!==this._fixedRange?this._writePriceRange(this._fixedRange):this._autoScale=e}setFixedRange(e){this._fixedRangeOwner=null,this._fixedRange=null===e?null:{...e},null!==e&&(this._manualRangeOverride=!0,this._autoScale=!1,this._writePriceRange(e))}setOwnedFixedRange(e,t){return this._fixedRangeOwner===e&&this._manualRangeOverride?(this._fixedRange={...t},!0):!(this._manualRangeOverride||!(this._fixedRangeOwner===e||null===this._fixedRange&&this._autoScale))&&(this._fixedRangeOwner=e,this._fixedRange={...t},this._autoScale=!1,this._writePriceRange(t),!0)}clearOwnedFixedRange(e){return!!this.ownsFixedRange(e)&&(this._fixedRangeOwner=null,this._fixedRange=null,this._manualRangeOverride||(this._autoScale=!0),!0)}ownsFixedRange(e){return this._fixedRangeOwner===e&&null!==this._fixedRange}ownedFixedRangeState(e){return this.ownsFixedRange(e)?{manual:this._manualRangeOverride}:null}hasConfiguration(){return this._manualRangeOverride||null!==this._fixedRange||null!==this._priceFormatter||Object.keys(b).some(e=>this._options[e]!==b[e])}get fixedRange(){return null===this._fixedRange?null:{...this._fixedRange}}reset(){this._autoScale&&(this._min=0,this._max=1,this._scaled=!1,this._baseline=null)}scaleAroundCenter(e){this._manualRangeOverride=!0;const t=(this._min+this._max)/2,i=(this._max-this._min)/2*e;this._min=t-i,this._max=t+i,this._autoScale=!1}scaleAtY(e,t){if(!this._scaled||this._height<=0||!Number.isFinite(t)||t<=0)return;const i=this._t(this._min),s=this._t(this._max),r=this._t(this.yToPrice(e)),n=this._tInv(r+(i-r)*t),o=this._tInv(r+(s-r)*t);Number.isFinite(n)&&Number.isFinite(o)&&o>n&&(this.setPriceRange({min:n,max:o}),this._autoScale=!1)}panByPixels(e){if(this._height<=0||0===e)return;const t=this._t(this._min),i=this._t(this._max),s=i-t;if(!(s>0))return;const r=s*((this._options.inverted?-e:e)/this._height);this._min=this._tInv(t+r),this._max=this._tInv(i+r),this._manualRangeOverride=!0,this._autoScale=!1}autoscale(e,t,i=1){if(null!==this._fixedRange)return this._writePriceRange(this._fixedRange),!1;const s=g(e,t,this._options.marginTop,this._options.marginBottom),r=this._t(this._min),n=this._t(this._max),o=this._t(s.min),a=this._t(s.max),l=n-r,c=a-o,d=Math.max(Math.abs((o-r)/l),Math.abs((a-n)/l))*this._height;if(!this._scaled||i>=1||!Number.isFinite(i)||!(l>0)||!(c>0)||d<.1)return this._writePriceRange(s),!1;const u=h(i,0,1),p=(1-u)/l+u/c,_=((1-u)*r/l+u*o/c)/p;return this._writePriceRange({min:this._tInv(_),max:this._tInv(_+1/p)}),!0}_rebase(){const e=this._options.mode;if("percentage"!==e&&"indexed-to-100"!==e)return null;const t=this._baseline;return null!==t&&isFinite(t)&&t>0?t:null}_t(e){if("logarithmic"===this._options.mode)return Math.log10(Math.max(1e-10,e));const t=this._rebase();if(null===t)return e;const i=e/t*100;return"percentage"===this._options.mode?i-100:i}_tInv(e){if("logarithmic"===this._options.mode)return Math.pow(10,e);const t=this._rebase();return null===t?e:("percentage"===this._options.mode?e+100:e)*t/100}priceToY(e){const t=this._t(this._min),i=this._t(this._max)-t;if(i<=0)return this._height/2;const s=(this._t(e)-t)/i;return this._options.inverted?this._height*s:this._height*(1-s)}yToPrice(e){const t=this._t(this._min),i=this._t(this._max)-t,s=this._options.inverted?e/this._height:1-e/this._height;return this._tInv(t+s*i)}precision(){if(null!==this._rebase())return Math.max(2,f((this._t(this._max)-this._t(this._min))/100));if(this._options.minMove>0)return f(this._options.minMove);const e=f((this._max-this._min)/100),t=Math.max(Math.abs(this._min),Math.abs(this._max));return!Number.isFinite(t)||t>=1e4?e:Math.max(this._options.minPrecision,e)}ticks(e=6){return null===this._rebase()?_(this._min,this._max,e):_(this._t(this._min),this._t(this._max),e).map(e=>this._tInv(e))}snapToTick(e){const t=this._options.minMove;return t<=0?e:Math.round(e/t)*t}setPriceFormatter(e){this._priceFormatter=e}format(e){if(null!==this._rebase()){const t=this.precision(),i=this._t(e);if("indexed-to-100"===this._options.mode)return i.toFixed(t);const s=Number(i.toFixed(t));return`${s>0?"+":""}${(0===s?0:i).toFixed(t)}%`}return null!==this._priceFormatter?this._priceFormatter(e):e.toFixed(this.precision())}clampY(e){return h(e,0,this._height)}}const y={barSpacing:8,minBarSpacing:1,maxBarSpacing:80,rightOffset:4};class w{constructor(e={}){Object.defineProperty(this,"_barSpacing",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_rightOffset",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_minBarSpacing",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_maxBarSpacing",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_width",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_baseIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_onChange",{enumerable:!0,configurable:!0,writable:!0,value:null});const t={...y,...e};this._barSpacing=t.barSpacing,this._rightOffset=t.rightOffset,this._minBarSpacing=t.minBarSpacing,this._maxBarSpacing=t.maxBarSpacing}setWidth(e){this._width=e}get width(){return this._width}get barSpacing(){return this._barSpacing}setBarSpacing(e){const t=this.visibleRange();this._barSpacing=this.constrainBarSpacing(e),this._notifyChange(t)}constrainBarSpacing(e){return h(e,this._minBarSpacing,this._maxBarSpacing)}get rightOffset(){return this._rightOffset}setRightOffset(e){const t=this.visibleRange();this._rightOffset=e,this._notifyChange(t)}setBaseIndex(e){this._baseIndex=e}_rightEdgeIndex(){return this._baseIndex+this._rightOffset}indexToX(e){return this._width-(this._rightEdgeIndex()-e)*this._barSpacing}xToIndex(e){return this._rightEdgeIndex()-(this._width-e)/this._barSpacing}visibleRange(){const e=this._rightEdgeIndex();return{from:e-this._width/this._barSpacing,to:e}}getVisibleLogicalRange(){return this.visibleRange()}setVisibleLogicalRange(e){if(this._width<=0)return;const t=e.to-e.from;if(!(t>0))return;const i=this.visibleRange();this._barSpacing=this.constrainBarSpacing(this._width/t),this._rightOffset=e.to-this._baseIndex,this._onChange?.(i)}setChangeHandler(e){this._onChange=e}_notifyChange(e){const t=this.visibleRange();e.from===t.from&&e.to===t.to||this._onChange?.(e)}scrollByPixels(e){this.setRightOffset(this._rightOffset-e/this._barSpacing)}zoomAtX(e,t){const i=this.visibleRange(),s=this.xToIndex(e),r=this._barSpacing;if(this._barSpacing=this.constrainBarSpacing(r*t),this._barSpacing===r)return;const n=s+(this._width-e)/this._barSpacing;this._rightOffset=n-this._baseIndex,this._notifyChange(i)}fitContent(e){if(e<=0||this._width<=0)return;const t=this.visibleRange();this._baseIndex=e-1,this._rightOffset=y.rightOffset;const i=this._width/(e+this._rightOffset);this._barSpacing=this.constrainBarSpacing(i),this._notifyChange(t)}}const x=[];class S{constructor(){Object.defineProperty(this,"_series",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_sortedTimes",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_indexByTime",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_nextId",{enumerable:!0,configurable:!0,writable:!0,value:1})}createSeries(){const e=this._nextId++;return this._series.set(e,{bars:[]}),e}removeSeries(e){this._series.delete(e),this._rebuild()}setSeriesData(e,t){const i=this._series.get(e);if(void 0===i)throw new Error(`openalgo-charts: unknown series ${e}`);i.bars=function(e){const t=e.slice().sort((e,t)=>e.time-t.time);let i=0;for(let e=0;e<t.length;e++)i>0&&t[e].time===t[i-1].time?t[i-1]=t[e]:t[i++]=t[e];return t.length=i,t}(t),this._rebuild()}addBars(e,t){const i=this._series.get(e);if(void 0===i)throw new Error(`openalgo-charts: unknown series ${e}`);if(0===t.length)return;const s=new Map;for(const e of i.bars)s.set(e.time,e);for(const e of t)s.set(e.time,e);i.bars=Array.from(s.values()).sort((e,t)=>e.time-t.time),this._rebuild()}update(e,t){const i=this._series.get(e);if(void 0===i)throw new Error(`openalgo-charts: unknown series ${e}`);const s=i.bars,r=s[s.length-1];if(void 0===r||t.time>r.time){s.push(t);const e=this._sortedTimes.length,i=e>0?this._sortedTimes[e-1]:void 0;return void 0===i||t.time>i?(this._appendTime(t.time),"append"):this._indexByTime.has(t.time)?"replace":(this._rebuild(),"insert")}if(t.time===r.time)return s[s.length-1]=t,"replace";const n=s.findIndex(e=>e.time===t.time);return n>=0?(s[n]=t,"replace"):(this.addBars(e,[t]),"insert")}_appendTime(e){this._indexByTime.has(e)||(this._indexByTime.set(e,this._sortedTimes.length),this._sortedTimes.push(e))}get length(){return this._sortedTimes.length}get baseIndex(){return this._sortedTimes.length-1}indexToTime(e){return this._sortedTimes[e]}timeToIndex(e){return this._indexByTime.get(e)}indexToTimeFloat(e){const t=this._sortedTimes,i=t.length;if(0===i)return NaN;if(1===i)return t[0];if(e<=0)return t[0]+e*(t[1]-t[0]);if(e>=i-1)return t[i-1]+(e-(i-1))*(t[i-1]-t[i-2]);const s=Math.floor(e);return t[s]+(e-s)*(t[s+1]-t[s])}timeToIndexFloat(e){const t=this._sortedTimes,i=t.length;if(0===i)return NaN;if(1===i)return 0;if(e<=t[0]){const i=t[1]-t[0];return i>0?(e-t[0])/i:0}if(e>=t[i-1]){const s=t[i-1]-t[i-2];return s>0?i-1+(e-t[i-1])/s:i-1}let s=0,r=i-1;for(;s<r;){const i=s+r+1>>1;t[i]<=e?s=i:r=i-1}const n=t[s+1]-t[s];return n>0?s+(e-t[s])/n:s}seriesBars(e){return this._series.get(e)?.bars??x}indexedBars(e){const t=this._series.get(e);if(void 0===t)return[];const i=[];for(const e of t.bars){const t=this._indexByTime.get(e.time);void 0!==t&&i.push({index:t,bar:e})}return i}visibleBars(e,t,i){const s=this._series.get(e);if(void 0===s)return[];const r=s.bars,n=Math.max(0,Math.floor(t)),o=Math.min(this.baseIndex,Math.ceil(i));if(o<n||0===r.length)return[];const a=this._sortedTimes[n],l=this._sortedTimes[o];if(void 0===a||void 0===l)return[];let h=0,c=r.length;for(;h<c;){const e=h+c>>1;r[e].time<a?h=e+1:c=e}const d=[];for(let e=h;e<r.length;e++){const t=r[e].time;if(t>l)break;const i=this._indexByTime.get(t);void 0!==i&&d.push({index:i,bar:r[e]})}return d}lastIndexedBar(e){const t=this._series.get(e);if(void 0===t||0===t.bars.length)return null;const i=t.bars[t.bars.length-1],s=this._indexByTime.get(i.time);return void 0===s?null:{index:s,bar:i}}_rebuild(){const e=new Set;for(const t of this._series.values())for(const i of t.bars)e.add(i.time);this._sortedTimes=Array.from(e).sort((e,t)=>e-t),this._indexByTime.clear();for(let e=0;e<this._sortedTimes.length;e++)this._indexByTime.set(this._sortedTimes[e],e)}}const P=["left","right","hidden"];function O(e){return"string"==typeof e&&("right"===e||"left"===e||""===e||e.startsWith("overlay:"))}function k(e){return"left"===e||"right"===e?e:"hidden"}class I{constructor(){Object.defineProperty(this,"_configured",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_placements",{enumerable:!0,configurable:!0,writable:!0,value:new Map([["right",{side:"right",order:0}]])})}register(e){O(e)&&!this._placements.has(e)&&this._placements.set(e,this.get(e))}get(e){const t=this._placements.get(e);if(t)return{...t};const i=k(e);let s=0;for(const e of this._placements.values())e.side===i&&s++;return{side:i,order:s}}set(e,t,i){if(!O(e)||!P.includes(t)||void 0!==i&&(!Number.isSafeInteger(i)||i<0))return!1;const s=this.get(e),r=this._sideIds(t).filter(t=>t!==e),n=Math.min(i??(s.side===t?s.order:r.length),r.length);return(s.side!==t||s.order!==n)&&(this.register(e),r.splice(n,0,e),s.side!==t&&this._reorder(s.side,this._sideIds(s.side).filter(t=>t!==e)),this._reorder(t,r),!0)}entries(){return Array.from(this._placements,([e,t])=>({scaleId:e,...t}))}configured(e){return this._configured.has(e)}restore(e){this._configured.clear();for(const t of e.keys())this._configured.add(t);for(const t of e.keys())this.register(t);const t={left:0,right:0,hidden:0};for(const i of this._placements.keys()){const s=k(i),r={side:s,order:t[s]++};this._placements.set(i,{...e.get(i)??r})}for(const e of P)this._reorder(e,this._sideIds(e))}_sideIds(e){return this.entries().filter(t=>t.side===e).sort((e,t)=>e.order-t.order).map(e=>e.scaleId)}_reorder(e,t){t.forEach((t,i)=>{const s=this._placements.get(t);s?.side===e&&s.order===i||this._configured.add(t),this._placements.set(t,{side:e,order:i})})}}function M(e,t){return"dashed"===e?[4*t,4*t]:"dotted"===e?[1*t,3*t]:[]}function T(e,t,i){const s=M(e.gridStyle,i);return{color:e.grid,lineWidth:t?.lineWidth??1,dash:s,vert:{color:t?.vertColor??e.grid,dash:void 0===t?.vertStyle?s:M(t.vertStyle,i)},horz:{color:t?.horzColor??e.grid,dash:void 0===t?.horzStyle?s:M(t.horzStyle,i)}}}function C(e,t,i,s,r,n,o,l){if(0!==t.length){e.strokeStyle=s?.color??r.color,e.setLineDash(s?.dash??r.dash??[]),e.beginPath();for(const s of t){const t=Math.round(a(s,n)*n);i?(e.moveTo(t,0),e.lineTo(t,l)):(e.moveTo(0,t),e.lineTo(o,t))}e.stroke()}}const j=10,A=14;function L(e,t){const i=void 0===t?.fontSize?e.axisFontSize??11:h(Math.round(t.fontSize),10,14);return{textColor:t?.textColor??e.axisText,lineColor:t?.lineColor??e.axisLine,font:`${i}px system-ui, sans-serif`}}function R(e){const t={};return void 0!==e?.top&&(t.marginTop=h(e.top,0,49)/100),void 0!==e?.bottom&&(t.marginBottom=h(e.bottom,0,49)/100),t}const z={upColor:"#26a69a",downColor:"#ef5350",borderUpColor:"#26a69a",borderDownColor:"#ef5350",wickUpColor:"#26a69a",wickDownColor:"#ef5350",borderVisible:!0,wickVisible:!0};function F(e,t){const i=Math.floor(e*t*.8);let s=Math.max(1,i);if(s>=2){s%2!=Math.max(1,Math.floor(t))%2&&(s-=1)}return Math.max(1,s)}function N(e,t,i){return i.wickVisible?!0===i.hollow||!1===i.bodyVisible||e>t||i.borderVisible&&e>=3||i.upColor!==i.wickUpColor||i.downColor!==i.wickDownColor?"full":"wick":"full"}function E(e,t,i,s=1){const r=F(t,i),n=Math.max(1,Math.floor(i)),o=Math.round(e*i),a=Math.max(.05,Math.min(1,s)),l=1===a?r:Math.max(1,Math.round(r*a));return{cx:o,bodyX:o-Math.floor(l/2),bodyW:l,wickX:o-Math.floor(n/2),wickW:n}}function B(e,t,i,s,r,n=z){const o=F(s,r),a=Math.max(1,Math.floor(r)),l=n.widthScale?null:N(o,a,n);for(let o=0;o<t.length;o++){const{x:h,bar:c}=t[o],d=o>0?t[o-1].bar.close:t[o].prevClose,u=!0===n.colorByPreviousClose&&void 0!==d&&Number.isFinite(d)?c.close>=d:c.close>=c.open,p=Math.round(i(c.open)*r),_=Math.round(i(c.close)*r),f=Math.round(i(c.high)*r),m=Math.round(i(c.low)*r),b=E(h,s,r,n.widthScale?n.widthScale(c):1),g=b.cx,v=b.bodyW,y=g-b.bodyX,w=c.color,x=w??(u?n.upColor:n.downColor),S=c.wickColor??w??(u?n.wickUpColor:n.wickDownColor),P=c.borderColor??w??(u?n.borderUpColor:n.borderDownColor);if(n.wickVisible&&(e.fillStyle=S,e.fillRect(b.wickX,f,b.wickW,Math.max(1,m-f))),"wick"===(l??N(v,a,n))&&S===x)continue;const O=Math.min(p,_),k=Math.max(1,Math.abs(_-p));if(n.hollow&&u)e.strokeStyle=n.borderVisible?P:x,e.lineWidth=Math.max(1,a),e.strokeRect(g-y+.5,O+.5,v-1,k-1);else{const t=!1!==n.bodyVisible;t&&(e.fillStyle=x,e.fillRect(g-y,O,v,k)),n.borderVisible&&(!t||v>=3)&&(e.strokeStyle=P,e.lineWidth=1,e.strokeRect(g-y+.5,O+.5,v-1,k-1))}}}function $(e,t,i){const s=e.bar;return{cx:Math.round(e.x*i),yOpen:Math.round(t(s.open)*i),yClose:Math.round(t(s.close)*i),yHigh:Math.round(t(s.high)*i),yLow:Math.round(t(s.low)*i),up:s.close>=s.open}}function D(e,t,i,s,r,n,o=!1){const a=Math.max(1,Math.floor(F(s,r)/2)),l=Math.max(1,Math.floor(r));e.save();for(let s=0;s<t.length;s++){const h=t[s],c=$(h,i,r),d=s>0?t[s-1].bar.close:h.prevClose,u=!0===n.colorByPreviousClose&&void 0!==d&&Number.isFinite(d)?h.bar.close>=d:c.up;e.fillStyle=h.bar.color??(u?n.upColor??"#26a69a":n.downColor??"#ef5350"),e.fillRect(c.cx-Math.floor(l/2),c.yHigh,l,Math.max(1,c.yLow-c.yHigh)),o||(e.fillRect(c.cx-a,c.yOpen,a,l),e.fillRect(c.cx,c.yClose,a,l))}e.restore()}function W(e){const t=e.trim();if(t.startsWith("#")){const e=t.slice(1);if(3===e.length||4===e.length){const[t,i,s,r]=[...e].map(e=>parseInt(e+e,16));return[t,i,s].some(Number.isNaN)?null:{r:t,g:i,b:s,a:4===e.length?r/255:1}}if(6===e.length||8===e.length){const t=parseInt(e.slice(0,6),16);if(Number.isNaN(t))return null;const i=8===e.length?parseInt(e.slice(6,8),16)/255:1;return{r:t>>16&255,g:t>>8&255,b:255&t,a:Number.isNaN(i)?1:i}}return null}const i=/^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*(?:,\s*([\d.]+)\s*)?\)$/i.exec(t);return null===i?null:{r:Number(i[1]),g:Number(i[2]),b:Number(i[3]),a:void 0===i[4]?1:Number(i[4])}}function q(e){return function(e){const t=W(e);if(null===t)return.5;const i=e=>{const t=e/255;return t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)};return.2126*i(t.r)+.7152*i(t.g)+.0722*i(t.b)}(e)>.45?"#10131a":"#ffffff"}function V(e,t){const i=W(e);return null===i?e:`rgba(${i.r},${i.g},${i.b},${t})`}function H(e){if("transparent"===e.trim().toLowerCase())return!0;const t=W(e);return null!==t&&t.a<=0}function G(e,t){const i=W(e);if(null===i)return e;const s=t>=0?255:0,r=Math.min(1,Math.abs(t)),n=e=>Math.round(e+(s-e)*r);return`rgba(${n(i.r)},${n(i.g)},${n(i.b)},${i.a})`}function U(e,t,i,s,r,n){const o=e.roundRect;"function"==typeof o?o.call(e,t,i,s,r,Math.max(0,Math.min(n,s/2,r/2))):e.rect(t,i,s,r)}const K=new WeakMap;function Y(e,t,i,s){let r=K.get(e);void 0===r&&(r=new Map,K.set(e,r));const n=`${Math.round(t)}|${i}|${s}`;let o=r.get(n);return void 0===o&&(o=e.createLinearGradient(0,0,0,t),o.addColorStop(0,i),o.addColorStop(1,s),r.set(n,o)),o}function X(e,t,i,s,r){const n=W(s),o=W(r);if(null===n||null===o)return s;const a=(e-t)/(i-t),l=a>0?a<1?a:1:0;return`rgba(${Math.round(n.r+(o.r-n.r)*l)},${Math.round(n.g+(o.g-n.g)*l)},${Math.round(n.b+(o.b-n.b)*l)},${n.a+(o.a-n.a)*l})`}function J(e,t,i=e=>e.close){return e.map(e=>({x:e.x,y:t(i(e.bar))}))}function Z(e,t,i,s){if(0===t.length)return;const r=e.strokeStyle;let n,o;e.beginPath();let a=!1;for(let l=0;l<t.length;l++){const h=t[l];if(!Number.isFinite(h.x)||!Number.isFinite(h.y)){n=void 0;continue}if(void 0===n){e.moveTo(h.x*i,h.y*i),n=h;continue}const c=void 0===s?o:s[l];c!==o&&(a&&(e.stroke(),e.beginPath(),e.moveTo(n.x*i,n.y*i),a=!1),e.strokeStyle=c??r,o=c),e.lineTo(h.x*i,h.y*i),n=h,a=!0}e.stroke()}function Q(e,t,i,s,r){const n=J(t,i),o=r.step?function(e){if(0===e.length)return[];const t=[{...e[0]}];for(let i=1;i<e.length;i++)t.push({x:e[i].x,y:e[i-1].y}),t.push({x:e[i].x,y:e[i].y});return t}(n):n,a=function(e,t){let i=!1;for(const t of e)if(void 0!==t.bar.color){i=!0;break}if(!i)return;const s=[];for(const i of e)t&&s.length>0&&s.push(i.bar.color),s.push(i.bar.color);return s}(t,!0===r.step);e.save(),e.strokeStyle=r.color??"#4f8cff",e.lineWidth=Math.max(1,(r.lineWidth??1.5)*s),e.lineJoin="round",e.lineCap="round";const l="dashed"===r.lineStyle?[6*s,4*s]:"dotted"===r.lineStyle?[1*s,3*s]:[];if(e.setLineDash(l),r.markersOnly||Z(e,o,s,a),e.setLineDash([]),r.markers||r.markersOnly){const i=(r.markerRadius??2)*s,o=r.color??"#4f8cff";e.fillStyle=o;for(let r=0;r<n.length;r++){const l=n[r];Number.isFinite(l.x)&&Number.isFinite(l.y)&&(void 0!==a&&(e.fillStyle=t[r].bar.color??o),e.beginPath(),e.arc(l.x*s,l.y*s,i,0,2*Math.PI),e.fill())}}e.restore()}const ee={color:"#3a4666",base:0};function te(e,t,i={}){return{...z,upColor:e.upColor??t.upColor,downColor:e.downColor??t.downColor,borderUpColor:e.borderUpColor??t.upColor,borderDownColor:e.borderDownColor??t.downColor,wickUpColor:e.wickUpColor??t.wickUpColor,wickDownColor:e.wickDownColor??t.wickDownColor,borderVisible:e.borderVisible??z.borderVisible,bodyVisible:e.bodyVisible??!0,wickVisible:e.wickVisible??z.wickVisible,colorByPreviousClose:e.colorByPreviousClose,...i}}const ie=e=>({min:e.low,max:e.high}),se=e=>({min:e.close,max:e.close}),re=(e,t)=>{const i=t.base??0;return{min:Math.min(i,e.close),max:Math.max(i,e.close)}},ne=new Map,oe=new Set(["point-figure","kagi"]);function ae(e,t){ne.set(e,t)}function le(e){const t=ne.get(e);if(void 0===t){if(oe.has(e))throw new Error(`openalgo-charts: series type "${e}" needs the transform tier — import 'openalgo-charts/transform' first`);throw new Error(`openalgo-charts: unknown series type "${e}"`)}return t}function he(){return Array.from(ne.keys())}const ce=(e,t)=>({...e,upColor:e.upColor??t.upColor,downColor:e.downColor??t.downColor});function de(e,t,i=.5,s=1){const r=e*t;if(r<=0)return 1;const n=i*Math.max(1,s);return r>=n?1:Math.max(1,Math.ceil(n/r))}function ue(e){const t=e[0];let i=t.high,s=t.low,r=t.volume??0,n=void 0!==t.volume,o=t.oi;for(let t=1;t<e.length;t++){const a=e[t];a.high>i&&(i=a.high),a.low<s&&(s=a.low),void 0!==a.volume&&(r+=a.volume,n=!0),void 0!==a.oi&&(o=a.oi)}const a={time:t.time,open:t.open,high:i,low:s,close:e[e.length-1].close};return n&&(a.volume=r),void 0!==o&&(a.oi=o),a}function pe(e,t){if(t<=1)return e.slice();const i=[];for(let s=0;s<e.length;s+=t)i.push(ue(e.slice(s,s+t)));return i}function _e(e,t){if(t<=1)return e.map(e=>({x:e.x,bar:e.bar}));const i=[];for(let s=0;s<e.length;s+=t){const r=e.slice(s,s+t),n=r.reduce((e,t)=>e+t.x,0)/r.length;i.push({x:n,bar:ue(r.map(e=>e.bar))})}return i}ae("candlestick",{defaultStyle:{},isPriceSeries:!0,draw:(e,t,i,s,r,n,o)=>B(e,t,i,s,r,te(n,o.theme)),extents:ie}),ae("hollow-candle",{defaultStyle:{},isPriceSeries:!0,draw:(e,t,i,s,r,n,o)=>B(e,t,i,s,r,te(n,o.theme,{hollow:!0})),extents:ie}),ae("volume-candle",{defaultStyle:{},isPriceSeries:!0,draw:(e,t,i,s,r,n,o)=>{const a=o.maxVolume;B(e,t,i,s,r,te(n,o.theme,{widthScale:e=>a>0?(e.volume??0)/a:1}))},extents:ie}),ae("bar",{defaultStyle:{},isPriceSeries:!0,draw:(e,t,i,s,r,n,o)=>D(e,t,i,s,r,ce(n,o.theme)),extents:ie}),ae("high-low",{defaultStyle:{},isPriceSeries:!0,draw:(e,t,i,s,r,n,o)=>D(e,t,i,s,r,ce(n,o.theme),!0),extents:ie}),ae("line",{defaultStyle:{lineWidth:1.5},isPriceSeries:!0,draw:(e,t,i,s,r,n,o)=>Q(e,t,i,r,{...n,color:n.color??o.theme.lineColor}),extents:se}),ae("line-markers",{defaultStyle:{lineWidth:1.5,markers:!0},isPriceSeries:!0,draw:(e,t,i,s,r,n,o)=>Q(e,t,i,r,{...n,color:n.color??o.theme.lineColor,markers:!0}),extents:se}),ae("step",{defaultStyle:{lineWidth:1.5,step:!0},isPriceSeries:!0,draw:(e,t,i,s,r,n,o)=>Q(e,t,i,r,{...n,color:n.color??o.theme.lineColor,step:!0}),extents:se}),ae("area",{defaultStyle:{lineWidth:1.5},isPriceSeries:!0,draw:(e,t,i,s,r,n,o)=>function(e,t,i,s,r,n){const o=J(t,i);if(0===o.length)return;const a=r*s;e.save(),e.beginPath(),e.moveTo(o[0].x*s,a);for(const t of o)e.lineTo(t.x*s,t.y*s);e.lineTo(o[o.length-1].x*s,a),e.closePath(),e.fillStyle=Y(e,a,n.areaTopColor??"rgba(79,140,255,0.40)",n.areaBottomColor??"rgba(79,140,255,0.00)"),e.fill(),e.restore(),Q(e,t,i,s,{color:n.color??"#4f8cff",lineWidth:n.lineWidth??1.5,lineStyle:n.lineStyle})}(e,t,i,r,o.plotHeight,{...n,color:n.color??o.theme.lineColor,areaTopColor:n.areaTopColor??o.theme.areaTopColor,areaBottomColor:n.areaBottomColor??o.theme.areaBottomColor}),extents:se}),ae("hlc-area",{defaultStyle:{lineWidth:1.5},isPriceSeries:!0,draw:(e,t,i,s,r,n,o)=>function(e,t,i,s,r){if(0===t.length)return;const n=J(t,i,e=>e.high),o=J(t,i,e=>e.low);e.save(),e.beginPath(),e.moveTo(n[0].x*s,n[0].y*s);for(const t of n)e.lineTo(t.x*s,t.y*s);for(let t=o.length-1;t>=0;t--)e.lineTo(o[t].x*s,o[t].y*s);e.closePath(),e.fillStyle=r.areaTopColor??"rgba(79,140,255,0.15)",e.fill(),e.restore();for(const[t,i]of[[r.highColor,n],[r.lowColor,o]])void 0!==t&&(e.save(),e.strokeStyle=t,e.lineWidth=Math.max(1,Math.round((r.lineWidth??1.5)*s)),Z(e,i,s),e.restore());Q(e,t,i,s,{color:r.closeColor??"#4f8cff",lineWidth:r.lineWidth??1.5})}(e,t,i,r,{...n,closeColor:n.closeColor??o.theme.lineColor}),extents:ie}),ae("baseline",{defaultStyle:{baseValue:0,lineWidth:1.5},isPriceSeries:!0,draw:(e,t,i,s,r,n,o)=>function(e,t,i,s,r){const n=i(r.baseValue??0)*s,o=J(t,i);if(0===o.length)return;const a=o[0].x*s,l=o[o.length-1].x*s,h=()=>{e.beginPath(),e.moveTo(a,n);for(const t of o)e.lineTo(t.x*s,t.y*s);e.lineTo(l,n),e.closePath()},c=r.areaTopColor??"rgba(38,166,154,0.20)",d=r.areaBottomColor??"rgba(239,83,80,0.20)",u=1e5;e.save(),e.beginPath(),e.rect(a,n-u,l-a,u),e.clip(),h(),e.fillStyle=Y(e,n,c,"rgba(0,0,0,0)"),e.fill(),e.restore(),e.save(),e.beginPath(),e.rect(a,n,l-a,u),e.clip(),h(),e.fillStyle=d,e.fill(),e.restore(),e.save();for(let t=1;t<o.length;t++){const i=o[t-1],a=o[t],l=(i.y+a.y)/2<=n/s;e.strokeStyle=l?r.topColor??"#26a69a":r.bottomColor??"#ef5350",e.lineWidth=Math.max(1,Math.round((r.lineWidth??1.5)*s)),e.beginPath(),e.moveTo(i.x*s,i.y*s),e.lineTo(a.x*s,a.y*s),e.stroke()}e.restore()}(e,t,i,r,{...n,topColor:n.topColor??o.theme.baselineTopLine,bottomColor:n.bottomColor??o.theme.baselineBottomLine,areaTopColor:n.areaTopColor??o.theme.baselineTopFill,areaBottomColor:n.areaBottomColor??o.theme.baselineBottomFill}),extents:(e,t)=>{const i=t.baseValue??0;return{min:Math.min(i,e.close),max:Math.max(i,e.close)}}}),ae("column",{defaultStyle:{base:0},isPriceSeries:!1,draw:(e,t,i,s,r,n,o)=>function(e,t,i,s,r,n){const o=F(s,r),a=Math.floor(o/2),l=Math.round(i(n.base??0)*r);e.save();for(const s of t){const t=$(s,i,r);e.fillStyle=s.bar.color??n.color??(t.up?n.upColor??"#26a69a":n.downColor??"#ef5350");const h=Math.min(l,t.yClose);e.fillRect(t.cx-a,h,o,Math.max(1,Math.abs(l-t.yClose)))}e.restore()}(e,t,i,s,r,ce(n,o.theme)),extents:re}),ae("histogram",{defaultStyle:{base:0,color:"#3a4666"},isPriceSeries:!1,draw:(e,t,i,s,r,n)=>{!function(e,t,i,s,r,n=ee){const o=F(s,r),a=Math.floor(o/2),l=Math.round(i(n.base)*r);let h="";for(const{x:s,bar:c}of t){const t=c.color??n.color;t!==h&&(e.fillStyle=t,h=t);const d=Math.round(s*r),u=Math.round(i(c.close)*r),p=Math.min(l,u),_=Math.max(1,Math.abs(l-u));e.fillRect(d-a,p,o,_)}}(e,t,i,s,r,{color:n.color??"#3a4666",base:n.base??0})},extents:re});const fe=19800;function me(e){return Math.floor(e/1e3)}function be(e){const t=e.trim(),i=/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?/.exec(t);if(null===i)throw new Error(`openalgo-charts: unparseable IST time string "${e}"`);const s=Number(i[1]),r=Number(i[2]),n=Number(i[3]),o=void 0!==i[4]?Number(i[4]):0,a=void 0!==i[5]?Number(i[5]):0,l=void 0!==i[6]?Number(i[6]):0,h=Date.UTC(s,r-1,n,o,a,l);return Math.floor(h/1e3)-fe}function ge(e){const t=new Date(1e3*(e+fe));return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),weekday:t.getUTCDay()}}const ve=e=>e<10?`0${e}`:String(e);function ye(e){const t=ge(e);return`${ve(t.hour)}:${ve(t.minute)}`}function we(e){const t=ge(e);return`${ve(t.hour)}:${ve(t.minute)}:${ve(t.second)}`}function xe(e){const t=ge(e);return`${t.year}-${ve(t.month)}-${ve(t.day)}`}const Se=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Pe(e){const t=ge(e);return`${ve(t.day)} ${Se[t.month-1]}`}const Oe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function ke(e){const t=ge(e);let i=`${Oe[t.weekday]} ${ve(t.day)} ${Se[t.month-1]} '${String(t.year).slice(-2)}`;return 0===t.hour&&0===t.minute&&0===t.second||(i+=` ${ve(t.hour)}:${ve(t.minute)}`,0!==t.second&&(i+=`:${ve(t.second)}`)),i}function Ie(e,t){const i=ge(e),s=ge(t);return i.year!==s.year||i.month!==s.month||i.day!==s.day}const Me="Asia/Kolkata",Te=new Map,Ce={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function je(e){let t=Te.get(e);if(void 0===t){let i;try{i=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",weekday:"short"})}catch{throw new Error(`openalgo-charts: unknown IANA time zone "${e}"`)}t={format:i,parts:new Map,lastSecond:Number.NaN,lastParts:null},Te.set(e,t)}return t}function Ae(e){if(Te.has(e))return!0;try{return je(e),!0}catch{return!1}}function Le(e,t){const i=je(t);if(e===i.lastSecond&&null!==i.lastParts)return i.lastParts;let s=i.parts.get(e);return void 0===s&&(s=function(e,t){let i=1970,s=1,r=1,n=0,o=0,a=0,l=4;for(const h of e.formatToParts(new Date(1e3*t)))switch(h.type){case"year":i=Number(h.value);break;case"month":s=Number(h.value);break;case"day":r=Number(h.value);break;case"hour":n=Number(h.value)%24;break;case"minute":o=Number(h.value);break;case"second":a=Number(h.value);break;case"weekday":l=Ce[h.value]??0}return{year:i,month:s,day:r,hour:n,minute:o,second:a,weekday:l,dayIndex:Math.floor(Date.UTC(i,s-1,r)/864e5)}}(i.format,e),i.parts.size>=4096&&i.parts.clear(),i.parts.set(e,s)),i.lastSecond=e,i.lastParts=s,s}function Re(e,t=Me){const i=Le(e,t);return{year:i.year,month:i.month,day:i.day,hour:i.hour,minute:i.minute,second:i.second,weekday:i.weekday}}function ze(e,t=Me){return Le(e,t).dayIndex}function Fe(e,t=Me){return Math.floor((Le(e,t).dayIndex+3)/7)}function Ne(e,t=Me){const i=Le(e,t);return Math.floor(Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second)/1e3)-e}function Ee(e,t,i=Me){return Le(e,i).dayIndex!==Le(t,i).dayIndex}function Be(e,t,i=Me){return Math.floor((Le(e,i).dayIndex+3)/7)!==Math.floor((Le(t,i).dayIndex+3)/7)}function $e(e,t,i=Me){const s=Le(e,i),r=Le(t,i);return s.year!==r.year||s.month!==r.month}function De(e,t,i=Me){const s=Le(e,i),r=Le(t,i);return s.year!==r.year||Math.floor((s.month-1)/3)!==Math.floor((r.month-1)/3)}function We(e,t,i=Me){return Le(e,i).year!==Le(t,i).year}function qe(e,t,i,s=Me){switch(i){case"week":return Be(e,t,s);case"month":return $e(e,t,s);case"quarter":return De(e,t,s);case"year":return We(e,t,s);default:return Ee(e,t,s)}}function Ve(e,t=Me){const i=e.trim(),s=/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?/.exec(i);if(null===s)throw new Error(`openalgo-charts: unparseable time string "${e}"`);return He(Number(s[1]),Number(s[2]),Number(s[3]),void 0!==s[4]?Number(s[4]):0,void 0!==s[5]?Number(s[5]):0,void 0!==s[6]?Number(s[6]):0,t)}function He(e,t,i,s=0,r=0,n=0,o=Me){const a=Math.floor(Date.UTC(e,t-1,i,s,r,n)/1e3),l=a-Ne(a,o);return a-Ne(l,o)}function Ge(e,t=Me){const i=Le(e,t);return He(i.year,i.month,i.day,0,0,0,t)}function Ue(e,t=Me){const i=Le(e,t),s=(i.weekday+6)%7,r=new Date(Date.UTC(i.year,i.month-1,i.day-s));return He(r.getUTCFullYear(),r.getUTCMonth()+1,r.getUTCDate(),0,0,0,t)}function Ke(e,t=Me){const i=Le(e,t);return He(i.year,i.month,1,0,0,0,t)}function Ye(e,t=Me){const i=Le(e,t);return`${ve(i.hour)}:${ve(i.minute)}`}function Xe(e,t=Me){const i=Le(e,t);return`${ve(i.hour)}:${ve(i.minute)}:${ve(i.second)}`}function Je(e,t=Me){const i=Le(e,t);return`${ve(i.day)} ${Se[i.month-1]}`}function Ze(e,t=Me){const i=Le(e,t);return`${i.year}-${ve(i.month)}-${ve(i.day)}`}function Qe(e,t=Me){const i=Le(e,t);let s=`${Oe[i.weekday]} ${ve(i.day)} ${Se[i.month-1]} '${String(i.year).slice(-2)}`;return 0===i.hour&&0===i.minute&&0===i.second||(s+=` ${ve(i.hour)}:${ve(i.minute)}`,0!==i.second&&(s+=`:${ve(i.second)}`)),s}function et(e){const t=function(e){const t=[];for(let i=1;i<e.length;i++){const s=e[i]-e[i-1];s>0&&t.push(s)}return 0===t.length?0:(t.sort((e,t)=>e-t),t[t.length>>1])}(e);if(t<=0||t>=86400)return null;const i=Math.max(4*t,14400),s=[];for(let t=1;t<e.length;t++)e[t]-e[t-1]>=i&&s.push(t);if(0===s.length)return null;const r=[e[0],...s.map(t=>e[t])],n=[];for(let e=1;e<r.length;e++)n.push(r[e]-r[e-1]);return n.sort((e,t)=>e-t),n[n.length>>1]>129600?null:s}function tt(e,t=Me){const i=new Array(e.length).fill(!1),s=et(e);if(null===s){const s=t===Me?Ie:(e,i)=>Ee(e,i,t);for(let t=1;t<e.length;t++)i[t]=s(e[t-1],e[t]);return i}for(const e of s)i[e]=!0;return i}function it(e,t){const i=new Array(e.length).fill(!1),s=et(e);if(null===s){for(let s=1;s<e.length;s++)i[s]=t(e[s-1],e[s]);return i}let r=e[0];for(const n of s)t(r,e[n])&&(i[n]=!0),r=e[n];return i}const st=/^\s*(\d{2})(\d{2})\s*-\s*(\d{2})(\d{2})(?:\s*:\s*([1-7]+))?\s*$/;function rt(e,t){const i=Number(e),s=Number(t);return i>23||s>59?-1:60*i+s}function nt(e){const t=st.exec(e);if(null===t)return null;const i=rt(t[1],t[2]),s=rt(t[3],t[4]);return i<0||s<0?null:void 0===t[5]?{start:i,end:s}:{start:i,end:s,days:[...t[5]].map(Number)}}function ot(e,t){const i=60*e.hour+e.minute,s=t.end<=t.start,r=i<t.end;if(!(s?i>=t.start||r:i>=t.start&&r))return!1;if(void 0===t.days)return!0;const n=s&&r?(e.weekday+6)%7:e.weekday;return t.days.includes(n+1)}function at(e,t,i=Me){return ot(Le(e,i),t)}function lt(e,t,i=Me){const s=new Array(e.length).fill(!1),r="string"==typeof t?nt(t):t;if(null===r)return s;for(let t=0;t<e.length;t++)s[t]=ot(Le(e[t],i),r);return s}const ht={textColor:"#8b91a7",lineColor:"#2a3046",font:"11px system-ui, sans-serif"};function ct(e){return!Number.isFinite(e)||e<=0?2:Math.max(2,Math.min(30,Math.round(e/32)))}const dt=90,ut=30,pt=10;function _t(e,t=0){const i=new Array(e.length).fill(!1),s=e.map((e,t)=>t);s.sort((t,i)=>e[i].priority-e[t].priority||t-i);const r=[];for(const n of s){const s=e[n];if(!Number.isFinite(s.y)||!Number.isFinite(s.height))continue;let o=!0;for(const e of r)if(Math.abs(e.y-s.y)<(e.height+s.height)/2+t){o=!1;break}o&&(i[n]=!0,r.push(s))}return i}function ft(e,t,i,s){if(void 0===s||0===s.length)return null;return _t([...e.map(e=>({y:Math.round(t.priceToY(e)*i),height:16*i,priority:pt})),...s],2*i).slice(0,e.length)}function mt(e,t,i,s){const r=s?"timeWithSeconds":"time";if(i===Me){const i=ge(e),s=ge(t);return i.year!==s.year?"year":i.month!==s.month?"month":i.day!==s.day?"day":r}return We(e,t,i)?"year":$e(e,t,i)?"month":Ee(e,t,i)?"day":r}function bt(e,t,i){const s=[];for(let r=e;r<=t;r+=i)s.push(r);return s}function gt(e,t=64){const i=e.baseIndex,s=[];let r;for(let n=Math.max(0,i-t);n<=i;n++){const t=e.indexToTime(n);void 0!==t&&(void 0!==r&&t-r>0&&s.push(t-r),r=t)}return 0===s.length?0:(s.sort((e,t)=>e-t),s[s.length>>1])}function vt(e,t,i){if(!Number.isFinite(t)||t<=0)return null;if(!Number.isFinite(e)||!Number.isFinite(i))return null;const s=i-e;return s<0?t-s:t-s%t}const yt=e=>e<10?`0${e}`:String(e);function wt(e){if(null===e||!Number.isFinite(e))return"--:--:--";const t=Math.max(0,Math.ceil(e));return`${yt(Math.floor(t/3600))}:${yt(Math.floor(t%3600/60))}:${yt(t%60)}`}function xt(e,t=!1){return(t?28:16)*e}function St(e,t,i,s){return!Number.isFinite(e)||e<0||e>t?null:"right"===s?e:t<i?null:Math.max(i/2,Math.min(t-i/2,e))}function Pt(e,t,i,s,r,n,o,a){const l=Math.round(r.plotLeft*n)-1;if(!(l>0))return;const h=Math.min(6*n,l/4),c=s.map(t=>(e.font=t.font,e.measureText(t.text).width)),d=Math.min(l,Math.max(...c)+2*h),u=-1-d;e.fillStyle=o,e.fillRect(u,t-i/2,d,i),e.fillStyle=a;for(let r=0;r<s.length;r++){const o=s[r],a=Number(/(^|[^\d.])(\d{1,5}(?:\.\d{1,4})?)px/.exec(o.font)?.[2]),l=a>0?(i/s.length-2*n)/a:1,p=c[r]>0?(d-2*h)/c[r]:1;e.font=Tt(o.font,Math.min(1,p,l)),e.fillText(o.text,u+h,t+o.offset)}}function Ot(e,t,i,s,r,n,o,a){const l=e.measureText(n).width;e.fillStyle=o,e.fillRect(t+1,i-s/2,l+2*r,s),e.fillStyle=a,e.fillText(n,t+1+r,i)}function kt(e,t,i,s,r,n,o=ht,a="right"){if(!Number.isFinite(i))return;const l=St(Math.round(t.priceToY(i)*n),r.plotHeight*n,xt(n),a);null!==l&&(e.save(),e.font=Tt(o.font,n),e.textAlign="left",e.textBaseline="middle","left"===a?Pt(e,l,xt(n),[{text:t.format(i),font:e.font,offset:0}],r,n,s,q(s)):Ot(e,Math.round(r.plotWidth*n),l,xt(n),6*n,t.format(i),s,q(s)),e.restore())}function It(e,t,i,s,r,n,o=ht,a={up:"#26a69a",down:"#ef5350",text:"#0d0e12"},l=!0,h=!0,c,d="right"){if(!l&&!h)return;const u=Math.round(t.priceToY(i)*n);if(!Number.isFinite(u)||u<0||u>r.plotHeight*n)return;const p=s?a.up:a.down,_=Math.round(r.plotWidth*n);if(e.save(),l&&(e.strokeStyle=p,e.lineWidth=Math.max(1,Math.round(n)),e.setLineDash([3*n,3*n]),e.beginPath(),e.moveTo(0,u+.5),e.lineTo(_,u+.5),e.stroke(),e.setLineDash([])),h){const s=t.format(i),l=void 0!==c&&!0===c.visible,h=Tt(o.font,n);e.font=h;const f=6*n,m=xt(n,l);if(e.textAlign="left",e.textBaseline="middle","left"===d){const t=St(u,r.plotHeight*n,m,d);if(null!==t){const i=[{text:s,font:h,offset:l?-m/4:0}];l&&i.push({text:wt(vt(c.lastBarTime,c.intervalSec,c.now())),font:Tt(o.font,.9*n),offset:m/4}),Pt(e,t,m,i,r,n,p,a.text)}}else if(l){const t=wt(vt(c.lastBarTime,c.intervalSec,c.now())),i=Tt(o.font,.9*n),r=e.measureText(s).width;e.font=i;const l=e.measureText(t).width;e.fillStyle=p,e.fillRect(_+1,u-m/2,Math.max(r,l)+2*f,m),e.fillStyle=a.text,e.font=h,e.fillText(s,_+1+f,u-m/4),e.font=i,e.fillText(t,_+1+f,u+m/4)}else Ot(e,_,u,m,f,s,p,a.text)}e.restore()}function Mt(e,t,i,s,r=ht){if(!0!==s.visible)return;if(t.timeAxisHeight<=0||t.priceAxisWidth<=0)return;const n=s.now();if(!Number.isFinite(n))return;const o=Math.floor(n),a=void 0!==s.timezone&&s.timezone!==Me&&Ae(s.timezone)?s.timezone:Me,l=a===Me,h=l?we(o):Xe(o,a),c=l?fe:Ne(o,a),d=Math.round((t.plotWidth+t.priceAxisWidth/2)*i),u=Math.round(t.plotHeight*i),p=t.timeAxisHeight*i,_=!1!==s.showOffset&&t.timeAxisHeight>=20;e.save(),e.fillStyle=r.textColor,e.textAlign="center",e.textBaseline="middle",e.font=Tt(r.font,i),_?(e.fillText(h,d,u+.3*p),e.font=Tt(r.font,.82*i),e.fillText(function(e){const t=Math.round(e/60);if(0===t)return"UTC";const i=Math.abs(t),s=i%60;return`UTC${t<0?"-":"+"}${Math.floor(i/60)}${0===s?"":`:${yt(s)}`}`}(c),d,u+.74*p)):e.fillText(h,d,u+p/2),e.restore()}function Tt(e,t){return e.replace(/(^|[^\d.])(\d{1,5}(?:\.\d{1,4})?)px/,(e,i,s)=>`${i}${Number(s)*t}px`)}function Ct(e,t,i){return{color:t?.color??e.crosshair,width:t?.width??e.crosshairWidth??1,dash:M(t?.style??e.crosshairStyle??"dashed",i)}}function jt(e,t,i,s,r,n,o,a=1,l=[4*n,4*n]){if(e.save(),e.strokeStyle=o,e.lineWidth=Math.max(1,a),e.setLineDash(l),t>=0&&t<=s){const i=Math.round(t*n)+.5;e.beginPath(),e.moveTo(i,0),e.lineTo(i,Math.round(r*n)),e.stroke()}if(null!==i&&i>=0&&i<=r){const t=Math.round(i*n)+.5;e.beginPath(),e.moveTo(0,t),e.lineTo(Math.round(s*n),t),e.stroke()}e.setLineDash([]),e.restore()}function At(e){const t={top:2,normal:1,bottom:0};let i=null;for(const s of e)null!==s&&(null===i||s.distance<i.distance||s.distance===i.distance&&t[s.zOrder]>t[i.zOrder])&&(i=s);return i}const Lt="ui-sans-serif, system-ui, sans-serif",Rt={},zt={};function Ft(e){const t=e.iconSize;return"number"==typeof t&&Number.isFinite(t)?Math.max(12,Math.min(28,t)):16}function Nt(e){return Math.max(18,Ft(e)+2)}const Et=e=>e.parts.reduce((e,t)=>e+t.w+t.gap,0);function Bt(e,t,i){return"ohlc"===t?!1!==e.chartValues:"change"===t?!1!==e.barChange:"volume"===t?!1!==e.volume:"openInterest"===t?!0===e.openInterest&&!1!==i:!1!==e.lastValueLabel}const $t=["hide","settings","close"];function Dt(e,t,i,s,r,n,o){const a=.36*r*n,l=Math.max(1,Math.round(1.4*r*n/16));switch(e.save(),e.strokeStyle=e.fillStyle,e.lineWidth=l,e.lineCap="round",e.lineJoin="round",e.beginPath(),t){case"up":e.moveTo(i,s+a),e.lineTo(i,s-a),e.moveTo(i-.62*a,s-.35*a),e.lineTo(i,s-a),e.lineTo(i+.62*a,s-.35*a);break;case"down":e.moveTo(i,s-a),e.lineTo(i,s+a),e.moveTo(i-.62*a,s+.35*a),e.lineTo(i,s+a),e.lineTo(i+.62*a,s+.35*a);break;case"hide":e.moveTo(i-a,s),e.quadraticCurveTo(i,s-1.15*a,i+a,s),e.quadraticCurveTo(i,s+1.15*a,i-a,s),e.stroke(),e.beginPath(),e.arc(i,s,.34*a,0,2*Math.PI),!0===o.hidden&&(e.moveTo(i-a,s+.85*a),e.lineTo(i+a,s-.85*a));break;case"maximize":!0===o.maximized?(e.moveTo(i-a,s-.25*a),e.lineTo(i-.25*a,s-.25*a),e.lineTo(i-.25*a,s-a),e.moveTo(i+a,s+.25*a),e.lineTo(i+.25*a,s+.25*a),e.lineTo(i+.25*a,s+a)):(e.moveTo(i-a,s-.4*a),e.lineTo(i-a,s-a),e.lineTo(i-.4*a,s-a),e.moveTo(i+.4*a,s-a),e.lineTo(i+a,s-a),e.lineTo(i+a,s-.4*a),e.moveTo(i+a,s+.4*a),e.lineTo(i+a,s+a),e.lineTo(i+.4*a,s+a),e.moveTo(i-.4*a,s+a),e.lineTo(i-a,s+a),e.lineTo(i-a,s+.4*a));break;case"collapse":{const t=!0===o.collapsed?.6*a:0;e.moveTo(i-a,s-.7*a),e.lineTo(i+a,s-.7*a),e.moveTo(i-.6*a,s+.6*a-t),e.lineTo(i,s+t),e.lineTo(i+.6*a,s+.6*a-t);break}case"settings":e.arc(i,s,.46*a,0,2*Math.PI);for(let t=0;t<8;t++){const r=t*Math.PI/4,n=Math.cos(r),o=Math.sin(r);e.moveTo(i+n*a*.68,s+o*a*.68),e.lineTo(i+n*a,s+o*a)}break;case"source":{const t=.62*a,r=.34*a,n=.28*a;for(const o of[-1,1]){const l=i+o*t;e.moveTo(l-o*r,s-a),e.quadraticCurveTo(l,s-a,l,s-.55*a),e.lineTo(l,s-.2*a),e.quadraticCurveTo(l,s,l+o*n,s),e.quadraticCurveTo(l,s,l,s+.2*a),e.lineTo(l,s+.55*a),e.quadraticCurveTo(l,s+a,l-o*r,s+a)}break}case"close":e.moveTo(i-.8*a,s-.55*a),e.lineTo(i+.8*a,s-.55*a),e.moveTo(i-.3*a,s-.55*a),e.lineTo(i-.3*a,s-.85*a),e.lineTo(i+.3*a,s-.85*a),e.lineTo(i+.3*a,s-.55*a),e.moveTo(i-.6*a,s-.55*a),e.lineTo(i-.45*a,s+.85*a),e.lineTo(i+.45*a,s+.85*a),e.lineTo(i+.6*a,s-.55*a)}e.stroke(),e.restore()}class Wt{constructor(e){Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_values",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_buttons",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_width",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_plotWidth",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_plotHeight",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suppressed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._opts={font:11,left:8,top:6,row:0,...e}}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"top"}autoscaleInfo(){return null}setSuppressed(e){this._suppressed!==e&&(this._suppressed=e,e&&this._clearGeometry(),this._host?.requestUpdate())}_clearGeometry(){this._buttons=[],this._width=this._plotWidth=this._plotHeight=0}setValue(e,t){this.setValues(""===e?[]:[{text:e,color:t}])}setValues(e){e.length===this._values.length&&e.every((e,t)=>e.text===this._values[t].text&&e.label===this._values[t].label&&e.color===this._values[t].color&&e.field===this._values[t].field&&e.priority===this._values[t].priority)||(this._values=e.map(e=>({...e})),this._host?.requestUpdate())}setOptions(e){const t=this._opts.statusLine;this._opts={...this._opts,...e},void 0!==e.statusLine&&(this._opts.statusLine={...t,...e.statusLine}),!1===this._opts.visible&&this._clearGeometry(),this._host?.requestUpdate()}_status(){const e=this._opts.status;return void 0===e?zt:("function"==typeof e?e():e)??zt}options(){return this._opts}draw(e,t){const i=this._opts;if(this._suppressed||!1===i.visible)return void this._clearGeometry();const s=t.dpr,r=(i.font??11)*s,n=Ft(i),o=Nt(i),a=((i.top??6)+(i.row??0)*o)*s,l=a+o*s/2,h=(i.left??8)*s;let c=h;const d=!0===i.hidden,u=i.statusLine??Rt,p=this._status(),_=V(t.theme.axisText,.55);this._plotWidth=Math.max(0,t.plotWidth),this._plotHeight=Math.max(0,t.plotHeight);const f=Math.max(0,(this._plotWidth-4)*s-h),m="string"==typeof t.hoverId&&t.hoverId.startsWith(`${i.id}::`),b=Math.max(0,Math.floor((f/s-6)/(n+2))),g=m&&b>0?(i.actions??$t).slice(-b):[],v=g.length?(g.length*(n+2)+6)*s:0;e.save(),e.beginPath(),e.rect(0,0,this._plotWidth*s,t.plotHeight*s),e.clip(),e.textBaseline="middle",e.textAlign="left",e.globalAlpha=d?.45:1;const y=[],w=(t,i,n,o)=>(e.font=`${n?"600 ":""}${r}px ${Lt}`,{k:"text",text:t,color:i,bold:n,w:e.measureText(t).width,gap:o*s}),x=(e,t,i=1)=>{const s=[];void 0!==e.label&&""!==e.label&&s.push(w(e.label,_,!1,3)),s.push(w(e.text,e.color??t,!1,6)),y.push({parts:s,priority:Number.isFinite(e.priority)?e.priority:i,reading:i>0})};let S;if(void 0!==p.logo&&!1!==u.logo&&y.push({parts:[{k:"logo",img:p.logo,w:12*s,gap:5*s}],priority:-1}),void 0!==i.color&&y.push({parts:[{k:"dot",color:i.color,w:6*s,gap:5*s}],priority:-1}),!1!==u.title){const e=u.titleMode??"symbol",s="description"===e?p.description:"ticker"===e?p.ticker:void 0;S=w(s??i.title,t.theme.axisText,!0,6),y.push({parts:[S],priority:0})}void 0!==i.params&&""!==i.params&&y.push({parts:[w(i.params,_,!1,6)],priority:-3}),void 0!==p.marketStatus&&!1!==u.marketStatus&&x(p.marketStatus,_,-4);const P=i.valueColor??i.color??t.theme.axisText;for(const e of this._values)Bt(u,e.field,i.hasOpenInterest)&&x(e,P);void 0!==p.lastDayChange&&!1!==u.lastDayChange&&x(p.lastDayChange,P,-2),e.font=`600 ${r}px ${Lt}`;const O=function(e,t,i,s){if(t.reduce((e,t)=>e+Et(t),0)<=s)return t.flatMap(e=>e.parts);const r=t.filter(e=>!e.parts.includes(i)).sort((e,t)=>t.priority-e.priority);if("text"===i?.k){const t=r.find(e=>e.reading),n=t?Et(t):0,o=n<=.75*s?n:0,a=Math.max(0,s-o-i.gap);if(i.w>a){const t=Array.from(i.text);let s=0,r=t.length;for(;s<r;){const i=Math.ceil((s+r)/2);e.measureText(t.slice(0,i).join("")+"...").width<=a?s=i:r=i-1}i.text=e.measureText("...").width<=a?t.slice(0,s).join("")+"...":"",i.w=e.measureText(i.text).width,i.text||(i.gap=0)}s-=i.w+i.gap}const n=new Set;for(const e of r){const t=Et(e);t<=s&&(n.add(e),s-=t)}return t.filter(e=>e.parts.includes(i)||n.has(e)).flatMap(e=>e.parts)}(e,y,S,Math.max(0,f-v)),k=O[O.length-1];if(!0===u.background&&void 0!==k){const i=4*s,r=O.reduce((e,t)=>e+t.w+t.gap,0)-k.gap+2*i;e.globalAlpha=1,e.fillStyle=V(u.backgroundColor??t.theme.background,u.backgroundOpacity??.8),e.beginPath(),e.roundRect(h-i,l-o/2*s,r,o*s,4*s),e.fill(),e.globalAlpha=d?.45:1}for(const t of O)"text"===t.k?(e.font=`${t.bold?"600 ":""}${r}px ${Lt}`,e.fillStyle=t.color,e.fillText(t.text,c,l)):"dot"===t.k?(e.fillStyle=t.color,e.beginPath(),e.arc(c+3*s,l,3*s,0,2*Math.PI),e.fill()):e.drawImage(t.img,c,l-t.w/2,t.w,t.w),c+=t.w+t.gap;if(this._buttons=[],g.length>0){const r=(g.length*(n+2)+6)*s;e.globalAlpha=1,e.fillStyle=V(t.theme.background,.82),e.beginPath(),e.roundRect(c-3*s,l-o/2*s,r,o*s,5*s),e.fill(),c+=2*s;for(const r of g){const o=`${i.id}::${r}`,h=c;this._buttons.push({id:o,x:h/s,y:a/s});const u=t.hoverId===o;u&&(e.fillStyle=V(t.theme.axisText,.16),e.beginPath(),e.roundRect(h,l-n/2*s,n*s,n*s,4*s),e.fill()),e.globalAlpha=d?.5:u?1:.75,e.fillStyle="close"===r&&u?"#ff6b6b":t.theme.axisText,Dt(e,r,h+n/2*s,l,n,s,i),e.globalAlpha=1,c+=(n+2)*s}}this._width=c/s,e.restore()}hitTest(e,t){if(this._suppressed||!1===this._opts.visible)return null;if(e<0||e>=this._plotWidth||t<0||t>=this._plotHeight)return null;const i=this._opts,s=Nt(i),r=(i.top??6)+(i.row??0)*s;if(t<r||t>r+s)return null;const n=Ft(i);for(const t of this._buttons)if(e>=t.x&&e<=t.x+n)return{externalId:t.id,zOrder:"top",distance:0,cursor:"pointer"};const o=Math.max(this._width,(i.left??8)+40)+130;return e>=(i.left??8)-4&&e<=o?{externalId:`${i.id}::row`,zOrder:"top",distance:0,cursor:"default"}:null}}function qt(e){return"canvas2d"===e.kind||void 0===e.device?null:e.device.lost?"context-lost":e.device.available?null:"unavailable"}const Vt=new Map;function Ht(e,t){Vt.set(e,t)}function Gt(e){return"canvas2d"!==e&&Vt.delete(e)}function Ut(){return Array.from(Vt.keys())}function Kt(e="canvas2d"){const t=Vt.get("canvas2d");if(void 0===t)throw new Error("openalgo-charts: no canvas2d render backend is registered");if("auto"===e){const e=Vt.get("webgl2");return void 0===e?t:()=>e()??t()}const i=Vt.get(e);if(void 0===i)throw new Error(`openalgo-charts: render backend "${e}" is not registered; import the tier that provides it first`);return"canvas2d"===e?i:()=>i()??t()}function Yt(e="canvas2d"){const t=Kt(e)();if(null===t)throw new Error("openalgo-charts: the canvas2d render backend factory returned null");return t}class Xt{constructor(){Object.defineProperty(this,"kind",{enumerable:!0,configurable:!0,writable:!0,value:"canvas2d"}),Object.defineProperty(this,"_canvas",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_ctx",{enumerable:!0,configurable:!0,writable:!0,value:null})}mount(e,t){if(this._canvas=e,this._ctx=t??e.getContext("2d"),null===this._ctx)throw new Error("openalgo-charts: 2D canvas context is not available")}resize(e,t,i){}beginFrame(e){e&&null!==this._ctx&&null!==this._canvas&&(this._ctx.setTransform(1,0,0,1,0,0),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height))}drawSeries(e,t,i,s,r,n,o){null!==this._ctx&&e.draw(this._ctx,t,i,s,r,n,o)}endFrame(){}overlay2d(){return this._ctx}destroy(){this._ctx=null,this._canvas=null}}function Jt(e,t){if("string"==typeof e.color)return e.color;const i=t?e.upColor:e.downColor;return"string"==typeof i?i:"string"==typeof e.closeColor?e.closeColor:void 0}Ht("canvas2d",()=>new Xt);class Zt{constructor(e,t=new Xt){Object.defineProperty(this,"element",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"base",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"top",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_backend",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_rightScale",{enumerable:!0,configurable:!0,writable:!0,value:new v}),Object.defineProperty(this,"_leftScale",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_overlayScales",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_axisLayout",{enumerable:!0,configurable:!0,writable:!0,value:new I}),Object.defineProperty(this,"_ratioLocks",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"weight",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"_series",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_primitives",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_primitiveScales",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_width",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_height",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.element=e.createElement("div"),this.element.style.position="relative",this.element.style.width="100%",this.element.style.flex="1 1 auto",this.element.style.overflow="hidden",this.element.style.borderTopStyle="solid",this.element.style.borderTopWidth="0px",this.element.style.boxSizing="border-box",this.base=new l(e,0),this.top=new l(e,1),this.element.appendChild(this.base.element),this.element.appendChild(this.top.element),this._backend=t,t.mount(this.base.element,this.base.ctx)}get backend(){return this._backend}setBackend(e){e!==this._backend&&(this._backend.destroy(),this._backend=e,e.mount(this.base.element,this.base.ctx),this._width>0&&this._height>0&&e.resize(this._width,this._height,this.base.pixelRatio))}get backendDegradation(){return qt(this._backend)}get priceScale(){return this._rightScale}addSeries(e){this._scaleFor(e.scaleId),this._series.push(e)}_scaleFor(e){if(this._axisLayout.register(e),"left"===e)return this._leftScale??(this._leftScale=new v);if(""===e||e.startsWith("overlay:")){let t=this._overlayScales.get(e);return t||(t=new v,this._overlayScales.set(e,t)),t}return this._rightScale}scaleFor(e){return this._scaleFor(e)}usesScale(e){if(this._series.some(t=>t.scaleId===e))return!0;for(const t of this._primitiveScales.values())if(t===e)return!0;return!1}axisPlacement(e){return this._axisLayout.get(e)}setAxisPlacement(e,t,i){return!!this._axisLayout.set(e,t,i)&&(this._retainPlacedScales(),!0)}restoreAxisPlacements(e){this._axisLayout.restore(e),this._retainPlacedScales()}_retainPlacedScales(){for(const{scaleId:e}of this._axisLayout.entries())this._axisLayout.configured(e)&&this._scaleFor(e)}visibleAxes(e=!0){const t=e&&0===this._series.length&&0===this._primitiveScales.size;return this._axisLayout.entries().filter(e=>"hidden"!==e.side&&(this.usesScale(e.scaleId)||t&&"right"===e.scaleId)).sort((e,t)=>e.side.localeCompare(t.side)||e.order-t.order)}axisSlots(e){if(!0===e.collapsed)return[];const t=this._layout(e),i={left:0,right:0};return this.visibleAxes(e.emptyPriceAxis).map(s=>{const r=e.axisColumnWidth??("left"===s.side?t.plotLeft:t.priceAxisWidth),n=i[s.side]++;return{...s,width:r,x:"left"===s.side?-(n+1)*r:t.plotWidth+n*r}}).filter(e=>e.width>0)}moveSeriesScale(e,t){if(e===t||!this.usesScale(e)||this.usesScale(t))return!1;const i=this._scaleFor(e),s=this._scaleFor(t);this._axisLayout.set(t,t),this._axisLayout.set(e,e),"left"===t?(this._leftScale=i,this._rightScale=s):(this._rightScale=i,this._leftScale=s);for(const i of this._series)i.scaleId===e&&(i.scaleId=t);for(const[i,s]of this._primitiveScales)s===e&&this._primitiveScales.set(i,t);s.setFixedRange(null),s.setAutoScale(!0),s.reset();const r=this._ratioLocks.get(e);return void 0!==r&&(this._ratioLocks.delete(e),this._ratioLocks.set(t,r)),!0}ratioLocked(e){return this._ratioLocks.has(e)}setRatioLock(e,t,i,s){if(!t)return this._ratioLocks.delete(e),!0;const r=this._scaleFor(e);return!!(r.scaled&&i>0&&s>0)&&(r.setAutoScale(!1),this._ratioLocks.set(e,{barSpacing:i,height:s}),!0)}clearRatioLocks(){this._ratioLocks.clear()}scaleOf(e){return this._scaleFor(e.scaleId)}scales(){const e=[this.priceScale];return null!==this._leftScale&&e.push(this._leftScale),e.push(...this._overlayScales.values()),e}scaleStates(){const e=[["right",this.priceScale]];return null!==this._leftScale&&e.push(["left",this._leftScale]),e.push(...this._overlayScales),Object.fromEntries(e.map(([e,t])=>{const i=t.options,s={marginTop:i.marginTop,marginBottom:i.marginBottom,minMove:i.minMove,minPrecision:i.minPrecision,mode:i.mode,inverted:i.inverted,autoScale:t.autoScale,fixedRange:t.fixedRange,placement:this._axisLayout.get(e)};t.autoScale||(s.range=t.priceRange());const r=this._ratioLocks.get(e);return r&&!t.autoScale&&(s.ratioLock={...r}),[e,s]}))}axisScales(){return this._axisLayout.entries().filter(e=>"hidden"!==e.side).map(e=>this._scaleFor(e.scaleId))}hasLeftScale(){return null!==this._leftScale&&this.usesScale("left")}removeSeries(e){const t=this._series.indexOf(e);if(t<0)return!1;if(this._series.splice(t,1),!this.usesScale(e.scaleId)){const t=this._scaleFor(e.scaleId);t.reset(),""===e.scaleId||"hidden"!==this._axisLayout.get(e.scaleId).side||this._axisLayout.configured(e.scaleId)||t.hasConfiguration()||this._ratioLocks.has(e.scaleId)||this._overlayScales.delete(e.scaleId)}return!0}series(){return this._series}reorderSeries(e){const t=new Set(e),i=e.filter(e=>this._series.includes(e));let s=0;for(let e=0;e<this._series.length;e++)t.has(this._series[e])&&(this._series[e]=i[s++])}reorderPrimitives(e){const t=new Set(e),i=e.filter(e=>this._primitives.includes(e));let s=0;for(let e=0;e<this._primitives.length;e++)t.has(this._primitives[e])&&(this._primitives[e]=i[s++])}transferPrimitive(e,t){const i=this._primitives.indexOf(e);if(i<0||t===this||t._destroyed||t.hasPrimitive(e))return!1;const s=this._primitiveScales.get(e);return void 0!==s&&t._scaleFor(s),this._primitives.splice(i,1),this._primitiveScales.delete(e),t._primitives.push(e),void 0!==s&&t._primitiveScales.set(e,s),!0}bindPrimitiveScale(e,t){return!(this._destroyed||!this.hasPrimitive(e))&&(!(null!==t&&("string"!=typeof t||"left"!==t&&"right"!==t&&""!==t&&!t.startsWith("overlay:")))&&(this.primitiveScaleId(e)!==t&&(null===t?this._primitiveScales.delete(e):(this._scaleFor(t),this._primitiveScales.set(e,t)),!0)))}primitiveScaleId(e){return this._primitiveScales.get(e)??null}primitives(){return this._primitives}addPrimitive(e,t){this._primitives.push(e),e.attached?.(t)}hasPrimitive(e){return this._primitives.includes(e)}removePrimitive(e){const t=this._primitives.indexOf(e);return!(t<0)&&(this._primitives.splice(t,1),this._primitiveScales.delete(e),e.detached?.(),!0)}destroy(){this._destroyed=!0,this._primitiveScales.clear();for(const e of this._primitives)e.detached?.();this._primitives.length=0,this._backend.destroy(),this.element.remove()}_primitiveContext(e){const t=this._layout(e),i=this.axisSlots(e).find(e=>"right"===e.scaleId);return{timeScale:e.timeScale,priceScale:this.priceScale,readoutPriceScale:this._readoutScale(),dataLayer:e.dataLayer,plotWidth:t.plotWidth,plotHeight:t.plotHeight,priceAxisWidth:i?.width??0,priceAxisSide:i?.side??"hidden",priceAxisOffset:i?i.x+("left"===i.side?i.width:0):void 0,dpr:e.dpr,theme:e.theme,hoverId:e.hoverId??null,hoverKey:e.hoverKey??null,dragId:e.dragId??null,bars:()=>{for(const t of this._series)if(le(t.type).isPriceSeries)return e.dataLayer.seriesBars(t.dataId);return[]}}}_boundPrimitiveContext(e,t,i){const s=this._primitiveScales.get(e);if(void 0===s)return t;const r=this.axisSlots(i).find(e=>e.scaleId===s);return{...t,priceScale:this._scaleFor(s),priceAxisSide:r?.side??"hidden",priceAxisWidth:r?.width??0,priceAxisOffset:r?r.x+("left"===r.side?r.width:0):void 0}}_live(e){return!0===e.collapsed?this._primitives.filter(e=>e instanceof Wt):this._primitives}hitTestPrimitives(e,t,i){const s=this._primitiveContext(i);return At(this._live(i).map(r=>{if(!r.hitTest)return null;const n=this._boundPrimitiveContext(r,s,i),o=r.hitTest(e,t,n);return null!==o&&this._primitiveScales.has(r)?{...o,priceScale:n.priceScale}:o}))}resize(e,t,i){this._width=e,this._height=t,this.base.resize(e,t,i),this.top.resize(e,t,i),this._backend.resize(e,t,i)}setLayoutSize(e,t){this._width=e,this._height=t}setScaleHeights(e){this.priceScale.setHeight(e),this._leftScale?.setHeight(e);for(const t of this._overlayScales.values())t.setHeight(e)}_layout(e){const t=e.leftAxisWidth??0;return{plotWidth:Math.max(0,this._width-e.priceAxisWidth-t),plotHeight:Math.max(0,this._height-(e.showTimeAxis?e.timeAxisHeight:0)),priceAxisWidth:e.priceAxisWidth,timeAxisHeight:e.showTimeAxis?e.timeAxisHeight:0,plotLeft:t}}autoscale(e,t=1){let i=!1;const s=this._layout(e),r=e.timeScale.visibleRange();i=this._autoscaleScale(this.priceScale,"right",e,s.plotHeight,r,t)||i,this._leftScale&&(i=this._autoscaleScale(this._leftScale,"left",e,s.plotHeight,r,t)||i);for(const[n,o]of this._overlayScales)i=this._autoscaleScale(o,n,e,s.plotHeight,r,t)||i;this._ratioLocks.size>0&&this._applyRatioLocks(e.timeScale.barSpacing,s.plotHeight);for(const e of this._primitives)e.afterAutoscale?.();return i}_autoscaleScale(e,t,i,s,r,n){const o=!0===i.priceOnlyAutoScale&&this._series.some(e=>e.dataId===i.primaryDataId&&e.scaleId===t),a=e=>e.scaleId===t&&(!o||e.dataId===i.primaryDataId);e.setHeight(s);const l=e.options.mode;if("percentage"!==l&&"indexed-to-100"!==l||e.setBaseline(this._firstVisibleValue(a,i,r,o)),!e.autoScale)return!1;let h=1/0,c=-1/0;for(const e of this._series){if(!1===e.style.visible||!a(e))continue;const t=le(e.type),s=e.style.barOffset??0;for(const n of i.dataLayer.visibleBars(e.dataId,r.from-s,r.to-s)){const i=t.extents(n.bar,e.style);i.min<h&&(h=i.min),i.max>c&&(c=i.max)}}for(const e of this._primitives){if(o)break;if((this._primitiveScales.get(e)??"right")!==t)continue;const i=e.autoscaleInfo?.();i&&(i.min<h&&(h=i.min),i.max>c&&(c=i.max))}return h<=c&&e.autoscale(h,c,n)}_applyRatioLocks(e,t){if(e>0&&t>0)for(const[i,s]of this._ratioLocks){const r=t/e/(s.height/s.barSpacing);if(s.barSpacing=e,s.height=t,!isFinite(r)||r<=0||Math.abs(r-1)<1e-9)continue;const n=this._scaleFor(i);n.scaled&&this._scaleSpan(n,r)}}_scaleSpan(e,t){const i=e.height;if(!(i>0))return;const s=i/2*t,r=e.yToPrice(i/2-s),n=e.yToPrice(i/2+s);isFinite(r)&&isFinite(n)&&r!==n&&e.setPriceRange({min:Math.min(r,n),max:Math.max(r,n)})}_firstVisibleValue(e,t,i,s=!1){for(const r of this._series){if(!1===r.style.visible||!e(r))continue;const n=s?r.style.barOffset??0:0;for(const e of t.dataLayer.visibleBars(r.dataId,i.from-n,i.to-n))if(isFinite(e.bar.close))return e.bar.close}return null}paintBase(e,t){const i=this._layout(e),s=e.dpr,r=t??this._backend.overlay2d()??this.base.ctx;void 0===t&&this._backend.beginFrame(!0);const n=!0!==e.collapsed,o=this._live(e),a=L(e.theme,e.canvasOptions?.scales);!1!==e.paintBackground&&"transparent"!==e.theme.background&&(r.fillStyle=e.theme.background,r.fillRect(0,0,Math.round(this._width*s),Math.round(this._height*s))),r.save(),i.plotLeft>0&&r.translate(Math.round(i.plotLeft*s),0);const l=e.canvasOptions?.grid,h=function(e,t,i){const s=Math.max(1,i.spacing),r=[];if(!1!==i.vertLines)for(let t=s;t<e;t+=s)r.push(t);const n=[];if(!1!==i.horzLines)for(let e=s;e<t;e+=s)n.push(e);return{verticals:r,horizontals:n}}(i.plotWidth,i.plotHeight,{...l,spacing:l?.spacing??60,vertLines:e.showVertGrid&&n,horzLines:e.showHorzGrid&&n});(h.verticals.length>0||h.horizontals.length>0)&&function(e,t,i,s,r,n){e.save(),e.lineWidth=Math.max(1,Math.round(n.lineWidth*r));const o=Math.round(i*r),a=Math.round(s*r);C(e,t.verticals,!0,n.vert,n,r,o,a),C(e,t.horizontals,!1,n.horz,n,r,o,a),e.setLineDash([]),e.restore()}(r,h,i.plotWidth,i.plotHeight,s,T(e.theme,l,s)),r.save(),r.beginPath(),r.rect(0,0,Math.round(i.plotWidth*s),Math.round(i.plotHeight*s)),r.clip();const c=this._primitiveContext(e);for(const t of o)"bottom"===t.zOrder()&&t.draw(r,this._boundPrimitiveContext(t,c,e));const d=e.timeScale.visibleRange(),u=this._readoutScale();let p=null;const _=[],f=e.conflate?de(e.timeScale.barSpacing,s,.5,e.conflationFactor):1;for(const o of this._series){if(!1===o.style.visible||!n)continue;const a=this._scaleFor(o.scaleId),l=e=>a.priceToY(e),h=le(o.type),c=o.style.barOffset??0,m=e.dataLayer.visibleBars(o.dataId,d.from-c,d.to-c);let b=m.map(t=>({x:e.timeScale.indexToX(t.index+c),bar:t.bar}));if(f>1&&(b=_e(b,f)),!0===o.style.colorByPreviousClose&&b.length>0){const t=e.dataLayer.visibleBars(o.dataId,m[0].index-1,m[0].index-1);t.length>0&&(b[0].prevClose=t[0].bar.close)}let g=0;for(const e of b)(e.bar.volume??0)>g&&(g=e.bar.volume??0);const v={plotHeight:i.plotHeight,maxVolume:g,theme:e.theme};void 0===t?this._backend.drawSeries(h,b,l,e.timeScale.barSpacing,s,o.style,v):h.draw(r,b,l,e.timeScale.barSpacing,s,o.style,v);const y=e.dataLayer.lastIndexedBar(o.dataId);if(null!==y){const e=Jt(o.style,y.bar.close>=y.bar.open);a===u&&h.isPriceSeries&&null===p?p={close:y.bar.close,up:y.bar.close>=y.bar.open,showLine:!1!==o.style.priceLineVisible,showTag:!1!==o.style.lastValueVisible&&(void 0===e||!H(e))}:!1!==o.style.lastValueVisible&&void 0!==e&&!H(e)&&Number.isFinite(y.bar.close)&&_.push({price:y.bar.close,color:e,scaleId:o.scaleId})}}void 0===t&&this._backend.endFrame(),r.restore();const m=this.axisSlots(e),b={up:e.theme.lastPriceUp,down:e.theme.lastPriceDown,text:e.theme.lastPriceText};null!==p&&It(r,u,p.close,p.up,i,s,a,b,p.showLine,!1,e.barCountdown);const g=t=>{const{side:n,width:o,scaleId:l}=t,h=this._scaleFor(l);if(!h.scaled)return;const c=null!==p&&p.showTag&&u===h,d=_.filter(e=>e.scaleId===l),f={...i,plotLeft:o};r.save();const m=Math.round(t.x*s),g=Math.round((t.x+o)*s);r.beginPath(),r.rect(m,0,g-m,Math.round(i.plotHeight*s)),r.clip(),r.translate("left"===n?g:m-Math.round(i.plotWidth*s),0);const v=[];if(null!==p&&c&&u===h){const t=xt(s,!0===e.barCountdown?.visible),r=St(Math.round(h.priceToY(p.close)*s),i.plotHeight*s,t,n);null!==r&&v.push({y:r,height:t,priority:dt})}const y=v.length;for(const e of d){const t=xt(s),r=St(Math.round(h.priceToY(e.price)*s),i.plotHeight*s,t,n);v.push({y:r??NaN,height:t,priority:ut})}const w=v.length>0?_t(v,2*s):[],x=v.length>0?v.filter((e,t)=>w[t]):void 0;"left"===n?(r.save(),r.translate(-Math.round(o*s),0),function(e,t,i,s,r,n=ht,o){const a=t.ticks(ct(s)),l=ft(a,t,r,o),h=Math.round(i*r);e.save(),e.strokeStyle=n.lineColor,e.fillStyle=n.textColor,e.font=Tt(n.font,r),e.textAlign="right",e.textBaseline="middle",e.lineWidth=1,e.beginPath(),e.moveTo(h-.5,0),e.lineTo(h-.5,Math.round(s*r)),e.stroke();for(let i=0;i<a.length;i++){if(null!==l&&!l[i])continue;const n=a[i],o=Math.round(t.priceToY(n)*r);o<0||o>s*r||e.fillText(t.format(n),h-6*r,o)}e.restore()}(r,h,o,i.plotHeight,s,a,x),r.restore()):function(e,t,i,s,r=ht,n){const o=t.ticks(ct(i.plotHeight)),a=ft(o,t,s,n),l=Math.round(i.plotWidth*s);e.save(),e.strokeStyle=r.lineColor,e.fillStyle=r.textColor,e.font=Tt(r.font,s),e.textAlign="left",e.textBaseline="middle",e.lineWidth=1,e.beginPath(),e.moveTo(l+.5,0),e.lineTo(l+.5,Math.round(i.plotHeight*s)),e.stroke();for(let r=0;r<o.length;r++){if(null!==a&&!a[r])continue;const n=o[r],h=Math.round(t.priceToY(n)*s);h<0||h>i.plotHeight*s||e.fillText(t.format(n),l+6*s,h)}e.restore()}(r,h,f,s,a,x);for(let e=0;e<d.length;e++)w[y+e]&&kt(r,h,d[e].price,d[e].color,f,s,a,n);null!==p&&c&&It(r,h,p.close,p.up,f,s,a,b,!1,!0,e.barCountdown,n),r.restore()};for(const e of m)g(e);for(const t of o)"normal"===t.zOrder()&&t.draw(r,this._boundPrimitiveContext(t,c,e));e.showTimeAxis&&(!function(e,t,i,s,r,n=ht,o,a){const l=t.visibleRange(),h=Math.max(0,Math.floor(l.from)),c=Math.min(i.baseIndex,Math.ceil(l.to));if(c<h)return;const d=Math.max(1,Math.round(80/Math.max(1,t.barSpacing))),u=Math.round(s.plotHeight*r);let p=Number.POSITIVE_INFINITY;{let e=i.indexToTime(h);for(let t=h+1;t<=c;t++){const s=i.indexToTime(t);if(void 0!==s&&void 0!==e){const t=s-e;t>0&&t<p&&(p=t)}void 0!==s&&(e=s)}}const _=p*d,f=Number.isFinite(_)&&_<60,m=void 0!==a&&a!==Me&&Ae(a)?a:Me,b=m===Me,g=b?Ie:(e,t)=>Ee(e,t,m),v=b?Pe:e=>Je(e,m),y=b?ye:e=>Ye(e,m),w=b?we:e=>Xe(e,m);e.save(),e.fillStyle=n.textColor,e.strokeStyle=n.lineColor,e.font=Tt(n.font,r),e.textAlign="center",e.textBaseline="top",e.lineWidth=1,e.beginPath(),e.moveTo(0,u+.5),e.lineTo(Math.round(s.plotWidth*r),u+.5),e.stroke();const x=new Set;{let e=i.indexToTime(h);for(let t=h+1;t<=c;t++){const s=i.indexToTime(t);void 0!==s&&(void 0!==e&&g(e,s)&&x.add(t),e=s)}}const S=[...new Set([...bt(h,c,d),...x])].sort((e,t)=>e-t),P=[];let O;for(const n of S){const a=i.indexToTime(n);if(void 0===a)continue;const l=Math.round(t.indexToX(n)*r);if(l<0||l>s.plotWidth*r){O=a;continue}let h;h=o?o(a,void 0===O?"day":mt(O,a,m,f)):void 0===O||g(O,a)?v(a):f?w(a):y(a),P.push({x:l,text:h,half:e.measureText(h).width/2,boundary:x.has(n)}),O=a}const k=4*r,I=[],M=e=>I.every(t=>e.x+e.half+k<=t.x-t.half||e.x-e.half-k>=t.x+t.half);for(const e of P)e.boundary&&M(e)&&I.push(e);for(const e of P)!e.boundary&&M(e)&&I.push(e);I.sort((e,t)=>e.x-t.x);for(const t of I)e.fillText(t.text,t.x,u+4*r);e.restore()}(r,e.timeScale,e.dataLayer,i,s,a,e.timeFormatter,e.timezone),void 0!==e.sessionClock&&Mt(r,{...i,priceAxisWidth:Math.min(i.priceAxisWidth,e.axisColumnWidth??i.priceAxisWidth)},s,e.sessionClock,a)),r.restore()}paintTop(e,t,i){void 0===i&&this.top.clearBitmap();const s=this._layout(t),r=i??this.top.ctx,n=t.dpr;r.save(),s.plotLeft>0&&r.translate(Math.round(s.plotLeft*n),0);const o=this._primitiveContext(t);for(const e of this._live(t))"top"===e.zOrder()&&e.draw(r,this._boundPrimitiveContext(e,o,t));if(null!==e){const i=Ct(t.theme,t.canvasOptions?.crosshair,n);!0!==t.collapsed&&jt(r,e.x,e.yLocal,s.plotWidth,s.plotHeight,n,i.color,i.width,i.dash);const o=t.theme.crosshairLabelBackground??i.color,a=!1!==t.theme.crosshairLabelVisible;if(a&&null!==e.yLocal){const i=this._readoutScale(),a=this.axisSlots(t).find(e=>this._scaleFor(e.scaleId)===i);if(a){const l=i.format(i.yToPrice(e.yLocal)),h=Math.round(a.x*n),c=Math.round((a.x+a.width)*n),d="left"===a.side?c-this._tagWidth(r,l,n):h;r.save(),r.beginPath(),r.rect(h,0,c-h,Math.round(s.plotHeight*n)),r.clip(),function(e,t,i,s,r,n,o){e.save(),e.font=11*r+"px system-ui, sans-serif";const a=6*r,l=16*r,h=e.measureText(t).width;e.fillStyle=n,e.textBaseline="middle",e.fillRect(i+1,s-l/2,h+2*a,l),e.fillStyle=o,e.textAlign="left",e.fillText(t,i+1+a,s),e.restore()}(r,l,d,e.yLocal*n,n,o,t.theme.lastPriceText),r.restore()}}if(a&&e.showTimeTag&&e.x>=0&&e.x<=s.plotWidth){const i=Math.round(t.timeScale.xToIndex(e.x)),a=t.dataLayer.indexToTime(i);if(void 0!==a){!function(e,t,i,s,r,n,o=ht){e.save(),e.font=Tt(o.font,r);const a=7*r,l=18*r,h=e.measureText(t).width+2*a,c=Math.max(0,i-h/2),d=s+1*r,u=(n.radius??4)*r;e.beginPath(),U(e,c,d,h,l,u),void 0!==n.backplate&&(e.fillStyle=n.backplate,e.fill()),e.fillStyle=n.background,e.fill(),void 0!==n.border&&(e.strokeStyle=n.border,e.lineWidth=Math.max(1,Math.round(r)),e.stroke()),e.fillStyle=n.textColor,e.textAlign="center",e.textBaseline="middle",e.fillText(t,c+h/2,d+l/2),e.restore()}(r,t.timeFormatter?t.timeFormatter(a):Qe(a,t.timezone??Me),e.x*n,s.plotHeight*n,n,{background:o,textColor:t.theme.lastPriceText,backplate:t.theme.background},L(t.theme,t.canvasOptions?.scales))}}}r.restore()}_readoutScale(){for(const e of this._series)if(!1!==e.style.visible&&le(e.type).isPriceSeries)return this._scaleFor(e.scaleId);return this._rightScale}readoutScale(){return this._readoutScale()}priceToY(e){return this._readoutScale().priceToY(e)}_tagWidth(e,t,i){e.save(),e.font=11*i+"px system-ui, sans-serif";const s=e.measureText(t).width+12*i+1;return e.restore(),s}yToPrice(e){return this._readoutScale().yToPrice(e)}}const Qt={background:"#0d0e12",grid:"#161a26",axisText:"#8b91a7",axisLine:"#2a3046",paneSeparator:"#1e2334",crosshair:"#6b7280",upColor:"#26a69a",downColor:"#ef5350",wickUpColor:"#26a69a",wickDownColor:"#ef5350",lineColor:"#4f8cff",areaTopColor:"rgba(79,140,255,0.40)",areaBottomColor:"rgba(79,140,255,0.00)",baselineTopLine:"#26a69a",baselineTopFill:"rgba(38,166,154,0.20)",baselineBottomLine:"#ef5350",baselineBottomFill:"rgba(239,83,80,0.20)",lastPriceUp:"#26a69a",lastPriceDown:"#ef5350",lastPriceText:"#0d0e12",buy:"#26a69a",sell:"#ef5350",profit:"#26a69a",loss:"#ef5350"},ei={background:"#ffffff",grid:"#eef1f6",axisText:"#5b6472",axisLine:"#d4dae3",paneSeparator:"#e6eaf0",crosshair:"#9aa3b2",upColor:"#089981",downColor:"#e0473e",wickUpColor:"#089981",wickDownColor:"#e0473e",lineColor:"#2962ff",areaTopColor:"rgba(41,98,255,0.30)",areaBottomColor:"rgba(41,98,255,0.00)",baselineTopLine:"#089981",baselineTopFill:"rgba(8,153,129,0.18)",baselineBottomLine:"#e0473e",baselineBottomFill:"rgba(224,71,62,0.18)",lastPriceUp:"#089981",lastPriceDown:"#e0473e",lastPriceText:"#ffffff",buy:"#089981",sell:"#e0473e",profit:"#089981",loss:"#e0473e"},ti=ei;class ii{constructor(e,t,i,s,r){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"x0",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"y0",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"x1",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"y1",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"stops",{enumerable:!0,configurable:!0,writable:!0,value:[]})}addColorStop(e,t){this.stops.push({offset:e,color:t})}toString(){return`url(#${this.id})`}}const si=2*Math.PI;function ri(e){if(!Number.isFinite(e))return"0";const t=100*e,i=Number.isFinite(t)?Math.round(t)/100:e;return String(0===i?0:i)}function ni(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function oi(e){return/[ .,:;'|!iIljtfr[\]()-]/.test(e)?.3:/[mwMW@%]/.test(e)?.9:/[A-Z]/.test(e)?.68:.55}function ai(e){const t=e.trim().split(/\s+/);let i=null,s=null,r=10,n=0;for(;n<t.length;n++){const e=t[n],o=/^(\d+(?:\.\d+)?)(px|pt)(?:\/\S+)?$/.exec(e);if(null!==o){r=parseFloat(o[1])*("pt"===o[2]?4/3:1),n++;break}"italic"===e||"oblique"===e?s=e:/^(\d{3}|bold|bolder|lighter)$/.test(e)&&(i=e)}return{size:r,family:t.slice(n).join(" ")||"sans-serif",weight:i,style:s}}const li={top:"text-before-edge",hanging:"hanging",middle:"central",ideographic:"ideographic",bottom:"text-after-edge"},hi={center:"middle",right:"end",end:"end"};class ci{constructor(e,t,i={}){Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"fillStyle",{enumerable:!0,configurable:!0,writable:!0,value:"#000"}),Object.defineProperty(this,"strokeStyle",{enumerable:!0,configurable:!0,writable:!0,value:"#000"}),Object.defineProperty(this,"lineWidth",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"lineCap",{enumerable:!0,configurable:!0,writable:!0,value:"butt"}),Object.defineProperty(this,"lineJoin",{enumerable:!0,configurable:!0,writable:!0,value:"miter"}),Object.defineProperty(this,"miterLimit",{enumerable:!0,configurable:!0,writable:!0,value:10}),Object.defineProperty(this,"globalAlpha",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"font",{enumerable:!0,configurable:!0,writable:!0,value:"10px sans-serif"}),Object.defineProperty(this,"textAlign",{enumerable:!0,configurable:!0,writable:!0,value:"start"}),Object.defineProperty(this,"textBaseline",{enumerable:!0,configurable:!0,writable:!0,value:"alphabetic"}),Object.defineProperty(this,"shadowColor",{enumerable:!0,configurable:!0,writable:!0,value:"rgba(0, 0, 0, 0)"}),Object.defineProperty(this,"shadowBlur",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"shadowOffsetX",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"shadowOffsetY",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"globalCompositeOperation",{enumerable:!0,configurable:!0,writable:!0,value:"source-over"}),Object.defineProperty(this,"imageSmoothingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"canvas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"unsupported",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_out",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_frames",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_gradients",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_clips",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_rootOpen",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_path",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"_hasPoint",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_dash",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_ids",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_strict",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_background",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_fontCache",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._strict=!0===i.strict,this._background=i.background}asCanvasContext(){return this}save(){this._frames.push({kind:"save",open:0,state:this._snapshot()})}restore(){let e=this._frames.length-1;for(;e>=0&&"save"!==this._frames[e].kind;)e--;if(!(e<0)){if(e!==this._frames.length-1&&this._strict)throw new Error("SvgContext: restore() reached across an open pushGroup()");this._closeTo(e)}}pushGroup(e,t={}){let i="<g";for(const t in e)i+=` ${t}="${ni(String(e[t]))}"`;const{translate:s,clip:r}=t;if(void 0!==s&&(i+=` transform="translate(${ri(s.x)} ${ri(s.y)})"`),void 0!==r){i+=` clip-path="url(#${this._clipId(`<rect x="${ri(r.x)}" y="${ri(r.y)}" width="${ri(r.width)}" height="${ri(r.height)}"/>`)})"`}this._out.push(i+">"),this._frames.push({kind:"group",open:1,state:null})}popGroup(){let e=this._frames.length-1;for(;e>=0&&"group"!==this._frames[e].kind;)e--;if(e<0){if(this._strict)throw new Error("SvgContext: popGroup() without a pushGroup()")}else{if(e!==this._frames.length-1&&this._strict)throw new Error("SvgContext: popGroup() reached across an open save()");this._closeTo(e)}}translate(e,t){0===e&&0===t||this._openGroup(`transform="translate(${ri(e)} ${ri(t)})"`)}scale(e,t){1===e&&1===t||this._openGroup(`transform="scale(${ri(e)} ${ri(t)})"`)}rotate(e){0!==e&&this._openGroup(`transform="rotate(${ri(180*e/Math.PI)})"`)}setLineDash(e){this._dash=e.slice()}getLineDash(){return this._dash.slice()}beginPath(){this._path="",this._hasPoint=!1}closePath(){""!==this._path&&(this._path+="Z")}moveTo(e,t){this._path+=`M${ri(e)} ${ri(t)}`,this._hasPoint=!0}lineTo(e,t){this._path+=`${this._hasPoint?"L":"M"}${ri(e)} ${ri(t)}`,this._hasPoint=!0}quadraticCurveTo(e,t,i,s){this._hasPoint||this.moveTo(e,t),this._path+=`Q${ri(e)} ${ri(t)} ${ri(i)} ${ri(s)}`}bezierCurveTo(e,t,i,s,r,n){this._hasPoint||this.moveTo(e,t),this._path+=`C${ri(e)} ${ri(t)} ${ri(i)} ${ri(s)} ${ri(r)} ${ri(n)}`}rect(e,t,i,s){this._path+=`M${ri(e)} ${ri(t)}h${ri(i)}v${ri(s)}h${ri(-i)}Z`,this._hasPoint=!0}roundRect(e,t,i,s,r=0){const n=Array.isArray(r)?r:[r];let[o,a,l,h]=[n[0]??0,n[1]??n[0]??0,n[2]??n[0]??0,n[3]??n[1]??n[0]??0];const c=Math.min(1,i/Math.max(1e-9,o+a,h+l),s/Math.max(1e-9,o+h,a+l));o*=c,a*=c,l*=c,h*=c;const d=(e,t,i)=>e>0?`A${ri(e)} ${ri(e)} 0 0 1 ${ri(t)} ${ri(i)}`:"";this._path+=`M${ri(e+o)} ${ri(t)}H${ri(e+i-a)}${d(a,e+i,t+a)}V${ri(t+s-l)}${d(l,e+i-l,t+s)}H${ri(e+h)}${d(h,e,t+s-h)}V${ri(t+o)}${d(o,e+o,t)}Z`,this._hasPoint=!0}arc(e,t,i,s,r,n=!1){this.ellipse(e,t,i,i,0,s,r,n)}ellipse(e,t,i,s,r,n,o,a=!1){const l=Math.cos(r),h=Math.sin(r),c=r=>{const n=i*Math.cos(r),o=s*Math.sin(r);return[e+n*l-o*h,t+n*h+o*l]};let d,u=!1;a?(u=n-o>=si,d=-((n-o)%si+si)%si):(u=o-n>=si,d=((o-n)%si+si)%si);const[p,_]=c(n);this._path+=`${this._hasPoint?"L":"M"}${ri(p)} ${ri(_)}`,this._hasPoint=!0;const f=ri(180*r/Math.PI),m=(e,t,r)=>{const[n,o]=c(e);this._path+=`A${ri(i)} ${ri(s)} ${f} ${t?1:0} ${r?1:0} ${ri(n)} ${ri(o)}`};if(u){const e=a?-Math.PI:Math.PI;m(n+e,!1,!a),m(n+2*e,!1,!a)}else 0!==d&&m(n+d,Math.abs(d)>Math.PI,d>0)}fill(e,t){if("object"==typeof e)return void this._unsupported("fill(Path2D)");if(""===this._path)return;const i=this._paint(this.fillStyle);null!==i&&this._out.push(`<path d="${this._path}" fill="${i}"${"evenodd"===e?' fill-rule="evenodd"':""}${this._opacity()}/>`)}stroke(e){if(void 0!==e)return void this._unsupported("stroke(Path2D)");if(""===this._path)return;const t=this._strokeAttrs();null!==t&&this._out.push(`<path d="${this._path}" fill="none"${t}${this._opacity()}/>`)}clip(e){if("object"==typeof e)return void this._unsupported("clip(Path2D)");if(""===this._path)return;const t=this._clipId(`<path d="${this._path}"${"evenodd"===e?' clip-rule="evenodd"':""}/>`);this._openGroup(`clip-path="url(#${t})"`)}fillRect(e,t,i,s){const r=this._paint(this.fillStyle);null!==r&&this._rect(e,t,i,s,` fill="${r}"`)}strokeRect(e,t,i,s){const r=this._strokeAttrs();null!==r&&this._rect(e,t,i,s,` fill="none"${r}`)}clearRect(e,t,i,s){void 0!==this._background&&this._rect(e,t,i,s,` fill="${ni(this._background)}"`)}fillText(e,t,i){if(""===e)return;const s=this._paint(this.fillStyle);if(null===s)return;const r=this._font();let n=` font-family="${ni(r.family)}" font-size="${ri(r.size)}"`;null!==r.weight&&(n+=` font-weight="${r.weight}"`),null!==r.style&&(n+=` font-style="${r.style}"`);const o=hi[this.textAlign];void 0!==o&&(n+=` text-anchor="${o}"`);const a=li[this.textBaseline];void 0!==a&&(n+=` dominant-baseline="${a}"`),this._out.push(`<text x="${ri(t)}" y="${ri(i)}"${n} fill="${s}"${this._opacity()}>${ni(e)}</text>`)}measureText(e){const t=this._font();let i=0;for(const t of e)i+=oi(t);const s=null!==t.weight&&("bold"===t.weight||"bolder"===t.weight||parseInt(t.weight,10)>=600),r=i*t.size*(s?1.05:1);return{width:r,actualBoundingBoxLeft:0,actualBoundingBoxRight:r,actualBoundingBoxAscent:.8*t.size,actualBoundingBoxDescent:.2*t.size,fontBoundingBoxAscent:.8*t.size,fontBoundingBoxDescent:.2*t.size}}createLinearGradient(e,t,i,s){const r=new ii("g"+ ++this._ids,e,t,i,s);return this._gradients.push(r),r}drawImage(e,...t){const i=this._imageHref(e);if(null===i)return void this._unsupported("drawImage");const s=e,r=s.naturalWidth??("number"==typeof s.width?s.width:0),n=s.naturalHeight??("number"==typeof s.height?s.height:0),o=this._opacity();if(t.length>=8){const[e,s,a,l,h,c,d,u]=t;return void this._out.push(`<svg x="${ri(h)}" y="${ri(c)}" width="${ri(d)}" height="${ri(u)}" viewBox="${ri(e)} ${ri(s)} ${ri(a)} ${ri(l)}" preserveAspectRatio="none"><image href="${ni(i)}" width="${ri(r)}" height="${ri(n)}" preserveAspectRatio="none"${o}/></svg>`)}const[a,l]=t,h=t.length>=4?t[2]:r,c=t.length>=4?t[3]:n;this._out.push(`<image href="${ni(i)}" x="${ri(a)}" y="${ri(l)}" width="${ri(h)}" height="${ri(c)}" preserveAspectRatio="none"${o}/>`)}setTransform(){this._unsupported("setTransform")}resetTransform(){this._unsupported("resetTransform")}getTransform(){this._unsupported("getTransform")}createRadialGradient(){this._unsupported("createRadialGradient")}createConicGradient(){this._unsupported("createConicGradient")}createPattern(){return this._unsupported("createPattern"),null}getImageData(){this._unsupported("getImageData")}putImageData(){this._unsupported("putImageData")}createImageData(){this._unsupported("createImageData")}strokeText(){this._unsupported("strokeText")}drawFocusIfNeeded(){this._unsupported("drawFocusIfNeeded")}isPointInPath(){return this._unsupported("isPointInPath"),!1}isPointInStroke(){return this._unsupported("isPointInStroke"),!1}toString(){const e=ri(this.width),t=ri(this.height);let i="";for(const e of this._clips)i+=e;for(const e of this._gradients){i+=`<linearGradient id="${e.id}" gradientUnits="userSpaceOnUse" x1="${ri(e.x0)}" y1="${ri(e.y0)}" x2="${ri(e.x1)}" y2="${ri(e.y1)}">`;for(const t of e.stops)i+=`<stop offset="${ri(t.offset)}" stop-color="${ni(t.color)}"/>`;i+="</linearGradient>"}let s="";for(let e=this._frames.length-1;e>=0;e--)s+="</g>".repeat(this._frames[e].open);return s+="</g>".repeat(this._rootOpen),`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}" xml:space="preserve">`+(""===i?"":`<defs>${i}</defs>`)+this._out.join("")+s+"</svg>"}_snapshot(){return{fillStyle:this.fillStyle,strokeStyle:this.strokeStyle,lineWidth:this.lineWidth,lineCap:this.lineCap,lineJoin:this.lineJoin,miterLimit:this.miterLimit,globalAlpha:this.globalAlpha,font:this.font,textAlign:this.textAlign,textBaseline:this.textBaseline,dash:this._dash.slice()}}_apply(e){this.fillStyle=e.fillStyle,this.strokeStyle=e.strokeStyle,this.lineWidth=e.lineWidth,this.lineCap=e.lineCap,this.lineJoin=e.lineJoin,this.miterLimit=e.miterLimit,this.globalAlpha=e.globalAlpha,this.font=e.font,this.textAlign=e.textAlign,this.textBaseline=e.textBaseline,this._dash=e.dash}_closeTo(e){for(;this._frames.length>e;){const e=this._frames.pop();this._out.push("</g>".repeat(e.open)),null!==e.state&&this._apply(e.state)}}_openGroup(e){this._out.push(`<g ${e}>`);const t=this._frames[this._frames.length-1];void 0!==t?t.open++:this._rootOpen++}_clipId(e){const t="c"+ ++this._ids;return this._clips.push(`<clipPath id="${t}">${e}</clipPath>`),t}_rect(e,t,i,s,r){0!==i&&0!==s&&(i<0&&(e+=i,i=-i),s<0&&(t+=s,s=-s),this._out.push(`<rect x="${ri(e)}" y="${ri(t)}" width="${ri(i)}" height="${ri(s)}"${r}${this._opacity()}/>`))}_paint(e){return this.globalAlpha<=0?null:"string"!=typeof e?e instanceof ii?e.toString():null:"transparent"===e?null:ni(e)}_strokeAttrs(){if(!(this.lineWidth>0))return null;const e=this._paint(this.strokeStyle);if(null===e)return null;let t=` stroke="${e}" stroke-width="${ri(this.lineWidth)}"`;return"butt"!==this.lineCap&&(t+=` stroke-linecap="${this.lineCap}"`),"miter"!==this.lineJoin&&(t+=` stroke-linejoin="${this.lineJoin}"`),this._dash.some(e=>e>0)&&(t+=` stroke-dasharray="${this._dash.map(ri).join(" ")}"`),t}_opacity(){return this.globalAlpha<1?` opacity="${ri(this.globalAlpha)}"`:""}_font(){return null!==this._fontCache&&this._fontCache.font===this.font||(this._fontCache={font:this.font,parsed:ai(this.font)}),this._fontCache.parsed}_imageHref(e){const t=e;if("string"==typeof t.src&&""!==t.src)return t.src;if("function"==typeof t.toDataURL)try{return t.toDataURL.call(e)}catch{return null}return null}_unsupported(e){if(this._strict)throw new Error(`SvgContext: ${e} has no SVG form and cannot be exported`);this.unsupported.includes(e)||this.unsupported.push(e)}}function di(e,t=!1){if(void 0===e)return;if(null===e||"object"!=typeof e||Array.isArray(e))throw new TypeError("Series options must be an object");if(void 0!==e.confirmation&&"auto"!==e.confirmation&&"forming"!==e.confirmation&&"confirmed"!==e.confirmation)throw new TypeError("Series confirmation must be auto, forming or confirmed");const i=e.source;if(t&&void 0!==i&&"live"!==i&&"history"!==i)throw new TypeError("Series update source must be live or history")}class ui{constructor(e){Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tailTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._state=Object.freeze({sourceId:e,revision:0,historyRevision:0,provenance:"history",change:"reset"})}snapshot(){return this._state}record(e,t,i){const s="reset"===e||"prepend"===e||"correction"===e||"history"===i?.source,r="correction"===e?void 0:i?.confirmation,n="auto"===r?void 0:r??("reset"!==e&&t===this._tailTime?this._state.confirmation:void 0);this._tailTime=t,this._state=Object.freeze({sourceId:this._state.sourceId,revision:this._state.revision+1,historyRevision:this._state.historyRevision+(s?1:0),provenance:s?"history":"live",change:e,...void 0===t||void 0===n?{}:{confirmation:n,confirmationSource:"provider"}})}contextChanged(){this.record("reset",this._tailTime)}}const pi=new WeakMap;function _i(e){const t=pi.get(e)?.snapshot().confirmation;return void 0===t?void 0:{confirmation:t}}const fi=new WeakMap,mi=new WeakMap;function bi(e){return fi.get(e)}function gi(e){return fi.has(e)}function vi(e,t){t?fi.set(e,Object.freeze({...t})):fi.delete(e);for(const t of mi.get(e)??[])t()}function yi(e,t){let i=mi.get(e);return i||(i=new Set,mi.set(e,i)),i.add(t),()=>{i.delete(t),i.size||mi.delete(e)}}function wi(e,t){const i=[...new Set(t.filter(e=>void 0!==e))],s=1===i.length?null:new AbortController,r=s?.signal??i[0];return new Promise((t,n)=>{let o=!1;const a=new Map,l=e=>{o||(o=!0,(()=>{for(const[e,t]of a)e.removeEventListener("abort",t);a.clear()})(),e())},h=e=>{l(()=>{n(e.reason),s?.abort(e.reason)})},c=i.find(e=>e.aborted);if(c)h(c);else{for(const e of i){const t=()=>h(e);a.set(e,t),e.addEventListener("abort",t,{once:!0})}try{Promise.resolve(e(r)).then(e=>l(()=>t(e)),e=>l(()=>n(e)))}catch(e){l(()=>n(e))}}})}function xi(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function Si(e){return"string"==typeof e&&e.trim().length>0}function Pi(e){if("object"!=typeof e||null===e)return!1;const t=Object.getOwnPropertyDescriptor(e,"kind");return void 0!==t&&"value"in t&&"indicator"===t.value}function Oi(e){if(!xi(e))throw new TypeError("Study source reference must be a plain object.");const t=Reflect.ownKeys(e);if(3!==t.length||!t.every(e=>"kind"===e||"instanceId"===e||"plotKey"===e))throw new TypeError("Study source reference requires only kind, instanceId and plotKey.");const i=Object.getOwnPropertyDescriptor(e,"kind"),s=Object.getOwnPropertyDescriptor(e,"instanceId"),r=Object.getOwnPropertyDescriptor(e,"plotKey");if(!(i&&s&&r&&"value"in i&&"value"in s&&"value"in r))throw new TypeError("Study source reference fields must be own data properties.");if("indicator"!==i.value||!Si(s.value)||!Si(r.value))throw new TypeError("Study source reference requires nonempty instanceId and plotKey strings.");return{kind:"indicator",instanceId:s.value,plotKey:r.value}}function ki(e){if(!xi(e))throw new TypeError("Indicator settings must be a plain object.");const t={};for(const i of Object.keys(e)){const s=Object.getOwnPropertyDescriptor(e,i);if(!("value"in s))throw new TypeError(`Indicator settings property "${i}" must be a data property.`);const r=s.value;Object.defineProperty(t,i,{value:Pi(r)?Oi(r):r,writable:!0,configurable:!0,enumerable:!0})}return t}function Ii(e,t){let i=e.length;for(e.push(t);i>0;){const s=i-1>>>1;if(e[s]<=t)break;e[i]=e[s],i=s}e[i]=t}function Mi(e){const t=e[0],i=e.pop();if(0===e.length)return t;let s=0;for(;2*s+1<e.length;){let t=2*s+1;if(t+1<e.length&&e[t+1]<e[t]&&t++,e[t]>=i)break;e[s]=e[t],s=t}return e[s]=i,t}function Ti(e){const t=new Map;for(let i=0;i<e.length;i++){const s=e[i].id;if(!Si(s))throw new TypeError("Indicator instance id must be a nonempty string.");if(t.has(s))throw new TypeError(`Duplicate indicator instance id "${s}".`);t.set(s,i)}const i=new Map,s=e.map(()=>[]),r=e.map(()=>0);for(let n=0;n<e.length;n++){const o=e[n],a=ki(o.settings);for(const e of Object.keys(a))if(Pi(a[e])&&!o.descriptor.inputs.some(t=>t.key===e&&"source"===t.type&&!0===t.allowStudyOutputs))throw new TypeError(`Indicator "${o.id}" input "${e}" does not support study sources.`);const l=[],h=new Set;for(const i of o.descriptor.inputs){if("source"!==i.type)continue;const s=Object.getOwnPropertyDescriptor(a,i.key),r=s?s.value:i.default;if("string"==typeof r)continue;const n=Oi(r);if(!0!==i.allowStudyOutputs)throw new TypeError(`Indicator "${o.id}" input "${i.key}" does not support study sources.`);if(n.instanceId===o.id)throw new TypeError(`Indicator "${o.id}" cannot reference itself (self dependency).`);const c=t.get(n.instanceId);if(void 0!==c){const t=e[c].descriptor.plots.filter(e=>e.key===n.plotKey);if(1!==t.length)throw new TypeError(`Study source plot "${n.plotKey}" must identify one declared plot on "${n.instanceId}".`);if(void 0!==t[0].ohlc)throw new TypeError(`Study source plot "${n.plotKey}" must be scalar, without an OHLC mapping.`);h.add(c)}l.push({inputKey:i.key,source:n,available:void 0!==c})}i.set(o.id,l),r[n]=h.size;for(const e of h)s[e].push(n)}const n=[],o=[];for(let t=0;t<e.length;t++)0===r[t]&&Ii(n,t);for(;n.length>0;){const t=Mi(n);o.push(e[t].id);for(const e of s[t])r[e]--,0===r[e]&&Ii(n,e)}if(o.length!==e.length)throw new TypeError("Study source references contain a dependency cycle.");return{order:o,dependencies:i}}class Ci extends Error{constructor(e){super(e),this.name="IndicatorInputError"}}function ji(e,t){for(const i of e){if(!["symbol","session","multiline","price","timestamp"].includes(i.type))continue;const s=e=>{throw new Ci(`Invalid study input "${i.key}": ${e}`)},r=Object.getOwnPropertyDescriptor(t,i.key);r&&!("value"in r)&&s("expected a data property");const n=r?r.value:i.default;if("price"===i.type||"timestamp"===i.type){const{min:e,max:t,step:r}=i;(void 0!==e&&!Number.isFinite(e)||void 0!==t&&!Number.isFinite(t)||void 0!==e&&void 0!==t&&e>t||void 0!==r&&(!Number.isFinite(r)||r<=0))&&s("invalid numeric constraints");const o=i=>"number"==typeof i&&Number.isFinite(i)&&(void 0===e||i>=e)&&(void 0===t||i<=t);o(i.default)&&o(n)||s("expected a finite number within the declared bounds");const a=i.pick;if(void 0!==a&&"boolean"!=typeof a){"price"===i.type&&null!==a&&"object"==typeof a||s("invalid pick target");const e=a;[Object.prototype,null].includes(Object.getPrototypeOf(e))||s("invalid pick target");const t=Object.getOwnPropertyDescriptors(e);Object.values(t).some(e=>!("value"in e))&&s("invalid pick target");const r=t.paneIndex?.value,n=t.priceScaleId?.value;void 0!==r&&(!Number.isSafeInteger(r)||r<0)&&s("invalid pick pane"),void 0===n||"right"===n||"left"===n||""===n||"string"==typeof n&&n.startsWith("overlay:")||s("invalid pick scale")}}else if("string"==typeof i.default&&"string"==typeof n||s("expected text"),"session"!==i.type||nt(i.default)&&nt(n)||s("expected a session such as 0930-1600:23456"),"symbol"===i.type&&void 0!==i.exchangeKey){"string"==typeof i.exchangeKey&&i.exchangeKey&&i.exchangeKey!==i.key||s("invalid exchange field");const r=Object.getOwnPropertyDescriptor(t,i.exchangeKey);!r||"value"in r&&"string"==typeof r.value||s(`expected text in "${i.exchangeKey}"`);const n=e.find(e=>e.key===i.exchangeKey);n&&"string"!=typeof n.default&&s("exchange field must default to text")}}}const Ai=[{label:"Solid",value:"solid"},{label:"Dashed",value:"dashed"},{label:"Dotted",value:"dotted"}];function Li(e){return{color:e.colorKey??`${e.key}:color`,width:`${e.key}:width`,lineStyle:`${e.key}:lineStyle`,opacity:`${e.key}:opacity`,type:`${e.key}:type`}}function Ri(e){const t=[];for(const i of e.plots){const s=Li(i),r=e.inputs.find(e=>e.key===i.colorKey),n="string"==typeof r?.default?r.default:i.style?.color??"#4f8cff";t.push({key:s.color,type:"color",label:i.title,default:n,group:i.title}),t.push({key:s.opacity,type:"number",label:"Opacity",default:100,min:0,max:100,step:1,group:i.title}),t.push({key:s.width,type:"number",label:"Thickness",default:i.style?.lineWidth??1.5,min:.5,max:8,step:.5,group:i.title}),t.push({key:s.lineStyle,type:"select",label:"Line style",default:i.style?.lineStyle??"solid",options:Ai,group:i.title}),t.push({key:s.type,type:"select",label:"Plot style",default:i.type,options:zi,group:i.title})}return t}const zi=[{label:"Line",value:"line"},{label:"Line with markers",value:"line-markers"},{label:"Step line",value:"step"},{label:"Area",value:"area"},{label:"Histogram",value:"histogram"},{label:"Columns",value:"column"}],Fi=[{label:"Close",value:"close"},{label:"Open",value:"open"},{label:"High",value:"high"},{label:"Low",value:"low"},{label:"HL2",value:"hl2"},{label:"HLC3",value:"hlc3"},{label:"OHLC4",value:"ohlc4"}],Ni=new Map;function Ei(e){ji(e.inputs,{}),Ni.set(e.id,e)}function Bi(e){const t=Ni.get(e);if(void 0===t)throw new Error(`openalgo-charts: unknown indicator "${e}" — did you import 'openalgo-charts/indicators'?`);return t}function $i(e){return Ni.has(e)}function Di(){return Array.from(Ni.values())}function Wi(e){ji(e.inputs,{});const t=Object.fromEntries(e.inputs.map(e=>[e.key,e.default]));for(const i of e.inputs)"symbol"!==i.type||void 0===i.exchangeKey||Object.prototype.hasOwnProperty.call(t,i.exchangeKey)||Object.defineProperty(t,i.exchangeKey,{value:"",enumerable:!0,writable:!0,configurable:!0});return t}function qi(e,t){switch(t){case"open":return e.open;case"high":return e.high;case"low":return e.low;case"hl2":return(e.high+e.low)/2;case"hlc3":return(e.high+e.low+e.close)/3;case"ohlc4":return(e.open+e.high+e.low+e.close)/4;case"volume":return e.volume??0;default:return e.close}}function Vi(e,t,i){if("string"!=typeof t){if(null===t||"object"!=typeof t||Object.getPrototypeOf(t)!==Object.prototype&&null!==Object.getPrototypeOf(t))throw new Ci("Invalid study source reference");const s=Object.getOwnPropertyDescriptors(t);if(3!==Reflect.ownKeys(s).length||"indicator"!==s.kind?.value||"string"!=typeof s.instanceId?.value||!s.instanceId.value.trim()||"string"!=typeof s.plotKey?.value||!s.plotKey.value.trim())throw new Ci("Invalid study source reference");if(!i?.resolveSource)throw new Ci("Study source requires a calculation resolver");const r=i.resolveSource(t);if(!Array.isArray(r)||r.length!==e.length)throw new Ci("Study source length must align with source bars");return r.slice()}const s=new Array(e.length);for(let i=0;i<e.length;i++)s[i]=qi(e[i],t);return s}const Hi=new Set(["everyUpdate","oncePerBar","onBarClose","once"]);function Gi(e,t){const i={};for(const s of Object.keys(e))Object.defineProperty(i,s,{value:Object.freeze(e[s].slice(0,t)),enumerable:!0});return Object.freeze(i)}class Ui{constructor(e){Object.defineProperty(this,"_entries",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_legacyCalculations",{enumerable:!0,configurable:!0,writable:!0,value:new WeakSet}),Object.defineProperty(this,"_initialized",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_native",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_sourceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_historyRevision",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_revision",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_replaying",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_epoch",{enumerable:!0,configurable:!0,writable:!0,value:0});const t=new Set;for(const i of e){const e=i.frequency;if(void 0!==e){if(!Hi.has(e))throw new TypeError("Indicator alert frequency is invalid");if("string"!=typeof i.id||""===i.id.trim())throw new TypeError("Explicit indicator alert id must be nonempty");if(t.has(i.id))throw new TypeError("Explicit indicator alert ids must be unique");t.add(i.id),this._entries.push({spec:Object.freeze({...i,frequency:e}),onceSpent:!1,perBarTime:-1/0,closedTime:-1/0,failedCloses:new Set,busy:!1})}}}evaluate(e,t){if(0===this._entries.length||!e.current())return;const i=e.calculation.execution,s=void 0!==i,r="replay"===i?.provenance,n=!this._initialized||this._native!==s||s&&(i.sourceId!==this._sourceId||i.historyRevision!==this._historyRevision||r!==this._replaying);if(s){if(!n&&void 0!==this._revision&&i.revision<=this._revision)return}else{if(this._legacyCalculations.has(e.calculation))return;this._legacyCalculations.add(e.calculation)}const o=++this._epoch;this._initialized=!0,this._native=s,this._sourceId=i?.sourceId,this._historyRevision=i?.historyRevision,this._revision=i?.revision,this._replaying=r;const a=e.calculation.barState.isConfirmed,l=e.refresh||"refresh"===i?.change,h=s?"live"===i.provenance:e.tailOnly;if(n||!l&&!h)return void this._seed(e.bars,a);if(l||!h||0===e.bars.length)return;const c=Object.freeze(e.bars.map(e=>Object.freeze({...e}))),d=Gi(e.values),u=Object.freeze({...e.settings}),p=()=>this._epoch===o&&e.current();if(!p())return;let _,f=!1;const m=c.length-1,b=a?m:m-1;for(const e of this._entries){if(!p())return;if(e.busy||"once"===e.spec.frequency&&e.onceSpent)continue;const i="onBarClose"===e.spec.frequency,s=i?this._closeIndices(e,c,b):[m];for(const r of s){if(!p())return;const s=c[r].time;if("oncePerBar"===e.spec.frequency&&s<=e.perBarTime)continue;const n={bars:i?Object.freeze(c.slice(0,r+1)):c,values:i?Gi(d,r+1):d,settings:u,index:r};let o=!1;e.busy=!0;try{if(!p())return;const a=e.spec.when(n);if(!p())return;if(!a){i&&this._judgeClose(e,s);continue}const l="function"==typeof e.spec.message?e.spec.message(n):e.spec.message??e.spec.title;if(!p())return;const h={alertId:e.spec.id,title:e.spec.title,message:l,time:s,index:r};if("once"===e.spec.frequency&&(e.onceSpent=!0),"oncePerBar"===e.spec.frequency&&(e.perBarTime=s),i&&this._judgeClose(e,s),o=!0,t(h),!p())return}catch(t){if(!p())return;i&&!o&&e.failedCloses.add(s),f||(f=!0,_=t)}finally{e.busy=!1}}}if(f&&p())throw _}_seed(e,t){const i=e.length-(t?1:2),s=i>=0?e[i].time:-1/0;for(const e of this._entries)e.perBarTime=s,e.closedTime=s,e.failedCloses.clear()}_judgeClose(e,t){e.closedTime=Math.max(e.closedTime,t),e.failedCloses.delete(t)}_closeIndices(e,t,i){const s=[],r=new Set;for(let n=0;n<=i;n++){const i=t[n].time;(i>e.closedTime||e.failedCloses.has(i))&&s.push(n),r.add(i)}for(const t of e.failedCloses)r.has(t)||e.failedCloses.delete(t);return s}}function Ki(e){if(void 0!==e.fontSize&&("number"!=typeof e.fontSize||!Number.isFinite(e.fontSize)||e.fontSize<=0))throw new TypeError("Text fontSize must be a positive finite number");if(void 0!==e.fontFamily&&("string"!=typeof e.fontFamily||""===e.fontFamily.trim()))throw new TypeError("Text fontFamily must be a nonempty CSS font-family list");for(const t of["bold","italic"])if(void 0!==e[t]&&"boolean"!=typeof e[t])throw new TypeError(`Text ${t} must be boolean`);if(void 0!==e.textAlign&&!["left","center","right"].includes(e.textAlign))throw new TypeError("Text textAlign must be left, center or right")}function Yi(e){return void 0!==e.fontSize||void 0!==e.fontFamily||void 0!==e.bold||void 0!==e.italic||void 0!==e.textAlign}function Xi(e,t,i,s=!1){return`${e?.italic?"italic ":""}${e?.bold??s?"600 ":""}${function(e){const t=String(e),i=t.indexOf("e");if(i<0)return t;const s=t.slice(0,i),r=Number(t.slice(i+1)),n=s.replace(".",""),o=(s.indexOf(".")<0?s.length:s.indexOf("."))+r;return o<=0?`0.${"0".repeat(-o)}${n}`:o>=n.length?n+"0".repeat(o-n.length):`${n.slice(0,o)}.${n.slice(o)}`}(t)}px ${e?.fontFamily??i}`}const Ji={tiny:6,small:9,medium:12,big:16};function Zi(e){return Ji[e]}function Qi(e,t){return Math.max(4,Math.min(Ji[e],Math.floor(t)))}function es(e,t,i,s,r,n){const o=r/2;switch(e.fillStyle=n,e.strokeStyle=n,e.beginPath(),t){case"arrowUp":case"triangleUp":e.moveTo(i,s-o),e.lineTo(i+o,s+o),e.lineTo(i-o,s+o),e.closePath(),e.fill();break;case"arrowDown":case"triangleDown":e.moveTo(i,s+o),e.lineTo(i+o,s-o),e.lineTo(i-o,s-o),e.closePath(),e.fill();break;case"circle":e.arc(i,s,o,0,2*Math.PI),e.fill();break;case"square":e.fillRect(i-o,s-o,r,r);break;case"diamond":e.moveTo(i,s-o),e.lineTo(i+o,s),e.lineTo(i,s+o),e.lineTo(i-o,s),e.closePath(),e.fill();break;case"flag":e.fillRect(i-1,s-o,Math.max(1,r/8),r),e.fillRect(i,s-o,o,.8*o);break;case"cross":{const t=Math.max(1,Math.round(r/6));e.fillRect(i-o,s-Math.floor(t/2),r,t),e.fillRect(i-Math.floor(t/2),s-o,t,r);break}case"xcross":e.lineWidth=Math.max(1,Math.round(r/6)),e.moveTo(i-o,s-o),e.lineTo(i+o,s+o),e.moveTo(i+o,s-o),e.lineTo(i-o,s+o),e.stroke()}}const ts=1.35;function is(e,t,i,s,r){const n=.5*r,o=s.indexOf("\n")<0?void 0:s.split("\n");let a=e.measureText(void 0===o?s:o[0]).width;if(void 0!==o)for(let t=1;t<o.length;t++)a=Math.max(a,e.measureText(o[t]).width);const l=r*ts,h=a+2*n,c=r+.64*r+(void 0===o?0:l*(o.length-1)),d=.42*r;return{lines:o,lh:l,w:h,h:c,tail:d,textW:a,top:t?i+d:i-d-c}}function ss(e,t,i,s,r,n,o){e.font=`600 ${o}px system-ui, sans-serif`;rs(e,t,i,s,r,n,o,is(e,t,s,r,o))}function rs(e,t,i,s,r,n,o,a,l){const{w:h,h:c,top:d,tail:u,lines:p,lh:_,textW:f}=a;e.fillStyle=n,e.beginPath(),U(e,i-h/2,d,h,c,Math.min(.3*o,c/2)),e.fill();const m=t?d+1:d+c-1;e.beginPath(),e.moveTo(i,s),e.lineTo(i-u,m),e.lineTo(i+u,m),e.closePath(),e.fill(),e.fillStyle=l?.textColor??q(n),e.textAlign=l?.textAlign??"center",e.textBaseline="middle";const b="left"===l?.textAlign?i-f/2:"right"===l?.textAlign?i+f/2:i;if(void 0===p)return void e.fillText(r,b,d+c/2);const g=d+c/2-_*(p.length-1)/2;for(let t=0;t<p.length;t++)e.fillText(p[t],b,g+_*t)}class ns{constructor(e,t,i){Object.defineProperty(this,"_seriesId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_fallbackBars",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_priceScale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_markers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_lastPositions",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this._seriesId=e,this._fallbackBars=t,this._priceScale=i}attached(e){this._host=e}detached(){this._host=null,this._lastPositions=[]}zOrder(){return"normal"}setMarkers(e){for(const t of e)if(Ki(t),void 0!==t.textColor&&("string"!=typeof t.textColor||""===t.textColor.trim()))throw new TypeError("Marker textColor must be a nonempty color string");this._markers=e.slice().sort((e,t)=>e.time-t.time),this._lastPositions=[],this._host?.requestUpdate()}draw(e,t){if(this._lastPositions=[],0===this._markers.length)return;const i=new Map;if(void 0!==this._fallbackBars)for(const e of this._fallbackBars())i.set(e.time,e);for(const{bar:e}of t.dataLayer.indexedBars(this._seriesId))Number.isFinite(e.close)&&i.set(e.time,e);const s=this._priceScale?.()??t.priceScale,r=t.timeScale.visibleRange(),n=new Map;e.save();for(const o of this._markers){const a=Yi(o)||void 0!==o.textColor,l=t.dataLayer.timeToIndex(o.time);if(void 0===l||!a&&(l<r.from-1||l>r.to+1))continue;const h=i.get(o.time),c=Qi(o.size,t.timeScale.barSpacing)*t.dpr,d=t.timeScale.indexToX(l)*t.dpr,u=n.get(o.time)??0,p=(c+4*t.dpr)*u;let _;if("paneTop"===o.position)_=c/2+4*t.dpr+p;else if("paneBottom"===o.position)_=t.plotHeight*t.dpr-c/2-4*t.dpr-p;else if("atPrice"===o.position&&void 0!==o.price)_=s.priceToY(o.price)*t.dpr;else if(void 0!==h&&"aboveBar"===o.position)_=s.priceToY(h.high)*t.dpr-c-p;else if(void 0!==h&&"belowBar"===o.position)_=s.priceToY(h.low)*t.dpr+c+p;else{if(void 0===h)continue;_=s.priceToY((h.open+h.close)/2)*t.dpr}if(!Number.isFinite(_)||!Number.isFinite(d))continue;n.set(o.time,u+1);const f=(o.fontSize??Math.max(9,Zi(o.size)))*t.dpr,m="labelUp"===o.shape||"labelDown"===o.shape,b=Number.isFinite(f)&&f>0;if(m&&!b)continue;let g=b&&void 0!==o.text;const v="belowBar"===o.position||"paneTop"===o.position,y=v?_+c:_-c;let w,x=0;if(a){g&&(e.font=Xi(o,f,"system-ui, sans-serif",m));let i=d-c/2,s=d+c/2,r=_-c/2,n=_+c/2;if(g&&void 0!==o.text)if(m)w=is(e,"labelUp"===o.shape,_,o.text,f),i=d-w.w/2,s=d+w.w/2,r=Math.min(_,w.top),n=Math.max(_,w.top+w.h);else{const t=o.text.split("\n");for(const i of t)x=Math.max(x,e.measureText(i).width);const a=f+(t.length-1)*f*ts;i=Math.min(i,d-x/2),s=Math.max(s,d+x/2),r=Math.min(r,v?y:y-a),n=Math.max(n,v?y+a:y)}if(m||[i,s,r,n].every(Number.isFinite)||(g=!1,i=d-c/2,s=d+c/2,r=_-c/2,n=_+c/2),![i,s,r,n].every(Number.isFinite)||s<0||i>t.plotWidth*t.dpr||n<0||r>t.plotHeight*t.dpr)continue;e.save(),e.beginPath(),e.rect(0,0,t.plotWidth*t.dpr,t.plotHeight*t.dpr),e.clip()}const S=a?{width:t.plotWidth,height:t.plotHeight}:void 0;if("labelUp"!==o.shape&&"labelDown"!==o.shape){if(es(e,o.shape,d,_,c,o.color),g&&void 0!==o.text){e.fillStyle=o.textColor??o.color,e.font=Xi(o,f,"system-ui, sans-serif"),e.textAlign=o.textAlign??"center",e.textBaseline=v?"top":"bottom";const t="left"===o.textAlign?d-x/2:"right"===o.textAlign?d+x/2:d;if(o.text.indexOf("\n")<0)e.fillText(o.text,t,y);else{const i=o.text.split("\n"),s=f*ts;for(let r=0;r<i.length;r++)e.fillText(i[v?r:i.length-1-r],t,v?y+s*r:y-s*r)}}void 0!==o.id&&this._lastPositions.push({id:o.id,x:d/t.dpr,y:_/t.dpr,clip:S}),a&&e.restore()}else void 0!==o.text&&(w?rs(e,"labelUp"===o.shape,d,_,o.text,o.color,f,w,o):ss(e,"labelUp"===o.shape,d,_,o.text,o.color,f)),void 0!==o.id&&this._lastPositions.push({id:o.id,x:d/t.dpr,y:_/t.dpr,clip:S}),a&&e.restore()}e.restore()}hitTest(e,t){let i=null;for(const s of this._lastPositions){if(s.clip&&(e<0||t<0||e>s.clip.width||t>s.clip.height))continue;const r=Math.hypot(s.x-e,s.y-t);r<=8&&(null===i||r<i.distance)&&(i={externalId:s.id,zOrder:"normal",distance:r,cursor:"pointer"})}return i}}function os(e,t){return e===t||void 0!==e&&void 0!==t&&e.topValue===t.topValue&&e.bottomValue===t.bottomValue&&e.topColor===t.topColor&&e.bottomColor===t.bottomColor}class as{constructor(e){Object.defineProperty(this,"_points",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_visible",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this._opts={opacity:.12,...e}}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"bottom"}autoscaleInfo(){return null}setPoints(e){this._points=e.slice(),this._host?.requestUpdate()}setOptions(e){this._opts={...this._opts,...e},this._host?.requestUpdate()}setVisible(e){this._visible=e,this._host?.requestUpdate()}draw(e,t){if(!this._visible||this._points.length<2)return;const i=t.dpr,s=e=>t.timeScale.indexToX(e)*i,r=e=>t.priceScale.priceToY(e)*i,n=new Map;let o;const a=t=>{let i=t.topValue,s=t.bottomValue;if(void 0===i||void 0===s){if(void 0===o){let e=1/0,t=-1/0;for(const i of this._points)for(const s of[i.a,i.b])null!==s&&Number.isFinite(s)&&(e=Math.min(e,s),t=Math.max(t,s));o={min:e,max:t}}i??(i=o.max),s??(s=o.min)}const a=r(i),l=a+(r(s)-a||1),h=JSON.stringify([a,l,t.topColor,t.bottomColor]);let c=n.get(h);return void 0===c&&(c=e.createLinearGradient(0,a,0,l),c.addColorStop(0,t.topColor),c.addColorStop(1,t.bottomColor),n.set(h,c)),c};e.save(),e.globalAlpha=this._opts.opacity??.12;let l=null;const h=()=>{if(null!==l&&l.xs.length>=2){e.beginPath(),e.moveTo(l.xs[0],l.top[0]);for(let t=1;t<l.xs.length;t++)e.lineTo(l.xs[t],l.top[t]);for(let t=l.xs.length-1;t>=0;t--)e.lineTo(l.xs[t],l.bot[t]);e.closePath(),void 0===l.gradient||void 0!==l.color?(e.fillStyle=l.color??(l.up?this._opts.colorUp:this._opts.colorDown),e.fill()):(e.fillStyle=a(l.gradient),e.fill())}l=null};for(let e=0;e<this._points.length;e++){const t=this._points[e];if(null===t.a||null===t.b||!Number.isFinite(t.a)||!Number.isFinite(t.b)){h();continue}const i=t.a>=t.b,n=s(t.index),o=r(t.a),a=r(t.b),c=t.gradient??this._opts.gradient;if(null===l||l.up!==i||l.color===t.color&&(void 0!==t.color||os(l.gradient,c))){if(null!==l&&l.up!==i){const n=this._points[e-1];if(void 0!==n&&null!==n.a&&null!==n.b){const e=n.a-n.b,o=t.a-t.b,a=e===o?0:e/(e-o),d=s(n.index+(t.index-n.index)*a),u=r(n.a+(t.a-n.a)*a);l.xs.push(d),l.top.push(u),l.bot.push(u),h(),l={up:i,color:t.color,gradient:c,xs:[d],top:[u],bot:[u]}}else h()}null===l&&(l={up:i,color:t.color,gradient:c,xs:[],top:[],bot:[]}),l.xs.push(n),l.top.push(o),l.bot.push(a)}else l.xs.push(n),l.top.push(o),l.bot.push(a),h(),l={up:i,color:t.color,gradient:c,xs:[n],top:[o],bot:[a]}}h(),e.restore()}}function ls(e,t,i){const s=[];for(let i=0;i<e.length;i++){const r=s[s.length-1];r&&r[0]===e[i]&&r[1]===t[i]||s.push([e[i],t[i]])}if(i&&s.length>1&&s[0][0]===s[s.length-1][0]&&s[0][1]===s[s.length-1][1]&&s.pop(),s.length<2)return null;const r=[];if(s.length>2){const e=s.length;for(let t=0;t<(i?e:e-1);t++){const n=s[t],o=s[(t+1)%e],a=s[i?(t+e-1)%e:Math.max(0,t-1)],l=s[i?(t+2)%e:Math.min(e-1,t+2)],h=[n[0]+(o[0]-a[0])/6,n[1]+(o[1]-a[1])/6,o[0]-(l[0]-n[0])/6,o[1]-(l[1]-n[1])/6,o[0],o[1]];if(!h.every(Number.isFinite))return null;r.push(h)}}return{points:s,segments:r}}function hs(e,t){return"dashed"===e?[6*t,4*t]:"dotted"===e?[1*t,3*t]:[]}function cs(e,t,i,s,r,n,o,a,l,h){const c=(l?.fontSize??11)*t;if(!Number.isFinite(c)||c<=0)return null;e.font=Xi(l,c,"ui-sans-serif, system-ui, sans-serif"),e.textBaseline="middle",e.textAlign=l?.textAlign??"left";const d=r.split("\n");let u=0;for(const t of d)u=Math.max(u,e.measureText(t).width);const p=5*t,_=3*t,f=1.35*c,m=u+2*p,b=f*d.length+2*_,g="center"===a?i-m/2:"right"===a?i-m:i,v="top"===l?.verticalAlign?s:"bottom"===l?.verticalAlign?s-b:s-b/2;if(h){if(![g,v,m,b].every(Number.isFinite)||g+m<0||g>h.w||v+b<0||v>h.h)return null;e.save(),e.beginPath(),e.rect(0,0,h.w,h.h),e.clip()}e.beginPath(),U(e,g,v,m,b,3*t),e.fillStyle=n,e.fill(),e.fillStyle=o??q(n);const y="center"===l?.textAlign?g+m/2:"right"===l?.textAlign?g+m-p:g+p;for(let t=0;t<d.length;t++)e.fillText(d[t],y,v+_+f*(t+.5));return h&&e.restore(),{x:g,y:v,w:m,h:b}}class ds{constructor(e){Object.defineProperty(this,"_items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_visible",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_priceScale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_hits",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this._priceScale=e}attached(e){this._host=e}detached(){this._host=null,this._hits=[]}zOrder(){return"normal"}autoscaleInfo(){return null}setItems(e){for(const t of e)if("label"===t.kind||"box"===t.kind){if(Ki(t),void 0!==t.verticalAlign&&!["top","middle","bottom"].includes(t.verticalAlign))throw new TypeError("Drawing verticalAlign must be top, middle or bottom");if("box"===t.kind&&void 0!==t.align&&!["left","center","right"].includes(t.align))throw new TypeError("Box align must be left, center or right")}this._items=e,this._hits=[],this._host?.requestUpdate()}setVisible(e){this._visible=e,this._hits=[],this._host?.requestUpdate()}draw(e,t){if(this._hits=[],!this._visible||0===this._items.length)return;const i=t.dpr,s=t.plotWidth*i,r=t.plotHeight*i,n=t.theme.axisText,o=200*i,a=e=>t.timeScale.indexToX(t.dataLayer.timeToIndexFloat(e.time))*i,l=this._priceScale?.(t)??t.priceScale,h=e=>l.priceToY(e.price)*i,c=(e,t,i,n)=>Math.max(e,i)<0||Math.min(e,i)>s||Math.max(t,n)<0||Math.min(t,n)>r;e.save(),e.lineJoin="round",e.lineCap="round";for(const t of this._items){if("label"===t.kind){const l=Yi(t)||void 0!==t.verticalAlign,c=a(t.at),d=h(t.at);if(!l&&(c<-o||c>s+o||d<-o||d>r+o))continue;const u=cs(e,i,c,d,t.text,t.color??n,t.textColor,t.align??"center",t,l?{w:s,h:r}:void 0);u&&this._recordHit(t,u,i,l?{w:s,h:r}:void 0);continue}const l=t.color??n;if(e.lineWidth=Math.max(1,Math.round((t.lineWidth??1)*i)),"polyline"===t.kind){const i=t.points;if(i.length<2)continue;const n=new Array(i.length),o=new Array(i.length);let d=1/0,u=-1/0,p=1/0,_=-1/0,f=!0;for(let e=0;e<i.length;e++){if(!Number.isFinite(i[e].time)||!Number.isFinite(i[e].price)){f=!1;break}const t=a(i[e]),s=h(i[e]);if(!Number.isFinite(t)||!Number.isFinite(s)){f=!1;break}n[e]=t,o[e]=s,t<d&&(d=t),t>u&&(u=t),s<p&&(p=s),s>_&&(_=s)}if(!f)continue;const m="smooth"===t.curve,b=m?ls(n,o,!0===t.closed):null;if(m&&null===b)continue;if(b)for(const e of b.segments)for(let t=0;t<e.length;t+=2)d=Math.min(d,e[t]),u=Math.max(u,e[t]),p=Math.min(p,e[t+1]),_=Math.max(_,e[t+1]);const g=m?e.lineWidth/2:0;if(c(d-g,p-g,u+g,_+g))continue;if(m&&(e.save(),e.beginPath(),e.rect(0,0,s,r),e.clip()),e.beginPath(),e.moveTo(n[0],o[0]),b&&b.segments.length>0)for(const t of b.segments)e.bezierCurveTo(...t);else if(b)e.lineTo(b.points[1][0],b.points[1][1]);else for(let t=1;t<i.length;t++)e.lineTo(n[t],o[t]);!0===t.closed&&e.closePath(),void 0!==t.fillColor&&(e.globalAlpha=t.opacity??.12,e.fillStyle=t.fillColor,e.fill(),e.globalAlpha=1),e.setLineDash([]),e.strokeStyle=l,e.stroke(),m&&e.restore();continue}let d=a(t.from),u=h(t.from),p=a(t.to),_=h(t.to);if("box"===t.kind){const n=Yi(t)||void 0!==t.align||void 0!==t.verticalAlign;if(!n&&c(d,u,p,_))continue;if(n&&![d,u,p,_].every(Number.isFinite))continue;const o=Math.min(d,p),a=Math.min(u,_),h=Math.abs(p-d),f=Math.abs(_-u);if(n&&(!Number.isFinite(h)||!Number.isFinite(f)))continue;if(n&&(e.save(),e.beginPath(),e.rect(0,0,s,r),e.clip()),void 0!==t.fillColor&&(e.globalAlpha=t.opacity??.12,e.fillStyle=t.fillColor,e.fillRect(o,a,h,f),e.globalAlpha=1),e.setLineDash([]),e.strokeStyle=l,e.strokeRect(o,a,h,f),this._recordHit(t,{x:o,y:a,w:h,h:f},i,n?{w:s,h:r}:void 0),void 0!==t.text&&""!==t.text){const c="left"===t.align?o:"right"===t.align?o+h:o+h/2,d="top"===t.verticalAlign?a:"bottom"===t.verticalAlign?a+f:a+f/2;cs(e,i,c,d,t.text,l,t.textColor,t.align??"center",t,n?{w:s,h:r}:void 0)}n&&e.restore();continue}if(!0===t.extendLeft||!0===t.extendRight){const e=p-d;if(0===e)u=0,_=r;else{const i=(_-u)/e,r=d<=p;!0===t.extendLeft&&(r?(u-=i*d,d=0):(_-=i*p,p=0)),!0===t.extendRight&&(r?(_+=i*(s-p),p=s):(u+=i*(s-d),d=s))}}c(d,u,p,_)||(e.setLineDash(hs(t.lineStyle,i)),e.strokeStyle=l,e.beginPath(),e.moveTo(d,u),e.lineTo(p,_),e.stroke())}e.setLineDash([]),this._drawTooltip(e,t,i,s,r,n),e.restore()}_recordHit(e,t,i,s){const r=e.id??e.tooltip;if(void 0===r)return;const n=s?Math.max(0,t.x):t.x,o=s?Math.max(0,t.y):t.y,a=s?Math.min(s.w,t.x+t.w):t.x+t.w,l=s?Math.min(s.h,t.y+t.h):t.y+t.h;s&&(a<=n||l<=o)||this._hits.push({id:r,tooltip:e.tooltip,x:n/i,y:o/i,w:(a-n)/i,h:(l-o)/i,clipped:void 0!==s})}_drawTooltip(e,t,i,s,r,n){const o=t.hoverId;if(null==o)return;const a=this._hits.find(e=>e.id===o&&void 0!==e.tooltip);if(void 0===a?.tooltip)return;const l=8*i,h=11*i*1.35*a.tooltip.split("\n").length+6*i,c=a.y*i-l-h>=0?a.y*i-l-h/2:(a.y+a.h)*i+l+h/2,d=Math.min(Math.max((a.x+a.w/2)*i,0),s);c<-h||c>r+h||cs(e,i,d,c,a.tooltip,n,void 0,"center",void 0,a.clipped?{w:s,h:r}:void 0)}hitTest(e,t){for(let i=this._hits.length-1;i>=0;i--){const s=this._hits[i];if(e>=s.x&&e<=s.x+s.w&&t>=s.y&&t<=s.y+s.h)return{externalId:s.id,zOrder:"normal",distance:0,cursor:void 0===s.tooltip?"pointer":"default"}}return null}}class us{constructor(){Object.defineProperty(this,"_colors",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_anchor",{enumerable:!0,configurable:!0,writable:!0,value:NaN}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_visible",{enumerable:!0,configurable:!0,writable:!0,value:!0})}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"bottom"}autoscaleInfo(){return null}setColors(e,t){this._colors=e,this._anchor=t.length>0?t[0].time:NaN,this._host?.requestUpdate()}setVisible(e){this._visible=e,this._host?.requestUpdate()}draw(e,t){const i=this._colors,s=i.length;if(!this._visible||0===s)return;const r=Math.round(t.dataLayer.timeToIndexFloat(this._anchor)),n=t.timeScale.visibleRange(),o=Math.max(0,Math.floor(n.from-r)),a=Math.min(s-1,Math.ceil(n.to-r)),l=t.dpr,h=t.plotWidth*l,c=t.plotHeight*l,d=e=>Math.min(h,Math.max(0,Math.round(t.timeScale.indexToX(r+e-.5)*l)));e.save();for(let t=o,s=o;t<=a;t++){const r=i[t];if(!(t<a&&i[t+1]===r)){if(r){const i=d(s);e.fillStyle=r,e.fillRect(i,0,d(t+1)-i,c)}s=t+1}}e.restore()}}class ps extends Error{constructor(e){super(`openalgo-charts: unknown interval "${e}". Register it with registerInterval() or use a built-in token (1s, 1m, 5m, 1h, D, W).`),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="UnknownIntervalError",this.code=e}}const _s=/^(\d*)\s*([smhdw])$/i,fs={s:1,m:60,h:3600,d:86400,w:604800};const ms=new Map;function bs(e){return e.trim().toLowerCase()}function gs(e){const t=bs(e.code);if(""===t)throw new Error("openalgo-charts: interval code must not be empty");return function(e){if("interval"===e.mode&&!(e.seconds>0))throw new Error("openalgo-charts: interval bucketing needs seconds > 0");if("ticks"===e.mode&&!(e.count>=1))throw new Error("openalgo-charts: tick bucketing needs count >= 1");if("volume"===e.mode&&!(e.perBar>0))throw new Error("openalgo-charts: volume bucketing needs perBar > 0");if("calendar"===e.mode&&void 0!==e.count&&!(e.count>=1))throw new Error("openalgo-charts: calendar bucketing needs count >= 1")}(e.bucketing),ms.set(t,e),()=>{ms.get(t)===e&&ms.delete(t)}}function vs(e){return ms.delete(bs(e))}function ys(){return Array.from(ms.values())}function ws(e){const t=e.trim(),i=ms.get(t.toLowerCase());if(void 0!==i)return i;const s=function(e){if(/^\d*\s*M$/.test(e))return null;const t=_s.exec(e);return null===t?null:{mode:"interval",seconds:(""===t[1]?1:Number(t[1]))*fs[t[2].toLowerCase()]}}(t);return null===s?null:{code:t,bucketing:s}}function xs(e){return null!==ws(e)}function Ss(e){const t=ws(e);if(null===t)throw new ps(e);return t}function Ps(e){return"interval"===e.mode||"calendar"===e.mode}const Os={month:1,quarter:3,year:12};function ks(e){return Os[e.unit]*Math.max(1,Math.floor(e.count??1))}function Is(e,t){return e.timezone??t??Me}function Ms(e,t,i){const s=Re(t,i),r=ks(e);return Math.floor((12*s.year+(s.month-1))/r)*r}function Ts(e,t){return He(Math.floor(e/12),e%12+1,1,0,0,0,t)}function Cs(e,t,i){if("interval"===e.mode){const i=e.anchorSec??0;return i+Math.floor((t-i)/e.seconds)*e.seconds}if("calendar"!==e.mode)return t;const s=Is(e,i);return Ts(Ms(e,t,s),s)}function js(e,t,i){if("interval"===e.mode)return Cs(e,t)+e.seconds;if("calendar"!==e.mode)return null;const s=Is(e,i);return Ts(Ms(e,t,s)+ks(e),s)}function As(e){const t=ws(e);if(null===t)return null;const i=t.bucketing;if("ticks"===i.mode)return{multiplier:i.count,unit:"tick"};if("volume"===i.mode)return{multiplier:i.perBar,unit:"other"};if("calendar"===i.mode)return{multiplier:ks(i),unit:"M"};const s=i.seconds;return s%604800==0?{multiplier:s/604800,unit:"W"}:s%86400==0?{multiplier:s/86400,unit:"D"}:s%3600==0?{multiplier:s/3600,unit:"h"}:s%60==0?{multiplier:s/60,unit:"m"}:{multiplier:s,unit:"s"}}function Ls(e){const t=ws(e)?.bucketing;return void 0!==t&&"interval"===t.mode?t.seconds:0}function Rs(e){const t=Ls(e);return t>0&&t%60!=0}function zs(e){const t=Ls(e);return t>0&&t<86400}function Fs(e){return 86400===Ls(e)}function Ns(e){return"ticks"===ws(e)?.bucketing.mode}function Es(e){return"string"==typeof e&&("right"===e||"left"===e||""===e||e.startsWith("overlay:"))}function Bs(e,t,i){if(!t||"object"!=typeof t||Array.isArray(t)||![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw new TypeError("Invalid indicator plot price scale map");const s=new Set(e.plots.map(e=>e.key));return Reflect.ownKeys(t).map(e=>{const r=Object.getOwnPropertyDescriptor(t,e);if(!("string"==typeof e&&s.has(e)&&r.enumerable&&"value"in r&&(Es(r.value)||i&&null===r.value)))throw new TypeError("Invalid indicator plot price scale assignment");return[e,r.value]})}function $s(e,t){return void 0===t?{}:Object.fromEntries(Bs(e,t,!1))}function Ds(e,t,i){return(Object.prototype.hasOwnProperty.call(i,e.key)?i[e.key]:void 0)??(!0===e.overlay?null:t)??e.priceScaleId??"right"}function Ws(e,t,i){const s=e.plots.find(e=>!0!==e.overlay);return s?Ds(s,t,i):t??"right"}function qs(e,t,i,s,r){const n=e.plots.find(e=>e.key===t.between[0]),o=e.plots.find(e=>e.key===t.between[1]),a=!0===t.overlay?0:r;if(n&&(!0===n.overlay?0:r)!==a||o&&(!0===o.overlay?0:r)!==a)return null;const l=!0===t.overlay?"right":Ws(e,i,s),h=n?Ds(n,i,s):l;return h===(o?Ds(o,i,s):l)?h:null}function Vs(e,t,i,s){if(void 0!==t&&!Es(t))throw new TypeError("Invalid indicator price scale");const r=$s(e,i);if((void 0!==t||0!==Object.keys(r).length)&&(e.fills??[]).some(i=>null===qs(e,i,t??null,r,s)))throw new RangeError("Indicator fill endpoints must share their pane and price scale")}function Hs(e){const t={};for(const i of Ri(e))t[i.key]=i.default;return t}function Gs(e,t){if(void 0!==t&&t>0)return e.toFixed(f(t));const i=Math.abs(e);return i>=1e9?`${(e/1e9).toFixed(2)}B`:i>=1e6?`${(e/1e6).toFixed(2)}M`:i>=1e3?e.toFixed(0):i>=1?e.toFixed(2):e.toPrecision(3)}let Us=1,Ks=1,Ys=!1;class Xs extends Ci{}class Js{constructor(e,t,i={},s,r,n,o,a){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"indicatorId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"paneIndex",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_d",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ownPane",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_scaleOverride",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_plotScaleOverrides",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_zoned",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_series",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_plotTypes",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_fills",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_levels",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_levelSig",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"_values",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_barCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_firstTime",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastTime",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_removed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_store",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_attachedPrimitives",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_detach",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_lifetime",{enumerable:!0,configurable:!0,writable:!0,value:new AbortController}),Object.defineProperty(this,"_dataStatus",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dataRetry",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dataListeners",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_legend",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_markers",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_markerSeries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_markerLayers",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_table",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_tables",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_draws",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_drawLayers",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_background",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_alertTime",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_alertPolicy",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_calculationEpoch",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_live",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_sourceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sourceRevision",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_sourceHistoryRevision",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_sourceLastTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_visible",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_constructed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_calcFailed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_lifecycleStatus",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_generation",{enumerable:!0,configurable:!0,writable:!0,value:Ks++}),Object.defineProperty(this,"_outputRevision",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_outputHistoryRevision",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_outputSource",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_studySnapshots",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_dependencyUnavailable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_alertNeedsSeed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_outputPending",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_publishedBarColors",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._host=e,this._d=t,this._scaleOverride=o??null,this._plotScaleOverrides=$s(t,a),this.indicatorId=t.id,this.name=t.name,this._alertPolicy=new Ui(t.alerts??[]);let l=r;if(void 0===l)do{l=`${t.id}-${Us++}`}while(n?.has(l));this.id=l,this._settings=this._validatedSettings({...Wi(t),...Hs(t),...ki(i)}),void 0!==s?(this.paneIndex=s,this._ownPane=!1):"onchart"===t.placement?(this.paneIndex=0,this._ownPane=!1):(this.paneIndex=e.nextPaneIndex(),this._ownPane=!0),Vs(t,o,void 0===a?void 0:this._plotScaleOverrides,this.paneIndex);for(const i of t.plots){const t=this._plotType(i);this._plotTypes.set(i.key,t),this._series.set(i.key,e.addIndicatorSeries(t,this._plotPane(i),this._plotStyle(i),this._plotScale(i),i.priceFormat))}for(const i of t.fills??[]){const t=new as({colorUp:this._fillColor(i,!0),colorDown:this._fillColor(i,!1),opacity:i.opacity??.12});this._fills.push(t),e.addIndicatorFill(t,!0===i.overlay?0:this.paneIndex);const s=this._fillScale(i,this._scaleOverride);null!==s&&e.bindIndicatorPrimitiveScale?.(t,s)}this._legend=e.addIndicatorLegend({id:`indicator:${this.id}`,title:t.name,params:this._paramSummary(),color:this._legendColor(),row:e.legendRowsOn(this.paneIndex),paneIndex:this.paneIndex,hasSource:!0===t.hasSource}),this._applyRange();try{this.recompute()}catch(e){throw this.remove(),e}this._constructed=!0,this._attach()}_plotPane(e){return!0===e.overlay?0:this.paneIndex}_plotScale(e,t=this._scaleOverride,i=this._plotScaleOverrides){return Ds(e,t,i)}_localScale(e=this._scaleOverride,t=this._plotScaleOverrides){return Ws(this._d,e,t)}_fillScale(e,t,i=this.paneIndex,s=this._plotScaleOverrides){return qs(this._d,e,t,s,i)}_targetKey({plot:e,overlay:t}){if(void 0===e)return!0===t?null:void 0;if(!0===t||!this._d.plots.some(t=>t.key===e))throw new Error("Indicator output target must name one declared plot or the price pane");return e}_targets(){return[null,...this._d.plots.map(e=>e.key)]}_route(e,t){const i=[],s=new Map(this._targets().map(e=>[e,[]]));for(const r of e){const e=this._targetKey(r);(void 0===e||t?.(e)?i:s.get(e)).push(r)}for(const[e,t]of s)0===t.length&&s.delete(e);return[s.size>0?i:e,s]}_overlayTarget(e){return null===e||this._d.plots.some(t=>t.key===e&&!0===t.overlay)}_drawTarget(e,t=this._scaleOverride,i=this._plotScaleOverrides){const s=this._d.plots.find(t=>t.key===e);return s?[this._plotPane(s),this._plotScale(s,t,i)]:[0,null]}priceScaleId(){return this._scaleOverride}plotPriceScaleId(e){const t=this._d.plots.find(t=>t.key===e);return t?this._plotScale(t):null}plotPriceScaleIds(){return{...this._plotScaleOverrides}}canRelocate(e){return(this._d.fills??[]).every(t=>null!==this._fillScale(t,this._scaleOverride,e))}adoptPriceScale(e){this._scaleOverride=e,this._plotScaleOverrides=this._overlayScaleOverrides()}_overlayScaleOverrides(){return Object.fromEntries(this._d.plots.filter(e=>!0===e.overlay&&Object.prototype.hasOwnProperty.call(this._plotScaleOverrides,e.key)).map(e=>[e.key,this._plotScaleOverrides[e.key]]))}setPriceScale(e){if(this._removed||null!==e&&!Es(e))return!1;const t=this._overlayScaleOverrides();return(e!==this._scaleOverride||Object.keys(t).length!==Object.keys(this._plotScaleOverrides).length)&&this._assignPriceScales(e,t,!1)}setPlotPriceScales(e){if(this._removed)return!1;let t;try{t=Bs(this._d,e,!0)}catch{return!1}const i=new Map(Object.entries(this._plotScaleOverrides));let s=!1;for(const[e,r]of t)null===r?s=i.delete(e)||s:i.get(e)!==r&&(i.set(e,r),s=!0);return s&&this._assignPriceScales(this._scaleOverride,Object.fromEntries(i),!0)}_assignPriceScales(e,t,i){const s=this._d.plots.filter(e=>i||!0!==e.overlay),r=new Map;for(const i of s){const s=this._plotScale(i,e,t);if(s===this._plotScale(i))continue;const n=this._plotPane(i),o=r.get(n)??new Set;o.add(s),r.set(n,o)}const n=s.flatMap(i=>{const s=this._plotScale(i,e,t);if(!r.get(this._plotPane(i))?.has(s))return[];const n=this._series.get(i.key);return n?[{api:n,scaleId:s}]:[]}),o=[];for(let s=0;s<this._fills.length;s++){const r=this._fillScale(this._d.fills[s],e,this.paneIndex,t);if(null===r)return!1;!i&&!0===this._d.fills[s].overlay||r===this._fillScale(this._d.fills[s],this._scaleOverride)||o.push({primitive:this._fills[s],scaleId:r})}const a=this._localScale(e,t);if(a!==this._localScale())for(const e of[...this._levels,this._draws,...this._attachedPrimitives])null!==e&&o.push({primitive:e,scaleId:a});for(const[i,s]of this._drawLayers){const r=this._drawTarget(i,e,t)[1];null!==r&&r!==this._drawTarget(i)[1]&&o.push({primitive:s,scaleId:r})}const l=this._settings,h=this._plotScaleOverrides,c=this._scaleOverride,d=this.paneIndex,u=this._host.setIndicatorRange||this._ownPane?this._d.range?.(this._descriptorSettings())??null:null;if(this._removed||l!==this._settings||h!==this._plotScaleOverrides||c!==this._scaleOverride||d!==this.paneIndex)return!1;const p=this._host.assignIndicatorScale?.(this.id,n,o,()=>{this._scaleOverride=e,this._plotScaleOverrides=t,this._applyRange(u)})??!1;return p&&this.updateLegendValues(this._host.legendIndex?.()),p}_paramSummary(){const e=[];for(const t of this._d.inputs){if("color"===t.type||"boolean"===t.type)continue;const i=this._settings[t.key];if(null!=i&&""!==i)if("source"===t.type&&t.allowStudyOutputs&&"object"==typeof i){const t=i;e.push(`${t.instanceId}/${t.plotKey}`)}else e.push(String(i))}return e.join(" ")}_legendColor(){for(const e of this._d.plots){const t=e.colorKey;if(void 0!==t&&"string"==typeof this._settings[t])return this._settings[t];if("string"==typeof e.style?.color)return e.style.color}}visible(){return this._visible}setVisible(e){if(this._removed||e===this._visible)return;this._visible=e;for(const t of this._d.plots)this._series.get(t.key)?.applyOptions({visible:e&&!1!==t.style?.visible});for(const t of this._fills)t.setVisible(e);const t=this._host.sourceBars();this._applyLevels(t,this._descriptorSettings()),this._syncMarkers(t);try{this._syncTable(t)}catch(e){this._calcFailed=!0,this._publishStatus({state:"error",error:e})}this._syncBarColors(t),this._draws?.setVisible(e);for(const t of this._drawLayers.values())t.setVisible(e);this._background?.setVisible(e),this._legend?.setOptions({hidden:!e}),this._host.emit?.("objects:change",{})}shiftPane(e){this.paneIndex+=e}renderResources(){const e=this._d.plots.flatMap(e=>{const t=this._series.get(e.key);return t?[{api:t,overlay:!0===e.overlay}]:[]}),t=this._fills.map((e,t)=>({primitive:e,overlay:!0===this._d.fills?.[t].overlay}));for(const{table:e,overlay:i}of this._tables.values())t.push({primitive:e,overlay:i});Ys&&(e.length=0,t.length=0);const i=(...i)=>{for(const s of i)null===s||Ys||t.push({primitive:s,overlay:s===this._markers&&(this._markerSeries===this._host.primarySeries?.()||e.some(e=>e.api===this._markerSeries&&e.overlay))})},s=e=>{for(const i of this._targets()){const s=e(i);s&&t.push({primitive:s,overlay:this._overlayTarget(i)})}};return i(this._legend,...this._levels,this._markers),s(e=>this._markerLayers.get(e)?.[0]),i(this._table,this._draws),s(e=>this._drawLayers.get(e)),i(this._background,...this._attachedPrimitives),{series:e,primitives:t}}relocate(e){this._ownPane&&!this._host.setIndicatorRange&&this._host.setPaneRange(this.paneIndex,null),this.paneIndex=e,this._applyRange(),this._syncMarkers(this._host.sourceBars())}refreshBarColors(){Ys||this._syncBarColors(this._host.sourceBars())}republishBarColors(){this._d.barColors&&this._host.setBarColors?.(this._publishedBarColors,this.id)}legend(){return this._legend}updateLegendValues(e){if(null===this._legend)return;const t=this._barCount,i=void 0===e||e<0||e>=t?t-1:e;if(i<0)return void this._legend.setValues([]);const s=[];for(const e of this._d.plots){const t=this._values[e.ohlc?.close??e.key]?.[i-(e.offset??0)];if(null==t||!Number.isFinite(t))continue;const r=this._plotPane(e),n=this._plotColor(e);if(void 0!==n&&H(n))continue;const o=this._host.formatPrice?.(r,t,this._series.get(e.key))??Gs(t,this._host.tickSize?.(r));s.push({text:o,color:n})}this._legend.setValues(s)}_fillColor(e,t){const i=t?e.colorUpKey:e.colorDownKey,s=void 0!==i?this._settings[i]:void 0;if("string"==typeof s)return s;return(t?e.colorUp:e.colorDown)??(t?"#26a69a":"#ef5350")}_syncFills(e){const t=this._d.fills??[],i=this._descriptorSettings();for(let s=0;s<t.length;s++){const r=this._fills[s];if(void 0===r)continue;const n=t[s],o=this._values[n.between[0]],a=this._values[n.between[1]];if(r.setOptions({colorUp:this._fillColor(n,!0),colorDown:this._fillColor(n,!1),opacity:n.opacity??.12,gradient:"function"==typeof n.gradient?n.gradient({bars:e,values:this._values,settings:i}):n.gradient}),void 0===o||void 0===a){r.setPoints([]);continue}const l=this._d.plots.find(e=>e.key===n.between[0])?.offset??0,h=[];for(let e=0;e<this._barCount;e++){const t=o[e]??null,s=a[e]??null,r={index:e,a:t,b:s,values:this._values,settings:i},c=n.colorBy?.(r),d=n.gradientBy?.(r);h.push({index:e+l,a:t,b:s,color:c,gradient:d})}r.setPoints(h)}}_syncMarkers(e){if(this._dependencyUnavailable)return;if(void 0===this._d.markers)return;const t=this._visible?this._d.markers({bars:e,values:this._values,settings:this._descriptorSettings()}):[],i=this._host.primarySeries?.()??void 0,s=("price"===this._d.markerAnchor&&0===this.paneIndex?i:void 0)??this._series.get(this._d.plots[0]?.key??""),r=e=>null===e?i:this._series.get(e),[n,o]=this._route(t,e=>r(e)===s&&!(this.paneIndex&&this._overlayTarget(e)));o.size>0&&new ns(0).setMarkers(t);let a=!1;null!==this._markers&&s!==this._markerSeries&&(this._host.removeIndicatorMarkers(this._markers),this._markers=null),null===this._markers&&n.length>0&&void 0!==s&&(this._markerSeries=s,this._markers=s.createMarkers(()=>{const e=this._host.primarySeries?.();return 0===this.paneIndex&&null!=e&&s.priceScale()===e.priceScale()?this._host.sourceBars():[]})),this._markers?.setMarkers(n);for(const[e,[t,i]]of this._markerLayers)i!==r(e)||this._visible&&!o.has(e)?(this._host.removeIndicatorMarkers(t),this._markerLayers.delete(e)):this._visible||t.setMarkers([]);for(const[e,t]of o){let i=this._markerLayers.get(e);const s=r(e);if(void 0===i&&void 0!==s){const t=this._d.plots.find(t=>t.key===e);a=!0,this._markerLayers.set(e,i=[s.createMarkers(t&&(()=>{const e=this._host.primarySeries?.();return 0===this._plotPane(t)&&null!=e&&s.priceScale()===e.priceScale()?this._host.sourceBars():[]})),s])}i?.[0].setMarkers(t)}this._restack(a)}_syncTable(e){if(this._dependencyUnavailable)return;if(void 0!==this._d.tables)return void this._syncTables(e);if(void 0===this._d.table)return;const t=this._visible?this._d.table({bars:e,values:this._values,settings:this._descriptorSettings()}):null,i=t?.rows??[];if(null===this._table){if(0===i.length)return;this._table=this._host.addIndicatorTable(this.paneIndex)}void 0!==t?.options&&this._table.setOptions(t.options),this._table.setRows(i)}_syncTables(e){if(!this._visible){for(const{table:e}of this._tables.values())e.setRows([]);return}const t=this._d.tables({bars:e,values:this._values,settings:this._descriptorSettings()}),i=new Set;for(const e of t){if("string"!=typeof e.id||""===e.id.trim()||i.has(e.id))throw new Error("Indicator table IDs must be nonempty and unique");i.add(e.id)}for(const[e,{table:t}]of this._tables)i.has(e)||(this._host.removeIndicatorTable(t),this._tables.delete(e));for(const e of t){const t=!0===e.overlay;let i=this._tables.get(e.id);void 0!==i&&i.overlay!==t&&(this._host.removeIndicatorTable(i.table),this._tables.delete(e.id),i=void 0),void 0===i&&(i={table:this._host.addIndicatorTable(t?0:this.paneIndex),overlay:t},this._tables.set(e.id,i)),void 0!==e.options&&i.table.setOptions(e.options),i.table.setRows(e.rows)}}_syncDraws(e){if(void 0===this._d.draws)return;const t=this._d.draws({bars:e,values:this._values,settings:this._descriptorSettings()}),[i,s]=this._route(t);s.size>0&&(new ds).setItems(t);let r=!1;null===this._draws&&i.length>0&&void 0!==this._host.addIndicatorPrimitive&&(this._draws=new ds,this._draws.setVisible(this._visible),this._host.addIndicatorPrimitive(this._draws,this.paneIndex),this._host.bindIndicatorPrimitiveScale?.(this._draws,this._localScale())),this._draws?.setItems(i);for(const[e,t]of this._drawLayers)s.has(e)||(this._host.removeIndicatorPrimitive?.(t),this._drawLayers.delete(e));for(const[e,t]of s){let i=this._drawLayers.get(e);if(void 0===i){if(void 0===this._host.addIndicatorPrimitive)return;const[t,s]=this._drawTarget(e);r=!0,this._drawLayers.set(e,i=new ds(null===s?e=>e.readoutPriceScale:void 0)),i.setVisible(this._visible),this._host.addIndicatorPrimitive(i,t),null!==s&&this._host.bindIndicatorPrimitiveScale?.(i,s)}i.setItems(t)}this._restack(r)}_restack(e){if(e&&this._constructed){Ys=!0;try{this._host.resourcesChanged?.()}finally{Ys=!1}}}_syncBackground(e){if(void 0===this._d.background)return;const t=this._d.background({bars:e,values:this._values,settings:this._descriptorSettings()});if(null===this._background){if(0===t.length||void 0===this._host.addIndicatorPrimitive)return;this._background=new us,this._background.setVisible(this._visible),this._host.addIndicatorPrimitive(this._background,this.paneIndex)}this._background.setColors(t,e)}_syncBarColors(e){if(void 0===this._d.barColors)return;const t=this._visible&&!this._dependencyUnavailable?this._d.barColors({bars:e,values:this._values,settings:this._descriptorSettings()}):null;this._publishedBarColors=t,this._host.setBarColors?.(t,this.id)}_syncAlerts(e,t,i,s,r,n){const o=this._d.alerts,a=e.length;if(void 0===o||!n())return;const l=this._alertTime;a>0&&(this._alertTime=e[a-1].time);let h=a;if(i&&!r)for(;h>0&&e[h-1].time>l;)h--;let c,d=!1;for(let i=h;i<a;i++)for(const s of o){if(void 0!==s.frequency)continue;if(!n())return;const r={bars:e,values:this._values,settings:t,index:i};try{const t=s.when(r);if(!n())return;if(!t)continue;const o="function"==typeof s.message?s.message(r):s.message??s.title;if(!n())return;this._host.emit?.("indicator:alert",{indicatorId:this.indicatorId,instanceId:this.id,alertId:s.id,title:s.title,message:o,time:e[i].time,index:i})}catch(e){if(!n())return;d||(d=!0,c=e)}}if(n()){try{this._alertPolicy.evaluate({bars:e,values:this._values,settings:t,calculation:s,tailOnly:i,refresh:r,current:n},e=>{this._host.emit?.("indicator:alert",{...e,indicatorId:this.indicatorId,instanceId:this.id})})}catch(e){d||(d=!0,c=e)}if(d&&n())throw c}}_calcContext(e,t,i){const s=e.length,r=()=>this._host.now?.()??Date.now()/1e3,n=this._host.interval?.(),o=this._host.timezone?.()??Me,a=s>1?e[s-1].time-e[s-2].time:0;let l=0===s,h=0===s?"empty":"unknown";if(s>0){const t=e[s-1].time;if(void 0===n)l=a<=0||r()>=t+a,h="clock";else{const e=ws(n)?.bucketing,i="interval"===e?.mode?e.seconds>0?t+e.seconds:null:void 0===e?null:js(e,t,o);l=null!==i&&r()>=i,null!==i&&(h="clock")}}s>0&&void 0!==i?.confirmation&&(l="confirmed"===i.confirmation,h=i.confirmationSource??"provider");const c=null===this._sourceRevision||i?.sourceId!==this._sourceId,d=void 0!==i&&i.revision!==this._sourceRevision,u=void 0===i?this._live:!c&&d&&"live"===i.provenance;return{...void 0===i?{}:{execution:{sourceId:i.sourceId,provenance:"replay"===i.provenance?"replay":u?"live":"history",change:c?"initial":d?i.change:"refresh",revision:i.revision,historyRevision:i.historyRevision,confirmationSource:h}},barState:{isNew:void 0===i?t:u&&s>0&&(void 0===this._sourceLastTime||e[s-1].time>this._sourceLastTime),isConfirmed:l,isRealtime:u,lastIndex:s-1},symbol:this._host.symbol?.(),interval:n,timezone:o,now:r,tickSize:this._host.tickSize?.(0)||void 0}}_plotType(e){const t=this._settings[Li(e).type];return"string"==typeof t&&""!==t?t:e.type}_plotColor(e){const t=this._settings[Li(e).color];return"string"==typeof t?t:"string"==typeof e.style?.color?e.style.color:void 0}_plotStyle(e){const t=Li(e),i={...e.style??{},title:e.title,visible:this._visible&&!1!==e.style?.visible},s=this._plotColor(e),r=(n=this._settings[t.opacity],o=100,"number"==typeof n&&Number.isFinite(n)?n:o);var n,o;void 0!==s&&(i.color=r>=100?s:V(s,r/100));const a=this._settings[t.width];"number"==typeof a&&a>0&&(i.lineWidth=a);const l=this._settings[t.lineStyle];return"string"==typeof l&&(i.lineStyle=l),void 0!==e.offset&&0!==e.offset&&(i.barOffset=e.offset),i}_attach(){this._dataRetry=null;const e=this._d.attach?.({dataContext:()=>this._host.dataContext?.(),subscribeDataChanges:e=>this._host.subscribeDataChanges?.(e)??(()=>{}),signal:this._lifetime.signal,setDataStatus:e=>{this._lifecycleStatus=Object.freeze({...e}),this._publishStatus(this._lifecycleStatus)},setDataRetry:e=>{this._removed||(this._dataRetry=e)},requestBars:e=>{const t=this._host.requestBars;return void 0===t?Promise.reject(new Error("openalgo-charts: this chart has no bars provider; call chart.setBarsProvider(...) to serve other instruments")):wi(i=>t.call(this._host,{...e,signal:i}),[e.signal,this._lifetime.signal])},requestSnapshot:e=>wi(t=>{const i=this._host.requestSnapshot;if(!i)throw new Error("Requested snapshots are unsupported by this host");return i.call(this._host,{...e,signal:t})},[e.signal,this._lifetime.signal]),requestState:this._host.requestState?()=>this._host.requestState():void 0,subscribeRequestChanges:this._host.subscribeRequestChanges?e=>this._host.subscribeRequestChanges(e):void 0,settings:()=>this._descriptorSettings(),bars:()=>this._host.sourceBars(),requestRecompute:()=>{this._removed||(this._barCount=0,this._requestRecompute(!0))},store:this._store,symbol:()=>this._host.symbol?.(),interval:()=>this._host.interval?.(),timezone:()=>this._host.timezone?.()??Me,now:()=>this._host.now?.()??Date.now()/1e3,paneIndex:()=>this.paneIndex,addPrimitive:e=>{this._attachedPrimitives.add(e),this._host.addIndicatorPrimitive?.(e,this.paneIndex),this._host.bindIndicatorPrimitiveScale?.(e,this._localScale())},removePrimitive:e=>{this._attachedPrimitives.delete(e),this._host.removeIndicatorPrimitive?.(e)},emit:(e,t)=>{this._host.emit?.(e,t)}});this._detach="function"==typeof e?e:null}_publishStatus(e){if(this._removed)return;const t=this._dataStatus;if(t?.state!==e.state||"error"===e.state&&("error"!==t.state||t.error!==e.error)){this._dataStatus=Object.freeze({...e}),this._outputRevision++,this._outputHistoryRevision++,this._host.indicatorOutputChanged?.(this.id,!0);for(const e of this._dataListeners)e(this._dataStatus);this._host.emit?.("indicator:data-status",{id:this.id,indicatorId:this.indicatorId,status:this._dataStatus})}}dataStatus(){return this._dataStatus}subscribeDataStatus(e){return this._removed?()=>{}:(this._dataListeners.add(e),null!==this._dataStatus&&e(this._dataStatus),()=>{this._dataListeners.delete(e)})}retryData(){this._removed||this._dataRetry?.()}dependencyNode(){return{id:this.id,descriptor:this._d,settings:this._settings}}invalidateStudyOutput(){this._outputPending=!0}_validatedSettings(e){const t=ki(e);ji(this._d.inputs,t),Ti([{id:this.id,descriptor:this._d,settings:t}]),this._host.validateIndicatorSettings?.(this.id,this._d,t);for(const e of this._d.inputs)"source"===e.type&&"object"==typeof t[e.key]&&null!==t[e.key]&&Object.freeze(t[e.key]);return t}studyOutput(e){const t=this._d.plots.find(t=>t.key===e);if(t&&!t.ohlc)return{generation:this._generation,revision:this._outputRevision,historyRevision:this._outputHistoryRevision,source:this._outputSource,values:this._values[e]??[],available:!this._removed&&this._outputRevision>0&&!this._outputPending&&!this._calcFailed&&!this._dependencyUnavailable&&(null===this._lifecycleStatus||"ready"===this._lifecycleStatus.state)}}_studyBindings(e,t){const i=Ti([this.dependencyNode()]).dependencies.get(this.id)??[],s=new Map,r=new Map;let n=this._studySnapshots.size===i.length;for(const{inputKey:o,source:a}of i){const i=this._host.studyOutput?.(a);if(!i?.available||i.values.length!==e.length||void 0!==t&&(i.source?.sourceId!==t.sourceId||i.source.revision!==t.revision||i.source.historyRevision!==t.historyRevision))throw new Xs(`Study input ${o} is unavailable: ${a.instanceId}/${a.plotKey}`);s.set(o,i),r.set(o,Object.freeze(i.values.slice()));const l=this._studySnapshots.get(o);(!l||l.generation!==i.generation||l.historyRevision!==i.historyRevision||l.revision>i.revision)&&(n=!1)}return{snapshots:s,canTail:n,current:()=>i.every(({inputKey:e,source:t})=>{const i=s.get(e),r=this._host.studyOutput?.(t);return!0===r?.available&&i.generation===r.generation&&i.revision===r.revision&&i.historyRevision===r.historyRevision}),resolve:e=>{const t=i.find(t=>t.source.instanceId===e.instanceId&&t.source.plotKey===e.plotKey);if(!t)throw new Ci("Study source must be declared by an opted-in input");return r.get(t.inputKey)}}}_requestRecompute(e){this._host.indicatorRecompute?this._host.indicatorRecompute(this.id,e,()=>this.recompute(e)):this.recompute(e)}_clearUnavailableOutput(e){this._dependencyUnavailable=!0,this._alertNeedsSeed=!0,this._studySnapshots.clear();const t=new Set([...Object.keys(this._values),...this._d.plots.map(e=>e.key)]);this._values=Object.fromEntries([...t].map(t=>[t,new Array(e.length).fill(null)])),this._barCount=0,this._outputHistoryRevision++;for(const e of this._series.values())e.setData([]);for(const e of this._fills)e.setPoints([]);this._markers?.setMarkers([]);for(const[e]of this._markerLayers.values())e.setMarkers([]);this._table?.setRows([]);for(const{table:e}of this._tables.values())e.setRows([]);this._draws?.setItems([]);for(const e of this._drawLayers.values())e.setItems([]);this._background?.setColors([],e);for(const e of this._levels)this._host.removeIndicatorLevel(e);this._levels=[],this._publishedBarColors=null,this._host.setBarColors?.(null,this.id),this.updateLegendValues()}settings(){return ki(this._settings)}_descriptorSettings(){const e=this._host.timezone?.()??Me;if(e===Me)return this._settings;const t=this._zoned;if(null!==t&&t.zone===e&&t.base===this._settings)return t.merged;const i={...this._settings,timezone:e};return this._zoned={zone:e,base:this._settings,merged:i},i}series(e){return this._series.get(e)}values(){return this._host.flushIndicators?.(),this._values}setSettings(e){if(!this._removed){this._settings=this._validatedSettings({...this._settings,...ki(e)}),this._outputPending=!0,this._host.indicatorOutputChanged?.(this.id,!0);for(const e of this._d.plots){const t=this._plotType(e);if(t!==this._plotTypes.get(e.key)){const i=this._series.get(e.key);if(i&&this._host.setIndicatorSeriesType?.(i,t)){i.applyOptions(this._plotStyle(e)),this._plotTypes.set(e.key,t);continue}this._series.get(e.key)?.remove(),this._series.set(e.key,this._host.addIndicatorSeries(t,this._plotPane(e),this._plotStyle(e),this._plotScale(e),e.priceFormat)),this._plotTypes.set(e.key,t);continue}this._series.get(e.key)?.applyOptions(this._plotStyle(e))}this._legend?.setOptions({params:this._paramSummary(),color:this._legendColor()}),this._applyRange(),this._values={},this._barCount=0,this._requestRecompute(!0),this._detach?.(),this._attach(),this._host.resourcesChanged?.(),this._host.emit?.("objects:change",{})}}recompute(e=!1){if(this._removed)return;const t=++this._calculationEpoch,i=this._settings,s=this._host.sourceState?.(),r=this._host.sourceBars();let n;const o=()=>{if(this._removed||t!==this._calculationEpoch||i!==this._settings)return!1;if(n&&!n.current())return!1;const e=this._host.sourceState?.();return void 0===s?void 0===e:void 0!==e&&s.sourceId===e.sourceId&&s.revision===e.revision&&s.historyRevision===e.historyRevision&&s.provenance===e.provenance};try{n=this._studyBindings(r,s),this._recompute(e,r,s,n,o)}catch(e){if(!o())return;if(!(this._constructed||e instanceof Xs))throw e;return e instanceof Xs&&this._clearUnavailableOutput(r),this._calcFailed=!0,this._publishStatus({state:"error",error:e}),void this._host.indicatorOutputChanged?.(this.id,!0)}o()&&(this._calcFailed&&(this._calcFailed=!1,this._publishStatus(this._lifecycleStatus??{state:"ready"})),o()&&this._host.indicatorOutputChanged?.(this.id,e))}_recompute(e,t,i,s,r){const n=t.length,o=this._descriptorSettings();let a=null;const l=this._barCount>0&&n===this._barCount+1&&t[n-2].time===this._lastTime&&t[0].time===this._firstTime,h=n>0&&this._barCount>0&&t[0].time===this._firstTime&&(n===this._barCount&&t[n-1].time===this._lastTime||l)&&(void 0===i||i.sourceId===this._sourceId&&i.revision!==this._sourceRevision&&i.historyRevision===this._sourceHistoryRevision&&"live"===i.provenance);void 0===i&&h&&(this._live=!0);const c=this._calcContext(t,l,i);c.resolveSource=s.resolve;let d=!1;if(h&&s.canTail&&void 0!==this._d.calcTail){const e=this._barCount-1,i=this._d.calcTail(t,o,e,this._values,this._store,c);null!==i&&(a=function(e,t,i,s){const r={};for(const n of Object.keys(t)){const o=e[n],a=t[n];if(void 0===o||void 0===a)return null;if(a.length!==s-i)return null;const l=new Array(s);for(let e=0;e<i;e++)l[e]=o[e]??null;for(let e=i;e<s;e++)l[e]=a[e-i]??null;r[n]=l}return r}(this._values,i,e,n),d=!0)}if(null===a&&(a=this._d.calc(t,o,this._store,c)),r()){this._values=a,this._outputPending=!1,this._dependencyUnavailable=!1,this._studySnapshots=s.snapshots,this._outputRevision++,d||this._outputHistoryRevision++,this._outputSource=i?{...i}:void 0,this._barCount=n,this._firstTime=n>0?t[0].time:0,this._lastTime=n>0?t[n-1].time:0,void 0!==i&&(this._sourceId=i.sourceId,this._sourceRevision=i.revision,this._sourceHistoryRevision=i.historyRevision,this._sourceLastTime=t[n-1]?.time);for(const e of this._d.plots){const i=this._series.get(e.key);if(void 0===i)continue;if(void 0!==e.ohlc){i.setData(this._ohlcPoints(e,e.ohlc,a,t,o));continue}const s=a[e.key];if(void 0===s){i.setData([]);continue}const r=e.colorBy,l=e.colorParts,h=new Array(n);for(let e=0;e<n;e++){const i=s[e],n=null==i?NaN:i,c={time:t[e].time,value:n};if(Number.isFinite(n)){const t=l?.({value:n,index:e,values:a,settings:o})?.body??r?.({value:n,index:e,values:a,settings:o});void 0!==t&&(c.color=t)}h[e]=c}i.setData(h)}if(this._syncFills(t),this._syncMarkers(t),this._syncTable(t),this._syncDraws(t),this._syncBackground(t),this._syncBarColors(t),this._applyLevels(t,o),this._alertNeedsSeed){this._alertNeedsSeed=!1;const e={...c,execution:c.execution?{...c.execution,provenance:"history"}:void 0};this._syncAlerts(t,o,!1,e,!1,r)}else this._syncAlerts(t,o,h,c,e,r);r()&&this.updateLegendValues(this._host.legendIndex?.())}}_ohlcPoints(e,t,i,s,r){const n=s.length,o=[t.open,t.high,t.low,t.close].map(t=>{const s=i[t];if(void 0===s||s.length!==n)throw new Error(`openalgo-charts: ${this.indicatorId} plot "${e.key}" ohlc column "${t}" must be ${n} values`);return s}),a=e.colorBy,l=e.colorParts,h=new Array(n);for(let e=0;e<n;e++){const t=o[3][e],n=null===t?NaN:t,c={time:s[e].time,open:o[0][e]??NaN,high:o[1][e]??NaN,low:o[2][e]??NaN,close:n};if(Number.isFinite(n)){const t=a?.({value:n,index:e,values:i,settings:r});void 0!==t&&(c.color=t);const s=l?.({value:n,index:e,values:i,settings:r});void 0!==s&&(void 0!==s.body&&(c.color=s.body),void 0!==s.wick&&(c.wickColor=s.wick),void 0!==s.border&&(c.borderColor=s.border))}h[e]=c}return h}_applyLevels(e,t){if(void 0===this._d.levels)return;const i={...t,settings:t,bars:e,values:this._values},s=this._visible?this._d.levels(i):[];let r="";for(const e of s)r+=`${e.price}|${e.color??""}|${e.title??""}|${e.dashed??""}|${e.lineWidth??""}|${e.lineStyle??""};`;if(r===this._levelSig)return;this._levelSig=r;for(const e of this._levels)this._host.removeIndicatorLevel(e);this._levels=[];let n=0;for(const e of s){const t=e.lineStyle??(!1===e.dashed?"solid":"dashed");this._levels.push(this._host.addIndicatorLevel({price:e.price,color:e.color??"#8892a6",dashed:"dashed"===t,lineWidth:e.lineWidth??1,lineStyle:t,label:e.title??"",id:`${this.id}:level:${n++}`},this.paneIndex)),this._host.bindIndicatorPrimitiveScale?.(this._levels[this._levels.length-1],this._localScale())}}_applyRange(e){if(this._host.setIndicatorRange){const t=this._d.plots.filter(e=>!0!==e.overlay).flatMap(e=>{const t=this._series.get(e.key);return t?[t]:[]});return void this._host.setIndicatorRange(this.id,this.paneIndex,this._localScale(),void 0===e?this._d.range?.(this._descriptorSettings())??null:e,t)}this._ownPane&&this._host.setPaneRange(this.paneIndex,void 0===e?this._d.range?.(this._descriptorSettings())??null:e)}remove(){if(!this._removed){this._removed=!0,this._lifetime.abort(),this._dataRetry=null,this._dataListeners.clear();try{this._detach?.()}catch{}this._detach=null;for(const e of this._attachedPrimitives)this._host.removeIndicatorPrimitive?.(e);this._attachedPrimitives.clear(),null!==this._legend&&(this._host.removeIndicatorLegend(this._legend),this._legend=null);for(const e of this._levels)this._host.removeIndicatorLevel(e);this._levels=[];for(const e of this._series.values())e.remove();this._series.clear();for(const e of this._fills)this._host.removeIndicatorFill(e);this._fills.length=0,null!==this._markers&&(this._host.removeIndicatorMarkers(this._markers),this._markers=null);for(const[e]of this._markerLayers.values())this._host.removeIndicatorMarkers(e);this._markerLayers.clear(),null!==this._table&&(this._host.removeIndicatorTable(this._table),this._table=null);for(const{table:e}of this._tables.values())this._host.removeIndicatorTable(e);this._tables.clear(),null!==this._draws&&(this._host.removeIndicatorPrimitive?.(this._draws),this._draws=null);for(const e of this._drawLayers.values())this._host.removeIndicatorPrimitive?.(e);this._drawLayers.clear(),null!==this._background&&(this._host.removeIndicatorPrimitive?.(this._background),this._background=null),this._host.setIndicatorRange?.(this.id,this.paneIndex,this._localScale(),null,[]),void 0!==this._d.barColors&&this._host.setBarColors?.(null,this.id),this._ownPane&&!this._host.setIndicatorRange&&this._host.setPaneRange(this.paneIndex,null),this._host.indicatorRemoved?.(this.id,!this._constructed&&this._ownPane?this.paneIndex:void 0)}}}const Zs=["crossing","crossingUp","crossingDown","greaterThan","lessThan","enteringRange","leavingRange"];function Qs(e,t,i,s,r,n=s,o=r){if(!Number.isFinite(i))return!1;if("greaterThan"===e)return i>s;if("lessThan"===e)return i<s;if(void 0===t||!Number.isFinite(t))return!1;const a=t<=n&&i>s,l=t>=n&&i<s;if("crossing"===e)return a||l;if("crossingUp"===e)return a;if("crossingDown"===e)return l;const h=t>=n&&t<=o,c=i>=s&&i<=r;return"enteringRange"===e?!h&&c:h&&!c}function er(e,t,i,s,r,n,o=r,a=n){if(![t,i,s].every(Number.isFinite))return;const l=t<=o&&s>r,h=t>=o&&i<r;switch(e){case"crossing":return l||h?r:void 0;case"crossingUp":return l?r:void 0;case"crossingDown":return h?r:void 0;case"greaterThan":return s>r?s:void 0;case"lessThan":return i<r?i:void 0;case"enteringRange":return t<o&&s>=r?r:t>a&&i<=n?n:void 0;case"leavingRange":if(t<o||t>a)return;return i<r?r:s>n?n:void 0;case"matches":return}}const tr=e=>"string"==typeof e&&e.trim().length>0;function ir(e){if(!tr(e.id))throw new Error("Alert id must be nonempty");const t=e.source;if(!t||!["price","indicator","barCondition","drawing"].includes(t.kind))throw new Error("Unknown alert source");if("barCondition"===t.kind&&!tr(t.id))throw new Error("Invalid bar condition id");if(!("indicator"!==t.kind||tr(t.instanceId)&&tr(t.plotKey)))throw new Error("Invalid indicator source");if(!("drawing"!==t.kind||tr(t.drawingId)&&(void 0===t.level||tr(t.level))&&(void 0===t.input||t.input&&tr(t.input.instanceId)&&tr(t.input.plotKey))))throw new Error("Invalid drawing source");if("barCondition"===t.kind?"matches"!==e.condition:!Zs.includes(e.condition))throw new Error("Invalid source condition");if("price"===t.kind||"indicator"===t.kind){const i="price"===t.kind?t.price:t.value,s="price"===t.kind?t.upperPrice:t.upperValue;if(!Number.isFinite(i)||void 0!==s&&!Number.isFinite(s))throw new Error("Alert bounds must be finite");if(("enteringRange"===e.condition||"leavingRange"===e.condition)&&(void 0===s||s<i))throw new Error("Alert range requires ordered finite bounds")}if("onBarClose"!==e.policy&&"onTouch"!==e.policy)throw new Error("Unknown alert policy");if("once"!==e.repeat&&"everyTime"!==e.repeat)throw new Error("Unknown alert repeat");if(!["armed","triggered","disabled","expired"].includes(e.state))throw new Error("Unknown alert state");if(!Number.isFinite(e.cooldownSeconds)||e.cooldownSeconds<0)throw new Error("Invalid alert cooldown");if("string"!=typeof e.title||void 0!==e.message&&"string"!=typeof e.message)throw new Error("Alert title and message must be text");const i=rr(e.scope);for(const e of["symbol","exchange","interval"])if(void 0!==i[e]&&"string"!=typeof i[e])throw new Error("Invalid alert scope");for(const t of["expiresAt","lastTriggeredAt","lastTriggeredTime","lastClosedTime","lastTouchedTime"])if(void 0!==e[t]&&!Number.isFinite(e[t]))throw new Error(`Invalid alert ${t}`)}function sr(e){return{...e,source:"drawing"===e.source.kind?{...e.source,...e.source.input?{input:{...e.source.input}}:{}}:{...e.source},scope:{...e.scope}}}function rr(e){if(null===e||"object"!=typeof e||Array.isArray(e)||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw new Error("Alert document needs plain JSON records");for(const t of Reflect.ownKeys(e)){const i=Object.getOwnPropertyDescriptor(e,t);if("string"!=typeof t||!("value"in i)||!i.enumerable)throw new Error("Alert document needs JSON data properties")}return e}function nr(e){if(!Array.isArray(e)||e.length>1e5||Reflect.ownKeys(e).length!==e.length+1)throw new Error("Alert document array is not JSON data");return Array.from({length:e.length},(t,i)=>{const s=Object.getOwnPropertyDescriptor(e,String(i));if(!s||!("value"in s))throw new Error("Alert document array needs JSON data values");return s.value})}function or(e){const t=new Set;let i=0,s=0;const r=(e,n)=>{if(++i>1e5||n>32)throw new Error("Alert payload exceeds JSON limits");if(null===e||"boolean"==typeof e)return e;if("string"==typeof e){if(s+=e.length,s>5242880)throw new Error("Alert payload exceeds JSON size limit");return e}if("number"==typeof e&&Number.isFinite(e))return e;if("object"!=typeof e)throw new Error("Alert payload must be finite JSON data");if(t.has(e))throw new Error("Alert payload contains a cycle");let o;if(t.add(e),Array.isArray(e))o=nr(e).map(e=>r(e,n+1));else{const t=rr(e),i={};for(const e of Object.keys(t)){if(s+=e.length,s>5242880)throw new Error("Alert payload exceeds JSON size limit");Object.defineProperty(i,e,{value:r(t[e],n+1),enumerable:!0,writable:!0,configurable:!0})}o=i}return t.delete(e),o};return r(e,0)}function ar(e){if("string"==typeof e){if(e.length>5242880)throw new Error("Alert document exceeds JSON size limit");e=JSON.parse(e)}const t=Array.isArray(e)?{version:1,alerts:e}:rr(e);if(1!==t.version||!Array.isArray(t.alerts)||t.alerts.length>1e4)throw new Error("Unsupported alert document");const i=new Set,s=nr(t.alerts).map(e=>{const t=rr(e),s=rr(t.source);void 0!==s.input&&rr(s.input);const r=(e,i)=>void 0===t[e]?i:t[e],n=rr(r("scope",{})),o={id:t.id,source:{...s},condition:r("condition","barCondition"===s.kind?"matches":"crossing"),policy:r("policy","onBarClose"),repeat:r("repeat","once"),state:r("state","armed"),title:r("title","Chart alert"),cooldownSeconds:r("cooldownSeconds",0),scope:or(Object.fromEntries(Object.entries(n).filter(([,e])=>void 0!==e)))};for(const e of["message","expiresAt","lastTriggeredAt","lastTriggeredTime","lastClosedTime","lastTouchedTime"])void 0!==t[e]&&Object.assign(o,{[e]:t[e]});if(ir(o),i.has(o.id))throw new Error(`Duplicate alert id: ${o.id}`);return i.add(o.id),o.source=or(Object.fromEntries(Object.entries(o.source).filter(([,e])=>void 0!==e))),void 0!==t.payload&&(o.payload=or(t.payload)),o});return{version:1,alerts:s}}const lr=1;function hr(e){if(!e||"object"!=typeof e||Array.isArray(e)||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw new Error("Invalid pane scale object");if(Object.values(Object.getOwnPropertyDescriptors(e)).some(e=>!("value"in e)))throw new Error("Pane scale accessors are not supported");return e}function cr(e,t,i=-Number.MAX_VALUE,s=Number.MAX_VALUE){if("number"!=typeof e||!Number.isFinite(e)||e<i||e>s)throw new Error(`Invalid ${t}`);return e}function dr(e){const t=hr(e),i=cr(t.min,"scale range minimum");return{min:i,max:cr(t.max,"scale range maximum",i)}}function ur(e,t){const i=hr(e),s=(e,s)=>void 0===i[e]&&t?s:i[e],r=s("mode","linear"),n=s("inverted",!1),o=s("autoScale",!0);if(!["linear","logarithmic","percentage","indexed-to-100"].includes(r)||"boolean"!=typeof n||"boolean"!=typeof o)throw new Error("Invalid price scale mode or flags");const a={marginTop:cr(s("marginTop",.1),"top scale margin"),marginBottom:cr(s("marginBottom",.1),"bottom scale margin"),minMove:cr(s("minMove",0),"scale tick",0),mode:r,inverted:n,autoScale:o};if(void 0!==i.minPrecision&&(a.minPrecision=cr(i.minPrecision,"scale precision",0,100),!Number.isInteger(a.minPrecision)))throw new Error("Scale precision must be an integer");if(void 0!==i.range&&(a.range=dr(i.range)),void 0!==i.fixedRange&&(a.fixedRange=null===i.fixedRange?null:dr(i.fixedRange)),void 0!==i.indicatorRange){const e=hr(i.indicatorRange);if("string"!=typeof e.instanceId||!e.instanceId.trim()||"boolean"!=typeof e.manual||!a.fixedRange)throw new Error("Invalid indicator range ownership");a.indicatorRange={instanceId:e.instanceId,manual:e.manual}}if(void 0!==i.ratioLock){const e=hr(i.ratioLock);if(o||!a.range)throw new Error("A scale ratio lock requires a manual range");a.ratioLock={barSpacing:cr(e.barSpacing,"ratio bar spacing",Number.MIN_VALUE),height:cr(e.height,"ratio height",Number.MIN_VALUE)}}if(void 0!==i.placement){const e=hr(i.placement);if(!Object.prototype.hasOwnProperty.call(e,"side")||!Object.prototype.hasOwnProperty.call(e,"order")||!["left","right","hidden"].includes(e.side)||"number"!=typeof e.order||!Number.isSafeInteger(e.order)||e.order<0)throw new Error("Invalid price axis placement side or order");a.placement={side:e.side,order:e.order}}return a}function pr(e,t=!1){const i=hr(e),s={weight:cr(i.weight,"pane weight",Number.MIN_VALUE),priceScale:ur(i.priceScale,t)};if(void 0!==i.scales){const e=hr(i.scales);s.scales={};for(const[t,i]of Object.entries(e)){if("left"!==t&&""!==t&&!t.startsWith("overlay:"))throw new Error("Invalid secondary price scale id");s.scales[t]=ur(i,!1)}}if(void 0!==i.collapsed){if("boolean"!=typeof i.collapsed)throw new Error("Invalid pane collapse flag");s.collapsed=i.collapsed}return s}function _r(e){return!("open"in e)&&!("value"in e)}function fr(e){if("open"in e)return e;if("value"in e){const t=e.value,i={time:e.time,open:t,high:t,low:t,close:t};return void 0!==e.color&&(i.color=e.color),i}return{time:e.time,open:NaN,high:NaN,low:NaN,close:NaN}}const mr={friction:.0055,minSpeed:.02,triggerSpeed:.08};class br{constructor(e,t={}){Object.defineProperty(this,"_v0",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_k",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_minSpeed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_duration",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const i={...mr,...t};this._v0=e,this._k=i.friction,this._minSpeed=i.minSpeed;const s=Math.abs(this._v0)>0?this._minSpeed/Math.abs(this._v0):1;this._duration=s>=1?0:-Math.log(s)/this._k}static shouldAnimate(e,t={}){const i=t.triggerSpeed??mr.triggerSpeed;return Math.abs(e)>=i}distanceAt(e){const t=Math.min(Math.max(0,e),this._duration);return this._v0/this._k*(1-Math.exp(-this._k*t))}get durationMs(){return this._duration}finished(e){return e>=this._duration}}const gr={tau:55,stopFraction:.995,minLogStep:.02};class vr{constructor(e,t={}){Object.defineProperty(this,"_base",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_target",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_epoch",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_tau",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_duration",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const i={...gr,...t};this._target=e,this._tau=i.tau,this._duration=-Math.log(1-i.stopFraction)*i.tau}static leadFraction(e={}){const t=e.tau??gr.tau;return 1-Math.exp(-16.666666666666668/t)}static shouldAnimate(e,t={}){const i=t.minLogStep??gr.minLogStep;return Math.abs(e)>=i}add(e,t,i){this._base=t,this._target+=e,this._epoch=i}appliedAt(e){const t=e-this._epoch;return t<=0?this._base:t>=this._duration?this._target:this._base+(this._target-this._base)*(1-Math.exp(-t/this._tau))}get totalLogFactor(){return this._target}get durationMs(){return this._duration}finished(e){return e-this._epoch>=this._duration}}function yr(e){return Math.max(-2,Math.min(2,-e*Math.log(1.1)/100))}const wr=["Mod","Ctrl","Meta","Alt","Shift"],xr=new Set(wr),Sr=new Set(["Shift","Control","Alt","Meta","OS","ShiftLeft","ShiftRight","ControlLeft","ControlRight","AltLeft","AltRight","MetaLeft","MetaRight","OSLeft","OSRight"]);function Pr(){return"undefined"!=typeof navigator&&/mac|iphone|ipad/i.test(navigator.platform||navigator.userAgent||"")}function Or(e){const t=e.split("+").map(e=>e.trim()).filter(e=>e.length>0);if(0===t.length)return null;const i=t[t.length-1];if(!/^[A-Za-z0-9]+$/.test(i)||xr.has(i))return null;const s=[];for(const e of t.slice(0,-1)){if(!xr.has(e))return null;s.includes(e)||s.push(e)}return s.sort((e,t)=>wr.indexOf(e)-wr.indexOf(t)),{mods:s,key:i}}function kr(e){const t=Or(e);return null===t?"":[...t.mods,t.key].join("+")}function Ir(e){return""!==kr(e)}const Mr={ArrowLeft:"←",ArrowRight:"→",ArrowUp:"↑",ArrowDown:"↓",Equal:"=",Minus:"-",NumpadAdd:"+",NumpadSubtract:"-",Escape:"Esc",Space:"Space"};function Tr(e,t=Pr()){const i=Or(e);if(null===i)return"";const s=t?{Mod:"⌘",Ctrl:"⌃",Meta:"⌘",Alt:"⌥",Shift:"⇧"}:{Mod:"Ctrl",Ctrl:"Ctrl",Meta:"Win",Alt:"Alt",Shift:"Shift"};var r;return[...i.mods.map(e=>s[e]),(r=i.key,void 0!==Mr[r]?Mr[r]:/^Key[A-Z]$/.test(r)?r.slice(3):/^Digit[0-9]$/.test(r)?r.slice(5):r)].join(t?" ":" + ")}function Cr(e,t=Pr()){const i=e.code??e.key??"";if(""===i||Sr.has(i))return"";const s=[];return(t?e.metaKey:e.ctrlKey)&&s.push("Mod"),t&&e.ctrlKey&&s.push("Ctrl"),!t&&e.metaKey&&s.push("Meta"),e.altKey&&s.push("Alt"),e.shiftKey&&s.push("Shift"),kr([...s,i].join("+"))}const jr=new Set(["Mod+KeyW","Mod+KeyT","Mod+KeyN","Mod+KeyQ","Mod+KeyR","Mod+KeyL","Mod+Shift+KeyT","Mod+Shift+KeyN","Mod+Shift+KeyW"]);function Ar(e){return jr.has(kr(e))}const Lr=[{command:"panLeft",label:"Pan left",combos:["ArrowLeft"]},{command:"panRight",label:"Pan right",combos:["ArrowRight"]},{command:"panLeftFast",label:"Pan left (fast)",combos:["Mod+ArrowLeft"]},{command:"panRightFast",label:"Pan right (fast)",combos:["Mod+ArrowRight"]},{command:"panUp",label:"Pan up",combos:["ArrowUp"]},{command:"panDown",label:"Pan down",combos:["ArrowDown"]},{command:"zoomIn",label:"Zoom in",combos:["Equal","Shift+Equal","NumpadAdd"]},{command:"zoomOut",label:"Zoom out",combos:["Minus","NumpadSubtract"]},{command:"resetScale",label:"Reset scale",combos:["Home","Digit0"]},{command:"fitContent",label:"Fit content",combos:["Alt+KeyF"]},{command:"screenshot",label:"Screenshot (PNG)",combos:["Alt+Shift+KeyS"]},{command:"toggleGridVert",label:"Toggle vertical grid",combos:["Alt+KeyV"]},{command:"toggleGridHorz",label:"Toggle horizontal grid",combos:["Alt+KeyH"]},{command:"toggleCrosshairMagnet",label:"Toggle crosshair magnet",combos:["Alt+KeyM"]}],Rr={panLeftFast:["Alt+ArrowLeft"],panRightFast:["Alt+ArrowRight"],screenshot:["Mod+Shift+KeyS"]},zr=new Set(Lr.map(e=>e.command)),Fr=e=>Array.isArray(e)?e:[e];class Nr{constructor(e={}){Object.defineProperty(this,"scope",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isMac",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_persist",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_storageKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_preset",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_overrides",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_disabled",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_custom",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_entries",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_reverse",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),this.scope=e.scope??"hover",this._isMac=e.isMac??Pr(),this._persist=e.persist??!1,this._storageKey=e.storageKey??"openalgo-charts:shortcuts",this._preset=e.preset??"default";const t=e=>{for(const[t,i]of Object.entries(e??{})){if(null===i){this._disabled.add(t);continue}const e=Fr(i).map(kr).filter(e=>""!==e&&!Ar(e));this._overrides[t]=e}};t(e.overrides);for(const t of e.disabledCommands??[])this._disabled.add(t);for(const t of e.customShortcuts??[])this._custom.set(t.command,t);const i=this._load();if(null!==i){void 0!==i.preset&&(this._preset=i.preset),t(i.overrides);for(const e of i.disabled??[])this._disabled.add(e)}this._rebuild()}_presetCombos(e){return"alt"===this._preset?Rr[e]:void 0}_effectiveCombos(e,t){return this._disabled.has(e)?[]:void 0!==this._overrides[e]?this._overrides[e]:this._presetCombos(e)??t}_rebuild(){this._entries=new Map;for(const e of Lr)this._entries.set(e.command,{command:e.command,label:e.label,combos:this._effectiveCombos(e.command,e.combos)});for(const e of this._custom.values())this._entries.set(e.command,{command:e.command,label:e.label??e.command,combos:this._effectiveCombos(e.command,Fr(e.combos).map(kr).filter(e=>""!==e))});this._reverse=new Map;for(const e of this._entries.values())for(const t of e.combos)this._reverse.has(t)||this._reverse.set(t,e.command)}resolve(e){const t=Cr(e,this._isMac);return""===t?null:this._reverse.get(t)??null}handleKey(e){return this._reverse.get(kr(e))??null}runCustom(e){const t=this._custom.get(e);return void 0!==t&&(t.onTrigger(),this.emitTrigger(e),!0)}emitTrigger(e,t=""){const i={command:e,combo:t,isCustom:this._custom.has(e)};for(const e of this._listeners)e(i)}on(e){return this._listeners.add(e),()=>this._listeners.delete(e)}setBinding(e,t){const i=Fr(t).map(kr).filter(e=>""!==e&&!Ar(e));return 0!==i.length&&(this._overrides[e]=i,this._disabled.delete(e),this._after(),!0)}disable(e){this._disabled.add(e),delete this._overrides[e],this._after()}resetBinding(e){delete this._overrides[e],this._disabled.delete(e),this._after()}resetAll(){this._overrides={},this._disabled.clear(),this._after()}setPreset(e){this._preset=e,this._after()}addCustom(e){this._custom.set(e.command,e),this._after()}list(){return[...this._entries.values()].map(e=>({command:e.command,label:e.label,combos:e.combos,isCustom:this._custom.has(e.command),isDisabled:this._disabled.has(e.command)}))}state(){return{preset:this._preset,overrides:this._overrides,disabled:[...this._disabled]}}_after(){this._rebuild(),this._save()}_save(){if(this._persist&&"undefined"!=typeof localStorage)try{localStorage.setItem(this._storageKey,JSON.stringify(this.state()))}catch{}}_load(){if(!this._persist||"undefined"==typeof localStorage)return null;try{const e=localStorage.getItem(this._storageKey);return null===e?null:JSON.parse(e)}catch{return null}}static shouldIgnore(e){const t=e;if(null==t)return!1;if(!0===t.isContentEditable)return!0;const i=(t.tagName??"").toUpperCase();return"INPUT"===i||"TEXTAREA"===i||"SELECT"===i}}class Er{constructor(e){Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_ghostPrice",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_group",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._opts=e}attached(e){this._host=e}detached(){this._host=null}get price(){return this._opts.price}setPrice(e){this._opts.price=e,this._host?.requestUpdate()}setLeftLabel(e){this._opts.leftLabel=e,this._host?.requestUpdate()}setOptions(e){this._opts={...this._opts,...e},this._host?.requestUpdate()}setDragGhost(e){this._ghostPrice=e,this._host?.requestUpdate()}options(){return this._opts}zOrder(){return"normal"}autoscaleInfo(){return{min:this._opts.price,max:this._opts.price}}draw(e,t){this._group=null;const i=Math.round(t.priceScale.priceToY(this._opts.price)*t.dpr)+.5,s="left"===t.priceAxisSide?i-.5:i;if(!Number.isFinite(i)||s<0||s>t.plotHeight*t.dpr)return;const r=t.dpr,n=this._opts.lineWidth??1,o=Math.round(t.plotWidth*r),a=Math.max(0,Math.min(1,this._opts.extentFromRight??1)),l=Math.round(t.plotWidth*(1-a)*r),h=this._opts.color,c=void 0!==this._opts.cursor||!0===this._opts.closeButton,d=t.dragId===this._opts.id,u=c&&!d&&(t.hoverId===this._opts.id||t.hoverId===`${this._opts.id}::close`),p=t.hoverId===`${this._opts.id}::close`;if(e.save(),null!==this._ghostPrice&&d){const i=Math.round(t.priceScale.priceToY(this._ghostPrice)*r)+.5;i>=0&&i<=t.plotHeight*r&&(e.strokeStyle=V(h,.35),e.lineWidth=Math.max(1,Math.round(r)),e.setLineDash([2*r,3*r]),e.beginPath(),e.moveTo(l,i),e.lineTo(o,i),e.stroke(),e.setLineDash([]))}d&&(e.strokeStyle=V(h,.18),e.lineWidth=Math.max(5*r,Math.round(n*r)+4*r),e.beginPath(),e.moveTo(l,i),e.lineTo(o,i),e.stroke()),e.strokeStyle=u||d?G(h,.1):h;const _=Math.max(1,Math.round(n*r));e.lineWidth=u||d?_+Math.round(r):_,e.setLineDash(M(this._opts.lineStyle??(!0===this._opts.dashed?"dashed":"solid"),r)),e.beginPath(),e.moveTo(l,i),e.lineTo(o,i),e.stroke(),e.setLineDash([]),e.font=`500 ${11*r}px system-ui, sans-serif`,e.textBaseline="middle",e.textAlign="left";const f=18*r,m=6*r,b=3*r,g=d||u?G(h,.12):h,v=this._opts.label??t.priceScale.format(this._opts.price);if("hidden"!==t.priceAxisSide&&t.priceAxisWidth>0){const s="left"===t.priceAxisSide;if(s||void 0!==t.priceAxisOffset){const n=t.priceAxisOffset??0,o=Math.round(n*r),a=Math.round((n+(s?-t.priceAxisWidth:t.priceAxisWidth))*r),l=(void 0===t.priceAxisOffset?Math.round(t.priceAxisWidth*r):Math.abs(a-o))-1;if(Number.isFinite(o)&&Number.isFinite(a)&&l>0&&t.plotHeight*r>=f){e.save(),void 0!==t.priceAxisOffset&&(e.beginPath(),e.rect(Math.min(o,a),0,l+1,t.plotHeight*r),e.clip());const n=Math.min(m,l/4),c=e.measureText(v).width,d=Math.min(l,c+2*n),u=s?o-1-d:o+1,p=Math.max(f/2,Math.min(t.plotHeight*r-f/2,i));e.fillStyle=g,e.fillRect(u,p-f/2,d,f),e.fillStyle=q(h),e.font=`500 ${11*r*(c>0?Math.min(1,(d-2*n)/c):1)}px system-ui, sans-serif`,e.fillText(v,u+n,p),e.restore(),e.font=`500 ${11*r}px system-ui, sans-serif`}}else e.fillStyle=g,e.fillRect(o+1,i-f/2,e.measureText(v).width+2*m,f),e.fillStyle=q(h),e.fillText(v,o+1+m,i)}if(void 0!==this._opts.badge||void 0!==this._opts.qty||void 0!==this._opts.leftLabel&&""!==this._opts.leftLabel||!0===this._opts.closeButton){const s="transparent"===t.theme.background,n=s?V(h,.14):t.theme.background,o=s?t.theme.axisText:q(t.theme.background),c=V(t.theme.axisText,u||d?.75:.5),_=[];void 0!==this._opts.badge&&_.push({text:this._opts.badge,fill:d?G(h,.2):u?G(h,.12):h,textColor:q(h),border:G(h,-.25)}),void 0!==this._opts.qty&&_.push({text:String(this._opts.qty),fill:n,textColor:o,border:c}),void 0!==this._opts.leftLabel&&""!==this._opts.leftLabel&&_.push({text:this._opts.leftLabel,fill:n,textColor:o,border:c}),!0===this._opts.closeButton&&_.push({close:!0,fill:p?h:n,textColor:p?q(h):o,border:p?h:c}),this._group=function(e,t,i,s,r){const{height:n,padX:o,radius:a,gap:l,dpr:h}=r,c=s.map(t=>!0===t.close?20*h:e.measureText(t.text??"").width+2*o),d=c.reduce((e,t)=>e+t,0)+l*Math.max(0,s.length-1);void 0!==r.backplate&&(e.beginPath(),U(e,t,i-n/2,d,n,a),e.fillStyle=r.backplate,e.fill());let u=Number.POSITIVE_INFINITY,p=t;for(let t=0;t<s.length;t++){const r=s[t],d=c[t];if(e.beginPath(),U(e,p,i-n/2,d,n,a),e.fillStyle=r.fill,e.fill(),void 0!==r.border&&(e.strokeStyle=r.border,e.lineWidth=Math.max(1,Math.round(h)),e.stroke()),!0===r.close){u=p,e.strokeStyle=r.textColor,e.lineWidth=Math.max(1,Math.round(1.4*h));const t=p+d/2,s=3.5*h;e.beginPath(),e.moveTo(t-s,i-s),e.lineTo(t+s,i+s),e.moveTo(t+s,i-s),e.lineTo(t-s,i+s),e.stroke()}else e.fillStyle=r.textColor,e.textAlign="left",e.textBaseline="middle",e.fillText(r.text??"",p+o,i);p+=d+l}return{x0:t/h,x1:(p-l)/h,closeX0:u/h}}(e,l+(1===a?6*r:0),i,_,{height:f,padX:m,radius:b,gap:2*r,backplate:s?void 0:t.theme.background,dpr:r})}e.restore()}hitTest(e,t,i){if(e<0||e>i.plotWidth)return null;const s=i.priceScale.priceToY(this._opts.price),r=Math.abs(t-s),n=this._group;return null!==n&&r<=10&&e>=n.x0&&e<=n.x1?this._opts.closeButton&&e>=n.closeX0?{externalId:`${this._opts.id}::close`,zOrder:"normal",distance:r,cursor:"pointer"}:{externalId:this._opts.id,zOrder:"normal",distance:r,cursor:this._opts.cursor}:r>4?null:{externalId:this._opts.id,zOrder:"normal",distance:r,cursor:this._opts.cursor}}}const Br={long:"#2f6df6",short:"#ef5350",order:"#3b82f6",tp:"#26a69a",sl:"#ef5350",buy:"#26a69a",sell:"#ef5350"},$r="::close";function Dr(e,t){const i=e.length;if(0===i)return;let s=0,r=i-1;for(;s<r;){const i=s+r+1>>1,n=e.indexToTime(i);void 0!==n&&n<=t?s=i:r=i-1}const n=e.indexToTime(s);if(void 0!==n){if(s+1<i){const i=e.indexToTime(s+1);if(void 0!==i&&Math.abs(i-t)<Math.abs(n-t))return s+1}return s}}function Wr(e,t,i,s,r,n){const o=5*n;e.fillStyle=r,e.beginPath(),"buy"===s?(e.moveTo(t,i-1.5*o),e.lineTo(t-o,i),e.lineTo(t+o,i)):(e.moveTo(t,i+1.5*o),e.lineTo(t-o,i),e.lineTo(t+o,i)),e.closePath(),e.fill()}function qr(e,t,i,s,r,n){const o=9*n;e.fillStyle=s,e.beginPath(),e.arc(t,i,o,0,2*Math.PI),e.fill(),""!==r&&(e.fillStyle=q(s),e.font=`500 ${9*n}px system-ui, sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillText(r,t,i+.5*n))}function Vr(e,t,i,s,r,n){const o=String(s);e.font=`500 ${9*n}px system-ui, sans-serif`;const a=e.measureText(o).width+10*n,l=15*n;e.fillStyle=r,e.beginPath(),U(e,Math.round(t-a/2),Math.round(i-l/2),Math.round(a),Math.round(l),3*n),e.fill(),e.fillStyle=q(r),e.textAlign="center",e.textBaseline="middle",e.fillText(o,t,i+.5*n)}class Hr{constructor(e){Object.defineProperty(this,"_trades",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_colors",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._colors=e}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"top"}autoscaleInfo(){return null}setTrades(e){this._trades=e,this._host?.requestUpdate()}setColors(e){this._colors=e,this._host?.requestUpdate()}draw(e,t){if(0===this._trades.length)return;const i=t.dpr,s=new Map;e.save();for(const r of this._trades){const n=Dr(t.dataLayer,Math.floor(r.timestamp/1e3));if(void 0===n)continue;const o=Math.round(t.timeScale.indexToX(n)*i),a=r.color??("buy"===r.side?this._colors.buy:this._colors.sell),l=r.variant??"chevron";if("count"===l){const e=`${n}:${r.side}`;let t=s.get(e);void 0===t&&(t={index:n,sumPS:0,sumS:0,n:0,color:a},s.set(e,t)),t.sumPS+=r.price*r.size,t.sumS+=r.size,t.n+=1;continue}const h=Math.round(t.priceScale.priceToY(r.price)*i);"bubble"===l?qr(e,o,h,a,r.label??("buy"===r.side?"B":"S"),i):Wr(e,o,h,r.side,a,i)}for(const r of s.values()){const s=r.sumS>0?r.sumPS/r.sumS:0;Vr(e,Math.round(t.timeScale.indexToX(r.index)*i),Math.round(t.priceScale.priceToY(s)*i),r.n,r.color,i)}e.restore()}}class Gr{constructor(e){Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_positions",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_orders",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_trades",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_dragPrev",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_colors",{enumerable:!0,configurable:!0,writable:!0,value:{...Br}}),Object.defineProperty(this,"_markers",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._host=e,e.subscribeClick(e=>this._onClick(e)),e.subscribeDrag((e,t)=>this._onDrag(e,t),(e,t)=>this._onDragEnd(e,t))}on(e,t){let i=this._listeners.get(e);return void 0===i&&(i=new Set,this._listeners.set(e,i)),i.add(t),()=>{this._listeners.get(e)?.delete(t)}}off(e,t){this._listeners.get(e)?.delete(t)}_emit(e,t){const i=this._listeners.get(e);if(void 0!==i)for(const e of i)e(t);this._host.emit?.(e,t)}setSettings(e){void 0!==e.longColor&&(this._colors.long=e.longColor),void 0!==e.shortColor&&(this._colors.short=e.shortColor),void 0!==e.orderColor&&(this._colors.order=e.orderColor),void 0!==e.tpColor&&(this._colors.tp=e.tpColor),void 0!==e.slColor&&(this._colors.sl=e.slColor),void 0!==e.buyColor&&(this._colors.buy=e.buyColor),void 0!==e.sellColor&&(this._colors.sell=e.sellColor),this.setPositions(this.getPositions()),this.setOrders(this.getOrders()),this._markers?.setColors(this._colors)}getSettings(){return{...this._colors}}setPositions(e){this._sync(this._positions,e,"pos")}setOrders(e){this._sync(this._orders,e,"ord")}setTrades(e){this._trades.clear();for(const t of e)this._trades.set(t.id,t);this._renderTrades()}addTrade(e){this._trades.set(e.id,e),this._renderTrades()}upsertOrder(e){const t=this.getOrders().filter(t=>t.id!==e.id);t.push(e),this.setOrders(t)}removeOrder(e){const t=this.getOrders().filter(t=>t.id!==e&&t.parentId!==e);this.setOrders(t)}syncState(e){void 0!==e.positions&&this.setPositions(e.positions),void 0!==e.orders&&this.setOrders(e.orders),void 0!==e.trades&&this.setTrades(e.trades)}updatePositionPnl(e,t,i,s){const r=this._positions.get(e);void 0!==r&&(void 0!==i&&(r.entity.pnlText=i),void 0!==s&&(r.entity.pnlPercent=s),r.line.setLeftLabel(this._positionPill(r.entity)))}getPositions(){return[...this._positions.values()].map(e=>e.entity)}getOrders(){return[...this._orders.values()].map(e=>e.entity)}getTrades(){return[...this._trades.values()]}clear(){for(const e of this._positions.values())this._host.removePrimitive(e.line);for(const e of this._orders.values())this._host.removePrimitive(e.line);this._positions.clear(),this._orders.clear(),this._trades.clear(),null!==this._markers&&(this._host.removePrimitive(this._markers),this._markers=null)}_renderTrades(){null===this._markers&&(this._markers=new Hr(this._colors),this._host.addPrimitive(this._markers)),this._markers.setTrades(this.getTrades())}_sync(e,t,i){const s=new Set;for(const r of t){s.add(r.id);const t="pos"===i?this._positionOpts(r):this._orderOpts(r),n=this._sig(t),o=e.get(r.id);if(void 0!==o&&o.sig===n)o.entity=r,o.line.setPrice(t.price),void 0!==t.leftLabel&&o.line.setLeftLabel(t.leftLabel);else{void 0!==o&&this._host.removePrimitive(o.line);const i=new Er(t);this._host.addPrimitive(i),e.set(r.id,{entity:r,line:i,sig:n})}}for(const[t,i]of e)s.has(t)||(this._host.removePrimitive(i.line),e.delete(t))}_sig(e){return`${e.color}|${e.dashed}|${!0===e.closeButton}|${e.cursor??""}|${void 0!==e.leftLabel}|${e.badge??""}|${e.qty??""}`}_positionPill(e){return void 0===e.pnlText?"":`${e.pnlText}${void 0!==e.pnlPercent?` (${e.pnlPercent})`:""}`}_positionOpts(e){const t="line-only"===e.variant;return{price:e.entryPrice,color:e.color??("long"===e.side?this._colors.long:this._colors.short),lineWidth:2,dashed:!1,id:`pos:${e.id}`,badge:t?void 0:e.side.toUpperCase(),qty:t?void 0:e.size,leftLabel:t?void 0:this._positionPill(e),closeButton:!t&&!0!==e.readOnly,extentFromRight:.3}}_orderOpts(e){const t="line-only"===e.variant,i=!t&&(e.draggable??!0!==e.readOnly),s=e.color??("tp"===e.bracketRole?this._colors.tp:"sl"===e.bracketRole?this._colors.sl:this._colors.order);return{price:e.price,color:s,lineWidth:e.lineWidth??1,dashed:"solid"!==(e.lineStyle??"solid"),id:`ord:${e.id}`,badge:t?void 0:(e.bracketRole??e.side).toUpperCase(),qty:t?void 0:e.size,leftLabel:t||void 0!==e.bracketRole?void 0:e.type.replace("_"," ").toUpperCase(),closeButton:!t&&!0!==e.readOnly,extentFromRight:.3,cursor:i?"ns-resize":void 0}}_onClick(e){if(e.endsWith($r)){const t=e.slice(0,-7);if(t.startsWith("ord:")){const e=t.slice(4);this._orders.has(e)&&this._emit("trading:order_cancel",{orderId:e})}else if(t.startsWith("pos:")){const e=t.slice(4);this._positions.has(e)&&this._emit("trading:position_close",{positionId:e})}return}if(e.startsWith("ord:")){const t=this._orders.get(e.slice(4));void 0!==t&&this._emit("trading:order_click",{order:t.entity})}else if(e.startsWith("pos:")){const t=this._positions.get(e.slice(4));void 0!==t&&this._emit("trading:position_click",{position:t.entity})}}_onDrag(e,t){if(!e.startsWith("ord:"))return;const i=this._orders.get(e.slice(4));if(void 0===i)return;const s=e.slice(4);this._dragPrev.has(s)||(this._dragPrev.set(s,i.entity.price),i.line.setDragGhost(i.entity.price)),i.line.setPrice(t)}_onDragEnd(e,t){if(!e.startsWith("ord:"))return;const i=e.slice(4),s=this._orders.get(i);if(void 0===s)return;const r=this._dragPrev.get(i)??s.entity.price;this._dragPrev.delete(i),s.line.setDragGhost(null),s.entity.price=t,s.line.setPrice(t),void 0!==s.entity.bracketRole?this._emit("trading:bracket_modify",{parentId:s.entity.parentId,bracketRole:s.entity.bracketRole,newPrice:t}):this._emit("trading:order_modify",{orderId:i,newPrice:t,previousPrice:r})}}function Ur(e,t){return{dist:Math.hypot(e.x-t.x,e.y-t.y),cx:(e.x+t.x)/2,cy:(e.y+t.y)/2}}const Kr=new WeakMap,Yr=new WeakMap;function Xr(e){Yr.set(e,{}),Kr.get(e)?.()}function Jr(e,t,i){return Zr(e,t,i)}function Zr(e,t,i,s){if("price"!==t&&"time"!==t)throw new TypeError("Invalid pick kind");const r={};Yr.set(e,r);let n=!1,o=!1;const a=[],l=s=>{if(n){n=!1,Kr.get(e)===h&&Kr.delete(e);try{e.emit("pick:end",{kind:t,value:s}),null===s||o||Yr.get(e)!==r||i(s)}finally{for(const e of a.splice(0))e()}}},h=Object.assign(()=>{o=!0,l(null)},{active:()=>n});for(const t of["destroy","state:restore:start","data:context","paneRemoved","paneMoved"])a.push(e.on(t,h));if(a.push(e.on("data:update",e=>{"reset"===e?.kind&&h()})),Kr.get(e)?.(),o||Yr.get(e)!==r){for(const e of a.splice(0))e();return h}return n=!0,a.push(e.on("click",i=>{if(!n)return;const r=i;let o=s?s(i):"price"===t?r.price:r.time;if(null!==o&&Number.isFinite(o)){if("time"===t){const t=e.dataLayer;o=t.indexToTime(Math.round(t.timeToIndexFloat(o)))??o}Number.isFinite(o)&&l(o)}})),Kr.set(e,h),e.emit("pick:start",{kind:t}),h}const Qr={earnings:"#f0a020",dividend:"#26a69a",split:"#4f8cff",news:"#9aa0b4"};function en(e){return{...e,..."object"==typeof e.details&&null!==e.details?{details:{...e.details,...e.details.fields?{fields:e.details.fields.map(e=>({...e}))}:{}}}:{}}}class tn{constructor(e={}){Object.defineProperty(this,"_entries",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_groups",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:{clustering:!1,clusterRadius:18}}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_positions",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_hits",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_providedIds",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_duplicateIds",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_width",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_height",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.setOptions(e)}attached(e){this._host=e}detached(){this._host=null,this._invalidate()}zOrder(){return"normal"}setEvents(e){const t=e.map(e=>{if(!Number.isFinite(e.time))throw new Error("openalgo-charts: event time must be finite");return en(e)}).sort((e,t)=>e.time-t.time),i=new Map;this._entries=t.map(e=>{const t=void 0===e.id?JSON.stringify([e.time,e.type,e.label,e.group??null]):JSON.stringify(e.id),s=i.get(t)??0;return i.set(t,s+1),{event:e,key:`${t}:${s}`}}),this._providedIds=new Set(t.flatMap(e=>void 0===e.id?[]:[e.id])),this._duplicateIds=new Set([...this._providedIds].filter(e=>(i.get(JSON.stringify(e))??0)>1)),this._invalidate()}events(){return this._entries.map(e=>en(e.event))}setGroups(e){const t=new Map;for(const i of e){if(!i.id||t.has(i.id))throw new Error("openalgo-charts: event group IDs must be nonempty and unique");t.set(i.id,{...i})}const i=new Set;for(const e of t.keys()){const s=new Set;let r=e;for(;void 0!==r&&!i.has(r);){if(s.has(r))throw new Error("openalgo-charts: event group cycle");const e=t.get(r);if(void 0===e)throw new Error("openalgo-charts: event group parent is missing");s.add(r),r=e.parentId}for(const e of s)i.add(e)}this._groups=t,this._invalidate()}groups(){return Array.from(this._groups.values(),e=>({...e}))}setGroupVisible(e,t){const i=this._groups.get(e);if(void 0===i)throw new Error(`openalgo-charts: unknown event group ${e}`);i.visible=t,this._invalidate()}isGroupVisible(e){let t=this._groups.get(e);for(;void 0!==t;){if(!1===t.visible)return!1;t=void 0===t.parentId?void 0:this._groups.get(t.parentId)}return!0}setOptions(e){const t=e.clusterRadius??this._options.clusterRadius;if(!Number.isFinite(t)||t<1||t>200)throw new Error("openalgo-charts: event clusterRadius must be from 1 to 200");this._options={clustering:e.clustering??this._options.clustering,clusterRadius:t},this._invalidate()}options(){return{...this._options}}detailsForHit(e){const t=this._hits.get(e);return void 0===t?null:{id:t.id,cluster:t.entries.length>1,events:t.entries.map(e=>en(e.event))}}draw(e,t){if(this._positions=[],this._hits.clear(),this._width=t.plotWidth,this._height=t.plotHeight,!(0!==this._entries.length&&t.dpr>0&&Number.isFinite(t.dpr)&&t.plotWidth>0&&t.plotHeight>0))return;const i=[];for(const e of this._entries){if(void 0!==e.event.group&&!this.isGroupVisible(e.event.group))continue;const s=t.dataLayer.timeToIndexFloat(e.event.time),r=t.timeScale.indexToX(s);if(!Number.isFinite(r))continue;const n=i[i.length-1];this._options.clustering&&void 0!==n&&r-n.firstX<=this._options.clusterRadius?(n.entries.push(e),n.x+=(r-n.x)/n.entries.length):i.push({x:r,firstX:r,entries:[e]})}const s=t.plotHeight-8-4;e.save(),e.beginPath(),e.rect(0,0,t.plotWidth*t.dpr,t.plotHeight*t.dpr),e.clip(),e.textAlign="center",e.textBaseline="middle",e.font=10*t.dpr+"px system-ui, sans-serif";for(const r of i){if(r.x+8<0||r.x-8>t.plotWidth||s+8<0)continue;const i=r.entries[0].event,n=r.entries.length>1;let o=i.id;if(n||void 0===o||this._duplicateIds.has(o))for(o=`${n?"event-cluster:":"event:"}${JSON.stringify(r.entries.map(e=>e.key).sort())}`;this._providedIds.has(o);)o=":"+o;e.fillStyle=i.color??Qr[i.type]??"#9aa0b4",e.beginPath(),e.arc(r.x*t.dpr,s*t.dpr,8*t.dpr,0,2*Math.PI),e.fill(),e.fillStyle="#0d0e12";const a=n?r.entries.length>99?"99+":String(r.entries.length):i.label.slice(0,2);e.fillText(a,r.x*t.dpr,s*t.dpr);const l={id:o,x:r.x,y:s,r:8,entries:r.entries};this._positions.push(l),this._hits.set(o,l)}e.restore()}hitTest(e,t){if(e<0||t<0||e>this._width||t>this._height)return null;let i=null;for(const s of this._positions){const r=Math.hypot(s.x-e,s.y-t);r<=s.r&&(null===i||r<=i.distance)&&(i={externalId:s.id,zOrder:"normal",distance:r,cursor:"pointer"})}return i}_invalidate(){this._positions=[],this._hits.clear(),this._host?.requestUpdate()}}const sn="indicator-legend::toggle";class rn{constructor(){Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_bounds",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:{count:0,collapsed:!1,left:8,top:6,height:18}})}attached(e){this._host=e}detached(){this._host=null,this._bounds=null}zOrder(){return"top"}setOptions(e){Object.keys(e).every(t=>e[t]===this._options[t])||(this._options=e,this._bounds=null,this._host?.requestUpdate())}draw(e,t){this._bounds=null;const i=this._options,s=t.dpr,r=i.height;if(0===i.count||t.plotWidth<18||i.top<0||i.top+r>t.plotHeight)return;e.save(),e.font=`500 ${11*s}px ui-sans-serif, system-ui, sans-serif`;let n=`Indicators ${i.count}`;e.measureText(n).width/s+24>t.plotWidth&&(n=String(i.count));const o=Math.min(t.plotWidth,e.measureText(n).width/s+24),a=Math.max(0,Math.min(i.left,t.plotWidth-o)),l=i.top;this._bounds={x:a,y:l,width:o,height:r},e.beginPath(),e.rect(a*s,l*s,o*s,r*s),e.clip(),e.fillStyle=V(t.theme.background,.9),e.beginPath(),e.roundRect(a*s,l*s,o*s,r*s,3*s),e.fill(),e.strokeStyle=t.theme.axisText,e.lineWidth=s;const h=(a+8)*s,c=(l+r/2)*s,d=3*s;e.beginPath(),i.collapsed?(e.moveTo(h-d/2,c-d),e.lineTo(h+d/2,c),e.lineTo(h-d/2,c+d)):(e.moveTo(h-d,c-d/2),e.lineTo(h,c+d/2),e.lineTo(h+d,c-d/2)),e.stroke(),e.fillStyle=t.theme.axisText,e.textBaseline="middle",e.textAlign="left",e.fillText(n,(a+16)*s,c),e.restore()}hitTest(e,t){const i=this._bounds;return i&&e>=i.x&&e<i.x+i.width&&t>=i.y&&t<i.y+i.height?{externalId:sn,zOrder:"top",distance:0,cursor:"pointer"}:null}}const nn={position:"bottom-right",margin:8,cellWidth:64,cellHeight:18,fontSize:11,borderWidth:1};function on(e,t,i){const s=Math.floor(.62*e);return 1===t?s:Math.max(0,Math.min(s,Math.floor((e-2*Math.round(4*i))/(1.2*t))))}function an(e,t,i,s){return Math.min(Math.round(e*i),on(t,s,i))}function ln(e,t){return`${!0===e.italic?"italic ":""}${!0===e.bold?"600 ":""}${t}px ${e.fontFamily??"system-ui, sans-serif"}`}function hn(e){return e.text.split(/\r\n|\r|\n/)}function cn(e,t){let i=0;for(const s of t)i=Math.max(i,e.measureText(s).width);return i}const dn=28;function un(e,t,i,s,r,n){const[o,a]=e.split("-");return{x:"left"===a?t:"right"===a?r-i-t:(r-i)/2,y:"top"===o?t:"bottom"===o?n-s-t:(n-s)/2}}let pn=0;class _n{constructor(e={}){Object.defineProperty(this,"_rows",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_grid",{enumerable:!0,configurable:!0,writable:!0,value:{cols:0,cells:[]}}),Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_rect",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_hitId",{enumerable:!0,configurable:!0,writable:!0,value:"table-tooltip:"+ ++pn}),Object.defineProperty(this,"_revision",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_hits",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_size",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._opts={...nn,...e}}attached(e){this._host=e}detached(){this._host=null,this._clearHits()}zOrder(){return"top"}options(){return this._opts}setOptions(e){this._opts={...this._opts,...e},this._clearHits(),this._host?.requestUpdate()}setRows(e){const t=function(e){let t=0;for(const i of e)t=Math.max(t,i.length);const i=new Map,s=[];for(let r=0;r<e.length;r++)for(let n=0;n<e[r].length;n++){const o=e[r][n];if(void 0!==o.tooltip&&"string"!=typeof o.tooltip)throw new TypeError("Table tooltip must be text");const a=void 0===o.rowSpan?1:o.rowSpan,l=void 0===o.colSpan?1:o.colSpan;if(!Number.isSafeInteger(a)||a<1||!Number.isSafeInteger(l)||l<1)throw new RangeError("Table spans must be positive safe integers");if(a>e.length-r||l>t-n)throw new RangeError("Table span exceeds the grid bounds");if(a>1||l>1)for(let e=r;e<r+a;e++){let t=i.get(e);if(void 0===t&&(t=[],i.set(e,t)),t.some(e=>n<e.to&&e.from<n+l))throw new RangeError("Table spans overlap");t.push({from:n,to:n+l})}else if(i.get(r)?.some(e=>e.from<=n&&n<e.to))continue;s.push({cell:o,row:r,col:n,rowSpan:a,colSpan:l})}return{cols:t,cells:s}}(e);this._rows=e,this._grid=t,this._clearHits(),this._host?.requestUpdate()}rows(){return this._rows}_clearHits(){this._rect=null,this._hits=[],this._size=null,this._revision++}_sameSize(e){return this._size?.width===e.plotWidth&&this._size.height===e.plotHeight&&this._size.dpr===e.dpr}draw(e,t){this._sameSize(t)||this._clearHits(),this._size={width:t.plotWidth,height:t.plotHeight,dpr:t.dpr},this._rect=null,this._hits=[];const i=this._rows;if(0===i.length)return;const s=this._opts,r=t.dpr,{cols:n,cells:o}=this._grid;if(0===n)return;const a=i.map((e,t)=>{const i=s.rowWeights?.[t];return"number"==typeof i&&i>0?i:1}),l=a.reduce((e,t)=>e+t,0);let h=s.cellHeight,c=h*l;void 0!==s.heightPercent&&s.heightPercent>0&&(c=t.plotHeight*s.heightPercent/100,h=c/l);const d=[];for(let e=0,t=0;e<i.length;e++)d.push(t),t+=h*a[e];const u=a.map(e=>Math.round(h*e*r)),p=o.map(e=>1===e.rowSpan?u[e.row]:Math.round((d[e.row+e.rowSpan]??c)*r)-Math.round(d[e.row]*r));e.save();const _=function(e,t){const i=[];let s=0;for(let r=0;r<t;r++)i.push(s),s+="number"==typeof e?e:e[r]??e[e.length-1]??0;return{x:i,total:s}}("auto"===s.cellWidth?function(e,t,i,s,r,n){const o=Array(i).fill(dn),a=({cell:t},i)=>{if(""===t.text)return 0;const s=hn(t),o=t.fontSize??r.fontSize,a="auto"===o?Math.round(11*n):an(o,i,n,s.length);return a<=0?0:(e.font=ln(t,a),cn(e,s)/n+10)};for(let e=0;e<t.length;e++){const i=t[e];1===i.colSpan&&(o[i.col]=Math.max(o[i.col],a(i,s[e])))}for(let e=0;e<t.length;e++){const i=t[e];if(1===i.colSpan)continue;let r=0;for(let e=i.col;e<i.col+i.colSpan;e++)r+=o[e];const n=Math.max(0,a(i,s[e])-r)/i.colSpan;for(let e=i.col;e<i.col+i.colSpan;e++)o[e]+=n}return o}(e,o,n,p,s,r):s.cellWidth,n);let f=_.x,m=_.total;if(void 0!==s.widthPercent&&s.widthPercent>0&&m>0){const e=t.plotWidth*s.widthPercent/100,i=e/m;f=f.map(e=>e*i),m=e}const b=un(s.position,s.margin,m,c,t.plotWidth,t.plotHeight);this._rect={x:b.x,y:b.y,w:m,h:c};const g=e=>Math.round(e*r),v=g(b.x),y=g(b.y);void 0!==s.background&&(e.fillStyle=s.background,e.fillRect(v,y,g(m),g(c))),e.textBaseline="middle";for(let i=0;i<o.length;i++){const{cell:n,row:a,col:l,colSpan:h}=o[i],c=y+g(d[a]),u=p[i],_=v+g(f[l]),b=f[l+h]??m,w=1===h?g(b-f[l]):g(b)-g(f[l]);if(n.tooltip){const e=Math.max(0,_/r),i=Math.max(0,c/r),s=Math.min(t.plotWidth,(_+w)/r),o=Math.min(t.plotHeight,(c+u)/r);s>e&&o>i&&this._hits.push({x:e,y:i,w:s-e,h:o-i,key:`${this._hitId}:${this._revision}:${a}:${l}`,tooltip:n.tooltip})}if(void 0!==n.bgColor&&(e.fillStyle=n.bgColor,e.fillRect(_,c,w,u)),void 0!==s.borderColor&&s.borderWidth>0&&(e.strokeStyle=s.borderColor,e.lineWidth=Math.max(1,g(s.borderWidth)),e.strokeRect(_,c,w,u)),""===n.text)continue;const x=g(4);e.save(),e.beginPath(),e.rect(_,c,w,u),e.clip();const S=hn(n),P=on(u,S.length,r);let O;if(void 0===n.fontSize&&"auto"===s.fontSize){const t=1===S.length,i=t?g(6):Math.min(g(6),P);O=t?Math.max(i,P):P,e.font=ln(n,O);const s=w-2*x,r=t?Math.max(1,g(1)):1;for(;O>i&&cn(e,S)>s;)O=t?O-r:Math.max(i,O-r),e.font=ln(n,O)}else O=an(n.fontSize??("auto"===s.fontSize?11:s.fontSize),u,r,S.length);if(O<=0){e.restore();continue}e.font=ln(n,O),e.fillStyle=n.textColor??(void 0!==n.bgColor?q(n.bgColor):t.theme.axisText);const k=n.align??"center";e.textAlign=k;const I="left"===k?_+x:"right"===k?_+w-x:_+w/2,M=1.2*O,T=S.length*M,C=Math.min(x,Math.max(0,(u-T)/2)),j="top"===n.verticalAlign?c+C+M/2:"bottom"===n.verticalAlign?c+u-C-T+M/2:c+u/2-(S.length-1)*M/2;for(let t=0;t<S.length;t++)e.fillText(S[t],I,j+t*M);e.restore()}void 0!==s.frameColor&&(s.frameWidth??1)>0&&(e.strokeStyle=s.frameColor,e.lineWidth=Math.max(1,g(s.frameWidth??1)),e.strokeRect(v,y,g(m),g(c))),this._drawTooltip(e,t),e.restore()}_drawTooltip(e,t){if(t.hoverId!==(this._opts.id??this._hitId)||!t.hoverKey)return;const i=this._hits.find(e=>e.key===t.hoverKey),s=t.dpr,r=t.plotWidth*s,n=t.plotHeight*s;if(!i||r<=10*s||n<=6*s)return;e.save(),e.font=11*s+"px system-ui, sans-serif",e.textAlign="left",e.textBaseline="middle";const o=5*s,a=3*s,l=11*s*1.35,h=function(e,t,i,s){const r=[];for(const n of t.split(/\r\n|\r|\n/)){const t=Array.from(n);0===t.length&&r.push("");for(let n=0;n<t.length&&r.length<s;){let s=0,o=t.length-n;for(;s<o;){const r=Math.ceil((s+o)/2);e.measureText(t.slice(n,n+r).join("")).width<=i?s=r:o=r-1}let a=Math.max(1,s);if(n+a<t.length)for(let e=a-1;e>0;e--)if(/\s/.test(t[n+e])){a=e+1;break}r.push(t.slice(n,n+a).join("")),n+=a}if(r.length>=s)break}return r}(e,i.tooltip,r-2*o,Math.ceil((n-2*a)/l)),c=Math.min(r,cn(e,h)+2*o),d=h.length*l+2*a,u=Math.max(0,Math.min((i.x+i.w/2)*s-c/2,r-c)),p=i.y*s-8*s-d,_=Math.max(0,Math.min(p>=0?p:(i.y+i.h)*s+8*s,n-d));e.beginPath(),e.rect(0,0,r,n),e.clip(),e.beginPath(),U(e,u,_,c,d,Math.min(3*s,c/2,d/2)),e.fillStyle=t.theme.axisText,e.fill(),e.fillStyle=q(t.theme.axisText);for(let t=0;t<h.length;t++)e.fillText(h[t],u+o,_+a+(t+.5)*l);e.restore()}hitTest(e,t,i){if(void 0!==i&&!this._sameSize(i))return this._clearHits(),null;if(!Number.isFinite(e)||!Number.isFinite(t)||!this._size||e<0||t<0||e>this._size.width||t>this._size.height)return null;const s=this._rect;if(null===s)return null;for(const i of this._hits)if(e>=i.x&&e<i.x+i.w&&t>=i.y&&t<i.y+i.h)return{externalId:this._opts.id??this._hitId,hoverKey:i.key,zOrder:"top",distance:0,cursor:"default"};return void 0===this._opts.id||e<s.x||e>s.x+s.w||t<s.y||t>s.y+s.h?null:{externalId:this._opts.id,zOrder:"top",distance:0,cursor:"default"}}}const fn={zoomOut:"Zoom out",zoomIn:"Zoom in",resetScale:"Reset view",panLeftBar:"Move left",panRightBar:"Move right"},mn={id:"timenav",buttons:["zoomOut","zoomIn",null,"resetScale",null,"panLeftBar","panRightBar"],size:26,gap:4,groupGap:16,bottomMargin:10,revealHeight:64,fadeSeconds:.12,labels:fn,hints:{},showTooltip:!0,font:11,radius:6,zOrder:"top"};class bn{constructor(e={},t){Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_boxes",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_pointer",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_opacity",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastFrameMs",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_revealTop",{enumerable:!0,configurable:!0,writable:!0,value:1/0}),this._opts={...mn,...e,labels:{...mn.labels,...e.labels}},this._now=t??(()=>"undefined"!=typeof performance?performance.now():0)}attached(e){this._host=e}detached(){this._host=null}zOrder(){return this._opts.zOrder??"top"}options(){return this._opts}setOptions(e){this._opts={...this._opts,...e,labels:{...this._opts.labels,...e.labels}},this._host?.requestUpdate()}setPointer(e){const t=this._pointer;this._pointer=e,(null===t!=(null===e)||this._opacity>0||this._targetOpacity()>0)&&this._host?.requestUpdate()}_revealed(){return null!==this._pointer&&this._pointer.y>=this._revealTop}_targetOpacity(){return this._revealed()?1:0}animating(){return Math.abs(this._targetOpacity()-this._opacity)>.001}draw(e,t){const i=this._opts,s=t.dpr;this._revealTop=Math.max(0,t.plotHeight-i.revealHeight);const r=this._targetOpacity(),n=this._now(),o=null===this._lastFrameMs?0:Math.max(0,(n-this._lastFrameMs)/1e3);if(this._lastFrameMs=n,i.fadeSeconds<=0||o<=0)i.fadeSeconds<=0&&(this._opacity=r);else{const e=o/i.fadeSeconds;this._opacity+=Math.sign(r-this._opacity)*Math.min(e,Math.abs(r-this._opacity))}if(this._opacity<=.001)return this._boxes=[],void(this._opacity=0);const a=i.size;let l=0;for(let e=0;e<i.buttons.length;e++){null!==i.buttons[e]?(l+=a,e<i.buttons.length-1&&null!==i.buttons[e+1]&&(l+=i.gap)):l+=i.groupGap}const h=(t.plotWidth-l)/2,c=t.plotHeight-i.bottomMargin-a;this._boxes=[];let d=h;for(let e=0;e<i.buttons.length;e++){const t=i.buttons[e];null!==t?(this._boxes.push({action:t,x:d,y:c,w:a,h:a}),d+=a,e<i.buttons.length-1&&null!==i.buttons[e+1]&&(d+=i.gap)):d+=i.groupGap}const u=this._hoveredAction();e.save(),e.globalAlpha=this._opacity;for(const i of this._boxes)this._button(e,i,i.action===u,t,s);i.showTooltip&&null!==u&&this._tooltip(e,u,t,s),e.restore()}_hoveredAction(){const e=this._pointer;if(null===e)return null;for(const t of this._boxes)if(e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h)return t.action;return null}_button(e,t,i,s,r){const n=this._opts,o=t.x*r,a=t.y*r,l=t.w*r,h=t.h*r,c=Math.min(n.radius*r,l/2,h/2);e.beginPath(),e.roundRect(o,a,l,h,c),e.fillStyle=gn(s.theme.background,s.theme.axisText,i?.28:.12),e.fill(),e.strokeStyle=yn(s.theme.axisLine,i?1:.8),e.lineWidth=Math.max(1,Math.round(r)),e.stroke(),e.strokeStyle=s.theme.axisText,e.fillStyle=s.theme.axisText,e.lineWidth=Math.max(1,Math.round(1.5*r)),e.lineCap="round",e.lineJoin="round";const d=o+l/2,u=a+h/2,p=.22*Math.min(l,h);switch(e.beginPath(),t.action){case"zoomOut":e.moveTo(d-p,u),e.lineTo(d+p,u);break;case"zoomIn":e.moveTo(d-p,u),e.lineTo(d+p,u),e.moveTo(d,u-p),e.lineTo(d,u+p);break;case"resetScale":{const t=p*Math.SQRT1_2;e.arc(d,u,p,.75*-Math.PI,.75*Math.PI),e.moveTo(d-t,u-2*t),e.lineTo(d-t,u-t),e.lineTo(d,u-t);break}case"panLeftBar":e.moveTo(d+.55*p,u-p),e.lineTo(d-.5*p,u),e.lineTo(d+.55*p,u+p);break;case"panRightBar":e.moveTo(d-.55*p,u-p),e.lineTo(d+.5*p,u),e.lineTo(d-.55*p,u+p)}e.stroke()}_tooltip(e,t,i,s){const r=this._opts,n=this._boxes.find(e=>e.action===t);if(void 0===n)return;const o=r.labels[t]??fn[t],a=r.hints[t];e.font=r.font*s+"px ui-sans-serif, system-ui, sans-serif",e.textBaseline="middle",e.textAlign="left";const l=7*s,h=8*s,c=e.measureText(o).width,d=2*l+c+(void 0===a?0:e.measureText(a).width+h+8*s),u=22*s;let p=(n.x+n.w/2)*s-d/2;p=Math.max(2*s,Math.min(p,i.plotWidth*s-d-2*s));const _=n.y*s-u-6*s;if(e.beginPath(),e.roundRect(p,_,d,u,5*s),e.fillStyle=gn(i.theme.background,i.theme.axisText,.22),e.fill(),e.strokeStyle=yn(i.theme.axisLine,.9),e.lineWidth=Math.max(1,Math.round(s)),e.stroke(),e.fillStyle=i.theme.axisText,e.fillText(o,p+l,_+u/2),void 0!==a){const t=p+l+c+h,r=e.measureText(a).width+8*s;e.beginPath(),e.roundRect(t-4*s,_+4*s,r,u-8*s,3*s),e.fillStyle=gn(i.theme.background,i.theme.axisText,.42),e.fill(),e.fillStyle=i.theme.axisText,e.fillText(a,t,_+u/2)}}hitTest(e,t){if(this._opacity<.5)return null;for(const i of this._boxes)if(e>=i.x&&e<=i.x+i.w&&t>=i.y&&t<=i.y+i.h)return{externalId:`${this._opts.id}::${i.action}`,zOrder:"top",distance:0,cursor:"pointer"};return null}}function gn(e,t,i){const s=vn(e),r=vn(t);if(null===s||null===r)return e;const n=i<0?0:i>1?1:i;return`rgb(${Math.round(s[0]+(r[0]-s[0])*n)},${Math.round(s[1]+(r[1]-s[1])*n)},${Math.round(s[2]+(r[2]-s[2])*n)})`}function vn(e){if(e.startsWith("#")){const t=e.slice(1),i=3===t.length?t.split("").map(e=>e+e).join(""):t,s=parseInt(i.slice(0,6),16);return Number.isNaN(s)?null:[s>>16&255,s>>8&255,255&s]}const t=/^rgba?\(([^)]+)\)$/.exec(e);if(null===t)return null;const i=t[1].split(",").map(e=>parseFloat(e));return[i[0],i[1],i[2]]}function yn(e,t){if(e.startsWith("#")){const i=e.slice(1),s=3===i.length?i.split("").map(e=>e+e).join(""):i,r=parseInt(s.slice(0,6),16);return Number.isNaN(r)?e:`rgba(${r>>16&255},${r>>8&255},${255&r},${t})`}const i=/^rgba?\(([^)]+)\)$/.exec(e);if(null===i)return e;const s=i[1].split(",").map(e=>e.trim());return`rgba(${s[0]},${s[1]},${s[2]},${t})`}function wn(e){return void 0===e?{x:7,y:4}:"number"==typeof e?{x:e,y:e}:{x:e.x,y:e.y}}function xn(e,t,i,s,r,n){const o=r-t-i,a=n-t-s;switch(e){case"top-left":return{x:t,y:t,w:i,h:s};case"top-right":return{x:o,y:t,w:i,h:s};case"bottom-left":return{x:t,y:a,w:i,h:s};case"center":return{x:(r-i)/2,y:(n-s)/2,w:i,h:s};default:return{x:o,y:a,w:i,h:s}}}class Sn{constructor(e={}){Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_reveal",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastFrameMs",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_labelW",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:"undefined"!=typeof performance?()=>performance.now():()=>0}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_img",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_ready",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_autoHeight",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tintCanvas",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_tintKey",{enumerable:!0,configurable:!0,writable:!0,value:""}),this._autoHeight=void 0===e.height,this._opts={position:e.position??"bottom-right",margin:e.margin??12,height:e.height??28,opacity:e.opacity??.7,zOrder:e.zOrder??"top",src:e.src,image:e.image,tint:e.tint,label:e.label,id:e.id??"watermark",revealSeconds:e.revealSeconds??.18,labelColor:e.labelColor,fontSize:e.fontSize??12,background:e.background,borderColor:e.borderColor,radius:e.radius??6,padding:wn(e.padding),href:e.href,utmMedium:e.utmMedium??"oac-link",utmCampaign:e.utmCampaign??"oac-chart"},e.image&&(this._img=e.image,this._ready=!0)}attached(e){if(this._host=e,!this._ready&&this._opts.src&&"undefined"!=typeof Image){const e=new Image;e.onload=()=>{this._img=e,this._ready=!0,this._host?.requestUpdate()},e.decoding="async",e.src=this._opts.src}}detached(){this._host=null}zOrder(){return this._opts.zOrder}autoscaleInfo(){return null}setOptions(e){const{padding:t,...i}=e;this._opts={...this._opts,...i},void 0!==t&&(this._opts.padding=wn(t)),void 0!==e.height&&(this._autoHeight=!1),void 0===e.label&&void 0===e.fontSize||(this._labelW=0),this._tintCanvas=null,e.image?(this._img=e.image,this._ready=!0):void 0!==e.src&&(this._ready=!1,this._img=null,this.attached(this._host)),this._host?.requestUpdate()}_rect(e){if(!(this._builtin()||this._ready&&null!==this._img))return null;const t=this._img?.naturalWidth??this._img?.width??1,i=this._img?.naturalHeight??this._img?.height??1;if(!t||!i)return null;const s=this._opts,r=Math.max(0,s.margin,s.padding.x,s.padding.y),n=e.plotWidth-2*r,o=e.plotHeight-2*r;if(n<=0||o<=0)return null;const a=this._builtin()&&this._autoHeight&&e.plotWidth<480?24:s.height,l=Math.max(0,Math.min(a,o,n*i/t));if(!Number.isFinite(l)||l<=0)return null;const h=l*(t/i),c=Math.min(n,h+this._labelW*this._reveal);return{...xn(s.position,r,c,l,e.plotWidth,e.plotHeight),logoW:h}}_builtin(){return void 0===this._opts.src&&void 0===this._opts.image}href(){const e=this._opts.href;if(void 0===e||e.includes("?"))return e;const t="undefined"!=typeof location?location:void 0,i=[`utm_medium=${encodeURIComponent(this._opts.utmMedium)}`,`utm_campaign=${encodeURIComponent(this._opts.utmCampaign)}`];return t?.host&&i.push(`utm_source=${t.host}${t.pathname}`),`${e}${e.includes("?")?"&":"?"}${i.join("&")}`}hitTest(e,t,i){if(void 0===this._opts.label&&void 0===this._opts.href)return null;const s=this._rect(i);if(null===s)return null;const r=Math.max(this._opts.padding.x,4,(44-s.w)/2),n=Math.max(this._opts.padding.y,4,(44-s.h)/2),o=Math.min(i.plotWidth,s.w+2*r),a=Math.min(i.plotHeight,s.h+2*n),l=Math.max(0,Math.min(i.plotWidth-o,s.x-r)),h=Math.max(0,Math.min(i.plotHeight-a,s.y-n));return e>=l&&e<=l+o&&t>=h&&t<=h+a?{externalId:this._opts.id,zOrder:this._opts.zOrder,distance:0,cursor:void 0!==this._opts.href?"pointer":"default"}:null}draw(e,t){if(!(this._builtin()||this._ready&&null!==this._img))return;const i=this._opts,s=t.dpr;void 0!==i.label&&0===this._labelW&&(e.save(),e.font=`600 ${i.fontSize*s}px system-ui, sans-serif`,this._labelW=e.measureText(i.label).width/s+8,e.restore()),this._advanceReveal(t);const r=this._rect(t);if(null===r)return;const n=Math.round(r.x*s),o=Math.round(r.y*s),a=Math.round(r.logoW*s),l=Math.round(r.h*s);e.save();const h=i.padding,c=Math.round((r.x-h.x)*s),d=Math.round((r.y-h.y)*s),u=Math.round((r.x+r.w+h.x)*s)-c,p=Math.round((r.y+r.h+h.y)*s)-d,_=t.theme,f=i.background??(_?V(_.background,.82):"none"),m=i.borderColor??_?.axisLine??"none";"none"!==f&&(e.beginPath(),U(e,c,d,u,p,Math.round(i.radius*s)),e.fillStyle=f,e.fill(),"none"!==m&&(e.strokeStyle=m,e.lineWidth=Math.max(1,Math.round(s)),e.stroke())),e.globalAlpha=Math.max(0,Math.min(1,i.opacity));const b=this._ink(t),g=void 0!==i.label?b:i.tint;if(this._builtin())e.fillStyle=b,function(e,t,i,s){e.save(),e.translate(t,i),e.scale(s/397,s/397),e.translate(-315.1,-217.65),e.beginPath(),e.moveTo(367.5,255.5),e.bezierCurveTo(371.3,251.3,374.8,247.3,378.7,242.8),e.bezierCurveTo(398.1,262.7,416.4,281.4,435.2,300.6),e.bezierCurveTo(461.6,273.7,487.4,247.4,513.6,220.6),e.bezierCurveTo(540.7,247.4,566.9,273.2,592.9,298.9),e.bezierCurveTo(611.4,280.3,629.8,262,648.4,243.3),e.bezierCurveTo(654.6,249.9,660.3,256.1,665.9,262.2),e.bezierCurveTo(648.3,280.2,630.3,298.7,612.5,316.9),e.bezierCurveTo(645.6,350.8,679,384.9,712.1,418.6),e.bezierCurveTo(684.7,446.7,656.7,475.5,628.4,504.5),e.bezierCurveTo(647.5,523.2,667.4,542.7,686.8,561.8),e.bezierCurveTo(680.8,568.3,675,574.7,668.8,581.5),e.bezierCurveTo(648.3,561.4,628.3,541.7,608.1,521.8),e.bezierCurveTo(577.2,551.9,546.6,581.7,516,611.7),e.bezierCurveTo(488.3,584.7,461,558,433.6,531.3),e.bezierCurveTo(415.9,548.5,398.2,565.6,380.1,583.1),e.bezierCurveTo(374.3,576.6,368.7,570.4,363.5,564.6),e.bezierCurveTo(379.4,548,396.1,530.5,412.9,512.9),e.bezierCurveTo(380.7,481.9,348,450.4,315.1,418.7),e.bezierCurveTo(349.2,385,383,351.6,416.6,318.3),e.bezierCurveTo(398.1,299.3,379.8,280.6,360.9,261.3),e.bezierCurveTo(362.8,259.7,365,257.7,367.5,255.5),e.moveTo(540.5,406),e.bezierCurveTo(552,417.1,563.4,428.1,575,439.2),e.bezierCurveTo(588.1,426.5,601.7,413.3,615.9,399.5),e.bezierCurveTo(621.9,406.1,627.8,412.6,633.8,419.2),e.bezierCurveTo(620.3,431.7,606.4,444.8,592.9,457.3),e.bezierCurveTo(600,464.3,606.9,471.2,613.8,478.1),e.bezierCurveTo(633.5,458.1,653.4,437.7,673.2,417.5),e.bezierCurveTo(620.7,365.5,567.7,313.2,514.8,260.8),e.bezierCurveTo(494.6,280.6,474.6,300.2,454.3,320),e.bezierCurveTo(461.7,327,468.8,333.8,477.5,342.1),e.bezierCurveTo(489.4,329.1,501.6,315.8,514.3,301.9),e.bezierCurveTo(521,308.7,526.7,314.6,531.9,319.9),e.bezierCurveTo(519.2,333.3,506.8,346.5,494.7,359.4),e.bezierCurveTo(509.5,374.4,524.7,390,540.5,406),e.moveTo(575.3,514.8),e.bezierCurveTo(581.4,508.6,587.6,502.3,593.4,496.4),e.bezierCurveTo(586.7,489.5,580.1,482.5,573.2,475.3),e.bezierCurveTo(557.6,490.1,542.3,504.7,526.9,519.3),e.bezierCurveTo(520.9,513.3,515.2,507.5,509.4,501.6),e.bezierCurveTo(524.7,487,540,472.3,555.6,457.4),e.bezierCurveTo(528.5,430.5,501.6,403.8,474.5,377),e.bezierCurveTo(461.3,389.6,448,402.3,434.6,415.2),e.bezierCurveTo(455,435.2,475.1,454.9,494.9,474.3),e.bezierCurveTo(482.1,487.6,469.4,500.8,456.5,514.1),e.bezierCurveTo(476.3,533.2,496.5,552.7,516.8,572.4),e.bezierCurveTo(536.3,553.1,555.6,534.2,575.3,514.8),e.moveTo(413.2,474.3),e.bezierCurveTo(420.1,481,427,487.7,434.6,495.1),e.bezierCurveTo(441.3,487.6,447.8,480.3,453.9,473.5),e.bezierCurveTo(435.5,454.7,416.3,435.1,397.1,415.5),e.bezierCurveTo(416.9,396.5,436.7,377.7,456.9,358.4),e.bezierCurveTo(449.8,351.8,442.7,345.3,435.6,338.7),e.bezierCurveTo(409,364.8,381.8,391.4,354.7,418),e.bezierCurveTo(374.3,436.9,393.4,455.4,413.2,474.3),e.closePath(),e.fill(),e.restore()}(e,n,o,l);else{const t=g?this._tinted(e,a,l,g):this._img;g&&t?e.drawImage(t,n,o):this._img&&e.drawImage(this._img,n,o,a,l)}if(void 0!==i.label&&this._reveal>.001){const t=(r.w-r.logoW)*s;e.beginPath(),e.rect(n+a,o,t,l),e.clip(),e.globalAlpha=this._reveal,e.font=`600 ${Math.round(i.fontSize*s)}px system-ui, -apple-system, sans-serif`,e.textBaseline="middle",e.textAlign="left",e.fillStyle=b,e.fillText(i.label,Math.round(n+a+6*s),Math.round(o+l/2))}e.restore()}_ink(e){const t=this._opts,i=e.theme;return t.labelColor??t.tint??i?.axisText??"#9aa3b2"}_advanceReveal(e){if(void 0===this._opts.label)return;const t=e.hoverId===this._opts.id?1:0,i=this._now(),s=null===this._lastFrameMs?0:Math.max(0,(i-this._lastFrameMs)/1e3);this._lastFrameMs=i;const r=this._opts.revealSeconds;if(r<=0)this._reveal=t;else if(this._reveal!==t){const e=s/r;this._reveal+=Math.sign(t-this._reveal)*Math.min(e,Math.abs(t-this._reveal))}Math.abs(t-this._reveal)>.001?this._host?.requestUpdate():this._reveal=t}_tinted(e,t,i,s){const r=`${t}x${i}:${s}`;if(this._tintCanvas&&this._tintKey===r)return this._tintCanvas;const n=e.canvas,o=n?.ownerDocument;let a=null;if(o&&"function"==typeof o.createElement&&(a=o.createElement("canvas")),!a)return null;a.width=t,a.height=i;const l=a.getContext("2d");return l&&null!==this._img?(l.clearRect(0,0,t,i),l.drawImage(this._img,0,0,t,i),l.globalCompositeOperation="source-in",l.fillStyle=s,l.fillRect(0,0,t,i),this._tintCanvas=a,this._tintKey=r,a):null}}const Pn='600 {size}px system-ui, -apple-system, "Segoe UI", sans-serif';class On{constructor(e){Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._opts={text:e.text,fontSize:e.fontSize??64,opacity:e.opacity??.08,zOrder:e.zOrder??"bottom",id:e.id??"text-watermark",color:e.color,font:e.font}}zOrder(){return this._opts.zOrder}attached(e){this._host=e}detached(){this._host=null}autoscaleInfo(){return null}hitTest(){return null}setOptions(e){this._opts={...this._opts,...e},this._host?.requestUpdate()}draw(e,t){const i=this._opts;if(""===i.text)return;const s=t.dpr,r=t.plotWidth*s,n=t.plotHeight*s;if(r<=0||n<=0)return;e.save(),e.beginPath(),e.rect(0,0,r,n),e.clip(),e.globalAlpha=i.opacity,e.fillStyle=i.color??"#9aa4b2",e.textAlign="center",e.textBaseline="middle";const o=Math.min(i.fontSize*s,.8*n),a=(i.font??Pn).replace("{size}",String(Math.round(o)));e.font=a;const l=e.measureText(i.text).width,h=.8*r;if(l>h&&l>0){const t=Math.max(.1,o*(h/l));e.font=(i.font??Pn).replace("{size}",String(t))}e.fillText(i.text,r/2,n/2),e.restore()}}const kn=["up","down","collapse","maximize"];function In(e=[],t){const i=e.filter(e=>!kn.includes(e));return t&&i.splice(i.includes("close")?i.indexOf("close"):i.length,0,...kn),i}const Mn=["#f5a623","#26a69a","#ab47bc","#ef5350","#26c6da","#8bc34a","#ff7043","#5c6bc0"];function Tn(e){if(!Ae(e))throw new Error(`openalgo-charts: unknown IANA time zone "${e}"`);return e}function Cn(e){const t=Math.abs(e);return t>=1e9?(e/1e9).toFixed(2)+"B":t>=1e6?(e/1e6).toFixed(2)+"M":t>=1e3?(e/1e3).toFixed(2)+"K":String(Math.round(e))}function jn(e){const t=e.pointerType;return{modifiers:{shift:!0===e.shiftKey,alt:!0===e.altKey,ctrl:!0===e.ctrlKey,meta:!0===e.metaKey},pointerType:"touch"===t||"pen"===t?t:"mouse",pressure:An(e)}}function An(e){const t=e.pressure;return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):0!==(e.buttons??0)?.5:0}const Ln=["linear","logarithmic","percentage","indexed-to-100"];function Rn(){return"undefined"!=typeof window&&window.devicePixelRatio?window.devicePixelRatio:1}class zn{constructor(e,t={}){Object.defineProperty(this,"_container",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_doc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pixelRatio",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_theme",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_panes",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_loop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_raf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_remeasureHandle",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dataLayer",{enumerable:!0,configurable:!0,writable:!0,value:new S}),Object.defineProperty(this,"_timeScale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timeScaleMutationDepth",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_priceAxisWidth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timeAxisHeight",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pending",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_scaleMutationDepth",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_resizeObserver",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_width",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_height",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_hasFitContent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_crosshairMode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_crosshairSnapToBar",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_priceOnlyAutoScale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_indicatorLegendCollapsed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_shortcuts",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_trading",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pointerInside",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_keyTarget",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_conflate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_conflationFactor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_backendFactory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_rendererKind",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_requestedRenderer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_gridVert",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_gridHorz",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_canvas",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_statusLine",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_legendIconSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_axisChrome",{enumerable:!0,configurable:!0,writable:!0,value:{sessionClock:!1,barCountdown:!1}}),Object.defineProperty(this,"_sessionClockForm",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_wallClock",{enumerable:!0,configurable:!0,writable:!0,value:()=>Date.now()/1e3}),Object.defineProperty(this,"_tradingSettings",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_events",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_eventMarkers",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_eventPane",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_eventVisible",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_cursorPane",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_cursor",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dragging",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_navigation",{enumerable:!0,configurable:!0,writable:!0,value:{mousePan:"both",defaultVisibleBars:0,panEnabled:!0,zoomEnabled:!0}}),Object.defineProperty(this,"_navigationCancelled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_dragStartX",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_dragStartY",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastDragY",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_endedPointers",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_pointers",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_pinch",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pinchPane",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_liveRegion",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dragStartOffset",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastDragX",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastDragT",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_dragVelocity",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_kineticHandle",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_kineticEpoch",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_zoomHandle",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_zoomGlide",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_zoomGlideStart",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_zoomGlideApplied",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_animZoom",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_animAutoscale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_autoscaleTime",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_autoscaleFrames",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_navigationEpoch",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_zoomAnchor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_doubleClick",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_firstDataId",{enumerable:!0,configurable:!0,writable:!0,value:{value:null}}),Object.defineProperty(this,"_primary",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_seriesRecords",{enumerable:!0,configurable:!0,writable:!0,value:new WeakMap}),Object.defineProperty(this,"_seriesProvenance",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_indicators",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_restoreGeneration",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_indicatorRanges",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_ownedScaleRanges",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_seriesOwners",{enumerable:!0,configurable:!0,writable:!0,value:new WeakMap}),Object.defineProperty(this,"_dataContext",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_barsProvider",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_barsRequests",{enumerable:!0,configurable:!0,writable:!0,value:new AbortController}),Object.defineProperty(this,"_barsProviderRevision",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_requestedDataRevision",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_recomputing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_indicatorsDirty",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_indicatorRefreshes",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_indicatorWork",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_indicatorProcessed",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_indicatorReservedIds",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_barColorOwner",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_barColors",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_barColorBase",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_barColorAnchor",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_drawingState",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_alertState",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_maximizedPane",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_collapsed",{enumerable:!0,configurable:!0,writable:!0,value:new WeakSet}),Object.defineProperty(this,"_legends",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_studyLegends",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_indicatorLegendToggle",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_indicatorLegendRow",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_indicatorTogglePress",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_lastPressOnIndicatorToggle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_previousPressOnIndicatorToggle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_firstPaneIndex",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_historyLoader",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_loadingHistory",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_clickCb",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_crosshairCb",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_readoutTime",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pointerMoved",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_placementMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_legendOffset",{enumerable:!0,configurable:!0,writable:!0,value:{top:6,left:8}}),Object.defineProperty(this,"_downPane",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_downX",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_downLocalY",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_downPressure",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_dragId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dragPriceScale",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dragCancelOnEscape",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_hoverId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_hoverKey",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_hoverOnBase",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_overlayFrozen",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_dragCb",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dragEndCb",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_axisDrag",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_axisDragScale",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_dragMoved",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_dragFrom",{enumerable:!0,configurable:!0,writable:!0,value:{time:0,price:0}}),Object.defineProperty(this,"_paneResize",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_axisStartCoord",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_axisStartMin",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_axisStartMax",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_axisStartSpacing",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_priceFormatter",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_priceScaleOptions",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pricePanes",{enumerable:!0,configurable:!0,writable:!0,value:new WeakSet}),Object.defineProperty(this,"_timeFormatter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timezone",{enumerable:!0,configurable:!0,writable:!0,value:Me}),Object.defineProperty(this,"_leftAxisWidth",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_rightAxisWidth",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_axisColumnWidth",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_emptyPriceAxis",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_timeNav",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_timeNavButtons",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_schedulingTimeNav",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_timeNavPane",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"_branding",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_brandingOptions",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_brandingPress",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_watermark",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_watermarkOptions",{enumerable:!0,configurable:!0,writable:!0,value:{visible:!1,text:"",color:"#9aa4b2",opacity:.08,fontSize:64}}),Object.defineProperty(this,"_listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_anchored",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_onPointerEnter",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this._pointerInside=!0}}),Object.defineProperty(this,"_onContextMenu",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(e.defaultPrevented)return;const t=this._localPoint(e),i=this._panes[t.pane];if(void 0===i)return;const s=this._listeners.get("contextmenu");if(void 0!==s&&s.size>0)this.emit("contextmenu",this._contextMenuEvent(e,t));else{this._cursor=null,this._cursorPane=null;try{const e=i.top.ctx;e.save(),e.globalCompositeOperation="destination-over",e.drawImage(i.base.element,0,0),e.restore(),this._overlayFrozen=!0}catch{}}}}),Object.defineProperty(this,"_onPointerDown",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(this._unfreezeOverlay(),("mouse"===e.pointerType||"pen"===e.pointerType)&&0!==e.button)return;this._previousPressOnIndicatorToggle=this._lastPressOnIndicatorToggle,this._lastPressOnIndicatorToggle=!1,this._endedPointers.delete(e.pointerId),0===this._pointers.size&&(this._navigationCancelled=!1),this._stopKinetic(),this._stopZoomGlide();const t=this._localPoint(e);this._pointers.set(e.pointerId,{x:t.x,y:t.y,pane:t.pane});try{this._container.setPointerCapture?.(e.pointerId)}catch{}if(this._navigationCancelled)return;if(this._pointers.size>=2)return void this._beginPinch();this._downPane=t.pane,this._downX=t.x,this._downLocalY=t.localY,this._downPressure=An(e);const s=this._dividerAt(t.y);if(null!==s){const e=this._paneLayout(),[i,r]=s;return this._paneResize={a:i,b:r,startY:t.y,aWeight:this._panes[i].weight,bWeight:this._panes[r].weight,aHeight:e[i].height,bHeight:e[r].height},void(this._dragging=!1)}const r=Math.max(0,this._width-this._rightAxisWidth),n=this._leftAxisWidth>0&&t.x<this._leftAxisWidth,o=t.x>=r||n,a=t.pane===this._bottomPaneIndex()&&t.localY>=t.paneHeight-this._timeAxisHeight;if(o){const e=this._axisAt(t.pane,t.x);if(this._dragging=!1,!e||!1===this._navigation.zoomEnabled)return void(this._axisDrag="empty");this._axisDrag="price",this._axisDragScale=this._panes[t.pane].scaleFor(e.scaleId),this._axisStartCoord=t.localY;const i=this._axisDragScale.priceRange();return this._axisStartMin=i.min,this._axisStartMax=i.max,void(this._dragging=!1)}if(a)return!1===this._navigation.zoomEnabled?void(this._axisDrag="empty"):(this._axisDrag="time",this._axisStartCoord=t.x,this._axisStartSpacing=this._timeScale.barSpacing,void(this._dragging=!1));if(this._indicatorLegendHit(t.pane,t.x,t.localY))return this._lastPressOnIndicatorToggle=!0,this._indicatorTogglePress={pointerId:e.pointerId,moved:!1},this._dragging=!1,void(this._pointerMoved=!1);if(null!==this._branding&&this._brandingHit(t.pane,t.x,t.localY))return this._brandingPress={pointerId:e.pointerId,mark:this._branding,moved:!1},this._dragging=!1,void(this._pointerMoved=!1);if(this._placementMode)return this._dragging=!1,void(this._pointerMoved=!1);const l=this._panes[t.pane]?.hitTestPrimitives(t.x-this._leftAxisWidth,t.localY,this._renderContext(t.pane));if(l&&(!0===l.draggable||"ns-resize"===l.cursor&&null!==this._dragCb)){this._dragId=l.externalId,this._dragPriceScale=l.priceScale??null,this._dragCancelOnEscape=!0===l.cancelOnEscape,this._dragMoved=!1,this._ensureScaled(t.pane),this._dragFrom={time:this._xToTime(t.x),price:this._dragPriceScale?.yToPrice(t.localY)??this._panes[t.pane].yToPrice(t.localY)},this._setHover(l),this._cursor=null,this._cursorPane=null,this._readoutTime=null,this.invalidate(e=>e.invalidateGlobal(i.Cursor)),this._dragging=!1,this._pointerMoved=!1;const s={id:l.externalId,...this._dragFrom,paneIndex:this._downPane,point:{x:t.x,y:t.localY},...jn(e)};return void this.emit("drag:start",s)}this._dragging=!1!==this._navigation.panEnabled,this._setHover(l??null),this._pointerMoved=!1,this._dragStartX=t.x,this._dragStartY=t.y,this._lastDragY=t.y,this._dragStartOffset=this._timeScale.rightOffset,this._lastDragX=t.x,this._lastDragT=this._now(),this._dragVelocity=0}}),Object.defineProperty(this,"_onPointerMove",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(this._unfreezeOverlay(),this._pointers.size>0&&!this._pointers.has(e.pointerId))return;if(("mouse"===e.pointerType||"pen"===e.pointerType)&&!(1&e.buttons)&&(this._pointers.has(e.pointerId)||this._dragging||null!==this._dragId||null!==this._axisDrag||null!==this._brandingPress||null!==this._indicatorTogglePress))return null!==this._brandingPress&&(this._brandingPress.moved=!0),null!==this._indicatorTogglePress&&(this._indicatorTogglePress.moved=!0),this._onPointerUp(e),void this._endedPointers.add(e.pointerId);const t=this._localPoint(e);if(this._pointers.has(e.pointerId)&&this._pointers.set(e.pointerId,{x:t.x,y:t.y,pane:t.pane}),!this._navigationCancelled)if(null===this._pinch){if("empty"!==this._axisDrag)if(null===this._indicatorTogglePress)if(null===this._brandingPress){if("price"===this._axisDrag){const e=t.localY-this._axisStartCoord,s=Math.exp(.005*e),r=(this._axisStartMin+this._axisStartMax)/2,n=(this._axisStartMax-this._axisStartMin)/2*s,o=this._axisDragScale??this._panes[this._downPane].priceScale;return o.setPriceRange({min:r-n,max:r+n}),o.setAutoScale(!1),void this.invalidate(e=>e.invalidatePane(this._downPane,{level:i.Light,autoScale:!1}))}if(null!==this._paneResize){const e=this._paneResize,s=e.aHeight+e.bHeight,r=e.aWeight+e.bWeight,n=Math.min(24,s/4),o=Math.max(n,Math.min(s-n,e.aHeight+(t.y-e.startY)));return this._panes[e.a].weight=o/s*r,this._panes[e.b].weight=r-this._panes[e.a].weight,this._relayout(),void this.invalidate(e=>e.invalidateGlobal(i.Full))}if("time"===this._axisDrag){this._beginAutoscaleMotion();const e=t.x-this._axisStartCoord;return this._mutateTimeScale(()=>this._timeScale.setBarSpacing(this._axisStartSpacing*Math.exp(.005*-e))),this.invalidate(e=>e.invalidateGlobal(i.Full)),void this._emitViewport("zoom")}if((this._placementMode||!this._dragging)&&this._pointers.size>0&&(Math.abs(t.x-this._downX)>3||Math.abs(t.localY-this._downLocalY)>3)&&(this._pointerMoved=!0),null!==this._dragId){const i=t.y-(this._paneLayout()[this._downPane]?.top??0);(Math.abs(t.x-this._downX)>3||Math.abs(i-this._downLocalY)>3)&&(this._dragMoved=!0);const s=this._dragPriceScale?.yToPrice(i)??this._panes[this._downPane].yToPrice(i),r=this._xToTime(t.x);this._dragCb?.(this._dragId,s,r);const n={id:this._dragId,price:s,time:r,paneIndex:this._downPane,fromPrice:this._dragFrom.price,fromTime:this._dragFrom.time,point:{x:t.x,y:i},samples:this._dragSamples(e),...jn(e)};return void this.emit("drag",n)}if(this._dragging){this._beginAutoscaleMotion();const s=t.x-this._dragStartX;if((Math.abs(s)>3||Math.abs(t.y-this._dragStartY)>3)&&(this._pointerMoved=!0),this._pointerMoved&&null!==this._hoverId&&this._setHover(null),this._mutateTimeScale(()=>this._timeScale.setRightOffset(this._dragStartOffset-s/this._timeScale.barSpacing)),"touch"===e.pointerType||"both"===this._navigation.mousePan){const i=this._collapsedShown(this._downPane)?void 0:this._panes[this._downPane]?.priceScale,s=t.y-this._dragStartY;i&&("touch"===e.pointerType||!i.autoScale||Math.abs(s)>3)&&i.panByPixels("touch"!==e.pointerType&&i.autoScale?s:t.y-this._lastDragY)}this._lastDragY=t.y;const r=this._now(),n=r-this._lastDragT;if(n>0){const e=(t.x-this._lastDragX)/n,i=Math.exp(-n/50);this._dragVelocity=this._dragVelocity*i+e*(1-i)}return this._lastDragX=t.x,this._lastDragT=r,this._maybeLoadHistory(),this.invalidate(e=>e.invalidateGlobal(i.Full)),void this._emitViewport("pan")}this._updateCursor(t.pane,t.x,t.localY,t.y,e)}else(Math.abs(t.x-this._downX)>3||Math.abs(t.localY-this._downLocalY)>3||t.pane!==this._downPane||"mouse"===e.pointerType&&!(1&e.buttons))&&(this._brandingPress.moved=!0);else(Math.abs(t.x-this._downX)>3||Math.abs(t.localY-this._downLocalY)>3||t.pane!==this._downPane)&&(this._indicatorTogglePress.moved=!0)}else this._updatePinch()}}),Object.defineProperty(this,"_onPointerUp",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(this._pointers.size>0&&!this._pointers.has(e.pointerId))return;const t=this._indicatorTogglePress?.pointerId===e.pointerId?this._indicatorTogglePress:null;t&&(this._indicatorTogglePress=null),this._pointers.delete(e.pointerId);try{this._container.releasePointerCapture?.(e.pointerId)}catch{}if(this._endedPointers.has(e.pointerId))return void this._endedPointers.delete(e.pointerId);if(this._navigationCancelled)return 0===this._pointers.size&&(this._navigationCancelled=!1),void this._endedPointers.add(e.pointerId);if(t){const i=this._localPoint(e);return this._endedPointers.add(e.pointerId),void(!t.moved&&i.pane===this._downPane&&Math.abs(i.x-this._downX)<=3&&Math.abs(i.localY-this._downLocalY)<=3&&this._indicatorLegendHit(i.pane,i.x,i.localY)&&this._handleLegendAction(sn))}if(this._brandingPress?.pointerId===e.pointerId){const t=this._brandingPress;this._brandingPress=null;const i=this._localPoint(e);if(!t.moved&&t.mark===this._branding&&i.pane===this._downPane&&Math.abs(i.x-this._downX)<=3&&Math.abs(i.localY-this._downLocalY)<=3&&this._brandingHit(i.pane,i.x,i.localY)){const e=t.mark.href();e&&/^https?:\/\//i.test(e)&&this._doc.defaultView?.open(e,"_blank","noopener,noreferrer")}return void this._endedPointers.add(e.pointerId)}if(null!==this._pinch)return void(0===this._pointers.size&&(this._pinch=null,this._dragging=!1));if(null!==this._paneResize)return this._paneResize=null,void this.emit("paneResized",{paneIndex:this._downPane});if(null!==this._axisDrag)return this._axisDrag=null,void(this._axisDragScale=null);if(null!==this._dragId){const t=this._localPoint(e),s=t.y-(this._paneLayout()[this._downPane]?.top??0),r=this._dragPriceScale?.yToPrice(s)??this._panes[this._downPane].yToPrice(s),n=this._xToTime(t.x);this._dragEndCb?.(this._dragId,r,n);const o={id:this._dragId,price:r,time:n,paneIndex:this._downPane,point:{x:t.x,y:s},...jn(e)};if(this.emit("drag:end",o),!this._dragMoved){const t=this._dragId;this._clickCb?.(t);const i={id:t,price:r,time:n,paneIndex:this._downPane,point:{x:this._downX,y:this._downLocalY},...this._clickInfo(e)};this.emit("click",i)}this._dragId=null,this._dragPriceScale=null;const a="touch"===e.pointerType?null:this._panes[t.pane]?.hitTestPrimitives(t.x-this._leftAxisWidth,t.localY,this._renderContext(t.pane))??null;return this._setHover(a),void this.invalidate(e=>e.invalidateGlobal(i.Light))}const s=this._dragging;if(this._dragging=!1,this._placementMode&&this._pointerMoved){s&&this._setHover(null);const t=this._localPoint(e);this._ensureScaled(this._downPane);const i=this._clickInfo(e),r={id:null,price:this._priceAt(this._downPane,this._downLocalY),time:this._xToTime(this._downX),paneIndex:this._downPane,point:{x:this._downX,y:this._downLocalY},...i};this.emit("click",r);const n={id:null,price:this._priceAt(this._downPane,t.localY),time:this._xToTime(t.x),paneIndex:this._downPane,point:{x:t.x,y:t.localY},viaDrag:!0,...i};return void this.emit("click",n)}if(!this._pointerMoved){const t=this._panes[this._downPane]?.hitTestPrimitives(this._downX-this._leftAxisWidth,this._downLocalY,this._renderContext(this._downPane));if(s&&this._setHover("touch"===e.pointerType?null:t??null),t&&this._handleLegendAction(t.externalId))return;t&&this._clickCb?.(t.externalId),this._ensureScaled(this._downPane);const i={id:t?.externalId??null,price:this._priceAt(this._downPane,this._downLocalY),time:this._xToTime(this._downX),paneIndex:this._downPane,point:{x:this._downX,y:this._downLocalY},...this._clickInfo(e)};return void this.emit("click",i)}s&&this._setHover(null),s&&!1!==this._navigation.panEnabled&&"touch"===e.pointerType&&"pointercancel"!==e.type&&br.shouldAnimate(this._dragVelocity)&&this._startKinetic(this._dragVelocity)}}),Object.defineProperty(this,"_onPointerUpNative",{enumerable:!0,configurable:!0,writable:!0,value:e=>{("mouse"!==e.pointerType&&"pen"!==e.pointerType||0===e.button)&&this._onPointerUp(e)}}),Object.defineProperty(this,"_onPointerCancel",{enumerable:!0,configurable:!0,writable:!0,value:e=>{this._cancelPrimitiveDrag("pointercancel"),this._pointers.has(e.pointerId)&&(this._pointerMoved=!0),this._brandingPress?.pointerId===e.pointerId&&(this._brandingPress.moved=!0),this._indicatorTogglePress?.pointerId===e.pointerId&&(this._indicatorTogglePress.moved=!0),this._onPointerUp(e)}}),Object.defineProperty(this,"_onLostPointerCapture",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(this._indicatorTogglePress?.pointerId===e.pointerId)return this._indicatorTogglePress.moved=!0,void this._onPointerUp(e);this._pointers.has(e.pointerId)&&null===this._dragId&&null===this._paneResize&&null===this._brandingPress&&((null!==this._pinch||this._navigationCancelled)&&(this._navigationCancelled=!0,this._pinch=null),this._dragging=!1,this._axisDrag=null,this._axisDragScale=null,this._dragVelocity=0,this._pointerMoved=!0,this._pointers.delete(e.pointerId),0===this._pointers.size&&(this._navigationCancelled=!1),this._endedPointers.add(e.pointerId),this._setHover(null))}}),Object.defineProperty(this,"_onPointerLeave",{enumerable:!0,configurable:!0,writable:!0,value:()=>{if(this._pointerInside=!1,this._feedTimeNav(null),null===this._dragId&&this._setHover(null),null!==this._cursor){this._cursor=null,this._cursorPane=null,this.invalidate(e=>e.invalidateGlobal(i.Cursor));for(const e of this._indicators)e.updateLegendValues();const e={time:null,index:null,price:null,bar:null,point:null,paneIndex:null};this._crosshairCb?.(e),this.emit("crosshair:readout",e),this.emit("crosshair:move",e)}}}),Object.defineProperty(this,"_onWheel",{enumerable:!0,configurable:!0,writable:!0,value:e=>{const t=function(e,t,i){const s=e.deltaMode,r=e.deltaX??0,n=e.deltaY??0;return{x:Number.isFinite(r)?r*(1===s?16:2===s?t:1):0,y:Number.isFinite(n)?n*(1===s?16:2===s?i:1):0}}(e,this._width,this._height);if(0===t.x&&0===t.y)return;const s=this._localPoint(e),r=this._leftAxisWidth>0&&s.x<this._leftAxisWidth,n=this._rightAxisWidth>0&&s.x>=this._width-this._rightAxisWidth,o=!r&&!n&&!e.ctrlKey&&!e.metaKey&&(e.shiftKey||Math.abs(t.x)>Math.abs(t.y));if(o?!1===this._navigation.panEnabled:!1===this._navigation.zoomEnabled)return;if(!o&&0===t.y)return;if(this._unfreezeOverlay(),e.preventDefault(),this._stopKinetic(),r||n){if(0===t.y)return;const e=this._axisAt(s.pane,s.x);if(!e)return;this._stopZoomGlide();return this._panes[s.pane].scaleFor(e.scaleId).scaleAtY(s.localY,Math.exp(-yr(t.y))),void this.invalidate(e=>e.invalidateGlobal(i.Full))}if(o)return this._stopZoomGlide(),this._beginAutoscaleMotion(),this._mutateTimeScale(()=>this._timeScale.scrollByPixels(-(e.shiftKey&&0===t.x?t.y:t.x))),this._maybeLoadHistory(),this.invalidate(e=>e.invalidateGlobal(i.Full)),void this._emitViewport("pan");if(0===t.y)return;const a="right"!==this._zoomAnchor||e.ctrlKey||e.metaKey?Math.max(0,Math.min(this._timeScale.width,s.x-this._leftAxisWidth)):this._timeScale.width,l=null===this._zoomGlide?0:this._zoomGlide.totalLogFactor-this._zoomGlideApplied,h=this._timeScale.barSpacing,c=this._timeScale.constrainBarSpacing(h*Math.exp(l+yr(t.y))),d=Math.log(c/h);if(this._stopZoomGlide(),0===d)return;if(!this._animZoom||!vr.shouldAnimate(d))return void this._applyZoom(a,d);const u=d*vr.leadFraction(),p=this._navigationEpoch;this._applyZoom(a,u),this._destroyed||p!==this._navigationEpoch||this._startZoomGlide(a,d-u)}}),Object.defineProperty(this,"_onDblClick",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(this._lastPressOnIndicatorToggle||this._previousPressOnIndicatorToggle)return;const t=this._localPoint(e);if(this._indicatorLegendHit(t.pane,t.x,t.localY))return;if(this._brandingHit(t.pane,t.x,t.localY))return;const i={paneIndex:t.pane,x:t.x,y:t.y,handled:!1};this.emit("dblclick",i),this._placementMode||i.handled||("reset"===this._doubleClick&&!1!==this._navigation.zoomEnabled?this.resetScale():"maximize"===this._doubleClick&&this.maximizePane(t.pane))}}),Object.defineProperty(this,"_onKeyDown",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(this._unfreezeOverlay(),"Escape"===e.key&&this._dragCancelOnEscape&&null!==this._dragId&&!Nr.shouldIgnore(e.target)){this._cancelPrimitiveDrag("escape"),this._dragId=null,this._dragPriceScale=null,this._dragging=!1,this._pointerMoved=!0;for(const e of this._pointers.keys())this._endedPointers.add(e);return this._pointers.clear(),this._setHover(null),this.invalidate(e=>e.invalidateGlobal(i.Light)),void e.preventDefault()}const t=this._shortcuts;if(null===t||Nr.shouldIgnore(e.target)||!this._shortcutsActive())return;const s=t.resolve(e);if(null===s)return;if(!this._navigationAllowed(s))return;let r=this._runShortcut(s);r||(r=t.runCustom(s)),r&&(e.preventDefault(),t.emitTrigger(s),this._maybeLoadHistory(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._updateAccessibleSummary())}}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_destroying",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._timeScale=new w(t.timeScale),this._container=e,this._doc=t.document??e.ownerDocument,this._pixelRatio=t.pixelRatio??Rn,this._theme=t.theme??ti,this._priceAxisWidth=t.priceAxisWidth??56,this._rightAxisWidth=this._priceAxisWidth,void 0!==t.legendOffset?.top&&(this._legendOffset.top=t.legendOffset.top),void 0!==t.legendOffset?.left&&(this._legendOffset.left=t.legendOffset.left),this._timeAxisHeight=t.timeAxisHeight??22,this._crosshairMode=t.crosshairMode??"normal",this._crosshairSnapToBar=!0===t.crosshairSnapToBar,this._priceOnlyAutoScale=!0===t.priceOnlyAutoScale,this._indicatorLegendCollapsed=!0===t.indicatorLegendCollapsed,Object.assign(this._axisChrome,t.axisChrome),"object"==typeof t.axisChrome?.sessionClock&&(this._sessionClockForm={...t.axisChrome.sessionClock}),void 0!==t.axisChrome?.clock&&(this._wallClock=t.axisChrome.clock);const s=t.shortcuts;this._shortcuts=!1===s?null:s instanceof Nr?s:new Nr(s??{}),this._now=t.now??(()=>"undefined"!=typeof performance?performance.now():0),this._animZoom=t.animZoom??!0,this._barsProvider=t.barsProvider??null,this._animAutoscale=t.animAutoscale??this._animZoom,this._zoomAnchor=t.zoomAnchor??"cursor",this._doubleClick=t.doubleClick??"reset",this._conflate=t.conflate??!1,this._conflationFactor=t.conflationFactor??1,this._backendFactory=t.renderBackend??Kt(t.renderer??"canvas2d"),this._requestedRenderer=void 0===t.renderBackend?t.renderer??"canvas2d":null,this._priceFormatter=t.priceFormatter??null,this._priceScaleOptions=t.priceScale??null,this._timeFormatter=t.timeFormatter,void 0!==t.timezone&&(this._timezone=Tn(t.timezone)),this._gridVert=t.grid?.vertLines??!0,this._gridHorz=t.grid?.horzLines??!0,Object.assign(this._canvas,t.canvas),t.grid&&(this._canvas.grid={...this._canvas.grid,...t.grid}),Object.assign(this._statusLine,t.statusLine),"number"==typeof t.legendIconSize&&Number.isFinite(t.legendIconSize)&&(this._legendIconSize=t.legendIconSize);const r=R(this._canvas.margins);void 0===r.marginTop&&void 0===r.marginBottom||(this._priceScaleOptions={...this._priceScaleOptions,...r}),this._patchNavigation(t.navigation??{});const o=t.timeNavigator??!0;!1!==o&&(this._timeNav=new bn({...!0===o?{}:o,hints:this._navHints(!0===o?void 0:o)},this._now),this._timeNavButtons=[...this._timeNav.options().buttons],this._syncNavigatorPolicy());const a="function"==typeof getComputedStyle?getComputedStyle(e).position:e.style.position;a&&"static"!==a||(e.style.position="relative"),e.style.display="flex",e.style.flexDirection="column",e.style.background=this._theme.background,e.style.touchAction="none",e.getAttribute("role")||e.setAttribute("role","application"),e.setAttribute("aria-label",t.ariaLabel??"Interactive financial chart"),e.hasAttribute("tabindex")||(e.tabIndex=0);const l=this._doc.createElement("div");l.setAttribute("aria-live","polite");const h=l.style;var c;h.position="absolute",h.width="1px",h.height="1px",h.overflow="hidden",h.clip="rect(0 0 0 0)",h.whiteSpace="nowrap",h.border="0",h.padding="0",h.margin="-1px",e.appendChild(l),this._liveRegion=l,this._raf=(c=t.raf)?{schedule:c.schedule,cancel:c.cancel??(()=>{})}:"function"==typeof requestAnimationFrame?{schedule:e=>requestAnimationFrame(e),cancel:e=>cancelAnimationFrame(e)}:{schedule:e=>setTimeout(e,16),cancel:e=>clearTimeout(e)},this._loop=new n(()=>this._onFrame(),this._raf.schedule,this._raf.cancel),this._addPane(),this.setBranding(t.branding??!0),this.setWatermarkOptions(t.watermark??!1),this._observeSize(),this._attachInput(),this._timeScale.setChangeHandler(e=>{if(this._timeScaleMutationDepth>0||this._destroyed)return;this._stopNavigationMotion();const t=this._timeScale.visibleRange();t.from===e.from&&t.to===e.to||(this.invalidate(e=>e.invalidateGlobal(i.Full)),this._emitViewportIfMoved(e))}),this.applySize(e.clientWidth,e.clientHeight),this._remeasureHandle=this._raf.schedule(()=>{this._remeasureHandle=null,this._remeasure()}),"function"==typeof queueMicrotask&&queueMicrotask(()=>this.emit("ready",{}))}setHistoryLoader(e){this._historyLoader=e}historyLoadComplete(){this._loadingHistory=!1}get dataLayer(){return this._dataLayer}primaryBars(){const e=this._firstDataId.value;return null===e?[]:this._dataLayer.seriesBars(e)}get timeScale(){return this._timeScale}setVisibleLogicalRange(e){this._stopNavigationMotion(),this._timeScale.setVisibleLogicalRange(e)}getVisibleLogicalRange(){return this._timeScale.visibleRange()}fitContent(){this._stopNavigationMotion(),this._dataLayer.length<=0||this._timeScale.fitContent(this._dataLayer.length)}navigationOptions(){return{...this._navigation}}setNavigationOptions(e){const t=this._navigation.defaultVisibleBars,i=this._navigation.defaultBarSpacing,s=this._navigation.panEnabled,r=this._navigation.zoomEnabled;this._patchNavigation(e),t===this._navigation.defaultVisibleBars&&i===this._navigation.defaultBarSpacing||this.resetScale(),s===this._navigation.panEnabled&&r===this._navigation.zoomEnabled||this.emit("objects:change",void 0)}_patchNavigation(e){const t=this._navigation.panEnabled,i=this._navigation.zoomEnabled;for(const t of["panEnabled","zoomEnabled"]){const i=Object.getOwnPropertyDescriptor(e,t);i&&"value"in i&&"boolean"==typeof i.value&&(this._navigation[t]=i.value)}const s=!1!==t&&!1===this._navigation.panEnabled,r=!1!==i&&!1===this._navigation.zoomEnabled;(s||r)&&(r&&this._navigationEpoch++,s&&this._stopKinetic(),r&&this._stopZoomGlide(),this._autoscaleTime=null,(null!==this._pinch||s&&this._dragging||r&&("price"===this._axisDrag||"time"===this._axisDrag))&&(this._navigationCancelled=!0,this._dragging=!1,this._axisDrag=null,this._axisDragScale=null,this._pinch=null,this._pointerMoved=!0,this._dragVelocity=0,this._setHover(null))),t===this._navigation.panEnabled&&i===this._navigation.zoomEnabled||this._syncNavigatorPolicy(),"horizontal"!==e.mousePan&&"both"!==e.mousePan||(this._navigation.mousePan=e.mousePan);const n=e.defaultVisibleBars;"number"==typeof n&&Number.isFinite(n)&&n>=0&&(this._navigation.defaultVisibleBars=Math.min(1e5,Math.floor(n)),void 0===e.defaultBarSpacing&&delete this._navigation.defaultBarSpacing);const o=e.defaultBarSpacing;"number"==typeof o&&Number.isFinite(o)&&o>=0&&(0===o?delete this._navigation.defaultBarSpacing:this._navigation.defaultBarSpacing=o)}_navigationAllowed(e){switch(e){case"panLeftBar":case"panRightBar":case"panLeft":case"panRight":case"panLeftFast":case"panRightFast":case"panUp":case"panDown":return!1!==this._navigation.panEnabled;case"zoomIn":case"zoomOut":case"resetScale":case"fitContent":return!1!==this._navigation.zoomEnabled;default:return!0}}_syncNavigatorPolicy(){if(null===this._timeNav)return;if(this._timeNavButtons.every(e=>null===e||this._navigationAllowed(e)))return void this._timeNav.setOptions({buttons:[...this._timeNavButtons]});const e=[];let t=!1;for(const i of this._timeNavButtons)null!==i?this._navigationAllowed(i)&&(t&&e.length>0&&e.push(null),e.push(i),t=!1):t=!0;this._timeNav.setOptions({buttons:e})}_fitDefaultView(){const e=this._dataLayer.length;return!(e<=0)&&this._timeScale.width>0&&(this._mutateTimeScale(()=>{if(this._timeScale.fitContent(e),void 0!==this._navigation.defaultBarSpacing)this._timeScale.setBarSpacing(this._navigation.defaultBarSpacing);else if(this._navigation.defaultVisibleBars>0){const t=Math.min(e,this._navigation.defaultVisibleBars);this._timeScale.setBarSpacing(this._timeScale.width/(t+this._timeScale.rightOffset))}}),!0)}get shortcuts(){return this._shortcuts}get trading(){return null===this._trading&&(this._trading=new Gr(this),this._trading.setSettings(this._tradingSettings)),this._trading}hasTrading(){return null!==this._trading}tradingSettings(){if(null!==this._trading)return this._trading.getSettings();const e={...Br};for(const[t,i]of Object.entries(this._tradingSettings))"string"==typeof i&&(e[t.slice(0,-5)]=i);return e}setTradingSettings(e){Object.assign(this._tradingSettings,e),this._trading?.setSettings(e)}addSeries(e,t={}){return this._createSeries(e,t,!0)}seriesType(e){const t=this._seriesRecords.get(e),i=this._seriesOwners.get(e);return!this._destroyed&&t&&i&&this._panes.includes(i.pane)&&i.pane.series().includes(t)?t.type:null}seriesStyle(e){return null===this.seriesType(e)?null:Object.freeze({...this._seriesRecords.get(e).style})}setSeriesPriceScale(e,t){if("string"!=typeof t||"right"!==t&&"left"!==t&&""!==t&&!t.startsWith("overlay:")||null===this.seriesType(e))return!1;const s=this._seriesRecords.get(e),r=this._seriesOwners.get(e);if(r.indicatorOwned||s.scaleId===t)return!1;const n=r.pane.scaleFor(t);return s.scaleId=t,this._reconcileIndicatorRanges(),this._applySeriesPriceFormat(n,r.priceFormat),void 0!==s.style.precision&&this._applyPrecision(n,s.style.precision),this._recomputeAxisColumns(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this.emit("objects:change",{}),!0}setSeriesType(e,t){return this._setSeriesType(e,t,!0)}_setSeriesType(e,t,s){if(null===this.seriesType(e))return!1;const r=this._seriesRecords.get(e),n=this._seriesOwners.get(e),o=le(t);if(r.type===t)return!1;const a=r.style.precision,l={...r.style};for(const e of Object.keys(n.inheritedStyle))l[e]===n.inheritedStyle[e]&&delete l[e];const h={};for(const e of Object.keys(o.defaultStyle))Object.prototype.hasOwnProperty.call(l,e)||Object.assign(h,{[e]:o.defaultStyle[e]});for(const e of Object.keys(r.style))delete r.style[e];if(Object.assign(r.style,h,l),n.inheritedStyle=h,r.type=t,r.style.precision!==a){const e=n.pane.scaleOf(r);this._applyPrecision(e,r.style.precision),void 0===r.style.precision&&this._applySeriesPriceFormat(e,n.priceFormat)}return this.invalidate(e=>e.invalidateGlobal(i.Full)),s&&this.emit("objects:change",{}),!0}_createSeries(e,t,s,r){const n=this._dataLayer.createSeries(),o=new ui(n);this._seriesProvenance.set(n,o);const a=t.paneIndex??0;this._ensurePane(a);const l=function(e,t,i,s="right"){return{dataId:e,type:t,style:{...le(t).defaultStyle,...i},scaleId:s}}(n,e,t.style,t.priceScaleId??"right");s&&le(e).isPriceSeries&&this._claimPricePane(this._panes[a]);const h=s&&null===this._firstDataId.value&&le(e).isPriceSeries;h&&(this._firstDataId.value=n,this._firstPaneIndex=a),this._panes[a].addSeries(l),this._recomputeAxisColumns();const c={...le(e).defaultStyle};for(const e of Object.keys(t.style??{}))delete c[e];const d={pane:this._panes[a],priceFormat:t.priceFormat,inheritedStyle:c,indicatorOwned:!s},u=d.pane.scaleOf(l),p=!0===r?.get(d.pane)?.has(l.scaleId);this._applySeriesPriceFormat(u,t.priceFormat,p),p||void 0===l.style.precision||this._applyPrecision(u,l.style.precision);const _={setData:(e,t)=>this._setData(n,e.map(fr),t),prependData:e=>this._prependData(n,e.map(fr)),update:(e,t)=>this._updateBar(n,fr(e),t),getData:()=>this._dataLayer.indexedBars(n).map(e=>e.bar),applyOptions:e=>{for(const t of Object.keys(e))delete d.inheritedStyle[t];Object.assign(l.style,e),"precision"in e&&this._applyPrecision(d.pane.scaleOf(l),e.precision),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._primary?.record===l&&this.emit("objects:change",{})},remove:()=>{const e=this._primary?.record===l;d.pane.removeSeries(l),this._dataLayer.removeSeries(n),this._seriesProvenance.delete(n),this._firstDataId.value===n&&(this._firstDataId.value=null),this._primary?.record===l&&(this._primary=null),d.indicatorOwned||this._reconcileIndicatorRanges(),this._timeScale.setBaseIndex(this._dataLayer.baseIndex),this._recomputeAxisColumns(),this.invalidate(e=>e.invalidateGlobal(i.Full)),e&&(this.emit("data:update",{kind:"reset"}),this.emit("objects:change",{}))},priceScale:()=>d.pane.scaleOf(l),createMarkers:e=>{const t=new ns(n,e,()=>d.pane.scaleOf(l));return this._addPrimitive(this._panes.indexOf(d.pane),t),t}};var f,m;return this._seriesRecords.set(_,l),f=_,m=o,pi.set(f,m),this._seriesOwners.set(_,d),d.indicatorOwned||this._reconcileIndicatorRanges(),h&&(this._primary={api:_,record:l},this.emit("objects:change",{})),_}_applySeriesPriceFormat(e,t,i=!1){if(t)if("custom"===t.type)i||e.setPriceFormatter(t.formatter);else if("volume"===t.type)i||e.setPriceFormatter(Cn);else if("percent"===t.type){const s=t.precision??2;i||e.setPriceFormatter(e=>`${e.toFixed(s)}%`)}else{i||e.setPriceFormatter(this._priceFormatter);const s=t.minMove??(void 0!==t.precision?Math.pow(10,-t.precision):void 0);void 0!==s&&e.setOptions({minMove:s})}}primarySeries(){return this._primary?.api??null}primarySeriesInfo(){const e=this._primary;return null===e?null:{type:e.record.type,style:e.record.style}}_applyPrecision(e,t){if(void 0===t||!isFinite(t))return void e.setPriceFormatter(this._priceFormatter);const i=h(Math.round(t),0,8);e.setPriceFormatter(e=>e.toFixed(i))}addPriceLine(e,t=0){const i=new Er(e);return this._addPrimitive(t,i),i}addEventMarkers(e=0,t={}){const i=new tn(t);return this._addPrimitive(e,i),i}setEvents(e,t=0){const i=this._ensureEventMarkers();i.setEvents(e),this._events=i.events(),t!==this._eventPane&&(this.removePrimitive(i),this._addPrimitive(t,i)),this._eventPane=t,this._syncEvents()}eventMarkers(){return this._eventMarkers}setEventMarkerOptions(e){this._ensureEventMarkers().setOptions(e)}setEventGroups(e){this._ensureEventMarkers().setGroups(e),this.emit("events:change",void 0)}setEventGroupVisible(e,t){this._ensureEventMarkers().setGroupVisible(e,t),this.emit("events:change",void 0)}setEventOptions(e){Object.assign(this._eventVisible,e),this._syncEvents()}eventOptions(){return{...this._eventVisible}}_ensureEventMarkers(){return null===this._eventMarkers&&(this._eventMarkers=new tn,this._addPrimitive(this._eventPane,this._eventMarkers),this.on("click",e=>{const t=e;if(!t.id||t.viaDrag||t.paneIndex!==this._eventPane)return;const i=this._eventMarkers?.detailsForHit(t.id);i&&this.emit("event:click",{...i,point:{x:t.point.x,y:t.point.y+(this._paneLayout()[t.paneIndex]?.top??0)},paneIndex:t.paneIndex})})),this._eventMarkers}_syncEvents(){if(null===this._eventMarkers&&0===this._events.length)return;const e=this._eventVisible;this._ensureEventMarkers().setEvents(this._events.filter(t=>!1!==e[t.type])),this.emit("events:change",void 0)}addIndicator(e,t={},i={}){if(void 0!==i.priceScaleId&&!this._validPriceScaleId(i.priceScaleId))throw new TypeError("Invalid indicator price scale");const s=Bi(e),r=ki(t);ji(s.inputs,r);const n=void 0===i.plotPriceScaleIds?void 0:$s(s,i.plotPriceScaleIds);Vs(s,i.priceScaleId,n,i.paneIndex??("onchart"===s.placement?0:this._panes.length)),this._flushIndicators();const o=new Set([...this._indicatorReservedIds,...this._indicators.map(e=>e.id)]);for(const e of Ti(this._indicators.map(e=>e.dependencyNode())).dependencies.values())for(const t of e)o.add(t.source.instanceId);const a=new Js(this._indicatorHost(),s,this._distinctColors(s,r),i.paneIndex,void 0,o,i.priceScaleId,n);return this._indicators.push(a),this._restackLegends(),this._indicatorReservedIds.add(a.id),this._queueIndicatorDependents(a.id,!0),this.emit("objects:change",{}),a}_distinctColors(e,t){const i=this._indicators.filter(t=>t.indicatorId===e.id).length;if(0===i)return t;const s={...t},r=e.plots;for(let e=0;e<r.length;e++){const t=Li(r[e]).color;void 0===s[t]&&(s[t]=Mn[(i*r.length+e)%Mn.length])}return s}indicators(){return this._flushIndicators(),this._indicators}moveIndicator(e,t){const s=this._indicators.find(t=>t.id===e);if(this.isDestroyed||!s||!Number.isInteger(t)||t<0||t>this._panes.length||s.paneIndex===t||!s.canRelocate(t))return!1;const r=s.paneIndex,n=t===this._panes.length;this._ensurePane(t);const o=this._panes[t],a=s.renderResources();for(const{api:e,overlay:t}of a.series){if(t)continue;const i=this._seriesOwners.get(e),s=this._seriesRecords.get(e);if(!i||!s||i.pane===o)continue;const r=i.pane.scaleOf(s).options;i.pane.removeSeries(s),o.addSeries(s),i.pane=o,n&&1===o.series().filter(e=>e.scaleId===s.scaleId).length&&o.scaleOf(s).setOptions(r),this._applySeriesPriceFormat(o.scaleOf(s),i.priceFormat),void 0!==s.style.precision&&this._applyPrecision(o.scaleOf(s),s.style.precision)}for(const{primitive:e,overlay:t}of a.primitives)t||this._panes.find(t=>t.hasPrimitive(e))?.transferPrimitive(e,o);s.relocate(t),this._syncLegendPanes(),this.emit("objects:change",{});const l=this._panes[r];return r>0&&0===l.series().length&&l.primitives().every(e=>e===this._timeNav||this._anchored.some(t=>t.primitive===e))&&this.removePane(r),this._reorderIndicatorResources(),this._recomputeAxisColumns(),this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this.emit("objects:change",{}),!0}reorderIndicator(e,t){if(-1!==t&&1!==t)return!1;const s=this._indicators.findIndex(t=>t.id===e);if(this.isDestroyed||s<0)return!1;const r=this._indicators[s].paneIndex;let n=s+t;for(;n>=0&&n<this._indicators.length&&this._indicators[n].paneIndex!==r;)n+=t;return!(n<0||n>=this._indicators.length)&&([this._indicators[s],this._indicators[n]]=[this._indicators[n],this._indicators[s]],this._reorderIndicatorResources(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this.emit("objects:change",{}),!0)}_reorderIndicatorResources(){for(const e of this._indicators)e.refreshBarColors();const e=this._indicators.map(e=>e.renderResources()),t=e.flatMap(e=>e.series.flatMap(({api:e})=>{const t=this._seriesRecords.get(e);return t?[t]:[]})),i=e.flatMap(e=>e.primitives.map(e=>e.primitive));for(const e of this._panes)e.reorderSeries(t),e.reorderPrimitives(i);const s=this._indicators.flatMap(e=>e.legend()?[e.legend()]:[]),r=new Set(s);let n=0;for(const e of this._legends)r.has(e.legend)&&(e.legend=s[n++]);this._syncLegendPanes()}_syncLegendPanes(){for(const e of this._legends)e.paneIndex=this._panes.findIndex(t=>t.hasPrimitive(e.legend));this._restackLegends()}removeIndicator(e){const t=this._indicators.find(t=>t.id===e);return void 0!==t&&(t.remove(),!0)}_forgetIndicator(e,t){const i=this._indicators.findIndex(t=>t.id===e);if(i<0){const e=void 0===t?void 0:this._panes[t];return void(void 0!==t&&t>0&&0===e?.series().length&&e.primitives().every(e=>e===this._timeNav||this._anchored.some(t=>t.primitive===e))&&this.removePane(t))}const{indicatorId:s,paneIndex:r}=this._indicators[i];this._indicators.splice(i,1),this._restackLegends(),this._indicatorReservedIds.add(e),this._indicatorRefreshes.delete(e),this._queueIndicatorDependents(e,!0),this.emit("indicatorRemoved",{instanceId:e,indicatorId:s,paneIndex:r}),r>0&&0===this._panes[r]?.series().length&&this.removePane(r)}getDataContext(){return this._dataContext}get hasOpenInterest(){return this._dataContext?.hasOpenInterest}setDataContext(e){if(this._dataContext?.symbol===e?.symbol&&this._dataContext?.exchange===e?.exchange&&this._dataContext?.hasOpenInterest===e?.hasOpenInterest&&this._dataContext?.interval===e?.interval&&!!this._dataContext==!!e)return;const t=this._dataContext?.symbol!==e?.symbol||this._dataContext?.exchange!==e?.exchange,i=t||this._dataContext?.interval!==e?.interval;if(this._dataContext=e?Object.freeze({...e}):void 0,i&&this._cancelBarsRequests(),i)for(const e of this._seriesProvenance.values())e.contextChanged();this._indicators.length>0&&(this._indicatorsDirty=!0,this._loop.requestFrame()),t&&this._events.length&&(this._events=[],this._syncEvents());for(const e of this._legends)e.legend.setOptions({hasOpenInterest:this.hasOpenInterest});this._syncWatermark(),this.emit("data:context",this._dataContext)}setBarsProvider(e){this._destroyed||this._destroying||e===this._barsProvider||(this._barsProvider=e,this._barsProviderRevision++,this._cancelBarsRequests(),this.emit("data:requests",{}))}_cancelBarsRequests(){if(this._destroying)return;const e=this._barsRequests;this._barsRequests=new AbortController,e.abort()}invalidateRequestedData(){this._destroyed||this._destroying||(this._requestedDataRevision++,this.emit("data:requests",{}))}hasSnapshotProvider(){return"object"==typeof this._barsProvider&&null!==this._barsProvider&&"function"==typeof this._barsProvider.requestSnapshot}hasBarsProvider(){return null!==this._barsProvider}setBranding(e){null!==this._branding&&this.removePrimitive(this._branding),this._branding=null,this._brandingOptions=!1!==e&&{position:"bottom-left",margin:14,opacity:1,padding:8,label:"Chart by OpenAlgo",href:"https://openalgo.in",id:"chart-branding",...!0===e?{}:e},!1!==this._brandingOptions&&("object"==typeof this._brandingOptions.padding&&(this._brandingOptions.padding={...this._brandingOptions.padding}),this._branding=new Sn(this._brandingOptions),this.addPrimitive(this._branding,{anchor:"chart-bottom"})),this.invalidate(e=>e.invalidateGlobal(i.Light)),this.emit("branding:changed",this.brandingOptions())}brandingOptions(){const e=this._brandingOptions;return!1!==e&&{...e,..."object"==typeof e.padding?{padding:{...e.padding}}:{}}}setWatermarkOptions(e){const t="boolean"==typeof e?{visible:e}:e;if(null===t||"object"!=typeof t)return;const i=this._watermarkOptions;"boolean"==typeof t.visible&&(i.visible=t.visible);for(const e of["text","color","font","id"])"string"==typeof t[e]&&(i[e]=t[e]);"number"==typeof t.opacity&&Number.isFinite(t.opacity)&&(i.opacity=Math.max(0,Math.min(1,t.opacity))),"number"==typeof t.fontSize&&Number.isFinite(t.fontSize)&&(i.fontSize=Math.max(10,Math.min(200,t.fontSize))),"bottom"!==t.zOrder&&"normal"!==t.zOrder&&"top"!==t.zOrder||(i.zOrder=t.zOrder),this._syncWatermark()}watermarkOptions(){return{...this._watermarkOptions}}_syncWatermark(){const e=this._watermarkOptions;if(!e.visible)return null!==this._watermark&&this.removePrimitive(this._watermark),void(this._watermark=null);const t=e.text?.trim()?e.text:[this._dataContext?.symbol,this._dataContext?.interval].filter(Boolean).join(" ");null===this._watermark?(this._watermark=new On({...e,text:t}),this.addPrimitive(this._watermark,{anchor:"chart-top"})):this._watermark.setOptions({...e,text:t}),this.invalidate(e=>e.invalidateGlobal(i.Light))}_indicatorHost(e){return{assignIndicatorScale:(e,t,i,s)=>this._assignIndicatorScale(e,t,i,s),bindIndicatorPrimitiveScale:(e,t)=>{this._panes.find(t=>t.hasPrimitive(e))?.bindPrimitiveScale(e,t),this._recomputeAxisColumns(),this.invalidate(e=>e.invalidateGlobal(i.Full))},setIndicatorRange:(e,t,i,s,r)=>{const n=this._indicatorRanges.get(e),o=this._panes[t];s&&o?this._indicatorRanges.set(e,{pane:o,scaleId:i,range:s,series:r,token:n?.token??{}}):this._indicatorRanges.delete(e),this._reconcileIndicatorRanges()},legendIndex:()=>this._readoutIndex(),indicatorRemoved:(e,t)=>this._forgetIndicator(e,t),flushIndicators:()=>this._flushIndicators(),validateIndicatorSettings:(e,t,i)=>{const s=this._indicators.filter(t=>t.id!==e).map(e=>e.dependencyNode());s.push({id:e,descriptor:t,settings:i}),Ti(s)},studyOutput:e=>this._indicators.find(t=>t.id===e.instanceId)?.studyOutput(e.plotKey),indicatorOutputChanged:(e,t)=>this._queueIndicatorDependents(e,t),indicatorRecompute:(e,t,i)=>{if(!this._indicators.some(t=>t.id===e))return void i();if(this._recomputing)return i(),this._indicatorWork?.delete(e),void this._indicatorProcessed?.add(e);this._indicatorRefreshes.set(e,t||!0===this._indicatorRefreshes.get(e)),this._queueIndicatorDependents(e,t);const s=this._indicatorsDirty;this._flushIndicators(),s&&(this._indicatorsDirty=!0,this._loop.requestFrame())},resourcesChanged:()=>this._reorderIndicatorResources(),formatPrice:(e,t,i)=>(i?.priceScale()??this._panes[e]?.priceScale)?.format(t),addIndicatorLegend:e=>{const t=["hide","settings","close"];!0===e.hasSource&&t.splice(t.indexOf("settings")+1,0,"source");const i=new Wt({...e,actions:t});return this._studyLegends.add(i),this._addPrimitive(e.paneIndex,i),i},removeIndicatorLegend:e=>{this._studyLegends.delete(e),this.removePrimitive(e),this._restackLegends()},legendRowsOn:e=>this._legends.filter(t=>t.paneIndex===e).length,primarySeries:()=>this.primarySeries(),setIndicatorSeriesType:(e,t)=>this._setSeriesType(e,t,!1),addIndicatorSeries:(t,i,s,r,n)=>this._createSeries(t,{paneIndex:i,style:s,priceScaleId:r,priceFormat:n},!1,e),addIndicatorLevel:(e,t)=>{const i={price:e.price,color:e.color,lineWidth:e.lineWidth,dashed:e.dashed,lineStyle:e.lineStyle,leftLabel:e.label,id:e.id};return this.addPriceLine(i,t)},removeIndicatorLevel:e=>this.removePrimitive(e),addIndicatorFill:(e,t)=>this._addPrimitive(t,e),removeIndicatorFill:e=>this.removePrimitive(e),removeIndicatorMarkers:e=>this.removePrimitive(e),addIndicatorPrimitive:(e,t)=>this._addPrimitive(t,e),removeIndicatorPrimitive:e=>this.removePrimitive(e),addIndicatorTable:e=>{const t=new _n;return this._addPrimitive(e,t),t},removeIndicatorTable:e=>this.removePrimitive(e),sourceBars:()=>null===this._firstDataId.value?[]:this._dataLayer.seriesBars(this._firstDataId.value),sourceState:()=>{const e=this._seriesProvenance.get(this._firstDataId.value??-1)?.snapshot(),t=bi(this);return e&&t?{...e,provenance:"replay",confirmation:t.forming?"forming":"confirmed",confirmationSource:"replay"}:e},nextPaneIndex:()=>this._panes.length,timezone:()=>this._timezone,now:()=>this._wallClock(),symbol:()=>this._dataContext?.symbol,interval:()=>this._dataContext?.interval,dataContext:()=>this._dataContext,requestBars:e=>{const t=this._barsProvider;return null===t?Promise.reject(new Error("openalgo-charts: this chart has no bars provider; call chart.setBarsProvider(...) to serve other instruments")):wi(i=>"function"==typeof t?t({...e,signal:i}):t.requestBars({...e,signal:i}),[e.signal,this._barsRequests.signal])},requestSnapshot:e=>{const t=this._barsProvider;return wi(i=>{if("object"!=typeof t||void 0===t?.requestSnapshot)throw new Error("Requested snapshots are unsupported by this provider");const s=bi(this);if(s&&void 0===s.asOf)throw new Error("Requested snapshots require an availability clock during replay");if(void 0!==e.asOf&&!Number.isFinite(e.asOf))throw new RangeError("Requested availability time must be finite");const r=void 0===s?.asOf?e.asOf:Math.min(e.asOf??1/0,s.asOf);return t.requestSnapshot({...e,...void 0===r?{}:{asOf:r},signal:i})},[e.signal,this._barsRequests.signal])},requestState:()=>({source:this._seriesProvenance.get(this._firstDataId.value??-1)?.snapshot(),providerRevision:this._barsProviderRevision,dataRevision:this._requestedDataRevision,supportsSnapshots:this.hasSnapshotProvider(),replay:bi(this)}),subscribeRequestChanges:e=>{const t=["data:context","data:range","data:requests"].map(t=>this.on(t,e));return t.push(yi(this,e)),()=>{for(const e of t)e()}},subscribeDataChanges:e=>{const t=this.on("data:context",()=>e("context")),i=this.on("data:range",()=>e("range"));return()=>{t(),i()}},tickSize:e=>{const t=this._panes[e]??this._panes[0],i=t?.priceScale.options.minMove??0;return i>0?i:void 0},setBarColors:(e,t)=>this._setBarColors(e,t),emit:(e,t)=>this.emit(e,t),setPaneRange:(e,t)=>{const i=this._panes[e];if(void 0===i)return;const s=0===e||this._indicators.filter(t=>t.paneIndex===e).length>1;i.priceScale.setFixedRange(s?null:t),null===t&&i.priceScale.setAutoScale(!0)}}}_validPriceScaleId(e){return"string"==typeof e&&("right"===e||"left"===e||""===e||e.startsWith("overlay:"))}_assignIndicatorScale(e,t,s,r){if(this._destroyed||!this._indicators.some(t=>t.id===e))return!1;for(const e of t)if(!this._validPriceScaleId(e.scaleId)||null===this.seriesType(e.api))return!1;for(const e of s)if(!this._validPriceScaleId(e.scaleId)||!this._panes.some(t=>t.hasPrimitive(e.primitive)))return!1;this._scaleMutationDepth++;try{for(const{api:e,scaleId:i}of t){const t=this._seriesRecords.get(e),s=this._seriesOwners.get(e),r=s.pane.scaleFor(i);t.scaleId=i,this._applySeriesPriceFormat(r,s.priceFormat),void 0!==t.style.precision&&this._applyPrecision(r,t.style.precision)}for(const{primitive:e,scaleId:t}of s)this._panes.find(t=>t.hasPrimitive(e)).bindPrimitiveScale(e,t);r(),this._recomputeAxisColumns()}finally{this._scaleMutationDepth--,this.invalidate(e=>e.invalidateGlobal(i.Full))}return this.emit("objects:change",{}),!0}_reconcileIndicatorRanges(){const e=new Map;for(const t of this._indicatorRanges.values()){if(!this._panes.includes(t.pane))continue;const i=t.pane.scaleFor(t.scaleId);if(e.has(i))continue;const s=[...this._indicatorRanges.values()].filter(e=>e.pane===t.pane&&e.scaleId===t.scaleId&&e.range.min===t.range.min&&e.range.max===t.range.max),r=new Set(s.flatMap(e=>e.series.flatMap(e=>{const t=this._seriesRecords.get(e);return t?[t]:[]})));t.pane.series().some(e=>e.scaleId===t.scaleId&&!r.has(e))||e.set(i,t)}for(const[t,i]of this._ownedScaleRanges)e.has(t)||(t.clearOwnedFixedRange(i),this._ownedScaleRanges.delete(t));for(const[t,i]of e){const e=this._ownedScaleRanges.get(t)??i.token;t.setOwnedFixedRange(e,i.range)?this._ownedScaleRanges.set(t,e):t.ownsFixedRange(e)||this._ownedScaleRanges.delete(t)}}_setBarColors(e,t){if(null===e){if(this._barColorOwner!==t)return;this._barColorOwner=null}else this._barColorOwner=t;this._barColors=e,this._applyBarColors()}_applyBarColors(){const e=this._firstDataId.value;if(null===e)return;const t=this._dataLayer.seriesBars(e),s=t.length,r=this._barColorBase;(s<r.length||r.length>0&&t[0].time!==this._barColorAnchor)&&(r.length=0),0===r.length&&(this._barColorAnchor=s>0?t[0].time:0);for(let e=r.length;e<s;e++)r[e]=t[e].color;const n=this._barColors,o=new Array(s);let a=!1;for(let e=0;e<s;e++){const i=t[e],s=n?.[e]??r[e];s!==i.color?(o[e]={...i,color:s},a=!0):o[e]=i}a&&(this._dataLayer.setSeriesData(e,o),this.invalidate(e=>e.invalidateGlobal(i.Light)))}_invalidateIndicators(){this.emit("data:range",{}),0!==this._indicators.length&&(this._indicatorsDirty=!0,this._loop.requestFrame())}_flushIndicators(){if(!this._indicatorsDirty&&0===this._indicatorRefreshes.size)return;if(this._recomputing)return;if(0===this._indicators.length)return this._indicatorsDirty=!1,void this._indicatorRefreshes.clear();const e=this._indicatorsDirty,t=Ti(this._indicators.map(e=>e.dependencyNode())).order,i=new Map(this._indicatorRefreshes);if(this._indicatorRefreshes.clear(),e)for(const e of t)i.has(e)||i.set(e,!1);this._indicatorsDirty=!1,this._recomputing=!0,this._indicatorWork=i,this._indicatorProcessed=new Set;try{for(const e of t){if(!i.has(e)||this._indicatorProcessed.has(e))continue;const t=this._indicators.find(t=>t.id===e);t&&(this._indicatorProcessed.add(e),t.recompute(i.get(e)))}for(const e of this._indicators)e.republishBarColors()}finally{this._indicatorWork=null,this._indicatorProcessed=null,this._recomputing=!1}}_queueIndicatorDependents(e,t){const i=Ti(this._indicators.map(e=>e.dependencyNode())),s=[e],r=new Set(s);for(let e=0;e<s.length;e++)for(const[n,o]of i.dependencies){if(r.has(n)||!o.some(t=>t.source.instanceId===s[e]))continue;r.add(n),s.push(n),this._indicators.find(e=>e.id===n)?.invalidateStudyOutput();const i=this._indicatorWork&&!this._indicatorProcessed?.has(n)?this._indicatorWork:this._indicatorRefreshes;i.set(n,t||!0===i.get(n))}this._indicatorRefreshes.size>0&&this._loop.requestFrame()}subscribeClick(e){this._clickCb=e}subscribeCrosshairMove(e){this._crosshairCb=e}setLinkedCrosshairIndex(e){if(this.isDestroyed||null!==this._cursor)return;const t=null===e?null:this._dataLayer.indexToTime(e)??null;if(t===this._readoutTime)return;this._readoutTime=t;for(const t of this._indicators)t.updateLegendValues(e??void 0);const i={source:"linked",time:t,index:e,bar:null===e||null===this._firstDataId.value?null:this._dataLayer.visibleBars(this._firstDataId.value,e,e)[0]?.bar??null,price:null,point:null,paneIndex:null};this._crosshairCb?.(i),this.emit("crosshair:readout",i)}_readoutIndex(){return null===this._readoutTime?void 0:this._dataLayer.timeToIndex(this._readoutTime)}subscribeDrag(e,t){this._dragCb=e,this._dragEndCb=t??null}_ensureScaled(e){const t=this._panes[e];void 0===t||t.readoutScale().scaled||t.autoscale(this._renderContext(e))}_xToTime(e){return this._dataLayer.indexToTimeFloat(this._timeScale.xToIndex(e-this._leftAxisWidth))}timeToCoordinate(e){return this._timeScale.indexToX(this._dataLayer.timeToIndexFloat(e))+this._leftAxisWidth}coordinateToTime(e){return this._xToTime(e)}on(e,t){let i=this._listeners.get(e);return void 0===i&&(i=new Set,this._listeners.set(e,i)),i.add(t),()=>this.off(e,t)}once(e,t){const i=s=>{this.off(e,i),t(s)};return this.on(e,i)}off(e,t){void 0!==t?this._listeners.get(e)?.delete(t):this._listeners.delete(e)}emit(e,t){const i=this._listeners.get(e);if(void 0!==i)for(const e of[...i])try{e(t)}catch{}}_mutateTimeScale(e){this._timeScaleMutationDepth++;try{return e()}finally{this._timeScaleMutationDepth--}}_emitViewport(e){if(void 0===this._listeners.get(e))return;const t=this._timeScale.visibleRange();this.emit(e,{from:this._dataLayer.indexToTime(Math.round(t.from))??null,to:this._dataLayer.indexToTime(Math.round(t.to))??null,logicalFrom:t.from,logicalTo:t.to})}_emitViewportIfMoved(e){const t=this._timeScale.visibleRange();if(t.from===e.from&&t.to===e.to)return;const i=Math.abs(t.to-t.from-(e.to-e.from))>1e-9;this._emitViewport(i?"zoom":"pan")}addPrimitive(e,t=0){"number"!=typeof t?(this._anchored.push({primitive:e,anchor:t.anchor}),this._addPrimitive(this._anchorTarget(t.anchor),e)):this._addPrimitive(t,e)}_anchorTarget(e){return"chart-bottom"===e?this._bottomPaneIndex(!0):this._topPaneIndex()}_rehomeAnchored(){if(0!==this._anchored.length)for(const e of this._anchored){const t=this._anchorTarget(e.anchor),i=this._panes.findIndex(t=>t.hasPrimitive(e.primitive));if(i===t)continue;i>=0&&this._panes[i].removePrimitive(e.primitive);const s=this._legends.findIndex(t=>t.legend===e.primitive);s>=0&&this._legends.splice(s,1),this._addPrimitive(t,e.primitive)}}priceToCoordinate(e,t=0){const i=this._mappedPane(t);return i&&this._paneLayout()[t].top+i.priceToY(e)}coordinateToPrice(e,t=0){const i=this._mappedPane(t);return i&&i.yToPrice(e-this._paneLayout()[t].top)}_mappedPane(e){return this._ensureScaled(e),this._collapsedShown(e)?null:this._panes[e]??null}setGridOptions(e){void 0!==e.vertLines&&(this._gridVert=e.vertLines),void 0!==e.horzLines&&(this._gridHorz=e.horzLines),this._canvas.grid={...this._canvas.grid,...e},this.invalidate(e=>e.invalidateGlobal(i.Full))}gridOptions(){return{...this._canvas.grid,vertLines:this._gridVert,horzLines:this._gridHorz}}setCanvasOptions(e){e.grid&&this.setGridOptions(e.grid),e.crosshair&&(this._canvas.crosshair={...this._canvas.crosshair,...e.crosshair}),e.scales&&(this._canvas.scales={...this._canvas.scales,...e.scales}),e.margins&&(this._canvas.margins={...this._canvas.margins,...e.margins},this.setPriceScaleOptions(R(this._canvas.margins),"axes")),this.invalidate(e=>e.invalidateGlobal(i.Full))}canvasOptions(){return{...this._canvas}}setPriceScaleOptions(e,t="primary"){this._priceScaleOptions={...this._priceScaleOptions,...e};for(const i of this._panes){const s="all"===t?i.scales():"axes"===t?i.axisScales():[i.priceScale],r=this._scalePatchFor(i,e);for(const e of s)e.setOptions(r)}this.invalidate(e=>e.invalidateGlobal(i.Full))}_scalePatchFor(e,t){if(void 0===t.minMove||this._pricePanes.has(e))return t;const i={...t};return delete i.minMove,i.minPrecision=2,i}_claimPricePane(e){if(this._pricePanes.has(e))return;this._pricePanes.add(e);const t=this._priceScaleOptions?.minMove;for(const i of e.axisScales())i.setOptions(void 0!==t?{minMove:t,minPrecision:0}:{minPrecision:0})}priceScaleOptions(){return{...this._panes[0].priceScale.options}}setAutoScale(e){for(const t of this._panes)for(const{scaleId:i}of t.visibleAxes(this._emptyPriceAxis))e&&t.setRatioLock(i,!1,0,0),t.scaleFor(i).setAutoScale(e);this.invalidate(e=>e.invalidateGlobal(i.Full))}priceOnlyAutoScale(){return this._priceOnlyAutoScale}setPriceOnlyAutoScale(e){"boolean"==typeof e&&e!==this._priceOnlyAutoScale&&(this._priceOnlyAutoScale=e,this.invalidate(e=>e.invalidateGlobal(i.Full)),this.emit("objects:change",{}))}priceAxisState(e=0,t="right"){const i=this._panes[e];if(void 0===i)return null;const s=i.scaleFor(t),r="left"===t?"right":"left";return{paneIndex:e,scaleId:t,side:"left"===i.axisPlacement(t).side?"left":"right",active:i.usesScale(t),autoFit:s.autoScale,inverted:s.options.inverted,mode:s.options.mode,scaled:s.scaled,lockRatio:i.ratioLocked(t),movable:("right"===t||"left"===t)&&this._canMovePriceAxis(e,t,r)}}priceAxisPlacement(e,t){return this._validPriceScaleId(t)?this._priceAxisPane(e)?.axisPlacement(t)??null:null}setPriceAxisPlacement(e,t,s,r){const n=this._priceAxisPane(e);return!!(n&&this._validPriceScaleId(t)&&n.setAxisPlacement(t,s,r))&&(this._recomputeAxisColumns(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this.emit("priceAxisPlacementChanged",{paneIndex:e,scaleId:t,...n.axisPlacement(t)}),this.emit("objects:change",{}),!0)}priceAxisLayout(e=0){return this._priceAxisPane(e)?.axisSlots(this._renderContext(e)).map(e=>({...e,x:e.x+this._leftAxisWidth}))??[]}_priceAxisPane(e){return!this._destroyed&&Number.isInteger(e)&&e>=0?this._panes[e]:void 0}setPriceAxisOptions(e,t,s){const r=this._panes[e];void 0!==r&&(r.scaleFor(t).setOptions(s),this.invalidate(e=>e.invalidateGlobal(i.Full)))}setPriceAxisAutoFit(e,t,s){const r=this._panes[e];void 0!==r&&(s&&r.setRatioLock(t,!1,0,0),r.scaleFor(t).setAutoScale(s),this.invalidate(e=>e.invalidateGlobal(i.Full)))}setPriceAxisLockRatio(e,t,s){const r=this._panes[e];if(void 0===r)return!1;s&&this._ensureScaledFor(e,t);const n=r.setRatioLock(t,s,this._timeScale.barSpacing,r.scaleFor(t).height);return this.invalidate(e=>e.invalidateGlobal(i.Full)),n}movePriceAxis(e,t,s){const r=this._panes[e];if(!this._canMovePriceAxis(e,t,s)||!r.moveSeriesScale(t,s))return!1;for(const e of this._indicatorRanges.values())e.pane===r&&e.scaleId===t&&(e.scaleId=s);for(const t of this._indicators){if(t.paneIndex!==e)continue;const i=t.renderResources().series.filter(e=>!e.overlay),n=t.renderResources().primitives.filter(e=>!e.overlay&&null!==r.primitiveScaleId(e.primitive));(i.length?i.every(e=>this._seriesRecords.get(e.api)?.scaleId===s):n.length&&n.every(e=>r.primitiveScaleId(e.primitive)===s))&&t.adoptPriceScale(s)}const n=r.scaleFor(t);return this._priceScaleOptions&&n.setOptions(this._scalePatchFor(r,this._priceScaleOptions)),n.setPriceFormatter(this._priceFormatter),this._recomputeAxisColumns(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this.emit("priceAxisMoved",{paneIndex:e,from:t,to:s}),!0}_canMovePriceAxis(e,t,i){const s=this._panes[e];if(!s||t===i||!s.usesScale(t)||s.usesScale(i))return!1;for(const e of this._indicators){const i=e.renderResources(),r=i.series.filter(e=>this._seriesOwners.get(e.api)?.pane===s),n=i.primitives.filter(e=>s.hasPrimitive(e.primitive)&&null!==s.primitiveScaleId(e.primitive)),o=r.filter(e=>this._seriesRecords.get(e.api)?.scaleId===t),a=n.filter(e=>s.primitiveScaleId(e.primitive)===t);if(o.length||a.length){if(o.some(e=>e.overlay)||a.some(e=>e.overlay))return!1;if(r.some(e=>!e.overlay&&this._seriesRecords.get(e.api)?.scaleId!==t)||n.some(e=>!e.overlay&&s.primitiveScaleId(e.primitive)!==t))return!1}}return!0}_ensureScaledFor(e,t){const i=this._panes[e];void 0===i||i.scaleFor(t).scaled||i.autoscale(this._renderContext(e))}setStatusLineOptions(e){Object.assign(this._statusLine,e);for(const e of this._legends)e.legend.setOptions({statusLine:this._statusLine});this.invalidate(e=>e.invalidateGlobal(i.Full))}statusLineOptions(){return{...this._statusLine}}indicatorLegendCollapsed(){return this._indicatorLegendCollapsed}setIndicatorLegendCollapsed(e){"boolean"==typeof e&&e!==this._indicatorLegendCollapsed&&(this._indicatorLegendCollapsed=e,this._restackLegends(),this.invalidate(e=>e.invalidateGlobal(i.Cursor)),this.emit("objects:change",{}))}setLegendIconSize(e){if(Number.isFinite(e)){this._legendIconSize=e;for(const t of this._legends)t.legend.setOptions({iconSize:e});this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full))}}legendIconSize(){return this._legendIconSize}setAxisChromeOptions(e){void 0!==e.sessionClock&&("object"==typeof e.sessionClock&&(this._sessionClockForm={...e.sessionClock}),this._axisChrome.sessionClock=!0===e.sessionClock?this._sessionClockForm??!0:e.sessionClock),void 0!==e.barCountdown&&(this._axisChrome.barCountdown=e.barCountdown),void 0!==e.clock&&(this._axisChrome.clock=e.clock,this._wallClock=e.clock),this.invalidate(e=>e.invalidateGlobal(i.Full))}axisChromeOptions(){return{...this._axisChrome}}crosshairMode(){return this._crosshairMode}crosshairSnapToBar(){return this._crosshairSnapToBar}theme(){return this._theme}takeScreenshot(){const e=this._pixelRatio(),t=this._doc.createElement("canvas");t.width=Math.max(1,Math.round(this._width*e)),t.height=Math.max(1,Math.round(this._height*e));const i=t.getContext("2d");if(null===i)return t;i.fillStyle=this._theme.background,i.fillRect(0,0,t.width,t.height);const s=this._paneLayout();for(let t=0;t<this._panes.length;t++){if(this._layoutWeight(t)<=0)continue;const r=Math.round((s[t]?.top??0)*e);for(const e of[this._panes[t].base,this._panes[t].top])e.element.width>0&&e.element.height>0&&i.drawImage(e.element,0,r)}return t}exportSVG(e={}){if(void 0!==e.dpr&&1!==e.dpr)throw new RangeError("exportSVG: dpr must be 1, SVG has no device pixels");const t=Math.max(1,Math.round(e.width??this._width)),s=Math.max(1,Math.round(e.height??this._height)),r=!1!==e.background,n=new ci(t,s,{background:r?this._theme.background:void 0}),o=n.asCanvasContext();this._flushIndicators();const a=this._width,l=this._height,h=t!==a||s!==l;h&&(this._width=t,this._height=s,this._relayout(!0));try{r&&"transparent"!==this._theme.background&&(n.fillStyle=this._theme.background,n.fillRect(0,0,t,s));const e=this._paneLayout(),i=this._topPaneIndex();for(let s=0;s<this._panes.length;s++){if(this._layoutWeight(s)<=0)continue;const a=this._panes[s],l={...this._renderContext(s),dpr:1,hoverId:null,hoverKey:null,dragId:null,paintBackground:r},h=s===i,c=e[s].top+(h?0:1),d=e[s].height-(h?0:1);h||(n.fillStyle=this._theme.paneSeparator,n.fillRect(0,e[s].top,t,1)),n.pushGroup({"data-pane":s},{translate:{x:0,y:c},clip:{x:0,y:0,width:t,height:d}}),a.autoscale(l),a.paintBase(l,o),a.paintTop(null,l,o),n.popGroup()}}finally{h&&(this._width=a,this._height=l,this._relayout(!0),this.invalidate(e=>e.invalidateGlobal(i.Full)))}return n.toString()}_addPrimitive(e,t){this._ensurePane(e);const s={requestUpdate:()=>this.invalidate(e=>e.invalidatePane(this._panes.findIndex(e=>e.hasPrimitive(t)),{level:"top"===t.zOrder()?i.Cursor:i.Light,autoScale:!1}))};if(this._panes[e].addPrimitive(t,s),t instanceof Wt){if(this._legends.push({legend:t,paneIndex:e}),t.setOptions({hasOpenInterest:this.hasOpenInterest}),Object.keys(this._statusLine).length>0){const e=t.options().statusLine;t.setOptions({statusLine:{...this._statusLine,...e}})}void 0!==this._legendIconSize&&t.setOptions({iconSize:this._legendIconSize}),this._restackLegends()}this.invalidate(t=>t.invalidatePane(e,{level:i.Light,autoScale:!1}))}removePrimitive(e){const t=this._anchored.findIndex(t=>t.primitive===e);t>=0&&this._anchored.splice(t,1);const s=this._legends.findIndex(t=>t.legend===e);s>=0&&this._legends.splice(s,1);for(let t=0;t<this._panes.length;t++)if(this._panes[t].removePrimitive(e))return s>=0&&this._restackLegends(),this._recomputeAxisColumns(),void this.invalidate(e=>e.invalidatePane(t,{level:i.Light,autoScale:!1}))}_restackLegends(){const e=new Map,t=this._topPaneIndex(),i=this._indicators.length,s=new Map;for(const{legend:e,paneIndex:t}of this._legends)this._studyLegends.has(e)&&!s.has(t)&&s.set(t,e);const r=e=>s.get(e.paneIndex)===e.legend&&this._collapsedShown(e.paneIndex);let n=!1;for(const o of[...this._legends.filter(r),...this._legends.filter(e=>!r(e))]){let a=e.get(o.paneIndex)??0;const l=this._studyLegends.has(o.legend),h=l&&this._indicatorLegendCollapsed&&!r(o);o.legend.setSuppressed(h||a>0&&this._collapsedShown(o.paneIndex)),i>0&&o.paneIndex===t&&l&&!n&&(this._indicatorLegendRow=a++,n=!0);const c=this._collapsed.has(this._panes[o.paneIndex]);o.legend.setOptions(l?{row:a,collapsed:c,actions:In(o.legend.options().actions,o.paneIndex>0&&s.get(o.paneIndex)===o.legend)}:{row:a}),e.set(o.paneIndex,a+(h||!1===o.legend.options().visible?0:1))}if(n||(this._indicatorLegendRow=e.get(t)??0),i>0&&null===this._indicatorLegendToggle)this._indicatorLegendToggle=new rn,this.addPrimitive(this._indicatorLegendToggle,{anchor:"chart-top"});else if(0===i&&null!==this._indicatorLegendToggle){const e=this._indicatorLegendToggle;this._indicatorLegendToggle=null,this.removePrimitive(e)}this._syncLegendOffsets()}_syncLegendOffsets(){const e=this._paneLayout(),t=Nt({iconSize:this._legendIconSize}),i=this._legendOffset.top+this._indicatorLegendRow*t;let s=i;for(const e of this._legends){const t=e.legend.options();this._studyLegends.has(e.legend)||e.paneIndex!==this._topPaneIndex()||!1===t.visible||(t.row??0)>=this._indicatorLegendRow||(s=Math.max(s,(t.top??6)+((t.row??0)+1)*Nt(t)))}for(const t of this._legends){if(!this._studyLegends.has(t.legend))continue;const r=(e[t.paneIndex]?.top??Number.POSITIVE_INFINITY)<=12;t.legend.setOptions(r?{top:this._legendOffset.top+(this._indicatorLegendToggle?s-i:0),left:this._legendOffset.left}:{top:6,left:8})}this._indicatorLegendToggle?.setOptions({count:this._indicators.length,collapsed:this._indicatorLegendCollapsed,left:this._legendOffset.left,top:s,height:t})}tradeHost(e=0){return{addPrimitive:t=>this._addPrimitive(e,t),removePrimitive:e=>this.removePrimitive(e)}}_updateBar(e,t,s){di(s,!0);const r=this._dataLayer.seriesBars(e),n=r[r.length-1]?.time,o=void 0===n||t.time>n?"append":t.time===n?"replace":"correction",a=this._timeScale.rightOffset>=0,l=this._dataLayer.update(e,t);this._seriesProvenance.get(e)?.record(o,Math.max(n??t.time,t.time),s),this._timeScale.setBaseIndex(this._dataLayer.baseIndex),"append"!==l||a||this._mutateTimeScale(()=>this._timeScale.setRightOffset(this._timeScale.rightOffset-1)),e===this._firstDataId.value&&this._invalidateIndicators(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._updateAccessibleSummary(),e===this._firstDataId.value&&this.emit("data:update",{kind:"update",time:t.time})}_ensurePane(e){const t=[];for(;this._panes.length<=e;)this._addPane(0===this._panes.length?1:.32),t.push(this._panes.length-1);if(0!==t.length){this._relayout(),this._rehomeAnchored();for(const e of t)this.emit("paneAdded",{paneIndex:e})}}_setData(e,t,s){di(s),e===this._firstDataId.value&&this._stopNavigationMotion(),this._dataLayer.setSeriesData(e,t);const r=this._dataLayer.seriesBars(e);this._seriesProvenance.get(e)?.record("reset",r[r.length-1]?.time,s),e===this._firstDataId.value&&(this._invalidateIndicators(),this._flushIndicators()),this._timeScale.setBaseIndex(this._dataLayer.baseIndex),!this._hasFitContent&&this._dataLayer.length>0&&(this._timeScale.setWidth(Math.max(0,this._width-this._rightAxisWidth-this._leftAxisWidth)),this._hasFitContent=this._fitDefaultView()),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._updateAccessibleSummary(),e===this._firstDataId.value&&this.emit("data:update",{kind:"reset"})}_prependData(e,t){this._dataLayer.addBars(e,t);const s=this._dataLayer.seriesBars(e);this._seriesProvenance.get(e)?.record("prepend",s[s.length-1]?.time),this._timeScale.setBaseIndex(this._dataLayer.baseIndex),e===this._firstDataId.value&&this._invalidateIndicators(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._updateAccessibleSummary(),e===this._firstDataId.value&&this.emit("data:update",{kind:"prepend"})}get rendererKind(){return this._rendererKind??"canvas2d"}get renderer(){return this.rendererKind}_newBackend(){const e=this._backendFactory()??Kt("canvas2d")();if(null===e)throw new Error("openalgo-charts: the canvas2d render backend factory returned null");return null===this._rendererKind&&(this._rendererKind=e.kind,null!==this._requestedRenderer&&"auto"!==this._requestedRenderer&&e.kind!==this._requestedRenderer&&console.warn(`openalgo-charts: render backend "${this._requestedRenderer}" is unavailable on this device; using "${e.kind}"`)),e}_fallbackToCanvas2d(e){const t=this.rendererKind;this._backendFactory=Kt("canvas2d");for(const e of this._panes)e.setBackend(this._newBackend());this._rendererKind="canvas2d";const s={from:t,to:"canvas2d",reason:e};this.emit("renderer:fallback",s),this.invalidate(e=>e.invalidateGlobal(i.Full))}_addPane(e=1){const t=new Zt(this._doc,this._newBackend());if(t.weight=e,0===this._panes.length)this._pricePanes.add(t);else for(const e of t.scales())e.setOptions({minPrecision:2});return t.priceScale.setPriceFormatter(this._priceFormatter),this._priceScaleOptions&&t.priceScale.setOptions(this._scalePatchFor(t,this._priceScaleOptions)),this._panes.push(t),this._container.appendChild(t.element),t}setPriceFormatter(e){this._priceFormatter=e;for(const t of this._panes)t.priceScale.setPriceFormatter(e);for(const e of this._panes)for(const t of e.series())void 0!==t.style.precision&&this._applyPrecision(e.scaleOf(t),t.style.precision);this.invalidate(e=>e.invalidateGlobal(i.Full))}setTimeFormatter(e){this._timeFormatter=e,this.invalidate(e=>e.invalidateGlobal(i.Full))}timezone(){return this._timezone}setTimezone(e){const t=Tn(e);t!==this._timezone&&(this._timezone=t,this._invalidateIndicators(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this.emit("timezone:changed",{timezone:t}))}setPlacementMode(e){this._placementMode=e,e&&Xr(this)}beginPick(e,t,i={}){if(this._destroyed||this._destroying)throw new Error("Cannot pick on a destroyed chart");if(this._placementMode)throw new Error("Finish drawing placement before picking a study value");if(null===i||"object"!=typeof i||![Object.prototype,null].includes(Object.getPrototypeOf(i))||Object.values(Object.getOwnPropertyDescriptors(i)).some(e=>!("value"in e)))throw new TypeError("Invalid pick options");const s=Object.getOwnPropertyDescriptors(i),r=s.paneIndex?.value,n=s.priceScaleId?.value;if(void 0!==r&&(!Number.isSafeInteger(r)||r<0||!this._panes[r]))throw new RangeError("Invalid pick pane");const o=r??(void 0!==n?this._firstPaneIndex:void 0);if(!(void 0===n||"price"===e&&this._validPriceScaleId(n)&&Object.prototype.hasOwnProperty.call(this._panes[o]?.scaleStates()??{},n)))throw new RangeError("Invalid pick scale");return Zr(this,e,t,t=>{const i=t,s=i?.point,r=i?.paneIndex;if(void 0===r||!Number.isSafeInteger(r)||!s||!Number.isFinite(s.x)||!Number.isFinite(s.y)||i.viaDrag||void 0!==i.id&&null!==i.id||void 0!==o&&r!==o)return null;const a=this._panes[r],l=(this._paneLayout()[r]?.height??0)-(r===this._bottomPaneIndex()?this._timeAxisHeight:0);return!a||s.x<this._leftAxisWidth||s.x>=this._width-this._rightAxisWidth||s.y<0||s.y>=l?null:"time"===e?i.time??null:(this._ensureScaled(r),void 0===n?i.price??null:Object.prototype.hasOwnProperty.call(a.scaleStates(),n)?a.scaleFor(n).yToPrice(s.y):null)})}setTheme(e){this._theme=e,this._container.style.background=e.background,this.invalidate(e=>e.invalidateGlobal(i.Full))}applyOptions(e){e.theme&&this.setTheme(e.theme),e.grid&&this.setGridOptions(e.grid),e.canvas&&this.setCanvasOptions(e.canvas),e.statusLine&&this.setStatusLineOptions(e.statusLine),void 0!==e.legendIconSize&&this.setLegendIconSize(e.legendIconSize),e.priceScale&&this.setPriceScaleOptions(e.priceScale),void 0!==e.priceFormatter&&this.setPriceFormatter(e.priceFormatter),"timeFormatter"in e&&this.setTimeFormatter(e.timeFormatter),void 0!==e.timezone&&this.setTimezone(e.timezone),e.crosshairMode&&(this._crosshairMode=e.crosshairMode),"boolean"==typeof e.crosshairSnapToBar&&(this._crosshairSnapToBar=e.crosshairSnapToBar,this.invalidate(e=>e.invalidateGlobal(i.Cursor)))}panes(){return this._panes}getState(){const e=Ti(this._indicators.map(e=>e.dependencyNode())).dependencies,t=this._panes.map(e=>{const t=e.scaleStates();for(const[i,s]of this._indicatorRanges){if(s.pane!==e)continue;const r=e.scaleFor(s.scaleId),n=this._ownedScaleRanges.get(r),o=n?r.ownedFixedRangeState(n):null;o&&t[s.scaleId]&&!t[s.scaleId].indicatorRange&&(t[s.scaleId].indicatorRange={instanceId:i,manual:o.manual})}const{right:i,...s}=t,r={weight:e.weight,priceScale:i};return Object.keys(s).length&&(r.scales=s),this._collapsed.has(e)&&(r.collapsed=!0),r}),i=[];this._panes.forEach((e,t)=>{for(const s of e.series()){const e=Object.fromEntries(Object.entries(s.style).filter(([,e])=>void 0!==e));i.push({type:s.type,style:e,paneIndex:t,priceScaleId:s.scaleId})}});const s={version:1,timezone:this._timezone,viewport:{...this.getVisibleLogicalRange()},barSpacing:this._timeScale.barSpacing,navigation:this.navigationOptions(),grid:this.gridOptions(),canvas:this.canvasOptions(),statusLine:this.statusLineOptions(),watermark:this.watermarkOptions(),trading:{...this._tradingSettings},axisChrome:{sessionClock:this._axisChrome.sessionClock,barCountdown:this._axisChrome.barCountdown},events:this.eventOptions(),crosshairMode:this._crosshairMode,crosshairSnapToBar:this._crosshairSnapToBar,priceOnlyAutoScale:this._priceOnlyAutoScale,indicatorLegendCollapsed:this._indicatorLegendCollapsed,panes:t,series:i,indicators:this._indicators.map(t=>({indicatorId:t.indicatorId,instanceId:t.id,settings:t.settings(),paneIndex:t.paneIndex,visible:t.visible(),...e.get(t.id)?.length?{studyInputs:e.get(t.id).map(e=>e.inputKey)}:{},...null===t.priceScaleId()?{}:{priceScaleId:t.priceScaleId()},...Object.keys(t.plotPriceScaleIds()).length?{plotPriceScaleIds:t.plotPriceScaleIds()}:{}}))};return void 0!==this._drawingState&&(s.drawings=this._drawingState),void 0!==this._alertState&&(s.alerts=ar(this._alertState)),s}restoreState(e,t={}){const s=e;if(null===s||"object"!=typeof s||"number"!=typeof s.version)return{applied:!1,series:[],indicators:0,reason:"not a chart state object"};if(s.version>1)return{applied:!1,series:[],indicators:0,reason:`state version ${s.version} is newer than 1`};let r,n,o;const a=new Map,l=new Set;try{const e=Object.getOwnPropertyDescriptor(s,"priceOnlyAutoScale");if(e&&(!("value"in e)||void 0!==e.value&&"boolean"!=typeof e.value))throw new Error("Invalid price-only autoscale preference");const i=Object.getOwnPropertyDescriptor(s,"indicatorLegendCollapsed");if(i&&(!("value"in i)||void 0!==i.value&&"boolean"!=typeof i.value))throw new Error("Invalid indicator legend preference");const h=e=>null!==e&&"object"==typeof e&&[Object.prototype,null].includes(Object.getPrototypeOf(e))&&Object.values(Object.getOwnPropertyDescriptors(e)).every(e=>"value"in e);if(!h(t))throw new Error("Invalid chart restore options");if(void 0!==t.preserveScaleFormats){const e=t.preserveScaleFormats;if(!Array.isArray(e))throw new Error("Invalid preserved scale formats");const i=Object.getOwnPropertyDescriptors(e);if(Reflect.ownKeys(i).some(t=>"length"!==t&&("string"!=typeof t||!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=e.length||!("value"in i[t]))))throw new Error("Invalid preserved scale formats");for(let t=0;t<e.length;t++){const e=i[t]?.value;if(!h(e)||"number"!=typeof e.paneIndex||!Number.isInteger(e.paneIndex)||e.paneIndex<0||!this._validPriceScaleId(e.scaleId))throw new Error("Invalid preserved scale selector");const s=this._panes[e.paneIndex];if(!s||!Object.prototype.hasOwnProperty.call(s.scaleStates(),e.scaleId))throw new Error("Preserved scale must already exist");const r=a.get(s)??new Set;r.add(e.scaleId),a.set(s,r)}}if(void 0!==s.panes){if(!Array.isArray(s.panes))throw new Error("Invalid pane list");n=s.panes.map(e=>pr(e,!0))}if(void 0!==s.alerts&&(r=ar(s.alerts)),void 0!==s.indicators){if(!Array.isArray(s.indicators))throw new Error("Invalid indicator list");for(const e of s.indicators){if("plotPriceScaleIds"in e){const t=Object.getOwnPropertyDescriptor(e,"plotPriceScaleIds");if(!t?.enumerable||!("value"in t))throw new Error("Invalid indicator plot price scale map field")}if(void 0!==e.priceScaleId&&!this._validPriceScaleId(e.priceScaleId))throw new Error("Invalid indicator price scale");if(void 0!==e.instanceId){if("string"!=typeof e.instanceId||!e.instanceId.trim()||l.has(e.instanceId))throw new Error("Invalid or duplicate indicator instance id");l.add(e.instanceId)}}this._reserveAlertStudyIds(r,l);const e=new Set([...l,...this._indicatorReservedIds,...this._indicators.map(e=>e.id)]),t=s.indicators.map(e=>({...e,settings:ki(e.settings??{})}));for(const i of t)for(const t of Object.values(i.settings))t&&"object"==typeof t&&"kind"in t&&"indicator"===t.kind&&"instanceId"in t&&"string"==typeof t.instanceId&&(e.add(t.instanceId),l.add(t.instanceId));let i=0;for(const s of t){if(void 0===s.instanceId){do{s.instanceId="restored-study-"+ ++i}while(e.has(s.instanceId));e.add(s.instanceId)}l.add(s.instanceId)}const n=new Map(t.filter(e=>$i(e.indicatorId)).map(e=>[e.instanceId,Bi(e.indicatorId)])),a=t.flatMap(e=>{const t=n.get(e.instanceId);return t&&void 0!==e.plotPriceScaleIds&&(e.plotPriceScaleIds=$s(t,e.plotPriceScaleIds)),t&&(ji(t.inputs,e.settings),Vs(t,e.priceScaleId,e.plotPriceScaleIds,e.paneIndex)),t?[{id:e.instanceId,descriptor:t,settings:e.settings}]:[]});o={specs:t,order:Ti(a).order,descriptors:n}}}catch(e){return{applied:!1,series:[],indicators:0,reason:e instanceof Error?e.message:"Invalid saved alerts or identities"}}this._reserveAlertStudyIds(r,l);for(const e of l)this._indicatorReservedIds.add(e);const h=++this._restoreGeneration,c=this._priceOnlyAutoScale,d=this._indicatorLegendCollapsed;this.emit("state:restore:start",{});const u=this._timeScale.visibleRange();try{if(h!==this._restoreGeneration)return{applied:!1,series:[],indicators:0,reason:"superseded by a newer chart restore"};const e=this._mutateTimeScale(()=>this._restoreState(s,r,l,n,o,a));return!e.applied||h!==this._restoreGeneration||c===this._priceOnlyAutoScale&&d===this._indicatorLegendCollapsed||this.emit("objects:change",{}),e}finally{a.clear(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._emitViewportIfMoved(u),this.emit("state:restore:end",{})}}_restoreState(e,t,s,r,n,o){if(r)for(const e of this._panes)e.clearRatioLocks();e.grid&&this.setGridOptions(e.grid),e.canvas&&this.setCanvasOptions(e.canvas),e.statusLine&&this.setStatusLineOptions(e.statusLine),e.watermark&&this.setWatermarkOptions(e.watermark),e.trading&&this.setTradingSettings(e.trading),e.axisChrome&&this.setAxisChromeOptions(e.axisChrome),e.navigation&&"object"==typeof e.navigation&&this._patchNavigation(e.navigation),e.events&&this.setEventOptions(e.events),e.crosshairMode&&(this._crosshairMode=e.crosshairMode),"boolean"==typeof e.crosshairSnapToBar&&(this._crosshairSnapToBar=e.crosshairSnapToBar);const a=Object.getOwnPropertyDescriptor(e,"priceOnlyAutoScale");a&&"boolean"==typeof a.value&&(this._priceOnlyAutoScale=a.value);const l=Object.getOwnPropertyDescriptor(e,"indicatorLegendCollapsed");l&&"boolean"==typeof l.value&&(this._indicatorLegendCollapsed=l.value),this._restackLegends(),"string"==typeof e.timezone&&Ae(e.timezone)&&this.setTimezone(e.timezone),r?.forEach((e,t)=>{this._ensurePane(t),this._panes[t].weight=e.weight}),(r||n)&&(this._panes.forEach((e,t)=>{t>0&&r?.[t]?.collapsed?this._collapsed.add(e):this._collapsed.delete(e)}),this._relayout(),this._rehomeAnchored());let h=0;if(n){this._indicatorRefreshes.clear();for(const e of this._indicators.splice(0))e.remove();const e=new Map(n.specs.map(e=>[e.instanceId,e]));for(const t of n.order){const i=e.get(t),r=n.descriptors.get(t),a=new Js(this._indicatorHost(o),r,i.settings,i.paneIndex,i.instanceId,s,i.priceScaleId,i.plotPriceScaleIds);s.add(a.id),this._indicators.push(a),!1===i.visible&&a.setVisible(!1),h+=1}const t=new Map(n.specs.map((e,t)=>[e.instanceId,t]));this._indicators.sort((e,i)=>t.get(e.id)-t.get(i.id)),this._reorderIndicatorResources()}const c=[];r&&r.forEach((e,t)=>{const i=this._panes[t];if(void 0===i)return;const s=[["right",e.priceScale],...Object.entries(e.scales??{})];i.restoreAxisPlacements(new Map(s.flatMap(([e,t])=>t.placement?[[e,t.placement]]:[])));for(const[e,t]of s){const s=i.scaleFor(e),r={marginTop:t.marginTop,marginBottom:t.marginBottom,minMove:t.minMove,mode:t.mode,inverted:t.inverted};void 0!==t.minPrecision&&(r.minPrecision=t.minPrecision),s.setOptions("right"===e&&void 0===t.minPrecision?this._scalePatchFor(i,r):r);const n=t.indicatorRange?this._indicatorRanges.get(t.indicatorRange.instanceId):void 0;n&&n.pane===i&&n.scaleId===e&&t.fixedRange?.min===n.range.min&&t.fixedRange?.max===n.range.max?(s.ownsFixedRange(n.token)||(s.setFixedRange(null),s.setAutoScale(!0),s.setOwnedFixedRange(n.token,n.range),this._ownedScaleRanges.set(s,n.token)),s.setAutoScale(!0),t.indicatorRange.manual&&(s.setAutoScale(!1),t.range&&s.setPriceRange(t.range))):(void 0!==t.fixedRange&&s.setFixedRange(t.fixedRange),s.setAutoScale(t.autoScale),!t.autoScale&&t.range&&s.setPriceRange(t.range)),t.ratioLock&&c.push({pane:i,id:e,reference:t.ratioLock})}});for(let e=this._panes.length-1;e>0;e--){const t=this._panes[e];0===t.series().length&&!this._indicators.some(t=>t.paneIndex===e)&&t.primitives().every(e=>e===this._timeNav||this._anchored.some(t=>t.primitive===e))&&this.removePane(e)}this._drawingState=e.drawings,this._alertState=t,this._recomputeAxisColumns(),void 0!==e.barSpacing&&this._timeScale.setBarSpacing(e.barSpacing),e.viewport&&this._dataLayer.length>0&&this.setVisibleLogicalRange(e.viewport);for(const{pane:e,id:t,reference:i}of c)this._panes.includes(e)&&e.setRatioLock(t,!0,i.barSpacing,i.height);return this.invalidate(e=>e.invalidateGlobal(i.Full)),this.emit("drawings:restore",e.drawings??[]),this.emit("alerts:restore",t??{version:1,alerts:[]}),this.emit("objects:change",{}),{applied:!0,series:e.series??[],indicators:h}}drawingState(){return this._drawingState}setDrawingState(e){this._drawingState=e,this.emit("objects:change",{})}snapPrice(e,t){if(!Number.isFinite(t))return t;const i=this._panes[e]?.priceScale.options.minMove??0;return i>0?d(t,i):t}alertState(){return void 0===this._alertState?void 0:ar(this._alertState)}setAlertState(e){if(void 0!==e){if(1!==e.version)throw new Error("Unsupported alert document");for(const t of e.alerts)ir(t)}this._alertState=void 0===e?void 0:{version:1,alerts:e.alerts.map(sr)},this._reserveAlertStudyIds(this._alertState,this._indicatorReservedIds)}_reserveAlertStudyIds(e,t){for(const{source:i}of e?.alerts??[])"indicator"===i.kind?t.add(i.instanceId):"drawing"===i.kind&&i.input&&t.add(i.input.instanceId)}invalidate(e){null===this._pending&&(this._pending=new s),e(this._pending),0===this._scaleMutationDepth&&this._loop.requestFrame()}_remeasure(){if(0===this._panes.length)return;const e=this._container.clientWidth,t=this._container.clientHeight;e>0&&t>0&&this.applySize(e,t)}applySize(e,t){e===this._width&&t===this._height||(this._width=e,this._height=t,this._relayout(),this._hasFitContent||(this._hasFitContent=this._fitDefaultView()),this.invalidate(e=>e.invalidateGlobal(i.Full)),this.emit("resize",{width:e,height:t}))}_relayout(e=!1){this._measureAxisColumns(),e||(this._syncTimeNavPane(),this._restackLegends());const t=this._pixelRatio(),i=this._paneLayout(),s=this._topPaneIndex(),r=this._bottomPaneIndex();this._panes.forEach((n,o)=>{const a=i[o].height;if(e)n.setLayoutSize(this._width,a);else{n.element.style.display=this._layoutWeight(o)>0?"":"none",n.element.style.flex=`0 0 ${a}px`;const e=o===s;n.element.style.borderTopWidth=e?"0px":"1px",n.element.style.borderTopColor=e?"transparent":this._theme.paneSeparator,n.resize(this._width,a,t)}n.setScaleHeights(Math.max(0,a-(o===r?this._timeAxisHeight:0)))}),this._timeScale.setWidth(Math.max(0,this._width-this._rightAxisWidth-this._leftAxisWidth))}_recomputeAxisColumns(){const e=[this._leftAxisWidth,this._rightAxisWidth,this._axisColumnWidth];this._measureAxisColumns(),e[0]===this._leftAxisWidth&&e[1]===this._rightAxisWidth&&e[2]===this._axisColumnWidth||(this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full)))}_measureAxisColumns(){let e=0,t=0;this._emptyPriceAxis=!this._panes.some(e=>e.series().length>0||e.primitives().some(t=>null!==e.primitiveScaleId(t)));for(const i of this._panes){const s=i.visibleAxes(this._emptyPriceAxis);e=Math.max(e,s.filter(e=>"left"===e.side).length),t=Math.max(t,s.filter(e=>"right"===e.side).length)}this._axisColumnWidth=Math.max(0,Math.min(this._priceAxisWidth,this._width/(e+t+1))),this._leftAxisWidth=e*this._axisColumnWidth,this._rightAxisWidth=t*this._axisColumnWidth}_layoutWeight(e){const t=this._panes[e];return void 0===t?0:null===this._maximizedPane?t.weight:e===this._maximizedPane?1:0}_topPaneIndex(){for(let e=0;e<this._panes.length;e++)if(this._layoutWeight(e)>0)return e;return 0}_bottomPaneIndex(e=!1){for(let t=this._panes.length-1;t>=0;t--)if(this._layoutWeight(t)>0&&(!e||!this._collapsedShown(t)))return t;return this._panes.length-1}_collapsedShown(e){return null===this._maximizedPane&&this._collapsed.has(this._panes[e])}_dividerAt(e){const t=this._paneLayout(),i=e=>this._layoutWeight(e)>0&&!this._collapsedShown(e);for(let s=0;s<t.length-1;s++){if(Math.abs(e-t[s].top-t[s].height)>zn.DIVIDER_GRAB)continue;let r=s,n=s+1;for(;r>=0&&!i(r);)r--;for(;n<t.length&&!i(n);)n++;if(r>=0&&n<t.length)return[r,n]}return null}setPaneWeight(e,t){const s=this._panes[e];void 0!==s&&(s.weight=Math.max(.05,t),this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full)))}paneWeight(e){return this._panes[e]?.weight??0}removePane(e){if(e<=0||e>=this._panes.length)return!1;this._eventPane===e&&null!==this._eventMarkers?(this.removePrimitive(this._eventMarkers),this._eventPane=0,this._addPrimitive(0,this._eventMarkers),this.emit("events:change",void 0)):this._eventPane>e&&(this._eventPane-=1);for(let t=this._indicators.length-1;t>=0;t--){if(this._indicators[t].paneIndex!==e)continue;const[i]=this._indicators.splice(t,1);i.remove()}const t=this._panes[e];for(const e of[...t.series()])t.removeSeries(e),this._dataLayer.removeSeries(e.dataId),this._seriesProvenance.delete(e.dataId),this._firstDataId.value===e.dataId&&(this._firstDataId.value=null);t.destroy(),this._panes.splice(e,1),null!==this._maximizedPane&&(this._maximizedPane===e?this._maximizedPane=null:this._maximizedPane>e&&(this._maximizedPane-=1));for(const t of this._indicators)t.paneIndex>e&&t.shiftPane(-1);return this._timeScale.setBaseIndex(this._dataLayer.baseIndex),this._recomputeAxisColumns(),this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._rehomeAnchored(),this._syncLegendPanes(),this.emit("paneRemoved",{paneIndex:e}),!0}movePane(e,t){const s=e+t;if(e<=0||s<=0||e>=this._panes.length||s>=this._panes.length)return!1;const r=this._panes;[r[e],r[s]]=[r[s],r[e]],this._eventPane===e?this._eventPane=s:this._eventPane===s&&(this._eventPane=e),null!==this._eventMarkers&&this.emit("events:change",void 0),this._maximizedPane===e?this._maximizedPane=s:this._maximizedPane===s&&(this._maximizedPane=e);for(const i of this._indicators)i.paneIndex===e?i.shiftPane(t):i.paneIndex===s&&i.shiftPane(-t);for(const e of r)this._container.appendChild(e.element);return this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._rehomeAnchored(),this._syncLegendPanes(),this.emit("paneMoved",{from:e,to:s}),!0}maximizePane(e){return!(e<0||e>=this._panes.length)&&(this._maximizedPane=this._maximizedPane===e?null:e,this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._rehomeAnchored(),this.emit("paneMaximized",{paneIndex:this._maximizedPane}),!0)}maximizedPane(){return this._maximizedPane}setPaneCollapsed(e,t){const s=this._panes[e];if(!(e>0)||void 0===s||"boolean"!=typeof t||this._collapsed.has(s)===t)return!1;t?this._collapsed.add(s):this._collapsed.delete(s);const r=t&&this._maximizedPane===e;return r&&(this._maximizedPane=null),this._relayout(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._rehomeAnchored(),r&&this.emit("paneMaximized",{paneIndex:null}),this.emit("paneCollapsed",{paneIndex:e,collapsed:t}),!0}paneCollapsed(e){return this._collapsed.has(this._panes[e])}_handleLegendAction(e){if(e===sn)return this.setIndicatorLegendCollapsed(!this._indicatorLegendCollapsed),!0;const t=e.lastIndexOf("::");if(t<0)return!1;const s=e.slice(t+2);if(null!==this._timeNav&&e.startsWith(`${this._timeNav.options().id}::`))return this._runShortcut(s)&&this.invalidate(e=>e.invalidateGlobal(i.Full)),!0;if("row"===s&&!e.startsWith("indicator:"))return!0;if(!e.startsWith("indicator:"))return!1;const r=e.slice(10,t);if("row"===s)return!0;const n=this._indicators.find(e=>e.id===r);if(void 0===n)return!1;const o=n.paneIndex;switch(s){case"close":return this.removeIndicator(r),!0;case"hide":return n.setVisible(!n.visible()),!0;case"up":return this.movePane(o,-1),!0;case"down":return this.movePane(o,1),!0;case"collapse":return this.setPaneCollapsed(o,!this.paneCollapsed(o)),!0;case"maximize":return this.maximizePane(o),!0;case"settings":return this.emit("indicatorSettings",{instanceId:r,indicatorId:n.indicatorId,paneIndex:o}),!0;case"source":return this.emit("indicatorSource",{instanceId:r,indicatorId:n.indicatorId,paneIndex:o}),!0;default:return!1}}_indicatorLegendHit(e,t,i){return null!==this._indicatorLegendToggle&&!0===this._panes[e]?.hasPrimitive(this._indicatorLegendToggle)&&null!==this._indicatorLegendToggle.hitTest(t-this._leftAxisWidth,i)}_paneLayout(){const e=this._bottomPaneIndex(),t=Nt({iconSize:this._legendIconSize})+12,i=this._panes.map((i,s)=>this._collapsedShown(s)?t+(s===e?this._timeAxisHeight:0):0);let s=0,r=0;i.forEach((e,t)=>{s+=e,e||(r+=this._layoutWeight(t))});const n=s>this._height?this._height/s:1,o=Math.max(0,this._height-s);let a=0;return i.map((e,t)=>{const i={top:a,height:e?e*n:r>0?o*this._layoutWeight(t)/r:0};return a+=i.height,i})}_navHints(e){if(void 0!==e?.hints)return e.hints;if(null===this._shortcuts)return{};const t={};for(const e of this._shortcuts.list()){if("zoomIn"!==e.command&&"zoomOut"!==e.command&&"resetScale"!==e.command)continue;const i=e.combos[0];void 0!==i&&(t[e.command]=Nn(i))}return t}_syncTimeNavPane(){const e=this._timeNav;if(null===e)return;const t=this._bottomPaneIndex(!0),i=this._panes.findIndex(t=>t.hasPrimitive(e));this._timeNavPane=t,t===i||t<0||(this._panes[i]?.removePrimitive(e),this._addPrimitive(t,e))}_feedTimeNav(e){const t=this._timeNav;null!==t&&(t.setPointer(e),t.animating()&&this.invalidate(e=>e.invalidateGlobal(i.Light)))}_renderContext(e){return{timeScale:this._timeScale,dataLayer:this._dataLayer,priceOnlyAutoScale:this._priceOnlyAutoScale,primaryDataId:this._primary?.record.dataId,dpr:this._pixelRatio(),priceAxisWidth:this._rightAxisWidth,axisColumnWidth:this._axisColumnWidth,emptyPriceAxis:this._emptyPriceAxis,timeAxisHeight:this._timeAxisHeight,showTimeAxis:e===this._bottomPaneIndex(),collapsed:this._collapsedShown(e),conflate:this._conflate,conflationFactor:this._conflationFactor,theme:this._theme,showVertGrid:this._gridVert,showHorzGrid:this._gridHorz,canvasOptions:this._canvas,timeFormatter:this._timeFormatter,timezone:this._timezone,leftAxisWidth:this._leftAxisWidth,hoverId:this._hoverId,hoverKey:this._hoverKey,dragId:this._dragId,sessionClock:this._sessionClockOptions(),barCountdown:this._barCountdownOptions()}}_sessionClockOptions(){const e=this._axisChrome.sessionClock;if(void 0!==e&&!1!==e)return{visible:!0,now:this._wallClock,timezone:this._timezone,showOffset:!0===e?void 0:e.showOffset}}_barCountdownOptions(){if(!0!==this._axisChrome.barCountdown)return;const e=this._dataLayer.indexToTime(this._dataLayer.baseIndex);return void 0!==e?{visible:!0,now:this._wallClock,lastBarTime:e,intervalSec:gt(this._dataLayer)}:void 0}_observeSize(){"undefined"!=typeof ResizeObserver&&(this._resizeObserver=new ResizeObserver(e=>{const t=e[0];t&&this.applySize(t.contentRect.width,t.contentRect.height)}),this._resizeObserver.observe(this._container))}_onFrame(){if(this._destroyed||this._destroying)return;this._flushIndicators();const e=this._pending;if(this._pending=null,null===e||e.isEmpty())return;const t=e.globalLevel;let s=!1;const r=this._now(),n=null===this._autoscaleTime||++this._autoscaleFrames>=90?1:1-Math.exp(-Math.max(1,r-this._autoscaleTime)/80);null!==this._autoscaleTime&&(this._autoscaleTime=r);let o=this._cursor?.x??0;const a=this._firstDataId.value??this._panes[0]?.series()[0]?.dataId;if(null!==this._cursor&&this._crosshairSnapToBar&&void 0!==a){const e=Math.round(this._timeScale.xToIndex(o));this._dataLayer.visibleBars(a,e,e).length>0&&(o=this._timeScale.indexToX(e))}for(let r=0;r<this._panes.length;r++){const a=this._panes[r],l=e.paneInvalidation(r),h=Math.max(t,l?.level??i.None),c=this._renderContext(r);if((h>=i.Full||l?.autoScale||null!==this._autoscaleTime)&&(s=a.autoscale(c,n)||s),h>=i.Light&&a.paintBase(c),h>=i.Cursor&&!this._overlayFrozen){const e=null===this._cursor?null:{x:o,yLocal:r===this._cursorPane?this._cursor.y:null,showTimeTag:c.showTimeAxis};a.paintTop(e,c)}}s?this.invalidate(e=>e.invalidateGlobal(i.Light)):this._autoscaleTime=null;const l=this._timeNav;if(l?.animating()&&!this._schedulingTimeNav&&(!this._overlayFrozen||"top"!==l.zOrder())&&this._panes[this._timeNavPane]?.primitives().includes(l)){this._schedulingTimeNav=!0;try{this.invalidate(e=>e.invalidateGlobal(i.Light))}finally{this._schedulingTimeNav=!1}}if(null!==this._rendererKind&&"canvas2d"!==this._rendererKind)for(const e of this._panes){const t=e.backendDegradation;if(null!==t){this._fallbackToCanvas2d(t);break}}}_attachInput(){if("undefined"==typeof window)return;const e=this._container;e.addEventListener("pointerdown",this._onPointerDown),e.addEventListener("pointermove",this._onPointerMove),e.addEventListener("pointerup",this._onPointerUpNative),e.addEventListener("pointercancel",this._onPointerCancel),e.addEventListener("lostpointercapture",this._onLostPointerCapture),e.addEventListener("pointerleave",this._onPointerLeave),e.addEventListener("wheel",this._onWheel,{passive:!1}),e.addEventListener("dblclick",this._onDblClick),e.addEventListener("pointerenter",this._onPointerEnter),e.addEventListener("contextmenu",this._onContextMenu);const t="function"==typeof this._doc.addEventListener?this._doc:e;t.addEventListener("keydown",this._onKeyDown),this._keyTarget=t}_contextMenuEvent(e,t){const i=t.x-this._leftAxisWidth,s=i>=0&&t.x<this._width-this._rightAxisWidth,r=s?Math.round(this._timeScale.xToIndex(i)):null;return s&&this._ensureScaled(t.pane),{paneIndex:t.pane,point:{x:t.x,y:t.y},price:s?this._priceAt(t.pane,t.localY):null,time:null===r?null:this._dataLayer.indexToTime(r)??null,index:r,target:this._contextTarget(t,i,s,r),preventDefault:()=>e.preventDefault()}}_contextTarget(e,t,i,s){const r=e.pane===this._bottomPaneIndex(),n=e.x>=this._width-this._rightAxisWidth;if(r&&e.localY>=e.paneHeight-this._timeAxisHeight&&!n)return{kind:"time-scale",id:null};if(!i){const t=this._axisAt(e.pane,e.x);return t?{kind:"price-scale",id:null,side:t.side,scaleId:t.scaleId}:{kind:"empty",id:null}}const o=this._panes[e.pane]?.hitTestPrimitives(t,e.localY,this._renderContext(e.pane));if(null!=o){const e=o.externalId;if(e.startsWith("draw:"))return{kind:"drawing",id:e};if(e.startsWith("indicator:")){const t=e.lastIndexOf("::"),i=e.slice(10,t<0?void 0:t);return{kind:"indicator",id:e,instanceId:i}}return e.endsWith("::row")?{kind:"legend",id:e}:{kind:"primitive",id:e}}const a=null===s||this._collapsedShown(e.pane)?null:this._seriesAt(e.pane,s,e.localY);if(null===a)return{kind:"empty",id:null};for(const e of this._indicators)for(const t of Bi(e.indicatorId).plots){const i=e.series(t.key);if(i&&this._seriesRecords.get(i)===a)return{kind:"indicator",id:`indicator:${e.id}`,instanceId:e.id,plotKey:t.key}}return{kind:"series",id:null,seriesType:a.type}}_axisAt(e,t){return this.priceAxisLayout(e).find(e=>t>=e.x&&t<e.x+e.width)}_seriesAt(e,t,i){const s=this._panes[e];if(void 0===s)return null;const r=s.series();for(let e=r.length-1;e>=0;e--){const n=r[e];if(!1===n.style.visible)continue;const o=this._dataLayer.visibleBars(n.dataId,t,t);if(0===o.length)continue;const a=le(n.type).extents(o[0].bar,n.style);if(!isFinite(a.min)||!isFinite(a.max))continue;const l=s.scaleOf(n),h=l.priceToY(a.max),c=l.priceToY(a.min);if(i>=Math.min(h,c)-3&&i<=Math.max(h,c)+3)return n}return null}_priceAt(e,t){return this._collapsedShown(e)?null:this._panes[e]?.yToPrice(t)??null}_unfreezeOverlay(){this._overlayFrozen&&(this._overlayFrozen=!1,this.invalidate(e=>e.invalidateGlobal(i.Cursor)))}_localPoint(e){const t=this._container.getBoundingClientRect();return this._project(e.clientX-t.left,e.clientY-t.top,this._paneLayout())}_project(e,t,i){let s=0;for(let e=0;e<i.length;e++)t>=i[e].top&&(s=e);const r=i[s]??{top:0,height:this._height};return{x:e,y:t,pane:s,localY:t-r.top,paneHeight:r.height}}_dragSamples(e){const t="function"==typeof e.getCoalescedEvents?e.getCoalescedEvents():[],i=t.length>0?t:[e],s=this._container.getBoundingClientRect(),r=this._paneLayout(),n=[];for(const e of i){const t=this._project(e.clientX-s.left,e.clientY-s.top,r);n.push({x:t.x,y:null===this._dragId?t.localY:t.y-(r[this._downPane]?.top??0),pressure:An(e)})}return n}_clickInfo(e){const t=jn(e);return t.pressure=this._downPressure,{...t,shiftKey:t.modifiers.shift,ctrlKey:t.modifiers.ctrl,metaKey:t.modifiers.meta}}_brandingHit(e,t,i){const s=this._panes[e];if(null===this._branding||!s?.hasPrimitive(this._branding))return!1;const r=e===this._bottomPaneIndex();return null!==this._branding.hitTest(t-this._leftAxisWidth,i,{timeScale:this._timeScale,priceScale:s.priceScale,dataLayer:this._dataLayer,plotWidth:this._width-this._leftAxisWidth-this._rightAxisWidth,plotHeight:(this._paneLayout()[e]?.height??0)-(r?this._timeAxisHeight:0),priceAxisWidth:this._rightAxisWidth,dpr:this._pixelRatio(),theme:this._theme})}_applyZoom(e,t){!1!==this._navigation.zoomEnabled&&(this._beginAutoscaleMotion(),this._mutateTimeScale(()=>this._timeScale.zoomAtX(e,Math.exp(t))),this._maybeLoadHistory(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._emitViewport("zoom"))}_startZoomGlide(e,t){if(!1===this._navigation.zoomEnabled)return;const i=new vr(t);this._zoomGlide=i,this._zoomGlideStart=this._now(),this._zoomGlideApplied=0;let s=0;const r=()=>{if(this._zoomGlide!==i||this._destroyed||!1===this._navigation.zoomEnabled)return;const t=this._now()-this._zoomGlideStart,n=i.appliedAt(t),o=n-this._zoomGlideApplied;if(this._zoomGlideApplied=n,0!==o&&this._applyZoom(e,o),this._zoomGlide===i&&!this._destroyed)if(!i.finished(t)&&++s<600)this._zoomHandle=this._raf.schedule(r);else{const t=i.totalLogFactor-this._zoomGlideApplied;0!==t&&this._applyZoom(e,t),this._zoomHandle=null,this._zoomGlide=null}};this._zoomHandle=this._raf.schedule(r)}_beginAutoscaleMotion(){this._animAutoscale&&null===this._autoscaleTime&&(this._autoscaleTime=this._now()-16,this._autoscaleFrames=0)}_stopNavigationMotion(){this._navigationEpoch++,this._stopZoomGlide(),this._stopKinetic(),this._autoscaleTime=null}_stopZoomGlide(){null!==this._zoomHandle&&(this._raf.cancel(this._zoomHandle),this._zoomHandle=null),this._zoomGlide=null}resetScale(){this._stopNavigationMotion();const e=this._timeScale.visibleRange();this._hasFitContent=this._fitDefaultView();for(const e of this._panes){e.clearRatioLocks();for(const t of e.scales())t.setAutoScale(!0)}this.invalidate(e=>e.invalidateGlobal(i.Full)),this._emitViewportIfMoved(e)}_beginPinch(){this._cancelPrimitiveDrag("pinch"),this._brandingPress=null,this._indicatorTogglePress=null;const e=[...this._pointers.values()];this._pinch=Ur(e[0],e[1]),this._pinchPane=e[0].pane,this._dragging=!1,this._axisDrag=null,this._axisDragScale=null,this._dragId=null,this._pointerMoved=!0,this._dragPriceScale=null,this._setHover(null)}_updatePinch(){const e=[...this._pointers.values()];if(e.length<2||null===this._pinch)return;const t=Ur(e[0],e[1]),s=function(e,t){return{factor:e.dist>0?t.dist/e.dist:1,dx:t.cx-e.cx,dy:t.cy-e.cy}}(this._pinch,t);this._pinch=t;const r=!1!==this._navigation.zoomEnabled&&1!==s.factor,n=!1!==this._navigation.panEnabled&&(0!==s.dx||0!==s.dy);(r||n)&&(this._beginAutoscaleMotion(),this._mutateTimeScale(()=>{r&&this._timeScale.zoomAtX(t.cx,s.factor),n&&this._timeScale.setRightOffset(this._timeScale.rightOffset-s.dx/this._timeScale.barSpacing)}),n&&0!==s.dy&&!this._collapsedShown(this._pinchPane)&&this._panes[this._pinchPane]?.priceScale.panByPixels(s.dy),this._maybeLoadHistory(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._emitViewport(r?"zoom":"pan"))}_cancelPrimitiveDrag(e){null!==this._dragId&&(this._dragMoved=!0,this.emit("drag:cancel",{id:this._dragId,paneIndex:this._downPane,reason:e}))}_shortcutsActive(){if(null===this._shortcuts)return!1;if("global"===this._shortcuts.scope||this._pointerInside)return!0;const e=this._doc.activeElement;return null!==e&&(e===this._container||!0===this._container.contains?.(e))}_runShortcut(e){if(!this._navigationAllowed(e))return!1;const t=this._timeScale,i=e=>{this._stopZoomGlide(),this._beginAutoscaleMotion();const i=t.visibleRange();return this._mutateTimeScale(()=>t.setRightOffset(t.rightOffset+e)),this._emitViewportIfMoved(i),!0},s=e=>{this._stopZoomGlide(),this._beginAutoscaleMotion();const i=t.visibleRange();return this._mutateTimeScale(()=>t.zoomAtX(this._width/2,e)),this._emitViewportIfMoved(i),!0};switch(e){case"panLeftBar":return i(-1);case"panRightBar":return i(1);case"panLeft":return i(-2);case"panRight":return i(2);case"panLeftFast":return i(-10);case"panRightFast":return i(10);case"panUp":return this._panes[0]?.priceScale.panByPixels(20),!0;case"panDown":return this._panes[0]?.priceScale.panByPixels(-20),!0;case"zoomIn":return s(1.1);case"zoomOut":return s(1/1.1);case"resetScale":return this.resetScale(),!0;case"fitContent":return this.fitContent(),!0;case"screenshot":return this.downloadScreenshot(),!0;case"toggleGridVert":return this.setGridOptions({vertLines:!this._gridVert}),!0;case"toggleGridHorz":return this.setGridOptions({horzLines:!this._gridHorz}),!0;case"toggleCrosshairMagnet":return this._crosshairMode="magnet"===this._crosshairMode?"normal":"magnet",!0;default:return!1}}downloadScreenshot(e="chart.png"){try{const t=this.takeScreenshot(),i=this._doc.createElement("a");i.href=t.toDataURL("image/png"),i.download=e,i.click()}catch{}}_updateAccessibleSummary(){if(null===this._liveRegion)return;const e=this._dataLayer.length;let t=`${e} bar${1===e?"":"s"}`;if(null!==this._firstDataId.value&&void 0!==this._panes[0]){const e=this._dataLayer.lastIndexedBar(this._firstDataId.value);null!==e&&(t+=`, latest price ${this._panes[0].priceScale.format(e.bar.close)}`)}this._liveRegion.textContent=`Financial chart, ${t}`}_setHover(e){const t=e?.externalId??null,s=e?.hoverKey??t;if(this._container.style.cursor=this._dragging&&"pointer"!==e?.cursor?"grabbing":e?.cursor??"",t===this._hoverId&&s===this._hoverKey)return;const r=t!==this._hoverId,n=null!==e&&"top"!==e.zOrder,o=n||this._hoverOnBase?i.Light:i.Cursor;this._hoverId=t,this._hoverKey=s,this._hoverOnBase=n,this.invalidate(e=>e.invalidateGlobal(o)),r&&this.emit("hover",{id:t})}_updateCursor(e,t,s,r,n){const o=this._width-this._rightAxisWidth,a=t-this._leftAxisWidth,l=Math.max(0,o-this._leftAxisWidth);if(a<0||a>l)return void this._onPointerLeave();const h=this._panes[e],c=h.hitTestPrimitives(a,s,this._renderContext(e))??null;if(null===c&&null!==this._dividerAt(r))return this._setHover(null),void(this._container.style.cursor="row-resize");this._setHover(c),this._feedTimeNav(e!==this._timeNavPane||this._brandingHit(e,t,s)?null:{x:a,y:s});let d=s;const u=Math.round(this._timeScale.xToIndex(a));let p=null;if(null!==this._firstDataId.value){const t=this._dataLayer.visibleBars(this._firstDataId.value,u,u);if(t.length>0&&(p=t[0].bar,"magnet"===this._crosshairMode&&e===this._firstPaneIndex)){const e=function(e,t){const i=[t.open,t.high,t.low,t.close];let s=i[0],r=Math.abs(e-s);for(let t=1;t<i.length;t++){const n=Math.abs(e-i[t]);n<r&&(r=n,s=i[t])}return s}(h.yToPrice(s),p);d=h.priceToY(e)}}this._cursorPane=e,this._cursor={x:a,y:d},this._readoutTime=p?.time??null;for(const e of this._indicators)e.updateLegendValues(u);if(this.invalidate(e=>e.invalidateGlobal(i.Cursor)),null!==this._crosshairCb||void 0!==this._listeners.get("crosshair:move")||void 0!==this._listeners.get("crosshair:readout")){const i={time:this._dataLayer.indexToTime(u)??null,index:u,price:this._priceAt(e,s),bar:p,point:{x:t,y:r},paneIndex:e,pressed:this._pointers.size>0,...jn(n),...this._pointers.size>0?{samples:this._dragSamples(n)}:{}};this._crosshairCb?.(i),this.emit("crosshair:readout",i),this.emit("crosshair:move",i)}}_maybeLoadHistory(){if(null===this._historyLoader||this._loadingHistory)return;const e=this._timeScale.visibleRange();e.from<10&&(this._loadingHistory=!0,this.emit("lazy-load",{from:this._dataLayer.indexToTime(Math.round(e.from))??null,to:this._dataLayer.indexToTime(Math.round(e.to))??null,direction:"backward"}),this._historyLoader())}_startKinetic(e){if(!1===this._navigation.panEnabled)return;this._stopKinetic();const t=this._kineticEpoch,s=new br(e);if(s.durationMs<=0)return;const r=this._now();let n=0,o=0;const a=()=>{if(t!==this._kineticEpoch||this._destroyed||!1===this._navigation.panEnabled)return;const e=this._now()-r,l=s.distanceAt(e),h=l-n;n=l,this._beginAutoscaleMotion(),this._mutateTimeScale(()=>this._timeScale.setRightOffset(this._timeScale.rightOffset-h/this._timeScale.barSpacing)),this._maybeLoadHistory(),this.invalidate(e=>e.invalidateGlobal(i.Full)),this._emitViewport("pan"),t!==this._kineticEpoch||this._destroyed||(!s.finished(e)&&++o<600?this._kineticHandle=this._raf.schedule(a):this._kineticHandle=null)};this._kineticHandle=this._raf.schedule(a)}_stopKinetic(){this._kineticEpoch++,null!==this._kineticHandle&&(this._raf.cancel(this._kineticHandle),this._kineticHandle=null)}get isDestroyed(){return this._destroyed}destroy(){if(!this._destroyed&&!this._destroying){this._destroying=!0,this._barsRequests.abort(),this._timeScale.setChangeHandler(null),this._loop.stop(),null!==this._remeasureHandle&&(this._raf.cancel(this._remeasureHandle),this._remeasureHandle=null),this._stopNavigationMotion();for(const e of this._indicators.splice(0))e.remove();if(this._resizeObserver?.disconnect(),this._resizeObserver=null,"undefined"!=typeof window){const e=this._container;e.removeEventListener("pointerdown",this._onPointerDown),e.removeEventListener("pointermove",this._onPointerMove),e.removeEventListener("pointerup",this._onPointerUpNative),e.removeEventListener("pointercancel",this._onPointerCancel),e.removeEventListener("lostpointercapture",this._onLostPointerCapture),e.removeEventListener("pointerleave",this._onPointerLeave),e.removeEventListener("wheel",this._onWheel),e.removeEventListener("dblclick",this._onDblClick),e.removeEventListener("pointerenter",this._onPointerEnter),e.removeEventListener("contextmenu",this._onContextMenu),this._keyTarget?.removeEventListener("keydown",this._onKeyDown),this._keyTarget=null}this._liveRegion?.remove(),this._liveRegion=null,this._container.style.cursor="",this._pointers.clear();for(const e of this._panes)e.destroy();this._panes.length=0,this._seriesProvenance.clear(),this._destroyed=!0,this.emit("destroy",{}),this._listeners.clear()}}}function Fn(e,t={}){return new zn(e,t)}function Nn(e){const t={Equal:"+",Minus:"-",NumpadAdd:"+",NumpadSubtract:"-",ArrowLeft:"<",ArrowRight:">",ArrowUp:"^",ArrowDown:"v"};return e.split("+").map(e=>e.trim()).map(e=>"Mod"===e?"Ctrl":t[e]??e.replace(/^(Key|Digit)/,"")).join(" + ")}Object.defineProperty(zn,"DIVIDER_GRAB",{enumerable:!0,configurable:!0,writable:!0,value:4});const En={bars:0,matched:0,gaps:0,dropped:0};function Bn(e,t){const i=new Map;for(const e of t){const t=fr(e);isFinite(t.close)?i.set(t.time,t):i.delete(t.time)}const s=[];let r=0;for(const t of e){const e=i.get(t.time);void 0!==e?(s.push(e),r++):s.push({time:t.time})}return{items:s,alignment:{bars:s.length,matched:r,gaps:s.length-r,dropped:i.size-r}}}class $n{constructor(e,t={}){Object.defineProperty(this,"_chart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_mode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_baseline",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_panes",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_items",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_alignedAt",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"_realigning",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_nextScale",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_syncing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_alignedPrimary",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_primaryLength",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"_primaryFirst",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_primaryLast",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_off",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._chart=e,this._mode=t.mode??"percentage",this._baseline=t.baseline??"first-visible",this._off.push(yi(e,()=>this.realign())),e.on&&(this._off.push(e.on("data:update",()=>{this._needsAlignment()&&this.realign()})),this._off.push(e.on("destroy",()=>this._dispose())))}add(e){if(this._destroyed)throw new Error("openalgo-charts: comparison controller is destroyed");if(null===this._chart.primarySeries())throw new Error("openalgo-charts: a comparison needs a primary series to align against");const t=e.paneIndex??0,i={...e.style};void 0===i.color&&void 0!==e.color&&(i.color=e.color);const s=this._panes.get(t),r=this._scaleIdFor(t),n=this._chart.addSeries(e.type??"line",{paneIndex:t,style:i,priceScaleId:r}),o=s??this._openPane(t);o.count++;const a={series:n,entry:o,scale:n.priceScale(),savedScaleMode:n.priceScale().options.mode,savedInverted:n.priceScale().options.inverted,appliedInverted:null,scaleId:r,type:e.type??"line",style:i,items:[],values:new Map,suppressed:!1,bars:e.bars,alignment:En,removed:!1};"none"!==this._mode&&a.scale.setOptions({mode:this._mode});const l={symbol:e.symbol,series:n,paneIndex:t,priceScale:()=>a.scale,alignment:()=>a.alignment,barAt:e=>{const t=a.values.get(e);return!a.removed&&!a.suppressed&&t&&Number.isFinite(t.close)?t:null},setBars:e=>{a.removed||(a.bars=e,this._align(a,this._primaryBars()))},remove:()=>{this.remove(l)},list:()=>this.list()};return this._items.set(l,a),this._align(a,this._primaryBars()),this._rememberAlignment(),l}remove(e){const t=this._items.get(e);if(void 0===t||t.removed)return!1;this._restoreScale(t),t.removed=!0,this._items.delete(e);const i=t.entry;return--i.count<=0&&this._closePane(i),t.series.remove(),!0}list(){return Array.from(this._items.keys())}clear(){for(const e of this.list())this.remove(e)}setMode(e){if(e!==this._mode){this._mode=e,this._syncing=!0;try{for(const e of this._panes.values())this._restoreMode(e),this._applyMode(e);for(const e of this._items.values())this._setSuppressed(e,!1)}finally{this._syncing=!1}this._repaint()}}get mode(){return this._mode}setBaseline(e){if(e!==this._baseline){this._baseline=e,this._syncing=!0;try{for(const e of this._items.values())this._setSuppressed(e,!1)}finally{this._syncing=!1}this._repaint()}}get baseline(){return this._baseline}baselineTime(e=0){const t=this._panes.get(e);return"common"===this._baseline&&"none"!==this._mode&&t&&t.primary.options.mode===t.applied?this._commonAnchor(t,this._visiblePrimary())?.time??null:null}realign(){if(this._realigning||this._destroyed||!this._items.size)return;this._realigning=!0;const e=this._syncing;this._syncing=!0;try{const e=this._primaryBars();for(const t of this._items.values())this._align(t,e);this._rememberAlignment()}finally{this._realigning=!1,this._syncing=e}e||this._repaint()}sync(){if(!this._syncing){this._syncing=!0;try{this._needsAlignment()&&this.realign();for(const e of this._panes.values())this._mirror(e)}finally{this._syncing=!1}}}destroy(){this._destroyed||(this.clear(),this._dispose())}_dispose(){if(!this._destroyed){this._destroyed=!0;for(const e of this._off.splice(0))e();for(const e of this._items.values())e.removed=!0,e.bars=[],e.items=[],e.values.clear();this._items.clear(),this._panes.clear(),this._alignedPrimary=null,Dn.delete(this._chart)}}_needsAlignment(){if(this._destroyed||!this._items.size)return!1;const e=this._chart.primaryBars?.();return this._chart.dataLayer.length!==this._alignedAt||Boolean(e&&(e!==this._alignedPrimary||e.length!==this._primaryLength||e[0]?.time!==this._primaryFirst||e[e.length-1]?.time!==this._primaryLast))}_rememberAlignment(){this._alignedAt=this._chart.dataLayer.length,this._alignedPrimary=this._chart.primaryBars?.()??null,this._primaryLength=this._alignedPrimary?.length??-1,this._primaryFirst=this._alignedPrimary?.[0]?.time,this._primaryLast=this._alignedPrimary?.[this._primaryLength-1]?.time}_scaleIdFor(e){const t=this._chart.panes()[e],i=e=>t?.series().some(t=>t.scaleId===e)??!1;if(!this._panes.has(e)){if(!i(""))return"";if(!i("left"))return"left"}let s;do{s="overlay:comparison-"+ ++this._nextScale}while(i(s));return s}_openPane(e){const t=this._chart.panes()[e].priceScale,i={paneIndex:e,primary:t,savedPrimaryMode:t.options.mode,applied:null,sync:{zOrder:()=>"bottom",draw:()=>{},afterAutoscale:()=>{this.sync()}},count:0};return this._panes.set(e,i),this._applyMode(i),this._chart.addPrimitive(i.sync,e),i}_closePane(e){this._restoreMode(e),this._chart.removePrimitive(e.sync),this._panes.delete(e.paneIndex)}_applyMode(e){if("none"!==this._mode){e.applied=this._mode,e.primary.setOptions({mode:this._mode});for(const t of this._items.values())t.entry===e&&t.scale.setOptions({mode:this._mode})}}_restoreScale(e){null!==e.entry.applied&&e.scale.options.mode===e.entry.applied&&e.scale.setOptions({mode:e.savedScaleMode}),null!==e.appliedInverted&&e.scale.options.inverted===e.appliedInverted&&e.scale.setOptions({inverted:e.savedInverted}),e.appliedInverted=null}_restoreMode(e){const t=e.applied;if(null!==t){for(const t of this._items.values())t.entry===e&&this._restoreScale(t);e.applied=null,e.primary.options.mode===t&&e.primary.setOptions({mode:e.savedPrimaryMode})}}_mirror(e){if(null===e.applied)return;const t=Array.from(this._items.values()).filter(t=>t.entry===e);if(e.primary.options.mode!==e.applied){for(const e of t)this._setSuppressed(e,!1);return}if("common"===this._baseline&&e.primary.options.mode===e.applied){const i=this._visiblePrimary(),s=this._commonAnchor(e,i);for(const e of t){const t=s&&e.values.get(s.time)?.close;this._setSuppressed(e,!t||!Number.isFinite(t)||t<=0)}if(null===s)return;e.primary.setBaseline(s.close);const r=e.primary.priceRange();for(const n of t){const t=n.values.get(s.time)?.close;if(n.scale.setBaseline(t&&t>0?t:null),!e.primary.autoScale||!t||t<=0||!this._visible(n))continue;const o=le(n.type),a=this._record(n)?.style??n.style;let l=1/0,h=-1/0;for(const e of i){const t=n.values.get(e.time);if(!t)continue;const i=o.extents(t,a);Number.isFinite(i.min)&&Number.isFinite(i.max)&&(l=Math.min(l,i.min),h=Math.max(h,i.max))}if(!(l<=h))continue;const c=g(l,h,e.primary.options.marginTop,e.primary.options.marginBottom),d=s.close/t;r.min=Math.min(r.min,c.min*d),r.max=Math.max(r.max,c.max*d)}e.primary.autoScale&&e.primary.setComputedRange(r)}const i=e.primary.baseline;if(null===i||!Number.isFinite(i)||i<=0||!e.primary.scaled)return;const s=e.primary.priceRange();for(const t of this._items.values()){if(t.entry!==e)continue;const r=t.scale.baseline;if(null===r||!Number.isFinite(r)||r<=0)continue;const n=r/i;t.appliedInverted=e.primary.options.inverted,t.scale.setOptions({inverted:t.appliedInverted}),t.scale.setComputedRange({min:s.min*n,max:s.max*n})}}_primaryBars(){return this._chart.primaryBars?.()??this._chart.primarySeries()?.getData()??[]}_record(e){return this._chart.panes()[e.entry.paneIndex]?.series().find(t=>t.scaleId===e.scaleId)}_visible(e){return!1!==this._record(e)?.style?.visible}_visiblePrimary(){const e=this._primaryBars(),t=this._chart.getVisibleLogicalRange?.();if(!t)return e;const i=Math.max(0,Math.floor(t.from)),s=Math.min(this._chart.dataLayer.length-1,Math.ceil(t.to));if(i>s)return[];const r=this._chart.dataLayer.indexToTime?.(i)??e[i]?.time,n=this._chart.dataLayer.indexToTime?.(s)??e[s]?.time;if(void 0===r||void 0===n)return[];let o=0,a=e.length;for(;o<a;){const t=o+a>>>1;e[t].time<r?o=t+1:a=t}let l=o;for(;l<e.length&&e[l].time<=n;)l++;return e.slice(o,l)}_commonAnchor(e,t){const i=Array.from(this._items.values()).filter(t=>t.entry===e&&this._visible(t));return i.length?t.find(e=>Number.isFinite(e.close)&&e.close>0&&i.every(t=>{const i=t.values.get(e.time)?.close;return void 0!==i&&Number.isFinite(i)&&i>0}))??null:null}_setSuppressed(e,t){t!==e.suppressed&&(e.suppressed=t,this._write(e))}_write(e){e.series.setData(e.suppressed?e.items.map(e=>({time:e.time})):e.items)}_align(e,t){const i=bi(this._chart),s=Bn(i?t.filter(e=>e.time<=i.time):t,i?.forming?e.bars.filter(e=>e.time!==i.time):e.bars);e.alignment=s.alignment,e.items=s.items,e.values=new Map(s.items.map(e=>{const t=fr(e);return[t.time,t]})),this._write(e)}_repaint(){for(const e of this._items.values())e.series.applyOptions({})}}const Dn=new WeakMap;function Wn(e,t){let i=Dn.get(e);return void 0===i&&(i=new $n(e,t),Dn.set(e,i)),i}function qn(e,t){return Wn(e).add(t)}const Vn=["open","high","low","close","volume","oi"],Hn=["time",...Vn],Gn=["open","high","low","close"],Un=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Kn=(e,t)=>(void 0===t.from||e>=t.from)&&(void 0===t.to||e<=t.to);function Yn(e,t,i,s,r){const n=e.primaryBars().map(({time:e,open:t,high:i,low:s,close:r,volume:n,oi:o})=>({time:e,open:t,high:i,low:s,close:r,volume:n,oi:o})),o=!1===t?[]:e.indicators().slice(),a=new Map(o.map(e=>[e.id,e])),l="boolean"==typeof t?o:t.map(e=>{const t=a.get(e);if(!t)throw new RangeError(`Unknown CSV indicator ID: ${e}`);return t}),h=Vn.map(e=>({meta:Object.freeze({key:e,title:e,kind:"primary",field:e}),values:n.map(t=>Un(t[e])),offset:0}));for(const t of l){const s=t.values();for(const r of Bi(t.indicatorId).plots){let n=0;if("display"===i){const i=t.series(r.key),s=i&&e.seriesStyle(i);if(!s)throw new Error(`CSV plot resource is unavailable: ${t.id}:${r.key}`);if(n=void 0===s.barOffset?0:s.barOffset,"number"!=typeof n||!Number.isFinite(n))throw new TypeError("CSV plot offset must be finite")}const o="display"===i&&r.ohlc?Gn:[void 0];for(const e of o){const i=`indicator:${t.id}:${r.key}${e?":"+e:""}`,o=s[e?r.ohlc[e]:r.key];h.push({meta:Object.freeze({key:i,title:e?`${r.title} ${e}`:r.title,kind:"indicator",instanceId:t.id,plotKey:r.key,...e?{field:e}:{}}),values:Array.isArray(o)?o.map(Un):[],offset:n})}}}const c=e.primaryBars();if(n.length!==c.length||n.some((e,t)=>Hn.some(i=>!Object.is(e[i],c[t][i]))))throw new Error("Chart data changed during CSV snapshot");const d=bi(e),u="display"===i?Array.from({length:e.dataLayer.length},(t,i)=>e.dataLayer.indexToTime(i)).filter(e=>!d||e<=d.time):[];if(u.some((e,t)=>!Number.isFinite(e)||t>0&&e<=u[t-1]))throw new Error("CSV axis times must be finite and increasing");const p=Object.freeze({axisTimes:Object.freeze(u),...d?{replay:Object.freeze({...d})}:{}}),_=(r??function(e){return Dn.get(e)?.list()??[]}(e)).map(e=>({symbol:e.symbol,item:e})),f=_.map(({symbol:e},t)=>{const i=`comparison:${t+1}:${e}:close`;return{meta:Object.freeze({key:i,title:e,kind:"comparison",comparisonIndex:t+1,symbol:e,field:"close"}),values:[],offset:0}});return n.forEach((e,t)=>{("source"!==i||Kn(e.time,s))&&_.forEach(({item:i},s)=>{f[s].values[t]=Un(i.barAt(e.time)?.close)})}),h.push(...f),{times:n.map(e=>e.time),columns:h,context:p}}const Xn=e=>/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e;function Jn(e){if("string"!=typeof e)throw new TypeError("CSV formatter must return a string");const t=e.charCodeAt(0);return t<=31||127===t||/^[\s\ufeff]*[=+@-]/.test(e)?"'"+e:e}const Zn=(e,t)=>Object.freeze({key:t,title:t,kind:e});function Qn(e,t){if(null===e||"object"!=typeof e)throw new TypeError("Invalid CSV options");const i=Object.getOwnPropertyDescriptor(e,t);if(i?!("value"in i):t in e)throw new TypeError(`CSV ${t} must be an own data property`);return i?.value}function eo(e,t={}){const i=function(e){if(void 0===e||!0===e)return!0;if(!1===e)return!1;if(!Array.isArray(e))throw new TypeError("CSV indicators must be a boolean or an array of instance IDs");const t=Object.getOwnPropertyDescriptors(e);if(Reflect.ownKeys(t).length!==e.length+1)throw new TypeError("Invalid CSV indicator ID array");const i=[],s=new Set;for(let r=0;r<e.length;r++){const e=t[String(r)];if(!e||!("value"in e)||"string"!=typeof e.value||0===e.value.trim().length)throw new TypeError("CSV indicator IDs must be nonempty strings in a dense data array");const n=e.value;if(s.has(n))throw new RangeError(`Duplicate CSV indicator ID: ${n}`);s.add(n),i.push(n)}return 0!==i.length&&i}(Qn(t,"indicators")),s=function(e){if(void 0===e)return{};if(null===e||"object"!=typeof e||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw new TypeError("Invalid CSV range");const t=Object.getOwnPropertyDescriptors(e);for(const e of Reflect.ownKeys(t))if("from"!==e&&"to"!==e||!("value"in t[e]))throw new TypeError("Invalid CSV range property");const i={};for(const s of["from","to"]){const r=t[s];if(!r&&s in e)throw new TypeError("CSV range bounds must be own properties");const n=r?.value;if(void 0!==n){if("number"!=typeof n||!Number.isFinite(n))throw new TypeError("CSV range bounds must be finite UTC seconds");i[s]=n}}if(void 0!==i.from&&void 0!==i.to&&i.from>i.to)throw new RangeError("CSV range is reversed");return i}(Qn(t,"range")),r=Qn(t,"alignment"),n=void 0===r?"source":r;if("source"!==n&&"display"!==n)throw new TypeError("Invalid CSV alignment");const o=Qn(t,"projectTime");if(void 0!==o&&("function"!=typeof o||"display"!==n))throw new TypeError("CSV projectTime requires display alignment and a function");const a=function(e){if(void 0===e)return{};if(null===e||"object"!=typeof e||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw new TypeError("Invalid CSV formatters");const t=Object.getOwnPropertyDescriptors(e);for(const e of Reflect.ownKeys(t))if(!["time","value","header"].includes(e)||!("value"in t[e]))throw new TypeError("Invalid CSV formatter property");const i={};for(const s of["time","value","header"]){const r=t[s];if(!r&&s in e)throw new TypeError("CSV formatters must be own properties");const n=r?.value;if(void 0!==n&&"function"!=typeof n)throw new TypeError("CSV formatters must be functions");i[s]=n}return i}(Qn(t,"formatters")),l=Yn(e,i,n,s,t.comparisons),h=function(e,t,i,s){if("source"===t)return e.times.flatMap((t,s)=>Kn(t,i)?[{time:t,values:e.columns.map(e=>e.values[s])}]:[]);const r=e.context.axisTimes,n=new Map(r.map((e,t)=>[e,t])),o=e.times.map(e=>{const t=n.get(e);if(void 0===t)throw new Error("CSV primary time is absent from the installed axis");return t}),a=new Map,l=e=>{let t=a.get(e);return t||(t={time:null,logicalIndex:e,values:[]},a.set(e,t)),t};o.forEach(l),e.columns.forEach((e,t)=>{const i=new Set;o.forEach((s,r)=>{const n=e.values[r];if("indicator"!==e.meta.kind)return void(l(s).values[t]=n);if(void 0===n)return;const o=s+e.offset;if(!Number.isFinite(o)||Math.abs(o)>Number.MAX_SAFE_INTEGER||0!==e.offset&&o===s||!Number.isInteger(e.offset)&&Number.isInteger(o)||i.has(o))throw new RangeError("CSV plot position cannot be represented safely");i.add(o),l(o).values[t]=n})});const h=[...a.values()].sort((e,t)=>e.logicalIndex-t.logicalIndex);let c;for(const t of h){const i=t.logicalIndex;if(Number.isInteger(i)&&i>=0&&i<r.length)t.time=r[i],t.origin="axis";else if(i>=0&&i<r.length-1){const e=Math.floor(i);if(t.time=r[e]+(r[e+1]-r[e])*(i-e),t.origin="interpolated",!(t.time>r[e]&&t.time<r[e+1]))throw new RangeError("CSV interpolated time collides with the axis")}else{if(t.origin="unknown",s)t.time=s(i,e.context);else if(r.length>1){const e=i<0?0:r.length-1,s=i<0?r[1]-r[0]:r[e]-r[e-1];t.time=r[e]+(i-e)*s}if(null!==t.time){if("number"!=typeof t.time||!Number.isFinite(t.time))throw new TypeError("CSV projected time must be finite or null");if(r.length&&(i<0?t.time>=r[0]:t.time<=r[r.length-1]))throw new RangeError("CSV projected time collides with the axis");t.origin="projected"}}if(null!==t.time){if(!Number.isFinite(t.time)||void 0!==c&&t.time<=c)throw new RangeError("CSV times must be strictly increasing");c=t.time}}return h.filter(e=>null===e.time?void 0===i.from&&void 0===i.to:Kn(e.time,i))}(l,n,s,o);return function(e,t,i,s){const r=[Zn("time","time"),...s.time?[Zn("timeLabel","time_label")]:[],..."display"===i?[Zn("logicalIndex","logical_index"),Zn("timeOrigin","time_origin")]:[],...e.map(e=>e.meta)],n=r.map(e=>s.header?Jn(s.header(e)):e.key),o=new Map;n.forEach(e=>o.set(e,(o.get(e)??0)+1));const a=n.map((e,t)=>s.header&&o.get(e)>1?`${r[t].key}:${e}`:e);!s.header&&"display"!==i||new Set(a).size===a.length||a.forEach((e,t)=>{a[t]=`${t+1}:${r[t].key}:${e}`});const l=[a.map(Xn).join(",")];for(const r of t){const t=null!==r.time&&Number.isFinite(r.time)?r.time:null,n=[null===t?"":String(t)];s.time&&n.push(null===t?"":Xn(Jn(s.time(t)))),"display"===i&&n.push(String(r.logicalIndex),r.origin),e.forEach((e,t)=>{const i=r.values[t];n.push(void 0===i?"":s.value?Xn(Jn(s.value(i,e.meta))):String(i))}),l.push(n.join(","))}return l.join("\r\n")+"\r\n"}(l.columns,h,n,a)}const to=Object.freeze([]),io=(e,t)=>e.length===t.length&&e.every((e,i)=>{const s=t[i];return e.id===s.id&&e.name===s.name&&e.kind===s.kind&&e.paneIndex===s.paneIndex&&e.visible===s.visible&&e.locked===s.locked&&e.selected===s.selected&&e.groupId===s.groupId&&e.dataStatus?.state===s.dataStatus?.state&&("error"!==e.dataStatus?.state||"error"===s.dataStatus?.state&&e.dataStatus.error===s.dataStatus.error)&&Object.keys(e.capabilities).every(t=>e.capabilities[t]===s.capabilities[t])});class so{constructor(e,t={}){if(Object.defineProperty(this,"_chart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_off",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_providers",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_entries",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_rows",{enumerable:!0,configurable:!0,writable:!0,value:to}),Object.defineProperty(this,"_selected",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_refreshing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_pending",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._chart=e,this._options=t,e.isDestroyed)return void(this._destroyed=!0);for(const t of["objects:change","indicatorRemoved","paneRemoved","paneMoved","paneAdded","data:context","indicator:data-status","drawing:change","drawing:select"])this._off.push(e.on(t,()=>this.refresh()));let i=e.dataLayer.length>0;this._off.push(e.on("data:range",()=>{const t=e.dataLayer.length>0;t!==i&&(i=t,this.refresh())})),this._off.push(e.on("destroy",()=>this.destroy())),this.refresh()}list(){return this._refreshing||this.refresh(),this._rows}get(e){return this._refreshing||this.refresh(),this._entries.get(e)?.row}subscribe(e){this.refresh(),this._destroyed||this._listeners.add(e);try{e(this._rows)}catch{}return()=>{this._listeners.delete(e)}}register(e){if(this._destroyed)return()=>{};if("string"!=typeof e.id||""===e.id.trim())throw new Error("An object provider needs an id");const t="custom:"+e.id;if(this._providers.has(t))throw new Error("Object provider already registered: "+e.id);const i={provider:e};this._providers.set(t,i);try{i.off=e.subscribe?.(()=>this.refresh())}catch(e){throw this._providers.get(t)===i&&this._providers.delete(t),this.refresh(),e}if(this._destroyed||this._providers.get(t)!==i){try{i.off?.()}catch{}return()=>{}}return this.refresh(),()=>{if(this._providers.get(t)===i){this._providers.delete(t);try{i.off?.()}catch{}this.refresh()}}}refresh(){if(!this._destroyed)if(this._refreshing)this._pending=!0;else{this._refreshing=!0;try{do{this._pending=!1;const e=this._read();if(this._destroyed)break;this._entries=e,null===this._selected||e.has(this._selected)||(this._selected=null);const t=Object.freeze([...e.values()].map(e=>e.row));if(!io(t,this._rows)){this._rows=t;for(const e of[...this._listeners]){if(this._destroyed)break;try{e(t)}catch{}}}}while(this._pending&&!this._destroyed)}finally{this._refreshing=!1}}}select(e,t=!1){if(this._destroyed)return!1;if(null===e)return this._selected=null,this._options.drawings?.select(null),this.refresh(),!0;const i=this.get(e);if(!i?.capabilities.select)return!1;try{return this._selected="drawing"===i.kind?null:e,e.startsWith("drawing:")?this._options.drawings?.select(i.sourceId,t):(this._options.drawings?.select(null),this._entries.get(e)?.actions.select?.()),this.refresh(),!0}catch{return this.refresh(),!1}}paneCount(){return this._chart.panes().length}canReorder(e,t){const i=this.get(e);if(!i?.capabilities.reorder||-1!==t&&1!==t)return!1;if(this._providers.has(e))return!0;const s="drawing"===i.kind?this._options.drawings?.get(i.sourceId):void 0,r=this._rows.filter(e=>e.kind===i.kind&&e.paneIndex===i.paneIndex&&(void 0===s||(this._options.drawings?.get(e.sourceId)?.zIndex??0)<0==(s.zIndex??0)<0)),n=r.findIndex(t=>t.id===e)+t;return n>=0&&n<r.length}reorder(e,t){if(!this.get(e)?.capabilities.reorder||this._destroyed)return!1;try{const i=!0===this._entries.get(e)?.actions.reorder?.(t);return this.refresh(),i}catch{return this.refresh(),!1}}move(e,t){if(!this.get(e)?.capabilities.move||this._destroyed)return!1;try{const i=!0===this._entries.get(e)?.actions.move?.(t);return this.refresh(),i}catch{return this.refresh(),!1}}canGroup(){return!this._destroyed&&"function"==typeof this._options.drawings?.createGroup}createGroup(e,t){if(!this.canGroup())return null;const i=t.flatMap(e=>{const t=this.get(e);return"drawing"===t?.kind&&e==="drawing:"+t.sourceId?[t.sourceId]:[]}),s=this._options.drawings.createGroup(e,i);return this.refresh(),s?"group:"+s.id:null}renameGroup(e,t){const i=this.get(e);if(this._destroyed||"group"!==i?.kind||e!=="group:"+i.sourceId)return!1;const s=!0===this._options.drawings?.renameGroup?.(i.sourceId,t);return this.refresh(),s}ungroup(e){const t=this._destroyed?void 0:this._entries.get(e)?.actions.ungroup;if(!t)return!1;const i=t();return this.refresh(),i}setVisible(e,t){return this._act(e,"visibility",e=>e.setVisible(t))}setLocked(e,t){return this._act(e,"lock",e=>e.setLocked(t))}remove(e){return this._act(e,"remove",e=>e.remove())}openSettings(e){return this._act(e,"settings",e=>e.openSettings())}focus(e){return this._act(e,"focus",e=>e.focus())}_act(e,t,i){const s=this.get(e);if(this._destroyed||!s?.capabilities[t])return!1;try{return i(this._entries.get(e).actions),this.refresh(),!0}catch{return this.refresh(),!1}}_read(){const e=new Map,t=this._options.drawings,i=t?.selection()??[];i.length>0&&(this._selected=null);const s=(t,i,s,r)=>{const n=Object.freeze({select:"function"==typeof r.select,visibility:"function"==typeof r.setVisible,lock:"function"==typeof r.setLocked,remove:"function"==typeof r.remove,settings:"function"==typeof r.openSettings,focus:"function"==typeof r.focus,reorder:"function"==typeof r.reorder,move:"function"==typeof r.move}),o=Object.freeze({id:t,sourceId:i,kind:s.kind,name:s.name,paneIndex:s.paneIndex??0,visible:!1!==s.visible,locked:s.locked,groupId:s.groupId,selected:!0===s.selected||this._selected===t,dataStatus:s.dataStatus?Object.freeze({...s.dataStatus}):void 0,capabilities:n});e.set(t,{row:o,actions:r})},r=e=>this._options.onSettings?{openSettings:()=>{const t=this.get(e);t&&this._options.onSettings(t)}}:{},n=this._chart;if(null!==n.primarySeries()){const e=n.getDataContext();s("source:primary","primary",{kind:"source",name:e?.symbol||"Price",visible:!1!==n.primarySeriesInfo()?.style.visible},r("source:primary"))}for(const e of n.indicators()){const t="indicator:"+e.id;s(t,e.id,{kind:"indicator",name:e.name,paneIndex:e.paneIndex,visible:e.visible(),dataStatus:e.dataStatus()??void 0},{select:()=>{},setVisible:t=>e.setVisible(t),reorder:t=>n.reorderIndicator(e.id,t),move:t=>n.moveIndicator(e.id,t),remove:()=>{n.removeIndicator(e.id)},...r(t)})}if(t){const e=e=>!1!==e.policy?.listed,o=new Map;for(const r of t.groups?.()??[]){const n=r.members.flatMap(e=>{const i=t.get(e);return i?[i]:[]}),a=n.filter(e);if(!a.length)continue;const l="group:"+r.id;for(const e of a)o.set(e.id,l);const h=e=>{if(t.updateMany)t.updateMany(a.map(t=>({id:t.id,patch:e})));else for(const i of a)t.update(i.id,e)},c=a.filter(e=>!1!==e.policy?.selectable),d=a.length===n.length,u=d?t.removeGroup&&(()=>{t.removeGroup(r.id,!0)}):t.removeMany&&(()=>{t.removeMany(a.map(e=>e.id))});s(l,r.id,{kind:"group",name:r.name,paneIndex:a[0].paneIndex,visible:a.some(e=>!1!==e.visible),locked:a.every(e=>!0===e.locked),selected:c.length>0&&c.every(e=>i.includes(e.id))},{...c.length?{select:()=>t.select(c.map(e=>e.id))}:{},...d&&t.removeGroup?{ungroup:()=>!0===t.removeGroup(r.id,!1)}:{},...a.every(e=>!1!==e.policy?.editable)?{setVisible:e=>h({visible:e}),setLocked:e=>h({locked:e}),...u?{remove:u}:{}}:{}})}for(const a of[...t.drawings()].filter(e).sort((e,t)=>(e.zIndex??0)-(t.zIndex??0))){const e="drawing:"+a.id,l=n.dataLayer.length>0&&a.points.length>0&&a.points.every(e=>Number.isFinite(e.time)&&Number.isFinite(e.price))&&void 0!==n.panes()[a.paneIndex];s(e,a.id,{kind:"drawing",groupId:o.get(a.id),name:a.tool.replace(/-/g," ").replace(/^./,e=>e.toUpperCase()),paneIndex:a.paneIndex,visible:!1!==a.visible,locked:!0===a.locked,selected:i.includes(a.id)},{...t.reorder?{reorder:e=>t.reorder(a.id,e)}:{},...!1!==a.policy?.selectable?{select:()=>t.select(a.id)}:{},...!1!==a.policy?.editable?{setVisible:e=>t.update(a.id,{visible:e}),setLocked:e=>t.update(a.id,{locked:e}),remove:()=>{t.remove(a.id)}}:{},...l?{focus:()=>this._focusDrawing(a)}:{},...r(e)})}}for(const[e,{provider:t}]of this._providers)try{const i=t.get();if(!i||"string"!=typeof i.name||!["source","indicator","drawing","profile","group"].includes(i.kind))continue;s(e,t.id,i,t)}catch{}return e}_focusDrawing(e){const t=this._chart,i=e.points.map(e=>t.dataLayer.timeToIndexFloat(e.time));if(!i.every(Number.isFinite))return;const s=Math.min(...i),r=Math.max(...i),n=t.getVisibleLogicalRange(),o=Math.max(n.to-n.from,1.2*(r-s),10),a=t.panes()[e.paneIndex].readoutScale(),l=e.points.map(e=>e.price),h=Math.min(...l),c=Math.max(...l),d=Math.max(.15*(c-h),.001*Math.abs(c),a.options.minMove);a.setAutoScale(!1),a.setPriceRange({min:h-d,max:c+d});const u=t.maximizedPane();null!==u&&u!==e.paneIndex&&t.maximizePane(u),t.setPaneCollapsed(e.paneIndex,!1),t.setVisibleLogicalRange({from:(s+r-o)/2,to:(s+r+o)/2})}destroy(){if(this._destroyed)return;this._destroyed=!0;for(const e of this._off.splice(0))e();const e=[...this._providers.values()];this._providers.clear(),this._entries.clear(),this._rows=to,this._selected=null;for(const{off:t}of e)try{t?.()}catch{}const t=[...this._listeners];this._listeners.clear();for(const e of t)try{e(to)}catch{}}}const ro=new Set([..."precision priceLineVisible lastValueVisible colorByPreviousClose upColor downColor bodyVisible borderUpColor borderDownColor borderVisible wickUpColor wickDownColor wickVisible topColor bottomColor closeColor color lineWidth lineStyle areaTopColor areaBottomColor".split(" ").map(e=>`symbol.${e}`),..."titleMode title logo marketStatus chartValues barChange volume openInterest lastDayChange lastValueLabel background backgroundColor backgroundOpacity".split(" ").map(e=>`statusLine.${e}`),..."visible color opacity fontSize".split(" ").map(e=>`watermark.${e}`),..."mode autoScale inverted".split(" ").map(e=>`scales.${e}`),"axisChrome.sessionClock","axisChrome.barCountdown",..."grid.vertLines grid.vertColor grid.vertStyle grid.horzLines grid.horzColor grid.horzStyle grid.lineWidth grid.spacing crosshairMode crosshairSnapToBar crosshair.color crosshair.style crosshair.width scales.textColor scales.fontSize scales.lineColor margins.top margins.bottom".split(" ").map(e=>`canvas.${e}`)]);function no(e){const t={};for(const[i,s]of Object.entries(e))ro.has(i)&&("string"==typeof s||"boolean"==typeof s||"number"==typeof s&&Number.isFinite(s))&&(t[i]=s);return t}function oo(e,t,i,s,r,n){return{input:{key:e,type:"boolean",label:t,default:s,group:i},fields:[{key:e,read:r,write:(e,t)=>n(e,!0===t)}]}}function ao(e,t,i,s,r,n){return{input:{key:e,type:"color",label:t,default:s,group:i},fields:[{key:e,read:r,write:(e,t)=>n(e,String(t))}]}}function lo(e,t,i,s,r,n,o){return{input:{key:e,type:"number",label:t,default:s,min:r.min,max:r.max,step:r.step,group:i},fields:[{key:e,read:n,write:(e,t)=>o(e,Number(t))}]}}function ho(e,t,i,s,r,n,o,a){return{input:{key:e,type:"select",label:t,default:s,options:r,group:i,tooltip:a},fields:[{key:e,read:n,write:(e,t)=>o(e,String(t))}]}}function co(e,t,i,s,r,n){const o={key:e,type:"colorPair",label:t,group:i,up:{key:s.key,label:s.label,default:s.def},down:{key:r.key,label:r.label,default:r.def}},a=[{key:s.key,read:s.get,write:(e,t)=>s.set(e,String(t))},{key:r.key,read:r.get,write:(e,t)=>r.set(e,String(t))}];return void 0!==n&&(o.enabled={key:n.key,default:n.def},a.unshift({key:n.key,read:n.get,write:(e,t)=>n.set(e,!0===t)})),{input:o,fields:a}}const uo=[{label:"Solid",value:"solid"},{label:"Dashed",value:"dashed"},{label:"Dotted",value:"dotted"}],po=[{label:"Default",value:"default"},...Array.from({length:9},(e,t)=>({label:String(t),value:String(t)}))],_o=e=>e.primarySeriesInfo()?.style??{},fo=(e,t)=>{e.primarySeries()?.applyOptions(t)},mo=(e,t,i)=>fo(e,{[t]:i});function bo(e,t,i,s,r,n){const o=e=>({key:`symbol.${e.key}`,label:e.label,def:e.def,get:t=>_o(t)[e.key]??e.def,set:(t,i)=>mo(t,e.key,i)}),a=void 0===n?void 0:{key:`symbol.${n.key}`,def:!0,get:e=>!1!==_o(e)[n.key],set:(e,t)=>mo(e,n.key,t)};return co(e,t,i,o(s),o(r),a)}const go=e=>Math.round(1e3*e)/10;const vo=e=>oo("symbol.colorByPreviousClose","Color from previous close",e,!1,e=>!0===_o(e).colorByPreviousClose,(e,t)=>fo(e,{colorByPreviousClose:t}));function yo(e){const t=e.theme(),i=e.primarySeriesInfo()?.type,s=[];if(void 0===i)return[];if("candlestick"===i||"hollow-candle"===i||"volume-candle"===i)s.push(bo("symbol.body","Body","Candles",{key:"upColor",label:"Up",def:t.upColor},{key:"downColor",label:"Down",def:t.downColor},{key:"bodyVisible"}),bo("symbol.borders","Borders","Candles",{key:"borderUpColor",label:"Up",def:t.upColor},{key:"borderDownColor",label:"Down",def:t.downColor},{key:"borderVisible"}),bo("symbol.wick","Wick","Candles",{key:"wickUpColor",label:"Up",def:t.wickUpColor},{key:"wickDownColor",label:"Down",def:t.wickDownColor},{key:"wickVisible"}),vo("Candles"));else if("bar"===i||"high-low"===i||"column"===i){const e="column"===i?"Columns":"Bars";s.push(bo("symbol.body","column"===i?"Columns":"Bars",e,{key:"upColor",label:"Up",def:t.upColor},{key:"downColor",label:"Down",def:t.downColor})),"column"!==i&&s.push(vo(e))}else"baseline"===i?s.push(bo("symbol.baseline","Line","Baseline",{key:"topColor",label:"Above",def:t.baselineTopLine},{key:"bottomColor",label:"Below",def:t.baselineBottomLine})):"hlc-area"===i?s.push(ao("symbol.closeColor","Close line","Line",t.lineColor,e=>_o(e).closeColor??t.lineColor,(e,t)=>fo(e,{closeColor:t}))):s.push(ao("symbol.color","Line","Line",t.lineColor,e=>_o(e).color??t.lineColor,(e,t)=>fo(e,{color:t}))),"histogram"!==i&&s.push(lo("symbol.lineWidth","Thickness","Line",1.5,{min:.5,max:8,step:.5},e=>_o(e).lineWidth??1.5,(e,t)=>fo(e,{lineWidth:t}))),"line"!==i&&"line-markers"!==i&&"step"!==i||s.push(ho("symbol.lineStyle","Line style","Line","solid",uo,e=>_o(e).lineStyle??"solid",(e,t)=>fo(e,{lineStyle:t}))),"area"===i?s.push(bo("symbol.fill","Fill","Line",{key:"areaTopColor",label:"Top",def:t.areaTopColor},{key:"areaBottomColor",label:"Bottom",def:t.areaBottomColor})):"baseline"===i?s.push(bo("symbol.fill","Fill","Baseline",{key:"areaTopColor",label:"Above",def:t.baselineTopFill},{key:"areaBottomColor",label:"Below",def:t.baselineBottomFill})):"hlc-area"===i&&s.push(ao("symbol.areaTopColor","Band","Line",t.areaTopColor,e=>_o(e).areaTopColor??t.areaTopColor,(e,t)=>fo(e,{areaTopColor:t})));return[...s,ho("symbol.precision","Precision","Values","default",po,e=>{const t=_o(e).precision;return void 0===t?"default":String(t)},(e,t)=>fo(e,{precision:"default"===t?void 0:Number(t)})),oo("symbol.priceLineVisible","Price line","Values",!0,e=>!1!==_o(e).priceLineVisible,(e,t)=>fo(e,{priceLineVisible:t})),oo("symbol.lastValueVisible","Last value label","Values",!0,e=>!1!==_o(e).lastValueVisible,(e,t)=>fo(e,{lastValueVisible:t}))]}const wo=[{label:"Symbol",value:"symbol"},{label:"Description",value:"description"},{label:"Ticker",value:"ticker"}];function xo(e,t,i){return oo(`statusLine.${e}`,t,i,!0,t=>!1!==t.statusLineOptions()[e],(t,i)=>t.setStatusLineOptions({[e]:i}))}function So(e){const t=e.theme();return[xo("logo","Logo","Show"),xo("title","Title","Show"),ho("statusLine.titleMode","Title shows","Show","symbol",wo,e=>e.statusLineOptions().titleMode??"symbol",(e,t)=>e.setStatusLineOptions({titleMode:t})),xo("marketStatus","Session state","Show"),xo("chartValues","Open, high, low, close","Show"),xo("barChange","Bar change","Show"),xo("volume","Volume","Show"),oo("statusLine.openInterest","Open interest","Show",!1,e=>!0===e.statusLineOptions().openInterest,(e,t)=>e.setStatusLineOptions({openInterest:t})),xo("lastDayChange","Change since previous close","Show"),xo("lastValueLabel","Indicator values","Show"),oo("statusLine.indicatorsCollapsed","Collapse indicator legends","Show",!1,e=>e.indicatorLegendCollapsed(),(e,t)=>e.setIndicatorLegendCollapsed(t)),oo("statusLine.background","Background","Background",!1,e=>!0===e.statusLineOptions().background,(e,t)=>e.setStatusLineOptions({background:t})),ao("statusLine.backgroundColor","Color","Background",t.background,e=>e.statusLineOptions().backgroundColor??t.background,(e,t)=>e.setStatusLineOptions({backgroundColor:t})),lo("statusLine.backgroundOpacity","Opacity","Background",.8,{min:0,max:1,step:.05},e=>e.statusLineOptions().backgroundOpacity??.8,(e,t)=>e.setStatusLineOptions({backgroundOpacity:t}))]}const Po=[{label:"Regular",value:"linear"},{label:"Logarithmic",value:"logarithmic"},{label:"Percent",value:"percentage"},{label:"Indexed to 100",value:"indexed-to-100"}],Oo=["UTC","Europe/London","Europe/Berlin","Europe/Moscow","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Hong_Kong","Asia/Tokyo","Australia/Sydney","America/Sao_Paulo","America/New_York","America/Chicago","America/Los_Angeles"];function ko(e){const t=e.timezone();return(Oo.includes(t)?Oo:[...Oo,t]).map(e=>({label:e,value:e}))}function Io(e){const t=[oo("navigation.panEnabled","Enable panning","Navigation",!0,e=>!1!==e.navigationOptions().panEnabled,(e,t)=>e.setNavigationOptions({panEnabled:t})),oo("navigation.zoomEnabled","Enable zooming","Navigation",!0,e=>!1!==e.navigationOptions().zoomEnabled,(e,t)=>e.setNavigationOptions({zoomEnabled:t})),ho("navigation.mousePan","Mouse drag","Navigation","both",[{label:"Horizontal only",value:"horizontal"},{label:"Time and price",value:"both"}],e=>e.navigationOptions().mousePan,(e,t)=>e.setNavigationOptions({mousePan:t})),lo("navigation.defaultVisibleBars","Default visible bars (0 = all)","Navigation",0,{min:0,max:1e5,step:1},e=>e.navigationOptions().defaultVisibleBars,(e,t)=>e.setNavigationOptions({defaultVisibleBars:t})),lo("navigation.defaultBarSpacing","Default bar spacing (0 = use bar count)","Navigation",0,{min:0,max:1e4,step:.5},e=>e.navigationOptions().defaultBarSpacing??0,(e,t)=>e.setNavigationOptions({defaultBarSpacing:t})),ho("scales.mode","Scale","Price scale","linear",Po,e=>e.priceScaleOptions().mode,(e,t)=>e.setPriceScaleOptions({mode:t}),"Regular plots the price. Logarithmic gives equal space to equal percentage moves. Percent and Indexed to 100 both rebase to the left edge of the visible range, the first as a change from it, the second as a level starting at 100."),oo("scales.autoScale","Auto (fits data to screen)","Price scale",!0,e=>e.panes()[0].priceScale.autoScale,(e,t)=>e.setAutoScale(t)),oo("scales.priceOnly","Fit primary prices only","Price scale",!1,e=>e.priceOnlyAutoScale(),(e,t)=>e.setPriceOnlyAutoScale(t)),oo("scales.inverted","Invert scale","Price scale",!1,e=>e.priceScaleOptions().inverted,(e,t)=>e.setPriceScaleOptions({inverted:t})),ho("time.timezone","Timezone","Time axis",Me,ko(e),e=>e.timezone(),(e,t)=>{Ae(t)&&e.setTimezone(t)},"The calendar the axis and crosshair label in, and the one every session-anchored study resets on. Changing it moves VWAP and pivot values, not only the labels."),oo("axisChrome.sessionClock","Corner clock","Axis chrome",!1,e=>void 0!==e.axisChromeOptions().sessionClock&&!1!==e.axisChromeOptions().sessionClock,(e,t)=>e.setAxisChromeOptions({sessionClock:t}))];return function(e){const t=e.primarySeriesInfo()?.type;return void 0!==t&&le(t).isPriceSeries}(e)&&t.push(oo("axisChrome.barCountdown","Countdown to bar close","Axis chrome",!1,e=>!0===e.axisChromeOptions().barCountdown,(e,t)=>e.setAxisChromeOptions({barCountdown:t}))),t}const Mo=[{label:"Cross",value:"normal"},{label:"Magnet",value:"magnet"}];function To(e){const t=e.theme(),i=e=>e.gridOptions(),s=e=>e.canvasOptions().crosshair??{},r=e=>e.canvasOptions().scales??{};return[oo("watermark.visible","Show watermark","Watermark",!1,e=>e.watermarkOptions().visible??!1,(e,t)=>e.setWatermarkOptions({visible:t})),{input:{key:"watermark.text",type:"text",label:"Text (blank uses symbol and interval)",group:"Watermark",default:""},fields:[{key:"watermark.text",read:e=>e.watermarkOptions().text??"",write:(e,t)=>e.setWatermarkOptions({text:String(t)})}]},ao("watermark.color","Color","Watermark","#9aa4b2",e=>e.watermarkOptions().color??"#9aa4b2",(e,t)=>e.setWatermarkOptions({color:t})),lo("watermark.opacity","Opacity","Watermark",.08,{min:0,max:1,step:.01},e=>e.watermarkOptions().opacity??.08,(e,t)=>e.setWatermarkOptions({opacity:t})),lo("watermark.fontSize","Text size","Watermark",64,{min:10,max:200,step:1},e=>e.watermarkOptions().fontSize??64,(e,t)=>e.setWatermarkOptions({fontSize:t})),oo("canvas.grid.vertLines","Vert grid lines","Grid",!0,e=>e.gridOptions().vertLines,(e,t)=>e.setGridOptions({vertLines:t})),ao("canvas.grid.vertColor","Vert color","Grid",t.grid,e=>i(e)?.vertColor??t.grid,(e,t)=>e.setGridOptions({vertColor:t})),ho("canvas.grid.vertStyle","Vert style","Grid",t.gridStyle??"solid",uo,e=>i(e)?.vertStyle??t.gridStyle??"solid",(e,t)=>e.setGridOptions({vertStyle:t})),oo("canvas.grid.horzLines","Horz grid lines","Grid",!0,e=>e.gridOptions().horzLines,(e,t)=>e.setGridOptions({horzLines:t})),ao("canvas.grid.horzColor","Horz color","Grid",t.grid,e=>i(e)?.horzColor??t.grid,(e,t)=>e.setGridOptions({horzColor:t})),ho("canvas.grid.horzStyle","Horz style","Grid",t.gridStyle??"solid",uo,e=>i(e)?.horzStyle??t.gridStyle??"solid",(e,t)=>e.setGridOptions({horzStyle:t})),lo("canvas.grid.lineWidth","Width","Grid",1,{min:1,max:4,step:1},e=>i(e)?.lineWidth??1,(e,t)=>e.setGridOptions({lineWidth:t})),lo("canvas.grid.spacing","Spacing","Grid",60,{min:20,max:200,step:10},e=>i(e)?.spacing??60,(e,t)=>e.setGridOptions({spacing:t})),ho("canvas.crosshairMode","Mode","Crosshair","normal",Mo,e=>e.crosshairMode(),(e,t)=>e.applyOptions({crosshairMode:"magnet"===t?"magnet":"normal"})),oo("canvas.crosshairSnapToBar","Snap to candle center","Crosshair",!1,e=>e.crosshairSnapToBar(),(e,t)=>e.applyOptions({crosshairSnapToBar:t})),ao("canvas.crosshair.color","Color","Crosshair",t.crosshair,e=>s(e).color??t.crosshair,(e,t)=>e.setCanvasOptions({crosshair:{color:t}})),ho("canvas.crosshair.style","Style","Crosshair",t.crosshairStyle??"dashed",uo,e=>s(e).style??t.crosshairStyle??"dashed",(e,t)=>e.setCanvasOptions({crosshair:{style:t}})),lo("canvas.crosshair.width","Width","Crosshair",1,{min:1,max:4,step:1},e=>s(e).width??t.crosshairWidth??1,(e,t)=>e.setCanvasOptions({crosshair:{width:t}})),ao("canvas.scales.textColor","Text color","Scale text",t.axisText,e=>r(e).textColor??t.axisText,(e,t)=>e.setCanvasOptions({scales:{textColor:t}})),lo("canvas.scales.fontSize","Text size","Scale text",t.axisFontSize??11,{min:10,max:14,step:1},e=>r(e).fontSize??t.axisFontSize??11,(e,t)=>e.setCanvasOptions({scales:{fontSize:t}})),ao("canvas.scales.lineColor","Lines color","Scale text",t.axisLine,e=>r(e).lineColor??t.axisLine,(e,t)=>e.setCanvasOptions({scales:{lineColor:t}})),lo("canvas.margins.top","Top margin %","Plot margins",10,{min:0,max:49,step:1},e=>go(e.priceScaleOptions().marginTop),(e,t)=>e.setCanvasOptions({margins:{top:t}})),lo("canvas.margins.bottom","Bottom margin %","Plot margins",10,{min:0,max:49,step:1},e=>go(e.priceScaleOptions().marginBottom),(e,t)=>e.setCanvasOptions({margins:{bottom:t}}))]}function Co(e){const t=(t,i,s)=>function(e,t,i,s){return{key:`trading.${t}`,label:s,def:e.tradingSettings()[i],get:e=>e.tradingSettings()[i],set:(e,i)=>e.setTradingSettings({[t]:i})}}(e,t,i,s);return[co("trading.positions","Position","Positions",t("longColor","long","Long"),t("shortColor","short","Short")),ao("trading.orderColor","Order","Orders",e.tradingSettings().order,e=>e.tradingSettings().order,(e,t)=>e.setTradingSettings({orderColor:t})),co("trading.bracket","Bracket","Orders",t("tpColor","tp","Take profit"),t("slColor","sl","Stop loss")),co("trading.executions","Execution","Executions",t("buyColor","buy","Buy"),t("sellColor","sell","Sell"))]}function jo(e){return[{id:"price",label:"Price",controls:yo(e)},{id:"readout",label:"Readout",controls:So(e)},{id:"axes",label:"Axes",controls:Io(e)},{id:"appearance",label:"Appearance",controls:To(e)},{id:"trading",label:"Trading",controls:Co(e)}]}function Ao(e){return jo(e).map(e=>({id:e.id,label:e.label,inputs:e.controls.map(e=>e.input)}))}function Lo(e){const t={};for(const i of jo(e))for(const s of i.controls)for(const i of s.fields)t[i.key]=i.read(e);return t}function Ro(e,t){const i=new Map,s={};for(const t of jo(e))for(const e of t.controls)for(const t of e.fields)i.set(t.key,t);for(const r of Object.keys(t)){const n=t[r];if(void 0===n)continue;const o=i.get(r);o&&(o.write(e,n),s[r]=o.read(e))}const r=no(s);Object.keys(r).length&&e.emit("style:change",r)}function zo(e,t){return e.map((i,s)=>{const r=i.time,n=t(i,s),o=e[s+1]?.time;if(!Number.isFinite(r)||!Number.isFinite(n)||n<r||s>0&&r<=e[s-1].time||void 0!==o&&n>o)throw new Error("openalgo-charts: replay time must be finite, ordered and within its candle interval");return n})}class Fo{constructor(e,t,i){if(Object.defineProperty(this,"points",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"ends",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.ends=zo(e,i.barEndTime),t.length&&!i.subBarEndTime)throw new Error("openalgo-charts: replay timing needs subBarEndTime");const s=t.length?zo(t,i.subBarEndTime):[];let r=0;for(let i=0;i<e.length;i++){const n=e[i],o=this.ends[i],a=this.points.length;for(;r<t.length&&t[r].time<n.time;)r++;let l,h=n.time,c=!1;for(;r<t.length&&t[r].time<o;){const e=t[r],a=s[r++];if((e.time!==h||a>o)&&(c=!0),c)continue;if(h=a,l?(l.high=Math.max(l.high,e.high),l.low=Math.min(l.low,e.low),l.close=e.close,l.volume=(l.volume??0)+(e.volume??0),void 0!==e.oi&&(l.oi=e.oi)):l={...e,time:n.time},a>=o)continue;const d=this.points[this.points.length-1];d?.index===i&&d.time===a?d.bar={...l}:this.points.push({time:a,index:i,subIndex:0,subSteps:0,bar:{...l}})}this.points.push({time:o,index:i,subIndex:0,subSteps:0,bar:n});const d=this.points.length-a;this.steps[i]=d;for(let e=a;e<this.points.length;e++)this.points[e].subIndex=e-a,this.points[e].subSteps=d}}at(e){let t=0,i=this.points.length;for(;t<i;){const s=t+i>>>1;this.points[s].time<=e?t=s+1:i=s}return t-1}}const No=(e,t)=>{const i=setInterval(e,t);return()=>clearInterval(i)};function Eo(e,t){let i=0,s=e.length;for(;i<s;){const r=i+s>>1;e[r].time<=t?i=r+1:s=r}return i}function Bo(e,t,i,s){const r=e[t];let n=r.high,o=r.low,a=r.volume??0,l=r.oi;for(let s=t+1;s<=i;s++){const t=e[s];t.high>n&&(n=t.high),t.low<o&&(o=t.low),a+=t.volume??0,void 0!==t.oi&&(l=t.oi)}return{time:s,open:r.open,high:n,low:o,close:e[i].close,volume:a,...void 0===l?{}:{oi:l}}}class $o{constructor(e,t={}){Object.defineProperty(this,"_chart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_series",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_bars",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_restore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_restoreConfirmation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_view",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_onFrame",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schedule",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_barMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_startIndex",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timeline",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_startTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_time",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pointIndex",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"_subBars",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subCount",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_intra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_speed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_index",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sub",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_playing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_active",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_transition",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_cancel",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_interval",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastAdvance",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_tick",{enumerable:!0,configurable:!0,writable:!0,value:()=>{if(!this._playing)return;const e=this._now();let t=Math.floor((e-this._lastAdvance)/this._interval);t<=0||(t>10?(t=10,this._lastAdvance=e):this._lastAdvance+=t*this._interval,this._advance(t),this._atEnd()&&this._end())}}),this._chart=e;const i=t.series,s=void 0===i?[]:"setData"in i?[i]:[...i];if(0===s.length){const t=e.primarySeries?.()??null;if(null===t)throw new Error("openalgo-charts: replay needs a series to drive (pass options.series)");s.push(t)}this._series=s,this._restore=s.map(e=>e.getData()),this._restoreConfirmation=s.map(_i),this._bars=t.bars??this._restore[0],this._view={barSpacing:e.timeScale.barSpacing,rightOffset:e.timeScale.rightOffset},this._subBars=t.subBars??[],this._intra=this._subBars.length>0&&this._bars.length>0;const r=this._buildBuckets();if(this._subStart=r.start,this._subCount=r.count,this._startIndex=h(Math.floor(t.startIndex??0),0,Math.max(0,this._bars.length-1)),this._index=this._startIndex,this._timeline=t.timing?new Fo(this._bars,this._subBars,t.timing):null,!(void 0===t.startTime||this._timeline&&Number.isFinite(t.startTime)))throw new Error("openalgo-charts: replay start time must be finite and requires timing");this._startTime=t.startTime??this._timeline?.ends[this._startIndex]??null,this._time=this._startTime,this._timeline&&(this._index=-1);const n=t.barMs??1e3;this._barMs=n>0?n:1e3;const o=t.speed??1;this._speed=o>0?o:1,this._onFrame=t.onFrame??null,this._now=t.now??(()=>"undefined"!=typeof performance?performance.now():0),this._schedule=t.scheduler??No,!1!==t.autoStart&&(this._timeline?null!==this._startTime&&this.seekTime(this._startTime):this._apply(this._startIndex,this._steps(this._startIndex)-1))}_buildBuckets(){const e=this._bars.length,t=new Int32Array(e),i=new Int32Array(e);if(!this._intra)return{start:t,count:i};const s=this._subBars;let r=-1;for(let n=0;n<s.length;n++){const o=s[n].time;for(;r+1<e&&this._bars[r+1].time<=o;)r++,t[r]=n;r>=0&&i[r]++}return{start:t,count:i}}_steps(e){return this._timeline?this._timeline.steps[e]??1:this._intra?Math.max(1,this._subCount[e]):1}seek(e){if(this._timeline){const t=this._timeline.ends[h(Math.floor(e),0,Math.max(0,this._bars.length-1))];return void(void 0!==t&&this.seekTime(t))}this._apply(e,this._steps(h(Math.floor(e),0,Math.max(0,this._bars.length-1)))-1)}seekTime(e){if(!this._timeline)throw new Error("openalgo-charts: replay seekTime requires timing");if(!Number.isFinite(e))throw new Error("openalgo-charts: replay time must be finite");const t=this._timeline.at(e),i=this._time!==e;if(this._time=e,this._active&&t===this._pointIndex){if(i){const i=this._timeline.points[t];vi(this._chart,{time:i?.bar.time??Number.NEGATIVE_INFINITY,asOf:e,forming:!!i&&i.subIndex<i.subSteps-1})}return}const s=!this._active,r=this._timeline.points[t];this._active=!0,this._pointIndex=t,this._index=r?.index??-1,this._sub=r?.subIndex??0;const n=this._bars.slice(0,this._index+1);r&&(n[this._index]=r.bar),this._write(n,!!r&&r.subIndex<r.subSteps-1,s)}time(){return this._timeline?this._time:this.state().bar?.time??null}timePoints(){if(!this._timeline)throw new Error("openalgo-charts: replay timePoints requires timing");return this._timeline.points.map(e=>e.time)}step(e=1){this._advance(e)}stepBack(e=1){this._advance(-e)}_advance(e){if(this._timeline){if(!Number.isFinite(e))throw new Error("openalgo-charts: replay step must be finite");const t=Math.trunc(e);if(0===t||t<0&&this._pointIndex<0)return;const i=h(this._pointIndex+t,0,this._timeline.points.length-1),s=this._timeline.points[i];return void(s&&this.seekTime(s.time))}if(!this._intra)return void this._apply(this._index+e,0);let t=this._index,i=this._sub;const s=this._bars.length-1;for(let r=0;r<Math.abs(e);r++)if(e>0)if(i+1<this._steps(t))i++;else{if(!(t<s))break;t++,i=0}else if(i>0)i--;else{if(!(t>0))break;t--,i=this._steps(t)-1}this._apply(t,i)}play(e={}){const t=e.speed;void 0!==t&&t>0&&(this._speed=t),0!==this._bars.length&&(this._timeline?null!==this._time&&this.seekTime(this._time):this._apply(this._index,this._sub),this._atEnd()?this._end():(this._stopTimer(),this._interval=this._barMs/this._speed,this._lastAdvance=this._now(),this._playing=!0,this._cancel=this._schedule(this._tick,this._interval),this._chart.emit("replay:play",this.state())))}pause(){this._playing&&(this._playing=!1,this._stopTimer(),this._chart.emit("replay:pause",this.state()))}stop(){if(this._playing=!1,this._stopTimer(),!this._active)return;const e=++this._transition;if(this._active=!1,this._index=this._startIndex,this._sub=0,this._timeline){this._time=this._startTime,this._pointIndex=null===this._time?-1:this._timeline.at(this._time);const e=this._timeline.points[this._pointIndex];this._index=e?.index??-1,this._sub=e?.subIndex??0}if(vi(this._chart),e!==this._transition)return;for(let t=0;t<this._series.length;t++)if(this._series[t].setData(this._restore[t],this._restoreConfirmation[t]),e!==this._transition)return;const t=this._chart.timeScale;t.setBarSpacing(this._view.barSpacing),e===this._transition&&(t.setRightOffset(this._view.rightOffset),e===this._transition&&this._chart.emit("replay:stop",this.state()))}state(){const e=this._bars.length,t=0===e?1:this._steps(this._index);let i=null;if(this._timeline)i=this._timeline.points[this._pointIndex]?.bar??null;else if(e>0&&(i=this._bars[this._index],this._intra&&this._sub<t-1&&this._subCount[this._index]>0)){const e=this._subStart[this._index];i=Bo(this._subBars,e,e+this._sub,i.time)}return{index:this._index,total:e,playing:this._playing,speed:this._speed,bar:i,subIndex:this._sub,subSteps:t}}_apply(e,t=0){const i=this._bars.length;if(0===i)return;const s=h(Math.floor(e),0,i-1),r=this._steps(s),n=h(Math.floor(t),0,r-1);if(this._active&&s===this._index&&n===this._sub)return;const o=!this._active;this._active=!0,this._index=s,this._sub=n;const a=this._bars.slice(0,s+1);if(this._intra&&n<r-1&&this._subCount[s]>0){const e=this._subStart[s];a[s]=Bo(this._subBars,e,e+n,this._bars[s].time)}const l=this._intra&&n<r-1;this._write(a,l,o)}_write(e,t,i){const s=++this._transition,r=e[e.length-1]?.time??Number.NEGATIVE_INFINITY;if(vi(this._chart,{time:r,forming:t,...this._timeline&&null!==this._time?{asOf:this._time}:{}}),s!==this._transition)return;if(this._series[0].setData(e),s!==this._transition)return;const n=t?e[e.length-2]?.time??Number.NEGATIVE_INFINITY:r;for(let e=1;e<this._series.length;e++){const t=this._restore[e];if(this._series[e].setData(t.slice(0,Eo(t,n))),s!==this._transition)return}if(i&&this._chart.emit("replay:start",this.state()),s!==this._transition)return;const o=this.state();this._onFrame?.(o),s===this._transition&&this._chart.emit("replay:frame",o)}_atEnd(){if(this._timeline)return this._pointIndex>=this._timeline.points.length-1;const e=this._bars.length-1;return this._index>=e&&this._sub>=this._steps(e)-1}_end(){this.pause(),this._chart.emit("replay:end",this.state())}_stopTimer(){this._cancel?.(),this._cancel=null}}class Do extends $o{constructor(e,t,i){super(e,{...t,autoStart:!1}),Object.defineProperty(this,"_transport",{enumerable:!0,configurable:!0,writable:!0,value:i})}state(){return{...super.state(),...this._transport()}}}const Wo=new WeakMap,qo=e=>new Error("openalgo-charts: replay group "+e);function Vo(e,t){if(!Number.isFinite(e))throw qo(t+" must be finite")}function Ho(e,t){if(Vo(e,t),e<=0)throw qo(t+" must be positive")}function Go(e,t){if(null===t)return-1;let i=0,s=e.length;for(;i<s;){const r=i+s>>>1;e[r]<=t?i=r+1:s=r}return i-1}class Uo{constructor(e,t={}){if(Object.defineProperty(this,"_members",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_activeIds",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_times",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_scope",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_focusedId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_time",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_startTime",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_active",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_playing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_busy",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_closing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_revision",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_speed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_barMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_scheduler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_onChange",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_cancel",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_clockRevision",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastAdvance",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_pending",{enumerable:!0,configurable:!0,writable:!0,value:[]}),!e.length)throw qo("needs at least one member");this._scope=t.scope??"focused",this._focusedId=t.focusedId??e[0].id,this._speed=t.speed??1,this._barMs=t.barMs??1e3,Ho(this._speed,"speed"),Ho(this._barMs,"barMs"),Ho(this._barMs/this._speed,"clock interval"),void 0!==t.startTime&&Vo(t.startTime,"start time"),this._now=t.now??(()=>performance.now()),this._scheduler=t.scheduler??((e,t)=>{const i=setInterval(e,Math.min(2147483647,Math.max(1,t)));return()=>clearInterval(i)}),this._onChange=t.onChange;const i=new Set,s=new Set;for(const t of e){if("string"!=typeof t.id||!t.id.trim()||i.has(t.id))throw qo("member id must be unique and nonempty");if(s.has(t.chart))throw qo("cannot drive the same chart twice");if(Wo.has(t.chart))throw qo("chart already has a replay group owner");if(t.chart.isDestroyed)throw qo("cannot own a destroyed chart");if(bi(t.chart))throw qo("chart already has active replay");if("function"!=typeof t.options?.timing?.barEndTime)throw qo("member needs explicit timing");i.add(t.id),s.add(t.chart)}this._validateScope(this._scope,this._focusedId,i);for(const t of e){const e={id:t.id,chart:t.chart,options:{...t.options,timing:{...t.options.timing}}};this._members.push({...e,controller:this._prepare(e),dead:!1})}this._execute(()=>{for(const e of this._members)Wo.set(e.chart,this),e.dispose=e.chart.on?.("destroy",()=>this._chartGone(e));this._rebuildTimes(),this._startTime=t.startTime??this._times[0]??null,this._apply(this._startTime)})}state(){return{active:this._active,destroyed:this._destroyed,scope:this._scope,focusedId:this._focusedId,time:this._time,index:Go(this._times,this._time),total:this._times.length,playing:this._playing,speed:this._speed,members:this._members.map(e=>({id:e.id,active:this._activeIds.has(e.id),state:e.controller.state()}))}}seekTime(e){if(Vo(e,"time"),this._check(),this._active&&e===this._time)return;const t=this._prepareEntering();this._execute(()=>{this._install(t),this._apply(e)})}seek(e){Vo(e,"index"),this._check();const t=this._prepareEntering();this._execute(()=>{this._install(t);const i=this._times[Math.max(0,Math.min(this._times.length-1,Math.floor(e)))];void 0===i||this._active&&this._time===i||this._apply(i)})}step(e=1){this._move(e)}stepBack(e=1){this._move(-e)}_move(e){Vo(e,"step"),this._check();const t=Math.trunc(e);if(!t)return;const i=this._prepareEntering();this._execute(()=>{this._install(i);const e=Go(this._times,this._time);if(t<0&&e<0)return;const s=this._times[Math.max(0,Math.min(this._times.length-1,e+t))];void 0===s||this._active&&this._time===s||this._apply(s)})}setScope(e,t=this._focusedId){if(this._check(),this._validateScope(e,t,new Set(this._members.map(e=>e.id))),e===this._scope&&t===this._focusedId)return;const i=this._prepareEntering(e,t);this._execute(()=>{this._scope=e,this._focusedId=t,this._install(i)||this._rebuildTimes(),this._apply(this._time??this._times[0]??null)})}play(e={}){const t=e.speed??this._speed;Ho(t,"speed"),Ho(this._barMs/t,"clock interval"),this._check();const i=this._prepareEntering();this._execute(()=>{if(this._install(i),this._active||this._apply(this._startTime??this._times[0]??null),!this._active||this._destroyed)return;if(this._speed=t,this._atEnd())return this._emit("replay:end"),void this._notify();this._clearClock(),this._lastAdvance=this._now(),Vo(this._lastAdvance,"clock"),this._playing=!0;const e=++this._clockRevision,s=this._scheduler(()=>{e===this._clockRevision&&this._tick()},this._barMs/this._speed);this._playing&&!this._destroyed&&e===this._clockRevision?this._cancel=s:s(),this._emit("replay:play"),this._notify()})}pause(){this._check(),this._playing&&this._execute(()=>{this._clearClock(),this._emit("replay:pause"),this._notify()})}stop(){this._destroyed||this._closing||!this._active||this._execute(()=>{this._cleanup(!1),this._notify()})}destroy(){this._destroyed||this._closing||this._execute(()=>{this._cleanup(!0),this._notify()})}_validateScope(e,t,i){if("all"!==e&&"focused"!==e)throw qo("scope must be focused or all");if(!i.has(t))throw qo("focus must name a member")}_prepare(e){const t=e.options.onFrame;return new Do(e.chart,{...e.options,onFrame:t?e=>this._pending.push({callback:t,state:e}):void 0},()=>({playing:this._playing&&this._activeIds.has(e.id),speed:this._speed}))}_prepareEntering(e=this._scope,t=this._focusedId){const i=new Map;for(const s of this._members)if(("all"===e||s.id===t)&&!this._activeIds.has(s.id)){if(s.dead||s.chart.isDestroyed)throw qo("cannot enter a destroyed chart");if(bi(s.chart))throw qo("chart already has active replay");i.set(s,this._prepare(s))}return i}_install(e){if(!e.size)return!1;for(const[t,i]of e)t.controller=i;return this._rebuildTimes(),!0}_wanted(e){return"all"===this._scope||e.id===this._focusedId}_rebuildTimes(){const e=new Set;for(const t of this._members)if(this._wanted(t))for(const i of t.controller.timePoints())e.add(i);this._times=[...e].sort((e,t)=>e-t)}_check(){if(this._destroyed)throw qo("has been destroyed");if(this._busy)throw qo("cannot change transport during a member frame");if(this._members.some(e=>this._activeIds.has(e.id)&&e.chart.isDestroyed))throw this.destroy(),qo("active chart was destroyed")}_apply(e){const t=++this._revision,i=this._activeIds;this._busy=!0,this._pending=[],this._time=e,this._active=!0,this._activeIds=new Set(this._members.filter(e=>this._wanted(e)).map(e=>e.id));try{for(const e of this._members){if(t!==this._revision)return;i.has(e.id)&&!this._activeIds.has(e.id)&&e.controller.stop()}for(const i of this._members){if(t!==this._revision)return;this._activeIds.has(i.id)&&i.controller.seekTime(e??0)}}finally{this._busy=!1}const s=this._pending;this._pending=[];for(const e of s){if(t!==this._revision)return;e.callback(e.state)}t===this._revision&&(this._playing&&this._atEnd()?(this._clearClock(),this._emit("replay:pause"),this._emit("replay:end")):this._playing&&this._emit("replay:play",e=>!i.has(e.id)),t===this._revision&&this._notify())}_atEnd(){return!this._times.length||Go(this._times,this._time)>=this._times.length-1}_tick(){this._playing&&this._execute(()=>{const e=this._now();Vo(e,"clock");const t=this._barMs/this._speed;if(e<this._lastAdvance)return void(this._lastAdvance=e);let i=Math.floor((e-this._lastAdvance)/t);i<=0||(i>10?(i=10,this._lastAdvance=e):this._lastAdvance+=i*t,this._move(i))})}_clearClock(){this._playing=!1,this._clockRevision++;const e=this._cancel;this._cancel=null,e?.()}_emit(e,t=()=>!0){const i=this._revision;for(const s of this._members){if(i!==this._revision)return;this._activeIds.has(s.id)&&t(s)&&s.chart.emit(e,s.controller.state())}}_notify(){this._onChange?.(this.state())}_execute(e){try{e()}catch(e){try{this._cleanup(!0)}catch{}throw e}}_chartGone(e){e.dead=!0,this._closing||this._destroyed||(this._activeIds.has(e.id)||e.id===this._focusedId?this.destroy():this._execute(()=>{const t=this._busy;t||this._revision++,e.dispose?.(),Wo.delete(e.chart),this._members=this._members.filter(t=>t!==e),this._rebuildTimes(),t||this._notify()}))}_cleanup(e){if(this._closing)return;this._closing=!0,this._revision++;const t=this._activeIds;let i;this._activeIds=new Set,this._active=!1,this._pending=[];const s=e=>{try{e()}catch(e){i??(i=e)}};s(()=>this._clearClock());for(const e of this._members)t.has(e.id)&&(e.dead||e.chart.isDestroyed?s(()=>vi(e.chart)):s(()=>e.controller.stop()));e||(e=void 0!==i||this._members.some(e=>e.dead&&(t.has(e.id)||e.id===this._focusedId)));for(const t of this._members)(e||t.dead)&&(s(()=>t.dispose?.()),Wo.get(t.chart)===this&&Wo.delete(t.chart));if(this._time=this._startTime,e?(this._destroyed=!0,this._members=[],this._times=[]):(this._members=this._members.filter(e=>!e.dead),this._rebuildTimes()),this._closing=!1,void 0!==i)throw i}}const Ko=.55;class Yo{constructor(){Object.defineProperty(this,"_index",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null})}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"top"}index(){return this._index}setIndex(e){e!==this._index&&(this._index=e,this._host?.requestUpdate())}draw(e,t){const i=this._index;if(null===i)return;const s=Ct(t.theme,void 0,t.dpr);jt(e,t.timeScale.indexToX(i),null,t.plotWidth,t.plotHeight,t.dpr,V(s.color,.55),s.width,s.dash)}}function Xo(e,t,i="nearest"){if(!Number.isFinite(t)||0===e.length)return null;const s=e.indexToTime(0),r=e.indexToTime(e.length-1);if(void 0===s||void 0===r)return null;if(t<s||t>r)return null;const n=e.timeToIndex(t);if(void 0!==n)return n;if("hide"===i)return null;const o=Math.floor(e.timeToIndexFloat(t));return void 0===e.indexToTime(o)?null:Math.max(0,Math.min(o,e.length-1))}function Jo(e,t,i){if(0===e.length||t.length<2)return null;const s=e.indexToTimeFloat(i.from),r=e.indexToTimeFloat(i.to);if(!Number.isFinite(s)||!Number.isFinite(r)||r<=s)return null;const n=t.timeToIndexFloat(s),o=t.timeToIndexFloat(r);return!Number.isFinite(n)||!Number.isFinite(o)||o<=n?null:{from:n,to:o}}const Zo={crosshair:!0,viewport:!0,symbol:!1,interval:!1,appearance:!1,whenMissing:"nearest"};function Qo(e){return!0!==e.isDestroyed&&e.panes().length>0}function ea(e){return"string"==typeof e&&e.trim().length>0}class ta{constructor(e={}){Object.defineProperty(this,"_members",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_broadcasting",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_symbol",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_interval",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._options={...Zo,...e}}options(){return{...this._options}}setOptions(e){const t=this._options;if(this._options={...t,...e},t.crosshair&&!this._options.crosshair)for(const e of this._members)this._detachCrosshairs(e);!t.symbol&&this._options.symbol&&this._convergeSymbol(),!t.interval&&this._options.interval&&this._convergeInterval()}members(){return this._prune(),this._members.map(e=>e.chart)}has(e){return null!==this._find(e)}symbol(){return this._symbol}interval(){return this._interval}crosshairIndex(e){return this._find(e)?.crosshairs[0]?.index()??null}add(e,t={}){if(this._destroyed||!Qo(e))return;const i=this._find(e);if(null!==i)return void 0!==t.symbol&&(i.symbol=t.symbol),void 0!==t.onSymbol&&(i.onSymbol=t.onSymbol),ea(t.interval)&&(i.interval=t.interval),void 0!==t.onInterval&&(i.onInterval=t.onInterval),void 0!==t.appearance&&(i.appearance=t.appearance),void(this._options.interval&&this._convergeInterval());const s={chart:e,appearance:t.appearance??null,symbol:t.symbol??null,onSymbol:t.onSymbol??null,interval:ea(t.interval)?t.interval:null,onInterval:t.onInterval??null,unsubscribe:[],crosshairs:[]};s.unsubscribe.push(e.on("crosshair:move",e=>this._onCrosshair(s,e)),e.on("pan",()=>this._onViewport(s)),e.on("zoom",()=>this._onViewport(s)),e.on("symbol",e=>this._onSymbolEvent(s,e)),e.on("style:change",()=>this.syncAppearance(e)),e.on("interval",e=>{const t="string"==typeof e?e:e?.interval;ea(t)&&this._applyInterval(s,t)}),e.on("destroy",()=>this._prune())),this._members.push(s),null===this._symbol&&null!==s.symbol&&(this._symbol=s.symbol),this._options.symbol&&this._convergeSymbol(),null===this._interval&&null!==s.interval&&(this._interval=s.interval),this._options.interval&&this._convergeInterval()}remove(e){const t=this._members.findIndex(t=>t.chart===e);t<0||(this._release(this._members[t]),this._members.splice(t,1))}setSymbol(e,t){const i=this._find(e);null!==i&&this._applySymbol(i,t)}setInterval(e,t){const i=this._find(e);null!==i&&ea(t)&&this._applyInterval(i,t)}syncAppearance(e){if(this._destroyed||this._broadcasting||!this._options.appearance||!Qo(e))return;const t=this._find(e);if(null===t?.appearance||null===t)return;const i=no(t.appearance.read());0!==Object.keys(i).length&&this._broadcast(t,e=>e.appearance?.apply({...i}))}destroy(){this._destroyed=!0;for(const e of this._members)this._release(e);this._members.length=0,this._symbol=null,this._interval=null}_onCrosshair(e,t){if(!this._options.crosshair)return;const i=t?.time??null;this._broadcast(e,e=>{const t=null===i?null:Xo(e.chart.dataLayer,i,this._options.whenMissing);this._setCrosshair(e,t)},e=>{this._setCrosshair(e,null)})}_onViewport(e){if(!this._options.viewport)return;if(!Qo(e.chart))return void this._prune();const t=e.chart.getVisibleLogicalRange(),i=e.chart.dataLayer;this._broadcast(e,e=>{const s=Jo(i,e.chart.dataLayer,t);null!==s&&e.chart.setVisibleLogicalRange(s)})}_onSymbolEvent(e,t){const i="string"==typeof t?t:t?.symbol;"string"==typeof i&&0!==i.length&&this._applySymbol(e,i)}_applySymbol(e,t){e.symbol=t,this._symbol=t,this._options.symbol&&this._broadcast(e,e=>{e.symbol!==t&&(e.symbol=t,e.onSymbol?.(t,e.chart))})}_convergeSymbol(){const e=this._symbol;null!==e&&this._options.symbol&&this._broadcast(null,t=>{t.symbol!==e&&(t.symbol=e,t.onSymbol?.(e,t.chart))})}_applyInterval(e,t){this._broadcasting||this._destroyed||!Qo(e.chart)||(e.interval=t,this._interval=t,this._options.interval&&this._broadcast(e,e=>this._followInterval(e,t)))}_followInterval(e,t){e.interval!==t&&null!==e.onInterval&&!1!==e.onInterval(t,e.chart)&&(e.interval=t)}_convergeInterval(){const e=this._interval;null!==e&&this._options.interval&&this._broadcast(null,t=>this._followInterval(t,e))}_broadcast(e,t,i){if(!this._broadcasting){this._broadcasting=!0;try{this._prune(),null!==e&&this._members.includes(e)&&i?.(e);for(const i of[...this._members])i!==e&&this._members.includes(i)&&Qo(i.chart)&&t(i)}finally{this._broadcasting=!1}}}_prune(){for(let e=this._members.length-1;e>=0;e--)Qo(this._members[e].chart)||this._members.splice(e,1)}_find(e){return this._members.find(t=>t.chart===e)??null}_release(e){for(const t of e.unsubscribe)t();e.unsubscribe.length=0,this._detachCrosshairs(e)}_setCrosshair(e,t){if(!Qo(e.chart))return;const i=null===t?e.crosshairs.length:e.chart.panes().length;for(;e.crosshairs.length>i;){const t=e.crosshairs.pop();void 0!==t&&e.chart.removePrimitive(t)}for(;e.crosshairs.length<i;){const t=new Yo;e.chart.addPrimitive(t,e.crosshairs.length),e.crosshairs.push(t)}for(const i of e.crosshairs)i.setIndex(t);e.chart.setLinkedCrosshairIndex?.(t)}_detachCrosshairs(e){if(Qo(e.chart)){for(const t of e.crosshairs)e.chart.removePrimitive(t);e.chart.setLinkedCrosshairIndex?.(null)}e.crosshairs.length=0}}function ia(e={}){return new ta(e)}const sa={intervalSec:60,volumeMode:"ltq-sum",lateTickPolicy:"foldIntoBar",sessionAnchorSec:0};class ra{constructor(e={}){Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_current",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_cumAtBarStart",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_lastCum",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_hasCum",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_streamed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_provisional",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._opts={...sa,...e}}seed(e,t){this._current={...e},this._hasCum=!1,this._streamed=!1,this._provisional=!1,void 0!==t&&(this._lastCum=t,this._cumAtBarStart=t-(e.volume??0),this._hasCum=!0)}current(){return null===this._current?null:{...this._current}}isProvisional(){return null!==this._current&&this._provisional}reconcile(e){const t=this._current;if(null===t||e.time!==t.time)return null;const i=void 0===t.volume&&void 0===e.volume?void 0:Math.max(t.volume??0,e.volume??0),s={...t,open:this._provisional?e.open:t.open,high:Math.max(t.high,e.high),low:Math.min(t.low,e.low),volume:i};return"day-delta"===this._opts.volumeMode&&this._hasCum&&void 0!==i&&(this._cumAtBarStart=this._lastCum-i),this._current=s,this._provisional=!1,{...s}}bucketStart(e){const t=this._opts.sessionAnchorSec,i=this._opts.intervalSec;return t+Math.floor((e-t)/i)*i}onTick(e){const t=this.bucketStart(e.time);if(null!==this._current&&t<this._current.time)return"dropOlderThanPrevBar"===this._opts.lateTickPolicy?null:(this._foldInto(this._current,e),this._streamed=!0,{bar:{...this._current},isNew:!1,provisional:this._provisional});if(null===this._current||t>this._current.time){const i=null===this._current||!this._streamed,s=this._volumeForNewBar(e),r={time:t,open:e.price,high:e.price,low:e.price,close:e.price,volume:s};return void 0!==e.oi&&Number.isFinite(e.oi)&&(r.oi=e.oi),this._current=r,this._streamed=!0,this._provisional=i,{bar:{...r},isNew:!0,provisional:i}}return this._foldInto(this._current,e),this._streamed=!0,{bar:{...this._current},isNew:!1,provisional:this._provisional}}_foldInto(e,t){t.price>e.high&&(e.high=t.price),t.price<e.low&&(e.low=t.price),e.close=t.price,e.volume=this._volumeForSameBar(e,t),void 0!==t.oi&&Number.isFinite(t.oi)?e.oi=t.oi:delete e.oi}_volumeForNewBar(e){if("ltq-sum"===this._opts.volumeMode)return e.ltq??0;const t=e.cumDayVolume??0;return this._hasCum?t<this._lastCum?this._cumAtBarStart=0:this._cumAtBarStart=this._lastCum:this._cumAtBarStart=t,this._lastCum=t,this._hasCum=!0,Math.max(0,t-this._cumAtBarStart)}_volumeForSameBar(e,t){if("ltq-sum"===this._opts.volumeMode)return(e.volume??0)+(t.ltq??0);const i=t.cumDayVolume??0;return this._hasCum||(this._cumAtBarStart=i-(e.volume??0),this._hasCum=!0),this._lastCum=i,Math.max(0,i-this._cumAtBarStart)}}const na=["previousClose","sessionHigh","sessionLow","lastPrice","preMarketOpen","preMarketClose","postMarketOpen","postMarketClose","bid","ask"];const oa={previousClose:{line:!0,label:!0,lineStyle:"dashed"},sessionHigh:{line:!1,label:!1,lineStyle:"dashed"},sessionLow:{line:!1,label:!1,lineStyle:"dashed"},lastPrice:{line:!1,label:!1,lineStyle:"dashed"},preMarketOpen:{line:!1,label:!1,lineStyle:"dotted"},preMarketClose:{line:!1,label:!1,lineStyle:"dotted"},postMarketOpen:{line:!1,label:!1,lineStyle:"dotted"},postMarketClose:{line:!1,label:!1,lineStyle:"dotted"},bid:{line:!1,label:!1,lineStyle:"dotted"},ask:{line:!1,label:!1,lineStyle:"dotted"}};function aa(e){return"number"==typeof e&&Number.isFinite(e)?e:null}const la=new WeakMap;function ha(e){const t={previousClose:null,sessionHigh:null,sessionLow:null,lastPrice:null,preMarketOpen:null,preMarketClose:null,postMarketOpen:null,postMarketClose:null,bid:null,ask:null},i=e.quote;null!=i&&(t.bid=aa(i.bid),t.ask=aa(i.ask));const s=e.bars,r=s.length;if(0===r)return t;t.lastPrice=aa(s[r-1].close);const n=function(e,t){const i=e.length;if(void 0===t||!Number.isFinite(t))return i-1;if(t>=e[i-1].time)return i-1;if(t<e[0].time)return-1;let s=0,r=i-1;for(;s<r;){const i=s+r+1>>1;e[i].time<=t?s=i:r=i-1}return s}(s,e.anchorTime);if(n<0)return t;const o=function(e,t){const i=e.length;if(0===i)return[];const s=e[0].time,r=e[i-1].time,n=la.get(e);if(void 0!==n&&n.len===i&&n.first===s&&n.last===r&&n.zone===t)return n.starts;const o=new Array(i);for(let t=0;t<i;t++)o[t]=e[t].time;const a=tt(o,t),l=[0];for(let e=1;e<i;e++)a[e]&&l.push(e);return la.set(e,{len:i,first:s,last:r,zone:t,starts:l}),l}(s,e.timezone??Me),a=function(e,t){let i=0,s=e.length-1;for(;i<s;){const r=i+s+1>>1;e[r]<=t?i=r:s=r-1}return i}(o,n),l=o[a],h=a+1<o.length?o[a+1]-1:r-1;let c=-1/0,d=1/0;for(let e=l;e<=h;e++){const t=s[e];Number.isFinite(t.high)&&t.high>c&&(c=t.high),Number.isFinite(t.low)&&t.low<d&&(d=t.low)}if(c>-1/0&&(t.sessionHigh=c),d<1/0&&(t.sessionLow=d),a>0){const e=o[a-1];for(let i=l-1;i>=e;i--){const e=aa(s[i].close);if(null!==e){t.previousClose=e;break}}}const u=e.marketPhase;if(null!=u)for(let e=l;e<=h;e++){const i=s[e],r=u(i);if("pre"===r){null===t.preMarketOpen&&(t.preMarketOpen=aa(i.open));const e=aa(i.close);null!==e&&(t.preMarketClose=e)}else if("post"===r){null===t.postMarketOpen&&(t.postMarketOpen=aa(i.open));const e=aa(i.close);null!==e&&(t.postMarketClose=e)}}return t}function ca(e,t,i){switch(e){case"sessionHigh":return t.upColor;case"sessionLow":return t.downColor;case"bid":return t.buy;case"ask":return t.sell;case"lastPrice":return i?t.lastPriceUp:t.lastPriceDown;default:return t.crosshair}}function da(e){return{line:!1!==e.priceLineVisible,label:!1!==e.lastValueVisible}}function ua(e){return{priceLineVisible:e.line,lastValueVisible:e.label}}class pa{constructor(e={}){Object.defineProperty(this,"_levels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timezone",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_phase",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_quote",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_values",{enumerable:!0,configurable:!0,writable:!0,value:{previousClose:null,sessionHigh:null,sessionLow:null,lastPrice:null,preMarketOpen:null,preMarketClose:null,postMarketOpen:null,postMarketClose:null,bid:null,ask:null}}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._levels={...oa};for(const t of na){const i=e.levels?.[t];void 0!==i&&(this._levels[t]={...oa[t],...i})}this._timezone=e.timezone??Me,this._phase=e.marketPhase??null,this._quote=e.quote??null}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"normal"}level(e){return this._levels[e]}setLevel(e,t){this._levels[e]={...this._levels[e],...t},this._host?.requestUpdate()}setOptions(e){for(const t of na){const i=e.levels?.[t];void 0!==i&&(this._levels[t]={...this._levels[t],...i})}void 0!==e.timezone&&(this._timezone=e.timezone),void 0!==e.marketPhase&&(this._phase=e.marketPhase),void 0!==e.quote&&(this._quote=e.quote),this._host?.requestUpdate()}setQuote(e){this._quote=e,this._host?.requestUpdate()}values(){return this._values}available(e){return null!==this._values[e]}draw(e,t){const i=t.bars?.()??[],s=t.dataLayer.indexToTimeFloat(t.timeScale.visibleRange().to);this._values=ha({bars:i,anchorTime:s,timezone:this._timezone,marketPhase:this._phase,quote:"function"==typeof this._quote?this._quote()??null:this._quote});const r=t.dpr,n=Math.round(t.plotWidth*r),o=t.plotHeight*r,a=i.length>0?i[i.length-1]:null,l=null!==a&&a.close>=a.open;e.save(),e.font=`500 ${11*r}px system-ui, sans-serif`,e.textBaseline="middle",e.textAlign="left";for(const i of na){const s=this._levels[i];if(!s.line&&!s.label)continue;const a=this._values[i];if(null===a)continue;const h=Math.round(t.priceScale.priceToY(a)*r)+.5;if(h<0||h>o)continue;const c=s.color??ca(i,t.theme,l);if(s.line){const i=Math.max(0,Math.min(1,s.extentFromRight??1)),o=Math.round(t.plotWidth*(1-i)*r);e.strokeStyle=c,e.lineWidth=Math.max(1,Math.round((s.lineWidth??1)*r)),e.setLineDash(M(s.lineStyle,r)),e.beginPath(),e.moveTo(o,h),e.lineTo(n,h),e.stroke(),e.setLineDash([])}if(s.label&&"hidden"!==t.priceAxisSide&&t.priceAxisWidth>0){const i=s.text??t.priceScale.format(a),l=6*r,d=16*r,u="left"===t.priceAxisSide;if(u||void 0!==t.priceAxisOffset){const s=t.priceAxisOffset??0,n=Math.round(s*r),a=Math.round((s+(u?-t.priceAxisWidth:t.priceAxisWidth))*r),p=Math.abs(a-n)-1;if(Number.isFinite(n)&&Number.isFinite(a)&&p>0&&o>=d){e.save(),e.beginPath(),e.rect(Math.min(n,a),0,p+1,o),e.clip();const t=Math.min(l,p/4),s=e.measureText(i).width,_=Math.min(p,s+2*t),f=u?n-1-_:n+1,m=Math.max(d/2,Math.min(o-d/2,h));e.fillStyle=c,e.fillRect(f,m-d/2,_,d),e.fillStyle=q(c),e.font=`500 ${11*r*(s>0?Math.min(1,(_-2*t)/s):1)}px system-ui, sans-serif`,e.fillText(i,f+t,m),e.restore(),e.font=`500 ${11*r}px system-ui, sans-serif`}}else e.fillStyle=c,e.fillRect(n+1,h-d/2,e.measureText(i).width+2*l,d),e.fillStyle=q(c),e.fillText(i,n+1+l,h)}}e.restore()}}class _a{constructor(e){Object.defineProperty(this,"_opts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._opts={index:e.index,color:e.color??"rgba(12,14,20,0.62)",lineColor:e.lineColor??"#3b82f6",lineWidth:e.lineWidth??1,lineVisible:e.lineVisible??!0,zOrder:e.zOrder??"top",id:e.id??"replay-shade"}}zOrder(){return this._opts.zOrder}autoscaleInfo(){return null}hitTest(){return null}setOptions(e){this._opts={...this._opts,...e}}draw(e,t){const i=this._opts;if(null===i.index)return;const s=t.dpr,r=t.plotWidth*s,n=t.plotHeight*s;if(r<=0||n<=0)return;const o=t.timeScale.barSpacing*s/2,a=Math.round(t.timeScale.indexToX(i.index)*s+o);if(a>=r)return;const l=Math.max(0,a);e.save(),e.fillStyle=i.color,e.fillRect(l,0,r-l,n),i.lineVisible&&a>=0&&(e.strokeStyle=i.lineColor,e.lineWidth=Math.max(1,Math.round(i.lineWidth*s)),e.beginPath(),e.moveTo(a+.5,0),e.lineTo(a+.5,n),e.stroke()),e.restore()}}class fa{constructor(e={}){Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_position",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_mx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_my",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_scale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_btnW",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_qtyW",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_h",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_buyLabel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sellLabel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_showPrices",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_qty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_buyColor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sellColor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_bid",{enumerable:!0,configurable:!0,writable:!0,value:NaN}),Object.defineProperty(this,"_ask",{enumerable:!0,configurable:!0,writable:!0,value:NaN}),Object.defineProperty(this,"_host",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_sellRect",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_buyRect",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_qtyRect",{enumerable:!0,configurable:!0,writable:!0,value:null}),this._id=e.id??"trade",this._position=e.position??"top-left";const t=e.margin??12;this._mx="number"==typeof t?t:t.x,this._my="number"==typeof t?t:t.y,this._buyLabel=e.buyLabel??"BUY",this._sellLabel=e.sellLabel??"SELL",this._showPrices=e.showPrices??!0,this._scale=Math.max(.6,Math.min(1.5,e.scale??1)),this._btnW=74*this._scale,this._qtyW=40*this._scale,this._h=42*this._scale,this._qty=void 0!==e.qty?String(e.qty):"",this._buyColor=e.buyColor,this._sellColor=e.sellColor}attached(e){this._host=e}detached(){this._host=null}zOrder(){return"top"}autoscaleInfo(){return null}setPrices(e,t){this._bid=e,this._ask=t,this._host?.requestUpdate()}setMark(e){this.setPrices(e,e)}setQty(e){this._qty=String(e),this._host?.requestUpdate()}setColors(e,t){this._buyColor=e,this._sellColor=t,this._host?.requestUpdate()}_origin(e,t){const i=2*this._btnW+this._qtyW+2,s=this._mx,r=e-this._mx-i,n=this._my,o=t-this._my-this._h;switch(this._position){case"top-right":return{x:r,y:n,w:i};case"bottom-left":return{x:s,y:o,w:i};case"bottom-right":return{x:r,y:o,w:i};case"center":return{x:(e-i)/2,y:(t-this._h)/2,w:i};default:return{x:s,y:n,w:i}}}draw(e,t){this._sellRect=this._buyRect=this._qtyRect=null;const i=t.dpr,s=this._origin(t.plotWidth,t.plotHeight),r=this._sellColor??t.theme.sell,n=this._buyColor??t.theme.buy;this._sellRect={x:s.x,y:s.y,w:this._btnW,h:this._h},this._qtyRect={x:s.x+this._btnW+1,y:s.y,w:this._qtyW,h:this._h},this._buyRect={x:s.x+this._btnW+this._qtyW+2,y:s.y,w:this._btnW,h:this._h},e.save(),e.shadowColor="rgba(0,0,0,0.35)",e.shadowBlur=8*i,e.shadowOffsetY=2*i;const o=(e,i)=>null!==e&&t.hoverId===`${this._id}:${i}`;this._drawButton(e,this._sellRect,i,o(this._sellRect,"sell")?G(r,.12):r,this._sellLabel,this._showPrices?this._fmt(t,this._bid):"","left");const a="transparent"===t.theme.background?G(r,-.6):t.theme.grid;this._drawChip(e,this._qtyRect,i,a,this._qty||"—",t.theme.axisText),this._drawButton(e,this._buyRect,i,o(this._buyRect,"buy")?G(n,.12):n,this._buyLabel,this._showPrices?this._fmt(t,this._ask):"","right"),e.restore()}_fmt(e,t){return Number.isNaN(t)?"":e.priceScale.format(t)}_drawButton(e,t,i,s,r,n,o){const a=7*this._scale*i;e.beginPath(),this._roundedSide(e,t.x*i,t.y*i,t.w*i,t.h*i,a,o),e.fillStyle=s,e.fill();const l=q(s);e.textAlign="center";const h=(t.x+t.w/2)*i;""!==n?(e.fillStyle=l,e.font=10*this._scale*i+"px system-ui, sans-serif",e.textBaseline="alphabetic",e.fillText(n,h,(t.y+t.h*(18/42))*i),e.font=`700 ${12*this._scale*i}px system-ui, sans-serif`,e.fillText(r,h,(t.y+t.h*(33/42))*i)):(e.fillStyle=l,e.font=`700 ${13*this._scale*i}px system-ui, sans-serif`,e.textBaseline="middle",e.fillText(r,h,(t.y+t.h/2)*i))}_drawChip(e,t,i,s,r,n){e.beginPath(),e.rect(t.x*i,t.y*i,t.w*i,t.h*i),e.fillStyle=s,e.fill(),e.fillStyle=n,e.font=`600 ${13*this._scale*i}px system-ui, sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillText(r,(t.x+t.w/2)*i,(t.y+t.h/2)*i)}_roundedSide(e,t,i,s,r,n,o){const a=e;if("function"==typeof a.roundRect){const e="left"===o?[n,0,0,n]:[0,n,n,0];a.roundRect(t,i,s,r,e)}else U(e,t,i,s,r,n)}hitTest(e,t,i){const s=i=>null!==i&&e>=i.x&&e<=i.x+i.w&&t>=i.y&&t<=i.y+i.h;return s(this._buyRect)?{externalId:`${this._id}:buy`,zOrder:"top",distance:0,cursor:"pointer"}:s(this._sellRect)?{externalId:`${this._id}:sell`,zOrder:"top",distance:0,cursor:"pointer"}:s(this._qtyRect)?{externalId:`${this._id}:qty`,zOrder:"top",distance:0,cursor:"pointer"}:null}}function ma(e,t){if(t<=0)throw new Error("openalgo-charts: EMA period must be > 0");const i=[];if(0===e.length)return i;const s=2/(t+1);let r=e[0];i.push(r);for(let t=1;t<e.length;t++)r=e[t]*s+r*(1-s),i.push(r);return i}function ba(e,t){const i=ma(e.map(e=>e.close),t);return e.map((e,t)=>({time:e.time,open:i[t],high:i[t],low:i[t],close:i[t]}))}function ga(e,t=14){if(t<=0)throw new Error("openalgo-charts: RSI period must be > 0");const i=e.length,s=new Array(i).fill(NaN);if(i<=t||!Number.isInteger(t))return s;let r=NaN,n=NaN,o=!1,a=!1,l=0;for(let h=1;h<i;h++){const i=e[h]-e[h-1];if(!Number.isFinite(i)){l=0;continue}l++;if(o&&(r=(r*(t-1)+(i>0?i:0))/t),a&&(n=(n*(t-1)+(i<0?-i:0))/t),(!o||!a)&&l>=t){let i=0,s=0;for(let r=h-t+1;r<=h;r++){const t=e[r]-e[r-1];t>=0?i+=t:s-=t}!o&&Number.isFinite(i/t)&&(r=i/t,o=!0),!a&&Number.isFinite(s/t)&&(n=s/t,a=!0)}if(Number.isFinite(r)&&Number.isFinite(n)){const e=0===n?100:100-100/(1+r/n);Number.isFinite(e)&&(s[h]=e)}}return s}function va(e,t=14){const i=ga(e.map(e=>e.close),t);return e.map((e,t)=>({time:e.time,open:i[t],high:i[t],low:i[t],close:i[t]}))}function ya(e,t,i){const s=e.length,r=new Array(s);if(0===s)return r;r[0]=e[0]-t[0];for(let n=1;n<s;n++){const s=e[n]-t[n],o=Math.abs(e[n]-i[n-1]),a=Math.abs(t[n]-i[n-1]);r[n]=Math.max(s,o,a)}return r}function wa(e,t,i,s=14){if(s<=0)throw new Error("openalgo-charts: ATR period must be > 0");const r=ya(e,t,i),n=r.length,o=new Array(n).fill(NaN);if(n<s)return o;let a=0;for(let e=0;e<s;e++)a+=r[e];let l=a/s;o[s-1]=l;for(let e=s;e<n;e++)l=(l*(s-1)+r[e])/s,o[e]=l;return o}function xa(e,t=10,i=3){const s=e.length,r=e.map(()=>({value:NaN,direction:1})),n=e.map(e=>e.high),o=e.map(e=>e.low),a=e.map(e=>e.close),l=wa(n,o,a,t);let h=NaN,c=NaN,d=NaN,u=!1;for(let e=0;e<s;e++){if(!Number.isFinite(l[e]))continue;const t=(n[e]+o[e])/2,s=t+i*l[e],p=t-i*l[e],_=u?s<h||a[e-1]>h?s:h:s,f=u?p>c||a[e-1]<c?p:c:p;let m,b;u&&d!==h?a[e]>=f?(m=f,b=-1):(m=_,b=1):a[e]<=_?(m=_,b=1):(m=f,b=-1),r[e]={value:m,direction:b},h=_,c=f,d=m,u=!0}return r}function Sa(e,t=10,i=3){const s=xa(e,t,i),r=(e,t)=>({time:e,open:t,high:t,low:t,close:t}),n=[],o=[];for(let t=0;t<e.length;t++){const i=s[t],a=Number.isFinite(i.value);n.push(r(e[t].time,a&&-1===i.direction?i.value:NaN)),o.push(r(e[t].time,a&&1===i.direction?i.value:NaN))}return{up:n,down:o}}function Pa(e){throw new Error(`Invalid instrument: ${e}`)}function Oa(e){return e&&"object"==typeof e&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e))?Object.values(Object.getOwnPropertyDescriptors(e)).some(e=>!("value"in e))?Pa("accessors are not metadata"):e:Pa("expected a plain object")}function ka(e,t){return"string"!=typeof e||!e.trim()||e.length>200||Array.from(e).some(e=>e.charCodeAt(0)<32)?Pa(t):e}function Ia(e,t){return"number"!=typeof e||!Number.isFinite(e)||e<=0?Pa(t):e}function Ma(e,t){return!Array.isArray(e)||e.length>t?Pa("invalid list"):e.map(e=>ka(e,"invalid list item"))}function Ta(e){const t=Ma(e,16);return t.some(e=>!nt(e))?Pa("invalid session"):Object.freeze(t)}function Ca(e){return e.toISOString().slice(0,10)}function ja(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return Pa("invalid exception date");const t=new Date(e+"T00:00:00Z");return Number.isFinite(t.getTime())&&Ca(t)===e?t:Pa("invalid exception date")}function Aa(e,t,i){const s=new Date(e.getTime()+6e4*t),r=s.getUTCFullYear(),n=s.getUTCMonth()+1,o=s.getUTCDate(),a=s.getUTCHours(),l=s.getUTCMinutes(),h=He(r,n,o,a,l,0,i),c=Re(h,i);return c.year!==r||c.month!==n||c.day!==o||c.hour!==a||c.minute!==l?Pa("session boundary is absent in this timezone"):h}class La{constructor(e){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sessions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_exceptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=function(e){const t=Oa(e),i=Oa(t.calendar),s=ka(t.timezone,"timezone");if(!Ae(s))return Pa("unknown timezone");const r=Ia(t.priceTick,"price tick"),n=t.pricePrecision;if("number"!=typeof n||!Number.isInteger(n)||n<0||n>12)return Pa("price precision must be 0..12");const o=r*10**n;if(!Number.isFinite(o)||o<1||Math.abs(o-Math.round(o))>8*Number.EPSILON*Math.max(1,o))return Pa("price precision cannot represent the tick");const a=Ma(t.intervals,128);if(!a.length||new Set(a).size!==a.length)return Pa("intervals must be nonempty and unique");for(const e of a){const t=ws(e)?.bucketing;if(!t||"interval"===t.mode&&(!Number.isFinite(t.seconds)||t.seconds<=0))return Pa(`unsupported interval ${e}`)}const l={};if(void 0!==i.exceptions){const e=Oa(i.exceptions);if(Object.keys(e).length>3660)return Pa("too many session exceptions");for(const[t,i]of Object.entries(e))ja(t),l[t]=Ta(i)}return void 0!==t.hasOpenInterest&&"boolean"!=typeof t.hasOpenInterest?Pa("invalid OI capability"):Object.freeze({symbol:ka(t.symbol,"symbol"),exchange:ka(t.exchange,"exchange"),timezone:s,priceTick:r,pricePrecision:n,quantityStep:Ia(t.quantityStep,"quantity step"),intervals:Object.freeze(a),calendar:Object.freeze({sessions:Ta(i.sessions),exceptions:Object.freeze(l)}),...void 0===t.hasOpenInterest?{}:{hasOpenInterest:t.hasOpenInterest}})}(e),this._sessions=this.metadata.calendar.sessions.map(e=>nt(e)),this._exceptions=new Map(Object.entries(this.metadata.calendar.exceptions??{}).map(([e,t])=>[e,t.map(e=>nt(e))]))}supportsInterval(e){return this.metadata.intervals.includes(e)}formatPrice(e){return Number.isFinite(e)?e.toFixed(this.metadata.pricePrecision):""}sessionAt(e){if(!Number.isFinite(e)||!Number.isFinite(new Date(1e3*e).getTime()))return Pa("invalid timestamp");const t=Re(e,this.metadata.timezone);let i=null;for(const s of[0,-1]){const r=new Date(Date.UTC(t.year,t.month-1,t.day+s)),n=Ca(r);for(const t of this._exceptions.get(n)??this._sessions){if(t.days&&!t.days.includes(r.getUTCDay()+1))continue;if(-1===s&&t.end>t.start)continue;const o=Aa(r,t.start,this.metadata.timezone),a=Aa(r,t.end+(t.end<=t.start?1440:0),this.metadata.timezone);if(!(e<o||e>=a)){if(i)return Pa("overlapping active sessions");i={date:n,open:o,close:a}}}}return i}applyTo(e,t){if(!this.supportsInterval(t))return Pa(`unsupported interval ${t}`);if(e.isDestroyed)return Pa("chart is destroyed");const i=e.primarySeries();if(!i)return Pa("chart needs a primary series");const s=e.getDataContext(),r=this.metadata;if(s&&(s.symbol!==r.symbol||s.exchange!==r.exchange||s.interval!==t)&&e.primaryBars().length)return Pa("clear previous source bars before applying metadata");e.setTimezone(r.timezone),e.setPriceScaleOptions({minMove:r.priceTick}),i.priceScale().setOptions({minMove:r.priceTick}),i.priceScale().setPriceFormatter(e=>this.formatPrice(e)),e.setDataContext({symbol:r.symbol,exchange:r.exchange,interval:t,hasOpenInterest:r.hasOpenInterest})}}function Ra(e,t){if(void 0===e)return{supported:!0};try{const i="function"==typeof e?e(Object.freeze({...t})):e;if(!i||"object"!=typeof i||Array.isArray(i)||"then"in i)return{supported:!1,reason:"Trading capabilities are unavailable"};const s=i[t.operation];if(!1===s)return{supported:!1,reason:`Trading operation ${t.operation} is not supported`};if(void 0!==s&&!0!==s)return{supported:!1,reason:`Support for trading operation ${t.operation} is unknown`};if("place"===t.operation){if(void 0!==i.orderTypes){if(!Array.isArray(i.orderTypes)||void 0===t.type)return{supported:!1,reason:"Supported order types are unavailable for this request"};if(!i.orderTypes.includes(t.type))return{supported:!1,reason:`Order type ${t.type} is not supported`}}if(void 0!==i.modes){if(!Array.isArray(i.modes)||void 0===t.mode)return{supported:!1,reason:"Supported trading modes are unavailable for this request"};if(!i.modes.includes(t.mode))return{supported:!1,reason:`Trading mode ${t.mode} is not supported`}}}return{supported:!0}}catch{return{supported:!1,reason:"Trading capabilities are unavailable"}}}class za extends Error{constructor(e,t){super(t),Object.defineProperty(this,"preflight",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TradingCapabilityError",this.operation=e}}function Fa(e,t){const i=Ra(e,t);if(!i.supported)throw new za(t.operation,i.reason)}function Na(e,t){const i=new Error(t);return i.name=e,i}function Ea(e){if(!Number.isFinite(e)||e<=0)throw new RangeError("History timeout must be positive and finite");return e}function Ba(e,t){if(e.signal?.aborted)return Promise.reject(Na("AbortError","History request cancelled"));const i=Ea(e.timeoutMs??15e3);return new Promise((s,r)=>{const n=new AbortController;let o=!1;const a=(t,i)=>{o||(o=!0,clearTimeout(h),e.signal?.removeEventListener("abort",l),t?s(i):(n.abort(),r(i)))},l=()=>a(!1,Na("AbortError","History request cancelled")),h=setTimeout(()=>a(!1,Na("TimeoutError","History request timed out")),i);e.signal?.addEventListener("abort",l,{once:!0});try{t(n.signal).then(e=>a(!0,e),e=>a(!1,e))}catch(e){a(!1,e)}})}function $a(e){const t=e=>e.map(e=>{if(null===e||"object"!=typeof e)throw new TypeError("Invalid history bar");return{...e}});return Array.isArray(e)?t(e):{...e,bars:t(e.bars)}}class Da{constructor(e,t={}){if(Object.defineProperty(this,"_feed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_max",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_jobs",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_active",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_draining",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._feed=e,this._max=t.maxConcurrent??4,!Number.isInteger(this._max)||this._max<1)throw new RangeError("History concurrency must be a positive integer");this._timeout=Ea(t.timeoutMs??15e3)}getBars(e,t=0){return this._request(e,!1,t)}getBarsPage(e,t=0){return this._feed.getBarsPage?this._request(e,!0,t):Promise.reject(new Error("This feed does not support history pages"))}_request(e,t,i){if(e.signal?.aborted)return Promise.reject(Na("AbortError","History request cancelled"));if(!Number.isFinite(i))return Promise.reject(new RangeError("History priority must be finite"));let s;try{s=Ea(e.timeoutMs??this._timeout)}catch(e){return Promise.reject(e)}const r=JSON.stringify([t,e.symbol,e.exchange,e.interval,e.from,e.to,e.countBack,!0===e.noCache,"before"in e?e.before:null]);let n=this._jobs.get(r);n||(n={key:r,req:{...e,signal:void 0,timeoutMs:2147483647},page:t,priority:i,controller:new AbortController,consumers:new Set,running:!1,done:!1},this._jobs.set(r,n));const o=n;o.priority=Math.max(o.priority,i);const a=new Promise((t,i)=>{const r=e=>{o.consumers.delete(l)&&(l.cleanup(),i(e),0===o.consumers.size&&(this._remove(o),o.controller.abort(),this._drain()))},n=()=>r(Na("AbortError","History request cancelled")),a=setTimeout(()=>r(Na("TimeoutError","History request timed out")),s),l={resolve:t,reject:i,cleanup:()=>{clearTimeout(a),e.signal?.removeEventListener("abort",n)}};o.consumers.add(l),e.signal?.addEventListener("abort",n,{once:!0})});return this._drain(),a}_remove(e){e.done||(e.done=!0,this._jobs.get(e.key)===e&&this._jobs.delete(e.key),e.running&&this._active--)}_finish(e,t,i){if(e.done)return;let s;if(t)try{if(e.page===Array.isArray(i))throw new TypeError("Invalid history result shape");s=$a(i)}catch(e){t=!1,i=e}this._remove(e);for(const r of e.consumers)r.cleanup(),t?r.resolve($a(s)):r.reject(i);e.consumers.clear(),this._drain()}_drain(){if(!this._draining){this._draining=!0;try{for(;this._active<this._max;){let e;for(const t of this._jobs.values())t.running||e&&!(t.priority>e.priority)||(e=t);if(!e)return;const t=e;t.running=!0,this._active++;const i={...t.req,signal:t.controller.signal};try{(t.page?this._feed.getBarsPage(i):this._feed.getBars(i)).then(e=>this._finish(t,!0,e),e=>this._finish(t,!1,e))}catch(e){this._finish(t,!1,e)}}}finally{this._draining=!1}}}}const Wa=new WeakMap;function qa(e){let t=Wa.get(e);return t||(t=new Da(e),Wa.set(e,t)),t}const Va={delayMs:2500,retries:2,retryDelayMs:5e3};function Ha(e){return e instanceof Error?e:new Error(String(e??"History request failed"))}function Ga(e,t){if(!Number.isFinite(e)||e<=0)throw new RangeError(`${t} must be positive and finite`);return e}function Ua(e){const t=new Map;for(const i of e){if(![i.time,i.open,i.high,i.low,i.close].every(Number.isFinite)||i.high<Math.max(i.open,i.close,i.low)||i.low>Math.min(i.open,i.close)||void 0!==i.volume&&(!Number.isFinite(i.volume)||i.volume<0))throw new Error("History contains an invalid candle");t.set(i.time,{...i})}return[...t.values()].sort((e,t)=>e.time-t.time)}function Ka(...e){return Ua(e.flat())}class Ya{constructor(e,t={}){Object.defineProperty(this,"_feed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pool",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:{request:null,bars:[],status:"idle",historyStatus:"idle",hasMore:null,reason:"state",paused:!1}}),Object.defineProperty(this,"_bars",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_scope",{enumerable:!0,configurable:!0,writable:!0,value:new AbortController}),Object.defineProperty(this,"_refreshAbort",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pageAbort",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_loadWork",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_pageWork",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_unsubscribe",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_stream",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_generation",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_refreshId",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_before",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_buffer",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_poll",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_visible",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_seconds",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_provisionalTime",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_repairTimer",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_repairRetries",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_pendingRepair",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_barClose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._feed=e,this._pool=t.requestPool??qa(e),this._options={pageSize:500,maxEmptyPages:4,maxBars:1e5,pollIntervalMs:0,...t};for(const e of["pageSize","maxEmptyPages","maxBars"]){const t=Ga(this._options[e],e);if(!Number.isInteger(t))throw new RangeError(`${e} must be an integer`)}if(void 0!==t.pageWindowSec&&Ga(t.pageWindowSec,"pageWindowSec"),void 0!==t.timeoutMs&&Ga(t.timeoutMs,"timeoutMs"),!Number.isFinite(this._options.pollIntervalMs)||this._options.pollIntervalMs<0)throw new RangeError("pollIntervalMs must be nonnegative");if(void 0!==t.refreshWindowBars&&!Number.isInteger(Ga(t.refreshWindowBars,"refreshWindowBars")))throw new RangeError("refreshWindowBars must be an integer");const i=t.refreshOnBarClose;if(this._barClose=i?{...Va,...!0===i?{}:i}:null,this._barClose){for(const e of["delayMs","retries","retryDelayMs"]){const t=this._barClose[e];if(!Number.isFinite(t)||t<0)throw new RangeError(`refreshOnBarClose.${e} must be nonnegative`)}if(!Number.isInteger(this._barClose.retries))throw new RangeError("refreshOnBarClose.retries must be an integer")}}getState(){return this._state}bars(){return this._bars}subscribe(e){return this._destroyed?()=>{}:(this._listeners.add(e),()=>{this._listeners.delete(e)})}load(e){if(this._destroyed)return Promise.resolve([]);const t=++this._generation;if(this._cancel(),!this._current(t))return this._loadWork??Promise.resolve(this._bars);this._scope=new AbortController,this._bars=[],this._before=void 0,this._provisionalTime=null;const i=ws(e.interval);this._seconds="interval"===i?.bucketing.mode?i.bucketing.seconds:null;const s={...e,signal:void 0,timeoutMs:e.timeoutMs??this._options.timeoutMs};let r;this._state={request:s,bars:[],status:"loading",historyStatus:"idle",hasMore:null,reason:"load",paused:!1};const n=new Promise(e=>{r=e});return this._loadWork=n,this._publish("load"),this._load(s,e.signal,t).then(r),n.then(()=>{this._loadWork===n&&(this._loadWork=null)}),n}async _load(e,t,i){if(!this._current(i))return this._bars;const s=this._scope,r=()=>s.abort();t?.addEventListener("abort",r,{once:!0}),t?.aborted&&s.abort();try{let t;if(!e.noCache&&this._feed.getCachedBars)try{const i=await Ba({signal:s.signal,timeoutMs:Math.min(e.timeoutMs??500,500)},t=>this._feed.getCachedBars({...e,signal:t}));t=i?Ua(i):void 0}catch{}if(!this._current(i))return this._bars;if(s.signal.aborted)throw s.signal.reason;t?.length&&(this._bars=t,this._publish("cache",{status:"refreshing"}));const r=t?.length&&void 0!==e.from&&t[0].time<=e.from?Math.max(e.from,t[Math.max(0,t.length-2)].time):e.from,n=await this._pool.getBars({...e,from:r,signal:s.signal,noCache:e.noCache||!!this._feed.getCachedBars},10);if(!this._current(i))return this._bars;this._bars=this._replaceWindow(Ua(n),r,e.to),this._limit(),this._before=this._bars[0]?.time??e.from,this._publish("load",{status:this._bars.length?"ready":"empty",error:void 0}),this._startStream(i),this._current(i)&&this._schedulePoll()}catch(e){this._current(i)&&this._publish("state",{status:s.signal.aborted?"idle":this._bars.length?"stale":"error",error:s.signal.aborted?void 0:Ha(e)})}finally{t?.removeEventListener("abort",r)}return this._bars}refresh(){return this._refresh()}async _refresh(e){if(this._destroyed||!this._state.request)return this._bars;if(this._loadWork)return this._loadWork;const t=this._generation,i=++this._refreshId,s=this._refreshAbort;if(this._refreshAbort=null,s?.abort(),!this._current(t)||i!==this._refreshId)return this._bars;const r=new AbortController;this._refreshAbort=r,this._clearPoll(),this._buffer??(this._buffer=new Map);const n=this._state.request,o=Math.max(n.to??0,(this._options.now??(()=>Date.now()/1e3))()),a=void 0!==n.from&&void 0!==n.to?n.to-n.from:void 0,l=this._bars[this._bars.length-1];let h=void 0===a?n.from:o-a;void 0!==this._options.refreshWindowBars&&null!==this._seconds&&l&&(h=l.time-this._options.refreshWindowBars*this._seconds,void 0!==e?.from&&(h=Math.min(h,e.from))),this._publish("state",{status:"refreshing",error:void 0});try{const s=await this._pool.getBars({...n,from:h,to:o,noCache:!0,signal:r.signal},5);if(!this._current(t)||i!==this._refreshId)return this._bars;if(0===s.length&&this._bars.length)throw new Error("History refresh returned no bars");const a=Ua(s);let c=-1/0;for(const e of a)e.time>c&&(c=e.time);const d=a.length?Math.min(o,c):o,u=this._replaceWindow(a,h,d),p=new Map(u.map(e=>[e.time,e])),_=l&&l.time===c?p.get(l.time):void 0;l&&_&&p.set(l.time,{..._,high:Math.max(_.high,l.high),low:Math.min(_.low,l.low),volume:void 0===_.volume&&void 0===l.volume?void 0:Math.max(_.volume??0,l.volume??0)}),null!==this._provisionalTime&&p.has(this._provisionalTime)&&this._provisionalTime<=d&&(this._provisionalTime=null);for(const e of this._buffer?.values()??[]){const t=p.get(e.time);p.set(e.time,t?{...t,high:Math.max(t.high,e.high),low:Math.min(t.low,e.low),close:e.close,volume:void 0===t.volume&&void 0===e.volume?void 0:Math.max(t.volume??0,e.volume??0),oi:e.oi}:e)}this._bars=Ua([...p.values()]),this._buffer=null,this._limit(),this._publish("refresh",{status:this._bars.length?"ready":"empty",error:void 0}),this._startStream(t),void 0!==e?.expect&&c<e.expect&&this._barClose&&this._repairRetries<this._barClose.retries&&(this._repairRetries++,this._scheduleRepair({expect:e.expect},this._barClose.retryDelayMs))}catch(e){if(!this._current(t)||i!==this._refreshId||r.signal.aborted)return this._bars;this._limit(),this._publish("refresh",{status:this._bars.length?"stale":"error",error:Ha(e)})}finally{if(this._current(t)&&i===this._refreshId){this._refreshAbort=null,this._schedulePoll();const e=this._pendingRepair;this._pendingRepair=null,e&&this._refresh(e)}}return this._bars}pushBar(e,t){if(this._destroyed||!this._state.request)return;let i;try{i=Ua([e])[0]}catch(e){return void this._publish("state",{status:this._bars.length?"stale":"error",error:Ha(e)})}const s=this._bars[this._bars.length-1];if(s&&i.time<s.time)return;const r=!0===t?.provisional,n=!s||i.time>s.time;if(n?r&&(this._provisionalTime=i.time):r&&this._provisionalTime!==i.time&&(i={...i,open:s.open,high:Math.max(s.high,i.high),low:Math.min(s.low,i.low),volume:void 0===s.volume&&void 0===i.volume?void 0:Math.max(s.volume??0,i.volume??0)}),this._buffer)for(this._buffer.set(i.time,i);this._buffer.size>this._options.maxBars;)this._buffer.delete(this._buffer.keys().next().value);const o=this._bars.slice();s?.time===i.time?o[o.length-1]={...i,volume:i.volume??s.volume}:o.push(i),this._bars=o,this._limit(),this._buffer||this._publish("live",{status:"stale"===this._state.status?"stale":"ready"}),n&&this._onNewBucket(s?.time,i.time)}_onNewBucket(e,t){this._options.refreshOnGap&&null!==this._seconds&&void 0!==e&&t-e>this._seconds?this._requestRepair({from:e}):this._barClose&&(this._repairRetries=0,this._scheduleRepair({expect:e},this._barClose.delayMs))}_scheduleRepair(e,t){this._clearRepairTimer(),!this._destroyed&&this._visible&&(this._repairTimer=setTimeout(()=>{this._repairTimer=null,this._requestRepair(e)},t))}_requestRepair(e){if(!this._destroyed&&this._visible&&this._state.request&&!this._loadWork){if(this._refreshAbort){const t=this._pendingRepair;return void(this._pendingRepair={from:void 0===t?.from?e.from:void 0===e.from?t.from:Math.min(t.from,e.from),expect:void 0===t?.expect?e.expect:void 0===e.expect?t.expect:Math.max(t.expect,e.expect)})}this._refresh(e)}}_clearRepairTimer(){null!==this._repairTimer&&clearTimeout(this._repairTimer),this._repairTimer=null}loadMore(e){if(this._pageWork)return this._pageWork;if(this._destroyed||!this._state.request||this._loadWork||this._state.paused||!1===this._state.hasMore)return Promise.resolve(this._bars);if(this._bars.length>=this._options.maxBars)return this._publish("state",{historyStatus:"limited"}),Promise.resolve(this._bars);const t=this._generation;let i;const s=new Promise(e=>{i=e});return this._pageWork=s,this._loadMore(t,e).then(i),s.then(()=>{this._pageWork===s&&(this._pageWork=null)}),s}async _loadMore(e,t){const i=this._state.request,s=this._options.pageWindowSec??Math.max(1,(i.to??0)-(i.from??0)||86400),r=this._feed.getBarsPage||!Number.isFinite(t)?0:this._options.maxBars*(this._seconds??1/0),n=new AbortController;this._pageAbort=n,this._publish("state",{historyStatus:"loading",historyError:void 0});try{for(let o=0;o<this._options.maxEmptyPages;o++){const o=this._before??this._bars[0]?.time??i.from;if(void 0===o)throw new Error("Older history needs a starting time");const a=r>0?Math.max(s,Math.min(r,o-t)):s,l={...i,from:o-a,to:o-1e-6,before:o,countBack:this._options.pageSize,signal:n.signal},h=this._feed.getBarsPage?await this._pool.getBarsPage(l):{bars:await this._pool.getBars(l),hasMore:void 0,nextBefore:void 0};if(!this._current(e)||n.signal.aborted)return this._bars;const c=Ua(h.bars).filter(e=>e.time<o),d=h.nextBefore??c[0]?.time??o-a;if(!Number.isFinite(d)||d>=o)throw new Error("History page did not advance its cursor");if(this._before=d,c.length){const e=new Set(this._bars.map(e=>e.time)),t=c.filter(t=>!e.has(t.time)),i=Math.max(0,this._options.maxBars-this._bars.length);this._bars=Ka(i?t.slice(-i):[],this._bars);const s=t.length>i||this._bars.length>=this._options.maxBars;return this._publish("prepend",{hasMore:t.length>i||(h.hasMore??null),historyStatus:s?"limited":!1===h.hasMore?"exhausted":"idle"}),this._bars}if(!1===h.hasMore)return this._publish("state",{hasMore:!1,historyStatus:"exhausted"}),this._bars}this._publish("state",{hasMore:null,historyStatus:"idle"})}catch(t){this._current(e)&&!n.signal.aborted&&this._publish("state",{historyStatus:"error",historyError:Ha(t)})}finally{this._pageAbort===n&&(this._pageAbort=null)}return this._bars}setPaused(e){this._destroyed||e===this._state.paused||(this._state={...this._state,paused:e},this._publish(e?"state":"resume"))}setVisible(e){this._destroyed||e===this._visible||(this._visible=e,e?this.refresh():(this._clearPoll(),this._clearRepairTimer(),this._pendingRepair=null))}destroy(){this._destroyed||(this._destroyed=!0,this._generation++,this._cancel(),this._listeners.clear())}_current(e){return!this._destroyed&&e===this._generation}_replaceWindow(e,t,i){return void 0===t||void 0===i?e:Ka(this._bars.filter(e=>e.time<t||e.time>i),e)}_limit(){this._bars.length>this._options.maxBars&&(this._bars=this._bars.slice(-this._options.maxBars))}_publish(e,t={}){if(this._destroyed)return;this._state={...this._state,...t,reason:e,bars:this._state.paused||this._buffer?this._state.bars:this._bars};const i=this._state;for(const e of[...this._listeners]){if(this._destroyed||this._state!==i)break;try{e(i)}catch{}}}_startStream(e){if(!this._current(e))return;const t=this._stream,i=++this._stream,s=this._unsubscribe;if(this._unsubscribe=null,this._feed.subscribeBars)try{const t=this._feed.subscribeBars(this._state.request,(t,s)=>{this._current(e)&&i===this._stream&&this.pushBar(t,s)},{seedFrom:this._bars[this._bars.length-1],onResync:()=>{this._current(e)&&i===this._stream&&this.refresh()}});this._current(e)&&i===this._stream?this._unsubscribe=t:this._release(t),this._release(s)}catch(r){this._current(e)&&i===this._stream?(this._stream=t,this._unsubscribe=s,this._buffer??(this._buffer=new Map),this._publish("state",{status:this._bars.length?"stale":"error",error:Ha(r)})):this._release(s)}else this._release(s)}_release(e){try{e?.()}catch{}}_clearPoll(){null!==this._poll&&clearTimeout(this._poll),this._poll=null}_schedulePoll(){this._clearPoll(),!this._destroyed&&this._visible&&this._options.pollIntervalMs>0&&(this._poll=setTimeout(()=>{this._poll=null,this.refresh()},this._options.pollIntervalMs))}_cancel(){const e=this._scope,t=this._refreshAbort,i=this._pageAbort,s=this._unsubscribe;this._refreshAbort=null,this._pageAbort=null,this._loadWork=null,this._pageWork=null,this._buffer=null,this._pendingRepair=null,this._stream++,this._unsubscribe=null,this._clearPoll(),this._clearRepairTimer(),e.abort(),t?.abort(),i?.abort(),this._release(s)}}function Xa(e){if("number"==typeof e)return e>1e12?me(e):Math.floor(e);const t=Number(e);if(""!==e.trim()&&!Number.isNaN(t)&&!/[-T :]/.test(e.trim()))return t>1e12?me(t):Math.floor(t);if(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(e.trim())){const t=Date.parse(e.trim().replace(" ","T"));if(Number.isFinite(t))return me(t)}return be(e)}function Ja(e,t){if("error"===e.status)throw new Error(e.message??"OpenAlgo history request failed");const i=e.data??[],s=[];for(const e of i){const i=e.timestamp??e.time;void 0!==i&&s.push({time:Xa(i),open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume,...!1!==t&&Number.isFinite(e.oi)?{oi:e.oi}:{}})}return s.sort((e,t)=>e.time-t.time)}class Za{constructor(e){Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_fetch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._config=e;const t=e.fetchImpl??("undefined"!=typeof fetch?fetch.bind(globalThis):void 0);if(void 0===t)throw new Error("openalgo-charts: no fetch available; pass config.fetchImpl");this._fetch=t}async getBars(e){const t=this._config.hasOpenInterest?.(e),{from:i,to:s}=e;if(void 0===i||void 0===s)throw new Error("openalgo-charts: getBars requires `from` and `to` (UTC seconds): OpenAlgo history needs a date range");return Ba(e,async r=>{const n=await this._fetch(`${this._config.baseUrl}/api/v1/history`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this._config.apiKey,symbol:e.symbol,exchange:e.exchange,interval:{"1d":"D","1D":"D","1w":"W","1W":"W","1M":"M",MN:"M"}[e.interval]??e.interval,start_date:xe(i),end_date:xe(s)})});if(!n.ok)throw new Error(`openalgo-charts: history request failed (${n.status})`);return Ja(await n.json(),t)})}}const Qa={LTP:1,Quote:2,Depth:3};function el(){return JSON.stringify({action:"subscribe_orders"})}function tl(e,t,i,s){const r={action:"subscribe",symbol:t,exchange:i,mode:Qa[e]};return"Depth"===e&&void 0!==s&&(r.depth=s,r.depth_level=s),JSON.stringify(r)}function il(e,t,i){return JSON.stringify({action:"unsubscribe",symbol:t,exchange:i,mode:Qa[e]})}function sl(e){if("string"==typeof e&&/^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(e.trim())&&(e=Number(e)),"number"==typeof e)return Number.isFinite(e)&&e>0?e>1e12?me(e):Math.floor(e):0;if("string"==typeof e&&""!==e.trim()){const t=Date.parse(e);if(Number.isFinite(t)&&t>0)return Math.floor(t/1e3)}return 0}function rl(e){for(const t of[e.last_trade_time,e.ltt,e.exchange_timestamp,e.timestamp]){const e=sl(t);if(e>0)return e}return 0}function nl(e){if("string"!=typeof e)return null;const t=e.split(".");if(2!==t.length)return null;const[i,s]=t;return""===i||""===s?null:{symbol:i,exchange:s}}function ol(e){if("object"!=typeof e||null===e)return null;const t=e,i="string"==typeof t.type?t.type.toLowerCase():"",s="string"==typeof t.status?t.status.toLowerCase():"",r="success"===s||"ok"===s||"authenticated"===s;return"auth"===i||"authenticate"===i||"auth_response"===i?r?"ok":"failed":"error"===i||"error"===s?"failed":""===i&&r&&"string"==typeof t.message&&/auth/i.test(t.message)?"ok":null}function al(e){if("object"!=typeof e||null===e)return;const t=e,i=e=>{if(void 0!==e)for(const t of["seq","sequence","sequence_number"]){const i=e[t];if("number"==typeof i&&Number.isFinite(i))return i}};return i(t)??i(t.data)}function ll(e,t,i=Math.random){const s=Math.min(t.maxDelayMs,t.baseDelayMs*2**e);return!1===t.jitter?s:Math.floor(s/2+i()*(s/2))}function hl(e){if("object"!=typeof e||null===e)return null;const t=e,i=t.data??t,s=nl(t.topic),r=i.symbol||t.symbol||s?.symbol||"",n=i.exchange||t.exchange||s?.exchange||"";if(i.depth&&(i.depth.buy||i.depth.sell)){const e=(i.depth.buy??[]).map(e=>({price:e.price,qty:e.quantity})),t=(i.depth.sell??[]).map(e=>({price:e.price,qty:e.quantity})),s=i.ltp??i.last_price??e[0]?.price??0,o=rl(i);return{kind:"depth",symbol:r,exchange:n,depth:{bids:e,asks:t,ltp:s,...Number.isFinite(o)&&o>0?{timeSec:o}:{}}}}const o=i.ltp??i.last_price;return"number"==typeof o?{kind:"ltp",event:{symbol:r,exchange:n,ltp:o,ltq:i.last_trade_quantity??i.ltq,volume:i.volume,timeSec:rl(i)}}:null}class cl{constructor(e){Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_factory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sock",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_phase",{enumerable:!0,configurable:!0,writable:!0,value:"idle"}),Object.defineProperty(this,"_epoch",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_ltpCbs",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_depthCbs",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_stateCbs",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_controlCbs",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_orderCbs",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_ordersSubscribed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_subs",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_seq",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_userClosed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_fatal",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_everAuthed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_attempts",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_reconnectTimer",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_authTimer",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_liveTimer",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_rc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_auth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_hbTimeoutMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_hbProbeMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._config=e;const t=e.socketFactory??(e=>new WebSocket(e));this._factory=t;const i=e.reconnect??{};this._rc={enabled:i.enabled??!0,baseDelayMs:i.baseDelayMs??1e3,maxDelayMs:i.maxDelayMs??3e4,maxAttempts:i.maxAttempts??1/0,jitter:i.jitter??!0,random:i.random??Math.random};const s=e.auth??{};this._auth={requireAck:s.requireAck??!0,ackTimeoutMs:s.ackTimeoutMs??5e3},this._hbTimeoutMs=e.heartbeat?.timeoutMs??45e3,this._hbProbeMs=e.heartbeat?.probeMs??5e3}connect(){null===this._sock&&(this._userClosed=!1,this._fatal=!1,this._attempts=0,null!==this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._openSocket())}isReady(){return"ready"===this._phase}_openSocket(){if(null!==this._sock)return;this._phase="connecting",this._emitState("connecting");const e=this._factory(this._config.url),t=++this._epoch;e.onmessage=e=>{t===this._epoch&&this._dispatch(e.data)},e.onopen=()=>{t===this._epoch&&this._onOpen()},e.onclose=()=>{t===this._epoch&&this._onClose()},e.onerror=()=>{t===this._epoch&&this._emitState("error")},this._sock=e,1===e.readyState&&this._onOpen()}onState(e){return this._stateCbs.add(e),()=>this._stateCbs.delete(e)}onControl(e){return this._controlCbs.add(e),()=>this._controlCbs.delete(e)}_emitState(e){for(const t of this._stateCbs)t(e)}_emitControl(e){for(const t of this._controlCbs)t(e)}_warn(e,t){const i={type:"client_warning",code:e,message:t};this._emitControl(i)}_later(e,t){const i=setTimeout(e,t);return i.unref?.(),i}_onOpen(){if("connecting"===this._phase){var e;if(this._phase="authenticating",this._sock?.send((e=this._config.apiKey,JSON.stringify({action:"authenticate",api_key:e}))),!this._auth.requireAck)return this._warn("AUTH_UNACKNOWLEDGED","proceeding without an auth acknowledgement (auth.requireAck is false)"),void this._onAuthenticated();this._authTimer=this._later(()=>this._failConnection("AUTH_TIMEOUT",`no auth acknowledgement within ${this._auth.ackTimeoutMs}ms`),this._auth.ackTimeoutMs)}}_onAuthenticated(){if("authenticating"===this._phase){this._clearTimer("auth"),this._phase="ready",this._attempts=0,this._armLiveness();for(const e of Array.from(this._subs.values()))this._sock?.send(tl(e.mode,e.symbol,e.exchange,e.depthLevel));this._ordersSubscribed&&this._sock?.send(el()),this._everAuthed&&(this._seq.clear(),this._warn("STREAM_RESYNC","reconnected: ticks were missed and the forming bar is stale, refetch it")),this._everAuthed=!0,this._emitState("open")}}_onAuthFailed(e){const t="object"==typeof e&&null!==e&&"string"==typeof e.message?e.message:"authentication refused";this._fatal=!0,this._warn("AUTH_FAILED",t),this._emitState("error"),this._dropSocket(),this._clearTimer("auth"),this._clearTimer("live"),this._phase="fatal",this._emitState("closed")}_failConnection(e,t){this._warn(e,t),this._emitState("error"),this._dropSocket(),this._clearTimer("auth"),this._clearTimer("live"),this._phase="idle",this._emitState("closed"),this._maybeReconnect()}_onClose(){this._sock=null,this._clearTimer("auth"),this._clearTimer("live"),this._phase=this._userClosed?"closed":"idle",this._emitState("closed"),this._maybeReconnect()}_maybeReconnect(){if(this._userClosed||this._fatal||!this._rc.enabled)return;if(this._attempts>=this._rc.maxAttempts)return void("fatal"!==this._phase&&(this._phase="fatal",this._warn("RECONNECT_ABANDONED",`gave up after ${this._attempts} attempts; call connect() to retry`)));const e=ll(this._attempts++,this._rc,this._rc.random);this._phase="backoff",this._emitState("reconnecting"),this._reconnectTimer=this._later(()=>{this._reconnectTimer=null,this._sock=null,this._openSocket()},e)}_sendGated(e){"ready"===this._phase&&null!==this._sock&&this._sock.send(e)}_armLiveness(){this._hbTimeoutMs<=0||"ready"!==this._phase||(this._clearTimer("live"),this._liveTimer=this._later(()=>this._probeLiveness(),this._hbTimeoutMs))}_probeLiveness(){"ready"===this._phase&&null!==this._sock&&(this._sock.send(JSON.stringify({action:"ping"})),this._liveTimer=this._later(()=>this._failConnection("HEARTBEAT_DEAD",`no answer to a liveness ping within ${this._hbProbeMs}ms`),this._hbProbeMs))}_clearTimer(e){const t="auth"===e?this._authTimer:"live"===e?this._liveTimer:this._reconnectTimer;null!==t&&clearTimeout(t),"auth"===e?this._authTimer=null:"live"===e?this._liveTimer=null:this._reconnectTimer=null}_dropSocket(){const e=this._sock;if(this._sock=null,this._epoch++,null!==e)try{e.close()}catch{}}onLtp(e){return this._ltpCbs.add(e),()=>this._ltpCbs.delete(e)}onDepth(e){return this._depthCbs.add(e),()=>this._depthCbs.delete(e)}subscribe(e,t,i,s){this._subs.set(`${e}:${t}:${i}`,{mode:e,symbol:t,exchange:i,depthLevel:s}),this._sendGated(tl(e,t,i,s))}unsubscribe(e,t,i){this._subs.delete(`${e}:${t}:${i}`),this._sendGated(il(e,t,i))}onOrderUpdate(e){return this._orderCbs.add(e),()=>this._orderCbs.delete(e)}subscribeOrders(){this._ordersSubscribed=!0,this._sendGated(el())}unsubscribeOrders(){this._ordersSubscribed=!1,this._sendGated(JSON.stringify({action:"unsubscribe_orders"}))}close(){this._userClosed=!0,this._clearTimer("reconnect"),this._clearTimer("auth"),this._clearTimer("live"),this._dropSocket(),this._subs.clear(),this._ordersSubscribed=!1,this._seq.clear(),this._attempts=0,this._everAuthed=!1,this._fatal=!1,this._phase="closed",this._emitState("closed")}_sequenceOk(e,t){const i=al(t);if(void 0===i)return!0;const s=this._seq.get(e);return!(void 0!==s&&i<=s)&&(void 0!==s&&i>s+1&&this._warn("SEQUENCE_GAP",`${e}: ${i-s-1} frame(s) missing, the forming bar is suspect`),this._seq.set(e,i),!0)}_dispatch(e){let t;try{t=JSON.parse(e)}catch{t=e}if(this._armLiveness(),function(e){return"ping"===e||"object"==typeof e&&null!==e&&"ping"===e.type}(t))return void this._sock?.send(JSON.stringify({action:"pong"}));if("authenticating"===this._phase){const e=ol(t);if(null!==e)return this._emitControl(t),void("ok"===e?this._onAuthenticated():this._onAuthFailed(t))}const i=function(e){if("object"!=typeof e||null===e)return null;const t=e;if("order_update"!==t.type)return null;const i=e=>{if("number"==typeof e)return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isNaN(t)?0:t}return 0},s=e=>"string"==typeof e?e:"",r=i(t.trigger_price);return{orderId:s(t.orderid),symbol:s(t.symbol),exchange:s(t.exchange),action:"SELL"===t.action?"SELL":"BUY",quantity:i(t.quantity),price:i(t.price),triggerPrice:r>0?r:void 0,pricetype:""===s(t.pricetype)?"LIMIT":s(t.pricetype),product:s(t.product),status:s(t.order_status).toLowerCase(),filledQuantity:i(t.filled_quantity),pendingQuantity:i(t.pending_quantity),averagePrice:i(t.average_price),rejectionReason:s(t.rejection_reason),mode:s(t.mode)}}(t);if(null!==i){if(!this._sequenceOk("orders",t))return;for(const e of this._orderCbs)e(i);return}const s=hl(t);if(null===s)return void("object"==typeof t&&null!==t&&this._emitControl(t));const r=t.topic;if("ltp"===s.kind){if(!this._sequenceOk(r??`ltp:${s.event.symbol}.${s.event.exchange}`,t))return;for(const e of this._ltpCbs)e(s.event)}else{if(!this._sequenceOk(r??`depth:${s.symbol}.${s.exchange}`,t))return;for(const e of this._depthCbs)e(s.symbol,s.exchange,s.depth)}}}function dl(e,t){if(!Number.isFinite(e))return{ok:!1,code:"QTY_INVALID",reason:"quantity must be a finite number"};if(e<=0)return{ok:!1,code:"QTY_INVALID",reason:"quantity must be positive"};const i=t.lotSize??(!0===t.allowFractionalQty?void 0:1);return void 0!==i&&function(e,t){if(!Number.isFinite(t)||t<=0)return!1;const i=e/t,s=Math.round(i);if(!Number.isSafeInteger(s)||s<1)return!0;if(s*t===e)return!1;const r=Math.min(1e-7,8*Number.EPSILON*Math.max(1,Math.abs(i)));return Math.abs(i-s)>r}(e,i)?{ok:!1,code:"QTY_STEP",reason:void 0!==t.lotSize?`quantity ${e} is not a multiple of lot size ${t.lotSize}`:`quantity ${e} must be a whole number`}:void 0!==t.freezeQty&&e>t.freezeQty?{ok:!1,code:"QTY_FREEZE_LIMIT",reason:`quantity ${e} exceeds freeze limit ${t.freezeQty}`}:{ok:!0}}function ul(e){return Object.assign(new Error(e),{preflight:!0})}class pl{constructor(e){Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_fetch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_strategy",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_defaultProduct",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ctx",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_claimed",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_verifyMode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_modeCacheMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_mode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_modeAt",{enumerable:!0,configurable:!0,writable:!0,value:0}),this._config=e,this._strategy=e.strategy??"openalgo-charts",this._defaultProduct=e.defaultProduct??"MIS",this._verifyMode=e.verifyMode??"auto",this._modeCacheMs=e.modeCacheMs??5e3,this._now=e.now??Date.now;const t=e.fetchImpl??("undefined"!=typeof fetch?fetch.bind(globalThis):void 0);if(void 0===t)throw new Error("openalgo-charts: no fetch available; pass config.fetchImpl");this._fetch=t}async _post(e,t){const i=await this._fetch(`${this._config.baseUrl}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this._config.apiKey,...t})});if(!i.ok){let t="";try{const e=await i.json();"string"==typeof e.message&&""!==e.message&&(t=`: ${e.message}`)}catch{}throw new Error(`openalgo-charts: ${e} failed (${i.status})${t}`)}const s=await i.json(),r=Ol(s);return void 0!==r&&(this._mode=r,this._modeAt=this._now()),s}async getServerMode(e=this._modeCacheMs){const t=this._freshMode(e);if(void 0!==t)return t;const i=Ol(await this._post("/api/v1/analyzer/",{}));if(void 0===i)throw new Error("openalgo-charts: /api/v1/analyzer/ returned no readable mode");return i}serverMode(e=this._modeCacheMs){return this._freshMode(e)}_freshMode(e){if(void 0!==this._mode)return this._now()-this._modeAt<=e?this._mode:void 0}async _assertMode(e){if("off"===this._verifyMode)return;if("live"!==e&&"analyzer"!==e)return;let t=this._freshMode(this._modeCacheMs);if(void 0===t&&("always"===this._verifyMode||"analyzer"===e))try{t=await this.getServerMode()}catch(e){throw ul(`openalgo-charts: cannot confirm the server mode, no order was sent (${String(e.message??e)})`)}if(void 0!==t&&t!==e)throw ul(`openalgo-charts: refusing to place, caller expects ${e} mode but the OpenAlgo server is in ${t} mode`)}_assertQuantity(e){const t=e.exchange??"NSE",i=this._config.constraints?.(e.symbol,t)??{},s=dl(e.qty,i);if(!s.ok)throw ul(`openalgo-charts: ${e.symbol} ${t}: ${s.reason}`)}_claimToken(e){if(void 0===e||!0===this._config.disableIdempotency)return;const t=this._claimed.get(e);if(void 0!==t)throw ul("ambiguous"===t?`openalgo-charts: clientToken ${e} may already be live at the broker; check the order book before retrying`:`openalgo-charts: duplicate clientToken ${e}`);return this._claimed.set(e,"inflight"),e}get capabilities(){return this._config.capabilities}async place(e){const t={...e},i={operation:"place",symbol:t.symbol,exchange:t.exchange??"NSE",type:t.type,mode:t.mode};Fa(this.capabilities,i),await this._assertMode(t.mode),Fa(this.capabilities,i),this._assertQuantity(t);const s=this._claimToken(t.clientToken),r={symbol:t.symbol,exchange:t.exchange??"NSE",action:t.side,pricetype:t.type,product:t.product??this._defaultProduct,quantity:t.qty,price:t.price??0,triggerPrice:t.triggerPrice??0};let n;try{n=await this._post("/api/v1/placeorder",{strategy:this._strategy,symbol:r.symbol,action:r.action,exchange:r.exchange,pricetype:r.pricetype,product:r.product,quantity:t.qty,price:t.price??0,trigger_price:t.triggerPrice??0,disclosed_quantity:0})}catch(e){throw void 0!==s&&this._claimed.set(s,"ambiguous"),e}const o=n.orderid??n.order_id;if(void 0===o)throw new Error("openalgo-charts: placeorder returned no orderid");return void 0!==s&&this._claimed.set(s,"sent"),this._ctx.set(o,r),{orderId:o}}tokenState(e){return this._claimed.get(e)??"unknown"}releaseToken(e){this._claimed.delete(e)}async modify(e,t){const i={...t},s=this._ctx.get(e);if(Fa(this.capabilities,{operation:"modify",orderId:e,symbol:s?.symbol,exchange:s?.exchange,type:s?.pricetype}),void 0===s)throw ul(`openalgo-charts: cannot modify ${e}, unknown order context (place it or load the order book first)`);void 0!==i.qty&&(s.quantity=i.qty),void 0!==i.price&&(s.price=i.price),void 0!==i.triggerPrice&&(s.triggerPrice=i.triggerPrice),await this._post("/api/v1/modifyorder",{orderid:e,strategy:this._strategy,symbol:s.symbol,action:s.action,exchange:s.exchange,pricetype:s.pricetype,product:s.product,quantity:s.quantity,price:s.price,trigger_price:s.triggerPrice,disclosed_quantity:0})}async cancel(e){const t=this._ctx.get(e);Fa(this.capabilities,{operation:"cancel",orderId:e,symbol:t?.symbol,exchange:t?.exchange,type:t?.pricetype}),await this._post("/api/v1/cancelorder",{orderid:e,strategy:this._strategy})}async getOrderBook(){const e=await this._post("/api/v1/orderbook",{}),t=Array.isArray(e.data)?e.data:e.data?.orders??[],i=[],s=[];for(let e=0;e<t.length;e++){const r=t[e],n=xl(r,`orders[${e}]`);if(!n.ok){s.push({issue:n.issue,raw:r});continue}i.push(n.order);const o=fl(r.exchange),a=fl(r.product);void 0!==o&&void 0!==a&&this._ctx.set(n.order.id,{symbol:n.order.symbol,exchange:o,action:n.order.side,pricetype:n.order.type,product:a,quantity:n.order.qty,price:n.order.price,triggerPrice:n.order.triggerPrice??0})}return s.length>0&&this._config.onDecodeIssue?.({orders:i,quarantined:s}),{orders:i,quarantined:s}}async getOrders(){return(await this.getOrderBook()).orders}async getPositions(){return((await this._post("/api/v1/positionbook",{})).data??[]).map(Pl)}}function _l(e){const t="number"==typeof e?e:"string"==typeof e&&""!==e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function fl(e){return"string"==typeof e&&""!==e.trim()?e.trim():void 0}const ml="a non-empty string",bl="a finite number",gl="a number of 0 or more";function vl(e,t,i,s){return{ok:!1,issue:{path:e,code:t,expected:i,got:("string"==typeof s?s:String(s)).slice(0,64)}}}const yl={open:"working",pending:"pending",trigger_pending:"working","trigger pending":"working",complete:"filled",cancelled:"cancelled",rejected:"rejected"};function wl(e){return yl[e.trim().toLowerCase()]??"unknown"}function xl(e,t="order"){const i=fl(e.orderid);if(void 0===i)return vl(`${t}.orderid`,"MISSING",ml,e.orderid);const s=fl(e.symbol);if(void 0===s)return vl(`${t}.symbol`,"MISSING",ml,e.symbol);const r=fl(e.action)?.toUpperCase();if("BUY"!==r&&"SELL"!==r)return vl(`${t}.action`,"UNKNOWN_ENUM","BUY or SELL",e.action);const n=fl(e.pricetype)?.toUpperCase();if("MARKET"!==n&&"LIMIT"!==n&&"SL"!==n&&"SL-M"!==n)return vl(`${t}.pricetype`,"UNKNOWN_ENUM","MARKET, LIMIT, SL or SL-M",e.pricetype);const o=_l(e.quantity);if(void 0===o)return vl(`${t}.quantity`,void 0===e.quantity?"MISSING":"NON_FINITE",bl,e.quantity);if(o<0)return vl(`${t}.quantity`,"RANGE",gl,e.quantity);const a=void 0===e.filled_quantity?0:_l(e.filled_quantity);if(void 0===a)return vl(`${t}.filled_quantity`,"NON_FINITE",bl,e.filled_quantity);const l=void 0===e.price?0:_l(e.price);if(void 0===l)return vl(`${t}.price`,"NON_FINITE",bl,e.price);if(l<0)return vl(`${t}.price`,"RANGE",gl,e.price);const h=void 0===e.trigger_price?0:_l(e.trigger_price);if(void 0===h)return vl(`${t}.trigger_price`,"NON_FINITE",bl,e.trigger_price);const c=fl(e.order_status)??"",d=yl[c.toLowerCase()],u={id:i,symbol:s,side:r,type:n,qty:o,filledQty:a,price:l,triggerPrice:h>0?h:void 0,status:d??"unknown"};return void 0===d&&(u.rawStatus=c),{ok:!0,order:u}}function Sl(e){const t=xl(e);return t.ok?t.order:{id:fl(e.orderid)??"",symbol:fl(e.symbol)??"",side:fl(e.action)??"",type:fl(e.pricetype)??"",qty:_l(e.quantity)??0,filledQty:_l(e.filled_quantity)??0,price:_l(e.price)??0,status:"unknown",rawStatus:fl(e.order_status)??""}}function Pl(e){return{symbol:e.symbol??"",netQty:_l(e.quantity)??0,avgPrice:_l(e.average_price)??0}}function Ol(e){if("object"!=typeof e||null===e)return;const t=e,i=t.mode??t.data?.mode;if("analyze"===i)return"analyzer";if("live"===i)return"live";const s=t.data?.analyze_mode;return"boolean"==typeof s?s?"analyzer":"live":void 0}class kl{constructor(e,t={}){Object.defineProperty(this,"_tf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_zone",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_cur",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_count",{enumerable:!0,configurable:!0,writable:!0,value:0}),this._tf=e,this._zone=t.timezone}current(){return null===this._cur?null:{...this._cur}}seed(e){Ps(this._tf)&&(this._cur={...e},this._count=0)}onTick(e){const t=null===this._cur;let i=t;if(t||null===this._cur||(i="interval"===this._tf.mode||"calendar"===this._tf.mode?Cs(this._tf,e.time,this._zone)!==this._cur.time:"ticks"===this._tf.mode?this._count>=this._tf.count:(this._cur.volume??0)>=this._tf.perBar),i){const t=Cs(this._tf,e.time,this._zone);return this._cur={time:t,open:e.price,high:e.price,low:e.price,close:e.price,volume:e.qty},void 0!==e.oi&&Number.isFinite(e.oi)&&(this._cur.oi=e.oi),this._count=1,{bar:{...this._cur},isNew:!0}}const s=this._cur;return e.price>s.high&&(s.high=e.price),e.price<s.low&&(s.low=e.price),s.close=e.price,s.volume=(s.volume??0)+e.qty,void 0!==e.oi&&Number.isFinite(e.oi)?s.oi=e.oi:delete s.oi,this._count+=1,{bar:{...s},isNew:!1}}}function Il(e){const{bucketing:t}=Ss(e);if("interval"!==t.mode)throw new Error(`openalgo-charts: interval "${e}" is ${t.mode}-bucketed and has no fixed length. Use resolveInterval() and bucketStartOf() instead of intervalToSeconds().`);return t.seconds}class Ml{constructor(e){Object.defineProperty(this,"_rest",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_volumeMode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timezone",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_depthLevel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tickMode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subs",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),this._rest=new Za(e),this._ws=new cl({url:e.wsUrl,apiKey:e.apiKey,socketFactory:e.socketFactory,reconnect:e.reconnect,auth:e.auth,heartbeat:e.heartbeat}),this._volumeMode=e.volumeMode??"ltq-sum",this._timezone=e.timezone,this._depthLevel=e.depthLevel,this._tickMode="day-delta"===this._volumeMode?"Quote":"LTP",this._ws.connect()}_acquire(e,t,i,s){const r=`${e}:${t}:${i}`,n=this._subs.get(r);void 0===n?(this._subs.set(r,{count:1,level:s}),this._ws.subscribe(e,t,i,s)):(n.count+=1,void 0!==s&&(void 0===n.level||s>n.level)&&(n.level=s,this._ws.subscribe(e,t,i,s)));let o=!1;return()=>{if(o)return;o=!0;const s=this._subs.get(r);void 0!==s&&(s.count-=1,s.count>0||(this._subs.delete(r),this._ws.unsubscribe(e,t,i)))}}getBars(e){return this._rest.getBars(e)}subscribeBars(e,t,i){const{bucketing:s}=Ss(e.interval),r="interval"===s.mode?this._candleReader(s,t,i):this._aggregatorReader(s,t,i),n=this._ws.onLtp(t=>{t.symbol===e.symbol&&(t.exchange&&e.exchange&&t.exchange!==e.exchange||r(t))}),o=i?.onResync?this._ws.onControl(e=>{"client_warning"===e.type&&"STREAM_RESYNC"===e.code&&i.onResync?.()}):void 0,a=this._acquire(this._tickMode,e.symbol,e.exchange);return()=>{n(),o?.(),a()}}static _tickTime(e){return e.timeSec&&e.timeSec>0?e.timeSec:Math.floor(Date.now()/1e3)}_candleReader(e,t,i){const s=new ra({intervalSec:e.seconds,sessionAnchorSec:e.anchorSec??0,volumeMode:this._volumeMode});return i?.seedFrom&&s.seed(i.seedFrom,i.cumDayVolumeSoFar),e=>{const i=s.onTick({time:Ml._tickTime(e),price:e.ltp,ltq:e.ltq,cumDayVolume:e.volume});null!==i&&t(i.bar,i.provisional?{provisional:!0}:void 0)}}_aggregatorReader(e,t,i){const s=new kl(e,{timezone:this._timezone});i?.seedFrom&&Ps(e)&&s.seed(i.seedFrom);const r=function(e,t){if("ltq-sum"===e)return e=>e.ltq??0;let i=t??null;return e=>{const t=e.volume??0,s=null===i?0:t<i?t:t-i;return i=t,Math.max(0,s)}}(this._volumeMode,i?.cumDayVolumeSoFar);return e=>{const i=s.onTick({time:Ml._tickTime(e),price:e.ltp,qty:r(e)});t(i.bar)}}subscribeDepth(e,t,i){const s=this._ws.onDepth((i,s,r)=>{i===e.symbol&&(s&&e.exchange&&s!==e.exchange||t(r))}),r=this._acquire("Depth",e.symbol,e.exchange,i?.depthLevel??this._depthLevel);return()=>{s(),r()}}close(){this._subs.clear(),this._ws.close()}}const Tl=(e,t)=>{const i=setInterval(e,t);return()=>clearInterval(i)};class Cl{constructor(e=60,t=Tl){Object.defineProperty(this,"intervalSec",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schedule",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.intervalSec=e,this._schedule=t}async getBars(e){return jl(e.from??17e8,500,this.intervalSec)}subscribeBars(e,t,i){let s=i?.seedFrom?.time??e.from??17e8,r=i?.seedFrom?.close??100,n=19088743;const o=()=>(n^=n<<13,n>>>=0,n^=n>>17,n^=n<<5,n>>>=0,n/4294967295);return this._schedule(()=>{s+=this.intervalSec;const e=r,i=Math.max(1,e+2*(o()-.5)),n=Math.max(e,i)+o(),a=Math.max(.01,Math.min(e,i)-o());t({time:s,open:e,high:n,low:a,close:i,volume:Math.round(1e3+9e3*o())}),r=i},i?.tickMs??1e3)}}function jl(e,t,i){const s=[];let r=100,n=2654435769;const o=()=>(n^=n<<13,n>>>=0,n^=n>>17,n^=n<<5,n>>>=0,n/4294967295);for(let n=0;n<t;n++){const t=2*(o()-.5),a=r,l=Math.max(1,a+t),h=Math.max(a,l)+o(),c=Math.min(a,l)-o();s.push({time:e+n*i,open:a,high:h,low:c,close:l,volume:Math.round(1e3+9e3*o())}),r=l}return s}const Al=1;function Ll(e,t,i){const s=ws(e);if(null===s)return null;const r=s.bucketing;return"interval"===r.mode?t+r.seconds:js(r,t,i)}function Rl(e){return`${e.symbol}|${e.exchange}|${e.interval}`}function zl(e){const t=new Array(e.length);for(let i=0;i<e.length;i++)t[i]={...e[i]};return t}function Fl(e){e?.throwIfAborted()}class Nl{constructor(e,t={}){Object.defineProperty(this,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_backing",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_memory",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_tombstones",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_writes",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_ttlMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_max",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_maxBars",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_barCloses",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_index",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_tick",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_hits",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_misses",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_evictions",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"subscribeBars",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscribeDepth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"getBarsPage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.source=e,this._backing=t.storage,this._ttlMs=t.ttlMs??3e5,this._max=t.max??24,this._maxBars=t.maxBars??25e4,this._now=t.now??(()=>Date.now());const i=t.timezone;this._barCloses=t.barCloses??((e,t)=>Ll(e,t,i)),"function"==typeof e.subscribeBars&&(this.subscribeBars=(t,i,...s)=>e.subscribeBars(t,i,...s)),"function"==typeof e.subscribeDepth&&(this.subscribeDepth=(t,i,...s)=>e.subscribeDepth(t,i,...s)),"function"==typeof e.getBarsPage&&(this.getBarsPage=t=>e.getBarsPage(t))}async getBars(e){if(Fl(e.signal),void 0===e.from||void 0===e.to){const t=await this.source.getBars(e);return Fl(e.signal),t}const t=Rl(e);if(!0!==e.noCache){const i=await this._lookup(t,e.interval,e.from,e.to);if(Fl(e.signal),void 0!==i)return this._hits++,i;this._misses++}Fl(e.signal);const i=await this.source.getBars(e);return Fl(e.signal),await this._put(t,e.from,e.to,e.interval,i,e.signal),Fl(e.signal),i}async getCachedBars(e){if(Fl(e.signal),!0===e.noCache||void 0===e.from||void 0===e.to)return;const t=Rl(e),i=await this._readEntry(t,e.interval);if(Fl(e.signal),void 0===i)return;if(this._now()-i.storedAt>this._ttlMs)return await this._drop(t),void Fl(e.signal);const s=this._slice(i,e.from,e.to);return 0!==s.length?(this._remember(t,i),await this._evict(),Fl(e.signal),s):void 0}async invalidate(e){if(void 0===e)return this.clear();const t=Rl(e);await this._drop(t)}async clear(){const e=new Set([...this._memory.keys(),...this._tombstones]);this._memory.clear(),this._index.clear();for(const t of e)await this._deleteBacking(t)}stats(){let e=0;for(const t of this._index.values())e+=t.bars;return{entries:this._index.size,bars:e,hits:this._hits,misses:this._misses,evictions:this._evictions}}async _lookup(e,t,i,s){const r=await this._readEntry(e,t);if(void 0===r)return;const n=this._now();if(n-r.storedAt>this._ttlMs)return void await this._drop(e);if(i<r.from)return;const o=Math.floor(n/1e3);return s>r.to&&o>=r.nextClose?void 0:(this._remember(e,r),await this._evict(),this._slice(r,i,s))}_slice(e,t,i){const s=[];for(const r of e.bars)if(!(r.time<t)){if(r.time>i)break;s.push({...r})}return s}async _put(e,t,i,s,r,n){const o=this._now(),a=Math.floor(o/1e3),l=r.filter(e=>e.time>=t&&e.time<=i);let h=l.length;for(;h>0;){const e=this._barCloses(s,l[h-1].time);if(null!==e&&e<=a)break;h--}if(0===h)return;if(h>this._maxBars)return;const c=zl(l.slice(0,h)),d=c[c.length-1],u=this._barCloses(s,d.time),p=this._barCloses(s,u)??u,_={version:1,bars:c,from:t,to:Math.min(i,u-1),storedAt:o,nextClose:p};if(!this._validEntry(_,s,o))return;Fl(n);const f=Symbol(e);if(this._writes.set(e,f),this._remember(e,_),await this._writeBacking(e,_),this._writes.get(e)!==f)return await this._restoreLatestBacking(e),void Fl(n);!0===n?.aborted&&(this._memory.delete(e),this._index.delete(e),this._writes.delete(e),await this._deleteBacking(e),Fl(n)),await this._evict(),!0===n?.aborted&&this._writes.get(e)===f&&(this._memory.delete(e),this._index.delete(e),this._writes.delete(e),await this._deleteBacking(e),Fl(n)),this._writes.get(e)===f&&this._writes.delete(e)}async _drop(e){this._memory.delete(e),this._index.delete(e),await this._deleteBacking(e)}async _evict(){for(;;){let e,t=0;for(const e of this._index.values())t+=e.bars;if(this._index.size<=this._max&&t<=this._maxBars)return;let i=1/0;for(const[t,s]of this._index)s.lastUsed<i&&(i=s.lastUsed,e=t);if(void 0===e)return;this._evictions++,await this._drop(e)}}_remember(e,t){const i=this._cloneEntry(t);this._memory.set(e,i),this._index.set(e,{lastUsed:++this._tick,bars:i.bars.length})}async _readEntry(e,t){const i=this._memory.get(e);if(void 0===this._backing||this._tombstones.has(e))return i;let s;try{s=await this._backing.get(e)}catch{return i}if(void 0===s)return i;const r=this._now();if(!this._validEntry(s,t,r))return await this._deleteBacking(e),i;const n=this._cloneEntry(s);return void 0!==i&&i.storedAt>=n.storedAt?i:n}_validEntry(e,t,i){if("object"!=typeof e||null===e)return!1;const s=e;if(void 0!==s.version&&1!==s.version)return!1;if(!Number.isFinite(s.from)||!Number.isInteger(s.from))return!1;if(!Number.isFinite(s.to)||!Number.isInteger(s.to))return!1;if(!Number.isFinite(s.storedAt)||s.storedAt<0||s.storedAt>i)return!1;if(!Number.isFinite(s.nextClose)||!Number.isInteger(s.nextClose))return!1;if(s.from>s.to||s.nextClose<=s.to)return!1;if(!Array.isArray(s.bars)||0===s.bars.length)return!1;if(s.bars.length>this._maxBars||this._max<1)return!1;const r=Math.floor(i/1e3);let n=-1/0,o=null;for(const e of s.bars){if(!this._validBar(e)||e.time<=n)return!1;if(e.time<s.from||e.time>s.to)return!1;if(o=this._barCloses(t,e.time),null===o||o>r)return!1;n=e.time}const a=this._barCloses(t,o)??o;return s.nextClose===a}_validBar(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Number.isInteger(t.time)&&(!![t.open,t.high,t.low,t.close].every(Number.isFinite)&&(!(void 0!==t.volume&&!Number.isFinite(t.volume))&&(!(void 0!==t.oi&&!Number.isFinite(t.oi))&&(void 0===t.color||"string"==typeof t.color))))}_cloneEntry(e){const t={bars:zl(e.bars),from:e.from,to:e.to,storedAt:e.storedAt,nextClose:e.nextClose};return void 0!==e.version&&(t.version=e.version),t}async _writeBacking(e,t){if(void 0!==this._backing)try{await this._backing.set(e,this._cloneEntry(t)),this._tombstones.delete(e)}catch{this._tombstones.add(e)}}async _deleteBacking(e){if(void 0!==this._backing)try{await this._backing.delete(e),this._tombstones.delete(e)}catch{this._tombstones.add(e)}}async _restoreLatestBacking(e){const t=this._memory.get(e);void 0===t?await this._deleteBacking(e):await this._writeBacking(e,t)}}function El(e,t){return new Nl(e,t)}let Bl;function $l(){if(!Bl){Bl=new Map([{id:"bullish",title:"Bullish bar",when:({bars:e,index:t})=>e[t].close>e[t].open},{id:"bearish",title:"Bearish bar",when:({bars:e,index:t})=>e[t].close<e[t].open},{id:"inside",title:"Inside bar",when:({bars:e,index:t})=>t>0&&e[t].high<e[t-1].high&&e[t].low>e[t-1].low},{id:"outside",title:"Outside bar",when:({bars:e,index:t})=>t>0&&e[t].high>e[t-1].high&&e[t].low<e[t-1].low},{id:"gap-up",title:"Gap up",when:({bars:e,index:t})=>t>0&&e[t].low>e[t-1].high},{id:"gap-down",title:"Gap down",when:({bars:e,index:t})=>t>0&&e[t].high<e[t-1].low}].map(e=>[e.id,Object.freeze(e)]))}return Bl}function Dl(e){if("string"!=typeof e.id||!e.id.trim()||"string"!=typeof e.title||!e.title.trim()||"function"!=typeof e.when)throw new Error("Invalid bar condition");if($l().has(e.id))throw new Error(`Bar condition id already registered: ${e.id}`);$l().set(e.id,Object.freeze({...e}))}function Wl(e){return $l().delete(e)}function ql(e){return $l().get(e)}function Vl(){return[...$l().values()]}const Hl={armed:"#3b82f6",triggered:"#22c55e",disabled:"#64748b",expired:"#d97706"};function Gl(e,t){return t?"Paused":"armed"===e?"Alert":e[0].toUpperCase()+e.slice(1)}class Ul extends Er{constructor(){super(...arguments),Object.defineProperty(this,"_movable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_committedPrice",{enumerable:!0,configurable:!0,writable:!0,value:this.price}),Object.defineProperty(this,"_context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_resolveScale",{enumerable:!0,configurable:!0,writable:!0,value:e=>e.priceScale}),Object.defineProperty(this,"_canAutoscale",{enumerable:!0,configurable:!0,writable:!0,value:()=>!0})}bind(e,t,i,s){this._movable=e,this._committedPrice=t,this._resolveScale=i,this._canAutoscale=s}zOrder(){return"top"}autoscaleInfo(){return this._canAutoscale()?this._context&&this._resolveScale(this._context)!==this._context.priceScale?null:{min:this._committedPrice,max:this._committedPrice}:null}draw(e,t){this._context=t;const i=this._resolveScale(t);e.save(),i!==t.priceScale&&(e.beginPath(),e.rect(0,0,t.plotWidth*t.dpr,t.plotHeight*t.dpr),e.clip()),super.draw(e,{...t,priceScale:i}),e.restore()}hitTest(e,t,i){this._context=i;const s=this._movable?super.hitTest(e,t,{...i,priceScale:this._resolveScale(i)}):null;return s?{...s,zOrder:"top",draggable:!0,cancelOnEscape:!0}:null}coordinateToPrice(e){return this._context?this._resolveScale(this._context).yToPrice(e):void 0}}function Kl(e){const t=/^alert:(.+):(\d+)$/.exec(e);if(null===t)return null;const i=Number(t[2]);return 0===i||1===i?{id:t[1],index:i}:null}class Yl{constructor(e){Object.defineProperty(this,"_chart",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_lines",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}update(e,t,i,s){if(!this._chart.addPrimitive||!this._chart.removePrimitive)return;if(!t)return void this.remove(e.id);const r=void 0===t.upperPrice?[t.price]:[t.price,t.upperPrice],n=function(e){return"price"===e.source.kind||"indicator"===e.source.kind}(e)&&"armed"===e.state&&!i,{source:o}=e,a=()=>"indicator"===o.kind?this._chart.indicators?.().find(e=>e.id===o.instanceId)?.series(o.plotKey)?.priceScale():"price"===o.kind?this._chart.primarySeries?.()?.priceScale():void 0,l=e=>"indicator"===o.kind?a()??e.priceScale:"price"===o.kind?e.readoutPriceScale??e.priceScale:e.priceScale,h=()=>{const e=this._chart.panes?.()[t.paneIndex]?.priceScale;return void 0===e||(a()??e)===e};let c=this._lines.get(e.id);!c||c.pane===t.paneIndex&&c.lines.length===r.length||(this.remove(e.id),c=void 0),c||(c={pane:t.paneIndex,lines:[]},this._lines.set(e.id,c));for(let o=0;o<r.length;o++){const a={price:r[o],color:Hl[e.state],lineStyle:"armed"===e.state?"dashed":"dotted",badge:Gl(e.state,i),leftLabel:e.title+(void 0===s?"":` (${s})`)+(2===r.length?0===o?" (lower)":" (upper)":""),cursor:n?"ns-resize":void 0},d=c.lines[o];if(d){d.bind(n,r[o],l,h);const e=d.options();Object.entries(a).some(([t,i])=>e[t]!==i)&&d.setOptions(a)}else{const i=new Ul({...a,id:`alert:${e.id}:${o}`});i.bind(n,r[o],l,h),c.lines.push(i),this._chart.addPrimitive(i,t.paneIndex)}}}preview(e,t){const i=Kl(e);i&&this._lines.get(i.id)?.lines[i.index]?.setPrice(t)}coordinateToPrice(e,t){const i=Kl(e);return i?this._lines.get(i.id)?.lines[i.index]?.coordinateToPrice(t):void 0}remove(e){const t=this._lines.get(e);if(t){this._lines.delete(e);for(const e of t.lines)this._chart.removePrimitive?.(e)}}destroy(){for(const e of this._lines.keys())this.remove(e)}}const Xl=new WeakSet;let Jl=1;const Zl=e=>{const t=e.getDataContext();return{symbol:t?.symbol,exchange:t?.exchange,interval:t?.interval}},Ql=(e,t)=>e.symbol===t.symbol&&e.exchange===t.exchange,eh=(e,t)=>Ql(e,t)&&e.interval===t.interval;class th{constructor(e,t={}){if(Object.defineProperty(this,"_chart",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_records",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_hovered",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_off",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_drawings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_spentLines",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_visuals",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timerAt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_paused",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_restoring",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_replay",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_revision",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_drag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Xl.has(e))throw new Error("An alert controller already owns this chart");this._now=t.now??(()=>Date.now()/1e3),this._drawings=t.drawings,this._spentLines=t.spentLines??"show",this._visuals=!1===t.visuals?void 0:new Yl(e),Xl.add(e),this._off=[e.on("data:update",e=>this._onData(e)),e.on("data:context",()=>this._seedAll()),e.on("objects:change",()=>this._onObjects()),e.on("paneMoved",()=>this._onObjects()),e.on("state:restore:start",()=>{this._hovered=void 0,this._cancelDrag(),this._restoring=!0,this._revision++}),e.on("state:restore:end",()=>{this._restoring=!1,this._seedAll()}),e.on("alerts:restore",e=>this.fromJSON(e)),e.on("replay:start",()=>{this._replay=!0,this._seedAll()}),e.on("replay:stop",()=>{this._replay=!1,this._seedAll()}),e.on("destroy",()=>this.destroy()),e.on("drag:start",e=>this._startDrag(e)),e.on("hover",e=>{const t=e?.id,i="string"==typeof t?Kl(t):null;this._hovered=null!==i&&this._records.has(i.id)?i.id:void 0}),e.on("drag",e=>this._onDrag(e,!1)),e.on("drag:end",e=>this._onDrag(e,!0)),e.on("drag:cancel",e=>{e.id===this._drag?.externalId&&this._cancelDrag()})];try{const t=e.alertState?.();void 0!==t&&this.fromJSON(t)}catch(e){throw this.destroy(),e}}_dragAvailability(e,t){const i=e.alert.source;return this._destroyed||this._restoring||"armed"!==e.alert.state||this._records.get(e.alert.id)!==e||"price"!==i.kind&&"indicator"!==i.kind||0!==t&&(1!==t||void 0===("price"===i.kind?i.upperPrice:i.upperValue))?{available:!1}:this.availability(e.alert.id)}hovered(){const e=void 0===this._hovered?void 0:this._records.get(this._hovered);return e&&this._dragAvailability(e,0).available?e.alert.id:void 0}_dragPrice(e,t,i){const s=e.point?.y,r=("number"==typeof s&&Number.isFinite(s)?this._visuals?.coordinateToPrice(t,s):void 0)??e.price;if("number"!=typeof r||!Number.isFinite(r))return;const n=Kl(t),o=n&&this._records.get(n.id)?.alert.source,a="price"===o?.kind?this._chart.primarySeries?.()?.priceScale():"indicator"===o?.kind?this._chart.indicators?.().find(e=>e.id===o.instanceId)?.series(o.plotKey)?.priceScale():void 0,l=i??e.paneIndex,h=a?d(r,a.options.minMove):"number"==typeof l?this._chart.snapPrice?.(l,r)??r:r;let c=Number.isFinite(h)?h:r;if(n&&("price"===o?.kind||"indicator"===o?.kind)){const e=0===n.index?"price"===o.kind?o.upperPrice:o.upperValue:"price"===o.kind?o.price:o.value;if(void 0!==e&&(0===n.index?c>e:c<e)){c=e;const t=a?.options.minMove??0;if(t>0){c=d(e,t);const i=Number.EPSILON*Math.max(1,Math.abs(e))*4;Math.abs(c-e)<=i?c=e:(0===n.index?c>e:c<e)&&(c=d(e+(0===n.index?-t:t),t))}else if(!a&&"number"==typeof l&&this._chart.snapPrice&&(c=this._chart.snapPrice(l,e),!Number.isFinite(c)||(0===n.index?c>e:c<e)))return}}return c}_startDrag(e){if(this._cancelDrag(),"string"!=typeof e.id)return;const t=Kl(e.id),i=t&&this._records.get(t.id);if(!t||!i)return;const s=this._dragAvailability(i,t.index),r=this._dragPrice(e,e.id,s.paneIndex);!s.available||void 0===s.paneIndex||void 0===r||void 0!==e.paneIndex&&e.paneIndex!==s.paneIndex||(this._drag={externalId:e.id,record:i,index:t.index,paneIndex:s.paneIndex,startPrice:r,startY:"number"==typeof e.point?.y?e.point.y:void 0,moved:!1})}_cancelDrag(e){const t=this._drag;if(!t||void 0!==e&&t.record.alert.id!==e)return;this._drag=void 0;const i=this._records.get(t.record.alert.id);i&&this._syncVisual(i)}_onDrag(e,t){this._expireDue();const i=this._drag;if(!i||e.id!==i.externalId)return;const s=this._dragAvailability(i.record,i.index);if(!s.available||s.paneIndex!==i.paneIndex||void 0!==e.paneIndex&&e.paneIndex!==i.paneIndex)return void this._cancelDrag();const r=this._dragPrice(e,i.externalId,i.paneIndex);if(void 0===r)return void(t&&this._cancelDrag());const n=e.point?.y;i.moved||(i.moved=void 0!==i.startY&&"number"==typeof n?n!==i.startY:r!==i.startPrice);const o=i.record.alert.source;if("price"!==o.kind&&"indicator"!==o.kind)return void this._cancelDrag();const a="price"===o.kind?o.price:o.value,l="price"===o.kind?o.upperPrice:o.upperValue,h=0===i.index?Math.min(r,l??1/0):Math.max(r,a);if(!t)return void(i.moved&&this._visuals?.preview(i.externalId,h));if(this._cancelDrag(),!i.moved||h===(0===i.index?a:l))return;const c="price"===o.kind?{...o,...0===i.index?{price:h}:{upperPrice:h}}:{...o,...0===i.index?{value:h}:{upperValue:h}};this.update(i.record.alert.id,{source:c}),this._chart.emit("alerts:changed",{id:i.record.alert.id,reason:"dragged"})}add(e){this._assertAlive();let t=e.id;if(void 0===t)do{t="alert-"+Jl++}while(this._records.has(t));if(this._records.has(t))throw new Error(`Duplicate alert id: ${t}`);const i={...e,id:t,source:{...e.source},condition:e.condition??("barCondition"===e.source.kind?"matches":"crossing"),policy:e.policy??"onBarClose",repeat:e.repeat??"once",state:e.state??"armed",title:e.title??"Chart alert",cooldownSeconds:e.cooldownSeconds??0,scope:Zl(this._chart)};ir(i),i.source=sr(i).source,"armed"===i.state&&void 0!==i.expiresAt&&this._now()>=i.expiresAt&&(i.state="expired");const s={alert:i};return this._seed(s),this._records.set(t,s),this._syncVisual(s),this._scheduleExpiry(),this._saveState(),this._chart.emit("alert:created",{alert:sr(i)}),sr(i)}update(e,t){this._assertAlive();const i=this._records.get(e);if(!i)return;const s={...i.alert,...t,id:e,source:{...t.source??i.alert.source}};ir(s),s.source=sr(s).source,this._cancelDrag(e),"armed"===s.state&&void 0!==s.expiresAt&&this._now()>=s.expiresAt&&(s.state="expired");const r={...i,alert:s};return this._seed(r),this._records.set(e,r),this._syncVisual(r),this._scheduleExpiry(),this._saveState(),this._chart.emit("alert:updated",{alert:sr(s)}),sr(s)}remove(e){return this._remove(e,"removed")}_remove(e,t){const i=this._records.get(e);return!!i&&(this._cancelDrag(e),this._records.delete(e),this._hovered===e&&(this._hovered=void 0),this._visuals?.remove(e),this._scheduleExpiry(),this._saveState(),this._chart.emit("alert:removed",{alert:sr(i.alert),reason:t}),!0)}list(){return[...this._records.values()].map(e=>sr(e.alert))}toJSON(){return ar({version:1,alerts:this.list()})}fromJSON(e){this._assertAlive();const t=ar(e),i=new Map,s=[];for(const e of t.alerts){const t=e.source;let r;"drawing"===t.kind&&this._drawings&&null==this._drawings.get(t.drawingId)&&(r="drawing-missing");const n="indicator"===t.kind?t:"drawing"===t.kind?t.input:void 0;if(!r&&n&&this._chart.indicators){const e=this._chart.indicators().find(e=>e.id===n.instanceId);e?e.series(n.plotKey)||(r="plot-missing"):r="indicator-missing"}if(r){s.push({alert:e,reason:r});continue}if("armed"===e.state&&void 0!==e.expiresAt&&this._now()>=e.expiresAt&&(e.state="expired"),void 0!==e.lastTriggeredTime){const t="onTouch"===e.policy?"lastTouchedTime":"lastClosedTime";e[t]=Math.max(e[t]??-1/0,e.lastTriggeredTime)}const o={alert:e};this._seed(o),i.set(e.id,o)}this._cancelDrag(),this._revision++,this._visuals?.destroy(),this._hovered=void 0,this._records.clear();for(const[e,t]of i)this._records.set(e,t),this._syncVisual(t);this._scheduleExpiry(),this._saveState();for(const e of s){if(this._destroyed)break;this._chart.emit("alert:removed",{...e,alert:sr(e.alert)})}this._destroyed||this._chart.emit("alerts:restored",{alerts:this.list()})}_saveState(){this._destroyed||this._chart.setAlertState?.({version:1,alerts:this.list()})}availability(e){const t=this._records.get(e);if(!t)return{available:!1,reason:"Alert is unavailable"};if(this._paused||this._replay)return{available:!1,reason:"Alerts are paused"};const i=Zl(this._chart);if(!Ql(t.alert.scope,i))return{available:!1,reason:"Instrument context differs"};if(t.alert.scope.interval!==i.interval)return{available:!1,reason:`Switch to ${t.alert.scope.interval??"the original timeframe"} to evaluate this alert`};const{source:s}=t.alert,r=this._chart.primaryBars();if("drawing"===s.kind){const e=this._drawings?.alertInfo(s.drawingId);if(!e?.available)return{available:!1,reason:e?.reason??"Drawing provider is unavailable"};if(0!==e.paneIndex&&!s.input)return{available:!1,reason:"Select an input plot for this drawing pane"};const i=this._drawingValue(t.alert,r[r.length-1]?.time);return i?{available:!0,paneIndex:i.paneIndex}:{available:!1,reason:"Drawing level, time, input plot or condition is unavailable",paneIndex:e.paneIndex}}if("indicator"===s.kind){const e=this._plot(s);return e.values?Number.isFinite(e.values[r.length-1])?{available:!0,paneIndex:e.paneIndex}:{available:!1,reason:"Plot value is unavailable",paneIndex:e.paneIndex}:{available:!1,reason:e.reason}}return"barCondition"!==s.kind||ql(s.id)?r.length?{available:!0,paneIndex:0}:{available:!1,reason:"Source data is unavailable"}:{available:!1,reason:"Bar condition is unavailable"}}enable(e){return this.update(e,{state:"armed"})}disable(e){return this.update(e,{state:"disabled"})}setPaused(e){this._assertAlive(),this._paused!==e&&(this._paused=e,this._seedAll())}destroy(){if(!this._destroyed){this._destroyed=!0,this._drag=void 0,this._revision++;for(const e of this._off)e();this._clearTimer(),this._visuals?.destroy(),this._hovered=void 0,this._records.clear(),Xl.delete(this._chart)}}_assertAlive(){if(this._destroyed)throw new Error("Alert controller is destroyed")}_seed(e){if(!eh(e.alert.scope,Zl(this._chart)))return e.tail=void 0,e.value=void 0,void(e.plotPane=void 0);const t=this._chart.primaryBars(),i=t[t.length-1];if(e.tail=i?{...i}:void 0,"indicator"===e.alert.source.kind){const i=this._plot(e.alert.source);e.value=this._reading(i.values,t.length-1),e.plotPane=i.paneIndex}else"drawing"===e.alert.source.kind&&e.alert.source.input&&(e.value=this._reading(this._plot(e.alert.source.input).values,t.length-1));const s=t[t.length-2]?.time;void 0!==s&&(e.alert.lastClosedTime=Math.max(e.alert.lastClosedTime??-1/0,s))}_seedAll(){this._cancelDrag(),this._revision++;for(const e of this._records.values())this._seed(e),this._syncVisual(e);this._restoring||(this._saveState(),!this._destroyed&&this._records.size&&this._chart.emit("alerts:checkpoint",{}))}_onObjects(){if(this._destroyed||this._restoring)return;this._cancelDrag();const e=++this._revision;for(const t of[...this._records.values()]){if(this._destroyed||this._revision!==e)break;const i=t.alert.source;"drawing"===i.kind&&this._drawings&&null==this._drawings.get(i.drawingId)?this._remove(t.alert.id,"drawing-removed"):"indicator"!==i.kind&&"drawing"!==i.kind||(this._seed(t),this._syncVisual(t))}}_syncVisual(e){if(!this._visuals)return;const{alert:t}=e,{source:i}=t;if("hide"===this._spentLines&&("triggered"===t.state||"expired"===t.state))return void this._visuals.update(t,void 0,!0);const s=Zl(this._chart),r=eh(t.scope,s);let n;if("price"===i.kind&&Ql(t.scope,s)&&(n={price:i.price,upperPrice:i.upperPrice,paneIndex:0}),r&&("indicator"===i.kind&&void 0!==e.plotPane&&(n={price:i.value,upperPrice:i.upperValue,paneIndex:e.plotPane}),"drawing"===i.kind)){const e=this._chart.primaryBars();n=this._drawingValue(t,e[e.length-1]?.time)}this._visuals.update(t,n,this._paused||this._replay||!r&&"armed"===t.state,r?void 0:t.scope.interval??"original timeframe")}_onData(e){if(this._destroyed||this._restoring)return;const t=++this._revision;if(this._expireDue(),this._drag&&!this._dragAvailability(this._drag.record,this._drag.index).available&&this._cancelDrag(),this._destroyed||t!==this._revision)return;if(this._paused||this._replay)return;if("update"!==e.kind)return void this._seedAll();const i=this._chart.primaryBars(),s=i[i.length-1];if(!s||e.time!==s.time)return;const r=Zl(this._chart);let n=!1;for(const e of[...this._records.values()]){if(this._destroyed||t!==this._revision)break;if(this._records.get(e.alert.id)!==e)continue;if(!eh(e.alert.scope,r))continue;const o=e.tail;if(e.tail={...s},"drawing"===e.alert.source.kind&&o?.time!==s.time&&this._syncVisual(e),this._destroyed||t!==this._revision)break;if("armed"!==e.alert.state||!o)continue;const{alert:a}=e;if("onBarClose"===a.policy){const r=i.length-2,l=i[r];if(s.time<=o.time||!l||l.time!==o.time||void 0!==a.lastClosedTime&&l.time<=a.lastClosedTime)continue;a.lastClosedTime=l.time,n=!0;const h=this._closedMatch(e,i,r);void 0!==h&&t===this._revision&&this._records.get(a.id)===e&&this._trigger(e,l,r,h)}else{if(s.time<o.time||void 0!==a.lastTouchedTime&&s.time<=a.lastTouchedTime)continue;const r=this._touchMatch(e,i,o);void 0!==r&&t===this._revision&&this._records.get(a.id)===e&&(a.lastTouchedTime=s.time,n=!0,this._trigger(e,s,i.length-1,r))}}n&&(this._saveState(),this._destroyed||this._chart.emit("alerts:checkpoint",{}))}_plot(e){const t=this._chart.indicators?.().find(t=>t.id===e.instanceId);if(!t)return{reason:"Indicator instance is unavailable"};if(!t.series(e.plotKey))return{reason:"Indicator plot is unavailable"};const i=t.values()[e.plotKey],s=t.indicatorId&&$i(t.indicatorId)&&Bi(t.indicatorId).plots.some(t=>t.key===e.plotKey&&t.overlay);return i?{values:i,paneIndex:s?0:t.paneIndex}:{reason:"Indicator plot is unavailable"}}_reading(e,t){const i=e?.[t];return"number"==typeof i&&Number.isFinite(i)?i:void 0}_closedMatch(e,t,i){const{source:s,condition:r}=e.alert;if("barCondition"===s.kind)return this._barMatch(e,t,i)?t[i].close:void 0;if("drawing"===s.kind){const n=this._drawingValue(e.alert,t[i].time),o=this._drawingValue(e.alert,t[i-1]?.time),a=s.input?this._plot(s.input).values:void 0,l=s.input?this._reading(a,i):t[i].close,h=s.input?this._reading(a,i-1):t[i-1]?.close;if(!n||void 0===l)return;return Qs(r,o?h:void 0,l,n.price,n.upperPrice,o?.price,o?.upperPrice)?l:void 0}if("price"===s.kind)return Qs(r,t[i-1]?.close,t[i].close,s.price,s.upperPrice)?t[i].close:void 0;const n=this._plot(s).values,o=this._reading(n,i);return void 0!==o&&Qs(r,this._reading(n,i-1),o,s.value,s.upperValue)?o:void 0}_touchMatch(e,t,i){const{source:s,condition:r}=e.alert,n=t.length-1,o=t[n];if("barCondition"===s.kind)return this._barMatch(e,t,n)?o.close:void 0;if("drawing"===s.kind)return this._drawingTouch(e,s,t,i);if("indicator"===s.kind){const t=this._plot(s).values,a=this._reading(t,n),l=o.time>i.time?this._reading(t,n-1):e.value;if(e.value=a,void 0===a||a===l&&o.time===i.time)return;return Qs(r,l,a,s.value,s.upperValue)?a:void 0}const a=o.time>i.time;if(!(a||o.close!==i.close||o.high>i.high||o.low<i.low))return;const l=Math.max(i.close,o.close,a||o.high>i.high?o.high:-1/0),h=Math.min(i.close,o.close,a||o.low<i.low?o.low:1/0);return er(r,i.close,h,l,s.price,s.upperPrice)}_barMatch(e,t,i){const s=e.alert.source;if("barCondition"!==s.kind||e.errorTime===t[i].time)return!1;const r=ql(s.id);if(!r)return!1;try{return!0===r.when({bars:t.slice(0,i+1),index:i})}catch(s){return e.errorTime=t[i].time,this._chart.emit("alert:error",{alert:sr(e.alert),error:s}),!1}}_drawingValue(e,t){const i=e.source;if("drawing"!==i.kind||void 0===t)return;const s=this._drawings?.valueAt(i.drawingId,t,i.level);if(!s||0!==s.paneIndex&&!i.input)return;if(i.input&&this._plot(i.input).paneIndex!==s.paneIndex)return;return("enteringRange"===e.condition||"leavingRange"===e.condition)===(void 0!==s.upperPrice)?s:void 0}_drawingTouch(e,t,i,s){const r=i[i.length-1],n=this._drawingValue(e.alert,r.time),o=this._drawingValue(e.alert,s.time);if(t.input){const a=this._plot(t.input).values,l=this._reading(a,i.length-1),h=r.time>s.time?this._reading(a,i.length-2):e.value;if(e.value=l,!n||void 0===l||l===h&&r.time===s.time)return;return Qs(e.alert.condition,o?h:void 0,l,n.price,n.upperPrice,o?.price,o?.upperPrice)?l:void 0}if(!n||!o)return;const a=r.time>s.time;if(!a&&r.close===s.close&&r.high<=s.high&&r.low>=s.low)return;const l=Math.max(s.close,r.close,a||r.high>s.high?r.high:-1/0),h=Math.min(s.close,r.close,a||r.low<s.low?r.low:1/0);return er(e.alert.condition,s.close,h,l,n.price,n.upperPrice,o.price,o.upperPrice)}_trigger(e,t,i,s){const{alert:r}=e,n=this._now();if(void 0!==r.expiresAt&&n>=r.expiresAt)return void this._expireDue();if(void 0!==r.lastTriggeredAt&&n-r.lastTriggeredAt<r.cooldownSeconds)return;this._cancelDrag(r.id),r.lastTriggeredAt=n,r.lastTriggeredTime=t.time,"once"===r.repeat&&(r.state="triggered"),this._syncVisual(e),this._scheduleExpiry(),this._saveState();const o={alertId:r.id,title:r.title,message:r.message,time:t.time,index:i,price:s,alert:sr(r)};this._chart.emit("alert:triggered",o)}_expireDue(){const e=this._now(),t=[];for(const i of this._records.values()){const{alert:s}=i;"armed"===s.state&&void 0!==s.expiresAt&&e>=s.expiresAt&&(this._cancelDrag(s.id),s.state="expired",this._syncVisual(i),t.push(i))}this._scheduleExpiry(),t.length&&this._saveState();for(const e of t){if(this._destroyed)break;this._records.get(e.alert.id)===e&&this._chart.emit("alert:expired",{alert:sr(e.alert)})}}_clearTimer(){void 0!==this._timer&&clearTimeout(this._timer),this._timer=void 0,this._timerAt=void 0}_scheduleExpiry(){if(this._destroyed)return;let e;for(const{alert:t}of this._records.values())"armed"===t.state&&void 0!==t.expiresAt&&(e=Math.min(e??1/0,t.expiresAt));e!==this._timerAt&&(this._clearTimer(),void 0!==e&&(this._timerAt=e,this._timer=setTimeout(()=>{this._timer=void 0,this._timerAt=void 0,this._destroyed||this._expireDue()},Math.max(1,Math.min(2147483647,1e3*(e-this._now())))),this._timer.unref?.()))}}const ih={crossing:"Crossing",crossingUp:"Crossing up",crossingDown:"Crossing down",greaterThan:"Above",lessThan:"Below",enteringRange:"Entering range",leavingRange:"Leaving range",matches:"Matches"},sh=["crossing","crossingUp","crossingDown","greaterThan","lessThan"],rh=["enteringRange","leavingRange"];function nh(e,t){const i="barCondition"===e.kind?["matches"]:"drawing"===e.kind?"band"===e.level?rh:sh:[...sh,...rh],s=t&&i.includes(t)?t:i[0],r=rh.includes(s),n=[{key:"title",type:"text",label:"Name",default:"Chart alert"},{key:"condition",type:"select",label:"Condition",default:s,options:i.map(e=>({value:e,label:ih[e]}))}];if("price"===e.kind||"indicator"===e.kind){const t="price"===e.kind;n.push({key:t?"price":"value",type:"number",label:r?"Lower bound":"Threshold",default:t?e.price:e.value,step:.01}),r&&n.push({key:t?"upperPrice":"upperValue",type:"number",label:"Upper bound",default:t?e.upperPrice??e.price:e.upperValue??e.value,step:.01})}return n.push({key:"policy",type:"select",label:"Evaluate",default:"onBarClose",options:[{value:"onBarClose",label:"Bar close"},{value:"onTouch",label:"Intrabar touch"}]},{key:"repeat",type:"select",label:"Repeat",default:"once",options:[{value:"once",label:"Once"},{value:"everyTime",label:"Every match"}]},{key:"cooldownSeconds",type:"number",label:"Cooldown (seconds)",default:0,min:0,step:1},{key:"expiresAt",type:"text",label:"Expires",default:"",tooltip:"Leave empty for no expiry."},{key:"message",type:"text",label:"Message",default:""},{key:"enabled",type:"boolean",label:"Enabled",default:!0}),n}export{Rr as ALT_PRESET,th as AlertController,Al as BAR_CACHE_VERSION,zr as BUILTIN_COMMANDS,Nl as BarCache,fa as BuySellButtons,lr as CHART_STATE_VERSION,ra as CandleBuilder,Xt as Canvas2dBackend,zn as Chart,so as ChartObjects,_n as ChartTable,$n as ComparisonController,sa as DEFAULT_CANDLE_BUILDER_OPTIONS,z as DEFAULT_CANDLE_STYLE,nn as DEFAULT_CHART_TABLE_OPTIONS,ee as DEFAULT_HISTOGRAM_STYLE,Lr as DEFAULT_KEYMAP,b as DEFAULT_PRICE_SCALE_OPTIONS,ti as DEFAULT_THEME,Me as DEFAULT_TIMEZONE,mn as DEFAULT_TIME_NAVIGATOR_OPTIONS,y as DEFAULT_TIME_SCALE_OPTIONS,Br as DEFAULT_TRADING_COLORS,gr as DEFAULT_ZOOM_GLIDE_OPTIONS,Ya as DataLoadingController,tn as EventMarkers,Cl as FakeDataFeed,Da as HistoryRequestPool,Ai as INDICATOR_LINE_STYLES,zi as INDICATOR_PLOT_STYLES,Fi as INDICATOR_SOURCES,fe as IST_OFFSET_SECONDS,us as IndicatorBackground,ds as IndicatorDrawings,as as IndicatorFill,Ci as IndicatorInputError,La as Instrument,i as InvalidationLevel,Ko as LINK_CROSSHAIR_ALPHA,Yo as LinkCrosshair,ta as LinkGroup,Sn as LogoWatermark,Za as OpenAlgoDataFeed,Ml as OpenAlgoLiveDataFeed,pl as OpenAlgoTradeFeed,cl as OpenAlgoWsFeed,na as PRICE_LEVEL_KINDS,Ln as PRICE_SCALE_MODES,Zt as Pane,Wt as PaneLegend,pa as PriceLevels,Er as PriceLine,v as PriceScale,$o as ReplayController,Uo as ReplayGroup,_a as ReplayShade,A as SCALE_FONT_MAX,j as SCALE_FONT_MIN,ns as SeriesMarkers,Nr as ShortcutManager,ci as SvgContext,ii as SvgLinearGradient,On as TextWatermark,kl as TickBarAggregator,bn as TimeNavigator,w as TimeScale,Hr as TradeMarkersPrimitive,za as TradingCapabilityError,Gr as TradingController,ps as UnknownIntervalError,e as VERSION,vr as ZoomGlide,qn as addComparison,nh as alertSettingsSchema,Bn as alignToPrimary,Ro as applyChartSettings,Fa as assertTradingCapability,wa as atr,g as autoscaleRange,qt as backendDegradation,ll as backoffDelayMs,Rl as barCacheKey,Ll as barCloseSec,Jr as beginPick,At as bestHit,o as bitmapSize,Cs as bucketStartOf,it as calendarPeriodFlags,E as candleGeometry,N as candleTier,Ao as chartSettingsSchema,Ra as checkTradingCapability,h as clamp,ol as classifyAuthAck,Cn as compactVolume,Wn as comparisonController,ha as computePriceLevels,pe as conflateBars,_e as conflateItems,de as conflationGroupSize,Fn as createChart,ia as createLinkGroup,Yt as createRenderBackend,Qt as darkTheme,M as dashPattern,xl as decodeOrder,ss as drawLabel,es as drawShape,Qi as effectiveMarkerPx,ma as ema,ba as emaSeries,me as epochMsToUtcSeconds,Cr as eventToCombo,eo as exportChartDataCsv,no as filterLinkAppearance,Xo as followerIndex,Jo as followerRange,Tr as formatCombo,ke as formatIstCrosshairLabel,Pe as formatIstDate,ye as formatIstTime,we as formatIstTimeSeconds,tl as formatSubscribe,il as formatUnsubscribe,Qe as formatZonedCrosshairLabel,Je as formatZonedDate,Ye as formatZonedTime,Xe as formatZonedTimeSeconds,X as fromGradient,jl as generateBars,ql as getBarCondition,le as getChartType,Bi as getIndicator,$i as hasIndicator,at as inSessionAt,Wi as indicatorDefaults,Ri as indicatorStyleInputs,As as intervalParts,Il as intervalToSeconds,Fs as isDailyInterval,zs as isIntradayInterval,xs as isKnownInterval,Ie as isNewIstDay,Ee as isNewZonedDay,$e as isNewZonedMonth,qe as isNewZonedPeriod,De as isNewZonedQuarter,Be as isNewZonedWeek,We as isNewZonedYear,m as isRebasing,gi as isReplaying,Ar as isReservedCombo,Rs as isSecondsInterval,Ns as isTickInterval,Ps as isTimeBucketed,Ir as isValidCombo,Ae as isValidTimezone,_r as isWhitespace,be as istStringToUtcSeconds,da as lastPriceLevelFromSeriesStyle,c as lerp,ei as lightTheme,Ja as mapHistoryResponse,Sl as mapOrder,wl as mapOrderStatus,Pl as mapPosition,Zi as markerSizePx,ue as mergeBars,js as nextBucketStart,_ as niceTicks,kr as normalizeCombo,F as optimalBarWidth,ar as parseAlertsDocument,Or as parseCombo,hl as parseMessage,pr as parsePaneState,nt as parseSessionSpec,nl as parseTopic,Li as plotStyleKeys,f as precisionForStep,Lo as readChartSettings,al as readSequence,Dl as registerBarCondition,ae as registerChartType,Ei as registerIndicator,gs as registerInterval,Ht as registerRenderBackend,Vl as registeredBarConditions,he as registeredChartTypes,Di as registeredIndicators,ys as registeredIntervals,Ut as registeredRenderBackends,Ct as resolveCrosshairStyle,T as resolveGridStyle,Ss as resolveInterval,R as resolvePlotMargins,Kt as resolveRenderBackend,L as resolveScaleStyle,d as roundToTick,Xa as rowTimeToUtcSeconds,ga as rsi,va as rsiSeries,ua as seriesStyleForLastPriceLevel,lt as sessionFlags,tt as sessionStartFlags,et as sessionStartIndices,qa as sharedHistoryRequests,a as snapToDevicePixel,qi as sourceValue,Vi as sourceValues,Ge as startOfZonedDay,Ke as startOfZonedMonth,Ue as startOfZonedWeek,xa as supertrend,Sa as supertrendSeries,un as tableOrigin,fr as toBar,ya as trueRange,ws as tryResolveInterval,Wl as unregisterBarCondition,vs as unregisterInterval,Gt as unregisterRenderBackend,xe as utcSecondsToIstDateString,ge as utcSecondsToIstParts,Ze as utcSecondsToZonedDateString,Re as utcSecondsToZonedParts,t as version,Y as verticalGradient,xn as watermarkRect,V as withAlpha,El as withBarCache,Ne as zoneOffsetSeconds,ze as zonedDayIndex,Ve as zonedStringToUtcSeconds,He as zonedWallClockToUtcSeconds,Fe as zonedWeekIndex};
|
|
2
2
|
//# sourceMappingURL=openalgo-charts.mjs.map
|