diff --git a/README.md b/README.md index 2233478d..337c91e3 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,16 @@
# lightweight-charts-python +## Installation + +```bash +pip install lightweight-charts-esistjosh + + +## Installation +``` +pip install lightweight-charts-esistjosh +``` ## Forked to Add Features ![Cover Image](https://raw.githubusercontent.com/EsIstJosh/lightweight-charts-python/main/Screenshot2025-02-07114921.png) @@ -133,12 +143,12 @@ For full details, refer to the [MIT License](./MIT_LICENSE). ## Installation ```bash -pip install lightweight-charts +pip install lightweight-charts-esistjosh ## Installation ``` -pip install lightweight-charts +pip install lightweight-charts-esistjosh ``` ___ diff --git a/lightweight_charts_esistjosh/abstract.py b/lightweight_charts_esistjosh/abstract.py index 5f3bc428..4f232d5b 100644 --- a/lightweight_charts_esistjosh/abstract.py +++ b/lightweight_charts_esistjosh/abstract.py @@ -1193,7 +1193,7 @@ class AbstractChart(Candlestick, Pane): def __init__(self, window: Window, width: float = 1.0, height: float = 1.0, scale_candles_only: bool = False, toolbox: bool = False, autosize: bool = True, position: FLOAT = 'left', - defaults: str = '../../src/general/defaults', scripts: str = '../../src/general/scripts'): + defaults: str = '../defaults', scripts: str = '../scripts'): Pane.__init__(self, window) Candlestick.__init__(self, self) self._lines = [] @@ -1216,11 +1216,11 @@ def __init__(self, window: Window, width: float = 1.0, height: float = 1.0, self.toolbox: ToolBox = ToolBox(self) # Set and initialize defaults directory - self.defaults = defaults or './defaults' + self.defaults = defaults or '../defaults' if not os.path.exists(self.defaults): os.makedirs(self.defaults, exist_ok=True) - if os.path.exists('../../src/general/defaults'): - shutil.copytree('../../src/general/defaults', self.defaults, dirs_exist_ok=True) + if os.path.exists('../defaults'): + shutil.copytree('../defaults', self.defaults, dirs_exist_ok=True) self.set_defaults(self.defaults) # Handlers for defaults @@ -1228,11 +1228,11 @@ def __init__(self, window: Window, width: float = 1.0, height: float = 1.0, self.events.save_defaults += self._save_defaults # Set and initialize scripts directory - self.scripts = scripts or './scripts' + self.scripts = scripts or '../scripts' if not os.path.exists(self.scripts): os.makedirs(self.scripts, exist_ok=True) - if os.path.exists('../../src/general/scripts'): - shutil.copytree('../../src/general/scripts', self.scripts, dirs_exist_ok=True) + if os.path.exists('../scripts'): + shutil.copytree('../scripts', self.scripts, dirs_exist_ok=True) self.set_scripts(self.scripts) # Handlers for scripts diff --git a/defaults/area.json b/lightweight_charts_esistjosh/defaults/area.json similarity index 100% rename from defaults/area.json rename to lightweight_charts_esistjosh/defaults/area.json diff --git a/defaults/bar.json b/lightweight_charts_esistjosh/defaults/bar.json similarity index 100% rename from defaults/bar.json rename to lightweight_charts_esistjosh/defaults/bar.json diff --git a/defaults/candlestick.json b/lightweight_charts_esistjosh/defaults/candlestick.json similarity index 100% rename from defaults/candlestick.json rename to lightweight_charts_esistjosh/defaults/candlestick.json diff --git a/defaults/chart.json b/lightweight_charts_esistjosh/defaults/chart.json similarity index 100% rename from defaults/chart.json rename to lightweight_charts_esistjosh/defaults/chart.json diff --git a/defaults/histogram.json b/lightweight_charts_esistjosh/defaults/histogram.json similarity index 100% rename from defaults/histogram.json rename to lightweight_charts_esistjosh/defaults/histogram.json diff --git a/defaults/line.json b/lightweight_charts_esistjosh/defaults/line.json similarity index 100% rename from defaults/line.json rename to lightweight_charts_esistjosh/defaults/line.json diff --git a/defaults/ohlc.json b/lightweight_charts_esistjosh/defaults/ohlc.json similarity index 100% rename from defaults/ohlc.json rename to lightweight_charts_esistjosh/defaults/ohlc.json diff --git a/defaults/pitchfork.json b/lightweight_charts_esistjosh/defaults/pitchfork.json similarity index 100% rename from defaults/pitchfork.json rename to lightweight_charts_esistjosh/defaults/pitchfork.json diff --git a/defaults/trend-trace.json b/lightweight_charts_esistjosh/defaults/trend-trace.json similarity index 100% rename from defaults/trend-trace.json rename to lightweight_charts_esistjosh/defaults/trend-trace.json diff --git a/defaults/volume-profile.json b/lightweight_charts_esistjosh/defaults/volume-profile.json similarity index 100% rename from defaults/volume-profile.json rename to lightweight_charts_esistjosh/defaults/volume-profile.json diff --git a/lightweight_charts_esistjosh/js/.old b/lightweight_charts_esistjosh/js/.old new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/lightweight_charts_esistjosh/js/.old @@ -0,0 +1 @@ + diff --git a/lightweight_charts_esistjosh/js/bundle.js b/lightweight_charts_esistjosh/js/bundle.js index 4acc766d..a2f82142 100644 --- a/lightweight_charts_esistjosh/js/bundle.js +++ b/lightweight_charts_esistjosh/js/bundle.js @@ -1,3 +1,3 @@ -var Lib=function(e,t,i){"use strict";function s(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var s=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var n,o=s(i);function r(e){if(void 0===e)throw new Error("Value is undefined");return e}class a{_chart=void 0;_series=void 0;requestUpdate(){this._requestUpdate&&this._requestUpdate()}_requestUpdate;attached({chart:e,series:t,requestUpdate:i}){this._chart=e,this._series=t,this._series.subscribeDataChanged(this._fireDataUpdated),this._requestUpdate=i,this.requestUpdate()}detached(){this._chart=void 0,this._series=void 0,this._requestUpdate=void 0}get chart(){return r(this._chart)}get series(){return r(this._series)}_fireDataUpdated(e){this.dataUpdated&&this.dataUpdated(e)}toJSON(){return{}}fromJSON(e){}}function l(e,t){if(e.startsWith("#"))return function(e,t){if(e=e.replace(/^#/,""),!/^([0-9A-F]{3}){1,2}$/i.test(e))throw new Error("Invalid hex color format.");const[i,s,n]=3===(o=e).length?[parseInt(o[0]+o[0],16),parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16)]:[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)];var o;return`rgba(${i}, ${s}, ${n}, ${t})`}(e,t);{const i=/^rgb(a)?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:,\s*([\d.]+))?\)/i,s=e.match(i);if(s){const e=s[2],i=s[3],n=s[4],o=s[1]?s[5]??"1":"1";return`rgba(${e}, ${i}, ${n}, ${t??o})`}throw new Error("Unsupported color format. Use hex, rgb, or rgba.")}}function c(e,t=.2){let[i,s,n,o=1]=e.startsWith("#")?[...(r=e,3===(r=r.replace(/^#/,"")).length?[parseInt(r[0]+r[0],16),parseInt(r[1]+r[1],16),parseInt(r[2]+r[2],16)]:[parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.slice(4,6),16)]),1]:e.match(/\d+(\.\d+)?/g).map(Number);var r;return i=Math.max(0,Math.min(255,i*(1-t))),s=Math.max(0,Math.min(255,s*(1-t))),n=Math.max(0,Math.min(255,n*(1-t))),e.startsWith("#")?`#${((1<<24)+(Math.round(i)<<16)+(Math.round(s)<<8)+Math.round(n)).toString(16).slice(1)}`:`rgba(${Math.round(i)}, ${Math.round(s)}, ${Math.round(n)}, ${o})`}function h(e,t,i=""){for(const s of Object.keys(e)){const n=i?`${i}.${s}`:s,o=e[s];"object"==typeof o&&null!==o?h(o,t,n):s.toLowerCase().includes("color")&&t(n,o)}}function p(e){if(e.length>100)return 1;let t=1;const i=/^rgba\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*(\d?\.?\d+)\s*$/i.exec(e),s=/^hsla\s*\d{1,3}(?:\.\d+)?\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*,\s*(\d?\.?\d+)\s*$/i.exec(e);return i?t=parseFloat(i[1]):s&&(t=parseFloat(s[1])),isNaN(t)?1:Math.max(0,Math.min(1,t))}class d{numbers;cache;constructor(e){this.numbers=e,this.cache=new Map}findClosestIndex(e,t){const i=`${e}:${t}`;if(this.cache.has(i))return this.cache.get(i);const s=this._performSearch(e,t);return this.cache.set(i,s),s}_performSearch(e,t){let i=0,s=this.numbers.length-1;if(e<=this.numbers[0].time)return 0;if(e>=this.numbers[s].time)return s;for(;i<=s;){const t=Math.floor((i+s)/2),n=this.numbers[t].time;if(n===e)return t;n>e?s=t-1:i=t+1}return"left"===t?i:s}}function u(e){switch(e.trim().toLowerCase()){case"rectangle":return n.Rectangle;case"rounded":return n.Rounded;case"ellipse":return n.Ellipse;case"arrow":return n.Arrow;case"3d":return n.Cube;case"polygon":return n.Polygon;case"bar":return n.Bar;case"slanted":return n.Slanted;default:return console.warn(`Unknown CandleShape: ${e}`),n.Rectangle}}function m(e){return e.type===t.ColorType.Solid}function g(e){return e.type===t.ColorType.VerticalGradient}function f(e){return"value"in e}function y(e){return"close"in e&&"open"in e&&"high"in e&&"low"in e}function b(e){return!(!e||"object"!=typeof e)&&("time"in e&&!("value"in e||"open"in e||"close"in e||"high"in e||"low"in e))}function v(e){const t=e.options();return"lineColor"in t||"color"in t}function x(e){return"object"==typeof e&&null!==e&&"function"==typeof e.data&&"function"==typeof e.options}!function(e){e.Rectangle="Rectangle",e.Rounded="Rounded",e.Ellipse="Ellipse",e.Arrow="Arrow",e.Cube="3d",e.Polygon="Polygon",e.Bar="Bar",e.Slanted="Slanted"}(n||(n={}));class _ extends a{static type="Fill Area";_paneViews;_originSeries;_destinationSeries;_bandsData=[];options;_timeIndices;constructor(e,t,i){super();const s=l("#0000FF",.25),n=l("#FF0000",.25),o=v(e)?l(e.options().color||s,.3):l(s,.3),r=v(t)?l(t.options().color||n,.3):l(n,.3);this.options={...S,...i,originColor:i.originColor??o,destinationColor:i.destinationColor??r},this._paneViews=[new C(this)],this._timeIndices=new d([]),this._originSeries=e,this._destinationSeries=t,this._originSeries.subscribeDataChanged((()=>{console.log("Origin series data has changed. Recalculating bands."),this.dataUpdated("full"),this.updateAllViews()})),this._destinationSeries.subscribeDataChanged((()=>{console.log("Destination series data has changed. Recalculating bands."),this.dataUpdated("full"),this.updateAllViews()}))}updateAllViews(){this._paneViews.forEach((e=>e.update()))}applyOptions(e){this.options={...this.options,...e},this.calculateBands(),this.updateAllViews(),super.requestUpdate(),console.log("FillArea options updated:",this.options)}paneViews(){return this._paneViews}attached(e){super.attached(e),this.dataUpdated("full")}dataUpdated(e){if(this.calculateBands(),"full"===e){const e=this._originSeries.data();this._timeIndices=new d([...e])}}calculateBands(){const e=this._originSeries.data(),t=this._destinationSeries.data(),i=this._alignDataLengths([...e],[...t]),s=[];for(let e=0;es){const e=t[s-1];for(;t.lengthi){const t=e[i-1];for(;e.lengthe.lower)).slice(o,r+1)),maxValue:Math.max(...this._bandsData.map((e=>e.upper)).slice(o,r+1))};return{priceRange:{minValue:a.minValue,maxValue:a.maxValue}}}}class w{_viewData;_options;constructor(e){this._viewData=e,this._options=e.options}draw(){}drawBackground(e){const t=this._viewData.data,i=this._options;t.length<2||e.useBitmapCoordinateSpace((e=>{const s=e.context;s.scale(e.horizontalPixelRatio,e.verticalPixelRatio);let n=!1,o=0;for(let e=0;e=o;i--)s.lineTo(t[i].x,t[i].destination);s.closePath(),s.fill()}s.beginPath(),s.moveTo(r.x,r.origin),s.fillStyle=r.isOriginAbove?i.originColor||"rgba(0, 0, 0, 0)":i.destinationColor||"rgba(0, 0, 0, 0)",o=e,n=!0}if(s.lineTo(a.x,a.origin),e===t.length-2||a.isOriginAbove!==r.isOriginAbove){for(let i=e+1;i>=o;i--)s.lineTo(t[i].x,t[i].destination);s.closePath(),s.fill(),n=!1}}i.lineWidth&&(s.lineWidth=i.lineWidth,s.strokeStyle=i.originColor||"rgba(0, 0, 0, 0)",s.stroke())}))}}class C{_source;_data;constructor(e){this._source=e,this._data={data:[],options:this._source.options}}update(){const e=this._source.chart.timeScale();this._data.data=this._source._bandsData.map((t=>({x:e.timeToCoordinate(t.time),origin:this._source._originSeries.priceToCoordinate(t.origin),destination:this._source._destinationSeries.priceToCoordinate(t.destination),isOriginAbove:t.origin>t.destination}))),this._data.options=this._source.options}renderer(){return new w(this._data)}zOrder(){return"bottom"}}const S={originColor:null,destinationColor:null,lineWidth:null};function k(e,t){let i,s;if(void 0!==e.close){i=e.close}else void 0!==e.value&&(i=e.value);if(void 0!==t.close){s=t.close}else void 0!==t.value&&(s=t.value);if(void 0!==i&&void 0!==s){if(i{e&&(window.cursor=e),document.body.style.cursor=window.cursor},window.cursor="default",window.textBoxFocused=!1}const P='\n\n \n \n\n',T='\n\n \n \n \n\n';class I{contextMenu;handler;constructor(e){this.contextMenu=e.contextMenu,this.handler=e.handler}populateLegendMenu(e,t){this.contextMenu.clearMenu();void 0!==e.seriesList?this.populateGroupMenu(e,t):this.populateSeriesMenu(e,t),this.contextMenu.separator(),this.contextMenu.addMenuItem("Close Menu",(()=>this.contextMenu.hideMenu())),this.contextMenu.showMenu(t)}populateGroupMenu(e,t){if(this.contextMenu.addMenuItem("Rename",(()=>{const t=prompt("Enter new group name:",e.name);t&&""!==t.trim()&&this.renameGroup(e,t.trim())}),!1),this.contextMenu.addMenuItem("Remove",(()=>{confirm(`Are you sure you want to remove the group "${e.name}"? This will also remove all contained series.`)&&(e.seriesList.forEach((e=>{this.handler.legend.removeLegendSeries(e.series),this.handler.removeSeries(e.series)})),this.removeGroup(e))})),this.contextMenu.addMenuItem("Ungroup",(()=>{this.ungroupSeries(e)})),e.seriesList&&e.seriesList.length>0){const t=e.seriesList[0].series.getPane().paneIndex(),i=this.handler.chart.panes(),s=`Pane ${t}`,n=()=>{0===t?i.length>1?(e.seriesList.forEach((e=>{e.series.moveToPane(1)})),console.log(`Default: Moved group "${e.name}" series from pane ${t} to pane 1.`)):(e.seriesList.forEach((e=>{e.series.moveToPane(i.length)})),console.log(`Default: Moved group "${e.name}" series from pane ${t} to a new pane at index ${i.length}.`)):(e.seriesList.forEach((e=>{e.series.moveToPane(0)})),console.log(`Default: Moved group "${e.name}" series from pane ${t} back to main pane (0).`))},o=[];for(let t=0;t{e.seriesList.forEach((e=>{e.series.moveToPane(t)})),console.log(`Moved group "${e.name}" series to existing pane ${t}.`)}});o.push({name:"New Pane",action:()=>{e.seriesList.forEach((e=>{e.series.moveToPane(i.length)})),console.log(`Moved group "${e.name}" series to a new pane at index ${i.length}.`)}}),this.contextMenu.addMenuInput(this.contextMenu.div,{type:"hybrid",label:"Move to",sublabel:s,value:s,onChange:e=>{const t=o.find((t=>t.name===e));t&&t.action()},hybridConfig:{defaultAction:n,options:o.map((e=>({name:e.name,action:e.action})))}})}this.contextMenu.showMenu(t)}populateSeriesMenu(e,t){this.contextMenu.addMenuItem("Open Series Menu",(()=>{this.contextMenu.populateSeriesMenu(e.series,t)}),!1),this.contextMenu.addMenuItem("Move to Group ▸",(()=>{this.populateMoveToGroupMenu(e)}),!1),this.contextMenu.addMenuItem("Remove Series",(()=>{confirm(`Are you sure you want to remove the series "${e.name}"?`)&&(this.handler.legend.removeLegendSeries(e.series),this.handler.removeSeries(e.series))})),e.primitives&&this.contextMenu.addMenuItem("Remove Primitives",(()=>{this.removePrimitivesFromSeries(e)})),e.group&&this.contextMenu.addMenuItem("Ungroup",(()=>{this.ungroupSeriesFromGroup(e)})),this.contextMenu.showMenu(t)}populateMoveToGroupMenu(e){this.contextMenu.clearMenu();this.handler.legend._groups.forEach((t=>{this.contextMenu.addMenuItem(t.name,(()=>{this.handler.legend.moveSeriesToGroup(e,t)}))})),this.contextMenu.addMenuItem("Create New Group...",(()=>{const t=prompt("Enter new group name:","New Group");t&&""!==t.trim()&&this.createNewGroup(e,t.trim())})),e.group&&this.contextMenu.addMenuItem("Ungroup",(()=>{this.ungroupSeriesFromGroup(e)}))}renameGroup(e,t){e.name=t,e.seriesList.forEach((e=>{e.group=t}));const i=e.row.querySelector(".group-header span");i&&(i.textContent=t),console.log(`Group renamed to: ${t}`)}removeGroup(e){this.handler.legend.removeLegendGroup(e),this.handler.legend._groups=this.handler.legend._groups.filter((t=>t!==e)),console.log(`Group "${e.name}" removed along with its series.`)}createNewGroup(e,t){this.handler.legend.deleteLegendEntry(e),e.group=t,this.handler.legend.addLegendItem(e)}ungroupSeriesFromGroup(e){this.handler.legend.getGroupOfSeries(e.series)&&(this.handler.legend.deleteLegendEntry(e),e.group=void 0,this.handler.legend.addLegendItem(e)),console.log(`Series "${e.name}" removed from its group and is now standalone.`)}removePrimitivesFromSeries(e){e.series.primitives&&(Object.values(e.series.primitives).forEach((t=>{e.series.detachPrimitive(t),console.log(`Primitive removed from series "${e.name}".`)})),e.primitives=void 0),console.log(`All primitives removed from series "${e.name}".`)}ungroupSeries(e){e.seriesList.forEach((e=>{this.handler.legend.deleteLegendEntry(e),e.group=void 0,this.handler.legend.addLegendItem(e)})),this.removeGroup(e),console.log(`All series in group "${e.name}" have been ungrouped and are now standalone.`)}}function A(e){return e.data()[e.data().length-1]}class D{handler;div;seriesContainer;legendMenu;linesEnabled=!1;contextMenu;text;_items=[];_lines=[];_groups=[];constructor(e){this.handler=e,this.div=document.createElement("div"),this.div.classList.add("legend"),this.seriesContainer=document.createElement("div"),this.text=document.createElement("span"),this.contextMenu=this.handler.ContextMenu,this.legendMenu=new I({contextMenu:this.contextMenu,handler:e}),this.setupLegend(),this.legendHandler=this.legendHandler.bind(this),e.chart.subscribeCrosshairMove(this.legendHandler)}setupLegend(){this.div.style.maxWidth=100*this.handler.scale.width-8+"vw",this.div.style.display="none";const e=document.createElement("div");e.style.display="flex",e.style.flexDirection="row",this.seriesContainer.classList.add("series-container"),this.text.style.lineHeight="1.8",e.appendChild(this.seriesContainer),this.div.appendChild(this.text),this.div.appendChild(e),this.handler.div.appendChild(this.div)}legendItemFormat(e,t){return"number"!=typeof e||isNaN(e)?"-":e.toFixed(t).toString().padStart(8," ")}shorthandFormat(e){const t=Math.abs(e);return t>=1e6?(e/1e6).toFixed(1)+"M":t>=1e3?(e/1e3).toFixed(1)+"K":e.toString().padStart(8," ")}createSvgIcon(e){const t=document.createElement("div");t.innerHTML=e.trim();return t.querySelector("svg")}addLegendItem(e){const t=this.mapToSeries(e);if(t.group)return this.addItemToGroup(t,t.group);{const e=this.makeSeriesRow(t,this.seriesContainer);return this._lines.push(t),this._items.push(t),e}}addLegendPrimitive(e,t,i){const s=i||t.constructor.name,n=this._lines.find((t=>t.series===e));if(!n)return void console.warn(`Parent series not found in legend for primitive: ${s}`);n.primitives||(n.primitives=[]);let o=this.seriesContainer.querySelector(`[data-series-id="${n.name}"] .primitives-container`);o||(o=document.createElement("div"),o.classList.add("primitives-container"),o.style.display="none",o.style.marginLeft="20px",o.style.flexDirection="column",n.row.insertAdjacentElement("afterend",o));const r=Array.from(o.children).find((e=>e.getAttribute("data-primitive-type")===s));if(r)return console.warn(`Primitive "${s}" already exists under the parent series.`),r;const a=document.createElement("div");a.classList.add("legend-primitive-row"),a.setAttribute("data-primitive-type",s),a.style.display="flex",a.style.justifyContent="space-between",a.style.marginTop="4px";const l=document.createElement("span");l.innerText=s;const c=document.createElement("div");c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center";const h=this.createSvgIcon(P),p=this.createSvgIcon(T);c.appendChild(h.cloneNode(!0));let d=!0;c.addEventListener("click",(()=>{d=!d,c.innerHTML="",c.appendChild(d?h.cloneNode(!0):p.cloneNode(!0)),this.togglePrimitive(t,d)})),a.appendChild(l),a.appendChild(c),o.appendChild(a),o.children.length>0&&(o.style.display="block");const u={name:s,primitive:t,row:a};return this._items.push(u),n.primitives.push(u),a}togglePrimitive(e,t){const i=e.options||e._options;if(!i)return void console.warn("Primitive has no options to update.");const s={};if("visible"in i)return s.visible=t,console.log(`Toggling visible option for primitive: ${e.constructor.name} to ${t}`),void e.applyOptions(s);const n="_originalColors";e[n]||(e[n]={});const o=e[n];for(const e of Object.keys(i))e.toLowerCase().includes("color")&&(t?s[e]=o[e]||i[e]:(o[e]||(o[e]=i[e]),s[e]="rgba(0,0,0,0)"));Object.keys(s).length>0&&(console.log(`Updating visibility for primitive: ${e.constructor.name}`),e.applyOptions(s),t&&delete e[n])}findLegendPrimitive(e,t){const i=this._lines.find((t=>t.series===e));if(!i||!i.primitives)return null;return i.primitives.find((e=>e.primitive===t))||null}mapToSeries(e){return{name:e.name,series:e.series,group:e.group||void 0,legendSymbol:e.legendSymbol||[],colors:e.colors||["#000"],seriesType:e.seriesType||"Line",div:document.createElement("div"),row:document.createElement("div"),toggle:document.createElement("div"),extraData:e.extraData||null}}addItemToGroup(e,t){let i=this._groups.find((e=>e.name===t));return i?(i.seriesList.push(e),this.makeSeriesRow(e,i.div),i.row):this.makeSeriesGroup(t,[e])}makeSeriesGroup(e,t){let i=this._groups.find((t=>t.name===e));if(i)return i.seriesList.push(...t),t.forEach((e=>this.makeSeriesRow(e,i.div))),i.row;{const i={name:e,seriesList:t,subGroups:[],div:document.createElement("div"),row:document.createElement("div"),toggle:document.createElement("div")};return this._groups.push(i),this.renderGroup(i,this.seriesContainer),i.row}}makeSeriesRow(e,t){const i=document.createElement("div");i.classList.add("legend-series-row"),i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="space-between",i.style.marginBottom="4px";const s=document.createElement("button");s.classList.add("legend-action-button"),s.innerHTML="◇",s.title="Series Actions",s.style.marginRight="0px",s.style.fontSize="1em",s.style.border="none",s.style.background="none",s.style.cursor="pointer",s.style.color="#ffffff",s.addEventListener("click",(t=>{t.stopPropagation(),t.preventDefault(),"◇"===s.innerHTML?s.innerHTML="◈":s.innerHTML="◇",this.legendMenu.populateLegendMenu(e,t)}));const n=document.createElement("div");n.classList.add("series-info"),n.style.flex="1";if(["Bar","Candlestick","Ohlc"].includes(e.seriesType||"")){const t="-",i="-",s=e.legendSymbol[0]||"▨",o=e.legendSymbol[1]||s,r=e.colors[0]||"#00FF00",a=e.colors[1]||"#FF0000";n.innerHTML=`\n ${s}\n ${o}\n ${e.name}: O ${t}, \n C ${i}\n `}else n.innerHTML=e.legendSymbol.map(((t,i)=>`${t}`)).join(" ")+` ${e.name}`;const o=document.createElement("div");o.classList.add("legend-toggle-switch"),o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center";const r=this.createSvgIcon(P),a=this.createSvgIcon(T);o.appendChild(r.cloneNode(!0));let l=!0;o.addEventListener("click",(t=>{l=!l,e.series.applyOptions({visible:l}),o.innerHTML="",o.appendChild(l?r.cloneNode(!0):a.cloneNode(!0)),o.setAttribute("aria-pressed",l.toString()),o.classList.toggle("inactive",!l),t.stopPropagation()})),o.setAttribute("role","button"),o.setAttribute("aria-label",`Toggle visibility for ${e.name}`),o.setAttribute("aria-pressed",l.toString()),i.appendChild(s),i.appendChild(n),i.appendChild(o),t.appendChild(i),i.addEventListener("contextmenu",(t=>{t.preventDefault(),this.legendMenu.populateLegendMenu(e,t)}));const c={...e,div:n,row:i,toggle:o};return this._lines.push(c),this._items.push(c),i}isLegendPrimitive(e){return void 0!==e.primitive&&void 0!==e.row}deleteLegendEntry(e,t){if(t&&!e){const e=this._groups.findIndex((e=>e.name===t));if(-1!==e){const i=this._groups[e];this.seriesContainer.removeChild(i.row),this._groups.splice(e,1),this._items=this._items.filter((e=>e!==i)),console.log(`Group "${t}" removed.`)}else console.warn(`Legend group with name "${t}" not found.`)}else if(e){let i=!1;if(t){const s=this._groups.find((e=>e.name===t));if(s){const n=s.seriesList.findIndex((t=>t.name===e));-1!==n&&(s.seriesList.splice(n,1),0===s.seriesList.length?(this.seriesContainer.removeChild(s.row),this._groups=this._groups.filter((e=>e!==s)),this._items=this._items.filter((e=>e!==s)),console.log(`Group "${t}" is empty and has been removed.`)):this.renderGroup(s,this.seriesContainer),i=!0,console.log(`Series "${e}" removed from group "${t}".`))}else console.warn(`Legend group with name "${t}" not found.`)}if(!i){const t=this._lines.findIndex((t=>t.name===e));if(-1!==t){const s=this._lines[t];this.seriesContainer.removeChild(s.row),this._lines.splice(t,1),this._items=this._items.filter((e=>e!==s)),i=!0,console.log(`Series "${e}" removed.`)}}i||console.warn(`Legend item with name "${e}" not found.`)}else console.warn("No seriesName or groupName provided for deletion.")}removeLegendGroup(e){this.seriesContainer.contains(e.row)&&this.seriesContainer.removeChild(e.row);const t=this._groups.indexOf(e);-1!==t&&this._groups.splice(t,1),this._items=this._items.filter((t=>t!==e)),console.log(`Group "${e.name}" removed from legend.`)}findSeriesAnywhere(e){const t=this._lines.find((t=>t.series===e));if(t)return t;for(const t of this._groups){const i=this.findSeriesInGroup(t,e);if(i)return i}}findSeriesInGroup(e,t){const i=e.seriesList.find((e=>e.series===t));if(i)return i;for(const i of e.subGroups){const e=this.findSeriesInGroup(i,t);if(e)return e}}removeSeriesFromGroupDOM(e,t){if(!e.div||!t.row)return console.warn(`⚠️ Cannot remove series "${t.name}" – missing group div or series row.`),!1;if(e.div.contains(t.row))try{return e.div.removeChild(t.row),console.log(`✅ Removed series "${t.name}" from group "${e.name}".`),!0}catch(i){return console.warn(`⚠️ Error removing series "${t.name}" from group "${e.name}":`,i),!1}return e.subGroups.some((e=>this.removeSeriesFromGroupDOM(e,t)))}removeLegendSeries(e){let t;if(t=x(e)?this.findSeriesAnywhere(e):e,t){if(this._lines=this._lines.filter((e=>e!==t)),this._items=this._items.filter((e=>e!==t)),t.group){const e=this.findGroup(t.group);if(e){if(e.seriesList=e.seriesList.filter((e=>e!==t)),t.row&&e.div.contains(t.row))try{e.div.removeChild(t.row),console.log(`✅ Removed "${t.name}" from group "${e.name}".`)}catch(i){console.warn(`⚠️ Error removing "${t.name}" from group "${e.name}":`,i)}0===e.seriesList.length&&this.removeGroupCompletely(e)}}else if(t.row?.parentElement)try{t.row.parentElement.removeChild(t.row),console.log(`✅ Removed row for standalone series: ${t.name}`)}catch(e){console.warn("⚠️ Error removing standalone series row:",e)}}else console.warn("⚠️ LegendSeries not found in legend.")}removeGroupCompletely(e){if(e.row.parentElement)try{e.row.parentElement.removeChild(e.row)}catch(t){console.warn(`Error removing group "${e.name}":`,t)}this._groups=this._groups.filter((t=>t!==e)),this._items=this._items.filter((t=>t!==e)),console.log(`Group "${e.name}" removed as it became empty.`)}removeLegendPrimitive(e){let t;if(t=this.isLegendPrimitive(e)?e:this._items.find((t=>this.isLegendPrimitive(t)&&t.primitive===e)),!t)return void console.warn("❌ LegendPrimitive not found in legend.");t.row&&t.row.parentElement?t.row.parentElement.removeChild(t.row):console.warn("❌ LegendPrimitive row not found in the DOM.");const i=this._lines.find((e=>e.primitives?.includes(t)));if(i&&(i.primitives=i.primitives.filter((e=>e!==t)),console.log(`✅ Removed primitive "${t.name}" from series "${i.name}".`)),this._items=this._items.filter((e=>e!==t)),t.primitive)try{console.log(`Detaching underlying chart primitive for "${t.name}".`),i?.series.detachPrimitive(t.primitive)}catch(e){console.warn(`⚠️ Failed to detach primitive "${t.name}":`,e)}console.log(`✅ LegendPrimitive "${t.name}" removed from legend.`)}getGroupOfSeries(e){for(const t of this._groups){const i=this.findGroupOfSeriesRecursive(t,e);if(i)return i}}findGroupOfSeriesRecursive(e,t){for(const i of e.seriesList)if(i.series===t)return e.name;for(const i of e.subGroups){const e=this.findGroupOfSeriesRecursive(i,t);if(e)return e}}moveSeriesToGroup(e,t){let i=this._lines.findIndex((t=>t.name===e)),s=null;if(-1!==i)s=this._lines[i];else for(const t of this._groups){const i=t.seriesList.findIndex((t=>t.name===e));if(-1!==i){s=t.seriesList[i],t.seriesList.splice(i,1),0===t.seriesList.length?(this.seriesContainer.removeChild(t.row),this._groups=this._groups.filter((e=>e!==t)),this._items=this._items.filter((e=>e!==t)),console.log(`Group "${t.name}" is empty and has been removed.`)):this.renderGroup(t,this.seriesContainer);break}}if(!s)return void console.warn(`Series "${e}" not found in legend.`);-1!==i?(this.seriesContainer.removeChild(s.row),this._lines.splice(i,1),this._items=this._items.filter((e=>e!==s))):this._items=this._items.filter((e=>e!==s));let n=this.findGroup(t);n?(n.seriesList.push(s),this.makeSeriesRow(s,n.div)):(n={name:t,seriesList:[s],subGroups:[],div:document.createElement("div"),row:document.createElement("div"),toggle:document.createElement("div")},this._groups.push(n),this.renderGroup(n,this.seriesContainer)),this._items.push(s),console.log(`Series "${e}" moved to group "${t}".`)}renderGroup(e,t){e.row.innerHTML="",e.row.style.display="flex",e.row.style.flexDirection="column",e.row.style.width="100%";const i=document.createElement("div");i.classList.add("group-header"),i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="space-between",i.style.cursor="pointer";const s=document.createElement("button");s.classList.add("legend-action-button"),s.innerHTML="◇",s.title="Group Actions",s.style.marginRight="0px",s.style.fontSize="1em",s.style.border="none",s.style.background="none",s.style.cursor="pointer",s.style.color="#ffffff",s.addEventListener("click",(t=>{t.stopPropagation(),t.preventDefault(),"◇"===s.innerHTML?s.innerHTML="◈":s.innerHTML="◇",this.legendMenu.populateLegendMenu(e,t)}));const n=document.createElement("span");n.style.fontWeight="bold",n.innerHTML=e.seriesList.map((e=>e.legendSymbol.map(((t,i)=>`${t}`)).join(" "))).join(" ")+` ${e.name}`;const o=document.createElement("span");o.classList.add("toggle-button"),o.style.marginLeft="auto",o.style.fontSize="1.2em",o.style.cursor="pointer",o.innerHTML="⌲",o.setAttribute("aria-expanded","true"),o.addEventListener("click",(t=>{t.stopPropagation(),"none"===e.div.style.display?(e.div.style.display="block",o.innerHTML="⌲",o.setAttribute("aria-expanded","true")):(e.div.style.display="none",o.innerHTML="☰",o.setAttribute("aria-expanded","false"))})),i.appendChild(s),i.appendChild(n),i.appendChild(o),i.addEventListener("contextmenu",(t=>{t.preventDefault(),this.legendMenu.populateLegendMenu(e,t)})),e.row.appendChild(i),e.div=document.createElement("div"),e.div.style.display="block",e.div.style.marginLeft="10px";for(const t of e.seriesList)this.makeSeriesRow(t,e.div);for(const t of e.subGroups){const i=document.createElement("div");i.style.display="flex",i.style.flexDirection="column",i.style.paddingLeft="5px",this.renderGroup(t,i),e.div.appendChild(i)}e.row.appendChild(e.div),t.contains(e.row)||t.appendChild(e.row),e.row.oncontextmenu=e=>{e.preventDefault()}}legendHandler(e,t=!1){this.updateGroupDisplay(e,null,t),this.updateSeriesDisplay(e,null,t)}updateSeriesDisplay(e,t,i){this._lines&&this._lines.length?this._lines.forEach((t=>{const i=e.seriesData.get(t.series)||A(t.series);if(!i)return;const s=t.seriesType||"Line",n=t.series.options().priceFormat;if("Line"===s||"Area"===s||"Histogram"===s||"Symbol"==s){const e=i;if(null==e.value)return;const s=this.legendItemFormat(e.value,n.precision);t.div.innerHTML=`\n ${t.legendSymbol[0]||"▨"} \n ${t.name}: ${s}`}else if("Bar"===s||"Candlestick"===s||"Ohlc"===s){const{open:e,close:s}=i;if(null==e||null==s)return;const o=this.legendItemFormat(e,n.precision),r=this.legendItemFormat(s,n.precision),a=s>e,l=a?t.colors[0]:t.colors[1],c=a?t.legendSymbol[0]:t.legendSymbol[1];t.div.innerHTML=`\n ${c||"▨"}\n ${t.name}: \n O ${o}, \n C ${r}`}})):console.error("No lines available to update legend.")}updateGroupDisplay(e,t,i){this._groups.forEach((t=>{this.linesEnabled?(t.row.style.display="flex",t.seriesList.forEach((t=>{const i=e.seriesData.get(t.series)||A(t.series);if(!i)return;const s=t.seriesType||"Line",n=t.name,o=t.series.options().priceFormat;if(["Bar","Candlestick","Ohlc"].includes(s)){const{open:e,close:s,high:r,low:a}=i;if(null==e||null==s||null==r||null==a)return;const l=this.legendItemFormat(e,o.precision),c=this.legendItemFormat(s,o.precision),h=s>e,p=h?t.colors[0]:t.colors[1],d=h?t.legendSymbol[0]:t.legendSymbol[1];t.div.innerHTML=`\n ${d||"▨"}\n ${n}: \n O ${l}, \n C ${c}\n `}else{const e="value"in i?i.value:void 0;if(null==e)return;const s=this.legendItemFormat(e,o.precision),r=t.colors[0],a=t.legendSymbol[0]||"▨";t.div.innerHTML=`\n ${a}\n ${n}: ${s}\n `}}))):t.row.style.display="none"}))}findGroup(e,t=this._groups){for(const i of t){if(i.name===e)return i;const t=this.findGroup(e,i.subGroups);if(t)return t}}}const L={lineColor:"#1E80F0",lineStyle:t.LineStyle.Solid,width:4};var N;!function(e){e[e.NONE=0]="NONE",e[e.HOVERING=1]="HOVERING",e[e.DRAGGING=2]="DRAGGING",e[e.DRAGGINGP1=3]="DRAGGINGP1",e[e.DRAGGINGP2=4]="DRAGGINGP2",e[e.DRAGGINGP3=5]="DRAGGINGP3",e[e.DRAGGINGP4=6]="DRAGGINGP4"}(N||(N={}));class O extends a{_paneViews=[];_options;_points=[];_state=N.NONE;_startDragPoint=null;_latestHoverPoint=null;static _mouseIsDown=!1;static hoveredObject=null;static lastHoveredObject=null;_listeners=[];constructor(e){super(),this._options={...L,...e}}updateAllViews(){this._paneViews.forEach((e=>e.update()))}paneViews(){return this._paneViews}applyOptions(e){this._options={...this._options,...e},this.requestUpdate()}updatePoints(...e){for(let t=0;ti.name===e&&i.listener===t));this._listeners.splice(this._listeners.indexOf(i),1)}_handleHoverInteraction(e){if(this._latestHoverPoint=e.point,O._mouseIsDown)this._handleDragInteraction(e);else if(this._mouseIsOverDrawing(e)){if(this._state!=N.NONE)return;this._moveToState(N.HOVERING),O.hoveredObject=O.lastHoveredObject=this}else{if(this._state==N.NONE)return;this._moveToState(N.NONE),O.hoveredObject===this&&(O.hoveredObject=null)}}static _eventToPoint(e,t){if(!t||!e.point||!e.logical)return null;const i=t.coordinateToPrice(e.point.y);return null==i?null:{time:e.time||null,logical:e.logical,price:i.valueOf()}}static _getDiff(e,t){return{logical:e.logical-t.logical,price:e.price-t.price}}_addDiffToPoint(e,t,i){e&&(e.logical=e.logical+t,e.price=e.price+i,e.time=this.series.dataByIndex(e.logical)?.time||null)}_handleMouseDownInteraction=()=>{O._mouseIsDown=!0,this._onMouseDown()};_handleMouseUpInteraction=()=>{O._mouseIsDown=!1,this._moveToState(N.HOVERING)};_handleDragInteraction(e){if(this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1&&this._state!=N.DRAGGINGP2&&this._state!=N.DRAGGINGP3&&this._state!=N.DRAGGINGP4)return;const t=O._eventToPoint(e,this.series);if(!t)return;this._startDragPoint=this._startDragPoint||t;const i=O._getDiff(t,this._startDragPoint);this._onDrag(i),this.requestUpdate(),this._startDragPoint=t}}class V extends O{_paneViews=[];_hovered=!1;linkedObjects=[];constructor(e,t,i){super(),this.points.push(e),this.points.push(t),this._options={...L,...i}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}_mouseIsOverObjects(e){for(const t of this.linkedObjects)for(const i in t){if(i.includes("mouseIsOver")&&"function"==typeof t[i]&&t[i](e))return!0;if(i.includes("_hovered")&&"function"==typeof t[i]&&t[i]())return!0}return!1}_mouseIsOverDrawing(e){const t=this._mouseIsOverTwoPointDrawing(e),i=this._mouseIsOverObjects(e),s=t||i;return console.debug("Mouse over check",{selfResult:t,objectsResult:i,finalResult:s}),s}detach(){this.linkedObjects.forEach((e=>{const t=e.series;t&&t.detachPrimitive(e)})),this.linkedObjects=[],super.detach()}get p1(){return this.points[0]}get p2(){return this.points[1]}get hovered(){return this._hovered}}class R extends O{_paneViews=[];_hovered=!1;linkedObjects=[];detach(){this.linkedObjects.forEach((e=>{const t=e.series;t&&t.detachPrimitive(e)})),this.linkedObjects=[],super.detach()}constructor(e,t,i,s){super(),this.points.push(e),this.points.push(t),this.points.push(i),this._options={...L,...s}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}setThirdPoint(e){this.updatePoints(null,null,e)}get p1(){return this.points[0]}get p2(){return this.points[1]}get p3(){return this.points[2]}get hovered(){return this._hovered}}class B extends O{_paneViews=[];_hovered=!1;linkedObjects=[];detach(){this.linkedObjects.forEach((e=>{const t=e.series;t&&t.detachPrimitive(e)})),this.linkedObjects=[],super.detach()}constructor(e,t,i,s,n){super(),this.points.push(e),this.points.push(t),this.points.push(i),this.points.push(s),this._options={...L,...n}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}setThirdPoint(e){this.updatePoints(null,null,e)}setFourthPoint(e){this.updatePoints(null,null,null,e)}get p1(){return this.points[0]}get p2(){return this.points[1]}get p3(){return this.points[2]}get p4(){return this.points[3]}get hovered(){return this._hovered}}class ${_chart;_series;_finishDrawingCallback=null;_drawings=[];_activeDrawing=null;_isDrawing=!1;_drawingType=null;_tempStartPoint=null;_tempSecondPoint=null;_clickCount=0;constructor(e,t,i=null){this._chart=e,this._series=t,this._finishDrawingCallback=i,this._chart.subscribeClick(this._clickHandler),this._chart.subscribeCrosshairMove(this._moveHandler)}_clickHandler=e=>this._onClick(e);_moveHandler=e=>this._onMouseMove(e);beginDrawing(e){this._drawingType=e,this._isDrawing=!0,this._tempStartPoint=null,this._tempSecondPoint=null,this._clickCount=0}stopDrawing(){this._isDrawing=!1,this._activeDrawing=null,this._tempStartPoint=null,this._tempSecondPoint=null,this._clickCount=0}get drawings(){return this._drawings}addNewDrawing(e){this._series.attachPrimitive(e),this._drawings.push(e)}delete(e){if(null==e)return;const t=this._drawings.indexOf(e);-1!=t&&(this._drawings.splice(t,1),e.detach())}clearDrawings(){for(const e of this._drawings)e.detach();this._drawings=[]}repositionOnTime(){for(const e of this.drawings){const t=[];for(const i of e.points){if(!i){t.push(i);continue}const e=i.time?this._chart.timeScale().coordinateToLogical(this._chart.timeScale().timeToCoordinate(i.time)||0):i.logical;t.push({time:i.time,logical:e,price:i.price})}e.updatePoints(...t)}}_onClick(e){if(!this._isDrawing)return;const t=O._eventToPoint(e,this._series);if(!t)return;let i;if(this._drawingType)if(i=this._drawingType.prototype instanceof B?4:this._drawingType.prototype instanceof R?3:(this._drawingType.prototype,2),3===i){if(null==this._activeDrawing)return null==this._tempStartPoint?(this._tempStartPoint=t,void(this._clickCount=1)):(this._activeDrawing=new this._drawingType(this._tempStartPoint,t,null),this._series.attachPrimitive(this._activeDrawing),this._clickCount=2,void(this._tempStartPoint=null));2===this._clickCount&&(this._activeDrawing.setThirdPoint(t),this._clickCount=3,this._drawings.push(this._activeDrawing),this.stopDrawing(),this._finishDrawingCallback&&this._finishDrawingCallback())}else if(4===i){if(null==this._activeDrawing)return null==this._tempStartPoint?(this._tempStartPoint=t,void(this._clickCount=1)):null==this._tempSecondPoint?(this._tempSecondPoint=t,void(this._clickCount=2)):(this._activeDrawing=new this._drawingType(this._tempStartPoint,this._tempSecondPoint,t,null),this._series.attachPrimitive(this._activeDrawing),this._clickCount=3,this._tempStartPoint=null,void(this._tempSecondPoint=null));3===this._clickCount&&(this._activeDrawing.setFourthPoint(t),this._clickCount=4,this._drawings.push(this._activeDrawing),this.stopDrawing(),this._finishDrawingCallback&&this._finishDrawingCallback())}else null==this._activeDrawing?(this._activeDrawing=new this._drawingType(t,t),this._series.attachPrimitive(this._activeDrawing),this._clickCount=1):(this._activeDrawing.setSecondPoint(t),this._clickCount=2,this._drawings.push(this._activeDrawing),this.stopDrawing(),this._finishDrawingCallback&&this._finishDrawingCallback())}_onMouseMove(e){if(!e)return;for(const t of this._drawings)t._handleHoverInteraction(e);if(!this._isDrawing||!this._activeDrawing)return;const t=O._eventToPoint(e,this._series);if(!t)return;const i=this._drawingType&&this._drawingType.prototype instanceof R;this._drawingType&&this._drawingType.prototype instanceof B?2===this._clickCount?this._activeDrawing.updatePoints(null,null,t,null):3===this._clickCount&&this._activeDrawing.updatePoints(null,null,null,t):i?2===this._clickCount&&this._activeDrawing.updatePoints(null,null,t):this._activeDrawing.setSecondPoint(t)}}class G{_options;constructor(e){this._options=e}}class F extends G{_p1;_p2;_hovered;constructor(e,t,i,s){super(i),this._p1=e,this._p2=t,this._hovered=s}_getScaledCoordinates(e){return null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y?null:{x1:Math.round(this._p1.x*e.horizontalPixelRatio),y1:Math.round(this._p1.y*e.verticalPixelRatio),x2:Math.round(this._p2.x*e.horizontalPixelRatio),y2:Math.round(this._p2.y*e.verticalPixelRatio)}}_drawEndCircle(e,t,i){e.context.fillStyle="#000",e.context.beginPath(),e.context.arc(t,i,9,0,2*Math.PI),e.context.stroke(),e.context.fill()}}class j extends G{_p1;_p2;_p3;_hovered;constructor(e,t,i,s,n){super(s),this._p1=e,this._p2=t,this._p3=i,this._hovered=n}_getScaledCoordinates(e){return null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y||null===this._p3.x||null===this._p3.y?null:{x1:Math.round(this._p1.x*e.horizontalPixelRatio),y1:Math.round(this._p1.y*e.verticalPixelRatio),x2:Math.round(this._p2.x*e.horizontalPixelRatio),y2:Math.round(this._p2.y*e.verticalPixelRatio),x3:Math.round(this._p3.x*e.horizontalPixelRatio),y3:Math.round(this._p3.y*e.verticalPixelRatio)}}_drawEndCircle(e,t,i){e.context.fillStyle="#000",e.context.beginPath(),e.context.arc(t,i,9,0,2*Math.PI),e.context.stroke(),e.context.fill()}}function U(e,i){const s={[t.LineStyle.Solid]:[],[t.LineStyle.Dotted]:[e.lineWidth,e.lineWidth],[t.LineStyle.Dashed]:[2*e.lineWidth,2*e.lineWidth],[t.LineStyle.LargeDashed]:[6*e.lineWidth,6*e.lineWidth],[t.LineStyle.SparseDotted]:[e.lineWidth,4*e.lineWidth]}[i];e.setLineDash(s)}class z extends F{constructor(e,t,i,s){super(e,t,i,s)}draw(e){e.useBitmapCoordinateSpace((e=>{if(null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y)return;const t=e.context,i=this._getScaledCoordinates(e);i&&(t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.beginPath(),t.moveTo(i.x1,i.y1),t.lineTo(i.x2,i.y2),t.stroke(),this._hovered&&(this._drawEndCircle(e,i.x1,i.y1),this._drawEndCircle(e,i.x2,i.y2)))}))}}class H{_source;constructor(e){this._source=e}}class W extends H{_p1={x:null,y:null};_p2={x:null,y:null};_source;constructor(e){super(e),this._source=e}update(){if(!this._source.p1||!this._source.p2)return;const e=this._source.series,t=e.priceToCoordinate(this._source.p1.price),i=e.priceToCoordinate(this._source.p2.price),s=this._getX(this._source.p1),n=this._getX(this._source.p2);this._p1={x:s,y:t},this._p2={x:n,y:i}}_getX(e){return this._source.chart.timeScale().logicalToCoordinate(e.logical)}}class q extends H{_p1={x:null,y:null};_p2={x:null,y:null};_p3={x:null,y:null};_source;constructor(e){super(e),this._source=e}update(){if(!this._source.p1||!this._source.p2||!this._source.p3)return;const e=this._source.series,t=e.priceToCoordinate(this._source.p1.price),i=e.priceToCoordinate(this._source.p2.price),s=e.priceToCoordinate(this._source.p3.price),n=this._getX(this._source.p1),o=this._getX(this._source.p2),r=this._getX(this._source.p3);this._p1={x:n,y:t},this._p2={x:o,y:i},this._p3={x:r,y:s}}_getX(e){return this._source.chart.timeScale().logicalToCoordinate(e.logical)}}class X extends W{constructor(e){super(e)}renderer(){return new z(this._p1,this._p2,this._source._options,this._source.hovered)}}class J extends V{_type="TrendLine";constructor(e,t,i){super(e,t,i),this._paneViews=[new X(this)]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this.requestUpdate(),this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this.requestUpdate(),this._subscribe("mousedown",this._handleMouseDownInteraction),this._unsubscribe("mouseup",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this.p2,e.logical,e.price)}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint;if(!e)return;const t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);Math.abs(e.x-t.x)<10&&Math.abs(e.y-t.y)<10?this._moveToState(N.DRAGGINGP1):Math.abs(e.x-i.x)<10&&Math.abs(e.y-i.y)<10?this._moveToState(N.DRAGGINGP2):this._moveToState(N.DRAGGING)}_mouseIsOverTwoPointDrawing(e,t=4){if(!e.point)return!1;const i=this._paneViews[0]._p1.x,s=this._paneViews[0]._p1.y,n=this._paneViews[0]._p2.x,o=this._paneViews[0]._p2.y;if(!(i&&n&&s&&o))return!1;const r=e.point.x,a=e.point.y;if(r<=Math.min(i,n)-t||r>=Math.max(i,n)+t)return!1;return Math.abs((o-s)*r-(n-i)*a+n*s-o*i)/Math.sqrt((o-s)**2+(n-i)**2)<=t}}class Y extends F{constructor(e,t,i,s){super(e,t,i,s)}draw(e){e.useBitmapCoordinateSpace((e=>{const t=e.context,i=this._getScaledCoordinates(e);if(!i)return;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.fillStyle=this._options.fillColor;const s=Math.min(i.x1,i.x2),n=Math.min(i.y1,i.y2),o=Math.abs(i.x1-i.x2),r=Math.abs(i.y1-i.y2);t.strokeRect(s,n,o,r),t.fillRect(s,n,o,r),this._hovered&&(this._drawEndCircle(e,s,n),this._drawEndCircle(e,s+o,n),this._drawEndCircle(e,s+o,n+r),this._drawEndCircle(e,s,n+r))}))}}class K extends W{constructor(e){super(e)}renderer(){return new Y(this._p1,this._p2,this._source._options,this._source.hovered)}}const Q={fillEnabled:!0,fillColor:"rgba(255, 255, 255, 0.2)",...L};class Z extends V{_type="Box";constructor(e,t,i){super(e,t,i),this._options={...Q,...i},this._paneViews=[new K(this)]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._unsubscribe("mouseup",this._handleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGINGP3:case N.DRAGGINGP4:case N.DRAGGING:document.body.style.cursor="grabbing",document.body.addEventListener("mouseup",this._handleMouseUpInteraction),this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this.p2,e.logical,e.price),this._state!=N.DRAGGING&&(this._state==N.DRAGGINGP3&&(this._addDiffToPoint(this.p1,e.logical,0),this._addDiffToPoint(this.p2,0,e.price)),this._state==N.DRAGGINGP4&&(this._addDiffToPoint(this.p1,0,e.price),this._addDiffToPoint(this.p2,e.logical,0)))}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint,t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);const s=10;Math.abs(e.x-t.x)l-d&&rc-d&&a{if(null==this._point.y)return;const t=e.context,i=Math.round(this._point.y*e.verticalPixelRatio),s=this._point.x?this._point.x*e.horizontalPixelRatio:0;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.beginPath(),t.moveTo(s,i),t.lineTo(e.bitmapSize.width,i),t.stroke()}))}}class te extends H{_source;_point={x:null,y:null};constructor(e){super(e),this._source=e}update(){const e=this._source._point,t=this._source.chart.timeScale(),i=this._source.series;"RayLine"==this._source._type&&(this._point.x=e.time?t.timeToCoordinate(e.time):t.logicalToCoordinate(e.logical)),this._point.y=i.priceToCoordinate(e.price)}renderer(){return new ee(this._point,this._source._options)}}class ie{_source;_y=null;_price=null;constructor(e){this._source=e}update(){if(!this._source.series||!this._source._point)return;this._y=this._source.series.priceToCoordinate(this._source._point.price);const e=this._source.series.options().priceFormat.precision;this._price=this._source._point.price.toFixed(e).toString()}visible(){return!0}tickVisible(){return!0}coordinate(){return this._y??0}text(){return this._source._options.text||this._price||""}textColor(){return"white"}backColor(){return this._source._options.lineColor}}class se extends O{_type="HorizontalLine";_paneViews;_point;_callbackName;_priceAxisViews;_startDragPoint=null;constructor(e,t,i=null){super(t),this._point=e,this._point.time=null,this._paneViews=[new te(this)],this._priceAxisViews=[new ie(this)],this._callbackName=i}get points(){return[this._point]}updatePoints(...e){for(const t of e)t&&(this._point.price=t.price);this.requestUpdate()}updateAllViews(){this._paneViews.forEach((e=>e.update())),this._priceAxisViews.forEach((e=>e.update()))}priceAxisViews(){return this._priceAxisViews}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._unsubscribe("mouseup",this._childHandleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._childHandleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._addDiffToPoint(this._point,0,e.price),this.requestUpdate()}_mouseIsOverDrawing(e,t=4){if(!e.point)return!1;const i=this.series.priceToCoordinate(this._point.price);return!!i&&Math.abs(i-e.point.y){this._handleMouseUpInteraction(),this._callbackName&&window.callbackFunction(`${this._callbackName}_~_${this._point.price.toFixed(8)}`)}}class ne extends se{_type="RayLine";constructor(e,t){super({...e},t),this._point.time=e.time}updatePoints(...e){for(const t of e)t&&(this._point=t);this.requestUpdate()}_onDrag(e){this._addDiffToPoint(this._point,e.logical,e.price),this.requestUpdate()}_mouseIsOverTwoPointDrawing(e,t=4){if(!e.point)return!1;const i=this.series.priceToCoordinate(this._point.price),s=this._point.time?this.chart.timeScale().timeToCoordinate(this._point.time):null;return!(!i||!s)&&(Math.abs(i-e.point.y)s-t)}}class oe extends G{_point={x:null,y:null};constructor(e,t){super(t),this._point=e}draw(e){e.useBitmapCoordinateSpace((e=>{if(null==this._point.x)return;const t=e.context,i=this._point.x*e.horizontalPixelRatio;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.beginPath(),t.moveTo(i,0),t.lineTo(i,e.bitmapSize.height),t.stroke()}))}}class re extends H{_source;_point={x:null,y:null};constructor(e){super(e),this._source=e}update(){const e=this._source._point,t=this._source.chart.timeScale(),i=this._source.series;this._point.x=e.time?t.timeToCoordinate(e.time):t.logicalToCoordinate(e.logical),this._point.y=i.priceToCoordinate(e.price)}renderer(){return new oe(this._point,this._source._options)}}class ae{_source;_x=null;constructor(e){this._source=e}update(){if(!this._source.chart||!this._source._point)return;const e=this._source._point,t=this._source.chart.timeScale();this._x=e.time?t.timeToCoordinate(e.time):t.logicalToCoordinate(e.logical)}visible(){return!!this._source._options.text}tickVisible(){return!0}coordinate(){return this._x??0}text(){return this._source._options.text||""}textColor(){return"white"}backColor(){return this._source._options.lineColor}}class le extends O{_type="VerticalLine";_paneViews;_timeAxisViews;_point;_callbackName;_startDragPoint=null;constructor(e,t,i=null){super(t),this._point=e,this._paneViews=[new re(this)],this._callbackName=i,this._timeAxisViews=[new ae(this)]}updateAllViews(){this._paneViews.forEach((e=>e.update())),this._timeAxisViews.forEach((e=>e.update()))}timeAxisViews(){return this._timeAxisViews}updatePoints(...e){for(const t of e)t&&(!t.time&&t.logical&&(t.time=this.series.dataByIndex(t.logical)?.time||null),this._point=t);this.requestUpdate()}get points(){return[this._point]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._unsubscribe("mouseup",this._childHandleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._childHandleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._addDiffToPoint(this._point,e.logical,0),this.requestUpdate()}_mouseIsOverDrawing(e,t=4){if(!e.point)return!1;const i=this.chart.timeScale();let s;return s=this._point.time?i.timeToCoordinate(this._point.time):i.logicalToCoordinate(this._point.logical),!!s&&Math.abs(s-e.point.x){this._handleMouseUpInteraction(),this._callbackName&&window.callbackFunction(`${this._callbackName}_~_${this._point.price.toFixed(8)}`)}}class ce extends j{options;variant;width;constructor(e,t,i,s,n,o){super(e,t,i,s,n),this.options=s,this.variant=s.variant??"standard",this.width=o}draw(e){e.useBitmapCoordinateSpace((e=>{if(null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y||null===this._p3.x||null===this._p3.y)return;const i=e.context,s=this._getScaledCoordinates(e);if(!s)return;const{x1:n,y1:o,x2:r,y2:a,x3:l,y3:c}=s,h=(r+l)/2,p=(a+c)/2;let d,u,m,g,f,y;const b=this.width-Math.max(this._p1.x,this._p2.x);if("inside"===this.variant){d=h,u=p;const e=(n+r)/2-l,t=(o+a)/2-c;let i=Math.atan2(t,e);Math.cos(i)<0&&(i+=Math.PI),m=d+b*Math.cos(i),g=u+b*Math.sin(i)}else{const{anchorX:e,anchorY:t}=this._computeAnchorPoint(this.variant,n,o,r,a),i=this._lineIntersection(n,o,r,a,h,p,e,t);i?[d,u]=i:(d=n,u=o);const s=h-d;m=d+b,g=u+(Math.abs(s)>1e-9?(p-u)/s:0)*b}if(f=m-d,y=g-u,i.lineWidth=this.options.width,i.strokeStyle=this.options.lineColor,U(i,this.options.lineStyle),U(i,t.LineStyle.Solid),i.beginPath(),i.moveTo(r,a),i.lineTo(l,c),i.stroke(),U(i,this.options.lineStyle),i.beginPath(),i.moveTo(n,o),i.lineTo(r,a),i.stroke(),i.beginPath(),i.moveTo(d,u),i.lineTo(m,g),i.stroke(),i.beginPath(),i.moveTo(r,a),i.lineTo(r+f,a+y),i.stroke(),i.beginPath(),i.moveTo(l,c),i.lineTo(l+f,c+y),i.stroke(),this.options.forkLines&&this.options.forkLines.length>0){const e=this.options.forkLines;for(let t=0;tMath.max(i,n,r)+t)return!1;const h=this._distanceFromSegment(i,s,n,o,l,c),p=this._distanceFromSegment(n,o,r,a,l,c),d=this._distanceFromSegment(i,s,r,a,l,c);return h<=t||p<=t||d<=t}_distanceFromSegment(e,t,i,s,n,o){const r=i-e,a=s-t,l=r*r+a*a;let c,h,p=0!==l?((n-e)*r+(o-t)*a)/l:-1;p<0?(c=e,h=t):p>1?(c=i,h=s):(c=e+p*r,h=t+p*a);const d=n-c,u=o-h;return Math.sqrt(d*d+u*u)}fromJSON(e){if(e.options){const t=e.options;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const i=e;this.applyOptions({[i]:t[i]})}}}toJSON(){return{options:this._options}}title="PitchFork"}class ue{static TREND_SVG='';static HORZ_SVG='';static RAY_SVG='';static BOX_SVG='';static VERT_SVG=ue.RAY_SVG;static PITCHFORK_SVG='';div;activeIcon=null;buttons=[];_commandFunctions;_handlerID;_drawingTool;handler;constructor(e,t,i,s,n){this._handlerID=t,this._commandFunctions=n,this._drawingTool=new $(i,s,(()=>this.removeActiveAndSave())),this.div=this._makeToggleToolBox(),this.handler=e,this.handler.ContextMenu.setupDrawingTools(this.saveDrawings,this._drawingTool),n.push((e=>{if((e.metaKey||e.ctrlKey)&&"KeyZ"===e.code){const e=this._drawingTool.drawings.pop();return e&&this._drawingTool.delete(e),!0}return!1}))}toJSON(){const{...e}=this;return e}_makeToggleToolBox(){const e=document.createElement("div");e.classList.add("flyout-toolbox"),e.style.position="absolute",e.style.top="0",e.style.left="50%",e.style.transform="translateX(-50%)",e.style.zIndex="1000",e.style.overflow="hidden",e.style.transition="height 0.3s ease";const t=document.createElement("div");t.classList.add("toolbox-content"),t.style.display="inline-flex",t.style.flexDirection="row",t.style.justifyContent="center",t.style.alignItems="center",t.style.padding="5px",t.style.backgroundColor="rgba(0, 0, 0, 0.5)",t.style.display="none",this.buttons=[],this.buttons.push(this._makeToolBoxElement(J,"KeyT",ue.TREND_SVG)),this.buttons.push(this._makeToolBoxElement(se,"KeyH",ue.HORZ_SVG)),this.buttons.push(this._makeToolBoxElement(ne,"KeyR",ue.RAY_SVG)),this.buttons.push(this._makeToolBoxElement(Z,"KeyB",ue.BOX_SVG)),this.buttons.push(this._makeToolBoxElement(le,"KeyV",ue.VERT_SVG,!0)),this.buttons.push(this._makeToolBoxElement(de,"KeyP",ue.PITCHFORK_SVG));for(const e of this.buttons)t.appendChild(e);const i=document.createElement("div");i.textContent="▼",i.style.width="15px",i.style.height="10px",i.style.backgroundColor="rgba(0, 0, 0, 0)",i.style.color="#fff",i.style.textAlign="center",i.style.lineHeight="15px",i.style.cursor="pointer",e.appendChild(t),e.appendChild(i);let s=!1;return e.style.height="15px",i.onclick=()=>{if(s=!s,s){t.style.display="inline-flex";const s=t.scrollHeight;e.style.height=`${15+s}px`,i.textContent="▲"}else t.style.display="none",e.style.height="15px",i.textContent="▼"},e}_makeToolBoxElement(e,t,i,s=!1){const n=document.createElement("div");n.classList.add("toolbox-button");const o=document.createElementNS("http://www.w3.org/2000/svg","svg");o.setAttribute("width","29"),o.setAttribute("height","29");const r=document.createElementNS("http://www.w3.org/2000/svg","g");r.innerHTML=i,r.setAttribute("fill",window.pane.color),o.appendChild(r),n.appendChild(o);const a={div:n,group:r,type:e};return n.addEventListener("click",(()=>this._onIconClick(a))),this._commandFunctions.push((e=>this._handlerID===window.handlerInFocus&&(!(!e.altKey||e.code!==t)&&(e.preventDefault(),this._onIconClick(a),!0)))),1==s&&(o.style.transform="rotate(90deg)",o.style.transformBox="fill-box",o.style.transformOrigin="center"),n}_onIconClick(e){this.activeIcon&&(this.activeIcon.div.classList.remove("active-toolbox-button"),window.setCursor("crosshair"),this._drawingTool?.stopDrawing(),this.activeIcon===e)?this.activeIcon=null:(this.activeIcon=e,this.activeIcon.div.classList.add("active-toolbox-button"),window.setCursor("crosshair"),this._drawingTool?.beginDrawing(this.activeIcon.type))}removeActiveAndSave=()=>{window.setCursor("default"),this.activeIcon&&this.activeIcon.div.classList.remove("active-toolbox-button"),this.activeIcon=null,this.saveDrawings()};addNewDrawing(e){this._drawingTool.addNewDrawing(e)}clearDrawings(){this._drawingTool.clearDrawings()}saveDrawings=()=>{const e=[];for(const t of this._drawingTool.drawings)e.push({type:t._type,points:t.points,options:t._options});const t=JSON.stringify(e);window.callbackFunction(`save_drawings${this._handlerID}_~_${t}`)};loadDrawings(e){e.forEach((e=>{switch(e.type){case"Box":this._drawingTool.addNewDrawing(new Z(e.points[0],e.points[1],e.options));break;case"TrendLine":this._drawingTool.addNewDrawing(new J(e.points[0],e.points[1],e.options));break;case"HorizontalLine":this._drawingTool.addNewDrawing(new se(e.points[0],e.options));break;case"RayLine":this._drawingTool.addNewDrawing(new ne(e.points[0],e.options));break;case"VerticalLine":this._drawingTool.addNewDrawing(new le(e.points[0],e.options));break;case"PitchFork":this._drawingTool.addNewDrawing(new de(e.points[0],e.points[1],e.points[2],e.options))}}))}}var me=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],ge=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],fe="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲊᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꟍꟐꟑꟓꟕ-Ƛꟲ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",ye={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},be="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",ve={5:be,"5module":be+" export import",6:be+" const class extends export import super"},xe=/^in(stanceof)?$/,_e=new RegExp("["+fe+"]"),we=new RegExp("["+fe+"‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࢗ-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-ᫎᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・]");function Ce(e,t){for(var i=65536,s=0;se)return!1;if((i+=t[s+1])>=e)return!0}return!1}function Se(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&_e.test(String.fromCharCode(e)):!1!==t&&Ce(e,ge)))}function ke(e,t){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&we.test(String.fromCharCode(e)):!1!==t&&(Ce(e,ge)||Ce(e,me)))))}var Ee=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function Me(e,t){return new Ee(e,{beforeExpr:!0,binop:t})}var Pe={beforeExpr:!0},Te={startsExpr:!0},Ie={};function Ae(e,t){return void 0===t&&(t={}),t.keyword=e,Ie[e]=new Ee(e,t)}var De={num:new Ee("num",Te),regexp:new Ee("regexp",Te),string:new Ee("string",Te),name:new Ee("name",Te),privateId:new Ee("privateId",Te),eof:new Ee("eof"),bracketL:new Ee("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new Ee("]"),braceL:new Ee("{",{beforeExpr:!0,startsExpr:!0}),braceR:new Ee("}"),parenL:new Ee("(",{beforeExpr:!0,startsExpr:!0}),parenR:new Ee(")"),comma:new Ee(",",Pe),semi:new Ee(";",Pe),colon:new Ee(":",Pe),dot:new Ee("."),question:new Ee("?",Pe),questionDot:new Ee("?."),arrow:new Ee("=>",Pe),template:new Ee("template"),invalidTemplate:new Ee("invalidTemplate"),ellipsis:new Ee("...",Pe),backQuote:new Ee("`",Te),dollarBraceL:new Ee("${",{beforeExpr:!0,startsExpr:!0}),eq:new Ee("=",{beforeExpr:!0,isAssign:!0}),assign:new Ee("_=",{beforeExpr:!0,isAssign:!0}),incDec:new Ee("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new Ee("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:Me("||",1),logicalAND:Me("&&",2),bitwiseOR:Me("|",3),bitwiseXOR:Me("^",4),bitwiseAND:Me("&",5),equality:Me("==/!=/===/!==",6),relational:Me("/<=/>=",7),bitShift:Me("<>/>>>",8),plusMin:new Ee("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:Me("%",10),star:Me("*",10),slash:Me("/",10),starstar:new Ee("**",{beforeExpr:!0}),coalesce:Me("??",1),_break:Ae("break"),_case:Ae("case",Pe),_catch:Ae("catch"),_continue:Ae("continue"),_debugger:Ae("debugger"),_default:Ae("default",Pe),_do:Ae("do",{isLoop:!0,beforeExpr:!0}),_else:Ae("else",Pe),_finally:Ae("finally"),_for:Ae("for",{isLoop:!0}),_function:Ae("function",Te),_if:Ae("if"),_return:Ae("return",Pe),_switch:Ae("switch"),_throw:Ae("throw",Pe),_try:Ae("try"),_var:Ae("var"),_const:Ae("const"),_while:Ae("while",{isLoop:!0}),_with:Ae("with"),_new:Ae("new",{beforeExpr:!0,startsExpr:!0}),_this:Ae("this",Te),_super:Ae("super",Te),_class:Ae("class",Te),_extends:Ae("extends",Pe),_export:Ae("export"),_import:Ae("import",Te),_null:Ae("null",Te),_true:Ae("true",Te),_false:Ae("false",Te),_in:Ae("in",{beforeExpr:!0,binop:7}),_instanceof:Ae("instanceof",{beforeExpr:!0,binop:7}),_typeof:Ae("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:Ae("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:Ae("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},Le=/\r\n?|\n|\u2028|\u2029/,Ne=new RegExp(Le.source,"g");function Oe(e){return 10===e||13===e||8232===e||8233===e}function Ve(e,t,i){void 0===i&&(i=e.length);for(var s=t;s>10),56320+(1023&e)))}var qe=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,Xe=function(e,t){this.line=e,this.column=t};Xe.prototype.offset=function(e){return new Xe(this.line,this.column+e)};var Je=function(e,t,i){this.start=t,this.end=i,null!==e.sourceFile&&(this.source=e.sourceFile)};function Ye(e,t){for(var i=1,s=0;;){var n=Ve(e,s,t);if(n<0)return new Xe(i,t-s);++i,s=n}}var Ke={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},Qe=!1;function Ze(e){var t={};for(var i in Ke)t[i]=e&&je(e,i)?e[i]:Ke[i];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!Qe&&"object"==typeof console&&console.warn&&(Qe=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),Ue(t.onToken)){var s=t.onToken;t.onToken=function(e){return s.push(e)}}return Ue(t.onComment)&&(t.onComment=function(e,t){return function(i,s,n,o,r,a){var l={type:i?"Block":"Line",value:s,start:n,end:o};e.locations&&(l.loc=new Je(this,r,a)),e.ranges&&(l.range=[n,o]),t.push(l)}}(t,t.onComment)),t}var et=256;function tt(e,t){return 2|(e?4:0)|(t?8:0)}var it=function(e,t,i){this.options=e=Ze(e),this.sourceFile=e.sourceFile,this.keywords=He(ve[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var s="";!0!==e.allowReserved&&(s=ye[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(s+=" await")),this.reservedWords=He(s);var n=(s?s+" ":"")+ye.strict;this.reservedWordsStrict=He(n),this.reservedWordsStrictBind=He(n+" "+ye.strictBind),this.input=String(t),this.containsEsc=!1,i?(this.pos=i,this.lineStart=this.input.lastIndexOf("\n",i-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(Le).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=De.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},st={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};it.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},st.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},st.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},st.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},st.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&et)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},st.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,i=e.inClassFieldInit;return(64&t)>0||i||this.options.allowSuperOutsideMethod},st.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},st.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},st.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,i=e.inClassFieldInit;return(258&t)>0||i},st.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&et)>0},it.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var i=this,s=0;s=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(s+1))}e+=t[0].length,Be.lastIndex=e,e+=Be.exec(this.input)[0].length,";"===this.input[e]&&e++}},nt.eat=function(e){return this.type===e&&(this.next(),!0)},nt.isContextual=function(e){return this.type===De.name&&this.value===e&&!this.containsEsc},nt.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},nt.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},nt.canInsertSemicolon=function(){return this.type===De.eof||this.type===De.braceR||Le.test(this.input.slice(this.lastTokEnd,this.start))},nt.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},nt.semicolon=function(){this.eat(De.semi)||this.insertSemicolon()||this.unexpected()},nt.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},nt.expect=function(e){this.eat(e)||this.unexpected()},nt.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var rt=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};nt.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var i=t?e.parenthesizedAssign:e.parenthesizedBind;i>-1&&this.raiseRecoverable(i,t?"Assigning to rvalue":"Parenthesized pattern")}},nt.checkExpressionErrors=function(e,t){if(!e)return!1;var i=e.shorthandAssign,s=e.doubleProto;if(!t)return i>=0||s>=0;i>=0&&this.raise(i,"Shorthand property assignments are valid only in destructuring patterns"),s>=0&&this.raiseRecoverable(s,"Redefinition of __proto__ property")},nt.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&s<56320)return!0;if(Se(s,!0)){for(var n=i+1;ke(s=this.input.charCodeAt(n),!0);)++n;if(92===s||s>55295&&s<56320)return!0;var o=this.input.slice(i,n);if(!xe.test(o))return!0}return!1},at.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;Be.lastIndex=this.pos;var e,t=Be.exec(this.input),i=this.pos+t[0].length;return!(Le.test(this.input.slice(this.pos,i))||"function"!==this.input.slice(i,i+8)||i+8!==this.input.length&&(ke(e=this.input.charCodeAt(i+8))||e>55295&&e<56320))},at.parseStatement=function(e,t,i){var s,n=this.type,o=this.startNode();switch(this.isLet(e)&&(n=De._var,s="let"),n){case De._break:case De._continue:return this.parseBreakContinueStatement(o,n.keyword);case De._debugger:return this.parseDebuggerStatement(o);case De._do:return this.parseDoStatement(o);case De._for:return this.parseForStatement(o);case De._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(o,!1,!e);case De._class:return e&&this.unexpected(),this.parseClass(o,!0);case De._if:return this.parseIfStatement(o);case De._return:return this.parseReturnStatement(o);case De._switch:return this.parseSwitchStatement(o);case De._throw:return this.parseThrowStatement(o);case De._try:return this.parseTryStatement(o);case De._const:case De._var:return s=s||this.value,e&&"var"!==s&&this.unexpected(),this.parseVarStatement(o,s);case De._while:return this.parseWhileStatement(o);case De._with:return this.parseWithStatement(o);case De.braceL:return this.parseBlock(!0,o);case De.semi:return this.parseEmptyStatement(o);case De._export:case De._import:if(this.options.ecmaVersion>10&&n===De._import){Be.lastIndex=this.pos;var r=Be.exec(this.input),a=this.pos+r[0].length,l=this.input.charCodeAt(a);if(40===l||46===l)return this.parseExpressionStatement(o,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===De._import?this.parseImport(o):this.parseExport(o,i);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(o,!0,!e);var c=this.value,h=this.parseExpression();return n===De.name&&"Identifier"===h.type&&this.eat(De.colon)?this.parseLabeledStatement(o,c,h,e):this.parseExpressionStatement(o,h)}},at.parseBreakContinueStatement=function(e,t){var i="break"===t;this.next(),this.eat(De.semi)||this.insertSemicolon()?e.label=null:this.type!==De.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var s=0;s=6?this.eat(De.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},at.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(lt),this.enterScope(0),this.expect(De.parenL),this.type===De.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var i=this.isLet();if(this.type===De._var||this.type===De._const||i){var s=this.startNode(),n=i?"let":this.value;return this.next(),this.parseVar(s,!0,n),this.finishNode(s,"VariableDeclaration"),(this.type===De._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===s.declarations.length?(this.options.ecmaVersion>=9&&(this.type===De._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,s)):(t>-1&&this.unexpected(t),this.parseFor(e,s))}var o=this.isContextual("let"),r=!1,a=this.containsEsc,l=new rt,c=this.start,h=t>-1?this.parseExprSubscripts(l,"await"):this.parseExpression(!0,l);return this.type===De._in||(r=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===De._in&&this.unexpected(t),e.await=!0):r&&this.options.ecmaVersion>=8&&(h.start!==c||a||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),o&&r&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,l),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(l,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},at.parseFunctionStatement=function(e,t,i){return this.next(),this.parseFunction(e,pt|(i?0:dt),!1,t)},at.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(De._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},at.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(De.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},at.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(De.braceL),this.labels.push(ct),this.enterScope(0);for(var i=!1;this.type!==De.braceR;)if(this.type===De._case||this.type===De._default){var s=this.type===De._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),s?t.test=this.parseExpression():(i&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),i=!0,t.test=null),this.expect(De.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},at.parseThrowStatement=function(e){return this.next(),Le.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var ht=[];at.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(De.parenR),e},at.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===De._catch){var t=this.startNode();this.next(),this.eat(De.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(De._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},at.parseVarStatement=function(e,t,i){return this.next(),this.parseVar(e,!1,t,i),this.semicolon(),this.finishNode(e,"VariableDeclaration")},at.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(lt),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},at.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},at.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},at.parseLabeledStatement=function(e,t,i,s){for(var n=0,o=this.labels;n=0;a--){var l=this.labels[a];if(l.statementStart!==e.start)break;l.statementStart=this.start,l.kind=r}return this.labels.push({name:t,kind:r,statementStart:this.start}),e.body=this.parseStatement(s?-1===s.indexOf("label")?s+"label":s:"label"),this.labels.pop(),e.label=i,this.finishNode(e,"LabeledStatement")},at.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},at.parseBlock=function(e,t,i){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(De.braceL),e&&this.enterScope(0);this.type!==De.braceR;){var s=this.parseStatement(null);t.body.push(s)}return i&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},at.parseFor=function(e,t){return e.init=t,this.expect(De.semi),e.test=this.type===De.semi?null:this.parseExpression(),this.expect(De.semi),e.update=this.type===De.parenR?null:this.parseExpression(),this.expect(De.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},at.parseForIn=function(e,t){var i=this.type===De._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!i||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(i?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=i?this.parseExpression():this.parseMaybeAssign(),this.expect(De.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,i?"ForInStatement":"ForOfStatement")},at.parseVar=function(e,t,i,s){for(e.declarations=[],e.kind=i;;){var n=this.startNode();if(this.parseVarId(n,i),this.eat(De.eq)?n.init=this.parseMaybeAssign(t):s||"const"!==i||this.type===De._in||this.options.ecmaVersion>=6&&this.isContextual("of")?s||"Identifier"===n.id.type||t&&(this.type===De._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(De.comma))break}return e},at.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var pt=1,dt=2;function ut(e,t){var i=t.key.name,s=e[i],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===s&&"iset"===n||"iset"===s&&"iget"===n||"sget"===s&&"sset"===n||"sset"===s&&"sget"===n?(e[i]="true",!1):!!s||(e[i]=n,!1)}function mt(e,t){var i=e.computed,s=e.key;return!i&&("Identifier"===s.type&&s.name===t||"Literal"===s.type&&s.value===t)}at.parseFunction=function(e,t,i,s,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!s)&&(this.type===De.star&&t&dt&&this.unexpected(),e.generator=this.eat(De.star)),this.options.ecmaVersion>=8&&(e.async=!!s),t&pt&&(e.id=4&t&&this.type!==De.name?null:this.parseIdent(),!e.id||t&dt||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var o=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(tt(e.async,e.generator)),t&pt||(e.id=this.type===De.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,i,!1,n),this.yieldPos=o,this.awaitPos=r,this.awaitIdentPos=a,this.finishNode(e,t&pt?"FunctionDeclaration":"FunctionExpression")},at.parseFunctionParams=function(e){this.expect(De.parenL),e.params=this.parseBindingList(De.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},at.parseClass=function(e,t){this.next();var i=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var s=this.enterClassBody(),n=this.startNode(),o=!1;for(n.body=[],this.expect(De.braceL);this.type!==De.braceR;){var r=this.parseClassElement(null!==e.superClass);r&&(n.body.push(r),"MethodDefinition"===r.type&&"constructor"===r.kind?(o&&this.raiseRecoverable(r.start,"Duplicate constructor in the same class"),o=!0):r.key&&"PrivateIdentifier"===r.key.type&&ut(s,r)&&this.raiseRecoverable(r.key.start,"Identifier '#"+r.key.name+"' has already been declared"))}return this.strict=i,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},at.parseClassElement=function(e){if(this.eat(De.semi))return null;var t=this.options.ecmaVersion,i=this.startNode(),s="",n=!1,o=!1,r="method",a=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(De.braceL))return this.parseClassStaticBlock(i),i;this.isClassElementNameStart()||this.type===De.star?a=!0:s="static"}if(i.static=a,!s&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==De.star||this.canInsertSemicolon()?s="async":o=!0),!s&&(t>=9||!o)&&this.eat(De.star)&&(n=!0),!s&&!o&&!n){var l=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?r=l:s=l)}if(s?(i.computed=!1,i.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),i.key.name=s,this.finishNode(i.key,"Identifier")):this.parseClassElementName(i),t<13||this.type===De.parenL||"method"!==r||n||o){var c=!i.static&&mt(i,"constructor"),h=c&&e;c&&"method"!==r&&this.raise(i.key.start,"Constructor can't have get/set modifier"),i.kind=c?"constructor":r,this.parseClassMethod(i,n,o,h)}else this.parseClassField(i);return i},at.isClassElementNameStart=function(){return this.type===De.name||this.type===De.privateId||this.type===De.num||this.type===De.string||this.type===De.bracketL||this.type.keyword},at.parseClassElementName=function(e){this.type===De.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},at.parseClassMethod=function(e,t,i,s){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),i&&this.raise(n.start,"Constructor can't be an async method")):e.static&&mt(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var o=e.value=this.parseMethod(t,i,s);return"get"===e.kind&&0!==o.params.length&&this.raiseRecoverable(o.start,"getter should have no params"),"set"===e.kind&&1!==o.params.length&&this.raiseRecoverable(o.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===o.params[0].type&&this.raiseRecoverable(o.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},at.parseClassField=function(e){if(mt(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&mt(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(De.eq)){var t=this.currentThisScope(),i=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=i}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},at.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==De.braceR;){var i=this.parseStatement(null);e.body.push(i)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},at.parseClassId=function(e,t){this.type===De.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},at.parseClassSuper=function(e){e.superClass=this.eat(De._extends)?this.parseExprSubscripts(null,!1):null},at.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},at.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,i=e.used;if(this.options.checkPrivateFields)for(var s=this.privateNameStack.length,n=0===s?null:this.privateNameStack[s-1],o=0;o=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==De.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},at.parseExport=function(e,t){if(this.next(),this.eat(De.star))return this.parseExportAllDeclaration(e,t);if(this.eat(De._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==De.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var i=0,s=e.specifiers;i=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},at.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},at.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},at.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},at.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===De.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(De.comma)))return e;if(this.type===De.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(De.braceL);!this.eat(De.braceR);){if(t)t=!1;else if(this.expect(De.comma),this.afterTrailingComma(De.braceR))break;e.push(this.parseImportSpecifier())}return e},at.parseWithClause=function(){var e=[];if(!this.eat(De._with))return e;this.expect(De.braceL);for(var t={},i=!0;!this.eat(De.braceR);){if(i)i=!1;else if(this.expect(De.comma),this.afterTrailingComma(De.braceR))break;var s=this.parseImportAttribute(),n="Identifier"===s.key.type?s.key.name:s.key.value;je(t,n)&&this.raiseRecoverable(s.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(s)}return e},at.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===De.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(De.colon),this.type!==De.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},at.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===De.string){var e=this.parseLiteral(this.value);return qe.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},at.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var gt=it.prototype;gt.toAssignable=function(e,t,i){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",i&&this.checkPatternErrors(i,!0);for(var s=0,n=e.properties;s=8&&!a&&"async"===l.name&&!this.canInsertSemicolon()&&this.eat(De._function))return this.overrideContext(yt.f_expr),this.parseFunction(this.startNodeAt(o,r),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(De.arrow))return this.parseArrowExpression(this.startNodeAt(o,r),[l],!1,t);if(this.options.ecmaVersion>=8&&"async"===l.name&&this.type===De.name&&!a&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return l=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(De.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(o,r),[l],!0,t)}return l;case De.regexp:var c=this.value;return(s=this.parseLiteral(c.value)).regex={pattern:c.pattern,flags:c.flags},s;case De.num:case De.string:return this.parseLiteral(this.value);case De._null:case De._true:case De._false:return(s=this.startNode()).value=this.type===De._null?null:this.type===De._true,s.raw=this.type.keyword,this.next(),this.finishNode(s,"Literal");case De.parenL:var h=this.start,p=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(p)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),p;case De.bracketL:return s=this.startNode(),this.next(),s.elements=this.parseExprList(De.bracketR,!0,!0,e),this.finishNode(s,"ArrayExpression");case De.braceL:return this.overrideContext(yt.b_expr),this.parseObj(!1,e);case De._function:return s=this.startNode(),this.next(),this.parseFunction(s,0);case De._class:return this.parseClass(this.startNode(),!1);case De._new:return this.parseNew();case De.backQuote:return this.parseTemplate();case De._import:return this.options.ecmaVersion>=11?this.parseExprImport(i):this.unexpected();default:return this.parseExprAtomDefault()}},vt.parseExprAtomDefault=function(){this.unexpected()},vt.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===De.parenL&&!e)return this.parseDynamicImport(t);if(this.type===De.dot){var i=this.startNodeAt(t.start,t.loc&&t.loc.start);return i.name="import",t.meta=this.finishNode(i,"Identifier"),this.parseImportMeta(t)}this.unexpected()},vt.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(De.parenR)?e.options=null:(this.expect(De.comma),this.afterTrailingComma(De.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(De.parenR)||(this.expect(De.comma),this.afterTrailingComma(De.parenR)||this.unexpected())));else if(!this.eat(De.parenR)){var t=this.start;this.eat(De.comma)&&this.eat(De.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},vt.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},vt.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},vt.parseParenExpression=function(){this.expect(De.parenL);var e=this.parseExpression();return this.expect(De.parenR),e},vt.shouldParseArrow=function(e){return!this.canInsertSemicolon()},vt.parseParenAndDistinguishExpression=function(e,t){var i,s=this.start,n=this.startLoc,o=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var r,a=this.start,l=this.startLoc,c=[],h=!0,p=!1,d=new rt,u=this.yieldPos,m=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==De.parenR;){if(h?h=!1:this.expect(De.comma),o&&this.afterTrailingComma(De.parenR,!0)){p=!0;break}if(this.type===De.ellipsis){r=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===De.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}c.push(this.parseMaybeAssign(!1,d,this.parseParenItem))}var g=this.lastTokEnd,f=this.lastTokEndLoc;if(this.expect(De.parenR),e&&this.shouldParseArrow(c)&&this.eat(De.arrow))return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=u,this.awaitPos=m,this.parseParenArrowList(s,n,c,t);c.length&&!p||this.unexpected(this.lastTokStart),r&&this.unexpected(r),this.checkExpressionErrors(d,!0),this.yieldPos=u||this.yieldPos,this.awaitPos=m||this.awaitPos,c.length>1?((i=this.startNodeAt(a,l)).expressions=c,this.finishNodeAt(i,"SequenceExpression",g,f)):i=c[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(s,n);return y.expression=i,this.finishNode(y,"ParenthesizedExpression")}return i},vt.parseParenItem=function(e){return e},vt.parseParenArrowList=function(e,t,i,s){return this.parseArrowExpression(this.startNodeAt(e,t),i,!1,s)};var wt=[];vt.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===De.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var i=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),i&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var s=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),s,n,!0,!1),this.eat(De.parenL)?e.arguments=this.parseExprList(De.parenR,this.options.ecmaVersion>=8,!1):e.arguments=wt,this.finishNode(e,"NewExpression")},vt.parseTemplateElement=function(e){var t=e.isTagged,i=this.startNode();return this.type===De.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),i.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):i.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),i.tail=this.type===De.backQuote,this.finishNode(i,"TemplateElement")},vt.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var i=this.startNode();this.next(),i.expressions=[];var s=this.parseTemplateElement({isTagged:t});for(i.quasis=[s];!s.tail;)this.type===De.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(De.dollarBraceL),i.expressions.push(this.parseExpression()),this.expect(De.braceR),i.quasis.push(s=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(i,"TemplateLiteral")},vt.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===De.name||this.type===De.num||this.type===De.string||this.type===De.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===De.star)&&!Le.test(this.input.slice(this.lastTokEnd,this.start))},vt.parseObj=function(e,t){var i=this.startNode(),s=!0,n={};for(i.properties=[],this.next();!this.eat(De.braceR);){if(s)s=!1;else if(this.expect(De.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(De.braceR))break;var o=this.parseProperty(e,t);e||this.checkPropClash(o,n,t),i.properties.push(o)}return this.finishNode(i,e?"ObjectPattern":"ObjectExpression")},vt.parseProperty=function(e,t){var i,s,n,o,r=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(De.ellipsis))return e?(r.argument=this.parseIdent(!1),this.type===De.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(r,"RestElement")):(r.argument=this.parseMaybeAssign(!1,t),this.type===De.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(r,"SpreadElement"));this.options.ecmaVersion>=6&&(r.method=!1,r.shorthand=!1,(e||t)&&(n=this.start,o=this.startLoc),e||(i=this.eat(De.star)));var a=this.containsEsc;return this.parsePropertyName(r),!e&&!a&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(r)?(s=!0,i=this.options.ecmaVersion>=9&&this.eat(De.star),this.parsePropertyName(r)):s=!1,this.parsePropertyValue(r,e,i,s,n,o,t,a),this.finishNode(r,"Property")},vt.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var i=e.value.start;"get"===e.kind?this.raiseRecoverable(i,"getter should have no params"):this.raiseRecoverable(i,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},vt.parsePropertyValue=function(e,t,i,s,n,o,r,a){(i||s)&&this.type===De.colon&&this.unexpected(),this.eat(De.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,r),e.kind="init"):this.options.ecmaVersion>=6&&this.type===De.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(i,s)):t||a||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===De.comma||this.type===De.braceR||this.type===De.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((i||s)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,o,this.copyNode(e.key)):this.type===De.eq&&r?(r.shorthandAssign<0&&(r.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,o,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((i||s)&&this.unexpected(),this.parseGetterSetter(e))},vt.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(De.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(De.bracketR),e.key;e.computed=!1}return e.key=this.type===De.num||this.type===De.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},vt.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},vt.parseMethod=function(e,t,i){var s=this.startNode(),n=this.yieldPos,o=this.awaitPos,r=this.awaitIdentPos;return this.initFunction(s),this.options.ecmaVersion>=6&&(s.generator=e),this.options.ecmaVersion>=8&&(s.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|tt(t,s.generator)|(i?128:0)),this.expect(De.parenL),s.params=this.parseBindingList(De.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(s,!1,!0,!1),this.yieldPos=n,this.awaitPos=o,this.awaitIdentPos=r,this.finishNode(s,"FunctionExpression")},vt.parseArrowExpression=function(e,t,i,s){var n=this.yieldPos,o=this.awaitPos,r=this.awaitIdentPos;return this.enterScope(16|tt(i,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!i),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,s),this.yieldPos=n,this.awaitPos=o,this.awaitIdentPos=r,this.finishNode(e,"ArrowFunctionExpression")},vt.parseFunctionBody=function(e,t,i,s){var n=t&&this.type!==De.braceL,o=this.strict,r=!1;if(n)e.body=this.parseMaybeAssign(s),e.expression=!0,this.checkParams(e,!1);else{var a=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);o&&!a||(r=this.strictDirective(this.end))&&a&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var l=this.labels;this.labels=[],r&&(this.strict=!0),this.checkParams(e,!o&&!r&&!t&&!i&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,r&&!o),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=l}this.exitScope()},vt.isSimpleParamList=function(e){for(var t=0,i=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t){this.currentScope().lexical.push(e)}else if(3===t){var o=this.currentScope();s=this.treatFunctionsAsVar?o.lexical.indexOf(e)>-1:o.lexical.indexOf(e)>-1||o.var.indexOf(e)>-1,o.functions.push(e)}else for(var r=this.scopeStack.length-1;r>=0;--r){var a=this.scopeStack[r];if(a.lexical.indexOf(e)>-1&&!(32&a.flags&&a.lexical[0]===e)||!this.treatFunctionsAsVarInScope(a)&&a.functions.indexOf(e)>-1){s=!0;break}if(a.var.push(e),this.inModule&&1&a.flags&&delete this.undefinedExports[e],259&a.flags)break}s&&this.raiseRecoverable(i,"Identifier '"+e+"' has already been declared")},St.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},St.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},St.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},St.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var Et=function(e,t,i){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new Je(e,i)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},Mt=it.prototype;function Pt(e,t,i,s){return e.type=t,e.end=i,this.options.locations&&(e.loc.end=s),this.options.ranges&&(e.range[1]=i),e}Mt.startNode=function(){return new Et(this,this.start,this.startLoc)},Mt.startNodeAt=function(e,t){return new Et(this,e,t)},Mt.finishNode=function(e,t){return Pt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},Mt.finishNodeAt=function(e,t,i,s){return Pt.call(this,e,t,i,s)},Mt.copyNode=function(e){var t=new Et(this,e.start,this.startLoc);for(var i in e)t[i]=e[i];return t};var Tt="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",It=Tt+" Extended_Pictographic",At=It+" EBase EComp EMod EPres ExtPict",Dt={9:Tt,10:It,11:It,12:At,13:At,14:At},Lt={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Nt="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Ot="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Vt=Ot+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",Rt=Vt+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",Bt=Rt+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",$t=Bt+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Gt={9:Ot,10:Vt,11:Rt,12:Bt,13:$t,14:$t+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},Ft={};function jt(e){var t=Ft[e]={binary:He(Dt[e]+" "+Nt),binaryOfStrings:He(Lt[e]),nonBinary:{General_Category:He(Nt),Script:He(Gt[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Ut=0,zt=[9,10,11,12,13,14];Ut=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=Ft[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Xt(e){return 105===e||109===e||115===e}function Jt(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Yt(e){return e>=65&&e<=90||e>=97&&e<=122}qt.prototype.reset=function(e,t,i){var s=-1!==i.indexOf("v"),n=-1!==i.indexOf("u");this.start=0|e,this.source=t+"",this.flags=i,s&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},qt.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},qt.prototype.at=function(e,t){void 0===t&&(t=!1);var i=this.source,s=i.length;if(e>=s)return-1;var n=i.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=s)return n;var o=i.charCodeAt(e+1);return o>=56320&&o<=57343?(n<<10)+o-56613888:n},qt.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var i=this.source,s=i.length;if(e>=s)return s;var n,o=i.charCodeAt(e);return!t&&!this.switchU||o<=55295||o>=57344||e+1>=s||(n=i.charCodeAt(e+1))<56320||n>57343?e+1:e+2},qt.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},qt.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},qt.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},qt.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},qt.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var i=this.pos,s=0,n=e;s-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===r&&(s=!0),"v"===r&&(n=!0)}this.options.ecmaVersion>=15&&s&&n&&this.raise(e.start,"Invalid regular expression flag")},Ht.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Ht.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,i=e.backReferenceNames;t=16;for(t&&(e.branchID=new Wt(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Ht.regexp_alternative=function(e){for(;e.pos=9&&(i=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!i,!0}return e.pos=t,!1},Ht.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Ht.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Ht.regexp_eatBracedQuantifier=function(e,t){var i=e.pos;if(e.eat(123)){var s=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(s=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var i=this.regexp_eatModifiers(e),s=e.eat(45);if(i||s){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(s){var r=this.regexp_eatModifiers(e);i||r||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var a=0;a-1||i.indexOf(l)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Ht.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Ht.regexp_eatModifiers=function(e){for(var t="",i=0;-1!==(i=e.current())&&Xt(i);)t+=We(i),e.advance();return t},Ht.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Ht.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Ht.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Jt(t)&&(e.lastIntValue=t,e.advance(),!0)},Ht.regexp_eatPatternCharacters=function(e){for(var t=e.pos,i=0;-1!==(i=e.current())&&!Jt(i);)e.advance();return e.pos!==t},Ht.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t)&&(e.advance(),!0)},Ht.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,i=e.groupNames[e.lastStringValue];if(i)if(t)for(var s=0,n=i;s=11,s=e.current(i);return e.advance(i),92===s&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)&&(s=e.lastIntValue),function(e){return Se(e,!0)||36===e||95===e}(s)?(e.lastIntValue=s,!0):(e.pos=t,!1)},Ht.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,i=this.options.ecmaVersion>=11,s=e.current(i);return e.advance(i),92===s&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)&&(s=e.lastIntValue),function(e){return ke(e,!0)||36===e||95===e||8204===e||8205===e}(s)?(e.lastIntValue=s,!0):(e.pos=t,!1)},Ht.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Ht.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var i=e.lastIntValue;if(e.switchU)return i>e.maxBackReference&&(e.maxBackReference=i),!0;if(i<=e.numCapturingParens)return!0;e.pos=t}return!1},Ht.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Ht.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Ht.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Ht.regexp_eatZero=function(e){return 48===e.current()&&!Zt(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Ht.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Ht.regexp_eatControlLetter=function(e){var t=e.current();return!!Yt(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Ht.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var i,s=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(n&&o>=55296&&o<=56319){var r=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var a=e.lastIntValue;if(a>=56320&&a<=57343)return e.lastIntValue=1024*(o-55296)+(a-56320)+65536,!0}e.pos=r,e.lastIntValue=o}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&((i=e.lastIntValue)>=0&&i<=1114111))return!0;n&&e.raise("Invalid unicode escape"),e.pos=s}return!1},Ht.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t)&&(e.lastIntValue=t,e.advance(),!0)},Ht.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1};function Kt(e){return Yt(e)||95===e}function Qt(e){return Kt(e)||Zt(e)}function Zt(e){return e>=48&&e<=57}function ei(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ti(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function ii(e){return e>=48&&e<=55}Ht.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var i=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((i=80===t)||112===t)){var s;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(s=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return i&&2===s&&e.raise("Invalid property name"),s;e.raise("Invalid property name")}return 0},Ht.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var i=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var s=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,i,s),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Ht.regexp_validateUnicodePropertyNameAndValue=function(e,t,i){je(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(i)||e.raise("Invalid property value")},Ht.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Ht.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Kt(t=e.current());)e.lastStringValue+=We(t),e.advance();return""!==e.lastStringValue},Ht.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Qt(t=e.current());)e.lastStringValue+=We(t),e.advance();return""!==e.lastStringValue},Ht.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Ht.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),i=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===i&&e.raise("Negated character class may contain strings"),!0}return!1},Ht.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Ht.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var i=e.lastIntValue;!e.switchU||-1!==t&&-1!==i||e.raise("Invalid character class"),-1!==t&&-1!==i&&t>i&&e.raise("Range out of order in character class")}}},Ht.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var i=e.current();(99===i||ii(i))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var s=e.current();return 93!==s&&(e.lastIntValue=s,e.advance(),!0)},Ht.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Ht.regexp_classSetExpression=function(e){var t,i=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(i=2);for(var s=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(i=1):e.raise("Invalid character in character class");if(s!==e.pos)return i;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(s!==e.pos)return i}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return i;2===t&&(i=2)}},Ht.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var i=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;return-1!==i&&-1!==s&&i>s&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Ht.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Ht.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var i=e.eat(94),s=this.regexp_classContents(e);if(e.eat(93))return i&&2===s&&e.raise("Negated character class may contain strings"),s;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Ht.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var i=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return i}else e.raise("Invalid escape");e.pos=t}return null},Ht.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Ht.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Ht.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e))||(e.eat(98)?(e.lastIntValue=8,!0):(e.pos=t,!1));var i=e.current();return!(i<0||i===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(i))&&(!function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(i)&&(e.advance(),e.lastIntValue=i,!0))},Ht.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Ht.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Zt(t)&&95!==t)&&(e.lastIntValue=t%32,e.advance(),!0)},Ht.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Ht.regexp_eatDecimalDigits=function(e){var t=e.pos,i=0;for(e.lastIntValue=0;Zt(i=e.current());)e.lastIntValue=10*e.lastIntValue+(i-48),e.advance();return e.pos!==t},Ht.regexp_eatHexDigits=function(e){var t=e.pos,i=0;for(e.lastIntValue=0;ei(i=e.current());)e.lastIntValue=16*e.lastIntValue+ti(i),e.advance();return e.pos!==t},Ht.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var i=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*i+e.lastIntValue:e.lastIntValue=8*t+i}else e.lastIntValue=t;return!0}return!1},Ht.regexp_eatOctalDigit=function(e){var t=e.current();return ii(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Ht.regexp_eatFixedHexDigits=function(e,t){var i=e.pos;e.lastIntValue=0;for(var s=0;s=this.input.length?this.finishToken(De.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},ni.readToken=function(e){return Se(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},ni.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},ni.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,i=this.input.indexOf("*/",this.pos+=2);if(-1===i&&this.raise(this.pos-2,"Unterminated comment"),this.pos=i+2,this.options.locations)for(var s=void 0,n=t;(s=Ve(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=s;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,i),t,this.pos,e,this.curPosition())},ni.skipLineComment=function(e){for(var t=this.pos,i=this.options.onComment&&this.curPosition(),s=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&Re.test(String.fromCharCode(e))))break e;++this.pos}}},ni.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var i=this.type;this.type=e,this.value=t,this.updateContext(i)},ni.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(De.ellipsis)):(++this.pos,this.finishToken(De.dot))},ni.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(De.assign,2):this.finishOp(De.slash,1)},ni.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),i=1,s=42===e?De.star:De.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++i,s=De.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(De.assign,i+1):this.finishOp(s,i)},ni.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(De.assign,3);return this.finishOp(124===e?De.logicalOR:De.logicalAND,2)}return 61===t?this.finishOp(De.assign,2):this.finishOp(124===e?De.bitwiseOR:De.bitwiseAND,1)},ni.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(De.assign,2):this.finishOp(De.bitwiseXOR,1)},ni.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!Le.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(De.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(De.assign,2):this.finishOp(De.plusMin,1)},ni.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),i=1;return t===e?(i=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+i)?this.finishOp(De.assign,i+1):this.finishOp(De.bitShift,i)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(i=2),this.finishOp(De.relational,i)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},ni.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(De.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(De.arrow)):this.finishOp(61===e?De.eq:De.prefix,1)},ni.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var i=this.input.charCodeAt(this.pos+2);if(i<48||i>57)return this.finishOp(De.questionDot,2)}if(63===t){if(e>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(De.assign,3);return this.finishOp(De.coalesce,2)}}return this.finishOp(De.question,1)},ni.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,Se(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(De.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+We(e)+"'")},ni.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(De.parenL);case 41:return++this.pos,this.finishToken(De.parenR);case 59:return++this.pos,this.finishToken(De.semi);case 44:return++this.pos,this.finishToken(De.comma);case 91:return++this.pos,this.finishToken(De.bracketL);case 93:return++this.pos,this.finishToken(De.bracketR);case 123:return++this.pos,this.finishToken(De.braceL);case 125:return++this.pos,this.finishToken(De.braceR);case 58:return++this.pos,this.finishToken(De.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(De.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(De.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+We(e)+"'")},ni.finishOp=function(e,t){var i=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,i)},ni.readRegexp=function(){for(var e,t,i=this.pos;;){this.pos>=this.input.length&&this.raise(i,"Unterminated regular expression");var s=this.input.charAt(this.pos);if(Le.test(s)&&this.raise(i,"Unterminated regular expression"),e)e=!1;else{if("["===s)t=!0;else if("]"===s&&t)t=!1;else if("/"===s&&!t)break;e="\\"===s}++this.pos}var n=this.input.slice(i,this.pos);++this.pos;var o=this.pos,r=this.readWord1();this.containsEsc&&this.unexpected(o);var a=this.regexpState||(this.regexpState=new qt(this));a.reset(i,n,r),this.validateRegExpFlags(a),this.validateRegExpPattern(a);var l=null;try{l=new RegExp(n,r)}catch(e){}return this.finishToken(De.regexp,{pattern:n,flags:r,value:l})},ni.readInt=function(e,t,i){for(var s=this.options.ecmaVersion>=12&&void 0===t,n=i&&48===this.input.charCodeAt(this.pos),o=this.pos,r=0,a=0,l=0,c=null==t?1/0:t;l=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;a=h,r=r*e+p}}return s&&95===a&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===o||null!=t&&this.pos-o!==t?null:r},ni.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var i=this.readInt(e);return null==i&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(i=oi(this.input.slice(t,this.pos)),++this.pos):Se(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(De.num,i)},ni.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var i=this.pos-t>=2&&48===this.input.charCodeAt(t);i&&this.strict&&this.raise(t,"Invalid number");var s=this.input.charCodeAt(this.pos);if(!i&&!e&&this.options.ecmaVersion>=11&&110===s){var n=oi(this.input.slice(t,this.pos));return++this.pos,Se(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(De.num,n)}i&&/[89]/.test(this.input.slice(t,this.pos))&&(i=!1),46!==s||i||(++this.pos,this.readInt(10),s=this.input.charCodeAt(this.pos)),69!==s&&101!==s||i||(43!==(s=this.input.charCodeAt(++this.pos))&&45!==s||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),Se(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var o,r=(o=this.input.slice(t,this.pos),i?parseInt(o,8):parseFloat(o.replace(/_/g,"")));return this.finishToken(De.num,r)},ni.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},ni.readString=function(e){for(var t="",i=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var s=this.input.charCodeAt(this.pos);if(s===e)break;92===s?(t+=this.input.slice(i,this.pos),t+=this.readEscapedChar(!1),i=this.pos):8232===s||8233===s?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(Oe(s)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(i,this.pos++),this.finishToken(De.string,t)};var ri={};ni.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==ri)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},ni.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw ri;this.raise(e,t)},ni.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var i=this.input.charCodeAt(this.pos);if(96===i||36===i&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==De.template&&this.type!==De.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(De.template,e)):36===i?(this.pos+=2,this.finishToken(De.dollarBraceL)):(++this.pos,this.finishToken(De.backQuote));if(92===i)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(Oe(i)){switch(e+=this.input.slice(t,this.pos),++this.pos,i){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(i)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},ni.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var s=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(s,8);return n>255&&(s=s.slice(0,-1),n=parseInt(s,8)),this.pos+=s.length-1,t=this.input.charCodeAt(this.pos),"0"===s&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-s.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return Oe(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},ni.readHexChar=function(e){var t=this.pos,i=this.readInt(16,e);return null===i&&this.invalidStringToken(t,"Bad character escape sequence"),i},ni.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,i=this.pos,s=this.options.ecmaVersion>=6;this.pos":9,"<=":9,">=":9,in:9,instanceof:9,"<<":10,">>":10,">>>":10,"+":11,"-":11,"*":12,"%":12,"/":12,"**":13},mi=17,gi={ArrayExpression:20,TaggedTemplateExpression:20,ThisExpression:20,Identifier:20,PrivateIdentifier:20,Literal:18,TemplateLiteral:20,Super:20,SequenceExpression:20,MemberExpression:19,ChainExpression:19,CallExpression:19,NewExpression:19,ArrowFunctionExpression:mi,ClassExpression:mi,FunctionExpression:mi,ObjectExpression:mi,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function fi(e,t){const{generator:i}=e;if(e.write("("),null!=t&&t.length>0){i[t[0].type](t[0],e);const{length:s}=t;for(let n=1;n0){e.write(s);for(let t=1;t0){i.VariableDeclarator(s[0],e);for(let t=1;t0){t.write(s),n&&null!=e.comments&&xi(t,e.comments,o,s);const{length:a}=r;for(let e=0;e0){for(;o0&&t.write(", ");const e=i[o],s=e.type[6];if("D"===s)t.write(e.local.name,e),o++;else{if("N"!==s)break;t.write("* as "+e.local.name,e),o++}}if(o0){t.write(" with { ");for(let e=0;e0)for(let e=0;;){const n=i[e],{name:o}=n.local;if(t.write(o,n),o!==n.exported.name&&t.write(" as "+n.exported.name),!(++e0){t.write(" with { ");for(let i=0;i0){t.write(" with { ");for(let i=0;i "),"O"===e.body.type[0]?(t.write("("),this.ObjectExpression(e.body,t),t.write(")")):this[e.body.type](e.body,t)},ThisExpression(e,t){t.write("this",e)},Super(e,t){t.write("super",e)},RestElement:Si=function(e,t){t.write("..."),this[e.argument.type](e.argument,t)},SpreadElement:Si,YieldExpression(e,t){t.write(e.delegate?"yield*":"yield"),e.argument&&(t.write(" "),this[e.argument.type](e.argument,t))},AwaitExpression(e,t){t.write("await ",e),bi(t,e.argument,e)},TemplateLiteral(e,t){const{quasis:i,expressions:s}=e;t.write("`");const{length:n}=s;for(let e=0;e0){const{elements:i}=e,{length:s}=i;for(let e=0;;){const n=i[e];if(null!=n&&this[n.type](n,t),!(++e0){t.write(s),n&&null!=e.comments&&xi(t,e.comments,o,s);const r=","+s,{properties:a}=e,{length:l}=a;for(let e=0;;){const i=a[e];if(n&&null!=i.comments&&xi(t,i.comments,o,s),t.write(o),this[i.type](i,t),!(++e0){const{properties:i}=e,{length:s}=i;for(let e=0;this[i[e].type](i[e],t),++e1)&&("U"!==n[0]||"n"!==n[1]&&"p"!==n[1]||!s.prefix||s.operator[0]!==i||"+"!==i&&"-"!==i)||t.write(" "),o?(t.write(i.length>1?" (":"("),this[n](s,t),t.write(")")):this[n](s,t)}else this[e.argument.type](e.argument,t),t.write(e.operator)},UpdateExpression(e,t){e.prefix?(t.write(e.operator),this[e.argument.type](e.argument,t)):(this[e.argument.type](e.argument,t),t.write(e.operator))},AssignmentExpression(e,t){this[e.left.type](e.left,t),t.write(" "+e.operator+" "),this[e.right.type](e.right,t)},AssignmentPattern(e,t){this[e.left.type](e.left,t),t.write(" = "),this[e.right.type](e.right,t)},BinaryExpression:ki=function(e,t){const i="in"===e.operator;i&&t.write("("),bi(t,e.left,e,!1),t.write(" "+e.operator+" "),bi(t,e.right,e,!0),i&&t.write(")")},LogicalExpression:ki,ConditionalExpression(e,t){const{test:i}=e,s=t.expressionsPrecedence[i.type];s===mi||s<=t.expressionsPrecedence.ConditionalExpression?(t.write("("),this[i.type](i,t),t.write(")")):this[i.type](i,t),t.write(" ? "),this[e.consequent.type](e.consequent,t),t.write(" : "),this[e.alternate.type](e.alternate,t)},NewExpression(e,t){t.write("new ");const i=t.expressionsPrecedence[e.callee.type];i===mi||i0&&(this.lineEndSize>0&&(1===s.length?e[i-1]===s:e.endsWith(s))?(this.line+=this.lineEndSize,this.column=0):this.column+=i)}toString(){return this.output}}var Ai=Object.defineProperty,Di=(e,t,i)=>((e,t,i)=>t in e?Ai(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Li{constructor(){Di(this,"scopes",[]),Di(this,"scopeTypes",[]),Di(this,"scopeCounts",new Map),Di(this,"contextBoundVars",new Set),Di(this,"arrayPatternElements",new Set),Di(this,"rootParams",new Set),Di(this,"varKinds",new Map),Di(this,"loopVars",new Set),Di(this,"loopVarNames",new Map),Di(this,"paramIdCounter",0),Di(this,"cacheIdCounter",0),Di(this,"tempVarCounter",0),this.pushScope("glb")}get nextParamIdArg(){return{type:"Identifier",name:`'p${this.paramIdCounter++}'`}}get nextCacheIdArg(){return{type:"Identifier",name:`'cache_${this.cacheIdCounter++}'`}}pushScope(e){this.scopes.push(new Map),this.scopeTypes.push(e),this.scopeCounts.set(e,(this.scopeCounts.get(e)||0)+1)}popScope(){this.scopes.pop(),this.scopeTypes.pop()}getCurrentScopeType(){return this.scopeTypes[this.scopeTypes.length-1]}getCurrentScopeCount(){return this.scopeCounts.get(this.getCurrentScopeType())||1}addContextBoundVar(e,t=!1){this.contextBoundVars.add(e),t&&this.rootParams.add(e)}addArrayPatternElement(e){this.arrayPatternElements.add(e)}isContextBound(e){return this.contextBoundVars.has(e)}isArrayPatternElement(e){return this.arrayPatternElements.has(e)}isRootParam(e){return this.rootParams.has(e)}addLoopVariable(e,t){this.loopVars.add(e),this.loopVarNames.set(e,t)}getLoopVariableName(e){return this.loopVarNames.get(e)}isLoopVariable(e){return this.loopVars.has(e)}addVariable(e,t){if(this.isContextBound(e))return e;const i=this.scopes[this.scopes.length-1],s=this.scopeTypes[this.scopeTypes.length-1],n=`${s}${this.scopeCounts.get(s)||1}_${e}`;return i.set(e,n),this.varKinds.set(n,t),n}getVariable(e){if(this.loopVars.has(e)){const t=this.loopVarNames.get(e);if(t)return[t,"let"]}if(this.isContextBound(e))return[e,"let"];for(let t=this.scopes.length-1;t>=0;t--){const i=this.scopes[t];if(i.has(e)){const t=i.get(e);return[t,this.varKinds.get(t)||"let"]}}return[e,"let"]}generateTempVar(){return"temp_"+ ++this.tempVarCounter}}//!!!Warning!!! this code is not clean, it was initially written as a PoC then used as transpiler for PineTS -const Ni="$",Oi={type:"Identifier",name:"undefined"};function Vi(e,t){if(e.computed&&"Identifier"===e.property.type){if(t.isLoopVariable(e.property.name))return;if(!t.isContextBound(e.property.name)){const[i,s]=t.getVariable(e.property.name);e.property={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},e.property={type:"MemberExpression",object:e.property,property:{type:"Literal",value:0},computed:!0}}}if(e.computed&&"Identifier"===e.object.type){if(t.isLoopVariable(e.object.name))return;if(!t.isContextBound(e.object.name)){const[i,s]=t.getVariable(e.object.name);e.object={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}if("MemberExpression"===e.property.type){const i=e.property;i._indexTransformed||(Vi(i,t),i._indexTransformed=!0)}}}function Ri(e,t,i){if(e.object&&"Identifier"===e.object.type&&"Math"===e.object.name)return;const s="if"==i.getCurrentScopeType(),n="els"==i.getCurrentScopeType(),o="for"==i.getCurrentScopeType();!s&&!n&&!o&&e.object&&"Identifier"===e.object.type&&i.isContextBound(e.object.name)&&!i.isRootParam(e.object.name)||e._indexTransformed||(Vi(e,i),e._indexTransformed=!0)}function Bi(e,t){e.declarations.forEach((i=>{"na"==i.init.name&&(i.init.name="NaN");const s=i.init&&"MemberExpression"===i.init.type&&i.init.object&&("context"===i.init.object.name||i.init.object.name===Ni||"context2"===i.init.object.name),n=i.init&&"MemberExpression"===i.init.type&&i.init.object?.object&&("context"===i.init.object.object.name||i.init.object.object.name===Ni||"context2"===i.init.object.object.name),o=i.init&&"ArrowFunctionExpression"===i.init.type;if(s)return i.id.name&&t.addContextBoundVar(i.id.name),i.id.properties&&i.id.properties.forEach((e=>{e.key.name&&t.addContextBoundVar(e.key.name)})),void(i.init.object.name=Ni);if(n)return i.id.name&&t.addContextBoundVar(i.id.name),i.id.properties&&i.id.properties.forEach((e=>{e.key.name&&t.addContextBoundVar(e.key.name)})),void(i.init.object.object.name=Ni);o&&i.init.params.forEach((e=>{"Identifier"===e.type&&t.addContextBoundVar(e.name)}));const r=t.addVariable(i.id.name,e.kind),a=e.kind;i.init&&!o&&("CallExpression"===i.init.type&&"MemberExpression"===i.init.callee.type&&i.init.callee.object&&"Identifier"===i.init.callee.object.type&&t.isContextBound(i.init.callee.object.name)?qi(i.init,t):li(i.init,{parent:i.init},{Identifier(e,i){e.parent=i.parent,$i(e,t);const s=e.parent&&"BinaryExpression"===e.parent.type,n=e.parent&&"ConditionalExpression"===e.parent.type;"Identifier"===e.type&&(s||n)&&Object.assign(e,{type:"MemberExpression",object:{type:"Identifier",name:e.name},property:{type:"Literal",value:0},computed:!0})},CallExpression(e,i,s){"Identifier"===e.callee.type&&(e.callee.parent=e),e.arguments.forEach((t=>{"Identifier"===t.type&&(t.parent=e)})),qi(e,t),e.arguments.forEach((t=>s(t,{parent:e})))},BinaryExpression(e,t,i){"Identifier"===e.left.type&&(e.left.parent=e),"Identifier"===e.right.type&&(e.right.parent=e),i(e.left,{parent:e}),i(e.right,{parent:e})},MemberExpression(e,i,s){"Identifier"===e.object.type&&(e.object.parent=e),"Identifier"===e.property.type&&(e.property.parent=e),Vi(e,t),e.object&&s(e.object,{parent:e})}}));const l={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:a},computed:!1},property:{type:"Identifier",name:r},computed:!1},c=t.isArrayPatternElement(i.id.name),h=!c&&i.init&&"MemberExpression"===i.init.type&&i.init.computed&&i.init.property&&("Literal"===i.init.property.type||"MemberExpression"===i.init.property.type);"MemberExpression"===i.init?.property?.type&&(i.init.property._indexTransformed||(Vi(i.init.property,t),i.init.property._indexTransformed=!0));const p={type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:l,right:i.init?o||c?i.init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:"init"},computed:!1},arguments:h?[l,i.init.object,i.init.property]:[l,i.init]}:{type:"Identifier",name:"undefined"}}};if(c){p.expression.right.object.property.name+=`?.[0][${i.init.property.value}]`;const e=p.expression.right.object;p.expression.right={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:"init"},computed:!1},arguments:[l,e]}}o&&(t.pushScope("fn"),li(i.init.body,t,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},IfStatement(e,t,i){t.pushScope("if"),i(e.consequent,t),e.alternate&&(t.pushScope("els"),i(e.alternate,t),t.popScope()),t.popScope()},VariableDeclaration(e,t){Bi(e,t)},Identifier(e,t){$i(e,t)},AssignmentExpression(e,t){Gi(e,t)}}),t.popScope()),Object.assign(e,p)}))}function $i(e,t){if(e.name!==Ni){if("Math"===e.name||"NaN"===e.name||"undefined"===e.name||"Infinity"===e.name||"null"===e.name||e.name.startsWith("'")&&e.name.endsWith("'")||e.name.startsWith('"')&&e.name.endsWith('"')||e.name.startsWith("`")&&e.name.endsWith("`")||t.isLoopVariable(e.name)||t.isContextBound(e.name)&&!t.isRootParam(e.name))return;const i=e.parent&&"MemberExpression"===e.parent.type&&e.parent.object===e&&t.isContextBound(e.name),s=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&"MemberExpression"===e.parent.callee.type&&"param"===e.parent.callee.property.name;e.parent&&"AssignmentExpression"===e.parent.type&&e.parent.left;const n=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&"MemberExpression"===e.parent.callee.type&&t.isContextBound(e.parent.callee.object.name),o=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed,r=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.property===e&&e.parent.parent&&"CallExpression"===e.parent.parent.type&&e.parent.parent.callee&&"MemberExpression"===e.parent.parent.callee.type&&t.isContextBound(e.parent.parent.callee.object.name),a=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee===e;if(i||s||n||r||a){if(a)return;const[i,s]=t.getVariable(e.name);return void Object.assign(e,{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1})}const[l,c]=t.getVariable(e.name),h={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:c},computed:!1},property:{type:"Identifier",name:l},computed:!1};e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.object===e||o?Object.assign(e,h):Object.assign(e,{type:"MemberExpression",object:h,property:{type:"Literal",value:0},computed:!0})}}function Gi(e,t){if("Identifier"===e.left.type){const[i,s]=t.getVariable(e.left.name),n={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1};e.left={type:"MemberExpression",object:n,property:{type:"Literal",value:0},computed:!0}}li(e.right,{parent:e.right,inNamespaceCall:!1},{Identifier(e,i,s){"na"==e.name&&(e.name="NaN"),e.parent=i.parent,$i(e,t);const n=e.parent&&"BinaryExpression"===e.parent.type,o=e.parent&&"ConditionalExpression"===e.parent.type,r=t.isContextBound(e.name)&&!t.isRootParam(e.name),a=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.object===e,l=e.parent&&e.parent._isParamCall,c=e.parent&&"MemberExpression"===e.parent.type,h="NaN"===e.name;(r||o||n)&&("MemberExpression"===e.type?Vi(e,t):"Identifier"===e.type&&!c&&!a&&!l&&!h&&Xi(e))},MemberExpression(e,i,s){Vi(e,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})},CallExpression(e,i,s){const n=e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&t.isContextBound(e.callee.object.name);qi(e,t),e.arguments.forEach((t=>s(t,{parent:e,inNamespaceCall:n||i.inNamespaceCall})))}})}function Fi(e,t){const i=t.getCurrentScopeType();if(e.argument){if("ArrayExpression"===e.argument.type)e.argument.elements=e.argument.elements.map((e=>{if("Identifier"===e.type){if(t.isContextBound(e.name)&&!t.isRootParam(e.name))return{type:"MemberExpression",object:e,property:{type:"Literal",value:0},computed:!0};const[i,s]=t.getVariable(e.name);return{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},property:{type:"Literal",value:0},computed:!0}}return"MemberExpression"===e.type?(e.computed&&"Identifier"===e.object.type&&t.isContextBound(e.object.name)&&!t.isRootParam(e.object.name)||Ri(e,0,t),e):e})),e.argument={type:"ArrayExpression",elements:[e.argument]};else if("BinaryExpression"===e.argument.type)li(e.argument,t,{Identifier(e,t){$i(e,t),"Identifier"===e.type&&Xi(e)},MemberExpression(e){Ri(e,0,t)}});else if("ObjectExpression"===e.argument.type)e.argument.properties=e.argument.properties.map((e=>{if(e.shorthand){const[i,s]=t.getVariable(e.value.name);return{type:"Property",key:{type:"Identifier",name:e.key.name},value:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},kind:"init",method:!1,shorthand:!1,computed:!1}}return e}));else if("Identifier"===e.argument.type){const[i,s]=t.getVariable(e.argument.name);e.argument={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},e.argument={type:"MemberExpression",object:e.argument,property:{type:"Literal",value:0},computed:!0}}"fn"===i&&(e.argument={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:"precision"}},arguments:[e.argument]})}}function ji(e,t){if("Identifier"===e.type){if("na"===e.name)return e.name="NaN",e;if(t.isLoopVariable(e.name))return e;if(t.isRootParam(e.name)){const[i,s]=t.getVariable(e.name);return{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}if(t.isContextBound(e.name))return e;const[i,s]=t.getVariable(e.name);return{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}return e}function Ui(e,t,i){const s=zi(e.argument,t,i);return{type:"UnaryExpression",operator:e.operator,prefix:e.prefix,argument:s,start:e.start,end:e.end}}function zi(e,t,i=""){switch(e.type){case"BinaryExpression":return Hi(e,t,i);case"MemberExpression":return{type:"MemberExpression",object:"Identifier"===e.object.type?ji(e.object,t):e.object,property:e.property,computed:e.computed};case"Identifier":return t.isLoopVariable(e.name)||e.parent&&"MemberExpression"===e.parent.type&&e.parent.property===e?e:{type:"MemberExpression",object:ji(e,t),property:{type:"Literal",value:0},computed:!0};case"UnaryExpression":return Ui(e,t,i)}return e}function Hi(e,t,i){const s=zi(e.left,t,i),n=zi(e.right,t,i),o={type:"BinaryExpression",operator:e.operator,left:s,right:n,start:e.start,end:e.end};return li(o,t,{CallExpression(e,t){e._transformed||qi(e,t)},MemberExpression(e){Ri(e,0,t)}}),o}function Wi(e,t,i){switch(e?.type){case"BinaryExpression":e=Hi(e,i,t);break;case"LogicalExpression":e=function(e,t,i){const s=zi(e.left,t,i),n=zi(e.right,t,i),o={type:"LogicalExpression",operator:e.operator,left:s,right:n,start:e.start,end:e.end};return li(o,t,{CallExpression(e,t){e._transformed||qi(e,t)}}),o}(e,i,t);break;case"ConditionalExpression":return function(e,t,i){return li(e,{parent:e,inNamespaceCall:!1},{Identifier(e,i,s){if("NaN"==e.name)return;if("na"==e.name)return void(e.name="NaN");e.parent=i.parent,$i(e,t);const n=e.parent&&"BinaryExpression"===e.parent.type;(e.parent&&"ConditionalExpression"===e.parent.type||n)&&("MemberExpression"===e.type?Vi(e,t):"Identifier"===e.type&&Xi(e))},MemberExpression(e,i,s){Vi(e,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})},CallExpression(e,i,s){const n=e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&t.isContextBound(e.callee.object.name);qi(e,t),e.arguments.forEach((t=>s(t,{parent:e,inNamespaceCall:n||i.inNamespaceCall})))}}),{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:i},property:{type:"Identifier",name:"param"}},arguments:[e,Oi,t.nextParamIdArg],_transformed:!0,_isParamCall:!0}}(e,i,t);case"UnaryExpression":e=Ui(e,i,t)}if("MemberExpression"===e.type&&e.computed&&e.property){return{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:["Identifier"===e.object.type&&i.isContextBound(e.object.name)&&!i.isRootParam(e.object.name)?e.object:ji(e.object,i),"Identifier"!==e.property.type||i.isContextBound(e.property.name)||i.isLoopVariable(e.property.name)?e.property:ji(e.property,i),i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}if("ObjectExpression"===e.type&&(e.properties=e.properties.map((e=>{if(e.value.name){const[t,s]=i.getVariable(e.value.name);return{type:"Property",key:{type:"Identifier",name:e.key.name},value:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Ni},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:t},computed:!1},kind:"init",method:!1,shorthand:!1,computed:!1}}return e}))),"Identifier"===e.type){if("na"===e.name)return e.name="NaN",e;if(i.isContextBound(e.name)&&!i.isRootParam(e.name))return{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:[e,Oi,i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}return"CallExpression"===e?.type&&qi(e,i),{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:["Identifier"===e.type?ji(e,i):e,Oi,i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}function qi(e,t,i){if(!e._transformed){if(e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&(t.isContextBound(e.callee.object.name)||"math"===e.callee.object.name||"ta"===e.callee.object.name)){const i=e.callee.object.name;e.arguments=e.arguments.map((e=>e._isParamCall?e:Wi(e,i,t))),e._transformed=!0}else e.callee&&"Identifier"===e.callee.type&&(e.arguments=e.arguments.map((e=>e._isParamCall?e:Wi(e,Ni,t))),e._transformed=!0);e.arguments.forEach((e=>{li(e,t,{Identifier(e,i,s){e.parent=i.parent,$i(e,t);const n=e.parent&&"BinaryExpression"===e.parent.type;(e.parent&&"ConditionalExpression"===e.parent.type||n)&&("MemberExpression"===e.type?Vi(e,t):"Identifier"===e.type&&Xi(e))},CallExpression(e,t,i){e._transformed||qi(e,t)},MemberExpression(e,i,s){Ri(e,0,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})}})}))}}function Xi(e,t){Object.assign(e,{type:"MemberExpression",object:{type:"Identifier",name:e.name,start:e.start,end:e.end},property:{type:"Literal",value:0},computed:!0,_indexTransformed:!0})}function Ji(e,t,i){if(e.init&&"VariableDeclaration"===e.init.type){const i=e.init.declarations[0],s=i.id.name;t.addLoopVariable(s,s),e.init={type:"VariableDeclaration",kind:e.init.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:s},init:i.init}]},i.init&&li(i.init,t,{Identifier(e,i){t.isLoopVariable(e.name)||(t.pushScope("for"),$i(e,i),t.popScope())},MemberExpression(e){t.pushScope("for"),Ri(e,0,t),t.popScope()}})}e.test&&li(e.test,t,{Identifier(e,i){!t.isLoopVariable(e.name)&&!e.computed&&(t.pushScope("for"),$i(e,i),"Identifier"===e.type&&(e.computed=!0,Xi(e)),t.popScope())},MemberExpression(e){t.pushScope("for"),Ri(e,0,t),t.popScope()}}),e.update&&li(e.update,t,{Identifier(e,i){t.isLoopVariable(e.name)||(t.pushScope("for"),$i(e,i),t.popScope())}}),t.pushScope("for"),i(e.body,t),t.popScope()}function Yi(e,t,i){e.test&&(t.pushScope("if"),function(e,t){li(e,t,{MemberExpression(e){Ri(e,0,t)},CallExpression(e,t){qi(e,t)},Identifier(e,i){$i(e,i);const s="if"===t.getCurrentScopeType();t.isContextBound(e.name)&&!t.isRootParam(e.name)&&s&&Xi(e)}})}(e.test,t),t.popScope()),t.pushScope("if"),i(e.consequent,t),t.popScope(),e.alternate&&(t.pushScope("els"),i(e.alternate,t),t.popScope())}function Ki(e){let t="function"==typeof e?e.toString():e;const i=(s=t.trim(),it.parse(s,{ecmaVersion:"latest",sourceType:"module"}));var s;!function(e){li(e,null,{VariableDeclaration(e,t,i){e.declarations&&e.declarations.length>0&&e.declarations.forEach((t=>{if(t.init&&"ArrowFunctionExpression"===t.init.type&&0!==t.init.start){const i={type:"FunctionDeclaration",id:t.id,params:t.init.params,body:"BlockStatement"===t.init.body.type?t.init.body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:t.init.body}]},async:t.init.async,generator:!1};Object.assign(e,i)}})),e.body&&e.body.body&&e.body.body.forEach((e=>i(e,t)))}})}(i);const n=new Li;let o;(function(e,t){ai(e,{VariableDeclaration(e){e.declarations.forEach((e=>{const i=e.init&&"MemberExpression"===e.init.type&&e.init.object&&("context"===e.init.object.name||e.init.object.name===Ni||"context2"===e.init.object.name),s=e.init&&"MemberExpression"===e.init.type&&e.init.object?.object&&("context"===e.init.object.object.name||e.init.object.object.name===Ni||"context2"===e.init.object.object.name);(i||s)&&(e.id.name&&t.addContextBoundVar(e.id.name),e.id.properties&&e.id.properties.forEach((e=>{e.key.name&&t.addContextBoundVar(e.key.name)})))}))}})})(i,n),ai(i,{FunctionDeclaration(e){!function(e,t){e.params.forEach((e=>{"Identifier"===e.type&&t.addContextBoundVar(e.name,!1)})),e.body&&"BlockStatement"===e.body.type&&(t.pushScope("fn"),li(e.body,t,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},ReturnStatement(e,t){Fi(e,t)},VariableDeclaration(e,t){Bi(e,t)},Identifier(e,t){$i(e,t)},CallExpression(e,t){qi(e,t),e.arguments.forEach((e=>{"BinaryExpression"===e.type&&li(e,t,{CallExpression(e,t){qi(e,t)},MemberExpression(e){Ri(e,0,t)}})}))},MemberExpression(e){Ri(e,0,t)},AssignmentExpression(e,t){Gi(e,t)},ForStatement(e,t,i){Ji(e,t,i)},IfStatement(e,t,i){Yi(e,t,i)},BinaryExpression(e,t,i){li(e,t,{CallExpression(e,t){qi(e,t)},MemberExpression(e){Ri(e,0,t)}})}}),t.popScope())}(e,n)},ArrowFunctionExpression(e){const t=0===e.start;t&&e.params&&e.params.length>0&&(o=e.params[0].name,e.params[0].name=Ni),function(e,t,i=!1){e.params.forEach((e=>{"Identifier"===e.type&&t.addContextBoundVar(e.name,i)}))}(e,n,t)},VariableDeclaration(e){e.declarations.forEach((t=>{if("ArrayPattern"===t.id.type){const i=n.generateTempVar(),s={type:"VariableDeclaration",kind:e.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:i},init:t.init}]};t.id.elements?.forEach((e=>{"Identifier"===e.type&&n.addArrayPatternElement(e.name)}));const o=t.id.elements.map(((t,s)=>({type:"VariableDeclaration",kind:e.kind,declarations:[{type:"VariableDeclarator",id:t,init:{type:"MemberExpression",object:{type:"Identifier",name:i},property:{type:"Literal",value:s},computed:!0}}]})));Object.assign(e,{type:"BlockStatement",body:[s,...o]})}}))},ForStatement(e){}}),li(i,n,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},ReturnStatement(e,t){Fi(e,t)},VariableDeclaration(e,t){Bi(e,t)},Identifier(e,t){$i(e,t)},CallExpression(e,t){qi(e,t)},MemberExpression(e){Ri(e,0,n)},AssignmentExpression(e,t){Gi(e,t)},FunctionDeclaration(e,t){},ForStatement(e,t,i){Ji(e,t,i)},IfStatement(e,t,i){Yi(e,t,i)}});const r=function(e,t){const i=new Ii(t);return i.generator[e.type](e,i),i.output}(i);return new Function("",`return ${r}`)(this)}var Qi=Object.defineProperty,Zi=(e,t,i)=>((e,t,i)=>t in e?Qi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class es{constructor(e,t,i,s,n,o,r){this.source=e,this.tickerId=t,this.timeframe=i,this.limit=s,this.sDate=n,this.eDate=o,this.title=r,Zi(this,"data",[]),Zi(this,"open",[]),Zi(this,"high",[]),Zi(this,"low",[]),Zi(this,"close",[]),Zi(this,"volume",[]),Zi(this,"hl2",[]),Zi(this,"hlc3",[]),Zi(this,"ohlc4",[]),Zi(this,"openTime",[]),Zi(this,"closeTime",[]),Zi(this,"_periods"),Zi(this,"pineTSCode"),Zi(this,"fn"),Zi(this,"_readyPromise",null),Zi(this,"_ready",!1),this._readyPromise=new Promise((a=>{this.loadMarketData(e,t,i,s,n,o,r).then((e=>{const t=e.reverse();this._periods=t.length,this.data=t;const i=t.map((e=>e.open)),s=t.map((e=>e.close)),n=t.map((e=>e.high)),o=t.map((e=>e.low)),r=t.map((e=>e.volume)),l=t.map((e=>(e.high+e.low+e.close)/3)),c=t.map((e=>(e.high+e.low)/2)),h=t.map((e=>(e.high+e.low+e.open+e.close)/4)),p=t.map((e=>e.openTime)),d=t.map((e=>e.closeTime));this.open=i,this.close=s,this.high=n,this.low=o,this.volume=r,this.hl2=c,this.hlc3=l,this.ohlc4=h,this.openTime=p,this.closeTime=d,this._ready=!0,a(!0)}))}))}get periods(){return this._periods}async loadMarketData(e,t,i,s,n,o,r){return Array.isArray(e)?e:e.getMarketData(t,i,s,n,o,r)}async ready(){if(this._ready)return!0;if(!this._readyPromise)throw new Error("PineTS is not ready");return this._readyPromise}updateData(e){if(!e)throw new Error("Invalid data: newData must be a valid object.");this.data=[e,...this.data],this._periods=this.data.length,this.open=[e.open,...this.open],this.close=[e.close,...this.close],this.high=[e.high,...this.high],this.low=[e.low,...this.low],this.volume=[e.volume,...this.volume],this.hl2=[(e.high+e.low)/2,...this.hl2],this.hlc3=[(e.high+e.low+e.close)/3,...this.hlc3],this.ohlc4=[(e.high+e.low+e.open+e.close)/4,...this.ohlc4],this.openTime=[e.openTime,...this.openTime],this.closeTime=[e.closeTime,...this.closeTime]}async run(e,t,i){if(await this.ready(),t||(t=this._periods),!this.pineTSCode&&!e)throw new Error("Invalid PineTS Code: No pineTSCode supplied/stored.");e=e||this.pineTSCode;const s=new ws({marketData:this.data,source:this.source,tickerId:this.tickerId,timeframe:this.timeframe,limit:this.limit,sDate:this.sDate,eDate:this.eDate,title:this.title});if(s.pineTSCode=e,s.useTACache=i,!this.fn||this.pineTSCode!==e){const t=Ki.bind(this);this.fn=t(e),this.pineTSCode=e}const n=this.fn,o=["const","var","let","params"];for(let e=this._periods-t,i=t-1;e((e,t,i)=>t in e?ts(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class ss{constructor(e){this.context=e,is(this,"script"),is(this,"pane",0),is(this,"color",{param:(e,t=0)=>Array.isArray(e)?e[t]:e,rgb:(e,t,i,s)=>s?`rgba(${e}, ${t}, ${i}, ${s})`:`rgb(${e}, ${t}, ${i})`,new:(e,t)=>{if(e&&e.startsWith("#")){const i=e.slice(1),s=parseInt(i.slice(0,2),16),n=parseInt(i.slice(2,4),16),o=parseInt(i.slice(4,6),16);return t?`rgba(${s}, ${n}, ${o}, ${t})`:`rgb(${s}, ${n}, ${o})`}return t?`rgba(${e}, ${t})`:e},white:"white",lime:"lime",green:"green",red:"red",maroon:"maroon",black:"black",gray:"gray",blue:"blue"})}extractPlotOptions(e){const t={};for(let i in e)Array.isArray(e[i])?t[i]=e[i][0]:t[i]=e[i];return t}indicator(e,t,i){this.script=e??t??"PineTS Script",i&&(this.pane=i.overlay?0:1)}plotchar(e,t,i){this.context.plots[t]||(this.context.plots[t]={data:[],options:this.extractPlotOptions(i),title:t}),this.context.plots[t].data.push({time:this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,value:e[0],options:{...this.extractPlotOptions(i),style:"char"}})}plot(e,t,i){this.script&&(i.group=this.script),this.context.plots[t]||(this.context.plots[t]={data:[],options:this.extractPlotOptions(i),title:t,pane:this.pane}),this.context.plots[t].data.push({time:this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,value:e[0],options:this.extractPlotOptions(i)})}na(e){return Array.isArray(e)?isNaN(e[0]):isNaN(e)}nz(e,t=0){const i=Array.isArray(e)?e[0]:e,s=Array.isArray(e)?t[0]:t;return isNaN(i)?s:i}plotcandle(e,t,i,s,n,o){this.script&&(o.group=this.script),this.context.candles[n]||(this.context.candles[n]={data:[],options:this.extractPlotOptions(o),title:n,pane:this.pane});const r=this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,a=e[0],l=t[0],c=i[0],h=s[0];this.context.candles[n].data.push({time:r,open:a,high:l,low:c,close:h,pane:this.pane,options:this.extractPlotOptions(o)})}plotbar(e,t,i,s,n,o){this.script&&(o.group=this.script),this.context.bars[n]||(this.context.bars[n]={data:[],options:this.extractPlotOptions(o),title:n,pane:this.pane});const r=this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,a=e[0],l=t[0],c=i[0],h=s[0];this.context.bars[n].data.push({time:r,open:a,high:l,low:c,close:h,pane:this.pane,options:this.extractPlotOptions(o)})}fill(e,t,i){this.context.fills[e]||(this.context.fills[e]={plot1:e,plot2:t,options:this.extractPlotOptions(i)})}}class ns{constructor(e){this.context=e}param(e,t=0){return Array.isArray(e)?[e[t]]:[e]}any(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}int(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}float(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}bool(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}string(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}timeframe(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}time(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}price(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}session(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}source(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}symbol(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}text_area(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}enum(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}color(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}}var os=Object.defineProperty,rs=(e,t,i)=>((e,t,i)=>t in e?os(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);class as{constructor(e){this.context=e,rs(this,"_cache",{})}param(e,t,i){return this.context.params[i]||(this.context.params[i]=[]),Array.isArray(e)?t?(this.context.params[i]=e.slice(t),this.context.params[i].length=e.length,this.context.params[i]):(this.context.params[i]=e.slice(0),this.context.params[i]):(this.context.params[i][0]=e,this.context.params[i])}abs(e){return Math.abs(e[0])}pow(e,t){return Math.pow(e[0],t[0])}sqrt(e){return Math.sqrt(e[0])}log(e){return Math.log(e[0])}ln(e){return Math.log(e[0])}exp(e){return Math.exp(e[0])}floor(e){return Math.floor(e[0])}ceil(e){return Math.ceil(e[0])}round(e){return Math.round(e[0])}random(){return Math.random()}max(...e){const t=e.map((e=>Array.isArray(e)?e[0]:e));return Math.max(...t)}min(...e){const t=e.map((e=>Array.isArray(e)?e[0]:e));return Math.min(...t)}sum(e,t){const i=Array.isArray(t)?t[0]:t;return Array.isArray(e)?e.slice(0,i).reduce(((e,t)=>e+t),0):e}sin(e){return Math.sin(e[0])}cos(e){return Math.cos(e[0])}tan(e){return Math.tan(e[0])}acos(e){return Math.acos(e[0])}asin(e){return Math.asin(e[0])}atan(e){return Math.atan(e[0])}avg(...e){const t=e.map((e=>Array.isArray(e)?e[0]:e));return t.reduce(((e,t)=>(Array.isArray(e)?e[0]:e)+(Array.isArray(t)?t[0]:t)),0)/t.length}}var ls=Object.defineProperty,cs=(e,t,i)=>((e,t,i)=>t in e?ls(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);const hs=["1","3","5","15","30","45","60","120","180","240","D","W","M"];class ps{constructor(e){this.context=e,cs(this,"_cache",{})}param(e,t,i){return this.context.params[i]||(this.context.params[i]=[]),Array.isArray(e)?(this.context.params[i]=t?e.slice(t):e.slice(0),[e[t],i]):(this.context.params[i][0]=e,[e,i])}async security(e,t,i,s=!1,n=!1,o=!1,r=null,a=null){const l=e[0],c=t[0],h=i[0],p=i[1],d=hs.indexOf(this.context.timeframe),u=hs.indexOf(c);if(-1==d||-1==u)throw new Error("Invalid timeframe");if(d>u)throw new Error("Only higher timeframes are supported for now");if(d===u)return h;const m=this.context.data.openTime[0],g=this.context.data.closeTime[0];if(this.context.cache[p]){const e=this.context.cache[p],t=this._findSecContextIdx(m,g,e.data.openTime,e.data.closeTime,n);return-1==t?NaN:e.params[p][t]}const f=await new es(this.context.source,l,c,this.context.limit||1e3,this.context.sDate,this.context.eDate).run(this.context.pineTSCode);this.context.cache[p]=f;const y=this._findSecContextIdx(m,g,f.data.openTime,f.data.closeTime,n);return-1==y?NaN:f.params[p][y]}_findSecContextIdx(e,t,i,s,n=!1){for(let o=0;o2*e-n[t])),r=Math.floor(Math.sqrt(t));return gs(o,r)}(e.slice(0).reverse(),i),n=this.context.idx;return this.context.precision(s[n])}rma(e,t){const i=Array.isArray(t)?t[0]:t,s=function(e,t){const i=new Array(e.length).fill(NaN),s=1/t;let n=0;for(let i=0;i0?i:0,n[t]=i<0?-i:0}let o=0,r=0;for(let e=1;e<=t;e++)o+=s[e],r+=n[e];o/=t,r/=t,i[t]=0===r?100:100-100/(1+o/r);for(let a=t+1;ae-t)),o=Math.floor(t/2);i[s]=t%2==0?(n[o-1]+n[o])/2:n[o]}return i}(e.slice(0).reverse(),i),n=this.context.idx;return this.context.precision(s[n])}stdev(e,t,i=!0){const s=Array.isArray(t)?t[0]:t,n=Array.isArray(i)?i[0]:i,o=function(e,t,i=!0){const s=new Array(e.length).fill(NaN),n=ms(e,t);for(let o=t-1;op?c[e]=t:c[e]=p;let s=h[e];s>d||i[e-1]c[e]?(a[e]=1,r[e]=h[e]):(a[e]=-1,r[e]=c[e]):i[e]e+t),0)/t,n=p.reduce(((e,t)=>e+t*t),0)/t-i*i,l=Math.sqrt(n);r[d]=o[d]+s*l,a[d]=o[d]-s*l}return l?[o,r,a]:o}(e,this.context.data.volume,t,i),n=this.context.idx;if(void 0!==i&&Array.isArray(s)){const[e,t,i]=s;return[this.context.precision(e[n]),this.context.precision(t[n]),this.context.precision(i[n])]}return this.context.precision(s[n])}swma(e){const t=function(e){const t=e.length,i=new Array(t).fill(NaN);for(let s=3;s((e,t,i)=>t in e?fs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);class bs{constructor(e){this.array=e}}class vs{constructor(e){this.context=e,ys(this,"_cache",{})}param(e,t=0){return Array.isArray(e)?e[t]:e}get(e,t){return e.array[t]}set(e,t,i){e.array[t]=i}push(e,t){e.array.push(t)}sum(e){return e.array.reduce(((e,t)=>e+(isNaN(t)?0:t)),0)}avg(e){return this.sum(e)/e.array.length}min(e,t=0){return[...e.array].sort(((e,t)=>e-t))[t]??this.context.NA}max(e,t=0){return[...e.array].sort(((e,t)=>t-e))[t]??this.context.NA}size(e){return e.array.length}new_bool(e,t=!1){return new bs(Array(e).fill(t))}new_float(e,t=NaN){return new bs(Array(e).fill(t))}new_int(e,t=0){return new bs(Array(e).fill(Math.round(t)))}new_string(e,t=""){return new bs(Array(e).fill(t))}new(e,t){return new bs(Array(e).fill(t))}slice(e,t,i){const s=void 0!==i?i+1:void 0;return new bs(e.array.slice(t,s))}reverse(e){e.array.reverse()}includes(e,t){return e.array.includes(t)}indexof(e,t){return e.array.indexOf(t)}lastindexof(e,t){return e.array.lastIndexOf(t)}stdev(e,t=!0){const i=this.avg(e),s=e.array.map((e=>Math.pow(e-i,2))),n=t?e.array.length:e.array.length-1;return Math.sqrt(this.sum(new bs(s))/n)}variance(e,t=!0){const i=this.avg(e),s=e.array.map((e=>Math.pow(e-i,2))),n=t?e.array.length:e.array.length-1;return this.sum(new bs(s))/n}covariance(e,t,i=!0){if(e.array.length!==t.array.length||e.array.length<2)return NaN;const s=i?e.array.length:e.array.length-1,n=this.avg(e),o=this.avg(t);let r=0;for(let i=0;i0?e.array[0]:this.context.NA}last(e){return e.array.length>0?e.array[e.array.length-1]:this.context.NA}clear(e){e.array.length=0}join(e,t=","){return e.array.join(t)}abs(e){return new bs(e.array.map((e=>Math.abs(e))))}concat(e,t){return e.array.push(...t.array),e}copy(e){return new bs([...e.array])}every(e,t){return e.array.every(t)}fill(e,t,i=0,s){const n=e.array.length,o=void 0!==s?Math.min(s,n):n;for(let s=i;s=0&&t"asc"===t?e-i:i-e))}sort_indices(e,t){const i=e.array.map(((e,t)=>t));return i.sort(((i,s)=>{const n=e.array[i],o=e.array[s];return t?t(n,o):n-o})),new bs(i)}standardize(e){const t=this.avg(e),i=this.stdev(e);return new bs(0===i?e.array.map((()=>0)):e.array.map((e=>(e-t)/i)))}unshift(e,t){e.array.unshift(t)}some(e,t){return e.array.some(t)}}var xs=Object.defineProperty,_s=(e,t,i)=>((e,t,i)=>t in e?xs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class ws{constructor({marketData:e,source:t,tickerId:i,timeframe:s,limit:n,sDate:o,eDate:r,title:a}){_s(this,"data",{open:[],high:[],low:[],close:[],volume:[],hl2:[],hlc3:[],ohlc4:[]}),_s(this,"cache",{}),_s(this,"useTACache",!1),_s(this,"NA",NaN),_s(this,"math"),_s(this,"ta"),_s(this,"input"),_s(this,"request"),_s(this,"array"),_s(this,"core"),_s(this,"lang"),_s(this,"idx",0),_s(this,"params",{}),_s(this,"const",{}),_s(this,"var",{}),_s(this,"let",{}),_s(this,"result"),_s(this,"plots",{}),_s(this,"candles",{}),_s(this,"bars",{}),_s(this,"fills",{}),_s(this,"marketData"),_s(this,"source"),_s(this,"tickerId"),_s(this,"timeframe",""),_s(this,"limit"),_s(this,"sDate"),_s(this,"eDate"),_s(this,"group"),_s(this,"pineTSCode"),this.marketData=e,this.source=t,this.tickerId=i,this.timeframe=s,this.limit=n,this.sDate=o,this.eDate=r,this.group=a,this.math=new as(this),this.ta=new ds(this),this.input=new ns(this),this.request=new ps(this),this.array=new vs(this);const l=new ss(this);this.core={color:l.color,indicator:l.indicator.bind(l),na:l.na.bind(l),nz:l.nz.bind(l),plot:l.plot.bind(l),plotbar:l.plotbar.bind(l),plotchar:l.plotchar.bind(l),plotcandle:l.plotcandle.bind(l),fill:l.fill.bind(l)}}init(e,t,i=0){return e?!Array.isArray(t)||Array.isArray(t[0])?e[0]=Array.isArray(t?.[0])?t[0]:this.precision(t):e[0]=this.precision(t[t.length-this.idx-1+i]):e=Array.isArray(t)?[this.precision(t[t.length-this.idx-1+i])]:[this.precision(t)],e}precision(e,t=10){return"number"!=typeof e||isNaN(e)?e:Number(e.toFixed(t))}param(e,t,i){return"string"==typeof e||!Array.isArray(e)&&"object"==typeof e?e:(this.params[i]||(this.params[i]=[]),Array.isArray(e)?t?(this.params[i]=e.slice(t),this.params[i].length=e.length,this.params[i]):(this.params[i]=e.slice(0),this.params[i]):(this.params[i][0]=e,this.params[i]))}}var Cs=Object.defineProperty,Ss=(e,t,i)=>((e,t,i)=>t in e?Cs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);const ks={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",45:null,60:"1h",120:"2h",180:null,240:"4h","4H":"4h","1D":"1d",D:"1d","1W":"1w",W:"1w","1M":"1M",M:"1M"};class Es{constructor(e=3e5){Ss(this,"cache"),Ss(this,"cacheDuration"),this.cache=new Map,this.cacheDuration=e}generateKey(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>`${e}:${t}`)).join("|")}get(e){const t=this.generateKey(e),i=this.cache.get(t);return i?Date.now()-i.timestamp>this.cacheDuration?(this.cache.delete(t),null):i.data:null}set(e,t){const i=this.generateKey(e);this.cache.set(i,{data:t,timestamp:Date.now()})}clear(){this.cache.clear()}cleanup(){const e=Date.now();for(const[t,i]of this.cache.entries())e-i.timestamp>this.cacheDuration&&this.cache.delete(t)}}function Ms(e){let t;if("string"==typeof e){if(t=parseInt(e,10),isNaN(t)){const t=new Date(e);return Math.floor(t.getTime()/1e3)}}else t=e;return t.toString().length>=13?Math.floor(t/1e3):t}new class{constructor(){Ss(this,"cacheManager"),this.cacheManager=new Es(3e5)}async getMarketDataInterval(e,t,i,s){try{const n=ks[t.toUpperCase()];if(!n)return console.error(`Unsupported timeframe: ${t}`),[];let o=[],r=i;const a=s,l={"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"1d":864e5,"1w":6048e5,"1M":2592e6}[n];if(!l)return console.error(`Duration not defined for interval: ${n}`),[];for(;r({openTime:parseInt(e[0]),open:parseFloat(e[1]),high:parseFloat(e[2]),low:parseFloat(e[3]),close:parseFloat(e[4]),volume:parseFloat(e[5]),closeTime:parseInt(e[6]),quoteAssetVolume:parseFloat(e[7]),numberOfTrades:parseInt(e[8]),takerBuyBaseAssetVolume:parseFloat(e[9]),takerBuyQuoteAssetVolume:parseFloat(e[10]),ignore:e[11]})));return this.cacheManager.set(o,h),h}catch(e){return console.error("Error in binance.klines:",e),[]}}};const Ps={...t.customSeriesDefaultOptions,color:"#049981",lineWidth:1,lineStyle:t.LineStyle.Solid,shapeSize:.3,shape:"circles",join:!1,fontSize:.8};function Ts(e,t){if(e._isDecorated)return console.warn("Series is already decorated. Skipping decoration."),e;e._isDecorated=!0;const i=e.setData.bind(e),s=[];let n=null;const o=e.detachPrimitive?.bind(e),r=e.attachPrimitive?.bind(e),a=e.data?.bind(e),l=e.applyOptions?.bind(e),c=e.seriesType(),h=e.options().title;function p(e){const i=s.indexOf(e);-1!==i&&(s.splice(i,1),n===e&&(n=null),o&&o(e),t&&(t.removeLegendPrimitive(e),console.log(`Removed primitive of type "${e.constructor.name}" from legend.`)))}function d(){for(console.log("Detaching all primitives.");s.length>0;){p(s.pop())}console.log("All primitives detached.")}return Object.assign(e,{applyOptions:i=>{if(l&&l(i),t&&void 0!==t._lines){const s=e.seriesType(),n=t._lines.find((t=>t.series===e));if(n&&("Candlestick"===s||"Bar"===s||"Custom"===s&&("upColor"in i||"downColor"in i)?(void 0!==i.upColor&&(n.colors[0]=i.upColor),void 0!==i.downColor&&(n.colors[1]=i.downColor)):"Line"===s||"Histogram"===s||"Custom"===s&&"color"in i?void 0!==i.color&&(n.colors[0]=i.color):"Area"===s&&void 0!==i.lineColor&&(n.colors[0]=i.lineColor),"shape"in i)){const e=(()=>{switch(i.shape){case"circle":case"circles":return"●";case"cross":return"✚";case"triangleUp":return"▲";case"triangleDown":return"▼";case"arrowUp":return"↑";case"arrowDown":return"↓";default:return i.shape}})();n.legendSymbol=e}}},setData:function(t){if(t&&Array.isArray(t)||(t=[...e.data()]),!t||0===t.length)return void i(t);const s=e.seriesType();if("Line"!==s&&"Histogram"!==s&&"Area"!==s&&"Symbol"!=s&&"Custom"!=s||!("value"in t[0])){if(("Bar"===s||"Candlestick"===s||"Custom"===s||"Ohlc"===s)&&"open"in t[0]&&t.every((e=>y(e))))return void i(t)}else if(t.every((e=>f(e))))return void i(t);let n;n="Line"!==s&&"Histogram"!==s&&"Area"!==s&&"Symbol"!==s||!("open"in t[0])?("Bar"!==s&&"Candlestick"!==s&&"Ohlc"!==s||t[0],t.map(((e,i)=>As(t,s,i)))):t.map(((e,i)=>As(t,s,i))),i(n)},dataType:function(t){const i=e.data()[0];if(b(i))return null;let s=f(i),n=y(i);if(!s&&!n&&"open"in i&&"high"in i&&"low"in i&&"close"in i&&(n=!0),t){const e=t.data()[0];if(b(e))return!1;let i=f(e),o=y(e);return!i&&!o&&"open"in e&&"high"in e&&"low"in e&&"close"in e&&(o=!0),s&&i||n&&o}return s||n?i:null},dataTransform:function(){const t=e.data();if(!t||0===t.length)return[];const i=t[0];let s;if(y(i)||"open"in i&&"high"in i&&"low"in i&&"close"in i)s="Line";else{if(!f(i))return[...t];s="Candlestick"}return t.map(((t,i)=>As(e,s,i)))},primitives:s,sync:function(e){const t=e.options().seriesType??"Line",i=a();if(!i)return void console.warn("Source data is missing for synchronization.");const s=[...e.data()];for(let n=s.length;n{const i=[...a()];if(!i||0===i.length)return void console.warn("Source data is missing for synchronization.");const s=e.data().slice(-1)[0],n=i.length-1;if(!s||i[n].time>=s.time){const i=As(e,t,n);i&&(e.update(i),console.log(`Updated/added bar via "update()" for series type ${e.seriesType}`))}}))},attachPrimitive:function(i,o,a=!0,l=!1){const c=i.constructor.type||i.constructor.name;if(a)d();else{const e=s.findIndex((e=>e.constructor.type===c));-1!==e&&p(s[e])}r&&r(i),s.push(i),n=i,console.log(`Primitive of type "${c}" attached.`),t&&l&&t.addLegendPrimitive(e,i,o)},detachPrimitive:p,detachPrimitives:d,decorated:!0,_type:c,title:h,get primitive(){return n},toJSON:()=>({options:e.options(),data:a()}),fromJSON(t){if(t.data&&i(t.data),t.options){const i=t.options;for(const t in i)if(Object.prototype.hasOwnProperty.call(i,t)){const s=t;e.applyOptions({[s]:i[s]})}}}})}function Is(e){const t={};switch(e){case"Line":return{...t,title:e,color:"#195200",lineWidth:2,crosshairMarkerVisible:!0};case"Histogram":return{...t,title:e,color:"#9ACF01",base:0};case"Area":return{...t,title:e,lineColor:"#021698",topColor:"rgba(9, 32, 210, 0.4)",bottomColor:"rgba(0, 0, 0, 0.5)"};case"Bar":return{...t,title:e,upColor:"#006721",downColor:"#6E0000",borderUpColor:"#006721",borderDownColor:"#6E0000"};case"Candlestick":return{...t,title:e,upColor:"rgba(0, 103, 33, 0.33)",downColor:"rgba(110, 0, 0, 0.33)",borderUpColor:"#006721",borderDownColor:"#6E0000",wickUpColor:"#006721",wickDownColor:"#6E0000"};case"Ohlc":return{...t,title:e,upColor:"rgba(0, 103, 33, 0.33)",downColor:"rgba(110, 0, 0, 0.33)",borderUpColor:"#006721",borderDownColor:"#6E0000",wickUpColor:"#006721",wickDownColor:"#6E0000",shape:"Rounded",chandelierSize:1,barSpacing:.777,lineStyle:0,lineWidth:1};case"Symbol":return{...t,...Ps,title:e};default:throw new Error(`Unsupported series type: ${e}`)}}function As(e,t,i){let s;if(Array.isArray(e))s=e;else{if(!e||"function"!=typeof e.data)return console.warn("Invalid source provided to convertDataItem; expected an array or series object."),null;s=[...e.data()]}if(!s||0===s.length)return console.warn("No data available in the source series."),null;const n=s[i];switch(t){case"Line":case"Histogram":case"Area":case"Symbol":if(y(n))return{time:n.time,value:n.close};if(f(n))return{time:n.time,value:n.value};if(b(n))return{time:n.time};break;case"Bar":case"Candlestick":case"Ohlc":if(y(n))return{time:n.time,open:n.open,high:n.high,low:n.low,close:n.close};if(f(n))return{time:n.time,open:n.value,high:n.value,low:n.value,close:n.value};if(b(n))return{time:n.time};break;default:return console.error(`Unsupported target type: ${t}`),{time:n.time}}return console.warn("Could not convert data to the target type."),null}function Ds(e,t,i){const s=e.options(),n=t.split(".");let o=s;for(let e=0;evoid 0!==e.primitives)(e)?e:(console.log("Decorating the series dynamically."),Ts(e,t))}function Os(e,t){const i={...e.paramMap,...t},s=[...e.sourceSeries.data()];if(!s||!Array.isArray(s)||0===s.length)return;let n;n=s.every(y)?s:s.map(Vs);e.indicator.calc(n,i).forEach((t=>{const i=e.figures.get(t.key);if(i&&(i.setData(t.data),i.applyOptions({title:t.title}),t.pane&&i.getPane()===e.sourceSeries.getPane())){const e=i.getPane().paneIndex();i.moveToPane(e+t.pane)}})),e.paramMap=i}function Vs(e){return{time:e.time,open:e.value,high:e.value,low:e.value,close:e.value}}function Rs(e,t,i,s="Line",n="overwrite"){const{data:o,group:r,options:a,pane:l}=i,c={...Bs(a)};r&&(c.group=r),t&&(c.title=t);const h="circles"===c.style||"cross"===c.style?"Symbol":s;let p={...Is(h)||{},...e.defaultsManager.get(h)||{},...c};p.style&&"line"!==p.style&&(p.shape=p.style,delete p.style);const d=o.map((e=>({...e,time:"number"==typeof e.time?Ms(e.time):e.time}))),u=e.seriesMap.get(t);if(u&&("overwrite"===n||"update"===n))return"update"===n?(u.update(d[d.length-1]),p={...p,...u.options()}):(u.detachPrimitives(),u.setData(d)),void u.applyOptions(p);let m=null;"Line"===s?m="line"!==c.style?e.createSymbolSeries(t,{...p,shape:c.style},l):e.createLineSeries(t,p,l):"Bar"===s?m=e.createBarSeries(t,p,l):"Candlestick"===s||"Ohlc"===s||"Custom"===s&&void 0!==o[0]?.open?m=e.createCustomOHLCSeries?e.createCustomOHLCSeries(t,p):e.createBarSeries(t,p,l):"Histogram"===s?m=e.createHistogramSeries(t,p,l):"Area"===s?m=e.createAreaSeries(t,p,l):(console.warn(`Unsupported series type: ${s}. Defaulting to Line.`),m=e.createLineSeries(t,p,l)),m.series.setData(d),e.legend&&!m.series.decorated&&(m.series=Ts(m.series,e.legend)),e.seriesMap.set(t,m.series)}function Bs(e){const t={};for(const i in e){const s=Array.isArray(e[i])?e[i][0]:e[i];"linewidth"===i.toLowerCase()?t.lineWidth=s:t[i]=s}return t}function $s(e,t){const{plot1:i,plot2:s,options:n}=t,o=S,r=e.seriesMap.get(i),a=e.seriesMap.get(s);if(!r)return void console.warn(`Origin series with title "${i}" not found.`);if(!a)return void console.warn(`Destination series with title "${s}" not found.`);const l=a.options().title;let c=null;r.primitives[l]?c=r.primitives[l]:(c=new _(r,a,o),r.primitives[l]=c,r.attachPrimitive(c,`Fill ➣ ${a.options().title}`,!1,!0))}function Gs(e,t){const i=e.split("."),s={};let n=s;for(let e=0;ee.toUpperCase()))}function js(e,i,s){const n=i.timeScale(),o=s??i.addSeries(t.LineSeries);if(!o)return console.warn("No series found. Cannot perform y-axis conversions."),null;if("logical"in e){const t=e,i=n.logicalToCoordinate(t.logical),s=o.priceToCoordinate(t.price);return null===i||null===s?null:{x:i,y:s}}{const t=e,i=n.coordinateToLogical(t.x),s=n.coordinateToTime(t.x),r=o.coordinateToPrice(t.y);return null===i||null===r?null:{time:s,logical:i,price:r}}}function Us(e,t,i,s,n){const o=s-n/2,r=s+n/2;e.beginPath(),e.moveTo(t,o),e.lineTo(t,r),e.lineTo(i,r),e.lineTo(i,o),e.closePath(),e.fill(),e.stroke()}function zs(e,t,i,s,n,o){const r=i-t,a=o*Math.min(Math.abs(r),Math.abs(n)),l=Math.abs(Math.min(a,r/2,n/2)),c=s-n/2;e.beginPath(),"function"==typeof e.roundRect?e.roundRect(t,c,r,n,l):(e.moveTo(t+l,c),e.lineTo(i-l,c),e.quadraticCurveTo(i,c,i,c+l),e.lineTo(i,c+n-l),e.quadraticCurveTo(i,c+n,i-l,c+n),e.lineTo(t+l,c+n),e.quadraticCurveTo(t,c+n,t,c+n-l),e.lineTo(t,c+l),e.quadraticCurveTo(t,c,t+l,c)),e.closePath(),e.fill(),e.stroke()}function Hs(e,t,i,s,n,o){const r=t+(i-t)/2,a=i-t;e.beginPath(),e.ellipse(r,n,Math.abs(a/2),Math.abs(o/2),0,0,2*Math.PI),e.fill(),e.stroke()}function Ws(e,t,i,s,n,o,r,a,l,h,p,d){const u=-Math.max(a,1)*(1-d),m=c(l,.666),g=c(l,.333),f=c(l,.2),y=t-r/2,b=y+a+u,v=y-u,x=b-u;let _,w,C,S;p?(_=n,w=s,C=i,S=o):(_=n,w=i,C=s,S=o),e.fillStyle=g,e.strokeStyle=h,e.beginPath(),e.rect(v,C,a+u-r/2,S-C),e.fill(),e.stroke(),e.fillStyle=f,p?(e.fillStyle=m,e.beginPath(),e.moveTo(y,w),e.lineTo(v,S),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=m,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(v,S),e.lineTo(y,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=m,e.beginPath(),e.moveTo(b,_),e.lineTo(x,C),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=f,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(x,C),e.lineTo(b,_),e.closePath(),e.fill(),e.stroke()):(e.fillStyle=f,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(x,C),e.lineTo(b,_),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(b,_),e.lineTo(x,C),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(v,S),e.lineTo(y,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(y,w),e.lineTo(v,S),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke())}function qs(e,t,i,s,n,o,r,a){const l=s+n/2,c=s-n/2;e.save(),e.beginPath(),a?(e.moveTo(t,l),e.lineTo(i,o),e.lineTo(i,c),e.lineTo(t,r)):(e.moveTo(t,o),e.lineTo(i,l),e.lineTo(i,r),e.lineTo(t,c)),e.closePath(),e.stroke(),e.fill(),e.restore()}function Xs(e,t,i,s,n,o,r,a,l){e.save(),e.beginPath(),l?(e.moveTo(t,a),e.lineTo(t,n+o/2),e.lineTo(s,r),e.lineTo(i,n+o/2),e.lineTo(i,a),e.lineTo(s,n-o/2),e.lineTo(t,a)):(e.moveTo(t,r),e.lineTo(t,n-o/2),e.lineTo(s,a),e.lineTo(i,n-o/2),e.lineTo(i,r),e.lineTo(s,n+o/2),e.lineTo(t,r)),e.closePath(),e.fill(),e.stroke(),e.restore()}function Js(e,t,i,s,n,o,r){const a=(t+i)/2;e.beginPath(),e.moveTo(a,s),e.lineTo(a,n),e.stroke(),e.beginPath(),e.moveTo(t,o),e.lineTo(a,o),e.stroke(),e.beginPath(),e.moveTo(a,r),e.lineTo(i,r),e.stroke()}function Ys(e,t,i,s,n,o){const r=s-n/2,a=s+n/2,l=.9*Math.abs(i-t);e.save(),e.beginPath(),o?(e.moveTo(t,r),e.lineTo(t+l,r),e.lineTo(i,a),e.lineTo(i-l,a)):(e.moveTo(i-l,r),e.lineTo(i,r),e.lineTo(t+l,a),e.lineTo(t,a)),e.closePath(),e.fill(),e.stroke(),e.restore()}!function(e){e.Line="Line",e.Histogram="Histogram",e.Area="Area",e.Bar="Bar",e.Candlestick="Candlestick",e.Ohlc="Ohlc",e.Symbol="Symbol",e.Custom="Custom"}(Ls||(Ls={}));const Ks={visible:!0,autoScale:!1,xScaleLock:!1,yScaleLock:!1,color:"#737375",lineWidth:1,upColor:"rgba(0,255,0,.25)",downColor:"rgba(255,0,0,.25)",wickVisible:!0,borderVisible:!0,borderColor:"#737375",borderUpColor:"#1c9d1c",borderDownColor:"#d5160c",wickColor:"#737375",wickUpColor:"#1c9d1c",wickDownColor:"#d5160c",radius:100,shape:"Rounded",chandelierSize:1,barSpacing:.8,lineStyle:0,lineColor:"#ffffff",width:1};class Qs{handler;get data(){return this.convertAndAggregateDataPoints()}get sourceData(){return this._originalData}_originalP1;_originalP2;_barWidth=.8;p1;p2;_options;series;_originalData=[];_originalSlice=[];offset;onComplete;get spatial(){return this.recalculateSpatial()}transform={scale:{x:1,y:1},shift:{x:0,y:0}};constructor(e,t,i,s,n,o){let r,a;this.handler=e,this._options={...n,...Ks},Math.min(i.logical,s.logical)===i.logical?(r=i,a=s):(r=s,a=i),this._originalP1={...r},this._originalP2={...a},this.offset=o??0,this.p1=i,this.p2=s,x(t)?(this.series=t,this._originalData=this.series.data().map(((e,t)=>({...e,x1:t,x2:t+1})))):(this.series=this.handler.series||this.handler._seriesList[0],this._originalData=t._originalData);const l=Math.min(this._originalP1.logical,this._originalP2.logical),c=Math.max(this._originalP1.logical,this._originalP2.logical);o&&o>0?(this._originalSlice=this._originalData.slice(c,Math.min(this.series.data().length-1,c+1+o)),console.log("Data Sliced with Offset",l,c,o,"Offset Point:",Math.min(this.series.data().length-1,c+1+o))):(this._originalSlice=this._originalData.slice(l,c+1),console.log("Data Sliced:",l,c)),o&&o>0&&(this._originalSlice=this._originalSlice.map((e=>({...e,x1:e.x1+o,x2:e.x2+o}))),console.log("Adjusted originalSlice with pOffset:",o)),this.transform=this.recalculateSpatial(),this.p1&&this.p2&&this.setPoints(this.p1,this.p2)}setData(e){this._originalSlice=e}setPoints(e,t){let i,s;Math.min(e.logical,t.logical)===e.logical?(i=e,s=t):(i=t,s=e),null===this._originalP1?(this._originalP1={...i},console.log("First point (p1) set:",this._originalP1)):null===this._originalP2&&(this._originalP2={...s},console.log("Second point (p2) set:",this._originalP2)),this.p1=i,this.p2=s,this.recalculateSpatial(),this.processSequence()}updatePoint(e,t){1===e?this.p1=t:2===e&&(this._originalP2||(this._originalP2=t),this.p2=t),this.recalculateSpatial(),this.processSequence()}recalculateSpatial(){if(!(this.p1&&this.p2&&this._originalP1&&this._originalP2))return console.warn("Cannot recalc spatial without valid p1/p2."),{scale:{x:1,y:1},shift:{x:0,y:0}};const e=Math.abs(this._originalP1.logical-this._originalP2.logical),t=Math.abs(this._originalP1.price-this._originalP2.price);if(0===e||0===t)return console.warn("Cannot recalc scale if original points are zero difference."),{scale:{x:1,y:1},shift:{x:0,y:0}};const i=Math.abs(this.p1.logical-this.p2.logical)/e,s=((this._originalP2.price>this._originalP1.price?this.p2.price:this.p1.price)-(this._originalP2.price>this._originalP1.price?this.p1.price:this.p2.price))/t;this._options.xScaleLock||(this.transform.scale.x=i),this._options.yScaleLock||(this.transform.scale.y=s),this._options.autoScale&&i>-1&&i<1&&(this._options.chandelierSize=Math.abs(Math.ceil(1/i)));const n={scale:{x:0!==i?Math.round(100*i)/100:1,y:0!==s?Math.round(100*s)/100:1},shift:{x:this._originalP1.logical-this.p1.logical,y:this._originalP1.price-this.p1.price}};return this._barWidth=Math.abs(this.p1.logical-this.p2.logical)/this._originalData.length,console.log("Spatial recalculated:","scaleX=",n.scale.x,"scaleY=",n.scale.y,"shiftX=",n.shift.x,"shiftY=",n.shift.y),0===n.scale.x||0===n.scale.y?(console.warn("Scale factors cannot be zero."),{scale:{x:1,y:1},shift:{x:0,y:0}}):n}processSequence(){this.p1&&this.p2?(this.convertAndAggregateDataPoints(),this.onComplete&&this.onComplete()):console.warn("Cannot process sequence without valid p1/p2.")}convertAndAggregateDataPoints(){let e=Number.POSITIVE_INFINITY,t=Number.NEGATIVE_INFINITY;const i={...this.spatial};this._originalSlice.forEach((i=>{const s=[];void 0!==i.open&&s.push(i.open),void 0!==i.high&&s.push(i.high),void 0!==i.low&&s.push(i.low),void 0!==i.close&&s.push(i.close),void 0!==i.value&&s.push(i.value);for(const i of s)it&&(t=i)}));const s=t===e?1:t-e,n=this.p1.logical,o=this._originalSlice.map(((t,o)=>{const r=n+o;function a(t,i){if(void 0===t)return;const n=(t-e)/s;return e-i.shift.y+n*i.scale.y*s}const c=a(t.open,i),h=a(t.close,i),p=a(t.high,i),d=a(t.low,i),u=a(t.value,i);if(void 0!==c||void 0!==h||void 0!==p||void 0!==d){const e=(h??0)>(c??0),i=e?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)",s=e?this._options.borderUpColor||l(i,1):this._options.borderDownColor||l(i,1),n=e?this._options.wickUpColor||s:this._options.wickDownColor||s;return{open:c,close:h,high:p,low:d,isUp:e,x1:r+this.offset,x2:r+1+this.offset,isInProgress:!1,originalData:{...t,x1:o},barSpacing:this._barWidth,color:i,borderColor:s,wickColor:n,lineStyle:this._options.lineStyle,lineWidth:this._options.lineWidth,shape:this._options.shape??"Rounded"}}return{value:u,isUp:void 0,x1:r+this.offset,x2:r+1+this.offset,isInProgress:!1,originalData:t,barSpacing:this._options.barSpacing??.8}})),r=this._options.chandelierSize??1;if(r<=1)return o;const a=[];for(let e=0;eMath.max(e,t.high||0)),0),a=e.reduce(((e,t)=>Math.min(e,t.low||1/0)),1/0),c=o>i,h=c?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)",p=c?this._options.borderUpColor||l(h,1):this._options.borderDownColor||l(h,1),d=c?this._options.wickUpColor||p:this._options.wickDownColor||p,u=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options.lineStyle),m=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options.lineWidth??1);return{open:i,high:r,low:a,close:o,isUp:c,x1:s,x2:n,isInProgress:t,color:h,borderColor:p,wickColor:d,shape:this._options.shape??"Rounded",lineStyle:u,lineWidth:m}}{const t=e[0].value??0,i=(e[e.length-1].value??0)>t,o=i?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)";i?this._options.borderUpColor||l(o,1):this._options.borderDownColor||l(o,1);i?this._options.wickUpColor:this._options.wickDownColor;const r=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options.lineStyle),a=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options.lineWidth??1);return this._options.shape,{value:t,isUp:i,x1:s,x2:n,color:o,lineStyle:r,lineWidth:a}}}applyOptions(e){this._options={...this._options,...e},this.processSequence()}}class Zs extends a{_type="TrendTrace";_paneViews;_sequence;_options;_state=N.NONE;_handler;_source;_originalP1=null;_originalP2=null;p1=null;p2=null;_points=[];title="";static _type="Trend-Trace";_startDragPoint=null;_latestHoverPoint=null;static _mouseIsDown=!1;static hoveredObject=null;static lastHoveredObject=null;_listeners=[];_hovered=!1;constructor(e,t,i,s,n,o){super(),this._handler=e,this._source=t,this._originalP1={...i},this._originalP2={...s};const r=this._source.options(),a=function(e,t){const i={};for(const s in e)Object.prototype.hasOwnProperty.call(t,s)&&(i[s]=t[s]);return i}(Ks,r);this._options={...a,...n},this._sequence=this._createSequence({p1:i,p2:s},this._options,o),this.p1=this._sequence.p1,this.p2=this._sequence.p2,this._subscribeEvents(),this._paneViews=[new en(this)]}toJSON(){return{data:this._sequence.data,p1:this._sequence._originalP1,p2:this._sequence._originalP2,options:this._sequence._options}}fromJSON(e){if(e.data&&this._sequence.setData(e.data),e.options){const t=e.options;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const i=e;this.applyOptions({[i]:t[i]})}}e.p1&&(this.p1=e.p1),e.p2&&(this.p2=e.p2)}attached(e){super.attached(e),this._originalP1&&this._originalP2&&this._createSequence({p1:this._originalP1,p2:this._originalP2}),this._source=Ns(e.series,this._handler.legend),this.title=e.series.options().title;const i=new(t.defaultHorzScaleBehavior());return{chart:e.chart,series:e.series,requestUpdate:e.requestUpdate,horzScaleBehavior:i}}paneViews(){return this._paneViews}detached(){super.detached(),this._listeners.forEach((({name:e,listener:t})=>{document.body.removeEventListener(e,t)})),this._listeners=[],this._handler?.chart&&(this._handler.chart.unsubscribeCrosshairMove(this._handleMouseMove),this._handler.chart.unsubscribeClick(this._handleMouseDownOrUp)),this._paneViews=[],this._sequence=null,this._options=null,this._source=null,this._originalP1=null,this._originalP2=null,this.p1=null,this.p2=null,console.log("✅ All listeners and references successfully detached.")}_createSequence(e,t,i){let s;return"p1"in e&&"p2"in e?(s=new Qs(this._handler,this._source,e.p1,e.p2,t??this._options,i),s.onComplete=()=>this.updateViewFromSequence(),this.updateViewFromSequence(),s):(s=new Qs(this._handler,e.data,e.data._originalP1,e.data._originalP2,t??this._options,i),s.onComplete=()=>this.updateViewFromSequence(),this.updateViewFromSequence(),s)}applyOptions(e){this._options={...this._options,...e},this._sequence&&this._sequence.applyOptions(this._options),this.requestUpdate()}_pendingUpdate=!1;updateViewFromSequence(){this._pendingUpdate||(this._pendingUpdate=!0,requestAnimationFrame((()=>{super.requestUpdate(),console.log("Updating view with sequence data:",this._sequence?.data),this._pendingUpdate=!1})))}getOptions(){return this._options}_subscribeEvents(){this._handler.chart.subscribeCrosshairMove(this._handleMouseMove),this._handler.chart.subscribeClick(this._handleMouseDownOrUp)}_subscribe(e,t){document.body.addEventListener(e,t),this._listeners.push({name:e,listener:t})}_unsubscribe(e,t){document.body.removeEventListener(e,t);const i=this._listeners.find((i=>i.name===e&&i.listener===t));this._listeners.splice(this._listeners.indexOf(i),1)}_handleHoverInteraction(e){if(this._latestHoverPoint=e.point,Zs._mouseIsDown)this._handleDragInteraction(e);else if(this._mouseIsOverSequence(e)){if(this._state!=N.NONE)return;this._moveToState(N.HOVERING),Zs.hoveredObject=Zs.lastHoveredObject=this}else{if(this._state==N.NONE)return;this._moveToState(N.NONE),Zs.hoveredObject===this&&(Zs.hoveredObject=null)}}_handleMouseDownOrUp=()=>{this._latestHoverPoint&&(Zs._mouseIsDown=!Zs._mouseIsDown,Zs._mouseIsDown?this._onMouseDown():this._onMouseUp())};_handleMouseMove=e=>{const t=this._eventToPoint(e,this._source);this._latestHoverPoint=t,Zs._mouseIsDown?this._handleDragInteraction(e):this._mouseIsOverPoint(e,1)||this._mouseIsOverPoint(e,2)||this._mouseIsOverSequence(e)?this._state===N.NONE&&this._moveToState(N.HOVERING):this._state!==N.NONE&&this._moveToState(N.NONE)};_onMouseUp(){Zs._mouseIsDown=!1,this.chart.applyOptions({handleScroll:!0}),this._moveToState(N.HOVERING),this._startDragPoint=null}_handleDragInteraction(e){if(this._state!==N.DRAGGING&&this._state!==N.DRAGGINGP1&&this._state!==N.DRAGGINGP2)return;const t=this._eventToPoint(e,this.series);if(!t||!this._startDragPoint)return;const i=this._getDiff(t,this._startDragPoint);this._onDrag(i),this._startDragPoint=t,this.requestUpdate()}_mouseIsOverPoint(e,t){const i=1===t?{x:this._paneViews[0]._p1.x,y:this._paneViews[0]._p1.y}:{x:this._paneViews[0]._p2.x,y:this._paneViews[0]._p2.y};return!!this.chart&&function(e,t,i,s){const n=function(e){if(!e)return null;const t=e.paneSize();return{width:t.width,height:t.height}}(s);if(!n)return!1;const o=n.width,r=n.height,a=o*i,l=r*i,c=function(e){if(e instanceof MouseEvent)return(t=e)?{x:t.x,y:t.y}:null;var t;if("point"in e&&e.point)return e.point;return null}(e);if(!c||null==c.x||null==c.y||null==t.x||null==t.y)return!1;const h=Math.abs(t.x-c.x),p=Math.abs(t.y-c.y);return h<=a&&p<=l}(e,i,.05,this.chart)}_mouseIsOverSequence(e){if(!e.logical||!e.point)return console.warn("Invalid MouseEventParams: Missing logical or point."),!1;const t=this._source.coordinateToPrice?.(e.point.y);if(null==t)return console.warn("Mouse price could not be determined."),!1;let i=e.time?this._sequence.data.find((t=>t.time===e.time)):void 0;if(i||(i=this._sequence.data.find((t=>Math.round(t.x1)===Math.round(e.logical)))),!i)return console.warn("No matching bar found for the given parameters."),!1;if(null!=i.low&&null!=i.high){const e=.05*(i.high-i.low);return t>=i.low-e&&t<=i.high+e}if(null!=i.value){const e=.05*i.value;return t>=i.value-e&&t<=i.value+e}return console.warn("Bar lacks price information."),!1}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this.requestUpdate(),this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this.requestUpdate(),this._subscribe("mousedown",this._handleMouseDownInteraction),this._unsubscribe("mouseup",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_addDiffToPoint(e,t,i){e&&(e.logical=e.logical+t,e.price=e.price+i,e.time=this.series.dataByIndex(e.logical)?.time||null)}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this._sequence.p1,this._options.xScaleLock&&this._state==N.DRAGGINGP1?0:e.logical,this._options.yScaleLock&&this._state==N.DRAGGINGP1?0:e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this._sequence.p2,this._options.xScaleLock&&this._state==N.DRAGGINGP2?0:e.logical,this._options.yScaleLock&&this._state==N.DRAGGINGP2?0:e.price)}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint;if(!e)return;const t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);Math.abs(e.x-t.x)<20&&Math.abs(e.y-t.y)<20?(this.chart.applyOptions({handleScroll:!1}),this._moveToState(N.DRAGGINGP1)):Math.abs(e.x-i.x)<20&&Math.abs(e.y-i.y)<20?(this.chart.applyOptions({handleScroll:!1}),this._moveToState(N.DRAGGINGP2)):(this.chart.applyOptions({handleScroll:!1}),this._moveToState(N.DRAGGING))}_handleMouseDownInteraction=()=>{this._onMouseDown()};_handleMouseUpInteraction=()=>{this._onMouseUp()};_getDiff(e,t){return{logical:e.logical-t.logical,price:e.price-t.price}}_eventToPoint(e,t){if(!t||!e.point||!e.logical)return null;const i=t.coordinateToPrice(e.point.y);return null==i?null:{time:e.time||null,logical:e.logical,price:i.valueOf()}}}class en{_p1={x:null,y:null};_p2={x:null,y:null};_plugin;constructor(e){this._plugin=e}renderer(){if(!this._plugin._sequence)throw new Error("No sequence available for rendering.");return new tn(this._plugin,this._plugin._options,!1)}}class tn extends F{_source;_options;constructor(e,t,i){super(js(e._sequence.p1,e.chart,e._source),js(e._sequence.p2,e.chart,e._source),t,i),this._source=e,this._options=t}draw(e){e.useBitmapCoordinateSpace((e=>{const t=e.context,{chart:i}=this._source;t.save();const{horizontalPixelRatio:s}=e,n=this._source._sequence.data,o=this._source.chart.timeScale(),r=this._source._source,a=i.timeScale().getVisibleLogicalRange(),l=i.options().width/((a?.to??n.length)-(a?.from??0));if(console.log("barSpace:",l),!r||!o||0===n.length)return void t.restore();const c=n[0].x1,h=n[n.length-1].x2,p=i.timeScale().logicalToCoordinate(c)??0,d=i.timeScale().logicalToCoordinate(h)??p,u=p*s,m=d*s,g=this._source._sequence._originalP2.logical>this._source._sequence._originalP1.logical&&this._source._sequence.p2.logical>this._source._sequence.p1.logical||this._source._sequence._originalP2.logical{const i=u+(g?1:-1)*(t*((m-u)/n.length)*this._source._sequence.spatial.scale.x),s=(t+1)*((m-u)/n.length)*this._source._sequence.spatial.scale.x-(1-(this._options.barSpacing??.8))*(m-u)/n.length/(this._options.chandelierSize??1),o=e.isUp?g?this._options.upColor:this._options.downColor:g?this._options.downColor:this._options.upColor,r=e.isUp?g?this._options.borderUpColor:this._options.borderDownColor:g?this._options.borderDownColor:this._options.borderUpColor,a=e.isUp?g?this._options.wickUpColor:this._options.wickDownColor:g?this._options.wickDownColor:this._options.wickUpColor;return{...e,scaledX1:i,scaledX2:s,color:o,borderColor:r,wickColor:a}})).filter((e=>null!==e));console.log("Scaled bars:",f),this.isOHLCData(n)?(this._options.wickVisible&&this._drawWicks(e,f,l),this._drawCandles(e,f,l)):this.isSingleValueData(n)&&this._drawSingleValueData(e,f),t.restore()}))}_drawSingleValueData(e,t){const{context:i,horizontalPixelRatio:s,verticalPixelRatio:n}=e;i.lineWidth=this._options.lineWidth??1,U(i,this._options.lineStyle??1),i.strokeStyle=this._options.visible?this._options.lineColor??"#ffffff":"rgba(0,0,0,0)",i.beginPath(),t.forEach((e=>{if(null===e.x1||void 0===e.x1)return;const t=e.scaledX1*s,o=(this._source._source?.priceToCoordinate(e.value??0)??0)*n;i.lineTo(t,o),i.stroke()}))}_drawWicks(e,t,i){const{context:s,verticalPixelRatio:n}=e;this._source._sequence._originalP2.price>this._source._sequence._originalP1.price&&this._source._sequence.p2.price>this._source._sequence.p1.price||this._source._sequence._originalP2.pricethis._source._sequence._originalP1.logical&&this._source._sequence.p2.price>this._source._sequence.p1.price;t[0].scaledX1,t[t.length-1].scaledX2;t.length;const r=Math.abs(i);t.forEach(((e,i)=>{const a=(this._options.barSpacing??.8)*r,l=r-a;let c=e.scaledX1,h=c+(e.x2-e.x1+((this._options.chandelierSize??1)>1?1:0))*r-l;if(i{const o=(this._options.barSpacing??.8)*a,l=a-o;if(!e)return;const c=(this._source.series.priceToCoordinate(e.open)??0)*r,h=(this._source.series.priceToCoordinate(e.close)??0)*r,p=(this._source.series.priceToCoordinate(e.high)??0)*r,d=(this._source.series.priceToCoordinate(e.low)??0)*r,u=h>=c,m=Math.min(c,h),g=Math.max(c,h),f=m-g,y=(m+g)/2;let b=e.scaledX1-.5*a,v=b+(e.x2-e.x1+((this._options.chandelierSize??1)>1?1:0))*a-l;if(ivoid 0!==e.open&&void 0!==e.high&&void 0!==e.low&&void 0!==e.close))}isSingleValueData(e){return e.every((e=>void 0!==e.value))}}function sn(e){let t=0;for(const i of e){if(!i||!Number.isNaN(i.value))break;t++}return t}const nn={color:"white",border:"none",padding:"5px 10px",cursor:"pointer",borderRadius:"12px",boxShadow:"0 2px 4px rgba(0,0,0,0.2)",transition:"transform 0.2s ease-in-out"};class on{container;header;editorDiv;resizer;editorInstance=null;closeButton;isResizing=!1;startY=0;startHeight=0;MIN_HEIGHT=100;MAX_HEIGHT=window.innerHeight-50;scripts={};handler;_dataChangeHandlers=new Map;selectedSeries=null;selectedVolumeSeries=null;constructor(e){this.handler=e,this.selectedSeries=this.handler.series,this.selectedVolumeSeries=this.handler.volumeSeries??null,this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"0",width:"100%",height:"300px",backgroundColor:"#000000",borderTop:"2px solid #222",zIndex:"10000",display:"none",flexDirection:"column"}),this.resizer=document.createElement("div"),Object.assign(this.resizer.style,{height:"5px",width:"100%",backgroundColor:"#111",cursor:"ns-resize",userSelect:"none"}),this.resizer.addEventListener("mousedown",this.onDragStart.bind(this)),document.addEventListener("mousemove",this.onDrag.bind(this)),document.addEventListener("mouseup",this.onDragEnd.bind(this)),this.container.appendChild(this.resizer),this.header=document.createElement("div"),Object.assign(this.header.style,{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"10px",backgroundColor:"#000"});const t=document.createElement("div");t.style.display="flex",t.style.alignItems="center",t.style.gap="10px";const i=document.createElement("span");i.innerText="PineTS Script Editor ",i.style.color="white",t.appendChild(i);const s=document.createElement("div");s.style.display="flex",s.style.gap="10px";const n=document.createElement("button");n.innerText="Execute",Object.assign(n.style,nn,{backgroundColor:"#2A8D08"}),n.onmouseover=()=>{n.style.transform="scale(1.05)"},n.onmouseout=()=>{n.style.transform="scale(1)"},n.onclick=()=>{this.executePineTS()},s.appendChild(n);const o=document.createElement("div");Object.assign(o.style,{display:"inline-flex",border:"1px solid #0A42FA",borderRadius:"8px",overflow:"hidden",position:"relative"});const r=document.createElement("button");r.innerText="Save",Object.assign(r.style,nn,{backgroundColor:"#0A42FA",borderRadius:"0px"}),r.onmouseover=()=>{r.style.transform="scale(1.05)"},r.onmouseout=()=>{r.style.transform="scale(1)"},r.onclick=()=>{this.saveScript()},o.appendChild(r);const a=document.createElement("button");a.innerText="🛠",Object.assign(a.style,nn,{backgroundColor:"#0A42FA",borderLeft:"1px solid #fff",borderRadius:"0px",padding:"5px"}),a.onmouseover=()=>{a.style.transform="scale(1.05)"},a.onmouseout=()=>{a.style.transform="scale(1)"},a.onclick=e=>{const t=document.getElementById("save-dropdown");if(t)return void t.remove();const i=document.createElement("div");i.id="save-dropdown",Object.assign(i.style,{position:"absolute",backgroundColor:"#0A42FA",color:"white",border:"1px solid #fff",borderRadius:"4px",marginTop:"5px",zIndex:"100000"});const s=document.createElement("div");s.innerText="Save As",s.style.padding="5px 10px",s.style.cursor="pointer",s.onclick=()=>{this.saveToFile(),i.remove()},i.appendChild(s);const n=o.getBoundingClientRect();i.style.left=n.left+"px",i.style.top=n.bottom+"px",document.body.appendChild(i)},o.appendChild(a),s.appendChild(o);const l=document.createElement("div");Object.assign(l.style,{display:"inline-flex",border:"1px solid #AC0202",borderRadius:"8px",overflow:"hidden",position:"relative"});const c=document.createElement("button");c.innerText="Script",Object.assign(c.style,nn,{backgroundColor:"#AC0202",borderRadius:"0px"}),c.onmouseover=()=>{c.style.transform="scale(1.05)"},c.onmouseout=()=>{c.style.transform="scale(1)"},c.onclick=()=>{console.log("Current script: "+c.innerText)},l.appendChild(c);const h=document.createElement("button");h.innerText="🗄",Object.assign(h.style,nn,{backgroundColor:"#AC0202",borderLeft:"1px solid #fff",borderRadius:"0px",padding:"5px"}),h.onmouseover=()=>{h.style.transform="scale(1.05)"},h.onmouseout=()=>{h.style.transform="scale(1)"},h.onclick=e=>{const t=document.getElementById("script-dropdown");if(t)return void t.remove();const i=document.createElement("div");i.id="script-dropdown",Object.assign(i.style,{position:"absolute",backgroundColor:"#AC0202",color:"white",border:"1px solid #fff",borderRadius:"4px",marginTop:"5px",zIndex:"100000"});Object.keys(this.scripts).forEach((e=>{const t=document.createElement("div");t.innerText=e,t.style.padding="5px 10px",t.style.cursor="pointer",t.onclick=()=>{this.scripts[e]&&this.scripts[e].code&&(this.setValue(this.scripts[e].code),c.innerText=e,console.log(`Loaded script "${e}" from memory.`)),i.remove()},i.appendChild(t)}));const s=document.createElement("div");s.innerText="Open...",s.style.padding="5px 10px",s.style.cursor="pointer",s.onclick=()=>{this.openScriptFromFile(),i.remove()},i.appendChild(s);const n=l.getBoundingClientRect();i.style.left=n.left+"px",i.style.top=n.bottom+"px",document.body.appendChild(i)},l.appendChild(h),s.appendChild(l);const p=document.createElement("div");Object.assign(p.style,{display:"inline-flex",border:"1px solid #696969",borderRadius:"8px",overflow:"hidden",position:"relative"});const d=document.createElement("button");d.innerText="Select Main Series",Object.assign(d.style,nn,{backgroundColor:"#696969",borderRadius:"0px"}),d.onmouseover=()=>{d.style.transform="scale(1.05)"},d.onmouseout=()=>{d.style.transform="scale(1)"},d.onclick=e=>{this.populateMainSeriesSelectMenu(e,(e=>{this.selectedSeries=e,console.log("Selected Main Series:",e)}))},p.appendChild(d);const u=document.createElement("button");u.innerText="∿",Object.assign(u.style,nn,{backgroundColor:"#696969",borderLeft:"1px solid #fff",borderRadius:"0px",padding:"5px"}),u.onmouseover=()=>{u.style.transform="scale(1.05)"},u.onmouseout=()=>{u.style.transform="scale(1)"},u.onclick=e=>{const t=document.getElementById("series-dropdown");if(t)return void t.remove();const i=document.createElement("div");i.id="series-dropdown",Object.assign(i.style,{position:"absolute",backgroundColor:"#696969",color:"white",border:"1px solid #fff",borderRadius:"4px",marginTop:"5px",zIndex:"100000"});const s=document.createElement("div");s.innerText="Select Main Series",s.style.padding="5px 10px",s.style.cursor="pointer",s.onclick=e=>{this.populateMainSeriesSelectMenu(e,(e=>{this.selectedSeries=e,console.log("Selected Main Series:",e)})),i.remove()},i.appendChild(s);const n=document.createElement("div");n.innerText="Select Volume Series",n.style.padding="5px 10px",n.style.cursor="pointer",n.onclick=e=>{this.populateVolumeSeriesSelectMenu(e,(e=>{this.selectedVolumeSeries=e,console.log("Selected Volume Series:",e)})),i.remove()},i.appendChild(n);const o=p.getBoundingClientRect();i.style.left=o.left+"px",i.style.top=o.bottom+"px",document.body.appendChild(i)},p.appendChild(u),s.appendChild(p),t.appendChild(s),this.closeButton=document.createElement("button"),this.closeButton.innerText="Close",Object.assign(this.closeButton.style,nn,{backgroundColor:"#ff0000"}),this.closeButton.onmouseover=()=>{this.closeButton.style.transform="scale(1.05)"},this.closeButton.onmouseout=()=>{this.closeButton.style.transform="scale(1)"},this.closeButton.onclick=()=>this.close(),this.header.appendChild(t),this.header.appendChild(this.closeButton),this.container.appendChild(this.header),this.editorDiv=document.createElement("div"),Object.assign(this.editorDiv.style,{flex:"1",height:"calc(100% - 45px)"}),this.container.appendChild(this.editorDiv),document.body.appendChild(this.container),this.initializeMonaco(),this.loadInitialScript()}initializeMonaco(){let e="";if(this.handler.scriptsManager&&"function"==typeof this.handler.scriptsManager.getLast){const t=this.handler.scriptsManager.getLast();t&&t.code&&(e=t.code)}e||(e="\n\n\n// * @EsIstJosh\n// * This feature implements a variation of PineTS, source : and is \n// * licensed under the GNU AGPL v3.0. V\n// * The original AGPL license text is included in the AGPL_LICENSE file in the repository.\n// * \n// * Note: This file imports modules that remain under the MIT license \n// * The original MIT license text is included in the MIT_LICENSE file in the repository.\n// *\n// * For the full text of the GNU AGPL v3.0, see .\n\n\n// * //-----------------Work in Progress...-------------------//\n// * EXAMPLE SCRIPT CONVERSION // \n// * PINE SCRIPT ⥵ //PINE TS \n// * \n// * //@version=5 ⥵ // @version=5\n// * indicator('Simple EMA','EMA', overlay=true) ⥵ indicator('Simple EMA','EMA', {overlay=true}) \n// * ⥵ \n// * ema9 = ta.ema(close, 9); ⥵ const ema9 = ta.ema(close, 9) \n// * ema18 = ta.ema(close, 18); ⥵ const ema18 = ta.ema(close, 18)\n// * plot(ema9,'EMA9', color= #ff0000, linewidth= 2, style = plot.style_line) ⥵ plot(ema9,'EMA9',{ style: 'line', color: '#ff0000', linewidth: 2 })\n// * plot(ema18,'EMA18', color= #ff7700, linewidth= 2, style = plot.style_line) ⥵ plot(ema18,'EMA18',{ style: 'line', color: '#ff7700', linewidth: 2 })\n\n\n\n indicator('Title', 'TA', { overlay : true })\n // \n const ema1 = ta.ema(close,16)\n const ema2 = ta.ema(close,32)\n const ema3 = ta.ema(close,48)\n const ema4 = ta.ema(close,64)\n const ema5 = ta.ema(close,96)\n const ema6 = ta.ema(close,128)\n plot(ema1,'EMA1',{ style: 'line', color: '#ff0000', linewidth: 2 })\n plot(ema2,'EMA2',{ style: 'cross', color: '#ff7700', linewidth: 2 })\n plot(ema3,'EMA3',{ style: 'circles', color: '#ffee00', linewidth: 2 })\n plot(ema4,'EMA4',{ style: '❖', color: '#00ff00', linewidth: 2 })\n plot(ema5,'EMA5',{ style: 'triangleUp', color: '#0050ff', linewidth: 2 })\n plot(ema6,'EMA6',{ style: 'arrowDown', color: '#ffffff', linewidth: 2 })\n\n fill('EMA1','EMA2')\n fill('EMA2','EMA3')\n fill('EMA3','EMA4')\n fill('EMA4','EMA5')\n fill('EMA5','EMA6')\n\n\n "),this.editorInstance=o.editor.create(this.editorDiv,{value:e,language:"javascript",theme:"vs-dark",automaticLayout:!0}),console.log("Monaco Editor initialized in pane with initial code.")}loadInitialScript(){let e="";if(this.handler.scriptsManager&&"function"==typeof this.handler.scriptsManager.getLast){const t=this.handler.scriptsManager.getLast();t&&t.code&&(e=t.code)}e?(this.setValue(e),console.log("Loaded most recent script from scriptsManager.")):console.log("No saved scripts available in scriptsManager; editor value remains unchanged.")}open(){this.container.style.display="flex",this.editorInstance?.layout(),window.monaco=!0}close(){this.container.style.display="none",window.monaco=!1}setValue(e){this.editorInstance?.setValue(e)}getValue(){return this.editorInstance?.getValue()||""}async executePineTS(){try{const e=this.getValue(),t=/^(?!\s*\/\/)(?!\s*\*)(.*indicator\s*\(\s*['"]([^'"]+)['"])/m,i=e.match(t),s=i?.[2]?i[2].replace(/['"]/g,""):"defaultScript";console.log("Extracted script key:",s);const n=(this.selectedSeries??this.handler.series).options().title,o=(this.selectedVolumeSeries??this.handler.volumeSeries)?.options?.()?.title||"",r=function(e,t=[]){return e.map(((e,i)=>rn(e,t[i]))).filter((e=>null!==e))}([...(this.selectedSeries??this.handler.series).data()],[...this.selectedVolumeSeries?this.selectedVolumeSeries.data():[]]),a=new es(r,this.handler.series.options().title,"1D"),l=`(context) => { \n \nconst { close, open, high, low, hlc3, volume, hl2, ohlc4 } = context.data;\nconst { plotchar, plot, na, indicator, nz, plotcandle, plotbar, fill} = context.core;\nconst ta = context.ta;\nconst math = context.math;\nconst input = context.input;\n\n${e}\n }`,{plots:c,candles:h,bars:p,fills:d,ta:u}=await a.run(l,void 0,!1);console.log("Plots:",c),console.log("Candles:",h),console.log("Bars:",p);let m=0;if(c)for(const e in c)if(c.hasOwnProperty(e)){Rs(this.handler,e,c[e],void 0,"overwrite");const t=c[e].data;if(Array.isArray(t)){const e=sn(t);e>m&&(m=e)}}if(h)for(const e in h)h.hasOwnProperty(e)&&Rs(this.handler,e,h[e],"Candlestick","overwrite");if(p)for(const e in p)p.hasOwnProperty(e)&&Rs(this.handler,e,p[e],"Bar","overwrite");if(d)for(const e in d)d.hasOwnProperty(e)&&$s(this.handler,d[e]);this.scripts[s]={pineTSInstance:a,ohlc:n,volume:o,code:e,n:m+1};this.handler.seriesMap.get(n);this.replaceScript(s)}catch(e){console.error("Error executing PineTS code:",e)}}replaceScript(e){const t=this.scripts[e];if(!t||!t.ohlc)return void console.warn(`No series information found for script key: ${e}`);const i=t.ohlc,s=this.handler.seriesMap.get(i);if(!s)return void console.warn(`Series with title "${i}" not found.`);const n=s.data().length;if(this._dataChangeHandlers.has(e))try{const t=this._dataChangeHandlers.get(e);s.unsubscribeDataChanged(t),console.log("Unsubscribing old Data Change Handler.... Data Length:",n),this._dataChangeHandlers.delete(e)}catch(t){console.warn(`Error unsubscribing from data changes for script "${e}":`,t)}const o=t=>{try{console.log("Data Changed, updating.... Data Length:",n),this.executeSavedScript(e)}catch(t){console.error(`Error executing saved script for "${e}":`,t)}};this._dataChangeHandlers.set(e,o),s.subscribeDataChanged(o)}async executeSavedScript(e){try{const t=this.scripts[e]?.ohlc,i=this.scripts[e]?.volume,s=this.scripts[e]?.n??void 0;console.log(s);const n=t?this.handler.seriesMap.get(t):null,o=i?this.handler.seriesMap.get(i):null;if(!n)return void console.warn(`Main series with title "${n}" not found.`);const r=rn(n.dataByIndex(n.data().length-1),o?o.dataByIndex(o.data().length-1):void 0),a=this.scripts[e]?.pineTSInstance;if(!a)return void console.warn(`No saved PineTS instance found for key: ${e}`);a.updateData(r);const{plots:l,candles:c,bars:h,fills:p,ta:d}=await a.run(void 0,s,!0);if(console.log("Plots:",l),console.log("Candles:",c),console.log("Bars:",h),l)for(const e in l)l.hasOwnProperty(e)&&Rs(this.handler,e,l[e],void 0,"update");if(c)for(const e in c)l.hasOwnProperty(e)&&Rs(this.handler,e,c[e],"Candlestick","update");if(h)for(const e in h)l.hasOwnProperty(e)&&Rs(this.handler,e,h[e],"Bar","update")}catch(e){console.error("Error executing PineTS code:",e)}}saveScript(e){const t=this.getValue(),i=t.match(/^(?!\s*\/\/)(?!\s*\*)(.*indicator\s*\(\s*['"]([^'"]+)['"])/m),s=i?.[2]?i[2].replace(/['"]/g,""):"defaultScript";this.scripts[s]?this.scripts[s].code=t:this.scripts[s]={ohlc:(this.selectedSeries??this.handler.series).options().title,volume:(this.selectedVolumeSeries??this.handler.volumeSeries).options().title,code:t,pineTSInstance:e??null,n:null},console.log(`Script "${s}" updated in memory.`);const n=this.scripts[s],o=JSON.stringify(n,null,2),r=`save_script_~_${s};;;${o}`;window.callbackFunction(r),console.log(`Script "${s}" sent via callback.`);const a=`save_script_~_cache;;;${o}`;window.callbackFunction(a),console.log('Cache script sent via callback under the name "cache".')}async saveToFile(e){const t=this.getValue(),i=prompt("Enter a new script name/title:","MyNewScript");if(!i)return void console.warn("Save To File canceled or no name provided.");this.scripts[i]={ohlc:(this.selectedSeries??this.handler.series).options().title,volume:(this.selectedVolumeSeries??this.handler.volumeSeries).options().title,code:t,pineTSInstance:e??null,n:null},console.log(`Script saved as "${i}" in memory.`);const s=JSON.stringify(this.scripts[i],null,2),n=`${i}.json`;this.downloadJson(s,n);const o=JSON.stringify(this.scripts[i],null,2);this.downloadJson(o,"cache.json")}openScriptFromFile(){const e=document.createElement("input");e.type="file",e.accept=".json",e.style.display="none",e.onchange=e=>{const t=e.target;if(t.files&&t.files.length>0){const e=t.files[0],i=new FileReader;i.onload=e=>{try{const t=e.target?.result;if("string"==typeof t){const e=JSON.parse(t);e&&e.code?(this.setValue(e.code),console.log("Loaded script from file.")):console.error("The selected file does not contain a valid script with a 'code' property.")}}catch(e){console.error("Error parsing JSON file:",e)}},i.readAsText(e)}},document.body.appendChild(e),e.click(),e.remove()}downloadJson(e,t){try{const i=new Blob([e],{type:"application/json"}),s=URL.createObjectURL(i),n=document.createElement("a");n.href=s,n.download=t,n.click(),URL.revokeObjectURL(s),console.log(`Downloaded ${t}`)}catch(e){console.error("Failed to download data: "+e)}}onDragStart(e){this.isResizing=!0,this.startY=e.clientY,this.startHeight=parseInt(window.getComputedStyle(this.container).height,10),e.preventDefault()}onDrag(e){if(!this.isResizing)return;const t=this.startHeight+(this.startY-e.clientY),i=Math.min(Math.max(t,this.MIN_HEIGHT),this.MAX_HEIGHT);this.container.style.height=`${i}px`,this.editorInstance?.layout()}onDragEnd(e){this.isResizing&&(this.isResizing=!1)}populateMainSeriesSelectMenu(e,t){const i=document.createElement("div");Object.assign(i.style,{position:"absolute",top:`${e.clientY}px`,left:`${e.clientX}px`,backgroundColor:"#333",color:"white",padding:"10px",borderRadius:"4px",zIndex:"100000"});const s=document.createElement("ul");Object.assign(s.style,{listStyle:"none",margin:"0",padding:"0"});const n=Array.from(this.handler.seriesMap.entries()).map((([e,t])=>({label:e,value:t})));this.handler.volumeSeries&&n.push({label:"Volume",value:this.handler.volumeSeries}),n.forEach((e=>{const n=document.createElement("li");n.innerText=e.label,n.style.cursor="pointer",n.style.padding="5px",n.onclick=()=>{t(e.value),document.body.removeChild(i)},s.appendChild(n)}));const o=document.createElement("li");o.innerText="Cancel",o.style.cursor="pointer",o.style.padding="5px",o.onclick=()=>{document.body.removeChild(i)},s.appendChild(o),i.appendChild(s),document.body.appendChild(i)}populateVolumeSeriesSelectMenu(e,t){const i=document.createElement("div");Object.assign(i.style,{position:"absolute",top:`${e.clientY}px`,left:`${e.clientX}px`,backgroundColor:"#333",color:"white",padding:"10px",borderRadius:"4px",zIndex:"100000"});const s=document.createElement("ul");Object.assign(s.style,{listStyle:"none",margin:"0",padding:"0"});const n=document.createElement("li");n.innerText="None",n.style.cursor="pointer",n.style.padding="5px",n.onclick=()=>{t(null),document.body.removeChild(i)},s.appendChild(n);const o=Array.from(this.handler.seriesMap.entries()).map((([e,t])=>({label:e,value:t})));this.handler.volumeSeries&&o.push({label:"Volume",value:this.handler.volumeSeries}),o.forEach((e=>{const n=document.createElement("li");n.innerText=e.label,n.style.cursor="pointer",n.style.padding="5px",n.onclick=()=>{t(e.value),document.body.removeChild(i)},s.appendChild(n)}));const r=document.createElement("li");r.innerText="Cancel",r.style.cursor="pointer",r.style.padding="5px",r.onclick=()=>{document.body.removeChild(i)},s.appendChild(r),i.appendChild(s),document.body.appendChild(i)}}function rn(e,t){let i;return i="number"==typeof e.time?e.time:new Date(e.time).getTime(),isNaN(i)?(console.warn(`Invalid time format: ${e.time}`),null):{...e,openTime:i,closeTime:i+86399,volume:void 0!==e.volume?Number(e.volume):void 0!==t?Number(t.value):0}}class an{makeButton;callbackName;div;isOpen=!1;widget;constructor(e,t,i,s,n,o){this.makeButton=e,this.callbackName=o,this.div=document.createElement("div"),this.div.classList.add("topbar-menu"),this.widget=this.makeButton(i+" ↓",null,s,!0,n),this.updateMenuItems(t),this.widget.elem.addEventListener("click",(()=>{if(this.isOpen=!this.isOpen,!this.isOpen)return void(this.div.style.display="none");let e=this.widget.elem.getBoundingClientRect();this.div.style.display="flex",this.div.style.flexDirection="column";let t=e.x+e.width/2;this.div.style.left=t-this.div.clientWidth/2+"px",this.div.style.top=e.y+e.height+"px"})),document.body.appendChild(this.div)}updateMenuItems(e){this.div.innerHTML="",e.forEach((e=>{let t=this.makeButton(e,null,!1,!1);t.elem.addEventListener("click",(()=>{this._clickHandler(t.elem.innerText)})),t.elem.style.margin="4px 4px",t.elem.style.padding="2px 2px",this.div.appendChild(t.elem)})),this.widget.elem.innerText=e[0]+" ↓"}_clickHandler(e){this.widget.elem.innerText=e+" ↓",window.callbackFunction(`${this.callbackName??"undefined"}_~_${e}`),this.div.style.display="none",this.isOpen=!1}}class ln{makeButton;div;isOpen=!1;widget;globalCallback;constructor(e,t,i,s,n,o,r){this.makeButton=e,this.globalCallback=r,this.div=document.createElement("div"),this.div.classList.add("topbar-menu"),this.widget=this.makeButton(i+" ↓",null,s,!0,n),this.updateMenuItems(t),this.widget.elem.addEventListener("click",(()=>{if(this.isOpen=!this.isOpen,!this.isOpen)return void(this.div.style.display="none");const e=this.widget.elem.getBoundingClientRect();this.div.style.display="flex",this.div.style.flexDirection="column";const t=e.x+e.width/2;this.div.style.left=t-this.div.clientWidth/2+"px",this.div.style.top=e.y+e.height+"px"})),document.body.appendChild(this.div)}updateMenuItems(e){this.div.innerHTML="",e.forEach((e=>{const t=this.makeButton(e.label,null,!1,!1);t.elem.addEventListener("click",(()=>{this._clickHandler(e)})),t.elem.style.margin="4px 4px",t.elem.style.padding="2px 2px",this.div.appendChild(t.elem)})),e.length>0&&(this.widget.elem.innerText=e[0].label+" ↓")}_clickHandler(e){this.widget.elem.innerText=e.label+" ↓",e.callback?e.callback():this.globalCallback?this.globalCallback(e.label):window.callbackFunction(`${e.label}`),this.div.style.display="none",this.isOpen=!1}}class cn{_handler;_div;left;right;codeEditor;constructor(e){this._handler=e,this._div=document.createElement("div"),this._div.classList.add("topbar");const t=e=>{const t=document.createElement("div");return t.classList.add("topbar-container"),t.style.justifyContent=e,this._div.appendChild(t),t};this.left=t("flex-start"),this.right=t("flex-end"),this.codeEditor=new on(this._handler),this.makeChartMenu([{label:"Add Series",callback:()=>this.openCSVFile("add")},{label:"Edit Series",callback:()=>this.openCSVFile("edit")}],"Add Series",!0,"left"),this.makeButton("{}=> ƒ",!0,!0,"right",!1,void 0,(()=>this.codeEditor.open()))}makeSwitcher(e,t,i,s="left"){const n=document.createElement("div");let o;n.style.margin="4px 12px";const r={elem:n,callbackName:i,intervalElements:e.map((e=>{const i=document.createElement("button");i.classList.add("topbar-button"),i.classList.add("switcher-button"),i.style.margin="0px 2px",i.innerText=e,e==t&&(o=i,i.classList.add("active-switcher-button"));const s=cn.getClientWidth(i);return i.style.minWidth=s+1+"px",i.addEventListener("click",(()=>r.onItemClicked(i))),n.appendChild(i),i})),onItemClicked:e=>{e!=o&&(o.classList.remove("active-switcher-button"),e.classList.add("active-switcher-button"),o=e,window.callbackFunction(`${r.callbackName}_~_${e.innerText}`))}};return this.appendWidget(n,s,!0),r}makeTextBoxWidget(e,t="left",i=null){if(i){const s=document.createElement("input");return s.classList.add("topbar-textbox-input"),s.value=e,s.style.width=`${s.value.length+2}ch`,s.addEventListener("focus",(()=>{window.textBoxFocused=!0})),s.addEventListener("input",(e=>{e.preventDefault(),s.style.width=`${s.value.length+2}ch`})),s.addEventListener("keydown",(e=>{"Enter"==e.key&&(e.preventDefault(),s.blur())})),s.addEventListener("blur",(()=>{window.callbackFunction(`${i}_~_${s.value}`),window.textBoxFocused=!1})),this.appendWidget(s,t,!0),s}{const i=document.createElement("div");return i.classList.add("topbar-textbox"),i.innerText=e,this.appendWidget(i,t,!0),i}}makeMenu(e,t,i,s,n){return new an(this.makeButton.bind(this),e,t,i,s,n)}makeChartMenu(e,t,i,s,n,o){return new ln(this.makeButton.bind(this),e,t,i,s,n,o)}makeButton(e,t,i=!0,s="left",n=!1,o,r){let a=document.createElement("button");a.classList.add("topbar-button"),a.innerText=e,document.body.appendChild(a),a.style.minWidth=`${a.clientWidth+1}px`,document.body.removeChild(a);let l=!1;return a.addEventListener("click",(()=>{n?(l=!l,a.style.backgroundColor=l?"var(--active-bg-color)":"",a.style.color=l?"var(--active-color)":"",o&&window.callbackFunction(`${o}_~_${l}`)):o&&window.callbackFunction(`${o}_~_${a.innerText}`),r&&r()})),i&&this.appendWidget(a,s,t),{elem:a,callbackName:o}}makeSliderWidget(e,t,i,s,n,o="left"){const r=document.createElement("div");r.classList.add("topbar-slider-container"),r.style.display="flex",r.style.alignItems="center",r.style.margin="4px 12px";const a=document.createElement("span");a.classList.add("topbar-slider-label"),a.style.marginRight="8px",a.innerText=s.toString();const l=document.createElement("input");return l.classList.add("topbar-slider"),l.type="range",l.min=e.toString(),l.max=t.toString(),l.step=i.toString(),l.value=s.toString(),l.style.cursor="pointer",l.addEventListener("input",(()=>{a.innerText=l.value,window.callbackFunction(`${n}_~_${l.value}`)})),r.appendChild(a),r.appendChild(l),this.appendWidget(r,o,!0),r}makeSeparator(e="left"){const t=document.createElement("div");t.classList.add("topbar-seperator");("left"==e?this.left:this.right).appendChild(t)}appendWidget(e,t,i){const s="left"==t?this.left:this.right;i?("left"==t&&s.appendChild(e),this.makeSeparator(t),"right"==t&&s.appendChild(e)):s.appendChild(e),this._handler.reSize()}openCSVFile(e){const t=document.createElement("input");t.type="file",t.accept=".csv",t.style.display="none",t.addEventListener("change",(t=>{const i=t.target;if(i.files&&i.files.length>0){const t=i.files[0],s=new FileReader;s.onload=i=>{const s=i.target?.result,n=this.parseCSV(s);if(0===n.length)return void alert("The CSV file is empty.");const o=["time","open","high","low","close"],r=Object.keys(n[0]);if(o.every((e=>r.includes(e))))try{if("edit"===e)this._handler.series.setData(n),console.log("Series data updated successfully.");else if("add"===e){const e=t.name.replace(/\.[^/.]+$/,"");this._handler.createCustomOHLCSeries(e,{}).series.setData(n),console.log("New series added successfully.")}}catch(e){console.error("Error updating chart data:",e)}else alert("The selected CSV does not contain all required OHLCV columns: "+o.join(", "))},s.readAsText(t)}})),document.body.appendChild(t),t.click(),document.body.removeChild(t)}parseCSV(e){const t=e.split(/\r?\n/).filter((e=>e.trim().length>0));if(0===t.length)return[];let i=t[0].split(",").map((e=>e.trim()));const s=i.map((e=>e.toLowerCase()));if(!s.includes("time"))if(s.includes("date")){const e=s.indexOf("date");i[e]="time"}else i[0]="time";return t.slice(1).map((e=>{const t=e.split(",").map((e=>e.trim())),s={};return i.forEach(((e,i)=>{const n=Number(t[i]);s[e]=isNaN(n)?t[i]:n})),s}))}static getClientWidth(e){document.body.appendChild(e);const t=e.clientWidth;return document.body.removeChild(e),t}}const hn={title:"",followMode:"tracking",horizontalDeadzoneWidth:45,verticalDeadzoneHeight:100,verticalSpacing:20,topOffset:20};class pn{_chart;_element;_titleElement;_priceElement;_dateElement;_timeElement;_options;_lastTooltipWidth=null;constructor(e,t){this._options={...hn,...t},this._chart=e;const i=document.createElement("div");un(i,{display:"flex","flex-direction":"column","align-items":"center",position:"absolute",transform:"translate(calc(0px - 50%), 0px)",opacity:"0",left:"0%",top:"0","z-index":"100","background-color":"white","border-radius":"4px",padding:"5px 10px","font-family":"-apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif","font-size":"12px","font-weight":"400","box-shadow":"0px 2px 4px rgba(0, 0, 0, 0.2)","line-height":"16px","pointer-events":"none",color:"#131722"});const s=document.createElement("div");un(s,{"font-size":"12px","line-height":"24px","font-weight":"590"}),dn(s,this._options.title),i.appendChild(s);const n=document.createElement("div");un(n,{"font-size":"12px","line-height":"18px","font-weight":"590"}),dn(n,""),i.appendChild(n);const o=document.createElement("div");un(o,{color:"#787B86"}),dn(o,""),i.appendChild(o);const r=document.createElement("div");un(r,{color:"#787B86"}),dn(r,""),i.appendChild(r),this._element=i,this._titleElement=s,this._priceElement=n,this._dateElement=o,this._timeElement=r;const a=this._chart.chartElement();a.appendChild(this._element);const l=a.parentElement;if(!l)return void console.error("Chart Element is not attached to the page.");const c=getComputedStyle(l).position;"relative"!==c&&"absolute"!==c&&console.error("Chart Element position is expected be `relative` or `absolute`.")}destroy(){this._chart&&this._element&&this._chart.chartElement().removeChild(this._element)}applyOptions(e){this._options={...this._options,...e}}options(){return this._options}updateTooltipContent(e){if(!this._element)return void console.warn("Tooltip element not found.");const t=this._element.getBoundingClientRect();this._lastTooltipWidth=t.width,void 0!==e.title&&this._titleElement?(console.log(`Setting title: ${e.title}`),dn(this._titleElement,e.title)):console.warn("Title element is missing or title data is undefined."),dn(this._priceElement,e.price),dn(this._dateElement,e.date),dn(this._timeElement,e.time)}updatePosition(e){if(!this._chart||!this._element)return;if(this._element.style.opacity=e.visible?"1":"0",!e.visible)return;const t=this._calculateXPosition(e,this._chart),i=this._calculateYPosition(e);this._element.style.transform=`translate(${t}, ${i})`}_calculateXPosition(e,t){const i=e.paneX+t.priceScale("left").width(),s=this._lastTooltipWidth?Math.ceil(this._lastTooltipWidth/2):this._options.horizontalDeadzoneWidth;return`calc(${Math.min(Math.max(s,i),t.timeScale().width()-s)}px - 50%)`}_calculateYPosition(e){if("top"==this._options.followMode)return`${this._options.topOffset}px`;const t=e.paneY,i=t<=this._options.verticalSpacing+this._options.verticalDeadzoneHeight;return`calc(${t+(i?1:-1)*this._options.verticalSpacing}px${i?"":" - 100%"})`}}function dn(e,t){e&&t!==e.innerText&&(e.innerText=t,e.style.display=t?"block":"none")}function un(e,t){for(const[i,s]of Object.entries(t))e.style.setProperty(i,s)}function mn(e,t,i=1,s){const n=Math.round(t*e),o=Math.round(i*t),r=function(e){return Math.floor(.5*e)}(o);return{position:n-r,length:o}}class gn{_data;constructor(e){this._data=e}draw(e){this._data.visible&&e.useBitmapCoordinateSpace((e=>{const t=e.context,i=mn(this._data.x,e.horizontalPixelRatio,1);t.fillStyle=this._data.color,t.fillRect(i.position,this._data.topMargin*e.verticalPixelRatio,i.length,e.bitmapSize.height)}))}}class fn{_data;constructor(e){this._data=e}update(e){this._data=e}renderer(){return new gn(this._data)}zOrder(){return"bottom"}}const yn={lineColor:"rgba(0, 0, 0, 0.2)",priceExtractor:e=>void 0!==e.value?e.value.toFixed(2):void 0!==e.close?e.close.toFixed(2):""};class bn{_options;_tooltip=void 0;_paneViews;_data={x:0,visible:!1,color:"rgba(0, 0, 0, 0.2)",topMargin:0};_attachedParams;constructor(e){this._options={...yn,...e},this._data.color=this._options.lineColor,this._paneViews=[new fn(this._data)]}attached(e){this._attachedParams=e;const t=this.series();if(t){const e=t.options(),i=e.lineColor||e.color||"rgba(0,0,0,0.2)";this._options.autoColor&&this.applyOptions({lineColor:i})}this._setCrosshairMode(),e.chart.subscribeCrosshairMove(this._moveHandler),this._createTooltipElement()}detached(){const e=this.chart();e&&e.unsubscribeCrosshairMove(this._moveHandler),this._hideCrosshair(),this._hideTooltip()}paneViews(){return this._paneViews}updateAllViews(){this._paneViews.forEach((e=>e.update(this._data)))}setData(e){this._data=e,this.updateAllViews(),this._attachedParams?.requestUpdate()}currentColor(){return this._options.lineColor}chart(){return this._attachedParams?.chart}series(){return this._attachedParams?.series}applyOptions(e){this._options={...this._options,...e},e.lineColor&&this.setData({...this._data,color:e.lineColor}),this._tooltip&&this._tooltip.applyOptions({...this._options.tooltip}),this._attachedParams?.requestUpdate()}_setCrosshairMode(){const e=this.chart();if(!e)throw new Error("Unable to change crosshair mode because the chart instance is undefined");e.applyOptions({crosshair:{mode:t.CrosshairMode.Magnet,vertLine:{visible:!1,labelVisible:!1},horzLine:{visible:!1,labelVisible:!1}}})}_moveHandler=e=>this._onMouseMove(e);switch(e){if(this.series()===e)return void console.log("Tooltip is already attached to this series.");this._hideCrosshair(),e.attachPrimitive(this,"Tooltip",!0,!1);const t=e.options(),i=t.lineColor||t.color||"rgba(0,0,0,0.2)";this._options.autoColor&&this.applyOptions({lineColor:i}),console.log("Switched tooltip to the new series.")}_hideCrosshair(){this._hideTooltip(),this.setData({x:0,visible:!1,color:this._options.lineColor,topMargin:0})}_hideTooltip(){this._tooltip&&(this._tooltip.updateTooltipContent({title:"",price:"",date:"",time:""}),this._tooltip.updatePosition({paneX:0,paneY:0,visible:!1}))}_onMouseMove(e){const t=this.chart(),i=this.series(),s=e.logical;if(!s||!t||!i)return void this._hideCrosshair();const n=e.seriesData.get(i);if(!n)return void this._hideCrosshair();const o=this._options.priceExtractor(n),r=t.timeScale().logicalToCoordinate(s),[a,l]=function(e){if(!e)return["",""];const t=new Date(e),i=t.getFullYear(),s=t.toLocaleString("default",{month:"short"});return[`${t.getDate().toString().padStart(2,"0")} ${s} ${i}`,`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}`]}(e.time?Ms(e.time):void 0);if(this._tooltip){const t=i.options()?.title||"Unknown Series",s=this._tooltip.options(),n="top"===s.followMode?s.topOffset+10:0;this.setData({x:r??0,visible:null!==r,color:this._options.lineColor,topMargin:n}),this._tooltip.updateTooltipContent({title:t,price:o,date:a,time:l}),this._tooltip.updatePosition({paneX:e.point?.x??0,paneY:e.point?.y??0,visible:!0})}}_createTooltipElement(){const e=this.chart();if(!e)throw new Error("Unable to create Tooltip element. Chart not attached");this._tooltip=new pn(e,{...this._options.tooltip})}}let vn=class e{colorOption;static colors=["#EBB0B0","#E9CEA1","#E5DF80","#ADEB97","#A3C3EA","#D8BDED","#E15F5D","#E1B45F","#E2D947","#4BE940","#639AE1","#D7A0E8","#E42C2A","#E49D30","#E7D827","#3CFF0A","#3275E4","#B06CE3","#F3000D","#EE9A14","#F1DA13","#2DFC0F","#1562EE","#BB00EF","#B50911","#E3860E","#D2BD11","#48DE0E","#1455B4","#6E009F","#7C1713","#B76B12","#8D7A13","#479C12","#165579","#51007E"];_div;saveDrawings;opacity=0;_opacitySlider;_opacityLabel;rgba;constructor(t,i){this.colorOption=i,this.saveDrawings=t,this._div=document.createElement("div"),this._div.classList.add("color-picker");let s=document.createElement("div");s.style.margin="10px",s.style.display="flex",s.style.flexWrap="wrap",e.colors.forEach((e=>s.appendChild(this.makeColorBox(e))));let n=document.createElement("div");n.style.backgroundColor=window.pane.borderColor,n.style.height="1px",n.style.width="130px";let o=document.createElement("div");o.style.margin="10px";let r=document.createElement("div");r.style.color="lightgray",r.style.fontSize="12px",r.innerText="Opacity",this._opacityLabel=document.createElement("div"),this._opacityLabel.style.color="lightgray",this._opacityLabel.style.fontSize="12px",this._opacitySlider=document.createElement("input"),this._opacitySlider.type="range",this._opacitySlider.value=(100*this.opacity).toString(),this._opacityLabel.innerText=this._opacitySlider.value+"%",this._opacitySlider.oninput=()=>{this._opacityLabel.innerText=this._opacitySlider.value+"%",this.opacity=parseInt(this._opacitySlider.value)/100,this.updateColor()},o.appendChild(r),o.appendChild(this._opacitySlider),o.appendChild(this._opacityLabel),this._div.appendChild(s),this._div.appendChild(n),this._div.appendChild(o),window.containerDiv.appendChild(this._div)}_updateOpacitySlider(){this._opacitySlider.value=(100*this.opacity).toString(),this._opacityLabel.innerText=this._opacitySlider.value+"%"}makeColorBox(t){const i=document.createElement("div");i.style.width="18px",i.style.height="18px",i.style.borderRadius="3px",i.style.margin="3px",i.style.boxSizing="border-box",i.style.backgroundColor=t,i.addEventListener("mouseover",(()=>i.style.border="2px solid lightgray")),i.addEventListener("mouseout",(()=>i.style.border="none"));const s=e.extractRGBA(t);return i.addEventListener("click",(()=>{this.rgba=s,this.updateColor()})),i}static extractRGBA(e){const t=document.createElement("div");t.style.color=e,document.body.appendChild(t);const i=getComputedStyle(t).color;document.body.removeChild(t);const s=i.match(/\d+/g)?.map(Number);if(!s)return[];let n=i.includes("rgba")?parseFloat(i.split(",")[3]):1;return[s[0],s[1],s[2],n]}updateColor(){if(!O.lastHoveredObject||!this.rgba)return;const e=`rgba(${this.rgba[0]}, ${this.rgba[1]}, ${this.rgba[2]}, ${this.opacity})`;O.lastHoveredObject.applyOptions({[this.colorOption]:e}),this.saveDrawings()}openMenu(t){O.lastHoveredObject&&(this.rgba=e.extractRGBA(O.lastHoveredObject._options[this.colorOption]),this.opacity=this.rgba[3],this._updateOpacitySlider(),this._div.style.top=t.top-30+"px",this._div.style.left=t.right+"px",this._div.style.display="flex",setTimeout((()=>document.addEventListener("mousedown",(e=>{this._div.contains(e.target)||this.closeMenu()}))),10))}closeMenu(){document.body.removeEventListener("click",this.closeMenu),this._div.style.display="none"}};class xn{container;_opacitySlider;_opacity_label;exitButton;color="#ff0000";rgba;opacity;applySelection;customColors;constructor(e,t,i){this.applySelection=t,this.rgba=xn.extractRGBA(e),this.opacity=this.rgba[3],this.container=document.createElement("div"),this.container.classList.add("color-picker"),this.container.style.display="flex",this.container.style.flexDirection="column",this.container.style.width="200px",this.container.style.height="350px",this.container.style.position="relative";const s=this.createColorGrid(),n=this.createOpacityUI();this.exitButton=this.createExitButton(),this.customColors=i??void 0,this.container.appendChild(s),this.container.appendChild(this.createSeparator()),this.customColors&&0!==this.customColors.length&&this.createCustomColorSection(),this.container.appendChild(this.createSeparator()),this.container.appendChild(n),this.container.appendChild(this.exitButton)}createCustomColorSection(){if(!this.customColors||0===this.customColors.length)return null;const e=document.createElement("div");e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="center",e.style.margin="8px 0";const t=document.createElement("div");t.innerText="Custom Colors",t.style.fontSize="14px",t.style.color="white",e.appendChild(t);const i=document.createElement("div");i.style.display="flex",i.style.flexWrap="wrap",i.style.justifyContent="center",i.style.gap="5px";const s=e=>{const t=document.createElement("div");return t.style.width="20px",t.style.height="20px",t.style.borderRadius="4px",t.style.cursor="pointer",t.style.border="1px solid #999",t.style.backgroundColor=e,t.title=e,t.addEventListener("click",(()=>{this.updateTargetColor()})),t};this.customColors.forEach((e=>{i.appendChild(s(e))}));const n=document.createElement("div");return n.style.width="20px",n.style.height="20px",n.style.borderRadius="4px",n.style.cursor="pointer",n.style.border="1px solid #999",n.style.backgroundColor="rgba(0,0,0,0)",n.style.display="flex",n.style.justifyContent="center",n.style.alignItems="center",n.style.color="#999",n.style.fontSize="16px",n.innerText="+",n.title="Add custom color",n.addEventListener("click",(e=>{const t=document.createElement("input");t.type="color",t.value=this.color,t.style.position="absolute",t.style.left="-9999px",document.body.appendChild(t),t.addEventListener("input",(()=>{this.color=t.value,this.updateTargetColor(),this.customColors.includes(this.color)||(this.customColors.push(this.color),i.appendChild(s(this.color)),this.saveColors()),document.body.removeChild(t)}),{once:!0}),t.click()})),i.appendChild(n),e.appendChild(i),e}saveColors(){const e=`save_defaults_colors_~_${JSON.stringify(this.customColors,null,2)}`;window.callbackFunction(e)}createExitButton(){const e=document.createElement("div");return e.innerText="✕",e.title="Close",e.style.position="absolute",e.style.bottom="5px",e.style.right="5px",e.style.width="20px",e.style.height="20px",e.style.cursor="pointer",e.style.display="flex",e.style.justifyContent="center",e.style.alignItems="center",e.style.fontSize="16px",e.style.backgroundColor="#ccc",e.style.borderRadius="50%",e.style.color="#000",e.style.boxShadow="0 1px 3px rgba(0,0,0,0.3)",e.addEventListener("mouseover",(()=>{e.style.backgroundColor="#e74c3c",e.style.color="#fff"})),e.addEventListener("mouseout",(()=>{e.style.backgroundColor="#ccc",e.style.color="#000"})),e.addEventListener("click",(()=>{this.closeMenu()})),e}createColorGrid(){const e=document.createElement("div");e.style.display="grid",e.style.gridTemplateColumns="repeat(7, 1fr)",e.style.gap="5px",e.style.overflowY="auto",e.style.flex="1";return xn.generateFullSpectrumColors(9).forEach((t=>{const i=this.createColorBox(t);e.appendChild(i)})),e}createColorBox(e){const t=document.createElement("div");return t.style.aspectRatio="1",t.style.borderRadius="6px",t.style.backgroundColor=e,t.style.cursor="pointer",t.addEventListener("click",(()=>{this.rgba=xn.extractRGBA(e),this.updateTargetColor()})),t}static generateFullSpectrumColors(e){const t=[];for(let i=0;i<=255;i+=Math.floor(255/e))t.push(`rgba(255, ${i}, 0, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(${i}, 255, 0, 1)`);for(let i=0;i<=255;i+=Math.floor(255/e))t.push(`rgba(0, 255, ${i}, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(0, ${i}, 255, 1)`);for(let i=0;i<=255;i+=Math.floor(255/e))t.push(`rgba(${i}, 0, 255, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(255, 0, ${i}, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(${i}, ${i}, ${i}, 1)`);return t}createOpacityUI(){const e=document.createElement("div");e.style.margin="10px",e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="center";const t=document.createElement("div");return t.style.color="lightgray",t.style.fontSize="12px",t.innerText="Opacity",this._opacitySlider=document.createElement("input"),this._opacitySlider.type="range",this._opacitySlider.min="0",this._opacitySlider.max="100",this._opacitySlider.value=(100*this.opacity).toString(),this._opacitySlider.style.width="80%",this._opacity_label=document.createElement("div"),this._opacity_label.style.color="lightgray",this._opacity_label.style.fontSize="12px",this._opacity_label.innerText=`${this._opacitySlider.value}%`,this._opacitySlider.oninput=()=>{this._opacity_label.innerText=`${this._opacitySlider.value}%`,this.opacity=parseInt(this._opacitySlider.value)/100,this.updateTargetColor()},e.appendChild(t),e.appendChild(this._opacitySlider),e.appendChild(this._opacity_label),e}createSeparator(){const e=document.createElement("div");return e.style.height="1px",e.style.width="100%",e.style.backgroundColor="#ccc",e.style.margin="5px 0",e}openMenu(e,t,i){this.applySelection=i,this.container.style.display="block",document.body.appendChild(this.container);const s=this.container.offsetWidth||150,n=this.container.offsetHeight||250,o=e.clientX,r=e.clientY,a=window.innerWidth,l=window.innerHeight;let c=o+t;const h=c+s>a?o-s:c,p=r+n>l?l-n-10:r;this.container.style.left=`${h}px`,this.container.style.top=`${p}px`,this.container.style.display="flex",this.container.style.position="absolute",this.exitButton.style.bottom="5px",this.exitButton.style.right="5px";const d=e=>{const t=this.container.getBoundingClientRect(),i=t.left-s,o=t.right+s,r=t.top-n,a=t.bottom+n;(e.clientXo||e.clientYa)&&(this.closeMenu(),document.removeEventListener("mousemove",d))};this.container.addEventListener("mouseenter",(()=>{document.addEventListener("mousemove",d)})),this.container.addEventListener("mouseleave",(()=>{document.removeEventListener("mousemove",d),this.closeMenu()})),document.addEventListener("mousedown",this._handleOutsideClick.bind(this),{once:!0})}closeMenu(){this.container.style.display="none",document.removeEventListener("mousedown",this._handleOutsideClick)}_handleOutsideClick(e){this.container.contains(e.target)||this.closeMenu()}static extractRGBA(e){const t=document.createElement("div");t.style.color=e,document.body.appendChild(t);const i=getComputedStyle(t).color;document.body.removeChild(t);const s=i.match(/\d+/g)?.map(Number)||[0,0,0],n=i.includes("rgba")?parseFloat(i.split(",")[3]):1;return[s[0],s[1],s[2],n]}getElement(){return this.container}update(e,t){this.rgba=xn.extractRGBA(e),this.opacity=this.rgba[3],this.applySelection=t,this.updateTargetColor()}updateTargetColor(){this.color=`rgba(${this.rgba[0]}, ${this.rgba[1]}, ${this.rgba[2]}, ${this.opacity})`,this.applySelection(this.color)}}class _n{static _styles=[{name:"Solid",var:t.LineStyle.Solid},{name:"Dotted",var:t.LineStyle.Dotted},{name:"Dashed",var:t.LineStyle.Dashed},{name:"Large Dashed",var:t.LineStyle.LargeDashed},{name:"Sparse Dotted",var:t.LineStyle.SparseDotted}];_div;_saveDrawings;constructor(e){this._saveDrawings=e,this._div=document.createElement("div"),this._div.classList.add("context-menu"),_n._styles.forEach((e=>{this._div.appendChild(this._makeTextBox(e.name,e.var))})),window.containerDiv.appendChild(this._div)}_makeTextBox(e,t){const i=document.createElement("span");return i.classList.add("context-menu-item"),i.innerText=e,i.addEventListener("click",(()=>{O.lastHoveredObject?.applyOptions({lineStyle:t}),this._saveDrawings()})),i}openMenu(e){this._div.style.top=e.top-30+"px",this._div.style.left=e.right+"px",this._div.style.display="block",setTimeout((()=>document.addEventListener("mousedown",(e=>{this._div.contains(e.target)||this.closeMenu()}))),10)}closeMenu(){document.removeEventListener("click",this.closeMenu),this._div.style.display="none"}}const wn={visible:!0,sections:0,upColor:void 0,downColor:void 0,borderUpColor:void 0,borderDownColor:void 0,rightSide:!0,width:0,lineColor:"#ffffff",lineStyle:t.LineStyle.Solid,drawGrid:!0,gridWidth:1,gridColor:"rgba(255, 255, 255, 0.125)",gridLineStyle:t.LineStyle.SparseDotted};class Cn extends a{p1;p2;_listeners=[];visibleRange=null;_originalData;_currentSlice=null;_vpData;_paneViews;_options;_pendingUpdate=!1;_state=N.NONE;_latestHoverPoint=null;_startDragPoint=null;static _mouseIsDown=!1;_hovered=!1;chart_;series_;constructor(e,t=wn,i,s){super(),this.chart_=e.chart,this.series_=e.series;const n=this.series_.data(),o=e.volumeSeries.data(),r=this.chart_.timeScale();this.visibleRange=r.getVisibleLogicalRange(),i&&s?(this.p1=i,this.p2=s):(this.p1={time:null,logical:this.visibleRange?.from??0,price:0},this.p2={time:null,logical:this.visibleRange?.to??this.series.data().length-1,price:0}),this._options={...wn,...t},o.length>0&&o.every((e=>"value"in e))?this._originalData=n.map(((e,t)=>({...e,x1:t,x2:t,volume:o[t]?.value||0}))):(console.warn('[ProfileProcessor] volumeData is empty or missing "value" property.'),this._originalData=n.map(((e,t)=>({...e,x1:t,x2:t,volume:0})))),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this._paneViews=[new Sn(this)],this._subscribeEvents(),this.update()}_handleDomMouseDown=()=>{};_handleDomMouseUp=()=>{this._onMouseUp()};_subscribe(e,t){document.addEventListener(e,t),this._listeners.push({name:e,listener:t})}_unsubscribe(e,t){document.removeEventListener(e,t);const i=this._listeners.findIndex((i=>i.name===e&&i.listener===t));-1!==i&&this._listeners.splice(i,1)}_subscribeEvents(){this.p1&&this.p2&&this.p1.time&&this.p2.time?(this.chart_.subscribeCrosshairMove(this._handleMouseMove),this.chart_.subscribeClick(this._handleMouseDownOrUp),this._listeners.push({name:"crosshairMove",listener:this._handleMouseMove},{name:"click",listener:this._handleMouseDownOrUp})):(this.chart_.timeScale().subscribeVisibleLogicalRangeChange(this._handleVisibleLogicalRangeChange),this._listeners.push({name:"visibleLogicalRangeChange",listener:this._handleVisibleLogicalRangeChange}))}_handleVisibleLogicalRangeChange=()=>{const e=this.chart_.timeScale();if(this.visibleRange=e.getVisibleLogicalRange(),!this.visibleRange||!this.series_)return void console.warn("[VolumeProfile] Visible range or source series is undefined.");this.p1={time:null,logical:this.visibleRange.from??0,price:0},this.p2={time:null,logical:this.visibleRange.to??this.series_.data().length-1,price:0},this.sliceData();const t=this.calculateVolumeProfile();t?(this._vpData=t,this.updateAllViews(),this.requestUpdate()):console.warn("[VolumeProfile] Failed to process Volume Profile data on visible range change.")};_handleMouseMove=e=>{const t=this._eventToPoint(e);this._latestHoverPoint=t,Cn._mouseIsDown?this._handleDragInteraction(e):this._mouseIsOverPointCanvas(e,1)||this._mouseIsOverPointCanvas(e,2)?this._state===N.NONE&&this._moveToState(N.HOVERING):this._state!==N.NONE&&this._moveToState(N.NONE)};_handleMouseDownOrUp=()=>{Cn._mouseIsDown=!Cn._mouseIsDown,Cn._mouseIsDown?this._onMouseDown():this._onMouseUp(),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()};_onMouseDown(){if(this._startDragPoint=this._latestHoverPoint,!this._startDragPoint||!this.p1||!this.p2)return;const e=this._mouseIsOverPointRaw(this._startDragPoint,this.p1),t=this._mouseIsOverPointRaw(this._startDragPoint,this.p2);e?this._moveToState(N.DRAGGINGP1):t?this._moveToState(N.DRAGGINGP2):this._moveToState(N.DRAGGING)}_onMouseUp(){Cn._mouseIsDown=!1,this._startDragPoint=null,this._moveToState(N.HOVERING),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}_handleDragInteraction(e){if(this._state!==N.DRAGGING&&this._state!==N.DRAGGINGP1&&this._state!==N.DRAGGINGP2)return;const t=this._eventToPoint(e);if(!t||!this._startDragPoint)return;const i={logical:t.logical-this._startDragPoint.logical,price:t.price-this._startDragPoint.price};this._onDrag(i),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update(),this._startDragPoint=t}_onDrag(e){this.p1&&this.p2&&(this._state===N.DRAGGING?(this._addDiffToPoint(this.p1,e.logical,e.price),this._addDiffToPoint(this.p2,e.logical,e.price)):this._state===N.DRAGGINGP1?this._addDiffToPoint(this.p1,e.logical,e.price):this._state===N.DRAGGINGP2&&this._addDiffToPoint(this.p2,e.logical,e.price),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update())}_addDiffToPoint(e,t,i){e.logical=e.logical+t,e.price=e.price+i}_mouseIsOverPointRaw(e,t){if(!e)return!1;return Math.abs(e.logical-t.logical)<1&&Math.abs(e.price-t.price)<1}_mouseIsOverPointCanvas(e,t){if(!e.point||!this.p1||!this.p2)return!1;const i=js(1===t?this.p1:this.p2,this.chart_,this.series_),s=e.point.x-i.x,n=e.point.y-i.y;return s*s+n*n<100}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleDomMouseDown),this._unsubscribe("mouseup",this._handleDomMouseUp);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._subscribe("mousedown",this._handleDomMouseDown),this._unsubscribe("mouseup",this._handleDomMouseUp);break;case N.DRAGGING:case N.DRAGGINGP1:case N.DRAGGINGP2:document.body.style.cursor="grabbing",this._hovered=!1,this._unsubscribe("mousedown",this._handleDomMouseDown),this._subscribe("mouseup",this._handleDomMouseUp)}this._state=e,this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}_eventToPoint(e){if(!e.point||null==e.logical)return null;const t=this.series_.coordinateToPrice(e.point.y);return null==t?null:{time:e.time??null,logical:e.logical,price:t.valueOf()}}sliceData(){if(!this.p1||!this.p2)return;const e=Math.min(this.p1.logical,this.p2.logical),t=Math.max(this.p1.logical,this.p2.logical);this._currentSlice=this._originalData.slice(Math.max(0,e),Math.min(t+1,this._originalData.length-1))}calculateDynamicSections(e,t,i){if(e<=0||i<=t)return 10;const s=e/20,n=(i-t)/5,o=2*Math.max(1,Math.floor(Math.max(s,n)));return Math.max(5,o)}calculateVolumeProfile(){const e=Math.min(this.visibleRange.to,this._originalData.length-1)-Math.max(this.visibleRange.from,0);let t=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;const s=[];let n;if(this._currentSlice&&this._currentSlice.length>0){for(const e of this._currentSlice){const s=e.close??e.open;void 0!==s&&(t=Math.min(t,s),i=Math.max(i,s))}t!==Number.POSITIVE_INFINITY&&i!==Number.NEGATIVE_INFINITY||(t=0,i=1);let o=void 0!==this._options.sections&&this._options.sections>0?this._options.sections:this.calculateDynamicSections(e,t,i);const r=(i===t?1:i-t)/o;for(let e=0;e=i&&t=(e.open??0),i=e.volume||0;t?o+=i:a+=i}}const c=o>=a,h=c?this._options.upColor??l(this.series_.options().upColor,.1)??"rgba(0,128,0,0.1)":this._options.downColor??l(this.series_.options().downColor,.1)??"rgba(128,0,0,0.1)",p=c?this._options.borderUpColor??l(this.series_.options().upColor,.5)??"rgba(0,128,0,0.66)":this._options.borderDownColor??l(this.series_.options().downColor,.5)??"rgba(128,0,0,0.66)";s.push({price:i,upData:o,downData:a,color:this._options.visible?h:"rgba(0,0,0,0)",borderColor:this._options.visible?p:"rgba(0,0,0,0)",minPrice:i,maxPrice:n})}n=this._options.rightSide?this._currentSlice[this._currentSlice.length-1].time:this._currentSlice[0].time}else n=Date.now().toString();return this.update(),{time:n,profile:s,width:this._options.width??20,visibleRange:this.visibleRange}}update(){this._pendingUpdate||(this._pendingUpdate=!0,requestAnimationFrame((()=>{super.requestUpdate(),this.updateAllViews(),console.log("VolumeProfile updated p1=",this.p1,"p2=",this.p2),this._pendingUpdate=!1})))}updateAllViews(){this._paneViews.forEach((e=>e.update()))}paneViews(){return this._paneViews}autoscaleInfo(){return this._vpData.profile.length?{priceRange:{minValue:this._vpData.profile[0].minPrice,maxValue:this._vpData.profile[this._vpData.profile.length-1].maxPrice}}:null}applyOptions(e){this._options={...this._options,...e},this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}}class Sn{_source;_x=null;_width=0;_items=[];_maxVolume;visibleRange=null;_p1={x:null,y:null};_p2={x:null,y:null};constructor(e){this._source=e,this._maxVolume=this._source._vpData.profile.reduce(((e,t)=>Math.max(e,t.upData+t.downData)),0)}update(){if(!this._source.p1||!this._source.p2)return;const e=this._source._vpData,t=this._source.chart_,i=this._source.series_,s=t.timeScale();this._x=s.timeToCoordinate(e.time)??null;const n=s.options().barSpacing??1,o=Math.max(0,Math.min(this._source.p1.logical,this._source.p2.logical)),r=Math.min(Math.max(this._source.p1.logical,this._source.p2.logical),this._source._originalData.length-1);if(this._width=(e.width&&0!==e.width?e.width:(r-o)/3)*n,this._p1=js(this._source.p1,t,i),this._p2=js(this._source.p2,t,i),this._items=[],e.profile.length){this._maxVolume=e.profile.reduce(((e,t)=>Math.max(e,t.upData+t.downData)),0);for(const t of e.profile){const e=i.priceToCoordinate(t.maxPrice),s=i.priceToCoordinate(t.minPrice);if(null==e||null==s){this._items.push({y1:null,y2:null,combinedWidth:0,upWidth:0,downWidth:0,color:t.color,borderColor:t.borderColor});continue}const n=t.upData+t.downData,o=this._maxVolume>0?this._width*(n/this._maxVolume):0;let r=0,a=0;n>0&&(r=t.upData/n*o,a=t.downData/n*o),this._items.push({y1:e,y2:s,combinedWidth:o,upWidth:r,downWidth:a,color:t.color,borderColor:t.borderColor})}}}renderer(){return new kn({x:this._x,width:this._width,items:this._items,visibleRange:{from:this._source.chart.timeScale().logicalToCoordinate(Math.max(0,this._source.visibleRange.from)),to:this._source.chart.timeScale().logicalToCoordinate(Math.min(this._source.series.data().length-1,this._source.visibleRange.to))},maxVolume:this._maxVolume,maxBars:this._source.series.data().length},this._p1,this._p2,this._source._options,!1)}zOrder(){return"bottom"}}class kn extends F{_data;options;p1;p2;constructor(e,t,i,s,n){super(t,i,s,n),this._data=e,this.options=s,this.p1=t,this.p2=i}draw(){}drawBackground(e){console.log(`[VolumeProfileRenderer] draw() called with rightSide: ${this.options.rightSide}`),e.useBitmapCoordinateSpace((e=>{let t=e.context;this._drawGrid(t,e),U(t,this.options.lineStyle),this._data.items.forEach((i=>{if(null===i.y1||null===i.y2)return;if(null===this._data.x)return;const s=Math.min(i.y1,i.y2)*e.verticalPixelRatio,n=Math.abs(i.y2-i.y1)*e.verticalPixelRatio,o=i.upWidth+i.downWidth,r=o*e.horizontalPixelRatio;let a;a=this.options.rightSide?(this._data.x-o)*e.horizontalPixelRatio:this._data.x*e.horizontalPixelRatio;const l=Math.min(Math.max(.25*n,2),25);if(n>0){t.beginPath(),this._drawRoundedRect(t,a,s,r,n,l),t.strokeStyle=i.borderColor,t.lineWidth=1,t.stroke();const c=Math.max(i.upWidth,i.downWidth)*e.horizontalPixelRatio;let h;h=this.options.rightSide?a+(o-c):a,t.beginPath(),this._drawRoundedRect(t,h,s,c,n,l),t.fillStyle=i.color,t.fill()}}))}))}_drawGrid(e,i){const{items:s,x:n}=this._data;if(!s||0===s.length||null===n)return;if(!this.options.drawGrid)return;let o;o=void 0!==this.options.gridWidth&&1!==this.options.gridWidth?this.options.gridWidth*i.horizontalPixelRatio:(this._data.visibleRange.to-this._data.visibleRange.from)*i.horizontalPixelRatio,e.strokeStyle=this.options.visible?this.options.gridColor||"rgba(255, 255, 255, 0.2)":"rgba(0,0,0,0)",U(e,this.options.gridLineStyle||t.LineStyle.Solid),s.forEach((t=>{if(null===t.y1||null===t.y2)return;const s=(t.upWidth+t.downWidth)*i.horizontalPixelRatio;let r,a;this.options.rightSide?(r=n-o,a=n-s):(r=n+s,a=n+o);const l=t.y1*i.verticalPixelRatio,c=t.y2*i.verticalPixelRatio;e.beginPath(),e.moveTo(r,l),e.lineTo(a,l),e.stroke(),e.beginPath(),e.moveTo(r,c),e.lineTo(a,c),e.stroke()}))}_drawRoundedRect(e,t,i,s,n,o){const r=Math.abs(Math.min(o,s/2,n/2));e.beginPath(),s>0&&o>0&&(this.options.rightSide?(e.moveTo(t+r,i),e.lineTo(t+s,i),e.lineTo(t+s,i+n),e.lineTo(t+r,i+n),e.arcTo(t,i+n,t,i+n-r,r),e.lineTo(t,i+r),e.arcTo(t,i,t+r,i,r)):(e.moveTo(t,i),e.lineTo(t+s-r,i),e.arcTo(t+s,i,t+s,i+r,r),e.lineTo(t+s,i+n-r),e.arcTo(t+s,i+n,t+s-r,i+n,r),e.lineTo(t,i+n),e.lineTo(t,i)),e.closePath())}}function En(e,t){if(e.length0){let t=e[0];s[0]=t;for(let n=1;n0===i?0:t-e[i-1])),s=i.map((e=>Math.max(e,0))),n=i.map((e=>Math.max(-e,0))),o=Mn(s,t),r=Mn(n,t);return 0===r?100:0===o?0:100-100/(1+o/r)}function Tn(e,t,i){for(let s=0;s=o?t:i}}function In(e,t,i){const s=e&&t in e?e[t]:i;return Array.isArray(s)?s.map((e=>Number(e))):[Number(s)]}function An(e,t){return t{if(o1?`_${t+1}`:""),d="ALMA"+i+(l>1?` #${t+1}`:"");c.push({key:p,title:d,type:"line",data:h})}return c}},Ln=(e,t)=>{let i=0;return e.forEach((e=>{const s=e.close-t;i+=s*s})),Math.sqrt(i/e.length)},Nn={name:"Bollinger Bands",shortName:"BOLL",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray"},multiplier:{defaultValue:[2],type:"numberArray"}},calc(e,t){const i=In(t,"length",this.paramMap.length.defaultValue),s=In(t,"multiplier",this.paramMap.multiplier.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(l+=t.close,i>=r-1){const s=l/r,n=e.slice(i-(r-1),i+1),o=Ln(n,s);c.push({time:t.time,value:s+a*o}),h.push({time:t.time,value:s}),p.push({time:t.time,value:s-a*o}),l-=e[i-(r-1)].close}else c.push({time:t.time,value:NaN}),h.push({time:t.time,value:NaN}),p.push({time:t.time,value:NaN})}));const d=n>1?`_${t+1}`:"";o.push({key:`boll_up${d}`,title:`BOLL_UP${r}${d}`,type:"line",data:c}),o.push({key:`boll_mid${d}`,title:`BOLL_MID${r}${d}`,type:"line",data:h}),o.push({key:`boll_dn${d}`,title:`BOLL_DN${r}${d}`,type:"line",data:p})}return o}},On={name:"Exponential Moving Average",shortName:"EMA",shouldOhlc:!0,paramMap:{length:{defaultValue:[6,12,20],type:"numberArray"}},calc(e,t){const i=In(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{let o=0,r=0;const a=[];e.forEach(((i,s)=>{if(r+=i.close,s===t-1)o=r/t;else if(s>t-1){const e=2/(t+1);o=(i.close-o)*e+o}s>=t-1?(a.push({time:i.time,value:o}),r-=e[s-(t-1)].close):a.push({time:i.time,value:NaN})}));const l="ema"+(i.length>1?`_${n+1}`:""),c="EMA"+t+(i.length>1?` #${n+1}`:"");s.push({key:l,title:c,type:"line",data:a})})),s}},Vn={name:"Highest High",shortName:"HH",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=In(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:""),a="HH"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Rn={name:"Linear Regression",shortName:"LINREG",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=In(t,"length",this.paramMap.length.defaultValue),s=e.map((e=>e.close)),n=[];return i.forEach(((t,o)=>{const r=[];e.forEach(((e,i)=>{if(ie+t),0),r=(s*i.reduce(((e,t,i)=>e+i*t),0)-n*o)/(s*(s*(s-1)*(2*s-1)/6)-n*n);return(o-r*n)/s+r*(s-1)}(s.slice(i-(t-1),i+1),t,0);r.push({time:e.time,value:n})}));const a="linreg"+(i.length>1?`_${o+1}`:""),l="LINREG"+t+(i.length>1?` #${o+1}`:"");n.push({key:a,title:l,type:"line",data:r})})),n}},Bn={name:"Lowest Low",shortName:"LL",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=In(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:""),a="LL"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},$n={name:"Median",shortName:"Median",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=In(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.close));n.sort(((e,t)=>e-t));const r=Math.floor(n.length/2),a=n.length%2==0?(n[r-1]+n[r])/2:n[r];o.push({time:i.time,value:a})}));const r="median"+(i.length>1?`_${n+1}`:""),a="Median"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Gn={name:"Moving Average",shortName:"MA",shouldOhlc:!0,paramMap:{length:{defaultValue:[5,10,30,60],type:"numberArray"}},calc(e,t){const i=In(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];let r=0;e.forEach(((i,s)=>{if(r+=i.close,s>=t-1){const n=r/t;o.push({time:i.time,value:n}),r-=e[s-(t-1)].close}else o.push({time:i.time,value:NaN})}));const a="ma"+(i.length>1?`_${n+1}`:""),l="MA"+t+(i.length>1?` #${n+1}`:"");s.push({key:a,title:l,type:"line",data:o})})),s}},Fn={name:"Rolling Moving Average",shortName:"RMA",shouldOhlc:!1,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=In(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=1/t;let r=0;const a=[];e.forEach(((e,t)=>{r=0===t?e.close:o*e.close+(1-o)*r,a.push({time:e.time,value:r})}));const l="rma"+(i.length>1?`_${n+1}`:""),c="RMA"+t+(i.length>1?` #${n+1}`:"");s.push({key:l,title:c,type:"line",data:a})})),s}},jn={name:"Simple Moving Average",shortName:"SMA",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray"},k:{defaultValue:[2],type:"numberArray"}},calc(e,t){const i=In(t,"n",this.paramMap.n.defaultValue),s=In(t,"k",this.paramMap.k.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{l+=t.close,i>=r-1?(c=i===r-1?l/r:(t.close*a+c*(r-a))/r,l-=e[i-(r-1)].close,h.push({time:t.time,value:c})):h.push({time:t.time,value:NaN})}));const p="sma"+(n>1?`_${t+1}`:""),d="SMA"+r+","+a+(n>1?` #${t+1}`:"");o.push({key:p,title:d,type:"line",data:h})}return o}},Un={name:"Stop and Reverse",shortName:"SAR",shouldOhlc:!0,paramMap:{accStart:{defaultValue:[.02],type:"numberArray"},accStep:{defaultValue:[.02],type:"numberArray"},accMax:{defaultValue:[.2],type:"numberArray"}},calc(e,t){const i=In(t,"accStart",this.paramMap.accStart.defaultValue),s=In(t,"accStep",this.paramMap.accStep.defaultValue),n=In(t,"accMax",this.paramMap.accMax.defaultValue),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t{0!==i?(1===i&&(u=t.close>e[0].close,p=u?t.high:t.low,d=u?e[0].low:e[0].high,m.push({time:e[0].time,value:d})),d+=h*(p-d),u?t.lowp&&(p=t.high,h=Math.min(h+l,c)):t.high>d?(u=!0,d=p,h=a,p=t.high):t.low1?`_${t+1}`:""),f="SAR"+a+","+l+","+c+(o>1?` #${t+1}`:"");r.push({key:g,title:f,type:"line",data:m})}return r}},zn={name:"Super Trend",shortName:"SuperTrend",shouldOhlc:!0,paramMap:{factor:{defaultValue:[3],type:"numberArray"},atrPeriod:{defaultValue:[10],type:"numberArray"}},calc(e,t){const i=In(t,"factor",this.paramMap.factor.defaultValue),s=In(t,"atrPeriod",this.paramMap.atrPeriod.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(id||e[i-1].closep?m:p),u=isNaN(h)?1:h===p?t.close>m?-1:1:t.close1?`_${t+1}`:"";o.push({key:"superTrend"+m,title:"SuperTrend"+r+(n>1?` #${t+1}`:""),type:"line",data:l}),o.push({key:"direction"+m,title:"Direction"+(n>1?` #${t+1}`:""),type:"line",data:c})}return o}},Hn={name:"Symmetrically Weighted Moving Average",shortName:"SWMA",shouldOhlc:!1,paramMap:{window:{defaultValue:[4],type:"numberArray"}},calc(e,t){const i=In(t,"window",this.paramMap.window.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:""),a="SWMA"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Wn={name:"TRIX",shortName:"TRIX",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray"},m:{defaultValue:[9],type:"numberArray"}},calc(e,t){const i=In(t,"n",this.paramMap.n.defaultValue),s=In(t,"m",this.paramMap.m.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{p+=e.close,t===r-1?l=p/r:t>r-1&&(l=(2*e.close+(r-1)*l)/(r+1)),t>=r-1&&(t===2*r-2?c=l:t>2*r-2&&(c=(2*l+(r-1)*c)/(r+1)));let i=NaN;if(t>=2*r-2)if(t===3*r-3)h=c;else if(t>3*r-3){const e=h;h=(2*c+(r-1)*e)/(r+1),i=(h-e)/e*100}if(d.push({time:e.time,value:i}),g.push(i),m+=isNaN(i)?0:i,g.length>a){const e=g[g.length-1-a];m-=isNaN(e)?0:e}const s=g.length>=a&&!isNaN(i)?m/a:NaN;u.push({time:e.time,value:s})}));const f=n>1?`_${t+1}`:"";o.push({key:"trix"+f,title:"TRIX"+r+(n>1?` #${t+1}`:""),type:"line",data:d}),o.push({key:"maTrix"+f,title:n>1?`MATRIX #${t+1}`:"MATRIX",type:"line",data:u})}return o}},qn={name:"Volume Weighted Average Price",shortName:"VWAP",shouldOhlc:!0,paramMap:{anchorInterval:{defaultValue:[1],type:"numberArray"}},calc(e,t,i){if(!i)return[{key:"vwap",title:"VWAP",type:"line",data:[]}];const s=In(t,"anchorInterval",this.paramMap.anchorInterval.defaultValue),n=[];return s.forEach(((t,o)=>{let r=0,a=0;const l=[];e.forEach(((e,s)=>{s%t==0&&(r=0,a=0);const n=i[s]?.value??0,o=(e.high+e.low+e.close)/3;a+=o*n,r+=n;const c=0!==r?a/r:NaN;l.push({time:e.time,value:c})}));const c=s.length>1?`_${o+1}`:"";n.push({key:"vwap"+c,title:"VWAP"+t+(s.length>1?` #${o+1}`:""),type:"line",data:l})})),n}},Xn={name:"Volume Weighted Moving Average",shortName:"VWMA",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray"}},calc(e,t,i){if(!i)return[{key:"vwma",title:"VWMA",type:"line",data:[]}];const s=In(t,"length",this.paramMap.length.defaultValue),n=[];return s.forEach(((t,o)=>{let r=0,a=0;const l=[];e.forEach(((s,n)=>{const o=i[n]?.value??0;if(r+=s.close*o,a+=o,n>=t-1){const o=0!==a?r/a:NaN;l.push({time:s.time,value:o});const c=i[n-(t-1)].value??0;r-=e[n-(t-1)].close*c,a-=c}else l.push({time:s.time,value:NaN})}));const c=s.length>1?`_${o+1}`:"";n.push({key:"vwma"+c,title:"VWMA"+t+(s.length>1?` #${o+1}`:""),type:"line",data:l})})),n}},Jn={name:"Weighted Moving Average",shortName:"WMA",shouldOhlc:!1,paramMap:{length:{defaultValue:[9],type:"numberArray"}},calc(e,t){const i=In(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:"";s.push({key:"wma"+r,title:"WMA"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o})})),s}},Yn={name:"High & Low",shortName:"HHLL",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=In(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[],r=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:"";s.push({key:"hh"+a,title:"HH"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o}),s.push({key:"ll"+a,title:"LL"+t+(i.length>1?` #${n+1}`:""),type:"line",data:r})})),s}},Kn=[Dn,Nn,On,Vn,Yn,Rn,Bn,$n,Gn,Fn,jn,Un,zn,Hn,Wn,qn,Xn,Jn],Qn={name:"Awesome Oscillator",shortName:"AO",shouldOhlc:!0,paramMap:{shortPeriod:{defaultValue:[5],type:"numberArray",min:1,max:100},longPeriod:{defaultValue:[34],type:"numberArray",min:1,max:200}},calc(e,t){const i=In(t,"shortPeriod",[5]),s=In(t,"longPeriod",[34]),n=Math.max(i.length,s.length),o=[];for(let r=0;r{const s=(t.high+t.low)/2;h+=s,p+=s;let n=NaN,o=NaN;if(i>=a-1){n=h/a;const t=(e[i-(a-1)].high+e[i-(a-1)].low)/2;h-=t}if(i>=l-1){o=p/l;const t=(e[i-(l-1)].high+e[i-(l-1)].low)/2;p-=t}let r=NaN;i>=c-1&&(r=n-o),d.push({time:t.time,value:r})}));const u="ao"+(n>1?`_${r+1}`:""),m="AO"+An(i,r)+(n>1?` #${r+1}`:"");Tn(d,t?.upColor??"green",t?.downColor??"red"),o.push({key:u,title:m,type:"histogram",data:d,pane:1})}return o}},Zn={name:"Average True Range",shortName:"ATR",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=In(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];let r=0;const a=[];e.forEach(((i,s)=>{if(0===s)return void o.push({time:i.time,value:NaN});const n=e[s-1].close,l=Math.max(i.high-i.low,Math.abs(i.high-n),Math.abs(i.low-n));a.push(l),r+=l,a.length>t&&(r-=a.shift());const c=a.length>=t?r/t:NaN;o.push({time:i.time,value:c})}));const l=i.length>1?`_${n+1}`:"";s.push({key:"atr"+l,title:"ATR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},eo={name:"Bias",shortName:"BIAS",shouldOhlc:!0,paramMap:{period1:{defaultValue:[6],type:"numberArray",min:1,max:999},period2:{defaultValue:[12],type:"numberArray",min:1,max:999},period3:{defaultValue:[24],type:"numberArray",min:1,max:999}},calc(e,t){const i=In(t,"period1",[6]),s=In(t,"period2",[12]),n=In(t,"period3",[24]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t0)),c=a.map(((e,i)=>({key:`bias${i+1}`+(o>1?`_${t+1}`:""),title:`BIAS${e}`+(o>1?` #${t+1}`:""),type:"line",data:[],pane:1})));e.forEach(((t,i)=>{const s=t.close;a.forEach(((n,o)=>{if(l[o]+=s,i>=n-1){const r=l[o]/n,a=(s-r)/r*100;c[o].data.push({time:t.time,value:a}),l[o]-=e[i-(n-1)].close}else c[o].data.push({time:t.time,value:NaN})}))})),r.push(...c)}return r}},to={name:"Buy-Ratio Analysis",shortName:"BRAR",shouldOhlc:!0,paramMap:{length:{defaultValue:[26],type:"numberArray",min:1}},calc(e,t){const i=In(t,"length",[26]),s=[];return i.forEach(((t,n)=>{let o=0,r=0,a=0,l=0;const c=[],h=[];e.forEach(((i,s)=>{const n=s-1>=0?e[s-1]:i;if(a+=i.high-i.open,l+=i.open-i.low,o+=i.high-n.close,r+=n.close-i.low,s>=t-1){const n=0!==r?o/r*100:0,p=0!==l?a/l*100:0;c.push({time:i.time,value:n}),h.push({time:i.time,value:p});const d=e[s-(t-1)],u=s-t>=0?e[s-t]:d;o-=d.high-u.close,r-=u.close-d.low,a-=d.high-d.open,l-=d.open-d.low}else c.push({time:i.time,value:NaN}),h.push({time:i.time,value:NaN})}));const p=i.length>1?`_${n+1}`:"";s.push({key:"br"+p,title:"BR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:c,pane:1}),s.push({key:"ar"+p,title:"AR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:h,pane:1})})),s}},io={name:"Bull and Bear Index",shortName:"BBI",shouldOhlc:!0,paramMap:{p1:{defaultValue:[3],type:"numberArray",min:1},p2:{defaultValue:[6],type:"numberArray",min:1},p3:{defaultValue:[12],type:"numberArray",min:1},p4:{defaultValue:[24],type:"numberArray",min:1}},calc(e,t){const i=In(t,"p1",[3]),s=In(t,"p2",[6]),n=In(t,"p3",[12]),o=In(t,"p4",[24]),r=Math.max(i.length,s.length,n.length,o.length),a=[];for(let t=0;t{const s=t.close;if(d.forEach(((t,n)=>{u[n]+=s,i>=t-1&&(m[n]=u[n]/t,u[n]-=e[i-(t-1)].close)})),i>=Math.max(...d)-1){const e=(m[0]+m[1]+m[2]+m[3])/4;g.push({time:t.time,value:e})}else g.push({time:t.time,value:NaN})}));const f=r>1?`_${t+1}`:"";a.push({key:"bbi"+f,title:"BBI"+[l,c,h,p].join(",")+(r>1?` #${t+1}`:""),type:"line",data:g,pane:1})}return a}},so={name:"Commodity Channel Index",shortName:"CCI",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray",min:1}},calc(e,t){const i=In(t,"length",[20]),s=[];return i.forEach(((t,n)=>{let o=0;const r=[],a=[];e.forEach(((i,s)=>{const n=(i.high+i.low+i.close)/3;if(o+=n,r.push(n),s>=t-1){const l=o/t;let c=0;for(let e=s-(t-1);e<=s;e++)c+=Math.abs(r[e]-l);const h=c/t,p=0!==h?(n-l)/(.015*h):0;a.push({time:i.time,value:p});const d=(e[s-(t-1)].high+e[s-(t-1)].low+e[s-(t-1)].close)/3;o-=d}else a.push({time:i.time,value:NaN})}));const l=i.length>1?`_${n+1}`:"";s.push({key:"cci"+l,title:"CCI"+t+(i.length>1?` #${n+1}`:""),type:"line",data:a,pane:1})})),s}},no={name:"Current Ratio",shortName:"CR",shouldOhlc:!0,paramMap:{length:{defaultValue:[26],type:"numberArray",min:1}},calc(e,t){const i=In(t,"length",[26]),s=[];return i.forEach(((t,n)=>{let o=0,r=0;const a=[],l=[],c=[];e.forEach(((i,s)=>{const n=s-1>=0?e[s-1]:i,h=(n.high+n.low)/2,p=Math.max(0,i.high-h),d=Math.max(0,h-i.low);o+=p,r+=d,a.push(p),l.push(d);let u=NaN;s>=t-1&&(u=0!==r?o/r*100:0,o-=a[s-(t-1)],r-=l[s-(t-1)]),c.push({time:i.time,value:u})}));const h=i.length>1?`_${n+1}`:"";s.push({key:"cr"+h,title:"CR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:c,pane:1})})),s}},oo={name:"Difference of Moving Average",shortName:"DMA",shouldOhlc:!0,paramMap:{n1:{defaultValue:[10],type:"numberArray",min:1},n2:{defaultValue:[50],type:"numberArray",min:1},m:{defaultValue:[10],type:"numberArray",min:1}},calc(e,t){const i=In(t,"n1",[10]),s=In(t,"n2",[50]),n=In(t,"m",[10]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t{p+=t.close,d+=t.close;let s=NaN,n=NaN;if(i>=a-1&&(s=p/a,p-=e[i-(a-1)].close),i>=l-1&&(n=d/l,d-=e[i-(l-1)].close),i>=h-1){const e=s-n;if(f.push(e),m.push({time:t.time,value:e}),u+=e,f.length>c){u-=f[f.length-1-c];const e=u/c;g.push({time:t.time,value:e})}else g.push({time:t.time,value:NaN})}else m.push({time:t.time,value:NaN}),g.push({time:t.time,value:NaN})}));const y=o>1?`_${t+1}`:"";r.push({key:"dma"+y,title:"DMA"+a+"-"+l+(o>1?` #${t+1}`:""),type:"line",data:m,pane:1}),r.push({key:"ama"+y,title:"AMA"+a+"-"+l+(o>1?` #${t+1}`:""),type:"line",data:g,pane:1})}return r}},ro={name:"Directional Movement Index",shortName:"DMI",shouldOhlc:!0,paramMap:{n:{defaultValue:[14],type:"numberArray",min:1},mm:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=In(t,"n",[14]),s=In(t,"mm",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{const s=i-1>=0?e[i-1]:t,n=t.high-s.high,o=s.low-t.low,y=Math.max(t.high-t.low,Math.abs(t.high-s.close),Math.abs(s.close-t.low));let b=0,v=0;n>0&&n>o&&(b=n),o>0&&o>n&&(v=o),0===i?(l=y,c=b,h=v):(l=(l*(r-1)+y)/r,c=(c*(r-1)+b)/r,h=(h*(r-1)+v)/r);let x=NaN,_=NaN;0!==l&&(x=c/l*100,_=h/l*100),u.push({time:t.time,value:x}),m.push({time:t.time,value:_});let w=NaN;if(isNaN(x)||isNaN(_)||x+_===0||(w=Math.abs(_-x)/(_+x)*100),i1?`_${t+1}`:"";o.push({key:"pdi"+y,title:"PDI"+r+(n>1?` #${t+1}`:""),type:"line",data:u,pane:1}),o.push({key:"mdi"+y,title:"MDI"+r+(n>1?` #${t+1}`:""),type:"line",data:m,pane:1}),o.push({key:"adx"+y,title:"ADX"+r+(n>1?` #${t+1}`:""),type:"line",data:g,pane:1}),o.push({key:"adxr"+y,title:"ADXR"+r+(n>1?` #${t+1}`:""),type:"line",data:f,pane:1})}return o}},ao={name:"Momentum",shortName:"MTM",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray",min:1},m:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=In(t,"n",[12]),s=In(t,"m",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(i>=r){const s=e[i-r],n=t.close-s.close;l.push({time:t.time,value:n}),p.push(n),h+=n,p.length>a&&(h-=p[p.length-1-a]);const o=p.length>=a?h/a:NaN;c.push({time:t.time,value:o})}else l.push({time:t.time,value:NaN}),c.push({time:t.time,value:NaN})}));const d=n>1?`_${t+1}`:"";o.push({key:"mtm"+d,title:"MTM"+r+(n>1?` #${t+1}`:""),type:"line",data:l,pane:1}),o.push({key:"maMtm"+d,title:"MAMTM"+r+(n>1?` #${t+1}`:""),type:"line",data:c,pane:1})}return o}},lo={name:"Psychological Line",shortName:"PSY",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray",min:1},m:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=In(t,"n",[12]),s=In(t,"m",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{const s=i-1>=0?e[i-1]:t,n=t.close>s.close?1:0;if(c.push(n),l+=n,i>=r-1){const e=l/r*100;p.push({time:t.time,value:e}),u.push(e),h+=e,u.length>a&&(h-=u[u.length-1-a]);const s=u.length>=a?h/a:NaN;d.push({time:t.time,value:s}),l-=c[i-(r-1)]}else p.push({time:t.time,value:NaN}),d.push({time:t.time,value:NaN})}));const m=n>1?`_${t+1}`:"";o.push({key:"psy"+m,title:"PSY"+r+(n>1?` #${t+1}`:""),type:"line",data:p,pane:1}),o.push({key:"maPsy"+m,title:"MAPSY"+r+(n>1?` #${t+1}`:""),type:"line",data:d,pane:1})}return o}},co={name:"Rate of Change",shortName:"ROC",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray",min:1},m:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=In(t,"n",[12]),s=In(t,"m",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(i>=r){const s=e[i-r].close;let n=0;0!==s&&(n=(t.close-s)/s*100),l.push({time:t.time,value:n}),p.push(n),h+=n,p.length>a&&(h-=p[p.length-1-a]);const o=p.length>=a?h/a:NaN;c.push({time:t.time,value:o})}else l.push({time:t.time,value:NaN}),c.push({time:t.time,value:NaN})}));const d=n>1?`_${t+1}`:"";o.push({key:"roc"+d,title:"ROC"+r+(n>1?` #${t+1}`:""),type:"line",data:l,pane:1}),o.push({key:"maRoc"+d,title:"MAROC"+r+(n>1?` #${t+1}`:""),type:"line",data:c,pane:1})}return o}},ho={name:"RSI + SMA",shortName:"RSI_SMA",shouldOhlc:!0,paramMap:{p1:{defaultValue:[14],type:"numberArray",min:1},p2:{defaultValue:[21],type:"numberArray",min:1}},calc(e,t){const i=In(t,"p1",[14]),s=In(t,"p2",[10]),n=Math.max(i.length,s.length),o=e.map((e=>e.close)),r=[];for(let t=0;t{const i=Pn(o.slice(0,t+1),a);c.push(i);const s=En(c,l);h.push({time:e.time,value:i}),p.push({time:e.time,value:s})}));const d=n>1?`_${t+1}`:"",u={key:`rsi${d}`,title:`RSI(${a})${d}`,type:"line",data:h,pane:1},m={key:`smaOfRsi${d}`,title:`SMA(${l}) of RSI(${a})${d}`,type:"line",data:p,pane:1};r.push(u,m)}return r}},po={name:"Stochastic",shortName:"KDJ",shouldOhlc:!0,paramMap:{n:{defaultValue:[9],type:"numberArray",min:1},kPeriod:{defaultValue:[3],type:"numberArray",min:1},dPeriod:{defaultValue:[3],type:"numberArray",min:1}},calc(e,t){const i=In(t,"n",[9]),s=In(t,"kPeriod",[3]),n=In(t,"dPeriod",[3]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t{if(ie.high))),o=Math.min(...s.map((e=>e.low))),r=n===o?100:(t.close-o)/(n-o)*100,g=((l-1)*h+r)/l,f=((c-1)*p+g)/c,y=3*g-2*f;d.push({time:t.time,value:g}),u.push({time:t.time,value:f}),m.push({time:t.time,value:y}),h=g,p=f}));const g=o>1?`_${t+1}`:"";r.push({key:"k"+g,title:"K"+a+(o>1?` #${t+1}`:""),type:"line",data:d,pane:1}),r.push({key:"d"+g,title:"D"+a+(o>1?` #${t+1}`:""),type:"line",data:u,pane:1}),r.push({key:"j"+g,title:"J"+a+(o>1?` #${t+1}`:""),type:"line",data:m,pane:1})}return r}},uo={name:"Variance",shortName:"Variance",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=In(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.close)),r=n.reduce(((e,t)=>e+t),0)/n.length,a=n.reduce(((e,t)=>e+Math.pow(t-r,2)),0)/n.length;o.push({time:i.time,value:a})}));const r=i.length>1?`_${n+1}`:"";s.push({key:"variance"+r,title:"Variance"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},mo={name:"Williams %R",shortName:"WR",shouldOhlc:!0,paramMap:{p1:{defaultValue:[6],type:"numberArray",min:1},p2:{defaultValue:[10],type:"numberArray",min:1},p3:{defaultValue:[14],type:"numberArray",min:1}},calc(e,t){const i=In(t,"p1",[6]),s=In(t,"p2",[10]),n=In(t,"p3",[14]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t({key:`wr${i+1}`+(o>1?`_${t+1}`:""),title:`WR${e}`+(o>1?` #${t+1}`:""),type:"line",data:[],pane:1})));e.forEach(((t,i)=>{a.forEach(((s,n)=>{if(i>=s-1){let o=-1/0,r=1/0;for(let t=i-(s-1);t<=i;t++)o=Math.max(o,e[t].high),r=Math.min(r,e[t].low);const a=o!==r?(t.close-o)/(o-r)*100:0;l[n].data.push({time:t.time,value:a})}else l[n].data.push({time:t.time,value:NaN})}))})),r.push(...l)}return r}},go={name:"Change",shortName:"Change",shouldOhlc:!0,paramMap:{length:{defaultValue:[1],type:"numberArray",min:1,max:100}},calc(e,t){const i=In(t,"length",[1]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:"";s.push({key:"change"+r,title:"Change"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},fo={name:"Range",shortName:"Range",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=In(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.high))),a=Math.min(...n.map((e=>e.low)));o.push({time:i.time,value:r-a})}));const r=i.length>1?`_${n+1}`:"";s.push({key:"range"+r,title:"Range"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},yo={name:"Standard Deviation",shortName:"StdDev",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=In(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.close)),r=n.reduce(((e,t)=>e+t),0)/n.length,a=n.reduce(((e,t)=>e+Math.pow(t-r,2)),0)/n.length,l=Math.sqrt(a);o.push({time:i.time,value:l})}));const r=i.length>1?`_${n+1}`:"";s.push({key:"stdDev"+r,title:"StdDev"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},bo={name:"Moving Average Convergence Divergence",shortName:"MACD",shouldOhlc:!0,paramMap:{shortPeriod:{defaultValue:12,type:"number",min:1},longPeriod:{defaultValue:26,type:"number",min:1},signalPeriod:{defaultValue:9,type:"number",min:1}},calc(e,t){const i=function(e,t){const i={};for(const[s,n]of Object.entries(e.paramMap)){const e=t?.[s]??n.defaultValue;i[s]=e}return i}(this,t),s=i.shortPeriod,n=i.longPeriod,o=i.signalPeriod;let r=0,a=0,l=0,c=0,h=0;const p=[],d=[],u=[];let m=0;e.forEach(((e,t)=>{m+=e.close,t===s-1?r=m/s:t>s-1&&(r=(2*e.close+(s-1)*r)/(s+1)),t===n-1?a=m/n:t>n-1&&(a=(2*e.close+(n-1)*a)/(n+1)),t>=Math.max(s,n)-1?(l=r-a,p.push({time:e.time,value:l}),h+=l,p.length===o?c=h/o:p.length>o&&(c=(2*l+(o-1)*c)/(o+1)),p.length>=o?(d.push({time:e.time,value:c}),u.push({time:e.time,value:2*(l-c)})):(d.push({time:e.time,value:NaN}),u.push({time:e.time,value:NaN}))):(p.push({time:e.time,value:NaN}),d.push({time:e.time,value:NaN}),u.push({time:e.time,value:NaN}))}));return Tn(u,t?.upColor??"green",t?.downColor??"red"),[{key:"dif",title:"DIF",type:"line",data:p,pane:1},{key:"dea",title:"DEA",type:"line",data:d,pane:1},{key:"macd",title:"MACD",type:"histogram",data:u,pane:1}]}},vo=[...Kn,...[Qn,Zn,eo,to,io,so,no,oo,ro,ao,bo,lo,co,ho,po,uo,mo,go,fo,yo]];class xo{contextMenu;handler;container;currentTab="options";constructor(e){this.contextMenu=e.contextMenu,this.handler=e.handler,this.container=this.contextMenu.div}openMenu(e,t,i){const s={type:i||e._type||e.constructor.name,object:e.toJSON(),title:e.title},n=JSON.stringify(s,null,2);let o={};e instanceof Lo?o=e.chart.options():void 0!==e.options?o="function"==typeof e.options?e.options():e.options:void 0!==e._options&&(o=e._options);const r={...o},a=JSON.stringify(r,null,2),l=document.createElement("div");l.style.position="fixed",l.style.top="0",l.style.left="0",l.style.width="100%",l.style.height="100%",l.style.backgroundColor="rgba(0, 0, 0, 0.5)",l.style.display="flex",l.style.justifyContent="center",l.style.alignItems="center",l.style.zIndex="1000";const c=e=>{"Escape"===e.key&&this.close(l,c)};document.addEventListener("keydown",c);const h=document.createElement("div");h.style.backgroundColor="#333",h.style.color="#fff",h.style.padding="20px",h.style.borderRadius="8px",h.style.width="80%",h.style.maxWidth="800px",h.style.maxHeight="90%",h.style.overflowY="auto",h.style.boxShadow="0 2px 10px rgba(0,0,0,0.5)",h.setAttribute("tabindex","-1"),h.focus();const p=document.createElement("div");p.style.display="flex",p.style.borderBottom="1px solid #555",p.style.marginBottom="10px";const d=document.createElement("button");d.textContent="Options",d.style.flex="1",d.style.padding="10px",d.style.cursor="pointer",d.style.border="none",d.style.backgroundColor="options"===this.currentTab?"#555":"#333",d.onclick=()=>{this.currentTab="options",d.style.backgroundColor="#555",u.style.backgroundColor="#333",g.value=a,v.style.display="flex",f.style.display="none"};const u=document.createElement("button");u.textContent="Full",u.style.flex="1",u.style.padding="10px",u.style.cursor="pointer",u.style.border="none",u.style.backgroundColor="full"===this.currentTab?"#555":"#333",u.onclick=()=>{this.currentTab="full",u.style.backgroundColor="#555",d.style.backgroundColor="#333",g.value=n,f.style.display="flex",v.style.display="none"},p.appendChild(d),p.appendChild(u),h.appendChild(p);const m=document.createElement("h2");m.textContent=`Export/Import ${e.title} Data`,h.appendChild(m);const g=document.createElement("textarea");g.value="full"===this.currentTab?n:a,g.style.width="100%",g.style.height="400px",g.style.marginTop="10px",g.style.marginBottom="10px",g.style.resize="vertical",g.style.backgroundColor="#444",g.style.color="#fff",g.setAttribute("aria-label","JSON Data Editor"),h.appendChild(g);const f=document.createElement("div");f.style.display="full"===this.currentTab?"flex":"none",f.style.flexWrap="wrap",f.style.justifyContent="flex-end",f.style.gap="10px";const y=document.createElement("button");y.textContent="Export",y.style.padding="8px 12px",y.style.cursor="pointer",y.style.backgroundColor="#f44336",y.style.color="#fff",y.style.border="none",y.style.borderRadius="4px",y.onclick=()=>{this.downloadJson(n,`${e.title}_full.json`)},f.appendChild(y);const b=document.createElement("button");b.textContent="Import",b.style.padding="8px 12px",b.style.cursor="pointer",b.style.backgroundColor="#4CAF50",b.style.color="#fff",b.style.border="none",b.style.borderRadius="4px",b.onclick=()=>{try{const t=JSON.parse(g.value);if("object"!=typeof t||!t.object)throw new Error("Invalid structure: missing 'object'.");e.fromJSON(t.object),"function"==typeof e.updateView&&e.updateView(),this.showNotification("Whole data imported successfully.","success")}catch(e){this.showNotification("Failed to import whole data: "+e.message,"error")}},f.appendChild(b);const v=document.createElement("div");v.style.display="options"===this.currentTab?"flex":"none",v.style.flexWrap="wrap",v.style.justifyContent="flex-end",v.style.gap="10px";const x=document.createElement("button");x.textContent="Export Options",x.style.padding="8px 12px",x.style.cursor="pointer",x.style.backgroundColor="#f44336",x.style.color="#fff",x.style.border="none",x.style.borderRadius="4px",x.onclick=()=>{this.downloadJson(a,`${e.title}_options.json`)},v.appendChild(x);const _=document.createElement("button");_.textContent="Import Options",_.style.padding="8px 12px",_.style.cursor="pointer",_.style.backgroundColor="#4CAF50",_.style.color="#fff",_.style.border="none",_.style.borderRadius="4px",_.onclick=()=>{const t=document.createElement("input");t.type="file",t.accept="application/json",t.style.display="none",t.addEventListener("change",(()=>{if(t.files&&t.files.length>0){const i=t.files[0],s=new FileReader;s.onload=()=>{try{const t=s.result;if("string"!=typeof t)throw new Error("File content is not a string.");g.value=t;const i=JSON.parse(t);if("object"!=typeof i||!i.options)throw new Error("Invalid structure: missing 'options'.");e.fromJSON(i.options),"function"==typeof e.updateView&&e.updateView(),this.showNotification("Options imported successfully.","success")}catch(e){this.showNotification("Failed to import options: "+e.message,"error")}},s.readAsText(i)}})),t.click()},v.appendChild(_);const w=document.createElement("button");w.textContent="Save",w.style.padding="8px 12px",w.style.cursor="pointer",w.style.backgroundColor="#008CBA",w.style.color="#fff",w.style.border="none",w.style.borderRadius="4px",w.onclick=()=>{try{const t=JSON.parse(g.value);if("object"!=typeof t||!t.options)throw new Error("Invalid structure: missing 'options'.");e.fromJSON(t),"function"==typeof e.updateView&&e.updateView();JSON.stringify(t,null,2);this.showNotification("Options applied and exported successfully.","success")}catch(e){this.showNotification("Failed to save options: "+e.message,"error")}};const C=document.createElement("button");C.textContent="Save as Default",C.style.padding="8px 12px",C.style.cursor="pointer",C.style.backgroundColor="#008CBA",C.style.color="#fff",C.style.border="none",C.style.borderRadius="4px",C.onclick=()=>{let t={};e instanceof Lo?t=e.chart.options():"function"==typeof e.options?t=e.options():void 0!==e.options?t=e.options:void 0!==e._options&&(t=e._options);const i=JSON.stringify(t,null,2);let s;if(e._type&&"custom/custom"===e._type.toLowerCase()){if(s=prompt("Enter save key (e.g., area, line, candlestick):",e.title.toLowerCase())||"",!s)return}else s=e._type?e._type.toLowerCase():e.title.toLowerCase();const n=`save_defaults_~_${s};;;${i}`;window.callbackFunction(n)},this.container.appendChild(C);const S=document.createElement("div");S.style.display="flex",S.style.flexDirection="column",S.style.gap="10px",S.appendChild(f),S.appendChild(v),S.appendChild(w),S.appendChild(C),h.appendChild(S),l.appendChild(h),this.container.appendChild(l)}downloadJson(e,t){try{const i=new Blob([e],{type:"application/json"}),s=URL.createObjectURL(i),n=document.createElement("a");n.href=s,n.download=t,n.click(),URL.revokeObjectURL(s)}catch(e){this.showNotification("Failed to download data: "+e,"error")}}addSaveDefaultButton(e){const t=document.createElement("button");t.textContent="Save as Default",t.style.padding="8px 12px",t.style.cursor="pointer",t.style.backgroundColor="#008CBA",t.style.color="#fff",t.style.border="none",t.style.borderRadius="4px",t.onclick=()=>{let t={};e instanceof Lo?t=e.chart.options():"function"==typeof e.options?t=e.options():void 0!==e.options?t=e.options:void 0!==e._options&&(t=e._options);const i=JSON.stringify(t,null,2),s=prompt("Enter save key (area, line, trend-trace, candlestick etc):",e.title.toLowerCase());if(!s)return;const n=`save_defaults_${s}_~_${i}`;window.callbackFunction(n)},this.container.appendChild(t)}close(e,t){e.parentElement&&e.parentElement.removeChild(e),document.removeEventListener("keydown",t)}showNotification(e,t){const i=document.createElement("div");i.textContent=e,i.style.position="fixed",i.style.bottom="20px",i.style.right="20px",i.style.padding="10px 20px",i.style.borderRadius="4px",i.style.color="#fff",i.style.backgroundColor="success"===t?"#4CAF50":"#f44336",i.style.boxShadow="0 2px 6px rgba(0,0,0,0.2)",i.style.zIndex="1001",i.style.opacity="0",i.style.transition="opacity 0.5s ease-in-out",this.container.appendChild(i),setTimeout((()=>{i.style.opacity="1"}),100),setTimeout((()=>{i.style.opacity="0",setTimeout((()=>{i.parentElement&&i.parentElement.removeChild(i)}),500)}),3e3)}openDefaultOptions(e){const t=this.handler.defaultsManager;if(!t)return void this.showNotification("No defaults manager found.","error");const i=t.get(e);if(!i)return void this.showNotification(`No default config found for key: "${e}"`,"error");JSON.stringify(i,null,2);const s=document.createElement("div");Object.assign(s.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:"1000"});const n=e=>{"Escape"===e.key&&this.close(s,n)};document.addEventListener("keydown",n);const o=document.createElement("div");Object.assign(o.style,{backgroundColor:"#333",color:"#fff",padding:"20px",borderRadius:"8px",width:"80%",maxWidth:"800px",maxHeight:"90%",overflowY:"auto",boxShadow:"0 2px 10px rgba(0,0,0,0.5)"}),o.setAttribute("tabindex","-1"),o.focus();const r=document.createElement("h2");r.textContent=`Edit Default Options - "${e}"`,o.appendChild(r);const a=document.createElement("textarea");a.value=JSON.stringify(i,null,2),Object.assign(a.style,{width:"100%",height:"400px",resize:"vertical",backgroundColor:"#444",color:"#fff",border:"none",margin:"10px 0",padding:"10px"}),o.appendChild(a);const l=document.createElement("div");Object.assign(l.style,{display:"flex",flexWrap:"wrap",gap:"10px",justifyContent:"flex-end"});const c=document.createElement("button");c.textContent="Export",Object.assign(c.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#f44336",color:"#fff",border:"none",borderRadius:"4px"}),c.onclick=()=>{this.downloadJson(a.value,`${e}_defaults.json`)},l.appendChild(c);const h=document.createElement("button");h.textContent="Import",Object.assign(h.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#4CAF50",color:"#fff",border:"none",borderRadius:"4px"}),h.onclick=()=>{const e=document.createElement("input");e.type="file",e.accept="application/json",e.style.display="none",e.addEventListener("change",(()=>{if(e.files&&e.files.length>0){const t=e.files[0],i=new FileReader;i.onload=()=>{try{if("string"!=typeof i.result)throw new Error("File content is not a string.");a.value=i.result}catch(e){this.showNotification("Failed to read defaults file: "+e.message,"error")}},i.readAsText(t)}})),e.click()},l.appendChild(h);const p=document.createElement("button");p.textContent="Save",Object.assign(p.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#008CBA",color:"#fff",border:"none",borderRadius:"4px"}),p.onclick=()=>{try{const t=JSON.parse(a.value),i=JSON.stringify(t,null,2);let s=e;const n=`save_defaults_${s}_~_${i}`;window.callbackFunction(n),this.showNotification(`Defaults for "${s}" saved successfully.`,"success")}catch(e){this.showNotification("Failed to save defaults: "+e.message,"error")}},l.appendChild(p);const d=document.createElement("button");d.textContent="Cancel",Object.assign(d.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#444",color:"#fff",border:"none",borderRadius:"4px"}),d.onclick=()=>{this.close(s,n)},l.appendChild(d),o.appendChild(l),s.appendChild(o),this.container.appendChild(s)}}class _o{container;backdrop;isOpen=!1;categories=[];contentArea;activeCategoryId="";handler;colorPicker=null;_originalOpacities={};constructor(e){this.handler=e;const t=Array.isArray(this.handler.defaultsManager.get("colors"))?[...this.handler.defaultsManager.get("colors")]:[];this.colorPicker=new xn("#ff0000",(()=>null),t&&0!==t.length?t:void 0),this.backdrop=document.createElement("div"),Object.assign(this.backdrop.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.5)",opacity:"0",transition:"opacity 0.3s ease",zIndex:"9998",display:"none"}),this.backdrop.addEventListener("click",(e=>{e.target===this.backdrop&&this.close(!1)})),document.body.appendChild(this.backdrop),this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"700px",maxWidth:"90%",height:"500px",maxHeight:"90%",backgroundColor:"#1E1E1E",color:"#FFF",borderRadius:"6px",boxShadow:"0 2px 10px rgba(0,0,0,0.8)",zIndex:"9999",opacity:"0",display:"none",transition:"opacity 0.3s ease, transform 0.3s ease"}),document.body.appendChild(this.container);const i=document.createElement("div");Object.assign(i.style,{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #3C3C3C",backgroundColor:"#2B2B2B"});const s=document.createElement("div");Object.assign(s.style,{fontSize:"16px",fontWeight:"bold"}),s.innerText="Settings",i.appendChild(s);const n=document.createElement("div");Object.assign(n.style,{fontSize:"20px",cursor:"pointer",userSelect:"none"}),n.innerText="×",n.onclick=()=>this.close(!1),i.appendChild(n),this.container.appendChild(i);const o=document.createElement("div");Object.assign(o.style,{display:"flex",flex:"1 1 auto",height:"calc(100% - 50px)",backgroundColor:"#1E1E1E"}),this.container.appendChild(o);const r=document.createElement("div");Object.assign(r.style,{width:"180px",borderRight:"1px solid #3C3C3C",display:"flex",flexDirection:"column",backgroundColor:"#2B2B2B"}),o.appendChild(r),this.contentArea=document.createElement("div"),Object.assign(this.contentArea.style,{flex:"1",padding:"16px",overflowY:"auto"}),o.appendChild(this.contentArea);const a=document.createElement("div");Object.assign(a.style,{borderTop:"1px solid #3C3C3C",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",backgroundColor:"#2B2B2B"});const l=document.createElement("button");Object.assign(l.style,{backgroundColor:"#444",color:"#FFF",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:"pointer",fontSize:"14px"}),l.innerText="Template ▾",a.appendChild(l);const c=document.createElement("div");Object.assign(c.style,{display:"flex",gap:"8px"});const h=document.createElement("button");Object.assign(h.style,{backgroundColor:"#444",color:"#FFF",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:"pointer",fontSize:"14px"}),h.innerText="Cancel",h.onclick=()=>this.close(!1),c.appendChild(h);const p=document.createElement("button");Object.assign(p.style,{backgroundColor:"#008CBA",color:"#FFF",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:"pointer",fontSize:"14px"}),p.innerText="Ok",p.onclick=()=>this.close(!0),c.appendChild(p),a.appendChild(c),this.container.appendChild(a),this.categories=[{id:"series-colors",label:"Series Colors",buildContent:()=>this.buildSeriesColorsTab()},{id:"primitive-colors",label:"Primitives Colors",buildContent:()=>this.buildPrimitivesTab()},{id:"layout-options",label:"Layout Options",buildContent:()=>this.buildLayoutOptionsTab()},{id:"grid-options",label:"Grid Options",buildContent:()=>this.buildGridOptionsTab()},{id:"crosshair-options",label:"Crosshair Options",buildContent:()=>this.buildCrosshairOptionsTab()},{id:"time-scale-options",label:"Time Scale",buildContent:()=>this.buildTimeScaleOptionsTab()},{id:"price-scale-options",label:"Price Scale",buildContent:()=>this.buildPriceScaleOptionsTab()},{id:"defaults-list",label:"Defaults",buildContent:()=>this.buildDefaultsListTab()},{id:"source-code",label:"source-code",buildContent:()=>this.buildSourceCodeTab()}],this.categories.forEach((e=>{const t=document.createElement("div");t.innerText=e.label,Object.assign(t.style,{padding:"12px 16px",cursor:"pointer",borderBottom:"1px solid #3C3C3C",userSelect:"none",transition:"background-color 0.2s"}),t.addEventListener("mouseenter",(()=>{t.style.backgroundColor="#3A3A3A"})),t.addEventListener("mouseleave",(()=>{t.style.backgroundColor=""})),t.addEventListener("click",(()=>this.switchCategory(e.id))),r.appendChild(t)})),this.categories.length>0&&(this.buildSeriesColorsTab(),this.switchCategory(this.categories[0].id))}open(){this.isOpen||(this.isOpen=!0,this.backdrop.style.display="block",setTimeout((()=>{this.backdrop.style.opacity="1"}),10),this.container.style.display="block",setTimeout((()=>{this.container.style.opacity="1",this.container.style.transform="translate(-50%, -50%) scale(1)"}),10),this.buildSeriesColorsTab())}close(e){e?console.log("Settings Modal: OK clicked. Save changes here."):console.log("Settings Modal: Cancel clicked."),this.isOpen=!1,this.backdrop.style.opacity="0",this.container.style.opacity="0",this.container.style.transform="translate(-50%, -50%) scale(0.95)",setTimeout((()=>{this.isOpen||(this.backdrop.style.display="none",this.container.style.display="none")}),300)}switchCategory(e){this.activeCategoryId=e,this.contentArea.innerHTML="";const t=this.categories.find((t=>t.id===e));t&&t.buildContent()}buildLayoutOptionsTab(){const e=document.createElement("div");e.innerText="Layout Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i=this.getCurrentOptionValue("layout.textColor")||"#000000";this.addColorPicker("Text Color",i,(e=>{this.handler.chart.applyOptions({layout:{textColor:e}})}));const s=this.handler.chart.options().layout?.background;if(s&&"solid"===s.type){const e=s.color||"#FFFFFF";this.addColorPicker("Background Color",e,(e=>{this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.Solid,color:e}}})}))}else if(s&&s.type===t.ColorType.VerticalGradient){let e=s.topColor||"rgba(255,0,0,0.33)",i=s.bottomColor||"rgba(0,255,0,0.33)";this.addColorPicker("Top Color",e,(e=>{i=s.bottomColor||"rgba(0,255,0,0.33)",this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.VerticalGradient,topColor:e,bottomColor:i}}})})),this.addColorPicker("Bottom Color",i,(i=>{e=s.topColor||"rgba(255,0,0,0.33)",this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.VerticalGradient,topColor:e,bottomColor:i}}})}))}else console.warn("Unknown background type.");const n=document.createElement("button");n.innerText="Switch Background Type",n.style.marginTop="12px",n.onclick=()=>this.toggleBackgroundType(),this.contentArea.appendChild(n)}buildGridOptionsTab(){const e=document.createElement("div");e.innerText="Grid Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i=this.getCurrentOptionValue("grid.vertLines.color")||"#D6DCDE";this.addColorPicker("Vertical Line Color",i,(e=>{this.handler.chart.applyOptions({grid:{vertLines:{color:e}}})}));const s=this.getCurrentOptionValue("grid.horzLines.color")||"#D6DCDE";this.addColorPicker("Horizontal Line Color",s,(e=>{this.handler.chart.applyOptions({grid:{horzLines:{color:e}}})}));const n={Solid:t.LineStyle.Solid,Dotted:t.LineStyle.Dotted,Dashed:t.LineStyle.Dashed,LargeDashed:t.LineStyle.LargeDashed,SparseDotted:t.LineStyle.SparseDotted};this.addDropdown("Vertical Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=n[e];this.handler.chart.applyOptions({grid:{vertLines:{style:t}}})})),this.addDropdown("Horizontal Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=n[e];this.handler.chart.applyOptions({grid:{horzLines:{style:t}}})}));const o=!1!==this.getCurrentOptionValue("grid.vertLines.visible");this.addCheckbox("Show Vertical Lines",o,(e=>{this.handler.chart.applyOptions({grid:{vertLines:{visible:e}}})}));const r=!1!==this.getCurrentOptionValue("grid.horzLines.visible");this.addCheckbox("Show Horizontal Lines",r,(e=>{this.handler.chart.applyOptions({grid:{horzLines:{visible:e}}})}))}buildCrosshairOptionsTab(){const e=document.createElement("div");e.innerText="Crosshair Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i={Solid:t.LineStyle.Solid,Dotted:t.LineStyle.Dotted,Dashed:t.LineStyle.Dashed,LargeDashed:t.LineStyle.LargeDashed,SparseDotted:t.LineStyle.SparseDotted},s=this.getCurrentOptionValue("crosshair.vertLine.style")||"Solid",n=this.getCurrentOptionValue("crosshair.horzLine.style")||"Solid",o=this.getCurrentOptionValue("crosshair.mode")||"Normal";this.addDropdown("Crosshair Mode",["Normal","Magnet","Hidden"],(e=>{this.handler.chart.applyOptions({crosshair:{mode:e}})}),o);const r=Array.from({length:10},((e,t)=>(t+1).toString())),a=(this.getCurrentOptionValue("crosshair.vertLine.width")||"1").toString();this.addDropdown("Vertical Line Width",r,(e=>{const t=parseInt(e,10);this.handler.chart.applyOptions({crosshair:{vertLine:{width:t}}})}),a),this.addDropdown("Vertical Crosshair Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=i[e];this.handler.chart.applyOptions({crosshair:{vertLine:{style:t}}})}),s);const l=this.getCurrentOptionValue("crosshair.vertLine.color")||"#C3BCDB44";this.addColorPicker("Vertical Line Color",l,(e=>{this.handler.chart.applyOptions({crosshair:{vertLine:{color:e}}})}));const c=this.getCurrentOptionValue("crosshair.vertLine.labelBackgroundColor")||"#9B7DFF";this.addColorPicker("Vertical Label Background",c,(e=>{this.handler.chart.applyOptions({crosshair:{vertLine:{labelBackgroundColor:e}}})})),(this.getCurrentOptionValue("crosshair.horzLine.width")||"1").toString(),this.addDropdown("Horizontal Line Width",r,(e=>{const t=parseInt(e,10);this.handler.chart.applyOptions({crosshair:{horzLine:{width:t}}})})),this.addDropdown("Horizontal Crosshair Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=i[e];this.handler.chart.applyOptions({crosshair:{horzLine:{style:t}}})}),n);const h=this.getCurrentOptionValue("crosshair.horzLine.color")||"#9B7DFF";this.addColorPicker("Horizontal Line Color",h,(e=>{this.handler.chart.applyOptions({crosshair:{horzLine:{color:e}}})}));const p=this.getCurrentOptionValue("crosshair.horzLine.labelBackgroundColor")||"#9B7DFF";this.addColorPicker("Horizontal Label Background",p,(e=>{this.handler.chart.applyOptions({crosshair:{horzLine:{labelBackgroundColor:e}}})}))}buildTimeScaleOptionsTab(){const e=document.createElement("div");e.innerText="Time Scale Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const t=this.getCurrentOptionValue("timeScale.rightOffset")||0;this.addNumberField("Right Offset",t,(e=>{this.handler.chart.applyOptions({timeScale:{rightOffset:e}})}));const i=this.getCurrentOptionValue("timeScale.barSpacing")||10;this.addNumberField("Bar Spacing",i,(e=>{this.handler.chart.applyOptions({timeScale:{barSpacing:e}})}));const s=this.getCurrentOptionValue("timeScale.minBarSpacing")||.1;this.addNumberField("Min Bar Spacing",s,(e=>{this.handler.chart.applyOptions({timeScale:{minBarSpacing:e}})}));const n=this.getCurrentOptionValue("timeScale.fixLeftEdge")||!1;this.addCheckbox("Fix Left Edge",n,(e=>{this.handler.chart.applyOptions({timeScale:{fixLeftEdge:e}})}));const o=this.getCurrentOptionValue("timeScale.fixRightEdge")||!1;this.addCheckbox("Fix Right Edge",o,(e=>{this.handler.chart.applyOptions({timeScale:{fixRightEdge:e}})}));const r=this.getCurrentOptionValue("timeScale.lockVisibleTimeRangeOnResize")||!1;this.addCheckbox("Lock Visible Range on Resize",r,(e=>{this.handler.chart.applyOptions({timeScale:{lockVisibleTimeRangeOnResize:e}})}));const a=this.getCurrentOptionValue("timeScale.visible");this.addCheckbox("Time Scale Visible",!1!==a,(e=>{this.handler.chart.applyOptions({timeScale:{visible:e}})}));const l=this.getCurrentOptionValue("timeScale.borderVisible");this.addCheckbox("Border Visible",!1!==l,(e=>{this.handler.chart.applyOptions({timeScale:{borderVisible:e}})}));const c=this.getCurrentOptionValue("timeScale.borderColor")||"#000000";this.addColorPicker("Border Color",c,(e=>{this.handler.chart.applyOptions({timeScale:{borderColor:e}})}))}buildPriceScaleOptionsTab(){const e=document.createElement("div");e.innerText="Price Scale Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i=this.handler.chart.priceScale("right");i.options().mode||t.PriceScaleMode.Normal;const s=[{label:"Normal",value:t.PriceScaleMode.Normal},{label:"Logarithmic",value:t.PriceScaleMode.Logarithmic},{label:"Percentage",value:t.PriceScaleMode.Percentage},{label:"Indexed To 100",value:t.PriceScaleMode.IndexedTo100}],n=s.map((e=>e.label));this.addDropdown("Price Scale Mode",n,(e=>{const t=s.find((t=>t.label===e));t&&i.applyOptions({mode:t.value})}));const o=void 0===i.options().autoScale||i.options().autoScale;this.addCheckbox("Auto Scale",o,(e=>{i.applyOptions({autoScale:e})}));const r=i.options().invertScale||!1;this.addCheckbox("Invert Scale",r,(e=>{i.applyOptions({invertScale:e})}));const a=void 0===i.options().alignLabels||i.options().alignLabels;this.addCheckbox("Align Labels",a,(e=>{i.applyOptions({alignLabels:e})}));const l=void 0===i.options().borderVisible||i.options().borderVisible;this.addCheckbox("Border Visible",l,(e=>{i.applyOptions({borderVisible:e})}));const c=i.options().ticksVisible||!1;this.addCheckbox("Ticks Visible",c,(e=>{i.applyOptions({ticksVisible:e})}))}buildCloneSeriesTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Clone Series - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Clone Series logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildVisibilityOptionsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Visibility Options - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Visibility Options logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildStyleOptionsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Style Options - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Style Options logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildWidthOptionsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Width Options - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Width Options logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildPrimitivesTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Primitives",Object.assign(e.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(e),this.handler._seriesList.forEach((e=>{if(e.primitives&&Array.isArray(e.primitives)&&e.primitives.length>0){let t="Unnamed Series";const i=e.options();i&&i.title&&(t=i.title);const s=document.createElement("div");Object.assign(s.style,{border:"2px solid #666",marginBottom:"12px",padding:"8px",borderRadius:"4px"});const n=document.createElement("div");n.innerText=`Series: ${t}`,Object.assign(n.style,{fontSize:"18px",fontWeight:"bold",marginBottom:"8px"}),s.appendChild(n),e.primitives.forEach(((e,t)=>{let i;if("function"==typeof e.options?i=e.options():e._options?i=e._options:e.options&&(i=e.options),!i)return;const n=document.createElement("div");Object.assign(n.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"});const o=document.createElement("div");o.innerText=`Primitive ${t+1}: ${e.name||"Unnamed"}`,Object.assign(o.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"6px"}),n.appendChild(o),this.buildPrimitiveColorOptions(i,n,(t=>{e.applyOptions(t)})),s.appendChild(n)})),this.contentArea.appendChild(s)}}))}buildIndicatorsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Indicators - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Indicators logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildSourceCodeTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Source Code & Licensing",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="12px",this.contentArea.appendChild(e);const t=document.createElement("div");t.style.marginBottom="12px",t.style.fontSize="16px",t.innerHTML='\n

\n This project is a derivative work that incorporates components from the following repositories:\n

\n

\n Base Source Repositories:\n

\n \n

\n Modified/Forked Repositories (by EsIstJosh):\n

\n \n ',this.contentArea.appendChild(t),this.addButton("⤝ Back",(()=>this.switchCategory(this.categories[0].id)),{backgroundColor:"#444"})}buildSeriesMenuTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Series Settings - ${e.options().title??"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t),this.addTextInput("Title",e.options().title||"",(t=>{e.applyOptions({title:t});const i=e.options().title;i&&this.handler.seriesMap.has(i)&&this.handler.seriesMap.delete(i),this.handler.seriesMap.set(t,e)})),this.addButton("Clone Series ▸",(()=>this.buildCloneSeriesTab(e))),this.addButton("Visibility Options ▸",(()=>this.buildVisibilityOptionsTab(e))),this.addButton("Style Options ▸",(()=>this.buildStyleOptionsTab(e))),this.addButton("Width Options ▸",(()=>this.buildWidthOptionsTab(e))),this.addButton("Color Options ▸",(()=>this.buildSeriesColorsTabSingle(e))),this.addButton("Price Scale Options ▸",(()=>this.buildPriceScaleOptionsTab())),this.addButton("Primitives ▸",(()=>this.buildPrimitivesTab())),this.addButton("Indicators ▸",(()=>this.buildIndicatorsTab(e))),this.addButton("Export/Import Series Data ▸",(()=>this.buildDataExportImportTab(e)))}buildSeriesColorsTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Series Colors (All Series)",Object.assign(e.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(e);const t=Array.from(this.handler.seriesMap.entries());if(0===t.length){const e=document.createElement("div");return e.innerText="No series found.",e.style.color="#ccc",void this.contentArea.appendChild(e)}if(t.forEach((([e,t])=>{this.buildSeriesColorSection(e,t)})),this.handler.volumeSeries){const e=document.createElement("div");Object.assign(e.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"});const t=document.createElement("div");t.innerText="Series: Volume",Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"6px"}),e.appendChild(t);const i=this.handler.volumeSeries,s=this.handler.series.options().borderUpColor||"#00FF00",n=this.handler.series.options().borderDownColor||"#FF0000";let o=this.handler.volumeUpColor,r=this.handler.volumeDownColor;let a=o??s,l=r??n;const c=(e,t)=>{const s=[...i.data()];if(!s||0===s.length)return void console.warn("No volume data available to update colors.");const n=s.map(((i,n)=>{if(0===n)return{...i,color:e};const o=s[n-1].value,r=i.value>o?e:t;return{...i,color:r}}));i.setData(n),this.handler.volumeUpColor=e,this.handler.volumeDownColor=t};this.addSideBySideColors("Volume Colors",a,l,((e,t)=>{a=e,l=t,c(e,t)}),e),this.contentArea.appendChild(e)}}buildSeriesColorSection(e,t){const i=document.createElement("div");Object.assign(i.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"});const s=document.createElement("div");s.innerText=`Series: ${e}`,Object.assign(s.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"6px"}),i.appendChild(s);const n=t.seriesType?.();if("Candlestick"===n||"Bar"===n||"Custom"===n&&"upColor"in t.options())"upColor"in t.options()&&this.addSideBySideColors("Body",t.options().upColor,t.options().downColor,((e,i)=>{t.applyOptions({upColor:e,downColor:i})}),i),"borderUpColor"in t.options()&&(this.addSideBySideColors("Borders",t.options().borderUpColor,t.options().borderDownColor,((e,i)=>{t.applyOptions({borderUpColor:e,borderDownColor:i})}),i,t),this.addSideBySideColors("Wick",t.options().wickUpColor,t.options().wickDownColor,((e,i)=>{t.applyOptions({wickUpColor:e,wickDownColor:i})}),i,t));else if("Line"===n||"Custom"===n&&"color"in t.options()){const e=t.options().color||"#ffffff";this.addColorPicker("Line Color",e,(e=>t.applyOptions({color:e})),i)}else if("Area"===n){const e=t.options();this.addColorPicker("Line Color",e.lineColor||"#EEEEEE",(e=>{t.applyOptions({lineColor:e})}),i,t),this.addColorPicker("Top Fill",e.topColor||"#008cff44",(e=>{t.applyOptions({topColor:e})}),i,t),this.addColorPicker("Bottom Fill",e.bottomColor||"#008cff00",(e=>{t.applyOptions({bottomColor:e})}),i,t)}else{const e=document.createElement("div");e.innerText=`No color settings for series type: ${n}`,e.style.color="#bbb",i.appendChild(e)}this.contentArea.appendChild(i)}buildSeriesColorsTabSingle(e){this.contentArea.innerHTML="";const t=document.createElement("div");Object.assign(t.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText=`Color Options - ${e.options().title||"Untitled"}`,Object.assign(i.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),t.appendChild(i);const s=e.type?.();if("Candlestick"===s||"Bar"===s||"Custom"===s&&"upColor"in e.options())"upColor"in e.options()&&this.addSideBySideColors("Body",e.options().upColor,e.options().downColor,((t,i)=>{e.applyOptions({upColor:t,downColor:i})}),t,e),"borderUpColor"in e.options()&&(this.addSideBySideColors("Borders",e.options().borderUpColor,e.options().borderDownColor,((t,i)=>{e.applyOptions({borderUpColor:t,borderDownColor:i})}),t,e),this.addSideBySideColors("Wick",e.options().wickUpColor,e.options().wickDownColor,((t,i)=>{e.applyOptions({wickUpColor:t,wickDownColor:i})}),t,e));else if("Line"===s||"Custom"===s&&"color"in e.options()){const i=e.options().color||"#FFFFFF";this.addColorPicker("Line Color",i,(t=>{e.applyOptions({color:t})}),t,e)}else if("Area"===s){const i=e.options();this.addColorPicker("Line Color",i.lineColor||"#EEEEEE",(t=>{e.applyOptions({lineColor:t})}),t,e)}else{const e=document.createElement("div");e.innerText=`No color settings for series type: ${s}`,e.style.color="#bbb",t.appendChild(e)}const n=document.createElement("button");n.innerText="⤝ Back",Object.assign(n.style,{backgroundColor:"#444",marginTop:"16px",padding:"8px 12px",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer"}),n.onclick=()=>this.buildSeriesMenuTab(e),t.appendChild(n)}buildDataExportImportTab(e){this.subTabSkeleton("Export/Import",e,"(Export/Import logic not yet implemented.)")}subTabSkeleton(e,t,i){this.contentArea.innerHTML="";const s=document.createElement("div");s.innerText=`${e} - ${t.options().title||"Untitled"}`,Object.assign(s.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(s);const n=document.createElement("div");n.innerText=i,Object.assign(n.style,{color:"#ccc",marginBottom:"12px"}),this.contentArea.appendChild(n),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(t)),{backgroundColor:"#444"})}buildDefaultsListTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Default Configurations",Object.assign(e.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(e);const t=this.handler?.defaultsManager;if(!t){const e=document.createElement("div");return e.innerText="No defaults manager found.",e.style.color="#ccc",void this.contentArea.appendChild(e)}const i=t.getAll(),s=Array.from(i.keys());if(0===s.length){const e=document.createElement("div");return e.innerText="No default configurations found.",e.style.color="#ccc",void this.contentArea.appendChild(e)}this.addButton("Current Chart Config ▸",(e=>{this.handler.ContextMenu.dataMenu||(this.handler.ContextMenu.dataMenu=new xo({contextMenu:this.handler.ContextMenu,handler:this.handler})),this.handler.ContextMenu.dataMenu.openMenu(this.handler,e,"Handler")}),{backgroundColor:"#444",borderRadius:"8px",marginBottom:"8px",display:"block"}),s.forEach((e=>{this.addButton(`Edit "${e}" Defaults`,(()=>{this.handler.ContextMenu?.dataMenu&&"function"==typeof this.handler.ContextMenu.dataMenu.openDefaultOptions?this.handler.ContextMenu.dataMenu.openDefaultOptions(e):console.warn("No dataMenu or openDefaultOptions method found on handler.")}),{backgroundColor:"#444",borderRadius:"8px",marginBottom:"8px",display:"block"})}))}addColorPicker(e,t,i,s=this.contentArea,n){const o=document.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px",fontFamily:"sans-serif",fontSize:"16px"});const r=document.createElement("span");r.innerText=e,o.appendChild(r);const a=document.createElement("div");Object.assign(a.style,{width:"26px",height:"26px",borderRadius:"4px",cursor:"pointer",border:"1px solid #999",backgroundColor:t}),o.appendChild(a);const l=e=>{if(!n)return;const t=this.handler.legend._lines.find((e=>e.series===n));t&&(t.colors[0]=e)};a.addEventListener("click",(e=>{this.colorPicker?(this.colorPicker.update(a.style.backgroundColor,(e=>{a.style.backgroundColor=e,i(e),l(e)})),this.colorPicker.openMenu(e,a.offsetWidth,(e=>{a.style.backgroundColor=e,i(e),l(e)}))):console.warn("No colorPicker defined!")})),s.appendChild(o)}addDropdown(e,t,i,s){const n=document.createElement("div");n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="space-between",n.style.marginBottom="8px";const o=document.createElement("span");o.innerText=e,n.appendChild(o);const r=document.createElement("select");r.style.backgroundColor="#444",r.style.color="#fff",r.style.border="1px solid #555",r.style.borderRadius="4px",r.style.outline="none",t.forEach((e=>{const t=document.createElement("option");t.value=e,t.innerText=e,s&&e===s&&(t.selected=!0),r.appendChild(t)})),s&&(r.value=s),r.onchange=()=>i(r.value),n.appendChild(r),this.contentArea.appendChild(n)}addButton(e,t,i){const s=document.createElement("button");s.innerText=e,Object.assign(s.style,{padding:"8px 12px",margin:"4px 0",backgroundColor:"#008CBA",color:"#fff",border:"none",borderRadius:"8px",cursor:"pointer",fontFamily:"sans-serif",fontSize:"16px"}),i&&Object.assign(s.style,i),s.onclick=t,this.contentArea.appendChild(s)}addNumberField(e,t,i){const s=document.createElement("div");s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="space-between",s.style.marginBottom="8px";const n=document.createElement("span");n.innerText=e,s.appendChild(n);const o=document.createElement("input");o.type="number",o.value=t.toString(),o.style.width="60px",o.style.backgroundColor="#444",o.style.color="#fff",o.style.border="1px solid #555",o.style.borderRadius="4px",o.oninput=()=>{const e=parseFloat(o.value);i(isNaN(e)?0:e)},s.appendChild(o),this.contentArea.appendChild(s)}addCheckbox(e,t,i){const s=document.createElement("label");s.style.display="flex",s.style.alignItems="center",s.style.marginBottom="8px";const n=document.createElement("input");n.type="checkbox",n.checked=t,n.style.marginRight="8px",n.onchange=()=>i(n.checked),s.appendChild(n);const o=document.createElement("span");o.innerText=e,s.appendChild(o),this.contentArea.appendChild(s)}getCurrentOptionValue(e){const t=e.split(".");let i=this.handler.chart.options();for(const s of t){if(!i||!(s in i))return console.warn(`Option path "${e}" is invalid.`),null;i=i[s]}return i}toggleBackgroundType(){const e=this.handler.chart.options().layout?.background;if(!e)return this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.Solid,color:"#FFFFFF"}}}),void this.buildLayoutOptionsTab();if(e.type===t.ColorType.Solid){const i=e.color||"#FFFFFF",s="rgba(0,255,0,0.33)",n={type:t.ColorType.VerticalGradient,topColor:i,bottomColor:s};this.handler.chart.applyOptions({layout:{background:n}})}else if(e.type===t.ColorType.VerticalGradient){const i=e.topColor||"#FFFFFF",s={type:t.ColorType.Solid,color:i};this.handler.chart.applyOptions({layout:{background:s}})}else console.warn("Unknown background type. Falling back to solid #FFFFFF."),this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.Solid,color:"#FFFFFF"}}});this.buildLayoutOptionsTab()}addTextInput(e,t,i){const s=document.createElement("div");Object.assign(s.style,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px",fontFamily:"sans-serif",fontSize:"16px"});const n=document.createElement("span");n.innerText=e,s.appendChild(n);const o=document.createElement("input");o.type="text",o.value=t,Object.assign(o.style,{width:"150px",padding:"4px",backgroundColor:"#444",color:"#fff",border:"1px solid #555",borderRadius:"4px"}),o.oninput=()=>i(o.value),s.appendChild(o),this.contentArea.appendChild(s)}addSideBySideColors(e,t,i,s,n=this.contentArea,o){const r=document.createElement("div");Object.assign(r.style,{display:"flex",alignItems:"center",marginBottom:"8px",gap:"12px"});const a=document.createElement("input");a.type="checkbox",a.checked=!(0===p(t)&&0===p(i)),r.appendChild(a);const c=document.createElement("span");c.innerText=e,Object.assign(c.style,{minWidth:"60px"}),r.appendChild(c);const h=document.createElement("div");Object.assign(h.style,{display:"flex",gap:"8px"}),r.appendChild(h);let d=t,u=i;e in this._originalOpacities||(this._originalOpacities[e]={up:p(t)??1,down:p(i)??1});const m=document.createElement("div");Object.assign(m.style,{width:"32px",height:"32px",borderRadius:"4px",cursor:"pointer",border:"1px solid #999",backgroundColor:d});const g=document.createElement("div");Object.assign(g.style,{width:"32px",height:"32px",borderRadius:"4px",cursor:"pointer",border:"1px solid #999",backgroundColor:u}),h.appendChild(m),h.appendChild(g);const f=()=>{if(s(d,u),o){const e=this.handler.legend._lines.find((e=>e.series===o));e&&(e.colors[0]=d,e.colors[1]=u)}};a.addEventListener("change",(()=>{a.checked?(d=l(d,this._originalOpacities[e].up??p(t)),u=l(u,this._originalOpacities[e].down??p(i)),m.style.border="1px solid #999",g.style.border="1px solid #999"):(this._originalOpacities[e].up=p(d),this._originalOpacities[e].down=p(u),d=l(d,0),u=l(u,0),m.style.border="0px",g.style.border="0px"),m.style.backgroundColor=d,g.style.backgroundColor=u,a.checked=!(0===p(d)&&0===p(u)),f()})),m.addEventListener("click",(e=>{a.checked||(a.checked=!0,a.dispatchEvent(new Event("change"))),this.colorPicker.openMenu(e,m.offsetWidth+g.offsetWidth,(e=>{d=e,m.style.backgroundColor=e,f()}))})),g.addEventListener("click",(e=>{a.checked||(a.checked=!0,a.dispatchEvent(new Event("change"))),this.colorPicker.openMenu(e,g.offsetWidth,(e=>{u=e,g.style.backgroundColor=e,f()}))})),n.appendChild(r)}buildPrimitiveColorOptions(e,t,i){const s={Body:["upColor","downColor"],Borders:["borderUpColor","borderDownColor"],Wick:["wickUpColor","wickDownColor"]},n=new Set;for(const o in s){const[r,a]=s[o];r in e&&a in e&&(n.add(r),n.add(a),this.addSideBySideColors(o,e[r],e[a],((t,s)=>{e[r]=t,e[a]=s,i(e)}),t))}Object.keys(e).forEach((s=>{s.toLowerCase().includes("color")&&!n.has(s)&&this.addColorPicker(s,e[s],(t=>{e[s]=t,i(e)}),t)}))}}let wo=null;class Co{handler;handlerMap;getMouseEventParams;div;hoverItem;items=[];colorPicker;saveDrawings=null;drawingTool=null;recentSeries=null;recentDrawing=null;SettingsModal=null;volumeProfile=null;dataMenu;constructor(e,t,i){this.handler=e,this.handlerMap=t,this.getMouseEventParams=i,this.div=document.createElement("div"),this.div.classList.add("context-menu"),document.body.appendChild(this.div),this.div.style.overflowY="scroll",this.hoverItem=null,document.body.addEventListener("contextmenu",this._onRightClick.bind(this)),document.body.addEventListener("click",this._onClick.bind(this));const s=Array.isArray(this.handler.defaultsManager.get("colors"))?[...this.handler.defaultsManager.get("colors")]:[];this.colorPicker=new xn("#ff0000",(()=>null),s&&0!==s.length?s:void 0),this.dataMenu=new xo({contextMenu:this,handler:this.handler}),this.SettingsModal=new _o(this.handler),this.setupMenu()}constraints={baseline:{skip:!0},title:{skip:!0},PriceLineSource:{skip:!0},tickInterval:{min:0,max:100},lastPriceAnimation:{skip:!0},lineType:{min:0,max:2},lineStyle:{min:0,max:4},seriesType:{skip:!0},chandelierSize:{min:1},volumeMALength:{skip:!0},volumeMultiplier:{skip:!0},volumeOpacityPeriod:{skip:!0}};setupDrawingTools(e,t){this.saveDrawings=e,this.drawingTool=t}shouldSkipOption(e){return!!(this.constraints[e]||{}).skip}separator(){const e=document.createElement("div");e.style.width="90%",e.style.height="1px",e.style.margin="3px 0px",e.style.backgroundColor=window.pane.borderColor,this.div.appendChild(e),this.items.push(e)}menuItem(e,t,i=null){const s=document.createElement("span");s.classList.add("context-menu-item"),this.div.appendChild(s);const n=document.createElement("span");if(n.innerText=e,n.style.pointerEvents="none",s.appendChild(n),i){let e=document.createElement("span");e.innerText="►",e.style.fontSize="8px",e.style.pointerEvents="none",s.appendChild(e)}if(s.addEventListener("mouseover",(()=>{this.hoverItem&&this.hoverItem.closeAction&&this.hoverItem.closeAction(),this.hoverItem={elem:n,action:t,closeAction:i}})),i){let e;s.addEventListener("mouseover",(()=>e=setTimeout((()=>t(s.getBoundingClientRect())),100))),s.addEventListener("mouseout",(()=>clearTimeout(e)))}else s.addEventListener("click",(e=>{t(e),this.div.style.display="none"}));this.items.push(s)}_onClick(e){const t=e.target;this.colorPicker&&!this.colorPicker.getElement().contains(t)&&this.colorPicker.closeMenu()}_onRightClick(e){e.preventDefault();const t=this.getMouseEventParams(),i=this.getProximitySeries(this.getMouseEventParams()),s=this.getProximityDrawing(),n=this.getProximityTrendTrace();console.log("Mouse Event Params:",t),console.log("Proximity Series:",i),console.log("Proximity Drawing:",s),this.clearMenu(),this.clearAllMenus(),i?(console.log("Right-click detected on a series (proximity)."),this.populateSeriesMenu(i,e),this.recentSeries=i):s?(console.log("Right-click detected on a drawing."),this.populateDrawingMenu(e,s),this.recentDrawing=s):n?(console.log("Right-click detected on a drawing."),this.populateTrendTraceMenu(e,n)):t?.hoveredSeries?(console.log("Right-click detected on a series (hovered)."),this.populateSeriesMenu(t.hoveredSeries,e),this.recentSeries=i):(console.log("Right-click detected on the chart background."),this.populateChartMenu(e)),this.showMenu(e),e.preventDefault(),e.stopPropagation()}getProximityDrawing(){return O.hoveredObject?O.hoveredObject:null}getProximityTrendTrace(){return Zs.hoveredObject?Zs.hoveredObject:null}getProximitySeries(e){if(!e||!e.seriesData)return console.warn("No mouse event parameters or series data available."),null;if(!e.point)return console.warn("No point data in MouseEventParams."),null;const t=e.point.y;let i=null;const s=this.handler.chart.panes()[e.paneIndex??0].getSeries()[0];if(this.handler.series&&this.handler.series.getPane().paneIndex()===e.paneIndex)i=this.handler.series,console.log("Using handler.series for coordinate conversion.");else{if(!s)return console.warn("No handler.series or referenceSeries available."),null;i=s,console.log("Using referenceSeries for coordinate conversion.")}e.paneIndex!==i.getPane().paneIndex()&&(i=this.handler.chart.panes()[e.paneIndex??1].getSeries()[0]);const n=i.coordinateToPrice(t);if(console.log(`Converted chart Y (${t}) to Price: ${n}`),null===n)return console.warn("Cursor price is null. Unable to determine proximity."),null;const o=[];return e.seriesData.forEach(((t,s)=>{let r;if(f(t)?r=t.value:y(t)&&(r=t.close),void 0!==r&&!isNaN(r)){const t=Math.abs(r-n),a=this.handler.chart.panes()[e.paneIndex].getHeight(),l=i.coordinateToPrice(0),c=i.coordinateToPrice(a);if(null===l||null===c)return null;t/(l-c)*100<=3&&e.paneIndex===s.getPane().paneIndex()&&o.push({distance:t,series:s})}})),o.sort(((e,t)=>e.distance-t.distance)),o.length>1&&this.recentSeries===o[0].series?(console.log("Multiple series found."),o[1].series):o.length>0?(console.log("Closest series found."),o[0].series):(console.log("No series found within the proximity threshold."),null)}showMenu(e){const t=e.clientX,i=e.clientY;this.div.style.position="absolute",this.div.style.zIndex="10000",this.div.style.left=`${t}px`,this.div.style.top=`${i}px`,this.div.style.width="250px",this.div.style.maxHeight="400px",this.div.style.overflowY="auto",this.div.style.display="block",this.div.style.overflowX="hidden",console.log("Displaying Menu at:",t,i),wo=this.div,console.log("Displaying Menu",t,i),document.addEventListener("mousedown",this.hideMenuOnOutsideClick.bind(this),{once:!0}),window.menu=!0}hideMenuOnOutsideClick(e){this.div.contains(e.target)||this.hideMenu()}hideMenu(){this.div.style.display="none",wo===this.div&&(wo=null,window.menu=!1)}clearAllMenus(){this.handlerMap.forEach((e=>{e.ContextMenu&&e.ContextMenu.clearMenu()}))}setupMenu(){if(!this.div.querySelector(".chart-options-container")){const e=document.createElement("div");e.classList.add("chart-options-container"),this.div.appendChild(e)}this.div.querySelector(".context-menu-item.close-menu")||this.addMenuItem("Close Menu",(()=>this.hideMenu()))}addNumberInput(e,t,i,s,n,o){return this.addMenuInput(this.div,{type:"number",label:e,value:t,onChange:i,min:s,max:n,step:o})}addCheckbox(e,t,i){return this.addMenuInput(this.div,{type:"boolean",label:e,value:t,onChange:i})}addSelectInput(e,t,i,s){return this.addMenuInput(this.div,{type:"select",label:e,value:t,onChange:s,options:i})}addMenuInput(e,t,i=""){const s=document.createElement("div");if(s.classList.add("context-menu-item"),s.style.display="flex",s.style.alignItems="right",s.style.justifyContent="space-around",t.label){const o=document.createElement("label");o.innerText=t.label,o.htmlFor=`${i}${t.label.toLowerCase()}`,o.style.flex="0.8",o.style.whiteSpace="nowrap",s.appendChild(o)}let n;switch(t.type){case"hybrid":{if(!t.hybridConfig)throw new Error("Hybrid type requires hybridConfig.");const r=document.createElement("div");r.classList.add("context-menu-item"),r.style.position="relative",r.style.display="flex",r.style.flexDirection="row",r.style.justifyContent="flex-end",r.style.alignItems="right";const a={backgroundColor:"#2b2b2b",color:"#fff",border:"1px solid #444",padding:"2px 2px",textAlign:"center",cursor:"pointer",boxSizing:"border-box",display:"flex",alignItems:"right",justifyContent:"right"};function l(e,t){for(const[i,s]of Object.entries(t))e.style[i]=s}const c=document.createElement("div");l(c,a),c.style.borderRadius="4px 0 0 4px",c.innerText=t.sublabel??"▵",c.addEventListener("click",(e=>{e.stopPropagation(),t.hybridConfig.defaultAction()}));const h=document.createElement("div");l(h,a),h.style.borderLeft="none",h.style.borderRadius="0 4px 4px 0",h.innerText="☷";const p=document.createElement("div");if(p.style.position="absolute",p.style.top="100%",p.style.right="0",p.style.backgroundColor="#2b2b2b",p.style.color="#fff",p.style.border="1px solid #444",p.style.borderRadius="4px",p.style.minWidth="100px",p.style.boxShadow="0px 2px 5px rgba(0, 0, 0, 0.5)",p.style.zIndex="10000",p.style.display="none",1===t.hybridConfig.options.length){const d=t.hybridConfig.options[0];h.addEventListener("click",(e=>{e.stopPropagation(),d.action()}))}else t.hybridConfig.options.forEach((e=>{const t=document.createElement("div");t.innerText=e.name,t.style.cursor="pointer",t.style.padding="5px 10px",t.addEventListener("click",(t=>{t.stopPropagation(),p.style.display="none",e.action()})),t.addEventListener("mouseenter",(()=>{t.style.backgroundColor="#444"})),t.addEventListener("mouseleave",(()=>{t.style.backgroundColor="#2b2b2b"})),p.appendChild(t)})),h.addEventListener("click",(e=>{e.stopPropagation(),p.style.display="none"===p.style.display?"block":"none"})),r.appendChild(p);r.appendChild(c),r.appendChild(h),n=r;break}case"number":{const u=document.createElement("input");u.type="number",u.value=void 0!==t.value?t.value.toString():"",u.style.backgroundColor="#2b2b2b",u.style.color="#fff",u.style.border="1px solid #444",u.style.borderRadius="4px",u.style.textAlign="center",u.style.marginLeft="auto",u.style.marginRight="8px",u.style.width="40px",void 0!==t.min&&(u.min=t.min.toString()),void 0!==t.max&&(u.max=t.max.toString()),void 0===t.step||isNaN(t.step)?u.step="1":u.step=t.step.toString(),u.addEventListener("input",(e=>{const i=e.target;let s=parseFloat(i.value);isNaN(s)||t.onChange(s)})),n=u;break}case"boolean":{const m=document.createElement("input");m.type="checkbox",m.checked=t.value??!1,m.style.marginLeft="auto",m.style.marginRight="8px",m.addEventListener("change",(e=>{const i=e.target;t.onChange(i.checked)})),n=m;break}case"select":{const g=document.createElement("select");g.id=`${i}${t.label?t.label.toLowerCase():"select"}`,g.style.backgroundColor="#2b2b2b",g.style.color="#fff",g.style.border="1px solid #444",g.style.borderRadius="4px",g.style.marginLeft="auto",g.style.marginRight="8px",g.style.width="80px",t.options?.forEach((e=>{const i=document.createElement("option");i.value=e,i.text=e,i.style.whiteSpace="normal",i.style.textAlign="right",e===t.value&&(i.selected=!0),g.appendChild(i)})),g.addEventListener("change",(e=>{const i=e.target;t.onChange(i.value)})),n=g;break}case"string":{const f=document.createElement("input");f.type="text",f.value=t.value??"",f.style.backgroundColor="#2b2b2b",f.style.color="#fff",f.style.border="1px solid #444",f.style.borderRadius="4px",f.style.marginLeft="auto",f.style.textAlign="center",f.style.marginRight="8px",f.style.width="60px",f.addEventListener("input",(e=>{const i=e.target;t.onChange(i.value)})),n=f;break}case"color":{const y=document.createElement("input");y.type="color",y.value=t.value??"#000000",y.style.marginLeft="auto",y.style.cursor="pointer",y.style.marginRight="8px",y.style.width="100px",y.addEventListener("input",(e=>{const i=e.target;t.onChange(i.value)})),n=y;break}default:throw new Error("Unsupported input type")}return s.style.padding="2px 10px 2px 10px",s.appendChild(n),e.appendChild(s),s}addMenuItem(e,t,i=!0,s=!1,n=1){const o=document.createElement("span");if(o.classList.add("context-menu-item"),o.innerText=e,s){const e=document.createElement("span");e.classList.add("submenu-arrow"),e.innerText="ː".repeat(n),o.appendChild(e)}o.addEventListener("click",(e=>{e.stopPropagation(),t(),i&&this.hideMenu()}));const r=["➩","➯","➱","➬","➫"];return o.addEventListener("mouseenter",(()=>{if(o.style.backgroundColor="royalblue",o.style.color="white",!o.querySelector(".hover-arrow")){const e=document.createElement("span");e.classList.add("hover-arrow");const t=Math.floor(Math.random()*r.length),i=r[t];e.innerText=i,e.style.marginLeft="auto",e.style.fontSize="8px",e.style.color="white",o.appendChild(e)}})),o.addEventListener("mouseleave",(()=>{o.style.backgroundColor="",o.style.color="";const e=o.querySelector(".hover-arrow");e&&o.removeChild(e)})),this.div.appendChild(o),this.items.push(o),o}clearMenu(){this.div.querySelectorAll(".context-menu-item:not(.close-menu), .context-submenu").forEach((e=>e.remove())),this.items=[],this.div.innerHTML=""}addColorPickerMenuItem(e,t,i,s){const n=document.createElement("span");n.classList.add("context-menu-item"),n.innerText=e,this.div.appendChild(n);const o=e=>{const t=Gs(i,e);s.applyOptions(t),console.log(`Updated ${i} to ${e}`);if("object"==typeof(n=s)&&null!==n&&"function"==typeof n.applyOptions&&"function"==typeof n.dataByIndex&&["color","lineColor","upColor","downColor"].includes(i)){const t=this.handler.legend._lines.find((e=>e.series===s));t&&("downColor"===i?(t.colors[1]=e,console.log(`Legend down color updated to: ${e}`)):(t.colors[0]=e,console.log(`Legend up/main color updated to: ${e}`)))}var n};return n.addEventListener("click",(e=>{e.stopPropagation(),this.colorPicker||(this.colorPicker=new xn(t??"#000000",o)),this.colorPicker.openMenu(e,225,o)})),n}currentWidthOptions=[];currentStyleOptions=[];populateSeriesMenu(e,i){const s=Ns(e,this.handler.legend),o=e.options();if(!o)return void console.warn("No options found for the selected series.");this.div.innerHTML="";const r=[],a=[],l=[],c=[],h=[];for(const e of Object.keys(o)){const i=o[e];if(this.shouldSkipOption(e))continue;if(e.toLowerCase().includes("base"))continue;const s=Fs(e).toLowerCase(),d=s.includes("width")||"radius"===s||s.includes("radius");if(s.includes("color"))"string"==typeof i?r.push({label:e,value:i}):console.warn(`Expected string value for color option "${e}".`);else if(d){if("number"==typeof i){let t=1,n=10,o=1;s.includes("radius")&&(t=0,n=1,o=.1),c.push({name:e,label:e,value:i,min:t,max:n,step:o})}}else if(s.includes("visible")||s.includes("visibility"))"boolean"==typeof i?a.push({label:e,value:i}):console.warn(`Expected boolean value for visibility option "${e}".`);else if("lineType"===e){const t=this.getPredefinedOptions(Fs(e));h.push({name:e,label:e,value:i,options:t})}else if("crosshairMarkerRadius"===e)"number"==typeof i?c.push({name:e,label:e,value:i,min:1,max:50}):console.warn(`Expected number value for crosshairMarkerRadius option "${e}".`);else if(s.includes("style")){if("string"==typeof i||Object.values(t.LineStyle).includes(i)||"number"==typeof i){const t=["Solid","Dotted","Dashed","Large Dashed","Sparse Dotted"];h.push({name:e,label:e,value:i,options:t})}}else if(s.includes("shape")){if(p=i,Object.values(n).includes(p)){const t=["Rectangle","Rounded","Ellipse","Arrow","3d","Polygon","Bar","Slanted"];t&&h.push({name:e,label:e,value:i,options:t})}}else l.push({label:e,value:i})}var p;this.currentWidthOptions=c,this.currentStyleOptions=h,this.addTextInput("Title",e.options().title||"",(t=>{const i={title:t};this.handler.seriesMap.has(e.options().title)&&this.handler.seriesMap.delete(e.options().title),this.handler.seriesMap.set(t,e),console.log(`Updated seriesMap label to: ${t}`);const s=this.handler.legend._lines.find((t=>t.series===e));s&&s.series===e&&(s.name=t,console.log(`Updated legend title to: ${t}`)),e.applyOptions(i),console.log(`Updated title to: ${t}`)}));const d=e.getPane().paneIndex(),u=this.handler.chart.panes(),m=`Pane ${d}`,g=[];for(let t=0;t{e.moveToPane(t),console.log(`Moved series to existing pane ${t}.`)}});if(g.push({name:"New Pane",action:()=>{e.moveToPane(u.length),console.log(`Moved series to a new pane at index ${u.length}.`)}}),this.addMenuInput(this.div,{type:"hybrid",label:"Move to pane",sublabel:0===d?"New Pane":"Top",value:m,onChange:e=>{const t=g.find((t=>t.name===e));t&&t.action()},hybridConfig:{defaultAction:()=>{0===d?(e.moveToPane(u.length),console.log(`Default: Moved series from pane ${d} to a new pane at index ${u.length}.`)):(e.moveToPane(0),console.log(`Default: Moved series from pane ${d} back to main pane (0).`))},options:g.map((e=>({name:e.name,action:e.action})))}}),this.addMenuItem("Clone Series ▸",(()=>{this.populateCloneSeriesMenu(e,i)}),!1,!0),a.length>0&&this.addMenuItem("Visibility Options ▸",(()=>{this.populateVisibilityMenu(i,e)}),!1,!0),this.currentStyleOptions.length>0&&this.addMenuItem("Style Options ▸",(()=>{this.populateStyleMenu(i,e)}),!1,!0),this.currentWidthOptions.length>0&&this.addMenuItem("Width Options ▸",(()=>{this.populateWidthMenu(i,e)}),!1,!0),r.length>0&&this.addMenuItem("Color Options ▸",(()=>{this.populateColorOptionsMenu(r,e,i)}),!1,!0),o.enableVolumeOpacity&&this.addNumberInput("Volume Opacity Period",o.volumeOpacityPeriod??21,(t=>{const i={volumeOpacityPeriod:t};e.applyOptions(i),console.log(`Updated Volume Opacity Period to ${t}`)}),1,1e4,1),o.enableVolumeOpacity){const t=["/ max","> previous","> average"],i=t.includes(o.volumeOpacityMode)?o.volumeOpacityMode:"/ max";this.addSelectInput("Volume Opacity Mode",i??"> previous",t,(t=>{const i={volumeOpacityMode:t};e.applyOptions(i),console.log(`Updated Volume Opacity Mode to: ${t}`)}))}if(void 0!==o.dynamicCandles){const t=["false","trend","trigger","volume_trend"],s=o.dynamicCandles;this.addSelectInput("Dynamic Candles",s,t,(t=>{const s={dynamicCandles:t};e.applyOptions(s),console.log(`Updated dynamicCandles to: ${t}`),this.populateSeriesMenu(e,i)}))}if(l.forEach((t=>{const i=Fs(t.label);if(!this.constraints[t.label]?.skip)if("boolean"==typeof t.value)this.addCheckbox(Fs(t.label),Boolean(t.value),(i=>{const s=Gs(t.label,i);e.applyOptions(s),console.log(`Updated ${t.label} to ${i}`)}));else if("string"==typeof t.value){const s=this.getPredefinedOptions(t.label);s&&s.length>0?this.addMenuItem(`${i} ▸`,(()=>{this.div.innerHTML="",this.addSelectInput(i,t.value,s,(i=>{const s=Gs(t.label,i);e.applyOptions(s),console.log(`Updated ${t.label} to ${i}`)}))}),!1,!0):this.addMenuItem(`${i} ▸`,(()=>{this.div.innerHTML="",this.addTextInput(i,t.value,(i=>{const s=Gs(t.label,i);e.applyOptions(s),console.log(`Updated ${t.label} to ${i}`)}))}),!1,!0)}else{if("number"!=typeof t.value)return;{const s=this.constraints[t.label]?.min,n=this.constraints[t.label]?.max;this.addNumberInput(i,t.value,(i=>{const s=Gs(t.label,i);e.applyOptions(s),console.log(`Updated ${t.label} to ${i}`)}),s,n)}}})),this.addMenuItem("Price Scale Options ▸",(()=>{this.populatePriceScaleMenu(i,e.options().priceScaleId??"right",e)}),!1,!0),this.addMenuItem("Primitives ▸",(()=>{this.populatePrimitivesMenu(s,i)}),!1,!0),this.addMenuItem("Indicators ▸",(()=>{this.populateIndicatorMenu(e,i)}),!1,!0),function(e){return void 0!==e.figures&&void 0!==e.sourceSeries&&void 0!==e.indicator}(e)){const t=e;this.addMenuItem(`Configure ${t.indicator.name}`,(()=>{this.configureIndicatorParams(t,i,t.figureCount)}),!1)}this.addMenuItem("Export/Import Series Data ▸",(()=>{this.dataMenu||(this.dataMenu=new xo({contextMenu:this,handler:this.handler})),this.dataMenu.openMenu(e,i,"Series")}),!1),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(i)}),!1,!1),this.showMenu(i)}populateDrawingMenu(e,t){this.div.innerHTML="",this.drawingTool||(this.drawingTool=new $(this.handler.chart,this.handler._seriesList[0]));for(const e of Object.keys(t._options)){let t;if(e.toLowerCase().includes("color"))t=new vn(this.saveDrawings,e);else{if("lineStyle"!==e)continue;t=new _n(this.saveDrawings)}const i=e=>t.openMenu(e);this.menuItem(Fs(e),i,(()=>{document.removeEventListener("click",t.closeMenu),t._div.style.display="none"}))}if("PitchFork"===t._type){const i=t._options.variant||"standard",s=["standard","schiff","modifiedSchiff","inside"];this.addSelectInput("Pitchfork Variant",i,s,(e=>{t._options.variant=e,this.saveDrawings&&this.saveDrawings()})),this.addNumberInput("Length",t._options.length,(e=>{t._options.length=e,this.saveDrawings&&this.saveDrawings()}),0,1e3,.1),this.addMenuItem("Fork Line Options ▸",(()=>{this.populateForkLineMainMenu(e,t)}),!1,!0),this.addMenuItem("Export/Import PitchFork Data ▸",(()=>{this.dataMenu||(this.dataMenu=new xo({contextMenu:this,handler:this.handler})),this.dataMenu.openMenu(t,e,"PitchFork")}),!1)}if(t.points?.length>=2&&t.points[0]&&t.points[1]){let i;i=(t.points,t),i.linkedObjects?.length&&i.linkedObjects.forEach((t=>{t instanceof Zs?this.addMenuItem(`${t.title} Options`,(()=>{this.populateTrendTraceMenu(e,t)}),!1,!0):t instanceof Cn&&this.addMenuItem("Volume Profile Options",(()=>{this.populateVolumeProfileMenu(e,t)}),!1,!0)})),this.addMenuItem("Trend Trace ▸",(()=>{this._createTrendTrace(e,i)}),!1,!0),this.addMenuItem("Volume Profile ▸",(()=>{this._createVolumeProfile(i)}),!1,!0)}this.separator(),this.menuItem("Delete Drawing",(()=>this.drawingTool.delete(t))),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1,!1),this.showMenu(e)}populateChartMenu(e){this.div.innerHTML="",console.log("Displaying Menu Options: Chart"),this.addResetViewOption();const t=this.getMouseEventParams(),i=this.handler.chart.panes(),s=t?.paneIndex,n=this.handler.chart.panes()[s??0],o=()=>{s?n.moveTo(0):n.moveTo(i.length-1)},r=[];r.push({name:"Top",action:()=>{n.moveTo(0),console.log("Moved pane to top")}}),i.length>2&&(s??0)>1&&r.push({name:"Up",action:()=>{n.moveTo((s??2)-1),console.log("Moved pane up")}}),i.length>2&&(s??0){n.moveTo((s??0)+1),console.log("Moved pane down")}}),r.push({name:"Bottom",action:()=>{n.moveTo(i.length-1),console.log("Moved pane to bottom")}}),i.length>1&&this.addMenuInput(this.div,{type:"hybrid",label:"Move pane",sublabel:s?"Top":"Bottom",hybridConfig:{defaultAction:o,options:r.map((e=>({name:e.name,action:e.action})))}}),this.addMenuInput(this.div,{type:"hybrid",label:"Display Volume Profile",sublabel:"≖",hybridConfig:{defaultAction:()=>{this.volumeProfile?(this.handler.series.detachPrimitive(this.volumeProfile),this.volumeProfile=null,console.log("[ChartMenu] Detached Volume Profile.")):(this.volumeProfile=new Cn(this.handler,wn),this.handler.series.attachPrimitive(this.volumeProfile,"Visible Range Volume Profile",!1,!0),console.log("[ChartMenu] Attached Volume Profile."))},options:[{name:"Options",action:()=>{this.volumeProfile&&this.populateVolumeProfileMenu(e,this.volumeProfile)}}]}}),this.addMenuItem(" ~ Series List",(()=>{this.populateSeriesListMenu(e,!1,(t=>{this.populateSeriesMenu(t,e)}))}),!1,!0),this.addMenuItem("Settings...",(()=>{this.SettingsModal.open()}),!0),this.showMenu(e)}populateLayoutMenu(e){this.div.innerHTML="";const t="Text Color",i="layout.textColor",s=this.getCurrentOptionValue(i)||"#000000";this.addColorPickerMenuItem(Fs(t),s,i,this.handler.chart);const n=this.handler.chart.options().layout?.background;m(n)?this.addColorPickerMenuItem("Background Color",n.color||"#FFFFFF","layout.background.color",this.handler.chart):g(n)?(this.addColorPickerMenuItem("Top Color",n.topColor||"rgba(255,0,0,0.33)","layout.background.topColor",this.handler.chart),this.addColorPickerMenuItem("Bottom Color",n.bottomColor||"rgba(0,255,0,0.33)","layout.background.bottomColor",this.handler.chart)):console.warn("Unknown background type; no color options displayed."),this.addMenuItem("Switch Background Type",(()=>{this.toggleBackgroundType(e)}),!1,!0),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1,!1),this.showMenu(e)}toggleBackgroundType(e){const i=this.handler.chart.options().layout?.background;let s;s=m(i)?{type:t.ColorType.VerticalGradient,topColor:"rgba(255,0,0,0.2)",bottomColor:"rgba(0,255,0,0.2)"}:{type:t.ColorType.Solid,color:"#000000"},this.handler.chart.applyOptions({layout:{background:s}}),this.populateLayoutMenu(e)}populateWidthMenu(e,t){this.div.innerHTML="",this.currentWidthOptions.forEach((e=>{"number"==typeof e.value&&this.addNumberInput(Fs(e.label),e.value,(i=>{const s=Gs(e.name,i);t.applyOptions(s),console.log(`Updated ${e.label} to ${i}`)}),e.min,e.max)})),this.addMenuItem("⤝ Back to Series Options",(()=>{this.populateSeriesMenu(t,e)}),!1,!1),this.showMenu(e)}populatePrimitivesMenu(e,t){this.div.innerHTML="",console.log("Showing Primitive Menu ");const i=e.primitives;this.addMenuItem("Fill Area Between",(()=>{this.startFillAreaBetween(t,e)}),!1,!1),console.log("Primitives:",i);const s=i?.FillArea??i?.pt;i.FillArea&&this.addMenuItem("Customize Fill Area",(()=>{this.customizeFillAreaOptions(t,s)}),!1,!0),this.addMenuItem("Create TrendTrace",(()=>{this._createTrendTrace(t,this.recentDrawing)}),!1,!1),console.log("Primitives:",i),i.TrendTrace&&this.addMenuItem("Customize TrendTrace",(()=>{this.populateTrendTraceMenu(t,i.TrendTrace)}),!1,!0),this.addMenuItem("⤝ Back",(()=>{this.populateSeriesMenu(e,t)}),!1,!1),this.showMenu(t)}populateStyleMenu(e,t){this.div.innerHTML="",this.currentStyleOptions.forEach((e=>{const i=this.getPredefinedOptions(e.name);i?this.addSelectInput(Fs(e.name),e.value.toString(),i,(i=>{let s=i;if(e.name.toLowerCase().includes("style")){s={Solid:0,Dotted:1,Dashed:2,"Large Dashed":3,"Sparse Dotted":4}[i]??0}else if(e.name.toLowerCase().includes("linetype")){s={Simple:0,WithSteps:1,Curved:2}[i]??0}const n=Gs(e.name,s);if(t.applyOptions(n),console.log(`Updated ${e.name} to "${i}" =>`,s),e.name.toLowerCase().includes("style")&&"Line"===t.seriesType()){const e=s,i=(()=>{switch(e){case 0:return"―";case 1:return"··";case 2:return"--";case 3:return"- -";case 4:return"· ·";default:return"~"}})(),n=this.handler.legend._lines.find((e=>e.series===t));n&&(n.legendSymbol=[i],console.log(`Updated legend symbol for lineStyle(${e}) to: ${i}`))}})):console.warn(`No predefined options found for "${e.name}".`)})),this.addMenuItem("⤝ Back",(()=>{this.populateSeriesMenu(t,e)}),!1,!1),this.showMenu(e)}populateCloneSeriesMenu(e,t){this.div.innerHTML="";const i=e.data(),s=["Line","Histogram","Area"];if(i&&i.length>0){i.some((e=>y(e)))&&s.push("Bar","Candlestick","Ohlc")}s.forEach((t=>{this.addMenuItem(`Clone as ${t}`,(()=>{const i=function(e,t,i,s){try{const n=e.options(),o=Is(i),r={...o,...s},a=e.options().title??i;let l;switch(console.log(`Cloning ${e.seriesType()} as ${i}...`),i){case"Line":l=t.createLineSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;case"Histogram":l=t.createHistogramSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;case"Area":l=t.createAreaSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;case"Bar":l=t.createBarSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;case"Candlestick":l={name:`${a}<${i}>`,series:t.createCandlestickSeries()};break;case"Ohlc":l=t.createCustomOHLCSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;default:return console.error(`Unsupported series type: ${i}`),null}let c=e.data().map(((t,s)=>As(e,i,s))).filter((e=>null!==e));return l.series.setData(c),h(n,((e,t)=>{if(function(e,t){const i=e.split(".");let s=t;for(const e of i){if(!(e in s))return("color"===e||"LineColor"===e)&&("color"in s||"LineColor"in s);s=s[e]}return!0}(e,o))if("LineColor"===e||"color"===e){const e="LineColor"in o||"LineColor"in r,i="color"in o||"color"in r;e&&i?(Ds(l.series,"LineColor",t),Ds(l.series,"color",t)):e?Ds(l.series,"LineColor",t):i&&Ds(l.series,"color",t)}else Ds(l.series,e,t)})),Object.keys(r).forEach((e=>{e.toString().toLowerCase().includes("color")&&h({[e]:r[e]},((e,t)=>{console.log(`Found color option: ${e} = ${t}`)}))})),e.subscribeDataChanged((()=>{const t=e.data().map(((t,s)=>As(e,i,s))).filter((e=>null!==e));l.series.setData(t),console.log(`Updated synced series of type ${i}`)})),l.series}catch(e){return console.error("Error cloning series:",e),null}}(e,this.handler,t,this.handler.defaultsManager.defaults.get(t.toLowerCase())||{});i?console.log(`Cloned series as ${t}:`,i):console.warn(`Failed to clone as ${t}.`)}),!1)})),this.addMenuItem("⤝ Series Options",(()=>{this.populateSeriesMenu(e,t)}),!1,!1),this.showMenu(t)}addTextInput(e,t,i){const s=document.createElement("div");s.classList.add("context-menu-item"),s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="space-between";const n=document.createElement("label");n.innerText=e,n.htmlFor=`${e.toLowerCase()}-input`,n.style.marginRight="8px",n.style.flex="1",s.appendChild(n);const o=document.createElement("input");return o.type="text",o.value=t,o.id=`${e.toLowerCase()}-input`,o.style.flex="0 0 100px",o.style.marginLeft="auto",o.style.backgroundColor="#2b2b2b",o.style.color="#fff",o.style.border="1px solid #444",o.style.borderRadius="4px",o.style.cursor="pointer",o.addEventListener("input",(e=>{const t=e.target;i(t.value)})),s.appendChild(o),this.div.appendChild(s),s}populateColorOptionsMenu(e,t,i){this.div.innerHTML="",e.forEach((e=>{this.addColorPickerMenuItem(Fs(e.label),e.value,e.label,t)})),this.addMenuItem("⤝ Back to Series Options",(()=>{this.populateSeriesMenu(t,i)}),!1,!1),this.showMenu(i)}populateVisibilityMenu(e,t){this.div.innerHTML="";const i=t.options();["visible","crosshairMarkerVisible","priceLineVisible"].forEach((e=>{const s=i[e];"boolean"==typeof s&&this.addCheckbox(Fs(e),s,(i=>{const s=Gs(e,i);t.applyOptions(s),console.log(`Toggled ${e} to ${i}`)}))})),this.addMenuItem("⤝ Back to Series Options",(()=>{this.populateSeriesMenu(t,e)}),!1,!1),this.showMenu(e)}populateBackgroundTypeMenu(e){this.div.innerHTML="";[{text:"Solid",action:()=>this.setBackgroundType(e,t.ColorType.Solid)},{text:"Vertical Gradient",action:()=>this.setBackgroundType(e,t.ColorType.VerticalGradient)}].forEach((e=>{this.addMenuItem(e.text,e.action,!1,!1,1)})),this.addMenuItem("⤝ Chart Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populateGradientBackgroundMenuInline(e,t){this.div.innerHTML="",this.addColorPickerMenuItem(Fs("Top Color"),t.topColor,"layout.background.topColor",this.handler.chart),this.addColorPickerMenuItem(Fs("Bottom Color"),t.bottomColor,"layout.background.bottomColor",this.handler.chart),this.addMenuItem("⤝ Background Type & Colors",(()=>{this.populateBackgroundTypeMenu(e)}),!1),this.showMenu(e)}populateGridMenu(e){this.div.innerHTML="";[{name:"Vertical Line Color",type:"color",valuePath:"grid.vertLines.color",defaultValue:"#D6DCDE"},{name:"Horizontal Line Color",type:"color",valuePath:"grid.horzLines.color",defaultValue:"#D6DCDE"},{name:"Vertical Line Style",type:"select",valuePath:"grid.vertLines.style",options:["Solid","Dashed","Dotted","LargeDashed"],defaultValue:"Solid"},{name:"Horizontal Line Style",type:"select",valuePath:"grid.horzLines.style",options:["Solid","Dashed","Dotted","LargeDashed"],defaultValue:"Solid"},{name:"Show Vertical Lines",type:"boolean",valuePath:"grid.vertLines.visible",defaultValue:!0},{name:"Show Horizontal Lines",type:"boolean",valuePath:"grid.horzLines.visible",defaultValue:!0}].forEach((e=>{const t=this.getCurrentOptionValue(e.valuePath)??e.defaultValue;"color"===e.type?this.addColorPickerMenuItem(Fs(e.name),t,e.valuePath,this.handler.chart):"select"===e.type?this.addSelectInput(Fs(e.name),t,e.options,(t=>{const i=e.options.indexOf(t),s=Gs(e.valuePath,i);this.handler.chart.applyOptions(s),console.log(`Updated ${e.name} to: ${t}`)})):"boolean"===e.type&&this.addCheckbox(Fs(e.name),t,(t=>{const i=Gs(e.valuePath,t);this.handler.chart.applyOptions(i),console.log(`Updated ${e.name} to: ${t}`)}))})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populateBackgroundMenu(e){this.div.innerHTML="",this.addMenuItem("Type & Colors",(()=>{this.populateBackgroundTypeMenu(e)}),!1,!0),this.addMenuItem("Options",(()=>{this.populateBackgroundOptionsMenu(e)}),!1,!0),this.addMenuItem("⤝ Layout Options",(()=>{this.populateLayoutMenu(e)}),!1),this.showMenu(e)}populateBackgroundOptionsMenu(e){this.div.innerHTML="";[{name:"Background Color",valuePath:"layout.background.color"},{name:"Background Top Color",valuePath:"layout.background.topColor"},{name:"Background Bottom Color",valuePath:"layout.background.bottomColor"}].forEach((e=>{const t=this.getCurrentOptionValue(e.valuePath)||"#FFFFFF";this.addColorPickerMenuItem(Fs(e.name),t,e.valuePath,this.handler.chart)})),this.addMenuItem("⤝ Background",(()=>{this.populateBackgroundMenu(e)}),!1),this.showMenu(e)}populateSolidBackgroundMenuInline(e,t){this.div.innerHTML="",this.addColorPickerMenuItem(Fs("Background Color"),t.color,"layout.background.color",this.handler.chart),this.addMenuItem("⤝ Type & Colors",(()=>{this.populateBackgroundTypeMenu(e)}),!1),this.showMenu(e)}populateCrosshairOptionsMenu(e){this.div.innerHTML="";[{name:"Line Color",valuePath:"crosshair.lineColor"},{name:"Vertical Line Color",valuePath:"crosshair.vertLine.color"},{name:"Horizontal Line Color",valuePath:"crosshair.horzLine.color"}].forEach((e=>{const t=this.getCurrentOptionValue(e.valuePath)||"#000000";this.addColorPickerMenuItem(Fs(e.name),t,e.valuePath,this.handler.chart)})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populateTimeScaleMenu(e){this.div.innerHTML="";[{name:"Right Offset",type:"number",valuePath:"timeScale.rightOffset",min:0,max:100},{name:"Bar Spacing",type:"number",valuePath:"timeScale.barSpacing",min:1,max:100},{name:"Min Bar Spacing",type:"number",valuePath:"timeScale.minBarSpacing",min:.1,max:10,step:.1},{name:"Fix Left Edge",type:"boolean",valuePath:"timeScale.fixLeftEdge"},{name:"Fix Right Edge",type:"boolean",valuePath:"timeScale.fixRightEdge"},{name:"Lock Visible Range on Resize",type:"boolean",valuePath:"timeScale.lockVisibleTimeRangeOnResize"},{name:"Visible",type:"boolean",valuePath:"timeScale.visible"},{name:"Border Visible",type:"boolean",valuePath:"timeScale.borderVisible"},{name:"Border Color",type:"color",valuePath:"timeScale.borderColor"}].forEach((e=>{if("number"===e.type){const t=this.getCurrentOptionValue(e.valuePath);this.addNumberInput(Fs(e.name),t,(t=>{const i=Gs(e.valuePath,t);this.handler.chart.applyOptions(i),console.log(`Updated TimeScale ${e.name} to: ${t}`)}),e.min,e.max)}else if("boolean"===e.type){const t=this.getCurrentOptionValue(e.valuePath);this.addCheckbox(Fs(e.name),t,(t=>{const i=Gs(e.valuePath,t);this.handler.chart.applyOptions(i),console.log(`Updated TimeScale ${e.name} to: ${t}`)}))}else if("color"===e.type){const t=this.getCurrentOptionValue(e.valuePath)||"#000000";this.addColorPickerMenuItem(Fs(e.name),t,e.valuePath,this.handler.chart)}})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populatePriceScaleMenu(e,i="right",s){if(this.div.innerHTML="",s)this.addMenuInput(this.div,{type:"hybrid",label:"Price Scale",value:s.options().priceScaleId||"",onChange:e=>{s.applyOptions({priceScaleId:e}),console.log(`Updated price scale to: ${e}`)},hybridConfig:{defaultAction:()=>{const e="left"===s.options().priceScaleId?"right":"left";s.applyOptions({priceScaleId:e}),console.log(`Series price scale switched to: ${e}`)},options:[{name:"Left",action:()=>s.applyOptions({priceScaleId:"left"})},{name:"Right",action:()=>s.applyOptions({priceScaleId:"right"})},{name:"Volume",action:()=>s.applyOptions({priceScaleId:"volume_scale"})},{name:"Custom",action:()=>{const e=document.createElement("div"),t=document.createElement("input");t.type="text",t.placeholder="Enter custom scale ID",t.value=s.options().priceScaleId||"",t.addEventListener("change",(()=>{s.applyOptions({priceScaleId:t.value}),console.log(`Custom scale ID set to: ${t.value}`)})),e.appendChild(t),this.div.appendChild(e)}}]}});else{const n=this.handler.chart.priceScale(i).options().mode??t.PriceScaleMode.Normal,o=[{label:"Normal",value:t.PriceScaleMode.Normal},{label:"Logarithmic",value:t.PriceScaleMode.Logarithmic},{label:"Percentage",value:t.PriceScaleMode.Percentage},{label:"Indexed To 100",value:t.PriceScaleMode.IndexedTo100}],r=o.map((e=>e.label));this.addSelectInput("Price Scale Mode",o.find((e=>e.value===n))?.label||"Normal",r,(t=>{const n=o.find((e=>e.label===t));n&&(this.applyPriceScaleOptions(i,{mode:n.value}),console.log(`Price scale (${i}) mode set to: ${t}`),this.populatePriceScaleMenu(e,i,s))}));const a=this.handler.chart.priceScale(i).options();[{name:"Auto Scale",value:a.autoScale??!0,action:e=>{this.applyPriceScaleOptions(i,{autoScale:e}),console.log(`Price scale (${i}) autoScale set to: ${e}`)}},{name:"Invert Scale",value:a.invertScale??!1,action:e=>{this.applyPriceScaleOptions(i,{invertScale:e}),console.log(`Price scale (${i}) invertScale set to: ${e}`)}},{name:"Align Labels",value:a.alignLabels??!0,action:e=>{this.applyPriceScaleOptions(i,{alignLabels:e}),console.log(`Price scale (${i}) alignLabels set to: ${e}`)}},{name:"Border Visible",value:a.borderVisible??!0,action:e=>{this.applyPriceScaleOptions(i,{borderVisible:e}),console.log(`Price scale (${i}) borderVisible set to: ${e}`)}},{name:"Ticks Visible",value:a.ticksVisible??!1,action:e=>{this.applyPriceScaleOptions(i,{ticksVisible:e}),console.log(`Price scale (${i}) ticksVisible set to: ${e}`)}}].forEach((t=>{this.addMenuItem(`${t.name}: ${t.value?"On":"Off"}`,(()=>{const n=!t.value;t.action(n),this.populatePriceScaleMenu(e,i,s)}),!1,!1)}))}this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}applyPriceScaleOptions(e,t){const i=this.handler.chart.priceScale(e);i?(i.applyOptions(t),console.log(`Applied options to price scale "${e}":`,t)):console.warn(`Price scale with ID "${e}" not found.`)}getCurrentOptionValue(e){const t=e.split(".");let i=this.handler.chart.options();for(const s of t){if(!i||!(s in i))return console.warn(`Option path "${e}" is invalid.`),null;i=i[s]}return i}setBackgroundType(e,i){const s=this.handler.chart.options().layout?.background;let n;if(i===t.ColorType.Solid)n=m(s)?{type:t.ColorType.Solid,color:s.color}:{type:t.ColorType.Solid,color:"#000000"};else{if(i!==t.ColorType.VerticalGradient)return void console.error(`Unsupported ColorType: ${i}`);n=g(s)?{type:t.ColorType.VerticalGradient,topColor:s.topColor,bottomColor:s.bottomColor}:{type:t.ColorType.VerticalGradient,topColor:"rgba(255,0,0,.2)",bottomColor:"rgba(0,255,0,.2)"}}this.handler.chart.applyOptions({layout:{background:n}}),i===t.ColorType.Solid?this.populateSolidBackgroundMenuInline(e,n):i===t.ColorType.VerticalGradient&&this.populateGradientBackgroundMenuInline(e,n)}startFillAreaBetween(e,t){console.log("Fill Area Between started. Origin series set:",t.options().title),this.populateSeriesListMenu(e,!1,(e=>{e&&e!==t?(console.log("Destination series selected:",e.options().title),t.primitives.FillArea=new _(t,e,{...S}),t.attachPrimitive(t.primitives.FillArea,`Fill Area ⥵ ${e.options().title}`,!1,!0),console.log("Fill Area successfully added between selected series."),alert(`Fill Area added between ${t.options().title} and ${e.options().title}`)):alert("Invalid selection. Please choose a different series as the destination.")}))}getPredefinedOptions(e){return{"Series Type":["Line","Histogram","Area","Bar","Candlestick"],"Line Style":["Solid","Dotted","Dashed","Large Dashed","Sparse Dotted"],"Line Type":["Simple","WithSteps","Curved"],seriesType:["Line","Histogram","Area","Bar","Candlestick"],lineStyle:["Solid","Dotted","Dashed","Large Dashed","Sparse Dotted"],"Price Line Style":["Solid","Dotted","Dashed","Large Dashed","Sparse Dotted"],lineType:["Simple","WithSteps","Curved"],Shape:["Rectangle","Rounded","Ellipse","Arrow","3d","Polygon","Bar","Slanted"],"Candle Shape":["Rectangle","Rounded","Ellipse","Arrow","3d","Polygon","Bar","Slanted"]}[Fs(e)]||null}populateSeriesListMenu(e,t,i){this.div.innerHTML="";let s=[...Array.from(this.handler.seriesMap.entries()).map((([e,t])=>({label:e,value:t})))];if(this.handler.volumeSeries){s=[{label:"Volume",value:this.handler.volumeSeries},...s]}console.log(s),s.forEach((s=>{this.addMenuItem(s.label,(()=>{i(s.value),t?this.hideMenu():(this.div.innerHTML="",this.populateSeriesMenu(s.value,e),this.showMenu(e))}),!1,!0)})),this.addMenuItem("Cancel",(()=>{console.log("Operation canceled."),this.hideMenu()})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}customizeFillAreaOptions(e,t){var i;this.div.innerHTML="",null!==(i=t).options.originColor&&null!==i.options.destinationColor&&(this.addColorPickerMenuItem("Origin > Destination",t.options.originColor,"originColor",t),this.addColorPickerMenuItem("Origin < Destination",t.options.destinationColor,"destinationColor",t)),this.addMenuItem("⤝ Back to Main Menu",(()=>this.populateChartMenu(e)),!1),this.showMenu(e)}addResetViewOption(){const e=this.addMenuInput(this.div,{type:"hybrid",label:"∟ Reset",sublabel:"View",hybridConfig:{defaultAction:()=>{this.handler.chart.timeScale().resetTimeScale(),this.handler.chart.timeScale().fitContent()},options:[{name:"⥗ Time Scale",action:()=>this.handler.chart.timeScale().resetTimeScale()},{name:"⥘ Price Scale",action:()=>this.handler.chart.timeScale().fitContent}]}});this.div.appendChild(e)}_createTrendTrace(e,t){this.populateSeriesListMenu(e,!1,(e=>{let i;if("PitchFork"===t._type&&e&&t.p1&&t.p2){console.log("Series selected:",e.options().title);i=(t._options.length??1)*Math.abs(t.p2.logical-t.p1.logical)}e&&t.p1&&t.p2&&(console.log("Series selected:",e.options().title),e.primitives.TrendTrace=new Zs(this.handler,e,t.p1,t.p2,Ks,i),e.attachPrimitive(e.primitives.TrendTrace,`${t.p1?.logical} ⥵ ${t.p2?.logical}`,!1,!0),console.log("Trend Trace successfully created for selected series."),t.linkedObjects.push(e.primitives.TrendTrace))}))}_createVolumeProfile(e){const t=this.handler.series??this.handler._seriesList[0];if(t&&e.p1&&e.p2){console.log("Series selected:",t.options().title);const i=new Cn(this.handler,wn,e.p1,e.p2);t.attachPrimitive(i,"Volume Profile",!1,!0),console.log("Volume Profile successfully created for selected series."),e.linkedObjects.push(i)}}populateTrendTraceMenu(e,t){this.div.innerHTML="",this.addMenuItem("Color Options ▸",(()=>this.populateTrendColorMenu(e,t)),!1,!0),this.addMenuItem("General Options ▸",(()=>this.populateTrendOptionsMenu(e,t)),!1,!0),this.addMenuItem("Export/Import Data ▸",(()=>{this.dataMenu||(this.dataMenu=new xo({contextMenu:this,handler:this.handler})),this.dataMenu.openMenu(t,e,"Trend Trace")}),!1),this.addMenuItem("⤝ Main Menu",(()=>this.populateChartMenu(e)),!1),this.showMenu(e)}populateTrendColorMenu(e,t){this.div.innerHTML="";const i=t.getOptions(),s=[];t._sequence.data.every((e=>void 0!==e.open&&void 0!==e.high&&void 0!==e.low&&void 0!==e.close))?s.push({name:"Up Color",type:"color",valuePath:"upColor",defaultValue:i.upColor??"rgba(0,255,0,.25)"},{name:"Down Color",type:"color",valuePath:"downColor",defaultValue:i.downColor??"rgba(255,0,0,.25)"},{name:"Border Up Color",type:"color",valuePath:"borderUpColor",defaultValue:i.borderUpColor??"#1c9d1c"},{name:"Border Down Color",type:"color",valuePath:"borderDownColor",defaultValue:i.borderDownColor??"#d5160c"},{name:"Wick Up Color",type:"color",valuePath:"wickUpColor",defaultValue:i.wickUpColor??"#1c9d1c"},{name:"Wick Down Color",type:"color",valuePath:"wickDownColor",defaultValue:i.wickDownColor??"#d5160c"}):s.push({name:"Line Color",type:"color",valuePath:"lineColor",defaultValue:i.lineColor??"#ffffff"}),s.forEach((e=>{this.addColorPickerMenuItem(Fs(e.name),e.defaultValue,e.valuePath,t)})),this.addMenuItem("⤝ Trend Trace Menu",(()=>this.populateTrendTraceMenu(e,t)),!1),this.showMenu(e)}populateTrendOptionsMenu(e,t){this.div.innerHTML="";const i=t.getOptions(),s=[];t._sequence.data.every((e=>void 0!==e.open&&void 0!==e.high&&void 0!==e.low&&void 0!==e.close))&&s.push({name:"Bar Spacing",type:"number",valuePath:"barSpacing",defaultValue:i.barSpacing??.8,min:.1,max:10,step:.1},{name:"Radius",type:"number",valuePath:"radius",defaultValue:i.radius??.6,min:0,max:1,step:.1},{name:"Shape",type:"select",valuePath:"shape",defaultValue:i.shape??"Rounded",options:[{label:"Rectangle",value:n.Rectangle},{label:"Rounded",value:n.Rounded},{label:"Ellipse",value:n.Ellipse},{label:"Arrow",value:n.Arrow},{label:"Polygon",value:n.Polygon},{label:"Bar",value:n.Bar},{label:"Slanted",value:n.Slanted}]},{name:"Show Wicks",type:"boolean",valuePath:"wickVisible",defaultValue:i.wickVisible??!0},{name:"Show Borders",type:"boolean",valuePath:"borderVisible",defaultValue:i.borderVisible??!0},{name:"Chandelier Size",type:"number",valuePath:"chandelierSize",defaultValue:i.chandelierSize??1,min:1,max:100,step:1},{name:"Auto Aggregate",type:"boolean",valuePath:"autoscale",defaultValue:i.autoScale??!0}),s.push({name:"Line Style",type:"select",valuePath:"lineStyle",defaultValue:i.lineStyle??0,options:[{label:"Solid",value:0},{label:"Dotted",value:1},{label:"Dashed",value:2},{label:"Large Dashed",value:3},{label:"Sparse Dotted",value:4}]}),s.push({name:"Line Width",type:"number",valuePath:"lineWidth",defaultValue:i.lineWidth??1,min:.5,max:10,step:.5}),s.push({name:"Visible",type:"boolean",valuePath:"visible",defaultValue:i.visible??!0}),s.forEach((e=>{if("number"===e.type)this.addNumberInput(Fs(e.name),e.defaultValue,(i=>{const s=Gs(e.valuePath,i);t.applyOptions(s),console.log(`Updated ${e.name} to: ${i}`)}),e.min,e.max,e.step);else if("boolean"===e.type)this.addCheckbox(Fs(e.name),e.defaultValue,(i=>{const s=Gs(e.valuePath,i);t.applyOptions(s),console.log(`Updated ${e.name} to: ${i}`)}));else if("select"===e.type){const i=Array.isArray(e.options)&&"object"==typeof e.options[0]?e.options.map((e=>e.label)):e.options;this.addSelectInput(Fs(e.name),e.defaultValue,i,(i=>{const s=e.options.find((e=>e.label===i));if(s){const i=Gs(e.valuePath,s.value);t.applyOptions(i),console.log(`Updated ${e.name} to: ${s.value}`)}}))}})),this.addMenuItem("⤝ Trend Trace Menu",(()=>this.populateTrendTraceMenu(e,t)),!1),this.showMenu(e)}populateVolumeProfileMenu(e,t){this.div.innerHTML="";const i=t._options,s=[];s.push({name:"Visible",type:"boolean",valuePath:"visible",defaultValue:i.visible??!0},{name:"Sections",type:"number",valuePath:"sections",defaultValue:i.sections??20,min:1,step:1},{name:"Right Side",type:"boolean",valuePath:"rightSide",defaultValue:i.rightSide??!0},{name:"Width",type:"number",valuePath:"width",defaultValue:i.width??30,min:1,step:1},{name:"Line Style",type:"select",valuePath:"lineStyle",defaultValue:i.lineStyle??0,options:[{label:"Solid",value:0},{label:"Dotted",value:1},{label:"Dashed",value:2},{label:"Large Dashed",value:3},{label:"Sparse Dotted",value:4}]},{name:"Draw Grid",type:"boolean",valuePath:"drawGrid",defaultValue:i.drawGrid??!0},{name:"Grid Width",type:"number",valuePath:"gridWidth",defaultValue:i.gridWidth??void 0,min:1,step:1},{name:"Grid Line Style",type:"select",valuePath:"gridLineStyle",defaultValue:i.gridLineStyle??4,options:[{label:"Solid",value:0},{label:"Dotted",value:1},{label:"Dashed",value:2},{label:"Large Dashed",value:3},{label:"Sparse Dotted",value:4}]}),s.push({name:"Up Color",type:"color",valuePath:"upColor",defaultValue:i.upColor??wn.upColor},{name:"Down Color",type:"color",valuePath:"downColor",defaultValue:i.downColor??wn.downColor},{name:"Border Up Color",type:"color",valuePath:"borderUpColor",defaultValue:i.borderUpColor??wn.borderUpColor},{name:"Border Down Color",type:"color",valuePath:"borderDownColor",defaultValue:i.borderDownColor??wn.borderDownColor},{name:"Grid Color",type:"color",valuePath:"gridColor",defaultValue:i.gridColor??wn.gridColor}),s.forEach((e=>{if("number"===e.type)this.addNumberInput(Fs(e.name),e.defaultValue,(i=>{const s=Gs(e.valuePath,i);t.applyOptions(s),console.log(`Updated ${e.name} to: ${i}`)}),e.min,e.max,e.step);else if("boolean"===e.type)this.addCheckbox(Fs(e.name),e.defaultValue,(i=>{const s=Gs(e.valuePath,i);t.applyOptions(s),console.log(`Updated ${e.name} to: ${i}`)}));else if("select"===e.type){const i=Array.isArray(e.options)&&"object"==typeof e.options[0]?e.options.map((e=>e.label)):e.options;this.addSelectInput(Fs(e.name),e.defaultValue,i,(i=>{const s=e.options.find((e=>e.label===i));if(s){const i=Gs(e.valuePath,s.value);t.applyOptions(i),console.log(`Updated ${e.name} to: ${s.value}`)}}))}else"color"===e.type&&this.addColorPickerMenuItem(Fs(e.name),e.defaultValue,e.valuePath,t)})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}indicatorSeriesMap=new Map;populateIndicatorMenu(e,t){this.div.innerHTML="",vo.forEach((i=>{this.addMenuItem(`${i.name} (${i.shortName})`,(()=>{i.paramMap?this.configureIndicatorParams({series:e,indicator:i},t,1,!0):this.applyIndicator(e,i,{},1)}),!1)})),this.addMenuItem("⤝ Back",(()=>{this.hideMenu()}),!1),this.showMenu(t)}configureIndicatorParams(e,t,i,s=!1){let n;this.div.innerHTML="";const o="sourceSeries"in e?e:e.series,r=e.indicator,a="paramMap"in e?e.paramMap:{},l={};let c=!1,h=0;Object.entries(r.paramMap).forEach((([e,t])=>{if("numberArray"===t.type||"selectArray"===t.type||"booleanArray"===t.type||"stringArray"===t.type){c=!0;const e=Array.isArray(t.defaultValue)?t.defaultValue:[t.defaultValue];h=Math.max(h,e.length)}})),c&&s&&(void 0!==i?(n=i,e.figureCount=i):n="figureCount"in e&&void 0!==e.figureCount?e.figureCount:h||1,this.addNumberInput("Number of Figures",n,(i=>{e.figureCount=i,this.configureIndicatorParams(e,t,i,!0)}),1,10,1)),Object.entries(r.paramMap).forEach((([t,s])=>{const n=t,o=void 0!==a[t]?a[t]:s.defaultValue;if("numberArray"===s.type||"selectArray"===s.type||"booleanArray"===s.type||"stringArray"===s.type){const r=i??e.figureCount,a=s.type.replace("Array","");l[t]=[];for(let e=0;e{l[t]||(l[t]=[]),l[t][e]=i}),s.min,s.max,s.step):"boolean"===a?this.addCheckbox(`${n} ${e+1}`,Boolean(i),(i=>{l[t]||(l[t]=[]),l[t][e]=i})):"select"===a?this.addSelectInput(`${n} ${e+1}`,String(i),s.options||[],(i=>{l[t]||(l[t]=[]),l[t][e]=i})):"string"===a&&this.addMenuInput(this.div,{type:"string",label:`${n} ${e+1}`,value:i,onChange:i=>{l[t]||(l[t]=[]),l[t][e]=i}}),l[t]||(l[t]=[]),l[t][e]=i}}else"number"===s.type?(this.addNumberInput(n,o,(e=>{l[t]=e}),s.min,s.max,s.step),l[t]=o):"boolean"===s.type?(this.addCheckbox(n,Boolean(o),(e=>{l[t]=e})),l[t]=o):"select"===s.type?(this.addSelectInput(n,String(o),s.options||[],(e=>{l[t]=e})),l[t]=o):(this.addMenuInput(this.div,{type:"string",label:n,value:o,onChange:e=>{l[t]=e}}),l[t]=o)})),this.addMenuItem("Apply",(()=>{this.hideMenu(),Object.entries(l).forEach((([e,t])=>{r.paramMap[e]&&(r.paramMap[e].defaultValue=t)})),"recalculate"in e?(e.recalculate(l),e.figures.forEach((e=>{const t=this.handler.legend._lines.find((t=>t.series===e));t&&(this.handler.seriesMap.set(e.options().title,o),t.name=e.options().title)}))):this.applyIndicator(o,r,l,n)}),!1),this.addMenuItem("Cancel",(()=>{this.hideMenu()}),!1),this.showMenu(t)}applyIndicator(e,t,i,s){const n=[...e.data()];if(!n||0===n.length)return void console.warn("No data found on this series.");let o;o=n.every(y)?n:n.map(Vs);const r=this.handler.volumeSeries.data(),a=t.calc([...o],i,r??void 0),l=new Map,c=function(e){const t={"#ff0000":["#ff0000","#f20000","#e60000","#d90000","#cc0000","#bf0000","#b30000","#a60000","#990000","#8c0000"],"#ff8700":["#ff8700","#f28000","#e67a00","#d97300","#cc6c00","#bf6500","#b35f00","#a65800","#995100","#8c4a00"],"#ffd300":["#ffd300","#fcca00","#e6c000","#d9b600","#ccb000","#bfaa00","#b3a000","#a69a00","#999000","#8c8600"],"#a1ff0a":["#a1ff0a","#97f207","#8ded04","#83e701","#79db00","#6fd200","#65c900","#5bc000","#51b700","#47ae00"],"#117a03":["#117a03","#107203","#0e6c03","#0c6603","#0a6003","#085a03","#065403","#044e03","#024803","#004203"],"#580aff":["#580aff","#5109f2","#4a08e6","#4307da","#3c06ce","#3505c2","#2e04b6","#2703aa","#2002a0","#190196"],"#be0aff":["#be0aff","#b308f2","#aa07e6","#a005da","#9704ce","#8e03c2","#8502b6","#7c01aa","#7300a0","#6a0096"]},i=Object.keys(t),s=t[i[Math.floor(Math.random()*i.length)]];if(e===s.length)return s;const n=[];for(let t=0;t{const r=c[o];let h=null;if("histogram"===n.type){const i=this.handler.createHistogramSeries(n.title,{color:r,base:0,title:n.title,...a.length>1?{group:t.name}:{}});i.series&&(i.series.setData(n.data),h=i.series,e.getPane().paneIndex()!==h.getPane().paneIndex()&&h.moveToPane(e.getPane().paneIndex()))}else{const i=this.handler.createLineSeries(n.title,{color:r,lineWidth:2,title:n.title,...a.length>1?{group:t.name}:{}});i.series&&(i.series.setData(n.data),h=i.series,e.getPane().paneIndex()!==h.getPane().paneIndex()&&h.moveToPane(e.getPane().paneIndex()))}if(h){const o=function(e,t,i,s,n,o,r){const a=Object.assign(e,{sourceSeries:t,indicator:i,figures:s,paramMap:o,figureCount:n,recalculate:function(e){r(this,e)}});return"function"==typeof t.subscribeDataChanged&&t.subscribeDataChanged((()=>{t.data()[t.data().length-1].time>e.data()[e.data().length-1].time&&r(a)})),a}(h,e,t,l,s,i,Os);if(l.set(n.key,o),n.pane&&o.getPane()===e.getPane()){const e=o.getPane().paneIndex();o.moveToPane(e+n.pane)}}})),this.indicatorSeriesMap.set(t.name,l)}populateForkLineMainMenu(e,i){if(this.div.innerHTML="","PitchFork"!==i._type)return;const s=i._options;s.forkLines||(s.forkLines=[]);const n=s.forkLines;n.forEach(((t,s)=>{this.addMenuItem(`Fork Line ${s+1}`,(()=>{this.populateForkLineOptions(e,i,s)}),!1,!0)})),this.addMenuItem("Add Fork Line",(()=>{const s={value:.5,width:1,style:t.LineStyle.Solid,color:"#ffffff",fillColor:void 0};n.push(s),this.saveDrawings&&this.saveDrawings(),this.populateForkLineMainMenu(e,i)}),!1,!0),this.addMenuItem("⤝ Back",(()=>{this.populateDrawingMenu(e,i)}),!1,!1),this.showMenu(e)}populateForkLineOptions(e,i,s){this.div.innerHTML="";const n=i._options;if(!n.forkLines||!n.forkLines[s])return;const o=n.forkLines[s];this.addNumberInput("Value",o.value,(e=>{o.value=e,this.saveDrawings&&this.saveDrawings()}),0,10,.1),this.addNumberInput("Width",o.width,(e=>{o.width=e,this.saveDrawings&&this.saveDrawings()}),1,10,1);const r=[{name:"Solid",var:t.LineStyle.Solid},{name:"Dotted",var:t.LineStyle.Dotted},{name:"Dashed",var:t.LineStyle.Dashed},{name:"Large Dashed",var:t.LineStyle.LargeDashed},{name:"Sparse Dotted",var:t.LineStyle.SparseDotted}];this.addSelectInput("Style",r.find((e=>e.var===o.style))?.name||r[0].name,r.map((e=>e.name)),(e=>{const t=r.find((t=>t.name===e));t&&(o.style=t.var,this.saveDrawings&&this.saveDrawings())})),this.addForkLineColorPickerMenuItem("Color",o.color,o,"color"),this.addForkLineColorPickerMenuItem("Fill Color",o.fillColor||"",o,"fillColor"),this.addMenuItem("Remove Fork Line",(()=>{n.forkLines.splice(s,1),this.saveDrawings&&this.saveDrawings(),this.populateForkLineMainMenu(e,i)}),!1,!0),this.addMenuItem("⤝ Back",(()=>{this.populateForkLineMainMenu(e,i)}),!1,!1),this.showMenu(e)}addForkLineColorPickerMenuItem(e,t,i,s){const n=document.createElement("span");n.classList.add("context-menu-item"),n.innerText=e,this.div.appendChild(n);const o=e=>{i[s]=e,console.log(`Updated fork line ${s} to ${e}`),this.saveDrawings&&this.saveDrawings()};return n.addEventListener("click",(e=>{e.stopPropagation(),this.colorPicker||(this.colorPicker=new xn(t??"#000000",o)),this.colorPicker.openMenu(e,225,o)})),n}}function So(e){return function(e){return Math.max(1,Math.floor(e))}(e)/e}class ko{_options;constructor(e){this._options=e}staticAggregate(e,t){const i=this._options?.chandelierSize??1,s=[];for(let n=0;n=s[0].open;r.close>=r.open!==e&&(a=!0)}else if("trigger"===n){(this._options?.dynamicTrigger&&this._options?.dynamicTrigger().newBar||r.newBar)&&(a=!0)}else if("volume_trend"===n){const e=s[0].volume,t=s[s.length-1].volume,i=r.volume;if(e&&t&&i){const s=t>=e;(s&&it)&&(a=!0)}}if(a){const e=o-s.length,n=o-1,a=this._chandelier(s,e,n,t,!1);i.push(a),s=[r]}else s.push(r)}if(s.length>0){const n=e.length-s.length,o=e.length-1,r=this._chandelier(s,n,o,t,!1);i.push(r)}return this.applyVolumeOpacity(i),i}applyVolumeOpacity(e){if(!this._options?.enableVolumeOpacity)return;if(!e.every((e=>void 0!==e.volume&&"number"==typeof e.volume)))return void console.warn("Volume opacity enabled but not all aggregated bars have volume data. Skipping volume-based opacity adjustment.");const t=this._options?.upColor||"rgba(0,255,0,0.333)",i=this._options?.downColor||"rgba(255,0,0,0.333)",s=p(t),n=p(i);if(0===s||0===n)return void console.warn("Volume opacity enabled but upColor/downColor alpha is zero. Skipping volume-based opacity adjustment.");const o=(this._options.volumeOpacityPeriod??20)*(this._options?.chandelierSize??1),r=this._options?.maxOpacity??.3;e.forEach(((e,s,n)=>{if(null==e.volume)return;const a=Math.max(0,s-o+1),c=n.slice(a,s+1);let h=1;if("/ max"!==this._options?.volumeOpacityMode&&this._options?.volumeOpacityMode)if("> previous"===this._options?.volumeOpacityMode)if(0!==s&&n[s-1].volume&&0!==n[s-1].volume){const t=n[s-1].volume??0;h=e.volume>t?r:0}else h=r;else if("> average"===this._options?.volumeOpacityMode){const t=c.reduce(((e,t)=>e+(void 0!==t.volume?t.volume:0)),0),i=c.length>0?t/c.length:0;h=i>0&&e.volume>i?r:0}else h=0;else{const t=c.reduce(((e,t)=>void 0!==t.volume&&t.volume>e?t.volume:e),0);h=t>0?e.volume/t*r:1}e.isUp?e.color=l(t,h):e.color=l(i,h)}))}_chandelier(e,t,i,s,o=!1){if(0===e.length)throw new Error("Bucket cannot be empty in _chandelier method.");const r=e[0].originalData?.open??e[0].open??0,a=e[e.length-1].originalData?.close??e[e.length-1].close??0,c=s(r)??0,h=s(a)??0,p=e.map((e=>e.originalData?.high??e.high)),d=e.map((e=>e.originalData?.low??e.low)),m=p.length>0?Math.max(...p):0,g=d.length>0?Math.min(...d):0,f=s(m)??0,y=s(g)??0,b=e[0].x,v=a>r,x=v?this._options?.upColor||"rgba(0,255,0,0.333)":this._options?.downColor||"rgba(255,0,0,0.333)",_=v?this._options?.borderUpColor||l(x,1):this._options?.borderDownColor||l(x,1),w=v?this._options?.wickUpColor||_:this._options?.wickDownColor||_,C=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options?.lineStyle??1),S=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options?.lineWidth??1),k=e.reduce(((e,t)=>(t.shape?u(t.shape):t.originalData?.shape?u(t.originalData.shape):void 0)??e),this._options?.shape??n.Rectangle);return{open:c,high:f,low:y,close:h,volume:e.reduce(((e,t)=>e+(t.originalData?.volume??t.volume??0)),0),x:b,isUp:v,startIndex:t,endIndex:i,isInProgress:o,color:x,borderColor:_,wickColor:w,shape:k||n.Rectangle,lineStyle:C,lineWidth:S}}}class Eo{_data=null;_options=null;_aggregator=null;draw(e,t){e.useBitmapCoordinateSpace((e=>this._drawImpl(e,t)))}update(e,t){this._data=e,this._options=t,this._aggregator=new ko(t)}_drawImpl(e,t){if(!this._data||0===this._data.bars.length||!this._data.visibleRange||!this._options)return;const i=this._data.bars.map(((e,t)=>({open:e.originalData?.open??0,high:e.originalData?.high??0,low:e.originalData?.low??0,close:e.originalData?.close??0,volume:e.originalData?.volume??0,x:e.x,shape:e.originalData?.shape??this._options?.shape??"Rectangle",lineStyle:e.originalData?.lineStyle??this._options?.lineStyle??1,lineWidth:e.originalData?.lineWidth??this._options?.lineWidth??1,isUp:(e.originalData?.close??0)>=(e.originalData?.open??0),color:this._options?.color??"rgba(0,0,0,0)",borderColor:this._options?.borderColor??"rgba(0,0,0,0)",wickColor:this._options?.wickColor??"rgba(0,0,0,0)",startIndex:t,endIndex:t})));let s;s="use Chandelier Size"===this._options.dynamicCandles?this._aggregator?.staticAggregate(i,t)??[]:this._aggregator?.dynamicAggregate(i,t)??[];const n=this._options.radius,{horizontalPixelRatio:o,verticalPixelRatio:r}=e,a=this._data.barSpacing*o;this._drawCandles(e,s,this._data.visibleRange,n,a,o,r),this._drawWicks(e,s,this._data.visibleRange)}_drawWicks(e,t,i){if(null===this._data||null===this._options)return;if("3d"===this._options.shape)return;const{context:s,horizontalPixelRatio:n,verticalPixelRatio:o}=e,r=this._data.barSpacing*n,a=So(n),l=this._options?.barSpacing??.8;s.save();for(const e of t){if(e.startIndexi.to)continue;const t=e.low*o,c=e.high*o,h=Math.min(e.open,e.close)*o,p=Math.max(e.open,e.close)*o,d=e.endIndex-e.startIndex,u=1!==this._options?.chandelierSize?r*Math.max(1,d+1)-(1-l)*r:r*l,m=e.x*n-r*l/2+u/2;let g=c,f=h,y=p,b=t;"Polygon"===this._options.shape&&(f=(c+h)/2,y=(t+p)/2),s.fillStyle=e.color,s.strokeStyle=e.wickColor??e.color;const v=(e,t,i,n,o)=>{s.roundRect?s.roundRect(e,t,i,n,o):s.rect(e,t,i,n)},x=f-g;x>0&&(s.beginPath(),v(m-Math.floor(a/2),g,a,x,a/2),s.fill(),s.stroke());const _=b-y;_>0&&(s.beginPath(),v(m-Math.floor(a/2),y,a,_,a/2),s.fill(),s.stroke())}}_drawCandles(e,t,i,s,n,o,r){const{context:a}=e,l=this._options?.barSpacing??.8;a.save();for(const e of t){const t=e.endIndex-e.startIndex,c=1!==this._options?.chandelierSize?n*Math.max(1,t+1)-(1-l)*n:n*l,h=e.x*o,p=n*l;if(e.startIndexi.to)continue;const d=Math.min(e.open,e.close)*r,u=Math.max(e.open,e.close)*r,m=d-u,g=(d+u)/2,f=h-p/2,y=f+c,b=f+c/2;switch(a.fillStyle=e.color??this._options?.color??"rgba(255,255,255,1)",a.strokeStyle=e.borderColor??this._options?.borderColor??e.color??"rgba(255,255,255,1)",U(a,e.lineStyle),a.lineWidth=e.lineWidth??1,e.shape){case"Rectangle":default:Us(a,f,y,g,m);break;case"Rounded":zs(a,f,y,g,m,s);break;case"Ellipse":Hs(a,f,y,0,g,m);break;case"Arrow":Xs(a,f,y,b,g,m,e.high*r,e.low*r,e.isUp);break;case"3d":Ws(a,h,e.high*r,e.low*r,e.open*r,e.close*r,p,c,e.color??this._options?.color??"rgba(255,255,255,1)",e.borderColor??this._options?.borderColor??"rgba(255,255,255,1)",e.isUp,l);break;case"Polygon":qs(a,f,y,g,m,e.high*r,e.low*r,e.isUp);break;case"Bar":Js(a,f,y,e.high*r,e.low*r,e.open*r,e.close*r);break;case"Slanted":Ys(a,f,y,g,m,e.isUp)}}a.restore()}}const Mo={...t.customSeriesDefaultOptions,upColor:"#008000",downColor:"#8C0000",wickVisible:!0,borderVisible:!0,borderColor:"#737375",borderUpColor:"#008000",borderDownColor:"#8C0000",wickColor:"#737375",wickUpColor:"#008000",wickDownColor:"#8C0000",radius:.6,shape:"Rounded",chandelierSize:1,barSpacing:.8,lineStyle:0,lineWidth:2,enableVolumeOpacity:!0,volumeOpacityMode:"> previous",volumeOpacityPeriod:21,maxOpacity:.3,dynamicCandles:"use Chandelier Size",dynamicTrigger:()=>({newBar:!0})};class Po{_renderer;constructor(){this._renderer=new Eo}priceValueBuilder(e){return[e.high,e.low,e.close]}renderer(){return this._renderer}isWhitespace(e){return void 0===e.close}update(e,t){this._renderer.update(e,t)}defaultOptions(){return Mo}}class To{defaults;constructor(){this.defaults=new Map}set(e,t){let i;if("string"==typeof t)try{i=JSON.parse(t)}catch(s){console.error(`Error parsing JSON string for key "${e}":`,s),i=t}else i=t;this.defaults.set(e,i),console.log(`Default options for key "${e}" set successfully.`),console.log(i)}get(e){const t=e.toLowerCase();for(const[e,i]of this.defaults)if(e.toLowerCase()===t)return i;return null}getAll(){return this.defaults}}class Io{scripts;constructor(){this.scripts=new Map}set(e,t){let i;if("string"==typeof t)try{i=JSON.parse(t)}catch(s){console.error(`Error parsing JSON string for key "${e}":`,s),i=t}else i=t;this.scripts.set(e,i),console.log(`Default options for key "${e}" set successfully.`),console.log(i)}get(e){return this.scripts.has(e)?this.scripts.get(e):null}getAll(){return this.scripts}getLast(){if(this.scripts.has("cache"))return this.scripts.get("cache");if(0===this.scripts.size)return null;const e=Array.from(this.scripts.values());return e[e.length-1]}}class Ao{_data=null;_options=null;draw(e,t){e.useBitmapCoordinateSpace((e=>{this._drawImpl(e,t)}))}update(e,t){this._data=e,this._options=t}_drawImpl(e,t){const i=this._data?.barSpacing??.8;if(null===this._data||0===this._data.bars.length||null===this._data.visibleRange||null===this._options)return;const{context:s,horizontalPixelRatio:n,verticalPixelRatio:o}=e,{visibleRange:r}=this._data,{color:a,lineWidth:c,lineStyle:h,join:p,shape:d,shapeSize:u,fontSize:m}=this._options,g=this._data.bars.map((e=>({x:e.x*n,y:t(e.originalData.value)*o})));s.save(),s.lineJoin="round",s.strokeStyle=a,s.lineWidth=c*o,U(s,h),s.beginPath();const f=r.from,y=r.to-1;s.moveTo(g[f].x,g[f].y);for(let e=f+1;e<=y;e++)p&&s.lineTo(g[e].x,g[e].y);s.stroke(),s.restore();const b=(u??.8)*i,v={shape:d,shapeSize:b??1,fillColor:l(a,.5),borderColor:a,lineWidth:c,textAlign:"center",textBaseline:"middle",fontSize:(m??1)*i},x=this._data.bars;for(let e=f;e<=y;e++){const r=x[e],a=r.x*n,l=t(r.originalData.value)*o,c=r.originalData.shapeOptions??{},h=c.shapeSize??null,p=null!==h?h*i:b,d={...v,...c,shapeSize:p};this._drawShape(s,a,l,d)}}_drawShape(e,t,i,s){e.save();const{shape:n,shapeSize:o,fillColor:r,borderColor:a,lineWidth:l=1,textAlign:c="center",textBaseline:h="middle",fontSize:p=1}=s;switch(e.fillStyle=r??this._options?.color,e.strokeStyle=a??r??this._options?.color,e.lineWidth=l,e.textAlign=c,e.textBaseline=h,e.font=`${p}px sans-serif`,n){case"circles":e.beginPath(),e.arc(t,i,o/2,0,2*Math.PI),e.fill(),a&&e.stroke();break;case"cross":{const s=o/2,n=o/3;e.beginPath(),e.moveTo(t-n/2,i-s),e.lineTo(t+n/2,i-s),e.lineTo(t+n/2,i-n/2),e.lineTo(t+s,i-n/2),e.lineTo(t+s,i+n/2),e.lineTo(t+n/2,i+n/2),e.lineTo(t+n/2,i+s),e.lineTo(t-n/2,i+s),e.lineTo(t-n/2,i+n/2),e.lineTo(t-s,i+n/2),e.lineTo(t-s,i-n/2),e.lineTo(t-n/2,i-n/2),e.closePath(),e.fill(),a&&e.stroke();break}case"triangleUp":{const s=o/2;e.beginPath(),e.moveTo(t,i-s),e.lineTo(t-s,i+s),e.lineTo(t+s,i+s),e.closePath(),e.fill(),a&&e.stroke();break}case"triangleDown":{const s=o/2;e.beginPath(),e.moveTo(t,i+s),e.lineTo(t-s,i-s),e.lineTo(t+s,i-s),e.closePath(),e.fill(),a&&e.stroke();break}case"arrowUp":{const s=.4*o,n=o/3/2,r=i-o/2,l=r+s,c=i+o/2;e.beginPath(),e.moveTo(t,r),e.lineTo(t+s,l),e.lineTo(t+n,l),e.lineTo(t+n,c),e.lineTo(t-n,c),e.lineTo(t-n,l),e.lineTo(t-s,l),e.closePath(),e.fill(),a&&e.stroke();break}case"arrowDown":{const s=.4*o,n=o/3/2,r=i+o/2,l=r-s,c=i-o/2;e.beginPath(),e.moveTo(t,r),e.lineTo(t+s,l),e.lineTo(t+n,l),e.lineTo(t+n,c),e.lineTo(t-n,c),e.lineTo(t-n,l),e.lineTo(t-s,l),e.closePath(),e.fill(),a&&e.stroke();break}default:e.fillText(n,t,i,this._data?.barSpacing??.8)}e.restore()}}class Do{_renderer;constructor(){this._renderer=new Ao}priceValueBuilder(e){return[e.value]}isWhitespace(e){return void 0===e.value}renderer(){return this._renderer}update(e,t){this._renderer.update(e,t)}defaultOptions(){return Ps}}M();class Lo{id;commandFunctions=[];static handlers=new Map;seriesOriginMap=new WeakMap;wrapper;div;chart;scale;precision=2;series;volumeSeries;volumeUpColor=null;volumeDownColor=null;legend;_topBar;toolBox;spinner;width=null;height=null;_seriesList=[];seriesMap=new Map;seriesMetadata;colorPicker=null;ContextMenu;currentMouseEventParams=null;defaultsManager;scriptsManager;constructor(e,t,i,s,n){this.reSize=this.reSize.bind(this),this.id=e,this.scale={width:t,height:i},this.defaultsManager=new To,this.scriptsManager=new Io,Lo.handlers.set(e,this),this.wrapper=document.createElement("div"),this.wrapper.classList.add("handler"),this.wrapper.style.float=s,this.div=document.createElement("div"),this.div.style.position="relative",this.wrapper.appendChild(this.div),window.containerDiv.append(this.wrapper),this.chart=this._createChart(),this.ContextMenu=new Co(this,Lo.handlers,(()=>window.MouseEventParams??null)),this.legend=new D(this),this.series=this.createCandlestickSeries(),this.volumeSeries=this.createVolumeSeries(),this.chart.subscribeCrosshairMove((e=>{this.currentMouseEventParams=e,window.MouseEventParams=e})),document.addEventListener("keydown",(e=>{for(let t=0;t{window.handlerInFocus=this.id,window.MouseEventParams=this.currentMouseEventParams||null})),this.seriesMetadata=new WeakMap,this.createTopBar(),window.monaco=!1,this.chart.subscribeCrosshairMove((e=>{this.currentMouseEventParams=e})),this.reSize(),n&&window.addEventListener("resize",(()=>this.reSize()))}reSize(){let e=0!==this.scale.height&&this._topBar?._div.offsetHeight||0;this.chart.resize(window.innerWidth*this.scale.width,window.innerHeight*this.scale.height-e),this.wrapper.style.width=100*this.scale.width+"%",this.wrapper.style.height=100*this.scale.height+"%",0===this.scale.height||0===this.scale.width?this.toolBox&&(this.toolBox.div.style.display="none"):this.toolBox&&(this.toolBox.div.style.display="flex")}primitives=new Map;_createChart(){return t.createChart(this.div,{width:window.innerWidth*this.scale.width,height:window.innerHeight*this.scale.height,layout:{textColor:window.pane.color,background:{color:"#000000",type:t.ColorType.Solid},fontSize:12},rightPriceScale:{scaleMargins:{top:.3,bottom:.25}},timeScale:{timeVisible:!0,secondsVisible:!1},crosshair:{mode:t.CrosshairMode.Normal,vertLine:{labelBackgroundColor:"rgb(46, 46, 46)"},horzLine:{labelBackgroundColor:"rgb(55, 55, 55)"}},grid:{vertLines:{color:"rgba(29, 30, 38, 5)"},horzLines:{color:"rgba(29, 30, 58, 5)"}},handleScroll:{vertTouchDrag:!0}})}mergeSeriesOptions(e,t){return{...Is(e),...this.defaultsManager.defaults.get(e.toLowerCase())||{},...t}}createCandlestickSeries(){const e="Candlestick",i={...Is(e),...this.defaultsManager.defaults.get(e.toLowerCase())||{}},s=this.chart.addSeries(t.CandlestickSeries,i);s.priceScale().applyOptions({scaleMargins:{top:.2,bottom:.2}});const n=Ts(s,this.legend);n.applyOptions({title:"OHLC"}),this._seriesList.push(n),this.seriesMap.set("OHLC",n);const o={name:"OHLC",series:n,colors:[i.upColor,i.downColor],legendSymbol:["⋰","⋱"],seriesType:"Candlestick",group:void 0};return this.legend.addLegendItem(o),n}createVolumeSeries(e){const i=this.chart.addSeries(t.HistogramSeries,{color:"#26a69a",priceFormat:{type:"volume"},priceScaleId:"volume_scale"});i.priceScale().applyOptions({scaleMargins:{top:0,bottom:.2}}),void 0!==e&&i.moveToPane(e);const s=Ts(i,this.legend);return s.applyOptions({title:"Volume"}),s}createLineSeries(e,i,s){const n=this.mergeSeriesOptions("Line",i??{}),o=(()=>{switch(n.lineStyle){case 0:return"―";case 1:return":··";case 2:return"--";case 3:return"- -";case 4:return"· ·";default:return"~"}})(),{group:r,legendSymbol:a=o,...l}=n,c=Ts(this.chart.addSeries(t.LineSeries,l),this.legend);c.applyOptions({title:e}),this._seriesList.push(c),this.seriesMap.set(e,c);const h=c.options().color||"rgba(255,0,0,1)",p={name:e,series:c,colors:[h.startsWith("rgba")?h.replace(/[^,]+(?=\))/,"1"):h],legendSymbol:Array.isArray(a)?a:[a],seriesType:"Line",group:r};return this.legend.addLegendItem(p),void 0!==s&&c.moveToPane(s),{name:e,series:c}}createHistogramSeries(e,i,s){const n=this.mergeSeriesOptions("Histogram",i??{}),{group:o,legendSymbol:r="▨",...a}=n,l=Ts(this.chart.addSeries(t.HistogramSeries,a),this.legend);l.applyOptions({title:e}),this._seriesList.push(l),this.seriesMap.set(e,l);const c=l.options().color||"rgba(255,0,0,1)",h={name:e,series:l,colors:[c.startsWith("rgba")?c.replace(/[^,]+(?=\))/,"1"):c],legendSymbol:Array.isArray(r)?r:[r],seriesType:"Histogram",group:o};return this.legend.addLegendItem(h),void 0!==s&&l.moveToPane(s),{name:e,series:l}}createAreaSeries(e,i,s){const n=this.mergeSeriesOptions("Area",i??{}),{group:o,legendSymbol:r="▨",...a}=n,l=Ts(this.chart.addSeries(t.AreaSeries,a),this.legend);this._seriesList.push(l),this.seriesMap.set(e,l);const c=l.options().lineColor||"rgba(255,0,0,1)",h={name:e,series:l,colors:[c.startsWith("rgba")?c.replace(/[^,]+(?=\))/,"1"):c],legendSymbol:Array.isArray(r)?r:[r],seriesType:"Area",group:o};return this.legend.addLegendItem(h),void 0!==s&&l.moveToPane(s),{name:e,series:l}}createBarSeries(e,i,s){const n=this.mergeSeriesOptions("Bar",i??{}),{group:o,legendSymbol:r=["┌","└"],...a}=n,l=Ts(this.chart.addSeries(t.BarSeries,a),this.legend);l.applyOptions({title:e}),this._seriesList.push(l),this.seriesMap.set(e,l);const c=l.options().upColor||"rgba(0,255,0,1)",h=l.options().downColor||"rgba(255,0,0,1)",p={name:e,series:l,colors:[c,h],legendSymbol:Array.isArray(r)?r:[r],seriesType:"Bar",group:o};return this.legend.addLegendItem(p),void 0!==s&&l.moveToPane(s),{name:e,series:l}}createCustomOHLCSeries(e,t,i){const s={...Mo,...this.defaultsManager.defaults.get("ohlc")||{},...t,seriesType:"Ohlc"},{group:n,legendSymbol:o=["⑃","⑂"],seriesType:r,chandelierSize:a,...l}=s,c=new Po,h=Ts(this.chart.addCustomSeries(c,{...l,chandelierSize:a,title:e}),this.legend);this._seriesList.push(h),this.seriesMap.set(e,h);const p={name:e,series:h,colors:[s.borderUpColor||s.upColor,s.borderDownColor||s.downColor],legendSymbol:Array.isArray(o)?o:o?[o]:[],seriesType:"Ohlc",group:n};return this.legend.addLegendItem(p),void 0!==i&&h.moveToPane(i),{name:e,series:h}}createSymbolSeries(e,t,i){const s={...Ps,...this.defaultsManager.defaults.get("symbol")||{},...t,seriesType:"Symbol"},n=(()=>{switch(s.shape){case"circle":case"circles":return"●";case"cross":return"✚";case"triangleUp":return"▲";case"triangleDown":return"▼";case"arrowUp":return"↑";case"arrowDown":return"↓";default:return s.shape}})(),{group:o,legendSymbol:r=n,...a}=s,l=new Do,c=Ts(this.chart.addCustomSeries(l,{...a,title:e}),this.legend);this._seriesList.push(c),this.seriesMap.set(e,c);const h={name:e,series:c,colors:[c.options().color||"rgba(255,0,0,1)"],legendSymbol:Array.isArray(r)?r:r?[r]:[],seriesType:"Symbol",group:o};return this.legend.addLegendItem(h),void 0!==i&&c.moveToPane(i),{name:e,series:c}}createFillArea(e,t,i,s,n){const o=this._seriesList.find((e=>e.options()?.title===t)),r=this._seriesList.find((e=>e.options()?.title===i));if(!o)return void console.warn(`Origin series with title "${t}" not found.`);if(!r)return void console.warn(`Destination series with title "${i}" not found.`);const a=Ns(o,this.legend),l=new _(o,r,{originColor:s||null,destinationColor:n||null,lineWidth:null});return a.attachPrimitive(l,e),l}attachPrimitive(e,t,i,s){let n=i;try{if(s&&!i&&(n=this.seriesMap.get(s)),!n)return void console.warn(`Series with the name "${s}" not found.`);const o=Ns(n,this.legend);let r;if("Tooltip"!==t)return void console.warn(`Unknown primitive type: ${t}`);r=new bn({lineColor:e}),o.attachPrimitive(r,"Tooltip"),this.primitives.set(n,r)}catch(e){console.error(`Failed to attach ${t}:`,e)}}removeSeries(e){let t;if(x(e)){for(const[i,s]of this.seriesMap.entries())if(s===e){t=i;break}}else t=e,e=this.seriesMap.get(e);if(e&&t){e.primitives&&e.primitives.length>0&&e.primitives.forEach((i=>{e.detachPrimitive(i),console.log(`✅ Detached primitive from series "${t}".`)})),this._seriesList=this._seriesList.filter((t=>t!==e)),this.seriesMap.delete(t),console.log(`✅ Series "${t}" removed from internal maps.`);try{const i=this.legend._items.find((t=>t.series===e));i?(i.primitives&&i.primitives.length>0&&i.primitives.forEach((e=>{this.legend.removeLegendPrimitive(e),console.log(`✅ Removed primitive from legend for series "${t}".`)})),this.legend.deleteLegendEntry(i.name,i.group??void 0),console.log(`✅ Removed series "${t}" from legend.`)):console.warn(`⚠️ Legend item for series "${t}" not found.`)}catch(e){console.error(`⚠️ Error removing legend entry for "${t}":`,e)}this.chart.removeSeries(e),console.log(`✅ Series "${t}" successfully removed.`)}else console.warn(`❌ Series "${e}" does not exist and cannot be removed.`)}createToolBox(){this.toolBox=new ue(this,this.id,this.chart,this.series,this.commandFunctions),this.div.appendChild(this.toolBox.div)}createTopBar(){return this._topBar=new cn(this),this.wrapper.prepend(this._topBar._div),this._topBar}extractSeriesData(e){const t=e.data();return Array.isArray(t)?t.map((e=>[e.time,e.value||e.close||0])):(console.warn("Failed to extract data: series data is not in array format."),[])}static syncCharts(e,t,i=!1){function s(e,t){t?(e.chart.setCrosshairPosition(t.value||t.close,t.time,e.series),e.legend.legendHandler(t,!0)):e.chart.clearCrosshairPosition()}function n(e,t){return t.time&&t.seriesData.get(e)||null}const o=e.chart.timeScale(),r=t.chart.timeScale(),a=e=>{e&&o.setVisibleLogicalRange(e)},l=e=>{e&&r.setVisibleLogicalRange(e)},c=i=>{s(t,n(e.series,i))},h=i=>{s(e,n(t.series,i))};let p=t;function d(e,t,s,n,o,r){e.wrapper.addEventListener("mouseover",(()=>{p!==e&&(p=e,t.chart.unsubscribeCrosshairMove(s),e.chart.subscribeCrosshairMove(n),i||(t.chart.timeScale().unsubscribeVisibleLogicalRangeChange(o),e.chart.timeScale().subscribeVisibleLogicalRangeChange(r)))}))}d(t,e,c,h,l,a),d(e,t,h,c,a,l),t.chart.subscribeCrosshairMove(h);const u=r.getVisibleLogicalRange();u&&o.setVisibleLogicalRange(u),i||t.chart.timeScale().subscribeVisibleLogicalRangeChange(a)}static makeSearchBox(e){const t=document.createElement("div");t.classList.add("searchbox"),t.style.display="none";const i=document.createElement("div");i.innerHTML='';const s=document.createElement("input");return s.type="text",t.appendChild(i),t.appendChild(s),e.div.appendChild(t),e.commandFunctions.push((i=>!1===window.monaco&&!1===window.menu&&(window.handlerInFocus===e.id&&!window.textBoxFocused&&("none"===t.style.display?!!/^[a-zA-Z0-9]$/.test(i.key)&&(t.style.display="flex",s.focus(),!0):("Enter"===i.key||"Escape"===i.key)&&("Enter"===i.key&&window.callbackFunction(`search${e.id}_~_${s.value}`),t.style.display="none",s.value="",!0))))),s.addEventListener("input",(()=>s.value=s.value.toUpperCase())),{window:t,box:s}}static makeSpinner(e){e.spinner=document.createElement("div"),e.spinner.classList.add("spinner"),e.wrapper.appendChild(e.spinner);let t=0;!function i(){e.spinner&&(t+=10,e.spinner.style.transform=`translate(-50%, -50%) rotate(${t}deg)`,requestAnimationFrame(i))}()}static _styleMap={"--bg-color":"backgroundColor","--hover-bg-color":"hoverBackgroundColor","--click-bg-color":"clickBackgroundColor","--active-bg-color":"activeBackgroundColor","--muted-bg-color":"mutedBackgroundColor","--border-color":"borderColor","--color":"color","--active-color":"activeColor"};static setRootStyles(e){const t=document.documentElement.style;for(const[i,s]of Object.entries(this._styleMap))t.setProperty(i,e[s])}toJSON(){return{id:this.id,options:this.chart.options(),scale:this.scale,precision:this.precision}}fromJSON(e){e?(e.options&&this.chart.applyOptions(e.options),void 0!==e.scale&&(this.scale=e.scale),void 0!==e.precision&&(this.precision=e.precision)):console.warn("No JSON data provided for handler deserialization.")}_type="chart";title="chart"}return e.Box=Z,e.CodeEditor=on,e.FillArea=_,e.Handler=Lo,e.HorizontalLine=se,e.Legend=D,e.RayLine=ne,e.Table=class{_div;callbackName;borderColor;borderWidth;table;rows={};headings;widths;alignments;footer;header;constructor(e,t,i,s,n,o,r=!1,a,l,c,h,p){this._div=document.createElement("div"),this.callbackName=null,this.borderColor=l,this.borderWidth=c,r?(this._div.style.position="absolute",this._div.style.cursor="move"):(this._div.style.position="relative",this._div.style.float=o),this._div.style.zIndex="2000",this.reSize(e,t),this._div.style.display="flex",this._div.style.flexDirection="column",this._div.style.borderRadius="5px",this._div.style.color="white",this._div.style.fontSize="12px",this._div.style.fontVariantNumeric="tabular-nums",this.table=document.createElement("table"),this.table.style.width="100%",this.table.style.borderCollapse="collapse",this._div.style.overflow="hidden",this.headings=i,this.widths=s.map((e=>100*e+"%")),this.alignments=n;let d=this.table.createTHead().insertRow();for(let e=0;e0?p[e]:a,t.style.color=h[e],d.appendChild(t)}let u,m,g=document.createElement("div");if(g.style.overflowY="auto",g.style.overflowX="hidden",g.style.backgroundColor=a,g.appendChild(this.table),this._div.appendChild(g),window.containerDiv.appendChild(this._div),!r)return;let f=e=>{this._div.style.left=e.clientX-u+"px",this._div.style.top=e.clientY-m+"px"},y=()=>{document.removeEventListener("mousemove",f),document.removeEventListener("mouseup",y)};this._div.addEventListener("mousedown",(e=>{u=e.clientX-this._div.offsetLeft,m=e.clientY-this._div.offsetTop,document.addEventListener("mousemove",f),document.addEventListener("mouseup",y)}))}divToButton(e,t){e.addEventListener("mouseover",(()=>e.style.backgroundColor="rgba(60, 60, 60, 0.6)")),e.addEventListener("mouseout",(()=>e.style.backgroundColor="transparent")),e.addEventListener("mousedown",(()=>e.style.backgroundColor="rgba(60, 60, 60)")),e.addEventListener("click",(()=>window.callbackFunction(t))),e.addEventListener("mouseup",(()=>e.style.backgroundColor="rgba(60, 60, 60, 0.6)"))}newRow(e,t=!1){let i=this.table.insertRow();i.style.cursor="default";for(let s=0;s{e&&(window.cursor=e),document.body.style.cursor=window.cursor},e}({},LightweightCharts,monaco); +var Lib=function(e,t,i){"use strict";function s(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var s=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var n,o=s(i);function r(e){if(void 0===e)throw new Error("Value is undefined");return e}class a{_chart=void 0;_series=void 0;requestUpdate(){this._requestUpdate&&this._requestUpdate()}_requestUpdate;attached({chart:e,series:t,requestUpdate:i}){this._chart=e,this._series=t,this._series.subscribeDataChanged(this._fireDataUpdated),this._requestUpdate=i,this.requestUpdate()}detached(){this._chart=void 0,this._series=void 0,this._requestUpdate=void 0}get chart(){return r(this._chart)}get series(){return r(this._series)}_fireDataUpdated(e){this.dataUpdated&&this.dataUpdated(e)}toJSON(){return{}}fromJSON(e){}}function l(e,t){if(e.startsWith("#"))return function(e,t){if(e=e.replace(/^#/,""),!/^([0-9A-F]{3}){1,2}$/i.test(e))throw new Error("Invalid hex color format.");const[i,s,n]=3===(o=e).length?[parseInt(o[0]+o[0],16),parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16)]:[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)];var o;return`rgba(${i}, ${s}, ${n}, ${t})`}(e,t);{const i=/^rgb(a)?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:,\s*([\d.]+))?\)/i,s=e.match(i);if(s){const e=s[2],i=s[3],n=s[4],o=s[1]?s[5]??"1":"1";return`rgba(${e}, ${i}, ${n}, ${t??o})`}throw new Error("Unsupported color format. Use hex, rgb, or rgba.")}}function c(e,t=.2){let[i,s,n,o=1]=e.startsWith("#")?[...(r=e,3===(r=r.replace(/^#/,"")).length?[parseInt(r[0]+r[0],16),parseInt(r[1]+r[1],16),parseInt(r[2]+r[2],16)]:[parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.slice(4,6),16)]),1]:e.match(/\d+(\.\d+)?/g).map(Number);var r;return i=Math.max(0,Math.min(255,i*(1-t))),s=Math.max(0,Math.min(255,s*(1-t))),n=Math.max(0,Math.min(255,n*(1-t))),e.startsWith("#")?`#${((1<<24)+(Math.round(i)<<16)+(Math.round(s)<<8)+Math.round(n)).toString(16).slice(1)}`:`rgba(${Math.round(i)}, ${Math.round(s)}, ${Math.round(n)}, ${o})`}function h(e,t,i=""){for(const s of Object.keys(e)){const n=i?`${i}.${s}`:s,o=e[s];"object"==typeof o&&null!==o?h(o,t,n):s.toLowerCase().includes("color")&&t(n,o)}}function p(e){if(e.length>100)return 1;let t=1;const i=/^rgba\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*(\d?\.?\d+)\s*$/i.exec(e),s=/^hsla\s*\d{1,3}(?:\.\d+)?\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*,\s*(\d?\.?\d+)\s*$/i.exec(e);return i?t=parseFloat(i[1]):s&&(t=parseFloat(s[1])),isNaN(t)?1:Math.max(0,Math.min(1,t))}class d{numbers;cache;constructor(e){this.numbers=e,this.cache=new Map}findClosestIndex(e,t){const i=`${e}:${t}`;if(this.cache.has(i))return this.cache.get(i);const s=this._performSearch(e,t);return this.cache.set(i,s),s}_performSearch(e,t){let i=0,s=this.numbers.length-1;if(e<=this.numbers[0].time)return 0;if(e>=this.numbers[s].time)return s;for(;i<=s;){const t=Math.floor((i+s)/2),n=this.numbers[t].time;if(n===e)return t;n>e?s=t-1:i=t+1}return"left"===t?i:s}}function u(e){switch(e.trim().toLowerCase()){case"rectangle":return n.Rectangle;case"rounded":return n.Rounded;case"ellipse":return n.Ellipse;case"arrow":return n.Arrow;case"3d":return n.Cube;case"polygon":return n.Polygon;case"bar":return n.Bar;case"slanted":return n.Slanted;default:return console.warn(`Unknown CandleShape: ${e}`),n.Rectangle}}function m(e){return e.type===t.ColorType.Solid}function g(e){return e.type===t.ColorType.VerticalGradient}function f(e){return"value"in e}function y(e){return"close"in e&&"open"in e&&"high"in e&&"low"in e}function b(e){return!(!e||"object"!=typeof e)&&("time"in e&&!("value"in e||"open"in e||"close"in e||"high"in e||"low"in e))}function v(e){const t=e.options();return"lineColor"in t||"color"in t}function x(e){return"object"==typeof e&&null!==e&&"function"==typeof e.data&&"function"==typeof e.options}!function(e){e.Rectangle="Rectangle",e.Rounded="Rounded",e.Ellipse="Ellipse",e.Arrow="Arrow",e.Cube="3d",e.Polygon="Polygon",e.Bar="Bar",e.Slanted="Slanted"}(n||(n={}));class _ extends a{static type="Fill Area";_paneViews;_originSeries;_destinationSeries;_bandsData=[];options;_timeIndices;constructor(e,t,i){super();const s=l("#0000FF",.25),n=l("#FF0000",.25),o=v(e)?l(e.options().color||s,.3):l(s,.3),r=v(t)?l(t.options().color||n,.3):l(n,.3);this.options={...S,...i,originColor:i.originColor??o,destinationColor:i.destinationColor??r},this._paneViews=[new C(this)],this._timeIndices=new d([]),this._originSeries=e,this._destinationSeries=t,this._originSeries.subscribeDataChanged((()=>{console.log("Origin series data has changed. Recalculating bands."),this.dataUpdated("full"),this.updateAllViews()})),this._destinationSeries.subscribeDataChanged((()=>{console.log("Destination series data has changed. Recalculating bands."),this.dataUpdated("full"),this.updateAllViews()}))}updateAllViews(){this._paneViews.forEach((e=>e.update()))}applyOptions(e){this.options={...this.options,...e},this.calculateBands(),this.updateAllViews(),super.requestUpdate(),console.log("FillArea options updated:",this.options)}paneViews(){return this._paneViews}attached(e){super.attached(e),this.dataUpdated("full")}dataUpdated(e){if(this.calculateBands(),"full"===e){const e=this._originSeries.data();this._timeIndices=new d([...e])}}calculateBands(){const e=this._originSeries.data(),t=this._destinationSeries.data(),i=this._alignDataLengths([...e],[...t]),s=[];for(let e=0;es){const e=t[s-1];for(;t.lengthi){const t=e[i-1];for(;e.lengthe.lower)).slice(o,r+1)),maxValue:Math.max(...this._bandsData.map((e=>e.upper)).slice(o,r+1))};return{priceRange:{minValue:a.minValue,maxValue:a.maxValue}}}}class w{_viewData;_options;constructor(e){this._viewData=e,this._options=e.options}draw(){}drawBackground(e){const t=this._viewData.data,i=this._options;t.length<2||e.useBitmapCoordinateSpace((e=>{const s=e.context;s.scale(e.horizontalPixelRatio,e.verticalPixelRatio);let n=!1,o=0;for(let e=0;e=o;i--)s.lineTo(t[i].x,t[i].destination);s.closePath(),s.fill()}s.beginPath(),s.moveTo(r.x,r.origin),s.fillStyle=r.isOriginAbove?i.originColor||"rgba(0, 0, 0, 0)":i.destinationColor||"rgba(0, 0, 0, 0)",o=e,n=!0}if(s.lineTo(a.x,a.origin),e===t.length-2||a.isOriginAbove!==r.isOriginAbove){for(let i=e+1;i>=o;i--)s.lineTo(t[i].x,t[i].destination);s.closePath(),s.fill(),n=!1}}i.lineWidth&&(s.lineWidth=i.lineWidth,s.strokeStyle=i.originColor||"rgba(0, 0, 0, 0)",s.stroke())}))}}class C{_source;_data;constructor(e){this._source=e,this._data={data:[],options:this._source.options}}update(){const e=this._source.chart.timeScale();this._data.data=this._source._bandsData.map((t=>({x:e.timeToCoordinate(t.time),origin:this._source._originSeries.priceToCoordinate(t.origin),destination:this._source._destinationSeries.priceToCoordinate(t.destination),isOriginAbove:t.origin>t.destination}))),this._data.options=this._source.options}renderer(){return new w(this._data)}zOrder(){return"bottom"}}const S={originColor:null,destinationColor:null,lineWidth:null};function k(e,t){let i,s;if(void 0!==e.close){i=e.close}else void 0!==e.value&&(i=e.value);if(void 0!==t.close){s=t.close}else void 0!==t.value&&(s=t.value);if(void 0!==i&&void 0!==s){if(i{e&&(window.cursor=e),document.body.style.cursor=window.cursor},window.cursor="default",window.textBoxFocused=!1}const P='\n\n \n \n\n',T='\n\n \n \n \n\n';class I{contextMenu;handler;constructor(e){this.contextMenu=e.contextMenu,this.handler=e.handler}populateLegendMenu(e,t){this.contextMenu.clearMenu();void 0!==e.seriesList?this.populateGroupMenu(e,t):this.populateSeriesMenu(e,t),this.contextMenu.separator(),this.contextMenu.addMenuItem("Close Menu",(()=>this.contextMenu.hideMenu())),this.contextMenu.showMenu(t)}populateGroupMenu(e,t){if(this.contextMenu.addMenuItem("Rename",(()=>{const t=prompt("Enter new group name:",e.name);t&&""!==t.trim()&&this.renameGroup(e,t.trim())}),!1),this.contextMenu.addMenuItem("Remove",(()=>{confirm(`Are you sure you want to remove the group "${e.name}"? This will also remove all contained series.`)&&(e.seriesList.forEach((e=>{this.handler.legend.removeLegendSeries(e.series),this.handler.removeSeries(e.series)})),this.removeGroup(e))})),this.contextMenu.addMenuItem("Ungroup",(()=>{this.ungroupSeries(e)})),e.seriesList&&e.seriesList.length>0){const t=e.seriesList[0].series.getPane().paneIndex(),i=this.handler.chart.panes(),s=`Pane ${t}`,n=()=>{0===t?i.length>1?(e.seriesList.forEach((e=>{e.series.moveToPane(1)})),console.log(`Default: Moved group "${e.name}" series from pane ${t} to pane 1.`)):(e.seriesList.forEach((e=>{e.series.moveToPane(i.length)})),console.log(`Default: Moved group "${e.name}" series from pane ${t} to a new pane at index ${i.length}.`)):(e.seriesList.forEach((e=>{e.series.moveToPane(0)})),console.log(`Default: Moved group "${e.name}" series from pane ${t} back to main pane (0).`))},o=[];for(let t=0;t{e.seriesList.forEach((e=>{e.series.moveToPane(t)})),console.log(`Moved group "${e.name}" series to existing pane ${t}.`)}});o.push({name:"New Pane",action:()=>{e.seriesList.forEach((e=>{e.series.moveToPane(i.length)})),console.log(`Moved group "${e.name}" series to a new pane at index ${i.length}.`)}}),this.contextMenu.addMenuInput(this.contextMenu.div,{type:"hybrid",label:"Move to",sublabel:s,value:s,onChange:e=>{const t=o.find((t=>t.name===e));t&&t.action()},hybridConfig:{defaultAction:n,options:o.map((e=>({name:e.name,action:e.action})))}})}this.contextMenu.showMenu(t)}populateSeriesMenu(e,t){this.contextMenu.addMenuItem("Open Series Menu",(()=>{this.contextMenu.populateSeriesMenu(e.series,t)}),!1),this.contextMenu.addMenuItem("Move to Group ▸",(()=>{this.populateMoveToGroupMenu(e)}),!1),this.contextMenu.addMenuItem("Remove Series",(()=>{confirm(`Are you sure you want to remove the series "${e.name}"?`)&&(this.handler.legend.removeLegendSeries(e.series),this.handler.removeSeries(e.series))})),e.primitives&&this.contextMenu.addMenuItem("Remove Primitives",(()=>{this.removePrimitivesFromSeries(e)})),e.group&&this.contextMenu.addMenuItem("Ungroup",(()=>{this.ungroupSeriesFromGroup(e)})),this.contextMenu.showMenu(t)}populateMoveToGroupMenu(e){this.contextMenu.clearMenu();this.handler.legend._groups.forEach((t=>{this.contextMenu.addMenuItem(t.name,(()=>{this.handler.legend.moveSeriesToGroup(e,t)}))})),this.contextMenu.addMenuItem("Create New Group...",(()=>{const t=prompt("Enter new group name:","New Group");t&&""!==t.trim()&&this.createNewGroup(e,t.trim())})),e.group&&this.contextMenu.addMenuItem("Ungroup",(()=>{this.ungroupSeriesFromGroup(e)}))}renameGroup(e,t){e.name=t,e.seriesList.forEach((e=>{e.group=t}));const i=e.row.querySelector(".group-header span");i&&(i.textContent=t),console.log(`Group renamed to: ${t}`)}removeGroup(e){this.handler.legend.removeLegendGroup(e),this.handler.legend._groups=this.handler.legend._groups.filter((t=>t!==e)),console.log(`Group "${e.name}" removed along with its series.`)}createNewGroup(e,t){this.handler.legend.deleteLegendEntry(e),e.group=t,this.handler.legend.addLegendItem(e)}ungroupSeriesFromGroup(e){this.handler.legend.getGroupOfSeries(e.series)&&(this.handler.legend.deleteLegendEntry(e),e.group=void 0,this.handler.legend.addLegendItem(e)),console.log(`Series "${e.name}" removed from its group and is now standalone.`)}removePrimitivesFromSeries(e){e.series.primitives&&(Object.values(e.series.primitives).forEach((t=>{e.series.detachPrimitive(t),console.log(`Primitive removed from series "${e.name}".`)})),e.primitives=void 0),console.log(`All primitives removed from series "${e.name}".`)}ungroupSeries(e){e.seriesList.forEach((e=>{this.handler.legend.deleteLegendEntry(e),e.group=void 0,this.handler.legend.addLegendItem(e)})),this.removeGroup(e),console.log(`All series in group "${e.name}" have been ungrouped and are now standalone.`)}}function A(e){return e.data()[e.data().length-1]}class D{handler;div;seriesContainer;legendMenu;linesEnabled=!1;contextMenu;text;_items=[];_lines=[];_groups=[];constructor(e){this.handler=e,this.div=document.createElement("div"),this.div.classList.add("legend"),this.seriesContainer=document.createElement("div"),this.text=document.createElement("span"),this.contextMenu=this.handler.ContextMenu,this.legendMenu=new I({contextMenu:this.contextMenu,handler:e}),this.setupLegend(),this.legendHandler=this.legendHandler.bind(this),e.chart.subscribeCrosshairMove(this.legendHandler)}setupLegend(){this.div.style.maxWidth=100*this.handler.scale.width-8+"vw",this.div.style.display="none";const e=document.createElement("div");e.style.display="flex",e.style.flexDirection="row",this.seriesContainer.classList.add("series-container"),this.text.style.lineHeight="1.8",e.appendChild(this.seriesContainer),this.div.appendChild(this.text),this.div.appendChild(e),this.handler.div.appendChild(this.div)}legendItemFormat(e,t){return"number"!=typeof e||isNaN(e)?"-":e.toFixed(t).toString().padStart(8," ")}shorthandFormat(e){const t=Math.abs(e);return t>=1e6?(e/1e6).toFixed(1)+"M":t>=1e3?(e/1e3).toFixed(1)+"K":e.toString().padStart(8," ")}createSvgIcon(e){const t=document.createElement("div");t.innerHTML=e.trim();return t.querySelector("svg")}addLegendItem(e){const t=this.mapToSeries(e);if(t.group)return this.addItemToGroup(t,t.group);{const e=this.makeSeriesRow(t,this.seriesContainer);return this._lines.push(t),this._items.push(t),e}}addLegendPrimitive(e,t,i){const s=i||t.constructor.name,n=this._lines.find((t=>t.series===e));if(!n)return void console.warn(`Parent series not found in legend for primitive: ${s}`);n.primitives||(n.primitives=[]);let o=this.seriesContainer.querySelector(`[data-series-id="${n.name}"] .primitives-container`);o||(o=document.createElement("div"),o.classList.add("primitives-container"),o.style.display="none",o.style.marginLeft="20px",o.style.flexDirection="column",n.row.insertAdjacentElement("afterend",o));const r=Array.from(o.children).find((e=>e.getAttribute("data-primitive-type")===s));if(r)return console.warn(`Primitive "${s}" already exists under the parent series.`),r;const a=document.createElement("div");a.classList.add("legend-primitive-row"),a.setAttribute("data-primitive-type",s),a.style.display="flex",a.style.justifyContent="space-between",a.style.marginTop="4px";const l=document.createElement("span");l.innerText=s;const c=document.createElement("div");c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center";const h=this.createSvgIcon(P),p=this.createSvgIcon(T);c.appendChild(h.cloneNode(!0));let d=!0;c.addEventListener("click",(()=>{d=!d,c.innerHTML="",c.appendChild(d?h.cloneNode(!0):p.cloneNode(!0)),this.togglePrimitive(t,d)})),a.appendChild(l),a.appendChild(c),o.appendChild(a),o.children.length>0&&(o.style.display="block");const u={name:s,primitive:t,row:a};return this._items.push(u),n.primitives.push(u),a}togglePrimitive(e,t){const i=e.options||e._options;if(!i)return void console.warn("Primitive has no options to update.");const s={};if("visible"in i)return s.visible=t,console.log(`Toggling visible option for primitive: ${e.constructor.name} to ${t}`),void e.applyOptions(s);const n="_originalColors";e[n]||(e[n]={});const o=e[n];for(const e of Object.keys(i))e.toLowerCase().includes("color")&&(t?s[e]=o[e]||i[e]:(o[e]||(o[e]=i[e]),s[e]="rgba(0,0,0,0)"));Object.keys(s).length>0&&(console.log(`Updating visibility for primitive: ${e.constructor.name}`),e.applyOptions(s),t&&delete e[n])}findLegendPrimitive(e,t){const i=this._lines.find((t=>t.series===e));if(!i||!i.primitives)return null;return i.primitives.find((e=>e.primitive===t))||null}mapToSeries(e){return{name:e.name,series:e.series,group:e.group||void 0,legendSymbol:e.legendSymbol||[],colors:e.colors||["#000"],seriesType:e.seriesType||"Line",div:document.createElement("div"),row:document.createElement("div"),toggle:document.createElement("div"),extraData:e.extraData||null}}addItemToGroup(e,t){let i=this._groups.find((e=>e.name===t));return i?(i.seriesList.push(e),this.makeSeriesRow(e,i.div),i.row):this.makeSeriesGroup(t,[e])}makeSeriesGroup(e,t){let i=this._groups.find((t=>t.name===e));if(i)return i.seriesList.push(...t),t.forEach((e=>this.makeSeriesRow(e,i.div))),i.row;{const i={name:e,seriesList:t,subGroups:[],div:document.createElement("div"),row:document.createElement("div"),toggle:document.createElement("div")};return this._groups.push(i),this.renderGroup(i,this.seriesContainer),i.row}}makeSeriesRow(e,t){const i=document.createElement("div");i.classList.add("legend-series-row"),i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="space-between",i.style.marginBottom="4px";const s=document.createElement("button");s.classList.add("legend-action-button"),s.innerHTML="◇",s.title="Series Actions",s.style.marginRight="0px",s.style.fontSize="1em",s.style.border="none",s.style.background="none",s.style.cursor="pointer",s.style.color="#ffffff",s.addEventListener("click",(t=>{t.stopPropagation(),t.preventDefault(),"◇"===s.innerHTML?s.innerHTML="◈":s.innerHTML="◇",this.legendMenu.populateLegendMenu(e,t)}));const n=document.createElement("div");n.classList.add("series-info"),n.style.flex="1";if(["Bar","Candlestick","Ohlc"].includes(e.seriesType||"")){const t="-",i="-",s=e.legendSymbol[0]||"▨",o=e.legendSymbol[1]||s,r=e.colors[0]||"#00FF00",a=e.colors[1]||"#FF0000";n.innerHTML=`\n ${s}\n ${o}\n ${e.name}: O ${t}, \n C ${i}\n `}else n.innerHTML=e.legendSymbol.map(((t,i)=>`${t}`)).join(" ")+` ${e.name}`;const o=document.createElement("div");o.classList.add("legend-toggle-switch"),o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center";const r=this.createSvgIcon(P),a=this.createSvgIcon(T);o.appendChild(r.cloneNode(!0));let l=!0;o.addEventListener("click",(t=>{l=!l,e.series.applyOptions({visible:l}),o.innerHTML="",o.appendChild(l?r.cloneNode(!0):a.cloneNode(!0)),o.setAttribute("aria-pressed",l.toString()),o.classList.toggle("inactive",!l),t.stopPropagation()})),o.setAttribute("role","button"),o.setAttribute("aria-label",`Toggle visibility for ${e.name}`),o.setAttribute("aria-pressed",l.toString()),i.appendChild(s),i.appendChild(n),i.appendChild(o),t.appendChild(i),i.addEventListener("contextmenu",(t=>{t.preventDefault(),this.legendMenu.populateLegendMenu(e,t)}));const c={...e,div:n,row:i,toggle:o};return this._lines.push(c),this._items.push(c),i}isLegendPrimitive(e){return void 0!==e.primitive&&void 0!==e.row}deleteLegendEntry(e,t){if(t&&!e){const e=this._groups.findIndex((e=>e.name===t));if(-1!==e){const i=this._groups[e];this.seriesContainer.removeChild(i.row),this._groups.splice(e,1),this._items=this._items.filter((e=>e!==i)),console.log(`Group "${t}" removed.`)}else console.warn(`Legend group with name "${t}" not found.`)}else if(e){let i=!1;if(t){const s=this._groups.find((e=>e.name===t));if(s){const n=s.seriesList.findIndex((t=>t.name===e));-1!==n&&(s.seriesList.splice(n,1),0===s.seriesList.length?(this.seriesContainer.removeChild(s.row),this._groups=this._groups.filter((e=>e!==s)),this._items=this._items.filter((e=>e!==s)),console.log(`Group "${t}" is empty and has been removed.`)):this.renderGroup(s,this.seriesContainer),i=!0,console.log(`Series "${e}" removed from group "${t}".`))}else console.warn(`Legend group with name "${t}" not found.`)}if(!i){const t=this._lines.findIndex((t=>t.name===e));if(-1!==t){const s=this._lines[t];this.seriesContainer.removeChild(s.row),this._lines.splice(t,1),this._items=this._items.filter((e=>e!==s)),i=!0,console.log(`Series "${e}" removed.`)}}i||console.warn(`Legend item with name "${e}" not found.`)}else console.warn("No seriesName or groupName provided for deletion.")}removeLegendGroup(e){this.seriesContainer.contains(e.row)&&this.seriesContainer.removeChild(e.row);const t=this._groups.indexOf(e);-1!==t&&this._groups.splice(t,1),this._items=this._items.filter((t=>t!==e)),console.log(`Group "${e.name}" removed from legend.`)}findSeriesAnywhere(e){const t=this._lines.find((t=>t.series===e));if(t)return t;for(const t of this._groups){const i=this.findSeriesInGroup(t,e);if(i)return i}}findSeriesInGroup(e,t){const i=e.seriesList.find((e=>e.series===t));if(i)return i;for(const i of e.subGroups){const e=this.findSeriesInGroup(i,t);if(e)return e}}removeSeriesFromGroupDOM(e,t){if(!e.div||!t.row)return console.warn(`⚠️ Cannot remove series "${t.name}" – missing group div or series row.`),!1;if(e.div.contains(t.row))try{return e.div.removeChild(t.row),console.log(`✅ Removed series "${t.name}" from group "${e.name}".`),!0}catch(i){return console.warn(`⚠️ Error removing series "${t.name}" from group "${e.name}":`,i),!1}return e.subGroups.some((e=>this.removeSeriesFromGroupDOM(e,t)))}removeLegendSeries(e){let t;if(t=x(e)?this.findSeriesAnywhere(e):e,t){if(this._lines=this._lines.filter((e=>e!==t)),this._items=this._items.filter((e=>e!==t)),t.group){const e=this.findGroup(t.group);if(e){if(e.seriesList=e.seriesList.filter((e=>e!==t)),t.row&&e.div.contains(t.row))try{e.div.removeChild(t.row),console.log(`✅ Removed "${t.name}" from group "${e.name}".`)}catch(i){console.warn(`⚠️ Error removing "${t.name}" from group "${e.name}":`,i)}0===e.seriesList.length&&this.removeGroupCompletely(e)}}else if(t.row?.parentElement)try{t.row.parentElement.removeChild(t.row),console.log(`✅ Removed row for standalone series: ${t.name}`)}catch(e){console.warn("⚠️ Error removing standalone series row:",e)}}else console.warn("⚠️ LegendSeries not found in legend.")}removeGroupCompletely(e){if(e.row.parentElement)try{e.row.parentElement.removeChild(e.row)}catch(t){console.warn(`Error removing group "${e.name}":`,t)}this._groups=this._groups.filter((t=>t!==e)),this._items=this._items.filter((t=>t!==e)),console.log(`Group "${e.name}" removed as it became empty.`)}removeLegendPrimitive(e){let t;if(t=this.isLegendPrimitive(e)?e:this._items.find((t=>this.isLegendPrimitive(t)&&t.primitive===e)),!t)return void console.warn("❌ LegendPrimitive not found in legend.");t.row&&t.row.parentElement?t.row.parentElement.removeChild(t.row):console.warn("❌ LegendPrimitive row not found in the DOM.");const i=this._lines.find((e=>e.primitives?.includes(t)));if(i&&(i.primitives=i.primitives.filter((e=>e!==t)),console.log(`✅ Removed primitive "${t.name}" from series "${i.name}".`)),this._items=this._items.filter((e=>e!==t)),t.primitive)try{console.log(`Detaching underlying chart primitive for "${t.name}".`),i?.series.detachPrimitive(t.primitive)}catch(e){console.warn(`⚠️ Failed to detach primitive "${t.name}":`,e)}console.log(`✅ LegendPrimitive "${t.name}" removed from legend.`)}getGroupOfSeries(e){for(const t of this._groups){const i=this.findGroupOfSeriesRecursive(t,e);if(i)return i}}findGroupOfSeriesRecursive(e,t){for(const i of e.seriesList)if(i.series===t)return e.name;for(const i of e.subGroups){const e=this.findGroupOfSeriesRecursive(i,t);if(e)return e}}moveSeriesToGroup(e,t){let i=this._lines.findIndex((t=>t.name===e)),s=null;if(-1!==i)s=this._lines[i];else for(const t of this._groups){const i=t.seriesList.findIndex((t=>t.name===e));if(-1!==i){s=t.seriesList[i],t.seriesList.splice(i,1),0===t.seriesList.length?(this.seriesContainer.removeChild(t.row),this._groups=this._groups.filter((e=>e!==t)),this._items=this._items.filter((e=>e!==t)),console.log(`Group "${t.name}" is empty and has been removed.`)):this.renderGroup(t,this.seriesContainer);break}}if(!s)return void console.warn(`Series "${e}" not found in legend.`);-1!==i?(this.seriesContainer.removeChild(s.row),this._lines.splice(i,1),this._items=this._items.filter((e=>e!==s))):this._items=this._items.filter((e=>e!==s));let n=this.findGroup(t);n?(n.seriesList.push(s),this.makeSeriesRow(s,n.div)):(n={name:t,seriesList:[s],subGroups:[],div:document.createElement("div"),row:document.createElement("div"),toggle:document.createElement("div")},this._groups.push(n),this.renderGroup(n,this.seriesContainer)),this._items.push(s),console.log(`Series "${e}" moved to group "${t}".`)}renderGroup(e,t){e.row.innerHTML="",e.row.style.display="flex",e.row.style.flexDirection="column",e.row.style.width="100%";const i=document.createElement("div");i.classList.add("group-header"),i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="space-between",i.style.cursor="pointer";const s=document.createElement("button");s.classList.add("legend-action-button"),s.innerHTML="◇",s.title="Group Actions",s.style.marginRight="0px",s.style.fontSize="1em",s.style.border="none",s.style.background="none",s.style.cursor="pointer",s.style.color="#ffffff",s.addEventListener("click",(t=>{t.stopPropagation(),t.preventDefault(),"◇"===s.innerHTML?s.innerHTML="◈":s.innerHTML="◇",this.legendMenu.populateLegendMenu(e,t)}));const n=document.createElement("span");n.style.fontWeight="bold",n.innerHTML=e.seriesList.map((e=>e.legendSymbol.map(((t,i)=>`${t}`)).join(" "))).join(" ")+` ${e.name}`;const o=document.createElement("span");o.classList.add("toggle-button"),o.style.marginLeft="auto",o.style.fontSize="1.2em",o.style.cursor="pointer",o.innerHTML="⌲",o.setAttribute("aria-expanded","true"),o.addEventListener("click",(t=>{t.stopPropagation(),"none"===e.div.style.display?(e.div.style.display="block",o.innerHTML="⌲",o.setAttribute("aria-expanded","true")):(e.div.style.display="none",o.innerHTML="☰",o.setAttribute("aria-expanded","false"))})),i.appendChild(s),i.appendChild(n),i.appendChild(o),i.addEventListener("contextmenu",(t=>{t.preventDefault(),this.legendMenu.populateLegendMenu(e,t)})),e.row.appendChild(i),e.div=document.createElement("div"),e.div.style.display="block",e.div.style.marginLeft="10px";for(const t of e.seriesList)this.makeSeriesRow(t,e.div);for(const t of e.subGroups){const i=document.createElement("div");i.style.display="flex",i.style.flexDirection="column",i.style.paddingLeft="5px",this.renderGroup(t,i),e.div.appendChild(i)}e.row.appendChild(e.div),t.contains(e.row)||t.appendChild(e.row),e.row.oncontextmenu=e=>{e.preventDefault()}}legendHandler(e,t=!1){this.updateGroupDisplay(e,null,t),this.updateSeriesDisplay(e,null,t)}updateSeriesDisplay(e,t,i){this._lines&&this._lines.length?this._lines.forEach((t=>{const i=e.seriesData.get(t.series)||A(t.series);if(!i)return;const s=t.seriesType||"Line",n=t.series.options().priceFormat;if("Line"===s||"Area"===s||"Histogram"===s||"Symbol"==s){const e=i;if(null==e.value)return;const s=this.legendItemFormat(e.value,n.precision);t.div.innerHTML=`\n ${t.legendSymbol[0]||"▨"} \n ${t.name}: ${s}`}else if("Bar"===s||"Candlestick"===s||"Ohlc"===s){const{open:e,close:s}=i;if(null==e||null==s)return;const o=this.legendItemFormat(e,n.precision),r=this.legendItemFormat(s,n.precision),a=s>e,l=a?t.colors[0]:t.colors[1],c=a?t.legendSymbol[0]:t.legendSymbol[1];t.div.innerHTML=`\n ${c||"▨"}\n ${t.name}: \n O ${o}, \n C ${r}`}})):console.error("No lines available to update legend.")}updateGroupDisplay(e,t,i){this._groups.forEach((t=>{this.linesEnabled?(t.row.style.display="flex",t.seriesList.forEach((t=>{const i=e.seriesData.get(t.series)||A(t.series);if(!i)return;const s=t.seriesType||"Line",n=t.name,o=t.series.options().priceFormat;if(["Bar","Candlestick","Ohlc"].includes(s)){const{open:e,close:s,high:r,low:a}=i;if(null==e||null==s||null==r||null==a)return;const l=this.legendItemFormat(e,o.precision),c=this.legendItemFormat(s,o.precision),h=s>e,p=h?t.colors[0]:t.colors[1],d=h?t.legendSymbol[0]:t.legendSymbol[1];t.div.innerHTML=`\n ${d||"▨"}\n ${n}: \n O ${l}, \n C ${c}\n `}else{const e="value"in i?i.value:void 0;if(null==e)return;const s=this.legendItemFormat(e,o.precision),r=t.colors[0],a=t.legendSymbol[0]||"▨";t.div.innerHTML=`\n ${a}\n ${n}: ${s}\n `}}))):t.row.style.display="none"}))}findGroup(e,t=this._groups){for(const i of t){if(i.name===e)return i;const t=this.findGroup(e,i.subGroups);if(t)return t}}}const L={lineColor:"#1E80F0",lineStyle:t.LineStyle.Solid,width:4};var N;!function(e){e[e.NONE=0]="NONE",e[e.HOVERING=1]="HOVERING",e[e.DRAGGING=2]="DRAGGING",e[e.DRAGGINGP1=3]="DRAGGINGP1",e[e.DRAGGINGP2=4]="DRAGGINGP2",e[e.DRAGGINGP3=5]="DRAGGINGP3",e[e.DRAGGINGP4=6]="DRAGGINGP4"}(N||(N={}));class O extends a{_paneViews=[];_options;_points=[];_state=N.NONE;_startDragPoint=null;_latestHoverPoint=null;static _mouseIsDown=!1;static hoveredObject=null;static lastHoveredObject=null;_listeners=[];constructor(e){super(),this._options={...L,...e}}updateAllViews(){this._paneViews.forEach((e=>e.update()))}paneViews(){return this._paneViews}applyOptions(e){this._options={...this._options,...e},this.requestUpdate()}updatePoints(...e){for(let t=0;ti.name===e&&i.listener===t));this._listeners.splice(this._listeners.indexOf(i),1)}_handleHoverInteraction(e){if(this._latestHoverPoint=e.point,O._mouseIsDown)this._handleDragInteraction(e);else if(this._mouseIsOverDrawing(e)){if(this._state!=N.NONE)return;this._moveToState(N.HOVERING),O.hoveredObject=O.lastHoveredObject=this}else{if(this._state==N.NONE)return;this._moveToState(N.NONE),O.hoveredObject===this&&(O.hoveredObject=null)}}static _eventToPoint(e,t){if(!t||!e.point||!e.logical)return null;const i=t.coordinateToPrice(e.point.y);return null==i?null:{time:e.time||null,logical:e.logical,price:i.valueOf()}}static _getDiff(e,t){return{logical:e.logical-t.logical,price:e.price-t.price}}_addDiffToPoint(e,t,i){e&&(e.logical=e.logical+t,e.price=e.price+i,e.time=this.series.dataByIndex(e.logical)?.time||null)}_handleMouseDownInteraction=()=>{O._mouseIsDown=!0,this._onMouseDown()};_handleMouseUpInteraction=()=>{O._mouseIsDown=!1,this._moveToState(N.HOVERING)};_handleDragInteraction(e){if(this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1&&this._state!=N.DRAGGINGP2&&this._state!=N.DRAGGINGP3&&this._state!=N.DRAGGINGP4)return;const t=O._eventToPoint(e,this.series);if(!t)return;this._startDragPoint=this._startDragPoint||t;const i=O._getDiff(t,this._startDragPoint);this._onDrag(i),this.requestUpdate(),this._startDragPoint=t}}class V extends O{_paneViews=[];_hovered=!1;linkedObjects=[];constructor(e,t,i){super(),this.points.push(e),this.points.push(t),this._options={...L,...i}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}_mouseIsOverObjects(e){for(const t of this.linkedObjects)for(const i in t){if(i.includes("mouseIsOver")&&"function"==typeof t[i]&&t[i](e))return!0;if(i.includes("_hovered")&&"function"==typeof t[i]&&t[i]())return!0}return!1}_mouseIsOverDrawing(e){const t=this._mouseIsOverTwoPointDrawing(e),i=this._mouseIsOverObjects(e),s=t||i;return console.debug("Mouse over check",{selfResult:t,objectsResult:i,finalResult:s}),s}detach(){this.linkedObjects.forEach((e=>{const t=e.series;t&&t.detachPrimitive(e)})),this.linkedObjects=[],super.detach()}get p1(){return this.points[0]}get p2(){return this.points[1]}get hovered(){return this._hovered}}class R extends O{_paneViews=[];_hovered=!1;linkedObjects=[];detach(){this.linkedObjects.forEach((e=>{const t=e.series;t&&t.detachPrimitive(e)})),this.linkedObjects=[],super.detach()}constructor(e,t,i,s){super(),this.points.push(e),this.points.push(t),this.points.push(i),this._options={...L,...s}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}setThirdPoint(e){this.updatePoints(null,null,e)}get p1(){return this.points[0]}get p2(){return this.points[1]}get p3(){return this.points[2]}get hovered(){return this._hovered}}class B extends O{_paneViews=[];_hovered=!1;linkedObjects=[];detach(){this.linkedObjects.forEach((e=>{const t=e.series;t&&t.detachPrimitive(e)})),this.linkedObjects=[],super.detach()}constructor(e,t,i,s,n){super(),this.points.push(e),this.points.push(t),this.points.push(i),this.points.push(s),this._options={...L,...n}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}setThirdPoint(e){this.updatePoints(null,null,e)}setFourthPoint(e){this.updatePoints(null,null,null,e)}get p1(){return this.points[0]}get p2(){return this.points[1]}get p3(){return this.points[2]}get p4(){return this.points[3]}get hovered(){return this._hovered}}class F{_chart;_series;_finishDrawingCallback=null;_drawings=[];_activeDrawing=null;_isDrawing=!1;_drawingType=null;_tempStartPoint=null;_tempSecondPoint=null;_clickCount=0;constructor(e,t,i=null){this._chart=e,this._series=t,this._finishDrawingCallback=i,this._chart.subscribeClick(this._clickHandler),this._chart.subscribeCrosshairMove(this._moveHandler)}_clickHandler=e=>this._onClick(e);_moveHandler=e=>this._onMouseMove(e);beginDrawing(e){this._drawingType=e,this._isDrawing=!0,this._tempStartPoint=null,this._tempSecondPoint=null,this._clickCount=0}stopDrawing(){this._isDrawing=!1,this._activeDrawing=null,this._tempStartPoint=null,this._tempSecondPoint=null,this._clickCount=0}get drawings(){return this._drawings}addNewDrawing(e){this._series.attachPrimitive(e),this._drawings.push(e)}delete(e){if(null==e)return;const t=this._drawings.indexOf(e);-1!=t&&(this._drawings.splice(t,1),e.detach())}clearDrawings(){for(const e of this._drawings)e.detach();this._drawings=[]}repositionOnTime(){for(const e of this.drawings){const t=[];for(const i of e.points){if(!i){t.push(i);continue}const e=i.time?this._chart.timeScale().coordinateToLogical(this._chart.timeScale().timeToCoordinate(i.time)||0):i.logical;t.push({time:i.time,logical:e,price:i.price})}e.updatePoints(...t)}}_onClick(e){if(!this._isDrawing)return;const t=O._eventToPoint(e,this._series);if(!t)return;let i;if(this._drawingType)if(i=this._drawingType.prototype instanceof B?4:this._drawingType.prototype instanceof R?3:(this._drawingType.prototype,2),3===i){if(null==this._activeDrawing)return null==this._tempStartPoint?(this._tempStartPoint=t,void(this._clickCount=1)):(this._activeDrawing=new this._drawingType(this._tempStartPoint,t,null),this._series.attachPrimitive(this._activeDrawing),this._clickCount=2,void(this._tempStartPoint=null));2===this._clickCount&&(this._activeDrawing.setThirdPoint(t),this._clickCount=3,this._drawings.push(this._activeDrawing),this.stopDrawing(),this._finishDrawingCallback&&this._finishDrawingCallback())}else if(4===i){if(null==this._activeDrawing)return null==this._tempStartPoint?(this._tempStartPoint=t,void(this._clickCount=1)):null==this._tempSecondPoint?(this._tempSecondPoint=t,void(this._clickCount=2)):(this._activeDrawing=new this._drawingType(this._tempStartPoint,this._tempSecondPoint,t,null),this._series.attachPrimitive(this._activeDrawing),this._clickCount=3,this._tempStartPoint=null,void(this._tempSecondPoint=null));3===this._clickCount&&(this._activeDrawing.setFourthPoint(t),this._clickCount=4,this._drawings.push(this._activeDrawing),this.stopDrawing(),this._finishDrawingCallback&&this._finishDrawingCallback())}else null==this._activeDrawing?(this._activeDrawing=new this._drawingType(t,t),this._series.attachPrimitive(this._activeDrawing),this._clickCount=1):(this._activeDrawing.setSecondPoint(t),this._clickCount=2,this._drawings.push(this._activeDrawing),this.stopDrawing(),this._finishDrawingCallback&&this._finishDrawingCallback())}_onMouseMove(e){if(!e)return;for(const t of this._drawings)t._handleHoverInteraction(e);if(!this._isDrawing||!this._activeDrawing)return;const t=O._eventToPoint(e,this._series);if(!t)return;const i=this._drawingType&&this._drawingType.prototype instanceof R;this._drawingType&&this._drawingType.prototype instanceof B?2===this._clickCount?this._activeDrawing.updatePoints(null,null,t,null):3===this._clickCount&&this._activeDrawing.updatePoints(null,null,null,t):i?2===this._clickCount&&this._activeDrawing.updatePoints(null,null,t):this._activeDrawing.setSecondPoint(t)}}class ${_options;constructor(e){this._options=e}}class G extends ${_p1;_p2;_hovered;constructor(e,t,i,s){super(i),this._p1=e,this._p2=t,this._hovered=s}_getScaledCoordinates(e){return null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y?null:{x1:Math.round(this._p1.x*e.horizontalPixelRatio),y1:Math.round(this._p1.y*e.verticalPixelRatio),x2:Math.round(this._p2.x*e.horizontalPixelRatio),y2:Math.round(this._p2.y*e.verticalPixelRatio)}}_drawEndCircle(e,t,i){e.context.fillStyle="#000",e.context.beginPath(),e.context.arc(t,i,9,0,2*Math.PI),e.context.stroke(),e.context.fill()}}class j extends ${_p1;_p2;_p3;_hovered;constructor(e,t,i,s,n){super(s),this._p1=e,this._p2=t,this._p3=i,this._hovered=n}_getScaledCoordinates(e){return null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y||null===this._p3.x||null===this._p3.y?null:{x1:Math.round(this._p1.x*e.horizontalPixelRatio),y1:Math.round(this._p1.y*e.verticalPixelRatio),x2:Math.round(this._p2.x*e.horizontalPixelRatio),y2:Math.round(this._p2.y*e.verticalPixelRatio),x3:Math.round(this._p3.x*e.horizontalPixelRatio),y3:Math.round(this._p3.y*e.verticalPixelRatio)}}_drawEndCircle(e,t,i){e.context.fillStyle="#000",e.context.beginPath(),e.context.arc(t,i,9,0,2*Math.PI),e.context.stroke(),e.context.fill()}}function U(e,i){const s={[t.LineStyle.Solid]:[],[t.LineStyle.Dotted]:[e.lineWidth,e.lineWidth],[t.LineStyle.Dashed]:[2*e.lineWidth,2*e.lineWidth],[t.LineStyle.LargeDashed]:[6*e.lineWidth,6*e.lineWidth],[t.LineStyle.SparseDotted]:[e.lineWidth,4*e.lineWidth]}[i];e.setLineDash(s)}class z extends G{constructor(e,t,i,s){super(e,t,i,s)}draw(e){e.useBitmapCoordinateSpace((e=>{if(null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y)return;const t=e.context,i=this._getScaledCoordinates(e);i&&(t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.beginPath(),t.moveTo(i.x1,i.y1),t.lineTo(i.x2,i.y2),t.stroke(),this._hovered&&(this._drawEndCircle(e,i.x1,i.y1),this._drawEndCircle(e,i.x2,i.y2)))}))}}class H{_source;constructor(e){this._source=e}}class W extends H{_p1={x:null,y:null};_p2={x:null,y:null};_source;constructor(e){super(e),this._source=e}update(){if(!this._source.p1||!this._source.p2)return;const e=this._source.series,t=e.priceToCoordinate(this._source.p1.price),i=e.priceToCoordinate(this._source.p2.price),s=this._getX(this._source.p1),n=this._getX(this._source.p2);this._p1={x:s,y:t},this._p2={x:n,y:i}}_getX(e){return this._source.chart.timeScale().logicalToCoordinate(e.logical)}}class q extends H{_p1={x:null,y:null};_p2={x:null,y:null};_p3={x:null,y:null};_source;constructor(e){super(e),this._source=e}update(){if(!this._source.p1||!this._source.p2||!this._source.p3)return;const e=this._source.series,t=e.priceToCoordinate(this._source.p1.price),i=e.priceToCoordinate(this._source.p2.price),s=e.priceToCoordinate(this._source.p3.price),n=this._getX(this._source.p1),o=this._getX(this._source.p2),r=this._getX(this._source.p3);this._p1={x:n,y:t},this._p2={x:o,y:i},this._p3={x:r,y:s}}_getX(e){return this._source.chart.timeScale().logicalToCoordinate(e.logical)}}class X extends W{constructor(e){super(e)}renderer(){return new z(this._p1,this._p2,this._source._options,this._source.hovered)}}class J extends V{_type="TrendLine";constructor(e,t,i){super(e,t,i),this._paneViews=[new X(this)]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this.requestUpdate(),this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this.requestUpdate(),this._subscribe("mousedown",this._handleMouseDownInteraction),this._unsubscribe("mouseup",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this.p2,e.logical,e.price)}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint;if(!e)return;const t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);Math.abs(e.x-t.x)<10&&Math.abs(e.y-t.y)<10?this._moveToState(N.DRAGGINGP1):Math.abs(e.x-i.x)<10&&Math.abs(e.y-i.y)<10?this._moveToState(N.DRAGGINGP2):this._moveToState(N.DRAGGING)}_mouseIsOverTwoPointDrawing(e,t=4){if(!e.point)return!1;const i=this._paneViews[0]._p1.x,s=this._paneViews[0]._p1.y,n=this._paneViews[0]._p2.x,o=this._paneViews[0]._p2.y;if(!(i&&n&&s&&o))return!1;const r=e.point.x,a=e.point.y;if(r<=Math.min(i,n)-t||r>=Math.max(i,n)+t)return!1;return Math.abs((o-s)*r-(n-i)*a+n*s-o*i)/Math.sqrt((o-s)**2+(n-i)**2)<=t}}class Y extends G{constructor(e,t,i,s){super(e,t,i,s)}draw(e){e.useBitmapCoordinateSpace((e=>{const t=e.context,i=this._getScaledCoordinates(e);if(!i)return;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.fillStyle=this._options.fillColor;const s=Math.min(i.x1,i.x2),n=Math.min(i.y1,i.y2),o=Math.abs(i.x1-i.x2),r=Math.abs(i.y1-i.y2);t.strokeRect(s,n,o,r),t.fillRect(s,n,o,r),this._hovered&&(this._drawEndCircle(e,s,n),this._drawEndCircle(e,s+o,n),this._drawEndCircle(e,s+o,n+r),this._drawEndCircle(e,s,n+r))}))}}class K extends W{constructor(e){super(e)}renderer(){return new Y(this._p1,this._p2,this._source._options,this._source.hovered)}}const Q={fillEnabled:!0,fillColor:"rgba(255, 255, 255, 0.2)",...L};class Z extends V{_type="Box";constructor(e,t,i){super(e,t,i),this._options={...Q,...i},this._paneViews=[new K(this)]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._unsubscribe("mouseup",this._handleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGINGP3:case N.DRAGGINGP4:case N.DRAGGING:document.body.style.cursor="grabbing",document.body.addEventListener("mouseup",this._handleMouseUpInteraction),this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this.p2,e.logical,e.price),this._state!=N.DRAGGING&&(this._state==N.DRAGGINGP3&&(this._addDiffToPoint(this.p1,e.logical,0),this._addDiffToPoint(this.p2,0,e.price)),this._state==N.DRAGGINGP4&&(this._addDiffToPoint(this.p1,0,e.price),this._addDiffToPoint(this.p2,e.logical,0)))}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint,t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);const s=10;Math.abs(e.x-t.x)l-d&&rc-d&&a{if(null==this._point.y)return;const t=e.context,i=Math.round(this._point.y*e.verticalPixelRatio),s=this._point.x?this._point.x*e.horizontalPixelRatio:0;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.beginPath(),t.moveTo(s,i),t.lineTo(e.bitmapSize.width,i),t.stroke()}))}}class te extends H{_source;_point={x:null,y:null};constructor(e){super(e),this._source=e}update(){const e=this._source._point,t=this._source.chart.timeScale(),i=this._source.series;"RayLine"==this._source._type&&(this._point.x=e.time?t.timeToCoordinate(e.time):t.logicalToCoordinate(e.logical)),this._point.y=i.priceToCoordinate(e.price)}renderer(){return new ee(this._point,this._source._options)}}class ie{_source;_y=null;_price=null;constructor(e){this._source=e}update(){if(!this._source.series||!this._source._point)return;this._y=this._source.series.priceToCoordinate(this._source._point.price);const e=this._source.series.options().priceFormat.precision;this._price=this._source._point.price.toFixed(e).toString()}visible(){return!0}tickVisible(){return!0}coordinate(){return this._y??0}text(){return this._source._options.text||this._price||""}textColor(){return"white"}backColor(){return this._source._options.lineColor}}class se extends O{_type="HorizontalLine";_paneViews;_point;_callbackName;_priceAxisViews;_startDragPoint=null;constructor(e,t,i=null){super(t),this._point=e,this._point.time=null,this._paneViews=[new te(this)],this._priceAxisViews=[new ie(this)],this._callbackName=i}get points(){return[this._point]}updatePoints(...e){for(const t of e)t&&(this._point.price=t.price);this.requestUpdate()}updateAllViews(){this._paneViews.forEach((e=>e.update())),this._priceAxisViews.forEach((e=>e.update()))}priceAxisViews(){return this._priceAxisViews}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._unsubscribe("mouseup",this._childHandleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._childHandleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._addDiffToPoint(this._point,0,e.price),this.requestUpdate()}_mouseIsOverDrawing(e,t=4){if(!e.point)return!1;const i=this.series.priceToCoordinate(this._point.price);return!!i&&Math.abs(i-e.point.y){this._handleMouseUpInteraction(),this._callbackName&&window.callbackFunction(`${this._callbackName}_~_${this._point.price.toFixed(8)}`)}}class ne extends se{_type="RayLine";constructor(e,t){super({...e},t),this._point.time=e.time}updatePoints(...e){for(const t of e)t&&(this._point=t);this.requestUpdate()}_onDrag(e){this._addDiffToPoint(this._point,e.logical,e.price),this.requestUpdate()}_mouseIsOverTwoPointDrawing(e,t=4){if(!e.point)return!1;const i=this.series.priceToCoordinate(this._point.price),s=this._point.time?this.chart.timeScale().timeToCoordinate(this._point.time):null;return!(!i||!s)&&(Math.abs(i-e.point.y)s-t)}}class oe extends ${_point={x:null,y:null};constructor(e,t){super(t),this._point=e}draw(e){e.useBitmapCoordinateSpace((e=>{if(null==this._point.x)return;const t=e.context,i=this._point.x*e.horizontalPixelRatio;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.beginPath(),t.moveTo(i,0),t.lineTo(i,e.bitmapSize.height),t.stroke()}))}}class re extends H{_source;_point={x:null,y:null};constructor(e){super(e),this._source=e}update(){const e=this._source._point,t=this._source.chart.timeScale(),i=this._source.series;this._point.x=e.time?t.timeToCoordinate(e.time):t.logicalToCoordinate(e.logical),this._point.y=i.priceToCoordinate(e.price)}renderer(){return new oe(this._point,this._source._options)}}class ae{_source;_x=null;constructor(e){this._source=e}update(){if(!this._source.chart||!this._source._point)return;const e=this._source._point,t=this._source.chart.timeScale();this._x=e.time?t.timeToCoordinate(e.time):t.logicalToCoordinate(e.logical)}visible(){return!!this._source._options.text}tickVisible(){return!0}coordinate(){return this._x??0}text(){return this._source._options.text||""}textColor(){return"white"}backColor(){return this._source._options.lineColor}}class le extends O{_type="VerticalLine";_paneViews;_timeAxisViews;_point;_callbackName;_startDragPoint=null;constructor(e,t,i=null){super(t),this._point=e,this._paneViews=[new re(this)],this._callbackName=i,this._timeAxisViews=[new ae(this)]}updateAllViews(){this._paneViews.forEach((e=>e.update())),this._timeAxisViews.forEach((e=>e.update()))}timeAxisViews(){return this._timeAxisViews}updatePoints(...e){for(const t of e)t&&(!t.time&&t.logical&&(t.time=this.series.dataByIndex(t.logical)?.time||null),this._point=t);this.requestUpdate()}get points(){return[this._point]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._unsubscribe("mouseup",this._childHandleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._childHandleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._addDiffToPoint(this._point,e.logical,0),this.requestUpdate()}_mouseIsOverDrawing(e,t=4){if(!e.point)return!1;const i=this.chart.timeScale();let s;return s=this._point.time?i.timeToCoordinate(this._point.time):i.logicalToCoordinate(this._point.logical),!!s&&Math.abs(s-e.point.x){this._handleMouseUpInteraction(),this._callbackName&&window.callbackFunction(`${this._callbackName}_~_${this._point.price.toFixed(8)}`)}}class ce extends j{options;variant;width;constructor(e,t,i,s,n,o){super(e,t,i,s,n),this.options=s,this.variant=s.variant??"standard",this.width=o}draw(e){e.useBitmapCoordinateSpace((e=>{if(null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y||null===this._p3.x||null===this._p3.y)return;const i=e.context,s=this._getScaledCoordinates(e);if(!s)return;const{x1:n,y1:o,x2:r,y2:a,x3:l,y3:c}=s,h=(r+l)/2,p=(a+c)/2;let d,u,m,g,f,y;const b=this.width-Math.max(this._p1.x,this._p2.x);if("inside"===this.variant){d=h,u=p;const e=(n+r)/2-l,t=(o+a)/2-c;let i=Math.atan2(t,e);Math.cos(i)<0&&(i+=Math.PI),m=d+b*Math.cos(i),g=u+b*Math.sin(i)}else{const{anchorX:e,anchorY:t}=this._computeAnchorPoint(this.variant,n,o,r,a),i=this._lineIntersection(n,o,r,a,h,p,e,t);i?[d,u]=i:(d=n,u=o);const s=h-d;m=d+b,g=u+(Math.abs(s)>1e-9?(p-u)/s:0)*b}if(f=m-d,y=g-u,i.lineWidth=this.options.width,i.strokeStyle=this.options.lineColor,U(i,this.options.lineStyle),U(i,t.LineStyle.Solid),i.beginPath(),i.moveTo(r,a),i.lineTo(l,c),i.stroke(),U(i,this.options.lineStyle),i.beginPath(),i.moveTo(n,o),i.lineTo(r,a),i.stroke(),i.beginPath(),i.moveTo(d,u),i.lineTo(m,g),i.stroke(),i.beginPath(),i.moveTo(r,a),i.lineTo(r+f,a+y),i.stroke(),i.beginPath(),i.moveTo(l,c),i.lineTo(l+f,c+y),i.stroke(),this.options.forkLines&&this.options.forkLines.length>0){const e=this.options.forkLines;for(let t=0;tMath.max(i,n,r)+t)return!1;const h=this._distanceFromSegment(i,s,n,o,l,c),p=this._distanceFromSegment(n,o,r,a,l,c),d=this._distanceFromSegment(i,s,r,a,l,c);return h<=t||p<=t||d<=t}_distanceFromSegment(e,t,i,s,n,o){const r=i-e,a=s-t,l=r*r+a*a;let c,h,p=0!==l?((n-e)*r+(o-t)*a)/l:-1;p<0?(c=e,h=t):p>1?(c=i,h=s):(c=e+p*r,h=t+p*a);const d=n-c,u=o-h;return Math.sqrt(d*d+u*u)}fromJSON(e){if(e.options){const t=e.options;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const i=e;this.applyOptions({[i]:t[i]})}}}toJSON(){return{options:this._options}}title="PitchFork"}class ue extends G{series;chart;constructor(e,t,i,s,n,o){super(i,s,n,o),this.series=e,this.chart=t}draw(e){e.useBitmapCoordinateSpace((e=>{const t=e.context,i=this._getScaledCoordinates(e);if(!i)return;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.fillStyle=this._options.fillColor;const s=Math.min(i.x1,i.x2),n=Math.min(i.y1,i.y2),o=Math.abs(i.x1-i.x2),r=Math.abs(i.y1-i.y2);if(t.strokeRect(s,n,o,r),t.fillRect(s,n,o,r),this._p1&&this._p2&&void 0!==this._p1.y&&void 0!==this._p2.y&&void 0!==this._p1.x&&void 0!==this._p2.x){const e=this.series.coordinateToPrice(this._p1.y),i=this.series.coordinateToPrice(this._p2.y),a=this.chart.timeScale().coordinateToTime(this._p1.x),l=this.chart.timeScale().coordinateToTime(this._p2.x),c=(i-e)/e*100;console.log(e),console.log(i);const h=`Price: ${c.toFixed(2)}%`,p=Math.abs(l-a),d=`Time: ${this._formatTimeDifference(p)}`;t.font="12px Arial",t.fillStyle="white",t.textAlign="center",t.textBaseline="middle";const u=s+o/2,m=n-10,g=n+r+10;t.fillText(h,u,m),t.fillText(d,u,g)}this._hovered&&(this._drawEndCircle(e,s,n),this._drawEndCircle(e,s+o,n),this._drawEndCircle(e,s+o,n+r),this._drawEndCircle(e,s,n+r))}))}_formatTimeDifference(e){const t=Math.floor(e),i=Math.floor(t/60),s=Math.floor(i/60),n=Math.floor(s/24);return n>0?`${n}d ${s%24}h`:s>0?`${s}h ${i%60}m`:i>0?`${i}m ${t%60}s`:`${t}s`}}class me extends W{constructor(e){super(e)}renderer(){return new ue(this._source._series,this._source._chart,this._p1,this._p2,this._source._options,this._source.hovered)}}const ge={fillEnabled:!0,fillColor:"rgba(255, 255, 255, 0.0)",lineColor:"#1E80F0",lineStyle:t.LineStyle.Solid,width:1};class fe extends V{_type="Measure";constructor(e,t,i){super(e,t,i),this._options={...ge,...i},this._paneViews=[new me(this)]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._unsubscribe("mouseup",this._handleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGINGP3:case N.DRAGGINGP4:case N.DRAGGING:document.body.style.cursor="grabbing",document.body.addEventListener("mouseup",this._handleMouseUpInteraction),this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this.p2,e.logical,e.price),this._state!=N.DRAGGING&&(this._state==N.DRAGGINGP3&&(this._addDiffToPoint(this.p1,e.logical,0),this._addDiffToPoint(this.p2,0,e.price)),this._state==N.DRAGGINGP4&&(this._addDiffToPoint(this.p1,0,e.price),this._addDiffToPoint(this.p2,e.logical,0)))}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint,t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);const s=10;Math.abs(e.x-t.x)l-d&&rc-d&&a',horz:'',ray:'',box:'',vert:'',pitch:'',measure:''};div;activeIcon=null;buttons=[];_commandFunctions;_handlerID;_drawingTool;constructor(e,t,i,s,n=!0){this.handler=e,this._handlerID=this.handler.id,this._commandFunctions=s,this._drawingTool=new F(t,i,(()=>this.removeActiveAndSave())),s.push((e=>{if((e.metaKey||e.ctrlKey)&&"KeyZ"===e.code){const e=this._drawingTool.drawings.pop();return e&&this._drawingTool.delete(e),!0}return!1}));const o=n?"toggle":"static";this.div=this._createToolBox(e,o),e.ContextMenu.setupDrawingTools(this.saveDrawings,this._drawingTool),s.push((e=>{if(this.handler.id!==window.handlerInFocus)return!1;if(e.altKey)for(const[t,i]of Object.keys(ye.ICONS).entries()){const i=["M","T","H","R","B","V","P"][t];if(e.code===`Key${i}`)return e.preventDefault(),this.buttons[t].click(),!0}return!1}))}_createToolBox(e,t){return"toggle"===t?this._makeToggleToolBox():this._makeToolBox()}_makeToolBox(){const e=document.createElement("div");return e.classList.add("toolbox"),this._registerIcon(e,"measure"),this._registerIcon(e,"trend"),this._registerIcon(e,"horz"),this._registerIcon(e,"ray"),this._registerIcon(e,"box"),this._registerIcon(e,"vert",!0),this._registerIcon(e,"pitch"),e}_makeToggleToolBox(){const e=document.createElement("div");e.classList.add("flyout-toolbox"),Object.assign(e.style,{position:"absolute",top:"0",left:"50%",transform:"translateX(-50%)",overflow:"hidden",transition:"height 0.3s ease",zIndex:"1000"});const t=document.createElement("div");t.classList.add("toolbox-content"),Object.assign(t.style,{display:"none",inlineFlex:"row",padding:"5px",backgroundColor:"rgba(0,0,0,0.5)"}),this._registerIcon(t,"measure"),this._registerIcon(t,"trend"),this._registerIcon(t,"horz"),this._registerIcon(t,"ray"),this._registerIcon(t,"box"),this._registerIcon(t,"vert",!0),this._registerIcon(t,"pitch"),e.appendChild(t);const i=document.createElement("div");i.textContent="▼",Object.assign(i.style,{width:"15px",height:"15px",textAlign:"center",lineHeight:"15px",cursor:"pointer",color:"#fff",background:"transparent"});let s=!1;return e.style.height="15px",i.onclick=()=>{if(s=!s,s){t.style.display="inline-flex";const s=t.scrollHeight;e.style.height=`${s+15}px`,i.textContent="▲"}else t.style.display="none",e.style.height="15px",i.textContent="▼"},e.appendChild(i),e}static TOOL_CLASSES={measure:fe,trend:J,horz:se,ray:ne,box:Z,vert:le,pitch:de};_registerIcon(e,t,i=!1){const s="http://www.w3.org/2000/svg",n=document.createElement("div");n.classList.add("toolbox-button");const o=document.createElementNS(s,"svg");o.setAttribute("width","28"),o.setAttribute("height","28"),o.setAttribute("viewBox","0 0 28 28");const r=document.createElementNS(s,"g");r.innerHTML=ye.ICONS[t],o.appendChild(r),i&&(o.style.transform="rotate(90deg)",o.style.transformBox="fill-box",o.style.transformOrigin="center"),n.appendChild(o),e.appendChild(n);const a={div:n,group:r,type:ye.TOOL_CLASSES[t]};n.addEventListener("click",(()=>this._onIconClick(a))),this.buttons.push(n)}_onIconClick(e){if(this.activeIcon&&(this.activeIcon.div.classList.remove("active-toolbox-button"),this._drawingTool.stopDrawing(),this.activeIcon===e))return this.activeIcon=null,void window.setCursor("default");this.activeIcon=e,e.div.classList.add("active-toolbox-button"),window.setCursor("crosshair"),this._drawingTool.beginDrawing(e.type)}removeActiveAndSave(){window.setCursor("default"),this.activeIcon&&(this.activeIcon.div.classList.remove("active-toolbox-button"),this.activeIcon=null),this.saveDrawings()}addNewDrawing(e){this._drawingTool.addNewDrawing(e)}clearDrawings(){this._drawingTool.clearDrawings()}saveDrawings=()=>{const e=[];for(const t of this._drawingTool.drawings)e.push({type:t._type,points:t.points,options:t._options});const t=JSON.stringify(e);window.callbackFunction(`save_drawings${this._handlerID}_~_${t}`)};loadDrawings(e){e.forEach((e=>{switch(e.type){case"Box":this._drawingTool.addNewDrawing(new Z(e.points[0],e.points[1],e.options));break;case"TrendLine":this._drawingTool.addNewDrawing(new J(e.points[0],e.points[1],e.options));break;case"HorizontalLine":this._drawingTool.addNewDrawing(new se(e.points[0],e.options));break;case"RayLine":this._drawingTool.addNewDrawing(new ne(e.points[0],e.options));break;case"VerticalLine":this._drawingTool.addNewDrawing(new le(e.points[0],e.options));break;case"PitchFork":this._drawingTool.addNewDrawing(new de(e.points[0],e.points[1],e.points[2],e.options));break;case"Measure":this._drawingTool.addNewDrawing(new fe(e.points[0],e.points[1],e.options))}}))}}var be=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],ve=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],xe="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲊᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꟍꟐꟑꟓꟕ-Ƛꟲ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",_e={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},we="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",Ce={5:we,"5module":we+" export import",6:we+" const class extends export import super"},Se=/^in(stanceof)?$/,ke=new RegExp("["+xe+"]"),Ee=new RegExp("["+xe+"‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࢗ-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-ᫎᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・]");function Me(e,t){for(var i=65536,s=0;se)return!1;if((i+=t[s+1])>=e)return!0}return!1}function Pe(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&ke.test(String.fromCharCode(e)):!1!==t&&Me(e,ve)))}function Te(e,t){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&Ee.test(String.fromCharCode(e)):!1!==t&&(Me(e,ve)||Me(e,be)))))}var Ie=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function Ae(e,t){return new Ie(e,{beforeExpr:!0,binop:t})}var De={beforeExpr:!0},Le={startsExpr:!0},Ne={};function Oe(e,t){return void 0===t&&(t={}),t.keyword=e,Ne[e]=new Ie(e,t)}var Ve={num:new Ie("num",Le),regexp:new Ie("regexp",Le),string:new Ie("string",Le),name:new Ie("name",Le),privateId:new Ie("privateId",Le),eof:new Ie("eof"),bracketL:new Ie("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new Ie("]"),braceL:new Ie("{",{beforeExpr:!0,startsExpr:!0}),braceR:new Ie("}"),parenL:new Ie("(",{beforeExpr:!0,startsExpr:!0}),parenR:new Ie(")"),comma:new Ie(",",De),semi:new Ie(";",De),colon:new Ie(":",De),dot:new Ie("."),question:new Ie("?",De),questionDot:new Ie("?."),arrow:new Ie("=>",De),template:new Ie("template"),invalidTemplate:new Ie("invalidTemplate"),ellipsis:new Ie("...",De),backQuote:new Ie("`",Le),dollarBraceL:new Ie("${",{beforeExpr:!0,startsExpr:!0}),eq:new Ie("=",{beforeExpr:!0,isAssign:!0}),assign:new Ie("_=",{beforeExpr:!0,isAssign:!0}),incDec:new Ie("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new Ie("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:Ae("||",1),logicalAND:Ae("&&",2),bitwiseOR:Ae("|",3),bitwiseXOR:Ae("^",4),bitwiseAND:Ae("&",5),equality:Ae("==/!=/===/!==",6),relational:Ae("/<=/>=",7),bitShift:Ae("<>/>>>",8),plusMin:new Ie("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:Ae("%",10),star:Ae("*",10),slash:Ae("/",10),starstar:new Ie("**",{beforeExpr:!0}),coalesce:Ae("??",1),_break:Oe("break"),_case:Oe("case",De),_catch:Oe("catch"),_continue:Oe("continue"),_debugger:Oe("debugger"),_default:Oe("default",De),_do:Oe("do",{isLoop:!0,beforeExpr:!0}),_else:Oe("else",De),_finally:Oe("finally"),_for:Oe("for",{isLoop:!0}),_function:Oe("function",Le),_if:Oe("if"),_return:Oe("return",De),_switch:Oe("switch"),_throw:Oe("throw",De),_try:Oe("try"),_var:Oe("var"),_const:Oe("const"),_while:Oe("while",{isLoop:!0}),_with:Oe("with"),_new:Oe("new",{beforeExpr:!0,startsExpr:!0}),_this:Oe("this",Le),_super:Oe("super",Le),_class:Oe("class",Le),_extends:Oe("extends",De),_export:Oe("export"),_import:Oe("import",Le),_null:Oe("null",Le),_true:Oe("true",Le),_false:Oe("false",Le),_in:Oe("in",{beforeExpr:!0,binop:7}),_instanceof:Oe("instanceof",{beforeExpr:!0,binop:7}),_typeof:Oe("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:Oe("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:Oe("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},Re=/\r\n?|\n|\u2028|\u2029/,Be=new RegExp(Re.source,"g");function Fe(e){return 10===e||13===e||8232===e||8233===e}function $e(e,t,i){void 0===i&&(i=e.length);for(var s=t;s>10),56320+(1023&e)))}var Ke=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,Qe=function(e,t){this.line=e,this.column=t};Qe.prototype.offset=function(e){return new Qe(this.line,this.column+e)};var Ze=function(e,t,i){this.start=t,this.end=i,null!==e.sourceFile&&(this.source=e.sourceFile)};function et(e,t){for(var i=1,s=0;;){var n=$e(e,s,t);if(n<0)return new Qe(i,t-s);++i,s=n}}var tt={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},it=!1;function st(e){var t={};for(var i in tt)t[i]=e&&We(e,i)?e[i]:tt[i];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!it&&"object"==typeof console&&console.warn&&(it=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),qe(t.onToken)){var s=t.onToken;t.onToken=function(e){return s.push(e)}}return qe(t.onComment)&&(t.onComment=function(e,t){return function(i,s,n,o,r,a){var l={type:i?"Block":"Line",value:s,start:n,end:o};e.locations&&(l.loc=new Ze(this,r,a)),e.ranges&&(l.range=[n,o]),t.push(l)}}(t,t.onComment)),t}var nt=256;function ot(e,t){return 2|(e?4:0)|(t?8:0)}var rt=function(e,t,i){this.options=e=st(e),this.sourceFile=e.sourceFile,this.keywords=Je(Ce[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var s="";!0!==e.allowReserved&&(s=_e[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(s+=" await")),this.reservedWords=Je(s);var n=(s?s+" ":"")+_e.strict;this.reservedWordsStrict=Je(n),this.reservedWordsStrictBind=Je(n+" "+_e.strictBind),this.input=String(t),this.containsEsc=!1,i?(this.pos=i,this.lineStart=this.input.lastIndexOf("\n",i-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(Re).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=Ve.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},at={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};rt.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},at.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},at.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},at.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},at.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&nt)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},at.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,i=e.inClassFieldInit;return(64&t)>0||i||this.options.allowSuperOutsideMethod},at.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},at.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},at.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,i=e.inClassFieldInit;return(258&t)>0||i},at.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&nt)>0},rt.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var i=this,s=0;s=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(s+1))}e+=t[0].length,je.lastIndex=e,e+=je.exec(this.input)[0].length,";"===this.input[e]&&e++}},lt.eat=function(e){return this.type===e&&(this.next(),!0)},lt.isContextual=function(e){return this.type===Ve.name&&this.value===e&&!this.containsEsc},lt.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},lt.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},lt.canInsertSemicolon=function(){return this.type===Ve.eof||this.type===Ve.braceR||Re.test(this.input.slice(this.lastTokEnd,this.start))},lt.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},lt.semicolon=function(){this.eat(Ve.semi)||this.insertSemicolon()||this.unexpected()},lt.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},lt.expect=function(e){this.eat(e)||this.unexpected()},lt.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var ht=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};lt.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var i=t?e.parenthesizedAssign:e.parenthesizedBind;i>-1&&this.raiseRecoverable(i,t?"Assigning to rvalue":"Parenthesized pattern")}},lt.checkExpressionErrors=function(e,t){if(!e)return!1;var i=e.shorthandAssign,s=e.doubleProto;if(!t)return i>=0||s>=0;i>=0&&this.raise(i,"Shorthand property assignments are valid only in destructuring patterns"),s>=0&&this.raiseRecoverable(s,"Redefinition of __proto__ property")},lt.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&s<56320)return!0;if(Pe(s,!0)){for(var n=i+1;Te(s=this.input.charCodeAt(n),!0);)++n;if(92===s||s>55295&&s<56320)return!0;var o=this.input.slice(i,n);if(!Se.test(o))return!0}return!1},pt.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;je.lastIndex=this.pos;var e,t=je.exec(this.input),i=this.pos+t[0].length;return!(Re.test(this.input.slice(this.pos,i))||"function"!==this.input.slice(i,i+8)||i+8!==this.input.length&&(Te(e=this.input.charCodeAt(i+8))||e>55295&&e<56320))},pt.parseStatement=function(e,t,i){var s,n=this.type,o=this.startNode();switch(this.isLet(e)&&(n=Ve._var,s="let"),n){case Ve._break:case Ve._continue:return this.parseBreakContinueStatement(o,n.keyword);case Ve._debugger:return this.parseDebuggerStatement(o);case Ve._do:return this.parseDoStatement(o);case Ve._for:return this.parseForStatement(o);case Ve._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(o,!1,!e);case Ve._class:return e&&this.unexpected(),this.parseClass(o,!0);case Ve._if:return this.parseIfStatement(o);case Ve._return:return this.parseReturnStatement(o);case Ve._switch:return this.parseSwitchStatement(o);case Ve._throw:return this.parseThrowStatement(o);case Ve._try:return this.parseTryStatement(o);case Ve._const:case Ve._var:return s=s||this.value,e&&"var"!==s&&this.unexpected(),this.parseVarStatement(o,s);case Ve._while:return this.parseWhileStatement(o);case Ve._with:return this.parseWithStatement(o);case Ve.braceL:return this.parseBlock(!0,o);case Ve.semi:return this.parseEmptyStatement(o);case Ve._export:case Ve._import:if(this.options.ecmaVersion>10&&n===Ve._import){je.lastIndex=this.pos;var r=je.exec(this.input),a=this.pos+r[0].length,l=this.input.charCodeAt(a);if(40===l||46===l)return this.parseExpressionStatement(o,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===Ve._import?this.parseImport(o):this.parseExport(o,i);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(o,!0,!e);var c=this.value,h=this.parseExpression();return n===Ve.name&&"Identifier"===h.type&&this.eat(Ve.colon)?this.parseLabeledStatement(o,c,h,e):this.parseExpressionStatement(o,h)}},pt.parseBreakContinueStatement=function(e,t){var i="break"===t;this.next(),this.eat(Ve.semi)||this.insertSemicolon()?e.label=null:this.type!==Ve.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var s=0;s=6?this.eat(Ve.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},pt.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(dt),this.enterScope(0),this.expect(Ve.parenL),this.type===Ve.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var i=this.isLet();if(this.type===Ve._var||this.type===Ve._const||i){var s=this.startNode(),n=i?"let":this.value;return this.next(),this.parseVar(s,!0,n),this.finishNode(s,"VariableDeclaration"),(this.type===Ve._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===s.declarations.length?(this.options.ecmaVersion>=9&&(this.type===Ve._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,s)):(t>-1&&this.unexpected(t),this.parseFor(e,s))}var o=this.isContextual("let"),r=!1,a=this.containsEsc,l=new ht,c=this.start,h=t>-1?this.parseExprSubscripts(l,"await"):this.parseExpression(!0,l);return this.type===Ve._in||(r=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===Ve._in&&this.unexpected(t),e.await=!0):r&&this.options.ecmaVersion>=8&&(h.start!==c||a||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),o&&r&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,l),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(l,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},pt.parseFunctionStatement=function(e,t,i){return this.next(),this.parseFunction(e,gt|(i?0:ft),!1,t)},pt.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(Ve._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},pt.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(Ve.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},pt.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(Ve.braceL),this.labels.push(ut),this.enterScope(0);for(var i=!1;this.type!==Ve.braceR;)if(this.type===Ve._case||this.type===Ve._default){var s=this.type===Ve._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),s?t.test=this.parseExpression():(i&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),i=!0,t.test=null),this.expect(Ve.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},pt.parseThrowStatement=function(e){return this.next(),Re.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var mt=[];pt.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(Ve.parenR),e},pt.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===Ve._catch){var t=this.startNode();this.next(),this.eat(Ve.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(Ve._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},pt.parseVarStatement=function(e,t,i){return this.next(),this.parseVar(e,!1,t,i),this.semicolon(),this.finishNode(e,"VariableDeclaration")},pt.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(dt),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},pt.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},pt.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},pt.parseLabeledStatement=function(e,t,i,s){for(var n=0,o=this.labels;n=0;a--){var l=this.labels[a];if(l.statementStart!==e.start)break;l.statementStart=this.start,l.kind=r}return this.labels.push({name:t,kind:r,statementStart:this.start}),e.body=this.parseStatement(s?-1===s.indexOf("label")?s+"label":s:"label"),this.labels.pop(),e.label=i,this.finishNode(e,"LabeledStatement")},pt.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},pt.parseBlock=function(e,t,i){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(Ve.braceL),e&&this.enterScope(0);this.type!==Ve.braceR;){var s=this.parseStatement(null);t.body.push(s)}return i&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},pt.parseFor=function(e,t){return e.init=t,this.expect(Ve.semi),e.test=this.type===Ve.semi?null:this.parseExpression(),this.expect(Ve.semi),e.update=this.type===Ve.parenR?null:this.parseExpression(),this.expect(Ve.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},pt.parseForIn=function(e,t){var i=this.type===Ve._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!i||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(i?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=i?this.parseExpression():this.parseMaybeAssign(),this.expect(Ve.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,i?"ForInStatement":"ForOfStatement")},pt.parseVar=function(e,t,i,s){for(e.declarations=[],e.kind=i;;){var n=this.startNode();if(this.parseVarId(n,i),this.eat(Ve.eq)?n.init=this.parseMaybeAssign(t):s||"const"!==i||this.type===Ve._in||this.options.ecmaVersion>=6&&this.isContextual("of")?s||"Identifier"===n.id.type||t&&(this.type===Ve._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(Ve.comma))break}return e},pt.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var gt=1,ft=2;function yt(e,t){var i=t.key.name,s=e[i],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===s&&"iset"===n||"iset"===s&&"iget"===n||"sget"===s&&"sset"===n||"sset"===s&&"sget"===n?(e[i]="true",!1):!!s||(e[i]=n,!1)}function bt(e,t){var i=e.computed,s=e.key;return!i&&("Identifier"===s.type&&s.name===t||"Literal"===s.type&&s.value===t)}pt.parseFunction=function(e,t,i,s,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!s)&&(this.type===Ve.star&&t&ft&&this.unexpected(),e.generator=this.eat(Ve.star)),this.options.ecmaVersion>=8&&(e.async=!!s),t>&&(e.id=4&t&&this.type!==Ve.name?null:this.parseIdent(),!e.id||t&ft||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var o=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(ot(e.async,e.generator)),t>||(e.id=this.type===Ve.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,i,!1,n),this.yieldPos=o,this.awaitPos=r,this.awaitIdentPos=a,this.finishNode(e,t>?"FunctionDeclaration":"FunctionExpression")},pt.parseFunctionParams=function(e){this.expect(Ve.parenL),e.params=this.parseBindingList(Ve.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},pt.parseClass=function(e,t){this.next();var i=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var s=this.enterClassBody(),n=this.startNode(),o=!1;for(n.body=[],this.expect(Ve.braceL);this.type!==Ve.braceR;){var r=this.parseClassElement(null!==e.superClass);r&&(n.body.push(r),"MethodDefinition"===r.type&&"constructor"===r.kind?(o&&this.raiseRecoverable(r.start,"Duplicate constructor in the same class"),o=!0):r.key&&"PrivateIdentifier"===r.key.type&&yt(s,r)&&this.raiseRecoverable(r.key.start,"Identifier '#"+r.key.name+"' has already been declared"))}return this.strict=i,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},pt.parseClassElement=function(e){if(this.eat(Ve.semi))return null;var t=this.options.ecmaVersion,i=this.startNode(),s="",n=!1,o=!1,r="method",a=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(Ve.braceL))return this.parseClassStaticBlock(i),i;this.isClassElementNameStart()||this.type===Ve.star?a=!0:s="static"}if(i.static=a,!s&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==Ve.star||this.canInsertSemicolon()?s="async":o=!0),!s&&(t>=9||!o)&&this.eat(Ve.star)&&(n=!0),!s&&!o&&!n){var l=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?r=l:s=l)}if(s?(i.computed=!1,i.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),i.key.name=s,this.finishNode(i.key,"Identifier")):this.parseClassElementName(i),t<13||this.type===Ve.parenL||"method"!==r||n||o){var c=!i.static&&bt(i,"constructor"),h=c&&e;c&&"method"!==r&&this.raise(i.key.start,"Constructor can't have get/set modifier"),i.kind=c?"constructor":r,this.parseClassMethod(i,n,o,h)}else this.parseClassField(i);return i},pt.isClassElementNameStart=function(){return this.type===Ve.name||this.type===Ve.privateId||this.type===Ve.num||this.type===Ve.string||this.type===Ve.bracketL||this.type.keyword},pt.parseClassElementName=function(e){this.type===Ve.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},pt.parseClassMethod=function(e,t,i,s){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),i&&this.raise(n.start,"Constructor can't be an async method")):e.static&&bt(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var o=e.value=this.parseMethod(t,i,s);return"get"===e.kind&&0!==o.params.length&&this.raiseRecoverable(o.start,"getter should have no params"),"set"===e.kind&&1!==o.params.length&&this.raiseRecoverable(o.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===o.params[0].type&&this.raiseRecoverable(o.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},pt.parseClassField=function(e){if(bt(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&bt(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(Ve.eq)){var t=this.currentThisScope(),i=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=i}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},pt.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==Ve.braceR;){var i=this.parseStatement(null);e.body.push(i)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},pt.parseClassId=function(e,t){this.type===Ve.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},pt.parseClassSuper=function(e){e.superClass=this.eat(Ve._extends)?this.parseExprSubscripts(null,!1):null},pt.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},pt.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,i=e.used;if(this.options.checkPrivateFields)for(var s=this.privateNameStack.length,n=0===s?null:this.privateNameStack[s-1],o=0;o=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==Ve.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},pt.parseExport=function(e,t){if(this.next(),this.eat(Ve.star))return this.parseExportAllDeclaration(e,t);if(this.eat(Ve._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==Ve.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var i=0,s=e.specifiers;i=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},pt.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},pt.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},pt.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},pt.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===Ve.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(Ve.comma)))return e;if(this.type===Ve.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(Ve.braceL);!this.eat(Ve.braceR);){if(t)t=!1;else if(this.expect(Ve.comma),this.afterTrailingComma(Ve.braceR))break;e.push(this.parseImportSpecifier())}return e},pt.parseWithClause=function(){var e=[];if(!this.eat(Ve._with))return e;this.expect(Ve.braceL);for(var t={},i=!0;!this.eat(Ve.braceR);){if(i)i=!1;else if(this.expect(Ve.comma),this.afterTrailingComma(Ve.braceR))break;var s=this.parseImportAttribute(),n="Identifier"===s.key.type?s.key.name:s.key.value;We(t,n)&&this.raiseRecoverable(s.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(s)}return e},pt.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===Ve.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(Ve.colon),this.type!==Ve.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},pt.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===Ve.string){var e=this.parseLiteral(this.value);return Ke.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},pt.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var vt=rt.prototype;vt.toAssignable=function(e,t,i){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",i&&this.checkPatternErrors(i,!0);for(var s=0,n=e.properties;s=8&&!a&&"async"===l.name&&!this.canInsertSemicolon()&&this.eat(Ve._function))return this.overrideContext(_t.f_expr),this.parseFunction(this.startNodeAt(o,r),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(Ve.arrow))return this.parseArrowExpression(this.startNodeAt(o,r),[l],!1,t);if(this.options.ecmaVersion>=8&&"async"===l.name&&this.type===Ve.name&&!a&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return l=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(Ve.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(o,r),[l],!0,t)}return l;case Ve.regexp:var c=this.value;return(s=this.parseLiteral(c.value)).regex={pattern:c.pattern,flags:c.flags},s;case Ve.num:case Ve.string:return this.parseLiteral(this.value);case Ve._null:case Ve._true:case Ve._false:return(s=this.startNode()).value=this.type===Ve._null?null:this.type===Ve._true,s.raw=this.type.keyword,this.next(),this.finishNode(s,"Literal");case Ve.parenL:var h=this.start,p=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(p)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),p;case Ve.bracketL:return s=this.startNode(),this.next(),s.elements=this.parseExprList(Ve.bracketR,!0,!0,e),this.finishNode(s,"ArrayExpression");case Ve.braceL:return this.overrideContext(_t.b_expr),this.parseObj(!1,e);case Ve._function:return s=this.startNode(),this.next(),this.parseFunction(s,0);case Ve._class:return this.parseClass(this.startNode(),!1);case Ve._new:return this.parseNew();case Ve.backQuote:return this.parseTemplate();case Ve._import:return this.options.ecmaVersion>=11?this.parseExprImport(i):this.unexpected();default:return this.parseExprAtomDefault()}},Ct.parseExprAtomDefault=function(){this.unexpected()},Ct.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===Ve.parenL&&!e)return this.parseDynamicImport(t);if(this.type===Ve.dot){var i=this.startNodeAt(t.start,t.loc&&t.loc.start);return i.name="import",t.meta=this.finishNode(i,"Identifier"),this.parseImportMeta(t)}this.unexpected()},Ct.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(Ve.parenR)?e.options=null:(this.expect(Ve.comma),this.afterTrailingComma(Ve.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(Ve.parenR)||(this.expect(Ve.comma),this.afterTrailingComma(Ve.parenR)||this.unexpected())));else if(!this.eat(Ve.parenR)){var t=this.start;this.eat(Ve.comma)&&this.eat(Ve.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},Ct.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},Ct.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},Ct.parseParenExpression=function(){this.expect(Ve.parenL);var e=this.parseExpression();return this.expect(Ve.parenR),e},Ct.shouldParseArrow=function(e){return!this.canInsertSemicolon()},Ct.parseParenAndDistinguishExpression=function(e,t){var i,s=this.start,n=this.startLoc,o=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var r,a=this.start,l=this.startLoc,c=[],h=!0,p=!1,d=new ht,u=this.yieldPos,m=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==Ve.parenR;){if(h?h=!1:this.expect(Ve.comma),o&&this.afterTrailingComma(Ve.parenR,!0)){p=!0;break}if(this.type===Ve.ellipsis){r=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===Ve.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}c.push(this.parseMaybeAssign(!1,d,this.parseParenItem))}var g=this.lastTokEnd,f=this.lastTokEndLoc;if(this.expect(Ve.parenR),e&&this.shouldParseArrow(c)&&this.eat(Ve.arrow))return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=u,this.awaitPos=m,this.parseParenArrowList(s,n,c,t);c.length&&!p||this.unexpected(this.lastTokStart),r&&this.unexpected(r),this.checkExpressionErrors(d,!0),this.yieldPos=u||this.yieldPos,this.awaitPos=m||this.awaitPos,c.length>1?((i=this.startNodeAt(a,l)).expressions=c,this.finishNodeAt(i,"SequenceExpression",g,f)):i=c[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(s,n);return y.expression=i,this.finishNode(y,"ParenthesizedExpression")}return i},Ct.parseParenItem=function(e){return e},Ct.parseParenArrowList=function(e,t,i,s){return this.parseArrowExpression(this.startNodeAt(e,t),i,!1,s)};var Et=[];Ct.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===Ve.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var i=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),i&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var s=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),s,n,!0,!1),this.eat(Ve.parenL)?e.arguments=this.parseExprList(Ve.parenR,this.options.ecmaVersion>=8,!1):e.arguments=Et,this.finishNode(e,"NewExpression")},Ct.parseTemplateElement=function(e){var t=e.isTagged,i=this.startNode();return this.type===Ve.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),i.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):i.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),i.tail=this.type===Ve.backQuote,this.finishNode(i,"TemplateElement")},Ct.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var i=this.startNode();this.next(),i.expressions=[];var s=this.parseTemplateElement({isTagged:t});for(i.quasis=[s];!s.tail;)this.type===Ve.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(Ve.dollarBraceL),i.expressions.push(this.parseExpression()),this.expect(Ve.braceR),i.quasis.push(s=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(i,"TemplateLiteral")},Ct.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===Ve.name||this.type===Ve.num||this.type===Ve.string||this.type===Ve.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===Ve.star)&&!Re.test(this.input.slice(this.lastTokEnd,this.start))},Ct.parseObj=function(e,t){var i=this.startNode(),s=!0,n={};for(i.properties=[],this.next();!this.eat(Ve.braceR);){if(s)s=!1;else if(this.expect(Ve.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(Ve.braceR))break;var o=this.parseProperty(e,t);e||this.checkPropClash(o,n,t),i.properties.push(o)}return this.finishNode(i,e?"ObjectPattern":"ObjectExpression")},Ct.parseProperty=function(e,t){var i,s,n,o,r=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(Ve.ellipsis))return e?(r.argument=this.parseIdent(!1),this.type===Ve.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(r,"RestElement")):(r.argument=this.parseMaybeAssign(!1,t),this.type===Ve.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(r,"SpreadElement"));this.options.ecmaVersion>=6&&(r.method=!1,r.shorthand=!1,(e||t)&&(n=this.start,o=this.startLoc),e||(i=this.eat(Ve.star)));var a=this.containsEsc;return this.parsePropertyName(r),!e&&!a&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(r)?(s=!0,i=this.options.ecmaVersion>=9&&this.eat(Ve.star),this.parsePropertyName(r)):s=!1,this.parsePropertyValue(r,e,i,s,n,o,t,a),this.finishNode(r,"Property")},Ct.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var i=e.value.start;"get"===e.kind?this.raiseRecoverable(i,"getter should have no params"):this.raiseRecoverable(i,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},Ct.parsePropertyValue=function(e,t,i,s,n,o,r,a){(i||s)&&this.type===Ve.colon&&this.unexpected(),this.eat(Ve.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,r),e.kind="init"):this.options.ecmaVersion>=6&&this.type===Ve.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(i,s)):t||a||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===Ve.comma||this.type===Ve.braceR||this.type===Ve.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((i||s)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,o,this.copyNode(e.key)):this.type===Ve.eq&&r?(r.shorthandAssign<0&&(r.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,o,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((i||s)&&this.unexpected(),this.parseGetterSetter(e))},Ct.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(Ve.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(Ve.bracketR),e.key;e.computed=!1}return e.key=this.type===Ve.num||this.type===Ve.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},Ct.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},Ct.parseMethod=function(e,t,i){var s=this.startNode(),n=this.yieldPos,o=this.awaitPos,r=this.awaitIdentPos;return this.initFunction(s),this.options.ecmaVersion>=6&&(s.generator=e),this.options.ecmaVersion>=8&&(s.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|ot(t,s.generator)|(i?128:0)),this.expect(Ve.parenL),s.params=this.parseBindingList(Ve.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(s,!1,!0,!1),this.yieldPos=n,this.awaitPos=o,this.awaitIdentPos=r,this.finishNode(s,"FunctionExpression")},Ct.parseArrowExpression=function(e,t,i,s){var n=this.yieldPos,o=this.awaitPos,r=this.awaitIdentPos;return this.enterScope(16|ot(i,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!i),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,s),this.yieldPos=n,this.awaitPos=o,this.awaitIdentPos=r,this.finishNode(e,"ArrowFunctionExpression")},Ct.parseFunctionBody=function(e,t,i,s){var n=t&&this.type!==Ve.braceL,o=this.strict,r=!1;if(n)e.body=this.parseMaybeAssign(s),e.expression=!0,this.checkParams(e,!1);else{var a=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);o&&!a||(r=this.strictDirective(this.end))&&a&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var l=this.labels;this.labels=[],r&&(this.strict=!0),this.checkParams(e,!o&&!r&&!t&&!i&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,r&&!o),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=l}this.exitScope()},Ct.isSimpleParamList=function(e){for(var t=0,i=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t){this.currentScope().lexical.push(e)}else if(3===t){var o=this.currentScope();s=this.treatFunctionsAsVar?o.lexical.indexOf(e)>-1:o.lexical.indexOf(e)>-1||o.var.indexOf(e)>-1,o.functions.push(e)}else for(var r=this.scopeStack.length-1;r>=0;--r){var a=this.scopeStack[r];if(a.lexical.indexOf(e)>-1&&!(32&a.flags&&a.lexical[0]===e)||!this.treatFunctionsAsVarInScope(a)&&a.functions.indexOf(e)>-1){s=!0;break}if(a.var.push(e),this.inModule&&1&a.flags&&delete this.undefinedExports[e],259&a.flags)break}s&&this.raiseRecoverable(i,"Identifier '"+e+"' has already been declared")},Pt.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},Pt.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},Pt.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},Pt.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var It=function(e,t,i){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new Ze(e,i)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},At=rt.prototype;function Dt(e,t,i,s){return e.type=t,e.end=i,this.options.locations&&(e.loc.end=s),this.options.ranges&&(e.range[1]=i),e}At.startNode=function(){return new It(this,this.start,this.startLoc)},At.startNodeAt=function(e,t){return new It(this,e,t)},At.finishNode=function(e,t){return Dt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},At.finishNodeAt=function(e,t,i,s){return Dt.call(this,e,t,i,s)},At.copyNode=function(e){var t=new It(this,e.start,this.startLoc);for(var i in e)t[i]=e[i];return t};var Lt="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",Nt=Lt+" Extended_Pictographic",Ot=Nt+" EBase EComp EMod EPres ExtPict",Vt={9:Lt,10:Nt,11:Nt,12:Ot,13:Ot,14:Ot},Rt={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Bt="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Ft="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",$t=Ft+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",Gt=$t+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",jt=Gt+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ut=jt+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",zt={9:Ft,10:$t,11:Gt,12:jt,13:Ut,14:Ut+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},Ht={};function Wt(e){var t=Ht[e]={binary:Je(Vt[e]+" "+Bt),binaryOfStrings:Je(Rt[e]),nonBinary:{General_Category:Je(Bt),Script:Je(zt[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var qt=0,Xt=[9,10,11,12,13,14];qt=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=Ht[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Qt(e){return 105===e||109===e||115===e}function Zt(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function ei(e){return e>=65&&e<=90||e>=97&&e<=122}Kt.prototype.reset=function(e,t,i){var s=-1!==i.indexOf("v"),n=-1!==i.indexOf("u");this.start=0|e,this.source=t+"",this.flags=i,s&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Kt.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Kt.prototype.at=function(e,t){void 0===t&&(t=!1);var i=this.source,s=i.length;if(e>=s)return-1;var n=i.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=s)return n;var o=i.charCodeAt(e+1);return o>=56320&&o<=57343?(n<<10)+o-56613888:n},Kt.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var i=this.source,s=i.length;if(e>=s)return s;var n,o=i.charCodeAt(e);return!t&&!this.switchU||o<=55295||o>=57344||e+1>=s||(n=i.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Kt.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Kt.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Kt.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Kt.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Kt.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var i=this.pos,s=0,n=e;s-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===r&&(s=!0),"v"===r&&(n=!0)}this.options.ecmaVersion>=15&&s&&n&&this.raise(e.start,"Invalid regular expression flag")},Jt.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Jt.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,i=e.backReferenceNames;t=16;for(t&&(e.branchID=new Yt(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Jt.regexp_alternative=function(e){for(;e.pos=9&&(i=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!i,!0}return e.pos=t,!1},Jt.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Jt.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Jt.regexp_eatBracedQuantifier=function(e,t){var i=e.pos;if(e.eat(123)){var s=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(s=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var i=this.regexp_eatModifiers(e),s=e.eat(45);if(i||s){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(s){var r=this.regexp_eatModifiers(e);i||r||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var a=0;a-1||i.indexOf(l)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Jt.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Jt.regexp_eatModifiers=function(e){for(var t="",i=0;-1!==(i=e.current())&&Qt(i);)t+=Ye(i),e.advance();return t},Jt.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Jt.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Jt.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Zt(t)&&(e.lastIntValue=t,e.advance(),!0)},Jt.regexp_eatPatternCharacters=function(e){for(var t=e.pos,i=0;-1!==(i=e.current())&&!Zt(i);)e.advance();return e.pos!==t},Jt.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t)&&(e.advance(),!0)},Jt.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,i=e.groupNames[e.lastStringValue];if(i)if(t)for(var s=0,n=i;s=11,s=e.current(i);return e.advance(i),92===s&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)&&(s=e.lastIntValue),function(e){return Pe(e,!0)||36===e||95===e}(s)?(e.lastIntValue=s,!0):(e.pos=t,!1)},Jt.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,i=this.options.ecmaVersion>=11,s=e.current(i);return e.advance(i),92===s&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)&&(s=e.lastIntValue),function(e){return Te(e,!0)||36===e||95===e||8204===e||8205===e}(s)?(e.lastIntValue=s,!0):(e.pos=t,!1)},Jt.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Jt.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var i=e.lastIntValue;if(e.switchU)return i>e.maxBackReference&&(e.maxBackReference=i),!0;if(i<=e.numCapturingParens)return!0;e.pos=t}return!1},Jt.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Jt.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Jt.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Jt.regexp_eatZero=function(e){return 48===e.current()&&!si(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Jt.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Jt.regexp_eatControlLetter=function(e){var t=e.current();return!!ei(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Jt.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var i,s=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(n&&o>=55296&&o<=56319){var r=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var a=e.lastIntValue;if(a>=56320&&a<=57343)return e.lastIntValue=1024*(o-55296)+(a-56320)+65536,!0}e.pos=r,e.lastIntValue=o}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&((i=e.lastIntValue)>=0&&i<=1114111))return!0;n&&e.raise("Invalid unicode escape"),e.pos=s}return!1},Jt.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t)&&(e.lastIntValue=t,e.advance(),!0)},Jt.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1};function ti(e){return ei(e)||95===e}function ii(e){return ti(e)||si(e)}function si(e){return e>=48&&e<=57}function ni(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function oi(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function ri(e){return e>=48&&e<=55}Jt.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var i=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((i=80===t)||112===t)){var s;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(s=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return i&&2===s&&e.raise("Invalid property name"),s;e.raise("Invalid property name")}return 0},Jt.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var i=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var s=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,i,s),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Jt.regexp_validateUnicodePropertyNameAndValue=function(e,t,i){We(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(i)||e.raise("Invalid property value")},Jt.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Jt.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";ti(t=e.current());)e.lastStringValue+=Ye(t),e.advance();return""!==e.lastStringValue},Jt.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";ii(t=e.current());)e.lastStringValue+=Ye(t),e.advance();return""!==e.lastStringValue},Jt.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Jt.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),i=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===i&&e.raise("Negated character class may contain strings"),!0}return!1},Jt.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Jt.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var i=e.lastIntValue;!e.switchU||-1!==t&&-1!==i||e.raise("Invalid character class"),-1!==t&&-1!==i&&t>i&&e.raise("Range out of order in character class")}}},Jt.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var i=e.current();(99===i||ri(i))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var s=e.current();return 93!==s&&(e.lastIntValue=s,e.advance(),!0)},Jt.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Jt.regexp_classSetExpression=function(e){var t,i=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(i=2);for(var s=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(i=1):e.raise("Invalid character in character class");if(s!==e.pos)return i;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(s!==e.pos)return i}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return i;2===t&&(i=2)}},Jt.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var i=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;return-1!==i&&-1!==s&&i>s&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Jt.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Jt.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var i=e.eat(94),s=this.regexp_classContents(e);if(e.eat(93))return i&&2===s&&e.raise("Negated character class may contain strings"),s;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Jt.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var i=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return i}else e.raise("Invalid escape");e.pos=t}return null},Jt.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Jt.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Jt.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e))||(e.eat(98)?(e.lastIntValue=8,!0):(e.pos=t,!1));var i=e.current();return!(i<0||i===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(i))&&(!function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(i)&&(e.advance(),e.lastIntValue=i,!0))},Jt.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Jt.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!si(t)&&95!==t)&&(e.lastIntValue=t%32,e.advance(),!0)},Jt.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Jt.regexp_eatDecimalDigits=function(e){var t=e.pos,i=0;for(e.lastIntValue=0;si(i=e.current());)e.lastIntValue=10*e.lastIntValue+(i-48),e.advance();return e.pos!==t},Jt.regexp_eatHexDigits=function(e){var t=e.pos,i=0;for(e.lastIntValue=0;ni(i=e.current());)e.lastIntValue=16*e.lastIntValue+oi(i),e.advance();return e.pos!==t},Jt.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var i=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*i+e.lastIntValue:e.lastIntValue=8*t+i}else e.lastIntValue=t;return!0}return!1},Jt.regexp_eatOctalDigit=function(e){var t=e.current();return ri(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Jt.regexp_eatFixedHexDigits=function(e,t){var i=e.pos;e.lastIntValue=0;for(var s=0;s=this.input.length?this.finishToken(Ve.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},li.readToken=function(e){return Pe(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},li.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},li.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,i=this.input.indexOf("*/",this.pos+=2);if(-1===i&&this.raise(this.pos-2,"Unterminated comment"),this.pos=i+2,this.options.locations)for(var s=void 0,n=t;(s=$e(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=s;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,i),t,this.pos,e,this.curPosition())},li.skipLineComment=function(e){for(var t=this.pos,i=this.options.onComment&&this.curPosition(),s=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&Ge.test(String.fromCharCode(e))))break e;++this.pos}}},li.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var i=this.type;this.type=e,this.value=t,this.updateContext(i)},li.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(Ve.ellipsis)):(++this.pos,this.finishToken(Ve.dot))},li.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(Ve.assign,2):this.finishOp(Ve.slash,1)},li.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),i=1,s=42===e?Ve.star:Ve.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++i,s=Ve.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(Ve.assign,i+1):this.finishOp(s,i)},li.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(Ve.assign,3);return this.finishOp(124===e?Ve.logicalOR:Ve.logicalAND,2)}return 61===t?this.finishOp(Ve.assign,2):this.finishOp(124===e?Ve.bitwiseOR:Ve.bitwiseAND,1)},li.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(Ve.assign,2):this.finishOp(Ve.bitwiseXOR,1)},li.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!Re.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(Ve.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(Ve.assign,2):this.finishOp(Ve.plusMin,1)},li.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),i=1;return t===e?(i=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+i)?this.finishOp(Ve.assign,i+1):this.finishOp(Ve.bitShift,i)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(i=2),this.finishOp(Ve.relational,i)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},li.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(Ve.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(Ve.arrow)):this.finishOp(61===e?Ve.eq:Ve.prefix,1)},li.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var i=this.input.charCodeAt(this.pos+2);if(i<48||i>57)return this.finishOp(Ve.questionDot,2)}if(63===t){if(e>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(Ve.assign,3);return this.finishOp(Ve.coalesce,2)}}return this.finishOp(Ve.question,1)},li.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,Pe(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(Ve.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+Ye(e)+"'")},li.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(Ve.parenL);case 41:return++this.pos,this.finishToken(Ve.parenR);case 59:return++this.pos,this.finishToken(Ve.semi);case 44:return++this.pos,this.finishToken(Ve.comma);case 91:return++this.pos,this.finishToken(Ve.bracketL);case 93:return++this.pos,this.finishToken(Ve.bracketR);case 123:return++this.pos,this.finishToken(Ve.braceL);case 125:return++this.pos,this.finishToken(Ve.braceR);case 58:return++this.pos,this.finishToken(Ve.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(Ve.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(Ve.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+Ye(e)+"'")},li.finishOp=function(e,t){var i=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,i)},li.readRegexp=function(){for(var e,t,i=this.pos;;){this.pos>=this.input.length&&this.raise(i,"Unterminated regular expression");var s=this.input.charAt(this.pos);if(Re.test(s)&&this.raise(i,"Unterminated regular expression"),e)e=!1;else{if("["===s)t=!0;else if("]"===s&&t)t=!1;else if("/"===s&&!t)break;e="\\"===s}++this.pos}var n=this.input.slice(i,this.pos);++this.pos;var o=this.pos,r=this.readWord1();this.containsEsc&&this.unexpected(o);var a=this.regexpState||(this.regexpState=new Kt(this));a.reset(i,n,r),this.validateRegExpFlags(a),this.validateRegExpPattern(a);var l=null;try{l=new RegExp(n,r)}catch(e){}return this.finishToken(Ve.regexp,{pattern:n,flags:r,value:l})},li.readInt=function(e,t,i){for(var s=this.options.ecmaVersion>=12&&void 0===t,n=i&&48===this.input.charCodeAt(this.pos),o=this.pos,r=0,a=0,l=0,c=null==t?1/0:t;l=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;a=h,r=r*e+p}}return s&&95===a&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===o||null!=t&&this.pos-o!==t?null:r},li.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var i=this.readInt(e);return null==i&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(i=ci(this.input.slice(t,this.pos)),++this.pos):Pe(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(Ve.num,i)},li.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var i=this.pos-t>=2&&48===this.input.charCodeAt(t);i&&this.strict&&this.raise(t,"Invalid number");var s=this.input.charCodeAt(this.pos);if(!i&&!e&&this.options.ecmaVersion>=11&&110===s){var n=ci(this.input.slice(t,this.pos));return++this.pos,Pe(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(Ve.num,n)}i&&/[89]/.test(this.input.slice(t,this.pos))&&(i=!1),46!==s||i||(++this.pos,this.readInt(10),s=this.input.charCodeAt(this.pos)),69!==s&&101!==s||i||(43!==(s=this.input.charCodeAt(++this.pos))&&45!==s||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),Pe(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var o,r=(o=this.input.slice(t,this.pos),i?parseInt(o,8):parseFloat(o.replace(/_/g,"")));return this.finishToken(Ve.num,r)},li.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},li.readString=function(e){for(var t="",i=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var s=this.input.charCodeAt(this.pos);if(s===e)break;92===s?(t+=this.input.slice(i,this.pos),t+=this.readEscapedChar(!1),i=this.pos):8232===s||8233===s?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(Fe(s)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(i,this.pos++),this.finishToken(Ve.string,t)};var hi={};li.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==hi)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},li.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw hi;this.raise(e,t)},li.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var i=this.input.charCodeAt(this.pos);if(96===i||36===i&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==Ve.template&&this.type!==Ve.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(Ve.template,e)):36===i?(this.pos+=2,this.finishToken(Ve.dollarBraceL)):(++this.pos,this.finishToken(Ve.backQuote));if(92===i)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(Fe(i)){switch(e+=this.input.slice(t,this.pos),++this.pos,i){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(i)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},li.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var s=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(s,8);return n>255&&(s=s.slice(0,-1),n=parseInt(s,8)),this.pos+=s.length-1,t=this.input.charCodeAt(this.pos),"0"===s&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-s.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return Fe(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},li.readHexChar=function(e){var t=this.pos,i=this.readInt(16,e);return null===i&&this.invalidStringToken(t,"Bad character escape sequence"),i},li.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,i=this.pos,s=this.options.ecmaVersion>=6;this.pos":9,"<=":9,">=":9,in:9,instanceof:9,"<<":10,">>":10,">>>":10,"+":11,"-":11,"*":12,"%":12,"/":12,"**":13},bi=17,vi={ArrayExpression:20,TaggedTemplateExpression:20,ThisExpression:20,Identifier:20,PrivateIdentifier:20,Literal:18,TemplateLiteral:20,Super:20,SequenceExpression:20,MemberExpression:19,ChainExpression:19,CallExpression:19,NewExpression:19,ArrowFunctionExpression:bi,ClassExpression:bi,FunctionExpression:bi,ObjectExpression:bi,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function xi(e,t){const{generator:i}=e;if(e.write("("),null!=t&&t.length>0){i[t[0].type](t[0],e);const{length:s}=t;for(let n=1;n0){e.write(s);for(let t=1;t0){i.VariableDeclarator(s[0],e);for(let t=1;t0){t.write(s),n&&null!=e.comments&&Si(t,e.comments,o,s);const{length:a}=r;for(let e=0;e0){for(;o0&&t.write(", ");const e=i[o],s=e.type[6];if("D"===s)t.write(e.local.name,e),o++;else{if("N"!==s)break;t.write("* as "+e.local.name,e),o++}}if(o0){t.write(" with { ");for(let e=0;e0)for(let e=0;;){const n=i[e],{name:o}=n.local;if(t.write(o,n),o!==n.exported.name&&t.write(" as "+n.exported.name),!(++e0){t.write(" with { ");for(let i=0;i0){t.write(" with { ");for(let i=0;i "),"O"===e.body.type[0]?(t.write("("),this.ObjectExpression(e.body,t),t.write(")")):this[e.body.type](e.body,t)},ThisExpression(e,t){t.write("this",e)},Super(e,t){t.write("super",e)},RestElement:Pi=function(e,t){t.write("..."),this[e.argument.type](e.argument,t)},SpreadElement:Pi,YieldExpression(e,t){t.write(e.delegate?"yield*":"yield"),e.argument&&(t.write(" "),this[e.argument.type](e.argument,t))},AwaitExpression(e,t){t.write("await ",e),wi(t,e.argument,e)},TemplateLiteral(e,t){const{quasis:i,expressions:s}=e;t.write("`");const{length:n}=s;for(let e=0;e0){const{elements:i}=e,{length:s}=i;for(let e=0;;){const n=i[e];if(null!=n&&this[n.type](n,t),!(++e0){t.write(s),n&&null!=e.comments&&Si(t,e.comments,o,s);const r=","+s,{properties:a}=e,{length:l}=a;for(let e=0;;){const i=a[e];if(n&&null!=i.comments&&Si(t,i.comments,o,s),t.write(o),this[i.type](i,t),!(++e0){const{properties:i}=e,{length:s}=i;for(let e=0;this[i[e].type](i[e],t),++e1)&&("U"!==n[0]||"n"!==n[1]&&"p"!==n[1]||!s.prefix||s.operator[0]!==i||"+"!==i&&"-"!==i)||t.write(" "),o?(t.write(i.length>1?" (":"("),this[n](s,t),t.write(")")):this[n](s,t)}else this[e.argument.type](e.argument,t),t.write(e.operator)},UpdateExpression(e,t){e.prefix?(t.write(e.operator),this[e.argument.type](e.argument,t)):(this[e.argument.type](e.argument,t),t.write(e.operator))},AssignmentExpression(e,t){this[e.left.type](e.left,t),t.write(" "+e.operator+" "),this[e.right.type](e.right,t)},AssignmentPattern(e,t){this[e.left.type](e.left,t),t.write(" = "),this[e.right.type](e.right,t)},BinaryExpression:Ti=function(e,t){const i="in"===e.operator;i&&t.write("("),wi(t,e.left,e,!1),t.write(" "+e.operator+" "),wi(t,e.right,e,!0),i&&t.write(")")},LogicalExpression:Ti,ConditionalExpression(e,t){const{test:i}=e,s=t.expressionsPrecedence[i.type];s===bi||s<=t.expressionsPrecedence.ConditionalExpression?(t.write("("),this[i.type](i,t),t.write(")")):this[i.type](i,t),t.write(" ? "),this[e.consequent.type](e.consequent,t),t.write(" : "),this[e.alternate.type](e.alternate,t)},NewExpression(e,t){t.write("new ");const i=t.expressionsPrecedence[e.callee.type];i===bi||i0&&(this.lineEndSize>0&&(1===s.length?e[i-1]===s:e.endsWith(s))?(this.line+=this.lineEndSize,this.column=0):this.column+=i)}toString(){return this.output}}var Oi=Object.defineProperty,Vi=(e,t,i)=>((e,t,i)=>t in e?Oi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Ri{constructor(){Vi(this,"scopes",[]),Vi(this,"scopeTypes",[]),Vi(this,"scopeCounts",new Map),Vi(this,"contextBoundVars",new Set),Vi(this,"arrayPatternElements",new Set),Vi(this,"rootParams",new Set),Vi(this,"varKinds",new Map),Vi(this,"loopVars",new Set),Vi(this,"loopVarNames",new Map),Vi(this,"paramIdCounter",0),Vi(this,"cacheIdCounter",0),Vi(this,"tempVarCounter",0),this.pushScope("glb")}get nextParamIdArg(){return{type:"Identifier",name:`'p${this.paramIdCounter++}'`}}get nextCacheIdArg(){return{type:"Identifier",name:`'cache_${this.cacheIdCounter++}'`}}pushScope(e){this.scopes.push(new Map),this.scopeTypes.push(e),this.scopeCounts.set(e,(this.scopeCounts.get(e)||0)+1)}popScope(){this.scopes.pop(),this.scopeTypes.pop()}getCurrentScopeType(){return this.scopeTypes[this.scopeTypes.length-1]}getCurrentScopeCount(){return this.scopeCounts.get(this.getCurrentScopeType())||1}addContextBoundVar(e,t=!1){this.contextBoundVars.add(e),t&&this.rootParams.add(e)}addArrayPatternElement(e){this.arrayPatternElements.add(e)}isContextBound(e){return this.contextBoundVars.has(e)}isArrayPatternElement(e){return this.arrayPatternElements.has(e)}isRootParam(e){return this.rootParams.has(e)}addLoopVariable(e,t){this.loopVars.add(e),this.loopVarNames.set(e,t)}getLoopVariableName(e){return this.loopVarNames.get(e)}isLoopVariable(e){return this.loopVars.has(e)}addVariable(e,t){if(this.isContextBound(e))return e;const i=this.scopes[this.scopes.length-1],s=this.scopeTypes[this.scopeTypes.length-1],n=`${s}${this.scopeCounts.get(s)||1}_${e}`;return i.set(e,n),this.varKinds.set(n,t),n}getVariable(e){if(this.loopVars.has(e)){const t=this.loopVarNames.get(e);if(t)return[t,"let"]}if(this.isContextBound(e))return[e,"let"];for(let t=this.scopes.length-1;t>=0;t--){const i=this.scopes[t];if(i.has(e)){const t=i.get(e);return[t,this.varKinds.get(t)||"let"]}}return[e,"let"]}generateTempVar(){return"temp_"+ ++this.tempVarCounter}}//!!!Warning!!! this code is not clean, it was initially written as a PoC then used as transpiler for PineTS +const Bi="$",Fi={type:"Identifier",name:"undefined"};function $i(e,t){if(e.computed&&"Identifier"===e.property.type){if(t.isLoopVariable(e.property.name))return;if(!t.isContextBound(e.property.name)){const[i,s]=t.getVariable(e.property.name);e.property={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},e.property={type:"MemberExpression",object:e.property,property:{type:"Literal",value:0},computed:!0}}}if(e.computed&&"Identifier"===e.object.type){if(t.isLoopVariable(e.object.name))return;if(!t.isContextBound(e.object.name)){const[i,s]=t.getVariable(e.object.name);e.object={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}if("MemberExpression"===e.property.type){const i=e.property;i._indexTransformed||($i(i,t),i._indexTransformed=!0)}}}function Gi(e,t,i){if(e.object&&"Identifier"===e.object.type&&"Math"===e.object.name)return;const s="if"==i.getCurrentScopeType(),n="els"==i.getCurrentScopeType(),o="for"==i.getCurrentScopeType();!s&&!n&&!o&&e.object&&"Identifier"===e.object.type&&i.isContextBound(e.object.name)&&!i.isRootParam(e.object.name)||e._indexTransformed||($i(e,i),e._indexTransformed=!0)}function ji(e,t){e.declarations.forEach((i=>{"na"==i.init.name&&(i.init.name="NaN");const s=i.init&&"MemberExpression"===i.init.type&&i.init.object&&("context"===i.init.object.name||i.init.object.name===Bi||"context2"===i.init.object.name),n=i.init&&"MemberExpression"===i.init.type&&i.init.object?.object&&("context"===i.init.object.object.name||i.init.object.object.name===Bi||"context2"===i.init.object.object.name),o=i.init&&"ArrowFunctionExpression"===i.init.type;if(s)return i.id.name&&t.addContextBoundVar(i.id.name),i.id.properties&&i.id.properties.forEach((e=>{e.key.name&&t.addContextBoundVar(e.key.name)})),void(i.init.object.name=Bi);if(n)return i.id.name&&t.addContextBoundVar(i.id.name),i.id.properties&&i.id.properties.forEach((e=>{e.key.name&&t.addContextBoundVar(e.key.name)})),void(i.init.object.object.name=Bi);o&&i.init.params.forEach((e=>{"Identifier"===e.type&&t.addContextBoundVar(e.name)}));const r=t.addVariable(i.id.name,e.kind),a=e.kind;i.init&&!o&&("CallExpression"===i.init.type&&"MemberExpression"===i.init.callee.type&&i.init.callee.object&&"Identifier"===i.init.callee.object.type&&t.isContextBound(i.init.callee.object.name)?Ki(i.init,t):di(i.init,{parent:i.init},{Identifier(e,i){e.parent=i.parent,Ui(e,t);const s=e.parent&&"BinaryExpression"===e.parent.type,n=e.parent&&"ConditionalExpression"===e.parent.type;"Identifier"===e.type&&(s||n)&&Object.assign(e,{type:"MemberExpression",object:{type:"Identifier",name:e.name},property:{type:"Literal",value:0},computed:!0})},CallExpression(e,i,s){"Identifier"===e.callee.type&&(e.callee.parent=e),e.arguments.forEach((t=>{"Identifier"===t.type&&(t.parent=e)})),Ki(e,t),e.arguments.forEach((t=>s(t,{parent:e})))},BinaryExpression(e,t,i){"Identifier"===e.left.type&&(e.left.parent=e),"Identifier"===e.right.type&&(e.right.parent=e),i(e.left,{parent:e}),i(e.right,{parent:e})},MemberExpression(e,i,s){"Identifier"===e.object.type&&(e.object.parent=e),"Identifier"===e.property.type&&(e.property.parent=e),$i(e,t),e.object&&s(e.object,{parent:e})}}));const l={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:a},computed:!1},property:{type:"Identifier",name:r},computed:!1},c=t.isArrayPatternElement(i.id.name),h=!c&&i.init&&"MemberExpression"===i.init.type&&i.init.computed&&i.init.property&&("Literal"===i.init.property.type||"MemberExpression"===i.init.property.type);"MemberExpression"===i.init?.property?.type&&(i.init.property._indexTransformed||($i(i.init.property,t),i.init.property._indexTransformed=!0));const p={type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:l,right:i.init?o||c?i.init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:"init"},computed:!1},arguments:h?[l,i.init.object,i.init.property]:[l,i.init]}:{type:"Identifier",name:"undefined"}}};if(c){p.expression.right.object.property.name+=`?.[0][${i.init.property.value}]`;const e=p.expression.right.object;p.expression.right={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:"init"},computed:!1},arguments:[l,e]}}o&&(t.pushScope("fn"),di(i.init.body,t,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},IfStatement(e,t,i){t.pushScope("if"),i(e.consequent,t),e.alternate&&(t.pushScope("els"),i(e.alternate,t),t.popScope()),t.popScope()},VariableDeclaration(e,t){ji(e,t)},Identifier(e,t){Ui(e,t)},AssignmentExpression(e,t){zi(e,t)}}),t.popScope()),Object.assign(e,p)}))}function Ui(e,t){if(e.name!==Bi){if("Math"===e.name||"NaN"===e.name||"undefined"===e.name||"Infinity"===e.name||"null"===e.name||e.name.startsWith("'")&&e.name.endsWith("'")||e.name.startsWith('"')&&e.name.endsWith('"')||e.name.startsWith("`")&&e.name.endsWith("`")||t.isLoopVariable(e.name)||t.isContextBound(e.name)&&!t.isRootParam(e.name))return;const i=e.parent&&"MemberExpression"===e.parent.type&&e.parent.object===e&&t.isContextBound(e.name),s=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&"MemberExpression"===e.parent.callee.type&&"param"===e.parent.callee.property.name;e.parent&&"AssignmentExpression"===e.parent.type&&e.parent.left;const n=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&"MemberExpression"===e.parent.callee.type&&t.isContextBound(e.parent.callee.object.name),o=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed,r=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.property===e&&e.parent.parent&&"CallExpression"===e.parent.parent.type&&e.parent.parent.callee&&"MemberExpression"===e.parent.parent.callee.type&&t.isContextBound(e.parent.parent.callee.object.name),a=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee===e;if(i||s||n||r||a){if(a)return;const[i,s]=t.getVariable(e.name);return void Object.assign(e,{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1})}const[l,c]=t.getVariable(e.name),h={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:c},computed:!1},property:{type:"Identifier",name:l},computed:!1};e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.object===e||o?Object.assign(e,h):Object.assign(e,{type:"MemberExpression",object:h,property:{type:"Literal",value:0},computed:!0})}}function zi(e,t){if("Identifier"===e.left.type){const[i,s]=t.getVariable(e.left.name),n={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1};e.left={type:"MemberExpression",object:n,property:{type:"Literal",value:0},computed:!0}}di(e.right,{parent:e.right,inNamespaceCall:!1},{Identifier(e,i,s){"na"==e.name&&(e.name="NaN"),e.parent=i.parent,Ui(e,t);const n=e.parent&&"BinaryExpression"===e.parent.type,o=e.parent&&"ConditionalExpression"===e.parent.type,r=t.isContextBound(e.name)&&!t.isRootParam(e.name),a=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.object===e,l=e.parent&&e.parent._isParamCall,c=e.parent&&"MemberExpression"===e.parent.type,h="NaN"===e.name;(r||o||n)&&("MemberExpression"===e.type?$i(e,t):"Identifier"===e.type&&!c&&!a&&!l&&!h&&Qi(e))},MemberExpression(e,i,s){$i(e,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})},CallExpression(e,i,s){const n=e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&t.isContextBound(e.callee.object.name);Ki(e,t),e.arguments.forEach((t=>s(t,{parent:e,inNamespaceCall:n||i.inNamespaceCall})))}})}function Hi(e,t){const i=t.getCurrentScopeType();if(e.argument){if("ArrayExpression"===e.argument.type)e.argument.elements=e.argument.elements.map((e=>{if("Identifier"===e.type){if(t.isContextBound(e.name)&&!t.isRootParam(e.name))return{type:"MemberExpression",object:e,property:{type:"Literal",value:0},computed:!0};const[i,s]=t.getVariable(e.name);return{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},property:{type:"Literal",value:0},computed:!0}}return"MemberExpression"===e.type?(e.computed&&"Identifier"===e.object.type&&t.isContextBound(e.object.name)&&!t.isRootParam(e.object.name)||Gi(e,0,t),e):e})),e.argument={type:"ArrayExpression",elements:[e.argument]};else if("BinaryExpression"===e.argument.type)di(e.argument,t,{Identifier(e,t){Ui(e,t),"Identifier"===e.type&&Qi(e)},MemberExpression(e){Gi(e,0,t)}});else if("ObjectExpression"===e.argument.type)e.argument.properties=e.argument.properties.map((e=>{if(e.shorthand){const[i,s]=t.getVariable(e.value.name);return{type:"Property",key:{type:"Identifier",name:e.key.name},value:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},kind:"init",method:!1,shorthand:!1,computed:!1}}return e}));else if("Identifier"===e.argument.type){const[i,s]=t.getVariable(e.argument.name);e.argument={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},e.argument={type:"MemberExpression",object:e.argument,property:{type:"Literal",value:0},computed:!0}}"fn"===i&&(e.argument={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:"precision"}},arguments:[e.argument]})}}function Wi(e,t){if("Identifier"===e.type){if("na"===e.name)return e.name="NaN",e;if(t.isLoopVariable(e.name))return e;if(t.isRootParam(e.name)){const[i,s]=t.getVariable(e.name);return{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}if(t.isContextBound(e.name))return e;const[i,s]=t.getVariable(e.name);return{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}return e}function qi(e,t,i){const s=Xi(e.argument,t,i);return{type:"UnaryExpression",operator:e.operator,prefix:e.prefix,argument:s,start:e.start,end:e.end}}function Xi(e,t,i=""){switch(e.type){case"BinaryExpression":return Ji(e,t,i);case"MemberExpression":return{type:"MemberExpression",object:"Identifier"===e.object.type?Wi(e.object,t):e.object,property:e.property,computed:e.computed};case"Identifier":return t.isLoopVariable(e.name)||e.parent&&"MemberExpression"===e.parent.type&&e.parent.property===e?e:{type:"MemberExpression",object:Wi(e,t),property:{type:"Literal",value:0},computed:!0};case"UnaryExpression":return qi(e,t,i)}return e}function Ji(e,t,i){const s=Xi(e.left,t,i),n=Xi(e.right,t,i),o={type:"BinaryExpression",operator:e.operator,left:s,right:n,start:e.start,end:e.end};return di(o,t,{CallExpression(e,t){e._transformed||Ki(e,t)},MemberExpression(e){Gi(e,0,t)}}),o}function Yi(e,t,i){switch(e?.type){case"BinaryExpression":e=Ji(e,i,t);break;case"LogicalExpression":e=function(e,t,i){const s=Xi(e.left,t,i),n=Xi(e.right,t,i),o={type:"LogicalExpression",operator:e.operator,left:s,right:n,start:e.start,end:e.end};return di(o,t,{CallExpression(e,t){e._transformed||Ki(e,t)}}),o}(e,i,t);break;case"ConditionalExpression":return function(e,t,i){return di(e,{parent:e,inNamespaceCall:!1},{Identifier(e,i,s){if("NaN"==e.name)return;if("na"==e.name)return void(e.name="NaN");e.parent=i.parent,Ui(e,t);const n=e.parent&&"BinaryExpression"===e.parent.type;(e.parent&&"ConditionalExpression"===e.parent.type||n)&&("MemberExpression"===e.type?$i(e,t):"Identifier"===e.type&&Qi(e))},MemberExpression(e,i,s){$i(e,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})},CallExpression(e,i,s){const n=e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&t.isContextBound(e.callee.object.name);Ki(e,t),e.arguments.forEach((t=>s(t,{parent:e,inNamespaceCall:n||i.inNamespaceCall})))}}),{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:i},property:{type:"Identifier",name:"param"}},arguments:[e,Fi,t.nextParamIdArg],_transformed:!0,_isParamCall:!0}}(e,i,t);case"UnaryExpression":e=qi(e,i,t)}if("MemberExpression"===e.type&&e.computed&&e.property){return{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:["Identifier"===e.object.type&&i.isContextBound(e.object.name)&&!i.isRootParam(e.object.name)?e.object:Wi(e.object,i),"Identifier"!==e.property.type||i.isContextBound(e.property.name)||i.isLoopVariable(e.property.name)?e.property:Wi(e.property,i),i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}if("ObjectExpression"===e.type&&(e.properties=e.properties.map((e=>{if(e.value.name){const[t,s]=i.getVariable(e.value.name);return{type:"Property",key:{type:"Identifier",name:e.key.name},value:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:t},computed:!1},kind:"init",method:!1,shorthand:!1,computed:!1}}return e}))),"Identifier"===e.type){if("na"===e.name)return e.name="NaN",e;if(i.isContextBound(e.name)&&!i.isRootParam(e.name))return{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:[e,Fi,i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}return"CallExpression"===e?.type&&Ki(e,i),{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:["Identifier"===e.type?Wi(e,i):e,Fi,i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}function Ki(e,t,i){if(!e._transformed){if(e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&(t.isContextBound(e.callee.object.name)||"math"===e.callee.object.name||"ta"===e.callee.object.name)){const i=e.callee.object.name;e.arguments=e.arguments.map((e=>e._isParamCall?e:Yi(e,i,t))),e._transformed=!0}else e.callee&&"Identifier"===e.callee.type&&(e.arguments=e.arguments.map((e=>e._isParamCall?e:Yi(e,Bi,t))),e._transformed=!0);e.arguments.forEach((e=>{di(e,t,{Identifier(e,i,s){e.parent=i.parent,Ui(e,t);const n=e.parent&&"BinaryExpression"===e.parent.type;(e.parent&&"ConditionalExpression"===e.parent.type||n)&&("MemberExpression"===e.type?$i(e,t):"Identifier"===e.type&&Qi(e))},CallExpression(e,t,i){e._transformed||Ki(e,t)},MemberExpression(e,i,s){Gi(e,0,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})}})}))}}function Qi(e,t){Object.assign(e,{type:"MemberExpression",object:{type:"Identifier",name:e.name,start:e.start,end:e.end},property:{type:"Literal",value:0},computed:!0,_indexTransformed:!0})}function Zi(e,t,i){if(e.init&&"VariableDeclaration"===e.init.type){const i=e.init.declarations[0],s=i.id.name;t.addLoopVariable(s,s),e.init={type:"VariableDeclaration",kind:e.init.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:s},init:i.init}]},i.init&&di(i.init,t,{Identifier(e,i){t.isLoopVariable(e.name)||(t.pushScope("for"),Ui(e,i),t.popScope())},MemberExpression(e){t.pushScope("for"),Gi(e,0,t),t.popScope()}})}e.test&&di(e.test,t,{Identifier(e,i){!t.isLoopVariable(e.name)&&!e.computed&&(t.pushScope("for"),Ui(e,i),"Identifier"===e.type&&(e.computed=!0,Qi(e)),t.popScope())},MemberExpression(e){t.pushScope("for"),Gi(e,0,t),t.popScope()}}),e.update&&di(e.update,t,{Identifier(e,i){t.isLoopVariable(e.name)||(t.pushScope("for"),Ui(e,i),t.popScope())}}),t.pushScope("for"),i(e.body,t),t.popScope()}function es(e,t,i){e.test&&(t.pushScope("if"),function(e,t){di(e,t,{MemberExpression(e){Gi(e,0,t)},CallExpression(e,t){Ki(e,t)},Identifier(e,i){Ui(e,i);const s="if"===t.getCurrentScopeType();t.isContextBound(e.name)&&!t.isRootParam(e.name)&&s&&Qi(e)}})}(e.test,t),t.popScope()),t.pushScope("if"),i(e.consequent,t),t.popScope(),e.alternate&&(t.pushScope("els"),i(e.alternate,t),t.popScope())}function ts(e){let t="function"==typeof e?e.toString():e;const i=(s=t.trim(),rt.parse(s,{ecmaVersion:"latest",sourceType:"module"}));var s;!function(e){di(e,null,{VariableDeclaration(e,t,i){e.declarations&&e.declarations.length>0&&e.declarations.forEach((t=>{if(t.init&&"ArrowFunctionExpression"===t.init.type&&0!==t.init.start){const i={type:"FunctionDeclaration",id:t.id,params:t.init.params,body:"BlockStatement"===t.init.body.type?t.init.body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:t.init.body}]},async:t.init.async,generator:!1};Object.assign(e,i)}})),e.body&&e.body.body&&e.body.body.forEach((e=>i(e,t)))}})}(i);const n=new Ri;let o;(function(e,t){pi(e,{VariableDeclaration(e){e.declarations.forEach((e=>{const i=e.init&&"MemberExpression"===e.init.type&&e.init.object&&("context"===e.init.object.name||e.init.object.name===Bi||"context2"===e.init.object.name),s=e.init&&"MemberExpression"===e.init.type&&e.init.object?.object&&("context"===e.init.object.object.name||e.init.object.object.name===Bi||"context2"===e.init.object.object.name);(i||s)&&(e.id.name&&t.addContextBoundVar(e.id.name),e.id.properties&&e.id.properties.forEach((e=>{e.key.name&&t.addContextBoundVar(e.key.name)})))}))}})})(i,n),pi(i,{FunctionDeclaration(e){!function(e,t){e.params.forEach((e=>{"Identifier"===e.type&&t.addContextBoundVar(e.name,!1)})),e.body&&"BlockStatement"===e.body.type&&(t.pushScope("fn"),di(e.body,t,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},ReturnStatement(e,t){Hi(e,t)},VariableDeclaration(e,t){ji(e,t)},Identifier(e,t){Ui(e,t)},CallExpression(e,t){Ki(e,t),e.arguments.forEach((e=>{"BinaryExpression"===e.type&&di(e,t,{CallExpression(e,t){Ki(e,t)},MemberExpression(e){Gi(e,0,t)}})}))},MemberExpression(e){Gi(e,0,t)},AssignmentExpression(e,t){zi(e,t)},ForStatement(e,t,i){Zi(e,t,i)},IfStatement(e,t,i){es(e,t,i)},BinaryExpression(e,t,i){di(e,t,{CallExpression(e,t){Ki(e,t)},MemberExpression(e){Gi(e,0,t)}})}}),t.popScope())}(e,n)},ArrowFunctionExpression(e){const t=0===e.start;t&&e.params&&e.params.length>0&&(o=e.params[0].name,e.params[0].name=Bi),function(e,t,i=!1){e.params.forEach((e=>{"Identifier"===e.type&&t.addContextBoundVar(e.name,i)}))}(e,n,t)},VariableDeclaration(e){e.declarations.forEach((t=>{if("ArrayPattern"===t.id.type){const i=n.generateTempVar(),s={type:"VariableDeclaration",kind:e.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:i},init:t.init}]};t.id.elements?.forEach((e=>{"Identifier"===e.type&&n.addArrayPatternElement(e.name)}));const o=t.id.elements.map(((t,s)=>({type:"VariableDeclaration",kind:e.kind,declarations:[{type:"VariableDeclarator",id:t,init:{type:"MemberExpression",object:{type:"Identifier",name:i},property:{type:"Literal",value:s},computed:!0}}]})));Object.assign(e,{type:"BlockStatement",body:[s,...o]})}}))},ForStatement(e){}}),di(i,n,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},ReturnStatement(e,t){Hi(e,t)},VariableDeclaration(e,t){ji(e,t)},Identifier(e,t){Ui(e,t)},CallExpression(e,t){Ki(e,t)},MemberExpression(e){Gi(e,0,n)},AssignmentExpression(e,t){zi(e,t)},FunctionDeclaration(e,t){},ForStatement(e,t,i){Zi(e,t,i)},IfStatement(e,t,i){es(e,t,i)}});const r=function(e,t){const i=new Ni(t);return i.generator[e.type](e,i),i.output}(i);return new Function("",`return ${r}`)(this)}var is=Object.defineProperty,ss=(e,t,i)=>((e,t,i)=>t in e?is(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class ns{constructor(e,t,i,s,n,o,r){this.source=e,this.tickerId=t,this.timeframe=i,this.limit=s,this.sDate=n,this.eDate=o,this.title=r,ss(this,"data",[]),ss(this,"open",[]),ss(this,"high",[]),ss(this,"low",[]),ss(this,"close",[]),ss(this,"volume",[]),ss(this,"hl2",[]),ss(this,"hlc3",[]),ss(this,"ohlc4",[]),ss(this,"openTime",[]),ss(this,"closeTime",[]),ss(this,"_periods"),ss(this,"pineTSCode"),ss(this,"fn"),ss(this,"_readyPromise",null),ss(this,"_ready",!1),this._readyPromise=new Promise((a=>{this.loadMarketData(e,t,i,s,n,o,r).then((e=>{const t=e.reverse();this._periods=t.length,this.data=t;const i=t.map((e=>e.open)),s=t.map((e=>e.close)),n=t.map((e=>e.high)),o=t.map((e=>e.low)),r=t.map((e=>e.volume)),l=t.map((e=>(e.high+e.low+e.close)/3)),c=t.map((e=>(e.high+e.low)/2)),h=t.map((e=>(e.high+e.low+e.open+e.close)/4)),p=t.map((e=>e.openTime)),d=t.map((e=>e.closeTime));this.open=i,this.close=s,this.high=n,this.low=o,this.volume=r,this.hl2=c,this.hlc3=l,this.ohlc4=h,this.openTime=p,this.closeTime=d,this._ready=!0,a(!0)}))}))}get periods(){return this._periods}async loadMarketData(e,t,i,s,n,o,r){return Array.isArray(e)?e:e.getMarketData(t,i,s,n,o,r)}async ready(){if(this._ready)return!0;if(!this._readyPromise)throw new Error("PineTS is not ready");return this._readyPromise}updateData(e){if(!e)throw new Error("Invalid data: newData must be a valid object.");this.data=[e,...this.data],this._periods=this.data.length,this.open=[e.open,...this.open],this.close=[e.close,...this.close],this.high=[e.high,...this.high],this.low=[e.low,...this.low],this.volume=[e.volume,...this.volume],this.hl2=[(e.high+e.low)/2,...this.hl2],this.hlc3=[(e.high+e.low+e.close)/3,...this.hlc3],this.ohlc4=[(e.high+e.low+e.open+e.close)/4,...this.ohlc4],this.openTime=[e.openTime,...this.openTime],this.closeTime=[e.closeTime,...this.closeTime]}async run(e,t,i){if(await this.ready(),t||(t=this._periods),!this.pineTSCode&&!e)throw new Error("Invalid PineTS Code: No pineTSCode supplied/stored.");e=e||this.pineTSCode;const s=new Es({marketData:this.data,source:this.source,tickerId:this.tickerId,timeframe:this.timeframe,limit:this.limit,sDate:this.sDate,eDate:this.eDate,title:this.title});if(s.pineTSCode=e,s.useTACache=i,!this.fn||e&&this.pineTSCode!==e){const t=ts.bind(this);this.fn=t(e),this.pineTSCode=e}const n=this.fn,o=["const","var","let","params"];for(let e=this._periods-t,i=t-1;e((e,t,i)=>t in e?os(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class as{constructor(e){this.context=e,rs(this,"script"),rs(this,"pane",0),rs(this,"color",{param:(e,t=0)=>Array.isArray(e)?e[t]:e,rgb:(e,t,i,s)=>s?`rgba(${e}, ${t}, ${i}, ${s})`:`rgb(${e}, ${t}, ${i})`,new:(e,t)=>{if(e&&e.startsWith("#")){const i=e.slice(1),s=parseInt(i.slice(0,2),16),n=parseInt(i.slice(2,4),16),o=parseInt(i.slice(4,6),16);return t?`rgba(${s}, ${n}, ${o}, ${t})`:`rgb(${s}, ${n}, ${o})`}return t?`rgba(${e}, ${t})`:e},white:"white",lime:"lime",green:"green",red:"red",maroon:"maroon",black:"black",gray:"gray",blue:"blue"})}extractPlotOptions(e){const t={};for(let i in e)Array.isArray(e[i])?t[i]=e[i][0]:t[i]=e[i];return t}indicator(e,t,i){this.script=e??t??"PineTS Script",i&&(this.pane=i.overlay?0:1)}plotchar(e,t,i){this.context.plots[t]||(this.context.plots[t]={data:[],options:this.extractPlotOptions(i),title:t}),this.context.plots[t].data.push({time:this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,value:e[0],options:{...this.extractPlotOptions(i),style:"char"}})}plot(e,t,i){this.script&&(i.group=this.script),this.context.plots[t]||(this.context.plots[t]={data:[],options:this.extractPlotOptions(i),title:t,pane:this.pane}),this.context.plots[t].data.push({time:this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,value:e[0],options:this.extractPlotOptions(i)})}na(e){return Array.isArray(e)?isNaN(e[0]):isNaN(e)}nz(e,t=0){const i=Array.isArray(e)?e[0]:e,s=Array.isArray(e)?t[0]:t;return isNaN(i)?s:i}plotcandle(e,t,i,s,n,o){this.script&&(o.group=this.script),this.context.candles[n]||(this.context.candles[n]={data:[],options:this.extractPlotOptions(o),title:n,pane:this.pane});const r=this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,a=e[0],l=t[0],c=i[0],h=s[0];this.context.candles[n].data.push({time:r,open:a,high:l,low:c,close:h,pane:this.pane,options:this.extractPlotOptions(o)})}plotbar(e,t,i,s,n,o){this.script&&(o.group=this.script),this.context.bars[n]||(this.context.bars[n]={data:[],options:this.extractPlotOptions(o),title:n,pane:this.pane});const r=this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,a=e[0],l=t[0],c=i[0],h=s[0];this.context.bars[n].data.push({time:r,open:a,high:l,low:c,close:h,pane:this.pane,options:this.extractPlotOptions(o)})}fill(e,t,i){this.context.fills[e]||(this.context.fills[e]={plot1:e,plot2:t,options:this.extractPlotOptions(i)})}hline(e,t,i){const s=this.extractPlotOptions(i),n=Array.isArray(e)?e[0]:e;this.context.hlines[t]?(this.context.hlines[t].price=n,this.context.hlines[t].options=s):this.context.hlines[t]={price:n,options:s,pane:this.pane}}}class ls{constructor(e){this.context=e}param(e,t=0){return Array.isArray(e)?[e[t]]:[e]}any(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}int(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}float(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}bool(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}string(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}timeframe(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}time(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}price(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}session(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}source(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}symbol(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}text_area(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}enum(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}color(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}}var cs=Object.defineProperty,hs=(e,t,i)=>((e,t,i)=>t in e?cs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);class ps{constructor(e){this.context=e,hs(this,"_cache",{})}param(e,t,i){return this.context.params[i]||(this.context.params[i]=[]),Array.isArray(e)?t?(this.context.params[i]=e.slice(t),this.context.params[i].length=e.length,this.context.params[i]):(this.context.params[i]=e.slice(0),this.context.params[i]):(this.context.params[i][0]=e,this.context.params[i])}abs(e){return Math.abs(e[0])}pow(e,t){return Math.pow(e[0],t[0])}sqrt(e){return Math.sqrt(e[0])}log(e){return Math.log(e[0])}ln(e){return Math.log(e[0])}exp(e){return Math.exp(e[0])}floor(e){return Math.floor(e[0])}ceil(e){return Math.ceil(e[0])}round(e){return Math.round(e[0])}random(){return Math.random()}max(...e){const t=e.map((e=>Array.isArray(e)?e[0]:e));return Math.max(...t)}min(...e){const t=e.map((e=>Array.isArray(e)?e[0]:e));return Math.min(...t)}sum(e,t){const i=Array.isArray(t)?t[0]:t;return Array.isArray(e)?e.slice(0,i).reduce(((e,t)=>e+t),0):e}sin(e){return Math.sin(e[0])}cos(e){return Math.cos(e[0])}tan(e){return Math.tan(e[0])}acos(e){return Math.acos(e[0])}asin(e){return Math.asin(e[0])}atan(e){return Math.atan(e[0])}avg(...e){const t=e.map((e=>Array.isArray(e)?e[0]:e));return t.reduce(((e,t)=>(Array.isArray(e)?e[0]:e)+(Array.isArray(t)?t[0]:t)),0)/t.length}}var ds=Object.defineProperty,us=(e,t,i)=>((e,t,i)=>t in e?ds(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);const ms=["1","3","5","15","30","45","60","120","180","240","D","W","M"];class gs{constructor(e){this.context=e,us(this,"_cache",{})}param(e,t,i){return this.context.params[i]||(this.context.params[i]=[]),Array.isArray(e)?(this.context.params[i]=t?e.slice(t):e.slice(0),[e[t],i]):(this.context.params[i][0]=e,[e,i])}async security(e,t,i,s=!1,n=!1,o=!1,r=null,a=null){const l=e[0],c=t[0],h=i[0],p=i[1],d=ms.indexOf(this.context.timeframe),u=ms.indexOf(c);if(-1==d||-1==u)throw new Error("Invalid timeframe");if(d>u)throw new Error("Only higher timeframes are supported for now");if(d===u)return h;const m=this.context.data.openTime[0],g=this.context.data.closeTime[0];if(this.context.cache[p]){const e=this.context.cache[p],t=this._findSecContextIdx(m,g,e.data.openTime,e.data.closeTime,n);return-1==t?NaN:e.params[p][t]}const f=await new ns(this.context.source,l,c,this.context.limit||1e3,this.context.sDate,this.context.eDate).run(this.context.pineTSCode);this.context.cache[p]=f;const y=this._findSecContextIdx(m,g,f.data.openTime,f.data.closeTime,n);return-1==y?NaN:f.params[p][y]}_findSecContextIdx(e,t,i,s,n=!1){for(let o=0;o2*e-n[t])),r=Math.floor(Math.sqrt(t));return vs(o,r)}(e.slice(0).reverse(),i),n=this.context.idx;return this.context.precision(s[n])}rma(e,t){const i=Array.isArray(t)?t[0]:t,s=function(e,t){const i=new Array(e.length).fill(NaN),s=1/t;let n=0;for(let i=0;i0?i:0,n[t]=i<0?-i:0}let o=0,r=0;for(let e=1;e<=t;e++)o+=s[e],r+=n[e];o/=t,r/=t,i[t]=0===r?100:100-100/(1+o/r);for(let a=t+1;ae-t)),o=Math.floor(t/2);i[s]=t%2==0?(n[o-1]+n[o])/2:n[o]}return i}(e.slice(0).reverse(),i),n=this.context.idx;return this.context.precision(s[n])}stdev(e,t,i=!0){const s=Array.isArray(t)?t[0]:t,n=Array.isArray(i)?i[0]:i,o=function(e,t,i=!0){const s=new Array(e.length).fill(NaN),n=bs(e,t);for(let o=t-1;op?c[e]=t:c[e]=p;let s=h[e];s>d||i[e-1]c[e]?(a[e]=1,r[e]=h[e]):(a[e]=-1,r[e]=c[e]):i[e]e+t),0)/t,n=p.reduce(((e,t)=>e+t*t),0)/t-i*i,l=Math.sqrt(n);r[d]=o[d]+s*l,a[d]=o[d]-s*l}return l?[o,r,a]:o}(e,this.context.data.volume,t,i),n=this.context.idx;if(void 0!==i&&Array.isArray(s)){const[e,t,i]=s;return[this.context.precision(e[n]),this.context.precision(t[n]),this.context.precision(i[n])]}return this.context.precision(s[n])}swma(e){const t=function(e){const t=e.length,i=new Array(t).fill(NaN);for(let s=3;s((e,t,i)=>t in e?xs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);class ws{constructor(e){this.array=e}}class Cs{constructor(e){this.context=e,_s(this,"_cache",{})}param(e,t=0){return Array.isArray(e)?e[t]:e}get(e,t){return e.array[t]}set(e,t,i){e.array[t]=i}push(e,t){e.array.push(t)}sum(e){return e.array.reduce(((e,t)=>e+(isNaN(t)?0:t)),0)}avg(e){return this.sum(e)/e.array.length}min(e,t=0){return[...e.array].sort(((e,t)=>e-t))[t]??this.context.NA}max(e,t=0){return[...e.array].sort(((e,t)=>t-e))[t]??this.context.NA}size(e){return e.array.length}new_bool(e,t=!1){return new ws(Array(e).fill(t))}new_float(e,t=NaN){return new ws(Array(e).fill(t))}new_int(e,t=0){return new ws(Array(e).fill(Math.round(t)))}new_string(e,t=""){return new ws(Array(e).fill(t))}new(e,t){return new ws(Array(e).fill(t))}slice(e,t,i){const s=void 0!==i?i+1:void 0;return new ws(e.array.slice(t,s))}reverse(e){e.array.reverse()}includes(e,t){return e.array.includes(t)}indexof(e,t){return e.array.indexOf(t)}lastindexof(e,t){return e.array.lastIndexOf(t)}stdev(e,t=!0){const i=this.avg(e),s=e.array.map((e=>Math.pow(e-i,2))),n=t?e.array.length:e.array.length-1;return Math.sqrt(this.sum(new ws(s))/n)}variance(e,t=!0){const i=this.avg(e),s=e.array.map((e=>Math.pow(e-i,2))),n=t?e.array.length:e.array.length-1;return this.sum(new ws(s))/n}covariance(e,t,i=!0){if(e.array.length!==t.array.length||e.array.length<2)return NaN;const s=i?e.array.length:e.array.length-1,n=this.avg(e),o=this.avg(t);let r=0;for(let i=0;i0?e.array[0]:this.context.NA}last(e){return e.array.length>0?e.array[e.array.length-1]:this.context.NA}clear(e){e.array.length=0}join(e,t=","){return e.array.join(t)}abs(e){return new ws(e.array.map((e=>Math.abs(e))))}concat(e,t){return e.array.push(...t.array),e}copy(e){return new ws([...e.array])}every(e,t){return e.array.every(t)}fill(e,t,i=0,s){const n=e.array.length,o=void 0!==s?Math.min(s,n):n;for(let s=i;s=0&&t"asc"===t?e-i:i-e))}sort_indices(e,t){const i=e.array.map(((e,t)=>t));return i.sort(((i,s)=>{const n=e.array[i],o=e.array[s];return t?t(n,o):n-o})),new ws(i)}standardize(e){const t=this.avg(e),i=this.stdev(e);return new ws(0===i?e.array.map((()=>0)):e.array.map((e=>(e-t)/i)))}unshift(e,t){e.array.unshift(t)}some(e,t){return e.array.some(t)}}var Ss=Object.defineProperty,ks=(e,t,i)=>((e,t,i)=>t in e?Ss(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Es{constructor({marketData:e,source:t,tickerId:i,timeframe:s,limit:n,sDate:o,eDate:r,title:a}){ks(this,"data",{open:[],high:[],low:[],close:[],volume:[],hl2:[],hlc3:[],ohlc4:[]}),ks(this,"cache",{}),ks(this,"useTACache",!1),ks(this,"NA",NaN),ks(this,"math"),ks(this,"ta"),ks(this,"input"),ks(this,"request"),ks(this,"array"),ks(this,"core"),ks(this,"lang"),ks(this,"idx",0),ks(this,"params",{}),ks(this,"const",{}),ks(this,"var",{}),ks(this,"let",{}),ks(this,"result"),ks(this,"plots",{}),ks(this,"candles",{}),ks(this,"bars",{}),ks(this,"fills",{}),ks(this,"hlines",{}),ks(this,"marketData"),ks(this,"source"),ks(this,"tickerId"),ks(this,"timeframe",""),ks(this,"limit"),ks(this,"sDate"),ks(this,"eDate"),ks(this,"group"),ks(this,"pineTSCode"),this.marketData=e,this.source=t,this.tickerId=i,this.timeframe=s,this.limit=n,this.sDate=o,this.eDate=r,this.group=a,this.math=new ps(this),this.ta=new fs(this),this.input=new ls(this),this.request=new gs(this),this.array=new Cs(this);const l=new as(this);this.core={color:l.color,indicator:l.indicator.bind(l),na:l.na.bind(l),nz:l.nz.bind(l),plot:l.plot.bind(l),plotbar:l.plotbar.bind(l),plotchar:l.plotchar.bind(l),plotcandle:l.plotcandle.bind(l),fill:l.fill.bind(l),hline:l.hline.bind(l)}}init(e,t,i=0){return e?!Array.isArray(t)||Array.isArray(t[0])?e[0]=Array.isArray(t?.[0])?t[0]:this.precision(t):e[0]=this.precision(t[t.length-this.idx-1+i]):e=Array.isArray(t)?[this.precision(t[t.length-this.idx-1+i])]:[this.precision(t)],e}precision(e,t=10){return"number"!=typeof e||isNaN(e)?e:Number(e.toFixed(t))}param(e,t,i){return"string"==typeof e||!Array.isArray(e)&&"object"==typeof e?e:(this.params[i]||(this.params[i]=[]),Array.isArray(e)?t?(this.params[i]=e.slice(t),this.params[i].length=e.length,this.params[i]):(this.params[i]=e.slice(0),this.params[i]):(this.params[i][0]=e,this.params[i]))}}var Ms=Object.defineProperty,Ps=(e,t,i)=>((e,t,i)=>t in e?Ms(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);const Ts={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",45:null,60:"1h",120:"2h",180:null,240:"4h","4H":"4h","1D":"1d",D:"1d","1W":"1w",W:"1w","1M":"1M",M:"1M"};class Is{constructor(e=3e5){Ps(this,"cache"),Ps(this,"cacheDuration"),this.cache=new Map,this.cacheDuration=e}generateKey(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>`${e}:${t}`)).join("|")}get(e){const t=this.generateKey(e),i=this.cache.get(t);return i?Date.now()-i.timestamp>this.cacheDuration?(this.cache.delete(t),null):i.data:null}set(e,t){const i=this.generateKey(e);this.cache.set(i,{data:t,timestamp:Date.now()})}clear(){this.cache.clear()}cleanup(){const e=Date.now();for(const[t,i]of this.cache.entries())e-i.timestamp>this.cacheDuration&&this.cache.delete(t)}}function As(e){let t;if("string"==typeof e){if(t=parseInt(e,10),isNaN(t)){const t=new Date(e);return Math.floor(t.getTime()/1e3)}}else t=e;return t.toString().length>=13?Math.floor(t/1e3):t}new class{constructor(){Ps(this,"cacheManager"),this.cacheManager=new Is(3e5)}async getMarketDataInterval(e,t,i,s){try{const n=Ts[t.toUpperCase()];if(!n)return console.error(`Unsupported timeframe: ${t}`),[];let o=[],r=i;const a=s,l={"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"1d":864e5,"1w":6048e5,"1M":2592e6}[n];if(!l)return console.error(`Duration not defined for interval: ${n}`),[];for(;r({openTime:parseInt(e[0]),open:parseFloat(e[1]),high:parseFloat(e[2]),low:parseFloat(e[3]),close:parseFloat(e[4]),volume:parseFloat(e[5]),closeTime:parseInt(e[6]),quoteAssetVolume:parseFloat(e[7]),numberOfTrades:parseInt(e[8]),takerBuyBaseAssetVolume:parseFloat(e[9]),takerBuyQuoteAssetVolume:parseFloat(e[10]),ignore:e[11]})));return this.cacheManager.set(o,h),h}catch(e){return console.error("Error in binance.klines:",e),[]}}};const Ds={...t.customSeriesDefaultOptions,color:"#049981",lineWidth:1,lineStyle:t.LineStyle.Solid,shapeSize:.3,shape:"circles",join:!1,fontSize:.8};function Ls(e,t){if(e._isDecorated)return console.warn("Series is already decorated. Skipping decoration."),e;e._isDecorated=!0;const i=e.setData.bind(e),s=[];let n=null;const o=e.detachPrimitive?.bind(e),r=e.attachPrimitive?.bind(e),a=e.data?.bind(e),l=e.applyOptions?.bind(e),c=e.seriesType(),h=e.options().title;function p(e){const i=s.indexOf(e);-1!==i&&(s.splice(i,1),n===e&&(n=null),o&&o(e),t&&(t.removeLegendPrimitive(e),console.log(`Removed primitive of type "${e.constructor.name}" from legend.`)))}function d(){for(console.log("Detaching all primitives.");s.length>0;){p(s.pop())}console.log("All primitives detached.")}return Object.assign(e,{applyOptions:i=>{if(l&&l(i),t&&void 0!==t._lines){const s=e.seriesType(),n=t._lines.find((t=>t.series===e));if(n&&("Candlestick"===s||"Bar"===s||"Custom"===s&&("upColor"in i||"downColor"in i)?(void 0!==i.upColor&&(n.colors[0]=i.upColor),void 0!==i.downColor&&(n.colors[1]=i.downColor)):"Line"===s||"Histogram"===s||"Custom"===s&&"color"in i?void 0!==i.color&&(n.colors[0]=i.color):"Area"===s&&void 0!==i.lineColor&&(n.colors[0]=i.lineColor),"shape"in i)){const e=(()=>{switch(i.shape){case"circle":case"circles":return"●";case"cross":return"✚";case"triangleUp":return"▲";case"triangleDown":return"▼";case"arrowUp":return"↑";case"arrowDown":return"↓";default:return i.shape}})();n.legendSymbol=e}}},setData:function(t){if(t&&Array.isArray(t)||(t=[...e.data()]),!t||0===t.length)return void i(t);const s=e.seriesType();if("Line"!==s&&"Histogram"!==s&&"Area"!==s&&"Symbol"!=s&&"Custom"!=s||!("value"in t[0])){if(("Bar"===s||"Candlestick"===s||"Custom"===s||"Ohlc"===s)&&"open"in t[0]&&t.every((e=>y(e))))return void i(t)}else if(t.every((e=>f(e))))return void i(t);let n;n="Line"!==s&&"Histogram"!==s&&"Area"!==s&&"Symbol"!==s||!("open"in t[0])?("Bar"!==s&&"Candlestick"!==s&&"Ohlc"!==s||t[0],t.map(((e,i)=>Os(t,s,i)))):t.map(((e,i)=>Os(t,s,i))),i(n)},dataType:function(t){const i=e.data()[0];if(b(i))return null;let s=f(i),n=y(i);if(!s&&!n&&"open"in i&&"high"in i&&"low"in i&&"close"in i&&(n=!0),t){const e=t.data()[0];if(b(e))return!1;let i=f(e),o=y(e);return!i&&!o&&"open"in e&&"high"in e&&"low"in e&&"close"in e&&(o=!0),s&&i||n&&o}return s||n?i:null},dataTransform:function(){const t=e.data();if(!t||0===t.length)return[];const i=t[0];let s;if(y(i)||"open"in i&&"high"in i&&"low"in i&&"close"in i)s="Line";else{if(!f(i))return[...t];s="Candlestick"}return t.map(((t,i)=>Os(e,s,i)))},primitives:s,sync:function(e){const t=e.options().seriesType??"Line",i=a();if(!i)return void console.warn("Source data is missing for synchronization.");const s=[...e.data()];for(let n=s.length;n{const i=[...a()];if(!i||0===i.length)return void console.warn("Source data is missing for synchronization.");const s=e.data().slice(-1)[0],n=i.length-1;if(!s||i[n].time>=s.time){const i=Os(e,t,n);i&&(e.update(i),console.log(`Updated/added bar via "update()" for series type ${e.seriesType}`))}}))},attachPrimitive:function(i,o,a=!0,l=!1){const c=i.constructor.type||i.constructor.name;if(a)d();else{const e=s.findIndex((e=>e.constructor.type===c));-1!==e&&p(s[e])}r&&r(i),s.push(i),n=i,console.log(`Primitive of type "${c}" attached.`),t&&l&&t.addLegendPrimitive(e,i,o)},detachPrimitive:p,detachPrimitives:d,decorated:!0,_type:c,title:h,get primitive(){return n},toJSON:()=>({options:e.options(),data:a()}),fromJSON(t){if(t.data&&i(t.data),t.options){const i=t.options;for(const t in i)if(Object.prototype.hasOwnProperty.call(i,t)){const s=t;e.applyOptions({[s]:i[s]})}}}})}function Ns(e){const t={};switch(e){case"Line":return{...t,title:e,color:"#195200",lineWidth:2,crosshairMarkerVisible:!0};case"Histogram":return{...t,title:e,color:"#9ACF01",base:0};case"Area":return{...t,title:e,lineColor:"#021698",topColor:"rgba(9, 32, 210, 0.4)",bottomColor:"rgba(0, 0, 0, 0.5)"};case"Bar":return{...t,title:e,upColor:"#006721",downColor:"#6E0000",borderUpColor:"#006721",borderDownColor:"#6E0000"};case"Candlestick":return{...t,title:e,upColor:"rgba(0, 103, 33, 0.33)",downColor:"rgba(110, 0, 0, 0.33)",borderUpColor:"#006721",borderDownColor:"#6E0000",wickUpColor:"#006721",wickDownColor:"#6E0000"};case"Ohlc":return{...t,title:e,upColor:"rgba(0, 103, 33, 0.33)",downColor:"rgba(110, 0, 0, 0.33)",borderUpColor:"#006721",borderDownColor:"#6E0000",wickUpColor:"#006721",wickDownColor:"#6E0000",shape:"Rounded",chandelierSize:1,barSpacing:.777,lineStyle:0,lineWidth:1};case"Symbol":return{...t,...Ds,title:e};default:throw new Error(`Unsupported series type: ${e}`)}}function Os(e,t,i){let s;if(Array.isArray(e))s=e;else{if(!e||"function"!=typeof e.data)return console.warn("Invalid source provided to convertDataItem; expected an array or series object."),null;s=[...e.data()]}if(!s||0===s.length)return console.warn("No data available in the source series."),null;const n=s[i];switch(t){case"Line":case"Histogram":case"Area":case"Symbol":if(y(n))return{time:n.time,value:n.close};if(f(n))return{time:n.time,value:n.value};if(b(n))return{time:n.time};break;case"Bar":case"Candlestick":case"Ohlc":if(y(n))return{time:n.time,open:n.open,high:n.high,low:n.low,close:n.close};if(f(n))return{time:n.time,open:n.value,high:n.value,low:n.value,close:n.value};if(b(n))return{time:n.time};break;default:return console.error(`Unsupported target type: ${t}`),{time:n.time}}return console.warn("Could not convert data to the target type."),null}function Vs(e,t,i){const s=e.options(),n=t.split(".");let o=s;for(let e=0;evoid 0!==e.primitives)(e)?e:(console.log("Decorating the series dynamically."),Ls(e,t))}function Fs(e,t){const i={...e.paramMap,...t},s=[...e.sourceSeries.data()];if(!s||!Array.isArray(s)||0===s.length)return;let n;n=s.every(y)?s:s.map($s);e.indicator.calc(n,i).forEach((t=>{const i=e.figures.get(t.key);if(i&&(i.setData(t.data),i.applyOptions({title:t.title}),t.pane&&i.getPane()===e.sourceSeries.getPane())){const e=i.getPane().paneIndex();i.moveToPane(e+t.pane)}})),e.paramMap=i}function $s(e){return{time:e.time,open:e.value,high:e.value,low:e.value,close:e.value}}function Gs(e,t,i,s="Line",n="overwrite"){const{data:o,group:r,options:a,pane:l}=i,c={...js(a)};r&&(c.group=r),t&&(c.title=t);const h="circles"===c.style||"cross"===c.style?"Symbol":s;let p={...Ns(h)||{},...e.defaultsManager.get(h)||{},...c};p.style&&"line"!==p.style&&(p.shape=p.style,delete p.style);const d=o.map((e=>({...e,time:"number"==typeof e.time?As(e.time):e.time}))),u=e.seriesMap.get(t);if(u&&("overwrite"===n||"update"===n))return"update"===n?(u.update(d[d.length-1]),p={...p,...u.options()}):(u.detachPrimitives(),u.setData(d)),void u.applyOptions(p);let m=null;"Line"===s?m="line"!==c.style?e.createSymbolSeries(t,{...p,shape:c.style},l):e.createLineSeries(t,p,l):"Bar"===s?m=e.createBarSeries(t,p,l):"Candlestick"===s||"Ohlc"===s||"Custom"===s&&void 0!==o[0]?.open?m=e.createCustomOHLCSeries?e.createCustomOHLCSeries(t,p):e.createBarSeries(t,p,l):"Histogram"===s?m=e.createHistogramSeries(t,p,l):"Area"===s?m=e.createAreaSeries(t,p,l):(console.warn(`Unsupported series type: ${s}. Defaulting to Line.`),m=e.createLineSeries(t,p,l)),m.series.setData(d),e.legend&&!m.series.decorated&&(m.series=Ls(m.series,e.legend)),e.seriesMap.set(t,m.series)}function js(e){const t={};for(const i in e){const s=Array.isArray(e[i])?e[i][0]:e[i];"linewidth"===i.toLowerCase()?t.lineWidth=s:t[i]=s}return t}function Us(e,t){const{plot1:i,plot2:s,options:n}=t,o=S,r=e.seriesMap.get(i),a=e.seriesMap.get(s);if(!r)return void console.warn(`Origin series with title "${i}" not found.`);if(!a)return void console.warn(`Destination series with title "${s}" not found.`);const l=a.options().title;let c=null;r.primitives[l]?c=r.primitives[l]:(c=new _(r,a,o),r.primitives[l]=c,r.attachPrimitive(c,`Fill ➣ ${a.options().title}`,!1,!0))}function zs(e,t){const i=e.split("."),s={};let n=s;for(let e=0;ee.toUpperCase()))}function Ws(e,i,s){const n=i.timeScale(),o=s??i.addSeries(t.LineSeries);if(!o)return console.warn("No series found. Cannot perform y-axis conversions."),null;if("logical"in e){const t=e,i=n.logicalToCoordinate(t.logical),s=o.priceToCoordinate(t.price);return null===i||null===s?null:{x:i,y:s}}{const t=e,i=n.coordinateToLogical(t.x),s=n.coordinateToTime(t.x),r=o.coordinateToPrice(t.y);return null===i||null===r?null:{time:s,logical:i,price:r}}}function qs(e,t,i,s,n){const o=s-n/2,r=s+n/2;e.beginPath(),e.moveTo(t,o),e.lineTo(t,r),e.lineTo(i,r),e.lineTo(i,o),e.closePath(),e.fill(),e.stroke()}function Xs(e,t,i,s,n,o){const r=i-t,a=o*Math.min(Math.abs(r),Math.abs(n)),l=Math.abs(Math.min(a,r/2,n/2)),c=s-n/2;e.beginPath(),"function"==typeof e.roundRect?e.roundRect(t,c,r,n,l):(e.moveTo(t+l,c),e.lineTo(i-l,c),e.quadraticCurveTo(i,c,i,c+l),e.lineTo(i,c+n-l),e.quadraticCurveTo(i,c+n,i-l,c+n),e.lineTo(t+l,c+n),e.quadraticCurveTo(t,c+n,t,c+n-l),e.lineTo(t,c+l),e.quadraticCurveTo(t,c,t+l,c)),e.closePath(),e.fill(),e.stroke()}function Js(e,t,i,s,n,o){const r=t+(i-t)/2,a=i-t;e.beginPath(),e.ellipse(r,n,Math.abs(a/2),Math.abs(o/2),0,0,2*Math.PI),e.fill(),e.stroke()}function Ys(e,t,i,s,n,o,r,a,l,h,p,d){const u=-Math.max(a,1)*(1-d),m=c(l,.666),g=c(l,.333),f=c(l,.2),y=t-r/2,b=y+a+u,v=y-u,x=b-u;let _,w,C,S;p?(_=n,w=s,C=i,S=o):(_=n,w=i,C=s,S=o),e.fillStyle=g,e.strokeStyle=h,e.beginPath(),e.rect(v,C,a+u-r/2,S-C),e.fill(),e.stroke(),e.fillStyle=f,p?(e.fillStyle=m,e.beginPath(),e.moveTo(y,w),e.lineTo(v,S),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=m,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(v,S),e.lineTo(y,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=m,e.beginPath(),e.moveTo(b,_),e.lineTo(x,C),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=f,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(x,C),e.lineTo(b,_),e.closePath(),e.fill(),e.stroke()):(e.fillStyle=f,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(x,C),e.lineTo(b,_),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(b,_),e.lineTo(x,C),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(v,S),e.lineTo(y,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(y,w),e.lineTo(v,S),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke())}function Ks(e,t,i,s,n,o,r,a){const l=s+n/2,c=s-n/2;e.save(),e.beginPath(),a?(e.moveTo(t,l),e.lineTo(i,o),e.lineTo(i,c),e.lineTo(t,r)):(e.moveTo(t,o),e.lineTo(i,l),e.lineTo(i,r),e.lineTo(t,c)),e.closePath(),e.stroke(),e.fill(),e.restore()}function Qs(e,t,i,s,n,o,r,a,l){e.save(),e.beginPath(),l?(e.moveTo(t,a),e.lineTo(t,n+o/2),e.lineTo(s,r),e.lineTo(i,n+o/2),e.lineTo(i,a),e.lineTo(s,n-o/2),e.lineTo(t,a)):(e.moveTo(t,r),e.lineTo(t,n-o/2),e.lineTo(s,a),e.lineTo(i,n-o/2),e.lineTo(i,r),e.lineTo(s,n+o/2),e.lineTo(t,r)),e.closePath(),e.fill(),e.stroke(),e.restore()}function Zs(e,t,i,s,n,o,r){const a=(t+i)/2;e.beginPath(),e.moveTo(a,s),e.lineTo(a,n),e.stroke(),e.beginPath(),e.moveTo(t,o),e.lineTo(a,o),e.stroke(),e.beginPath(),e.moveTo(a,r),e.lineTo(i,r),e.stroke()}function en(e,t,i,s,n,o){const r=s-n/2,a=s+n/2,l=.9*Math.abs(i-t);e.save(),e.beginPath(),o?(e.moveTo(t,r),e.lineTo(t+l,r),e.lineTo(i,a),e.lineTo(i-l,a)):(e.moveTo(i-l,r),e.lineTo(i,r),e.lineTo(t+l,a),e.lineTo(t,a)),e.closePath(),e.fill(),e.stroke(),e.restore()}!function(e){e.Line="Line",e.Histogram="Histogram",e.Area="Area",e.Bar="Bar",e.Candlestick="Candlestick",e.Ohlc="Ohlc",e.Symbol="Symbol",e.Custom="Custom"}(Rs||(Rs={}));const tn={visible:!0,autoScale:!1,xScaleLock:!1,yScaleLock:!1,color:"#737375",lineWidth:1,upColor:"rgba(0,255,0,.25)",downColor:"rgba(255,0,0,.25)",wickVisible:!0,borderVisible:!0,borderColor:"#737375",borderUpColor:"#1c9d1c",borderDownColor:"#d5160c",wickColor:"#737375",wickUpColor:"#1c9d1c",wickDownColor:"#d5160c",radius:100,shape:"Rounded",chandelierSize:1,barSpacing:.8,lineStyle:0,lineColor:"#ffffff",width:1};class sn{handler;get data(){return this.convertAndAggregateDataPoints()}get sourceData(){return this._originalData}_originalP1;_originalP2;_barWidth=.8;p1;p2;_options;series;_originalData=[];_originalSlice=[];offset;onComplete;get spatial(){return this.recalculateSpatial()}transform={scale:{x:1,y:1},shift:{x:0,y:0}};constructor(e,t,i,s,n,o){let r,a;this.handler=e,this._options={...n,...tn},Math.min(i.logical,s.logical)===i.logical?(r=i,a=s):(r=s,a=i),this._originalP1={...r},this._originalP2={...a},this.offset=o??0,this.p1=i,this.p2=s,x(t)?(this.series=t,this._originalData=this.series.data().map(((e,t)=>({...e,x1:t,x2:t+1})))):(this.series=this.handler.series||this.handler._seriesList[0],this._originalData=t._originalData);const l=Math.min(this._originalP1.logical,this._originalP2.logical),c=Math.max(this._originalP1.logical,this._originalP2.logical);o&&o>0?(this._originalSlice=this._originalData.slice(c,Math.min(this.series.data().length-1,c+1+o)),console.log("Data Sliced with Offset",l,c,o,"Offset Point:",Math.min(this.series.data().length-1,c+1+o))):(this._originalSlice=this._originalData.slice(l,c+1),console.log("Data Sliced:",l,c)),o&&o>0&&(this._originalSlice=this._originalSlice.map((e=>({...e,x1:e.x1+o,x2:e.x2+o}))),console.log("Adjusted originalSlice with pOffset:",o)),this.transform=this.recalculateSpatial(),this.p1&&this.p2&&this.setPoints(this.p1,this.p2)}setData(e){this._originalSlice=e}setPoints(e,t){let i,s;Math.min(e.logical,t.logical)===e.logical?(i=e,s=t):(i=t,s=e),null===this._originalP1?(this._originalP1={...i},console.log("First point (p1) set:",this._originalP1)):null===this._originalP2&&(this._originalP2={...s},console.log("Second point (p2) set:",this._originalP2)),this.p1=i,this.p2=s,this.recalculateSpatial(),this.processSequence()}updatePoint(e,t){1===e?this.p1=t:2===e&&(this._originalP2||(this._originalP2=t),this.p2=t),this.recalculateSpatial(),this.processSequence()}recalculateSpatial(){if(!(this.p1&&this.p2&&this._originalP1&&this._originalP2))return console.warn("Cannot recalc spatial without valid p1/p2."),{scale:{x:1,y:1},shift:{x:0,y:0}};const e=Math.abs(this._originalP1.logical-this._originalP2.logical),t=Math.abs(this._originalP1.price-this._originalP2.price);if(0===e||0===t)return console.warn("Cannot recalc scale if original points are zero difference."),{scale:{x:1,y:1},shift:{x:0,y:0}};const i=Math.abs(this.p1.logical-this.p2.logical)/e,s=((this._originalP2.price>this._originalP1.price?this.p2.price:this.p1.price)-(this._originalP2.price>this._originalP1.price?this.p1.price:this.p2.price))/t;this._options.xScaleLock||(this.transform.scale.x=i),this._options.yScaleLock||(this.transform.scale.y=s),this._options.autoScale&&i>-1&&i<1&&(this._options.chandelierSize=Math.abs(Math.ceil(1/i)));const n={scale:{x:0!==i?Math.round(100*i)/100:1,y:0!==s?Math.round(100*s)/100:1},shift:{x:this._originalP1.logical-this.p1.logical,y:this._originalP1.price-this.p1.price}};return this._barWidth=Math.abs(this.p1.logical-this.p2.logical)/this._originalData.length,console.log("Spatial recalculated:","scaleX=",n.scale.x,"scaleY=",n.scale.y,"shiftX=",n.shift.x,"shiftY=",n.shift.y),0===n.scale.x||0===n.scale.y?(console.warn("Scale factors cannot be zero."),{scale:{x:1,y:1},shift:{x:0,y:0}}):n}processSequence(){this.p1&&this.p2?(this.convertAndAggregateDataPoints(),this.onComplete&&this.onComplete()):console.warn("Cannot process sequence without valid p1/p2.")}convertAndAggregateDataPoints(){let e=Number.POSITIVE_INFINITY,t=Number.NEGATIVE_INFINITY;const i={...this.spatial};this._originalSlice.forEach((i=>{const s=[];void 0!==i.open&&s.push(i.open),void 0!==i.high&&s.push(i.high),void 0!==i.low&&s.push(i.low),void 0!==i.close&&s.push(i.close),void 0!==i.value&&s.push(i.value);for(const i of s)it&&(t=i)}));const s=t===e?1:t-e,n=this.p1.logical,o=this._originalSlice.map(((t,o)=>{const r=n+o;function a(t,i){if(void 0===t)return;const n=(t-e)/s;return e-i.shift.y+n*i.scale.y*s}const c=a(t.open,i),h=a(t.close,i),p=a(t.high,i),d=a(t.low,i),u=a(t.value,i);if(void 0!==c||void 0!==h||void 0!==p||void 0!==d){const e=(h??0)>(c??0),i=e?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)",s=e?this._options.borderUpColor||l(i,1):this._options.borderDownColor||l(i,1),n=e?this._options.wickUpColor||s:this._options.wickDownColor||s;return{open:c,close:h,high:p,low:d,isUp:e,x1:r+this.offset,x2:r+1+this.offset,isInProgress:!1,originalData:{...t,x1:o},barSpacing:this._barWidth,color:i,borderColor:s,wickColor:n,lineStyle:this._options.lineStyle,lineWidth:this._options.lineWidth,shape:this._options.shape??"Rounded"}}return{value:u,isUp:void 0,x1:r+this.offset,x2:r+1+this.offset,isInProgress:!1,originalData:t,barSpacing:this._options.barSpacing??.8}})),r=this._options.chandelierSize??1;if(r<=1)return o;const a=[];for(let e=0;eMath.max(e,t.high||0)),0),a=e.reduce(((e,t)=>Math.min(e,t.low||1/0)),1/0),c=o>i,h=c?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)",p=c?this._options.borderUpColor||l(h,1):this._options.borderDownColor||l(h,1),d=c?this._options.wickUpColor||p:this._options.wickDownColor||p,u=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options.lineStyle),m=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options.lineWidth??1);return{open:i,high:r,low:a,close:o,isUp:c,x1:s,x2:n,isInProgress:t,color:h,borderColor:p,wickColor:d,shape:this._options.shape??"Rounded",lineStyle:u,lineWidth:m}}{const t=e[0].value??0,i=(e[e.length-1].value??0)>t,o=i?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)";i?this._options.borderUpColor||l(o,1):this._options.borderDownColor||l(o,1);i?this._options.wickUpColor:this._options.wickDownColor;const r=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options.lineStyle),a=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options.lineWidth??1);return this._options.shape,{value:t,isUp:i,x1:s,x2:n,color:o,lineStyle:r,lineWidth:a}}}applyOptions(e){this._options={...this._options,...e},this.processSequence()}}class nn extends a{_type="TrendTrace";_paneViews;_sequence;_options;_state=N.NONE;_handler;_source;_originalP1=null;_originalP2=null;p1=null;p2=null;_points=[];title="";static _type="Trend-Trace";_startDragPoint=null;_latestHoverPoint=null;static _mouseIsDown=!1;static hoveredObject=null;static lastHoveredObject=null;_listeners=[];_hovered=!1;constructor(e,t,i,s,n,o){super(),this._handler=e,this._source=t,this._originalP1={...i},this._originalP2={...s};const r=this._source.options(),a=function(e,t){const i={};for(const s in e)Object.prototype.hasOwnProperty.call(t,s)&&(i[s]=t[s]);return i}(tn,r);this._options={...a,...n},this._sequence=this._createSequence({p1:i,p2:s},this._options,o),this.p1=this._sequence.p1,this.p2=this._sequence.p2,this._subscribeEvents(),this._paneViews=[new on(this)]}toJSON(){return{data:this._sequence.data,p1:this._sequence._originalP1,p2:this._sequence._originalP2,options:this._sequence._options}}fromJSON(e){if(e.data&&this._sequence.setData(e.data),e.options){const t=e.options;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const i=e;this.applyOptions({[i]:t[i]})}}e.p1&&(this.p1=e.p1),e.p2&&(this.p2=e.p2)}attached(e){super.attached(e),this._originalP1&&this._originalP2&&this._createSequence({p1:this._originalP1,p2:this._originalP2}),this._source=Bs(e.series,this._handler.legend),this.title=e.series.options().title;const i=new(t.defaultHorzScaleBehavior());return{chart:e.chart,series:e.series,requestUpdate:e.requestUpdate,horzScaleBehavior:i}}paneViews(){return this._paneViews}detached(){super.detached(),this._listeners.forEach((({name:e,listener:t})=>{document.body.removeEventListener(e,t)})),this._listeners=[],this._handler?.chart&&(this._handler.chart.unsubscribeCrosshairMove(this._handleMouseMove),this._handler.chart.unsubscribeClick(this._handleMouseDownOrUp)),this._paneViews=[],this._sequence=null,this._options=null,this._source=null,this._originalP1=null,this._originalP2=null,this.p1=null,this.p2=null,console.log("✅ All listeners and references successfully detached.")}_createSequence(e,t,i){let s;return"p1"in e&&"p2"in e?(s=new sn(this._handler,this._source,e.p1,e.p2,t??this._options,i),s.onComplete=()=>this.updateViewFromSequence(),this.updateViewFromSequence(),s):(s=new sn(this._handler,e.data,e.data._originalP1,e.data._originalP2,t??this._options,i),s.onComplete=()=>this.updateViewFromSequence(),this.updateViewFromSequence(),s)}applyOptions(e){this._options={...this._options,...e},this._sequence&&this._sequence.applyOptions(this._options),this.requestUpdate()}_pendingUpdate=!1;updateViewFromSequence(){this._pendingUpdate||(this._pendingUpdate=!0,requestAnimationFrame((()=>{super.requestUpdate(),console.log("Updating view with sequence data:",this._sequence?.data),this._pendingUpdate=!1})))}getOptions(){return this._options}_subscribeEvents(){this._handler.chart.subscribeCrosshairMove(this._handleMouseMove),this._handler.chart.subscribeClick(this._handleMouseDownOrUp)}_subscribe(e,t){document.body.addEventListener(e,t),this._listeners.push({name:e,listener:t})}_unsubscribe(e,t){document.body.removeEventListener(e,t);const i=this._listeners.find((i=>i.name===e&&i.listener===t));this._listeners.splice(this._listeners.indexOf(i),1)}_handleHoverInteraction(e){if(this._latestHoverPoint=e.point,nn._mouseIsDown)this._handleDragInteraction(e);else if(this._mouseIsOverSequence(e)){if(this._state!=N.NONE)return;this._moveToState(N.HOVERING),nn.hoveredObject=nn.lastHoveredObject=this}else{if(this._state==N.NONE)return;this._moveToState(N.NONE),nn.hoveredObject===this&&(nn.hoveredObject=null)}}_handleMouseDownOrUp=()=>{this._latestHoverPoint&&(nn._mouseIsDown=!nn._mouseIsDown,nn._mouseIsDown?this._onMouseDown():this._onMouseUp())};_handleMouseMove=e=>{const t=this._eventToPoint(e,this._source);this._latestHoverPoint=t,nn._mouseIsDown?this._handleDragInteraction(e):this._mouseIsOverPoint(e,1)||this._mouseIsOverPoint(e,2)||this._mouseIsOverSequence(e)?this._state===N.NONE&&this._moveToState(N.HOVERING):this._state!==N.NONE&&this._moveToState(N.NONE)};_onMouseUp(){nn._mouseIsDown=!1,this.chart.applyOptions({handleScroll:!0}),this._moveToState(N.HOVERING),this._startDragPoint=null}_handleDragInteraction(e){if(this._state!==N.DRAGGING&&this._state!==N.DRAGGINGP1&&this._state!==N.DRAGGINGP2)return;const t=this._eventToPoint(e,this.series);if(!t||!this._startDragPoint)return;const i=this._getDiff(t,this._startDragPoint);this._onDrag(i),this._startDragPoint=t,this.requestUpdate()}_mouseIsOverPoint(e,t){const i=1===t?{x:this._paneViews[0]._p1.x,y:this._paneViews[0]._p1.y}:{x:this._paneViews[0]._p2.x,y:this._paneViews[0]._p2.y};return!!this.chart&&function(e,t,i,s){const n=function(e){if(!e)return null;const t=e.paneSize();return{width:t.width,height:t.height}}(s);if(!n)return!1;const o=n.width,r=n.height,a=o*i,l=r*i,c=function(e){if(e instanceof MouseEvent)return(t=e)?{x:t.x,y:t.y}:null;var t;if("point"in e&&e.point)return e.point;return null}(e);if(!c||null==c.x||null==c.y||null==t.x||null==t.y)return!1;const h=Math.abs(t.x-c.x),p=Math.abs(t.y-c.y);return h<=a&&p<=l}(e,i,.05,this.chart)}_mouseIsOverSequence(e){if(!e.logical||!e.point)return console.warn("Invalid MouseEventParams: Missing logical or point."),!1;const t=this._source.coordinateToPrice?.(e.point.y);if(null==t)return console.warn("Mouse price could not be determined."),!1;let i=e.time?this._sequence.data.find((t=>t.time===e.time)):void 0;if(i||(i=this._sequence.data.find((t=>Math.round(t.x1)===Math.round(e.logical)))),!i)return console.warn("No matching bar found for the given parameters."),!1;if(null!=i.low&&null!=i.high){const e=.05*(i.high-i.low);return t>=i.low-e&&t<=i.high+e}if(null!=i.value){const e=.05*i.value;return t>=i.value-e&&t<=i.value+e}return console.warn("Bar lacks price information."),!1}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this.requestUpdate(),this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this.requestUpdate(),this._subscribe("mousedown",this._handleMouseDownInteraction),this._unsubscribe("mouseup",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_addDiffToPoint(e,t,i){e&&(e.logical=e.logical+t,e.price=e.price+i,e.time=this.series.dataByIndex(e.logical)?.time||null)}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this._sequence.p1,this._options.xScaleLock&&this._state==N.DRAGGINGP1?0:e.logical,this._options.yScaleLock&&this._state==N.DRAGGINGP1?0:e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this._sequence.p2,this._options.xScaleLock&&this._state==N.DRAGGINGP2?0:e.logical,this._options.yScaleLock&&this._state==N.DRAGGINGP2?0:e.price)}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint;if(!e)return;const t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);Math.abs(e.x-t.x)<20&&Math.abs(e.y-t.y)<20?(this.chart.applyOptions({handleScroll:!1}),this._moveToState(N.DRAGGINGP1)):Math.abs(e.x-i.x)<20&&Math.abs(e.y-i.y)<20?(this.chart.applyOptions({handleScroll:!1}),this._moveToState(N.DRAGGINGP2)):(this.chart.applyOptions({handleScroll:!1}),this._moveToState(N.DRAGGING))}_handleMouseDownInteraction=()=>{this._onMouseDown()};_handleMouseUpInteraction=()=>{this._onMouseUp()};_getDiff(e,t){return{logical:e.logical-t.logical,price:e.price-t.price}}_eventToPoint(e,t){if(!t||!e.point||!e.logical)return null;const i=t.coordinateToPrice(e.point.y);return null==i?null:{time:e.time||null,logical:e.logical,price:i.valueOf()}}}class on{_p1={x:null,y:null};_p2={x:null,y:null};_plugin;constructor(e){this._plugin=e}renderer(){if(!this._plugin._sequence)throw new Error("No sequence available for rendering.");return new rn(this._plugin,this._plugin._options,!1)}}class rn extends G{_source;_options;constructor(e,t,i){super(Ws(e._sequence.p1,e.chart,e._source),Ws(e._sequence.p2,e.chart,e._source),t,i),this._source=e,this._options=t}draw(e){e.useBitmapCoordinateSpace((e=>{const t=e.context,{chart:i}=this._source;t.save();const{horizontalPixelRatio:s}=e,n=this._source._sequence.data,o=this._source.chart.timeScale(),r=this._source._source,a=i.timeScale().getVisibleLogicalRange(),l=i.options().width/((a?.to??n.length)-(a?.from??0));if(console.log("barSpace:",l),!r||!o||0===n.length)return void t.restore();const c=n[0].x1,h=n[n.length-1].x2,p=i.timeScale().logicalToCoordinate(c)??0,d=i.timeScale().logicalToCoordinate(h)??p,u=p*s,m=d*s,g=this._source._sequence._originalP2.logical>this._source._sequence._originalP1.logical&&this._source._sequence.p2.logical>this._source._sequence.p1.logical||this._source._sequence._originalP2.logical{const i=u+(g?1:-1)*(t*((m-u)/n.length)*this._source._sequence.spatial.scale.x),s=(t+1)*((m-u)/n.length)*this._source._sequence.spatial.scale.x-(1-(this._options.barSpacing??.8))*(m-u)/n.length/(this._options.chandelierSize??1),o=e.isUp?g?this._options.upColor:this._options.downColor:g?this._options.downColor:this._options.upColor,r=e.isUp?g?this._options.borderUpColor:this._options.borderDownColor:g?this._options.borderDownColor:this._options.borderUpColor,a=e.isUp?g?this._options.wickUpColor:this._options.wickDownColor:g?this._options.wickDownColor:this._options.wickUpColor;return{...e,scaledX1:i,scaledX2:s,color:o,borderColor:r,wickColor:a}})).filter((e=>null!==e));console.log("Scaled bars:",f),this.isOHLCData(n)?(this._options.wickVisible&&this._drawWicks(e,f,l),this._drawCandles(e,f,l)):this.isSingleValueData(n)&&this._drawSingleValueData(e,f),t.restore()}))}_drawSingleValueData(e,t){const{context:i,horizontalPixelRatio:s,verticalPixelRatio:n}=e;i.lineWidth=this._options.lineWidth??1,U(i,this._options.lineStyle??1),i.strokeStyle=this._options.visible?this._options.lineColor??"#ffffff":"rgba(0,0,0,0)",i.beginPath(),t.forEach((e=>{if(null===e.x1||void 0===e.x1)return;const t=e.scaledX1*s,o=(this._source._source?.priceToCoordinate(e.value??0)??0)*n;i.lineTo(t,o),i.stroke()}))}_drawWicks(e,t,i){const{context:s,verticalPixelRatio:n}=e;this._source._sequence._originalP2.price>this._source._sequence._originalP1.price&&this._source._sequence.p2.price>this._source._sequence.p1.price||this._source._sequence._originalP2.pricethis._source._sequence._originalP1.logical&&this._source._sequence.p2.price>this._source._sequence.p1.price;t[0].scaledX1,t[t.length-1].scaledX2;t.length;const r=Math.abs(i);t.forEach(((e,i)=>{const a=(this._options.barSpacing??.8)*r,l=r-a;let c=e.scaledX1,h=c+(e.x2-e.x1+((this._options.chandelierSize??1)>1?1:0))*r-l;if(i{const o=(this._options.barSpacing??.8)*a,l=a-o;if(!e)return;const c=(this._source.series.priceToCoordinate(e.open)??0)*r,h=(this._source.series.priceToCoordinate(e.close)??0)*r,p=(this._source.series.priceToCoordinate(e.high)??0)*r,d=(this._source.series.priceToCoordinate(e.low)??0)*r,u=h>=c,m=Math.min(c,h),g=Math.max(c,h),f=m-g,y=(m+g)/2;let b=e.scaledX1-.5*a,v=b+(e.x2-e.x1+((this._options.chandelierSize??1)>1?1:0))*a-l;if(ivoid 0!==e.open&&void 0!==e.high&&void 0!==e.low&&void 0!==e.close))}isSingleValueData(e){return e.every((e=>void 0!==e.value))}}function an(e){let t=0;for(const i of e){if(!i||!Number.isNaN(i.value))break;t++}return t}const ln={color:"white",border:"none",padding:"5px 10px",cursor:"pointer",borderRadius:"12px",boxShadow:"0 2px 4px rgba(0,0,0,0.2)",transition:"transform 0.2s ease-in-out"};class cn{container;header;editorDiv;resizer;editorInstance=null;closeButton;isResizing=!1;startY=0;startHeight=0;MIN_HEIGHT=100;MAX_HEIGHT=window.innerHeight-50;scripts={};handler;_dataChangeHandlers=new Map;selectedSeries=null;selectedVolumeSeries=null;constructor(e){this.handler=e,this.selectedSeries=this.handler.series,this.selectedVolumeSeries=this.handler.volumeSeries??null,this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"0",width:"100%",height:"300px",backgroundColor:"#000000",borderTop:"2px solid #222",zIndex:"10000",display:"none",flexDirection:"column"}),this.resizer=document.createElement("div"),Object.assign(this.resizer.style,{height:"5px",width:"100%",backgroundColor:"#111",cursor:"ns-resize",userSelect:"none"}),this.resizer.addEventListener("mousedown",this.onDragStart.bind(this)),document.addEventListener("mousemove",this.onDrag.bind(this)),document.addEventListener("mouseup",this.onDragEnd.bind(this)),this.container.appendChild(this.resizer),this.header=document.createElement("div"),Object.assign(this.header.style,{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"10px",backgroundColor:"#000"});const t=document.createElement("div");t.style.display="flex",t.style.alignItems="center",t.style.gap="10px";const i=document.createElement("span");i.innerText="PineTS Script Editor ",i.style.color="white",t.appendChild(i);const s=document.createElement("div");s.style.display="flex",s.style.gap="10px";const n=document.createElement("button");n.innerText="Execute",Object.assign(n.style,ln,{backgroundColor:"#2A8D08"}),n.onmouseover=()=>{n.style.transform="scale(1.05)"},n.onmouseout=()=>{n.style.transform="scale(1)"},n.onclick=()=>{this.executePineTS()},s.appendChild(n);const o=document.createElement("div");Object.assign(o.style,{display:"inline-flex",border:"1px solid #0A42FA",borderRadius:"8px",overflow:"hidden",position:"relative"});const r=document.createElement("button");r.innerText="Save",Object.assign(r.style,ln,{backgroundColor:"#0A42FA",borderRadius:"0px"}),r.onmouseover=()=>{r.style.transform="scale(1.05)"},r.onmouseout=()=>{r.style.transform="scale(1)"},r.onclick=()=>{this.saveScript()},o.appendChild(r);const a=document.createElement("button");a.innerText="🛠",Object.assign(a.style,ln,{backgroundColor:"#0A42FA",borderLeft:"1px solid #fff",borderRadius:"0px",padding:"5px"}),a.onmouseover=()=>{a.style.transform="scale(1.05)"},a.onmouseout=()=>{a.style.transform="scale(1)"},a.onclick=e=>{const t=document.getElementById("save-dropdown");if(t)return void t.remove();const i=document.createElement("div");i.id="save-dropdown",Object.assign(i.style,{position:"absolute",backgroundColor:"#0A42FA",color:"white",border:"1px solid #fff",borderRadius:"4px",marginTop:"5px",zIndex:"100000"});const s=document.createElement("div");s.innerText="Save As",s.style.padding="5px 10px",s.style.cursor="pointer",s.onclick=()=>{this.saveToFile(),i.remove()},i.appendChild(s);const n=o.getBoundingClientRect();i.style.left=n.left+"px",i.style.top=n.bottom+"px",document.body.appendChild(i)},o.appendChild(a),s.appendChild(o);const l=document.createElement("div");Object.assign(l.style,{display:"inline-flex",border:"1px solid #AC0202",borderRadius:"8px",overflow:"hidden",position:"relative"});const c=document.createElement("button");c.innerText="Script",Object.assign(c.style,ln,{backgroundColor:"#AC0202",borderRadius:"0px"}),c.onmouseover=()=>{c.style.transform="scale(1.05)"},c.onmouseout=()=>{c.style.transform="scale(1)"},c.onclick=()=>{console.log("Current script: "+c.innerText)},l.appendChild(c);const h=document.createElement("button");h.innerText="🗄",Object.assign(h.style,ln,{backgroundColor:"#AC0202",borderLeft:"1px solid #fff",borderRadius:"0px",padding:"5px"}),h.onmouseover=()=>{h.style.transform="scale(1.05)"},h.onmouseout=()=>{h.style.transform="scale(1)"},h.onclick=e=>{const t=document.getElementById("script-dropdown");if(t)return void t.remove();const i=document.createElement("div");i.id="script-dropdown",Object.assign(i.style,{position:"absolute",backgroundColor:"#AC0202",color:"white",border:"1px solid #fff",borderRadius:"4px",marginTop:"5px",zIndex:"100000"});Object.keys(this.scripts).forEach((e=>{const t=document.createElement("div");t.innerText=e,t.style.padding="5px 10px",t.style.cursor="pointer",t.onclick=()=>{this.scripts[e]&&this.scripts[e].code&&(this.setValue(this.scripts[e].code),c.innerText=e,console.log(`Loaded script "${e}" from memory.`)),i.remove()},i.appendChild(t)}));const s=document.createElement("div");s.innerText="Open...",s.style.padding="5px 10px",s.style.cursor="pointer",s.onclick=()=>{this.openScriptFromFile(),i.remove()},i.appendChild(s);const n=l.getBoundingClientRect();i.style.left=n.left+"px",i.style.top=n.bottom+"px",document.body.appendChild(i)},l.appendChild(h),s.appendChild(l);const p=document.createElement("div");Object.assign(p.style,{display:"inline-flex",border:"1px solid #696969",borderRadius:"8px",overflow:"hidden",position:"relative"});const d=document.createElement("button");d.innerText="Select Main Series",Object.assign(d.style,ln,{backgroundColor:"#696969",borderRadius:"0px"}),d.onmouseover=()=>{d.style.transform="scale(1.05)"},d.onmouseout=()=>{d.style.transform="scale(1)"},d.onclick=e=>{this.populateMainSeriesSelectMenu(e,(e=>{this.selectedSeries=e,console.log("Selected Main Series:",e)}))},p.appendChild(d);const u=document.createElement("button");u.innerText="∿",Object.assign(u.style,ln,{backgroundColor:"#696969",borderLeft:"1px solid #fff",borderRadius:"0px",padding:"5px"}),u.onmouseover=()=>{u.style.transform="scale(1.05)"},u.onmouseout=()=>{u.style.transform="scale(1)"},u.onclick=e=>{const t=document.getElementById("series-dropdown");if(t)return void t.remove();const i=document.createElement("div");i.id="series-dropdown",Object.assign(i.style,{position:"absolute",backgroundColor:"#696969",color:"white",border:"1px solid #fff",borderRadius:"4px",marginTop:"5px",zIndex:"100000"});const s=document.createElement("div");s.innerText="Select Main Series",s.style.padding="5px 10px",s.style.cursor="pointer",s.onclick=e=>{this.populateMainSeriesSelectMenu(e,(e=>{this.selectedSeries=e,console.log("Selected Main Series:",e)})),i.remove()},i.appendChild(s);const n=document.createElement("div");n.innerText="Select Volume Series",n.style.padding="5px 10px",n.style.cursor="pointer",n.onclick=e=>{this.populateVolumeSeriesSelectMenu(e,(e=>{this.selectedVolumeSeries=e,console.log("Selected Volume Series:",e)})),i.remove()},i.appendChild(n);const o=p.getBoundingClientRect();i.style.left=o.left+"px",i.style.top=o.bottom+"px",document.body.appendChild(i)},p.appendChild(u),s.appendChild(p),t.appendChild(s),this.closeButton=document.createElement("button"),this.closeButton.innerText="Close",Object.assign(this.closeButton.style,ln,{backgroundColor:"#ff0000"}),this.closeButton.onmouseover=()=>{this.closeButton.style.transform="scale(1.05)"},this.closeButton.onmouseout=()=>{this.closeButton.style.transform="scale(1)"},this.closeButton.onclick=()=>this.close(),this.header.appendChild(t),this.header.appendChild(this.closeButton),this.container.appendChild(this.header),this.editorDiv=document.createElement("div"),Object.assign(this.editorDiv.style,{flex:"1",height:"calc(100% - 45px)"}),this.container.appendChild(this.editorDiv),document.body.appendChild(this.container),this.initializeMonaco(),this.loadInitialScript()}initializeMonaco(){let e="";if(this.handler.scriptsManager&&"function"==typeof this.handler.scriptsManager.getLast){const t=this.handler.scriptsManager.getLast();t&&t.code&&(e=t.code)}e||(e="\n\n\n// * @EsIstJosh\n// * This feature implements a variation of PineTS, source : and is \n// * licensed under the GNU AGPL v3.0. V\n// * The original AGPL license text is included in the AGPL_LICENSE file in the repository.\n// * \n// * Note: This file imports modules that remain under the MIT license \n// * The original MIT license text is included in the MIT_LICENSE file in the repository.\n// *\n// * For the full text of the GNU AGPL v3.0, see .\n\n\n// * //-----------------Work in Progress...-------------------//\n// * EXAMPLE SCRIPT CONVERSION // \n// * PINE SCRIPT ⥵ //PINE TS \n// * \n// * //@version=5 ⥵ // @version=5\n// * indicator('Simple EMA','EMA', overlay=true) ⥵ indicator('Simple EMA','EMA', {overlay=true}) \n// * ⥵ \n// * ema9 = ta.ema(close, 9); ⥵ const ema9 = ta.ema(close, 9) \n// * ema18 = ta.ema(close, 18); ⥵ const ema18 = ta.ema(close, 18)\n// * plot(ema9,'EMA9', color= #ff0000, linewidth= 2, style = plot.style_line) ⥵ plot(ema9,'EMA9',{ style: 'line', color: '#ff0000', linewidth: 2 })\n// * plot(ema18,'EMA18', color= #ff7700, linewidth= 2, style = plot.style_line) ⥵ plot(ema18,'EMA18',{ style: 'line', color: '#ff7700', linewidth: 2 })\n\n\n\n indicator('Title', 'TA', { overlay : true })\n // \n const ema1 = ta.ema(close,16)\n const ema2 = ta.ema(close,32)\n const ema3 = ta.ema(close,48)\n const ema4 = ta.ema(close,64)\n const ema5 = ta.ema(close,96)\n const ema6 = ta.ema(close,128)\n plot(ema1,'EMA1',{ style: 'line', color: '#ff0000', linewidth: 2 })\n plot(ema2,'EMA2',{ style: 'cross', color: '#ff7700', linewidth: 2 })\n plot(ema3,'EMA3',{ style: 'circles', color: '#ffee00', linewidth: 2 })\n plot(ema4,'EMA4',{ style: '❖', color: '#00ff00', linewidth: 2 })\n plot(ema5,'EMA5',{ style: 'triangleUp', color: '#0050ff', linewidth: 2 })\n plot(ema6,'EMA6',{ style: 'arrowDown', color: '#ffffff', linewidth: 2 })\n\n fill('EMA1','EMA2')\n fill('EMA2','EMA3')\n fill('EMA3','EMA4')\n fill('EMA4','EMA5')\n fill('EMA5','EMA6')\n\n\n "),this.editorInstance=o.editor.create(this.editorDiv,{value:e,language:"javascript",theme:"vs-dark",automaticLayout:!0}),console.log("Monaco Editor initialized in pane with initial code.")}loadInitialScript(){let e="";if(this.handler.scriptsManager&&"function"==typeof this.handler.scriptsManager.getLast){const t=this.handler.scriptsManager.getLast();t&&t.code&&(e=t.code)}e?(this.setValue(e),console.log("Loaded most recent script from scriptsManager.")):console.log("No saved scripts available in scriptsManager; editor value remains unchanged.")}open(){this.container.style.display="flex",this.editorInstance?.layout(),window.monaco=!0}close(){this.container.style.display="none",window.monaco=!1}setValue(e){this.editorInstance?.setValue(e)}getValue(){return this.editorInstance?.getValue()||""}async executePineTS(){try{const e=this.getValue(),t=/^(?!\s*\/\/)(?!\s*\*)(.*indicator\s*\(\s*['"]([^'"]+)['"])/m,i=e.match(t),s=i?.[2]?i[2].replace(/['"]/g,""):"defaultScript";console.log("Extracted script key:",s);const n=(this.selectedSeries??this.handler.series).options().title,o=(this.selectedVolumeSeries??this.handler.volumeSeries)?.options?.()?.title||"",r=function(e,t=[]){return e.map(((e,i)=>hn(e,t[i]))).filter((e=>null!==e))}([...(this.selectedSeries??this.handler.series).data()],[...this.selectedVolumeSeries?this.selectedVolumeSeries.data():[]]),a=new ns(r,this.handler.series.options().title,"1D"),l=`(context) => { \n \nconst { close, open, high, low, hlc3, volume, hl2, ohlc4 } = context.data;\nconst { plotchar, plot, na, indicator, nz, plotcandle, plotbar, fill} = context.core;\nconst ta = context.ta;\nconst math = context.math;\nconst input = context.input;\n\n${e}\n }`,{plots:c,candles:h,bars:p,fills:d,ta:u}=await a.run(l,void 0,!1);console.log("Plots:",c),console.log("Candles:",h),console.log("Bars:",p);let m=0;if(c)for(const e in c)if(c.hasOwnProperty(e)){Gs(this.handler,e,c[e],void 0,"overwrite");const t=c[e].data;if(Array.isArray(t)){const e=an(t);e>m&&(m=e)}}if(h)for(const e in h)h.hasOwnProperty(e)&&Gs(this.handler,e,h[e],"Candlestick","overwrite");if(p)for(const e in p)p.hasOwnProperty(e)&&Gs(this.handler,e,p[e],"Bar","overwrite");if(d)for(const e in d)d.hasOwnProperty(e)&&Us(this.handler,d[e]);this.scripts[s]={pineTSInstance:a,ohlc:n,volume:o,code:e,n:m+1};this.handler.seriesMap.get(n);this.replaceScript(s)}catch(e){console.error("Error executing PineTS code:",e)}}replaceScript(e){const t=this.scripts[e];if(!t||!t.ohlc)return void console.warn(`No series information found for script key: ${e}`);const i=t.ohlc,s=this.handler.seriesMap.get(i);if(!s)return void console.warn(`Series with title "${i}" not found.`);const n=s.data().length;if(this._dataChangeHandlers.has(e))try{const t=this._dataChangeHandlers.get(e);s.unsubscribeDataChanged(t),console.log("Unsubscribing old Data Change Handler.... Data Length:",n),this._dataChangeHandlers.delete(e)}catch(t){console.warn(`Error unsubscribing from data changes for script "${e}":`,t)}const o=t=>{try{console.log("Data Changed, updating.... Data Length:",n),this.executeSavedScript(e)}catch(t){console.error(`Error executing saved script for "${e}":`,t)}};this._dataChangeHandlers.set(e,o),s.subscribeDataChanged(o)}async executeSavedScript(e){try{const t=this.scripts[e]?.ohlc,i=this.scripts[e]?.volume,s=this.scripts[e]?.n??void 0;console.log(s);const n=t?this.handler.seriesMap.get(t):null,o=i?this.handler.seriesMap.get(i):null;if(!n)return void console.warn(`Main series with title "${n}" not found.`);const r=hn(n.dataByIndex(n.data().length-1),o?o.dataByIndex(o.data().length-1):void 0),a=this.scripts[e]?.pineTSInstance;if(!a)return void console.warn(`No saved PineTS instance found for key: ${e}`);a.updateData(r);const{plots:l,candles:c,bars:h,fills:p,ta:d}=await a.run(void 0,s,!0);if(console.log("Plots:",l),console.log("Candles:",c),console.log("Bars:",h),l)for(const e in l)l.hasOwnProperty(e)&&Gs(this.handler,e,l[e],void 0,"update");if(c)for(const e in c)l.hasOwnProperty(e)&&Gs(this.handler,e,c[e],"Candlestick","update");if(h)for(const e in h)l.hasOwnProperty(e)&&Gs(this.handler,e,h[e],"Bar","update")}catch(e){console.error("Error executing PineTS code:",e)}}saveScript(e){const t=this.getValue(),i=t.match(/^(?!\s*\/\/)(?!\s*\*)(.*indicator\s*\(\s*['"]([^'"]+)['"])/m),s=i?.[2]?i[2].replace(/['"]/g,""):"defaultScript";this.scripts[s]?this.scripts[s].code=t:this.scripts[s]={ohlc:(this.selectedSeries??this.handler.series).options().title,volume:(this.selectedVolumeSeries??this.handler.volumeSeries).options().title,code:t,pineTSInstance:e??null,n:null},console.log(`Script "${s}" updated in memory.`);const n=this.scripts[s],o=JSON.stringify(n,null,2),r=`save_script_~_${s};;;${o}`;window.callbackFunction(r),console.log(`Script "${s}" sent via callback.`);const a=`save_script_~_cache;;;${o}`;window.callbackFunction(a),console.log('Cache script sent via callback under the name "cache".')}async saveToFile(e){const t=this.getValue(),i=prompt("Enter a new script name/title:","MyNewScript");if(!i)return void console.warn("Save To File canceled or no name provided.");this.scripts[i]={ohlc:(this.selectedSeries??this.handler.series).options().title,volume:(this.selectedVolumeSeries??this.handler.volumeSeries).options().title,code:t,pineTSInstance:e??null,n:null},console.log(`Script saved as "${i}" in memory.`);const s=JSON.stringify(this.scripts[i],null,2),n=`${i}.json`;this.downloadJson(s,n);const o=JSON.stringify(this.scripts[i],null,2);this.downloadJson(o,"cache.json")}openScriptFromFile(){const e=document.createElement("input");e.type="file",e.accept=".json",e.style.display="none",e.onchange=e=>{const t=e.target;if(t.files&&t.files.length>0){const e=t.files[0],i=new FileReader;i.onload=e=>{try{const t=e.target?.result;if("string"==typeof t){const e=JSON.parse(t);e&&e.code?(this.setValue(e.code),console.log("Loaded script from file.")):console.error("The selected file does not contain a valid script with a 'code' property.")}}catch(e){console.error("Error parsing JSON file:",e)}},i.readAsText(e)}},document.body.appendChild(e),e.click(),e.remove()}downloadJson(e,t){try{const i=new Blob([e],{type:"application/json"}),s=URL.createObjectURL(i),n=document.createElement("a");n.href=s,n.download=t,n.click(),URL.revokeObjectURL(s),console.log(`Downloaded ${t}`)}catch(e){console.error("Failed to download data: "+e)}}onDragStart(e){this.isResizing=!0,this.startY=e.clientY,this.startHeight=parseInt(window.getComputedStyle(this.container).height,10),e.preventDefault()}onDrag(e){if(!this.isResizing)return;const t=this.startHeight+(this.startY-e.clientY),i=Math.min(Math.max(t,this.MIN_HEIGHT),this.MAX_HEIGHT);this.container.style.height=`${i}px`,this.editorInstance?.layout()}onDragEnd(e){this.isResizing&&(this.isResizing=!1)}populateMainSeriesSelectMenu(e,t){const i=document.createElement("div");Object.assign(i.style,{position:"absolute",top:`${e.clientY}px`,left:`${e.clientX}px`,backgroundColor:"#333",color:"white",padding:"10px",borderRadius:"4px",zIndex:"100000"});const s=document.createElement("ul");Object.assign(s.style,{listStyle:"none",margin:"0",padding:"0"});const n=Array.from(this.handler.seriesMap.entries()).map((([e,t])=>({label:e,value:t})));this.handler.volumeSeries&&n.push({label:"Volume",value:this.handler.volumeSeries}),n.forEach((e=>{const n=document.createElement("li");n.innerText=e.label,n.style.cursor="pointer",n.style.padding="5px",n.onclick=()=>{t(e.value),document.body.removeChild(i)},s.appendChild(n)}));const o=document.createElement("li");o.innerText="Cancel",o.style.cursor="pointer",o.style.padding="5px",o.onclick=()=>{document.body.removeChild(i)},s.appendChild(o),i.appendChild(s),document.body.appendChild(i)}populateVolumeSeriesSelectMenu(e,t){const i=document.createElement("div");Object.assign(i.style,{position:"absolute",top:`${e.clientY}px`,left:`${e.clientX}px`,backgroundColor:"#333",color:"white",padding:"10px",borderRadius:"4px",zIndex:"100000"});const s=document.createElement("ul");Object.assign(s.style,{listStyle:"none",margin:"0",padding:"0"});const n=document.createElement("li");n.innerText="None",n.style.cursor="pointer",n.style.padding="5px",n.onclick=()=>{t(null),document.body.removeChild(i)},s.appendChild(n);const o=Array.from(this.handler.seriesMap.entries()).map((([e,t])=>({label:e,value:t})));this.handler.volumeSeries&&o.push({label:"Volume",value:this.handler.volumeSeries}),o.forEach((e=>{const n=document.createElement("li");n.innerText=e.label,n.style.cursor="pointer",n.style.padding="5px",n.onclick=()=>{t(e.value),document.body.removeChild(i)},s.appendChild(n)}));const r=document.createElement("li");r.innerText="Cancel",r.style.cursor="pointer",r.style.padding="5px",r.onclick=()=>{document.body.removeChild(i)},s.appendChild(r),i.appendChild(s),document.body.appendChild(i)}}function hn(e,t){let i;return i="number"==typeof e.time?e.time:new Date(e.time).getTime(),isNaN(i)?(console.warn(`Invalid time format: ${e.time}`),null):{...e,openTime:i,closeTime:i+86399,volume:void 0!==e.volume?Number(e.volume):void 0!==t?Number(t.value):0}}class pn{makeButton;callbackName;div;isOpen=!1;widget;constructor(e,t,i,s,n,o){this.makeButton=e,this.callbackName=o,this.div=document.createElement("div"),this.div.classList.add("topbar-menu"),this.widget=this.makeButton(i+" ↓",null,s,!0,n),this.updateMenuItems(t),this.widget.elem.addEventListener("click",(()=>{if(this.isOpen=!this.isOpen,!this.isOpen)return void(this.div.style.display="none");let e=this.widget.elem.getBoundingClientRect();this.div.style.display="flex",this.div.style.flexDirection="column";let t=e.x+e.width/2;this.div.style.left=t-this.div.clientWidth/2+"px",this.div.style.top=e.y+e.height+"px"})),document.body.appendChild(this.div)}updateMenuItems(e){this.div.innerHTML="",e.forEach((e=>{let t=this.makeButton(e,null,!1,!1);t.elem.addEventListener("click",(()=>{this._clickHandler(t.elem.innerText)})),t.elem.style.margin="4px 4px",t.elem.style.padding="2px 2px",this.div.appendChild(t.elem)})),this.widget.elem.innerText=e[0]+" ↓"}_clickHandler(e){this.widget.elem.innerText=e+" ↓",window.callbackFunction(`${this.callbackName??"undefined"}_~_${e}`),this.div.style.display="none",this.isOpen=!1}}class dn{makeButton;div;isOpen=!1;widget;globalCallback;constructor(e,t,i,s,n,o,r){this.makeButton=e,this.globalCallback=r,this.div=document.createElement("div"),this.div.classList.add("topbar-menu"),this.widget=this.makeButton(i+" ↓",null,s,!0,n),this.updateMenuItems(t),this.widget.elem.addEventListener("click",(()=>{if(this.isOpen=!this.isOpen,!this.isOpen)return void(this.div.style.display="none");const e=this.widget.elem.getBoundingClientRect();this.div.style.display="flex",this.div.style.flexDirection="column";const t=e.x+e.width/2;this.div.style.left=t-this.div.clientWidth/2+"px",this.div.style.top=e.y+e.height+"px"})),document.body.appendChild(this.div)}updateMenuItems(e){this.div.innerHTML="",e.forEach((e=>{const t=this.makeButton(e.label,null,!1,!1);t.elem.addEventListener("click",(()=>{this._clickHandler(e)})),t.elem.style.margin="4px 4px",t.elem.style.padding="2px 2px",this.div.appendChild(t.elem)})),e.length>0&&(this.widget.elem.innerText=e[0].label+" ↓")}_clickHandler(e){this.widget.elem.innerText=e.label+" ↓",e.callback?e.callback():this.globalCallback?this.globalCallback(e.label):window.callbackFunction(`${e.label}`),this.div.style.display="none",this.isOpen=!1}}class un{_handler;_div;left;right;codeEditor;constructor(e){this._handler=e,this._div=document.createElement("div"),this._div.classList.add("topbar");const t=e=>{const t=document.createElement("div");return t.classList.add("topbar-container"),t.style.justifyContent=e,this._div.appendChild(t),t};this.left=t("flex-start"),this.right=t("flex-end"),this.codeEditor=new cn(this._handler),this.makeChartMenu([{label:"Add Series",callback:()=>this.openCSVFile("add")},{label:"Edit Series",callback:()=>this.openCSVFile("edit")}],"Add Series",!0,"left"),this.makeButton("{}=> ƒ",!0,!0,"right",!1,void 0,(()=>this.codeEditor.open()))}makeSwitcher(e,t,i,s="left"){const n=document.createElement("div");let o;n.style.margin="4px 12px";const r={elem:n,callbackName:i,intervalElements:e.map((e=>{const i=document.createElement("button");i.classList.add("topbar-button"),i.classList.add("switcher-button"),i.style.margin="0px 2px",i.innerText=e,e==t&&(o=i,i.classList.add("active-switcher-button"));const s=un.getClientWidth(i);return i.style.minWidth=s+1+"px",i.addEventListener("click",(()=>r.onItemClicked(i))),n.appendChild(i),i})),onItemClicked:e=>{e!=o&&(o.classList.remove("active-switcher-button"),e.classList.add("active-switcher-button"),o=e,window.callbackFunction(`${r.callbackName}_~_${e.innerText}`))}};return this.appendWidget(n,s,!0),r}makeTextBoxWidget(e,t="left",i=null){if(i){const s=document.createElement("input");return s.classList.add("topbar-textbox-input"),s.value=e,s.style.width=`${s.value.length+2}ch`,s.addEventListener("focus",(()=>{window.textBoxFocused=!0})),s.addEventListener("input",(e=>{e.preventDefault(),s.style.width=`${s.value.length+2}ch`})),s.addEventListener("keydown",(e=>{"Enter"==e.key&&(e.preventDefault(),s.blur())})),s.addEventListener("blur",(()=>{window.callbackFunction(`${i}_~_${s.value}`),window.textBoxFocused=!1})),this.appendWidget(s,t,!0),s}{const i=document.createElement("div");return i.classList.add("topbar-textbox"),i.innerText=e,this.appendWidget(i,t,!0),i}}makeMenu(e,t,i,s,n){return new pn(this.makeButton.bind(this),e,t,i,s,n)}makeChartMenu(e,t,i,s,n,o){return new dn(this.makeButton.bind(this),e,t,i,s,n,o)}makeButton(e,t,i=!0,s="left",n=!1,o,r){let a=document.createElement("button");a.classList.add("topbar-button"),a.innerText=e,document.body.appendChild(a),a.style.minWidth=`${a.clientWidth+1}px`,document.body.removeChild(a);let l=!1;return a.addEventListener("click",(()=>{n?(l=!l,a.style.backgroundColor=l?"var(--active-bg-color)":"",a.style.color=l?"var(--active-color)":"",o&&window.callbackFunction(`${o}_~_${l}`)):o&&window.callbackFunction(`${o}_~_${a.innerText}`),r&&r()})),i&&this.appendWidget(a,s,t),{elem:a,callbackName:o}}makeSliderWidget(e,t,i,s,n,o="left"){const r=document.createElement("div");r.classList.add("topbar-slider-container"),r.style.display="flex",r.style.alignItems="center",r.style.margin="4px 12px";const a=document.createElement("span");a.classList.add("topbar-slider-label"),a.style.marginRight="8px",a.innerText=s.toString();const l=document.createElement("input");return l.classList.add("topbar-slider"),l.type="range",l.min=e.toString(),l.max=t.toString(),l.step=i.toString(),l.value=s.toString(),l.style.cursor="pointer",l.addEventListener("input",(()=>{a.innerText=l.value,window.callbackFunction(`${n}_~_${l.value}`)})),r.appendChild(a),r.appendChild(l),this.appendWidget(r,o,!0),r}makeSeparator(e="left"){const t=document.createElement("div");t.classList.add("topbar-seperator");("left"==e?this.left:this.right).appendChild(t)}appendWidget(e,t,i){const s="left"==t?this.left:this.right;i?("left"==t&&s.appendChild(e),this.makeSeparator(t),"right"==t&&s.appendChild(e)):s.appendChild(e),this._handler.reSize()}openCSVFile(e){const t=document.createElement("input");t.type="file",t.accept=".csv",t.style.display="none",t.addEventListener("change",(t=>{const i=t.target;if(i.files&&i.files.length>0){const t=i.files[0],s=new FileReader;s.onload=i=>{const s=i.target?.result,n=this.parseCSV(s);if(0===n.length)return void alert("The CSV file is empty.");const o=["time","open","high","low","close"],r=Object.keys(n[0]);if(o.every((e=>r.includes(e))))try{if("edit"===e)this._handler.series.setData(n),console.log("Series data updated successfully.");else if("add"===e){const e=t.name.replace(/\.[^/.]+$/,"");this._handler.createCustomOHLCSeries(e,{}).series.setData(n),console.log("New series added successfully.")}}catch(e){console.error("Error updating chart data:",e)}else alert("The selected CSV does not contain all required OHLCV columns: "+o.join(", "))},s.readAsText(t)}})),document.body.appendChild(t),t.click(),document.body.removeChild(t)}parseCSV(e){const t=e.split(/\r?\n/).filter((e=>e.trim().length>0));if(0===t.length)return[];let i=t[0].split(",").map((e=>e.trim()));const s=i.map((e=>e.toLowerCase()));if(!s.includes("time"))if(s.includes("date")){const e=s.indexOf("date");i[e]="time"}else i[0]="time";return t.slice(1).map((e=>{const t=e.split(",").map((e=>e.trim())),s={};return i.forEach(((e,i)=>{const n=Number(t[i]);s[e]=isNaN(n)?t[i]:n})),s}))}static getClientWidth(e){document.body.appendChild(e);const t=e.clientWidth;return document.body.removeChild(e),t}}const mn={title:"",followMode:"tracking",horizontalDeadzoneWidth:45,verticalDeadzoneHeight:100,verticalSpacing:20,topOffset:20};class gn{_chart;_element;_titleElement;_priceElement;_dateElement;_timeElement;_options;_lastTooltipWidth=null;constructor(e,t){this._options={...mn,...t},this._chart=e;const i=document.createElement("div");yn(i,{display:"flex","flex-direction":"column","align-items":"center",position:"absolute",transform:"translate(calc(0px - 50%), 0px)",opacity:"0",left:"0%",top:"0","z-index":"100","background-color":"white","border-radius":"4px",padding:"5px 10px","font-family":"-apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif","font-size":"12px","font-weight":"400","box-shadow":"0px 2px 4px rgba(0, 0, 0, 0.2)","line-height":"16px","pointer-events":"none",color:"#131722"});const s=document.createElement("div");yn(s,{"font-size":"12px","line-height":"24px","font-weight":"590"}),fn(s,this._options.title),i.appendChild(s);const n=document.createElement("div");yn(n,{"font-size":"12px","line-height":"18px","font-weight":"590"}),fn(n,""),i.appendChild(n);const o=document.createElement("div");yn(o,{color:"#787B86"}),fn(o,""),i.appendChild(o);const r=document.createElement("div");yn(r,{color:"#787B86"}),fn(r,""),i.appendChild(r),this._element=i,this._titleElement=s,this._priceElement=n,this._dateElement=o,this._timeElement=r;const a=this._chart.chartElement();a.appendChild(this._element);const l=a.parentElement;if(!l)return void console.error("Chart Element is not attached to the page.");const c=getComputedStyle(l).position;"relative"!==c&&"absolute"!==c&&console.error("Chart Element position is expected be `relative` or `absolute`.")}destroy(){this._chart&&this._element&&this._chart.chartElement().removeChild(this._element)}applyOptions(e){this._options={...this._options,...e}}options(){return this._options}updateTooltipContent(e){if(!this._element)return void console.warn("Tooltip element not found.");const t=this._element.getBoundingClientRect();this._lastTooltipWidth=t.width,void 0!==e.title&&this._titleElement?(console.log(`Setting title: ${e.title}`),fn(this._titleElement,e.title)):console.warn("Title element is missing or title data is undefined."),fn(this._priceElement,e.price),fn(this._dateElement,e.date),fn(this._timeElement,e.time)}updatePosition(e){if(!this._chart||!this._element)return;if(this._element.style.opacity=e.visible?"1":"0",!e.visible)return;const t=this._calculateXPosition(e,this._chart),i=this._calculateYPosition(e);this._element.style.transform=`translate(${t}, ${i})`}_calculateXPosition(e,t){const i=e.paneX+t.priceScale("left").width(),s=this._lastTooltipWidth?Math.ceil(this._lastTooltipWidth/2):this._options.horizontalDeadzoneWidth;return`calc(${Math.min(Math.max(s,i),t.timeScale().width()-s)}px - 50%)`}_calculateYPosition(e){if("top"==this._options.followMode)return`${this._options.topOffset}px`;const t=e.paneY,i=t<=this._options.verticalSpacing+this._options.verticalDeadzoneHeight;return`calc(${t+(i?1:-1)*this._options.verticalSpacing}px${i?"":" - 100%"})`}}function fn(e,t){e&&t!==e.innerText&&(e.innerText=t,e.style.display=t?"block":"none")}function yn(e,t){for(const[i,s]of Object.entries(t))e.style.setProperty(i,s)}function bn(e,t,i=1,s){const n=Math.round(t*e),o=Math.round(i*t),r=function(e){return Math.floor(.5*e)}(o);return{position:n-r,length:o}}class vn{_data;constructor(e){this._data=e}draw(e){this._data.visible&&e.useBitmapCoordinateSpace((e=>{const t=e.context,i=bn(this._data.x,e.horizontalPixelRatio,1);t.fillStyle=this._data.color,t.fillRect(i.position,this._data.topMargin*e.verticalPixelRatio,i.length,e.bitmapSize.height)}))}}class xn{_data;constructor(e){this._data=e}update(e){this._data=e}renderer(){return new vn(this._data)}zOrder(){return"bottom"}}const _n={lineColor:"rgba(0, 0, 0, 0.2)",priceExtractor:e=>void 0!==e.value?e.value.toFixed(2):void 0!==e.close?e.close.toFixed(2):""};class wn{_options;_tooltip=void 0;_paneViews;_data={x:0,visible:!1,color:"rgba(0, 0, 0, 0.2)",topMargin:0};_attachedParams;constructor(e){this._options={..._n,...e},this._data.color=this._options.lineColor,this._paneViews=[new xn(this._data)]}attached(e){this._attachedParams=e;const t=this.series();if(t){const e=t.options(),i=e.lineColor||e.color||"rgba(0,0,0,0.2)";this._options.autoColor&&this.applyOptions({lineColor:i})}this._setCrosshairMode(),e.chart.subscribeCrosshairMove(this._moveHandler),this._createTooltipElement()}detached(){const e=this.chart();e&&e.unsubscribeCrosshairMove(this._moveHandler),this._hideCrosshair(),this._hideTooltip()}paneViews(){return this._paneViews}updateAllViews(){this._paneViews.forEach((e=>e.update(this._data)))}setData(e){this._data=e,this.updateAllViews(),this._attachedParams?.requestUpdate()}currentColor(){return this._options.lineColor}chart(){return this._attachedParams?.chart}series(){return this._attachedParams?.series}applyOptions(e){this._options={...this._options,...e},e.lineColor&&this.setData({...this._data,color:e.lineColor}),this._tooltip&&this._tooltip.applyOptions({...this._options.tooltip}),this._attachedParams?.requestUpdate()}_setCrosshairMode(){const e=this.chart();if(!e)throw new Error("Unable to change crosshair mode because the chart instance is undefined");e.applyOptions({crosshair:{mode:t.CrosshairMode.Magnet,vertLine:{visible:!1,labelVisible:!1},horzLine:{visible:!1,labelVisible:!1}}})}_moveHandler=e=>this._onMouseMove(e);switch(e){if(this.series()===e)return void console.log("Tooltip is already attached to this series.");this._hideCrosshair(),e.attachPrimitive(this,"Tooltip",!0,!1);const t=e.options(),i=t.lineColor||t.color||"rgba(0,0,0,0.2)";this._options.autoColor&&this.applyOptions({lineColor:i}),console.log("Switched tooltip to the new series.")}_hideCrosshair(){this._hideTooltip(),this.setData({x:0,visible:!1,color:this._options.lineColor,topMargin:0})}_hideTooltip(){this._tooltip&&(this._tooltip.updateTooltipContent({title:"",price:"",date:"",time:""}),this._tooltip.updatePosition({paneX:0,paneY:0,visible:!1}))}_onMouseMove(e){const t=this.chart(),i=this.series(),s=e.logical;if(!s||!t||!i)return void this._hideCrosshair();const n=e.seriesData.get(i);if(!n)return void this._hideCrosshair();const o=this._options.priceExtractor(n),r=t.timeScale().logicalToCoordinate(s),[a,l]=function(e){if(!e)return["",""];const t=new Date(e),i=t.getFullYear(),s=t.toLocaleString("default",{month:"short"});return[`${t.getDate().toString().padStart(2,"0")} ${s} ${i}`,`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}`]}(e.time?As(e.time):void 0);if(this._tooltip){const t=i.options()?.title||"Unknown Series",s=this._tooltip.options(),n="top"===s.followMode?s.topOffset+10:0;this.setData({x:r??0,visible:null!==r,color:this._options.lineColor,topMargin:n}),this._tooltip.updateTooltipContent({title:t,price:o,date:a,time:l}),this._tooltip.updatePosition({paneX:e.point?.x??0,paneY:e.point?.y??0,visible:!0})}}_createTooltipElement(){const e=this.chart();if(!e)throw new Error("Unable to create Tooltip element. Chart not attached");this._tooltip=new gn(e,{...this._options.tooltip})}}let Cn=class e{colorOption;static colors=["#EBB0B0","#E9CEA1","#E5DF80","#ADEB97","#A3C3EA","#D8BDED","#E15F5D","#E1B45F","#E2D947","#4BE940","#639AE1","#D7A0E8","#E42C2A","#E49D30","#E7D827","#3CFF0A","#3275E4","#B06CE3","#F3000D","#EE9A14","#F1DA13","#2DFC0F","#1562EE","#BB00EF","#B50911","#E3860E","#D2BD11","#48DE0E","#1455B4","#6E009F","#7C1713","#B76B12","#8D7A13","#479C12","#165579","#51007E"];_div;saveDrawings;opacity=0;_opacitySlider;_opacityLabel;rgba;constructor(t,i){this.colorOption=i,this.saveDrawings=t,this._div=document.createElement("div"),this._div.classList.add("color-picker");let s=document.createElement("div");s.style.margin="10px",s.style.display="flex",s.style.flexWrap="wrap",e.colors.forEach((e=>s.appendChild(this.makeColorBox(e))));let n=document.createElement("div");n.style.backgroundColor=window.pane.borderColor,n.style.height="1px",n.style.width="130px";let o=document.createElement("div");o.style.margin="10px";let r=document.createElement("div");r.style.color="lightgray",r.style.fontSize="12px",r.innerText="Opacity",this._opacityLabel=document.createElement("div"),this._opacityLabel.style.color="lightgray",this._opacityLabel.style.fontSize="12px",this._opacitySlider=document.createElement("input"),this._opacitySlider.type="range",this._opacitySlider.value=(100*this.opacity).toString(),this._opacityLabel.innerText=this._opacitySlider.value+"%",this._opacitySlider.oninput=()=>{this._opacityLabel.innerText=this._opacitySlider.value+"%",this.opacity=parseInt(this._opacitySlider.value)/100,this.updateColor()},o.appendChild(r),o.appendChild(this._opacitySlider),o.appendChild(this._opacityLabel),this._div.appendChild(s),this._div.appendChild(n),this._div.appendChild(o),window.containerDiv.appendChild(this._div)}_updateOpacitySlider(){this._opacitySlider.value=(100*this.opacity).toString(),this._opacityLabel.innerText=this._opacitySlider.value+"%"}makeColorBox(t){const i=document.createElement("div");i.style.width="18px",i.style.height="18px",i.style.borderRadius="3px",i.style.margin="3px",i.style.boxSizing="border-box",i.style.backgroundColor=t,i.addEventListener("mouseover",(()=>i.style.border="2px solid lightgray")),i.addEventListener("mouseout",(()=>i.style.border="none"));const s=e.extractRGBA(t);return i.addEventListener("click",(()=>{this.rgba=s,this.updateColor()})),i}static extractRGBA(e){const t=document.createElement("div");t.style.color=e,document.body.appendChild(t);const i=getComputedStyle(t).color;document.body.removeChild(t);const s=i.match(/\d+/g)?.map(Number);if(!s)return[];let n=i.includes("rgba")?parseFloat(i.split(",")[3]):1;return[s[0],s[1],s[2],n]}updateColor(){if(!O.lastHoveredObject||!this.rgba)return;const e=`rgba(${this.rgba[0]}, ${this.rgba[1]}, ${this.rgba[2]}, ${this.opacity})`;O.lastHoveredObject.applyOptions({[this.colorOption]:e}),this.saveDrawings()}openMenu(t){O.lastHoveredObject&&(this.rgba=e.extractRGBA(O.lastHoveredObject._options[this.colorOption]),this.opacity=this.rgba[3],this._updateOpacitySlider(),this._div.style.top=t.top-30+"px",this._div.style.left=t.right+"px",this._div.style.display="flex",setTimeout((()=>document.addEventListener("mousedown",(e=>{this._div.contains(e.target)||this.closeMenu()}))),10))}closeMenu(){document.body.removeEventListener("click",this.closeMenu),this._div.style.display="none"}};class Sn{container;_opacitySlider;_opacity_label;exitButton;color="#ff0000";rgba;opacity;applySelection;customColors;constructor(e,t,i){this.applySelection=t,this.rgba=Sn.extractRGBA(e),this.opacity=this.rgba[3],this.container=document.createElement("div"),this.container.classList.add("color-picker"),this.container.style.display="flex",this.container.style.flexDirection="column",this.container.style.width="200px",this.container.style.height="350px",this.container.style.position="relative";const s=this.createColorGrid(),n=this.createOpacityUI();this.exitButton=this.createExitButton(),this.customColors=i??void 0,this.container.appendChild(s),this.container.appendChild(this.createSeparator()),this.customColors&&0!==this.customColors.length&&this.createCustomColorSection(),this.container.appendChild(this.createSeparator()),this.container.appendChild(n),this.container.appendChild(this.exitButton)}createCustomColorSection(){if(!this.customColors||0===this.customColors.length)return null;const e=document.createElement("div");e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="center",e.style.margin="8px 0";const t=document.createElement("div");t.innerText="Custom Colors",t.style.fontSize="14px",t.style.color="white",e.appendChild(t);const i=document.createElement("div");i.style.display="flex",i.style.flexWrap="wrap",i.style.justifyContent="center",i.style.gap="5px";const s=e=>{const t=document.createElement("div");return t.style.width="20px",t.style.height="20px",t.style.borderRadius="4px",t.style.cursor="pointer",t.style.border="1px solid #999",t.style.backgroundColor=e,t.title=e,t.addEventListener("click",(()=>{this.updateTargetColor()})),t};this.customColors.forEach((e=>{i.appendChild(s(e))}));const n=document.createElement("div");return n.style.width="20px",n.style.height="20px",n.style.borderRadius="4px",n.style.cursor="pointer",n.style.border="1px solid #999",n.style.backgroundColor="rgba(0,0,0,0)",n.style.display="flex",n.style.justifyContent="center",n.style.alignItems="center",n.style.color="#999",n.style.fontSize="16px",n.innerText="+",n.title="Add custom color",n.addEventListener("click",(e=>{const t=document.createElement("input");t.type="color",t.value=this.color,t.style.position="absolute",t.style.left="-9999px",document.body.appendChild(t),t.addEventListener("input",(()=>{this.color=t.value,this.updateTargetColor(),this.customColors.includes(this.color)||(this.customColors.push(this.color),i.appendChild(s(this.color)),this.saveColors()),document.body.removeChild(t)}),{once:!0}),t.click()})),i.appendChild(n),e.appendChild(i),e}saveColors(){const e=`save_defaults_colors_~_${JSON.stringify(this.customColors,null,2)}`;window.callbackFunction(e)}createExitButton(){const e=document.createElement("div");return e.innerText="✕",e.title="Close",e.style.position="absolute",e.style.bottom="5px",e.style.right="5px",e.style.width="20px",e.style.height="20px",e.style.cursor="pointer",e.style.display="flex",e.style.justifyContent="center",e.style.alignItems="center",e.style.fontSize="16px",e.style.backgroundColor="#ccc",e.style.borderRadius="50%",e.style.color="#000",e.style.boxShadow="0 1px 3px rgba(0,0,0,0.3)",e.addEventListener("mouseover",(()=>{e.style.backgroundColor="#e74c3c",e.style.color="#fff"})),e.addEventListener("mouseout",(()=>{e.style.backgroundColor="#ccc",e.style.color="#000"})),e.addEventListener("click",(()=>{this.closeMenu()})),e}createColorGrid(){const e=document.createElement("div");e.style.display="grid",e.style.gridTemplateColumns="repeat(7, 1fr)",e.style.gap="5px",e.style.overflowY="auto",e.style.flex="1";return Sn.generateFullSpectrumColors(9).forEach((t=>{const i=this.createColorBox(t);e.appendChild(i)})),e}createColorBox(e){const t=document.createElement("div");return t.style.aspectRatio="1",t.style.borderRadius="6px",t.style.backgroundColor=e,t.style.cursor="pointer",t.addEventListener("click",(()=>{this.rgba=Sn.extractRGBA(e),this.updateTargetColor()})),t}static generateFullSpectrumColors(e){const t=[];for(let i=0;i<=255;i+=Math.floor(255/e))t.push(`rgba(255, ${i}, 0, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(${i}, 255, 0, 1)`);for(let i=0;i<=255;i+=Math.floor(255/e))t.push(`rgba(0, 255, ${i}, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(0, ${i}, 255, 1)`);for(let i=0;i<=255;i+=Math.floor(255/e))t.push(`rgba(${i}, 0, 255, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(255, 0, ${i}, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(${i}, ${i}, ${i}, 1)`);return t}createOpacityUI(){const e=document.createElement("div");e.style.margin="10px",e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="center";const t=document.createElement("div");return t.style.color="lightgray",t.style.fontSize="12px",t.innerText="Opacity",this._opacitySlider=document.createElement("input"),this._opacitySlider.type="range",this._opacitySlider.min="0",this._opacitySlider.max="100",this._opacitySlider.value=(100*this.opacity).toString(),this._opacitySlider.style.width="80%",this._opacity_label=document.createElement("div"),this._opacity_label.style.color="lightgray",this._opacity_label.style.fontSize="12px",this._opacity_label.innerText=`${this._opacitySlider.value}%`,this._opacitySlider.oninput=()=>{this._opacity_label.innerText=`${this._opacitySlider.value}%`,this.opacity=parseInt(this._opacitySlider.value)/100,this.updateTargetColor()},e.appendChild(t),e.appendChild(this._opacitySlider),e.appendChild(this._opacity_label),e}createSeparator(){const e=document.createElement("div");return e.style.height="1px",e.style.width="100%",e.style.backgroundColor="#ccc",e.style.margin="5px 0",e}openMenu(e,t,i){this.applySelection=i,this.container.style.display="block",document.body.appendChild(this.container);const s=this.container.offsetWidth||150,n=this.container.offsetHeight||250,o=e.clientX,r=e.clientY,a=window.innerWidth,l=window.innerHeight;let c=o+t;const h=c+s>a?o-s:c,p=r+n>l?l-n-10:r;this.container.style.left=`${h}px`,this.container.style.top=`${p}px`,this.container.style.display="flex",this.container.style.position="absolute",this.exitButton.style.bottom="5px",this.exitButton.style.right="5px";const d=e=>{const t=this.container.getBoundingClientRect(),i=t.left-s,o=t.right+s,r=t.top-n,a=t.bottom+n;(e.clientXo||e.clientYa)&&(this.closeMenu(),document.removeEventListener("mousemove",d))};this.container.addEventListener("mouseenter",(()=>{document.addEventListener("mousemove",d)})),this.container.addEventListener("mouseleave",(()=>{document.removeEventListener("mousemove",d),this.closeMenu()})),document.addEventListener("mousedown",this._handleOutsideClick.bind(this),{once:!0})}closeMenu(){this.container.style.display="none",document.removeEventListener("mousedown",this._handleOutsideClick)}_handleOutsideClick(e){this.container.contains(e.target)||this.closeMenu()}static extractRGBA(e){const t=document.createElement("div");t.style.color=e,document.body.appendChild(t);const i=getComputedStyle(t).color;document.body.removeChild(t);const s=i.match(/\d+/g)?.map(Number)||[0,0,0],n=i.includes("rgba")?parseFloat(i.split(",")[3]):1;return[s[0],s[1],s[2],n]}getElement(){return this.container}update(e,t){this.rgba=Sn.extractRGBA(e),this.opacity=this.rgba[3],this.applySelection=t,this.updateTargetColor()}updateTargetColor(){this.color=`rgba(${this.rgba[0]}, ${this.rgba[1]}, ${this.rgba[2]}, ${this.opacity})`,this.applySelection(this.color)}}class kn{static _styles=[{name:"Solid",var:t.LineStyle.Solid},{name:"Dotted",var:t.LineStyle.Dotted},{name:"Dashed",var:t.LineStyle.Dashed},{name:"Large Dashed",var:t.LineStyle.LargeDashed},{name:"Sparse Dotted",var:t.LineStyle.SparseDotted}];_div;_saveDrawings;constructor(e){this._saveDrawings=e,this._div=document.createElement("div"),this._div.classList.add("context-menu"),kn._styles.forEach((e=>{this._div.appendChild(this._makeTextBox(e.name,e.var))})),window.containerDiv.appendChild(this._div)}_makeTextBox(e,t){const i=document.createElement("span");return i.classList.add("context-menu-item"),i.innerText=e,i.addEventListener("click",(()=>{O.lastHoveredObject?.applyOptions({lineStyle:t}),this._saveDrawings()})),i}openMenu(e){this._div.style.top=e.top-30+"px",this._div.style.left=e.right+"px",this._div.style.display="block",setTimeout((()=>document.addEventListener("mousedown",(e=>{this._div.contains(e.target)||this.closeMenu()}))),10)}closeMenu(){document.removeEventListener("click",this.closeMenu),this._div.style.display="none"}}const En={visible:!0,sections:0,upColor:void 0,downColor:void 0,borderUpColor:void 0,borderDownColor:void 0,rightSide:!0,width:0,lineColor:"#ffffff",lineStyle:t.LineStyle.Solid,drawGrid:!0,gridWidth:1,gridColor:"rgba(255, 255, 255, 0.125)",gridLineStyle:t.LineStyle.SparseDotted};class Mn extends a{p1;p2;_listeners=[];visibleRange=null;_originalData;_currentSlice=null;_vpData;_paneViews;_options;_pendingUpdate=!1;_state=N.NONE;_latestHoverPoint=null;_startDragPoint=null;static _mouseIsDown=!1;_hovered=!1;chart_;series_;constructor(e,t=En,i,s){super(),this.chart_=e.chart,this.series_=e.series;const n=this.series_.data(),o=e.volumeSeries.data(),r=this.chart_.timeScale();this.visibleRange=r.getVisibleLogicalRange(),i&&s?(this.p1=i,this.p2=s):(this.p1={time:null,logical:this.visibleRange?.from??0,price:0},this.p2={time:null,logical:this.visibleRange?.to??this.series.data().length-1,price:0}),this._options={...En,...t},o.length>0&&o.every((e=>"value"in e))?this._originalData=n.map(((e,t)=>({...e,x1:t,x2:t,volume:o[t]?.value||0}))):(console.warn('[ProfileProcessor] volumeData is empty or missing "value" property.'),this._originalData=n.map(((e,t)=>({...e,x1:t,x2:t,volume:0})))),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this._paneViews=[new Pn(this)],this._subscribeEvents(),this.update()}_handleDomMouseDown=()=>{};_handleDomMouseUp=()=>{this._onMouseUp()};_subscribe(e,t){document.addEventListener(e,t),this._listeners.push({name:e,listener:t})}_unsubscribe(e,t){document.removeEventListener(e,t);const i=this._listeners.findIndex((i=>i.name===e&&i.listener===t));-1!==i&&this._listeners.splice(i,1)}_subscribeEvents(){this.p1&&this.p2&&this.p1.time&&this.p2.time?(this.chart_.subscribeCrosshairMove(this._handleMouseMove),this.chart_.subscribeClick(this._handleMouseDownOrUp),this._listeners.push({name:"crosshairMove",listener:this._handleMouseMove},{name:"click",listener:this._handleMouseDownOrUp})):(this.chart_.timeScale().subscribeVisibleLogicalRangeChange(this._handleVisibleLogicalRangeChange),this._listeners.push({name:"visibleLogicalRangeChange",listener:this._handleVisibleLogicalRangeChange}))}_handleVisibleLogicalRangeChange=()=>{const e=this.chart_.timeScale();if(this.visibleRange=e.getVisibleLogicalRange(),!this.visibleRange||!this.series_)return void console.warn("[VolumeProfile] Visible range or source series is undefined.");this.p1={time:null,logical:this.visibleRange.from??0,price:0},this.p2={time:null,logical:this.visibleRange.to??this.series_.data().length-1,price:0},this.sliceData();const t=this.calculateVolumeProfile();t?(this._vpData=t,this.updateAllViews(),this.requestUpdate()):console.warn("[VolumeProfile] Failed to process Volume Profile data on visible range change.")};_handleMouseMove=e=>{const t=this._eventToPoint(e);this._latestHoverPoint=t,Mn._mouseIsDown?this._handleDragInteraction(e):this._mouseIsOverPointCanvas(e,1)||this._mouseIsOverPointCanvas(e,2)?this._state===N.NONE&&this._moveToState(N.HOVERING):this._state!==N.NONE&&this._moveToState(N.NONE)};_handleMouseDownOrUp=()=>{Mn._mouseIsDown=!Mn._mouseIsDown,Mn._mouseIsDown?this._onMouseDown():this._onMouseUp(),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()};_onMouseDown(){if(this._startDragPoint=this._latestHoverPoint,!this._startDragPoint||!this.p1||!this.p2)return;const e=this._mouseIsOverPointRaw(this._startDragPoint,this.p1),t=this._mouseIsOverPointRaw(this._startDragPoint,this.p2);e?this._moveToState(N.DRAGGINGP1):t?this._moveToState(N.DRAGGINGP2):this._moveToState(N.DRAGGING)}_onMouseUp(){Mn._mouseIsDown=!1,this._startDragPoint=null,this._moveToState(N.HOVERING),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}_handleDragInteraction(e){if(this._state!==N.DRAGGING&&this._state!==N.DRAGGINGP1&&this._state!==N.DRAGGINGP2)return;const t=this._eventToPoint(e);if(!t||!this._startDragPoint)return;const i={logical:t.logical-this._startDragPoint.logical,price:t.price-this._startDragPoint.price};this._onDrag(i),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update(),this._startDragPoint=t}_onDrag(e){this.p1&&this.p2&&(this._state===N.DRAGGING?(this._addDiffToPoint(this.p1,e.logical,e.price),this._addDiffToPoint(this.p2,e.logical,e.price)):this._state===N.DRAGGINGP1?this._addDiffToPoint(this.p1,e.logical,e.price):this._state===N.DRAGGINGP2&&this._addDiffToPoint(this.p2,e.logical,e.price),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update())}_addDiffToPoint(e,t,i){e.logical=e.logical+t,e.price=e.price+i}_mouseIsOverPointRaw(e,t){if(!e)return!1;return Math.abs(e.logical-t.logical)<1&&Math.abs(e.price-t.price)<1}_mouseIsOverPointCanvas(e,t){if(!e.point||!this.p1||!this.p2)return!1;const i=Ws(1===t?this.p1:this.p2,this.chart_,this.series_),s=e.point.x-i.x,n=e.point.y-i.y;return s*s+n*n<100}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleDomMouseDown),this._unsubscribe("mouseup",this._handleDomMouseUp);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._subscribe("mousedown",this._handleDomMouseDown),this._unsubscribe("mouseup",this._handleDomMouseUp);break;case N.DRAGGING:case N.DRAGGINGP1:case N.DRAGGINGP2:document.body.style.cursor="grabbing",this._hovered=!1,this._unsubscribe("mousedown",this._handleDomMouseDown),this._subscribe("mouseup",this._handleDomMouseUp)}this._state=e,this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}_eventToPoint(e){if(!e.point||null==e.logical)return null;const t=this.series_.coordinateToPrice(e.point.y);return null==t?null:{time:e.time??null,logical:e.logical,price:t.valueOf()}}sliceData(){if(!this.p1||!this.p2)return;const e=Math.min(this.p1.logical,this.p2.logical),t=Math.max(this.p1.logical,this.p2.logical);this._currentSlice=this._originalData.slice(Math.max(0,e),Math.min(t+1,this._originalData.length-1))}calculateDynamicSections(e,t,i){if(e<=0||i<=t)return 10;const s=e/20,n=(i-t)/5,o=2*Math.max(1,Math.floor(Math.max(s,n)));return Math.max(5,o)}calculateVolumeProfile(){const e=Math.min(this.visibleRange.to,this._originalData.length-1)-Math.max(this.visibleRange.from,0);let t=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;const s=[];let n;if(this._currentSlice&&this._currentSlice.length>0){for(const e of this._currentSlice){const s=e.close??e.open;void 0!==s&&(t=Math.min(t,s),i=Math.max(i,s))}t!==Number.POSITIVE_INFINITY&&i!==Number.NEGATIVE_INFINITY||(t=0,i=1);let o=void 0!==this._options.sections&&this._options.sections>0?this._options.sections:this.calculateDynamicSections(e,t,i);const r=(i===t?1:i-t)/o;for(let e=0;e=i&&t=(e.open??0),i=e.volume||0;t?o+=i:a+=i}}const c=o>=a,h=c?this._options.upColor??l(this.series_.options().upColor,.1)??"rgba(0,128,0,0.1)":this._options.downColor??l(this.series_.options().downColor,.1)??"rgba(128,0,0,0.1)",p=c?this._options.borderUpColor??l(this.series_.options().upColor,.5)??"rgba(0,128,0,0.66)":this._options.borderDownColor??l(this.series_.options().downColor,.5)??"rgba(128,0,0,0.66)";s.push({price:i,upData:o,downData:a,color:this._options.visible?h:"rgba(0,0,0,0)",borderColor:this._options.visible?p:"rgba(0,0,0,0)",minPrice:i,maxPrice:n})}n=this._options.rightSide?this._currentSlice[this._currentSlice.length-1].time:this._currentSlice[0].time}else n=Date.now().toString();return this.update(),{time:n,profile:s,width:this._options.width??20,visibleRange:this.visibleRange}}update(){this._pendingUpdate||(this._pendingUpdate=!0,requestAnimationFrame((()=>{super.requestUpdate(),this.updateAllViews(),console.log("VolumeProfile updated p1=",this.p1,"p2=",this.p2),this._pendingUpdate=!1})))}updateAllViews(){this._paneViews.forEach((e=>e.update()))}paneViews(){return this._paneViews}autoscaleInfo(){return this._vpData.profile.length?{priceRange:{minValue:this._vpData.profile[0].minPrice,maxValue:this._vpData.profile[this._vpData.profile.length-1].maxPrice}}:null}applyOptions(e){this._options={...this._options,...e},this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}}class Pn{_source;_x=null;_width=0;_items=[];_maxVolume;visibleRange=null;_p1={x:null,y:null};_p2={x:null,y:null};constructor(e){this._source=e,this._maxVolume=this._source._vpData.profile.reduce(((e,t)=>Math.max(e,t.upData+t.downData)),0)}update(){if(!this._source.p1||!this._source.p2)return;const e=this._source._vpData,t=this._source.chart_,i=this._source.series_,s=t.timeScale();this._x=s.timeToCoordinate(e.time)??null;const n=s.options().barSpacing??1,o=Math.max(0,Math.min(this._source.p1.logical,this._source.p2.logical)),r=Math.min(Math.max(this._source.p1.logical,this._source.p2.logical),this._source._originalData.length-1);if(this._width=(e.width&&0!==e.width?e.width:(r-o)/3)*n,this._p1=Ws(this._source.p1,t,i),this._p2=Ws(this._source.p2,t,i),this._items=[],e.profile.length){this._maxVolume=e.profile.reduce(((e,t)=>Math.max(e,t.upData+t.downData)),0);for(const t of e.profile){const e=i.priceToCoordinate(t.maxPrice),s=i.priceToCoordinate(t.minPrice);if(null==e||null==s){this._items.push({y1:null,y2:null,combinedWidth:0,upWidth:0,downWidth:0,color:t.color,borderColor:t.borderColor});continue}const n=t.upData+t.downData,o=this._maxVolume>0?this._width*(n/this._maxVolume):0;let r=0,a=0;n>0&&(r=t.upData/n*o,a=t.downData/n*o),this._items.push({y1:e,y2:s,combinedWidth:o,upWidth:r,downWidth:a,color:t.color,borderColor:t.borderColor})}}}renderer(){return new Tn({x:this._x,width:this._width,items:this._items,visibleRange:{from:this._source.chart.timeScale().logicalToCoordinate(Math.max(0,this._source.visibleRange.from)),to:this._source.chart.timeScale().logicalToCoordinate(Math.min(this._source.series.data().length-1,this._source.visibleRange.to))},maxVolume:this._maxVolume,maxBars:this._source.series.data().length},this._p1,this._p2,this._source._options,!1)}zOrder(){return"bottom"}}class Tn extends G{_data;options;p1;p2;constructor(e,t,i,s,n){super(t,i,s,n),this._data=e,this.options=s,this.p1=t,this.p2=i}draw(){}drawBackground(e){console.log(`[VolumeProfileRenderer] draw() called with rightSide: ${this.options.rightSide}`),e.useBitmapCoordinateSpace((e=>{let t=e.context;this._drawGrid(t,e),U(t,this.options.lineStyle),this._data.items.forEach((i=>{if(null===i.y1||null===i.y2)return;if(null===this._data.x)return;const s=Math.min(i.y1,i.y2)*e.verticalPixelRatio,n=Math.abs(i.y2-i.y1)*e.verticalPixelRatio,o=i.upWidth+i.downWidth,r=o*e.horizontalPixelRatio;let a;a=this.options.rightSide?(this._data.x-o)*e.horizontalPixelRatio:this._data.x*e.horizontalPixelRatio;const l=Math.min(Math.max(.25*n,2),25);if(n>0){t.beginPath(),this._drawRoundedRect(t,a,s,r,n,l),t.strokeStyle=i.borderColor,t.lineWidth=1,t.stroke();const c=Math.max(i.upWidth,i.downWidth)*e.horizontalPixelRatio;let h;h=this.options.rightSide?a+(o-c):a,t.beginPath(),this._drawRoundedRect(t,h,s,c,n,l),t.fillStyle=i.color,t.fill()}}))}))}_drawGrid(e,i){const{items:s,x:n}=this._data;if(!s||0===s.length||null===n)return;if(!this.options.drawGrid)return;let o;o=void 0!==this.options.gridWidth&&1!==this.options.gridWidth?this.options.gridWidth*i.horizontalPixelRatio:(this._data.visibleRange.to-this._data.visibleRange.from)*i.horizontalPixelRatio,e.strokeStyle=this.options.visible?this.options.gridColor||"rgba(255, 255, 255, 0.2)":"rgba(0,0,0,0)",U(e,this.options.gridLineStyle||t.LineStyle.Solid),s.forEach((t=>{if(null===t.y1||null===t.y2)return;const s=(t.upWidth+t.downWidth)*i.horizontalPixelRatio;let r,a;this.options.rightSide?(r=n-o,a=n-s):(r=n+s,a=n+o);const l=t.y1*i.verticalPixelRatio,c=t.y2*i.verticalPixelRatio;e.beginPath(),e.moveTo(r,l),e.lineTo(a,l),e.stroke(),e.beginPath(),e.moveTo(r,c),e.lineTo(a,c),e.stroke()}))}_drawRoundedRect(e,t,i,s,n,o){const r=Math.abs(Math.min(o,s/2,n/2));e.beginPath(),s>0&&o>0&&(this.options.rightSide?(e.moveTo(t+r,i),e.lineTo(t+s,i),e.lineTo(t+s,i+n),e.lineTo(t+r,i+n),e.arcTo(t,i+n,t,i+n-r,r),e.lineTo(t,i+r),e.arcTo(t,i,t+r,i,r)):(e.moveTo(t,i),e.lineTo(t+s-r,i),e.arcTo(t+s,i,t+s,i+r,r),e.lineTo(t+s,i+n-r),e.arcTo(t+s,i+n,t+s-r,i+n,r),e.lineTo(t,i+n),e.lineTo(t,i)),e.closePath())}}function In(e,t){if(e.length0){let t=e[0];s[0]=t;for(let n=1;n0===i?0:t-e[i-1])),s=i.map((e=>Math.max(e,0))),n=i.map((e=>Math.max(-e,0))),o=An(s,t),r=An(n,t);return 0===r?100:0===o?0:100-100/(1+o/r)}function Ln(e,t,i){for(let s=0;s=o?t:i}}function Nn(e,t,i){const s=e&&t in e?e[t]:i;return Array.isArray(s)?s.map((e=>Number(e))):[Number(s)]}function On(e,t){return t{if(o1?`_${t+1}`:""),d="ALMA"+i+(l>1?` #${t+1}`:"");c.push({key:p,title:d,type:"line",data:h})}return c}},Rn=(e,t)=>{let i=0;return e.forEach((e=>{const s=e.close-t;i+=s*s})),Math.sqrt(i/e.length)},Bn={name:"Bollinger Bands",shortName:"BOLL",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray"},multiplier:{defaultValue:[2],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=Nn(t,"multiplier",this.paramMap.multiplier.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(l+=t.close,i>=r-1){const s=l/r,n=e.slice(i-(r-1),i+1),o=Rn(n,s);c.push({time:t.time,value:s+a*o}),h.push({time:t.time,value:s}),p.push({time:t.time,value:s-a*o}),l-=e[i-(r-1)].close}else c.push({time:t.time,value:NaN}),h.push({time:t.time,value:NaN}),p.push({time:t.time,value:NaN})}));const d=n>1?`_${t+1}`:"";o.push({key:`boll_up${d}`,title:`BOLL_UP${r}${d}`,type:"line",data:c}),o.push({key:`boll_mid${d}`,title:`BOLL_MID${r}${d}`,type:"line",data:h}),o.push({key:`boll_dn${d}`,title:`BOLL_DN${r}${d}`,type:"line",data:p})}return o}},Fn={name:"Exponential Moving Average",shortName:"EMA",shouldOhlc:!0,paramMap:{length:{defaultValue:[6,12,20],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{let o=0,r=0;const a=[];e.forEach(((i,s)=>{if(r+=i.close,s===t-1)o=r/t;else if(s>t-1){const e=2/(t+1);o=(i.close-o)*e+o}s>=t-1?(a.push({time:i.time,value:o}),r-=e[s-(t-1)].close):a.push({time:i.time,value:NaN})}));const l="ema"+(i.length>1?`_${n+1}`:""),c="EMA"+t+(i.length>1?` #${n+1}`:"");s.push({key:l,title:c,type:"line",data:a})})),s}},$n={name:"Highest High",shortName:"HH",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:""),a="HH"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Gn={name:"Linear Regression",shortName:"LINREG",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=e.map((e=>e.close)),n=[];return i.forEach(((t,o)=>{const r=[];e.forEach(((e,i)=>{if(ie+t),0),r=(s*i.reduce(((e,t,i)=>e+i*t),0)-n*o)/(s*(s*(s-1)*(2*s-1)/6)-n*n);return(o-r*n)/s+r*(s-1)}(s.slice(i-(t-1),i+1),t,0);r.push({time:e.time,value:n})}));const a="linreg"+(i.length>1?`_${o+1}`:""),l="LINREG"+t+(i.length>1?` #${o+1}`:"");n.push({key:a,title:l,type:"line",data:r})})),n}},jn={name:"Lowest Low",shortName:"LL",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:""),a="LL"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Un={name:"Median",shortName:"Median",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.close));n.sort(((e,t)=>e-t));const r=Math.floor(n.length/2),a=n.length%2==0?(n[r-1]+n[r])/2:n[r];o.push({time:i.time,value:a})}));const r="median"+(i.length>1?`_${n+1}`:""),a="Median"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},zn={name:"Moving Average",shortName:"MA",shouldOhlc:!0,paramMap:{length:{defaultValue:[5,10,30,60],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];let r=0;e.forEach(((i,s)=>{if(r+=i.close,s>=t-1){const n=r/t;o.push({time:i.time,value:n}),r-=e[s-(t-1)].close}else o.push({time:i.time,value:NaN})}));const a="ma"+(i.length>1?`_${n+1}`:""),l="MA"+t+(i.length>1?` #${n+1}`:"");s.push({key:a,title:l,type:"line",data:o})})),s}},Hn={name:"Rolling Moving Average",shortName:"RMA",shouldOhlc:!1,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=1/t;let r=0;const a=[];e.forEach(((e,t)=>{r=0===t?e.close:o*e.close+(1-o)*r,a.push({time:e.time,value:r})}));const l="rma"+(i.length>1?`_${n+1}`:""),c="RMA"+t+(i.length>1?` #${n+1}`:"");s.push({key:l,title:c,type:"line",data:a})})),s}},Wn={name:"Simple Moving Average",shortName:"SMA",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray"},k:{defaultValue:[2],type:"numberArray"}},calc(e,t){const i=Nn(t,"n",this.paramMap.n.defaultValue),s=Nn(t,"k",this.paramMap.k.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{l+=t.close,i>=r-1?(c=i===r-1?l/r:(t.close*a+c*(r-a))/r,l-=e[i-(r-1)].close,h.push({time:t.time,value:c})):h.push({time:t.time,value:NaN})}));const p="sma"+(n>1?`_${t+1}`:""),d="SMA"+r+","+a+(n>1?` #${t+1}`:"");o.push({key:p,title:d,type:"line",data:h})}return o}},qn={name:"Stop and Reverse",shortName:"SAR",shouldOhlc:!0,paramMap:{accStart:{defaultValue:[.02],type:"numberArray"},accStep:{defaultValue:[.02],type:"numberArray"},accMax:{defaultValue:[.2],type:"numberArray"}},calc(e,t){const i=Nn(t,"accStart",this.paramMap.accStart.defaultValue),s=Nn(t,"accStep",this.paramMap.accStep.defaultValue),n=Nn(t,"accMax",this.paramMap.accMax.defaultValue),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t{0!==i?(1===i&&(u=t.close>e[0].close,p=u?t.high:t.low,d=u?e[0].low:e[0].high,m.push({time:e[0].time,value:d})),d+=h*(p-d),u?t.lowp&&(p=t.high,h=Math.min(h+l,c)):t.high>d?(u=!0,d=p,h=a,p=t.high):t.low1?`_${t+1}`:""),f="SAR"+a+","+l+","+c+(o>1?` #${t+1}`:"");r.push({key:g,title:f,type:"line",data:m})}return r}},Xn={name:"Super Trend",shortName:"SuperTrend",shouldOhlc:!0,paramMap:{factor:{defaultValue:[3],type:"numberArray"},atrPeriod:{defaultValue:[10],type:"numberArray"}},calc(e,t){const i=Nn(t,"factor",this.paramMap.factor.defaultValue),s=Nn(t,"atrPeriod",this.paramMap.atrPeriod.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(id||e[i-1].closep?m:p),u=isNaN(h)?1:h===p?t.close>m?-1:1:t.close1?`_${t+1}`:"";o.push({key:"superTrend"+m,title:"SuperTrend"+r+(n>1?` #${t+1}`:""),type:"line",data:l}),o.push({key:"direction"+m,title:"Direction"+(n>1?` #${t+1}`:""),type:"line",data:c})}return o}},Jn={name:"Symmetrically Weighted Moving Average",shortName:"SWMA",shouldOhlc:!1,paramMap:{window:{defaultValue:[4],type:"numberArray"}},calc(e,t){const i=Nn(t,"window",this.paramMap.window.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:""),a="SWMA"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Yn={name:"TRIX",shortName:"TRIX",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray"},m:{defaultValue:[9],type:"numberArray"}},calc(e,t){const i=Nn(t,"n",this.paramMap.n.defaultValue),s=Nn(t,"m",this.paramMap.m.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{p+=e.close,t===r-1?l=p/r:t>r-1&&(l=(2*e.close+(r-1)*l)/(r+1)),t>=r-1&&(t===2*r-2?c=l:t>2*r-2&&(c=(2*l+(r-1)*c)/(r+1)));let i=NaN;if(t>=2*r-2)if(t===3*r-3)h=c;else if(t>3*r-3){const e=h;h=(2*c+(r-1)*e)/(r+1),i=(h-e)/e*100}if(d.push({time:e.time,value:i}),g.push(i),m+=isNaN(i)?0:i,g.length>a){const e=g[g.length-1-a];m-=isNaN(e)?0:e}const s=g.length>=a&&!isNaN(i)?m/a:NaN;u.push({time:e.time,value:s})}));const f=n>1?`_${t+1}`:"";o.push({key:"trix"+f,title:"TRIX"+r+(n>1?` #${t+1}`:""),type:"line",data:d}),o.push({key:"maTrix"+f,title:n>1?`MATRIX #${t+1}`:"MATRIX",type:"line",data:u})}return o}},Kn={name:"Volume Weighted Average Price",shortName:"VWAP",shouldOhlc:!0,paramMap:{anchorInterval:{defaultValue:[1],type:"numberArray"}},calc(e,t,i){if(!i)return[{key:"vwap",title:"VWAP",type:"line",data:[]}];const s=Nn(t,"anchorInterval",this.paramMap.anchorInterval.defaultValue),n=[];return s.forEach(((t,o)=>{let r=0,a=0;const l=[];e.forEach(((e,s)=>{s%t==0&&(r=0,a=0);const n=i[s]?.value??0,o=(e.high+e.low+e.close)/3;a+=o*n,r+=n;const c=0!==r?a/r:NaN;l.push({time:e.time,value:c})}));const c=s.length>1?`_${o+1}`:"";n.push({key:"vwap"+c,title:"VWAP"+t+(s.length>1?` #${o+1}`:""),type:"line",data:l})})),n}},Qn={name:"Volume Weighted Moving Average",shortName:"VWMA",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray"}},calc(e,t,i){if(!i)return[{key:"vwma",title:"VWMA",type:"line",data:[]}];const s=Nn(t,"length",this.paramMap.length.defaultValue),n=[];return s.forEach(((t,o)=>{let r=0,a=0;const l=[];e.forEach(((s,n)=>{const o=i[n]?.value??0;if(r+=s.close*o,a+=o,n>=t-1){const o=0!==a?r/a:NaN;l.push({time:s.time,value:o});const c=i[n-(t-1)].value??0;r-=e[n-(t-1)].close*c,a-=c}else l.push({time:s.time,value:NaN})}));const c=s.length>1?`_${o+1}`:"";n.push({key:"vwma"+c,title:"VWMA"+t+(s.length>1?` #${o+1}`:""),type:"line",data:l})})),n}},Zn={name:"Weighted Moving Average",shortName:"WMA",shouldOhlc:!1,paramMap:{length:{defaultValue:[9],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:"";s.push({key:"wma"+r,title:"WMA"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o})})),s}},eo={name:"High & Low",shortName:"HHLL",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[],r=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:"";s.push({key:"hh"+a,title:"HH"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o}),s.push({key:"ll"+a,title:"LL"+t+(i.length>1?` #${n+1}`:""),type:"line",data:r})})),s}},to=[Vn,Bn,Fn,$n,eo,Gn,jn,Un,zn,Hn,Wn,qn,Xn,Jn,Yn,Kn,Qn,Zn],io={name:"Awesome Oscillator",shortName:"AO",shouldOhlc:!0,paramMap:{shortPeriod:{defaultValue:[5],type:"numberArray",min:1,max:100},longPeriod:{defaultValue:[34],type:"numberArray",min:1,max:200}},calc(e,t){const i=Nn(t,"shortPeriod",[5]),s=Nn(t,"longPeriod",[34]),n=Math.max(i.length,s.length),o=[];for(let r=0;r{const s=(t.high+t.low)/2;h+=s,p+=s;let n=NaN,o=NaN;if(i>=a-1){n=h/a;const t=(e[i-(a-1)].high+e[i-(a-1)].low)/2;h-=t}if(i>=l-1){o=p/l;const t=(e[i-(l-1)].high+e[i-(l-1)].low)/2;p-=t}let r=NaN;i>=c-1&&(r=n-o),d.push({time:t.time,value:r})}));const u="ao"+(n>1?`_${r+1}`:""),m="AO"+On(i,r)+(n>1?` #${r+1}`:"");Ln(d,t?.upColor??"green",t?.downColor??"red"),o.push({key:u,title:m,type:"histogram",data:d,pane:1})}return o}},so={name:"Average True Range",shortName:"ATR",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=Nn(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];let r=0;const a=[];e.forEach(((i,s)=>{if(0===s)return void o.push({time:i.time,value:NaN});const n=e[s-1].close,l=Math.max(i.high-i.low,Math.abs(i.high-n),Math.abs(i.low-n));a.push(l),r+=l,a.length>t&&(r-=a.shift());const c=a.length>=t?r/t:NaN;o.push({time:i.time,value:c})}));const l=i.length>1?`_${n+1}`:"";s.push({key:"atr"+l,title:"ATR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},no={name:"Bias",shortName:"BIAS",shouldOhlc:!0,paramMap:{period1:{defaultValue:[6],type:"numberArray",min:1,max:999},period2:{defaultValue:[12],type:"numberArray",min:1,max:999},period3:{defaultValue:[24],type:"numberArray",min:1,max:999}},calc(e,t){const i=Nn(t,"period1",[6]),s=Nn(t,"period2",[12]),n=Nn(t,"period3",[24]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t0)),c=a.map(((e,i)=>({key:`bias${i+1}`+(o>1?`_${t+1}`:""),title:`BIAS${e}`+(o>1?` #${t+1}`:""),type:"line",data:[],pane:1})));e.forEach(((t,i)=>{const s=t.close;a.forEach(((n,o)=>{if(l[o]+=s,i>=n-1){const r=l[o]/n,a=(s-r)/r*100;c[o].data.push({time:t.time,value:a}),l[o]-=e[i-(n-1)].close}else c[o].data.push({time:t.time,value:NaN})}))})),r.push(...c)}return r}},oo={name:"Buy-Ratio Analysis",shortName:"BRAR",shouldOhlc:!0,paramMap:{length:{defaultValue:[26],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"length",[26]),s=[];return i.forEach(((t,n)=>{let o=0,r=0,a=0,l=0;const c=[],h=[];e.forEach(((i,s)=>{const n=s-1>=0?e[s-1]:i;if(a+=i.high-i.open,l+=i.open-i.low,o+=i.high-n.close,r+=n.close-i.low,s>=t-1){const n=0!==r?o/r*100:0,p=0!==l?a/l*100:0;c.push({time:i.time,value:n}),h.push({time:i.time,value:p});const d=e[s-(t-1)],u=s-t>=0?e[s-t]:d;o-=d.high-u.close,r-=u.close-d.low,a-=d.high-d.open,l-=d.open-d.low}else c.push({time:i.time,value:NaN}),h.push({time:i.time,value:NaN})}));const p=i.length>1?`_${n+1}`:"";s.push({key:"br"+p,title:"BR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:c,pane:1}),s.push({key:"ar"+p,title:"AR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:h,pane:1})})),s}},ro={name:"Bull and Bear Index",shortName:"BBI",shouldOhlc:!0,paramMap:{p1:{defaultValue:[3],type:"numberArray",min:1},p2:{defaultValue:[6],type:"numberArray",min:1},p3:{defaultValue:[12],type:"numberArray",min:1},p4:{defaultValue:[24],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"p1",[3]),s=Nn(t,"p2",[6]),n=Nn(t,"p3",[12]),o=Nn(t,"p4",[24]),r=Math.max(i.length,s.length,n.length,o.length),a=[];for(let t=0;t{const s=t.close;if(d.forEach(((t,n)=>{u[n]+=s,i>=t-1&&(m[n]=u[n]/t,u[n]-=e[i-(t-1)].close)})),i>=Math.max(...d)-1){const e=(m[0]+m[1]+m[2]+m[3])/4;g.push({time:t.time,value:e})}else g.push({time:t.time,value:NaN})}));const f=r>1?`_${t+1}`:"";a.push({key:"bbi"+f,title:"BBI"+[l,c,h,p].join(",")+(r>1?` #${t+1}`:""),type:"line",data:g,pane:1})}return a}},ao={name:"Commodity Channel Index",shortName:"CCI",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"length",[20]),s=[];return i.forEach(((t,n)=>{let o=0;const r=[],a=[];e.forEach(((i,s)=>{const n=(i.high+i.low+i.close)/3;if(o+=n,r.push(n),s>=t-1){const l=o/t;let c=0;for(let e=s-(t-1);e<=s;e++)c+=Math.abs(r[e]-l);const h=c/t,p=0!==h?(n-l)/(.015*h):0;a.push({time:i.time,value:p});const d=(e[s-(t-1)].high+e[s-(t-1)].low+e[s-(t-1)].close)/3;o-=d}else a.push({time:i.time,value:NaN})}));const l=i.length>1?`_${n+1}`:"";s.push({key:"cci"+l,title:"CCI"+t+(i.length>1?` #${n+1}`:""),type:"line",data:a,pane:1})})),s}},lo={name:"Current Ratio",shortName:"CR",shouldOhlc:!0,paramMap:{length:{defaultValue:[26],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"length",[26]),s=[];return i.forEach(((t,n)=>{let o=0,r=0;const a=[],l=[],c=[];e.forEach(((i,s)=>{const n=s-1>=0?e[s-1]:i,h=(n.high+n.low)/2,p=Math.max(0,i.high-h),d=Math.max(0,h-i.low);o+=p,r+=d,a.push(p),l.push(d);let u=NaN;s>=t-1&&(u=0!==r?o/r*100:0,o-=a[s-(t-1)],r-=l[s-(t-1)]),c.push({time:i.time,value:u})}));const h=i.length>1?`_${n+1}`:"";s.push({key:"cr"+h,title:"CR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:c,pane:1})})),s}},co={name:"Difference of Moving Average",shortName:"DMA",shouldOhlc:!0,paramMap:{n1:{defaultValue:[10],type:"numberArray",min:1},n2:{defaultValue:[50],type:"numberArray",min:1},m:{defaultValue:[10],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"n1",[10]),s=Nn(t,"n2",[50]),n=Nn(t,"m",[10]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t{p+=t.close,d+=t.close;let s=NaN,n=NaN;if(i>=a-1&&(s=p/a,p-=e[i-(a-1)].close),i>=l-1&&(n=d/l,d-=e[i-(l-1)].close),i>=h-1){const e=s-n;if(f.push(e),m.push({time:t.time,value:e}),u+=e,f.length>c){u-=f[f.length-1-c];const e=u/c;g.push({time:t.time,value:e})}else g.push({time:t.time,value:NaN})}else m.push({time:t.time,value:NaN}),g.push({time:t.time,value:NaN})}));const y=o>1?`_${t+1}`:"";r.push({key:"dma"+y,title:"DMA"+a+"-"+l+(o>1?` #${t+1}`:""),type:"line",data:m,pane:1}),r.push({key:"ama"+y,title:"AMA"+a+"-"+l+(o>1?` #${t+1}`:""),type:"line",data:g,pane:1})}return r}},ho={name:"Directional Movement Index",shortName:"DMI",shouldOhlc:!0,paramMap:{n:{defaultValue:[14],type:"numberArray",min:1},mm:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"n",[14]),s=Nn(t,"mm",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{const s=i-1>=0?e[i-1]:t,n=t.high-s.high,o=s.low-t.low,y=Math.max(t.high-t.low,Math.abs(t.high-s.close),Math.abs(s.close-t.low));let b=0,v=0;n>0&&n>o&&(b=n),o>0&&o>n&&(v=o),0===i?(l=y,c=b,h=v):(l=(l*(r-1)+y)/r,c=(c*(r-1)+b)/r,h=(h*(r-1)+v)/r);let x=NaN,_=NaN;0!==l&&(x=c/l*100,_=h/l*100),u.push({time:t.time,value:x}),m.push({time:t.time,value:_});let w=NaN;if(isNaN(x)||isNaN(_)||x+_===0||(w=Math.abs(_-x)/(_+x)*100),i1?`_${t+1}`:"";o.push({key:"pdi"+y,title:"PDI"+r+(n>1?` #${t+1}`:""),type:"line",data:u,pane:1}),o.push({key:"mdi"+y,title:"MDI"+r+(n>1?` #${t+1}`:""),type:"line",data:m,pane:1}),o.push({key:"adx"+y,title:"ADX"+r+(n>1?` #${t+1}`:""),type:"line",data:g,pane:1}),o.push({key:"adxr"+y,title:"ADXR"+r+(n>1?` #${t+1}`:""),type:"line",data:f,pane:1})}return o}},po={name:"Momentum",shortName:"MTM",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray",min:1},m:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"n",[12]),s=Nn(t,"m",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(i>=r){const s=e[i-r],n=t.close-s.close;l.push({time:t.time,value:n}),p.push(n),h+=n,p.length>a&&(h-=p[p.length-1-a]);const o=p.length>=a?h/a:NaN;c.push({time:t.time,value:o})}else l.push({time:t.time,value:NaN}),c.push({time:t.time,value:NaN})}));const d=n>1?`_${t+1}`:"";o.push({key:"mtm"+d,title:"MTM"+r+(n>1?` #${t+1}`:""),type:"line",data:l,pane:1}),o.push({key:"maMtm"+d,title:"MAMTM"+r+(n>1?` #${t+1}`:""),type:"line",data:c,pane:1})}return o}},uo={name:"Psychological Line",shortName:"PSY",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray",min:1},m:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"n",[12]),s=Nn(t,"m",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{const s=i-1>=0?e[i-1]:t,n=t.close>s.close?1:0;if(c.push(n),l+=n,i>=r-1){const e=l/r*100;p.push({time:t.time,value:e}),u.push(e),h+=e,u.length>a&&(h-=u[u.length-1-a]);const s=u.length>=a?h/a:NaN;d.push({time:t.time,value:s}),l-=c[i-(r-1)]}else p.push({time:t.time,value:NaN}),d.push({time:t.time,value:NaN})}));const m=n>1?`_${t+1}`:"";o.push({key:"psy"+m,title:"PSY"+r+(n>1?` #${t+1}`:""),type:"line",data:p,pane:1}),o.push({key:"maPsy"+m,title:"MAPSY"+r+(n>1?` #${t+1}`:""),type:"line",data:d,pane:1})}return o}},mo={name:"Rate of Change",shortName:"ROC",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray",min:1},m:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"n",[12]),s=Nn(t,"m",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(i>=r){const s=e[i-r].close;let n=0;0!==s&&(n=(t.close-s)/s*100),l.push({time:t.time,value:n}),p.push(n),h+=n,p.length>a&&(h-=p[p.length-1-a]);const o=p.length>=a?h/a:NaN;c.push({time:t.time,value:o})}else l.push({time:t.time,value:NaN}),c.push({time:t.time,value:NaN})}));const d=n>1?`_${t+1}`:"";o.push({key:"roc"+d,title:"ROC"+r+(n>1?` #${t+1}`:""),type:"line",data:l,pane:1}),o.push({key:"maRoc"+d,title:"MAROC"+r+(n>1?` #${t+1}`:""),type:"line",data:c,pane:1})}return o}},go={name:"RSI + SMA",shortName:"RSI_SMA",shouldOhlc:!0,paramMap:{p1:{defaultValue:[14],type:"numberArray",min:1},p2:{defaultValue:[21],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"p1",[14]),s=Nn(t,"p2",[10]),n=Math.max(i.length,s.length),o=e.map((e=>e.close)),r=[];for(let t=0;t{const i=Dn(o.slice(0,t+1),a);c.push(i);const s=In(c,l);h.push({time:e.time,value:i}),p.push({time:e.time,value:s})}));const d=n>1?`_${t+1}`:"",u={key:`rsi${d}`,title:`RSI(${a})${d}`,type:"line",data:h,pane:1},m={key:`smaOfRsi${d}`,title:`SMA(${l}) of RSI(${a})${d}`,type:"line",data:p,pane:1};r.push(u,m)}return r}},fo={name:"Stochastic",shortName:"KDJ",shouldOhlc:!0,paramMap:{n:{defaultValue:[9],type:"numberArray",min:1},kPeriod:{defaultValue:[3],type:"numberArray",min:1},dPeriod:{defaultValue:[3],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"n",[9]),s=Nn(t,"kPeriod",[3]),n=Nn(t,"dPeriod",[3]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t{if(ie.high))),o=Math.min(...s.map((e=>e.low))),r=n===o?100:(t.close-o)/(n-o)*100,g=((l-1)*h+r)/l,f=((c-1)*p+g)/c,y=3*g-2*f;d.push({time:t.time,value:g}),u.push({time:t.time,value:f}),m.push({time:t.time,value:y}),h=g,p=f}));const g=o>1?`_${t+1}`:"";r.push({key:"k"+g,title:"K"+a+(o>1?` #${t+1}`:""),type:"line",data:d,pane:1}),r.push({key:"d"+g,title:"D"+a+(o>1?` #${t+1}`:""),type:"line",data:u,pane:1}),r.push({key:"j"+g,title:"J"+a+(o>1?` #${t+1}`:""),type:"line",data:m,pane:1})}return r}},yo={name:"Variance",shortName:"Variance",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=Nn(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.close)),r=n.reduce(((e,t)=>e+t),0)/n.length,a=n.reduce(((e,t)=>e+Math.pow(t-r,2)),0)/n.length;o.push({time:i.time,value:a})}));const r=i.length>1?`_${n+1}`:"";s.push({key:"variance"+r,title:"Variance"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},bo={name:"Williams %R",shortName:"WR",shouldOhlc:!0,paramMap:{p1:{defaultValue:[6],type:"numberArray",min:1},p2:{defaultValue:[10],type:"numberArray",min:1},p3:{defaultValue:[14],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"p1",[6]),s=Nn(t,"p2",[10]),n=Nn(t,"p3",[14]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t({key:`wr${i+1}`+(o>1?`_${t+1}`:""),title:`WR${e}`+(o>1?` #${t+1}`:""),type:"line",data:[],pane:1})));e.forEach(((t,i)=>{a.forEach(((s,n)=>{if(i>=s-1){let o=-1/0,r=1/0;for(let t=i-(s-1);t<=i;t++)o=Math.max(o,e[t].high),r=Math.min(r,e[t].low);const a=o!==r?(t.close-o)/(o-r)*100:0;l[n].data.push({time:t.time,value:a})}else l[n].data.push({time:t.time,value:NaN})}))})),r.push(...l)}return r}},vo={name:"Change",shortName:"Change",shouldOhlc:!0,paramMap:{length:{defaultValue:[1],type:"numberArray",min:1,max:100}},calc(e,t){const i=Nn(t,"length",[1]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:"";s.push({key:"change"+r,title:"Change"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},xo={name:"Range",shortName:"Range",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=Nn(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.high))),a=Math.min(...n.map((e=>e.low)));o.push({time:i.time,value:r-a})}));const r=i.length>1?`_${n+1}`:"";s.push({key:"range"+r,title:"Range"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},_o={name:"Standard Deviation",shortName:"StdDev",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=Nn(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.close)),r=n.reduce(((e,t)=>e+t),0)/n.length,a=n.reduce(((e,t)=>e+Math.pow(t-r,2)),0)/n.length,l=Math.sqrt(a);o.push({time:i.time,value:l})}));const r=i.length>1?`_${n+1}`:"";s.push({key:"stdDev"+r,title:"StdDev"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},wo={name:"Moving Average Convergence Divergence",shortName:"MACD",shouldOhlc:!0,paramMap:{shortPeriod:{defaultValue:12,type:"number",min:1},longPeriod:{defaultValue:26,type:"number",min:1},signalPeriod:{defaultValue:9,type:"number",min:1}},calc(e,t){const i=function(e,t){const i={};for(const[s,n]of Object.entries(e.paramMap)){const e=t?.[s]??n.defaultValue;i[s]=e}return i}(this,t),s=i.shortPeriod,n=i.longPeriod,o=i.signalPeriod;let r=0,a=0,l=0,c=0,h=0;const p=[],d=[],u=[];let m=0;e.forEach(((e,t)=>{m+=e.close,t===s-1?r=m/s:t>s-1&&(r=(2*e.close+(s-1)*r)/(s+1)),t===n-1?a=m/n:t>n-1&&(a=(2*e.close+(n-1)*a)/(n+1)),t>=Math.max(s,n)-1?(l=r-a,p.push({time:e.time,value:l}),h+=l,p.length===o?c=h/o:p.length>o&&(c=(2*l+(o-1)*c)/(o+1)),p.length>=o?(d.push({time:e.time,value:c}),u.push({time:e.time,value:2*(l-c)})):(d.push({time:e.time,value:NaN}),u.push({time:e.time,value:NaN}))):(p.push({time:e.time,value:NaN}),d.push({time:e.time,value:NaN}),u.push({time:e.time,value:NaN}))}));return Ln(u,t?.upColor??"green",t?.downColor??"red"),[{key:"dif",title:"DIF",type:"line",data:p,pane:1},{key:"dea",title:"DEA",type:"line",data:d,pane:1},{key:"macd",title:"MACD",type:"histogram",data:u,pane:1}]}},Co=[...to,...[io,so,no,oo,ro,ao,lo,co,ho,po,wo,uo,mo,go,fo,yo,bo,vo,xo,_o]];class So{contextMenu;handler;container;currentTab="options";constructor(e){this.contextMenu=e.contextMenu,this.handler=e.handler,this.container=this.contextMenu.div}openMenu(e,t,i){const s={type:i||e._type||e.constructor.name,object:e.toJSON(),title:e.title},n=JSON.stringify(s,null,2);let o={};e instanceof Ro?o=e.chart.options():void 0!==e.options?o="function"==typeof e.options?e.options():e.options:void 0!==e._options&&(o=e._options);const r={...o},a=JSON.stringify(r,null,2),l=document.createElement("div");l.style.position="fixed",l.style.top="0",l.style.left="0",l.style.width="100%",l.style.height="100%",l.style.backgroundColor="rgba(0, 0, 0, 0.5)",l.style.display="flex",l.style.justifyContent="center",l.style.alignItems="center",l.style.zIndex="1000";const c=e=>{"Escape"===e.key&&this.close(l,c)};document.addEventListener("keydown",c);const h=document.createElement("div");h.style.backgroundColor="#333",h.style.color="#fff",h.style.padding="20px",h.style.borderRadius="8px",h.style.width="80%",h.style.maxWidth="800px",h.style.maxHeight="90%",h.style.overflowY="auto",h.style.boxShadow="0 2px 10px rgba(0,0,0,0.5)",h.setAttribute("tabindex","-1"),h.focus();const p=document.createElement("div");p.style.display="flex",p.style.borderBottom="1px solid #555",p.style.marginBottom="10px";const d=document.createElement("button");d.textContent="Options",d.style.flex="1",d.style.padding="10px",d.style.cursor="pointer",d.style.border="none",d.style.backgroundColor="options"===this.currentTab?"#555":"#333",d.onclick=()=>{this.currentTab="options",d.style.backgroundColor="#555",u.style.backgroundColor="#333",g.value=a,v.style.display="flex",f.style.display="none"};const u=document.createElement("button");u.textContent="Full",u.style.flex="1",u.style.padding="10px",u.style.cursor="pointer",u.style.border="none",u.style.backgroundColor="full"===this.currentTab?"#555":"#333",u.onclick=()=>{this.currentTab="full",u.style.backgroundColor="#555",d.style.backgroundColor="#333",g.value=n,f.style.display="flex",v.style.display="none"},p.appendChild(d),p.appendChild(u),h.appendChild(p);const m=document.createElement("h2");m.textContent=`Export/Import ${e.title} Data`,h.appendChild(m);const g=document.createElement("textarea");g.value="full"===this.currentTab?n:a,g.style.width="100%",g.style.height="400px",g.style.marginTop="10px",g.style.marginBottom="10px",g.style.resize="vertical",g.style.backgroundColor="#444",g.style.color="#fff",g.setAttribute("aria-label","JSON Data Editor"),h.appendChild(g);const f=document.createElement("div");f.style.display="full"===this.currentTab?"flex":"none",f.style.flexWrap="wrap",f.style.justifyContent="flex-end",f.style.gap="10px";const y=document.createElement("button");y.textContent="Export",y.style.padding="8px 12px",y.style.cursor="pointer",y.style.backgroundColor="#f44336",y.style.color="#fff",y.style.border="none",y.style.borderRadius="4px",y.onclick=()=>{this.downloadJson(n,`${e.title}_full.json`)},f.appendChild(y);const b=document.createElement("button");b.textContent="Import",b.style.padding="8px 12px",b.style.cursor="pointer",b.style.backgroundColor="#4CAF50",b.style.color="#fff",b.style.border="none",b.style.borderRadius="4px",b.onclick=()=>{try{const t=JSON.parse(g.value);if("object"!=typeof t||!t.object)throw new Error("Invalid structure: missing 'object'.");e.fromJSON(t.object),"function"==typeof e.updateView&&e.updateView(),this.showNotification("Whole data imported successfully.","success")}catch(e){this.showNotification("Failed to import whole data: "+e.message,"error")}},f.appendChild(b);const v=document.createElement("div");v.style.display="options"===this.currentTab?"flex":"none",v.style.flexWrap="wrap",v.style.justifyContent="flex-end",v.style.gap="10px";const x=document.createElement("button");x.textContent="Export Options",x.style.padding="8px 12px",x.style.cursor="pointer",x.style.backgroundColor="#f44336",x.style.color="#fff",x.style.border="none",x.style.borderRadius="4px",x.onclick=()=>{this.downloadJson(a,`${e.title}_options.json`)},v.appendChild(x);const _=document.createElement("button");_.textContent="Import Options",_.style.padding="8px 12px",_.style.cursor="pointer",_.style.backgroundColor="#4CAF50",_.style.color="#fff",_.style.border="none",_.style.borderRadius="4px",_.onclick=()=>{const t=document.createElement("input");t.type="file",t.accept="application/json",t.style.display="none",t.addEventListener("change",(()=>{if(t.files&&t.files.length>0){const i=t.files[0],s=new FileReader;s.onload=()=>{try{const t=s.result;if("string"!=typeof t)throw new Error("File content is not a string.");g.value=t;const i=JSON.parse(t);if("object"!=typeof i||!i.options)throw new Error("Invalid structure: missing 'options'.");e.fromJSON(i.options),"function"==typeof e.updateView&&e.updateView(),this.showNotification("Options imported successfully.","success")}catch(e){this.showNotification("Failed to import options: "+e.message,"error")}},s.readAsText(i)}})),t.click()},v.appendChild(_);const w=document.createElement("button");w.textContent="Save",w.style.padding="8px 12px",w.style.cursor="pointer",w.style.backgroundColor="#008CBA",w.style.color="#fff",w.style.border="none",w.style.borderRadius="4px",w.onclick=()=>{try{const t=JSON.parse(g.value);if("object"!=typeof t||!t.options)throw new Error("Invalid structure: missing 'options'.");e.fromJSON(t),"function"==typeof e.updateView&&e.updateView();JSON.stringify(t,null,2);this.showNotification("Options applied and exported successfully.","success")}catch(e){this.showNotification("Failed to save options: "+e.message,"error")}};const C=document.createElement("button");C.textContent="Save as Default",C.style.padding="8px 12px",C.style.cursor="pointer",C.style.backgroundColor="#008CBA",C.style.color="#fff",C.style.border="none",C.style.borderRadius="4px",C.onclick=()=>{let t={};e instanceof Ro?t=e.chart.options():"function"==typeof e.options?t=e.options():void 0!==e.options?t=e.options:void 0!==e._options&&(t=e._options);const i=JSON.stringify(t,null,2);let s;if(e._type&&"custom/custom"===e._type.toLowerCase()){if(s=prompt("Enter save key (e.g., area, line, candlestick):",e.title.toLowerCase())||"",!s)return}else s=e._type?e._type.toLowerCase():e.title.toLowerCase();const n=`save_defaults_~_${s};;;${i}`;window.callbackFunction(n)},this.container.appendChild(C);const S=document.createElement("div");S.style.display="flex",S.style.flexDirection="column",S.style.gap="10px",S.appendChild(f),S.appendChild(v),S.appendChild(w),S.appendChild(C),h.appendChild(S),l.appendChild(h),this.container.appendChild(l)}downloadJson(e,t){try{const i=new Blob([e],{type:"application/json"}),s=URL.createObjectURL(i),n=document.createElement("a");n.href=s,n.download=t,n.click(),URL.revokeObjectURL(s)}catch(e){this.showNotification("Failed to download data: "+e,"error")}}addSaveDefaultButton(e){const t=document.createElement("button");t.textContent="Save as Default",t.style.padding="8px 12px",t.style.cursor="pointer",t.style.backgroundColor="#008CBA",t.style.color="#fff",t.style.border="none",t.style.borderRadius="4px",t.onclick=()=>{let t={};e instanceof Ro?t=e.chart.options():"function"==typeof e.options?t=e.options():void 0!==e.options?t=e.options:void 0!==e._options&&(t=e._options);const i=JSON.stringify(t,null,2),s=prompt("Enter save key (area, line, trend-trace, candlestick etc):",e.title.toLowerCase());if(!s)return;const n=`save_defaults_${s}_~_${i}`;window.callbackFunction(n)},this.container.appendChild(t)}close(e,t){e.parentElement&&e.parentElement.removeChild(e),document.removeEventListener("keydown",t)}showNotification(e,t){const i=document.createElement("div");i.textContent=e,i.style.position="fixed",i.style.bottom="20px",i.style.right="20px",i.style.padding="10px 20px",i.style.borderRadius="4px",i.style.color="#fff",i.style.backgroundColor="success"===t?"#4CAF50":"#f44336",i.style.boxShadow="0 2px 6px rgba(0,0,0,0.2)",i.style.zIndex="1001",i.style.opacity="0",i.style.transition="opacity 0.5s ease-in-out",this.container.appendChild(i),setTimeout((()=>{i.style.opacity="1"}),100),setTimeout((()=>{i.style.opacity="0",setTimeout((()=>{i.parentElement&&i.parentElement.removeChild(i)}),500)}),3e3)}openDefaultOptions(e){const t=this.handler.defaultsManager;if(!t)return void this.showNotification("No defaults manager found.","error");const i=t.get(e);if(!i)return void this.showNotification(`No default config found for key: "${e}"`,"error");JSON.stringify(i,null,2);const s=document.createElement("div");Object.assign(s.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:"1000"});const n=e=>{"Escape"===e.key&&this.close(s,n)};document.addEventListener("keydown",n);const o=document.createElement("div");Object.assign(o.style,{backgroundColor:"#333",color:"#fff",padding:"20px",borderRadius:"8px",width:"80%",maxWidth:"800px",maxHeight:"90%",overflowY:"auto",boxShadow:"0 2px 10px rgba(0,0,0,0.5)"}),o.setAttribute("tabindex","-1"),o.focus();const r=document.createElement("h2");r.textContent=`Edit Default Options - "${e}"`,o.appendChild(r);const a=document.createElement("textarea");a.value=JSON.stringify(i,null,2),Object.assign(a.style,{width:"100%",height:"400px",resize:"vertical",backgroundColor:"#444",color:"#fff",border:"none",margin:"10px 0",padding:"10px"}),o.appendChild(a);const l=document.createElement("div");Object.assign(l.style,{display:"flex",flexWrap:"wrap",gap:"10px",justifyContent:"flex-end"});const c=document.createElement("button");c.textContent="Export",Object.assign(c.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#f44336",color:"#fff",border:"none",borderRadius:"4px"}),c.onclick=()=>{this.downloadJson(a.value,`${e}_defaults.json`)},l.appendChild(c);const h=document.createElement("button");h.textContent="Import",Object.assign(h.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#4CAF50",color:"#fff",border:"none",borderRadius:"4px"}),h.onclick=()=>{const e=document.createElement("input");e.type="file",e.accept="application/json",e.style.display="none",e.addEventListener("change",(()=>{if(e.files&&e.files.length>0){const t=e.files[0],i=new FileReader;i.onload=()=>{try{if("string"!=typeof i.result)throw new Error("File content is not a string.");a.value=i.result}catch(e){this.showNotification("Failed to read defaults file: "+e.message,"error")}},i.readAsText(t)}})),e.click()},l.appendChild(h);const p=document.createElement("button");p.textContent="Save",Object.assign(p.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#008CBA",color:"#fff",border:"none",borderRadius:"4px"}),p.onclick=()=>{try{const t=JSON.parse(a.value),i=JSON.stringify(t,null,2);let s=e;const n=`save_defaults_${s}_~_${i}`;window.callbackFunction(n),this.showNotification(`Defaults for "${s}" saved successfully.`,"success")}catch(e){this.showNotification("Failed to save defaults: "+e.message,"error")}},l.appendChild(p);const d=document.createElement("button");d.textContent="Cancel",Object.assign(d.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#444",color:"#fff",border:"none",borderRadius:"4px"}),d.onclick=()=>{this.close(s,n)},l.appendChild(d),o.appendChild(l),s.appendChild(o),this.container.appendChild(s)}}class ko{container;backdrop;isOpen=!1;categories=[];contentArea;activeCategoryId="";handler;colorPicker=null;_originalOpacities={};constructor(e){this.handler=e;const t=Array.isArray(this.handler.defaultsManager.get("colors"))?[...this.handler.defaultsManager.get("colors")]:[];this.colorPicker=new Sn("#ff0000",(()=>null),t&&0!==t.length?t:void 0),this.backdrop=document.createElement("div"),Object.assign(this.backdrop.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.5)",opacity:"0",transition:"opacity 0.3s ease",zIndex:"9998",display:"none"}),this.backdrop.addEventListener("click",(e=>{e.target===this.backdrop&&this.close(!1)})),document.body.appendChild(this.backdrop),this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"700px",maxWidth:"90%",height:"500px",maxHeight:"90%",backgroundColor:"#1E1E1E",color:"#FFF",borderRadius:"6px",boxShadow:"0 2px 10px rgba(0,0,0,0.8)",zIndex:"9999",opacity:"0",display:"none",transition:"opacity 0.3s ease, transform 0.3s ease"}),document.body.appendChild(this.container);const i=document.createElement("div");Object.assign(i.style,{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #3C3C3C",backgroundColor:"#2B2B2B"});const s=document.createElement("div");Object.assign(s.style,{fontSize:"16px",fontWeight:"bold"}),s.innerText="Settings",i.appendChild(s);const n=document.createElement("div");Object.assign(n.style,{fontSize:"20px",cursor:"pointer",userSelect:"none"}),n.innerText="×",n.onclick=()=>this.close(!1),i.appendChild(n),this.container.appendChild(i);const o=document.createElement("div");Object.assign(o.style,{display:"flex",flex:"1 1 auto",height:"calc(100% - 50px)",backgroundColor:"#1E1E1E"}),this.container.appendChild(o);const r=document.createElement("div");Object.assign(r.style,{width:"180px",borderRight:"1px solid #3C3C3C",display:"flex",flexDirection:"column",backgroundColor:"#2B2B2B"}),o.appendChild(r),this.contentArea=document.createElement("div"),Object.assign(this.contentArea.style,{flex:"1",padding:"16px",overflowY:"auto"}),o.appendChild(this.contentArea);const a=document.createElement("div");Object.assign(a.style,{borderTop:"1px solid #3C3C3C",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",backgroundColor:"#2B2B2B"});const l=document.createElement("button");Object.assign(l.style,{backgroundColor:"#444",color:"#FFF",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:"pointer",fontSize:"14px"}),l.innerText="Template ▾",a.appendChild(l);const c=document.createElement("div");Object.assign(c.style,{display:"flex",gap:"8px"});const h=document.createElement("button");Object.assign(h.style,{backgroundColor:"#444",color:"#FFF",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:"pointer",fontSize:"14px"}),h.innerText="Cancel",h.onclick=()=>this.close(!1),c.appendChild(h);const p=document.createElement("button");Object.assign(p.style,{backgroundColor:"#008CBA",color:"#FFF",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:"pointer",fontSize:"14px"}),p.innerText="Ok",p.onclick=()=>this.close(!0),c.appendChild(p),a.appendChild(c),this.container.appendChild(a),this.categories=[{id:"series-colors",label:"Series Colors",buildContent:()=>this.buildSeriesColorsTab()},{id:"primitive-colors",label:"Primitives Colors",buildContent:()=>this.buildPrimitivesTab()},{id:"layout-options",label:"Layout Options",buildContent:()=>this.buildLayoutOptionsTab()},{id:"grid-options",label:"Grid Options",buildContent:()=>this.buildGridOptionsTab()},{id:"crosshair-options",label:"Crosshair Options",buildContent:()=>this.buildCrosshairOptionsTab()},{id:"time-scale-options",label:"Time Scale",buildContent:()=>this.buildTimeScaleOptionsTab()},{id:"price-scale-options",label:"Price Scale",buildContent:()=>this.buildPriceScaleOptionsTab()},{id:"defaults-list",label:"Defaults",buildContent:()=>this.buildDefaultsListTab()},{id:"source-code",label:"source-code",buildContent:()=>this.buildSourceCodeTab()}],this.categories.forEach((e=>{const t=document.createElement("div");t.innerText=e.label,Object.assign(t.style,{padding:"12px 16px",cursor:"pointer",borderBottom:"1px solid #3C3C3C",userSelect:"none",transition:"background-color 0.2s"}),t.addEventListener("mouseenter",(()=>{t.style.backgroundColor="#3A3A3A"})),t.addEventListener("mouseleave",(()=>{t.style.backgroundColor=""})),t.addEventListener("click",(()=>this.switchCategory(e.id))),r.appendChild(t)})),this.categories.length>0&&(this.buildSeriesColorsTab(),this.switchCategory(this.categories[0].id))}open(){this.isOpen||(this.isOpen=!0,this.backdrop.style.display="block",setTimeout((()=>{this.backdrop.style.opacity="1"}),10),this.container.style.display="block",setTimeout((()=>{this.container.style.opacity="1",this.container.style.transform="translate(-50%, -50%) scale(1)"}),10),this.buildSeriesColorsTab())}close(e){e?console.log("Settings Modal: OK clicked. Save changes here."):console.log("Settings Modal: Cancel clicked."),this.isOpen=!1,this.backdrop.style.opacity="0",this.container.style.opacity="0",this.container.style.transform="translate(-50%, -50%) scale(0.95)",setTimeout((()=>{this.isOpen||(this.backdrop.style.display="none",this.container.style.display="none")}),300)}switchCategory(e){this.activeCategoryId=e,this.contentArea.innerHTML="";const t=this.categories.find((t=>t.id===e));t&&t.buildContent()}buildLayoutOptionsTab(){const e=document.createElement("div");e.innerText="Layout Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i=this.getCurrentOptionValue("layout.textColor")||"#000000";this.addColorPicker("Text Color",i,(e=>{this.handler.chart.applyOptions({layout:{textColor:e}})}));const s=this.handler.chart.options().layout?.background;if(s&&"solid"===s.type){const e=s.color||"#FFFFFF";this.addColorPicker("Background Color",e,(e=>{this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.Solid,color:e}}})}))}else if(s&&s.type===t.ColorType.VerticalGradient){let e=s.topColor||"rgba(255,0,0,0.33)",i=s.bottomColor||"rgba(0,255,0,0.33)";this.addColorPicker("Top Color",e,(e=>{i=s.bottomColor||"rgba(0,255,0,0.33)",this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.VerticalGradient,topColor:e,bottomColor:i}}})})),this.addColorPicker("Bottom Color",i,(i=>{e=s.topColor||"rgba(255,0,0,0.33)",this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.VerticalGradient,topColor:e,bottomColor:i}}})}))}else console.warn("Unknown background type.");const n=document.createElement("button");n.innerText="Switch Background Type",n.style.marginTop="12px",n.onclick=()=>this.toggleBackgroundType(),this.contentArea.appendChild(n)}buildGridOptionsTab(){const e=document.createElement("div");e.innerText="Grid Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i=this.getCurrentOptionValue("grid.vertLines.color")||"#D6DCDE";this.addColorPicker("Vertical Line Color",i,(e=>{this.handler.chart.applyOptions({grid:{vertLines:{color:e}}})}));const s=this.getCurrentOptionValue("grid.horzLines.color")||"#D6DCDE";this.addColorPicker("Horizontal Line Color",s,(e=>{this.handler.chart.applyOptions({grid:{horzLines:{color:e}}})}));const n={Solid:t.LineStyle.Solid,Dotted:t.LineStyle.Dotted,Dashed:t.LineStyle.Dashed,LargeDashed:t.LineStyle.LargeDashed,SparseDotted:t.LineStyle.SparseDotted};this.addDropdown("Vertical Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=n[e];this.handler.chart.applyOptions({grid:{vertLines:{style:t}}})})),this.addDropdown("Horizontal Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=n[e];this.handler.chart.applyOptions({grid:{horzLines:{style:t}}})}));const o=!1!==this.getCurrentOptionValue("grid.vertLines.visible");this.addCheckbox("Show Vertical Lines",o,(e=>{this.handler.chart.applyOptions({grid:{vertLines:{visible:e}}})}));const r=!1!==this.getCurrentOptionValue("grid.horzLines.visible");this.addCheckbox("Show Horizontal Lines",r,(e=>{this.handler.chart.applyOptions({grid:{horzLines:{visible:e}}})}))}buildCrosshairOptionsTab(){const e=document.createElement("div");e.innerText="Crosshair Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i={Solid:t.LineStyle.Solid,Dotted:t.LineStyle.Dotted,Dashed:t.LineStyle.Dashed,LargeDashed:t.LineStyle.LargeDashed,SparseDotted:t.LineStyle.SparseDotted},s=this.getCurrentOptionValue("crosshair.vertLine.style")||"Solid",n=this.getCurrentOptionValue("crosshair.horzLine.style")||"Solid",o=this.getCurrentOptionValue("crosshair.mode")||"Normal";this.addDropdown("Crosshair Mode",["Normal","Magnet","Hidden"],(e=>{this.handler.chart.applyOptions({crosshair:{mode:e}})}),o);const r=Array.from({length:10},((e,t)=>(t+1).toString())),a=(this.getCurrentOptionValue("crosshair.vertLine.width")||"1").toString();this.addDropdown("Vertical Line Width",r,(e=>{const t=parseInt(e,10);this.handler.chart.applyOptions({crosshair:{vertLine:{width:t}}})}),a),this.addDropdown("Vertical Crosshair Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=i[e];this.handler.chart.applyOptions({crosshair:{vertLine:{style:t}}})}),s);const l=this.getCurrentOptionValue("crosshair.vertLine.color")||"#C3BCDB44";this.addColorPicker("Vertical Line Color",l,(e=>{this.handler.chart.applyOptions({crosshair:{vertLine:{color:e}}})}));const c=this.getCurrentOptionValue("crosshair.vertLine.labelBackgroundColor")||"#9B7DFF";this.addColorPicker("Vertical Label Background",c,(e=>{this.handler.chart.applyOptions({crosshair:{vertLine:{labelBackgroundColor:e}}})})),(this.getCurrentOptionValue("crosshair.horzLine.width")||"1").toString(),this.addDropdown("Horizontal Line Width",r,(e=>{const t=parseInt(e,10);this.handler.chart.applyOptions({crosshair:{horzLine:{width:t}}})})),this.addDropdown("Horizontal Crosshair Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=i[e];this.handler.chart.applyOptions({crosshair:{horzLine:{style:t}}})}),n);const h=this.getCurrentOptionValue("crosshair.horzLine.color")||"#9B7DFF";this.addColorPicker("Horizontal Line Color",h,(e=>{this.handler.chart.applyOptions({crosshair:{horzLine:{color:e}}})}));const p=this.getCurrentOptionValue("crosshair.horzLine.labelBackgroundColor")||"#9B7DFF";this.addColorPicker("Horizontal Label Background",p,(e=>{this.handler.chart.applyOptions({crosshair:{horzLine:{labelBackgroundColor:e}}})}))}buildTimeScaleOptionsTab(){const e=document.createElement("div");e.innerText="Time Scale Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const t=this.getCurrentOptionValue("timeScale.rightOffset")||0;this.addNumberField("Right Offset",t,(e=>{this.handler.chart.applyOptions({timeScale:{rightOffset:e}})}));const i=this.getCurrentOptionValue("timeScale.barSpacing")||10;this.addNumberField("Bar Spacing",i,(e=>{this.handler.chart.applyOptions({timeScale:{barSpacing:e}})}));const s=this.getCurrentOptionValue("timeScale.minBarSpacing")||.1;this.addNumberField("Min Bar Spacing",s,(e=>{this.handler.chart.applyOptions({timeScale:{minBarSpacing:e}})}));const n=this.getCurrentOptionValue("timeScale.fixLeftEdge")||!1;this.addCheckbox("Fix Left Edge",n,(e=>{this.handler.chart.applyOptions({timeScale:{fixLeftEdge:e}})}));const o=this.getCurrentOptionValue("timeScale.fixRightEdge")||!1;this.addCheckbox("Fix Right Edge",o,(e=>{this.handler.chart.applyOptions({timeScale:{fixRightEdge:e}})}));const r=this.getCurrentOptionValue("timeScale.lockVisibleTimeRangeOnResize")||!1;this.addCheckbox("Lock Visible Range on Resize",r,(e=>{this.handler.chart.applyOptions({timeScale:{lockVisibleTimeRangeOnResize:e}})}));const a=this.getCurrentOptionValue("timeScale.visible");this.addCheckbox("Time Scale Visible",!1!==a,(e=>{this.handler.chart.applyOptions({timeScale:{visible:e}})}));const l=this.getCurrentOptionValue("timeScale.borderVisible");this.addCheckbox("Border Visible",!1!==l,(e=>{this.handler.chart.applyOptions({timeScale:{borderVisible:e}})}));const c=this.getCurrentOptionValue("timeScale.borderColor")||"#000000";this.addColorPicker("Border Color",c,(e=>{this.handler.chart.applyOptions({timeScale:{borderColor:e}})}))}buildPriceScaleOptionsTab(){const e=document.createElement("div");e.innerText="Price Scale Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i=this.handler.chart.priceScale("right");i.options().mode||t.PriceScaleMode.Normal;const s=[{label:"Normal",value:t.PriceScaleMode.Normal},{label:"Logarithmic",value:t.PriceScaleMode.Logarithmic},{label:"Percentage",value:t.PriceScaleMode.Percentage},{label:"Indexed To 100",value:t.PriceScaleMode.IndexedTo100}],n=s.map((e=>e.label));this.addDropdown("Price Scale Mode",n,(e=>{const t=s.find((t=>t.label===e));t&&i.applyOptions({mode:t.value})}));const o=void 0===i.options().autoScale||i.options().autoScale;this.addCheckbox("Auto Scale",o,(e=>{i.applyOptions({autoScale:e})}));const r=i.options().invertScale||!1;this.addCheckbox("Invert Scale",r,(e=>{i.applyOptions({invertScale:e})}));const a=void 0===i.options().alignLabels||i.options().alignLabels;this.addCheckbox("Align Labels",a,(e=>{i.applyOptions({alignLabels:e})}));const l=void 0===i.options().borderVisible||i.options().borderVisible;this.addCheckbox("Border Visible",l,(e=>{i.applyOptions({borderVisible:e})}));const c=i.options().ticksVisible||!1;this.addCheckbox("Ticks Visible",c,(e=>{i.applyOptions({ticksVisible:e})}))}buildCloneSeriesTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Clone Series - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Clone Series logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildVisibilityOptionsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Visibility Options - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Visibility Options logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildStyleOptionsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Style Options - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Style Options logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildWidthOptionsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Width Options - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Width Options logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildPrimitivesTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Primitives",Object.assign(e.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(e),this.handler._seriesList.forEach((e=>{if(e.primitives&&Array.isArray(e.primitives)&&e.primitives.length>0){let t="Unnamed Series";const i=e.options();i&&i.title&&(t=i.title);const s=document.createElement("div");Object.assign(s.style,{border:"2px solid #666",marginBottom:"12px",padding:"8px",borderRadius:"4px"});const n=document.createElement("div");n.innerText=`Series: ${t}`,Object.assign(n.style,{fontSize:"18px",fontWeight:"bold",marginBottom:"8px"}),s.appendChild(n),e.primitives.forEach(((e,t)=>{let i;if("function"==typeof e.options?i=e.options():e._options?i=e._options:e.options&&(i=e.options),!i)return;const n=document.createElement("div");Object.assign(n.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"});const o=document.createElement("div");o.innerText=`Primitive ${t+1}: ${e.name||"Unnamed"}`,Object.assign(o.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"6px"}),n.appendChild(o),this.buildPrimitiveColorOptions(i,n,(t=>{e.applyOptions(t)})),s.appendChild(n)})),this.contentArea.appendChild(s)}}))}buildIndicatorsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Indicators - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Indicators logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildSourceCodeTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Source Code & Licensing",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="12px",this.contentArea.appendChild(e);const t=document.createElement("div");t.style.marginBottom="12px",t.style.fontSize="16px",t.innerHTML='\n

\n This project is a derivative work that incorporates components from the following repositories:\n

\n

\n Base Source Repositories:\n

\n \n

\n Modified/Forked Repositories (by EsIstJosh):\n

\n \n ',this.contentArea.appendChild(t),this.addButton("⤝ Back",(()=>this.switchCategory(this.categories[0].id)),{backgroundColor:"#444"})}buildSeriesMenuTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Series Settings - ${e.options().title??"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t),this.addTextInput("Title",e.options().title||"",(t=>{e.applyOptions({title:t});const i=e.options().title;i&&this.handler.seriesMap.has(i)&&this.handler.seriesMap.delete(i),this.handler.seriesMap.set(t,e)})),this.addButton("Clone Series ▸",(()=>this.buildCloneSeriesTab(e))),this.addButton("Visibility Options ▸",(()=>this.buildVisibilityOptionsTab(e))),this.addButton("Style Options ▸",(()=>this.buildStyleOptionsTab(e))),this.addButton("Width Options ▸",(()=>this.buildWidthOptionsTab(e))),this.addButton("Color Options ▸",(()=>this.buildSeriesColorsTabSingle(e))),this.addButton("Price Scale Options ▸",(()=>this.buildPriceScaleOptionsTab())),this.addButton("Primitives ▸",(()=>this.buildPrimitivesTab())),this.addButton("Indicators ▸",(()=>this.buildIndicatorsTab(e))),this.addButton("Export/Import Series Data ▸",(()=>this.buildDataExportImportTab(e)))}buildSeriesColorsTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Series Colors (All Series)",Object.assign(e.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(e);const t=Array.from(this.handler.seriesMap.entries());if(0===t.length){const e=document.createElement("div");return e.innerText="No series found.",e.style.color="#ccc",void this.contentArea.appendChild(e)}if(t.forEach((([e,t])=>{this.buildSeriesColorSection(e,t)})),this.handler.volumeSeries){const e=document.createElement("div");Object.assign(e.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"});const t=document.createElement("div");t.innerText="Series: Volume",Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"6px"}),e.appendChild(t);const i=this.handler.volumeSeries,s=this.handler.series.options().borderUpColor||"#00FF00",n=this.handler.series.options().borderDownColor||"#FF0000";let o=this.handler.volumeUpColor,r=this.handler.volumeDownColor;let a=o??s,l=r??n;const c=(e,t)=>{const s=[...i.data()];if(!s||0===s.length)return void console.warn("No volume data available to update colors.");const n=s.map(((i,n)=>{if(0===n)return{...i,color:e};const o=s[n-1].value,r=i.value>o?e:t;return{...i,color:r}}));i.setData(n),this.handler.volumeUpColor=e,this.handler.volumeDownColor=t};this.addSideBySideColors("Volume Colors",a,l,((e,t)=>{a=e,l=t,c(e,t)}),e),this.contentArea.appendChild(e)}}buildSeriesColorSection(e,t){const i=document.createElement("div");Object.assign(i.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"});const s=document.createElement("div");s.innerText=`Series: ${e}`,Object.assign(s.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"6px"}),i.appendChild(s);const n=t.seriesType?.();if("Candlestick"===n||"Bar"===n||"Custom"===n&&"upColor"in t.options())"upColor"in t.options()&&this.addSideBySideColors("Body",t.options().upColor,t.options().downColor,((e,i)=>{t.applyOptions({upColor:e,downColor:i})}),i),"borderUpColor"in t.options()&&(this.addSideBySideColors("Borders",t.options().borderUpColor,t.options().borderDownColor,((e,i)=>{t.applyOptions({borderUpColor:e,borderDownColor:i})}),i,t),this.addSideBySideColors("Wick",t.options().wickUpColor,t.options().wickDownColor,((e,i)=>{t.applyOptions({wickUpColor:e,wickDownColor:i})}),i,t));else if("Line"===n||"Custom"===n&&"color"in t.options()){const e=t.options().color||"#ffffff";this.addColorPicker("Line Color",e,(e=>t.applyOptions({color:e})),i)}else if("Area"===n){const e=t.options();this.addColorPicker("Line Color",e.lineColor||"#EEEEEE",(e=>{t.applyOptions({lineColor:e})}),i,t),this.addColorPicker("Top Fill",e.topColor||"#008cff44",(e=>{t.applyOptions({topColor:e})}),i,t),this.addColorPicker("Bottom Fill",e.bottomColor||"#008cff00",(e=>{t.applyOptions({bottomColor:e})}),i,t)}else{const e=document.createElement("div");e.innerText=`No color settings for series type: ${n}`,e.style.color="#bbb",i.appendChild(e)}this.contentArea.appendChild(i)}buildSeriesColorsTabSingle(e){this.contentArea.innerHTML="";const t=document.createElement("div");Object.assign(t.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText=`Color Options - ${e.options().title||"Untitled"}`,Object.assign(i.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),t.appendChild(i);const s=e.type?.();if("Candlestick"===s||"Bar"===s||"Custom"===s&&"upColor"in e.options())"upColor"in e.options()&&this.addSideBySideColors("Body",e.options().upColor,e.options().downColor,((t,i)=>{e.applyOptions({upColor:t,downColor:i})}),t,e),"borderUpColor"in e.options()&&(this.addSideBySideColors("Borders",e.options().borderUpColor,e.options().borderDownColor,((t,i)=>{e.applyOptions({borderUpColor:t,borderDownColor:i})}),t,e),this.addSideBySideColors("Wick",e.options().wickUpColor,e.options().wickDownColor,((t,i)=>{e.applyOptions({wickUpColor:t,wickDownColor:i})}),t,e));else if("Line"===s||"Custom"===s&&"color"in e.options()){const i=e.options().color||"#FFFFFF";this.addColorPicker("Line Color",i,(t=>{e.applyOptions({color:t})}),t,e)}else if("Area"===s){const i=e.options();this.addColorPicker("Line Color",i.lineColor||"#EEEEEE",(t=>{e.applyOptions({lineColor:t})}),t,e)}else{const e=document.createElement("div");e.innerText=`No color settings for series type: ${s}`,e.style.color="#bbb",t.appendChild(e)}const n=document.createElement("button");n.innerText="⤝ Back",Object.assign(n.style,{backgroundColor:"#444",marginTop:"16px",padding:"8px 12px",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer"}),n.onclick=()=>this.buildSeriesMenuTab(e),t.appendChild(n)}buildDataExportImportTab(e){this.subTabSkeleton("Export/Import",e,"(Export/Import logic not yet implemented.)")}subTabSkeleton(e,t,i){this.contentArea.innerHTML="";const s=document.createElement("div");s.innerText=`${e} - ${t.options().title||"Untitled"}`,Object.assign(s.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(s);const n=document.createElement("div");n.innerText=i,Object.assign(n.style,{color:"#ccc",marginBottom:"12px"}),this.contentArea.appendChild(n),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(t)),{backgroundColor:"#444"})}buildDefaultsListTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Default Configurations",Object.assign(e.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(e);const t=this.handler?.defaultsManager;if(!t){const e=document.createElement("div");return e.innerText="No defaults manager found.",e.style.color="#ccc",void this.contentArea.appendChild(e)}const i=t.getAll(),s=Array.from(i.keys());if(0===s.length){const e=document.createElement("div");return e.innerText="No default configurations found.",e.style.color="#ccc",void this.contentArea.appendChild(e)}this.addButton("Current Chart Config ▸",(e=>{this.handler.ContextMenu.dataMenu||(this.handler.ContextMenu.dataMenu=new So({contextMenu:this.handler.ContextMenu,handler:this.handler})),this.handler.ContextMenu.dataMenu.openMenu(this.handler,e,"Handler")}),{backgroundColor:"#444",borderRadius:"8px",marginBottom:"8px",display:"block"}),s.forEach((e=>{this.addButton(`Edit "${e}" Defaults`,(()=>{this.handler.ContextMenu?.dataMenu&&"function"==typeof this.handler.ContextMenu.dataMenu.openDefaultOptions?this.handler.ContextMenu.dataMenu.openDefaultOptions(e):console.warn("No dataMenu or openDefaultOptions method found on handler.")}),{backgroundColor:"#444",borderRadius:"8px",marginBottom:"8px",display:"block"})}))}addColorPicker(e,t,i,s=this.contentArea,n){const o=document.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px",fontFamily:"sans-serif",fontSize:"16px"});const r=document.createElement("span");r.innerText=e,o.appendChild(r);const a=document.createElement("div");Object.assign(a.style,{width:"26px",height:"26px",borderRadius:"4px",cursor:"pointer",border:"1px solid #999",backgroundColor:t}),o.appendChild(a);const l=e=>{if(!n)return;const t=this.handler.legend._lines.find((e=>e.series===n));t&&(t.colors[0]=e)};a.addEventListener("click",(e=>{this.colorPicker?(this.colorPicker.update(a.style.backgroundColor,(e=>{a.style.backgroundColor=e,i(e),l(e)})),this.colorPicker.openMenu(e,a.offsetWidth,(e=>{a.style.backgroundColor=e,i(e),l(e)}))):console.warn("No colorPicker defined!")})),s.appendChild(o)}addDropdown(e,t,i,s){const n=document.createElement("div");n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="space-between",n.style.marginBottom="8px";const o=document.createElement("span");o.innerText=e,n.appendChild(o);const r=document.createElement("select");r.style.backgroundColor="#444",r.style.color="#fff",r.style.border="1px solid #555",r.style.borderRadius="4px",r.style.outline="none",t.forEach((e=>{const t=document.createElement("option");t.value=e,t.innerText=e,s&&e===s&&(t.selected=!0),r.appendChild(t)})),s&&(r.value=s),r.onchange=()=>i(r.value),n.appendChild(r),this.contentArea.appendChild(n)}addButton(e,t,i){const s=document.createElement("button");s.innerText=e,Object.assign(s.style,{padding:"8px 12px",margin:"4px 0",backgroundColor:"#008CBA",color:"#fff",border:"none",borderRadius:"8px",cursor:"pointer",fontFamily:"sans-serif",fontSize:"16px"}),i&&Object.assign(s.style,i),s.onclick=t,this.contentArea.appendChild(s)}addNumberField(e,t,i){const s=document.createElement("div");s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="space-between",s.style.marginBottom="8px";const n=document.createElement("span");n.innerText=e,s.appendChild(n);const o=document.createElement("input");o.type="number",o.value=t.toString(),o.style.width="60px",o.style.backgroundColor="#444",o.style.color="#fff",o.style.border="1px solid #555",o.style.borderRadius="4px",o.oninput=()=>{const e=parseFloat(o.value);i(isNaN(e)?0:e)},s.appendChild(o),this.contentArea.appendChild(s)}addCheckbox(e,t,i){const s=document.createElement("label");s.style.display="flex",s.style.alignItems="center",s.style.marginBottom="8px";const n=document.createElement("input");n.type="checkbox",n.checked=t,n.style.marginRight="8px",n.onchange=()=>i(n.checked),s.appendChild(n);const o=document.createElement("span");o.innerText=e,s.appendChild(o),this.contentArea.appendChild(s)}getCurrentOptionValue(e){const t=e.split(".");let i=this.handler.chart.options();for(const s of t){if(!i||!(s in i))return console.warn(`Option path "${e}" is invalid.`),null;i=i[s]}return i}toggleBackgroundType(){const e=this.handler.chart.options().layout?.background;if(!e)return this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.Solid,color:"#FFFFFF"}}}),void this.buildLayoutOptionsTab();if(e.type===t.ColorType.Solid){const i=e.color||"#FFFFFF",s="rgba(0,255,0,0.33)",n={type:t.ColorType.VerticalGradient,topColor:i,bottomColor:s};this.handler.chart.applyOptions({layout:{background:n}})}else if(e.type===t.ColorType.VerticalGradient){const i=e.topColor||"#FFFFFF",s={type:t.ColorType.Solid,color:i};this.handler.chart.applyOptions({layout:{background:s}})}else console.warn("Unknown background type. Falling back to solid #FFFFFF."),this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.Solid,color:"#FFFFFF"}}});this.buildLayoutOptionsTab()}addTextInput(e,t,i){const s=document.createElement("div");Object.assign(s.style,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px",fontFamily:"sans-serif",fontSize:"16px"});const n=document.createElement("span");n.innerText=e,s.appendChild(n);const o=document.createElement("input");o.type="text",o.value=t,Object.assign(o.style,{width:"150px",padding:"4px",backgroundColor:"#444",color:"#fff",border:"1px solid #555",borderRadius:"4px"}),o.oninput=()=>i(o.value),s.appendChild(o),this.contentArea.appendChild(s)}addSideBySideColors(e,t,i,s,n=this.contentArea,o){const r=document.createElement("div");Object.assign(r.style,{display:"flex",alignItems:"center",marginBottom:"8px",gap:"12px"});const a=document.createElement("input");a.type="checkbox",a.checked=!(0===p(t)&&0===p(i)),r.appendChild(a);const c=document.createElement("span");c.innerText=e,Object.assign(c.style,{minWidth:"60px"}),r.appendChild(c);const h=document.createElement("div");Object.assign(h.style,{display:"flex",gap:"8px"}),r.appendChild(h);let d=t,u=i;e in this._originalOpacities||(this._originalOpacities[e]={up:p(t)??1,down:p(i)??1});const m=document.createElement("div");Object.assign(m.style,{width:"32px",height:"32px",borderRadius:"4px",cursor:"pointer",border:"1px solid #999",backgroundColor:d});const g=document.createElement("div");Object.assign(g.style,{width:"32px",height:"32px",borderRadius:"4px",cursor:"pointer",border:"1px solid #999",backgroundColor:u}),h.appendChild(m),h.appendChild(g);const f=()=>{if(s(d,u),o){const e=this.handler.legend._lines.find((e=>e.series===o));e&&(e.colors[0]=d,e.colors[1]=u)}};a.addEventListener("change",(()=>{a.checked?(d=l(d,this._originalOpacities[e].up??p(t)),u=l(u,this._originalOpacities[e].down??p(i)),m.style.border="1px solid #999",g.style.border="1px solid #999"):(this._originalOpacities[e].up=p(d),this._originalOpacities[e].down=p(u),d=l(d,0),u=l(u,0),m.style.border="0px",g.style.border="0px"),m.style.backgroundColor=d,g.style.backgroundColor=u,a.checked=!(0===p(d)&&0===p(u)),f()})),m.addEventListener("click",(e=>{a.checked||(a.checked=!0,a.dispatchEvent(new Event("change"))),this.colorPicker.openMenu(e,m.offsetWidth+g.offsetWidth,(e=>{d=e,m.style.backgroundColor=e,f()}))})),g.addEventListener("click",(e=>{a.checked||(a.checked=!0,a.dispatchEvent(new Event("change"))),this.colorPicker.openMenu(e,g.offsetWidth,(e=>{u=e,g.style.backgroundColor=e,f()}))})),n.appendChild(r)}buildPrimitiveColorOptions(e,t,i){const s={Body:["upColor","downColor"],Borders:["borderUpColor","borderDownColor"],Wick:["wickUpColor","wickDownColor"]},n=new Set;for(const o in s){const[r,a]=s[o];r in e&&a in e&&(n.add(r),n.add(a),this.addSideBySideColors(o,e[r],e[a],((t,s)=>{e[r]=t,e[a]=s,i(e)}),t))}Object.keys(e).forEach((s=>{s.toLowerCase().includes("color")&&!n.has(s)&&this.addColorPicker(s,e[s],(t=>{e[s]=t,i(e)}),t)}))}}let Eo=null;class Mo{handler;handlerMap;getMouseEventParams;div;hoverItem;items=[];colorPicker;saveDrawings=null;drawingTool=null;recentSeries=null;recentDrawing=null;SettingsModal=null;volumeProfile=null;dataMenu;constructor(e,t,i){this.handler=e,this.handlerMap=t,this.getMouseEventParams=i,this.div=document.createElement("div"),this.div.classList.add("context-menu"),document.body.appendChild(this.div),this.div.style.overflowY="scroll",this.hoverItem=null,document.body.addEventListener("contextmenu",this._onRightClick.bind(this)),document.body.addEventListener("click",this._onClick.bind(this));const s=Array.isArray(this.handler.defaultsManager.get("colors"))?[...this.handler.defaultsManager.get("colors")]:[];this.colorPicker=new Sn("#ff0000",(()=>null),s&&0!==s.length?s:void 0),this.dataMenu=new So({contextMenu:this,handler:this.handler}),this.SettingsModal=new ko(this.handler),this.setupMenu()}constraints={baseline:{skip:!0},title:{skip:!0},PriceLineSource:{skip:!0},tickInterval:{min:0,max:100},lastPriceAnimation:{skip:!0},lineType:{min:0,max:2},lineStyle:{min:0,max:4},seriesType:{skip:!0},chandelierSize:{min:1},volumeMALength:{skip:!0},volumeMultiplier:{skip:!0},volumeOpacityPeriod:{skip:!0}};setupDrawingTools(e,t){this.saveDrawings=e,this.drawingTool=t}shouldSkipOption(e){return!!(this.constraints[e]||{}).skip}separator(){const e=document.createElement("div");e.style.width="90%",e.style.height="1px",e.style.margin="3px 0px",e.style.backgroundColor=window.pane.borderColor,this.div.appendChild(e),this.items.push(e)}menuItem(e,t,i=null){const s=document.createElement("span");s.classList.add("context-menu-item"),this.div.appendChild(s);const n=document.createElement("span");if(n.innerText=e,n.style.pointerEvents="none",s.appendChild(n),i){let e=document.createElement("span");e.innerText="►",e.style.fontSize="8px",e.style.pointerEvents="none",s.appendChild(e)}if(s.addEventListener("mouseover",(()=>{this.hoverItem&&this.hoverItem.closeAction&&this.hoverItem.closeAction(),this.hoverItem={elem:n,action:t,closeAction:i}})),i){let e;s.addEventListener("mouseover",(()=>e=setTimeout((()=>t(s.getBoundingClientRect())),100))),s.addEventListener("mouseout",(()=>clearTimeout(e)))}else s.addEventListener("click",(e=>{t(e),this.div.style.display="none"}));this.items.push(s)}_onClick(e){const t=e.target;this.colorPicker&&!this.colorPicker.getElement().contains(t)&&this.colorPicker.closeMenu()}_onRightClick(e){e.preventDefault();const t=this.getMouseEventParams(),i=this.getProximitySeries(this.getMouseEventParams()),s=this.getProximityDrawing(),n=this.getProximityTrendTrace();console.log("Mouse Event Params:",t),console.log("Proximity Series:",i),console.log("Proximity Drawing:",s),this.clearMenu(),this.clearAllMenus(),i?(console.log("Right-click detected on a series (proximity)."),this.populateSeriesMenu(i,e),this.recentSeries=i):s?(console.log("Right-click detected on a drawing."),this.populateDrawingMenu(e,s),this.recentDrawing=s):n?(console.log("Right-click detected on a drawing."),this.populateTrendTraceMenu(e,n)):t?.hoveredSeries?(console.log("Right-click detected on a series (hovered)."),this.populateSeriesMenu(t.hoveredSeries,e),this.recentSeries=i):(console.log("Right-click detected on the chart background."),this.populateChartMenu(e)),this.showMenu(e),e.preventDefault(),e.stopPropagation()}getProximityDrawing(){return O.hoveredObject?O.hoveredObject:null}getProximityTrendTrace(){return nn.hoveredObject?nn.hoveredObject:null}getProximitySeries(e){if(!e||!e.seriesData)return console.warn("No mouse event parameters or series data available."),null;if(!e.point)return console.warn("No point data in MouseEventParams."),null;const t=e.point.y;let i=null;const s=this.handler.chart.panes()[e.paneIndex??0].getSeries()[0];if(this.handler.series&&this.handler.series.getPane().paneIndex()===e.paneIndex)i=this.handler.series,console.log("Using handler.series for coordinate conversion.");else{if(!s)return console.warn("No handler.series or referenceSeries available."),null;i=s,console.log("Using referenceSeries for coordinate conversion.")}e.paneIndex!==i.getPane().paneIndex()&&(i=this.handler.chart.panes()[e.paneIndex??1].getSeries()[0]);const n=i.coordinateToPrice(t);if(console.log(`Converted chart Y (${t}) to Price: ${n}`),null===n)return console.warn("Cursor price is null. Unable to determine proximity."),null;const o=[];return e.seriesData.forEach(((t,s)=>{let r;if(f(t)?r=t.value:y(t)&&(r=t.close),void 0!==r&&!isNaN(r)){const t=Math.abs(r-n),a=this.handler.chart.panes()[e.paneIndex].getHeight(),l=i.coordinateToPrice(0),c=i.coordinateToPrice(a);if(null===l||null===c)return null;t/(l-c)*100<=3&&e.paneIndex===s.getPane().paneIndex()&&o.push({distance:t,series:s})}})),o.sort(((e,t)=>e.distance-t.distance)),o.length>1&&this.recentSeries===o[0].series?(console.log("Multiple series found."),o[1].series):o.length>0?(console.log("Closest series found."),o[0].series):(console.log("No series found within the proximity threshold."),null)}showMenu(e){const t=e.clientX,i=e.clientY;this.div.style.position="absolute",this.div.style.zIndex="10000",this.div.style.left=`${t}px`,this.div.style.top=`${i}px`,this.div.style.width="250px",this.div.style.maxHeight="400px",this.div.style.overflowY="auto",this.div.style.display="block",this.div.style.overflowX="hidden",console.log("Displaying Menu at:",t,i),Eo=this.div,console.log("Displaying Menu",t,i),document.addEventListener("mousedown",this.hideMenuOnOutsideClick.bind(this),{once:!0}),window.menu=!0}hideMenuOnOutsideClick(e){this.div.contains(e.target)||this.hideMenu()}hideMenu(){this.div.style.display="none",Eo===this.div&&(Eo=null,window.menu=!1)}clearAllMenus(){this.handlerMap.forEach((e=>{e.ContextMenu&&e.ContextMenu.clearMenu()}))}setupMenu(){if(!this.div.querySelector(".chart-options-container")){const e=document.createElement("div");e.classList.add("chart-options-container"),this.div.appendChild(e)}this.div.querySelector(".context-menu-item.close-menu")||this.addMenuItem("Close Menu",(()=>this.hideMenu()))}addNumberInput(e,t,i,s,n,o){return this.addMenuInput(this.div,{type:"number",label:e,value:t,onChange:i,min:s,max:n,step:o})}addCheckbox(e,t,i){return this.addMenuInput(this.div,{type:"boolean",label:e,value:t,onChange:i})}addSelectInput(e,t,i,s){return this.addMenuInput(this.div,{type:"select",label:e,value:t,onChange:s,options:i})}addMenuInput(e,t,i=""){const s=document.createElement("div");if(s.classList.add("context-menu-item"),s.style.display="flex",s.style.alignItems="right",s.style.justifyContent="space-around",t.label){const o=document.createElement("label");o.innerText=t.label,o.htmlFor=`${i}${t.label.toLowerCase()}`,o.style.flex="0.8",o.style.whiteSpace="nowrap",s.appendChild(o)}let n;switch(t.type){case"hybrid":{if(!t.hybridConfig)throw new Error("Hybrid type requires hybridConfig.");const r=document.createElement("div");r.classList.add("context-menu-item"),r.style.position="relative",r.style.display="flex",r.style.flexDirection="row",r.style.justifyContent="flex-end",r.style.alignItems="right";const a={backgroundColor:"#2b2b2b",color:"#fff",border:"1px solid #444",padding:"2px 2px",textAlign:"center",cursor:"pointer",boxSizing:"border-box",display:"flex",alignItems:"right",justifyContent:"right"};function l(e,t){for(const[i,s]of Object.entries(t))e.style[i]=s}const c=document.createElement("div");l(c,a),c.style.borderRadius="4px 0 0 4px",c.innerText=t.sublabel??"▵",c.addEventListener("click",(e=>{e.stopPropagation(),t.hybridConfig.defaultAction()}));const h=document.createElement("div");l(h,a),h.style.borderLeft="none",h.style.borderRadius="0 4px 4px 0",h.innerText="☷";const p=document.createElement("div");if(p.style.position="absolute",p.style.top="100%",p.style.right="0",p.style.backgroundColor="#2b2b2b",p.style.color="#fff",p.style.border="1px solid #444",p.style.borderRadius="4px",p.style.minWidth="100px",p.style.boxShadow="0px 2px 5px rgba(0, 0, 0, 0.5)",p.style.zIndex="10000",p.style.display="none",1===t.hybridConfig.options.length){const d=t.hybridConfig.options[0];h.addEventListener("click",(e=>{e.stopPropagation(),d.action()}))}else t.hybridConfig.options.forEach((e=>{const t=document.createElement("div");t.innerText=e.name,t.style.cursor="pointer",t.style.padding="5px 10px",t.addEventListener("click",(t=>{t.stopPropagation(),p.style.display="none",e.action()})),t.addEventListener("mouseenter",(()=>{t.style.backgroundColor="#444"})),t.addEventListener("mouseleave",(()=>{t.style.backgroundColor="#2b2b2b"})),p.appendChild(t)})),h.addEventListener("click",(e=>{e.stopPropagation(),p.style.display="none"===p.style.display?"block":"none"})),r.appendChild(p);r.appendChild(c),r.appendChild(h),n=r;break}case"number":{const u=document.createElement("input");u.type="number",u.value=void 0!==t.value?t.value.toString():"",u.style.backgroundColor="#2b2b2b",u.style.color="#fff",u.style.border="1px solid #444",u.style.borderRadius="4px",u.style.textAlign="center",u.style.marginLeft="auto",u.style.marginRight="8px",u.style.width="40px",void 0!==t.min&&(u.min=t.min.toString()),void 0!==t.max&&(u.max=t.max.toString()),void 0===t.step||isNaN(t.step)?u.step="1":u.step=t.step.toString(),u.addEventListener("input",(e=>{const i=e.target;let s=parseFloat(i.value);isNaN(s)||t.onChange(s)})),n=u;break}case"boolean":{const m=document.createElement("input");m.type="checkbox",m.checked=t.value??!1,m.style.marginLeft="auto",m.style.marginRight="8px",m.addEventListener("change",(e=>{const i=e.target;t.onChange(i.checked)})),n=m;break}case"select":{const g=document.createElement("select");g.id=`${i}${t.label?t.label.toLowerCase():"select"}`,g.style.backgroundColor="#2b2b2b",g.style.color="#fff",g.style.border="1px solid #444",g.style.borderRadius="4px",g.style.marginLeft="auto",g.style.marginRight="8px",g.style.width="80px",t.options?.forEach((e=>{const i=document.createElement("option");i.value=e,i.text=e,i.style.whiteSpace="normal",i.style.textAlign="right",e===t.value&&(i.selected=!0),g.appendChild(i)})),g.addEventListener("change",(e=>{const i=e.target;t.onChange(i.value)})),n=g;break}case"string":{const f=document.createElement("input");f.type="text",f.value=t.value??"",f.style.backgroundColor="#2b2b2b",f.style.color="#fff",f.style.border="1px solid #444",f.style.borderRadius="4px",f.style.marginLeft="auto",f.style.textAlign="center",f.style.marginRight="8px",f.style.width="60px",f.addEventListener("input",(e=>{const i=e.target;t.onChange(i.value)})),n=f;break}case"color":{const y=document.createElement("input");y.type="color",y.value=t.value??"#000000",y.style.marginLeft="auto",y.style.cursor="pointer",y.style.marginRight="8px",y.style.width="100px",y.addEventListener("input",(e=>{const i=e.target;t.onChange(i.value)})),n=y;break}default:throw new Error("Unsupported input type")}return s.style.padding="2px 10px 2px 10px",s.appendChild(n),e.appendChild(s),s}addMenuItem(e,t,i=!0,s=!1,n=1){const o=document.createElement("span");if(o.classList.add("context-menu-item"),o.innerText=e,s){const e=document.createElement("span");e.classList.add("submenu-arrow"),e.innerText="ː".repeat(n),o.appendChild(e)}o.addEventListener("click",(e=>{e.stopPropagation(),t(),i&&this.hideMenu()}));const r=["➩","➯","➱","➬","➫"];return o.addEventListener("mouseenter",(()=>{if(o.style.backgroundColor="royalblue",o.style.color="white",!o.querySelector(".hover-arrow")){const e=document.createElement("span");e.classList.add("hover-arrow");const t=Math.floor(Math.random()*r.length),i=r[t];e.innerText=i,e.style.marginLeft="auto",e.style.fontSize="8px",e.style.color="white",o.appendChild(e)}})),o.addEventListener("mouseleave",(()=>{o.style.backgroundColor="",o.style.color="";const e=o.querySelector(".hover-arrow");e&&o.removeChild(e)})),this.div.appendChild(o),this.items.push(o),o}clearMenu(){this.div.querySelectorAll(".context-menu-item:not(.close-menu), .context-submenu").forEach((e=>e.remove())),this.items=[],this.div.innerHTML=""}addColorPickerMenuItem(e,t,i,s){const n=document.createElement("span");n.classList.add("context-menu-item"),n.innerText=e,this.div.appendChild(n);const o=e=>{const t=zs(i,e);s.applyOptions(t),console.log(`Updated ${i} to ${e}`);if("object"==typeof(n=s)&&null!==n&&"function"==typeof n.applyOptions&&"function"==typeof n.dataByIndex&&["color","lineColor","upColor","downColor"].includes(i)){const t=this.handler.legend._lines.find((e=>e.series===s));t&&("downColor"===i?(t.colors[1]=e,console.log(`Legend down color updated to: ${e}`)):(t.colors[0]=e,console.log(`Legend up/main color updated to: ${e}`)))}var n};return n.addEventListener("click",(e=>{e.stopPropagation(),this.colorPicker||(this.colorPicker=new Sn(t??"#000000",o)),this.colorPicker.openMenu(e,225,o)})),n}currentWidthOptions=[];currentStyleOptions=[];populateSeriesMenu(e,i){const s=Bs(e,this.handler.legend),o=e.options();if(!o)return void console.warn("No options found for the selected series.");this.div.innerHTML="";const r=[],a=[],l=[],c=[],h=[];for(const e of Object.keys(o)){const i=o[e];if(this.shouldSkipOption(e))continue;if(e.toLowerCase().includes("base"))continue;const s=Hs(e).toLowerCase(),d=s.includes("width")||"radius"===s||s.includes("radius");if(s.includes("color"))"string"==typeof i?r.push({label:e,value:i}):console.warn(`Expected string value for color option "${e}".`);else if(d){if("number"==typeof i){let t=1,n=10,o=1;s.includes("radius")&&(t=0,n=1,o=.1),c.push({name:e,label:e,value:i,min:t,max:n,step:o})}}else if(s.includes("visible")||s.includes("visibility"))"boolean"==typeof i?a.push({label:e,value:i}):console.warn(`Expected boolean value for visibility option "${e}".`);else if("lineType"===e){const t=this.getPredefinedOptions(Hs(e));h.push({name:e,label:e,value:i,options:t})}else if("crosshairMarkerRadius"===e)"number"==typeof i?c.push({name:e,label:e,value:i,min:1,max:50}):console.warn(`Expected number value for crosshairMarkerRadius option "${e}".`);else if(s.includes("style")){if("string"==typeof i||Object.values(t.LineStyle).includes(i)||"number"==typeof i){const t=["Solid","Dotted","Dashed","Large Dashed","Sparse Dotted"];h.push({name:e,label:e,value:i,options:t})}}else if(s.includes("shape")){if(p=i,Object.values(n).includes(p)){const t=["Rectangle","Rounded","Ellipse","Arrow","3d","Polygon","Bar","Slanted"];t&&h.push({name:e,label:e,value:i,options:t})}}else l.push({label:e,value:i})}var p;this.currentWidthOptions=c,this.currentStyleOptions=h,this.addTextInput("Title",e.options().title||"",(t=>{const i={title:t};this.handler.seriesMap.has(e.options().title)&&this.handler.seriesMap.delete(e.options().title),this.handler.seriesMap.set(t,e),console.log(`Updated seriesMap label to: ${t}`);const s=this.handler.legend._lines.find((t=>t.series===e));s&&s.series===e&&(s.name=t,console.log(`Updated legend title to: ${t}`)),e.applyOptions(i),console.log(`Updated title to: ${t}`)}));const d=e.getPane().paneIndex(),u=this.handler.chart.panes(),m=`Pane ${d}`,g=[];for(let t=0;t{e.moveToPane(t),console.log(`Moved series to existing pane ${t}.`)}});if(g.push({name:"New Pane",action:()=>{e.moveToPane(u.length),console.log(`Moved series to a new pane at index ${u.length}.`)}}),this.addMenuInput(this.div,{type:"hybrid",label:"Move to pane",sublabel:0===d?"New Pane":"Top",value:m,onChange:e=>{const t=g.find((t=>t.name===e));t&&t.action()},hybridConfig:{defaultAction:()=>{0===d?(e.moveToPane(u.length),console.log(`Default: Moved series from pane ${d} to a new pane at index ${u.length}.`)):(e.moveToPane(0),console.log(`Default: Moved series from pane ${d} back to main pane (0).`))},options:g.map((e=>({name:e.name,action:e.action})))}}),this.addMenuItem("Clone Series ▸",(()=>{this.populateCloneSeriesMenu(e,i)}),!1,!0),a.length>0&&this.addMenuItem("Visibility Options ▸",(()=>{this.populateVisibilityMenu(i,e)}),!1,!0),this.currentStyleOptions.length>0&&this.addMenuItem("Style Options ▸",(()=>{this.populateStyleMenu(i,e)}),!1,!0),this.currentWidthOptions.length>0&&this.addMenuItem("Width Options ▸",(()=>{this.populateWidthMenu(i,e)}),!1,!0),r.length>0&&this.addMenuItem("Color Options ▸",(()=>{this.populateColorOptionsMenu(r,e,i)}),!1,!0),o.enableVolumeOpacity&&this.addNumberInput("Volume Opacity Period",o.volumeOpacityPeriod??21,(t=>{const i={volumeOpacityPeriod:t};e.applyOptions(i),console.log(`Updated Volume Opacity Period to ${t}`)}),1,1e4,1),o.enableVolumeOpacity){const t=["/ max","> previous","> average"],i=t.includes(o.volumeOpacityMode)?o.volumeOpacityMode:"/ max";this.addSelectInput("Volume Opacity Mode",i??"> previous",t,(t=>{const i={volumeOpacityMode:t};e.applyOptions(i),console.log(`Updated Volume Opacity Mode to: ${t}`)}))}if(void 0!==o.dynamicCandles){const t=["false","trend","trigger","volume_trend"],s=o.dynamicCandles;this.addSelectInput("Dynamic Candles",s,t,(t=>{const s={dynamicCandles:t};e.applyOptions(s),console.log(`Updated dynamicCandles to: ${t}`),this.populateSeriesMenu(e,i)}))}if(l.forEach((t=>{const i=Hs(t.label);if(!this.constraints[t.label]?.skip)if("boolean"==typeof t.value)this.addCheckbox(Hs(t.label),Boolean(t.value),(i=>{const s=zs(t.label,i);e.applyOptions(s),console.log(`Updated ${t.label} to ${i}`)}));else if("string"==typeof t.value){const s=this.getPredefinedOptions(t.label);s&&s.length>0?this.addMenuItem(`${i} ▸`,(()=>{this.div.innerHTML="",this.addSelectInput(i,t.value,s,(i=>{const s=zs(t.label,i);e.applyOptions(s),console.log(`Updated ${t.label} to ${i}`)}))}),!1,!0):this.addMenuItem(`${i} ▸`,(()=>{this.div.innerHTML="",this.addTextInput(i,t.value,(i=>{const s=zs(t.label,i);e.applyOptions(s),console.log(`Updated ${t.label} to ${i}`)}))}),!1,!0)}else{if("number"!=typeof t.value)return;{const s=this.constraints[t.label]?.min,n=this.constraints[t.label]?.max;this.addNumberInput(i,t.value,(i=>{const s=zs(t.label,i);e.applyOptions(s),console.log(`Updated ${t.label} to ${i}`)}),s,n)}}})),this.addMenuItem("Price Scale Options ▸",(()=>{this.populatePriceScaleMenu(i,e.options().priceScaleId??"right",e)}),!1,!0),this.addMenuItem("Primitives ▸",(()=>{this.populatePrimitivesMenu(s,i)}),!1,!0),this.addMenuItem("Indicators ▸",(()=>{this.populateIndicatorMenu(e,i)}),!1,!0),function(e){return void 0!==e.figures&&void 0!==e.sourceSeries&&void 0!==e.indicator}(e)){const t=e;this.addMenuItem(`Configure ${t.indicator.name}`,(()=>{this.configureIndicatorParams(t,i,t.figureCount)}),!1)}this.addMenuItem("Export/Import Series Data ▸",(()=>{this.dataMenu||(this.dataMenu=new So({contextMenu:this,handler:this.handler})),this.dataMenu.openMenu(e,i,"Series")}),!1),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(i)}),!1,!1),this.showMenu(i)}populateDrawingMenu(e,t){this.div.innerHTML="",this.drawingTool||(this.drawingTool=new F(this.handler.chart,this.handler._seriesList[0]));for(const e of Object.keys(t._options)){let t;if(e.toLowerCase().includes("color"))t=new Cn(this.saveDrawings,e);else{if("lineStyle"!==e)continue;t=new kn(this.saveDrawings)}const i=e=>t.openMenu(e);this.menuItem(Hs(e),i,(()=>{document.removeEventListener("click",t.closeMenu),t._div.style.display="none"}))}if("PitchFork"===t._type){const i=t._options.variant||"standard",s=["standard","schiff","modifiedSchiff","inside"];this.addSelectInput("Pitchfork Variant",i,s,(e=>{t._options.variant=e,this.saveDrawings&&this.saveDrawings()})),this.addNumberInput("Length",t._options.length,(e=>{t._options.length=e,this.saveDrawings&&this.saveDrawings()}),0,1e3,.1),this.addMenuItem("Fork Line Options ▸",(()=>{this.populateForkLineMainMenu(e,t)}),!1,!0),this.addMenuItem("Export/Import PitchFork Data ▸",(()=>{this.dataMenu||(this.dataMenu=new So({contextMenu:this,handler:this.handler})),this.dataMenu.openMenu(t,e,"PitchFork")}),!1)}if(t.points?.length>=2&&t.points[0]&&t.points[1]){let i;i=(t.points,t),i.linkedObjects?.length&&i.linkedObjects.forEach((t=>{t instanceof nn?this.addMenuItem(`${t.title} Options`,(()=>{this.populateTrendTraceMenu(e,t)}),!1,!0):t instanceof Mn&&this.addMenuItem("Volume Profile Options",(()=>{this.populateVolumeProfileMenu(e,t)}),!1,!0)})),this.addMenuItem("Trend Trace ▸",(()=>{this._createTrendTrace(e,i)}),!1,!0),this.addMenuItem("Volume Profile ▸",(()=>{this._createVolumeProfile(i)}),!1,!0)}this.separator(),this.menuItem("Delete Drawing",(()=>this.drawingTool.delete(t))),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1,!1),this.showMenu(e)}populateChartMenu(e){this.div.innerHTML="",console.log("Displaying Menu Options: Chart"),this.addResetViewOption();const t=this.getMouseEventParams(),i=this.handler.chart.panes(),s=t?.paneIndex,n=this.handler.chart.panes()[s??0],o=()=>{s?n.moveTo(0):n.moveTo(i.length-1)},r=[];r.push({name:"Top",action:()=>{n.moveTo(0),console.log("Moved pane to top")}}),i.length>2&&(s??0)>1&&r.push({name:"Up",action:()=>{n.moveTo((s??2)-1),console.log("Moved pane up")}}),i.length>2&&(s??0){n.moveTo((s??0)+1),console.log("Moved pane down")}}),r.push({name:"Bottom",action:()=>{n.moveTo(i.length-1),console.log("Moved pane to bottom")}}),i.length>1&&this.addMenuInput(this.div,{type:"hybrid",label:"Move pane",sublabel:s?"Top":"Bottom",hybridConfig:{defaultAction:o,options:r.map((e=>({name:e.name,action:e.action})))}}),this.addMenuInput(this.div,{type:"hybrid",label:"Display Volume Profile",sublabel:"≖",hybridConfig:{defaultAction:()=>{this.volumeProfile?(this.handler.series.detachPrimitive(this.volumeProfile),this.volumeProfile=null,console.log("[ChartMenu] Detached Volume Profile.")):(this.volumeProfile=new Mn(this.handler,En),this.handler.series.attachPrimitive(this.volumeProfile,"Visible Range Volume Profile",!1,!0),console.log("[ChartMenu] Attached Volume Profile."))},options:[{name:"Options",action:()=>{this.volumeProfile&&this.populateVolumeProfileMenu(e,this.volumeProfile)}}]}}),this.addMenuItem(" ~ Series List",(()=>{this.populateSeriesListMenu(e,!1,(t=>{this.populateSeriesMenu(t,e)}))}),!1,!0),this.addMenuItem("Settings...",(()=>{this.SettingsModal.open()}),!0),this.showMenu(e)}populateLayoutMenu(e){this.div.innerHTML="";const t="Text Color",i="layout.textColor",s=this.getCurrentOptionValue(i)||"#000000";this.addColorPickerMenuItem(Hs(t),s,i,this.handler.chart);const n=this.handler.chart.options().layout?.background;m(n)?this.addColorPickerMenuItem("Background Color",n.color||"#FFFFFF","layout.background.color",this.handler.chart):g(n)?(this.addColorPickerMenuItem("Top Color",n.topColor||"rgba(255,0,0,0.33)","layout.background.topColor",this.handler.chart),this.addColorPickerMenuItem("Bottom Color",n.bottomColor||"rgba(0,255,0,0.33)","layout.background.bottomColor",this.handler.chart)):console.warn("Unknown background type; no color options displayed."),this.addMenuItem("Switch Background Type",(()=>{this.toggleBackgroundType(e)}),!1,!0),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1,!1),this.showMenu(e)}toggleBackgroundType(e){const i=this.handler.chart.options().layout?.background;let s;s=m(i)?{type:t.ColorType.VerticalGradient,topColor:"rgba(255,0,0,0.2)",bottomColor:"rgba(0,255,0,0.2)"}:{type:t.ColorType.Solid,color:"#000000"},this.handler.chart.applyOptions({layout:{background:s}}),this.populateLayoutMenu(e)}populateWidthMenu(e,t){this.div.innerHTML="",this.currentWidthOptions.forEach((e=>{"number"==typeof e.value&&this.addNumberInput(Hs(e.label),e.value,(i=>{const s=zs(e.name,i);t.applyOptions(s),console.log(`Updated ${e.label} to ${i}`)}),e.min,e.max)})),this.addMenuItem("⤝ Back to Series Options",(()=>{this.populateSeriesMenu(t,e)}),!1,!1),this.showMenu(e)}populatePrimitivesMenu(e,t){this.div.innerHTML="",console.log("Showing Primitive Menu ");const i=e.primitives;this.addMenuItem("Fill Area Between",(()=>{this.startFillAreaBetween(t,e)}),!1,!1),console.log("Primitives:",i);const s=i?.FillArea??i?.pt;i.FillArea&&this.addMenuItem("Customize Fill Area",(()=>{this.customizeFillAreaOptions(t,s)}),!1,!0),this.addMenuItem("Create TrendTrace",(()=>{this._createTrendTrace(t,this.recentDrawing)}),!1,!1),console.log("Primitives:",i),i.TrendTrace&&this.addMenuItem("Customize TrendTrace",(()=>{this.populateTrendTraceMenu(t,i.TrendTrace)}),!1,!0),this.addMenuItem("⤝ Back",(()=>{this.populateSeriesMenu(e,t)}),!1,!1),this.showMenu(t)}populateStyleMenu(e,t){this.div.innerHTML="",this.currentStyleOptions.forEach((e=>{const i=this.getPredefinedOptions(e.name);i?this.addSelectInput(Hs(e.name),e.value.toString(),i,(i=>{let s=i;if(e.name.toLowerCase().includes("style")){s={Solid:0,Dotted:1,Dashed:2,"Large Dashed":3,"Sparse Dotted":4}[i]??0}else if(e.name.toLowerCase().includes("linetype")){s={Simple:0,WithSteps:1,Curved:2}[i]??0}const n=zs(e.name,s);if(t.applyOptions(n),console.log(`Updated ${e.name} to "${i}" =>`,s),e.name.toLowerCase().includes("style")&&"Line"===t.seriesType()){const e=s,i=(()=>{switch(e){case 0:return"―";case 1:return"··";case 2:return"--";case 3:return"- -";case 4:return"· ·";default:return"~"}})(),n=this.handler.legend._lines.find((e=>e.series===t));n&&(n.legendSymbol=[i],console.log(`Updated legend symbol for lineStyle(${e}) to: ${i}`))}})):console.warn(`No predefined options found for "${e.name}".`)})),this.addMenuItem("⤝ Back",(()=>{this.populateSeriesMenu(t,e)}),!1,!1),this.showMenu(e)}populateCloneSeriesMenu(e,t){this.div.innerHTML="";const i=e.data(),s=["Line","Histogram","Area"];if(i&&i.length>0){i.some((e=>y(e)))&&s.push("Bar","Candlestick","Ohlc")}s.forEach((t=>{this.addMenuItem(`Clone as ${t}`,(()=>{const i=function(e,t,i,s){try{const n=e.options(),o=Ns(i),r={...o,...s},a=e.options().title??i;let l;switch(console.log(`Cloning ${e.seriesType()} as ${i}...`),i){case"Line":l=t.createLineSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;case"Histogram":l=t.createHistogramSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;case"Area":l=t.createAreaSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;case"Bar":l=t.createBarSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;case"Candlestick":l={name:`${a}<${i}>`,series:t.createCandlestickSeries()};break;case"Ohlc":l=t.createCustomOHLCSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;default:return console.error(`Unsupported series type: ${i}`),null}let c=e.data().map(((t,s)=>Os(e,i,s))).filter((e=>null!==e));return l.series.setData(c),h(n,((e,t)=>{if(function(e,t){const i=e.split(".");let s=t;for(const e of i){if(!(e in s))return("color"===e||"LineColor"===e)&&("color"in s||"LineColor"in s);s=s[e]}return!0}(e,o))if("LineColor"===e||"color"===e){const e="LineColor"in o||"LineColor"in r,i="color"in o||"color"in r;e&&i?(Vs(l.series,"LineColor",t),Vs(l.series,"color",t)):e?Vs(l.series,"LineColor",t):i&&Vs(l.series,"color",t)}else Vs(l.series,e,t)})),Object.keys(r).forEach((e=>{e.toString().toLowerCase().includes("color")&&h({[e]:r[e]},((e,t)=>{console.log(`Found color option: ${e} = ${t}`)}))})),e.subscribeDataChanged((()=>{const t=e.data().map(((t,s)=>Os(e,i,s))).filter((e=>null!==e));l.series.setData(t),console.log(`Updated synced series of type ${i}`)})),l.series}catch(e){return console.error("Error cloning series:",e),null}}(e,this.handler,t,this.handler.defaultsManager.defaults.get(t.toLowerCase())||{});i?console.log(`Cloned series as ${t}:`,i):console.warn(`Failed to clone as ${t}.`)}),!1)})),this.addMenuItem("⤝ Series Options",(()=>{this.populateSeriesMenu(e,t)}),!1,!1),this.showMenu(t)}addTextInput(e,t,i){const s=document.createElement("div");s.classList.add("context-menu-item"),s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="space-between";const n=document.createElement("label");n.innerText=e,n.htmlFor=`${e.toLowerCase()}-input`,n.style.marginRight="8px",n.style.flex="1",s.appendChild(n);const o=document.createElement("input");return o.type="text",o.value=t,o.id=`${e.toLowerCase()}-input`,o.style.flex="0 0 100px",o.style.marginLeft="auto",o.style.backgroundColor="#2b2b2b",o.style.color="#fff",o.style.border="1px solid #444",o.style.borderRadius="4px",o.style.cursor="pointer",o.addEventListener("input",(e=>{const t=e.target;i(t.value)})),s.appendChild(o),this.div.appendChild(s),s}populateColorOptionsMenu(e,t,i){this.div.innerHTML="",e.forEach((e=>{this.addColorPickerMenuItem(Hs(e.label),e.value,e.label,t)})),this.addMenuItem("⤝ Back to Series Options",(()=>{this.populateSeriesMenu(t,i)}),!1,!1),this.showMenu(i)}populateVisibilityMenu(e,t){this.div.innerHTML="";const i=t.options();["visible","crosshairMarkerVisible","priceLineVisible"].forEach((e=>{const s=i[e];"boolean"==typeof s&&this.addCheckbox(Hs(e),s,(i=>{const s=zs(e,i);t.applyOptions(s),console.log(`Toggled ${e} to ${i}`)}))})),this.addMenuItem("⤝ Back to Series Options",(()=>{this.populateSeriesMenu(t,e)}),!1,!1),this.showMenu(e)}populateBackgroundTypeMenu(e){this.div.innerHTML="";[{text:"Solid",action:()=>this.setBackgroundType(e,t.ColorType.Solid)},{text:"Vertical Gradient",action:()=>this.setBackgroundType(e,t.ColorType.VerticalGradient)}].forEach((e=>{this.addMenuItem(e.text,e.action,!1,!1,1)})),this.addMenuItem("⤝ Chart Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populateGradientBackgroundMenuInline(e,t){this.div.innerHTML="",this.addColorPickerMenuItem(Hs("Top Color"),t.topColor,"layout.background.topColor",this.handler.chart),this.addColorPickerMenuItem(Hs("Bottom Color"),t.bottomColor,"layout.background.bottomColor",this.handler.chart),this.addMenuItem("⤝ Background Type & Colors",(()=>{this.populateBackgroundTypeMenu(e)}),!1),this.showMenu(e)}populateGridMenu(e){this.div.innerHTML="";[{name:"Vertical Line Color",type:"color",valuePath:"grid.vertLines.color",defaultValue:"#D6DCDE"},{name:"Horizontal Line Color",type:"color",valuePath:"grid.horzLines.color",defaultValue:"#D6DCDE"},{name:"Vertical Line Style",type:"select",valuePath:"grid.vertLines.style",options:["Solid","Dashed","Dotted","LargeDashed"],defaultValue:"Solid"},{name:"Horizontal Line Style",type:"select",valuePath:"grid.horzLines.style",options:["Solid","Dashed","Dotted","LargeDashed"],defaultValue:"Solid"},{name:"Show Vertical Lines",type:"boolean",valuePath:"grid.vertLines.visible",defaultValue:!0},{name:"Show Horizontal Lines",type:"boolean",valuePath:"grid.horzLines.visible",defaultValue:!0}].forEach((e=>{const t=this.getCurrentOptionValue(e.valuePath)??e.defaultValue;"color"===e.type?this.addColorPickerMenuItem(Hs(e.name),t,e.valuePath,this.handler.chart):"select"===e.type?this.addSelectInput(Hs(e.name),t,e.options,(t=>{const i=e.options.indexOf(t),s=zs(e.valuePath,i);this.handler.chart.applyOptions(s),console.log(`Updated ${e.name} to: ${t}`)})):"boolean"===e.type&&this.addCheckbox(Hs(e.name),t,(t=>{const i=zs(e.valuePath,t);this.handler.chart.applyOptions(i),console.log(`Updated ${e.name} to: ${t}`)}))})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populateBackgroundMenu(e){this.div.innerHTML="",this.addMenuItem("Type & Colors",(()=>{this.populateBackgroundTypeMenu(e)}),!1,!0),this.addMenuItem("Options",(()=>{this.populateBackgroundOptionsMenu(e)}),!1,!0),this.addMenuItem("⤝ Layout Options",(()=>{this.populateLayoutMenu(e)}),!1),this.showMenu(e)}populateBackgroundOptionsMenu(e){this.div.innerHTML="";[{name:"Background Color",valuePath:"layout.background.color"},{name:"Background Top Color",valuePath:"layout.background.topColor"},{name:"Background Bottom Color",valuePath:"layout.background.bottomColor"}].forEach((e=>{const t=this.getCurrentOptionValue(e.valuePath)||"#FFFFFF";this.addColorPickerMenuItem(Hs(e.name),t,e.valuePath,this.handler.chart)})),this.addMenuItem("⤝ Background",(()=>{this.populateBackgroundMenu(e)}),!1),this.showMenu(e)}populateSolidBackgroundMenuInline(e,t){this.div.innerHTML="",this.addColorPickerMenuItem(Hs("Background Color"),t.color,"layout.background.color",this.handler.chart),this.addMenuItem("⤝ Type & Colors",(()=>{this.populateBackgroundTypeMenu(e)}),!1),this.showMenu(e)}populateCrosshairOptionsMenu(e){this.div.innerHTML="";[{name:"Line Color",valuePath:"crosshair.lineColor"},{name:"Vertical Line Color",valuePath:"crosshair.vertLine.color"},{name:"Horizontal Line Color",valuePath:"crosshair.horzLine.color"}].forEach((e=>{const t=this.getCurrentOptionValue(e.valuePath)||"#000000";this.addColorPickerMenuItem(Hs(e.name),t,e.valuePath,this.handler.chart)})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populateTimeScaleMenu(e){this.div.innerHTML="";[{name:"Right Offset",type:"number",valuePath:"timeScale.rightOffset",min:0,max:100},{name:"Bar Spacing",type:"number",valuePath:"timeScale.barSpacing",min:1,max:100},{name:"Min Bar Spacing",type:"number",valuePath:"timeScale.minBarSpacing",min:.1,max:10,step:.1},{name:"Fix Left Edge",type:"boolean",valuePath:"timeScale.fixLeftEdge"},{name:"Fix Right Edge",type:"boolean",valuePath:"timeScale.fixRightEdge"},{name:"Lock Visible Range on Resize",type:"boolean",valuePath:"timeScale.lockVisibleTimeRangeOnResize"},{name:"Visible",type:"boolean",valuePath:"timeScale.visible"},{name:"Border Visible",type:"boolean",valuePath:"timeScale.borderVisible"},{name:"Border Color",type:"color",valuePath:"timeScale.borderColor"}].forEach((e=>{if("number"===e.type){const t=this.getCurrentOptionValue(e.valuePath);this.addNumberInput(Hs(e.name),t,(t=>{const i=zs(e.valuePath,t);this.handler.chart.applyOptions(i),console.log(`Updated TimeScale ${e.name} to: ${t}`)}),e.min,e.max)}else if("boolean"===e.type){const t=this.getCurrentOptionValue(e.valuePath);this.addCheckbox(Hs(e.name),t,(t=>{const i=zs(e.valuePath,t);this.handler.chart.applyOptions(i),console.log(`Updated TimeScale ${e.name} to: ${t}`)}))}else if("color"===e.type){const t=this.getCurrentOptionValue(e.valuePath)||"#000000";this.addColorPickerMenuItem(Hs(e.name),t,e.valuePath,this.handler.chart)}})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populatePriceScaleMenu(e,i="right",s){if(this.div.innerHTML="",s)this.addMenuInput(this.div,{type:"hybrid",label:"Price Scale",value:s.options().priceScaleId||"",onChange:e=>{s.applyOptions({priceScaleId:e}),console.log(`Updated price scale to: ${e}`)},hybridConfig:{defaultAction:()=>{const e="left"===s.options().priceScaleId?"right":"left";s.applyOptions({priceScaleId:e}),console.log(`Series price scale switched to: ${e}`)},options:[{name:"Left",action:()=>s.applyOptions({priceScaleId:"left"})},{name:"Right",action:()=>s.applyOptions({priceScaleId:"right"})},{name:"Volume",action:()=>s.applyOptions({priceScaleId:"volume_scale"})},{name:"Custom",action:()=>{const e=document.createElement("div"),t=document.createElement("input");t.type="text",t.placeholder="Enter custom scale ID",t.value=s.options().priceScaleId||"",t.addEventListener("change",(()=>{s.applyOptions({priceScaleId:t.value}),console.log(`Custom scale ID set to: ${t.value}`)})),e.appendChild(t),this.div.appendChild(e)}}]}});else{const n=this.handler.chart.priceScale(i).options().mode??t.PriceScaleMode.Normal,o=[{label:"Normal",value:t.PriceScaleMode.Normal},{label:"Logarithmic",value:t.PriceScaleMode.Logarithmic},{label:"Percentage",value:t.PriceScaleMode.Percentage},{label:"Indexed To 100",value:t.PriceScaleMode.IndexedTo100}],r=o.map((e=>e.label));this.addSelectInput("Price Scale Mode",o.find((e=>e.value===n))?.label||"Normal",r,(t=>{const n=o.find((e=>e.label===t));n&&(this.applyPriceScaleOptions(i,{mode:n.value}),console.log(`Price scale (${i}) mode set to: ${t}`),this.populatePriceScaleMenu(e,i,s))}));const a=this.handler.chart.priceScale(i).options();[{name:"Auto Scale",value:a.autoScale??!0,action:e=>{this.applyPriceScaleOptions(i,{autoScale:e}),console.log(`Price scale (${i}) autoScale set to: ${e}`)}},{name:"Invert Scale",value:a.invertScale??!1,action:e=>{this.applyPriceScaleOptions(i,{invertScale:e}),console.log(`Price scale (${i}) invertScale set to: ${e}`)}},{name:"Align Labels",value:a.alignLabels??!0,action:e=>{this.applyPriceScaleOptions(i,{alignLabels:e}),console.log(`Price scale (${i}) alignLabels set to: ${e}`)}},{name:"Border Visible",value:a.borderVisible??!0,action:e=>{this.applyPriceScaleOptions(i,{borderVisible:e}),console.log(`Price scale (${i}) borderVisible set to: ${e}`)}},{name:"Ticks Visible",value:a.ticksVisible??!1,action:e=>{this.applyPriceScaleOptions(i,{ticksVisible:e}),console.log(`Price scale (${i}) ticksVisible set to: ${e}`)}}].forEach((t=>{this.addMenuItem(`${t.name}: ${t.value?"On":"Off"}`,(()=>{const n=!t.value;t.action(n),this.populatePriceScaleMenu(e,i,s)}),!1,!1)}))}this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}applyPriceScaleOptions(e,t){const i=this.handler.chart.priceScale(e);i?(i.applyOptions(t),console.log(`Applied options to price scale "${e}":`,t)):console.warn(`Price scale with ID "${e}" not found.`)}getCurrentOptionValue(e){const t=e.split(".");let i=this.handler.chart.options();for(const s of t){if(!i||!(s in i))return console.warn(`Option path "${e}" is invalid.`),null;i=i[s]}return i}setBackgroundType(e,i){const s=this.handler.chart.options().layout?.background;let n;if(i===t.ColorType.Solid)n=m(s)?{type:t.ColorType.Solid,color:s.color}:{type:t.ColorType.Solid,color:"#000000"};else{if(i!==t.ColorType.VerticalGradient)return void console.error(`Unsupported ColorType: ${i}`);n=g(s)?{type:t.ColorType.VerticalGradient,topColor:s.topColor,bottomColor:s.bottomColor}:{type:t.ColorType.VerticalGradient,topColor:"rgba(255,0,0,.2)",bottomColor:"rgba(0,255,0,.2)"}}this.handler.chart.applyOptions({layout:{background:n}}),i===t.ColorType.Solid?this.populateSolidBackgroundMenuInline(e,n):i===t.ColorType.VerticalGradient&&this.populateGradientBackgroundMenuInline(e,n)}startFillAreaBetween(e,t){console.log("Fill Area Between started. Origin series set:",t.options().title),this.populateSeriesListMenu(e,!1,(e=>{e&&e!==t?(console.log("Destination series selected:",e.options().title),t.primitives.FillArea=new _(t,e,{...S}),t.attachPrimitive(t.primitives.FillArea,`Fill Area ⥵ ${e.options().title}`,!1,!0),console.log("Fill Area successfully added between selected series."),alert(`Fill Area added between ${t.options().title} and ${e.options().title}`)):alert("Invalid selection. Please choose a different series as the destination.")}))}getPredefinedOptions(e){return{"Series Type":["Line","Histogram","Area","Bar","Candlestick"],"Line Style":["Solid","Dotted","Dashed","Large Dashed","Sparse Dotted"],"Line Type":["Simple","WithSteps","Curved"],seriesType:["Line","Histogram","Area","Bar","Candlestick"],lineStyle:["Solid","Dotted","Dashed","Large Dashed","Sparse Dotted"],"Price Line Style":["Solid","Dotted","Dashed","Large Dashed","Sparse Dotted"],lineType:["Simple","WithSteps","Curved"],Shape:["Rectangle","Rounded","Ellipse","Arrow","3d","Polygon","Bar","Slanted"],"Candle Shape":["Rectangle","Rounded","Ellipse","Arrow","3d","Polygon","Bar","Slanted"]}[Hs(e)]||null}populateSeriesListMenu(e,t,i){this.div.innerHTML="";let s=[...Array.from(this.handler.seriesMap.entries()).map((([e,t])=>({label:e,value:t})))];if(this.handler.volumeSeries){s=[{label:"Volume",value:this.handler.volumeSeries},...s]}console.log(s),s.forEach((s=>{this.addMenuItem(s.label,(()=>{i(s.value),t?this.hideMenu():(this.div.innerHTML="",this.populateSeriesMenu(s.value,e),this.showMenu(e))}),!1,!0)})),this.addMenuItem("Cancel",(()=>{console.log("Operation canceled."),this.hideMenu()})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}customizeFillAreaOptions(e,t){var i;this.div.innerHTML="",null!==(i=t).options.originColor&&null!==i.options.destinationColor&&(this.addColorPickerMenuItem("Origin > Destination",t.options.originColor,"originColor",t),this.addColorPickerMenuItem("Origin < Destination",t.options.destinationColor,"destinationColor",t)),this.addMenuItem("⤝ Back to Main Menu",(()=>this.populateChartMenu(e)),!1),this.showMenu(e)}addResetViewOption(){const e=this.addMenuInput(this.div,{type:"hybrid",label:"∟ Reset",sublabel:"View",hybridConfig:{defaultAction:()=>{this.handler.chart.timeScale().resetTimeScale(),this.handler.chart.timeScale().fitContent()},options:[{name:"⥗ Time Scale",action:()=>this.handler.chart.timeScale().resetTimeScale()},{name:"⥘ Price Scale",action:()=>this.handler.chart.timeScale().fitContent}]}});this.div.appendChild(e)}_createTrendTrace(e,t){this.populateSeriesListMenu(e,!1,(e=>{let i;if("PitchFork"===t._type&&e&&t.p1&&t.p2){console.log("Series selected:",e.options().title);i=(t._options.length??1)*Math.abs(t.p2.logical-t.p1.logical)}e&&t.p1&&t.p2&&(console.log("Series selected:",e.options().title),e.primitives.TrendTrace=new nn(this.handler,e,t.p1,t.p2,tn,i),e.attachPrimitive(e.primitives.TrendTrace,`${t.p1?.logical} ⥵ ${t.p2?.logical}`,!1,!0),console.log("Trend Trace successfully created for selected series."),t.linkedObjects.push(e.primitives.TrendTrace))}))}_createVolumeProfile(e){const t=this.handler.series??this.handler._seriesList[0];if(t&&e.p1&&e.p2){console.log("Series selected:",t.options().title);const i=new Mn(this.handler,En,e.p1,e.p2);t.attachPrimitive(i,"Volume Profile",!1,!0),console.log("Volume Profile successfully created for selected series."),e.linkedObjects.push(i)}}populateTrendTraceMenu(e,t){this.div.innerHTML="",this.addMenuItem("Color Options ▸",(()=>this.populateTrendColorMenu(e,t)),!1,!0),this.addMenuItem("General Options ▸",(()=>this.populateTrendOptionsMenu(e,t)),!1,!0),this.addMenuItem("Export/Import Data ▸",(()=>{this.dataMenu||(this.dataMenu=new So({contextMenu:this,handler:this.handler})),this.dataMenu.openMenu(t,e,"Trend Trace")}),!1),this.addMenuItem("⤝ Main Menu",(()=>this.populateChartMenu(e)),!1),this.showMenu(e)}populateTrendColorMenu(e,t){this.div.innerHTML="";const i=t.getOptions(),s=[];t._sequence.data.every((e=>void 0!==e.open&&void 0!==e.high&&void 0!==e.low&&void 0!==e.close))?s.push({name:"Up Color",type:"color",valuePath:"upColor",defaultValue:i.upColor??"rgba(0,255,0,.25)"},{name:"Down Color",type:"color",valuePath:"downColor",defaultValue:i.downColor??"rgba(255,0,0,.25)"},{name:"Border Up Color",type:"color",valuePath:"borderUpColor",defaultValue:i.borderUpColor??"#1c9d1c"},{name:"Border Down Color",type:"color",valuePath:"borderDownColor",defaultValue:i.borderDownColor??"#d5160c"},{name:"Wick Up Color",type:"color",valuePath:"wickUpColor",defaultValue:i.wickUpColor??"#1c9d1c"},{name:"Wick Down Color",type:"color",valuePath:"wickDownColor",defaultValue:i.wickDownColor??"#d5160c"}):s.push({name:"Line Color",type:"color",valuePath:"lineColor",defaultValue:i.lineColor??"#ffffff"}),s.forEach((e=>{this.addColorPickerMenuItem(Hs(e.name),e.defaultValue,e.valuePath,t)})),this.addMenuItem("⤝ Trend Trace Menu",(()=>this.populateTrendTraceMenu(e,t)),!1),this.showMenu(e)}populateTrendOptionsMenu(e,t){this.div.innerHTML="";const i=t.getOptions(),s=[];t._sequence.data.every((e=>void 0!==e.open&&void 0!==e.high&&void 0!==e.low&&void 0!==e.close))&&s.push({name:"Bar Spacing",type:"number",valuePath:"barSpacing",defaultValue:i.barSpacing??.8,min:.1,max:10,step:.1},{name:"Radius",type:"number",valuePath:"radius",defaultValue:i.radius??.6,min:0,max:1,step:.1},{name:"Shape",type:"select",valuePath:"shape",defaultValue:i.shape??"Rounded",options:[{label:"Rectangle",value:n.Rectangle},{label:"Rounded",value:n.Rounded},{label:"Ellipse",value:n.Ellipse},{label:"Arrow",value:n.Arrow},{label:"Polygon",value:n.Polygon},{label:"Bar",value:n.Bar},{label:"Slanted",value:n.Slanted}]},{name:"Show Wicks",type:"boolean",valuePath:"wickVisible",defaultValue:i.wickVisible??!0},{name:"Show Borders",type:"boolean",valuePath:"borderVisible",defaultValue:i.borderVisible??!0},{name:"Chandelier Size",type:"number",valuePath:"chandelierSize",defaultValue:i.chandelierSize??1,min:1,max:100,step:1},{name:"Auto Aggregate",type:"boolean",valuePath:"autoscale",defaultValue:i.autoScale??!0}),s.push({name:"Line Style",type:"select",valuePath:"lineStyle",defaultValue:i.lineStyle??0,options:[{label:"Solid",value:0},{label:"Dotted",value:1},{label:"Dashed",value:2},{label:"Large Dashed",value:3},{label:"Sparse Dotted",value:4}]}),s.push({name:"Line Width",type:"number",valuePath:"lineWidth",defaultValue:i.lineWidth??1,min:.5,max:10,step:.5}),s.push({name:"Visible",type:"boolean",valuePath:"visible",defaultValue:i.visible??!0}),s.forEach((e=>{if("number"===e.type)this.addNumberInput(Hs(e.name),e.defaultValue,(i=>{const s=zs(e.valuePath,i);t.applyOptions(s),console.log(`Updated ${e.name} to: ${i}`)}),e.min,e.max,e.step);else if("boolean"===e.type)this.addCheckbox(Hs(e.name),e.defaultValue,(i=>{const s=zs(e.valuePath,i);t.applyOptions(s),console.log(`Updated ${e.name} to: ${i}`)}));else if("select"===e.type){const i=Array.isArray(e.options)&&"object"==typeof e.options[0]?e.options.map((e=>e.label)):e.options;this.addSelectInput(Hs(e.name),e.defaultValue,i,(i=>{const s=e.options.find((e=>e.label===i));if(s){const i=zs(e.valuePath,s.value);t.applyOptions(i),console.log(`Updated ${e.name} to: ${s.value}`)}}))}})),this.addMenuItem("⤝ Trend Trace Menu",(()=>this.populateTrendTraceMenu(e,t)),!1),this.showMenu(e)}populateVolumeProfileMenu(e,t){this.div.innerHTML="";const i=t._options,s=[];s.push({name:"Visible",type:"boolean",valuePath:"visible",defaultValue:i.visible??!0},{name:"Sections",type:"number",valuePath:"sections",defaultValue:i.sections??20,min:1,step:1},{name:"Right Side",type:"boolean",valuePath:"rightSide",defaultValue:i.rightSide??!0},{name:"Width",type:"number",valuePath:"width",defaultValue:i.width??30,min:1,step:1},{name:"Line Style",type:"select",valuePath:"lineStyle",defaultValue:i.lineStyle??0,options:[{label:"Solid",value:0},{label:"Dotted",value:1},{label:"Dashed",value:2},{label:"Large Dashed",value:3},{label:"Sparse Dotted",value:4}]},{name:"Draw Grid",type:"boolean",valuePath:"drawGrid",defaultValue:i.drawGrid??!0},{name:"Grid Width",type:"number",valuePath:"gridWidth",defaultValue:i.gridWidth??void 0,min:1,step:1},{name:"Grid Line Style",type:"select",valuePath:"gridLineStyle",defaultValue:i.gridLineStyle??4,options:[{label:"Solid",value:0},{label:"Dotted",value:1},{label:"Dashed",value:2},{label:"Large Dashed",value:3},{label:"Sparse Dotted",value:4}]}),s.push({name:"Up Color",type:"color",valuePath:"upColor",defaultValue:i.upColor??En.upColor},{name:"Down Color",type:"color",valuePath:"downColor",defaultValue:i.downColor??En.downColor},{name:"Border Up Color",type:"color",valuePath:"borderUpColor",defaultValue:i.borderUpColor??En.borderUpColor},{name:"Border Down Color",type:"color",valuePath:"borderDownColor",defaultValue:i.borderDownColor??En.borderDownColor},{name:"Grid Color",type:"color",valuePath:"gridColor",defaultValue:i.gridColor??En.gridColor}),s.forEach((e=>{if("number"===e.type)this.addNumberInput(Hs(e.name),e.defaultValue,(i=>{const s=zs(e.valuePath,i);t.applyOptions(s),console.log(`Updated ${e.name} to: ${i}`)}),e.min,e.max,e.step);else if("boolean"===e.type)this.addCheckbox(Hs(e.name),e.defaultValue,(i=>{const s=zs(e.valuePath,i);t.applyOptions(s),console.log(`Updated ${e.name} to: ${i}`)}));else if("select"===e.type){const i=Array.isArray(e.options)&&"object"==typeof e.options[0]?e.options.map((e=>e.label)):e.options;this.addSelectInput(Hs(e.name),e.defaultValue,i,(i=>{const s=e.options.find((e=>e.label===i));if(s){const i=zs(e.valuePath,s.value);t.applyOptions(i),console.log(`Updated ${e.name} to: ${s.value}`)}}))}else"color"===e.type&&this.addColorPickerMenuItem(Hs(e.name),e.defaultValue,e.valuePath,t)})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}indicatorSeriesMap=new Map;populateIndicatorMenu(e,t){this.div.innerHTML="",Co.forEach((i=>{this.addMenuItem(`${i.name} (${i.shortName})`,(()=>{i.paramMap?this.configureIndicatorParams({series:e,indicator:i},t,1,!0):this.applyIndicator(e,i,{},1)}),!1)})),this.addMenuItem("⤝ Back",(()=>{this.hideMenu()}),!1),this.showMenu(t)}configureIndicatorParams(e,t,i,s=!1){let n;this.div.innerHTML="";const o="sourceSeries"in e?e:e.series,r=e.indicator,a="paramMap"in e?e.paramMap:{},l={};let c=!1,h=0;Object.entries(r.paramMap).forEach((([e,t])=>{if("numberArray"===t.type||"selectArray"===t.type||"booleanArray"===t.type||"stringArray"===t.type){c=!0;const e=Array.isArray(t.defaultValue)?t.defaultValue:[t.defaultValue];h=Math.max(h,e.length)}})),c&&s&&(void 0!==i?(n=i,e.figureCount=i):n="figureCount"in e&&void 0!==e.figureCount?e.figureCount:h||1,this.addNumberInput("Number of Figures",n,(i=>{e.figureCount=i,this.configureIndicatorParams(e,t,i,!0)}),1,10,1)),Object.entries(r.paramMap).forEach((([t,s])=>{const n=t,o=void 0!==a[t]?a[t]:s.defaultValue;if("numberArray"===s.type||"selectArray"===s.type||"booleanArray"===s.type||"stringArray"===s.type){const r=i??e.figureCount,a=s.type.replace("Array","");l[t]=[];for(let e=0;e{l[t]||(l[t]=[]),l[t][e]=i}),s.min,s.max,s.step):"boolean"===a?this.addCheckbox(`${n} ${e+1}`,Boolean(i),(i=>{l[t]||(l[t]=[]),l[t][e]=i})):"select"===a?this.addSelectInput(`${n} ${e+1}`,String(i),s.options||[],(i=>{l[t]||(l[t]=[]),l[t][e]=i})):"string"===a&&this.addMenuInput(this.div,{type:"string",label:`${n} ${e+1}`,value:i,onChange:i=>{l[t]||(l[t]=[]),l[t][e]=i}}),l[t]||(l[t]=[]),l[t][e]=i}}else"number"===s.type?(this.addNumberInput(n,o,(e=>{l[t]=e}),s.min,s.max,s.step),l[t]=o):"boolean"===s.type?(this.addCheckbox(n,Boolean(o),(e=>{l[t]=e})),l[t]=o):"select"===s.type?(this.addSelectInput(n,String(o),s.options||[],(e=>{l[t]=e})),l[t]=o):(this.addMenuInput(this.div,{type:"string",label:n,value:o,onChange:e=>{l[t]=e}}),l[t]=o)})),this.addMenuItem("Apply",(()=>{this.hideMenu(),Object.entries(l).forEach((([e,t])=>{r.paramMap[e]&&(r.paramMap[e].defaultValue=t)})),"recalculate"in e?(e.recalculate(l),e.figures.forEach((e=>{const t=this.handler.legend._lines.find((t=>t.series===e));t&&(this.handler.seriesMap.set(e.options().title,o),t.name=e.options().title)}))):this.applyIndicator(o,r,l,n)}),!1),this.addMenuItem("Cancel",(()=>{this.hideMenu()}),!1),this.showMenu(t)}applyIndicator(e,t,i,s){const n=[...e.data()];if(!n||0===n.length)return void console.warn("No data found on this series.");let o;o=n.every(y)?n:n.map($s);const r=this.handler.volumeSeries.data(),a=t.calc([...o],i,r??void 0),l=new Map,c=function(e){const t={"#ff0000":["#ff0000","#f20000","#e60000","#d90000","#cc0000","#bf0000","#b30000","#a60000","#990000","#8c0000"],"#ff8700":["#ff8700","#f28000","#e67a00","#d97300","#cc6c00","#bf6500","#b35f00","#a65800","#995100","#8c4a00"],"#ffd300":["#ffd300","#fcca00","#e6c000","#d9b600","#ccb000","#bfaa00","#b3a000","#a69a00","#999000","#8c8600"],"#a1ff0a":["#a1ff0a","#97f207","#8ded04","#83e701","#79db00","#6fd200","#65c900","#5bc000","#51b700","#47ae00"],"#117a03":["#117a03","#107203","#0e6c03","#0c6603","#0a6003","#085a03","#065403","#044e03","#024803","#004203"],"#580aff":["#580aff","#5109f2","#4a08e6","#4307da","#3c06ce","#3505c2","#2e04b6","#2703aa","#2002a0","#190196"],"#be0aff":["#be0aff","#b308f2","#aa07e6","#a005da","#9704ce","#8e03c2","#8502b6","#7c01aa","#7300a0","#6a0096"]},i=Object.keys(t),s=t[i[Math.floor(Math.random()*i.length)]];if(e===s.length)return s;const n=[];for(let t=0;t{const r=c[o];let h=null;if("histogram"===n.type){const i=this.handler.createHistogramSeries(n.title,{color:r,base:0,title:n.title,...a.length>1?{group:t.name}:{}});i.series&&(i.series.setData(n.data),h=i.series,e.getPane().paneIndex()!==h.getPane().paneIndex()&&h.moveToPane(e.getPane().paneIndex()))}else{const i=this.handler.createLineSeries(n.title,{color:r,lineWidth:2,title:n.title,...a.length>1?{group:t.name}:{}});i.series&&(i.series.setData(n.data),h=i.series,e.getPane().paneIndex()!==h.getPane().paneIndex()&&h.moveToPane(e.getPane().paneIndex()))}if(h){const o=function(e,t,i,s,n,o,r){const a=Object.assign(e,{sourceSeries:t,indicator:i,figures:s,paramMap:o,figureCount:n,recalculate:function(e){r(this,e)}});return"function"==typeof t.subscribeDataChanged&&t.subscribeDataChanged((()=>{t.data()[t.data().length-1].time>e.data()[e.data().length-1].time&&r(a)})),a}(h,e,t,l,s,i,Fs);if(l.set(n.key,o),n.pane&&o.getPane()===e.getPane()){const e=o.getPane().paneIndex();o.moveToPane(e+n.pane)}}})),this.indicatorSeriesMap.set(t.name,l)}populateForkLineMainMenu(e,i){if(this.div.innerHTML="","PitchFork"!==i._type)return;const s=i._options;s.forkLines||(s.forkLines=[]);const n=s.forkLines;n.forEach(((t,s)=>{this.addMenuItem(`Fork Line ${s+1}`,(()=>{this.populateForkLineOptions(e,i,s)}),!1,!0)})),this.addMenuItem("Add Fork Line",(()=>{const s={value:.5,width:1,style:t.LineStyle.Solid,color:"#ffffff",fillColor:void 0};n.push(s),this.saveDrawings&&this.saveDrawings(),this.populateForkLineMainMenu(e,i)}),!1,!0),this.addMenuItem("⤝ Back",(()=>{this.populateDrawingMenu(e,i)}),!1,!1),this.showMenu(e)}populateForkLineOptions(e,i,s){this.div.innerHTML="";const n=i._options;if(!n.forkLines||!n.forkLines[s])return;const o=n.forkLines[s];this.addNumberInput("Value",o.value,(e=>{o.value=e,this.saveDrawings&&this.saveDrawings()}),0,10,.1),this.addNumberInput("Width",o.width,(e=>{o.width=e,this.saveDrawings&&this.saveDrawings()}),1,10,1);const r=[{name:"Solid",var:t.LineStyle.Solid},{name:"Dotted",var:t.LineStyle.Dotted},{name:"Dashed",var:t.LineStyle.Dashed},{name:"Large Dashed",var:t.LineStyle.LargeDashed},{name:"Sparse Dotted",var:t.LineStyle.SparseDotted}];this.addSelectInput("Style",r.find((e=>e.var===o.style))?.name||r[0].name,r.map((e=>e.name)),(e=>{const t=r.find((t=>t.name===e));t&&(o.style=t.var,this.saveDrawings&&this.saveDrawings())})),this.addForkLineColorPickerMenuItem("Color",o.color,o,"color"),this.addForkLineColorPickerMenuItem("Fill Color",o.fillColor||"",o,"fillColor"),this.addMenuItem("Remove Fork Line",(()=>{n.forkLines.splice(s,1),this.saveDrawings&&this.saveDrawings(),this.populateForkLineMainMenu(e,i)}),!1,!0),this.addMenuItem("⤝ Back",(()=>{this.populateForkLineMainMenu(e,i)}),!1,!1),this.showMenu(e)}addForkLineColorPickerMenuItem(e,t,i,s){const n=document.createElement("span");n.classList.add("context-menu-item"),n.innerText=e,this.div.appendChild(n);const o=e=>{i[s]=e,console.log(`Updated fork line ${s} to ${e}`),this.saveDrawings&&this.saveDrawings()};return n.addEventListener("click",(e=>{e.stopPropagation(),this.colorPicker||(this.colorPicker=new Sn(t??"#000000",o)),this.colorPicker.openMenu(e,225,o)})),n}}function Po(e){return function(e){return Math.max(1,Math.floor(e))}(e)/e}class To{_options;constructor(e){this._options=e}staticAggregate(e,t){const i=this._options?.chandelierSize??1,s=[];for(let n=0;n=s[0].open;r.close>=r.open!==e&&(a=!0)}else if("trigger"===n){(this._options?.dynamicTrigger&&this._options?.dynamicTrigger().newBar||r.newBar)&&(a=!0)}else if("volume_trend"===n){const e=s[0].volume,t=s[s.length-1].volume,i=r.volume;if(e&&t&&i){const s=t>=e;(s&&it)&&(a=!0)}}if(a){const e=o-s.length,n=o-1,a=this._chandelier(s,e,n,t,!1);i.push(a),s=[r]}else s.push(r)}if(s.length>0){const n=e.length-s.length,o=e.length-1,r=this._chandelier(s,n,o,t,!1);i.push(r)}return this.applyVolumeOpacity(i),i}applyVolumeOpacity(e){if(!this._options?.enableVolumeOpacity)return;if(!e.every((e=>void 0!==e.volume&&"number"==typeof e.volume)))return void console.warn("Volume opacity enabled but not all aggregated bars have volume data. Skipping volume-based opacity adjustment.");const t=this._options?.upColor||"rgba(0,255,0,0.333)",i=this._options?.downColor||"rgba(255,0,0,0.333)",s=p(t),n=p(i);if(0===s||0===n)return void console.warn("Volume opacity enabled but upColor/downColor alpha is zero. Skipping volume-based opacity adjustment.");const o=(this._options.volumeOpacityPeriod??20)*(this._options?.chandelierSize??1),r=this._options?.maxOpacity??.3;e.forEach(((e,s,n)=>{if(null==e.volume)return;const a=Math.max(0,s-o+1),c=n.slice(a,s+1);let h=1;if("/ max"!==this._options?.volumeOpacityMode&&this._options?.volumeOpacityMode)if("> previous"===this._options?.volumeOpacityMode)if(0!==s&&n[s-1].volume&&0!==n[s-1].volume){const t=n[s-1].volume??0;h=e.volume>t?r:0}else h=r;else if("> average"===this._options?.volumeOpacityMode){const t=c.reduce(((e,t)=>e+(void 0!==t.volume?t.volume:0)),0),i=c.length>0?t/c.length:0;h=i>0&&e.volume>i?r:0}else h=0;else{const t=c.reduce(((e,t)=>void 0!==t.volume&&t.volume>e?t.volume:e),0);h=t>0?e.volume/t*r:1}e.isUp?e.color=l(t,h):e.color=l(i,h)}))}_chandelier(e,t,i,s,o=!1){if(0===e.length)throw new Error("Bucket cannot be empty in _chandelier method.");const r=e[0].originalData?.open??e[0].open??0,a=e[e.length-1].originalData?.close??e[e.length-1].close??0,c=s(r)??0,h=s(a)??0,p=e.map((e=>e.originalData?.high??e.high)),d=e.map((e=>e.originalData?.low??e.low)),m=p.length>0?Math.max(...p):0,g=d.length>0?Math.min(...d):0,f=s(m)??0,y=s(g)??0,b=e[0].x,v=a>r,x=v?this._options?.upColor||"rgba(0,255,0,0.333)":this._options?.downColor||"rgba(255,0,0,0.333)",_=v?this._options?.borderUpColor||l(x,1):this._options?.borderDownColor||l(x,1),w=v?this._options?.wickUpColor||_:this._options?.wickDownColor||_,C=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options?.lineStyle??1),S=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options?.lineWidth??1),k=e.reduce(((e,t)=>(t.shape?u(t.shape):t.originalData?.shape?u(t.originalData.shape):void 0)??e),this._options?.shape??n.Rectangle);return{open:c,high:f,low:y,close:h,volume:e.reduce(((e,t)=>e+(t.originalData?.volume??t.volume??0)),0),x:b,isUp:v,startIndex:t,endIndex:i,isInProgress:o,color:x,borderColor:_,wickColor:w,shape:k||n.Rectangle,lineStyle:C,lineWidth:S}}}class Io{_data=null;_options=null;_aggregator=null;draw(e,t){e.useBitmapCoordinateSpace((e=>this._drawImpl(e,t)))}update(e,t){this._data=e,this._options=t,this._aggregator=new To(t)}_drawImpl(e,t){if(!this._data||0===this._data.bars.length||!this._data.visibleRange||!this._options)return;const i=this._data.bars.map(((e,t)=>({open:e.originalData?.open??0,high:e.originalData?.high??0,low:e.originalData?.low??0,close:e.originalData?.close??0,volume:e.originalData?.volume??0,x:e.x,shape:e.originalData?.shape??this._options?.shape??"Rectangle",lineStyle:e.originalData?.lineStyle??this._options?.lineStyle??1,lineWidth:e.originalData?.lineWidth??this._options?.lineWidth??1,isUp:(e.originalData?.close??0)>=(e.originalData?.open??0),color:this._options?.color??"rgba(0,0,0,0)",borderColor:this._options?.borderColor??"rgba(0,0,0,0)",wickColor:this._options?.wickColor??"rgba(0,0,0,0)",startIndex:t,endIndex:t})));let s;s="use Chandelier Size"===this._options.dynamicCandles?this._aggregator?.staticAggregate(i,t)??[]:this._aggregator?.dynamicAggregate(i,t)??[];const n=this._options.radius,{horizontalPixelRatio:o,verticalPixelRatio:r}=e,a=this._data.barSpacing*o;this._drawCandles(e,s,this._data.visibleRange,n,a,o,r),this._drawWicks(e,s,this._data.visibleRange)}_drawWicks(e,t,i){if(null===this._data||null===this._options)return;if("3d"===this._options.shape)return;const{context:s,horizontalPixelRatio:n,verticalPixelRatio:o}=e,r=this._data.barSpacing*n,a=Po(n),l=this._options?.barSpacing??.8;s.save();for(const e of t){if(e.startIndexi.to)continue;const t=e.low*o,c=e.high*o,h=Math.min(e.open,e.close)*o,p=Math.max(e.open,e.close)*o,d=e.endIndex-e.startIndex,u=1!==this._options?.chandelierSize?r*Math.max(1,d+1)-(1-l)*r:r*l,m=e.x*n-r*l/2+u/2;let g=c,f=h,y=p,b=t;"Polygon"===this._options.shape&&(f=(c+h)/2,y=(t+p)/2),s.fillStyle=e.color,s.strokeStyle=e.wickColor??e.color;const v=(e,t,i,n,o)=>{s.roundRect?s.roundRect(e,t,i,n,o):s.rect(e,t,i,n)},x=f-g;x>0&&(s.beginPath(),v(m-Math.floor(a/2),g,a,x,a/2),s.fill(),s.stroke());const _=b-y;_>0&&(s.beginPath(),v(m-Math.floor(a/2),y,a,_,a/2),s.fill(),s.stroke())}}_drawCandles(e,t,i,s,n,o,r){const{context:a}=e,l=this._options?.barSpacing??.8;a.save();for(const e of t){const t=e.endIndex-e.startIndex,c=1!==this._options?.chandelierSize?n*Math.max(1,t+1)-(1-l)*n:n*l,h=e.x*o,p=n*l;if(e.startIndexi.to)continue;const d=Math.min(e.open,e.close)*r,u=Math.max(e.open,e.close)*r,m=d-u,g=(d+u)/2,f=h-p/2,y=f+c,b=f+c/2;switch(a.fillStyle=e.color??this._options?.color??"rgba(255,255,255,1)",a.strokeStyle=e.borderColor??this._options?.borderColor??e.color??"rgba(255,255,255,1)",U(a,e.lineStyle),a.lineWidth=e.lineWidth??1,e.shape){case"Rectangle":default:qs(a,f,y,g,m);break;case"Rounded":Xs(a,f,y,g,m,s);break;case"Ellipse":Js(a,f,y,0,g,m);break;case"Arrow":Qs(a,f,y,b,g,m,e.high*r,e.low*r,e.isUp);break;case"3d":Ys(a,h,e.high*r,e.low*r,e.open*r,e.close*r,p,c,e.color??this._options?.color??"rgba(255,255,255,1)",e.borderColor??this._options?.borderColor??"rgba(255,255,255,1)",e.isUp,l);break;case"Polygon":Ks(a,f,y,g,m,e.high*r,e.low*r,e.isUp);break;case"Bar":Zs(a,f,y,e.high*r,e.low*r,e.open*r,e.close*r);break;case"Slanted":en(a,f,y,g,m,e.isUp)}}a.restore()}}const Ao={...t.customSeriesDefaultOptions,upColor:"#008000",downColor:"#8C0000",wickVisible:!0,borderVisible:!0,borderColor:"#737375",borderUpColor:"#008000",borderDownColor:"#8C0000",wickColor:"#737375",wickUpColor:"#008000",wickDownColor:"#8C0000",radius:.6,shape:"Rounded",chandelierSize:1,barSpacing:.8,lineStyle:0,lineWidth:2,enableVolumeOpacity:!0,volumeOpacityMode:"> previous",volumeOpacityPeriod:21,maxOpacity:.3,dynamicCandles:"use Chandelier Size",dynamicTrigger:()=>({newBar:!0})};class Do{_renderer;constructor(){this._renderer=new Io}priceValueBuilder(e){return[e.high,e.low,e.close]}renderer(){return this._renderer}isWhitespace(e){return void 0===e.close}update(e,t){this._renderer.update(e,t)}defaultOptions(){return Ao}}class Lo{defaults;constructor(){this.defaults=new Map}set(e,t){let i;if("string"==typeof t)try{i=JSON.parse(t)}catch(s){console.error(`Error parsing JSON string for key "${e}":`,s),i=t}else i=t;this.defaults.set(e,i),console.log(`Default options for key "${e}" set successfully.`),console.log(i)}get(e){const t=e.toLowerCase();for(const[e,i]of this.defaults)if(e.toLowerCase()===t)return i;return null}getAll(){return this.defaults}}class No{scripts;constructor(){this.scripts=new Map}set(e,t){let i;if("string"==typeof t)try{i=JSON.parse(t)}catch(s){console.error(`Error parsing JSON string for key "${e}":`,s),i=t}else i=t;this.scripts.set(e,i),console.log(`Default options for key "${e}" set successfully.`),console.log(i)}get(e){return this.scripts.has(e)?this.scripts.get(e):null}getAll(){return this.scripts}getLast(){if(this.scripts.has("cache"))return this.scripts.get("cache");if(0===this.scripts.size)return null;const e=Array.from(this.scripts.values());return e[e.length-1]}}class Oo{_data=null;_options=null;draw(e,t){e.useBitmapCoordinateSpace((e=>{this._drawImpl(e,t)}))}update(e,t){this._data=e,this._options=t}_drawImpl(e,t){const i=this._data?.barSpacing??.8;if(null===this._data||0===this._data.bars.length||null===this._data.visibleRange||null===this._options)return;const{context:s,horizontalPixelRatio:n,verticalPixelRatio:o}=e,{visibleRange:r}=this._data,{color:a,lineWidth:c,lineStyle:h,join:p,shape:d,shapeSize:u,fontSize:m}=this._options,g=this._data.bars.map((e=>({x:e.x*n,y:t(e.originalData.value)*o})));s.save(),s.lineJoin="round",s.strokeStyle=a,s.lineWidth=c*o,U(s,h),s.beginPath();const f=r.from,y=r.to-1;s.moveTo(g[f].x,g[f].y);for(let e=f+1;e<=y;e++)p&&s.lineTo(g[e].x,g[e].y);s.stroke(),s.restore();const b=(u??.8)*i,v={shape:d,shapeSize:b??1,fillColor:l(a,.5),borderColor:a,lineWidth:c,textAlign:"center",textBaseline:"middle",fontSize:(m??1)*i},x=this._data.bars;for(let e=f;e<=y;e++){const r=x[e],a=r.x*n,l=t(r.originalData.value)*o,c=r.originalData.shapeOptions??{},h=c.shapeSize??null,p=null!==h?h*i:b,d={...v,...c,shapeSize:p};this._drawShape(s,a,l,d)}}_drawShape(e,t,i,s){e.save();const{shape:n,shapeSize:o,fillColor:r,borderColor:a,lineWidth:l=1,textAlign:c="center",textBaseline:h="middle",fontSize:p=1}=s;switch(e.fillStyle=r??this._options?.color,e.strokeStyle=a??r??this._options?.color,e.lineWidth=l,e.textAlign=c,e.textBaseline=h,e.font=`${p}px sans-serif`,n){case"circles":e.beginPath(),e.arc(t,i,o/2,0,2*Math.PI),e.fill(),a&&e.stroke();break;case"cross":{const s=o/2,n=o/3;e.beginPath(),e.moveTo(t-n/2,i-s),e.lineTo(t+n/2,i-s),e.lineTo(t+n/2,i-n/2),e.lineTo(t+s,i-n/2),e.lineTo(t+s,i+n/2),e.lineTo(t+n/2,i+n/2),e.lineTo(t+n/2,i+s),e.lineTo(t-n/2,i+s),e.lineTo(t-n/2,i+n/2),e.lineTo(t-s,i+n/2),e.lineTo(t-s,i-n/2),e.lineTo(t-n/2,i-n/2),e.closePath(),e.fill(),a&&e.stroke();break}case"triangleUp":{const s=o/2;e.beginPath(),e.moveTo(t,i-s),e.lineTo(t-s,i+s),e.lineTo(t+s,i+s),e.closePath(),e.fill(),a&&e.stroke();break}case"triangleDown":{const s=o/2;e.beginPath(),e.moveTo(t,i+s),e.lineTo(t-s,i-s),e.lineTo(t+s,i-s),e.closePath(),e.fill(),a&&e.stroke();break}case"arrowUp":{const s=.4*o,n=o/3/2,r=i-o/2,l=r+s,c=i+o/2;e.beginPath(),e.moveTo(t,r),e.lineTo(t+s,l),e.lineTo(t+n,l),e.lineTo(t+n,c),e.lineTo(t-n,c),e.lineTo(t-n,l),e.lineTo(t-s,l),e.closePath(),e.fill(),a&&e.stroke();break}case"arrowDown":{const s=.4*o,n=o/3/2,r=i+o/2,l=r-s,c=i-o/2;e.beginPath(),e.moveTo(t,r),e.lineTo(t+s,l),e.lineTo(t+n,l),e.lineTo(t+n,c),e.lineTo(t-n,c),e.lineTo(t-n,l),e.lineTo(t-s,l),e.closePath(),e.fill(),a&&e.stroke();break}default:e.fillText(n,t,i,this._data?.barSpacing??.8)}e.restore()}}class Vo{_renderer;constructor(){this._renderer=new Oo}priceValueBuilder(e){return[e.value]}isWhitespace(e){return void 0===e.value}renderer(){return this._renderer}update(e,t){this._renderer.update(e,t)}defaultOptions(){return Ds}}M();class Ro{id;commandFunctions=[];static handlers=new Map;seriesOriginMap=new WeakMap;wrapper;div;chart;scale;precision=2;series;volumeSeries;volumeUpColor=null;volumeDownColor=null;legend;_topBar;toolBox;spinner;width=null;height=null;_seriesList=[];seriesMap=new Map;seriesMetadata;colorPicker=null;ContextMenu;currentMouseEventParams=null;defaultsManager;scriptsManager;constructor(e,t,i,s,n){this.reSize=this.reSize.bind(this),this.id=e,this.scale={width:t,height:i},this.defaultsManager=new Lo,this.scriptsManager=new No,Ro.handlers.set(e,this),this.wrapper=document.createElement("div"),this.wrapper.classList.add("handler"),this.wrapper.style.float=s,this.div=document.createElement("div"),this.div.style.position="relative",this.wrapper.appendChild(this.div),window.containerDiv.append(this.wrapper),this.chart=this._createChart(),this.ContextMenu=new Mo(this,Ro.handlers,(()=>window.MouseEventParams??null)),this.legend=new D(this),this.series=this.createCandlestickSeries(),this.volumeSeries=this.createVolumeSeries(),this.chart.subscribeCrosshairMove((e=>{this.currentMouseEventParams=e,window.MouseEventParams=e})),document.addEventListener("keydown",(e=>{for(let t=0;t{window.handlerInFocus=this.id,window.MouseEventParams=this.currentMouseEventParams||null})),this.seriesMetadata=new WeakMap,this.createTopBar(),window.monaco=!1,this.chart.subscribeCrosshairMove((e=>{this.currentMouseEventParams=e})),this.reSize(),n&&window.addEventListener("resize",(()=>this.reSize()))}reSize(){let e=0!==this.scale.height&&this._topBar?._div.offsetHeight||0;this.chart.resize(window.innerWidth*this.scale.width,window.innerHeight*this.scale.height-e),this.wrapper.style.width=100*this.scale.width+"%",this.wrapper.style.height=100*this.scale.height+"%",0===this.scale.height||0===this.scale.width?this.toolBox&&(this.toolBox.div.style.display="none"):this.toolBox&&(this.toolBox.div.style.display="flex")}primitives=new Map;_createChart(){return t.createChart(this.div,{width:window.innerWidth*this.scale.width,height:window.innerHeight*this.scale.height,layout:{textColor:window.pane.color,background:{color:"#000000",type:t.ColorType.Solid},fontSize:12},rightPriceScale:{scaleMargins:{top:.3,bottom:.25}},timeScale:{timeVisible:!0,secondsVisible:!1},crosshair:{mode:t.CrosshairMode.Normal,vertLine:{labelBackgroundColor:"rgb(46, 46, 46)"},horzLine:{labelBackgroundColor:"rgb(55, 55, 55)"}},grid:{vertLines:{color:"rgba(29, 30, 38, 5)"},horzLines:{color:"rgba(29, 30, 58, 5)"}},handleScroll:{vertTouchDrag:!0}})}mergeSeriesOptions(e,t){return{...Ns(e),...this.defaultsManager.defaults.get(e.toLowerCase())||{},...t}}createCandlestickSeries(){const e="Candlestick",i={...Ns(e),...this.defaultsManager.defaults.get(e.toLowerCase())||{}},s=this.chart.addSeries(t.CandlestickSeries,i);s.priceScale().applyOptions({scaleMargins:{top:.2,bottom:.2}});const n=Ls(s,this.legend);n.applyOptions({title:"OHLC"}),this._seriesList.push(n),this.seriesMap.set("OHLC",n);const o={name:"OHLC",series:n,colors:[i.upColor,i.downColor],legendSymbol:["⋰","⋱"],seriesType:"Candlestick",group:void 0};return this.legend.addLegendItem(o),n}createVolumeSeries(e){const i=this.chart.addSeries(t.HistogramSeries,{color:"#26a69a",priceFormat:{type:"volume"},priceScaleId:"volume_scale"});i.priceScale().applyOptions({scaleMargins:{top:0,bottom:.2}}),void 0!==e&&i.moveToPane(e);const s=Ls(i,this.legend);return s.applyOptions({title:"Volume"}),s}createLineSeries(e,i,s){const n=this.mergeSeriesOptions("Line",i??{}),o=(()=>{switch(n.lineStyle){case 0:return"―";case 1:return":··";case 2:return"--";case 3:return"- -";case 4:return"· ·";default:return"~"}})(),{group:r,legendSymbol:a=o,...l}=n,c=Ls(this.chart.addSeries(t.LineSeries,l),this.legend);c.applyOptions({title:e}),this._seriesList.push(c),this.seriesMap.set(e,c);const h=c.options().color||"rgba(255,0,0,1)",p={name:e,series:c,colors:[h.startsWith("rgba")?h.replace(/[^,]+(?=\))/,"1"):h],legendSymbol:Array.isArray(a)?a:[a],seriesType:"Line",group:r};return this.legend.addLegendItem(p),void 0!==s&&c.moveToPane(s),{name:e,series:c}}createHistogramSeries(e,i,s){const n=this.mergeSeriesOptions("Histogram",i??{}),{group:o,legendSymbol:r="▨",...a}=n,l=Ls(this.chart.addSeries(t.HistogramSeries,a),this.legend);l.applyOptions({title:e}),this._seriesList.push(l),this.seriesMap.set(e,l);const c=l.options().color||"rgba(255,0,0,1)",h={name:e,series:l,colors:[c.startsWith("rgba")?c.replace(/[^,]+(?=\))/,"1"):c],legendSymbol:Array.isArray(r)?r:[r],seriesType:"Histogram",group:o};return this.legend.addLegendItem(h),void 0!==s&&l.moveToPane(s),{name:e,series:l}}createAreaSeries(e,i,s){const n=this.mergeSeriesOptions("Area",i??{}),{group:o,legendSymbol:r="▨",...a}=n,l=Ls(this.chart.addSeries(t.AreaSeries,a),this.legend);this._seriesList.push(l),this.seriesMap.set(e,l);const c=l.options().lineColor||"rgba(255,0,0,1)",h={name:e,series:l,colors:[c.startsWith("rgba")?c.replace(/[^,]+(?=\))/,"1"):c],legendSymbol:Array.isArray(r)?r:[r],seriesType:"Area",group:o};return this.legend.addLegendItem(h),void 0!==s&&l.moveToPane(s),{name:e,series:l}}createBarSeries(e,i,s){const n=this.mergeSeriesOptions("Bar",i??{}),{group:o,legendSymbol:r=["┌","└"],...a}=n,l=Ls(this.chart.addSeries(t.BarSeries,a),this.legend);l.applyOptions({title:e}),this._seriesList.push(l),this.seriesMap.set(e,l);const c=l.options().upColor||"rgba(0,255,0,1)",h=l.options().downColor||"rgba(255,0,0,1)",p={name:e,series:l,colors:[c,h],legendSymbol:Array.isArray(r)?r:[r],seriesType:"Bar",group:o};return this.legend.addLegendItem(p),void 0!==s&&l.moveToPane(s),{name:e,series:l}}createCustomOHLCSeries(e,t,i){const s={...Ao,...this.defaultsManager.defaults.get("ohlc")||{},...t,seriesType:"Ohlc"},{group:n,legendSymbol:o=["⑃","⑂"],seriesType:r,chandelierSize:a,...l}=s,c=new Do,h=Ls(this.chart.addCustomSeries(c,{...l,chandelierSize:a,title:e}),this.legend);this._seriesList.push(h),this.seriesMap.set(e,h);const p={name:e,series:h,colors:[s.borderUpColor||s.upColor,s.borderDownColor||s.downColor],legendSymbol:Array.isArray(o)?o:o?[o]:[],seriesType:"Ohlc",group:n};return this.legend.addLegendItem(p),void 0!==i&&h.moveToPane(i),{name:e,series:h}}createSymbolSeries(e,t,i){const s={...Ds,...this.defaultsManager.defaults.get("symbol")||{},...t,seriesType:"Symbol"},n=(()=>{switch(s.shape){case"circle":case"circles":return"●";case"cross":return"✚";case"triangleUp":return"▲";case"triangleDown":return"▼";case"arrowUp":return"↑";case"arrowDown":return"↓";default:return s.shape}})(),{group:o,legendSymbol:r=n,...a}=s,l=new Vo,c=Ls(this.chart.addCustomSeries(l,{...a,title:e}),this.legend);this._seriesList.push(c),this.seriesMap.set(e,c);const h={name:e,series:c,colors:[c.options().color||"rgba(255,0,0,1)"],legendSymbol:Array.isArray(r)?r:r?[r]:[],seriesType:"Symbol",group:o};return this.legend.addLegendItem(h),void 0!==i&&c.moveToPane(i),{name:e,series:c}}createFillArea(e,t,i,s,n){const o=this._seriesList.find((e=>e.options()?.title===t)),r=this._seriesList.find((e=>e.options()?.title===i));if(!o)return void console.warn(`Origin series with title "${t}" not found.`);if(!r)return void console.warn(`Destination series with title "${i}" not found.`);const a=Bs(o,this.legend),l=new _(o,r,{originColor:s||null,destinationColor:n||null,lineWidth:null});return a.attachPrimitive(l,e),l}attachPrimitive(e,t,i,s){let n=i;try{if(s&&!i&&(n=this.seriesMap.get(s)),!n)return void console.warn(`Series with the name "${s}" not found.`);const o=Bs(n,this.legend);let r;if("Tooltip"!==t)return void console.warn(`Unknown primitive type: ${t}`);r=new wn({lineColor:e}),o.attachPrimitive(r,"Tooltip"),this.primitives.set(n,r)}catch(e){console.error(`Failed to attach ${t}:`,e)}}removeSeries(e){let t;if(x(e)){for(const[i,s]of this.seriesMap.entries())if(s===e){t=i;break}}else t=e,e=this.seriesMap.get(e);if(e&&t){e.primitives&&e.primitives.length>0&&e.primitives.forEach((i=>{e.detachPrimitive(i),console.log(`✅ Detached primitive from series "${t}".`)})),this._seriesList=this._seriesList.filter((t=>t!==e)),this.seriesMap.delete(t),console.log(`✅ Series "${t}" removed from internal maps.`);try{const i=this.legend._items.find((t=>t.series===e));i?(i.primitives&&i.primitives.length>0&&i.primitives.forEach((e=>{this.legend.removeLegendPrimitive(e),console.log(`✅ Removed primitive from legend for series "${t}".`)})),this.legend.deleteLegendEntry(i.name,i.group??void 0),console.log(`✅ Removed series "${t}" from legend.`)):console.warn(`⚠️ Legend item for series "${t}" not found.`)}catch(e){console.error(`⚠️ Error removing legend entry for "${t}":`,e)}this.chart.removeSeries(e),console.log(`✅ Series "${t}" successfully removed.`)}else console.warn(`❌ Series "${e}" does not exist and cannot be removed.`)}createToolBox(){this.toolBox=new ye(this,this.chart,this.series,this.commandFunctions),this.div.appendChild(this.toolBox.div)}createTopBar(){return this._topBar=new un(this),this.wrapper.prepend(this._topBar._div),this._topBar}extractSeriesData(e){const t=e.data();return Array.isArray(t)?t.map((e=>[e.time,e.value||e.close||0])):(console.warn("Failed to extract data: series data is not in array format."),[])}static syncCharts(e,t,i=!1){function s(e,t){t?(e.chart.setCrosshairPosition(t.value||t.close,t.time,e.series),e.legend.legendHandler(t,!0)):e.chart.clearCrosshairPosition()}function n(e,t){return t.time&&t.seriesData.get(e)||null}const o=e.chart.timeScale(),r=t.chart.timeScale(),a=e=>{e&&o.setVisibleLogicalRange(e)},l=e=>{e&&r.setVisibleLogicalRange(e)},c=i=>{s(t,n(e.series,i))},h=i=>{s(e,n(t.series,i))};let p=t;function d(e,t,s,n,o,r){e.wrapper.addEventListener("mouseover",(()=>{p!==e&&(p=e,t.chart.unsubscribeCrosshairMove(s),e.chart.subscribeCrosshairMove(n),i||(t.chart.timeScale().unsubscribeVisibleLogicalRangeChange(o),e.chart.timeScale().subscribeVisibleLogicalRangeChange(r)))}))}d(t,e,c,h,l,a),d(e,t,h,c,a,l),t.chart.subscribeCrosshairMove(h);const u=r.getVisibleLogicalRange();u&&o.setVisibleLogicalRange(u),i||t.chart.timeScale().subscribeVisibleLogicalRangeChange(a)}static makeSearchBox(e){const t=document.createElement("div");t.classList.add("searchbox"),t.style.display="none";const i=document.createElement("div");i.innerHTML='';const s=document.createElement("input");return s.type="text",t.appendChild(i),t.appendChild(s),e.div.appendChild(t),e.commandFunctions.push((i=>!1===window.monaco&&!1===window.menu&&(window.handlerInFocus===e.id&&!window.textBoxFocused&&("none"===t.style.display?!!/^[a-zA-Z0-9]$/.test(i.key)&&(t.style.display="flex",s.focus(),!0):("Enter"===i.key||"Escape"===i.key)&&("Enter"===i.key&&window.callbackFunction(`search${e.id}_~_${s.value}`),t.style.display="none",s.value="",!0))))),s.addEventListener("input",(()=>s.value=s.value.toUpperCase())),{window:t,box:s}}static makeSpinner(e){e.spinner=document.createElement("div"),e.spinner.classList.add("spinner"),e.wrapper.appendChild(e.spinner);let t=0;!function i(){e.spinner&&(t+=10,e.spinner.style.transform=`translate(-50%, -50%) rotate(${t}deg)`,requestAnimationFrame(i))}()}static _styleMap={"--bg-color":"backgroundColor","--hover-bg-color":"hoverBackgroundColor","--click-bg-color":"clickBackgroundColor","--active-bg-color":"activeBackgroundColor","--muted-bg-color":"mutedBackgroundColor","--border-color":"borderColor","--color":"color","--active-color":"activeColor"};static setRootStyles(e){const t=document.documentElement.style;for(const[i,s]of Object.entries(this._styleMap))t.setProperty(i,e[s])}toJSON(){return{id:this.id,options:this.chart.options(),scale:this.scale,precision:this.precision}}fromJSON(e){e?(e.options&&this.chart.applyOptions(e.options),void 0!==e.scale&&(this.scale=e.scale),void 0!==e.precision&&(this.precision=e.precision)):console.warn("No JSON data provided for handler deserialization.")}_type="chart";title="chart"}return e.Box=Z,e.CodeEditor=cn,e.FillArea=_,e.Handler=Ro,e.HorizontalLine=se,e.Legend=D,e.RayLine=ne,e.Table=class{_div;callbackName;borderColor;borderWidth;table;rows={};headings;widths;alignments;footer;header;constructor(e,t,i,s,n,o,r=!1,a,l,c,h,p){this._div=document.createElement("div"),this.callbackName=null,this.borderColor=l,this.borderWidth=c,r?(this._div.style.position="absolute",this._div.style.cursor="move"):(this._div.style.position="relative",this._div.style.float=o),this._div.style.zIndex="2000",this.reSize(e,t),this._div.style.display="flex",this._div.style.flexDirection="column",this._div.style.borderRadius="5px",this._div.style.color="white",this._div.style.fontSize="12px",this._div.style.fontVariantNumeric="tabular-nums",this.table=document.createElement("table"),this.table.style.width="100%",this.table.style.borderCollapse="collapse",this._div.style.overflow="hidden",this.headings=i,this.widths=s.map((e=>100*e+"%")),this.alignments=n;let d=this.table.createTHead().insertRow();for(let e=0;e0?p[e]:a,t.style.color=h[e],d.appendChild(t)}let u,m,g=document.createElement("div");if(g.style.overflowY="auto",g.style.overflowX="hidden",g.style.backgroundColor=a,g.appendChild(this.table),this._div.appendChild(g),window.containerDiv.appendChild(this._div),!r)return;let f=e=>{this._div.style.left=e.clientX-u+"px",this._div.style.top=e.clientY-m+"px"},y=()=>{document.removeEventListener("mousemove",f),document.removeEventListener("mouseup",y)};this._div.addEventListener("mousedown",(e=>{u=e.clientX-this._div.offsetLeft,m=e.clientY-this._div.offsetTop,document.addEventListener("mousemove",f),document.addEventListener("mouseup",y)}))}divToButton(e,t){e.addEventListener("mouseover",(()=>e.style.backgroundColor="rgba(60, 60, 60, 0.6)")),e.addEventListener("mouseout",(()=>e.style.backgroundColor="transparent")),e.addEventListener("mousedown",(()=>e.style.backgroundColor="rgba(60, 60, 60)")),e.addEventListener("click",(()=>window.callbackFunction(t))),e.addEventListener("mouseup",(()=>e.style.backgroundColor="rgba(60, 60, 60, 0.6)"))}newRow(e,t=!1){let i=this.table.insertRow();i.style.cursor="default";for(let s=0;s{e&&(window.cursor=e),document.body.style.cursor=window.cursor},e}({},LightweightCharts,monaco); //# sourceMappingURL=bundle.js.map diff --git a/lightweight_charts_esistjosh/js/lightweight-charts.js b/lightweight_charts_esistjosh/js/lightweight-charts.js index 10125750..fc17c695 100644 --- a/lightweight_charts_esistjosh/js/lightweight-charts.js +++ b/lightweight_charts_esistjosh/js/lightweight-charts.js @@ -1,7 +1,7 @@ /*! * @license - * TradingView Lightweight Charts™ v5.0.1 + * TradingView Lightweight Charts™ v5.0.6 * Copyright (c) 2025 TradingView, Inc. * Licensed under Apache License 2.0 https://www.apache.org/licenses/LICENSE-2.0 */ -!function(){"use strict";const t={title:"",visible:!0,lastValueVisible:!0,priceLineVisible:!0,priceLineSource:0,priceLineWidth:1,priceLineColor:"",priceLineStyle:2,baseLineVisible:!0,baseLineWidth:1,baseLineColor:"#B2B5BE",baseLineStyle:0,priceFormat:{type:"price",precision:2,minMove:.01}};var i,n;function s(t,i){const n={0:[],1:[t.lineWidth,t.lineWidth],2:[2*t.lineWidth,2*t.lineWidth],3:[6*t.lineWidth,6*t.lineWidth],4:[t.lineWidth,4*t.lineWidth]}[i];t.setLineDash(n)}function e(t,i,n,s){t.beginPath();const e=t.lineWidth%2?.5:0;t.moveTo(n,i+e),t.lineTo(s,i+e),t.stroke()}function r(t,i){if(!t)throw new Error("Assertion failed"+(i?": "+i:""))}function h(t){if(void 0===t)throw new Error("Value is undefined");return t}function a(t){if(null===t)throw new Error("Value is null");return t}function l(t){return a(h(t))}!function(t){t[t.Simple=0]="Simple",t[t.WithSteps=1]="WithSteps",t[t.Curved=2]="Curved"}(i||(i={})),function(t){t[t.Solid=0]="Solid",t[t.Dotted=1]="Dotted",t[t.Dashed=2]="Dashed",t[t.LargeDashed=3]="LargeDashed",t[t.SparseDotted=4]="SparseDotted"}(n||(n={}));class o{constructor(){this.t=[]}i(t,i,n){const s={h:t,l:i,o:!0===n};this.t.push(s)}_(t){const i=this.t.findIndex((i=>t===i.h));i>-1&&this.t.splice(i,1)}u(t){this.t=this.t.filter((i=>i.l!==t))}p(t,i,n){const s=[...this.t];this.t=this.t.filter((t=>!t.o)),s.forEach((s=>s.h(t,i,n)))}v(){return this.t.length>0}m(){this.t=[]}}function _(t,...i){for(const n of i)for(const i in n)void 0!==n[i]&&Object.prototype.hasOwnProperty.call(n,i)&&!["__proto__","constructor","prototype"].includes(i)&&("object"!=typeof n[i]||void 0===t[i]||Array.isArray(n[i])?t[i]=n[i]:_(t[i],n[i]));return t}function u(t){return"number"==typeof t&&isFinite(t)}function c(t){return"number"==typeof t&&t%1==0}function d(t){return"string"==typeof t}function f(t){return"boolean"==typeof t}function p(t){const i=t;if(!i||"object"!=typeof i)return i;let n,s,e;for(s in n=Array.isArray(i)?[]:{},i)i.hasOwnProperty(s)&&(e=i[s],n[s]=e&&"object"==typeof e?p(e):e);return n}function v(t){return null!==t}function m(t){return null===t?void 0:t}const w="-apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif";function g(t,i,n){return void 0===i&&(i=w),`${n=void 0!==n?`${n} `:""}${t}px ${i}`}class M{constructor(t){this.M={S:1,C:5,k:NaN,P:"",T:"",R:"",D:"",I:0,V:0,A:0,B:0,O:0},this.L=t}N(){const t=this.M,i=this.W(),n=this.F();return t.k===i&&t.T===n||(t.k=i,t.T=n,t.P=g(i,n),t.B=2.5/12*i,t.I=t.B,t.V=i/12*t.C,t.A=i/12*t.C,t.O=0),t.R=this.H(),t.D=this.U(),this.M}H(){return this.L.N().layout.textColor}U(){return this.L.$()}W(){return this.L.N().layout.fontSize}F(){return this.L.N().layout.fontFamily}}function b(t){return t<0?0:t>255?255:Math.round(t)||0}function x(t){return.199*t[0]+.687*t[1]+.114*t[2]}class S{constructor(t,i){this.j=new Map,this.q=t,i&&(this.j=i)}Y(t,i){if("transparent"===t)return t;const n=this.Z(t),s=n[3];return`rgba(${n[0]}, ${n[1]}, ${n[2]}, ${i*s})`}K(t){const i=this.Z(t);return{X:`rgb(${i[0]}, ${i[1]}, ${i[2]})`,G:x(i)>160?"black":"white"}}J(t){return x(this.Z(t))}tt(t,i,n){const[s,e,r,h]=this.Z(t),[a,l,o,_]=this.Z(i),u=[b(s+n*(a-s)),b(e+n*(l-e)),b(r+n*(o-r)),(c=h+n*(_-h),c<=0||c>1?Math.min(Math.max(c,0),1):Math.round(1e4*c)/1e4)];var c;return`rgba(${u[0]}, ${u[1]}, ${u[2]}, ${u[3]})`}Z(t){const i=this.j.get(t);if(i)return i;const n=function(t){const i=document.createElement("div");i.style.display="none",document.body.appendChild(i),i.style.color=t;const n=window.getComputedStyle(i).color;return document.body.removeChild(i),n}(t),s=n.match(/^rgba?\s*\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d*\.?\d+))?\)$/);if(!s){if(this.q.length)for(const i of this.q){const n=i(t);if(n)return this.j.set(t,n),n}throw new Error(`Failed to parse color: ${t}`)}const e=[parseInt(s[1],10),parseInt(s[2],10),parseInt(s[3],10),s[4]?parseFloat(s[4]):1];return this.j.set(t,e),e}}class C{constructor(){this.it=[]}nt(t){this.it=t}st(t,i,n){this.it.forEach((s=>{s.st(t,i,n)}))}}class y{st(t,i,n){t.useBitmapCoordinateSpace((t=>this.et(t,i,n)))}}class k extends y{constructor(){super(...arguments),this.rt=null}ht(t){this.rt=t}et({context:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(null===this.rt||null===this.rt.lt)return;const s=this.rt.lt,e=this.rt,r=Math.max(1,Math.floor(i))%2/2,h=h=>{t.beginPath();for(let a=s.to-1;a>=s.from;--a){const s=e.ot[a],l=Math.round(s._t*i)+r,o=s.ut*n,_=h*n+r;t.moveTo(l,o),t.arc(l,o,_,0,2*Math.PI)}t.fill()};e.ct>0&&(t.fillStyle=e.dt,h(e.ft+e.ct)),t.fillStyle=e.vt,h(e.ft)}}function P(){return{ot:[{_t:0,ut:0,wt:0,gt:0}],vt:"",dt:"",ft:0,ct:0,lt:null}}const T={from:0,to:1};class R{constructor(t,i,n){this.Mt=new C,this.bt=[],this.xt=[],this.St=!0,this.L=t,this.Ct=i,this.yt=n,this.Mt.nt(this.bt)}kt(t){this.Pt(),this.St=!0}Tt(){return this.St&&(this.Rt(),this.St=!1),this.Mt}Pt(){const t=this.yt.Dt();t.length!==this.bt.length&&(this.xt=t.map(P),this.bt=this.xt.map((t=>{const i=new k;return i.ht(t),i})),this.Mt.nt(this.bt))}Rt(){const t=2===this.Ct.N().mode,i=this.yt.It(),n=this.Ct.Vt(),s=this.L.Et();this.Pt(),i.forEach(((i,e)=>{const r=this.xt[e],h=i.At(n),a=i.Bt();!t&&null!==h&&i.zt()&&null!==a?(r.vt=h.Ot,r.ft=h.ft,r.ct=h.Lt,r.ot[0].gt=h.gt,r.ot[0].ut=i.Wt().Nt(h.gt,a.Ft),r.dt=h.Ht??this.L.Ut(r.ot[0].ut/i.Wt().$t()),r.ot[0].wt=n,r.ot[0]._t=s.jt(n),r.lt=T):r.lt=null}))}}class D extends y{constructor(t){super(),this.qt=t}et({context:t,bitmapSize:i,horizontalPixelRatio:n,verticalPixelRatio:r}){if(null===this.qt)return;const h=this.qt.Yt.zt,a=this.qt.Zt.zt;if(!h&&!a)return;const l=Math.round(this.qt._t*n),o=Math.round(this.qt.ut*r);t.lineCap="butt",h&&l>=0&&(t.lineWidth=Math.floor(this.qt.Yt.ct*n),t.strokeStyle=this.qt.Yt.R,t.fillStyle=this.qt.Yt.R,s(t,this.qt.Yt.Kt),function(t,i,n,s){t.beginPath();const e=t.lineWidth%2?.5:0;t.moveTo(i+e,n),t.lineTo(i+e,s),t.stroke()}(t,l,0,i.height)),a&&o>=0&&(t.lineWidth=Math.floor(this.qt.Zt.ct*r),t.strokeStyle=this.qt.Zt.R,t.fillStyle=this.qt.Zt.R,s(t,this.qt.Zt.Kt),e(t,o,0,i.width))}}class I{constructor(t,i){this.St=!0,this.Xt={Yt:{ct:1,Kt:0,R:"",zt:!1},Zt:{ct:1,Kt:0,R:"",zt:!1},_t:0,ut:0},this.Gt=new D(this.Xt),this.Jt=t,this.yt=i}kt(){this.St=!0}Tt(t){return this.St&&(this.Rt(),this.St=!1),this.Gt}Rt(){const t=this.Jt.zt(),i=this.yt.Qt().N().crosshair,n=this.Xt;if(2===i.mode)return n.Zt.zt=!1,void(n.Yt.zt=!1);n.Zt.zt=t&&this.Jt.ti(this.yt),n.Yt.zt=t&&this.Jt.ii(),n.Zt.ct=i.horzLine.width,n.Zt.Kt=i.horzLine.style,n.Zt.R=i.horzLine.color,n.Yt.ct=i.vertLine.width,n.Yt.Kt=i.vertLine.style,n.Yt.R=i.vertLine.color,n._t=this.Jt.ni(),n.ut=this.Jt.si()}}function V(t,i,n,s,e,r){t.fillRect(i+r,n,s-2*r,r),t.fillRect(i+r,n+e-r,s-2*r,r),t.fillRect(i,n,r,e),t.fillRect(i+s-r,n,r,e)}function E(t,i,n,s,e,r){t.save(),t.globalCompositeOperation="copy",t.fillStyle=r,t.fillRect(i,n,s,e),t.restore()}function A(t,i,n,s,e,r){t.beginPath(),t.roundRect?t.roundRect(i,n,s,e,r):(t.lineTo(i+s-r[1],n),0!==r[1]&&t.arcTo(i+s,n,i+s,n+r[1],r[1]),t.lineTo(i+s,n+e-r[2]),0!==r[2]&&t.arcTo(i+s,n+e,i+s-r[2],n+e,r[2]),t.lineTo(i+r[3],n+e),0!==r[3]&&t.arcTo(i,n+e,i,n+e-r[3],r[3]),t.lineTo(i,n+r[0]),0!==r[0]&&t.arcTo(i,n,i+r[0],n,r[0]))}function B(t,i,n,s,e,r,h=0,a=[0,0,0,0],l=""){if(t.save(),!h||!l||l===r)return A(t,i,n,s,e,a),t.fillStyle=r,t.fill(),void t.restore();const o=h/2;var _;A(t,i+o,n+o,s-h,e-h,(_=-o,a.map((t=>0===t?t:t+_)))),"transparent"!==r&&(t.fillStyle=r,t.fill()),"transparent"!==l&&(t.lineWidth=h,t.strokeStyle=l,t.closePath(),t.stroke()),t.restore()}function z(t,i,n,s,e,r,h){t.save(),t.globalCompositeOperation="copy";const a=t.createLinearGradient(0,0,0,e);a.addColorStop(0,r),a.addColorStop(1,h),t.fillStyle=a,t.fillRect(i,n,s,e),t.restore()}class O{constructor(t,i){this.ht(t,i)}ht(t,i){this.qt=t,this.ei=i}$t(t,i){return this.qt.zt?t.k+t.B+t.I:0}st(t,i,n,s){if(!this.qt.zt||0===this.qt.ri.length)return;const e=this.qt.R,r=this.ei.X,h=t.useBitmapCoordinateSpace((t=>{const h=t.context;h.font=i.P;const a=this.hi(t,i,n,s),l=a.ai;return a.li?B(h,l.oi,l._i,l.ui,l.ci,r,l.di,[l.ft,0,0,l.ft],r):B(h,l.fi,l._i,l.ui,l.ci,r,l.di,[0,l.ft,l.ft,0],r),this.qt.pi&&(h.fillStyle=e,h.fillRect(l.fi,l.mi,l.wi-l.fi,l.gi)),this.qt.Mi&&(h.fillStyle=i.D,h.fillRect(a.li?l.bi-l.di:0,l._i,l.di,l.xi-l._i)),a}));t.useMediaCoordinateSpace((({context:t})=>{const n=h.Si;t.font=i.P,t.textAlign=h.li?"right":"left",t.textBaseline="middle",t.fillStyle=e,t.fillText(this.qt.ri,n.Ci,(n._i+n.xi)/2+n.yi)}))}hi(t,i,n,s){const{context:e,bitmapSize:r,mediaSize:h,horizontalPixelRatio:a,verticalPixelRatio:l}=t,o=this.qt.pi||!this.qt.ki?i.C:0,_=this.qt.Pi?i.S:0,u=i.B+this.ei.Ti,c=i.I+this.ei.Ri,d=i.V,f=i.A,p=this.qt.ri,v=i.k,m=n.Di(e,p),w=Math.ceil(n.Ii(e,p)),g=v+u+c,M=i.S+d+f+w+o,b=Math.max(1,Math.floor(l));let x=Math.round(g*l);x%2!=b%2&&(x+=1);const S=_>0?Math.max(1,Math.floor(_*a)):0,C=Math.round(M*a),y=Math.round(o*a),k=this.ei.Vi??this.ei.Ei,P=Math.round(k*l)-Math.floor(.5*l),T=Math.floor(P+b/2-x/2),R=T+x,D="right"===s,I=D?h.width-_:_,V=D?r.width-S:S;let E,A,B;return D?(E=V-C,A=V-y,B=I-o-d-_):(E=V+C,A=V+y,B=I+o+d),{li:D,ai:{_i:T,mi:P,xi:R,ui:C,ci:x,ft:2*a,di:S,oi:E,fi:V,wi:A,gi:b,bi:r.width},Si:{_i:T/l,xi:R/l,Ci:B,yi:m}}}}class L{constructor(t){this.Ai={Ei:0,X:"#000",Ri:0,Ti:0},this.Bi={ri:"",zt:!1,pi:!0,ki:!1,Ht:"",R:"#FFF",Mi:!1,Pi:!1},this.zi={ri:"",zt:!1,pi:!1,ki:!0,Ht:"",R:"#FFF",Mi:!0,Pi:!0},this.St=!0,this.Oi=new(t||O)(this.Bi,this.Ai),this.Li=new(t||O)(this.zi,this.Ai)}ri(){return this.Ni(),this.Bi.ri}Ei(){return this.Ni(),this.Ai.Ei}kt(){this.St=!0}$t(t,i=!1){return Math.max(this.Oi.$t(t,i),this.Li.$t(t,i))}Wi(){return this.Ai.Vi||0}Fi(t){this.Ai.Vi=t}Hi(){return this.Ni(),this.Bi.zt||this.zi.zt}Ui(){return this.Ni(),this.Bi.zt}Tt(t){return this.Ni(),this.Bi.pi=this.Bi.pi&&t.N().ticksVisible,this.zi.pi=this.zi.pi&&t.N().ticksVisible,this.Oi.ht(this.Bi,this.Ai),this.Li.ht(this.zi,this.Ai),this.Oi}$i(){return this.Ni(),this.Oi.ht(this.Bi,this.Ai),this.Li.ht(this.zi,this.Ai),this.Li}Ni(){this.St&&(this.Bi.pi=!0,this.zi.pi=!1,this.ji(this.Bi,this.zi,this.Ai))}}class N extends L{constructor(t,i,n){super(),this.Jt=t,this.qi=i,this.Yi=n}ji(t,i,n){if(t.zt=!1,2===this.Jt.N().mode)return;const s=this.Jt.N().horzLine;if(!s.labelVisible)return;const e=this.qi.Bt();if(!this.Jt.zt()||this.qi.Zi()||null===e)return;const r=this.qi.Ki().K(s.labelBackgroundColor);n.X=r.X,t.R=r.G;const h=2/12*this.qi.k();n.Ti=h,n.Ri=h;const a=this.Yi(this.qi);n.Ei=a.Ei,t.ri=this.qi.Xi(a.gt,e),t.zt=!0}}const W=/[1-9]/g;class F{constructor(){this.qt=null}ht(t){this.qt=t}st(t,i){if(null===this.qt||!1===this.qt.zt||0===this.qt.ri.length)return;const n=t.useMediaCoordinateSpace((({context:t})=>(t.font=i.P,Math.round(i.Gi.Ii(t,a(this.qt).ri,W)))));if(n<=0)return;const s=i.Ji,e=n+2*s,r=e/2,h=this.qt.Qi;let l=this.qt.Ei,o=Math.floor(l-r)+.5;o<0?(l+=Math.abs(0-o),o=Math.floor(l-r)+.5):o+e>h&&(l-=Math.abs(h-(o+e)),o=Math.floor(l-r)+.5);const _=o+e,u=Math.ceil(0+i.S+i.C+i.B+i.k+i.I);t.useBitmapCoordinateSpace((({context:t,horizontalPixelRatio:n,verticalPixelRatio:s})=>{const e=a(this.qt);t.fillStyle=e.X;const r=Math.round(o*n),h=Math.round(0*s),l=Math.round(_*n),c=Math.round(u*s),d=Math.round(2*n);if(t.beginPath(),t.moveTo(r,h),t.lineTo(r,c-d),t.arcTo(r,c,r+d,c,d),t.lineTo(l-d,c),t.arcTo(l,c,l,c-d,d),t.lineTo(l,h),t.fill(),e.pi){const r=Math.round(e.Ei*n),a=h,l=Math.round((a+i.C)*s);t.fillStyle=e.R;const o=Math.max(1,Math.floor(n)),_=Math.floor(.5*n);t.fillRect(r-_,a,o,l-a)}})),t.useMediaCoordinateSpace((({context:t})=>{const n=a(this.qt),e=0+i.S+i.C+i.B+i.k/2;t.font=i.P,t.textAlign="left",t.textBaseline="middle",t.fillStyle=n.R;const r=i.Gi.Di(t,"Apr0");t.translate(o+s,e+r),t.fillText(n.ri,0,0)}))}}class H{constructor(t,i,n){this.St=!0,this.Gt=new F,this.Xt={zt:!1,X:"#4c525e",R:"white",ri:"",Qi:0,Ei:NaN,pi:!0},this.Ct=t,this.tn=i,this.Yi=n}kt(){this.St=!0}Tt(){return this.St&&(this.Rt(),this.St=!1),this.Gt.ht(this.Xt),this.Gt}Rt(){const t=this.Xt;if(t.zt=!1,2===this.Ct.N().mode)return;const i=this.Ct.N().vertLine;if(!i.labelVisible)return;const n=this.tn.Et();if(n.Zi())return;t.Qi=n.Qi();const s=this.Yi();if(null===s)return;t.Ei=s.Ei;const e=n.nn(this.Ct.Vt());t.ri=n.sn(a(e)),t.zt=!0;const r=this.tn.Ki().K(i.labelBackgroundColor);t.X=r.X,t.R=r.G,t.pi=n.N().ticksVisible}}class U{constructor(){this.en=null,this.rn=0}hn(){return this.rn}an(t){this.rn=t}Wt(){return this.en}ln(t){this.en=t}_n(t){return[]}un(){return[]}zt(){return!0}}var $;!function(t){t[t.Normal=0]="Normal",t[t.Magnet=1]="Magnet",t[t.Hidden=2]="Hidden"}($||($={}));class j extends U{constructor(t,i){super(),this.yt=null,this.cn=NaN,this.dn=0,this.fn=!0,this.pn=new Map,this.vn=!1,this.mn=new WeakMap,this.wn=new WeakMap,this.gn=NaN,this.Mn=NaN,this.bn=NaN,this.xn=NaN,this.tn=t,this.Sn=i;this.Cn=((t,i)=>n=>{const s=i(),e=t();if(n===a(this.yt).yn())return{gt:e,Ei:s};{const t=a(n.Bt());return{gt:n.kn(s,t),Ei:s}}})((()=>this.cn),(()=>this.Mn));const n=((t,i)=>()=>{const n=this.tn.Et().Pn(t()),s=i();return n&&Number.isFinite(s)?{wt:n,Ei:s}:null})((()=>this.dn),(()=>this.ni()));this.Tn=new H(this,t,n)}N(){return this.Sn}Rn(t,i){this.bn=t,this.xn=i}Dn(){this.bn=NaN,this.xn=NaN}In(){return this.bn}Vn(){return this.xn}En(t,i,n){this.vn||(this.vn=!0),this.fn=!0,this.An(t,i,n)}Vt(){return this.dn}ni(){return this.gn}si(){return this.Mn}zt(){return this.fn}Bn(){this.fn=!1,this.zn(),this.cn=NaN,this.gn=NaN,this.Mn=NaN,this.yt=null,this.Dn(),this.On()}Ln(t){let i=this.mn.get(t);i||(i=new I(this,t),this.mn.set(t,i));let n=this.wn.get(t);return n||(n=new R(this.tn,this,t),this.wn.set(t,n)),[i,n]}ti(t){return t===this.yt&&this.Sn.horzLine.visible}ii(){return this.Sn.vertLine.visible}Nn(t,i){this.fn&&this.yt===t||this.pn.clear();const n=[];return this.yt===t&&n.push(this.Wn(this.pn,i,this.Cn)),n}un(){return this.fn?[this.Tn]:[]}Fn(){return this.yt}On(){this.tn.Hn().forEach((t=>{this.mn.get(t)?.kt(),this.wn.get(t)?.kt()})),this.pn.forEach((t=>t.kt())),this.Tn.kt()}Un(t){return t&&!t.yn().Zi()?t.yn():null}An(t,i,n){this.$n(t,i,n)&&this.On()}$n(t,i,n){const s=this.gn,e=this.Mn,r=this.cn,h=this.dn,a=this.yt,l=this.Un(n);this.dn=t,this.gn=isNaN(t)?NaN:this.tn.Et().jt(t),this.yt=n;const o=null!==l?l.Bt():null;return null!==l&&null!==o?(this.cn=i,this.Mn=l.Nt(i,o)):(this.cn=NaN,this.Mn=NaN),s!==this.gn||e!==this.Mn||h!==this.dn||r!==this.cn||a!==this.yt}zn(){const t=this.tn.jn().map((t=>t.Yn().qn())).filter(v),i=0===t.length?null:Math.max(...t);this.dn=null!==i?i:NaN}Wn(t,i,n){let s=t.get(i);return void 0===s&&(s=new N(this,i,n),t.set(i,s)),s}}function q(t){return"left"===t||"right"===t}class Y{constructor(t){this.Zn=new Map,this.Kn=[],this.Xn=t}Gn(t,i){const n=function(t,i){return void 0===t?i:{Jn:Math.max(t.Jn,i.Jn),Qn:t.Qn||i.Qn}}(this.Zn.get(t),i);this.Zn.set(t,n)}ts(){return this.Xn}ns(t){const i=this.Zn.get(t);return void 0===i?{Jn:this.Xn}:{Jn:Math.max(this.Xn,i.Jn),Qn:i.Qn}}ss(){this.es(),this.Kn=[{rs:0}]}hs(t){this.es(),this.Kn=[{rs:1,Ft:t}]}ls(t){this._s(),this.Kn.push({rs:5,Ft:t})}es(){this._s(),this.Kn.push({rs:6})}us(){this.es(),this.Kn=[{rs:4}]}cs(t){this.es(),this.Kn.push({rs:2,Ft:t})}ds(t){this.es(),this.Kn.push({rs:3,Ft:t})}fs(){return this.Kn}ps(t){for(const i of t.Kn)this.vs(i);this.Xn=Math.max(this.Xn,t.Xn),t.Zn.forEach(((t,i)=>{this.Gn(i,t)}))}static ws(){return new Y(2)}static gs(){return new Y(3)}vs(t){switch(t.rs){case 0:this.ss();break;case 1:this.hs(t.Ft);break;case 2:this.cs(t.Ft);break;case 3:this.ds(t.Ft);break;case 4:this.us();break;case 5:this.ls(t.Ft);break;case 6:this._s()}}_s(){const t=this.Kn.findIndex((t=>5===t.rs));-1!==t&&this.Kn.splice(t,1)}}const Z=".";function K(t,i){if(!u(t))return"n/a";if(!c(i))throw new TypeError("invalid length");if(i<0||i>16)throw new TypeError("invalid length");if(0===i)return t.toString();return("0000000000000000"+t.toString()).slice(-i)}class X{constructor(t,i){if(i||(i=1),u(t)&&c(t)||(t=100),t<0)throw new TypeError("invalid base");this.qi=t,this.Ms=i,this.bs()}format(t){const i=t<0?"−":"";return t=Math.abs(t),i+this.xs(t)}bs(){if(this.Ss=0,this.qi>0&&this.Ms>0){let t=this.qi;for(;t>1;)t/=10,this.Ss++}}xs(t){const i=this.qi/this.Ms;let n=Math.floor(t),s="";const e=void 0!==this.Ss?this.Ss:NaN;if(i>1){let r=+(Math.round(t*i)-n*i).toFixed(this.Ss);r>=i&&(r-=i,n+=1),s=Z+K(+r.toFixed(this.Ss)*this.Ms,e)}else n=Math.round(n*i)/i,e>0&&(s=Z+K(0,e));return n.toFixed(0)+s}}class G extends X{constructor(t=100){super(t)}format(t){return`${super.format(t)}%`}}class J{constructor(t){this.Cs=t}format(t){let i="";return t<0&&(i="-",t=-t),t<995?i+this.ys(t):t<999995?i+this.ys(t/1e3)+"K":t<999999995?(t=1e3*Math.round(t/1e3),i+this.ys(t/1e6)+"M"):(t=1e6*Math.round(t/1e6),i+this.ys(t/1e9)+"B")}ys(t){let i;const n=Math.pow(10,this.Cs);return i=(t=Math.round(t*n)/n)>=1e-15&&t<1?t.toFixed(this.Cs).replace(/\.?0+$/,""):String(t),i.replace(/(\.[1-9]*)0+$/,((t,i)=>i))}}const Q=/[2-9]/g;class tt{constructor(t=50){this.ks=0,this.Ps=1,this.Ts=1,this.Rs={},this.Ds=new Map,this.Is=t}Vs(){this.ks=0,this.Ds.clear(),this.Ps=1,this.Ts=1,this.Rs={}}Ii(t,i,n){return this.Es(t,i,n).width}Di(t,i,n){const s=this.Es(t,i,n);return((s.actualBoundingBoxAscent||0)-(s.actualBoundingBoxDescent||0))/2}Es(t,i,n){const s=n||Q,e=String(i).replace(s,"0");if(this.Ds.has(e))return h(this.Ds.get(e)).As;if(this.ks===this.Is){const t=this.Rs[this.Ts];delete this.Rs[this.Ts],this.Ds.delete(t),this.Ts++,this.ks--}t.save(),t.textBaseline="middle";const r=t.measureText(e);return t.restore(),0===r.width&&i.length||(this.Ds.set(e,{As:r,Bs:this.Ps}),this.Rs[this.Ps]=e,this.ks++,this.Ps++),r}}class it{constructor(t){this.zs=null,this.M=null,this.Os="right",this.Ls=t}Ns(t,i,n){this.zs=t,this.M=i,this.Os=n}st(t){null!==this.M&&null!==this.zs&&this.zs.st(t,this.M,this.Ls,this.Os)}}class nt{constructor(t,i,n){this.Ws=t,this.Ls=new tt(50),this.Fs=i,this.L=n,this.W=-1,this.Gt=new it(this.Ls)}Tt(){const t=this.L.Hs(this.Fs);if(null===t)return null;const i=t.Us(this.Fs)?t.$s():this.Fs.Wt();if(null===i)return null;const n=t.js(i);if("overlay"===n)return null;const s=this.L.qs();return s.k!==this.W&&(this.W=s.k,this.Ls.Vs()),this.Gt.Ns(this.Ws.$i(),s,n),this.Gt}}class st extends y{constructor(){super(...arguments),this.qt=null}ht(t){this.qt=t}Ys(t,i){if(!this.qt?.zt)return null;const{ut:n,ct:s,Zs:e}=this.qt;return i>=n-s-7&&i<=n+s+7?{Ks:this.qt,Zs:e}:null}et({context:t,bitmapSize:i,horizontalPixelRatio:n,verticalPixelRatio:r}){if(null===this.qt)return;if(!1===this.qt.zt)return;const h=Math.round(this.qt.ut*r);h<0||h>i.height||(t.lineCap="butt",t.strokeStyle=this.qt.R,t.lineWidth=Math.floor(this.qt.ct*n),s(t,this.qt.Kt),e(t,h,0,i.width))}}class et{constructor(t){this.Xs={ut:0,R:"rgba(0, 0, 0, 0)",ct:1,Kt:0,zt:!1},this.Gs=new st,this.St=!0,this.Js=t,this.Qs=t.Qt(),this.Gs.ht(this.Xs)}kt(){this.St=!0}Tt(){return this.Js.zt()?(this.St&&(this.te(),this.St=!1),this.Gs):null}}class rt extends et{constructor(t){super(t)}te(){this.Xs.zt=!1;const t=this.Js.Wt(),i=t.ie().ie;if(2!==i&&3!==i)return;const n=this.Js.N();if(!n.baseLineVisible||!this.Js.zt())return;const s=this.Js.Bt();null!==s&&(this.Xs.zt=!0,this.Xs.ut=t.Nt(s.Ft,s.Ft),this.Xs.R=n.baseLineColor,this.Xs.ct=n.baseLineWidth,this.Xs.Kt=n.baseLineStyle)}}class ht extends y{constructor(){super(...arguments),this.qt=null}ht(t){this.qt=t}ne(){return this.qt}et({context:t,horizontalPixelRatio:i,verticalPixelRatio:n}){const s=this.qt;if(null===s)return;const e=Math.max(1,Math.floor(i)),r=e%2/2,h=Math.round(s.se.x*i)+r,a=s.se.y*n;t.fillStyle=s.ee,t.beginPath();const l=Math.max(2,1.5*s.re)*i;t.arc(h,a,l,0,2*Math.PI,!1),t.fill(),t.fillStyle=s.he,t.beginPath(),t.arc(h,a,s.ft*i,0,2*Math.PI,!1),t.fill(),t.lineWidth=e,t.strokeStyle=s.ae,t.beginPath(),t.arc(h,a,s.ft*i+e/2,0,2*Math.PI,!1),t.stroke()}}const at=[{le:0,oe:.25,_e:4,ue:10,ce:.25,de:0,fe:.4,pe:.8},{le:.25,oe:.525,_e:10,ue:14,ce:0,de:0,fe:.8,pe:0},{le:.525,oe:1,_e:14,ue:14,ce:0,de:0,fe:0,pe:0}];class lt{constructor(t){this.Gt=new ht,this.St=!0,this.ve=!0,this.me=performance.now(),this.we=this.me-1,this.ge=t}Me(){this.we=this.me-1,this.kt()}be(){if(this.kt(),2===this.ge.N().lastPriceAnimation){const t=performance.now(),i=this.we-t;if(i>0)return void(i<650&&(this.we+=2600));this.me=t,this.we=t+2600}}kt(){this.St=!0}xe(){this.ve=!0}zt(){return 0!==this.ge.N().lastPriceAnimation}Se(){switch(this.ge.N().lastPriceAnimation){case 0:return!1;case 1:return!0;case 2:return performance.now()<=this.we}}Tt(){return this.St?(this.Rt(),this.St=!1,this.ve=!1):this.ve&&(this.Ce(),this.ve=!1),this.Gt}Rt(){this.Gt.ht(null);const t=this.ge.Qt().Et(),i=t.ye(),n=this.ge.Bt();if(null===i||null===n)return;const s=this.ge.ke(!0);if(s.Pe||!i.Te(s.Re))return;const e={x:t.jt(s.Re),y:this.ge.Wt().Nt(s.gt,n.Ft)},r=s.R,h=this.ge.N().lineWidth,a=this.De(this.Ie(),r);this.Gt.ht({ee:r,re:h,he:a.he,ae:a.ae,ft:a.ft,se:e})}Ce(){const t=this.Gt.ne();if(null!==t){const i=this.De(this.Ie(),t.ee);t.he=i.he,t.ae=i.ae,t.ft=i.ft}}Ie(){return this.Se()?performance.now()-this.me:2599}Ve(t,i,n,s){const e=n+(s-n)*i;return this.ge.Qt().Ki().Y(t,e)}De(t,i){const n=t%2600/2600;let s;for(const t of at)if(n>=t.le&&n<=t.oe){s=t;break}r(void 0!==s,"Last price animation internal logic error");const e=(n-s.le)/(s.oe-s.le);return{he:this.Ve(i,e,s.ce,s.de),ae:this.Ve(i,e,s.fe,s.pe),ft:(h=e,a=s._e,l=s.ue,a+(l-a)*h)};var h,a,l}}class ot extends et{constructor(t){super(t)}te(){const t=this.Xs;t.zt=!1;const i=this.Js.N();if(!i.priceLineVisible||!this.Js.zt())return;const n=this.Js.ke(0===i.priceLineSource);n.Pe||(t.zt=!0,t.ut=n.Ei,t.R=this.Js.Ee(n.R),t.ct=i.priceLineWidth,t.Kt=i.priceLineStyle)}}class _t extends L{constructor(t){super(),this.Jt=t}ji(t,i,n){t.zt=!1,i.zt=!1;const s=this.Jt;if(!s.zt())return;const e=s.N(),r=e.lastValueVisible,h=""!==s.Ae(),a=0===e.seriesLastValueMode,l=s.ke(!1);if(l.Pe)return;r&&(t.ri=this.Be(l,r,a),t.zt=0!==t.ri.length),(h||a)&&(i.ri=this.ze(l,r,h,a),i.zt=i.ri.length>0);const o=s.Ee(l.R),_=this.Jt.Qt().Ki().K(o);n.X=_.X,n.Ei=l.Ei,i.Ht=s.Qt().Ut(l.Ei/s.Wt().$t()),t.Ht=o,t.R=_.G,i.R=_.G}ze(t,i,n,s){let e="";const r=this.Jt.Ae();return n&&0!==r.length&&(e+=`${r} `),i&&s&&(e+=this.Jt.Wt().Oe()?t.Le:t.Ne),e.trim()}Be(t,i,n){return i?n?this.Jt.Wt().Oe()?t.Ne:t.Le:t.ri:""}}function ut(t,i,n,s){const e=Number.isFinite(i),r=Number.isFinite(n);return e&&r?t(i,n):e||r?e?i:n:s}class ct{constructor(t,i){this.We=t,this.Fe=i}He(t){return null!==t&&(this.We===t.We&&this.Fe===t.Fe)}Ue(){return new ct(this.We,this.Fe)}$e(){return this.We}je(){return this.Fe}qe(){return this.Fe-this.We}Zi(){return this.Fe===this.We||Number.isNaN(this.Fe)||Number.isNaN(this.We)}ps(t){return null===t?this:new ct(ut(Math.min,this.$e(),t.$e(),-1/0),ut(Math.max,this.je(),t.je(),1/0))}Ye(t){if(!u(t))return;if(0===this.Fe-this.We)return;const i=.5*(this.Fe+this.We);let n=this.Fe-i,s=this.We-i;n*=t,s*=t,this.Fe=i+n,this.We=i+s}Ze(t){u(t)&&(this.Fe+=t,this.We+=t)}Ke(){return{minValue:this.We,maxValue:this.Fe}}static Xe(t){return null===t?null:new ct(t.minValue,t.maxValue)}}class dt{constructor(t,i){this.Ge=t,this.Je=i||null}Qe(){return this.Ge}tr(){return this.Je}Ke(){return{priceRange:null===this.Ge?null:this.Ge.Ke(),margins:this.Je||void 0}}static Xe(t){return null===t?null:new dt(ct.Xe(t.priceRange),t.margins)}}class ft extends et{constructor(t,i){super(t),this.ir=i}te(){const t=this.Xs;t.zt=!1;const i=this.ir.N();if(!this.Js.zt()||!i.lineVisible)return;const n=this.ir.nr();null!==n&&(t.zt=!0,t.ut=n,t.R=i.color,t.ct=i.lineWidth,t.Kt=i.lineStyle,t.Zs=this.ir.N().id)}}class pt extends L{constructor(t,i){super(),this.ge=t,this.ir=i}ji(t,i,n){t.zt=!1,i.zt=!1;const s=this.ir.N(),e=s.axisLabelVisible,r=""!==s.title,h=this.ge;if(!e||!h.zt())return;const a=this.ir.nr();if(null===a)return;r&&(i.ri=s.title,i.zt=!0),i.Ht=h.Qt().Ut(a/h.Wt().$t()),t.ri=this.sr(s.price),t.zt=!0;const l=this.ge.Qt().Ki().K(s.axisLabelColor||s.color);n.X=l.X;const o=s.axisLabelTextColor||l.G;t.R=o,i.R=o,n.Ei=a}sr(t){const i=this.ge.Bt();return null===i?"":this.ge.Wt().Xi(t,i.Ft)}}class vt{constructor(t,i){this.ge=t,this.Sn=i,this.er=new ft(t,this),this.Ws=new pt(t,this),this.rr=new nt(this.Ws,t,t.Qt())}hr(t){_(this.Sn,t),this.kt(),this.ge.Qt().ar()}N(){return this.Sn}lr(){return this.er}_r(){return this.rr}ur(){return this.Ws}kt(){this.er.kt(),this.Ws.kt()}nr(){const t=this.ge,i=t.Wt();if(t.Qt().Et().Zi()||i.Zi())return null;const n=t.Bt();return null===n?null:i.Nt(this.Sn.price,n.Ft)}}class mt extends U{constructor(t){super(),this.tn=t}Qt(){return this.tn}}const wt={Bar:(t,i,n,s)=>{const e=i.upColor,r=i.downColor,h=a(t(n,s)),o=l(h.Ft[0])<=l(h.Ft[3]);return{cr:h.R??(o?e:r)}},Candlestick:(t,i,n,s)=>{const e=i.upColor,r=i.downColor,h=i.borderUpColor,o=i.borderDownColor,_=i.wickUpColor,u=i.wickDownColor,c=a(t(n,s)),d=l(c.Ft[0])<=l(c.Ft[3]);return{cr:c.R??(d?e:r),dr:c.Ht??(d?h:o),pr:c.vr??(d?_:u)}},Custom:(t,i,n,s)=>({cr:a(t(n,s)).R??i.color}),Area:(t,i,n,s)=>{const e=a(t(n,s));return{cr:e.vt??i.lineColor,vt:e.vt??i.lineColor,mr:e.mr??i.topColor,wr:e.wr??i.bottomColor}},Baseline:(t,i,n,s)=>{const e=a(t(n,s));return{cr:e.Ft[3]>=i.baseValue.price?i.topLineColor:i.bottomLineColor,gr:e.gr??i.topLineColor,Mr:e.Mr??i.bottomLineColor,br:e.br??i.topFillColor1,Sr:e.Sr??i.topFillColor2,Cr:e.Cr??i.bottomFillColor1,yr:e.yr??i.bottomFillColor2}},Line:(t,i,n,s)=>{const e=a(t(n,s));return{cr:e.R??i.color,vt:e.R??i.color}},Histogram:(t,i,n,s)=>({cr:a(t(n,s)).R??i.color})};class gt{constructor(t){this.kr=(t,i)=>void 0!==i?i.Ft:this.ge.Yn().Pr(t),this.ge=t,this.Tr=wt[t.Rr()]}Dr(t,i){return this.Tr(this.kr,this.ge.N(),t,i)}}function Mt(t,i,n,s,e=0,r=i.length){let h=r-e;for(;0>1,a=e+r;s(i[a],n)===t?(e=a+1,h-=r+1):h=r}return e}const bt=Mt.bind(null,!0),xt=Mt.bind(null,!1);var St;!function(t){t[t.NearestLeft=-1]="NearestLeft",t[t.None=0]="None",t[t.NearestRight=1]="NearestRight"}(St||(St={}));const Ct=30;class yt{constructor(){this.Ir=[],this.Vr=new Map,this.Er=new Map,this.Ar=[]}Br(){return this.zr()>0?this.Ir[this.Ir.length-1]:null}Or(){return this.zr()>0?this.Lr(0):null}qn(){return this.zr()>0?this.Lr(this.Ir.length-1):null}zr(){return this.Ir.length}Zi(){return 0===this.zr()}Te(t){return null!==this.Nr(t,0)}Pr(t){return this.Wr(t)}Wr(t,i=0){const n=this.Nr(t,i);return null===n?null:{...this.Fr(n),Re:this.Lr(n)}}Hr(){return this.Ir}Ur(t,i,n){if(this.Zi())return null;let s=null;for(const e of n){s=kt(s,this.$r(t,i,e))}return s}ht(t){this.Er.clear(),this.Vr.clear(),this.Ir=t,this.Ar=t.map((t=>t.Re))}jr(){return this.Ar}Lr(t){return this.Ir[t].Re}Fr(t){return this.Ir[t]}Nr(t,i){const n=this.qr(t);if(null===n&&0!==i)switch(i){case-1:return this.Yr(t);case 1:return this.Zr(t);default:throw new TypeError("Unknown search mode")}return n}Yr(t){let i=this.Kr(t);return i>0&&(i-=1),i!==this.Ir.length&&this.Lr(i)t.Ret.Re>i))}Gr(t,i,n){let s=null;for(let e=t;es.Qr&&(s.Qr=t)))}return s}$r(t,i,n){if(this.Zi())return null;let s=null;const e=a(this.Or()),r=a(this.qn()),h=Math.max(t,e),l=Math.min(i,r),o=Math.ceil(h/Ct)*Ct,_=Math.max(o,Math.floor(l/Ct)*Ct);{const t=this.Kr(h),e=this.Xr(Math.min(l,o,i));s=kt(s,this.Gr(t,e,n))}let u=this.Vr.get(n);void 0===u&&(u=new Map,this.Vr.set(n,u));for(let t=Math.max(o+1,h);t<_;t+=Ct){const i=Math.floor(t/Ct);let e=u.get(i);if(void 0===e){const t=this.Kr(i*Ct),s=this.Xr((i+1)*Ct-1);e=this.Gr(t,s,n),u.set(i,e)}s=kt(s,e)}{const t=this.Kr(_),i=this.Xr(l);s=kt(s,this.Gr(t,i,n))}return s}}function kt(t,i){if(null===t)return i;if(null===i)return t;return{Jr:Math.min(t.Jr,i.Jr),Qr:Math.max(t.Qr,i.Qr)}}class Pt{constructor(t){this.th=t}st(t,i,n){this.th.draw(t)}ih(t,i,n){this.th.drawBackground?.(t)}}class Tt{constructor(t){this.Ds=null,this.nh=t}Tt(){const t=this.nh.renderer();if(null===t)return null;if(this.Ds?.sh===t)return this.Ds.eh;const i=new Pt(t);return this.Ds={sh:t,eh:i},i}rh(){return this.nh.zOrder?.()??"normal"}}class Rt{constructor(t){this.hh=null,this.ah=t}oh(){return this.ah}On(){this.ah.updateAllViews?.()}Ln(){const t=this.ah.paneViews?.()??[];if(this.hh?.sh===t)return this.hh.eh;const i=t.map((t=>new Tt(t)));return this.hh={sh:t,eh:i},i}Ys(t,i){return this.ah.hitTest?.(t,i)??null}}let Dt=class extends Rt{_n(){return[]}};class It{constructor(t){this.th=t}st(t,i,n){this.th.draw(t)}ih(t,i,n){this.th.drawBackground?.(t)}}class Vt{constructor(t){this.Ds=null,this.nh=t}Tt(){const t=this.nh.renderer();if(null===t)return null;if(this.Ds?.sh===t)return this.Ds.eh;const i=new It(t);return this.Ds={sh:t,eh:i},i}rh(){return this.nh.zOrder?.()??"normal"}}function Et(t){return{ri:t.text(),Ei:t.coordinate(),Vi:t.fixedCoordinate?.(),R:t.textColor(),X:t.backColor(),zt:t.visible?.()??!0,pi:t.tickVisible?.()??!0}}class At{constructor(t,i){this.Gt=new F,this._h=t,this.uh=i}Tt(){return this.Gt.ht({Qi:this.uh.Qi(),...Et(this._h)}),this.Gt}}class Bt extends L{constructor(t,i){super(),this._h=t,this.qi=i}ji(t,i,n){const s=Et(this._h);n.X=s.X,t.R=s.R;const e=2/12*this.qi.k();n.Ti=e,n.Ri=e,n.Ei=s.Ei,n.Vi=s.Vi,t.ri=s.ri,t.zt=s.zt,t.pi=s.pi}}class zt extends Rt{constructor(t,i){super(t),this.dh=null,this.fh=null,this.ph=null,this.mh=null,this.ge=i}un(){const t=this.ah.timeAxisViews?.()??[];if(this.dh?.sh===t)return this.dh.eh;const i=this.ge.Qt().Et(),n=t.map((t=>new At(t,i)));return this.dh={sh:t,eh:n},n}Nn(){const t=this.ah.priceAxisViews?.()??[];if(this.fh?.sh===t)return this.fh.eh;const i=this.ge.Wt(),n=t.map((t=>new Bt(t,i)));return this.fh={sh:t,eh:n},n}wh(){const t=this.ah.priceAxisPaneViews?.()??[];if(this.ph?.sh===t)return this.ph.eh;const i=t.map((t=>new Vt(t)));return this.ph={sh:t,eh:i},i}gh(){const t=this.ah.timeAxisPaneViews?.()??[];if(this.mh?.sh===t)return this.mh.eh;const i=t.map((t=>new Vt(t)));return this.mh={sh:t,eh:i},i}Mh(t,i){return this.ah.autoscaleInfo?.(t,i)??null}}function Ot(t,i,n,s){t.forEach((t=>{i(t).forEach((t=>{t.rh()===n&&s.push(t)}))}))}function Lt(t){return t.Ln()}function Nt(t){return t.wh()}function Wt(t){return t.gh()}const Ft=["Area","Line","Baseline"];class Ht extends mt{constructor(t,i,n,s,e){super(t),this.qt=new yt,this.er=new ot(this),this.bh=[],this.xh=new rt(this),this.Sh=null,this.Ch=null,this.yh=null,this.kh=[],this.Sn=n,this.Ph=i;const r=new _t(this);this.pn=[r],this.rr=new nt(r,this,t),Ft.includes(this.Ph)&&(this.Sh=new lt(this)),this.Th(),this.nh=s(this,this.Qt(),e)}m(){null!==this.yh&&clearTimeout(this.yh)}Ee(t){return this.Sn.priceLineColor||t}ke(t){const i={Pe:!0},n=this.Wt();if(this.Qt().Et().Zi()||n.Zi()||this.qt.Zi())return i;const s=this.Qt().Et().ye(),e=this.Bt();if(null===s||null===e)return i;let r,h;if(t){const t=this.qt.Br();if(null===t)return i;r=t,h=t.Re}else{const t=this.qt.Wr(s.bi(),-1);if(null===t)return i;if(r=this.qt.Pr(t.Re),null===r)return i;h=t.Re}const a=r.Ft[3],l=this.Rh().Dr(h,{Ft:r}),o=n.Nt(a,e.Ft);return{Pe:!1,gt:a,ri:n.Xi(a,e.Ft),Le:n.Dh(a),Ne:n.Ih(a,e.Ft),R:l.cr,Ei:o,Re:h}}Rh(){return null!==this.Ch||(this.Ch=new gt(this)),this.Ch}N(){return this.Sn}hr(t){const i=t.priceScaleId;void 0!==i&&i!==this.Sn.priceScaleId&&this.Qt().Vh(this,i),_(this.Sn,t),void 0!==t.priceFormat&&(this.Th(),this.Qt().Eh()),this.Qt().Ah(this),this.Qt().Bh(),this.nh.kt("options")}ht(t,i){this.qt.ht(t),this.nh.kt("data"),null!==this.Sh&&(i&&i.zh?this.Sh.be():0===t.length&&this.Sh.Me());const n=this.Qt().Hs(this);this.Qt().Oh(n),this.Qt().Ah(this),this.Qt().Bh(),this.Qt().ar()}Lh(t){const i=new vt(this,t);return this.bh.push(i),this.Qt().Ah(this),i}Nh(t){const i=this.bh.indexOf(t);-1!==i&&this.bh.splice(i,1),this.Qt().Ah(this)}Wh(){return this.bh}Rr(){return this.Ph}Bt(){const t=this.Fh();return null===t?null:{Ft:t.Ft[3],Hh:t.wt}}Fh(){const t=this.Qt().Et().ye();if(null===t)return null;const i=t.Uh();return this.qt.Wr(i,1)}Yn(){return this.qt}$h(t){const i=this.qt.Pr(t);return null===i?null:"Bar"===this.Ph||"Candlestick"===this.Ph||"Custom"===this.Ph?{jh:i.Ft[0],qh:i.Ft[1],Yh:i.Ft[2],Zh:i.Ft[3]}:i.Ft[3]}Kh(t){const i=[];Ot(this.kh,Lt,"top",i);const n=this.Sh;return null!==n&&n.zt()?(null===this.yh&&n.Se()&&(this.yh=setTimeout((()=>{this.yh=null,this.Qt().Xh()}),0)),n.xe(),i.unshift(n),i):i}Ln(){const t=[];this.Gh()||t.push(this.xh),t.push(this.nh,this.er);const i=this.bh.map((t=>t.lr()));return t.push(...i),Ot(this.kh,Lt,"normal",t),t}Jh(){return this.Qh(Lt,"bottom")}ta(t){return this.Qh(Nt,t)}ia(t){return this.Qh(Wt,t)}na(t,i){return this.kh.map((n=>n.Ys(t,i))).filter((t=>null!==t))}_n(){return[this.rr,...this.bh.map((t=>t._r()))]}Nn(t,i){if(i!==this.en&&!this.Gh())return[];const n=[...this.pn];for(const t of this.bh)n.push(t.ur());return this.kh.forEach((t=>{n.push(...t.Nn())})),n}un(){const t=[];return this.kh.forEach((i=>{t.push(...i.un())})),t}Mh(t,i){if(void 0!==this.Sn.autoscaleInfoProvider){const n=this.Sn.autoscaleInfoProvider((()=>{const n=this.sa(t,i);return null===n?null:n.Ke()}));return dt.Xe(n)}return this.sa(t,i)}ea(){return this.Sn.priceFormat.minMove}ra(){return this.ha}On(){this.nh.kt();for(const t of this.pn)t.kt();for(const t of this.bh)t.kt();this.er.kt(),this.xh.kt(),this.Sh?.kt(),this.kh.forEach((t=>t.On()))}Wt(){return a(super.Wt())}At(t){if(!(("Line"===this.Ph||"Area"===this.Ph||"Baseline"===this.Ph)&&this.Sn.crosshairMarkerVisible))return null;const i=this.qt.Pr(t);if(null===i)return null;return{gt:i.Ft[3],ft:this.aa(),Ht:this.la(),Lt:this.oa(),Ot:this._a(t)}}Ae(){return this.Sn.title}zt(){return this.Sn.visible}ua(t){this.kh.push(new zt(t,this))}ca(t){this.kh=this.kh.filter((i=>i.oh()!==t))}da(){if("Custom"===this.Ph)return t=>this.nh.fa(t)}pa(){if("Custom"===this.Ph)return t=>this.nh.va(t)}ma(){return this.qt.jr()}Gh(){return!q(this.Wt().wa())}sa(t,i){if(!c(t)||!c(i)||this.qt.Zi())return null;const n="Line"===this.Ph||"Area"===this.Ph||"Baseline"===this.Ph||"Histogram"===this.Ph?[3]:[2,1],s=this.qt.Ur(t,i,n);let e=null!==s?new ct(s.Jr,s.Qr):null,r=null;if("Histogram"===this.Rr()){const t=this.Sn.base,i=new ct(t,t);e=null!==e?e.ps(i):i}return this.kh.forEach((n=>{const s=n.Mh(t,i);if(s?.priceRange){const t=new ct(s.priceRange.minValue,s.priceRange.maxValue);e=null!==e?e.ps(t):t}s?.margins&&(r=s.margins)})),new dt(e,r)}aa(){switch(this.Ph){case"Line":case"Area":case"Baseline":return this.Sn.crosshairMarkerRadius}return 0}la(){switch(this.Ph){case"Line":case"Area":case"Baseline":{const t=this.Sn.crosshairMarkerBorderColor;if(0!==t.length)return t}}return null}oa(){switch(this.Ph){case"Line":case"Area":case"Baseline":return this.Sn.crosshairMarkerBorderWidth}return 0}_a(t){switch(this.Ph){case"Line":case"Area":case"Baseline":{const t=this.Sn.crosshairMarkerBackgroundColor;if(0!==t.length)return t}}return this.Rh().Dr(t).cr}Th(){switch(this.Sn.priceFormat.type){case"custom":this.ha={format:this.Sn.priceFormat.formatter};break;case"volume":this.ha=new J(this.Sn.priceFormat.precision);break;case"percent":this.ha=new G(this.Sn.priceFormat.precision);break;default:{const t=Math.pow(10,this.Sn.priceFormat.precision);this.ha=new X(t,this.Sn.priceFormat.minMove*t)}}null!==this.en&&this.en.ga()}Qh(t,i){const n=[];return Ot(this.kh,t,i,n),n}}class Ut{constructor(t){this.Sn=t}Ma(t,i,n){let s=t;if(0===this.Sn.mode)return s;const e=n.yn(),r=e.Bt();if(null===r)return s;const h=e.Nt(t,r),a=n.ba().filter((t=>t instanceof Ht)).reduce(((t,s)=>{if(n.Us(s)||!s.zt())return t;const e=s.Wt(),r=s.Yn();if(e.Zi()||!r.Te(i))return t;const h=r.Pr(i);if(null===h)return t;const a=l(s.Bt());return t.concat([e.Nt(h.Ft[3],a.Ft)])}),[]);if(0===a.length)return s;a.sort(((t,i)=>Math.abs(t-h)-Math.abs(i-h)));const o=a[0];return s=e.kn(o,r),s}}class $t extends y{constructor(){super(...arguments),this.qt=null}ht(t){this.qt=t}et({context:t,bitmapSize:i,horizontalPixelRatio:n,verticalPixelRatio:e}){if(null===this.qt)return;const r=Math.max(1,Math.floor(n));t.lineWidth=r,function(t,i){t.save(),t.lineWidth%2&&t.translate(.5,.5),i(),t.restore()}(t,(()=>{const h=a(this.qt);if(h.xa){t.strokeStyle=h.Sa,s(t,h.Ca),t.beginPath();for(const s of h.ya){const e=Math.round(s.ka*n);t.moveTo(e,-r),t.lineTo(e,i.height+r)}t.stroke()}if(h.Pa){t.strokeStyle=h.Ta,s(t,h.Ra),t.beginPath();for(const n of h.Da){const s=Math.round(n.ka*e);t.moveTo(-r,s),t.lineTo(i.width+r,s)}t.stroke()}}))}}class jt{constructor(t){this.Gt=new $t,this.St=!0,this.yt=t}kt(){this.St=!0}Tt(){if(this.St){const t=this.yt.Qt().N().grid,i={Pa:t.horzLines.visible,xa:t.vertLines.visible,Ta:t.horzLines.color,Sa:t.vertLines.color,Ra:t.horzLines.style,Ca:t.vertLines.style,Da:this.yt.yn().Ia(),ya:(this.yt.Qt().Et().Ia()||[]).map((t=>({ka:t.coord})))};this.Gt.ht(i),this.St=!1}return this.Gt}}class qt{constructor(t){this.nh=new jt(t)}lr(){return this.nh}}const Yt={Va:4,Ea:1e-4};function Zt(t,i){const n=100*(t-i)/i;return i<0?-n:n}function Kt(t,i){const n=Zt(t.$e(),i),s=Zt(t.je(),i);return new ct(n,s)}function Xt(t,i){const n=100*(t-i)/i+100;return i<0?-n:n}function Gt(t,i){const n=Xt(t.$e(),i),s=Xt(t.je(),i);return new ct(n,s)}function Jt(t,i){const n=Math.abs(t);if(n<1e-15)return 0;const s=Math.log10(n+i.Ea)+i.Va;return t<0?-s:s}function Qt(t,i){const n=Math.abs(t);if(n<1e-15)return 0;const s=Math.pow(10,n-i.Va)-i.Ea;return t<0?-s:s}function ti(t,i){if(null===t)return null;const n=Jt(t.$e(),i),s=Jt(t.je(),i);return new ct(n,s)}function ii(t,i){if(null===t)return null;const n=Qt(t.$e(),i),s=Qt(t.je(),i);return new ct(n,s)}function ni(t){if(null===t)return Yt;const i=Math.abs(t.je()-t.$e());if(i>=1||i<1e-15)return Yt;const n=Math.ceil(Math.abs(Math.log10(i))),s=Yt.Va+n;return{Va:s,Ea:1/Math.pow(10,s)}}function si(t,i,n){return Math.min(Math.max(t,i),n)}function ei(t,i,n){return i-t<=n}function ri(t){const i=Math.ceil(t);return i%2==0?i-1:i}class hi{constructor(t,i){if(this.Aa=t,this.Ba=i,function(t){if(t<0)return!1;for(let i=t;i>1;i/=10)if(i%10!=0)return!1;return!0}(this.Aa))this.za=[2,2.5,2];else{this.za=[];for(let t=this.Aa;1!==t;){if(t%2==0)this.za.push(2),t/=2;else{if(t%5!=0)throw new Error("unexpected base");this.za.push(2,2.5),t/=5}if(this.za.length>100)throw new Error("something wrong with base")}}}Oa(t,i,n){const s=0===this.Aa?0:1/this.Aa;let e=Math.pow(10,Math.max(0,Math.ceil(Math.log10(t-i)))),r=0,h=this.Ba[0];for(;;){const t=ei(e,s,1e-14)&&e>s+1e-14,i=ei(e,n*h,1e-14),a=ei(e,1,1e-14);if(!(t&&i&&a))break;e/=h,h=this.Ba[++r%this.Ba.length]}if(e<=s+1e-14&&(e=s),e=Math.max(1,e),this.za.length>0&&(a=e,l=1,o=1e-14,Math.abs(a-l)s+1e-14;)e/=h,h=this.za[++r%this.za.length];var a,l,o;return e}}class ai{constructor(t,i,n,s){this.La=[],this.qi=t,this.Aa=i,this.Na=n,this.Wa=s}Oa(t,i){if(t=o?1:-1;let d=null,f=0;for(let n=l-u;n>o;n-=_){const s=this.Wa(n,i,!0);null!==d&&Math.abs(s-d)a||(fa(t.hn())-a(i.hn())))}var oi;!function(t){t[t.Normal=0]="Normal",t[t.Logarithmic=1]="Logarithmic",t[t.Percentage=2]="Percentage",t[t.IndexedTo100=3]="IndexedTo100"}(oi||(oi={}));const _i=new G,ui=new X(100,1);class ci{constructor(t,i,n,s,e){this.Ya=0,this.Za=null,this.Ge=null,this.Ka=null,this.Xa={Ga:!1,Ja:null},this.Qa=0,this.tl=0,this.il=new o,this.nl=new o,this.sl=[],this.el=null,this.rl=null,this.hl=null,this.al=null,this.ha=ui,this.ll=ni(null),this.ol=t,this.Sn=i,this._l=n,this.ul=s,this.cl=e,this.dl=new ai(this,100,this.fl.bind(this),this.pl.bind(this))}wa(){return this.ol}N(){return this.Sn}hr(t){if(_(this.Sn,t),this.ga(),void 0!==t.mode&&this.vl({ie:t.mode}),void 0!==t.scaleMargins){const i=h(t.scaleMargins.top),n=h(t.scaleMargins.bottom);if(i<0||i>1)throw new Error(`Invalid top margin - expect value between 0 and 1, given=${i}`);if(n<0||n>1)throw new Error(`Invalid bottom margin - expect value between 0 and 1, given=${n}`);if(i+n>1)throw new Error(`Invalid margins - sum of margins must be less than 1, given=${i+n}`);this.ml(),this.rl=null}}wl(){return this.Sn.autoScale}qa(){return 1===this.Sn.mode}Oe(){return 2===this.Sn.mode}gl(){return 3===this.Sn.mode}ie(){return{Qn:this.Sn.autoScale,Ml:this.Sn.invertScale,ie:this.Sn.mode}}vl(t){const i=this.ie();let n=null;void 0!==t.Qn&&(this.Sn.autoScale=t.Qn),void 0!==t.ie&&(this.Sn.mode=t.ie,2!==t.ie&&3!==t.ie||(this.Sn.autoScale=!0),this.Xa.Ga=!1),1===i.ie&&t.ie!==i.ie&&(!function(t,i){if(null===t)return!1;const n=Qt(t.$e(),i),s=Qt(t.je(),i);return isFinite(n)&&isFinite(s)}(this.Ge,this.ll)?this.Sn.autoScale=!0:(n=ii(this.Ge,this.ll),null!==n&&this.bl(n))),1===t.ie&&t.ie!==i.ie&&(n=ti(this.Ge,this.ll),null!==n&&this.bl(n));const s=i.ie!==this.Sn.mode;s&&(2===i.ie||this.Oe())&&this.ga(),s&&(3===i.ie||this.gl())&&this.ga(),void 0!==t.Ml&&i.Ml!==t.Ml&&(this.Sn.invertScale=t.Ml,this.xl()),this.nl.p(i,this.ie())}Sl(){return this.nl}k(){return this._l.fontSize}$t(){return this.Ya}Cl(t){this.Ya!==t&&(this.Ya=t,this.ml(),this.rl=null)}yl(){if(this.Za)return this.Za;const t=this.$t()-this.kl()-this.Pl();return this.Za=t,t}Qe(){return this.Tl(),this.Ge}bl(t,i){const n=this.Ge;(i||null===n&&null!==t||null!==n&&!n.He(t))&&(this.rl=null,this.Ge=t)}Zi(){return this.Tl(),0===this.Ya||!this.Ge||this.Ge.Zi()}Rl(t){return this.Ml()?t:this.$t()-1-t}Nt(t,i){return this.Oe()?t=Zt(t,i):this.gl()&&(t=Xt(t,i)),this.pl(t,i)}Dl(t,i,n){this.Tl();const s=this.Pl(),e=a(this.Qe()),r=e.$e(),h=e.je(),l=this.yl()-1,o=this.Ml(),_=l/(h-r),u=void 0===n?0:n.from,c=void 0===n?t.length:n.to,d=this.Il();for(let n=u;nt.On()))}ga(){this.rl=null;const t=this.Xl();let i=100;null!==t&&(i=Math.round(1/t.ea())),this.ha=ui,this.Oe()?(this.ha=_i,i=100):this.gl()?(this.ha=new X(100,1),i=100):null!==t&&(this.ha=t.ra()),this.dl=new ai(this,i,this.fl.bind(this),this.pl.bind(this)),this.dl.Ha()}Nl(){this.el=null}Ki(){return this.cl}Xl(){return this.sl[0]||null}kl(){return this.Ml()?this.Sn.scaleMargins.bottom*this.$t()+this.tl:this.Sn.scaleMargins.top*this.$t()+this.Qa}Pl(){return this.Ml()?this.Sn.scaleMargins.top*this.$t()+this.Qa:this.Sn.scaleMargins.bottom*this.$t()+this.tl}Tl(){this.Xa.Ga||(this.Xa.Ga=!0,this.Ql())}ml(){this.Za=null}pl(t,i){if(this.Tl(),this.Zi())return 0;t=this.qa()&&t?Jt(t,this.ll):t;const n=a(this.Qe()),s=this.Pl()+(this.yl()-1)*(t-n.$e())/n.qe();return this.Rl(s)}fl(t,i){if(this.Tl(),this.Zi())return 0;const n=this.Rl(t),s=a(this.Qe()),e=s.$e()+s.qe()*((n-this.Pl())/(this.yl()-1));return this.qa()?Qt(e,this.ll):e}xl(){this.rl=null,this.dl.Ha()}Ql(){const t=this.Xa.Ja;if(null===t)return;let i=null;const n=this.Gl();let s=0,e=0;for(const r of n){if(!r.zt())continue;const n=r.Bt();if(null===n)continue;const h=r.Mh(t.Uh(),t.bi());let l=h&&h.Qe();if(null!==l){switch(this.Sn.mode){case 1:l=ti(l,this.ll);break;case 2:l=Kt(l,n.Ft);break;case 3:l=Gt(l,n.Ft)}if(i=null===i?l:i.ps(a(l)),null!==h){const t=h.tr();null!==t&&(s=Math.max(s,t.above),e=Math.max(e,t.below))}}}if(s===this.Qa&&e===this.tl||(this.Qa=s,this.tl=e,this.rl=null,this.ml()),null!==i){if(i.$e()===i.je()){const t=this.Xl(),n=5*(null===t||this.Oe()||this.gl()?1:t.ea());this.qa()&&(i=ii(i,this.ll)),i=new ct(i.$e()-n,i.je()+n),this.qa()&&(i=ti(i,this.ll))}if(this.qa()){const t=ii(i,this.ll),n=ni(t);if(r=n,h=this.ll,r.Va!==h.Va||r.Ea!==h.Ea){const s=null!==this.Ka?ii(this.Ka,this.ll):null;this.ll=n,i=ti(t,n),null!==s&&(this.Ka=ti(s,n))}}this.bl(i)}else null===this.Ge&&(this.bl(new ct(-.5,.5)),this.ll=ni(null));var r,h;this.Xa.Ga=!0}Il(){return this.Oe()?Zt:this.gl()?Xt:this.qa()?t=>Jt(t,this.ll):null}io(t,i,n){return void 0===i?(void 0===n&&(n=this.ra()),n.format(t)):i(t)}sr(t,i){return this.io(t,this.ul.priceFormatter,i)}Kl(t,i){return this.io(t,this.ul.percentageFormatter,i)}}function di(t){return t instanceof Ht}class fi{constructor(t,i){this.sl=[],this.no=new Map,this.Ya=0,this.so=0,this.eo=1e3,this.el=null,this.ro=new o,this.kh=[],this.uh=t,this.tn=i,this.ho=new qt(this);const n=i.N();this.ao=this.lo("left",n.leftPriceScale),this.oo=this.lo("right",n.rightPriceScale),this.ao.Sl().i(this._o.bind(this,this.ao),this),this.oo.Sl().i(this._o.bind(this,this.oo),this),this.uo(n)}uo(t){if(t.leftPriceScale&&this.ao.hr(t.leftPriceScale),t.rightPriceScale&&this.oo.hr(t.rightPriceScale),t.localization&&(this.ao.ga(),this.oo.ga()),t.overlayPriceScales){const i=Array.from(this.no.values());for(const n of i){const i=a(n[0].Wt());i.hr(t.overlayPriceScales),t.localization&&i.ga()}}}co(t){switch(t){case"left":return this.ao;case"right":return this.oo}return this.no.has(t)?h(this.no.get(t))[0].Wt():null}m(){this.Qt().do().u(this),this.ao.Sl().u(this),this.oo.Sl().u(this),this.sl.forEach((t=>{t.m&&t.m()})),this.kh=this.kh.filter((t=>{const i=t.oh();return i.detached&&i.detached(),!1})),this.ro.p()}fo(){return this.eo}po(t){this.eo=t}Qt(){return this.tn}Qi(){return this.so}$t(){return this.Ya}vo(t){this.so=t,this.mo()}Cl(t){this.Ya=t,this.ao.Cl(t),this.oo.Cl(t),this.sl.forEach((i=>{if(this.Us(i)){const n=i.Wt();null!==n&&n.Cl(t)}})),this.mo()}wo(){return this.sl.filter(di)}ba(){return this.sl}Us(t){const i=t.Wt();return null===i||this.ao!==i&&this.oo!==i}Ll(t,i,n){const s=void 0!==n?n:this.bo().Mo+1;this.xo(t,i,s)}Wl(t){const i=this.sl.indexOf(t);r(-1!==i,"removeDataSource: invalid data source"),this.sl.splice(i,1);const n=a(t.Wt()).wa();if(this.no.has(n)){const i=h(this.no.get(n)),s=i.indexOf(t);-1!==s&&(i.splice(s,1),0===i.length&&this.no.delete(n))}const s=t.Wt();s&&s.ba().indexOf(t)>=0&&s.Wl(t),null!==s&&(s.Nl(),this.So(s)),this.el=null}js(t){return t===this.ao?"left":t===this.oo?"right":"overlay"}Co(){return this.ao}yo(){return this.oo}ko(t,i){t.Ul(i)}Po(t,i){t.$l(i),this.mo()}To(t){t.jl()}Ro(t,i){t.ql(i)}Do(t,i){t.Yl(i),this.mo()}Io(t){t.Zl()}mo(){this.sl.forEach((t=>{t.On()}))}yn(){let t=null;return this.tn.N().rightPriceScale.visible&&0!==this.oo.ba().length?t=this.oo:this.tn.N().leftPriceScale.visible&&0!==this.ao.ba().length?t=this.ao:0!==this.sl.length&&(t=this.sl[0].Wt()),null===t&&(t=this.oo),t}$s(){let t=null;return this.tn.N().rightPriceScale.visible?t=this.oo:this.tn.N().leftPriceScale.visible&&(t=this.ao),t}So(t){null!==t&&t.wl()&&this.Vo(t)}Eo(t){const i=this.uh.ye();t.vl({Qn:!0}),null!==i&&t.Jl(i),this.mo()}Ao(){this.Vo(this.ao),this.Vo(this.oo)}Bo(){this.So(this.ao),this.So(this.oo),this.sl.forEach((t=>{this.Us(t)&&this.So(t.Wt())})),this.mo(),this.tn.ar()}Dt(){return null===this.el&&(this.el=li(this.sl)),this.el}It(){return this.Dt().filter(di)}zo(){return this.ro}Oo(){return this.ho}ua(t){this.kh.push(new Dt(t))}ca(t){this.kh=this.kh.filter((i=>i.oh()!==t)),t.detached&&t.detached(),this.tn.ar()}Lo(){return this.kh}na(t,i){return this.kh.map((n=>n.Ys(t,i))).filter((t=>null!==t))}Vo(t){const i=t.Gl();if(i&&i.length>0&&!this.uh.Zi()){const i=this.uh.ye();null!==i&&t.Jl(i)}t.On()}bo(){const t=this.Dt();if(0===t.length)return{No:0,Mo:0};let i=0,n=0;for(let s=0;sn&&(n=e))}return{No:i,Mo:n}}xo(t,i,n){let s=this.co(i);if(null===s&&(s=this.lo(i,this.tn.N().overlayPriceScales)),this.sl.push(t),!q(i)){const n=this.no.get(i)||[];n.push(t),this.no.set(i,n)}s.Ll(t),t.ln(s),t.an(n),this.So(s),this.el=null}_o(t,i,n){i.ie!==n.ie&&this.Vo(t)}lo(t,i){const n={visible:!0,autoScale:!0,...p(i)},s=new ci(t,n,this.tn.N().layout,this.tn.N().localization,this.tn.Ki());return s.Cl(this.$t()),s}}function pi(t){return{Wo:t.Wo,Fo:{Zs:t.Ho.externalId},Uo:t.Ho.cursorStyle}}function vi(t,i,n,s){for(const e of t){const t=e.Tt(s);if(null!==t&&t.Ys){const s=t.Ys(i,n);if(null!==s)return{$o:e,Fo:s}}}return null}function mi(t){return void 0!==t.Ln}function wi(t,i,n){const s=[t,...t.Dt()],e=function(t,i,n){let s,e;for(const a of t){const t=a.na?.(i,n)??[];for(const i of t)r=i.zOrder,h=s?.zOrder,(!h||"top"===r&&"top"!==h||"normal"===r&&"bottom"===h)&&(s=i,e=a)}var r,h;return s&&e?{Ho:s,Wo:e}:null}(s,i,n);if("top"===e?.Ho.zOrder)return pi(e);for(const r of s){if(e&&e.Wo===r&&"bottom"!==e.Ho.zOrder&&!e.Ho.isBackground)return pi(e);if(mi(r)){const s=vi(r.Ln(t),i,n,t);if(null!==s)return{Wo:r,$o:s.$o,Fo:s.Fo}}if(e&&e.Wo===r&&"bottom"!==e.Ho.zOrder&&e.Ho.isBackground)return pi(e)}return e?.Ho?pi(e):null}class gi{constructor(t,i,n=50){this.ks=0,this.Ps=1,this.Ts=1,this.Ds=new Map,this.Rs=new Map,this.jo=t,this.qo=i,this.Is=n}Yo(t){const i=t.time,n=this.qo.cacheKey(i),s=this.Ds.get(n);if(void 0!==s)return s.Zo;if(this.ks===this.Is){const t=this.Rs.get(this.Ts);this.Rs.delete(this.Ts),this.Ds.delete(h(t)),this.Ts++,this.ks--}const e=this.jo(t);return this.Ds.set(n,{Zo:e,Bs:this.Ps}),this.Rs.set(this.Ps,n),this.ks++,this.Ps++,e}}class Mi{constructor(t,i){r(t<=i,"right should be >= left"),this.Ko=t,this.Xo=i}Uh(){return this.Ko}bi(){return this.Xo}Go(){return this.Xo-this.Ko+1}Te(t){return this.Ko<=t&&t<=this.Xo}He(t){return this.Ko===t.Uh()&&this.Xo===t.bi()}}function bi(t,i){return null===t||null===i?t===i:t.He(i)}class xi{constructor(){this.Jo=new Map,this.Ds=null,this.Qo=!1}t_(t){this.Qo=t,this.Ds=null}i_(t,i){this.n_(i),this.Ds=null;for(let n=i;n{t<=n[0].index?i.push(s):n.splice(bt(n,t,(i=>i.index!i||n.has(t.index);for(const i of Array.from(this.Jo.keys()).sort(((t,i)=>i-t))){if(!this.Jo.get(i))continue;const n=s;s=[];const r=n.length;let a=0;const l=h(this.Jo.get(i)),o=l.length;let _=1/0,u=-1/0;for(let i=0;i=t&&o-u>=t&&e(h))s.push(h),u=o;else if(this.Qo)return n}for(;ai.weight?t:i}class yi{constructor(t,i,n,s){this.so=0,this.c_=null,this.d_=[],this.al=null,this.hl=null,this.f_=new xi,this.p_=new Map,this.v_=Si.u_(),this.m_=!0,this.w_=new o,this.g_=new o,this.M_=new o,this.b_=null,this.x_=null,this.S_=new Map,this.C_=-1,this.y_=[],this.Sn=i,this.ul=n,this.k_=i.rightOffset,this.P_=i.barSpacing,this.tn=t,this.qo=s,this.T_(),this.f_.t_(i.uniformDistribution),this.R_()}N(){return this.Sn}D_(t){_(this.ul,t),this.I_(),this.T_()}hr(t,i){_(this.Sn,t),this.Sn.fixLeftEdge&&this.V_(),this.Sn.fixRightEdge&&this.E_(),void 0!==t.barSpacing&&this.tn.cs(t.barSpacing),void 0!==t.rightOffset&&this.tn.ds(t.rightOffset),void 0===t.minBarSpacing&&void 0===t.maxBarSpacing||this.tn.cs(t.barSpacing??this.P_),void 0!==t.ignoreWhitespaceIndices&&t.ignoreWhitespaceIndices!==this.Sn.ignoreWhitespaceIndices&&this.R_(),this.I_(),this.T_(),this.M_.p()}Pn(t){return this.d_[t]?.time??null}nn(t){return this.d_[t]??null}A_(t,i){if(this.d_.length<1)return null;if(this.qo.key(t)>this.qo.key(this.d_[this.d_.length-1].time))return i?this.d_.length-1:null;const n=bt(this.d_,this.qo.key(t),((t,i)=>this.qo.key(t.time)0}ye(){return this.z_(),this.v_.o_()}O_(){return this.z_(),this.v_.__()}L_(){const t=this.ye();if(null===t)return null;const i={from:t.Uh(),to:t.bi()};return this.N_(i)}N_(t){const i=Math.round(t.from),n=Math.round(t.to),s=a(this.W_()),e=a(this.F_());return{from:a(this.nn(Math.max(s,i))),to:a(this.nn(Math.min(e,n)))}}H_(t){return{from:a(this.A_(t.from,!0)),to:a(this.A_(t.to,!0))}}Qi(){return this.so}vo(t){if(!isFinite(t)||t<=0)return;if(this.so===t)return;const i=this.O_(),n=this.so;if(this.so=t,this.m_=!0,this.Sn.lockVisibleTimeRangeOnResize&&0!==n){const i=this.P_*t/n;this.P_=i}if(this.Sn.fixLeftEdge&&null!==i&&i.Uh()<=0){const i=n-t;this.k_-=Math.round(i/this.P_)+1,this.m_=!0}this.U_(),this.j_()}jt(t){if(this.Zi()||!c(t))return 0;const i=this.q_()+this.k_-t;return this.so-(i+.5)*this.P_-1}Y_(t,i){const n=this.q_(),s=void 0===i?0:i.from,e=void 0===i?t.length:i.to;for(let i=s;ii/2&&!_?n.needAlignCoordinate=!1:n.needAlignCoordinate=u&&t.index<=l||c&&t.index>=o,d++}return this.y_.length=d,this.x_=this.y_,this.y_}eu(){this.m_=!0,this.cs(this.Sn.barSpacing),this.ds(this.Sn.rightOffset)}ru(t){this.m_=!0,this.c_=t,this.j_(),this.V_()}hu(t,i){const n=this.K_(t),s=this.Q_(),e=s+i*(s/10);this.cs(e),this.Sn.rightBarStaysOnScroll||this.ds(this.iu()+(n-this.K_(t)))}Ul(t){this.al&&this.Zl(),null===this.hl&&null===this.b_&&(this.Zi()||(this.hl=t,this.au()))}$l(t){if(null===this.b_)return;const i=si(this.so-t,0,this.so),n=si(this.so-a(this.hl),0,this.so);0!==i&&0!==n&&this.cs(this.b_.Q_*i/n)}jl(){null!==this.hl&&(this.hl=null,this.lu())}ql(t){null===this.al&&null===this.b_&&(this.Zi()||(this.al=t,this.au()))}Yl(t){if(null===this.al)return;const i=(this.al-t)/this.Q_();this.k_=a(this.b_).iu+i,this.m_=!0,this.j_()}Zl(){null!==this.al&&(this.al=null,this.lu())}ou(){this._u(this.Sn.rightOffset)}_u(t,i=400){if(!isFinite(t))throw new RangeError("offset is required and must be finite number");if(!isFinite(i)||i<=0)throw new RangeError("animationDuration (optional) must be finite positive number");const n=this.k_,s=performance.now();this.tn.ls({uu:t=>(t-s)/i>=1,cu:e=>{const r=(e-s)/i;return r>=1?t:n+(t-n)*r}})}kt(t,i){this.m_=!0,this.d_=t,this.f_.i_(t,i),this.j_()}du(){return this.w_}fu(){return this.g_}pu(){return this.M_}q_(){return this.c_||0}vu(t){const i=t.Go();this.tu(this.so/i),this.k_=t.bi()-this.q_(),this.j_(),this.m_=!0,this.tn.J_(),this.tn.ar()}mu(){const t=this.W_(),i=this.F_();null!==t&&null!==i&&this.vu(new Mi(t,i+this.Sn.rightOffset))}wu(t){const i=new Mi(t.from,t.to);this.vu(i)}sn(t){return void 0!==this.ul.timeFormatter?this.ul.timeFormatter(t.originalTime):this.qo.formatHorzItem(t.time)}R_(){if(!this.Sn.ignoreWhitespaceIndices)return;this.S_.clear();const t=this.tn.jn();for(const i of t)for(const t of i.ma())this.S_.set(t,!0);this.C_++}nu(){const t=this.tn.N().handleScroll,i=this.tn.N().handleScale;return!(t.horzTouchDrag||t.mouseWheel||t.pressedMouseMove||t.vertTouchDrag||i.axisDoubleClickReset.time||i.axisPressedMouseMove.time||i.mouseWheel||i.pinch)}W_(){return 0===this.d_.length?null:0}F_(){return 0===this.d_.length?null:this.d_.length-1}gu(t){return(this.so-1-t)/this.P_}K_(t){const i=this.gu(t),n=this.q_()+this.k_-i;return Math.round(1e6*n)/1e6}tu(t){const i=this.P_;this.P_=t,this.U_(),i!==this.P_&&(this.m_=!0,this.Mu())}z_(){if(!this.m_)return;if(this.m_=!1,this.Zi())return void this.bu(Si.u_());const t=this.q_(),i=this.so/this.P_,n=this.k_+t,s=new Mi(n-i+1,n);this.bu(new Si(s))}U_(){const t=si(this.P_,this.xu(),this.Su());this.P_!==t&&(this.P_=t,this.m_=!0)}Su(){return this.Sn.maxBarSpacing>0?this.Sn.maxBarSpacing:.5*this.so}xu(){return this.Sn.fixLeftEdge&&this.Sn.fixRightEdge&&0!==this.d_.length?this.so/this.d_.length:this.Sn.minBarSpacing}j_(){const t=this.Cu();null!==t&&this.k_i&&(this.k_=i,this.m_=!0)}Cu(){const t=this.W_(),i=this.c_;if(null===t||null===i)return null;return t-i-1+(this.Sn.fixLeftEdge?this.so/this.P_:Math.min(2,this.d_.length))}yu(){return this.Sn.fixRightEdge?0:this.so/this.P_-Math.min(2,this.d_.length)}au(){this.b_={Q_:this.Q_(),iu:this.iu()}}lu(){this.b_=null}su(t){let i=this.p_.get(t.weight);return void 0===i&&(i=new gi((t=>this.ku(t)),this.qo),this.p_.set(t.weight,i)),i.Yo(t)}ku(t){return this.qo.formatTickmark(t,this.ul)}bu(t){const i=this.v_;this.v_=t,bi(i.o_(),this.v_.o_())||this.w_.p(),bi(i.__(),this.v_.__())||this.g_.p(),this.Mu()}Mu(){this.x_=null}I_(){this.Mu(),this.p_.clear()}T_(){this.qo.updateFormatter(this.ul)}V_(){if(!this.Sn.fixLeftEdge)return;const t=this.W_();if(null===t)return;const i=this.ye();if(null===i)return;const n=i.Uh()-t;if(n<0){const t=this.k_-n-1;this.ds(t)}this.U_()}E_(){this.j_(),this.U_()}X_(t){return!this.Sn.ignoreWhitespaceIndices||(this.S_.get(t)||!1)}G_(t){const i=function*(t){const i=Math.round(t),n=in)break}return t}}var ki,Pi,Ti,Ri,Di;!function(t){t[t.OnTouchEnd=0]="OnTouchEnd",t[t.OnNextTap=1]="OnNextTap"}(ki||(ki={}));class Ii{constructor(t,i,n){this.Pu=[],this.Tu=[],this.so=0,this.Ru=null,this.Du=new o,this.Iu=new o,this.Vu=null,this.Eu=t,this.Sn=i,this.qo=n,this.cl=new S(this.Sn.layout.colorParsers),this.Au=new M(this),this.uh=new yi(this,i.timeScale,this.Sn.localization,n),this.Ct=new j(this,i.crosshair),this.Bu=new Ut(i.crosshair),this.zu(0),this.Pu[0].po(2e3),this.Ou=this.Lu(0),this.Nu=this.Lu(1)}Eh(){this.Wu(Y.gs())}ar(){this.Wu(Y.ws())}Xh(){this.Wu(new Y(1))}Ah(t){const i=this.Fu(t);this.Wu(i)}Hu(){return this.Ru}Uu(t){if(this.Ru?.Wo===t?.Wo&&this.Ru?.Fo?.Zs===t?.Fo?.Zs)return;const i=this.Ru;this.Ru=t,null!==i&&this.Ah(i.Wo),null!==t&&t.Wo!==i?.Wo&&this.Ah(t.Wo)}N(){return this.Sn}hr(t){_(this.Sn,t),this.Pu.forEach((i=>i.uo(t))),void 0!==t.timeScale&&this.uh.hr(t.timeScale),void 0!==t.localization&&this.uh.D_(t.localization),(t.leftPriceScale||t.rightPriceScale)&&this.Du.p(),this.Ou=this.Lu(0),this.Nu=this.Lu(1),this.Eh()}$u(t,i){if("left"===t)return void this.hr({leftPriceScale:i});if("right"===t)return void this.hr({rightPriceScale:i});const n=this.ju(t);null!==n&&(n.Wt.hr(i),this.Du.p())}ju(t){for(const i of this.Pu){const n=i.co(t);if(null!==n)return{Fn:i,Wt:n}}return null}Et(){return this.uh}Hn(){return this.Pu}qu(){return this.Ct}Yu(){return this.Iu}Zu(t,i){t.Cl(i),this.J_()}vo(t){this.so=t,this.uh.vo(this.so),this.Pu.forEach((i=>i.vo(t))),this.J_()}Ku(t){1!==this.Pu.length&&(r(t>=0&&t=0&&tt+i.fo()),0),e=this.Pu.reduce(((t,i)=>t+i.$t()),0),h=e-30*(this.Pu.length-1);i=Math.min(h,Math.max(30,i));const a=s/e,l=n.$t();n.po(i*a);let o=i-l,_=this.Pu.length-1;for(const t of this.Pu)if(t!==n){const i=Math.min(h,Math.max(30,t.$t()-o/_));o-=t.$t()-i,_-=1;const n=i*a;t.po(n)}this.Eh()}Gu(t,i){r(t>=0&&t=0&&ithis.qo.key(e),l=null!==t&&t>r&&!a,o=this.uh.N().allowShiftVisibleRangeOnWhitespaceReplacement,_=i&&(!(void 0===n)||o)&&this.uh.N().shiftVisibleRangeOnNewBar;if(l&&!_){const i=t-r;this.uh.ds(this.uh.iu()-i)}}this.uh.ru(t)}Oh(t){null!==t&&t.Bo()}Hs(t){if(function(t){return t instanceof fi}(t))return t;const i=this.Pu.find((i=>i.Dt().includes(t)));return void 0===i?null:i}J_(){this.Pu.forEach((t=>t.Bo())),this.Bh()}m(){this.Pu.forEach((t=>t.m())),this.Pu.length=0,this.Sn.localization.priceFormatter=void 0,this.Sn.localization.percentageFormatter=void 0,this.Sn.localization.timeFormatter=void 0}dc(){return this.Au}qs(){return this.Au.N()}do(){return this.Du}fc(t,i){const n=this.zu(i);this.vc(t,n),this.Tu.push(t),1===this.Tu.length?this.Eh():this.ar()}mc(t){const i=this.Hs(t),n=this.Tu.indexOf(t);r(-1!==n,"Series not found");const s=a(i);this.Tu.splice(n,1),s.Wl(t),t.m&&t.m(),this.uh.R_(),this.wc(s)}Vh(t,i){const n=a(this.Hs(t));n.Wl(t),n.Ll(t,i,a(t.hn()))}mu(){const t=Y.ws();t.ss(),this.Wu(t)}gc(t){const i=Y.ws();i.hs(t),this.Wu(i)}us(){const t=Y.ws();t.us(),this.Wu(t)}cs(t){const i=Y.ws();i.cs(t),this.Wu(i)}ds(t){const i=Y.ws();i.ds(t),this.Wu(i)}ls(t){const i=Y.ws();i.ls(t),this.Wu(i)}es(){const t=Y.ws();t.es(),this.Wu(t)}Mc(){return this.Sn.rightPriceScale.visible?"right":"left"}bc(t,i){r(i>=0,"Index should be greater or equal to 0");if(i===this.xc(t))return;const n=a(this.Hs(t));n.Wl(t);const s=this.zu(i);this.vc(t,s),0===n.ba().length&&this.wc(n)}Sc(){return this.Nu}$(){return this.Ou}Ut(t){const i=this.Nu,n=this.Ou;if(i===n)return i;if(t=Math.max(0,Math.min(100,Math.round(100*t))),null===this.Vu||this.Vu.mr!==n||this.Vu.wr!==i)this.Vu={mr:n,wr:i,Cc:new Map};else{const i=this.Vu.Cc.get(t);if(void 0!==i)return i}const s=this.cl.tt(n,i,t/100);return this.Vu.Cc.set(t,s),s}yc(t){return this.Pu.indexOf(t)}Ki(){return this.cl}oc(t,i,n){if(t){const s=wi(t,i,n);this.Uu(s&&{Wo:s.Wo,Fo:s.Fo})}}zu(t){if(r(t>=0,"Index should be greater or equal to 0"),(t=Math.min(this.Pu.length,t))i.wo().includes(t)))}Ju(t,i){const n=new Y(i);if(null!==t){const s=this.Pu.indexOf(t);n.Gn(s,{Jn:i})}return n}Fu(t,i){return void 0===i&&(i=2),this.Ju(this.Hs(t),i)}Wu(t){this.Eu&&this.Eu(t),this.Pu.forEach((t=>t.Oo().lr().kt()))}vc(t,i){const n=t.N().priceScaleId,s=void 0!==n?n:this.Mc();i.Ll(t,s),q(s)||t.hr(t.N())}Lu(t){const i=this.Sn.layout;return"gradient"===i.background.type?0===t?i.background.topColor:i.background.bottomColor:i.background.color}wc(t){0===t.ba().length&&this.Pu.length>1&&(this.Pu.splice(this.yc(t),1),this.Eh())}}function Vi(t){return!u(t)&&!d(t)}function Ei(t){return u(t)}!function(t){t[t.Disabled=0]="Disabled",t[t.Continuous=1]="Continuous",t[t.OnDataUpdate=2]="OnDataUpdate"}(Pi||(Pi={})),function(t){t[t.LastBar=0]="LastBar",t[t.LastVisible=1]="LastVisible"}(Ti||(Ti={})),function(t){t.Solid="solid",t.VerticalGradient="gradient"}(Ri||(Ri={})),function(t){t[t.Year=0]="Year",t[t.Month=1]="Month",t[t.DayOfMonth=2]="DayOfMonth",t[t.Time=3]="Time",t[t.TimeWithSeconds=4]="TimeWithSeconds"}(Di||(Di={}));const Ai=t=>t.getUTCFullYear();function Bi(t,i,n){return i.replace(/yyyy/g,(t=>K(Ai(t),4))(t)).replace(/yy/g,(t=>K(Ai(t)%100,2))(t)).replace(/MMMM/g,((t,i)=>new Date(t.getUTCFullYear(),t.getUTCMonth(),1).toLocaleString(i,{month:"long"}))(t,n)).replace(/MMM/g,((t,i)=>new Date(t.getUTCFullYear(),t.getUTCMonth(),1).toLocaleString(i,{month:"short"}))(t,n)).replace(/MM/g,(t=>K((t=>t.getUTCMonth()+1)(t),2))(t)).replace(/dd/g,(t=>K((t=>t.getUTCDate())(t),2))(t))}class zi{constructor(t="yyyy-MM-dd",i="default"){this.kc=t,this.Pc=i}Yo(t){return Bi(t,this.kc,this.Pc)}}class Oi{constructor(t){this.Tc=t||"%h:%m:%s"}Yo(t){return this.Tc.replace("%h",K(t.getUTCHours(),2)).replace("%m",K(t.getUTCMinutes(),2)).replace("%s",K(t.getUTCSeconds(),2))}}const Li={Rc:"yyyy-MM-dd",Dc:"%h:%m:%s",Ic:" ",Vc:"default"};class Ni{constructor(t={}){const i={...Li,...t};this.Ec=new zi(i.Rc,i.Vc),this.Ac=new Oi(i.Dc),this.Bc=i.Ic}Yo(t){return`${this.Ec.Yo(t)}${this.Bc}${this.Ac.Yo(t)}`}}function Wi(t){return 60*t*60*1e3}function Fi(t){return 60*t*1e3}const Hi=[{zc:(Ui=1,1e3*Ui),Oc:10},{zc:Fi(1),Oc:20},{zc:Fi(5),Oc:21},{zc:Fi(30),Oc:22},{zc:Wi(1),Oc:30},{zc:Wi(3),Oc:31},{zc:Wi(6),Oc:32},{zc:Wi(12),Oc:33}];var Ui;function $i(t,i){if(t.getUTCFullYear()!==i.getUTCFullYear())return 70;if(t.getUTCMonth()!==i.getUTCMonth())return 60;if(t.getUTCDate()!==i.getUTCDate())return 50;for(let n=Hi.length-1;n>=0;--n)if(Math.floor(i.getTime()/Hi[n].zc)!==Math.floor(t.getTime()/Hi[n].zc))return Hi[n].Oc;return 0}function ji(t){let i=t;if(d(t)&&(i=Yi(t)),!Vi(i))throw new Error("time must be of type BusinessDay");const n=new Date(Date.UTC(i.year,i.month-1,i.day,0,0,0,0));return{Lc:Math.round(n.getTime()/1e3),Nc:i}}function qi(t){if(!Ei(t))throw new Error("time must be of type isUTCTimestamp");return{Lc:t}}function Yi(t){const i=new Date(t);if(isNaN(i.getTime()))throw new Error(`Invalid date string=${t}, expected format=yyyy-mm-dd`);return{day:i.getUTCDate(),month:i.getUTCMonth()+1,year:i.getUTCFullYear()}}function Zi(t){d(t.time)&&(t.time=Yi(t.time))}class Ki{options(){return this.Sn}setOptions(t){this.Sn=t,this.updateFormatter(t.localization)}preprocessData(t){Array.isArray(t)?function(t){t.forEach(Zi)}(t):Zi(t)}createConverterToInternalObj(t){return a(function(t){return 0===t.length?null:Vi(t[0].time)||d(t[0].time)?ji:qi}(t))}key(t){return"object"==typeof t&&"Lc"in t?t.Lc:this.key(this.convertHorzItemToInternal(t))}cacheKey(t){const i=t;return void 0===i.Nc?new Date(1e3*i.Lc).getTime():new Date(Date.UTC(i.Nc.year,i.Nc.month-1,i.Nc.day)).getTime()}convertHorzItemToInternal(t){return Ei(i=t)?qi(i):Vi(i)?ji(i):ji(Yi(i));var i}updateFormatter(t){if(!this.Sn)return;const i=t.dateFormat;this.Sn.timeScale.timeVisible?this.Wc=new Ni({Rc:i,Dc:this.Sn.timeScale.secondsVisible?"%h:%m:%s":"%h:%m",Ic:" ",Vc:t.locale}):this.Wc=new zi(i,t.locale)}formatHorzItem(t){const i=t;return this.Wc.Yo(new Date(1e3*i.Lc))}formatTickmark(t,i){const n=function(t,i,n){switch(t){case 0:case 10:return i?n?4:3:2;case 20:case 21:case 22:case 30:case 31:case 32:case 33:return i?3:2;case 50:return 2;case 60:return 1;case 70:return 0}}(t.weight,this.Sn.timeScale.timeVisible,this.Sn.timeScale.secondsVisible),s=this.Sn.timeScale;if(void 0!==s.tickMarkFormatter){const e=s.tickMarkFormatter(t.originalTime,n,i.locale);if(null!==e)return e}return function(t,i,n){const s={};switch(i){case 0:s.year="numeric";break;case 1:s.month="short";break;case 2:s.day="numeric";break;case 3:s.hour12=!1,s.hour="2-digit",s.minute="2-digit";break;case 4:s.hour12=!1,s.hour="2-digit",s.minute="2-digit",s.second="2-digit"}const e=void 0===t.Nc?new Date(1e3*t.Lc):new Date(Date.UTC(t.Nc.year,t.Nc.month-1,t.Nc.day));return new Date(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds()).toLocaleString(n,s)}(t.time,n,i.locale)}maxTickMarkWeight(t){let i=t.reduce(Ci,t[0]).weight;return i>30&&i<50&&(i=30),i}fillWeightsForPoints(t,i){!function(t,i=0){if(0===t.length)return;let n=0===i?null:t[i-1].time.Lc,s=null!==n?new Date(1e3*n):null,e=0;for(let r=i;r1){const i=Math.ceil(e/(t.length-1)),n=new Date(1e3*(t[0].time.Lc-i));t[0].timeWeight=$i(new Date(1e3*t[0].time.Lc),n)}}(t,i)}static Fc(t){return _({localization:{dateFormat:"dd MMM 'yy"}},t??{})}}function Xi(t){var i=t.width,n=t.height;if(i<0)throw new Error("Negative width is not allowed for Size");if(n<0)throw new Error("Negative height is not allowed for Size");return{width:i,height:n}}function Gi(t,i){return t.width===i.width&&t.height===i.height}var Ji=function(){function t(t){var i=this;this._resolutionListener=function(){return i._onResolutionChanged()},this._resolutionMediaQueryList=null,this._observers=[],this._window=t,this._installResolutionListener()}return t.prototype.dispose=function(){this._uninstallResolutionListener(),this._window=null},Object.defineProperty(t.prototype,"value",{get:function(){return this._window.devicePixelRatio},enumerable:!1,configurable:!0}),t.prototype.subscribe=function(t){var i=this,n={next:t};return this._observers.push(n),{unsubscribe:function(){i._observers=i._observers.filter((function(t){return t!==n}))}}},t.prototype._installResolutionListener=function(){if(null!==this._resolutionMediaQueryList)throw new Error("Resolution listener is already installed");var t=this._window.devicePixelRatio;this._resolutionMediaQueryList=this._window.matchMedia("all and (resolution: ".concat(t,"dppx)")),this._resolutionMediaQueryList.addListener(this._resolutionListener)},t.prototype._uninstallResolutionListener=function(){null!==this._resolutionMediaQueryList&&(this._resolutionMediaQueryList.removeListener(this._resolutionListener),this._resolutionMediaQueryList=null)},t.prototype._reinstallResolutionListener=function(){this._uninstallResolutionListener(),this._installResolutionListener()},t.prototype._onResolutionChanged=function(){var t=this;this._observers.forEach((function(i){return i.next(t._window.devicePixelRatio)})),this._reinstallResolutionListener()},t}();var Qi=function(){function t(t,i,n){var s;this._canvasElement=null,this._bitmapSizeChangedListeners=[],this._suggestedBitmapSize=null,this._suggestedBitmapSizeChangedListeners=[],this._devicePixelRatioObservable=null,this._canvasElementResizeObserver=null,this._canvasElement=t,this._canvasElementClientSize=Xi({width:this._canvasElement.clientWidth,height:this._canvasElement.clientHeight}),this._transformBitmapSize=null!=i?i:function(t){return t},this._allowResizeObserver=null===(s=null==n?void 0:n.allowResizeObserver)||void 0===s||s,this._chooseAndInitObserver()}return t.prototype.dispose=function(){var t,i;if(null===this._canvasElement)throw new Error("Object is disposed");null===(t=this._canvasElementResizeObserver)||void 0===t||t.disconnect(),this._canvasElementResizeObserver=null,null===(i=this._devicePixelRatioObservable)||void 0===i||i.dispose(),this._devicePixelRatioObservable=null,this._suggestedBitmapSizeChangedListeners.length=0,this._bitmapSizeChangedListeners.length=0,this._canvasElement=null},Object.defineProperty(t.prototype,"canvasElement",{get:function(){if(null===this._canvasElement)throw new Error("Object is disposed");return this._canvasElement},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"canvasElementClientSize",{get:function(){return this._canvasElementClientSize},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bitmapSize",{get:function(){return Xi({width:this.canvasElement.width,height:this.canvasElement.height})},enumerable:!1,configurable:!0}),t.prototype.resizeCanvasElement=function(t){this._canvasElementClientSize=Xi(t),this.canvasElement.style.width="".concat(this._canvasElementClientSize.width,"px"),this.canvasElement.style.height="".concat(this._canvasElementClientSize.height,"px"),this._invalidateBitmapSize()},t.prototype.subscribeBitmapSizeChanged=function(t){this._bitmapSizeChangedListeners.push(t)},t.prototype.unsubscribeBitmapSizeChanged=function(t){this._bitmapSizeChangedListeners=this._bitmapSizeChangedListeners.filter((function(i){return i!==t}))},Object.defineProperty(t.prototype,"suggestedBitmapSize",{get:function(){return this._suggestedBitmapSize},enumerable:!1,configurable:!0}),t.prototype.subscribeSuggestedBitmapSizeChanged=function(t){this._suggestedBitmapSizeChangedListeners.push(t)},t.prototype.unsubscribeSuggestedBitmapSizeChanged=function(t){this._suggestedBitmapSizeChangedListeners=this._suggestedBitmapSizeChangedListeners.filter((function(i){return i!==t}))},t.prototype.applySuggestedBitmapSize=function(){if(null!==this._suggestedBitmapSize){var t=this._suggestedBitmapSize;this._suggestedBitmapSize=null,this._resizeBitmap(t),this._emitSuggestedBitmapSizeChanged(t,this._suggestedBitmapSize)}},t.prototype._resizeBitmap=function(t){var i=this.bitmapSize;Gi(i,t)||(this.canvasElement.width=t.width,this.canvasElement.height=t.height,this._emitBitmapSizeChanged(i,t))},t.prototype._emitBitmapSizeChanged=function(t,i){var n=this;this._bitmapSizeChangedListeners.forEach((function(s){return s.call(n,t,i)}))},t.prototype._suggestNewBitmapSize=function(t){var i=this._suggestedBitmapSize,n=Xi(this._transformBitmapSize(t,this._canvasElementClientSize)),s=Gi(this.bitmapSize,n)?null:n;null===i&&null===s||null!==i&&null!==s&&Gi(i,s)||(this._suggestedBitmapSize=s,this._emitSuggestedBitmapSizeChanged(i,s))},t.prototype._emitSuggestedBitmapSizeChanged=function(t,i){var n=this;this._suggestedBitmapSizeChangedListeners.forEach((function(s){return s.call(n,t,i)}))},t.prototype._chooseAndInitObserver=function(){var t=this;this._allowResizeObserver?new Promise((function(t){var i=new ResizeObserver((function(n){t(n.every((function(t){return"devicePixelContentBoxSize"in t}))),i.disconnect()}));i.observe(document.body,{box:"device-pixel-content-box"})})).catch((function(){return!1})).then((function(i){return i?t._initResizeObserver():t._initDevicePixelRatioObservable()})):this._initDevicePixelRatioObservable()},t.prototype._initDevicePixelRatioObservable=function(){var t=this;if(null!==this._canvasElement){var i=tn(this._canvasElement);if(null===i)throw new Error("No window is associated with the canvas");this._devicePixelRatioObservable=function(t){return new Ji(t)}(i),this._devicePixelRatioObservable.subscribe((function(){return t._invalidateBitmapSize()})),this._invalidateBitmapSize()}},t.prototype._invalidateBitmapSize=function(){var t,i;if(null!==this._canvasElement){var n=tn(this._canvasElement);if(null!==n){var s=null!==(i=null===(t=this._devicePixelRatioObservable)||void 0===t?void 0:t.value)&&void 0!==i?i:n.devicePixelRatio,e=this._canvasElement.getClientRects(),r=void 0!==e[0]?function(t,i){return Xi({width:Math.round(t.left*i+t.width*i)-Math.round(t.left*i),height:Math.round(t.top*i+t.height*i)-Math.round(t.top*i)})}(e[0],s):Xi({width:this._canvasElementClientSize.width*s,height:this._canvasElementClientSize.height*s});this._suggestNewBitmapSize(r)}}},t.prototype._initResizeObserver=function(){var t=this;null!==this._canvasElement&&(this._canvasElementResizeObserver=new ResizeObserver((function(i){var n=i.find((function(i){return i.target===t._canvasElement}));if(n&&n.devicePixelContentBoxSize&&n.devicePixelContentBoxSize[0]){var s=n.devicePixelContentBoxSize[0],e=Xi({width:s.inlineSize,height:s.blockSize});t._suggestNewBitmapSize(e)}})),this._canvasElementResizeObserver.observe(this._canvasElement,{box:"device-pixel-content-box"}))},t}();function tn(t){return t.ownerDocument.defaultView}var nn=function(){function t(t,i,n){if(0===i.width||0===i.height)throw new TypeError("Rendering target could only be created on a media with positive width and height");if(this._mediaSize=i,0===n.width||0===n.height)throw new TypeError("Rendering target could only be created using a bitmap with positive integer width and height");this._bitmapSize=n,this._context=t}return t.prototype.useMediaCoordinateSpace=function(t){try{return this._context.save(),this._context.setTransform(1,0,0,1,0,0),this._context.scale(this._horizontalPixelRatio,this._verticalPixelRatio),t({context:this._context,mediaSize:this._mediaSize})}finally{this._context.restore()}},t.prototype.useBitmapCoordinateSpace=function(t){try{return this._context.save(),this._context.setTransform(1,0,0,1,0,0),t({context:this._context,mediaSize:this._mediaSize,bitmapSize:this._bitmapSize,horizontalPixelRatio:this._horizontalPixelRatio,verticalPixelRatio:this._verticalPixelRatio})}finally{this._context.restore()}},Object.defineProperty(t.prototype,"_horizontalPixelRatio",{get:function(){return this._bitmapSize.width/this._mediaSize.width},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_verticalPixelRatio",{get:function(){return this._bitmapSize.height/this._mediaSize.height},enumerable:!1,configurable:!0}),t}();function sn(t,i){var n=t.canvasElementClientSize;if(0===n.width||0===n.height)return null;var s=t.bitmapSize;if(0===s.width||0===s.height)return null;var e=t.canvasElement.getContext("2d",i);return null===e?null:new nn(e,n,s)}const en="undefined"!=typeof window;function rn(){return!!en&&window.navigator.userAgent.toLowerCase().indexOf("firefox")>-1}function hn(){return!!en&&/iPhone|iPad|iPod/.test(window.navigator.platform)}function an(t){return t+t%2}function ln(t){en&&void 0!==window.chrome&&t.addEventListener("mousedown",(t=>{if(1===t.button)return t.preventDefault(),!1}))}class on{constructor(t,i,n){this.Hc=0,this.Uc=null,this.$c={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY},this.jc=0,this.qc=null,this.Yc={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY},this.Zc=null,this.Kc=!1,this.Xc=null,this.Gc=null,this.Jc=!1,this.Qc=!1,this.td=!1,this.nd=null,this.sd=null,this.ed=null,this.rd=null,this.hd=null,this.ad=null,this.ld=null,this.od=0,this._d=!1,this.ud=!1,this.dd=!1,this.fd=0,this.pd=null,this.vd=!hn(),this.md=t=>{this.wd(t)},this.gd=t=>{if(this.Md(t)){const i=this.bd(t);if(++this.jc,this.qc&&this.jc>1){const{xd:n}=this.Sd(cn(t),this.Yc);n<30&&!this.td&&this.Cd(i,this.kd.yd),this.Pd()}}else{const i=this.bd(t);if(++this.Hc,this.Uc&&this.Hc>1){const{xd:n}=this.Sd(cn(t),this.$c);n<5&&!this.Qc&&this.Td(i,this.kd.Rd),this.Dd()}}},this.Id=t,this.kd=i,this.Sn=n,this.Vd()}m(){null!==this.nd&&(this.nd(),this.nd=null),null!==this.sd&&(this.sd(),this.sd=null),null!==this.rd&&(this.rd(),this.rd=null),null!==this.hd&&(this.hd(),this.hd=null),null!==this.ad&&(this.ad(),this.ad=null),null!==this.ed&&(this.ed(),this.ed=null),this.Ed(),this.Dd()}Ad(t){this.rd&&this.rd();const i=this.Bd.bind(this);if(this.rd=()=>{this.Id.removeEventListener("mousemove",i)},this.Id.addEventListener("mousemove",i),this.Md(t))return;const n=this.bd(t);this.Td(n,this.kd.zd),this.vd=!0}Dd(){null!==this.Uc&&clearTimeout(this.Uc),this.Hc=0,this.Uc=null,this.$c={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY}}Pd(){null!==this.qc&&clearTimeout(this.qc),this.jc=0,this.qc=null,this.Yc={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY}}Bd(t){if(this.dd||null!==this.Gc)return;if(this.Md(t))return;const i=this.bd(t);this.Td(i,this.kd.Od),this.vd=!0}Ld(t){const i=fn(t.changedTouches,a(this.pd));if(null===i)return;if(this.fd=dn(t),null!==this.ld)return;if(this.ud)return;this._d=!0;const n=this.Sd(cn(i),a(this.Gc)),{Nd:s,Wd:e,xd:r}=n;if(this.Jc||!(r<5)){if(!this.Jc){const t=.5*s,i=e>=t&&!this.Sn.Fd(),n=t>e&&!this.Sn.Hd();i||n||(this.ud=!0),this.Jc=!0,this.td=!0,this.Ed(),this.Pd()}if(!this.ud){const n=this.bd(t,i);this.Cd(n,this.kd.Ud),un(t)}}}$d(t){if(0!==t.button)return;const i=this.Sd(cn(t),a(this.Xc)),{xd:n}=i;if(n>=5&&(this.Qc=!0,this.Dd()),this.Qc){const i=this.bd(t);this.Td(i,this.kd.jd)}}Sd(t,i){const n=Math.abs(i._t-t._t),s=Math.abs(i.ut-t.ut);return{Nd:n,Wd:s,xd:n+s}}qd(t){let i=fn(t.changedTouches,a(this.pd));if(null===i&&0===t.touches.length&&(i=t.changedTouches[0]),null===i)return;this.pd=null,this.fd=dn(t),this.Ed(),this.Gc=null,this.ad&&(this.ad(),this.ad=null);const n=this.bd(t,i);if(this.Cd(n,this.kd.Yd),++this.jc,this.qc&&this.jc>1){const{xd:t}=this.Sd(cn(i),this.Yc);t<30&&!this.td&&this.Cd(n,this.kd.yd),this.Pd()}else this.td||(this.Cd(n,this.kd.Zd),this.kd.Zd&&un(t));0===this.jc&&un(t),0===t.touches.length&&this.Kc&&(this.Kc=!1,un(t))}wd(t){if(0!==t.button)return;const i=this.bd(t);if(this.Xc=null,this.dd=!1,this.hd&&(this.hd(),this.hd=null),rn()){this.Id.ownerDocument.documentElement.removeEventListener("mouseleave",this.md)}if(!this.Md(t))if(this.Td(i,this.kd.Kd),++this.Hc,this.Uc&&this.Hc>1){const{xd:n}=this.Sd(cn(t),this.$c);n<5&&!this.Qc&&this.Td(i,this.kd.Rd),this.Dd()}else this.Qc||this.Td(i,this.kd.Xd)}Ed(){null!==this.Zc&&(clearTimeout(this.Zc),this.Zc=null)}Gd(t){if(null!==this.pd)return;const i=t.changedTouches[0];this.pd=i.identifier,this.fd=dn(t);const n=this.Id.ownerDocument.documentElement;this.td=!1,this.Jc=!1,this.ud=!1,this.Gc=cn(i),this.ad&&(this.ad(),this.ad=null);{const i=this.Ld.bind(this),s=this.qd.bind(this);this.ad=()=>{n.removeEventListener("touchmove",i),n.removeEventListener("touchend",s)},n.addEventListener("touchmove",i,{passive:!1}),n.addEventListener("touchend",s,{passive:!1}),this.Ed(),this.Zc=setTimeout(this.Jd.bind(this,t),240)}const s=this.bd(t,i);this.Cd(s,this.kd.Qd),this.qc||(this.jc=0,this.qc=setTimeout(this.Pd.bind(this),500),this.Yc=cn(i))}tf(t){if(0!==t.button)return;const i=this.Id.ownerDocument.documentElement;rn()&&i.addEventListener("mouseleave",this.md),this.Qc=!1,this.Xc=cn(t),this.hd&&(this.hd(),this.hd=null);{const t=this.$d.bind(this),n=this.wd.bind(this);this.hd=()=>{i.removeEventListener("mousemove",t),i.removeEventListener("mouseup",n)},i.addEventListener("mousemove",t),i.addEventListener("mouseup",n)}if(this.dd=!0,this.Md(t))return;const n=this.bd(t);this.Td(n,this.kd.if),this.Uc||(this.Hc=0,this.Uc=setTimeout(this.Dd.bind(this),500),this.$c=cn(t))}Vd(){this.Id.addEventListener("mouseenter",this.Ad.bind(this)),this.Id.addEventListener("touchcancel",this.Ed.bind(this));{const t=this.Id.ownerDocument,i=t=>{this.kd.nf&&(t.composed&&this.Id.contains(t.composedPath()[0])||t.target&&this.Id.contains(t.target)||this.kd.nf())};this.sd=()=>{t.removeEventListener("touchstart",i)},this.nd=()=>{t.removeEventListener("mousedown",i)},t.addEventListener("mousedown",i),t.addEventListener("touchstart",i,{passive:!0})}hn()&&(this.ed=()=>{this.Id.removeEventListener("dblclick",this.gd)},this.Id.addEventListener("dblclick",this.gd)),this.Id.addEventListener("mouseleave",this.sf.bind(this)),this.Id.addEventListener("touchstart",this.Gd.bind(this),{passive:!0}),ln(this.Id),this.Id.addEventListener("mousedown",this.tf.bind(this)),this.ef(),this.Id.addEventListener("touchmove",(()=>{}),{passive:!1})}ef(){void 0===this.kd.rf&&void 0===this.kd.hf&&void 0===this.kd.af||(this.Id.addEventListener("touchstart",(t=>this.lf(t.touches)),{passive:!0}),this.Id.addEventListener("touchmove",(t=>{if(2===t.touches.length&&null!==this.ld&&void 0!==this.kd.hf){const i=_n(t.touches[0],t.touches[1])/this.od;this.kd.hf(this.ld,i),un(t)}}),{passive:!1}),this.Id.addEventListener("touchend",(t=>{this.lf(t.touches)})))}lf(t){1===t.length&&(this._d=!1),2!==t.length||this._d||this.Kc?this._f():this.uf(t)}uf(t){const i=this.Id.getBoundingClientRect()||{left:0,top:0};this.ld={_t:(t[0].clientX-i.left+(t[1].clientX-i.left))/2,ut:(t[0].clientY-i.top+(t[1].clientY-i.top))/2},this.od=_n(t[0],t[1]),void 0!==this.kd.rf&&this.kd.rf(),this.Ed()}_f(){null!==this.ld&&(this.ld=null,void 0!==this.kd.af&&this.kd.af())}sf(t){if(this.rd&&this.rd(),this.Md(t))return;if(!this.vd)return;const i=this.bd(t);this.Td(i,this.kd.cf),this.vd=!hn()}Jd(t){const i=fn(t.touches,a(this.pd));if(null===i)return;const n=this.bd(t,i);this.Cd(n,this.kd.df),this.td=!0,this.Kc=!0}Md(t){return t.sourceCapabilities&&void 0!==t.sourceCapabilities.firesTouchEvents?t.sourceCapabilities.firesTouchEvents:dn(t){"touchstart"!==t.type&&un(t)}}}}function _n(t,i){const n=t.clientX-i.clientX,s=t.clientY-i.clientY;return Math.sqrt(n*n+s*s)}function un(t){t.cancelable&&t.preventDefault()}function cn(t){return{_t:t.pageX,ut:t.pageY}}function dn(t){return t.timeStamp||performance.now()}function fn(t,i){for(let n=0;n!1,Hd:()=>!0}),this.wf={Bf:n,Af:t}}Tf(){this.Pf.style.background=this.xf.N().layout.panes.separatorColor}zf(t){null!==this.wf&&(this.wf.Bf.style.backgroundColor=this.xf.N().layout.panes.separatorHoverColor)}Of(t){null!==this.wf&&null===this.bf&&(this.wf.Bf.style.backgroundColor="")}Lf(t){if(null===this.wf)return;const i=this.Sf.Ff().fo()+this.yf.Ff().fo(),n=i/(this.Sf.If().height+this.yf.If().height),s=30*n;i<=2*s||(this.bf={Hf:t.pageY,Uf:this.Sf.Ff().fo(),$f:i-s,jf:i,qf:n,Yf:s},this.wf.Af.style.display="block")}Nf(t){const i=this.bf;if(null===i)return;const n=(t.pageY-i.Hf)*i.qf,s=si(i.Uf+n,i.Yf,i.$f);this.Sf.Ff().po(s),this.yf.Ff().po(i.jf-s),this.xf.Qt().Eh()}Wf(t){null!==this.bf&&null!==this.wf&&(this.bf=null,this.wf.Af.style.display="none")}}function vn(t,i){return t.Zf-i.Zf}function mn(t,i,n){const s=(t.Zf-i.Zf)/(t.wt-i.wt);return Math.sign(s)*Math.min(Math.abs(s),n)}class wn{constructor(t,i,n,s){this.Kf=null,this.Xf=null,this.Gf=null,this.Jf=null,this.Qf=null,this.tp=0,this.ip=0,this.np=t,this.sp=i,this.ep=n,this.Ms=s}rp(t,i){if(null!==this.Kf){if(this.Kf.wt===i)return void(this.Kf.Zf=t);if(Math.abs(this.Kf.Zf-t)50)return;let n=0;const s=mn(this.Kf,this.Xf,this.sp),e=vn(this.Kf,this.Xf),r=[s],h=[e];if(n+=e,null!==this.Gf){const t=mn(this.Xf,this.Gf,this.sp);if(Math.sign(t)===Math.sign(s)){const i=vn(this.Xf,this.Gf);if(r.push(t),h.push(i),n+=i,null!==this.Jf){const t=mn(this.Gf,this.Jf,this.sp);if(Math.sign(t)===Math.sign(s)){const i=vn(this.Gf,this.Jf);r.push(t),h.push(i),n+=i}}}}let a=0;for(let t=0;t160?"dark":"light"}pp(){return this.up.N().layout.attributionLogo}mp(){const t=new URL(location.href);return t.hostname?"&utm_source="+t.hostname+t.pathname:""}cp(){this.fp()&&(this.dp(),this.fn=this.pp(),this.fn&&(this.op=this.vp(),this.lp=document.createElement("style"),this.lp.innerText="a#tv-attr-logo{--fill:#131722;--stroke:#fff;position:absolute;left:10px;bottom:10px;height:19px;width:35px;margin:0;padding:0;border:0;z-index:3;}a#tv-attr-logo[data-dark]{--fill:#D1D4DC;--stroke:#131722;}",this.ap=document.createElement("a"),this.ap.href=`https://www.tradingview.com/?utm_medium=lwc-link&utm_campaign=lwc-chart${this.mp()}`,this.ap.title="Charting by TradingView",this.ap.id="tv-attr-logo",this.ap.target="_blank",this.ap.innerHTML='',this.ap.toggleAttribute("data-dark","dark"===this.op),this._p.appendChild(this.lp),this._p.appendChild(this.ap)))}}function Mn(t,i){const n=a(t.ownerDocument).createElement("canvas");t.appendChild(n);const s=function(t,i){if("device-pixel-content-box"===i.type)return new Qi(t,i.transform,i.options);throw new Error("Unsupported binding target")}(n,{type:"device-pixel-content-box",options:{allowResizeObserver:!0},transform:(t,i)=>({width:Math.max(t.width,i.width),height:Math.max(t.height,i.height)})});return s.resizeCanvasElement(i),s}function bn(t){t.width=1,t.height=1,t.getContext("2d")?.clearRect(0,0,1,1)}function xn(t,i,n,s){t.ih&&t.ih(i,n,s)}function Sn(t,i,n,s){t.st(i,n,s)}function Cn(t,i,n,s){const e=t(n,s);for(const t of e){const n=t.Tt(s);null!==n&&i(n)}}function yn(t,i){return n=>{if(!function(t){return void 0!==t.Wt}(n))return[];return(n.Wt()?.wa()??"")!==i?[]:n.ta?.(t)??[]}}function kn(t,i,n,s){if(!t.length)return;let e=0;const r=t[0].$t(s,!0);let h=1===i?n/2-(t[0].Wi()-r/2):t[0].Wi()-r/2-n/2;h=Math.max(0,h);for(let r=1;ru-o:_n)&&h>0){const s=1===i?-1-r:r-n,a=Math.min(s,h);for(let n=e;n{this.Sp||this.yt.yp().Qt().ar()},this.kp=()=>{this.Sp||this.yt.yp().Qt().ar()},this.yt=t,this.Sn=i,this._l=i.layout,this.Au=n,this.Pp="left"===s,this.Tp=yn("normal",s),this.Rp=yn("top",s),this.Dp=yn("bottom",s),this.Pf=document.createElement("div"),this.Pf.style.height="100%",this.Pf.style.overflow="hidden",this.Pf.style.width="25px",this.Pf.style.left="0",this.Pf.style.position="relative",this.Ip=Mn(this.Pf,Xi({width:16,height:16})),this.Ip.subscribeSuggestedBitmapSizeChanged(this.Cp);const e=this.Ip.canvasElement;e.style.position="absolute",e.style.zIndex="1",e.style.left="0",e.style.top="0",this.Vp=Mn(this.Pf,Xi({width:16,height:16})),this.Vp.subscribeSuggestedBitmapSizeChanged(this.kp);const r=this.Vp.canvasElement;r.style.position="absolute",r.style.zIndex="2",r.style.left="0",r.style.top="0";const h={if:this.Lf.bind(this),Qd:this.Lf.bind(this),jd:this.Nf.bind(this),Ud:this.Nf.bind(this),nf:this.Ep.bind(this),Kd:this.Wf.bind(this),Yd:this.Wf.bind(this),Rd:this.Ap.bind(this),yd:this.Ap.bind(this),zd:this.Bp.bind(this),cf:this.Of.bind(this)};this.gf=new on(this.Vp.canvasElement,h,{Fd:()=>!this.Sn.handleScroll.vertTouchDrag,Hd:()=>!0})}m(){this.gf.m(),this.Vp.unsubscribeSuggestedBitmapSizeChanged(this.kp),bn(this.Vp.canvasElement),this.Vp.dispose(),this.Ip.unsubscribeSuggestedBitmapSizeChanged(this.Cp),bn(this.Ip.canvasElement),this.Ip.dispose(),null!==this.qi&&this.qi.Hl().u(this),this.qi=null}Df(){return this.Pf}k(){return this._l.fontSize}zp(){const t=this.Au.N();return this.bp!==t.P&&(this.Mp.Vs(),this.bp=t.P),t}Op(){if(null===this.qi)return 0;let t=0;const i=this.zp(),n=a(this.Ip.canvasElement.getContext("2d",{colorSpace:this.yt.yp().N().layout.colorSpace}));n.save();const s=this.qi.Ia();n.font=this.Lp(),s.length>0&&(t=Math.max(this.Mp.Ii(n,s[0].$a),this.Mp.Ii(n,s[s.length-1].$a)));const e=this.Np();for(let i=e.length;i--;){const s=this.Mp.Ii(n,e[i].ri());s>t&&(t=s)}const r=this.qi.Bt();if(null!==r&&null!==this.wp&&(2!==(h=this.Sn.crosshair).mode&&h.horzLine.visible&&h.horzLine.labelVisible)){const i=this.qi.kn(1,r),s=this.qi.kn(this.wp.height-2,r);t=Math.max(t,this.Mp.Ii(n,this.qi.Xi(Math.floor(Math.min(i,s))+.11111111111111,r)),this.Mp.Ii(n,this.qi.Xi(Math.ceil(Math.max(i,s))-.11111111111111,r)))}var h;n.restore();const l=t||34;return an(Math.ceil(i.S+i.C+i.V+i.A+5+l))}Wp(t){null!==this.wp&&Gi(this.wp,t)||(this.wp=t,this.Sp=!0,this.Ip.resizeCanvasElement(t),this.Vp.resizeCanvasElement(t),this.Sp=!1,this.Pf.style.width=`${t.width}px`,this.Pf.style.height=`${t.height}px`)}Fp(){return a(this.wp).width}ln(t){this.qi!==t&&(null!==this.qi&&this.qi.Hl().u(this),this.qi=t,t.Hl().i(this.il.bind(this),this))}Wt(){return this.qi}Vs(){const t=this.yt.Ff();this.yt.yp().Qt().Eo(t,a(this.Wt()))}Hp(t){if(null===this.wp)return;const i={colorSpace:this.yt.yp().N().layout.colorSpace};if(1!==t){this.Up(),this.Ip.applySuggestedBitmapSize();const t=sn(this.Ip,i);null!==t&&(t.useBitmapCoordinateSpace((t=>{this.$p(t),this.jp(t)})),this.yt.qp(t,this.Dp),this.Yp(t),this.yt.qp(t,this.Tp),this.Zp(t))}this.Vp.applySuggestedBitmapSize();const n=sn(this.Vp,i);null!==n&&(n.useBitmapCoordinateSpace((({context:t,bitmapSize:i})=>{t.clearRect(0,0,i.width,i.height)})),this.Kp(n),this.yt.qp(n,this.Rp))}Vf(){return this.Ip.bitmapSize}Ef(t,i,n){const s=this.Vf();s.width>0&&s.height>0&&t.drawImage(this.Ip.canvasElement,i,n)}kt(){this.qi?.Ia()}Lf(t){if(null===this.qi||this.qi.Zi()||!this.Sn.handleScale.axisPressedMouseMove.price)return;const i=this.yt.yp().Qt(),n=this.yt.Ff();this.gp=!0,i.ko(n,this.qi,t.localY)}Nf(t){if(null===this.qi||!this.Sn.handleScale.axisPressedMouseMove.price)return;const i=this.yt.yp().Qt(),n=this.yt.Ff(),s=this.qi;i.Po(n,s,t.localY)}Ep(){if(null===this.qi||!this.Sn.handleScale.axisPressedMouseMove.price)return;const t=this.yt.yp().Qt(),i=this.yt.Ff(),n=this.qi;this.gp&&(this.gp=!1,t.To(i,n))}Wf(t){if(null===this.qi||!this.Sn.handleScale.axisPressedMouseMove.price)return;const i=this.yt.yp().Qt(),n=this.yt.Ff();this.gp=!1,i.To(n,this.qi)}Ap(t){this.Sn.handleScale.axisDoubleClickReset.price&&this.Vs()}Bp(t){if(null===this.qi)return;!this.yt.yp().Qt().N().handleScale.axisPressedMouseMove.price||this.qi.Oe()||this.qi.gl()||this.Xp(1)}Of(t){this.Xp(0)}Np(){const t=[],i=null===this.qi?void 0:this.qi;return(n=>{for(let s=0;s{t.fillStyle=n.borderColor;const a=Math.max(1,Math.floor(h)),l=Math.floor(.5*h),o=Math.round(s.C*r);t.beginPath();for(const n of i)t.rect(Math.floor(e*r),Math.round(n.ka*h)-l,o,a);t.fill()})),t.useMediaCoordinateSpace((({context:t})=>{t.font=this.Lp(),t.fillStyle=n.textColor??this._l.textColor,t.textAlign=this.Pp?"right":"left",t.textBaseline="middle";const r=this.Pp?Math.round(e-s.V):Math.round(e+s.C+s.V),h=i.map((i=>this.Mp.Di(t,i.$a)));for(let n=i.length;n--;){const s=i[n];t.fillText(s.$a,r,s.ka+h[n])}}))}Up(){if(null===this.wp||null===this.qi)return;let t=this.wp.height/2;const i=[],n=this.qi.Dt().slice(),s=this.yt.Ff(),e=this.zp();this.qi===s.$s()&&this.yt.Ff().Dt().forEach((t=>{s.Us(t)&&n.push(t)}));const r=this.qi.ba()[0],h=this.qi;n.forEach((n=>{const e=n.Nn(s,h);e.forEach((t=>{t.Fi(null),t.Hi()&&i.push(t)})),r===n&&e.length>0&&(t=e[0].Ei())})),i.forEach((t=>t.Fi(t.Ei())));this.qi.N().alignLabels&&this.Gp(i,e,t)}Gp(t,i,n){if(null===this.wp)return;const s=t.filter((t=>t.Ei()<=n)),e=t.filter((t=>t.Ei()>n));s.sort(((t,i)=>i.Ei()-t.Ei())),s.length&&e.length&&e.push(s[0]),e.sort(((t,i)=>t.Ei()-i.Ei()));for(const n of t){const t=Math.floor(n.$t(i)/2),s=n.Ei();s>-t&&sthis.wp.height-t&&s{if(i.Ui()){i.Tt(a(this.qi)).st(t,n,this.Mp,s)}}))}Kp(t){if(null===this.wp||null===this.qi)return;const i=this.yt.yp().Qt(),n=[],s=this.yt.Ff(),e=i.qu().Nn(s,this.qi);e.length&&n.push(e);const r=this.zp(),h=this.Pp?"right":"left";n.forEach((i=>{i.forEach((i=>{i.Tt(a(this.qi)).st(t,r,this.Mp,h)}))}))}Xp(t){this.Pf.style.cursor=1===t?"ns-resize":"default"}il(){const t=this.Op();this.xp{this.Sp||null===this.uv||this.tn().ar()},this.kp=()=>{this.Sp||null===this.uv||this.tn().ar()},this.up=t,this.uv=i,this.uv.zo().i(this.cv.bind(this),this,!0),this.dv=document.createElement("td"),this.dv.style.padding="0",this.dv.style.position="relative";const n=document.createElement("div");n.style.width="100%",n.style.height="100%",n.style.position="relative",n.style.overflow="hidden",this.fv=document.createElement("td"),this.fv.style.padding="0",this.pv=document.createElement("td"),this.pv.style.padding="0",this.dv.appendChild(n),this.Ip=Mn(n,Xi({width:16,height:16})),this.Ip.subscribeSuggestedBitmapSizeChanged(this.Cp);const s=this.Ip.canvasElement;s.style.position="absolute",s.style.zIndex="1",s.style.left="0",s.style.top="0",this.Vp=Mn(n,Xi({width:16,height:16})),this.Vp.subscribeSuggestedBitmapSizeChanged(this.kp);const e=this.Vp.canvasElement;e.style.position="absolute",e.style.zIndex="2",e.style.left="0",e.style.top="0",this.kf=document.createElement("tr"),this.kf.appendChild(this.fv),this.kf.appendChild(this.dv),this.kf.appendChild(this.pv),this.vv(),this.gf=new on(this.Vp.canvasElement,this,{Fd:()=>null===this.av&&!this.up.N().handleScroll.vertTouchDrag,Hd:()=>null===this.av&&!this.up.N().handleScroll.horzTouchDrag})}m(){null!==this.Jp&&this.Jp.m(),null!==this.Qp&&this.Qp.m(),this.tv=null,this.Vp.unsubscribeSuggestedBitmapSizeChanged(this.kp),bn(this.Vp.canvasElement),this.Vp.dispose(),this.Ip.unsubscribeSuggestedBitmapSizeChanged(this.Cp),bn(this.Ip.canvasElement),this.Ip.dispose(),null!==this.uv&&(this.uv.zo().u(this),this.uv.m()),this.gf.m()}Ff(){return a(this.uv)}mv(t){null!==this.uv&&this.uv.zo().u(this),this.uv=t,null!==this.uv&&this.uv.zo().i(Vn.prototype.cv.bind(this),this,!0),this.vv(),this.up.Cf().indexOf(this)===this.up.Cf().length-1?(this.tv=this.tv??new gn(this.dv,this.up),this.tv.kt()):(this.tv?.dp(),this.tv=null)}yp(){return this.up}Df(){return this.kf}vv(){if(null!==this.uv&&(this.wv(),0!==this.tn().jn().length)){if(null!==this.Jp){const t=this.uv.Co();this.Jp.ln(a(t))}if(null!==this.Qp){const t=this.uv.yo();this.Qp.ln(a(t))}}}gv(){null!==this.Jp&&this.Jp.kt(),null!==this.Qp&&this.Qp.kt()}fo(){return null!==this.uv?this.uv.fo():0}po(t){this.uv&&this.uv.po(t)}zd(t){if(!this.uv)return;this.Mv();const i=t.localX,n=t.localY;this.bv(i,n,t)}if(t){this.Mv(),this.xv(),this.bv(t.localX,t.localY,t)}Od(t){if(!this.uv)return;this.Mv();const i=t.localX,n=t.localY;this.bv(i,n,t)}Xd(t){null!==this.uv&&(this.Mv(),this.Sv(t))}Rd(t){null!==this.uv&&this.Cv(this.ev,t)}yd(t){this.Rd(t)}jd(t){this.Mv(),this.yv(t),this.bv(t.localX,t.localY,t)}Kd(t){null!==this.uv&&(this.Mv(),this.hv=!1,this.kv(t))}Zd(t){null!==this.uv&&this.Sv(t)}df(t){if(this.hv=!0,null===this.av){const i={x:t.localX,y:t.localY};this.Pv(i,i,t)}}cf(t){null!==this.uv&&(this.Mv(),this.uv.Qt().Uu(null),this.Tv())}Rv(){return this.sv}Dv(){return this.ev}rf(){this.rv=1,this.tn().es()}hf(t,i){if(!this.up.N().handleScale.pinch)return;const n=5*(i-this.rv);this.rv=i,this.tn().tc(t._t,n)}Qd(t){this.hv=!1,this.lv=null!==this.av,this.xv();const i=this.tn().qu();null!==this.av&&i.zt()&&(this.ov={x:i.ni(),y:i.si()},this.av={x:t.localX,y:t.localY})}Ud(t){if(null===this.uv)return;const i=t.localX,n=t.localY;if(null===this.av)this.yv(t);else{this.lv=!1;const s=a(this.ov),e=s.x+(i-this.av.x),r=s.y+(n-this.av.y);this.bv(e,r,t)}}Yd(t){0===this.yp().N().trackingMode.exitMode&&(this.lv=!0),this.Iv(),this.kv(t)}Ys(t,i){const n=this.uv;return null===n?null:wi(n,t,i)}Vv(t,i){a("left"===i?this.Jp:this.Qp).Wp(Xi({width:t,height:this.wp.height}))}If(){return this.wp}Wp(t){Gi(this.wp,t)||(this.wp=t,this.Sp=!0,this.Ip.resizeCanvasElement(t),this.Vp.resizeCanvasElement(t),this.Sp=!1,this.dv.style.width=t.width+"px",this.dv.style.height=t.height+"px")}Ev(){const t=a(this.uv);t.So(t.Co()),t.So(t.yo());for(const i of t.ba())if(t.Us(i)){const n=i.Wt();null!==n&&t.So(n),i.On()}for(const i of t.Lo())i.On()}Vf(){return this.Ip.bitmapSize}Ef(t,i,n){const s=this.Vf();s.width>0&&s.height>0&&t.drawImage(this.Ip.canvasElement,i,n)}Hp(t){if(0===t)return;if(null===this.uv)return;t>1&&this.Ev(),null!==this.Jp&&this.Jp.Hp(t),null!==this.Qp&&this.Qp.Hp(t);const i={colorSpace:this.up.N().layout.colorSpace};if(1!==t){this.Ip.applySuggestedBitmapSize();const t=sn(this.Ip,i);null!==t&&(t.useBitmapCoordinateSpace((t=>{this.$p(t)})),this.uv&&(this.Av(t,Tn),this.Bv(t),this.Av(t,Rn),this.Av(t,Dn)))}this.Vp.applySuggestedBitmapSize();const n=sn(this.Vp,i);null!==n&&(n.useBitmapCoordinateSpace((({context:t,bitmapSize:i})=>{t.clearRect(0,0,i.width,i.height)})),this.zv(n),this.Av(n,In),this.Av(n,Dn))}Ov(){return this.Jp}Lv(){return this.Qp}qp(t,i){this.Av(t,i)}cv(){null!==this.uv&&this.uv.zo().u(this),this.uv=null}Sv(t){this.Cv(this.sv,t)}Cv(t,i){const n=i.localX,s=i.localY;t.v()&&t.p(this.tn().Et().Z_(n),{x:n,y:s},i)}$p({context:t,bitmapSize:i}){const{width:n,height:s}=i,e=this.tn(),r=e.$(),h=e.Sc();r===h?E(t,0,0,n,s,h):z(t,0,0,n,s,r,h)}Bv(t){const i=a(this.uv),n=i.Oo().lr().Tt(i);null!==n&&n.st(t,!1)}zv(t){this.Nv(t,Rn,Sn,this.tn().qu())}Av(t,i){const n=a(this.uv),s=n.Dt(),e=n.Lo();for(const n of e)this.Nv(t,i,xn,n);for(const n of s)this.Nv(t,i,xn,n);for(const n of e)this.Nv(t,i,Sn,n);for(const n of s)this.Nv(t,i,Sn,n)}Nv(t,i,n,s){const e=a(this.uv),r=e.Qt().Hu(),h=null!==r&&r.Wo===s,l=null!==r&&h&&void 0!==r.Fo?r.Fo.Ks:void 0;Cn(i,(i=>n(i,t,h,l)),s,e)}wv(){if(null===this.uv)return;const t=this.up,i=this.uv.Co().N().visible,n=this.uv.yo().N().visible;i||null===this.Jp||(this.fv.removeChild(this.Jp.Df()),this.Jp.m(),this.Jp=null),n||null===this.Qp||(this.pv.removeChild(this.Qp.Df()),this.Qp.m(),this.Qp=null);const s=t.Qt().dc();i&&null===this.Jp&&(this.Jp=new Pn(this,t.N(),s,"left"),this.fv.appendChild(this.Jp.Df())),n&&null===this.Qp&&(this.Qp=new Pn(this,t.N(),s,"right"),this.pv.appendChild(this.Qp.Df()))}Wv(t){return t.ff&&this.hv||null!==this.av}Fv(t){return Math.max(0,Math.min(t,this.wp.width-1))}Hv(t){return Math.max(0,Math.min(t,this.wp.height-1))}bv(t,i,n){this.tn().lc(this.Fv(t),this.Hv(i),n,a(this.uv))}Tv(){this.tn().uc()}Iv(){this.lv&&(this.av=null,this.Tv())}Pv(t,i,n){this.av=t,this.lv=!1,this.bv(i.x,i.y,n);const s=this.tn().qu();this.ov={x:s.ni(),y:s.si()}}tn(){return this.up.Qt()}kv(t){if(!this.nv)return;const i=this.tn(),n=this.Ff();if(i.Io(n,n.yn()),this.iv=null,this.nv=!1,i.rc(),null!==this._v){const t=performance.now(),n=i.Et();this._v.le(n.iu(),t),this._v.uu(t)||i.ls(this._v)}}Mv(){this.av=null}xv(){if(!this.uv)return;if(this.tn().es(),document.activeElement!==document.body&&document.activeElement!==document.documentElement)a(document.activeElement).blur();else{const t=document.getSelection();null!==t&&t.removeAllRanges()}!this.uv.yn().Zi()&&this.tn().Et().Zi()}yv(t){if(null===this.uv)return;const i=this.tn(),n=i.Et();if(n.Zi())return;const s=this.up.N(),e=s.handleScroll,r=s.kineticScroll;if((!e.pressedMouseMove||t.ff)&&(!e.horzTouchDrag&&!e.vertTouchDrag||!t.ff))return;const h=this.uv.yn(),a=performance.now();if(null!==this.iv||this.Wv(t)||(this.iv={x:t.clientX,y:t.clientY,Lc:a,Uv:t.localX,$v:t.localY}),null!==this.iv&&!this.nv&&(this.iv.x!==t.clientX||this.iv.y!==t.clientY)){if(t.ff&&r.touch||!t.ff&&r.mouse){const t=n.Q_();this._v=new wn(.2/t,7/t,.997,15/t),this._v.rp(n.iu(),this.iv.Lc)}else this._v=null;h.Zi()||i.Ro(this.uv,h,t.localY),i.sc(t.localX),this.nv=!0}this.nv&&(h.Zi()||i.Do(this.uv,h,t.localY),i.ec(t.localX),null!==this._v&&this._v.rp(n.iu(),a))}}class En{constructor(t,i,n,s,e){this.St=!0,this.wp=Xi({width:0,height:0}),this.Cp=()=>this.Hp(3),this.Pp="left"===t,this.Au=n.dc,this.Sn=i,this.jv=s,this.qv=e,this.Pf=document.createElement("div"),this.Pf.style.width="25px",this.Pf.style.height="100%",this.Pf.style.overflow="hidden",this.Ip=Mn(this.Pf,Xi({width:16,height:16})),this.Ip.subscribeSuggestedBitmapSizeChanged(this.Cp)}m(){this.Ip.unsubscribeSuggestedBitmapSizeChanged(this.Cp),bn(this.Ip.canvasElement),this.Ip.dispose()}Df(){return this.Pf}If(){return this.wp}Wp(t){Gi(this.wp,t)||(this.wp=t,this.Ip.resizeCanvasElement(t),this.Pf.style.width=`${t.width}px`,this.Pf.style.height=`${t.height}px`,this.St=!0)}Hp(t){if(t<3&&!this.St)return;if(0===this.wp.width||0===this.wp.height)return;this.St=!1,this.Ip.applySuggestedBitmapSize();const i=sn(this.Ip,{colorSpace:this.Sn.layout.colorSpace});null!==i&&i.useBitmapCoordinateSpace((t=>{this.$p(t),this.jp(t)}))}Vf(){return this.Ip.bitmapSize}Ef(t,i,n){const s=this.Vf();s.width>0&&s.height>0&&t.drawImage(this.Ip.canvasElement,i,n)}jp({context:t,bitmapSize:i,horizontalPixelRatio:n,verticalPixelRatio:s}){if(!this.jv())return;t.fillStyle=this.Sn.timeScale.borderColor;const e=Math.floor(this.Au.N().S*n),r=Math.floor(this.Au.N().S*s),h=this.Pp?i.width-e:0;t.fillRect(h,0,e,r)}$p({context:t,bitmapSize:i}){E(t,0,0,i.width,i.height,this.qv())}}function An(t){return i=>i.ia?.(t)??[]}const Bn=An("normal"),zn=An("top"),On=An("bottom");class Ln{constructor(t,i){this.Yv=null,this.Zv=null,this.M=null,this.Kv=!1,this.wp=Xi({width:0,height:0}),this.Xv=new o,this.Mp=new tt(5),this.Sp=!1,this.Cp=()=>{this.Sp||this.up.Qt().ar()},this.kp=()=>{this.Sp||this.up.Qt().ar()},this.up=t,this.qo=i,this.Sn=t.N().layout,this.ap=document.createElement("tr"),this.Gv=document.createElement("td"),this.Gv.style.padding="0",this.Jv=document.createElement("td"),this.Jv.style.padding="0",this.Pf=document.createElement("td"),this.Pf.style.height="25px",this.Pf.style.padding="0",this.Qv=document.createElement("div"),this.Qv.style.width="100%",this.Qv.style.height="100%",this.Qv.style.position="relative",this.Qv.style.overflow="hidden",this.Pf.appendChild(this.Qv),this.Ip=Mn(this.Qv,Xi({width:16,height:16})),this.Ip.subscribeSuggestedBitmapSizeChanged(this.Cp);const n=this.Ip.canvasElement;n.style.position="absolute",n.style.zIndex="1",n.style.left="0",n.style.top="0",this.Vp=Mn(this.Qv,Xi({width:16,height:16})),this.Vp.subscribeSuggestedBitmapSizeChanged(this.kp);const s=this.Vp.canvasElement;s.style.position="absolute",s.style.zIndex="2",s.style.left="0",s.style.top="0",this.ap.appendChild(this.Gv),this.ap.appendChild(this.Pf),this.ap.appendChild(this.Jv),this.tm(),this.up.Qt().do().i(this.tm.bind(this),this),this.gf=new on(this.Vp.canvasElement,this,{Fd:()=>!0,Hd:()=>!this.up.N().handleScroll.horzTouchDrag})}m(){this.gf.m(),null!==this.Yv&&this.Yv.m(),null!==this.Zv&&this.Zv.m(),this.Vp.unsubscribeSuggestedBitmapSizeChanged(this.kp),bn(this.Vp.canvasElement),this.Vp.dispose(),this.Ip.unsubscribeSuggestedBitmapSizeChanged(this.Cp),bn(this.Ip.canvasElement),this.Ip.dispose()}Df(){return this.ap}im(){return this.Yv}nm(){return this.Zv}if(t){if(this.Kv)return;this.Kv=!0;const i=this.up.Qt();!i.Et().Zi()&&this.up.N().handleScale.axisPressedMouseMove.time&&i.Qu(t.localX)}Qd(t){this.if(t)}nf(){const t=this.up.Qt();!t.Et().Zi()&&this.Kv&&(this.Kv=!1,this.up.N().handleScale.axisPressedMouseMove.time&&t.ac())}jd(t){const i=this.up.Qt();!i.Et().Zi()&&this.up.N().handleScale.axisPressedMouseMove.time&&i.hc(t.localX)}Ud(t){this.jd(t)}Kd(){this.Kv=!1;const t=this.up.Qt();t.Et().Zi()&&!this.up.N().handleScale.axisPressedMouseMove.time||t.ac()}Yd(){this.Kd()}Rd(){this.up.N().handleScale.axisDoubleClickReset.time&&this.up.Qt().us()}yd(){this.Rd()}zd(){this.up.Qt().N().handleScale.axisPressedMouseMove.time&&this.Xp(1)}cf(){this.Xp(0)}If(){return this.wp}sm(){return this.Xv}rm(t,i,n){Gi(this.wp,t)||(this.wp=t,this.Sp=!0,this.Ip.resizeCanvasElement(t),this.Vp.resizeCanvasElement(t),this.Sp=!1,this.Pf.style.width=`${t.width}px`,this.Pf.style.height=`${t.height}px`,this.Xv.p(t)),null!==this.Yv&&this.Yv.Wp(Xi({width:i,height:t.height})),null!==this.Zv&&this.Zv.Wp(Xi({width:n,height:t.height}))}hm(){const t=this.am();return Math.ceil(t.S+t.C+t.k+t.B+t.I+t.lm)}kt(){this.up.Qt().Et().Ia()}Vf(){return this.Ip.bitmapSize}Ef(t,i,n){const s=this.Vf();s.width>0&&s.height>0&&t.drawImage(this.Ip.canvasElement,i,n)}Hp(t){if(0===t)return;const i={colorSpace:this.Sn.colorSpace};if(1!==t){this.Ip.applySuggestedBitmapSize();const n=sn(this.Ip,i);null!==n&&(n.useBitmapCoordinateSpace((t=>{this.$p(t),this.jp(t),this.om(n,On)})),this.Yp(n),this.om(n,Bn)),null!==this.Yv&&this.Yv.Hp(t),null!==this.Zv&&this.Zv.Hp(t)}this.Vp.applySuggestedBitmapSize();const n=sn(this.Vp,i);null!==n&&(n.useBitmapCoordinateSpace((({context:t,bitmapSize:i})=>{t.clearRect(0,0,i.width,i.height)})),this._m([...this.up.Qt().jn(),this.up.Qt().qu()],n),this.om(n,zn))}om(t,i){const n=this.up.Qt().jn();for(const s of n)Cn(i,(i=>xn(i,t,!1,void 0)),s,void 0);for(const s of n)Cn(i,(i=>Sn(i,t,!1,void 0)),s,void 0)}$p({context:t,bitmapSize:i}){E(t,0,0,i.width,i.height,this.up.Qt().Sc())}jp({context:t,bitmapSize:i,verticalPixelRatio:n}){if(this.up.N().timeScale.borderVisible){t.fillStyle=this.um();const s=Math.max(1,Math.floor(this.am().S*n));t.fillRect(0,0,i.width,s)}}Yp(t){const i=this.up.Qt().Et(),n=i.Ia();if(!n||0===n.length)return;const s=this.qo.maxTickMarkWeight(n),e=this.am(),r=i.N();r.borderVisible&&r.ticksVisible&&t.useBitmapCoordinateSpace((({context:t,horizontalPixelRatio:i,verticalPixelRatio:s})=>{t.strokeStyle=this.um(),t.fillStyle=this.um();const r=Math.max(1,Math.floor(i)),h=Math.floor(.5*i);t.beginPath();const a=Math.round(e.C*s);for(let s=n.length;s--;){const e=Math.round(n[s].coord*i);t.rect(e-h,0,r,a)}t.fill()})),t.useMediaCoordinateSpace((({context:t})=>{const i=e.S+e.C+e.B+e.k/2;t.textAlign="center",t.textBaseline="middle",t.fillStyle=this.H(),t.font=this.Lp();for(const e of n)if(e.weight=s){const n=e.needAlignCoordinate?this.dm(t,e.coord,e.label):e.coord;t.fillText(e.label,n,i)}}))}dm(t,i,n){const s=this.Mp.Ii(t,n),e=s/2,r=Math.floor(i-e)+.5;return r<0?i+=Math.abs(0-r):r+s>this.wp.width&&(i-=Math.abs(this.wp.width-(r+s))),i}_m(t,i){const n=this.am();for(const s of t)for(const t of s.un())t.Tt().st(i,n)}um(){return this.up.N().timeScale.borderColor}H(){return this.Sn.textColor}W(){return this.Sn.fontSize}Lp(){return g(this.W(),this.Sn.fontFamily)}fm(){return g(this.W(),this.Sn.fontFamily,"bold")}am(){null===this.M&&(this.M={S:1,O:NaN,B:NaN,I:NaN,Ji:NaN,C:5,k:NaN,P:"",Gi:new tt,lm:0});const t=this.M,i=this.Lp();if(t.P!==i){const n=this.W();t.k=n,t.P=i,t.B=3*n/12,t.I=3*n/12,t.Ji=9*n/12,t.O=0,t.lm=4*n/12,t.Gi.Vs()}return this.M}Xp(t){this.Pf.style.cursor=1===t?"ew-resize":"default"}tm(){const t=this.up.Qt(),i=t.N();i.leftPriceScale.visible||null===this.Yv||(this.Gv.removeChild(this.Yv.Df()),this.Yv.m(),this.Yv=null),i.rightPriceScale.visible||null===this.Zv||(this.Jv.removeChild(this.Zv.Df()),this.Zv.m(),this.Zv=null);const n={dc:this.up.Qt().dc()},s=()=>i.leftPriceScale.borderVisible&&t.Et().N().borderVisible,e=()=>t.Sc();i.leftPriceScale.visible&&null===this.Yv&&(this.Yv=new En("left",i,n,s,e),this.Gv.appendChild(this.Yv.Df())),i.rightPriceScale.visible&&null===this.Zv&&(this.Zv=new En("right",i,n,s,e),this.Jv.appendChild(this.Zv.Df()))}}const Nn=!!en&&!!navigator.userAgentData&&navigator.userAgentData.brands.some((t=>t.brand.includes("Chromium")))&&!!en&&(navigator?.userAgentData?.platform?"Windows"===navigator.userAgentData.platform:navigator.userAgent.toLowerCase().indexOf("win")>=0);class Wn{constructor(t,i,n){var s;this.pm=[],this.vm=[],this.wm=0,this.Ya=0,this.so=0,this.gm=0,this.Mm=0,this.bm=null,this.xm=!1,this.sv=new o,this.ev=new o,this.Iu=new o,this.Sm=null,this.Cm=null,this._p=t,this.Sn=i,this.qo=n,this.ap=document.createElement("div"),this.ap.classList.add("tv-lightweight-charts"),this.ap.style.overflow="hidden",this.ap.style.direction="ltr",this.ap.style.width="100%",this.ap.style.height="100%",(s=this.ap).style.userSelect="none",s.style.webkitUserSelect="none",s.style.msUserSelect="none",s.style.MozUserSelect="none",s.style.webkitTapHighlightColor="transparent",this.ym=document.createElement("table"),this.ym.setAttribute("cellspacing","0"),this.ap.appendChild(this.ym),this.km=this.Pm.bind(this),Fn(this.Sn)&&this.Tm(!0),this.tn=new Ii(this.Eu.bind(this),this.Sn,n),this.Qt().Yu().i(this.Rm.bind(this),this),this.Dm=new Ln(this,this.qo),this.ym.appendChild(this.Dm.Df());const e=i.autoSize&&this.Im();let r=this.Sn.width,h=this.Sn.height;if(e||0===r||0===h){const i=t.getBoundingClientRect();r=r||i.width,h=h||i.height}this.Vm(r,h),this.Em(),t.appendChild(this.ap),this.Am(),this.tn.Et().pu().i(this.tn.Eh.bind(this.tn),this),this.tn.do().i(this.tn.Eh.bind(this.tn),this)}Qt(){return this.tn}N(){return this.Sn}Cf(){return this.pm}Bm(){return this.Dm}m(){this.Tm(!1),0!==this.wm&&window.cancelAnimationFrame(this.wm),this.tn.Yu().u(this),this.tn.Et().pu().u(this),this.tn.do().u(this),this.tn.m();for(const t of this.pm)this.ym.removeChild(t.Df()),t.Rv().u(this),t.Dv().u(this),t.m();this.pm=[];for(const t of this.vm)this.zm(t);this.vm=[],a(this.Dm).m(),null!==this.ap.parentElement&&this.ap.parentElement.removeChild(this.ap),this.Iu.m(),this.sv.m(),this.ev.m(),this.Om()}Vm(t,i,n=!1){if(this.Ya===i&&this.so===t)return;const s=function(t){const i=Math.floor(t.width),n=Math.floor(t.height);return Xi({width:i-i%2,height:n-n%2})}(Xi({width:t,height:i}));this.Ya=s.height,this.so=s.width;const e=this.Ya+"px",r=this.so+"px";a(this.ap).style.height=e,a(this.ap).style.width=r,this.ym.style.height=e,this.ym.style.width=r,n?this.Lm(Y.gs(),performance.now()):this.tn.Eh()}Hp(t){void 0===t&&(t=Y.gs());for(let i=0;i{t.kt()}))}Wm(t){(void 0!==t.autoSize||!this.Sm||void 0===t.width&&void 0===t.height)&&(t.autoSize&&!this.Sm&&this.Im(),!1===t.autoSize&&null!==this.Sm&&this.Om(),t.autoSize||void 0===t.width&&void 0===t.height||this.Vm(t.width||this.so,t.height||this.Ya))}Hm(t){let i=0,n=0;const s=this.pm[0],e=(i,n)=>{let s=0;for(let e=0;e{a("left"===i?this.Dm.im():this.Dm.nm()).Ef(a(t),n,s)};if(this.Sn.timeScale.visible){const i=this.Dm.Vf();if(null!==t){let e=0;this.$m()&&(r("left",e,n),e=a(s.Ov()).Vf().width),this.Dm.Ef(t,e,n),e+=i.width,this.jm()&&r("right",e,n)}n+=i.height}return Xi({width:i,height:n})}Xm(){let t=0,i=0,n=0;for(const s of this.pm)this.$m()&&(i=Math.max(i,a(s.Ov()).Op(),this.Sn.leftPriceScale.minimumWidth)),this.jm()&&(n=Math.max(n,a(s.Lv()).Op(),this.Sn.rightPriceScale.minimumWidth)),t+=s.fo();i=an(i),n=an(n);const s=this.so,e=this.Ya,r=Math.max(s-i-n,0),h=1*this.vm.length,l=this.Sn.timeScale.visible;let o=l?Math.max(this.Dm.hm(),this.Sn.timeScale.minimumHeight):0;var _;o=(_=o)+_%2;const u=h+o,c=e{t.gv()})),3===this.bm?.ts()&&(this.bm.ps(t),this.Jm(),this.Qm(this.bm),this.tw(this.bm,i),t=this.bm,this.bm=null)),this.Hp(t)}tw(t,i){for(const n of t.fs())this.vs(n,i)}Qm(t){const i=this.tn.Hn();for(let n=0;n{if(this.xm=!1,this.wm=0,null!==this.bm){const i=this.bm;this.bm=null,this.Lm(i,t);for(const n of i.fs())if(5===n.rs&&!n.Ft.uu(t)){this.Qt().ls(n.Ft);break}}})))}Jm(){this.Em()}zm(t){this.ym.removeChild(t.Df()),t.m()}Em(){const t=this.tn.Hn(),i=t.length,n=this.pm.length;for(let t=i;t0){const t=new pn(this,s-1,s);this.vm.push(t),this.ym.insertBefore(t.Df(),this.Dm.Df())}this.ym.insertBefore(i.Df(),this.Dm.Df())}for(let n=0;n{const n=i.Yn().Wr(t);null!==n&&e.set(i,n)}))}let r;if(null!==t){const i=this.tn.Et().nn(t)?.originalTime;void 0!==i&&(r=i)}const h=this.Qt().Hu(),a=null!==h&&h.Wo instanceof Ht?h.Wo:void 0,l=null!==h&&void 0!==h.Fo?h.Fo.Zs:void 0,o=this.ew(s);return{rw:r,Re:t??void 0,hw:i??void 0,aw:-1!==o?o:void 0,lw:a,ow:e,_w:l,uw:n??void 0}}ew(t){let i=-1;if(t)i=this.pm.indexOf(t);else{const t=this.Qt().qu().Fn();null!==t&&(i=this.Qt().Hn().indexOf(t))}return i}iw(t,i,n,s){this.sv.p((()=>this.sw(i,n,s,t)))}nw(t,i,n,s){this.ev.p((()=>this.sw(i,n,s,t)))}Rm(t,i,n){this.Iu.p((()=>this.sw(t,i,n)))}Am(){const t=this.Sn.timeScale.visible?"":"none";this.Dm.Df().style.display=t}$m(){return this.pm[0].Ff().Co().N().visible}jm(){return this.pm[0].Ff().yo().N().visible}Im(){return"ResizeObserver"in window&&(this.Sm=new ResizeObserver((t=>{const i=t[t.length-1];i&&this.Vm(i.contentRect.width,i.contentRect.height)})),this.Sm.observe(this._p,{box:"border-box"}),!0)}Om(){null!==this.Sm&&this.Sm.disconnect(),this.Sm=null}}function Fn(t){return Boolean(t.handleScroll.mouseWheel||t.handleScale.mouseWheel)}function Hn(t){return void 0===t.open&&void 0===t.value}function Un(t){return function(t){return void 0!==t.open}(t)||function(t){return void 0!==t.value}(t)}function $n(t,i,n,s){const e=n.value,r={Re:i,wt:t,Ft:[e,e,e,e],rw:s};return void 0!==n.color&&(r.R=n.color),r}function jn(t,i,n,s){const e=n.value,r={Re:i,wt:t,Ft:[e,e,e,e],rw:s};return void 0!==n.lineColor&&(r.vt=n.lineColor),void 0!==n.topColor&&(r.mr=n.topColor),void 0!==n.bottomColor&&(r.wr=n.bottomColor),r}function qn(t,i,n,s){const e=n.value,r={Re:i,wt:t,Ft:[e,e,e,e],rw:s};return void 0!==n.topLineColor&&(r.gr=n.topLineColor),void 0!==n.bottomLineColor&&(r.Mr=n.bottomLineColor),void 0!==n.topFillColor1&&(r.br=n.topFillColor1),void 0!==n.topFillColor2&&(r.Sr=n.topFillColor2),void 0!==n.bottomFillColor1&&(r.Cr=n.bottomFillColor1),void 0!==n.bottomFillColor2&&(r.yr=n.bottomFillColor2),r}function Yn(t,i,n,s){const e={Re:i,wt:t,Ft:[n.open,n.high,n.low,n.close],rw:s};return void 0!==n.color&&(e.R=n.color),e}function Zn(t,i,n,s){const e={Re:i,wt:t,Ft:[n.open,n.high,n.low,n.close],rw:s};return void 0!==n.color&&(e.R=n.color),void 0!==n.borderColor&&(e.Ht=n.borderColor),void 0!==n.wickColor&&(e.vr=n.wickColor),e}function Kn(t,i,n,s,e){const r=h(e)(n),a=Math.max(...r),l=Math.min(...r),o=r[r.length-1],_=[o,a,l,o],{time:u,color:c,...d}=n;return{Re:i,wt:t,Ft:_,rw:s,ne:d,R:c}}function Xn(t){return void 0!==t.Ft}function Gn(t,i){return void 0!==i.customValues&&(t.cw=i.customValues),t}function Jn(t){return(i,n,s,e,r,h)=>function(t,i){return i?i(t):Hn(t)}(s,h)?Gn({wt:i,Re:n,rw:e},s):Gn(t(i,n,s,e,r),s)}function Qn(t){return{Candlestick:Jn(Zn),Bar:Jn(Yn),Area:Jn(jn),Baseline:Jn(qn),Histogram:Jn($n),Line:Jn($n),Custom:Jn(Kn)}[t]}function ts(t){return{Re:0,dw:new Map,Hh:t}}function is(t,i){if(void 0!==t&&0!==t.length)return{fw:i.key(t[0].wt),pw:i.key(t[t.length-1].wt)}}function ns(t){let i;return t.forEach((t=>{void 0===i&&(i=t.rw)})),h(i)}class ss{constructor(t){this.mw=new Map,this.ww=new Map,this.gw=new Map,this.Mw=[],this.qo=t}m(){this.mw.clear(),this.ww.clear(),this.gw.clear(),this.Mw=[]}bw(t,i){let n=0!==this.mw.size,s=!1;const e=this.ww.get(t);if(void 0!==e)if(1===this.ww.size)n=!1,s=!0,this.mw.clear();else for(const i of this.Mw)i.pointData.dw.delete(t)&&(s=!0);let r=[];if(0!==i.length){const n=i.map((t=>t.time)),e=this.qo.createConverterToInternalObj(i),h=Qn(t.Rr()),a=t.da(),l=t.pa();r=i.map(((i,r)=>{const o=e(i.time),_=this.qo.key(o);let u=this.mw.get(_);void 0===u&&(u=ts(o),this.mw.set(_,u),s=!0);const c=h(o,u.Re,i,n[r],a,l);return u.dw.set(t,c),c}))}n&&this.xw(),this.Sw(t,r);let h=-1;if(s){const t=[];this.mw.forEach((i=>{t.push({timeWeight:0,time:i.Hh,pointData:i,originalTime:ns(i.dw)})})),t.sort(((t,i)=>this.qo.key(t.time)-this.qo.key(i.time))),h=this.Cw(t)}return this.yw(t,h,function(t,i,n){const s=is(t,n),e=is(i,n);if(void 0!==s&&void 0!==e)return{kw:!1,zh:s.pw>=e.pw&&s.fw>=e.fw}}(this.ww.get(t),e,this.qo))}mc(t){return this.bw(t,[])}Pw(t,i,n){const s=i;!function(t){void 0===t.rw&&(t.rw=t.time)}(s),this.qo.preprocessData(i);const e=this.qo.createConverterToInternalObj([i])(i.time),r=this.gw.get(t);if(!n&&void 0!==r&&this.qo.key(e)this.qo.key(t.time)this.qo.key(s.wt)?Xn(i)&&n.push(i):Xn(i)?n[n.length-1]=i:n.splice(-1,1),this.gw.set(t,i.wt)}Tw(t,i,n){const s=this.ww.get(t);if(void 0===s)return;const e=bt(s,n,((t,i)=>t.Re{0!==i.length&&(t=Math.max(t,i[i.length-1].Re))})),t}yw(t,i,n){const s={wo:new Map,Et:{q_:this.Dw()}};if(-1!==i)this.ww.forEach(((i,e)=>{s.wo.set(e,{ne:i,Iw:e===t?n:void 0})})),this.ww.has(t)||s.wo.set(t,{ne:[],Iw:n}),s.Et.Vw=this.Mw,s.Et.Ew=i;else{const i=this.ww.get(t);s.wo.set(t,{ne:i||[],Iw:n})}return s}}function es(t,i){t.Re=i,t.dw.forEach((t=>{t.Re=i}))}function rs(t,i){return t.wt0&&r=s&&(a=r-1),h>0&&h({...t,...this.Js.Rh().Dr(t.wt)})))}Uw(){this.Lw=null}Ww(){this.Bw&&(this.$w(),this.Bw=!1),this.zw&&(this.Hw(),this.zw=!1),this.Aw&&(this.jw(),this.Aw=!1)}jw(){const t=this.Js.Wt(),i=this.Qs.Et();if(this.Uw(),i.Zi()||t.Zi())return;const n=i.ye();if(null===n)return;if(0===this.Js.Yn().zr())return;const s=this.Js.Bt();null!==s&&(this.Lw=as(this.Ow,n,this.Nw),this.qw(t,i,s.Ft),this.Yw())}}class os{constructor(t,i){this.Zw=t,this.qi=i}st(t,i,n){this.Zw.draw(t,this.qi,i,n)}}class _s extends ls{constructor(t,i,n){super(t,i,!1),this.nh=n,this.Fw=new os(this.nh.renderer(),(i=>{const n=t.Bt();return null===n?null:t.Wt().Nt(i,n.Ft)}))}fa(t){return this.nh.priceValueBuilder(t)}va(t){return this.nh.isWhitespace(t)}$w(){const t=this.Js.Rh();this.Ow=this.Js.Yn().Hr().map((i=>({wt:i.Re,_t:NaN,...t.Dr(i.Re),Kw:i.ne})))}qw(t,i){i.Y_(this.Ow,m(this.Lw))}Yw(){this.nh.update({bars:this.Ow.map(us),barSpacing:this.Qs.Et().Q_(),visibleRange:this.Lw},this.Js.N())}}function us(t){return{x:t._t,time:t.wt,originalData:t.Kw,barColor:t.cr}}const cs={color:"#2196f3"},ds=(t,i,n)=>{const s=l(n);return new _s(t,i,s)};function fs(t){const i={value:t.Ft[3],time:t.rw};return void 0!==t.cw&&(i.customValues=t.cw),i}function ps(t){const i=fs(t);return void 0!==t.R&&(i.color=t.R),i}function vs(t){const i=fs(t);return void 0!==t.vt&&(i.lineColor=t.vt),void 0!==t.mr&&(i.topColor=t.mr),void 0!==t.wr&&(i.bottomColor=t.wr),i}function ms(t){const i=fs(t);return void 0!==t.gr&&(i.topLineColor=t.gr),void 0!==t.Mr&&(i.bottomLineColor=t.Mr),void 0!==t.br&&(i.topFillColor1=t.br),void 0!==t.Sr&&(i.topFillColor2=t.Sr),void 0!==t.Cr&&(i.bottomFillColor1=t.Cr),void 0!==t.yr&&(i.bottomFillColor2=t.yr),i}function ws(t){const i={open:t.Ft[0],high:t.Ft[1],low:t.Ft[2],close:t.Ft[3],time:t.rw};return void 0!==t.cw&&(i.customValues=t.cw),i}function gs(t){const i=ws(t);return void 0!==t.R&&(i.color=t.R),i}function Ms(t){const i=ws(t),{R:n,Ht:s,vr:e}=t;return void 0!==n&&(i.color=n),void 0!==s&&(i.borderColor=s),void 0!==e&&(i.wickColor=e),i}function bs(t){return{Area:vs,Line:ps,Baseline:ms,Histogram:ps,Bar:gs,Candlestick:Ms,Custom:xs}[t]}function xs(t){const i=t.rw;return{...t.ne,time:i}}const Ss={vertLine:{color:"#9598A1",width:1,style:3,visible:!0,labelVisible:!0,labelBackgroundColor:"#131722"},horzLine:{color:"#9598A1",width:1,style:3,visible:!0,labelVisible:!0,labelBackgroundColor:"#131722"},mode:1},Cs={vertLines:{color:"#D6DCDE",style:0,visible:!0},horzLines:{color:"#D6DCDE",style:0,visible:!0}},ys={background:{type:"solid",color:"#FFFFFF"},textColor:"#191919",fontSize:12,fontFamily:w,panes:{enableResize:!0,separatorColor:"#E0E3EB",separatorHoverColor:"rgba(178, 181, 189, 0.2)"},attributionLogo:!0,colorSpace:"srgb",colorParsers:[]},ks={autoScale:!0,mode:0,invertScale:!1,alignLabels:!0,borderVisible:!0,borderColor:"#2B2B43",entireTextOnly:!1,visible:!1,ticksVisible:!1,scaleMargins:{bottom:.1,top:.2},minimumWidth:0},Ps={rightOffset:0,barSpacing:6,minBarSpacing:.5,maxBarSpacing:0,fixLeftEdge:!1,fixRightEdge:!1,lockVisibleTimeRangeOnResize:!1,rightBarStaysOnScroll:!1,borderVisible:!0,borderColor:"#2B2B43",visible:!0,timeVisible:!1,secondsVisible:!0,shiftVisibleRangeOnNewBar:!0,allowShiftVisibleRangeOnWhitespaceReplacement:!1,ticksVisible:!1,uniformDistribution:!1,minimumHeight:0,allowBoldLabels:!0,ignoreWhitespaceIndices:!1};function Ts(){return{width:0,height:0,autoSize:!1,layout:ys,crosshair:Ss,grid:Cs,overlayPriceScales:{...ks},leftPriceScale:{...ks,visible:!1},rightPriceScale:{...ks,visible:!0},timeScale:Ps,localization:{locale:en?navigator.language:"",dateFormat:"dd MMM 'yy"},handleScroll:{mouseWheel:!0,pressedMouseMove:!0,horzTouchDrag:!0,vertTouchDrag:!0},handleScale:{axisPressedMouseMove:{time:!0,price:!0},axisDoubleClickReset:{time:!0,price:!0},mouseWheel:!0,pinch:!0},kineticScroll:{mouse:!1,touch:!0},trackingMode:{exitMode:1}}}class Rs{constructor(t,i,n,s){this.xf=t,this.yt=n,this.Xw=i,this.Gw=s}getHeight(){return this.yt.$t()}setHeight(t){const i=this.xf.Qt(),n=i.yc(this.yt);i.Xu(n,t)}paneIndex(){return this.xf.Qt().yc(this.yt)}moveTo(t){const i=this.paneIndex();i!==t&&(r(t>=0&&tthis.Xw(t)))??[]}getHTMLElement(){return this.xf.Cf()[this.paneIndex()].Df()}attachPrimitive(t){this.yt.ua(t),t.attached&&t.attached({chart:this.Gw,requestUpdate:()=>this.yt.Qt().Eh()})}detachPrimitive(t){this.yt.ca(t)}}class Ds{constructor(t,i){this.xf=t,this.Jw=i}applyOptions(t){this.xf.Qt().$u(this.Jw,t)}options(){return this.qi().N()}width(){return q(this.Jw)?this.xf.Um(this.Jw):0}qi(){return a(this.xf.Qt().ju(this.Jw)).Wt}}const Is={color:"#FF0000",price:0,lineStyle:2,lineWidth:1,lineVisible:!0,axisLabelVisible:!0,title:"",axisLabelColor:"",axisLabelTextColor:""};class Vs{constructor(t){this.ir=t}applyOptions(t){this.ir.hr(t)}options(){return this.ir.N()}Qw(){return this.ir}}class Es{constructor(t,i,n,s,e,r){this.tg=new o,this.Js=t,this.ig=i,this.ng=n,this.qo=e,this.Gw=s,this.sg=r}m(){this.tg.m()}priceFormatter(){return this.Js.ra()}priceToCoordinate(t){const i=this.Js.Bt();return null===i?null:this.Js.Wt().Nt(t,i.Ft)}coordinateToPrice(t){const i=this.Js.Bt();return null===i?null:this.Js.Wt().kn(t,i.Ft)}barsInLogicalRange(t){if(null===t)return null;const i=new Si(new Mi(t.from,t.to)).o_(),n=this.Js.Yn();if(n.Zi())return null;const s=n.Wr(i.Uh(),1),e=n.Wr(i.bi(),-1),r=a(n.Or()),h=a(n.qn());if(null!==s&&null!==e&&s.Re>e.Re)return{barsBefore:t.from-r,barsAfter:h-t.to};const l={barsBefore:null===s||s.Re===r?t.from-r:s.Re-r,barsAfter:null===e||e.Re===h?h-t.to:h-e.Re};return null!==s&&null!==e&&(l.from=s.rw,l.to=e.rw),l}setData(t){this.qo,this.Js.Rr(),this.ig.eg(this.Js,t),this.rg("full")}update(t,i=!1){this.Js.Rr(),this.ig.hg(this.Js,t,i),this.rg("update")}dataByIndex(t,i){const n=this.Js.Yn().Wr(t,i);if(null===n)return null;return bs(this.seriesType())(n)}data(){const t=bs(this.seriesType());return this.Js.Yn().Hr().map((i=>t(i)))}subscribeDataChanged(t){this.tg.i(t)}unsubscribeDataChanged(t){this.tg._(t)}applyOptions(t){this.Js.hr(t)}options(){return p(this.Js.N())}priceScale(){return this.ng.priceScale(this.Js.Wt().wa())}createPriceLine(t){const i=_(p(Is),t),n=this.Js.Lh(i);return new Vs(n)}removePriceLine(t){this.Js.Nh(t.Qw())}priceLines(){return this.Js.Wh().map((t=>new Vs(t)))}seriesType(){return this.Js.Rr()}attachPrimitive(t){this.Js.ua(t),t.attached&&t.attached({chart:this.Gw,series:this,requestUpdate:()=>this.Js.Qt().Eh(),horzScaleBehavior:this.qo})}detachPrimitive(t){this.Js.ca(t),t.detached&&t.detached(),this.Js.Qt().Eh()}getPane(){const t=this.Js,i=a(this.Js.Qt().Hs(t));return this.sg(i)}moveToPane(t){this.Js.Qt().bc(this.Js,t)}rg(t){this.tg.v()&&this.tg.p(t)}}class As{constructor(t,i,n){this.ag=new o,this.g_=new o,this.Xv=new o,this.tn=t,this.uh=t.Et(),this.Dm=i,this.uh.du().i(this.lg.bind(this)),this.uh.fu().i(this.og.bind(this)),this.Dm.sm().i(this._g.bind(this)),this.qo=n}m(){this.uh.du().u(this),this.uh.fu().u(this),this.Dm.sm().u(this),this.ag.m(),this.g_.m(),this.Xv.m()}scrollPosition(){return this.uh.iu()}scrollToPosition(t,i){i?this.uh._u(t,1e3):this.tn.ds(t)}scrollToRealTime(){this.uh.ou()}getVisibleRange(){const t=this.uh.L_();return null===t?null:{from:t.from.originalTime,to:t.to.originalTime}}setVisibleRange(t){const i={from:this.qo.convertHorzItemToInternal(t.from),to:this.qo.convertHorzItemToInternal(t.to)},n=this.uh.H_(i);this.tn.gc(n)}getVisibleLogicalRange(){const t=this.uh.O_();return null===t?null:{from:t.Uh(),to:t.bi()}}setVisibleLogicalRange(t){r(t.from<=t.to,"The from index cannot be after the to index."),this.tn.gc(t)}resetTimeScale(){this.tn.us()}fitContent(){this.tn.mu()}logicalToCoordinate(t){const i=this.tn.Et();return i.Zi()?null:i.jt(t)}coordinateToLogical(t){return this.uh.Zi()?null:this.uh.Z_(t)}timeToIndex(t,i){const n=this.qo.convertHorzItemToInternal(t);return this.uh.A_(n,i)}timeToCoordinate(t){const i=this.timeToIndex(t,!1);return null===i?null:this.uh.jt(i)}coordinateToTime(t){const i=this.tn.Et(),n=i.Z_(t),s=i.nn(n);return null===s?null:s.originalTime}width(){return this.Dm.If().width}height(){return this.Dm.If().height}subscribeVisibleTimeRangeChange(t){this.ag.i(t)}unsubscribeVisibleTimeRangeChange(t){this.ag._(t)}subscribeVisibleLogicalRangeChange(t){this.g_.i(t)}unsubscribeVisibleLogicalRangeChange(t){this.g_._(t)}subscribeSizeChange(t){this.Xv.i(t)}unsubscribeSizeChange(t){this.Xv._(t)}applyOptions(t){this.uh.hr(t)}options(){return{...p(this.uh.N()),barSpacing:this.uh.Q_()}}lg(){this.ag.v()&&this.ag.p(this.getVisibleRange())}og(){this.g_.v()&&this.g_.p(this.getVisibleLogicalRange())}_g(t){this.Xv.p(t.width,t.height)}}function Bs(t){if(void 0===t||"custom"===t.type)return;const i=t;void 0!==i.minMove&&void 0===i.precision&&(i.precision=function(t){if(t>=1)return 0;let i=0;for(;i<8;i++){const n=Math.round(t);if(Math.abs(n-t)<1e-8)return i;t*=10}return i}(i.minMove))}function zs(t){return function(t){if(f(t.handleScale)){const i=t.handleScale;t.handleScale={axisDoubleClickReset:{time:i,price:i},axisPressedMouseMove:{time:i,price:i},mouseWheel:i,pinch:i}}else if(void 0!==t.handleScale){const{axisPressedMouseMove:i,axisDoubleClickReset:n}=t.handleScale;f(i)&&(t.handleScale.axisPressedMouseMove={time:i,price:i}),f(n)&&(t.handleScale.axisDoubleClickReset={time:n,price:n})}const i=t.handleScroll;f(i)&&(t.handleScroll={horzTouchDrag:i,vertTouchDrag:i,mouseWheel:i,pressedMouseMove:i})}(t),t}class Os{constructor(t,i,n){this.ug=new Map,this.cg=new Map,this.dg=new o,this.fg=new o,this.pg=new o,this.Pu=new WeakMap,this.vg=new ss(i);const s=void 0===n?p(Ts()):_(p(Ts()),zs(n));this.mg=i,this.xf=new Wn(t,s,i),this.xf.Rv().i((t=>{this.dg.v()&&this.dg.p(this.wg(t()))}),this),this.xf.Dv().i((t=>{this.fg.v()&&this.fg.p(this.wg(t()))}),this),this.xf.Yu().i((t=>{this.pg.v()&&this.pg.p(this.wg(t()))}),this);const e=this.xf.Qt();this.gg=new As(e,this.xf.Bm(),this.mg)}remove(){this.xf.Rv().u(this),this.xf.Dv().u(this),this.xf.Yu().u(this),this.gg.m(),this.xf.m(),this.ug.clear(),this.cg.clear(),this.dg.m(),this.fg.m(),this.pg.m(),this.vg.m()}resize(t,i,n){this.autoSizeActive()||this.xf.Vm(t,i,n)}addCustomSeries(t,i={},n=0){const s=(t=>({type:"Custom",isBuiltIn:!1,defaultOptions:{...cs,...t.defaultOptions()},Mg:ds,bg:t}))(l(t));return this.xg(s,i,n)}addSeries(t,i={},n=0){return this.xg(t,i,n)}removeSeries(t){const i=h(this.ug.get(t)),n=this.vg.mc(i);this.xf.Qt().mc(i),this.Sg(n),this.ug.delete(t),this.cg.delete(i)}eg(t,i){this.Sg(this.vg.bw(t,i))}hg(t,i,n){this.Sg(this.vg.Pw(t,i,n))}subscribeClick(t){this.dg.i(t)}unsubscribeClick(t){this.dg._(t)}subscribeCrosshairMove(t){this.pg.i(t)}unsubscribeCrosshairMove(t){this.pg._(t)}subscribeDblClick(t){this.fg.i(t)}unsubscribeDblClick(t){this.fg._(t)}priceScale(t){return new Ds(this.xf,t)}timeScale(){return this.gg}applyOptions(t){this.xf.hr(zs(t))}options(){return this.xf.N()}takeScreenshot(){return this.xf.Fm()}removePane(t){this.xf.Qt().Ku(t)}swapPanes(t,i){this.xf.Qt().Gu(t,i)}autoSizeActive(){return this.xf.qm()}chartElement(){return this.xf.Bf()}panes(){return this.xf.Qt().Hn().map((t=>this.Cg(t)))}paneSize(t=0){const i=this.xf.Km(t);return{height:i.height,width:i.width}}setCrosshairPosition(t,i,n){const s=this.ug.get(n);if(void 0===s)return;const e=this.xf.Qt().Hs(s);null!==e&&this.xf.Qt()._c(t,i,e)}clearCrosshairPosition(){this.xf.Qt().uc(!0)}horzBehaviour(){return this.mg}xg(i,n={},s=0){r(void 0!==i.Mg),Bs(n.priceFormat),"Candlestick"===i.type&&function(t){void 0!==t.borderColor&&(t.borderUpColor=t.borderColor,t.borderDownColor=t.borderColor),void 0!==t.wickColor&&(t.wickUpColor=t.wickColor,t.wickDownColor=t.wickColor)}(n);const e=_(p(t),p(i.defaultOptions),n),h=i.Mg,a=new Ht(this.xf.Qt(),i.type,e,h,i.bg);this.xf.Qt().fc(a,s);const l=new Es(a,this,this,this,this.mg,(t=>this.Cg(t)));return this.ug.set(l,a),this.cg.set(a,l),l}Sg(t){const i=this.xf.Qt();i.cc(t.Et.q_,t.Et.Vw,t.Et.Ew),t.wo.forEach(((t,i)=>i.ht(t.ne,t.Iw))),i.Et().R_(),i.J_()}yg(t){return h(this.cg.get(t))}wg(t){const i=new Map;t.ow.forEach(((t,n)=>{const s=n.Rr(),e=bs(s)(t);if("Custom"!==s)r(Un(e));else{const t=n.pa();r(!t||!1===t(e))}i.set(this.yg(n),e)}));const n=void 0!==t.lw&&this.cg.has(t.lw)?this.yg(t.lw):void 0;return{time:t.rw,logical:t.Re,point:t.hw,paneIndex:t.aw,hoveredSeries:n,hoveredObjectId:t._w,seriesData:i,sourceEvent:t.uw}}Cg(t){let i=this.Pu.get(t);return i||(i=new Rs(this.xf,(t=>this.yg(t)),t,this),this.Pu.set(t,i)),i}}function Ls(t){if(d(t)){const i=document.getElementById(t);return r(null!==i,`Cannot find element in DOM with id=${t}`),i}return t}function Ns(t,i,n){const s=Ls(t),e=new Os(s,i,n);return i.setOptions(e.options()),e}class Ws extends ls{constructor(t,i){super(t,i,!0)}qw(t,i,n){i.Y_(this.Ow,m(this.Lw)),t.Dl(this.Ow,n,m(this.Lw))}kg(t,i){return{wt:t,gt:i,_t:NaN,ut:NaN}}$w(){const t=this.Js.Rh();this.Ow=this.Js.Yn().Hr().map((i=>{const n=i.Ft[3];return this.Pg(i.Re,n,t)}))}}function Fs(t,i,n,s,e,r,h){if(0===i.length||s.from>=i.length||s.to<=0)return;const{context:a,horizontalPixelRatio:l,verticalPixelRatio:o}=t,_=i[s.from];let u=r(t,_),c=_;if(s.to-s.from<2){const i=e/2;a.beginPath();const n={_t:_._t-i,ut:_.ut},s={_t:_._t+i,ut:_.ut};a.moveTo(n._t*l,n.ut*o),a.lineTo(s._t*l,s.ut*o),h(t,u,n,s)}else{const e=(i,n)=>{h(t,u,c,n),a.beginPath(),u=i,c=n};let d=c;a.beginPath(),a.moveTo(_._t*l,_.ut*o);for(let h=s.from+1;h=s.from;--n){const s=i[n];if(s){const i=e(t,s);i!==l&&(a.beginPath(),null!==l&&a.fill(),a.fillStyle=i,l=i);const n=Math.round(s._t*r)+o,u=s.ut*h;a.moveTo(n,u),a.arc(n,u,_,0,2*Math.PI)}}a.fill()}(t,i,l,n,_)}}class Zs extends Ys{Ig(t,i){return i.vt}}class Ks extends Ws{constructor(){super(...arguments),this.Fw=new Zs}Pg(t,i,n){return{...this.kg(t,i),...n.Dr(t)}}Yw(){const t=this.Js.N(),i={ot:this.Ow,Kt:t.lineStyle,Rg:t.lineVisible?t.lineType:void 0,ct:t.lineWidth,Dg:t.pointMarkersVisible?t.pointMarkersRadius||t.lineWidth/2+2:void 0,lt:this.Lw,Tg:this.Qs.Et().Q_()};this.Fw.ht(i)}}const Xs={type:"Line",isBuiltIn:!0,defaultOptions:{color:"#2196f3",lineStyle:0,lineWidth:3,lineType:0,lineVisible:!0,crosshairMarkerVisible:!0,crosshairMarkerRadius:4,crosshairMarkerBorderColor:"",crosshairMarkerBorderWidth:2,crosshairMarkerBackgroundColor:"",lastPriceAnimation:0,pointMarkersVisible:!1},Mg:(t,i)=>new Ks(t,i)};function Gs(t,i){return t.weight>i.weight?t:i}class Js{constructor(){this.Vg=new o,this.Eg=function(t){let i=!1;return function(...n){i||(i=!0,queueMicrotask((()=>{t(...n),i=!1})))}}((()=>this.Vg.p(this.Ag))),this.Ag=0}Bg(){return this.Vg}m(){this.Vg.m()}options(){return this.Sn}setOptions(t){this.Sn=t}preprocessData(t){}updateFormatter(t){this.Sn&&(this.Sn.localization=t)}createConverterToInternalObj(t){return this.Eg(),t=>(t>this.Ag&&(this.Ag=t),t)}key(t){return t}cacheKey(t){return t}convertHorzItemToInternal(t){return t}formatHorzItem(t){return this.zg(t)}formatTickmark(t){return this.zg(t.time)}maxTickMarkWeight(t){return t.reduce(Gs,t[0]).weight}fillWeightsForPoints(t,i){for(let s=i;st.toFixed(3)+"%"}},te={lastValueVisible:!1,priceLineVisible:!1};class ie extends Os{constructor(t,i){const n=_(Qs,i||{}),s=new Js;super(t,s,n),s.setOptions(this.options()),this._initWhitespaceSeries()}addSeries(t,i={},n=0){if(t.isBuiltIn&&!1===["Area","Line"].includes(t.type))throw new Error("Yield curve only support Area and Line series");const s={...te,...i};return super.addSeries(t,s,n)}_initWhitespaceSeries(){const t=this.horzBehaviour(),i=this.addSeries(Xs);let n;function s(s){const e=function(t,i){return{le:Math.max(0,t.startTimeRange),oe:Math.max(0,t.minimumTimeRange,i||0),Og:Math.max(1,t.baseResolution)}}(t.options().yieldCurve,s),r=(({le:t,oe:i,Og:n})=>`${t}~${i}~${n}`)(e);r!==n&&(n=r,i.setData(function({le:t,oe:i,Og:n}){return Array.from({length:Math.floor((i-t)/n)+1},((i,s)=>({time:t+s*n})))}(e)))}s(0),t.Bg().i(s)}}function ne(t,i){return t.weight>i.weight?t:i}class se{options(){return this.Sn}setOptions(t){this.Sn=t}preprocessData(t){}updateFormatter(t){this.Sn&&(this.Sn.localization=t)}createConverterToInternalObj(t){return t=>t}key(t){return t}cacheKey(t){return t}convertHorzItemToInternal(t){return t}formatHorzItem(t){return t.toFixed(this.Cs())}formatTickmark(t,i){return t.time.toFixed(this.Cs())}maxTickMarkWeight(t){return t.reduce(ne,t[0]).weight}fillWeightsForPoints(t,i){for(let s=i;s0?n:1,u=l*_,c=o===t.bitmapSize.height?o:o*_,d=(a??0)*_,f=t.context.createLinearGradient(0,u,0,c);if(f.addColorStop(0,s),null!=a){const t=si((d-u)/(c-u),0,1);f.addColorStop(t,e),f.addColorStop(t,r)}f.addColorStop(1,h),this.Kg=f,this.Hg=i}return this.Kg}}class ae extends re{constructor(){super(...arguments),this.Xg=new he}Wg(t,i){const n=this.rt;return this.Xg.Fg(t,{Ug:i.br,$g:i.Sr,jg:i.Cr,qg:i.yr,Lg:n.Lg,Yg:n.Yg??0,Zg:n.Zg??t.bitmapSize.height})}}class le extends Ys{constructor(){super(...arguments),this.Gg=new he}Ig(t,i){const n=this.rt;return this.Gg.Fg(t,{Ug:i.gr,$g:i.gr,jg:i.Mr,qg:i.Mr,Lg:n.Lg,Yg:n.Yg??0,Zg:n.Zg??t.bitmapSize.height})}}class oe extends Ws{constructor(t,i){super(t,i),this.Fw=new C,this.Jg=new ae,this.Qg=new le,this.Fw.nt([this.Jg,this.Qg])}Pg(t,i,n){return{...this.kg(t,i),...n.Dr(t)}}Yw(){const t=this.Js.Bt();if(null===t)return;const i=this.Js.N(),n=this.Js.Wt().Nt(i.baseValue.price,t.Ft),s=this.Qs.Et().Q_();if(null===this.Lw||0===this.Ow.length)return;let e,r;if(i.relativeGradient){e=this.Ow[this.Lw.from].ut,r=this.Ow[this.Lw.from].ut;for(let t=this.Lw.from;tr&&(r=i.ut)}}this.Jg.ht({ot:this.Ow,ct:i.lineWidth,Kt:i.lineStyle,Rg:i.lineType,Lg:n,Yg:e,Zg:r,Ng:!1,lt:this.Lw,Tg:s}),this.Qg.ht({ot:this.Ow,ct:i.lineWidth,Kt:i.lineStyle,Rg:i.lineVisible?i.lineType:void 0,Dg:i.pointMarkersVisible?i.pointMarkersRadius||i.lineWidth/2+2:void 0,Lg:n,Yg:e,Zg:r,lt:this.Lw,Tg:s})}}const _e={type:"Baseline",isBuiltIn:!0,defaultOptions:{baseValue:{type:"price",price:0},relativeGradient:!1,topFillColor1:"rgba(38, 166, 154, 0.28)",topFillColor2:"rgba(38, 166, 154, 0.05)",topLineColor:"rgba(38, 166, 154, 1)",bottomFillColor1:"rgba(239, 83, 80, 0.05)",bottomFillColor2:"rgba(239, 83, 80, 0.28)",bottomLineColor:"rgba(239, 83, 80, 1)",lineWidth:3,lineStyle:0,lineType:0,lineVisible:!0,crosshairMarkerVisible:!0,crosshairMarkerRadius:4,crosshairMarkerBorderColor:"",crosshairMarkerBorderWidth:2,crosshairMarkerBackgroundColor:"",lastPriceAnimation:0,pointMarkersVisible:!1},Mg:(t,i)=>new oe(t,i)};class ue extends re{constructor(){super(...arguments),this.Xg=new he}Wg(t,i){return this.Xg.Fg(t,{Ug:i.mr,$g:"",jg:"",qg:i.wr,Yg:this.rt?.Yg??0,Zg:t.bitmapSize.height})}}class ce extends Ws{constructor(t,i){super(t,i),this.Fw=new C,this.tM=new ue,this.iM=new Zs,this.Fw.nt([this.tM,this.iM])}Pg(t,i,n){return{...this.kg(t,i),...n.Dr(t)}}Yw(){const t=this.Js.N();if(null===this.Lw||0===this.Ow.length)return;let i;if(t.relativeGradient){i=this.Ow[this.Lw.from].ut;for(let t=this.Lw.from;tnew ce(t,i)};class fe extends y{constructor(){super(...arguments),this.qt=null,this.nM=0,this.sM=0}ht(t){this.qt=t}et({context:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(null===this.qt||0===this.qt.Yn.length||null===this.qt.lt)return;if(this.nM=this.eM(i),this.nM>=2){Math.max(1,Math.floor(i))%2!=this.nM%2&&this.nM--}this.sM=this.qt.rM?Math.min(this.nM,Math.floor(i)):this.nM;let s=null;const e=this.sM<=this.nM&&this.qt.Q_>=Math.floor(1.5*i);for(let r=this.qt.lt.from;rf+v-1&&(e=f+v-1,s=e-_+1),t.fillRect(i,s,o-i,e-s+1)}const i=l+m;let s=Math.max(f,Math.round(h.zl*n)-a),e=s+_-1;e>f+v-1&&(e=f+v-1,s=e-_+1),t.fillRect(u+1,s,i-u,e-s+1)}}}eM(t){const i=Math.floor(t);return Math.max(i,Math.floor(function(t,i){return Math.floor(.3*t*i)}(a(this.qt).Q_,t)))}}class pe extends ls{constructor(t,i){super(t,i,!1)}qw(t,i,n){i.Y_(this.Ow,m(this.Lw)),t.Vl(this.Ow,n,m(this.Lw))}aM(t,i,n){return{wt:t,jh:i.Ft[0],qh:i.Ft[1],Yh:i.Ft[2],Zh:i.Ft[3],_t:NaN,El:NaN,Al:NaN,Bl:NaN,zl:NaN}}$w(){const t=this.Js.Rh();this.Ow=this.Js.Yn().Hr().map((i=>this.Pg(i.Re,i,t)))}}class ve extends pe{constructor(){super(...arguments),this.Fw=new fe}Pg(t,i,n){return{...this.aM(t,i,n),...n.Dr(t)}}Yw(){const t=this.Js.N();this.Fw.ht({Yn:this.Ow,Q_:this.Qs.Et().Q_(),hM:t.openVisible,rM:t.thinBars,lt:this.Lw})}}const me={type:"Bar",isBuiltIn:!0,defaultOptions:{upColor:"#26a69a",downColor:"#ef5350",openVisible:!0,thinBars:!0},Mg:(t,i)=>new ve(t,i)};class we extends y{constructor(){super(...arguments),this.qt=null,this.nM=0}ht(t){this.qt=t}et(t){if(null===this.qt||0===this.qt.Yn.length||null===this.qt.lt)return;const{horizontalPixelRatio:i}=t;if(this.nM=function(t,i){if(t>=2.5&&t<=4)return Math.floor(3*i);const n=1-.2*Math.atan(Math.max(4,t)-4)/(.5*Math.PI),s=Math.floor(t*n*i),e=Math.floor(t*i),r=Math.min(s,e);return Math.max(Math.floor(i),r)}(this.qt.Q_,i),this.nM>=2){Math.floor(i)%2!=this.nM%2&&this.nM--}const n=this.qt.Yn;this.qt.lM&&this.oM(t,n,this.qt.lt),this.qt.Mi&&this.jp(t,n,this.qt.lt);const s=this._M(i);(!this.qt.Mi||this.nM>2*s)&&this.uM(t,n,this.qt.lt)}oM(t,i,n){if(null===this.qt)return;const{context:s,horizontalPixelRatio:e,verticalPixelRatio:r}=t;let h="",a=Math.min(Math.floor(e),Math.floor(this.qt.Q_*e));a=Math.max(Math.floor(e),Math.min(a,this.nM));const l=Math.floor(.5*a);let o=null;for(let t=n.from;t2*a)V(s,o,u,_-o+1,c-u+1,a);else{const t=_-o+1;s.fillRect(o,u,t,c-u+1)}l=_}}uM(t,i,n){if(null===this.qt)return;const{context:s,horizontalPixelRatio:e,verticalPixelRatio:r}=t;let h="";const a=this._M(e);for(let t=n.from;to||s.fillRect(_,l,u-_+1,o-l+1)}}}class ge extends pe{constructor(){super(...arguments),this.Fw=new we}Pg(t,i,n){return{...this.aM(t,i,n),...n.Dr(t)}}Yw(){const t=this.Js.N();this.Fw.ht({Yn:this.Ow,Q_:this.Qs.Et().Q_(),lM:t.wickVisible,Mi:t.borderVisible,lt:this.Lw})}}const Me={type:"Candlestick",isBuiltIn:!0,defaultOptions:{upColor:"#26a69a",downColor:"#ef5350",wickVisible:!0,borderVisible:!0,borderColor:"#378658",borderUpColor:"#26a69a",borderDownColor:"#ef5350",wickColor:"#737375",wickUpColor:"#26a69a",wickDownColor:"#ef5350"},Mg:(t,i)=>new ge(t,i)};class be extends y{constructor(){super(...arguments),this.qt=null,this.cM=[]}ht(t){this.qt=t,this.cM=[]}et({context:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(null===this.qt||0===this.qt.ot.length||null===this.qt.lt)return;this.cM.length||this.dM(i);const s=Math.max(1,Math.floor(n)),e=Math.round(this.qt.fM*n)-Math.floor(s/2),r=e+s;for(let i=this.qt.lt.from;is.se?s.bi=n.Uh-i-1:n.Uh=s.bi+i+1))}let s=Math.ceil(this.qt.Q_*t);for(let t=this.qt.lt.from;t0&&s<4)for(let t=this.qt.lt.from;ts&&(i.pM>i.se?i.bi-=1:i.Uh+=1)}}}class xe extends Ws{constructor(){super(...arguments),this.Fw=new be}Pg(t,i,n){return{...this.kg(t,i),...n.Dr(t)}}Yw(){const t={ot:this.Ow,Q_:this.Qs.Et().Q_(),lt:this.Lw,fM:this.Js.Wt().Nt(this.Js.N().base,a(this.Js.Bt()).Ft)};this.Fw.ht(t)}}const Se={type:"Histogram",isBuiltIn:!0,defaultOptions:{color:"#26a69a",base:0},Mg:(t,i)=>new xe(t,i)};class Ce{constructor(t,i){this.yt=t,this.vM=i,this.mM()}detach(){this.yt.detachPrimitive(this.vM)}getPane(){return this.yt}applyOptions(t){this.vM.hr?.(t)}mM(){this.yt.attachPrimitive(this.vM)}}const ye={visible:!0,horzAlign:"center",vertAlign:"center",lines:[]},ke={color:"rgba(0, 0, 0, 0.5)",fontSize:48,fontFamily:w,fontStyle:"",text:""};class Pe{constructor(t){this.wM=new Map,this.qt=t}draw(t){t.useMediaCoordinateSpace((t=>{if(!this.qt.visible)return;const{context:i,mediaSize:n}=t;let s=0;for(const t of this.qt.lines){if(0===t.text.length)continue;i.font=t.P;const e=this.gM(i,t.text);e>n.width?t.hu=n.width/e:t.hu=1,s+=t.lineHeight*t.hu}let e=0;switch(this.qt.vertAlign){case"top":e=0;break;case"center":e=Math.max((n.height-s)/2,0);break;case"bottom":e=Math.max(n.height-s,0)}for(const t of this.qt.lines){i.save(),i.fillStyle=t.color;let s=0;switch(this.qt.horzAlign){case"left":i.textAlign="left",s=t.lineHeight/2;break;case"center":i.textAlign="center",s=n.width/2;break;case"right":i.textAlign="right",s=n.width-1-t.lineHeight/2}i.translate(s,e),i.textBaseline="top",i.font=t.P,i.scale(t.hu,t.hu),i.fillText(t.text,0,t.MM),i.restore(),e+=t.lineHeight*t.hu}}))}gM(t,i){const n=this.bM(t.font);let s=n.get(i);return void 0===s&&(s=t.measureText(i).width,n.set(i,s)),s}bM(t){let i=this.wM.get(t);return void 0===i&&(i=new Map,this.wM.set(t,i)),i}}class Te{constructor(t){this.Sn=De(t)}kt(t){this.Sn=De(t)}renderer(){return new Pe(this.Sn)}}function Re(t){return{...t,P:g(t.fontSize,t.fontFamily,t.fontStyle),lineHeight:t.lineHeight||1.2*t.fontSize,MM:0,hu:0}}function De(t){return{...t,lines:t.lines.map(Re)}}function Ie(t){return{...ke,...t}}function Ve(t){return{...ye,...t,lines:t.lines?.map(Ie)??[]}}class Ee{constructor(t){this.Sn=Ve(t),this.xM=[new Te(this.Sn)]}updateAllViews(){this.xM.forEach((t=>t.kt(this.Sn)))}paneViews(){return this.xM}attached({requestUpdate:t}){this.SM=t}detached(){this.SM=void 0}hr(t){this.Sn=Ve({...this.Sn,...t}),this.SM&&this.SM()}}const Ae={alpha:1,padding:0};class Be{constructor(t){this.qt=t}draw(t){t.useMediaCoordinateSpace((t=>{const i=t.context,n=this.CM(this.qt,t.mediaSize);n&&this.qt.yM&&(i.globalAlpha=this.qt.alpha??1,i.drawImage(this.qt.yM,n._t,n.ut,n.Qi,n.$t))}))}CM(t,i){const{maxHeight:n,maxWidth:s,kM:e,PM:r,padding:h}=t,a=Math.round(i.width/2),l=Math.round(i.height/2),o=h??0;let _=i.width-2*o,u=i.height-2*o;n&&(u=Math.min(u,n)),s&&(_=Math.min(_,s));const c=_/r,d=u/e,f=Math.min(c,d),p=r*f,v=e*f;return{_t:a-.5*p,ut:l-.5*v,$t:v,Qi:p}}}class ze{constructor(t){this.TM=null,this.RM=0,this.DM=0,this.Sn=t,this.M=Oe(this.Sn,this.TM,this.RM,this.DM)}IM(t){void 0!==t.VM&&(this.RM=t.VM),void 0!==t.EM&&(this.DM=t.EM),void 0!==t.AM&&(this.TM=t.AM),this.kt()}BM(t){this.Sn=t,this.kt()}zOrder(){return"bottom"}kt(){this.M=Oe(this.Sn,this.TM,this.RM,this.DM)}renderer(){return new Be(this.M)}}function Oe(t,i,n,s){return{...t,yM:i,PM:n,kM:s}}function Le(t){return{...Ae,...t}}class Ne{constructor(t,i){this.zM=null,this.OM=t,this.Sn=Le(i),this.xM=[new ze(this.Sn)]}updateAllViews(){this.xM.forEach((t=>t.kt()))}paneViews(){return this.xM}attached(t){const{requestUpdate:i}=t;this.LM=i,this.zM=new Image,this.zM.onload=()=>{const t=this.zM?.naturalHeight??1,i=this.zM?.naturalWidth??1;this.xM.forEach((n=>n.IM({EM:t,VM:i,AM:this.zM}))),this.LM&&this.LM()},this.zM.src=this.OM}detached(){this.LM=void 0,this.zM=null}hr(t){this.Sn=Le({...this.Sn,...t}),this.NM(),this.SM&&this.SM()}SM(){this.LM&&this.LM()}NM(){this.xM.forEach((t=>t.BM(this.Sn)))}}class We{constructor(t,i){this.Js=t,this.ah=i,this.mM()}detach(){this.Js.detachPrimitive(this.ah)}getSeries(){return this.Js}applyOptions(t){this.ah&&this.ah.hr&&this.ah.hr(t)}mM(){this.Js.attachPrimitive(this.ah)}}function Fe(t,i){return ri(Math.min(Math.max(t,12),30)*i)}function He(t,i){switch(t){case"arrowDown":case"arrowUp":return Fe(i,1);case"circle":return Fe(i,.8);case"square":return Fe(i,.7)}}function Ue(t){return function(t){const i=Math.ceil(t);return i%2!=0?i-1:i}(Fe(t,1))}function $e(t){return Math.max(Fe(t,.1),3)}function je(t,i,n){return i?t:n?Math.ceil(t/2):0}function qe(t,i,n,s){const e=(He("arrowUp",s)-1)/2*n.WM,r=(ri(s/2)-1)/2*n.WM;i.beginPath(),t?(i.moveTo(n._t-e,n.ut),i.lineTo(n._t,n.ut-e),i.lineTo(n._t+e,n.ut),i.lineTo(n._t+r,n.ut),i.lineTo(n._t+r,n.ut+e),i.lineTo(n._t-r,n.ut+e),i.lineTo(n._t-r,n.ut)):(i.moveTo(n._t-e,n.ut),i.lineTo(n._t,n.ut+e),i.lineTo(n._t+e,n.ut),i.lineTo(n._t+r,n.ut),i.lineTo(n._t+r,n.ut-e),i.lineTo(n._t-r,n.ut-e),i.lineTo(n._t-r,n.ut)),i.fill()}function Ye(t,i,n,s,e,r){const h=(He("arrowUp",s)-1)/2,a=(ri(s/2)-1)/2;if(e>=i-a-2&&e<=i+a+2&&r>=(t?n:n-h)-2&&r<=(t?n+h:n)+2)return!0;return(()=>{if(ei+h+3||r<(t?n-h-3:n)||r>(t?n:n+h+3))return!1;const s=Math.abs(e-i);return Math.abs(r-n)+3>=s/2})()}class Ze{constructor(){this.qt=null,this.Ls=new tt,this.W=-1,this.F="",this.bp=""}ht(t){this.qt=t}Ns(t,i){this.W===t&&this.F===i||(this.W=t,this.F=i,this.bp=g(t,i),this.Ls.Vs())}Ys(t,i){if(null===this.qt||null===this.qt.lt)return null;for(let n=this.qt.lt.from;n{this.et(t)}))}et({context:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(null!==this.qt&&null!==this.qt.lt){t.textBaseline="middle",t.font=this.bp;for(let s=this.qt.lt.from;s=t&&e<=t+n&&r>=i-h&&r<=i+h}(t.ri._t,t.ri.ut,t.ri.Qi,t.ri.$t,i,n))||function(t,i,n){if(0===t.zr)return!1;switch(t.HM){case"arrowDown":return Ye(!0,t._t,t.ut,t.zr,i,n);case"arrowUp":return Ye(!1,t._t,t.ut,t.zr,i,n);case"circle":return function(t,i,n,s,e){const r=2+He("circle",n)/2,h=t-s,a=i-e;return Math.sqrt(h*h+a*a)<=r}(t._t,t.ut,t.zr,i,n);case"square":return function(t,i,n,s,e){const r=He("square",n),h=(r-1)/2,a=t-h,l=i-h;return s>=a&&s<=a+r&&e>=l&&e<=l+r}(t._t,t.ut,t.zr,i,n)}}(t,i,n)}function Ge(t,i,n,s,e,r,h,l){const o=l.timeScale();let _,c,d;if("value"in(f=n)&&"number"==typeof f.value)_=n.value,c=n.value,d=n.value;else{if(!function(t){return"open"in t&&"high"in t&&"low"in t&&"close"in t}(n))return;_=n.close,c=n.high,d=n.low}var f;const p=u(i.size)?Math.max(i.size,0):1,v=Ue(o.options().barSpacing)*p,m=v/2;switch(t.zr=v,i.position){case"inBar":return t.ut=a(h.priceToCoordinate(_)),void(void 0!==t.ri&&(t.ri.ut=t.ut+m+r+.6*e));case"aboveBar":return t.ut=a(h.priceToCoordinate(c))-m-s.UM,void 0!==t.ri&&(t.ri.ut=t.ut-m-.6*e,s.UM+=1.2*e),void(s.UM+=v+r);case"belowBar":return t.ut=a(h.priceToCoordinate(d))+m+s.$M,void 0!==t.ri&&(t.ri.ut=t.ut+m+r+.6*e,s.$M+=1.2*e),void(s.$M+=v+r)}i.position}class Je{constructor(t,i){this.jM=[],this.St=!0,this.qM=!0,this.Gt=new Ze,this.ge=t,this.up=i,this.qt={ot:[],lt:null}}renderer(){if(!this.ge.options().visible)return null;this.St&&this.YM();const t=this.up.options().layout;return this.Gt.Ns(t.fontSize,t.fontFamily),this.Gt.ht(this.qt),this.Gt}ZM(t){this.jM=t,this.kt("data")}kt(t){this.St=!0,"data"===t&&(this.qM=!0)}YM(){const t=this.up.timeScale(),i=this.jM;this.qM&&(this.qt.ot=i.map((t=>({wt:t.time,_t:0,ut:0,zr:0,HM:t.shape,R:t.color,Zs:t.id,KM:t.KM,ri:void 0}))),this.qM=!1);const n=this.up.options().layout;this.qt.lt=null;const s=t.getVisibleLogicalRange();if(null===s)return;const e=new Mi(Math.floor(s.from),Math.ceil(s.to));if(null===this.ge.data()[0])return;if(0===this.qt.ot.length)return;let r=NaN;const h=$e(t.options().barSpacing),l={UM:h,$M:h};this.qt.lt=as(this.qt.ot,e,!0);for(let s=this.qt.lt.from;s0&&(o.ri={FM:e.text,_t:0,ut:0,Qi:0,$t:0});const _=a(this.ge.dataByIndex(e.time,-1));null!==_&&Ge(o,e,_,l,n.fontSize,h,this.ge,this.up)}this.St=!1}}class Qe{constructor(){this.nh=null,this.jM=[],this.XM=[],this.GM=null,this.ge=null,this.up=null,this.JM=!0,this.QM=null,this.tb=null,this.ib=null}attached(t){this.nb(),this.up=t.chart,this.ge=t.series,this.nh=new Je(this.ge,a(this.up)),this.LM=t.requestUpdate,this.ge.subscribeDataChanged((t=>this.rg(t))),this.SM()}SM(){this.LM&&this.LM()}detached(){this.ge&&this.GM&&this.ge.unsubscribeDataChanged(this.GM),this.up=null,this.ge=null,this.nh=null,this.GM=null}ZM(t){this.jM=t,this.nb(),this.JM=!0,this.tb=null,this.SM()}sb(){return this.jM}paneViews(){return this.nh?[this.nh]:[]}updateAllViews(){this.eb()}hitTest(t,i){return this.nh?this.nh.renderer()?.Ys(t,i)??null:null}autoscaleInfo(t,i){if(this.nh){const t=this.rb();if(t)return{priceRange:null,margins:t}}return null}rb(){const t=a(this.up).timeScale().options().barSpacing;if(this.JM||t!==this.ib){if(this.ib=t,this.jM.length>0){const i=$e(t),n=1.5*Ue(t)+2*i,s=this.hb();this.QM={above:je(n,s.aboveBar,s.inBar),below:je(n,s.belowBar,s.inBar)}}else this.QM=null;this.JM=!1}return this.QM}hb(){return null===this.tb&&(this.tb=this.jM.reduce(((t,i)=>(t[i.position]||(t[i.position]=!0),t)),{inBar:!1,aboveBar:!1,belowBar:!1})),this.tb}nb(){if(!this.up||!this.ge)return;const t=this.up.timeScale();if(null==t.getVisibleLogicalRange()||!this.ge||0===this.ge?.data().length)return void(this.XM=[]);const i=this.ge?.data(),n=t.timeToIndex(a(i[0].time),!0);this.XM=this.jM.map(((i,s)=>{const e=t.timeToIndex(i.time,!0),r=e{this.jM.delete(i),this._b()}),n),e={...t,ub:s,cb:Date.now()+n};this.jM.set(i,e)}else this.jM.set(i,{...t,ub:void 0,cb:void 0});this._b()}ob(t){const i=this.jM.get(t);i&&void 0!==i.ub&&window.clearTimeout(i.ub),this.jM.delete(t),this._b()}fb(){for(const[t]of this.jM)this.ob(t)}pb(){const t=Date.now(),i=[];for(const[n,s]of this.jM)!s.cb||s.cb>t?i.push({time:s.time,sign:s.sign,value:s.value}):this.ob(n);return i}mb(t){this.ab=t}_b(){this.ab&&this.ab()}}const nr={positiveColor:"#22AB94",negativeColor:"#F7525F",updateVisibilityDuration:5e3};class sr{constructor(t,i,n,s){this.qt=t,this.wb=i,this.gb=n,this.Mb=s}draw(t){t.useBitmapCoordinateSpace((t=>{const i=t.context,n=Math.max(1,Math.floor(t.horizontalPixelRatio))%2/2,s=4*t.verticalPixelRatio+n;this.qt.forEach((e=>{const r=Math.round(e._t*t.horizontalPixelRatio)+n;i.beginPath();const h=this.bb(e.xb);i.fillStyle=h,i.arc(r,e.ut*t.verticalPixelRatio,s,0,2*Math.PI,!1),i.fill(),e.xb&&(i.strokeStyle=h,i.lineWidth=Math.floor(2*t.horizontalPixelRatio),i.beginPath(),i.moveTo((e._t-4.7)*t.horizontalPixelRatio+n,(e.ut-7*e.xb)*t.verticalPixelRatio),i.lineTo(e._t*t.horizontalPixelRatio+n,(e.ut-7*e.xb-7*e.xb*.5)*t.verticalPixelRatio),i.lineTo((e._t+4.7)*t.horizontalPixelRatio+n,(e.ut-7*e.xb)*t.verticalPixelRatio),i.stroke())}))}))}bb(t){return 0===t?this.wb:t>0?this.Mb:this.gb}}class er{constructor(t,i,n){this.qt=[],this.ge=t,this.uh=i,this.Sn=n}kt(t){this.qt=t.map((t=>{const i=this.ge.priceToCoordinate(t.value);if(null===i)return null;return{_t:a(this.uh.timeToCoordinate(t.time)),ut:i,xb:t.sign}})).filter(v)}renderer(){const t=function(t,i){return function(t,i){return"Area"===i}(0,i)?t.lineColor:t.color}(this.ge.options(),this.ge.seriesType());return new sr(this.qt,t,this.Sn.negativeColor,this.Sn.positiveColor)}}function rr(t,i){return"Line"===i||"Area"===i}class hr{constructor(t){this.up=void 0,this.ge=void 0,this.xM=[],this.qo=null,this.Sb=new Map,this.Cb=new ir((()=>this.SM())),this.Sn={...nr,...t}}hr(t){this.Sn={...this.Sn,...t},this.SM()}ZM(t){this.Cb.fb();const i=this.qo;i&&t.forEach((t=>{this.Cb.lb(t,i.key(t.time))}))}sb(){return this.Cb.pb()}SM(){this.LM?.()}attached(t){const{chart:i,series:n,requestUpdate:s,horzScaleBehavior:e}=t;this.up=i,this.ge=n,this.qo=e;const r=this.ge.seriesType();if("Area"!==r&&"Line"!==r)throw new Error("UpDownMarkersPrimitive is only supported for Area and Line series types");this.xM=[new er(this.ge,this.up.timeScale(),this.Sn)],this.LM=s,this.SM()}detached(){this.up=void 0,this.ge=void 0,this.LM=void 0}yp(){return h(this.up)}wo(){return h(this.ge)}updateAllViews(){this.xM.forEach((t=>t.kt(this.sb())))}paneViews(){return this.xM}ht(t){if(!this.ge)throw new Error("Primitive not attached to series");const i=this.ge.seriesType();this.Sb.clear();const n=this.qo;n&&t.forEach((t=>{Un(t)&&rr(0,i)&&this.Sb.set(n.key(t.time),t.value)})),h(this.ge).setData(t)}kt(t,i){if(!this.ge||!this.qo)throw new Error("Primitive not attached to series");const n=this.ge.seriesType(),s=this.qo.key(t.time);if(Hn(t)&&this.Sb.delete(s),Un(t)&&rr(0,n)){const i=this.Sb.get(s);i&&this.Cb.lb({time:t.time,value:t.value,sign:ar(t.value,i)},s,this.Sn.updateVisibilityDuration)}h(this.ge).update(t,i)}yb(){this.Cb.fb()}}function ar(t,i){return t===i?0:t-i>0?1:-1}class lr extends We{setData(t){return this.ah.ht(t)}update(t,i){return this.ah.kt(t,i)}markers(){return this.ah.sb()}setMarkers(t){return this.ah.ZM(t)}clearMarkers(){return this.ah.yb()}}const or={...t,color:"#2196f3"};var _r=Object.freeze({__proto__:null,AreaSeries:de,BarSeries:me,BaselineSeries:_e,CandlestickSeries:Me,get ColorType(){return Ri},get CrosshairMode(){return $},HistogramSeries:Se,get LastPriceAnimationMode(){return Pi},LineSeries:Xs,get LineStyle(){return n},get LineType(){return i},get MismatchDirection(){return St},get PriceLineSource(){return Ti},get PriceScaleMode(){return oi},get TickMarkType(){return Di},get TrackingModeExitMode(){return ki},createChart:function(t,i){return Ns(t,new Ki,Ki.Fc(i))},createChartEx:Ns,createImageWatermark:function(t,i,n){return new Ce(t,new Ne(i,n))},createOptionsChart:function(t,i){return Ns(t,new se,i)},createSeriesMarkers:function(t,i){const n=new tr(t,new Qe);return i&&n.setMarkers(i),n},createTextWatermark:function(t,i){return new Ce(t,new Ee(i))},createUpDownMarkers:function(t,i={}){return new lr(t,new hr(i))},createYieldCurveChart:function(t,i){const n=Ls(t);return new ie(n,i)},customSeriesDefaultOptions:or,defaultHorzScaleBehavior:function(){return Ki},isBusinessDay:Vi,isUTCTimestamp:Ei,version:function(){return"5.0.1"}});window.LightweightCharts=_r}(); +!function(){"use strict";const t={title:"",visible:!0,lastValueVisible:!0,priceLineVisible:!0,priceLineSource:0,priceLineWidth:1,priceLineColor:"",priceLineStyle:2,baseLineVisible:!0,baseLineWidth:1,baseLineColor:"#B2B5BE",baseLineStyle:0,priceFormat:{type:"price",precision:2,minMove:.01}};var i,s;function n(t,i){const s={0:[],1:[t.lineWidth,t.lineWidth],2:[2*t.lineWidth,2*t.lineWidth],3:[6*t.lineWidth,6*t.lineWidth],4:[t.lineWidth,4*t.lineWidth]}[i];t.setLineDash(s)}function e(t,i,s,n){t.beginPath();const e=t.lineWidth%2?.5:0;t.moveTo(s,i+e),t.lineTo(n,i+e),t.stroke()}function r(t,i){if(!t)throw new Error("Assertion failed"+(i?": "+i:""))}function h(t){if(void 0===t)throw new Error("Value is undefined");return t}function a(t){if(null===t)throw new Error("Value is null");return t}function l(t){return a(h(t))}!function(t){t[t.Simple=0]="Simple",t[t.WithSteps=1]="WithSteps",t[t.Curved=2]="Curved"}(i||(i={})),function(t){t[t.Solid=0]="Solid",t[t.Dotted=1]="Dotted",t[t.Dashed=2]="Dashed",t[t.LargeDashed=3]="LargeDashed",t[t.SparseDotted=4]="SparseDotted"}(s||(s={}));class o{constructor(){this.t=[]}i(t,i,s){const n={h:t,l:i,o:!0===s};this.t.push(n)}_(t){const i=this.t.findIndex((i=>t===i.h));i>-1&&this.t.splice(i,1)}u(t){this.t=this.t.filter((i=>i.l!==t))}p(t,i,s){const n=[...this.t];this.t=this.t.filter((t=>!t.o)),n.forEach((n=>n.h(t,i,s)))}v(){return this.t.length>0}m(){this.t=[]}}function _(t,...i){for(const s of i)for(const i in s)void 0!==s[i]&&Object.prototype.hasOwnProperty.call(s,i)&&!["__proto__","constructor","prototype"].includes(i)&&("object"!=typeof s[i]||void 0===t[i]||Array.isArray(s[i])?t[i]=s[i]:_(t[i],s[i]));return t}function u(t){return"number"==typeof t&&isFinite(t)}function c(t){return"number"==typeof t&&t%1==0}function d(t){return"string"==typeof t}function f(t){return"boolean"==typeof t}function p(t){const i=t;if(!i||"object"!=typeof i)return i;let s,n,e;for(n in s=Array.isArray(i)?[]:{},i)i.hasOwnProperty(n)&&(e=i[n],s[n]=e&&"object"==typeof e?p(e):e);return s}function v(t){return null!==t}function m(t){return null===t?void 0:t}const w="-apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif";function g(t,i,s){return void 0===i&&(i=w),`${s=void 0!==s?`${s} `:""}${t}px ${i}`}class M{constructor(t){this.M={S:1,C:5,P:NaN,k:"",T:"",R:"",D:"",B:0,I:0,V:0,A:0,O:0},this.L=t}N(){const t=this.M,i=this.W(),s=this.F();return t.P===i&&t.T===s||(t.P=i,t.T=s,t.k=g(i,s),t.A=2.5/12*i,t.B=t.A,t.I=i/12*t.C,t.V=i/12*t.C,t.O=0),t.R=this.H(),t.D=this.U(),this.M}H(){return this.L.N().layout.textColor}U(){return this.L.$()}W(){return this.L.N().layout.fontSize}F(){return this.L.N().layout.fontFamily}}function b(t){return t<0?0:t>255?255:Math.round(t)||0}function x(t){return.199*t[0]+.687*t[1]+.114*t[2]}class S{constructor(t,i){this.j=new Map,this.q=t,i&&(this.j=i)}Y(t,i){if("transparent"===t)return t;const s=this.K(t),n=s[3];return`rgba(${s[0]}, ${s[1]}, ${s[2]}, ${i*n})`}X(t){const i=this.K(t);return{Z:`rgb(${i[0]}, ${i[1]}, ${i[2]})`,G:x(i)>160?"black":"white"}}J(t){return x(this.K(t))}tt(t,i,s){const[n,e,r,h]=this.K(t),[a,l,o,_]=this.K(i),u=[b(n+s*(a-n)),b(e+s*(l-e)),b(r+s*(o-r)),(c=h+s*(_-h),c<=0||c>1?Math.min(Math.max(c,0),1):Math.round(1e4*c)/1e4)];var c;return`rgba(${u[0]}, ${u[1]}, ${u[2]}, ${u[3]})`}K(t){const i=this.j.get(t);if(i)return i;const s=function(t){const i=document.createElement("div");i.style.display="none",document.body.appendChild(i),i.style.color=t;const s=window.getComputedStyle(i).color;return document.body.removeChild(i),s}(t),n=s.match(/^rgba?\s*\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d*\.?\d+))?\)$/);if(!n){if(this.q.length)for(const i of this.q){const s=i(t);if(s)return this.j.set(t,s),s}throw new Error(`Failed to parse color: ${t}`)}const e=[parseInt(n[1],10),parseInt(n[2],10),parseInt(n[3],10),n[4]?parseFloat(n[4]):1];return this.j.set(t,e),e}}class C{constructor(){this.it=[]}st(t){this.it=t}nt(t,i,s){this.it.forEach((n=>{n.nt(t,i,s)}))}}class y{nt(t,i,s){t.useBitmapCoordinateSpace((t=>this.et(t,i,s)))}}class P extends y{constructor(){super(...arguments),this.rt=null}ht(t){this.rt=t}et({context:t,horizontalPixelRatio:i,verticalPixelRatio:s}){if(null===this.rt||null===this.rt.lt)return;const n=this.rt.lt,e=this.rt,r=Math.max(1,Math.floor(i))%2/2,h=h=>{t.beginPath();for(let a=n.to-1;a>=n.from;--a){const n=e.ot[a],l=Math.round(n._t*i)+r,o=n.ut*s,_=h*s+r;t.moveTo(l,o),t.arc(l,o,_,0,2*Math.PI)}t.fill()};e.ct>0&&(t.fillStyle=e.dt,h(e.ft+e.ct)),t.fillStyle=e.vt,h(e.ft)}}function k(){return{ot:[{_t:0,ut:0,wt:0,gt:0}],vt:"",dt:"",ft:0,ct:0,lt:null}}const T={from:0,to:1};class R{constructor(t,i,s){this.Mt=new C,this.bt=[],this.xt=[],this.St=!0,this.L=t,this.Ct=i,this.yt=s,this.Mt.st(this.bt)}Pt(t){this.kt(),this.St=!0}Tt(){return this.St&&(this.Rt(),this.St=!1),this.Mt}kt(){const t=this.yt.Dt();t.length!==this.bt.length&&(this.xt=t.map(k),this.bt=this.xt.map((t=>{const i=new P;return i.ht(t),i})),this.Mt.st(this.bt))}Rt(){const t=2===this.Ct.N().mode||!this.Ct.Bt(),i=this.yt.Et(),s=this.Ct.It(),n=this.L.Vt();this.kt(),i.forEach(((i,e)=>{const r=this.xt[e],h=i.At(s),a=i.zt();!t&&null!==h&&i.Bt()&&null!==a?(r.vt=h.Ot,r.ft=h.ft,r.ct=h.Lt,r.ot[0].gt=h.gt,r.ot[0].ut=i.Wt().Nt(h.gt,a.Ft),r.dt=h.Ht??this.L.Ut(r.ot[0].ut/i.Wt().$t()),r.ot[0].wt=s,r.ot[0]._t=n.jt(s),r.lt=T):r.lt=null}))}}class D extends y{constructor(t){super(),this.qt=t}et({context:t,bitmapSize:i,horizontalPixelRatio:s,verticalPixelRatio:r}){if(null===this.qt)return;const h=this.qt.Yt.Bt,a=this.qt.Kt.Bt;if(!h&&!a)return;const l=Math.round(this.qt._t*s),o=Math.round(this.qt.ut*r);t.lineCap="butt",h&&l>=0&&(t.lineWidth=Math.floor(this.qt.Yt.ct*s),t.strokeStyle=this.qt.Yt.R,t.fillStyle=this.qt.Yt.R,n(t,this.qt.Yt.Xt),function(t,i,s,n){t.beginPath();const e=t.lineWidth%2?.5:0;t.moveTo(i+e,s),t.lineTo(i+e,n),t.stroke()}(t,l,0,i.height)),a&&o>=0&&(t.lineWidth=Math.floor(this.qt.Kt.ct*r),t.strokeStyle=this.qt.Kt.R,t.fillStyle=this.qt.Kt.R,n(t,this.qt.Kt.Xt),e(t,o,0,i.width))}}class B{constructor(t,i){this.St=!0,this.Zt={Yt:{ct:1,Xt:0,R:"",Bt:!1},Kt:{ct:1,Xt:0,R:"",Bt:!1},_t:0,ut:0},this.Gt=new D(this.Zt),this.Jt=t,this.yt=i}Pt(){this.St=!0}Tt(t){return this.St&&(this.Rt(),this.St=!1),this.Gt}Rt(){const t=this.Jt.Bt(),i=this.yt.Qt().N().crosshair,s=this.Zt;if(2===i.mode)return s.Kt.Bt=!1,void(s.Yt.Bt=!1);s.Kt.Bt=t&&this.Jt.ti(this.yt),s.Yt.Bt=t&&this.Jt.ii(),s.Kt.ct=i.horzLine.width,s.Kt.Xt=i.horzLine.style,s.Kt.R=i.horzLine.color,s.Yt.ct=i.vertLine.width,s.Yt.Xt=i.vertLine.style,s.Yt.R=i.vertLine.color,s._t=this.Jt.si(),s.ut=this.Jt.ni()}}function E(t,i,s,n,e,r){t.fillRect(i+r,s,n-2*r,r),t.fillRect(i+r,s+e-r,n-2*r,r),t.fillRect(i,s,r,e),t.fillRect(i+n-r,s,r,e)}function I(t,i,s,n,e,r){t.save(),t.globalCompositeOperation="copy",t.fillStyle=r,t.fillRect(i,s,n,e),t.restore()}function V(t,i,s,n,e,r){t.beginPath(),t.roundRect?t.roundRect(i,s,n,e,r):(t.lineTo(i+n-r[1],s),0!==r[1]&&t.arcTo(i+n,s,i+n,s+r[1],r[1]),t.lineTo(i+n,s+e-r[2]),0!==r[2]&&t.arcTo(i+n,s+e,i+n-r[2],s+e,r[2]),t.lineTo(i+r[3],s+e),0!==r[3]&&t.arcTo(i,s+e,i,s+e-r[3],r[3]),t.lineTo(i,s+r[0]),0!==r[0]&&t.arcTo(i,s,i+r[0],s,r[0]))}function A(t,i,s,n,e,r,h=0,a=[0,0,0,0],l=""){if(t.save(),!h||!l||l===r)return V(t,i,s,n,e,a),t.fillStyle=r,t.fill(),void t.restore();const o=h/2;var _;V(t,i+o,s+o,n-h,e-h,(_=-o,a.map((t=>0===t?t:t+_)))),"transparent"!==r&&(t.fillStyle=r,t.fill()),"transparent"!==l&&(t.lineWidth=h,t.strokeStyle=l,t.closePath(),t.stroke()),t.restore()}function z(t,i,s,n,e,r,h){t.save(),t.globalCompositeOperation="copy";const a=t.createLinearGradient(0,0,0,e);a.addColorStop(0,r),a.addColorStop(1,h),t.fillStyle=a,t.fillRect(i,s,n,e),t.restore()}class O{constructor(t,i){this.ht(t,i)}ht(t,i){this.qt=t,this.ei=i}$t(t,i){return this.qt.Bt?t.P+t.A+t.B:0}nt(t,i,s,n){if(!this.qt.Bt||0===this.qt.ri.length)return;const e=this.qt.R,r=this.ei.Z,h=t.useBitmapCoordinateSpace((t=>{const h=t.context;h.font=i.k;const a=this.hi(t,i,s,n),l=a.ai;return a.li?A(h,l.oi,l._i,l.ui,l.ci,r,l.di,[l.ft,0,0,l.ft],r):A(h,l.fi,l._i,l.ui,l.ci,r,l.di,[0,l.ft,l.ft,0],r),this.qt.pi&&(h.fillStyle=e,h.fillRect(l.fi,l.mi,l.wi-l.fi,l.gi)),this.qt.Mi&&(h.fillStyle=i.D,h.fillRect(a.li?l.bi-l.di:0,l._i,l.di,l.xi-l._i)),a}));t.useMediaCoordinateSpace((({context:t})=>{const s=h.Si;t.font=i.k,t.textAlign=h.li?"right":"left",t.textBaseline="middle",t.fillStyle=e,t.fillText(this.qt.ri,s.Ci,(s._i+s.xi)/2+s.yi)}))}hi(t,i,s,n){const{context:e,bitmapSize:r,mediaSize:h,horizontalPixelRatio:a,verticalPixelRatio:l}=t,o=this.qt.pi||!this.qt.Pi?i.C:0,_=this.qt.ki?i.S:0,u=i.A+this.ei.Ti,c=i.B+this.ei.Ri,d=i.I,f=i.V,p=this.qt.ri,v=i.P,m=s.Di(e,p),w=Math.ceil(s.Bi(e,p)),g=v+u+c,M=i.S+d+f+w+o,b=Math.max(1,Math.floor(l));let x=Math.round(g*l);x%2!=b%2&&(x+=1);const S=_>0?Math.max(1,Math.floor(_*a)):0,C=Math.round(M*a),y=Math.round(o*a),P=this.ei.Ei??this.ei.Ii,k=Math.round(P*l)-Math.floor(.5*l),T=Math.floor(k+b/2-x/2),R=T+x,D="right"===n,B=D?h.width-_:_,E=D?r.width-S:S;let I,V,A;return D?(I=E-C,V=E-y,A=B-o-d-_):(I=E+C,V=E+y,A=B+o+d),{li:D,ai:{_i:T,mi:k,xi:R,ui:C,ci:x,ft:2*a,di:S,oi:I,fi:E,wi:V,gi:b,bi:r.width},Si:{_i:T/l,xi:R/l,Ci:A,yi:m}}}}class L{constructor(t){this.Vi={Ii:0,Z:"#000",Ri:0,Ti:0},this.Ai={ri:"",Bt:!1,pi:!0,Pi:!1,Ht:"",R:"#FFF",Mi:!1,ki:!1},this.zi={ri:"",Bt:!1,pi:!1,Pi:!0,Ht:"",R:"#FFF",Mi:!0,ki:!0},this.St=!0,this.Oi=new(t||O)(this.Ai,this.Vi),this.Li=new(t||O)(this.zi,this.Vi)}ri(){return this.Ni(),this.Ai.ri}Ii(){return this.Ni(),this.Vi.Ii}Pt(){this.St=!0}$t(t,i=!1){return Math.max(this.Oi.$t(t,i),this.Li.$t(t,i))}Wi(){return this.Vi.Ei||0}Fi(t){this.Vi.Ei=t}Hi(){return this.Ni(),this.Ai.Bt||this.zi.Bt}Ui(){return this.Ni(),this.Ai.Bt}Tt(t){return this.Ni(),this.Ai.pi=this.Ai.pi&&t.N().ticksVisible,this.zi.pi=this.zi.pi&&t.N().ticksVisible,this.Oi.ht(this.Ai,this.Vi),this.Li.ht(this.zi,this.Vi),this.Oi}$i(){return this.Ni(),this.Oi.ht(this.Ai,this.Vi),this.Li.ht(this.zi,this.Vi),this.Li}Ni(){this.St&&(this.Ai.pi=!0,this.zi.pi=!1,this.ji(this.Ai,this.zi,this.Vi))}}class N extends L{constructor(t,i,s){super(),this.Jt=t,this.qi=i,this.Yi=s}ji(t,i,s){if(t.Bt=!1,2===this.Jt.N().mode)return;const n=this.Jt.N().horzLine;if(!n.labelVisible)return;const e=this.qi.zt();if(!this.Jt.Bt()||this.qi.Ki()||null===e)return;const r=this.qi.Xi().X(n.labelBackgroundColor);s.Z=r.Z,t.R=r.G;const h=2/12*this.qi.P();s.Ti=h,s.Ri=h;const a=this.Yi(this.qi);s.Ii=a.Ii,t.ri=this.qi.Zi(a.gt,e),t.Bt=!0}}const W=/[1-9]/g;class F{constructor(){this.qt=null}ht(t){this.qt=t}nt(t,i){if(null===this.qt||!1===this.qt.Bt||0===this.qt.ri.length)return;const s=t.useMediaCoordinateSpace((({context:t})=>(t.font=i.k,Math.round(i.Gi.Bi(t,a(this.qt).ri,W)))));if(s<=0)return;const n=i.Ji,e=s+2*n,r=e/2,h=this.qt.Qi;let l=this.qt.Ii,o=Math.floor(l-r)+.5;o<0?(l+=Math.abs(0-o),o=Math.floor(l-r)+.5):o+e>h&&(l-=Math.abs(h-(o+e)),o=Math.floor(l-r)+.5);const _=o+e,u=Math.ceil(0+i.S+i.C+i.A+i.P+i.B);t.useBitmapCoordinateSpace((({context:t,horizontalPixelRatio:s,verticalPixelRatio:n})=>{const e=a(this.qt);t.fillStyle=e.Z;const r=Math.round(o*s),h=Math.round(0*n),l=Math.round(_*s),c=Math.round(u*n),d=Math.round(2*s);if(t.beginPath(),t.moveTo(r,h),t.lineTo(r,c-d),t.arcTo(r,c,r+d,c,d),t.lineTo(l-d,c),t.arcTo(l,c,l,c-d,d),t.lineTo(l,h),t.fill(),e.pi){const r=Math.round(e.Ii*s),a=h,l=Math.round((a+i.C)*n);t.fillStyle=e.R;const o=Math.max(1,Math.floor(s)),_=Math.floor(.5*s);t.fillRect(r-_,a,o,l-a)}})),t.useMediaCoordinateSpace((({context:t})=>{const s=a(this.qt),e=0+i.S+i.C+i.A+i.P/2;t.font=i.k,t.textAlign="left",t.textBaseline="middle",t.fillStyle=s.R;const r=i.Gi.Di(t,"Apr0");t.translate(o+n,e+r),t.fillText(s.ri,0,0)}))}}class H{constructor(t,i,s){this.St=!0,this.Gt=new F,this.Zt={Bt:!1,Z:"#4c525e",R:"white",ri:"",Qi:0,Ii:NaN,pi:!0},this.Ct=t,this.ts=i,this.Yi=s}Pt(){this.St=!0}Tt(){return this.St&&(this.Rt(),this.St=!1),this.Gt.ht(this.Zt),this.Gt}Rt(){const t=this.Zt;if(t.Bt=!1,2===this.Ct.N().mode)return;const i=this.Ct.N().vertLine;if(!i.labelVisible)return;const s=this.ts.Vt();if(s.Ki())return;t.Qi=s.Qi();const n=this.Yi();if(null===n)return;t.Ii=n.Ii;const e=s.ss(this.Ct.It());t.ri=s.ns(a(e)),t.Bt=!0;const r=this.ts.Xi().X(i.labelBackgroundColor);t.Z=r.Z,t.R=r.G,t.pi=s.N().ticksVisible}}class U{constructor(){this.es=null,this.rs=0}hs(){return this.rs}ls(t){this.rs=t}Wt(){return this.es}_s(t){this.es=t}us(t){return[]}cs(){return[]}Bt(){return!0}}var $;!function(t){t[t.Normal=0]="Normal",t[t.Magnet=1]="Magnet",t[t.Hidden=2]="Hidden",t[t.MagnetOHLC=3]="MagnetOHLC"}($||($={}));class j extends U{constructor(t,i){super(),this.yt=null,this.ds=NaN,this.fs=0,this.ps=!1,this.vs=new Map,this.ws=!1,this.gs=new WeakMap,this.Ms=new WeakMap,this.bs=NaN,this.xs=NaN,this.Ss=NaN,this.Cs=NaN,this.ts=t,this.ys=i;this.Ps=((t,i)=>s=>{const n=i(),e=t();if(s===a(this.yt).ks())return{gt:e,Ii:n};{const t=a(s.zt());return{gt:s.Ts(n,t),Ii:n}}})((()=>this.ds),(()=>this.xs));const s=((t,i)=>()=>{const s=this.ts.Vt().Rs(t()),n=i();return s&&Number.isFinite(n)?{wt:s,Ii:n}:null})((()=>this.fs),(()=>this.si()));this.Ds=new H(this,t,s)}N(){return this.ys}Bs(t,i){this.Ss=t,this.Cs=i}Es(){this.Ss=NaN,this.Cs=NaN}Is(){return this.Ss}Vs(){return this.Cs}As(t,i,s){this.ws||(this.ws=!0),this.ps=!0,this.zs(t,i,s)}It(){return this.fs}si(){return this.bs}ni(){return this.xs}Bt(){return this.ps}Os(){this.ps=!1,this.Ls(),this.ds=NaN,this.bs=NaN,this.xs=NaN,this.yt=null,this.Es(),this.Ns()}Ws(t){let i=this.gs.get(t);i||(i=new B(this,t),this.gs.set(t,i));let s=this.Ms.get(t);return s||(s=new R(this.ts,this,t),this.Ms.set(t,s)),[i,s]}ti(t){return t===this.yt&&this.ys.horzLine.visible}ii(){return this.ys.vertLine.visible}Fs(t,i){this.ps&&this.yt===t||this.vs.clear();const s=[];return this.yt===t&&s.push(this.Hs(this.vs,i,this.Ps)),s}cs(){return this.ps?[this.Ds]:[]}Us(){return this.yt}Ns(){this.ts.$s().forEach((t=>{this.gs.get(t)?.Pt(),this.Ms.get(t)?.Pt()})),this.vs.forEach((t=>t.Pt())),this.Ds.Pt()}js(t){return t&&!t.ks().Ki()?t.ks():null}zs(t,i,s){this.qs(t,i,s)&&this.Ns()}qs(t,i,s){const n=this.bs,e=this.xs,r=this.ds,h=this.fs,a=this.yt,l=this.js(s);this.fs=t,this.bs=isNaN(t)?NaN:this.ts.Vt().jt(t),this.yt=s;const o=null!==l?l.zt():null;return null!==l&&null!==o?(this.ds=i,this.xs=l.Nt(i,o)):(this.ds=NaN,this.xs=NaN),n!==this.bs||e!==this.xs||h!==this.fs||r!==this.ds||a!==this.yt}Ls(){const t=this.ts.Ys().map((t=>t.Xs().Ks())).filter(v),i=0===t.length?null:Math.max(...t);this.fs=null!==i?i:NaN}Hs(t,i,s){let n=t.get(i);return void 0===n&&(n=new N(this,i,s),t.set(i,n)),n}}function q(t){return"left"===t||"right"===t}class Y{constructor(t){this.Zs=new Map,this.Gs=[],this.Js=t}Qs(t,i){const s=function(t,i){return void 0===t?i:{tn:Math.max(t.tn,i.tn),sn:t.sn||i.sn}}(this.Zs.get(t),i);this.Zs.set(t,s)}nn(){return this.Js}en(t){const i=this.Zs.get(t);return void 0===i?{tn:this.Js}:{tn:Math.max(this.Js,i.tn),sn:i.sn}}rn(){this.hn(),this.Gs=[{an:0}]}ln(t){this.hn(),this.Gs=[{an:1,Ft:t}]}_n(t){this.un(),this.Gs.push({an:5,Ft:t})}hn(){this.un(),this.Gs.push({an:6})}cn(){this.hn(),this.Gs=[{an:4}]}dn(t){this.hn(),this.Gs.push({an:2,Ft:t})}fn(t){this.hn(),this.Gs.push({an:3,Ft:t})}pn(){return this.Gs}vn(t){for(const i of t.Gs)this.mn(i);this.Js=Math.max(this.Js,t.Js),t.Zs.forEach(((t,i)=>{this.Qs(i,t)}))}static wn(){return new Y(2)}static gn(){return new Y(3)}mn(t){switch(t.an){case 0:this.rn();break;case 1:this.ln(t.Ft);break;case 2:this.dn(t.Ft);break;case 3:this.fn(t.Ft);break;case 4:this.cn();break;case 5:this._n(t.Ft);break;case 6:this.un()}}un(){const t=this.Gs.findIndex((t=>5===t.an));-1!==t&&this.Gs.splice(t,1)}}const K=".";function X(t,i){if(!u(t))return"n/a";if(!c(i))throw new TypeError("invalid length");if(i<0||i>16)throw new TypeError("invalid length");if(0===i)return t.toString();return("0000000000000000"+t.toString()).slice(-i)}class Z{constructor(t,i){if(i||(i=1),u(t)&&c(t)||(t=100),t<0)throw new TypeError("invalid base");this.qi=t,this.Mn=i,this.bn()}format(t){const i=t<0?"−":"";return t=Math.abs(t),i+this.xn(t)}bn(){if(this.Sn=0,this.qi>0&&this.Mn>0){let t=this.qi;for(;t>1;)t/=10,this.Sn++}}xn(t){const i=this.qi/this.Mn;let s=Math.floor(t),n="";const e=void 0!==this.Sn?this.Sn:NaN;if(i>1){let r=+(Math.round(t*i)-s*i).toFixed(this.Sn);r>=i&&(r-=i,s+=1),n=K+X(+r.toFixed(this.Sn)*this.Mn,e)}else s=Math.round(s*i)/i,e>0&&(n=K+X(0,e));return s.toFixed(0)+n}}class G extends Z{constructor(t=100){super(t)}format(t){return`${super.format(t)}%`}}class J{constructor(t){this.Cn=t}format(t){let i="";return t<0&&(i="-",t=-t),t<995?i+this.yn(t):t<999995?i+this.yn(t/1e3)+"K":t<999999995?(t=1e3*Math.round(t/1e3),i+this.yn(t/1e6)+"M"):(t=1e6*Math.round(t/1e6),i+this.yn(t/1e9)+"B")}yn(t){let i;const s=Math.pow(10,this.Cn);return i=(t=Math.round(t*s)/s)>=1e-15&&t<1?t.toFixed(this.Cn).replace(/\.?0+$/,""):String(t),i.replace(/(\.[1-9]*)0+$/,((t,i)=>i))}}const Q=/[2-9]/g;class tt{constructor(t=50){this.Pn=0,this.kn=1,this.Tn=1,this.Rn={},this.Dn=new Map,this.Bn=t}En(){this.Pn=0,this.Dn.clear(),this.kn=1,this.Tn=1,this.Rn={}}Bi(t,i,s){return this.In(t,i,s).width}Di(t,i,s){const n=this.In(t,i,s);return((n.actualBoundingBoxAscent||0)-(n.actualBoundingBoxDescent||0))/2}In(t,i,s){const n=s||Q,e=String(i).replace(n,"0");if(this.Dn.has(e))return h(this.Dn.get(e)).Vn;if(this.Pn===this.Bn){const t=this.Rn[this.Tn];delete this.Rn[this.Tn],this.Dn.delete(t),this.Tn++,this.Pn--}t.save(),t.textBaseline="middle";const r=t.measureText(e);return t.restore(),0===r.width&&i.length||(this.Dn.set(e,{Vn:r,An:this.kn}),this.Rn[this.kn]=e,this.Pn++,this.kn++),r}}class it{constructor(t){this.zn=null,this.M=null,this.On="right",this.Ln=t}Nn(t,i,s){this.zn=t,this.M=i,this.On=s}nt(t){null!==this.M&&null!==this.zn&&this.zn.nt(t,this.M,this.Ln,this.On)}}class st{constructor(t,i,s){this.Wn=t,this.Ln=new tt(50),this.Fn=i,this.L=s,this.W=-1,this.Gt=new it(this.Ln)}Tt(){const t=this.L.Hn(this.Fn);if(null===t)return null;const i=t.Un(this.Fn)?t.$n():this.Fn.Wt();if(null===i)return null;const s=t.jn(i);if("overlay"===s)return null;const n=this.L.qn();return n.P!==this.W&&(this.W=n.P,this.Ln.En()),this.Gt.Nn(this.Wn.$i(),n,s),this.Gt}}class nt extends y{constructor(){super(...arguments),this.qt=null}ht(t){this.qt=t}Yn(t,i){if(!this.qt?.Bt)return null;const{ut:s,ct:n,Kn:e}=this.qt;return i>=s-n-7&&i<=s+n+7?{Xn:this.qt,Kn:e}:null}et({context:t,bitmapSize:i,horizontalPixelRatio:s,verticalPixelRatio:r}){if(null===this.qt)return;if(!1===this.qt.Bt)return;const h=Math.round(this.qt.ut*r);h<0||h>i.height||(t.lineCap="butt",t.strokeStyle=this.qt.R,t.lineWidth=Math.floor(this.qt.ct*s),n(t,this.qt.Xt),e(t,h,0,i.width))}}class et{constructor(t){this.Zn={ut:0,R:"rgba(0, 0, 0, 0)",ct:1,Xt:0,Bt:!1},this.Gn=new nt,this.St=!0,this.Jn=t,this.Qn=t.Qt(),this.Gn.ht(this.Zn)}Pt(){this.St=!0}Tt(){return this.Jn.Bt()?(this.St&&(this.te(),this.St=!1),this.Gn):null}}class rt extends et{constructor(t){super(t)}te(){this.Zn.Bt=!1;const t=this.Jn.Wt(),i=t.ie().ie;if(2!==i&&3!==i)return;const s=this.Jn.N();if(!s.baseLineVisible||!this.Jn.Bt())return;const n=this.Jn.zt();null!==n&&(this.Zn.Bt=!0,this.Zn.ut=t.Nt(n.Ft,n.Ft),this.Zn.R=s.baseLineColor,this.Zn.ct=s.baseLineWidth,this.Zn.Xt=s.baseLineStyle)}}class ht extends y{constructor(){super(...arguments),this.qt=null}ht(t){this.qt=t}se(){return this.qt}et({context:t,horizontalPixelRatio:i,verticalPixelRatio:s}){const n=this.qt;if(null===n)return;const e=Math.max(1,Math.floor(i)),r=e%2/2,h=Math.round(n.ne.x*i)+r,a=n.ne.y*s;t.fillStyle=n.ee,t.beginPath();const l=Math.max(2,1.5*n.re)*i;t.arc(h,a,l,0,2*Math.PI,!1),t.fill(),t.fillStyle=n.he,t.beginPath(),t.arc(h,a,n.ft*i,0,2*Math.PI,!1),t.fill(),t.lineWidth=e,t.strokeStyle=n.ae,t.beginPath(),t.arc(h,a,n.ft*i+e/2,0,2*Math.PI,!1),t.stroke()}}const at=[{le:0,oe:.25,_e:4,ue:10,ce:.25,de:0,fe:.4,pe:.8},{le:.25,oe:.525,_e:10,ue:14,ce:0,de:0,fe:.8,pe:0},{le:.525,oe:1,_e:14,ue:14,ce:0,de:0,fe:0,pe:0}];class lt{constructor(t){this.Gt=new ht,this.St=!0,this.ve=!0,this.me=performance.now(),this.we=this.me-1,this.ge=t}Me(){this.we=this.me-1,this.Pt()}be(){if(this.Pt(),2===this.ge.N().lastPriceAnimation){const t=performance.now(),i=this.we-t;if(i>0)return void(i<650&&(this.we+=2600));this.me=t,this.we=t+2600}}Pt(){this.St=!0}xe(){this.ve=!0}Bt(){return 0!==this.ge.N().lastPriceAnimation}Se(){switch(this.ge.N().lastPriceAnimation){case 0:return!1;case 1:return!0;case 2:return performance.now()<=this.we}}Tt(){return this.St?(this.Rt(),this.St=!1,this.ve=!1):this.ve&&(this.Ce(),this.ve=!1),this.Gt}Rt(){this.Gt.ht(null);const t=this.ge.Qt().Vt(),i=t.ye(),s=this.ge.zt();if(null===i||null===s)return;const n=this.ge.Pe(!0);if(n.ke||!i.Te(n.Re))return;const e={x:t.jt(n.Re),y:this.ge.Wt().Nt(n.gt,s.Ft)},r=n.R,h=this.ge.N().lineWidth,a=this.De(this.Be(),r);this.Gt.ht({ee:r,re:h,he:a.he,ae:a.ae,ft:a.ft,ne:e})}Ce(){const t=this.Gt.se();if(null!==t){const i=this.De(this.Be(),t.ee);t.he=i.he,t.ae=i.ae,t.ft=i.ft}}Be(){return this.Se()?performance.now()-this.me:2599}Ee(t,i,s,n){const e=s+(n-s)*i;return this.ge.Qt().Xi().Y(t,e)}De(t,i){const s=t%2600/2600;let n;for(const t of at)if(s>=t.le&&s<=t.oe){n=t;break}r(void 0!==n,"Last price animation internal logic error");const e=(s-n.le)/(n.oe-n.le);return{he:this.Ee(i,e,n.ce,n.de),ae:this.Ee(i,e,n.fe,n.pe),ft:(h=e,a=n._e,l=n.ue,a+(l-a)*h)};var h,a,l}}class ot extends et{constructor(t){super(t)}te(){const t=this.Zn;t.Bt=!1;const i=this.Jn.N();if(!i.priceLineVisible||!this.Jn.Bt())return;const s=this.Jn.Pe(0===i.priceLineSource);s.ke||(t.Bt=!0,t.ut=s.Ii,t.R=this.Jn.Ie(s.R),t.ct=i.priceLineWidth,t.Xt=i.priceLineStyle)}}class _t extends L{constructor(t){super(),this.Jt=t}ji(t,i,s){t.Bt=!1,i.Bt=!1;const n=this.Jt;if(!n.Bt())return;const e=n.N(),r=e.lastValueVisible,h=""!==n.Ve(),a=0===e.seriesLastValueMode,l=n.Pe(!1);if(l.ke)return;r&&(t.ri=this.Ae(l,r,a),t.Bt=0!==t.ri.length),(h||a)&&(i.ri=this.ze(l,r,h,a),i.Bt=i.ri.length>0);const o=n.Ie(l.R),_=this.Jt.Qt().Xi().X(o);s.Z=_.Z,s.Ii=l.Ii,i.Ht=n.Qt().Ut(l.Ii/n.Wt().$t()),t.Ht=o,t.R=_.G,i.R=_.G}ze(t,i,s,n){let e="";const r=this.Jt.Ve();return s&&0!==r.length&&(e+=`${r} `),i&&n&&(e+=this.Jt.Wt().Oe()?t.Le:t.Ne),e.trim()}Ae(t,i,s){return i?s?this.Jt.Wt().Oe()?t.Ne:t.Le:t.ri:""}}function ut(t,i,s,n){const e=Number.isFinite(i),r=Number.isFinite(s);return e&&r?t(i,s):e||r?e?i:s:n}class ct{constructor(t,i){this.We=t,this.Fe=i}He(t){return null!==t&&(this.We===t.We&&this.Fe===t.Fe)}Ue(){return new ct(this.We,this.Fe)}$e(){return this.We}je(){return this.Fe}qe(){return this.Fe-this.We}Ki(){return this.Fe===this.We||Number.isNaN(this.Fe)||Number.isNaN(this.We)}vn(t){return null===t?this:new ct(ut(Math.min,this.$e(),t.$e(),-1/0),ut(Math.max,this.je(),t.je(),1/0))}Ye(t){if(!u(t))return;if(0===this.Fe-this.We)return;const i=.5*(this.Fe+this.We);let s=this.Fe-i,n=this.We-i;s*=t,n*=t,this.Fe=i+s,this.We=i+n}Ke(t){u(t)&&(this.Fe+=t,this.We+=t)}Xe(){return{minValue:this.We,maxValue:this.Fe}}static Ze(t){return null===t?null:new ct(t.minValue,t.maxValue)}}class dt{constructor(t,i){this.Ge=t,this.Je=i||null}Qe(){return this.Ge}tr(){return this.Je}Xe(){return{priceRange:null===this.Ge?null:this.Ge.Xe(),margins:this.Je||void 0}}static Ze(t){return null===t?null:new dt(ct.Ze(t.priceRange),t.margins)}}class ft extends et{constructor(t,i){super(t),this.ir=i}te(){const t=this.Zn;t.Bt=!1;const i=this.ir.N();if(!this.Jn.Bt()||!i.lineVisible)return;const s=this.ir.sr();null!==s&&(t.Bt=!0,t.ut=s,t.R=i.color,t.ct=i.lineWidth,t.Xt=i.lineStyle,t.Kn=this.ir.N().id)}}class pt extends L{constructor(t,i){super(),this.ge=t,this.ir=i}ji(t,i,s){t.Bt=!1,i.Bt=!1;const n=this.ir.N(),e=n.axisLabelVisible,r=""!==n.title,h=this.ge;if(!e||!h.Bt())return;const a=this.ir.sr();if(null===a)return;r&&(i.ri=n.title,i.Bt=!0),i.Ht=h.Qt().Ut(a/h.Wt().$t()),t.ri=this.nr(n.price),t.Bt=!0;const l=this.ge.Qt().Xi().X(n.axisLabelColor||n.color);s.Z=l.Z;const o=n.axisLabelTextColor||l.G;t.R=o,i.R=o,s.Ii=a}nr(t){const i=this.ge.zt();return null===i?"":this.ge.Wt().Zi(t,i.Ft)}}class vt{constructor(t,i){this.ge=t,this.ys=i,this.er=new ft(t,this),this.Wn=new pt(t,this),this.rr=new st(this.Wn,t,t.Qt())}hr(t){_(this.ys,t),this.Pt(),this.ge.Qt().ar()}N(){return this.ys}lr(){return this.er}_r(){return this.rr}ur(){return this.Wn}Pt(){this.er.Pt(),this.Wn.Pt()}sr(){const t=this.ge,i=t.Wt();if(t.Qt().Vt().Ki()||i.Ki())return null;const s=t.zt();return null===s?null:i.Nt(this.ys.price,s.Ft)}}class mt extends U{constructor(t){super(),this.ts=t}Qt(){return this.ts}}const wt={Bar:(t,i,s,n)=>{const e=i.upColor,r=i.downColor,h=a(t(s,n)),o=l(h.Ft[0])<=l(h.Ft[3]);return{cr:h.R??(o?e:r)}},Candlestick:(t,i,s,n)=>{const e=i.upColor,r=i.downColor,h=i.borderUpColor,o=i.borderDownColor,_=i.wickUpColor,u=i.wickDownColor,c=a(t(s,n)),d=l(c.Ft[0])<=l(c.Ft[3]);return{cr:c.R??(d?e:r),dr:c.Ht??(d?h:o),pr:c.vr??(d?_:u)}},Custom:(t,i,s,n)=>({cr:a(t(s,n)).R??i.color}),Area:(t,i,s,n)=>{const e=a(t(s,n));return{cr:e.vt??i.lineColor,vt:e.vt??i.lineColor,mr:e.mr??i.topColor,wr:e.wr??i.bottomColor}},Baseline:(t,i,s,n)=>{const e=a(t(s,n));return{cr:e.Ft[3]>=i.baseValue.price?i.topLineColor:i.bottomLineColor,gr:e.gr??i.topLineColor,Mr:e.Mr??i.bottomLineColor,br:e.br??i.topFillColor1,Sr:e.Sr??i.topFillColor2,Cr:e.Cr??i.bottomFillColor1,yr:e.yr??i.bottomFillColor2}},Line:(t,i,s,n)=>{const e=a(t(s,n));return{cr:e.R??i.color,vt:e.R??i.color}},Histogram:(t,i,s,n)=>({cr:a(t(s,n)).R??i.color})};class gt{constructor(t){this.Pr=(t,i)=>void 0!==i?i.Ft:this.ge.Xs().kr(t),this.ge=t,this.Tr=wt[t.Rr()]}Dr(t,i){return this.Tr(this.Pr,this.ge.N(),t,i)}}function Mt(t,i,s,n,e=0,r=i.length){let h=r-e;for(;0>1,a=e+r;n(i[a],s)===t?(e=a+1,h-=r+1):h=r}return e}const bt=Mt.bind(null,!0),xt=Mt.bind(null,!1);var St;!function(t){t[t.NearestLeft=-1]="NearestLeft",t[t.None=0]="None",t[t.NearestRight=1]="NearestRight"}(St||(St={}));const Ct=30;class yt{constructor(){this.Br=[],this.Er=new Map,this.Ir=new Map,this.Vr=[]}Ar(){return this.zr()>0?this.Br[this.Br.length-1]:null}Or(){return this.zr()>0?this.Lr(0):null}Ks(){return this.zr()>0?this.Lr(this.Br.length-1):null}zr(){return this.Br.length}Ki(){return 0===this.zr()}Te(t){return null!==this.Nr(t,0)}kr(t){return this.Wr(t)}Wr(t,i=0){const s=this.Nr(t,i);return null===s?null:{...this.Fr(s),Re:this.Lr(s)}}Hr(){return this.Br}Ur(t,i,s){if(this.Ki())return null;let n=null;for(const e of s){n=Pt(n,this.$r(t,i,e))}return n}ht(t){this.Ir.clear(),this.Er.clear(),this.Br=t,this.Vr=t.map((t=>t.Re))}jr(){return this.Vr}Lr(t){return this.Br[t].Re}Fr(t){return this.Br[t]}Nr(t,i){const s=this.qr(t);if(null===s&&0!==i)switch(i){case-1:return this.Yr(t);case 1:return this.Kr(t);default:throw new TypeError("Unknown search mode")}return s}Yr(t){let i=this.Xr(t);return i>0&&(i-=1),i!==this.Br.length&&this.Lr(i)t.Ret.Re>i))}Gr(t,i,s){let n=null;for(let e=t;en.Qr&&(n.Qr=t)))}return n}$r(t,i,s){if(this.Ki())return null;let n=null;const e=a(this.Or()),r=a(this.Ks()),h=Math.max(t,e),l=Math.min(i,r),o=Math.ceil(h/Ct)*Ct,_=Math.max(o,Math.floor(l/Ct)*Ct);{const t=this.Xr(h),e=this.Zr(Math.min(l,o,i));n=Pt(n,this.Gr(t,e,s))}let u=this.Er.get(s);void 0===u&&(u=new Map,this.Er.set(s,u));for(let t=Math.max(o+1,h);t<_;t+=Ct){const i=Math.floor(t/Ct);let e=u.get(i);if(void 0===e){const t=this.Xr(i*Ct),n=this.Zr((i+1)*Ct-1);e=this.Gr(t,n,s),u.set(i,e)}n=Pt(n,e)}{const t=this.Xr(_),i=this.Zr(l);n=Pt(n,this.Gr(t,i,s))}return n}}function Pt(t,i){if(null===t)return i;if(null===i)return t;return{Jr:Math.min(t.Jr,i.Jr),Qr:Math.max(t.Qr,i.Qr)}}class kt{constructor(t){this.th=t}nt(t,i,s){this.th.draw(t)}ih(t,i,s){this.th.drawBackground?.(t)}}class Tt{constructor(t){this.Dn=null,this.sh=t}Tt(){const t=this.sh.renderer();if(null===t)return null;if(this.Dn?.nh===t)return this.Dn.eh;const i=new kt(t);return this.Dn={nh:t,eh:i},i}rh(){return this.sh.zOrder?.()??"normal"}}class Rt{constructor(t){this.hh=null,this.ah=t}oh(){return this.ah}Ns(){this.ah.updateAllViews?.()}Ws(){const t=this.ah.paneViews?.()??[];if(this.hh?.nh===t)return this.hh.eh;const i=t.map((t=>new Tt(t)));return this.hh={nh:t,eh:i},i}Yn(t,i){return this.ah.hitTest?.(t,i)??null}}let Dt=class extends Rt{us(){return[]}};class Bt{constructor(t){this.th=t}nt(t,i,s){this.th.draw(t)}ih(t,i,s){this.th.drawBackground?.(t)}}class Et{constructor(t){this.Dn=null,this.sh=t}Tt(){const t=this.sh.renderer();if(null===t)return null;if(this.Dn?.nh===t)return this.Dn.eh;const i=new Bt(t);return this.Dn={nh:t,eh:i},i}rh(){return this.sh.zOrder?.()??"normal"}}function It(t){return{ri:t.text(),Ii:t.coordinate(),Ei:t.fixedCoordinate?.(),R:t.textColor(),Z:t.backColor(),Bt:t.visible?.()??!0,pi:t.tickVisible?.()??!0}}class Vt{constructor(t,i){this.Gt=new F,this._h=t,this.uh=i}Tt(){return this.Gt.ht({Qi:this.uh.Qi(),...It(this._h)}),this.Gt}}class At extends L{constructor(t,i){super(),this._h=t,this.qi=i}ji(t,i,s){const n=It(this._h);s.Z=n.Z,t.R=n.R;const e=2/12*this.qi.P();s.Ti=e,s.Ri=e,s.Ii=n.Ii,s.Ei=n.Ei,t.ri=n.ri,t.Bt=n.Bt,t.pi=n.pi}}class zt extends Rt{constructor(t,i){super(t),this.dh=null,this.fh=null,this.ph=null,this.mh=null,this.ge=i}cs(){const t=this.ah.timeAxisViews?.()??[];if(this.dh?.nh===t)return this.dh.eh;const i=this.ge.Qt().Vt(),s=t.map((t=>new Vt(t,i)));return this.dh={nh:t,eh:s},s}Fs(){const t=this.ah.priceAxisViews?.()??[];if(this.fh?.nh===t)return this.fh.eh;const i=this.ge.Wt(),s=t.map((t=>new At(t,i)));return this.fh={nh:t,eh:s},s}wh(){const t=this.ah.priceAxisPaneViews?.()??[];if(this.ph?.nh===t)return this.ph.eh;const i=t.map((t=>new Et(t)));return this.ph={nh:t,eh:i},i}gh(){const t=this.ah.timeAxisPaneViews?.()??[];if(this.mh?.nh===t)return this.mh.eh;const i=t.map((t=>new Et(t)));return this.mh={nh:t,eh:i},i}Mh(t,i){return this.ah.autoscaleInfo?.(t,i)??null}}function Ot(t,i,s,n){t.forEach((t=>{i(t).forEach((t=>{t.rh()===s&&n.push(t)}))}))}function Lt(t){return t.Ws()}function Nt(t){return t.wh()}function Wt(t){return t.gh()}const Ft=["Area","Line","Baseline"];class Ht extends mt{constructor(t,i,s,n,e){super(t),this.qt=new yt,this.er=new ot(this),this.bh=[],this.xh=new rt(this),this.Sh=null,this.Ch=null,this.yh=null,this.Ph=[],this.ys=s,this.kh=i;const r=new _t(this);this.vs=[r],this.rr=new st(r,this,t),Ft.includes(this.kh)&&(this.Sh=new lt(this)),this.Th(),this.sh=n(this,this.Qt(),e)}m(){null!==this.yh&&clearTimeout(this.yh)}Ie(t){return this.ys.priceLineColor||t}Pe(t){const i={ke:!0},s=this.Wt();if(this.Qt().Vt().Ki()||s.Ki()||this.qt.Ki())return i;const n=this.Qt().Vt().ye(),e=this.zt();if(null===n||null===e)return i;let r,h;if(t){const t=this.qt.Ar();if(null===t)return i;r=t,h=t.Re}else{const t=this.qt.Wr(n.bi(),-1);if(null===t)return i;if(r=this.qt.kr(t.Re),null===r)return i;h=t.Re}const a=r.Ft[3],l=this.Rh().Dr(h,{Ft:r}),o=s.Nt(a,e.Ft);return{ke:!1,gt:a,ri:s.Zi(a,e.Ft),Le:s.Dh(a),Ne:s.Bh(a,e.Ft),R:l.cr,Ii:o,Re:h}}Rh(){return null!==this.Ch||(this.Ch=new gt(this)),this.Ch}N(){return this.ys}hr(t){const i=t.priceScaleId;void 0!==i&&i!==this.ys.priceScaleId&&this.Qt().Eh(this,i),_(this.ys,t),void 0!==t.priceFormat&&(this.Th(),this.Qt().Ih()),this.Qt().Vh(this),this.Qt().Ah(),this.sh.Pt("options")}ht(t,i){this.qt.ht(t),this.sh.Pt("data"),null!==this.Sh&&(i&&i.zh?this.Sh.be():0===t.length&&this.Sh.Me());const s=this.Qt().Hn(this);this.Qt().Oh(s),this.Qt().Vh(this),this.Qt().Ah(),this.Qt().ar()}Lh(t){const i=new vt(this,t);return this.bh.push(i),this.Qt().Vh(this),i}Nh(t){const i=this.bh.indexOf(t);-1!==i&&this.bh.splice(i,1),this.Qt().Vh(this)}Wh(){return this.bh}Rr(){return this.kh}zt(){const t=this.Fh();return null===t?null:{Ft:t.Ft[3],Hh:t.wt}}Fh(){const t=this.Qt().Vt().ye();if(null===t)return null;const i=t.Uh();return this.qt.Wr(i,1)}Xs(){return this.qt}$h(t){const i=this.qt.kr(t);return null===i?null:"Bar"===this.kh||"Candlestick"===this.kh||"Custom"===this.kh?{jh:i.Ft[0],qh:i.Ft[1],Yh:i.Ft[2],Kh:i.Ft[3]}:i.Ft[3]}Xh(t){const i=[];Ot(this.Ph,Lt,"top",i);const s=this.Sh;return null!==s&&s.Bt()?(null===this.yh&&s.Se()&&(this.yh=setTimeout((()=>{this.yh=null,this.Qt().Zh()}),0)),s.xe(),i.unshift(s),i):i}Ws(){const t=[];this.Gh()||t.push(this.xh),t.push(this.sh,this.er);const i=this.bh.map((t=>t.lr()));return t.push(...i),Ot(this.Ph,Lt,"normal",t),t}Jh(){return this.Qh(Lt,"bottom")}ta(t){return this.Qh(Nt,t)}ia(t){return this.Qh(Wt,t)}sa(t,i){return this.Ph.map((s=>s.Yn(t,i))).filter((t=>null!==t))}us(){return[this.rr,...this.bh.map((t=>t._r()))]}Fs(t,i){if(i!==this.es&&!this.Gh())return[];const s=[...this.vs];for(const t of this.bh)s.push(t.ur());return this.Ph.forEach((t=>{s.push(...t.Fs())})),s}cs(){const t=[];return this.Ph.forEach((i=>{t.push(...i.cs())})),t}Mh(t,i){if(void 0!==this.ys.autoscaleInfoProvider){const s=this.ys.autoscaleInfoProvider((()=>{const s=this.na(t,i);return null===s?null:s.Xe()}));return dt.Ze(s)}return this.na(t,i)}ea(){return this.ys.priceFormat.minMove}ra(){return this.ha}Ns(){this.sh.Pt();for(const t of this.vs)t.Pt();for(const t of this.bh)t.Pt();this.er.Pt(),this.xh.Pt(),this.Sh?.Pt(),this.Ph.forEach((t=>t.Ns()))}Wt(){return a(super.Wt())}At(t){if(!(("Line"===this.kh||"Area"===this.kh||"Baseline"===this.kh)&&this.ys.crosshairMarkerVisible))return null;const i=this.qt.kr(t);if(null===i)return null;return{gt:i.Ft[3],ft:this.aa(),Ht:this.la(),Lt:this.oa(),Ot:this._a(t)}}Ve(){return this.ys.title}Bt(){return this.ys.visible}ua(t){this.Ph.push(new zt(t,this))}ca(t){this.Ph=this.Ph.filter((i=>i.oh()!==t))}da(){if("Custom"===this.kh)return t=>this.sh.fa(t)}pa(){if("Custom"===this.kh)return t=>this.sh.va(t)}ma(){return this.qt.jr()}Gh(){return!q(this.Wt().wa())}na(t,i){if(!c(t)||!c(i)||this.qt.Ki())return null;const s="Line"===this.kh||"Area"===this.kh||"Baseline"===this.kh||"Histogram"===this.kh?[3]:[2,1],n=this.qt.Ur(t,i,s);let e=null!==n?new ct(n.Jr,n.Qr):null,r=null;if("Histogram"===this.Rr()){const t=this.ys.base,i=new ct(t,t);e=null!==e?e.vn(i):i}return this.Ph.forEach((s=>{const n=s.Mh(t,i);if(n?.priceRange){const t=new ct(n.priceRange.minValue,n.priceRange.maxValue);e=null!==e?e.vn(t):t}n?.margins&&(r=n.margins)})),new dt(e,r)}aa(){switch(this.kh){case"Line":case"Area":case"Baseline":return this.ys.crosshairMarkerRadius}return 0}la(){switch(this.kh){case"Line":case"Area":case"Baseline":{const t=this.ys.crosshairMarkerBorderColor;if(0!==t.length)return t}}return null}oa(){switch(this.kh){case"Line":case"Area":case"Baseline":return this.ys.crosshairMarkerBorderWidth}return 0}_a(t){switch(this.kh){case"Line":case"Area":case"Baseline":{const t=this.ys.crosshairMarkerBackgroundColor;if(0!==t.length)return t}}return this.Rh().Dr(t).cr}Th(){switch(this.ys.priceFormat.type){case"custom":this.ha={format:this.ys.priceFormat.formatter};break;case"volume":this.ha=new J(this.ys.priceFormat.precision);break;case"percent":this.ha=new G(this.ys.priceFormat.precision);break;default:{const t=Math.pow(10,this.ys.priceFormat.precision);this.ha=new Z(t,this.ys.priceFormat.minMove*t)}}null!==this.es&&this.es.ga()}Qh(t,i){const s=[];return Ot(this.Ph,t,i,s),s}}const Ut=[3],$t=[0,1,2,3];class jt{constructor(t){this.ys=t}Ma(t,i,s){let n=t;if(0===this.ys.mode)return n;const e=s.ks(),r=e.zt();if(null===r)return n;const h=e.Nt(t,r),a=s.ba().filter((t=>t instanceof Ht)).reduce(((t,n)=>{if(s.Un(n)||!n.Bt())return t;const e=n.Wt(),r=n.Xs();if(e.Ki()||!r.Te(i))return t;const h=r.kr(i);if(null===h)return t;const a=l(n.zt()),o=3===this.ys.mode?$t:Ut;return t.concat(o.map((t=>e.Nt(h.Ft[t],a.Ft))))}),[]);if(0===a.length)return n;a.sort(((t,i)=>Math.abs(t-h)-Math.abs(i-h)));const o=a[0];return n=e.Ts(o,r),n}}function qt(t,i,s){return Math.min(Math.max(t,i),s)}function Yt(t,i,s){return i-t<=s}function Kt(t){const i=Math.ceil(t);return i%2==0?i-1:i}class Xt extends y{constructor(){super(...arguments),this.qt=null}ht(t){this.qt=t}et({context:t,bitmapSize:i,horizontalPixelRatio:s,verticalPixelRatio:e}){if(null===this.qt)return;const r=Math.max(1,Math.floor(s));t.lineWidth=r,function(t,i){t.save(),t.lineWidth%2&&t.translate(.5,.5),i(),t.restore()}(t,(()=>{const h=a(this.qt);if(h.xa){t.strokeStyle=h.Sa,n(t,h.Ca),t.beginPath();for(const n of h.ya){const e=Math.round(n.Pa*s);t.moveTo(e,-r),t.lineTo(e,i.height+r)}t.stroke()}if(h.ka){t.strokeStyle=h.Ta,n(t,h.Ra),t.beginPath();for(const s of h.Da){const n=Math.round(s.Pa*e);t.moveTo(-r,n),t.lineTo(i.width+r,n)}t.stroke()}}))}}class Zt{constructor(t){this.Gt=new Xt,this.St=!0,this.yt=t}Pt(){this.St=!0}Tt(){if(this.St){const t=this.yt.Qt().N().grid,i={ka:t.horzLines.visible,xa:t.vertLines.visible,Ta:t.horzLines.color,Sa:t.vertLines.color,Ra:t.horzLines.style,Ca:t.vertLines.style,Da:this.yt.ks().Ba(),ya:(this.yt.Qt().Vt().Ba()||[]).map((t=>({Pa:t.coord})))};this.Gt.ht(i),this.St=!1}return this.Gt}}class Gt{constructor(t){this.sh=new Zt(t)}lr(){return this.sh}}const Jt={Ea:4,Ia:1e-4};function Qt(t,i){const s=100*(t-i)/i;return i<0?-s:s}function ti(t,i){const s=Qt(t.$e(),i),n=Qt(t.je(),i);return new ct(s,n)}function ii(t,i){const s=100*(t-i)/i+100;return i<0?-s:s}function si(t,i){const s=ii(t.$e(),i),n=ii(t.je(),i);return new ct(s,n)}function ni(t,i){const s=Math.abs(t);if(s<1e-15)return 0;const n=Math.log10(s+i.Ia)+i.Ea;return t<0?-n:n}function ei(t,i){const s=Math.abs(t);if(s<1e-15)return 0;const n=Math.pow(10,s-i.Ea)-i.Ia;return t<0?-n:n}function ri(t,i){if(null===t)return null;const s=ni(t.$e(),i),n=ni(t.je(),i);return new ct(s,n)}function hi(t,i){if(null===t)return null;const s=ei(t.$e(),i),n=ei(t.je(),i);return new ct(s,n)}function ai(t){if(null===t)return Jt;const i=Math.abs(t.je()-t.$e());if(i>=1||i<1e-15)return Jt;const s=Math.ceil(Math.abs(Math.log10(i))),n=Jt.Ea+s;return{Ea:n,Ia:1/Math.pow(10,n)}}class li{constructor(t,i){if(this.Va=t,this.Aa=i,function(t){if(t<0)return!1;for(let i=t;i>1;i/=10)if(i%10!=0)return!1;return!0}(this.Va))this.za=[2,2.5,2];else{this.za=[];for(let t=this.Va;1!==t;){if(t%2==0)this.za.push(2),t/=2;else{if(t%5!=0)throw new Error("unexpected base");this.za.push(2,2.5),t/=5}if(this.za.length>100)throw new Error("something wrong with base")}}}Oa(t,i,s){const n=0===this.Va?0:1/this.Va;let e=Math.pow(10,Math.max(0,Math.ceil(Math.log10(t-i)))),r=0,h=this.Aa[0];for(;;){const t=Yt(e,n,1e-14)&&e>n+1e-14,i=Yt(e,s*h,1e-14),a=Yt(e,1,1e-14);if(!(t&&i&&a))break;e/=h,h=this.Aa[++r%this.Aa.length]}if(e<=n+1e-14&&(e=n),e=Math.max(1,e),this.za.length>0&&(a=e,l=1,o=1e-14,Math.abs(a-l)n+1e-14;)e/=h,h=this.za[++r%this.za.length];var a,l,o;return e}}class oi{constructor(t,i,s,n){this.La=[],this.qi=t,this.Va=i,this.Na=s,this.Wa=n}Oa(t,i){if(t=o?1:-1;let d=null,f=0;for(let s=l-u;s>o;s-=_){const n=this.Wa(s,i,!0);null!==d&&Math.abs(n-d)a||(fa(t.hs())-a(i.hs())))}var ui;!function(t){t[t.Normal=0]="Normal",t[t.Logarithmic=1]="Logarithmic",t[t.Percentage=2]="Percentage",t[t.IndexedTo100=3]="IndexedTo100"}(ui||(ui={}));const ci=new G,di=new Z(100,1);class fi{constructor(t,i,s,n,e){this.Ya=0,this.Ka=null,this.Ge=null,this.Xa=null,this.Za={Ga:!1,Ja:null},this.Qa=0,this.tl=0,this.il=new o,this.sl=new o,this.nl=[],this.el=null,this.rl=null,this.hl=null,this.al=null,this.ll=null,this.ha=di,this.ol=ai(null),this._l=t,this.ys=i,this.ul=s,this.cl=n,this.dl=e,this.fl=new oi(this,100,this.pl.bind(this),this.vl.bind(this))}wa(){return this._l}N(){return this.ys}hr(t){if(_(this.ys,t),this.ga(),void 0!==t.mode&&this.ml({ie:t.mode}),void 0!==t.scaleMargins){const i=h(t.scaleMargins.top),s=h(t.scaleMargins.bottom);if(i<0||i>1)throw new Error(`Invalid top margin - expect value between 0 and 1, given=${i}`);if(s<0||s>1)throw new Error(`Invalid bottom margin - expect value between 0 and 1, given=${s}`);if(i+s>1)throw new Error(`Invalid margins - sum of margins must be less than 1, given=${i+s}`);this.wl(),this.hl=null}}gl(){return this.ys.autoScale}qa(){return 1===this.ys.mode}Oe(){return 2===this.ys.mode}Ml(){return 3===this.ys.mode}ie(){return{sn:this.ys.autoScale,bl:this.ys.invertScale,ie:this.ys.mode}}ml(t){const i=this.ie();let s=null;void 0!==t.sn&&(this.ys.autoScale=t.sn),void 0!==t.ie&&(this.ys.mode=t.ie,2!==t.ie&&3!==t.ie||(this.ys.autoScale=!0),this.Za.Ga=!1),1===i.ie&&t.ie!==i.ie&&(!function(t,i){if(null===t)return!1;const s=ei(t.$e(),i),n=ei(t.je(),i);return isFinite(s)&&isFinite(n)}(this.Ge,this.ol)?this.ys.autoScale=!0:(s=hi(this.Ge,this.ol),null!==s&&this.xl(s))),1===t.ie&&t.ie!==i.ie&&(s=ri(this.Ge,this.ol),null!==s&&this.xl(s));const n=i.ie!==this.ys.mode;n&&(2===i.ie||this.Oe())&&this.ga(),n&&(3===i.ie||this.Ml())&&this.ga(),void 0!==t.bl&&i.bl!==t.bl&&(this.ys.invertScale=t.bl,this.Sl()),this.sl.p(i,this.ie())}Cl(){return this.sl}P(){return this.ul.fontSize}$t(){return this.Ya}yl(t){this.Ya!==t&&(this.Ya=t,this.wl(),this.hl=null)}Pl(){if(this.Ka)return this.Ka;const t=this.$t()-this.kl()-this.Tl();return this.Ka=t,t}Qe(){return this.Rl(),this.Ge}xl(t,i){const s=this.Ge;(i||null===s&&null!==t||null!==s&&!s.He(t))&&(this.hl=null,this.Ge=t)}Ki(){return this.Rl(),0===this.Ya||!this.Ge||this.Ge.Ki()}Dl(t){return this.bl()?t:this.$t()-1-t}Nt(t,i){return this.Oe()?t=Qt(t,i):this.Ml()&&(t=ii(t,i)),this.vl(t,i)}Bl(t,i,s){this.Rl();const n=this.Tl(),e=a(this.Qe()),r=e.$e(),h=e.je(),l=this.Pl()-1,o=this.bl(),_=l/(h-r),u=void 0===s?0:s.from,c=void 0===s?t.length:s.to,d=this.El();for(let s=u;st.Ns()))}ga(){this.hl=null;let t=1/0;this.el=null;for(const i of this.nl)i.hs()ni(t,this.ol):null}io(t,i,s){return void 0===i?(void 0===s&&(s=this.ra()),s.format(t)):i(t)}nr(t,i){return this.io(t,this.cl.priceFormatter,i)}Zl(t,i){return this.io(t,this.cl.percentageFormatter,i)}}function pi(t){return t instanceof Ht}class vi{constructor(t,i){this.nl=[],this.so=new Map,this.Ya=0,this.no=0,this.eo=1e3,this.rl=null,this.ro=new o,this.Ph=[],this.uh=t,this.ts=i,this.ho=new Gt(this);const s=i.N();this.ao=this.lo("left",s.leftPriceScale),this.oo=this.lo("right",s.rightPriceScale),this.ao.Cl().i(this._o.bind(this,this.ao),this),this.oo.Cl().i(this._o.bind(this,this.oo),this),this.uo(s)}uo(t){if(t.leftPriceScale&&this.ao.hr(t.leftPriceScale),t.rightPriceScale&&this.oo.hr(t.rightPriceScale),t.localization&&(this.ao.ga(),this.oo.ga()),t.overlayPriceScales){const i=Array.from(this.so.values());for(const s of i){const i=a(s[0].Wt());i.hr(t.overlayPriceScales),t.localization&&i.ga()}}}co(t){switch(t){case"left":return this.ao;case"right":return this.oo}return this.so.has(t)?h(this.so.get(t))[0].Wt():null}m(){this.Qt().do().u(this),this.ao.Cl().u(this),this.oo.Cl().u(this),this.nl.forEach((t=>{t.m&&t.m()})),this.Ph=this.Ph.filter((t=>{const i=t.oh();return i.detached&&i.detached(),!1})),this.ro.p()}fo(){return this.eo}po(t){this.eo=t}Qt(){return this.ts}Qi(){return this.no}$t(){return this.Ya}vo(t){this.no=t,this.mo()}yl(t){this.Ya=t,this.ao.yl(t),this.oo.yl(t),this.nl.forEach((i=>{if(this.Un(i)){const s=i.Wt();null!==s&&s.yl(t)}})),this.mo()}wo(){return this.nl.filter(pi)}ba(){return this.nl}Un(t){const i=t.Wt();return null===i||this.ao!==i&&this.oo!==i}Nl(t,i,s){this.Mo(t,i,s?t.hs():this.nl.length)}Fl(t,i){const s=this.nl.indexOf(t);r(-1!==s,"removeDataSource: invalid data source"),this.nl.splice(s,1),i||this.nl.forEach(((t,i)=>t.ls(i)));const n=a(t.Wt()).wa();if(this.so.has(n)){const i=h(this.so.get(n)),s=i.indexOf(t);-1!==s&&(i.splice(s,1),0===i.length&&this.so.delete(n))}const e=t.Wt();e&&e.ba().indexOf(t)>=0&&(e.Fl(t),this.bo(e)),this.rl=null}jn(t){return t===this.ao?"left":t===this.oo?"right":"overlay"}xo(){return this.ao}So(){return this.oo}Co(t,i){t.$l(i)}yo(t,i){t.jl(i),this.mo()}Po(t){t.ql()}ko(t,i){t.Yl(i)}To(t,i){t.Kl(i),this.mo()}Ro(t){t.Xl()}mo(){this.nl.forEach((t=>{t.Ns()}))}ks(){let t=null;return this.ts.N().rightPriceScale.visible&&0!==this.oo.ba().length?t=this.oo:this.ts.N().leftPriceScale.visible&&0!==this.ao.ba().length?t=this.ao:0!==this.nl.length&&(t=this.nl[0].Wt()),null===t&&(t=this.oo),t}$n(){let t=null;return this.ts.N().rightPriceScale.visible?t=this.oo:this.ts.N().leftPriceScale.visible&&(t=this.ao),t}bo(t){null!==t&&t.gl()&&this.Do(t)}Bo(t){const i=this.uh.ye();t.ml({sn:!0}),null!==i&&t.Jl(i),this.mo()}Eo(){this.Do(this.ao),this.Do(this.oo)}Io(){this.bo(this.ao),this.bo(this.oo),this.nl.forEach((t=>{this.Un(t)&&this.bo(t.Wt())})),this.mo(),this.ts.ar()}Dt(){return null===this.rl&&(this.rl=_i(this.nl)),this.rl}Vo(t,i){i=qt(i,0,this.nl.length-1);const s=this.nl.indexOf(t);r(-1!==s,"setSeriesOrder: invalid data source"),this.nl.splice(s,1),this.nl.splice(i,0,t),this.nl.forEach(((t,i)=>t.ls(i))),this.rl=null;for(const t of[this.ao,this.oo])t.Wl(),t.ga();this.ts.ar()}Et(){return this.Dt().filter(pi)}Ao(){return this.ro}zo(){return this.ho}ua(t){this.Ph.push(new Dt(t))}ca(t){this.Ph=this.Ph.filter((i=>i.oh()!==t)),t.detached&&t.detached(),this.ts.ar()}Oo(){return this.Ph}sa(t,i){return this.Ph.map((s=>s.Yn(t,i))).filter((t=>null!==t))}Do(t){const i=t.Gl();if(i&&i.length>0&&!this.uh.Ki()){const i=this.uh.ye();null!==i&&t.Jl(i)}t.Ns()}Mo(t,i,s){let n=this.co(i);if(null===n&&(n=this.lo(i,this.ts.N().overlayPriceScales)),this.nl.splice(s,0,t),!q(i)){const s=this.so.get(i)||[];s.push(t),this.so.set(i,s)}t.ls(s),n.Nl(t),t._s(n),this.bo(n),this.rl=null}_o(t,i,s){i.ie!==s.ie&&this.Do(t)}lo(t,i){const s={visible:!0,autoScale:!0,...p(i)},n=new fi(t,s,this.ts.N().layout,this.ts.N().localization,this.ts.Xi());return n.yl(this.$t()),n}}function mi(t){return{Lo:t.Lo,No:{Kn:t.Wo.externalId},Fo:t.Wo.cursorStyle}}function wi(t,i,s,n){for(const e of t){const t=e.Tt(n);if(null!==t&&t.Yn){const n=t.Yn(i,s);if(null!==n)return{Ho:e,No:n}}}return null}function gi(t){return void 0!==t.Ws}function Mi(t,i,s){const n=[t,...t.Dt()],e=function(t,i,s){let n,e;for(const a of t){const t=a.sa?.(i,s)??[];for(const i of t)r=i.zOrder,h=n?.zOrder,(!h||"top"===r&&"top"!==h||"normal"===r&&"bottom"===h)&&(n=i,e=a)}var r,h;return n&&e?{Wo:n,Lo:e}:null}(n,i,s);if("top"===e?.Wo.zOrder)return mi(e);for(const r of n){if(e&&e.Lo===r&&"bottom"!==e.Wo.zOrder&&!e.Wo.isBackground)return mi(e);if(gi(r)){const n=wi(r.Ws(t),i,s,t);if(null!==n)return{Lo:r,Ho:n.Ho,No:n.No}}if(e&&e.Lo===r&&"bottom"!==e.Wo.zOrder&&e.Wo.isBackground)return mi(e)}return e?.Wo?mi(e):null}class bi{constructor(t,i,s=50){this.Pn=0,this.kn=1,this.Tn=1,this.Dn=new Map,this.Rn=new Map,this.Uo=t,this.$o=i,this.Bn=s}jo(t){const i=t.time,s=this.$o.cacheKey(i),n=this.Dn.get(s);if(void 0!==n)return n.qo;if(this.Pn===this.Bn){const t=this.Rn.get(this.Tn);this.Rn.delete(this.Tn),this.Dn.delete(h(t)),this.Tn++,this.Pn--}const e=this.Uo(t);return this.Dn.set(s,{qo:e,An:this.kn}),this.Rn.set(this.kn,s),this.Pn++,this.kn++,e}}class xi{constructor(t,i){r(t<=i,"right should be >= left"),this.Yo=t,this.Ko=i}Uh(){return this.Yo}bi(){return this.Ko}Xo(){return this.Ko-this.Yo+1}Te(t){return this.Yo<=t&&t<=this.Ko}He(t){return this.Yo===t.Uh()&&this.Ko===t.bi()}}function Si(t,i){return null===t||null===i?t===i:t.He(i)}class Ci{constructor(){this.Zo=new Map,this.Dn=null,this.Go=!1}Jo(t){this.Go=t,this.Dn=null}Qo(t,i){this.t_(i),this.Dn=null;for(let s=i;s{t<=s[0].index?i.push(n):s.splice(bt(s,t,(i=>i.index!i||s.has(t.index);for(const i of Array.from(this.Zo.keys()).sort(((t,i)=>i-t))){if(!this.Zo.get(i))continue;const s=n;n=[];const r=s.length;let a=0;const l=h(this.Zo.get(i)),o=l.length;let _=1/0,u=-1/0;for(let i=0;i=t&&o-u>=t&&e(h))n.push(h),u=o;else if(this.Go)return s}for(;ai.weight?t:i}class ki{constructor(t,i,s,n){this.no=0,this.__=null,this.u_=[],this.ll=null,this.al=null,this.c_=new Ci,this.d_=new Map,this.f_=yi.o_(),this.p_=!0,this.v_=new o,this.m_=new o,this.w_=new o,this.g_=null,this.M_=null,this.b_=new Map,this.x_=-1,this.S_=[],this.ys=i,this.cl=s,this.C_=i.rightOffset,this.y_=i.barSpacing,this.ts=t,this.$o=n,this.P_(),this.c_.Jo(i.uniformDistribution),this.k_()}N(){return this.ys}T_(t){_(this.cl,t),this.R_(),this.P_()}hr(t,i){_(this.ys,t),this.ys.fixLeftEdge&&this.D_(),this.ys.fixRightEdge&&this.B_(),void 0!==t.barSpacing&&this.ts.dn(t.barSpacing),void 0!==t.rightOffset&&this.ts.fn(t.rightOffset),void 0===t.minBarSpacing&&void 0===t.maxBarSpacing||this.ts.dn(t.barSpacing??this.y_),void 0!==t.ignoreWhitespaceIndices&&t.ignoreWhitespaceIndices!==this.ys.ignoreWhitespaceIndices&&this.k_(),this.R_(),this.P_(),this.w_.p()}Rs(t){return this.u_[t]?.time??null}ss(t){return this.u_[t]??null}E_(t,i){if(this.u_.length<1)return null;if(this.$o.key(t)>this.$o.key(this.u_[this.u_.length-1].time))return i?this.u_.length-1:null;const s=bt(this.u_,this.$o.key(t),((t,i)=>this.$o.key(t.time)0}ye(){return this.V_(),this.f_.a_()}A_(){return this.V_(),this.f_.l_()}z_(){const t=this.ye();if(null===t)return null;const i={from:t.Uh(),to:t.bi()};return this.O_(i)}O_(t){const i=Math.round(t.from),s=Math.round(t.to),n=a(this.L_()),e=a(this.N_());return{from:a(this.ss(Math.max(n,i))),to:a(this.ss(Math.min(e,s)))}}W_(t){return{from:a(this.E_(t.from,!0)),to:a(this.E_(t.to,!0))}}Qi(){return this.no}vo(t){if(!isFinite(t)||t<=0)return;if(this.no===t)return;const i=this.A_(),s=this.no;if(this.no=t,this.p_=!0,this.ys.lockVisibleTimeRangeOnResize&&0!==s){const i=this.y_*t/s;this.y_=i}if(this.ys.fixLeftEdge&&null!==i&&i.Uh()<=0){const i=s-t;this.C_-=Math.round(i/this.y_)+1,this.p_=!0}this.F_(),this.H_()}jt(t){if(this.Ki()||!c(t))return 0;const i=this.U_()+this.C_-t;return this.no-(i+.5)*this.y_-1}j_(t,i){const s=this.U_(),n=void 0===i?0:i.from,e=void 0===i?t.length:i.to;for(let i=n;ii/2&&!_?s.needAlignCoordinate=!1:s.needAlignCoordinate=u&&t.index<=l||c&&t.index>=o,d++}return this.S_.length=d,this.M_=this.S_,this.S_}su(){this.p_=!0,this.dn(this.ys.barSpacing),this.fn(this.ys.rightOffset)}nu(t){this.p_=!0,this.__=t,this.H_(),this.D_()}eu(t,i){const s=this.Y_(t),n=this.G_(),e=n+i*(n/10);this.dn(e),this.ys.rightBarStaysOnScroll||this.fn(this.Q_()+(s-this.Y_(t)))}$l(t){this.ll&&this.Xl(),null===this.al&&null===this.g_&&(this.Ki()||(this.al=t,this.ru()))}jl(t){if(null===this.g_)return;const i=qt(this.no-t,0,this.no),s=qt(this.no-a(this.al),0,this.no);0!==i&&0!==s&&this.dn(this.g_.G_*i/s)}ql(){null!==this.al&&(this.al=null,this.hu())}Yl(t){null===this.ll&&null===this.g_&&(this.Ki()||(this.ll=t,this.ru()))}Kl(t){if(null===this.ll)return;const i=(this.ll-t)/this.G_();this.C_=a(this.g_).Q_+i,this.p_=!0,this.H_()}Xl(){null!==this.ll&&(this.ll=null,this.hu())}au(){this.lu(this.ys.rightOffset)}lu(t,i=400){if(!isFinite(t))throw new RangeError("offset is required and must be finite number");if(!isFinite(i)||i<=0)throw new RangeError("animationDuration (optional) must be finite positive number");const s=this.C_,n=performance.now();this.ts._n({ou:t=>(t-n)/i>=1,_u:e=>{const r=(e-n)/i;return r>=1?t:s+(t-s)*r}})}Pt(t,i){this.p_=!0,this.u_=t,this.c_.Qo(t,i),this.H_()}uu(){return this.v_}cu(){return this.m_}du(){return this.w_}U_(){return this.__||0}fu(t){const i=t.Xo();this.J_(this.no/i),this.C_=t.bi()-this.U_(),this.H_(),this.p_=!0,this.ts.Z_(),this.ts.ar()}pu(){const t=this.L_(),i=this.N_();null!==t&&null!==i&&this.fu(new xi(t,i+this.ys.rightOffset))}vu(t){const i=new xi(t.from,t.to);this.fu(i)}ns(t){return void 0!==this.cl.timeFormatter?this.cl.timeFormatter(t.originalTime):this.$o.formatHorzItem(t.time)}k_(){if(!this.ys.ignoreWhitespaceIndices)return;this.b_.clear();const t=this.ts.Ys();for(const i of t)for(const t of i.ma())this.b_.set(t,!0);this.x_++}tu(){const t=this.ts.N().handleScroll,i=this.ts.N().handleScale;return!(t.horzTouchDrag||t.mouseWheel||t.pressedMouseMove||t.vertTouchDrag||i.axisDoubleClickReset.time||i.axisPressedMouseMove.time||i.mouseWheel||i.pinch)}L_(){return 0===this.u_.length?null:0}N_(){return 0===this.u_.length?null:this.u_.length-1}mu(t){return(this.no-1-t)/this.y_}Y_(t){const i=this.mu(t),s=this.U_()+this.C_-i;return Math.round(1e6*s)/1e6}J_(t){const i=this.y_;this.y_=t,this.F_(),i!==this.y_&&(this.p_=!0,this.wu())}V_(){if(!this.p_)return;if(this.p_=!1,this.Ki())return void this.gu(yi.o_());const t=this.U_(),i=this.no/this.y_,s=this.C_+t,n=new xi(s-i+1,s);this.gu(new yi(n))}F_(){const t=qt(this.y_,this.Mu(),this.bu());this.y_!==t&&(this.y_=t,this.p_=!0)}bu(){return this.ys.maxBarSpacing>0?this.ys.maxBarSpacing:.5*this.no}Mu(){return this.ys.fixLeftEdge&&this.ys.fixRightEdge&&0!==this.u_.length?this.no/this.u_.length:this.ys.minBarSpacing}H_(){const t=this.xu();null!==t&&this.C_i&&(this.C_=i,this.p_=!0)}xu(){const t=this.L_(),i=this.__;if(null===t||null===i)return null;return t-i-1+(this.ys.fixLeftEdge?this.no/this.y_:Math.min(2,this.u_.length))}Su(){return this.ys.fixRightEdge?0:this.no/this.y_-Math.min(2,this.u_.length)}ru(){this.g_={G_:this.G_(),Q_:this.Q_()}}hu(){this.g_=null}iu(t){let i=this.d_.get(t.weight);return void 0===i&&(i=new bi((t=>this.Cu(t)),this.$o),this.d_.set(t.weight,i)),i.jo(t)}Cu(t){return this.$o.formatTickmark(t,this.cl)}gu(t){const i=this.f_;this.f_=t,Si(i.a_(),this.f_.a_())||this.v_.p(),Si(i.l_(),this.f_.l_())||this.m_.p(),this.wu()}wu(){this.M_=null}R_(){this.wu(),this.d_.clear()}P_(){this.$o.updateFormatter(this.cl)}D_(){if(!this.ys.fixLeftEdge)return;const t=this.L_();if(null===t)return;const i=this.ye();if(null===i)return;const s=i.Uh()-t;if(s<0){const t=this.C_-s-1;this.fn(t)}this.F_()}B_(){this.H_(),this.F_()}K_(t){return!this.ys.ignoreWhitespaceIndices||(this.b_.get(t)||!1)}X_(t){const i=function*(t){const i=Math.round(t),s=is)break}return t}}var Ti,Ri,Di,Bi,Ei;!function(t){t[t.OnTouchEnd=0]="OnTouchEnd",t[t.OnNextTap=1]="OnNextTap"}(Ti||(Ti={}));class Ii{constructor(t,i,s){this.yu=[],this.Pu=[],this.no=0,this.ku=null,this.Tu=new o,this.Ru=new o,this.Du=null,this.Bu=t,this.ys=i,this.$o=s,this.dl=new S(this.ys.layout.colorParsers),this.Eu=new M(this),this.uh=new ki(this,i.timeScale,this.ys.localization,s),this.Ct=new j(this,i.crosshair),this.Iu=new jt(i.crosshair),this.Vu(0),this.yu[0].po(2e3),this.Au=this.zu(0),this.Ou=this.zu(1)}Ih(){this.Lu(Y.gn())}ar(){this.Lu(Y.wn())}Zh(){this.Lu(new Y(1))}Vh(t){const i=this.Nu(t);this.Lu(i)}Wu(){return this.ku}Fu(t){if(this.ku?.Lo===t?.Lo&&this.ku?.No?.Kn===t?.No?.Kn)return;const i=this.ku;this.ku=t,null!==i&&this.Vh(i.Lo),null!==t&&t.Lo!==i?.Lo&&this.Vh(t.Lo)}N(){return this.ys}hr(t){_(this.ys,t),this.yu.forEach((i=>i.uo(t))),void 0!==t.timeScale&&this.uh.hr(t.timeScale),void 0!==t.localization&&this.uh.T_(t.localization),(t.leftPriceScale||t.rightPriceScale)&&this.Tu.p(),this.Au=this.zu(0),this.Ou=this.zu(1),this.Ih()}Hu(t,i,s=0){const n=this.yu[s];if(void 0===n)return;if("left"===t)return _(this.ys,{leftPriceScale:i}),n.uo({leftPriceScale:i}),this.Tu.p(),void this.Ih();if("right"===t)return _(this.ys,{rightPriceScale:i}),n.uo({rightPriceScale:i}),this.Tu.p(),void this.Ih();const e=this.Uu(t,s);null!==e&&(e.Wt.hr(i),this.Tu.p())}Uu(t,i){const s=this.yu[i];if(void 0===s)return null;const n=s.co(t);return null!==n?{Us:s,Wt:n}:null}Vt(){return this.uh}$s(){return this.yu}$u(){return this.Ct}ju(){return this.Ru}qu(t,i){t.yl(i),this.Z_()}vo(t){this.no=t,this.uh.vo(this.no),this.yu.forEach((i=>i.vo(t))),this.Z_()}Yu(t){1!==this.yu.length&&(r(t>=0&&t=0&&tt+i.fo()),0),e=this.yu.reduce(((t,i)=>t+i.$t()),0),h=e-30*(this.yu.length-1);i=Math.min(h,Math.max(30,i));const a=n/e,l=s.$t();s.po(i*a);let o=i-l,_=this.yu.length-1;for(const t of this.yu)if(t!==s){const i=Math.min(h,Math.max(30,t.$t()-o/_));o-=t.$t()-i,_-=1;const s=i*a;t.po(s)}this.Ih()}Xu(t,i){r(t>=0&&t=0&&ithis.$o.key(e),l=null!==t&&t>r&&!a,o=this.uh.N().allowShiftVisibleRangeOnWhitespaceReplacement,_=i&&(!(void 0===s)||o)&&this.uh.N().shiftVisibleRangeOnNewBar;if(l&&!_){const i=t-r;this.uh.fn(this.uh.Q_()-i)}}this.uh.nu(t)}Oh(t){null!==t&&t.Io()}Hn(t){if(function(t){return t instanceof vi}(t))return t;const i=this.yu.find((i=>i.Dt().includes(t)));return void 0===i?null:i}Z_(){this.yu.forEach((t=>t.Io())),this.Ah()}m(){this.yu.forEach((t=>t.m())),this.yu.length=0,this.ys.localization.priceFormatter=void 0,this.ys.localization.percentageFormatter=void 0,this.ys.localization.timeFormatter=void 0}_c(){return this.Eu}qn(){return this.Eu.N()}do(){return this.Tu}uc(t,i){const s=this.Vu(i);this.cc(t,s),this.Pu.push(t),1===this.Pu.length?this.Ih():this.ar()}dc(t){const i=this.Hn(t),s=this.Pu.indexOf(t);r(-1!==s,"Series not found");const n=a(i);this.Pu.splice(s,1),n.Fl(t),t.m&&t.m(),this.uh.k_(),this.fc(n)}Eh(t,i){const s=a(this.Hn(t));s.Fl(t,!0),s.Nl(t,i,!0)}pu(){const t=Y.wn();t.rn(),this.Lu(t)}vc(t){const i=Y.wn();i.ln(t),this.Lu(i)}cn(){const t=Y.wn();t.cn(),this.Lu(t)}dn(t){const i=Y.wn();i.dn(t),this.Lu(i)}fn(t){const i=Y.wn();i.fn(t),this.Lu(i)}_n(t){const i=Y.wn();i._n(t),this.Lu(i)}hn(){const t=Y.wn();t.hn(),this.Lu(t)}mc(){return this.ys.rightPriceScale.visible?"right":"left"}wc(t,i){r(i>=0,"Index should be greater or equal to 0");if(i===this.gc(t))return;const s=a(this.Hn(t));s.Fl(t);const n=this.Vu(i);this.cc(t,n),0===s.ba().length&&this.fc(s)}Mc(){return this.Ou}$(){return this.Au}Ut(t){const i=this.Ou,s=this.Au;if(i===s)return i;if(t=Math.max(0,Math.min(100,Math.round(100*t))),null===this.Du||this.Du.mr!==s||this.Du.wr!==i)this.Du={mr:s,wr:i,bc:new Map};else{const i=this.Du.bc.get(t);if(void 0!==i)return i}const n=this.dl.tt(s,i,t/100);return this.Du.bc.set(t,n),n}xc(t){return this.yu.indexOf(t)}Xi(){return this.dl}Vu(t){if(r(t>=0,"Index should be greater or equal to 0"),(t=Math.min(this.yu.length,t))i.wo().includes(t)))}Zu(t,i){const s=new Y(i);if(null!==t){const n=this.yu.indexOf(t);s.Qs(n,{tn:i})}return s}Nu(t,i){return void 0===i&&(i=2),this.Zu(this.Hn(t),i)}Lu(t){this.Bu&&this.Bu(t),this.yu.forEach((t=>t.zo().lr().Pt()))}cc(t,i){const s=t.N().priceScaleId,n=void 0!==s?s:this.mc();i.Nl(t,n),q(n)||t.hr(t.N())}zu(t){const i=this.ys.layout;return"gradient"===i.background.type?0===t?i.background.topColor:i.background.bottomColor:i.background.color}fc(t){0===t.ba().length&&this.yu.length>1&&(this.yu.splice(this.xc(t),1),this.Ih())}}function Vi(t){return!u(t)&&!d(t)}function Ai(t){return u(t)}!function(t){t[t.Disabled=0]="Disabled",t[t.Continuous=1]="Continuous",t[t.OnDataUpdate=2]="OnDataUpdate"}(Ri||(Ri={})),function(t){t[t.LastBar=0]="LastBar",t[t.LastVisible=1]="LastVisible"}(Di||(Di={})),function(t){t.Solid="solid",t.VerticalGradient="gradient"}(Bi||(Bi={})),function(t){t[t.Year=0]="Year",t[t.Month=1]="Month",t[t.DayOfMonth=2]="DayOfMonth",t[t.Time=3]="Time",t[t.TimeWithSeconds=4]="TimeWithSeconds"}(Ei||(Ei={}));const zi=t=>t.getUTCFullYear();function Oi(t,i,s){return i.replace(/yyyy/g,(t=>X(zi(t),4))(t)).replace(/yy/g,(t=>X(zi(t)%100,2))(t)).replace(/MMMM/g,((t,i)=>new Date(t.getUTCFullYear(),t.getUTCMonth(),1).toLocaleString(i,{month:"long"}))(t,s)).replace(/MMM/g,((t,i)=>new Date(t.getUTCFullYear(),t.getUTCMonth(),1).toLocaleString(i,{month:"short"}))(t,s)).replace(/MM/g,(t=>X((t=>t.getUTCMonth()+1)(t),2))(t)).replace(/dd/g,(t=>X((t=>t.getUTCDate())(t),2))(t))}class Li{constructor(t="yyyy-MM-dd",i="default"){this.Sc=t,this.Cc=i}jo(t){return Oi(t,this.Sc,this.Cc)}}class Ni{constructor(t){this.yc=t||"%h:%m:%s"}jo(t){return this.yc.replace("%h",X(t.getUTCHours(),2)).replace("%m",X(t.getUTCMinutes(),2)).replace("%s",X(t.getUTCSeconds(),2))}}const Wi={Pc:"yyyy-MM-dd",kc:"%h:%m:%s",Tc:" ",Rc:"default"};class Fi{constructor(t={}){const i={...Wi,...t};this.Dc=new Li(i.Pc,i.Rc),this.Bc=new Ni(i.kc),this.Ec=i.Tc}jo(t){return`${this.Dc.jo(t)}${this.Ec}${this.Bc.jo(t)}`}}function Hi(t){return 60*t*60*1e3}function Ui(t){return 60*t*1e3}const $i=[{Ic:(ji=1,1e3*ji),Vc:10},{Ic:Ui(1),Vc:20},{Ic:Ui(5),Vc:21},{Ic:Ui(30),Vc:22},{Ic:Hi(1),Vc:30},{Ic:Hi(3),Vc:31},{Ic:Hi(6),Vc:32},{Ic:Hi(12),Vc:33}];var ji;function qi(t,i){if(t.getUTCFullYear()!==i.getUTCFullYear())return 70;if(t.getUTCMonth()!==i.getUTCMonth())return 60;if(t.getUTCDate()!==i.getUTCDate())return 50;for(let s=$i.length-1;s>=0;--s)if(Math.floor(i.getTime()/$i[s].Ic)!==Math.floor(t.getTime()/$i[s].Ic))return $i[s].Vc;return 0}function Yi(t){let i=t;if(d(t)&&(i=Xi(t)),!Vi(i))throw new Error("time must be of type BusinessDay");const s=new Date(Date.UTC(i.year,i.month-1,i.day,0,0,0,0));return{Ac:Math.round(s.getTime()/1e3),zc:i}}function Ki(t){if(!Ai(t))throw new Error("time must be of type isUTCTimestamp");return{Ac:t}}function Xi(t){const i=new Date(t);if(isNaN(i.getTime()))throw new Error(`Invalid date string=${t}, expected format=yyyy-mm-dd`);return{day:i.getUTCDate(),month:i.getUTCMonth()+1,year:i.getUTCFullYear()}}function Zi(t){d(t.time)&&(t.time=Xi(t.time))}class Gi{options(){return this.ys}setOptions(t){this.ys=t,this.updateFormatter(t.localization)}preprocessData(t){Array.isArray(t)?function(t){t.forEach(Zi)}(t):Zi(t)}createConverterToInternalObj(t){return a(function(t){return 0===t.length?null:Vi(t[0].time)||d(t[0].time)?Yi:Ki}(t))}key(t){return"object"==typeof t&&"Ac"in t?t.Ac:this.key(this.convertHorzItemToInternal(t))}cacheKey(t){const i=t;return void 0===i.zc?new Date(1e3*i.Ac).getTime():new Date(Date.UTC(i.zc.year,i.zc.month-1,i.zc.day)).getTime()}convertHorzItemToInternal(t){return Ai(i=t)?Ki(i):Vi(i)?Yi(i):Yi(Xi(i));var i}updateFormatter(t){if(!this.ys)return;const i=t.dateFormat;this.ys.timeScale.timeVisible?this.Oc=new Fi({Pc:i,kc:this.ys.timeScale.secondsVisible?"%h:%m:%s":"%h:%m",Tc:" ",Rc:t.locale}):this.Oc=new Li(i,t.locale)}formatHorzItem(t){const i=t;return this.Oc.jo(new Date(1e3*i.Ac))}formatTickmark(t,i){const s=function(t,i,s){switch(t){case 0:case 10:return i?s?4:3:2;case 20:case 21:case 22:case 30:case 31:case 32:case 33:return i?3:2;case 50:return 2;case 60:return 1;case 70:return 0}}(t.weight,this.ys.timeScale.timeVisible,this.ys.timeScale.secondsVisible),n=this.ys.timeScale;if(void 0!==n.tickMarkFormatter){const e=n.tickMarkFormatter(t.originalTime,s,i.locale);if(null!==e)return e}return function(t,i,s){const n={};switch(i){case 0:n.year="numeric";break;case 1:n.month="short";break;case 2:n.day="numeric";break;case 3:n.hour12=!1,n.hour="2-digit",n.minute="2-digit";break;case 4:n.hour12=!1,n.hour="2-digit",n.minute="2-digit",n.second="2-digit"}const e=void 0===t.zc?new Date(1e3*t.Ac):new Date(Date.UTC(t.zc.year,t.zc.month-1,t.zc.day));return new Date(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds()).toLocaleString(s,n)}(t.time,s,i.locale)}maxTickMarkWeight(t){let i=t.reduce(Pi,t[0]).weight;return i>30&&i<50&&(i=30),i}fillWeightsForPoints(t,i){!function(t,i=0){if(0===t.length)return;let s=0===i?null:t[i-1].time.Ac,n=null!==s?new Date(1e3*s):null,e=0;for(let r=i;r1){const i=Math.ceil(e/(t.length-1)),s=new Date(1e3*(t[0].time.Ac-i));t[0].timeWeight=qi(new Date(1e3*t[0].time.Ac),s)}}(t,i)}static Lc(t){return _({localization:{dateFormat:"dd MMM 'yy"}},t??{})}}function Ji(t){var i=t.width,s=t.height;if(i<0)throw new Error("Negative width is not allowed for Size");if(s<0)throw new Error("Negative height is not allowed for Size");return{width:i,height:s}}function Qi(t,i){return t.width===i.width&&t.height===i.height}var ts=function(){function t(t){var i=this;this._resolutionListener=function(){return i._onResolutionChanged()},this._resolutionMediaQueryList=null,this._observers=[],this._window=t,this._installResolutionListener()}return t.prototype.dispose=function(){this._uninstallResolutionListener(),this._window=null},Object.defineProperty(t.prototype,"value",{get:function(){return this._window.devicePixelRatio},enumerable:!1,configurable:!0}),t.prototype.subscribe=function(t){var i=this,s={next:t};return this._observers.push(s),{unsubscribe:function(){i._observers=i._observers.filter((function(t){return t!==s}))}}},t.prototype._installResolutionListener=function(){if(null!==this._resolutionMediaQueryList)throw new Error("Resolution listener is already installed");var t=this._window.devicePixelRatio;this._resolutionMediaQueryList=this._window.matchMedia("all and (resolution: ".concat(t,"dppx)")),this._resolutionMediaQueryList.addListener(this._resolutionListener)},t.prototype._uninstallResolutionListener=function(){null!==this._resolutionMediaQueryList&&(this._resolutionMediaQueryList.removeListener(this._resolutionListener),this._resolutionMediaQueryList=null)},t.prototype._reinstallResolutionListener=function(){this._uninstallResolutionListener(),this._installResolutionListener()},t.prototype._onResolutionChanged=function(){var t=this;this._observers.forEach((function(i){return i.next(t._window.devicePixelRatio)})),this._reinstallResolutionListener()},t}();var is=function(){function t(t,i,s){var n;this._canvasElement=null,this._bitmapSizeChangedListeners=[],this._suggestedBitmapSize=null,this._suggestedBitmapSizeChangedListeners=[],this._devicePixelRatioObservable=null,this._canvasElementResizeObserver=null,this._canvasElement=t,this._canvasElementClientSize=Ji({width:this._canvasElement.clientWidth,height:this._canvasElement.clientHeight}),this._transformBitmapSize=null!=i?i:function(t){return t},this._allowResizeObserver=null===(n=null==s?void 0:s.allowResizeObserver)||void 0===n||n,this._chooseAndInitObserver()}return t.prototype.dispose=function(){var t,i;if(null===this._canvasElement)throw new Error("Object is disposed");null===(t=this._canvasElementResizeObserver)||void 0===t||t.disconnect(),this._canvasElementResizeObserver=null,null===(i=this._devicePixelRatioObservable)||void 0===i||i.dispose(),this._devicePixelRatioObservable=null,this._suggestedBitmapSizeChangedListeners.length=0,this._bitmapSizeChangedListeners.length=0,this._canvasElement=null},Object.defineProperty(t.prototype,"canvasElement",{get:function(){if(null===this._canvasElement)throw new Error("Object is disposed");return this._canvasElement},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"canvasElementClientSize",{get:function(){return this._canvasElementClientSize},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bitmapSize",{get:function(){return Ji({width:this.canvasElement.width,height:this.canvasElement.height})},enumerable:!1,configurable:!0}),t.prototype.resizeCanvasElement=function(t){this._canvasElementClientSize=Ji(t),this.canvasElement.style.width="".concat(this._canvasElementClientSize.width,"px"),this.canvasElement.style.height="".concat(this._canvasElementClientSize.height,"px"),this._invalidateBitmapSize()},t.prototype.subscribeBitmapSizeChanged=function(t){this._bitmapSizeChangedListeners.push(t)},t.prototype.unsubscribeBitmapSizeChanged=function(t){this._bitmapSizeChangedListeners=this._bitmapSizeChangedListeners.filter((function(i){return i!==t}))},Object.defineProperty(t.prototype,"suggestedBitmapSize",{get:function(){return this._suggestedBitmapSize},enumerable:!1,configurable:!0}),t.prototype.subscribeSuggestedBitmapSizeChanged=function(t){this._suggestedBitmapSizeChangedListeners.push(t)},t.prototype.unsubscribeSuggestedBitmapSizeChanged=function(t){this._suggestedBitmapSizeChangedListeners=this._suggestedBitmapSizeChangedListeners.filter((function(i){return i!==t}))},t.prototype.applySuggestedBitmapSize=function(){if(null!==this._suggestedBitmapSize){var t=this._suggestedBitmapSize;this._suggestedBitmapSize=null,this._resizeBitmap(t),this._emitSuggestedBitmapSizeChanged(t,this._suggestedBitmapSize)}},t.prototype._resizeBitmap=function(t){var i=this.bitmapSize;Qi(i,t)||(this.canvasElement.width=t.width,this.canvasElement.height=t.height,this._emitBitmapSizeChanged(i,t))},t.prototype._emitBitmapSizeChanged=function(t,i){var s=this;this._bitmapSizeChangedListeners.forEach((function(n){return n.call(s,t,i)}))},t.prototype._suggestNewBitmapSize=function(t){var i=this._suggestedBitmapSize,s=Ji(this._transformBitmapSize(t,this._canvasElementClientSize)),n=Qi(this.bitmapSize,s)?null:s;null===i&&null===n||null!==i&&null!==n&&Qi(i,n)||(this._suggestedBitmapSize=n,this._emitSuggestedBitmapSizeChanged(i,n))},t.prototype._emitSuggestedBitmapSizeChanged=function(t,i){var s=this;this._suggestedBitmapSizeChangedListeners.forEach((function(n){return n.call(s,t,i)}))},t.prototype._chooseAndInitObserver=function(){var t=this;this._allowResizeObserver?new Promise((function(t){var i=new ResizeObserver((function(s){t(s.every((function(t){return"devicePixelContentBoxSize"in t}))),i.disconnect()}));i.observe(document.body,{box:"device-pixel-content-box"})})).catch((function(){return!1})).then((function(i){return i?t._initResizeObserver():t._initDevicePixelRatioObservable()})):this._initDevicePixelRatioObservable()},t.prototype._initDevicePixelRatioObservable=function(){var t=this;if(null!==this._canvasElement){var i=ss(this._canvasElement);if(null===i)throw new Error("No window is associated with the canvas");this._devicePixelRatioObservable=function(t){return new ts(t)}(i),this._devicePixelRatioObservable.subscribe((function(){return t._invalidateBitmapSize()})),this._invalidateBitmapSize()}},t.prototype._invalidateBitmapSize=function(){var t,i;if(null!==this._canvasElement){var s=ss(this._canvasElement);if(null!==s){var n=null!==(i=null===(t=this._devicePixelRatioObservable)||void 0===t?void 0:t.value)&&void 0!==i?i:s.devicePixelRatio,e=this._canvasElement.getClientRects(),r=void 0!==e[0]?function(t,i){return Ji({width:Math.round(t.left*i+t.width*i)-Math.round(t.left*i),height:Math.round(t.top*i+t.height*i)-Math.round(t.top*i)})}(e[0],n):Ji({width:this._canvasElementClientSize.width*n,height:this._canvasElementClientSize.height*n});this._suggestNewBitmapSize(r)}}},t.prototype._initResizeObserver=function(){var t=this;null!==this._canvasElement&&(this._canvasElementResizeObserver=new ResizeObserver((function(i){var s=i.find((function(i){return i.target===t._canvasElement}));if(s&&s.devicePixelContentBoxSize&&s.devicePixelContentBoxSize[0]){var n=s.devicePixelContentBoxSize[0],e=Ji({width:n.inlineSize,height:n.blockSize});t._suggestNewBitmapSize(e)}})),this._canvasElementResizeObserver.observe(this._canvasElement,{box:"device-pixel-content-box"}))},t}();function ss(t){return t.ownerDocument.defaultView}var ns=function(){function t(t,i,s){if(0===i.width||0===i.height)throw new TypeError("Rendering target could only be created on a media with positive width and height");if(this._mediaSize=i,0===s.width||0===s.height)throw new TypeError("Rendering target could only be created using a bitmap with positive integer width and height");this._bitmapSize=s,this._context=t}return t.prototype.useMediaCoordinateSpace=function(t){try{return this._context.save(),this._context.setTransform(1,0,0,1,0,0),this._context.scale(this._horizontalPixelRatio,this._verticalPixelRatio),t({context:this._context,mediaSize:this._mediaSize})}finally{this._context.restore()}},t.prototype.useBitmapCoordinateSpace=function(t){try{return this._context.save(),this._context.setTransform(1,0,0,1,0,0),t({context:this._context,mediaSize:this._mediaSize,bitmapSize:this._bitmapSize,horizontalPixelRatio:this._horizontalPixelRatio,verticalPixelRatio:this._verticalPixelRatio})}finally{this._context.restore()}},Object.defineProperty(t.prototype,"_horizontalPixelRatio",{get:function(){return this._bitmapSize.width/this._mediaSize.width},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_verticalPixelRatio",{get:function(){return this._bitmapSize.height/this._mediaSize.height},enumerable:!1,configurable:!0}),t}();function es(t,i){var s=t.canvasElementClientSize;if(0===s.width||0===s.height)return null;var n=t.bitmapSize;if(0===n.width||0===n.height)return null;var e=t.canvasElement.getContext("2d",i);return null===e?null:new ns(e,s,n)}const rs="undefined"!=typeof window;function hs(){return!!rs&&window.navigator.userAgent.toLowerCase().indexOf("firefox")>-1}function as(){return!!rs&&/iPhone|iPad|iPod/.test(window.navigator.platform)}function ls(t){return t+t%2}function os(t){rs&&void 0!==window.chrome&&t.addEventListener("mousedown",(t=>{if(1===t.button)return t.preventDefault(),!1}))}class _s{constructor(t,i,s){this.Nc=0,this.Wc=null,this.Fc={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY},this.Hc=0,this.Uc=null,this.$c={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY},this.jc=null,this.qc=!1,this.Yc=null,this.Kc=null,this.Xc=!1,this.Zc=!1,this.Gc=!1,this.Jc=null,this.Qc=null,this.td=null,this.sd=null,this.nd=null,this.ed=null,this.rd=null,this.hd=0,this.ad=!1,this.ld=!1,this.od=!1,this._d=0,this.ud=null,this.dd=!as(),this.fd=t=>{this.pd(t)},this.vd=t=>{if(this.md(t)){const i=this.wd(t);if(++this.Hc,this.Uc&&this.Hc>1){const{gd:s}=this.Md(ds(t),this.$c);s<30&&!this.Gc&&this.bd(i,this.Sd.xd),this.Cd()}}else{const i=this.wd(t);if(++this.Nc,this.Wc&&this.Nc>1){const{gd:s}=this.Md(ds(t),this.Fc);s<5&&!this.Zc&&this.yd(i,this.Sd.Pd),this.kd()}}},this.Td=t,this.Sd=i,this.ys=s,this.Rd()}m(){null!==this.Jc&&(this.Jc(),this.Jc=null),null!==this.Qc&&(this.Qc(),this.Qc=null),null!==this.sd&&(this.sd(),this.sd=null),null!==this.nd&&(this.nd(),this.nd=null),null!==this.ed&&(this.ed(),this.ed=null),null!==this.td&&(this.td(),this.td=null),this.Dd(),this.kd()}Bd(t){this.sd&&this.sd();const i=this.Ed.bind(this);if(this.sd=()=>{this.Td.removeEventListener("mousemove",i)},this.Td.addEventListener("mousemove",i),this.md(t))return;const s=this.wd(t);this.yd(s,this.Sd.Id),this.dd=!0}kd(){null!==this.Wc&&clearTimeout(this.Wc),this.Nc=0,this.Wc=null,this.Fc={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY}}Cd(){null!==this.Uc&&clearTimeout(this.Uc),this.Hc=0,this.Uc=null,this.$c={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY}}Ed(t){if(this.od||null!==this.Kc)return;if(this.md(t))return;const i=this.wd(t);this.yd(i,this.Sd.Vd),this.dd=!0}Ad(t){const i=ps(t.changedTouches,a(this.ud));if(null===i)return;if(this._d=fs(t),null!==this.rd)return;if(this.ld)return;this.ad=!0;const s=this.Md(ds(i),a(this.Kc)),{zd:n,Od:e,gd:r}=s;if(this.Xc||!(r<5)){if(!this.Xc){const t=.5*n,i=e>=t&&!this.ys.Ld(),s=t>e&&!this.ys.Nd();i||s||(this.ld=!0),this.Xc=!0,this.Gc=!0,this.Dd(),this.Cd()}if(!this.ld){const s=this.wd(t,i);this.bd(s,this.Sd.Wd),cs(t)}}}Fd(t){if(0!==t.button)return;const i=this.Md(ds(t),a(this.Yc)),{gd:s}=i;if(s>=5&&(this.Zc=!0,this.kd()),this.Zc){const i=this.wd(t);this.yd(i,this.Sd.Hd)}}Md(t,i){const s=Math.abs(i._t-t._t),n=Math.abs(i.ut-t.ut);return{zd:s,Od:n,gd:s+n}}Ud(t){let i=ps(t.changedTouches,a(this.ud));if(null===i&&0===t.touches.length&&(i=t.changedTouches[0]),null===i)return;this.ud=null,this._d=fs(t),this.Dd(),this.Kc=null,this.ed&&(this.ed(),this.ed=null);const s=this.wd(t,i);if(this.bd(s,this.Sd.$d),++this.Hc,this.Uc&&this.Hc>1){const{gd:t}=this.Md(ds(i),this.$c);t<30&&!this.Gc&&this.bd(s,this.Sd.xd),this.Cd()}else this.Gc||(this.bd(s,this.Sd.jd),this.Sd.jd&&cs(t));0===this.Hc&&cs(t),0===t.touches.length&&this.qc&&(this.qc=!1,cs(t))}pd(t){if(0!==t.button)return;const i=this.wd(t);if(this.Yc=null,this.od=!1,this.nd&&(this.nd(),this.nd=null),hs()){this.Td.ownerDocument.documentElement.removeEventListener("mouseleave",this.fd)}if(!this.md(t))if(this.yd(i,this.Sd.qd),++this.Nc,this.Wc&&this.Nc>1){const{gd:s}=this.Md(ds(t),this.Fc);s<5&&!this.Zc&&this.yd(i,this.Sd.Pd),this.kd()}else this.Zc||this.yd(i,this.Sd.Yd)}Dd(){null!==this.jc&&(clearTimeout(this.jc),this.jc=null)}Kd(t){if(null!==this.ud)return;const i=t.changedTouches[0];this.ud=i.identifier,this._d=fs(t);const s=this.Td.ownerDocument.documentElement;this.Gc=!1,this.Xc=!1,this.ld=!1,this.Kc=ds(i),this.ed&&(this.ed(),this.ed=null);{const i=this.Ad.bind(this),n=this.Ud.bind(this);this.ed=()=>{s.removeEventListener("touchmove",i),s.removeEventListener("touchend",n)},s.addEventListener("touchmove",i,{passive:!1}),s.addEventListener("touchend",n,{passive:!1}),this.Dd(),this.jc=setTimeout(this.Xd.bind(this,t),240)}const n=this.wd(t,i);this.bd(n,this.Sd.Zd),this.Uc||(this.Hc=0,this.Uc=setTimeout(this.Cd.bind(this),500),this.$c=ds(i))}Gd(t){if(0!==t.button)return;const i=this.Td.ownerDocument.documentElement;hs()&&i.addEventListener("mouseleave",this.fd),this.Zc=!1,this.Yc=ds(t),this.nd&&(this.nd(),this.nd=null);{const t=this.Fd.bind(this),s=this.pd.bind(this);this.nd=()=>{i.removeEventListener("mousemove",t),i.removeEventListener("mouseup",s)},i.addEventListener("mousemove",t),i.addEventListener("mouseup",s)}if(this.od=!0,this.md(t))return;const s=this.wd(t);this.yd(s,this.Sd.Jd),this.Wc||(this.Nc=0,this.Wc=setTimeout(this.kd.bind(this),500),this.Fc=ds(t))}Rd(){this.Td.addEventListener("mouseenter",this.Bd.bind(this)),this.Td.addEventListener("touchcancel",this.Dd.bind(this));{const t=this.Td.ownerDocument,i=t=>{this.Sd.Qd&&(t.composed&&this.Td.contains(t.composedPath()[0])||t.target&&this.Td.contains(t.target)||this.Sd.Qd())};this.Qc=()=>{t.removeEventListener("touchstart",i)},this.Jc=()=>{t.removeEventListener("mousedown",i)},t.addEventListener("mousedown",i),t.addEventListener("touchstart",i,{passive:!0})}as()&&(this.td=()=>{this.Td.removeEventListener("dblclick",this.vd)},this.Td.addEventListener("dblclick",this.vd)),this.Td.addEventListener("mouseleave",this.tf.bind(this)),this.Td.addEventListener("touchstart",this.Kd.bind(this),{passive:!0}),os(this.Td),this.Td.addEventListener("mousedown",this.Gd.bind(this)),this.if(),this.Td.addEventListener("touchmove",(()=>{}),{passive:!1})}if(){void 0===this.Sd.sf&&void 0===this.Sd.nf&&void 0===this.Sd.ef||(this.Td.addEventListener("touchstart",(t=>this.rf(t.touches)),{passive:!0}),this.Td.addEventListener("touchmove",(t=>{if(2===t.touches.length&&null!==this.rd&&void 0!==this.Sd.nf){const i=us(t.touches[0],t.touches[1])/this.hd;this.Sd.nf(this.rd,i),cs(t)}}),{passive:!1}),this.Td.addEventListener("touchend",(t=>{this.rf(t.touches)})))}rf(t){1===t.length&&(this.ad=!1),2!==t.length||this.ad||this.qc?this.hf():this.af(t)}af(t){const i=this.Td.getBoundingClientRect()||{left:0,top:0};this.rd={_t:(t[0].clientX-i.left+(t[1].clientX-i.left))/2,ut:(t[0].clientY-i.top+(t[1].clientY-i.top))/2},this.hd=us(t[0],t[1]),void 0!==this.Sd.sf&&this.Sd.sf(),this.Dd()}hf(){null!==this.rd&&(this.rd=null,void 0!==this.Sd.ef&&this.Sd.ef())}tf(t){if(this.sd&&this.sd(),this.md(t))return;if(!this.dd)return;const i=this.wd(t);this.yd(i,this.Sd.lf),this.dd=!as()}Xd(t){const i=ps(t.touches,a(this.ud));if(null===i)return;const s=this.wd(t,i);this.bd(s,this.Sd._f),this.Gc=!0,this.qc=!0}md(t){return t.sourceCapabilities&&void 0!==t.sourceCapabilities.firesTouchEvents?t.sourceCapabilities.firesTouchEvents:fs(t){"touchstart"!==t.type&&cs(t)}}}}function us(t,i){const s=t.clientX-i.clientX,n=t.clientY-i.clientY;return Math.sqrt(s*s+n*n)}function cs(t){t.cancelable&&t.preventDefault()}function ds(t){return{_t:t.pageX,ut:t.pageY}}function fs(t){return t.timeStamp||performance.now()}function ps(t,i){for(let s=0;s!1,Nd:()=>!0}),this.pf={Ef:s,Bf:t}}yf(){this.Cf.style.background=this.gf.N().layout.panes.separatorColor}If(t){null!==this.pf&&(this.pf.Ef.style.backgroundColor=this.gf.N().layout.panes.separatorHoverColor)}Vf(t){null!==this.pf&&null===this.wf&&(this.pf.Ef.style.backgroundColor="")}Af(t){if(null===this.pf)return;const i=this.Mf.Lf().fo()+this.xf.Lf().fo(),s=i/(this.Mf.Tf().height+this.xf.Tf().height),n=30*s;i<=2*n||(this.wf={Nf:t.pageY,Wf:this.Mf.Lf().fo(),Ff:i-n,Hf:i,Uf:s,$f:n},this.pf.Bf.style.display="block")}zf(t){const i=this.wf;if(null===i)return;const s=(t.pageY-i.Nf)*i.Uf,n=qt(i.Wf+s,i.$f,i.Ff);this.Mf.Lf().po(n),this.xf.Lf().po(i.Hf-n),this.gf.Qt().Ih()}Of(t){null!==this.wf&&null!==this.pf&&(this.wf=null,this.pf.Bf.style.display="none")}}function ms(t,i){return t.jf-i.jf}function ws(t,i,s){const n=(t.jf-i.jf)/(t.wt-i.wt);return Math.sign(n)*Math.min(Math.abs(n),s)}class gs{constructor(t,i,s,n){this.qf=null,this.Yf=null,this.Kf=null,this.Xf=null,this.Zf=null,this.Gf=0,this.Jf=0,this.Qf=t,this.tp=i,this.ip=s,this.Mn=n}sp(t,i){if(null!==this.qf){if(this.qf.wt===i)return void(this.qf.jf=t);if(Math.abs(this.qf.jf-t)50)return;let s=0;const n=ws(this.qf,this.Yf,this.tp),e=ms(this.qf,this.Yf),r=[n],h=[e];if(s+=e,null!==this.Kf){const t=ws(this.Yf,this.Kf,this.tp);if(Math.sign(t)===Math.sign(n)){const i=ms(this.Yf,this.Kf);if(r.push(t),h.push(i),s+=i,null!==this.Xf){const t=ws(this.Kf,this.Xf,this.tp);if(Math.sign(t)===Math.sign(n)){const i=ms(this.Kf,this.Xf);r.push(t),h.push(i),s+=i}}}}let a=0;for(let t=0;t160?"dark":"light"}cp(){return this.lp.N().layout.attributionLogo}fp(){const t=new URL(location.href);return t.hostname?"&utm_source="+t.hostname+t.pathname:""}op(){this.up()&&(this._p(),this.ps=this.cp(),this.ps&&(this.hp=this.dp(),this.rp=document.createElement("style"),this.rp.innerText="a#tv-attr-logo{--fill:#131722;--stroke:#fff;position:absolute;left:10px;bottom:10px;height:19px;width:35px;margin:0;padding:0;border:0;z-index:3;}a#tv-attr-logo[data-dark]{--fill:#D1D4DC;--stroke:#131722;}",this.ep=document.createElement("a"),this.ep.href=`https://www.tradingview.com/?utm_medium=lwc-link&utm_campaign=lwc-chart${this.fp()}`,this.ep.title="Charting by TradingView",this.ep.id="tv-attr-logo",this.ep.target="_blank",this.ep.innerHTML='',this.ep.toggleAttribute("data-dark","dark"===this.hp),this.ap.appendChild(this.rp),this.ap.appendChild(this.ep)))}}function bs(t,i){const s=a(t.ownerDocument).createElement("canvas");t.appendChild(s);const n=new is(s,(e={options:{allowResizeObserver:!0},transform:(t,i)=>({width:Math.max(t.width,i.width),height:Math.max(t.height,i.height)})}).transform,e.options);var e;return n.resizeCanvasElement(i),n}function xs(t){t.width=1,t.height=1,t.getContext("2d")?.clearRect(0,0,1,1)}function Ss(t,i,s,n){t.ih&&t.ih(i,s,n)}function Cs(t,i,s,n){t.nt(i,s,n)}function ys(t,i,s,n){const e=t(s,n);for(const t of e){const s=t.Tt(n);null!==s&&i(s)}}function Ps(t,i){return s=>{if(!function(t){return void 0!==t.Wt}(s))return[];return(s.Wt()?.wa()??"")!==i?[]:s.ta?.(t)??[]}}function ks(t,i,s,n){if(!t.length)return;let e=0;const r=t[0].$t(n,!0);let h=1===i?s/2-(t[0].Wi()-r/2):t[0].Wi()-r/2-s/2;h=Math.max(0,h);for(let r=1;ru-o:_s)&&h>0){const n=1===i?-1-r:r-s,a=Math.min(n,h);for(let s=e;s{this.Mp||this.yt.xp().Qt().ar()},this.Sp=()=>{this.Mp||this.yt.xp().Qt().ar()},this.yt=t,this.ys=i,this.ul=i.layout,this.Eu=s,this.Cp="left"===n,this.yp=Ps("normal",n),this.Pp=Ps("top",n),this.kp=Ps("bottom",n),this.Cf=document.createElement("div"),this.Cf.style.height="100%",this.Cf.style.overflow="hidden",this.Cf.style.width="25px",this.Cf.style.left="0",this.Cf.style.position="relative",this.Tp=bs(this.Cf,Ji({width:16,height:16})),this.Tp.subscribeSuggestedBitmapSizeChanged(this.bp);const e=this.Tp.canvasElement;e.style.position="absolute",e.style.zIndex="1",e.style.left="0",e.style.top="0",this.Rp=bs(this.Cf,Ji({width:16,height:16})),this.Rp.subscribeSuggestedBitmapSizeChanged(this.Sp);const r=this.Rp.canvasElement;r.style.position="absolute",r.style.zIndex="2",r.style.left="0",r.style.top="0";const h={Jd:this.Af.bind(this),Zd:this.Af.bind(this),Hd:this.zf.bind(this),Wd:this.zf.bind(this),Qd:this.Dp.bind(this),qd:this.Of.bind(this),$d:this.Of.bind(this),Pd:this.Bp.bind(this),xd:this.Bp.bind(this),Id:this.Ep.bind(this),lf:this.Vf.bind(this)};this.vf=new _s(this.Rp.canvasElement,h,{Ld:()=>!this.ys.handleScroll.vertTouchDrag,Nd:()=>!0})}m(){this.vf.m(),this.Rp.unsubscribeSuggestedBitmapSizeChanged(this.Sp),xs(this.Rp.canvasElement),this.Rp.dispose(),this.Tp.unsubscribeSuggestedBitmapSizeChanged(this.bp),xs(this.Tp.canvasElement),this.Tp.dispose(),null!==this.qi&&this.qi.Ul().u(this),this.qi=null}kf(){return this.Cf}P(){return this.ul.fontSize}Ip(){const t=this.Eu.N();return this.wp!==t.k&&(this.mp.En(),this.wp=t.k),t}Vp(){if(null===this.qi)return 0;let t=0;const i=this.Ip(),s=a(this.Tp.canvasElement.getContext("2d",{colorSpace:this.yt.xp().N().layout.colorSpace}));s.save();const n=this.qi.Ba();s.font=this.Ap(),n.length>0&&(t=Math.max(this.mp.Bi(s,n[0].$a),this.mp.Bi(s,n[n.length-1].$a)));const e=this.zp();for(let i=e.length;i--;){const n=this.mp.Bi(s,e[i].ri());n>t&&(t=n)}const r=this.qi.zt();if(null!==r&&null!==this.pp&&(2!==(h=this.ys.crosshair).mode&&h.horzLine.visible&&h.horzLine.labelVisible)){const i=this.qi.Ts(1,r),n=this.qi.Ts(this.pp.height-2,r);t=Math.max(t,this.mp.Bi(s,this.qi.Zi(Math.floor(Math.min(i,n))+.11111111111111,r)),this.mp.Bi(s,this.qi.Zi(Math.ceil(Math.max(i,n))-.11111111111111,r)))}var h;s.restore();const l=t||34;return ls(Math.ceil(i.S+i.C+i.I+i.V+5+l))}Op(t){null!==this.pp&&Qi(this.pp,t)||(this.pp=t,this.Mp=!0,this.Tp.resizeCanvasElement(t),this.Rp.resizeCanvasElement(t),this.Mp=!1,this.Cf.style.width=`${t.width}px`,this.Cf.style.height=`${t.height}px`)}Lp(){return a(this.pp).width}_s(t){this.qi!==t&&(null!==this.qi&&this.qi.Ul().u(this),this.qi=t,t.Ul().i(this.il.bind(this),this))}Wt(){return this.qi}En(){const t=this.yt.Lf();this.yt.xp().Qt().Bo(t,a(this.Wt()))}Np(t){if(null===this.pp)return;const i={colorSpace:this.yt.xp().N().layout.colorSpace};if(1!==t){this.Wp(),this.Tp.applySuggestedBitmapSize();const t=es(this.Tp,i);null!==t&&(t.useBitmapCoordinateSpace((t=>{this.Fp(t),this.Hp(t)})),this.yt.Up(t,this.kp),this.$p(t),this.yt.Up(t,this.yp),this.jp(t))}this.Rp.applySuggestedBitmapSize();const s=es(this.Rp,i);null!==s&&(s.useBitmapCoordinateSpace((({context:t,bitmapSize:i})=>{t.clearRect(0,0,i.width,i.height)})),this.qp(s),this.yt.Up(s,this.Pp))}Rf(){return this.Tp.bitmapSize}Df(t,i,s){const n=this.Rf();n.width>0&&n.height>0&&t.drawImage(this.Tp.canvasElement,i,s)}Pt(){this.qi?.Ba()}Af(t){if(null===this.qi||this.qi.Ki()||!this.ys.handleScale.axisPressedMouseMove.price)return;const i=this.yt.xp().Qt(),s=this.yt.Lf();this.vp=!0,i.Co(s,this.qi,t.localY)}zf(t){if(null===this.qi||!this.ys.handleScale.axisPressedMouseMove.price)return;const i=this.yt.xp().Qt(),s=this.yt.Lf(),n=this.qi;i.yo(s,n,t.localY)}Dp(){if(null===this.qi||!this.ys.handleScale.axisPressedMouseMove.price)return;const t=this.yt.xp().Qt(),i=this.yt.Lf(),s=this.qi;this.vp&&(this.vp=!1,t.Po(i,s))}Of(t){if(null===this.qi||!this.ys.handleScale.axisPressedMouseMove.price)return;const i=this.yt.xp().Qt(),s=this.yt.Lf();this.vp=!1,i.Po(s,this.qi)}Bp(t){this.ys.handleScale.axisDoubleClickReset.price&&this.En()}Ep(t){if(null===this.qi)return;!this.yt.xp().Qt().N().handleScale.axisPressedMouseMove.price||this.qi.Oe()||this.qi.Ml()||this.Yp(1)}Vf(t){this.Yp(0)}zp(){const t=[],i=null===this.qi?void 0:this.qi;return(s=>{for(let n=0;n{t.fillStyle=s.borderColor;const a=Math.max(1,Math.floor(h)),l=Math.floor(.5*h),o=Math.round(n.C*r);t.beginPath();for(const s of i)t.rect(Math.floor(e*r),Math.round(s.Pa*h)-l,o,a);t.fill()})),t.useMediaCoordinateSpace((({context:t})=>{t.font=this.Ap(),t.fillStyle=s.textColor??this.ul.textColor,t.textAlign=this.Cp?"right":"left",t.textBaseline="middle";const r=this.Cp?Math.round(e-n.I):Math.round(e+n.C+n.I),h=i.map((i=>this.mp.Di(t,i.$a)));for(let s=i.length;s--;){const n=i[s];t.fillText(n.$a,r,n.Pa+h[s])}}))}Wp(){if(null===this.pp||null===this.qi)return;let t=this.pp.height/2;const i=[],s=this.qi.Dt().slice(),n=this.yt.Lf(),e=this.Ip();this.qi===n.$n()&&this.yt.Lf().Dt().forEach((t=>{n.Un(t)&&s.push(t)}));const r=this.qi.ba()[0],h=this.qi;s.forEach((s=>{const e=s.Fs(n,h);e.forEach((t=>{t.Fi(null),t.Hi()&&i.push(t)})),r===s&&e.length>0&&(t=e[0].Ii())})),i.forEach((t=>t.Fi(t.Ii())));this.qi.N().alignLabels&&this.Kp(i,e,t)}Kp(t,i,s){if(null===this.pp)return;const n=t.filter((t=>t.Ii()<=s)),e=t.filter((t=>t.Ii()>s));n.sort(((t,i)=>i.Ii()-t.Ii())),n.length&&e.length&&e.push(n[0]),e.sort(((t,i)=>t.Ii()-i.Ii()));for(const s of t){const t=Math.floor(s.$t(i)/2),n=s.Ii();n>-t&&nthis.pp.height-t&&n{if(i.Ui()){i.Tt(a(this.qi)).nt(t,s,this.mp,n)}}))}qp(t){if(null===this.pp||null===this.qi)return;const i=this.yt.xp().Qt(),s=[],n=this.yt.Lf(),e=i.$u().Fs(n,this.qi);e.length&&s.push(e);const r=this.Ip(),h=this.Cp?"right":"left";s.forEach((i=>{i.forEach((i=>{i.Tt(a(this.qi)).nt(t,r,this.mp,h)}))}))}Yp(t){this.Cf.style.cursor=1===t?"ns-resize":"default"}il(){const t=this.Vp();this.gp{this.Mp||null===this.lv||this.ts().ar()},this.Sp=()=>{this.Mp||null===this.lv||this.ts().ar()},this.lp=t,this.lv=i,this.lv.Ao().i(this.ov.bind(this),this,!0),this._v=document.createElement("td"),this._v.style.padding="0",this._v.style.position="relative";const s=document.createElement("div");s.style.width="100%",s.style.height="100%",s.style.position="relative",s.style.overflow="hidden",this.uv=document.createElement("td"),this.uv.style.padding="0",this.cv=document.createElement("td"),this.cv.style.padding="0",this._v.appendChild(s),this.Tp=bs(s,Ji({width:16,height:16})),this.Tp.subscribeSuggestedBitmapSizeChanged(this.bp);const n=this.Tp.canvasElement;n.style.position="absolute",n.style.zIndex="1",n.style.left="0",n.style.top="0",this.Rp=bs(s,Ji({width:16,height:16})),this.Rp.subscribeSuggestedBitmapSizeChanged(this.Sp);const e=this.Rp.canvasElement;e.style.position="absolute",e.style.zIndex="2",e.style.left="0",e.style.top="0",this.Sf=document.createElement("tr"),this.Sf.appendChild(this.uv),this.Sf.appendChild(this._v),this.Sf.appendChild(this.cv),this.dv(),this.vf=new _s(this.Rp.canvasElement,this,{Ld:()=>null===this.ev&&!this.lp.N().handleScroll.vertTouchDrag,Nd:()=>null===this.ev&&!this.lp.N().handleScroll.horzTouchDrag})}m(){null!==this.Xp&&this.Xp.m(),null!==this.Zp&&this.Zp.m(),this.Gp=null,this.Rp.unsubscribeSuggestedBitmapSizeChanged(this.Sp),xs(this.Rp.canvasElement),this.Rp.dispose(),this.Tp.unsubscribeSuggestedBitmapSizeChanged(this.bp),xs(this.Tp.canvasElement),this.Tp.dispose(),null!==this.lv&&(this.lv.Ao().u(this),this.lv.m()),this.vf.m()}Lf(){return a(this.lv)}fv(t){null!==this.lv&&this.lv.Ao().u(this),this.lv=t,null!==this.lv&&this.lv.Ao().i(Is.prototype.ov.bind(this),this,!0),this.dv(),this.lp.bf().indexOf(this)===this.lp.bf().length-1?(this.Gp=this.Gp??new Ms(this._v,this.lp),this.Gp.Pt()):(this.Gp?._p(),this.Gp=null)}xp(){return this.lp}kf(){return this.Sf}dv(){if(null!==this.lv&&(this.pv(),0!==this.ts().Ys().length)){if(null!==this.Xp){const t=this.lv.xo();this.Xp._s(a(t))}if(null!==this.Zp){const t=this.lv.So();this.Zp._s(a(t))}}}vv(){null!==this.Xp&&this.Xp.Pt(),null!==this.Zp&&this.Zp.Pt()}fo(){return null!==this.lv?this.lv.fo():0}po(t){this.lv&&this.lv.po(t)}Id(t){if(!this.lv)return;this.mv();const i=t.localX,s=t.localY;this.wv(i,s,t)}Jd(t){this.mv(),this.gv(),this.wv(t.localX,t.localY,t)}Vd(t){if(!this.lv)return;this.mv();const i=t.localX,s=t.localY;this.wv(i,s,t)}Yd(t){null!==this.lv&&(this.mv(),this.Mv(t))}Pd(t){null!==this.lv&&this.bv(this.iv,t)}xd(t){this.Pd(t)}Hd(t){this.mv(),this.xv(t),this.wv(t.localX,t.localY,t)}qd(t){null!==this.lv&&(this.mv(),this.nv=!1,this.Sv(t))}jd(t){null!==this.lv&&this.Mv(t)}_f(t){if(this.nv=!0,null===this.ev){const i={x:t.localX,y:t.localY};this.Cv(i,i,t)}}lf(t){null!==this.lv&&(this.mv(),this.lv.Qt().Fu(null),this.yv())}Pv(){return this.tv}kv(){return this.iv}sf(){this.sv=1,this.ts().hn()}nf(t,i){if(!this.lp.N().handleScale.pinch)return;const s=5*(i-this.sv);this.sv=i,this.ts().Ju(t._t,s)}Zd(t){this.nv=!1,this.rv=null!==this.ev,this.gv();const i=this.ts().$u();null!==this.ev&&i.Bt()&&(this.hv={x:i.si(),y:i.ni()},this.ev={x:t.localX,y:t.localY})}Wd(t){if(null===this.lv)return;const i=t.localX,s=t.localY;if(null===this.ev)this.xv(t);else{this.rv=!1;const n=a(this.hv),e=n.x+(i-this.ev.x),r=n.y+(s-this.ev.y);this.wv(e,r,t)}}$d(t){0===this.xp().N().trackingMode.exitMode&&(this.rv=!0),this.Tv(),this.Sv(t)}Yn(t,i){const s=this.lv;return null===s?null:Mi(s,t,i)}Rv(t,i){a("left"===i?this.Xp:this.Zp).Op(Ji({width:t,height:this.pp.height}))}Tf(){return this.pp}Op(t){Qi(this.pp,t)||(this.pp=t,this.Mp=!0,this.Tp.resizeCanvasElement(t),this.Rp.resizeCanvasElement(t),this.Mp=!1,this._v.style.width=t.width+"px",this._v.style.height=t.height+"px")}Dv(){const t=a(this.lv);t.bo(t.xo()),t.bo(t.So());for(const i of t.ba())if(t.Un(i)){const s=i.Wt();null!==s&&t.bo(s),i.Ns()}for(const i of t.Oo())i.Ns()}Rf(){return this.Tp.bitmapSize}Df(t,i,s){const n=this.Rf();n.width>0&&n.height>0&&t.drawImage(this.Tp.canvasElement,i,s)}Np(t){if(0===t)return;if(null===this.lv)return;t>1&&this.Dv(),null!==this.Xp&&this.Xp.Np(t),null!==this.Zp&&this.Zp.Np(t);const i={colorSpace:this.lp.N().layout.colorSpace};if(1!==t){this.Tp.applySuggestedBitmapSize();const t=es(this.Tp,i);null!==t&&(t.useBitmapCoordinateSpace((t=>{this.Fp(t)})),this.lv&&(this.Bv(t,Rs),this.Ev(t),this.Bv(t,Ds),this.Bv(t,Bs)))}this.Rp.applySuggestedBitmapSize();const s=es(this.Rp,i);null!==s&&(s.useBitmapCoordinateSpace((({context:t,bitmapSize:i})=>{t.clearRect(0,0,i.width,i.height)})),this.Iv(s),this.Bv(s,Es),this.Bv(s,Bs))}Vv(){return this.Xp}Av(){return this.Zp}Up(t,i){this.Bv(t,i)}ov(){null!==this.lv&&this.lv.Ao().u(this),this.lv=null}Mv(t){this.bv(this.tv,t)}bv(t,i){const s=i.localX,n=i.localY;t.v()&&t.p(this.ts().Vt().q_(s),{x:s,y:n},i)}Fp({context:t,bitmapSize:i}){const{width:s,height:n}=i,e=this.ts(),r=e.$(),h=e.Mc();r===h?I(t,0,0,s,n,h):z(t,0,0,s,n,r,h)}Ev(t){const i=a(this.lv),s=i.zo().lr().Tt(i);null!==s&&s.nt(t,!1)}Iv(t){this.zv(t,Ds,Cs,this.ts().$u())}Bv(t,i){const s=a(this.lv),n=s.Dt(),e=s.Oo();for(const s of e)this.zv(t,i,Ss,s);for(const s of n)this.zv(t,i,Ss,s);for(const s of e)this.zv(t,i,Cs,s);for(const s of n)this.zv(t,i,Cs,s)}zv(t,i,s,n){const e=a(this.lv),r=e.Qt().Wu(),h=null!==r&&r.Lo===n,l=null!==r&&h&&void 0!==r.No?r.No.Xn:void 0;ys(i,(i=>s(i,t,h,l)),n,e)}pv(){if(null===this.lv)return;const t=this.lp,i=this.lv.xo().N().visible,s=this.lv.So().N().visible;i||null===this.Xp||(this.uv.removeChild(this.Xp.kf()),this.Xp.m(),this.Xp=null),s||null===this.Zp||(this.cv.removeChild(this.Zp.kf()),this.Zp.m(),this.Zp=null);const n=t.Qt()._c();i&&null===this.Xp&&(this.Xp=new Ts(this,t.N(),n,"left"),this.uv.appendChild(this.Xp.kf())),s&&null===this.Zp&&(this.Zp=new Ts(this,t.N(),n,"right"),this.cv.appendChild(this.Zp.kf()))}Ov(t){return t.uf&&this.nv||null!==this.ev}Lv(t){return Math.max(0,Math.min(t,this.pp.width-1))}Nv(t){return Math.max(0,Math.min(t,this.pp.height-1))}wv(t,i,s){this.ts().hc(this.Lv(t),this.Nv(i),s,a(this.lv))}yv(){this.ts().lc()}Tv(){this.rv&&(this.ev=null,this.yv())}Cv(t,i,s){this.ev=t,this.rv=!1,this.wv(i.x,i.y,s);const n=this.ts().$u();this.hv={x:n.si(),y:n.ni()}}ts(){return this.lp.Qt()}Sv(t){if(!this.Qp)return;const i=this.ts(),s=this.Lf();if(i.Ro(s,s.ks()),this.Jp=null,this.Qp=!1,i.nc(),null!==this.av){const t=performance.now(),s=i.Vt();this.av.le(s.Q_(),t),this.av.ou(t)||i._n(this.av)}}mv(){this.ev=null}gv(){if(!this.lv)return;if(this.ts().hn(),document.activeElement!==document.body&&document.activeElement!==document.documentElement)a(document.activeElement).blur();else{const t=document.getSelection();null!==t&&t.removeAllRanges()}!this.lv.ks().Ki()&&this.ts().Vt().Ki()}xv(t){if(null===this.lv)return;const i=this.ts(),s=i.Vt();if(s.Ki())return;const n=this.lp.N(),e=n.handleScroll,r=n.kineticScroll;if((!e.pressedMouseMove||t.uf)&&(!e.horzTouchDrag&&!e.vertTouchDrag||!t.uf))return;const h=this.lv.ks(),a=performance.now();if(null!==this.Jp||this.Ov(t)||(this.Jp={x:t.clientX,y:t.clientY,Ac:a,Wv:t.localX,Fv:t.localY}),null!==this.Jp&&!this.Qp&&(this.Jp.x!==t.clientX||this.Jp.y!==t.clientY)){if(t.uf&&r.touch||!t.uf&&r.mouse){const t=s.G_();this.av=new gs(.2/t,7/t,.997,15/t),this.av.sp(s.Q_(),this.Jp.Ac)}else this.av=null;h.Ki()||i.ko(this.lv,h,t.localY),i.tc(t.localX),this.Qp=!0}this.Qp&&(h.Ki()||i.To(this.lv,h,t.localY),i.sc(t.localX),null!==this.av&&this.av.sp(s.Q_(),a))}}class Vs{constructor(t,i,s,n,e){this.St=!0,this.pp=Ji({width:0,height:0}),this.bp=()=>this.Np(3),this.Cp="left"===t,this.Eu=s._c,this.ys=i,this.Hv=n,this.Uv=e,this.Cf=document.createElement("div"),this.Cf.style.width="25px",this.Cf.style.height="100%",this.Cf.style.overflow="hidden",this.Tp=bs(this.Cf,Ji({width:16,height:16})),this.Tp.subscribeSuggestedBitmapSizeChanged(this.bp)}m(){this.Tp.unsubscribeSuggestedBitmapSizeChanged(this.bp),xs(this.Tp.canvasElement),this.Tp.dispose()}kf(){return this.Cf}Tf(){return this.pp}Op(t){Qi(this.pp,t)||(this.pp=t,this.Tp.resizeCanvasElement(t),this.Cf.style.width=`${t.width}px`,this.Cf.style.height=`${t.height}px`,this.St=!0)}Np(t){if(t<3&&!this.St)return;if(0===this.pp.width||0===this.pp.height)return;this.St=!1,this.Tp.applySuggestedBitmapSize();const i=es(this.Tp,{colorSpace:this.ys.layout.colorSpace});null!==i&&i.useBitmapCoordinateSpace((t=>{this.Fp(t),this.Hp(t)}))}Rf(){return this.Tp.bitmapSize}Df(t,i,s){const n=this.Rf();n.width>0&&n.height>0&&t.drawImage(this.Tp.canvasElement,i,s)}Hp({context:t,bitmapSize:i,horizontalPixelRatio:s,verticalPixelRatio:n}){if(!this.Hv())return;t.fillStyle=this.ys.timeScale.borderColor;const e=Math.floor(this.Eu.N().S*s),r=Math.floor(this.Eu.N().S*n),h=this.Cp?i.width-e:0;t.fillRect(h,0,e,r)}Fp({context:t,bitmapSize:i}){I(t,0,0,i.width,i.height,this.Uv())}}function As(t){return i=>i.ia?.(t)??[]}const zs=As("normal"),Os=As("top"),Ls=As("bottom");class Ns{constructor(t,i){this.$v=null,this.jv=null,this.M=null,this.qv=!1,this.pp=Ji({width:0,height:0}),this.Yv=new o,this.mp=new tt(5),this.Mp=!1,this.bp=()=>{this.Mp||this.lp.Qt().ar()},this.Sp=()=>{this.Mp||this.lp.Qt().ar()},this.lp=t,this.$o=i,this.ys=t.N().layout,this.ep=document.createElement("tr"),this.Kv=document.createElement("td"),this.Kv.style.padding="0",this.Xv=document.createElement("td"),this.Xv.style.padding="0",this.Cf=document.createElement("td"),this.Cf.style.height="25px",this.Cf.style.padding="0",this.Zv=document.createElement("div"),this.Zv.style.width="100%",this.Zv.style.height="100%",this.Zv.style.position="relative",this.Zv.style.overflow="hidden",this.Cf.appendChild(this.Zv),this.Tp=bs(this.Zv,Ji({width:16,height:16})),this.Tp.subscribeSuggestedBitmapSizeChanged(this.bp);const s=this.Tp.canvasElement;s.style.position="absolute",s.style.zIndex="1",s.style.left="0",s.style.top="0",this.Rp=bs(this.Zv,Ji({width:16,height:16})),this.Rp.subscribeSuggestedBitmapSizeChanged(this.Sp);const n=this.Rp.canvasElement;n.style.position="absolute",n.style.zIndex="2",n.style.left="0",n.style.top="0",this.ep.appendChild(this.Kv),this.ep.appendChild(this.Cf),this.ep.appendChild(this.Xv),this.Gv(),this.lp.Qt().do().i(this.Gv.bind(this),this),this.vf=new _s(this.Rp.canvasElement,this,{Ld:()=>!0,Nd:()=>!this.lp.N().handleScroll.horzTouchDrag})}m(){this.vf.m(),null!==this.$v&&this.$v.m(),null!==this.jv&&this.jv.m(),this.Rp.unsubscribeSuggestedBitmapSizeChanged(this.Sp),xs(this.Rp.canvasElement),this.Rp.dispose(),this.Tp.unsubscribeSuggestedBitmapSizeChanged(this.bp),xs(this.Tp.canvasElement),this.Tp.dispose()}kf(){return this.ep}Jv(){return this.$v}Qv(){return this.jv}Jd(t){if(this.qv)return;this.qv=!0;const i=this.lp.Qt();!i.Vt().Ki()&&this.lp.N().handleScale.axisPressedMouseMove.time&&i.Gu(t.localX)}Zd(t){this.Jd(t)}Qd(){const t=this.lp.Qt();!t.Vt().Ki()&&this.qv&&(this.qv=!1,this.lp.N().handleScale.axisPressedMouseMove.time&&t.rc())}Hd(t){const i=this.lp.Qt();!i.Vt().Ki()&&this.lp.N().handleScale.axisPressedMouseMove.time&&i.ec(t.localX)}Wd(t){this.Hd(t)}qd(){this.qv=!1;const t=this.lp.Qt();t.Vt().Ki()&&!this.lp.N().handleScale.axisPressedMouseMove.time||t.rc()}$d(){this.qd()}Pd(){this.lp.N().handleScale.axisDoubleClickReset.time&&this.lp.Qt().cn()}xd(){this.Pd()}Id(){this.lp.Qt().N().handleScale.axisPressedMouseMove.time&&this.Yp(1)}lf(){this.Yp(0)}Tf(){return this.pp}tm(){return this.Yv}im(t,i,s){Qi(this.pp,t)||(this.pp=t,this.Mp=!0,this.Tp.resizeCanvasElement(t),this.Rp.resizeCanvasElement(t),this.Mp=!1,this.Cf.style.width=`${t.width}px`,this.Cf.style.height=`${t.height}px`,this.Yv.p(t)),null!==this.$v&&this.$v.Op(Ji({width:i,height:t.height})),null!==this.jv&&this.jv.Op(Ji({width:s,height:t.height}))}sm(){const t=this.nm();return Math.ceil(t.S+t.C+t.P+t.A+t.B+t.rm)}Pt(){this.lp.Qt().Vt().Ba()}Rf(){return this.Tp.bitmapSize}Df(t,i,s){const n=this.Rf();n.width>0&&n.height>0&&t.drawImage(this.Tp.canvasElement,i,s)}Np(t){if(0===t)return;const i={colorSpace:this.ys.colorSpace};if(1!==t){this.Tp.applySuggestedBitmapSize();const s=es(this.Tp,i);null!==s&&(s.useBitmapCoordinateSpace((t=>{this.Fp(t),this.Hp(t),this.hm(s,Ls)})),this.$p(s),this.hm(s,zs)),null!==this.$v&&this.$v.Np(t),null!==this.jv&&this.jv.Np(t)}this.Rp.applySuggestedBitmapSize();const s=es(this.Rp,i);null!==s&&(s.useBitmapCoordinateSpace((({context:t,bitmapSize:i})=>{t.clearRect(0,0,i.width,i.height)})),this.am([...this.lp.Qt().Ys(),this.lp.Qt().$u()],s),this.hm(s,Os))}hm(t,i){const s=this.lp.Qt().Ys();for(const n of s)ys(i,(i=>Ss(i,t,!1,void 0)),n,void 0);for(const n of s)ys(i,(i=>Cs(i,t,!1,void 0)),n,void 0)}Fp({context:t,bitmapSize:i}){I(t,0,0,i.width,i.height,this.lp.Qt().Mc())}Hp({context:t,bitmapSize:i,verticalPixelRatio:s}){if(this.lp.N().timeScale.borderVisible){t.fillStyle=this.lm();const n=Math.max(1,Math.floor(this.nm().S*s));t.fillRect(0,0,i.width,n)}}$p(t){const i=this.lp.Qt().Vt(),s=i.Ba();if(!s||0===s.length)return;const n=this.$o.maxTickMarkWeight(s),e=this.nm(),r=i.N();r.borderVisible&&r.ticksVisible&&t.useBitmapCoordinateSpace((({context:t,horizontalPixelRatio:i,verticalPixelRatio:n})=>{t.strokeStyle=this.lm(),t.fillStyle=this.lm();const r=Math.max(1,Math.floor(i)),h=Math.floor(.5*i);t.beginPath();const a=Math.round(e.C*n);for(let n=s.length;n--;){const e=Math.round(s[n].coord*i);t.rect(e-h,0,r,a)}t.fill()})),t.useMediaCoordinateSpace((({context:t})=>{const i=e.S+e.C+e.A+e.P/2;t.textAlign="center",t.textBaseline="middle",t.fillStyle=this.H(),t.font=this.Ap();for(const e of s)if(e.weight=n){const s=e.needAlignCoordinate?this.om(t,e.coord,e.label):e.coord;t.fillText(e.label,s,i)}}))}om(t,i,s){const n=this.mp.Bi(t,s),e=n/2,r=Math.floor(i-e)+.5;return r<0?i+=Math.abs(0-r):r+n>this.pp.width&&(i-=Math.abs(this.pp.width-(r+n))),i}am(t,i){const s=this.nm();for(const n of t)for(const t of n.cs())t.Tt().nt(i,s)}lm(){return this.lp.N().timeScale.borderColor}H(){return this.ys.textColor}W(){return this.ys.fontSize}Ap(){return g(this.W(),this.ys.fontFamily)}_m(){return g(this.W(),this.ys.fontFamily,"bold")}nm(){null===this.M&&(this.M={S:1,O:NaN,A:NaN,B:NaN,Ji:NaN,C:5,P:NaN,k:"",Gi:new tt,rm:0});const t=this.M,i=this.Ap();if(t.k!==i){const s=this.W();t.P=s,t.k=i,t.A=3*s/12,t.B=3*s/12,t.Ji=9*s/12,t.O=0,t.rm=4*s/12,t.Gi.En()}return this.M}Yp(t){this.Cf.style.cursor=1===t?"ew-resize":"default"}Gv(){const t=this.lp.Qt(),i=t.N();i.leftPriceScale.visible||null===this.$v||(this.Kv.removeChild(this.$v.kf()),this.$v.m(),this.$v=null),i.rightPriceScale.visible||null===this.jv||(this.Xv.removeChild(this.jv.kf()),this.jv.m(),this.jv=null);const s={_c:this.lp.Qt()._c()},n=()=>i.leftPriceScale.borderVisible&&t.Vt().N().borderVisible,e=()=>t.Mc();i.leftPriceScale.visible&&null===this.$v&&(this.$v=new Vs("left",i,s,n,e),this.Kv.appendChild(this.$v.kf())),i.rightPriceScale.visible&&null===this.jv&&(this.jv=new Vs("right",i,s,n,e),this.Xv.appendChild(this.jv.kf()))}}const Ws=!!rs&&!!navigator.userAgentData&&navigator.userAgentData.brands.some((t=>t.brand.includes("Chromium")))&&!!rs&&(navigator?.userAgentData?.platform?"Windows"===navigator.userAgentData.platform:navigator.userAgent.toLowerCase().indexOf("win")>=0);class Fs{constructor(t,i,s){var n;this.um=[],this.dm=[],this.fm=0,this.Ya=0,this.no=0,this.pm=0,this.vm=0,this.wm=null,this.gm=!1,this.tv=new o,this.iv=new o,this.Ru=new o,this.Mm=null,this.bm=null,this.ap=t,this.ys=i,this.$o=s,this.ep=document.createElement("div"),this.ep.classList.add("tv-lightweight-charts"),this.ep.style.overflow="hidden",this.ep.style.direction="ltr",this.ep.style.width="100%",this.ep.style.height="100%",(n=this.ep).style.userSelect="none",n.style.webkitUserSelect="none",n.style.msUserSelect="none",n.style.MozUserSelect="none",n.style.webkitTapHighlightColor="transparent",this.xm=document.createElement("table"),this.xm.setAttribute("cellspacing","0"),this.ep.appendChild(this.xm),this.Sm=this.Cm.bind(this),Hs(this.ys)&&this.ym(!0),this.ts=new Ii(this.Bu.bind(this),this.ys,s),this.Qt().ju().i(this.Pm.bind(this),this),this.km=new Ns(this,this.$o),this.xm.appendChild(this.km.kf());const e=i.autoSize&&this.Tm();let r=this.ys.width,h=this.ys.height;if(e||0===r||0===h){const i=t.getBoundingClientRect();r=r||i.width,h=h||i.height}this.Rm(r,h),this.Dm(),t.appendChild(this.ep),this.Bm(),this.ts.Vt().du().i(this.ts.Ih.bind(this.ts),this),this.ts.do().i(this.ts.Ih.bind(this.ts),this)}Qt(){return this.ts}N(){return this.ys}bf(){return this.um}Em(){return this.km}m(){this.ym(!1),0!==this.fm&&window.cancelAnimationFrame(this.fm),this.ts.ju().u(this),this.ts.Vt().du().u(this),this.ts.do().u(this),this.ts.m();for(const t of this.um)this.xm.removeChild(t.kf()),t.Pv().u(this),t.kv().u(this),t.m();this.um=[];for(const t of this.dm)this.Im(t);this.dm=[],a(this.km).m(),null!==this.ep.parentElement&&this.ep.parentElement.removeChild(this.ep),this.Ru.m(),this.tv.m(),this.iv.m(),this.Vm()}Rm(t,i,s=!1){if(this.Ya===i&&this.no===t)return;const n=function(t){const i=Math.floor(t.width),s=Math.floor(t.height);return Ji({width:i-i%2,height:s-s%2})}(Ji({width:t,height:i}));this.Ya=n.height,this.no=n.width;const e=this.Ya+"px",r=this.no+"px";a(this.ep).style.height=e,a(this.ep).style.width=r,this.xm.style.height=e,this.xm.style.width=r,s?this.Am(Y.gn(),performance.now()):this.ts.Ih()}Np(t){void 0===t&&(t=Y.gn());for(let i=0;i{t.Pt()}))}Om(t){(void 0!==t.autoSize||!this.Mm||void 0===t.width&&void 0===t.height)&&(t.autoSize&&!this.Mm&&this.Tm(),!1===t.autoSize&&null!==this.Mm&&this.Vm(),t.autoSize||void 0===t.width&&void 0===t.height||this.Rm(t.width||this.no,t.height||this.Ya))}Nm(t){let i=0,s=0;const n=this.um[0],e=(i,s)=>{let n=0;for(let e=0;e{a("left"===i?this.km.Jv():this.km.Qv()).Df(a(t),s,n)};if(this.ys.timeScale.visible){const i=this.km.Rf();if(null!==t){let e=0;this.Fm()&&(r("left",e,s),e=a(n.Vv()).Rf().width),this.km.Df(t,e,s),e+=i.width,this.Hm()&&r("right",e,s)}s+=i.height}return Ji({width:i,height:s})}Ym(){let t=0,i=0,s=0;for(const n of this.um)this.Fm()&&(i=Math.max(i,a(n.Vv()).Vp(),this.ys.leftPriceScale.minimumWidth)),this.Hm()&&(s=Math.max(s,a(n.Av()).Vp(),this.ys.rightPriceScale.minimumWidth)),t+=n.fo();i=ls(i),s=ls(s);const n=this.no,e=this.Ya,r=Math.max(n-i-s,0),h=1*this.dm.length,l=this.ys.timeScale.visible;let o=l?Math.max(this.km.sm(),this.ys.timeScale.minimumHeight):0;var _;o=(_=o)+_%2;const u=h+o,c=e{t.vv()})),3===this.wm?.nn()&&(this.wm.vn(t),this.Xm(),this.Zm(this.wm),this.Gm(this.wm,i),t=this.wm,this.wm=null)),this.Np(t)}Gm(t,i){for(const s of t.pn())this.mn(s,i)}Zm(t){const i=this.ts.$s();for(let s=0;s{if(this.gm=!1,this.fm=0,null!==this.wm){const i=this.wm;this.wm=null,this.Am(i,t);for(const s of i.pn())if(5===s.an&&!s.Ft.ou(t)){this.Qt()._n(s.Ft);break}}})))}Xm(){this.Dm()}Im(t){this.xm.removeChild(t.kf()),t.m()}Dm(){const t=this.ts.$s(),i=t.length,s=this.um.length;for(let t=i;t0){const t=new vs(this,n-1,n);this.dm.push(t),this.xm.insertBefore(t.kf(),this.km.kf())}this.xm.insertBefore(i.kf(),this.km.kf())}for(let s=0;s{const s=i.Xs().Wr(t);null!==s&&e.set(i,s)}))}let r;if(null!==t){const i=this.ts.Vt().ss(t)?.originalTime;void 0!==i&&(r=i)}const h=this.Qt().Wu(),a=null!==h&&h.Lo instanceof Ht?h.Lo:void 0,l=null!==h&&void 0!==h.No?h.No.Kn:void 0,o=this.iw(n);return{sw:r,Re:t??void 0,nw:i??void 0,ew:-1!==o?o:void 0,rw:a,hw:e,aw:l,lw:s??void 0}}iw(t){let i=-1;if(t)i=this.um.indexOf(t);else{const t=this.Qt().$u().Us();null!==t&&(i=this.Qt().$s().indexOf(t))}return i}Jm(t,i,s,n){this.tv.p((()=>this.tw(i,s,n,t)))}Qm(t,i,s,n){this.iv.p((()=>this.tw(i,s,n,t)))}Pm(t,i,s){this.$m(this.Qt().Wu()?.Fo??null),this.Ru.p((()=>this.tw(t,i,s)))}Bm(){const t=this.ys.timeScale.visible?"":"none";this.km.kf().style.display=t}Fm(){return this.um[0].Lf().xo().N().visible}Hm(){return this.um[0].Lf().So().N().visible}Tm(){return"ResizeObserver"in window&&(this.Mm=new ResizeObserver((t=>{const i=t[t.length-1];i&&this.Rm(i.contentRect.width,i.contentRect.height)})),this.Mm.observe(this.ap,{box:"border-box"}),!0)}Vm(){null!==this.Mm&&this.Mm.disconnect(),this.Mm=null}}function Hs(t){return Boolean(t.handleScroll.mouseWheel||t.handleScale.mouseWheel)}function Us(t){return void 0===t.open&&void 0===t.value}function $s(t){return function(t){return void 0!==t.open}(t)||function(t){return void 0!==t.value}(t)}function js(t,i,s,n){const e=s.value,r={Re:i,wt:t,Ft:[e,e,e,e],sw:n};return void 0!==s.color&&(r.R=s.color),r}function qs(t,i,s,n){const e=s.value,r={Re:i,wt:t,Ft:[e,e,e,e],sw:n};return void 0!==s.lineColor&&(r.vt=s.lineColor),void 0!==s.topColor&&(r.mr=s.topColor),void 0!==s.bottomColor&&(r.wr=s.bottomColor),r}function Ys(t,i,s,n){const e=s.value,r={Re:i,wt:t,Ft:[e,e,e,e],sw:n};return void 0!==s.topLineColor&&(r.gr=s.topLineColor),void 0!==s.bottomLineColor&&(r.Mr=s.bottomLineColor),void 0!==s.topFillColor1&&(r.br=s.topFillColor1),void 0!==s.topFillColor2&&(r.Sr=s.topFillColor2),void 0!==s.bottomFillColor1&&(r.Cr=s.bottomFillColor1),void 0!==s.bottomFillColor2&&(r.yr=s.bottomFillColor2),r}function Ks(t,i,s,n){const e={Re:i,wt:t,Ft:[s.open,s.high,s.low,s.close],sw:n};return void 0!==s.color&&(e.R=s.color),e}function Xs(t,i,s,n){const e={Re:i,wt:t,Ft:[s.open,s.high,s.low,s.close],sw:n};return void 0!==s.color&&(e.R=s.color),void 0!==s.borderColor&&(e.Ht=s.borderColor),void 0!==s.wickColor&&(e.vr=s.wickColor),e}function Zs(t,i,s,n,e){const r=h(e)(s),a=Math.max(...r),l=Math.min(...r),o=r[r.length-1],_=[o,a,l,o],{time:u,color:c,...d}=s;return{Re:i,wt:t,Ft:_,sw:n,se:d,R:c}}function Gs(t){return void 0!==t.Ft}function Js(t,i){return void 0!==i.customValues&&(t.ow=i.customValues),t}function Qs(t){return(i,s,n,e,r,h)=>function(t,i){return i?i(t):Us(t)}(n,h)?Js({wt:i,Re:s,sw:e},n):Js(t(i,s,n,e,r),n)}function tn(t){return{Candlestick:Qs(Xs),Bar:Qs(Ks),Area:Qs(qs),Baseline:Qs(Ys),Histogram:Qs(js),Line:Qs(js),Custom:Qs(Zs)}[t]}function sn(t){return{Re:0,_w:new Map,Hh:t}}function nn(t,i){if(void 0!==t&&0!==t.length)return{uw:i.key(t[0].wt),cw:i.key(t[t.length-1].wt)}}function en(t){let i;return t.forEach((t=>{void 0===i&&(i=t.sw)})),h(i)}class rn{constructor(t){this.dw=new Map,this.fw=new Map,this.pw=new Map,this.mw=[],this.$o=t}m(){this.dw.clear(),this.fw.clear(),this.pw.clear(),this.mw=[]}ww(t,i){let s=0!==this.dw.size,n=!1;const e=this.fw.get(t);if(void 0!==e)if(1===this.fw.size)s=!1,n=!0,this.dw.clear();else for(const i of this.mw)i.pointData._w.delete(t)&&(n=!0);let r=[];if(0!==i.length){const s=i.map((t=>t.time)),e=this.$o.createConverterToInternalObj(i),h=tn(t.Rr()),a=t.da(),l=t.pa();r=i.map(((i,r)=>{const o=e(i.time),_=this.$o.key(o);let u=this.dw.get(_);void 0===u&&(u=sn(o),this.dw.set(_,u),n=!0);const c=h(o,u.Re,i,s[r],a,l);return u._w.set(t,c),c}))}s&&this.gw(),this.Mw(t,r);let h=-1;if(n){const t=[];this.dw.forEach((i=>{t.push({timeWeight:0,time:i.Hh,pointData:i,originalTime:en(i._w)})})),t.sort(((t,i)=>this.$o.key(t.time)-this.$o.key(i.time))),h=this.bw(t)}return this.xw(t,h,function(t,i,s){const n=nn(t,s),e=nn(i,s);if(void 0!==n&&void 0!==e)return{Sw:!1,zh:n.cw>=e.cw&&n.uw>=e.uw}}(this.fw.get(t),e,this.$o))}dc(t){return this.ww(t,[])}Cw(t,i,s){const n=i;!function(t){void 0===t.sw&&(t.sw=t.time)}(n),this.$o.preprocessData(i);const e=this.$o.createConverterToInternalObj([i])(i.time),r=this.pw.get(t);if(!s&&void 0!==r&&this.$o.key(e)this.$o.key(t.time)this.$o.key(n.wt)?Gs(i)&&s.push(i):Gs(i)?s[s.length-1]=i:s.splice(-1,1),this.pw.set(t,i.wt)}yw(t,i,s){const n=this.fw.get(t);if(void 0===n)return;const e=bt(n,s,((t,i)=>t.Re{0!==i.length&&(t=Math.max(t,i[i.length-1].Re))})),t}xw(t,i,s){const n={wo:new Map,Vt:{U_:this.kw()}};if(-1!==i)this.fw.forEach(((i,e)=>{n.wo.set(e,{se:i,Tw:e===t?s:void 0})})),this.fw.has(t)||n.wo.set(t,{se:[],Tw:s}),n.Vt.Rw=this.mw,n.Vt.Dw=i;else{const i=this.fw.get(t);n.wo.set(t,{se:i||[],Tw:s})}return n}}function hn(t,i){t.Re=i,t._w.forEach((t=>{t.Re=i}))}function an(t,i){return t.wt0&&r=n&&(a=r-1),h>0&&h({...t,...this.Jn.Rh().Dr(t.wt)})))}Ww(){this.Aw=null}Ow(){this.Ew&&(this.Fw(),this.Ew=!1),this.Iw&&(this.Nw(),this.Iw=!1),this.Bw&&(this.Hw(),this.Bw=!1)}Hw(){const t=this.Jn.Wt(),i=this.Qn.Vt();if(this.Ww(),i.Ki()||t.Ki())return;const s=i.ye();if(null===s)return;if(0===this.Jn.Xs().zr())return;const n=this.Jn.zt();null!==n&&(this.Aw=on(this.Vw,s,this.zw),this.Uw(t,i,n.Ft),this.$w())}}class un{constructor(t,i){this.jw=t,this.qi=i}nt(t,i,s){this.jw.draw(t,this.qi,i,s)}}class cn extends _n{constructor(t,i,s){super(t,i,!1),this.sh=s,this.Lw=new un(this.sh.renderer(),(i=>{const s=t.zt();return null===s?null:t.Wt().Nt(i,s.Ft)}))}fa(t){return this.sh.priceValueBuilder(t)}va(t){return this.sh.isWhitespace(t)}Fw(){const t=this.Jn.Rh();this.Vw=this.Jn.Xs().Hr().map((i=>({wt:i.Re,_t:NaN,...t.Dr(i.Re),qw:i.se})))}Uw(t,i){i.j_(this.Vw,m(this.Aw))}$w(){this.sh.update({bars:this.Vw.map(dn),barSpacing:this.Qn.Vt().G_(),visibleRange:this.Aw},this.Jn.N())}}function dn(t){return{x:t._t,time:t.wt,originalData:t.qw,barColor:t.cr}}const fn={color:"#2196f3"},pn=(t,i,s)=>{const n=l(s);return new cn(t,i,n)};function vn(t){const i={value:t.Ft[3],time:t.sw};return void 0!==t.ow&&(i.customValues=t.ow),i}function mn(t){const i=vn(t);return void 0!==t.R&&(i.color=t.R),i}function wn(t){const i=vn(t);return void 0!==t.vt&&(i.lineColor=t.vt),void 0!==t.mr&&(i.topColor=t.mr),void 0!==t.wr&&(i.bottomColor=t.wr),i}function gn(t){const i=vn(t);return void 0!==t.gr&&(i.topLineColor=t.gr),void 0!==t.Mr&&(i.bottomLineColor=t.Mr),void 0!==t.br&&(i.topFillColor1=t.br),void 0!==t.Sr&&(i.topFillColor2=t.Sr),void 0!==t.Cr&&(i.bottomFillColor1=t.Cr),void 0!==t.yr&&(i.bottomFillColor2=t.yr),i}function Mn(t){const i={open:t.Ft[0],high:t.Ft[1],low:t.Ft[2],close:t.Ft[3],time:t.sw};return void 0!==t.ow&&(i.customValues=t.ow),i}function bn(t){const i=Mn(t);return void 0!==t.R&&(i.color=t.R),i}function xn(t){const i=Mn(t),{R:s,Ht:n,vr:e}=t;return void 0!==s&&(i.color=s),void 0!==n&&(i.borderColor=n),void 0!==e&&(i.wickColor=e),i}function Sn(t){return{Area:wn,Line:mn,Baseline:gn,Histogram:mn,Bar:bn,Candlestick:xn,Custom:Cn}[t]}function Cn(t){const i=t.sw;return{...t.se,time:i}}const yn={vertLine:{color:"#9598A1",width:1,style:3,visible:!0,labelVisible:!0,labelBackgroundColor:"#131722"},horzLine:{color:"#9598A1",width:1,style:3,visible:!0,labelVisible:!0,labelBackgroundColor:"#131722"},mode:1},Pn={vertLines:{color:"#D6DCDE",style:0,visible:!0},horzLines:{color:"#D6DCDE",style:0,visible:!0}},kn={background:{type:"solid",color:"#FFFFFF"},textColor:"#191919",fontSize:12,fontFamily:w,panes:{enableResize:!0,separatorColor:"#E0E3EB",separatorHoverColor:"rgba(178, 181, 189, 0.2)"},attributionLogo:!0,colorSpace:"srgb",colorParsers:[]},Tn={autoScale:!0,mode:0,invertScale:!1,alignLabels:!0,borderVisible:!0,borderColor:"#2B2B43",entireTextOnly:!1,visible:!1,ticksVisible:!1,scaleMargins:{bottom:.1,top:.2},minimumWidth:0},Rn={rightOffset:0,barSpacing:6,minBarSpacing:.5,maxBarSpacing:0,fixLeftEdge:!1,fixRightEdge:!1,lockVisibleTimeRangeOnResize:!1,rightBarStaysOnScroll:!1,borderVisible:!0,borderColor:"#2B2B43",visible:!0,timeVisible:!1,secondsVisible:!0,shiftVisibleRangeOnNewBar:!0,allowShiftVisibleRangeOnWhitespaceReplacement:!1,ticksVisible:!1,uniformDistribution:!1,minimumHeight:0,allowBoldLabels:!0,ignoreWhitespaceIndices:!1};function Dn(){return{width:0,height:0,autoSize:!1,layout:kn,crosshair:yn,grid:Pn,overlayPriceScales:{...Tn},leftPriceScale:{...Tn,visible:!1},rightPriceScale:{...Tn,visible:!0},timeScale:Rn,localization:{locale:rs?navigator.language:"",dateFormat:"dd MMM 'yy"},handleScroll:{mouseWheel:!0,pressedMouseMove:!0,horzTouchDrag:!0,vertTouchDrag:!0},handleScale:{axisPressedMouseMove:{time:!0,price:!0},axisDoubleClickReset:{time:!0,price:!0},mouseWheel:!0,pinch:!0},kineticScroll:{mouse:!1,touch:!0},trackingMode:{exitMode:1}}}class Bn{constructor(t,i,s){this.gf=t,this.Yw=i,this.Kw=s??0}applyOptions(t){this.gf.Qt().Hu(this.Yw,t,this.Kw)}options(){return this.qi().N()}width(){return q(this.Yw)?this.gf.Wm(this.Yw):0}qi(){return a(this.gf.Qt().Uu(this.Yw,this.Kw)).Wt}}class En{constructor(t,i,s,n){this.gf=t,this.yt=s,this.Xw=i,this.Zw=n}getHeight(){return this.yt.$t()}setHeight(t){const i=this.gf.Qt(),s=i.xc(this.yt);i.Ku(s,t)}paneIndex(){return this.gf.Qt().xc(this.yt)}moveTo(t){const i=this.paneIndex();i!==t&&(r(t>=0&&tthis.Xw(t)))??[]}getHTMLElement(){return this.gf.bf()[this.paneIndex()].kf()}attachPrimitive(t){this.yt.ua(t),t.attached&&t.attached({chart:this.Zw,requestUpdate:()=>this.yt.Qt().Ih()})}detachPrimitive(t){this.yt.ca(t)}priceScale(t){if(null===this.yt.co(t))throw new Error(`Cannot find price scale with id: ${t}`);return new Bn(this.gf,t,this.paneIndex())}}const In={color:"#FF0000",price:0,lineStyle:2,lineWidth:1,lineVisible:!0,axisLabelVisible:!0,title:"",axisLabelColor:"",axisLabelTextColor:""};class Vn{constructor(t){this.ir=t}applyOptions(t){this.ir.hr(t)}options(){return this.ir.N()}Gw(){return this.ir}}class An{constructor(t,i,s,n,e,r){this.Jw=new o,this.Jn=t,this.Qw=i,this.tg=s,this.$o=e,this.Zw=n,this.ig=r}m(){this.Jw.m()}priceFormatter(){return this.Jn.ra()}priceToCoordinate(t){const i=this.Jn.zt();return null===i?null:this.Jn.Wt().Nt(t,i.Ft)}coordinateToPrice(t){const i=this.Jn.zt();return null===i?null:this.Jn.Wt().Ts(t,i.Ft)}barsInLogicalRange(t){if(null===t)return null;const i=new yi(new xi(t.from,t.to)).a_(),s=this.Jn.Xs();if(s.Ki())return null;const n=s.Wr(i.Uh(),1),e=s.Wr(i.bi(),-1),r=a(s.Or()),h=a(s.Ks());if(null!==n&&null!==e&&n.Re>e.Re)return{barsBefore:t.from-r,barsAfter:h-t.to};const l={barsBefore:null===n||n.Re===r?t.from-r:n.Re-r,barsAfter:null===e||e.Re===h?h-t.to:h-e.Re};return null!==n&&null!==e&&(l.from=n.sw,l.to=e.sw),l}setData(t){this.$o,this.Jn.Rr(),this.Qw.sg(this.Jn,t),this.ng("full")}update(t,i=!1){this.Jn.Rr(),this.Qw.eg(this.Jn,t,i),this.ng("update")}dataByIndex(t,i){const s=this.Jn.Xs().Wr(t,i);if(null===s)return null;return Sn(this.seriesType())(s)}data(){const t=Sn(this.seriesType());return this.Jn.Xs().Hr().map((i=>t(i)))}subscribeDataChanged(t){this.Jw.i(t)}unsubscribeDataChanged(t){this.Jw._(t)}applyOptions(t){this.Jn.hr(t)}options(){return p(this.Jn.N())}priceScale(){return this.tg.priceScale(this.Jn.Wt().wa(),this.getPane().paneIndex())}createPriceLine(t){const i=_(p(In),t),s=this.Jn.Lh(i);return new Vn(s)}removePriceLine(t){this.Jn.Nh(t.Gw())}priceLines(){return this.Jn.Wh().map((t=>new Vn(t)))}seriesType(){return this.Jn.Rr()}attachPrimitive(t){this.Jn.ua(t),t.attached&&t.attached({chart:this.Zw,series:this,requestUpdate:()=>this.Jn.Qt().Ih(),horzScaleBehavior:this.$o})}detachPrimitive(t){this.Jn.ca(t),t.detached&&t.detached(),this.Jn.Qt().Ih()}getPane(){const t=this.Jn,i=a(this.Jn.Qt().Hn(t));return this.ig(i)}moveToPane(t){this.Jn.Qt().wc(this.Jn,t)}seriesOrder(){const t=this.Jn.Qt().Hn(this.Jn);return null===t?-1:t.wo().indexOf(this.Jn)}setSeriesOrder(t){const i=this.Jn.Qt().Hn(this.Jn);null!==i&&i.Vo(this.Jn,t)}ng(t){this.Jw.v()&&this.Jw.p(t)}}class zn{constructor(t,i,s){this.rg=new o,this.m_=new o,this.Yv=new o,this.ts=t,this.uh=t.Vt(),this.km=i,this.uh.uu().i(this.hg.bind(this)),this.uh.cu().i(this.ag.bind(this)),this.km.tm().i(this.lg.bind(this)),this.$o=s}m(){this.uh.uu().u(this),this.uh.cu().u(this),this.km.tm().u(this),this.rg.m(),this.m_.m(),this.Yv.m()}scrollPosition(){return this.uh.Q_()}scrollToPosition(t,i){i?this.uh.lu(t,1e3):this.ts.fn(t)}scrollToRealTime(){this.uh.au()}getVisibleRange(){const t=this.uh.z_();return null===t?null:{from:t.from.originalTime,to:t.to.originalTime}}setVisibleRange(t){const i={from:this.$o.convertHorzItemToInternal(t.from),to:this.$o.convertHorzItemToInternal(t.to)},s=this.uh.W_(i);this.ts.vc(s)}getVisibleLogicalRange(){const t=this.uh.A_();return null===t?null:{from:t.Uh(),to:t.bi()}}setVisibleLogicalRange(t){r(t.from<=t.to,"The from index cannot be after the to index."),this.ts.vc(t)}resetTimeScale(){this.ts.cn()}fitContent(){this.ts.pu()}logicalToCoordinate(t){const i=this.ts.Vt();return i.Ki()?null:i.jt(t)}coordinateToLogical(t){return this.uh.Ki()?null:this.uh.q_(t)}timeToIndex(t,i){const s=this.$o.convertHorzItemToInternal(t);return this.uh.E_(s,i)}timeToCoordinate(t){const i=this.timeToIndex(t,!1);return null===i?null:this.uh.jt(i)}coordinateToTime(t){const i=this.ts.Vt(),s=i.q_(t),n=i.ss(s);return null===n?null:n.originalTime}width(){return this.km.Tf().width}height(){return this.km.Tf().height}subscribeVisibleTimeRangeChange(t){this.rg.i(t)}unsubscribeVisibleTimeRangeChange(t){this.rg._(t)}subscribeVisibleLogicalRangeChange(t){this.m_.i(t)}unsubscribeVisibleLogicalRangeChange(t){this.m_._(t)}subscribeSizeChange(t){this.Yv.i(t)}unsubscribeSizeChange(t){this.Yv._(t)}applyOptions(t){this.uh.hr(t)}options(){return{...p(this.uh.N()),barSpacing:this.uh.G_()}}hg(){this.rg.v()&&this.rg.p(this.getVisibleRange())}ag(){this.m_.v()&&this.m_.p(this.getVisibleLogicalRange())}lg(t){this.Yv.p(t.width,t.height)}}function On(t){if(void 0===t||"custom"===t.type)return;const i=t;void 0!==i.minMove&&void 0===i.precision&&(i.precision=function(t){if(t>=1)return 0;let i=0;for(;i<8;i++){const s=Math.round(t);if(Math.abs(s-t)<1e-8)return i;t*=10}return i}(i.minMove))}function Ln(t){return function(t){if(f(t.handleScale)){const i=t.handleScale;t.handleScale={axisDoubleClickReset:{time:i,price:i},axisPressedMouseMove:{time:i,price:i},mouseWheel:i,pinch:i}}else if(void 0!==t.handleScale){const{axisPressedMouseMove:i,axisDoubleClickReset:s}=t.handleScale;f(i)&&(t.handleScale.axisPressedMouseMove={time:i,price:i}),f(s)&&(t.handleScale.axisDoubleClickReset={time:s,price:s})}const i=t.handleScroll;f(i)&&(t.handleScroll={horzTouchDrag:i,vertTouchDrag:i,mouseWheel:i,pressedMouseMove:i})}(t),t}class Nn{constructor(t,i,s){this.og=new Map,this._g=new Map,this.ug=new o,this.cg=new o,this.dg=new o,this.yu=new WeakMap,this.fg=new rn(i);const n=void 0===s?p(Dn()):_(p(Dn()),Ln(s));this.pg=i,this.gf=new Fs(t,n,i),this.gf.Pv().i((t=>{this.ug.v()&&this.ug.p(this.vg(t()))}),this),this.gf.kv().i((t=>{this.cg.v()&&this.cg.p(this.vg(t()))}),this),this.gf.ju().i((t=>{this.dg.v()&&this.dg.p(this.vg(t()))}),this);const e=this.gf.Qt();this.mg=new zn(e,this.gf.Em(),this.pg)}remove(){this.gf.Pv().u(this),this.gf.kv().u(this),this.gf.ju().u(this),this.mg.m(),this.gf.m(),this.og.clear(),this._g.clear(),this.ug.m(),this.cg.m(),this.dg.m(),this.fg.m()}resize(t,i,s){this.autoSizeActive()||this.gf.Rm(t,i,s)}addCustomSeries(t,i={},s=0){const n=(t=>({type:"Custom",isBuiltIn:!1,defaultOptions:{...fn,...t.defaultOptions()},wg:pn,gg:t}))(l(t));return this.Mg(n,i,s)}addSeries(t,i={},s=0){return this.Mg(t,i,s)}removeSeries(t){const i=h(this.og.get(t)),s=this.fg.dc(i);this.gf.Qt().dc(i),this.bg(s),this.og.delete(t),this._g.delete(i)}sg(t,i){this.bg(this.fg.ww(t,i))}eg(t,i,s){this.bg(this.fg.Cw(t,i,s))}subscribeClick(t){this.ug.i(t)}unsubscribeClick(t){this.ug._(t)}subscribeCrosshairMove(t){this.dg.i(t)}unsubscribeCrosshairMove(t){this.dg._(t)}subscribeDblClick(t){this.cg.i(t)}unsubscribeDblClick(t){this.cg._(t)}priceScale(t,i=0){return new Bn(this.gf,t,i)}timeScale(){return this.mg}applyOptions(t){this.gf.hr(Ln(t))}options(){return this.gf.N()}takeScreenshot(){return this.gf.Lm()}removePane(t){this.gf.Qt().Yu(t)}swapPanes(t,i){this.gf.Qt().Xu(t,i)}autoSizeActive(){return this.gf.Um()}chartElement(){return this.gf.Ef()}panes(){return this.gf.Qt().$s().map((t=>this.xg(t)))}paneSize(t=0){const i=this.gf.qm(t);return{height:i.height,width:i.width}}setCrosshairPosition(t,i,s){const n=this.og.get(s);if(void 0===n)return;const e=this.gf.Qt().Hn(n);null!==e&&this.gf.Qt().ac(t,i,e)}clearCrosshairPosition(){this.gf.Qt().lc(!0)}horzBehaviour(){return this.pg}Mg(i,s={},n=0){r(void 0!==i.wg),On(s.priceFormat),"Candlestick"===i.type&&function(t){void 0!==t.borderColor&&(t.borderUpColor=t.borderColor,t.borderDownColor=t.borderColor),void 0!==t.wickColor&&(t.wickUpColor=t.wickColor,t.wickDownColor=t.wickColor)}(s);const e=_(p(t),p(i.defaultOptions),s),h=i.wg,a=new Ht(this.gf.Qt(),i.type,e,h,i.gg);this.gf.Qt().uc(a,n);const l=new An(a,this,this,this,this.pg,(t=>this.xg(t)));return this.og.set(l,a),this._g.set(a,l),l}bg(t){const i=this.gf.Qt();i.oc(t.Vt.U_,t.Vt.Rw,t.Vt.Dw),t.wo.forEach(((t,i)=>i.ht(t.se,t.Tw))),i.Vt().k_(),i.Z_()}Sg(t){return h(this._g.get(t))}vg(t){const i=new Map;t.hw.forEach(((t,s)=>{const n=s.Rr(),e=Sn(n)(t);if("Custom"!==n)r($s(e));else{const t=s.pa();r(!t||!1===t(e))}i.set(this.Sg(s),e)}));const s=void 0!==t.rw&&this._g.has(t.rw)?this.Sg(t.rw):void 0;return{time:t.sw,logical:t.Re,point:t.nw,paneIndex:t.ew,hoveredSeries:s,hoveredObjectId:t.aw,seriesData:i,sourceEvent:t.lw}}xg(t){let i=this.yu.get(t);return i||(i=new En(this.gf,(t=>this.Sg(t)),t,this),this.yu.set(t,i)),i}}function Wn(t){if(d(t)){const i=document.getElementById(t);return r(null!==i,`Cannot find element in DOM with id=${t}`),i}return t}function Fn(t,i,s){const n=Wn(t),e=new Nn(n,i,s);return i.setOptions(e.options()),e}class Hn extends _n{constructor(t,i){super(t,i,!0)}Uw(t,i,s){i.j_(this.Vw,m(this.Aw)),t.Bl(this.Vw,s,m(this.Aw))}Cg(t,i){return{wt:t,gt:i,_t:NaN,ut:NaN}}Fw(){const t=this.Jn.Rh();this.Vw=this.Jn.Xs().Hr().map((i=>{const s=i.Ft[3];return this.yg(i.Re,s,t)}))}}function Un(t,i,s,n,e,r,h){if(0===i.length||n.from>=i.length||n.to<=0)return;const{context:a,horizontalPixelRatio:l,verticalPixelRatio:o}=t,_=i[n.from];let u=r(t,_),c=_;if(n.to-n.from<2){const i=e/2;a.beginPath();const s={_t:_._t-i,ut:_.ut},n={_t:_._t+i,ut:_.ut};a.moveTo(s._t*l,s.ut*o),a.lineTo(n._t*l,n.ut*o),h(t,u,s,n)}else{const e=(i,s)=>{h(t,u,c,s),a.beginPath(),u=i,c=s};let d=c;a.beginPath(),a.moveTo(_._t*l,_.ut*o);for(let h=n.from+1;h=n.from;--s){const n=i[s];if(n){const i=e(t,n);i!==l&&(a.beginPath(),null!==l&&a.fill(),a.fillStyle=i,l=i);const s=Math.round(n._t*r)+o,u=n.ut*h;a.moveTo(s,u),a.arc(s,u,_,0,2*Math.PI)}}a.fill()}(t,i,l,s,_)}}class Zn extends Xn{Rg(t,i){return i.vt}}class Gn extends Hn{constructor(){super(...arguments),this.Lw=new Zn}yg(t,i,s){return{...this.Cg(t,i),...s.Dr(t)}}$w(){const t=this.Jn.N(),i={ot:this.Vw,Xt:t.lineStyle,kg:t.lineVisible?t.lineType:void 0,ct:t.lineWidth,Tg:t.pointMarkersVisible?t.pointMarkersRadius||t.lineWidth/2+2:void 0,lt:this.Aw,Pg:this.Qn.Vt().G_()};this.Lw.ht(i)}}const Jn={type:"Line",isBuiltIn:!0,defaultOptions:{color:"#2196f3",lineStyle:0,lineWidth:3,lineType:0,lineVisible:!0,crosshairMarkerVisible:!0,crosshairMarkerRadius:4,crosshairMarkerBorderColor:"",crosshairMarkerBorderWidth:2,crosshairMarkerBackgroundColor:"",lastPriceAnimation:0,pointMarkersVisible:!1},wg:(t,i)=>new Gn(t,i)};function Qn(t,i){return t.weight>i.weight?t:i}class te{constructor(){this.Dg=new o,this.Bg=function(t){let i=!1;return function(...s){i||(i=!0,queueMicrotask((()=>{t(...s),i=!1})))}}((()=>this.Dg.p(this.Eg))),this.Eg=0}Ig(){return this.Dg}m(){this.Dg.m()}options(){return this.ys}setOptions(t){this.ys=t}preprocessData(t){}updateFormatter(t){this.ys&&(this.ys.localization=t)}createConverterToInternalObj(t){return this.Bg(),t=>(t>this.Eg&&(this.Eg=t),t)}key(t){return t}cacheKey(t){return t}convertHorzItemToInternal(t){return t}formatHorzItem(t){return this.Vg(t)}formatTickmark(t){return this.Vg(t.time)}maxTickMarkWeight(t){return t.reduce(Qn,t[0]).weight}fillWeightsForPoints(t,i){for(let n=i;nt.toFixed(3)+"%"}},se={lastValueVisible:!1,priceLineVisible:!1};class ne extends Nn{constructor(t,i){const s=_(ie,i||{}),n=new te;super(t,n,s),n.setOptions(this.options()),this._initWhitespaceSeries()}addSeries(t,i={},s=0){if(t.isBuiltIn&&!1===["Area","Line"].includes(t.type))throw new Error("Yield curve only support Area and Line series");const n={...se,...i};return super.addSeries(t,n,s)}_initWhitespaceSeries(){const t=this.horzBehaviour(),i=this.addSeries(Jn);let s;function n(n){const e=function(t,i){return{le:Math.max(0,t.startTimeRange),oe:Math.max(0,t.minimumTimeRange,i||0),Ag:Math.max(1,t.baseResolution)}}(t.options().yieldCurve,n),r=(({le:t,oe:i,Ag:s})=>`${t}~${i}~${s}`)(e);r!==s&&(s=r,i.setData(function({le:t,oe:i,Ag:s}){return Array.from({length:Math.floor((i-t)/s)+1},((i,n)=>({time:t+n*s})))}(e)))}n(0),t.Ig().i(n)}}function ee(t,i){return t.weight>i.weight?t:i}class re{options(){return this.ys}setOptions(t){this.ys=t}preprocessData(t){}updateFormatter(t){this.ys&&(this.ys.localization=t)}createConverterToInternalObj(t){return t=>t}key(t){return t}cacheKey(t){return t}convertHorzItemToInternal(t){return t}formatHorzItem(t){return t.toFixed(this.Cn())}formatTickmark(t,i){return t.time.toFixed(this.Cn())}maxTickMarkWeight(t){return t.reduce(ee,t[0]).weight}fillWeightsForPoints(t,i){for(let n=i;n0?s:1,u=l*_,c=o===t.bitmapSize.height?o:o*_,d=(a??0)*_,f=t.context.createLinearGradient(0,u,0,c);if(f.addColorStop(0,n),null!=a){const t=qt((d-u)/(c-u),0,1);f.addColorStop(t,e),f.addColorStop(t,r)}f.addColorStop(1,h),this.Yg=f,this.Wg=i}return this.Yg}}class oe extends ae{constructor(){super(...arguments),this.Kg=new le}Lg(t,i){const s=this.rt;return this.Kg.Ng(t,{Fg:i.br,Hg:i.Sr,Ug:i.Cr,$g:i.yr,zg:s.zg,jg:s.jg??0,qg:s.qg??t.bitmapSize.height})}}class _e extends Xn{constructor(){super(...arguments),this.Xg=new le}Rg(t,i){const s=this.rt;return this.Xg.Ng(t,{Fg:i.gr,Hg:i.gr,Ug:i.Mr,$g:i.Mr,zg:s.zg,jg:s.jg??0,qg:s.qg??t.bitmapSize.height})}}class ue extends Hn{constructor(t,i){super(t,i),this.Lw=new C,this.Zg=new oe,this.Gg=new _e,this.Lw.st([this.Zg,this.Gg])}yg(t,i,s){return{...this.Cg(t,i),...s.Dr(t)}}$w(){const t=this.Jn.zt();if(null===t)return;const i=this.Jn.N(),s=this.Jn.Wt().Nt(i.baseValue.price,t.Ft),n=this.Qn.Vt().G_();if(null===this.Aw||0===this.Vw.length)return;let e,r;if(i.relativeGradient){e=this.Vw[this.Aw.from].ut,r=this.Vw[this.Aw.from].ut;for(let t=this.Aw.from;tr&&(r=i.ut)}}this.Zg.ht({ot:this.Vw,ct:i.lineWidth,Xt:i.lineStyle,kg:i.lineType,zg:s,jg:e,qg:r,Og:!1,lt:this.Aw,Pg:n}),this.Gg.ht({ot:this.Vw,ct:i.lineWidth,Xt:i.lineStyle,kg:i.lineVisible?i.lineType:void 0,Tg:i.pointMarkersVisible?i.pointMarkersRadius||i.lineWidth/2+2:void 0,zg:s,jg:e,qg:r,lt:this.Aw,Pg:n})}}const ce={type:"Baseline",isBuiltIn:!0,defaultOptions:{baseValue:{type:"price",price:0},relativeGradient:!1,topFillColor1:"rgba(38, 166, 154, 0.28)",topFillColor2:"rgba(38, 166, 154, 0.05)",topLineColor:"rgba(38, 166, 154, 1)",bottomFillColor1:"rgba(239, 83, 80, 0.05)",bottomFillColor2:"rgba(239, 83, 80, 0.28)",bottomLineColor:"rgba(239, 83, 80, 1)",lineWidth:3,lineStyle:0,lineType:0,lineVisible:!0,crosshairMarkerVisible:!0,crosshairMarkerRadius:4,crosshairMarkerBorderColor:"",crosshairMarkerBorderWidth:2,crosshairMarkerBackgroundColor:"",lastPriceAnimation:0,pointMarkersVisible:!1},wg:(t,i)=>new ue(t,i)};class de extends ae{constructor(){super(...arguments),this.Kg=new le}Lg(t,i){return this.Kg.Ng(t,{Fg:i.mr,Hg:"",Ug:"",$g:i.wr,jg:this.rt?.jg??0,qg:t.bitmapSize.height})}}class fe extends Hn{constructor(t,i){super(t,i),this.Lw=new C,this.Jg=new de,this.Qg=new Zn,this.Lw.st([this.Jg,this.Qg])}yg(t,i,s){return{...this.Cg(t,i),...s.Dr(t)}}$w(){const t=this.Jn.N();if(null===this.Aw||0===this.Vw.length)return;let i;if(t.relativeGradient){i=this.Vw[this.Aw.from].ut;for(let t=this.Aw.from;tnew fe(t,i)};class ve extends y{constructor(){super(...arguments),this.qt=null,this.tM=0,this.iM=0}ht(t){this.qt=t}et({context:t,horizontalPixelRatio:i,verticalPixelRatio:s}){if(null===this.qt||0===this.qt.Xs.length||null===this.qt.lt)return;if(this.tM=this.sM(i),this.tM>=2){Math.max(1,Math.floor(i))%2!=this.tM%2&&this.tM--}this.iM=this.qt.nM?Math.min(this.tM,Math.floor(i)):this.tM;let n=null;const e=this.iM<=this.tM&&this.qt.G_>=Math.floor(1.5*i);for(let r=this.qt.lt.from;rf+v-1&&(e=f+v-1,n=e-_+1),t.fillRect(i,n,o-i,e-n+1)}const i=l+m;let n=Math.max(f,Math.round(h.Ol*s)-a),e=n+_-1;e>f+v-1&&(e=f+v-1,n=e-_+1),t.fillRect(u+1,n,i-u,e-n+1)}}}sM(t){const i=Math.floor(t);return Math.max(i,Math.floor(function(t,i){return Math.floor(.3*t*i)}(a(this.qt).G_,t)))}}class me extends _n{constructor(t,i){super(t,i,!1)}Uw(t,i,s){i.j_(this.Vw,m(this.Aw)),t.Il(this.Vw,s,m(this.Aw))}rM(t,i,s){return{wt:t,jh:i.Ft[0],qh:i.Ft[1],Yh:i.Ft[2],Kh:i.Ft[3],_t:NaN,Vl:NaN,Al:NaN,zl:NaN,Ol:NaN}}Fw(){const t=this.Jn.Rh();this.Vw=this.Jn.Xs().Hr().map((i=>this.yg(i.Re,i,t)))}}class we extends me{constructor(){super(...arguments),this.Lw=new ve}yg(t,i,s){return{...this.rM(t,i,s),...s.Dr(t)}}$w(){const t=this.Jn.N();this.Lw.ht({Xs:this.Vw,G_:this.Qn.Vt().G_(),eM:t.openVisible,nM:t.thinBars,lt:this.Aw})}}const ge={type:"Bar",isBuiltIn:!0,defaultOptions:{upColor:"#26a69a",downColor:"#ef5350",openVisible:!0,thinBars:!0},wg:(t,i)=>new we(t,i)};class Me extends y{constructor(){super(...arguments),this.qt=null,this.tM=0}ht(t){this.qt=t}et(t){if(null===this.qt||0===this.qt.Xs.length||null===this.qt.lt)return;const{horizontalPixelRatio:i}=t;if(this.tM=function(t,i){if(t>=2.5&&t<=4)return Math.floor(3*i);const s=1-.2*Math.atan(Math.max(4,t)-4)/(.5*Math.PI),n=Math.floor(t*s*i),e=Math.floor(t*i),r=Math.min(n,e);return Math.max(Math.floor(i),r)}(this.qt.G_,i),this.tM>=2){Math.floor(i)%2!=this.tM%2&&this.tM--}const s=this.qt.Xs;this.qt.hM&&this.aM(t,s,this.qt.lt),this.qt.Mi&&this.Hp(t,s,this.qt.lt);const n=this.lM(i);(!this.qt.Mi||this.tM>2*n)&&this.oM(t,s,this.qt.lt)}aM(t,i,s){if(null===this.qt)return;const{context:n,horizontalPixelRatio:e,verticalPixelRatio:r}=t;let h="",a=Math.min(Math.floor(e),Math.floor(this.qt.G_*e));a=Math.max(Math.floor(e),Math.min(a,this.tM));const l=Math.floor(.5*a);let o=null;for(let t=s.from;t2*a)E(n,o,u,_-o+1,c-u+1,a);else{const t=_-o+1;n.fillRect(o,u,t,c-u+1)}l=_}}oM(t,i,s){if(null===this.qt)return;const{context:n,horizontalPixelRatio:e,verticalPixelRatio:r}=t;let h="";const a=this.lM(e);for(let t=s.from;to||n.fillRect(_,l,u-_+1,o-l+1)}}}class be extends me{constructor(){super(...arguments),this.Lw=new Me}yg(t,i,s){return{...this.rM(t,i,s),...s.Dr(t)}}$w(){const t=this.Jn.N();this.Lw.ht({Xs:this.Vw,G_:this.Qn.Vt().G_(),hM:t.wickVisible,Mi:t.borderVisible,lt:this.Aw})}}const xe={type:"Candlestick",isBuiltIn:!0,defaultOptions:{upColor:"#26a69a",downColor:"#ef5350",wickVisible:!0,borderVisible:!0,borderColor:"#378658",borderUpColor:"#26a69a",borderDownColor:"#ef5350",wickColor:"#737375",wickUpColor:"#26a69a",wickDownColor:"#ef5350"},wg:(t,i)=>new be(t,i)};class Se extends y{constructor(){super(...arguments),this.qt=null,this._M=[]}ht(t){this.qt=t,this._M=[]}et({context:t,horizontalPixelRatio:i,verticalPixelRatio:s}){if(null===this.qt||0===this.qt.ot.length||null===this.qt.lt)return;this._M.length||this.uM(i);const n=Math.max(1,Math.floor(s)),e=Math.round(this.qt.cM*s)-Math.floor(n/2),r=e+n;for(let i=this.qt.lt.from;in.ne?n.bi=s.Uh-i-1:s.Uh=n.bi+i+1))}let n=Math.ceil(this.qt.G_*t);for(let t=this.qt.lt.from;t0&&n<4)for(let t=this.qt.lt.from;tn&&(i.dM>i.ne?i.bi-=1:i.Uh+=1)}}}class Ce extends Hn{constructor(){super(...arguments),this.Lw=new Se}yg(t,i,s){return{...this.Cg(t,i),...s.Dr(t)}}$w(){const t={ot:this.Vw,G_:this.Qn.Vt().G_(),lt:this.Aw,cM:this.Jn.Wt().Nt(this.Jn.N().base,a(this.Jn.zt()).Ft)};this.Lw.ht(t)}}const ye={type:"Histogram",isBuiltIn:!0,defaultOptions:{color:"#26a69a",base:0},wg:(t,i)=>new Ce(t,i)};class Pe{constructor(t,i){this.yt=t,this.fM=i,this.pM()}detach(){this.yt.detachPrimitive(this.fM)}getPane(){return this.yt}applyOptions(t){this.fM.hr?.(t)}pM(){this.yt.attachPrimitive(this.fM)}}const ke={visible:!0,horzAlign:"center",vertAlign:"center",lines:[]},Te={color:"rgba(0, 0, 0, 0.5)",fontSize:48,fontFamily:w,fontStyle:"",text:""};class Re{constructor(t){this.vM=new Map,this.qt=t}draw(t){t.useMediaCoordinateSpace((t=>{if(!this.qt.visible)return;const{context:i,mediaSize:s}=t;let n=0;for(const t of this.qt.lines){if(0===t.text.length)continue;i.font=t.k;const e=this.mM(i,t.text);e>s.width?t.eu=s.width/e:t.eu=1,n+=t.lineHeight*t.eu}let e=0;switch(this.qt.vertAlign){case"top":e=0;break;case"center":e=Math.max((s.height-n)/2,0);break;case"bottom":e=Math.max(s.height-n,0)}for(const t of this.qt.lines){i.save(),i.fillStyle=t.color;let n=0;switch(this.qt.horzAlign){case"left":i.textAlign="left",n=t.lineHeight/2;break;case"center":i.textAlign="center",n=s.width/2;break;case"right":i.textAlign="right",n=s.width-1-t.lineHeight/2}i.translate(n,e),i.textBaseline="top",i.font=t.k,i.scale(t.eu,t.eu),i.fillText(t.text,0,t.wM),i.restore(),e+=t.lineHeight*t.eu}}))}mM(t,i){const s=this.gM(t.font);let n=s.get(i);return void 0===n&&(n=t.measureText(i).width,s.set(i,n)),n}gM(t){let i=this.vM.get(t);return void 0===i&&(i=new Map,this.vM.set(t,i)),i}}class De{constructor(t){this.ys=Ee(t)}Pt(t){this.ys=Ee(t)}renderer(){return new Re(this.ys)}}function Be(t){return{...t,k:g(t.fontSize,t.fontFamily,t.fontStyle),lineHeight:t.lineHeight||1.2*t.fontSize,wM:0,eu:0}}function Ee(t){return{...t,lines:t.lines.map(Be)}}function Ie(t){return{...Te,...t}}function Ve(t){return{...ke,...t,lines:t.lines?.map(Ie)??[]}}class Ae{constructor(t){this.ys=Ve(t),this.MM=[new De(this.ys)]}updateAllViews(){this.MM.forEach((t=>t.Pt(this.ys)))}paneViews(){return this.MM}attached({requestUpdate:t}){this.bM=t}detached(){this.bM=void 0}hr(t){this.ys=Ve({...this.ys,...t}),this.bM&&this.bM()}}const ze={alpha:1,padding:0};class Oe{constructor(t){this.qt=t}draw(t){t.useMediaCoordinateSpace((t=>{const i=t.context,s=this.xM(this.qt,t.mediaSize);s&&this.qt.SM&&(i.globalAlpha=this.qt.alpha??1,i.drawImage(this.qt.SM,s._t,s.ut,s.Qi,s.$t))}))}xM(t,i){const{maxHeight:s,maxWidth:n,CM:e,yM:r,padding:h}=t,a=Math.round(i.width/2),l=Math.round(i.height/2),o=h??0;let _=i.width-2*o,u=i.height-2*o;s&&(u=Math.min(u,s)),n&&(_=Math.min(_,n));const c=_/r,d=u/e,f=Math.min(c,d),p=r*f,v=e*f;return{_t:a-.5*p,ut:l-.5*v,$t:v,Qi:p}}}class Le{constructor(t){this.PM=null,this.kM=0,this.TM=0,this.ys=t,this.M=Ne(this.ys,this.PM,this.kM,this.TM)}RM(t){void 0!==t.DM&&(this.kM=t.DM),void 0!==t.BM&&(this.TM=t.BM),void 0!==t.EM&&(this.PM=t.EM),this.Pt()}IM(t){this.ys=t,this.Pt()}zOrder(){return"bottom"}Pt(){this.M=Ne(this.ys,this.PM,this.kM,this.TM)}renderer(){return new Oe(this.M)}}function Ne(t,i,s,n){return{...t,SM:i,yM:s,CM:n}}function We(t){return{...ze,...t}}class Fe{constructor(t,i){this.VM=null,this.AM=t,this.ys=We(i),this.MM=[new Le(this.ys)]}updateAllViews(){this.MM.forEach((t=>t.Pt()))}paneViews(){return this.MM}attached(t){const{requestUpdate:i}=t;this.zM=i,this.VM=new Image,this.VM.onload=()=>{const t=this.VM?.naturalHeight??1,i=this.VM?.naturalWidth??1;this.MM.forEach((s=>s.RM({BM:t,DM:i,EM:this.VM}))),this.zM&&this.zM()},this.VM.src=this.AM}detached(){this.zM=void 0,this.VM=null}hr(t){this.ys=We({...this.ys,...t}),this.OM(),this.bM&&this.bM()}bM(){this.zM&&this.zM()}OM(){this.MM.forEach((t=>t.IM(this.ys)))}}class He{constructor(t,i){this.Jn=t,this.ah=i,this.pM()}detach(){this.Jn.detachPrimitive(this.ah)}getSeries(){return this.Jn}applyOptions(t){this.ah&&this.ah.hr&&this.ah.hr(t)}pM(){this.Jn.attachPrimitive(this.ah)}}function Ue(t,i){return Kt(Math.min(Math.max(t,12),30)*i)}function $e(t,i){switch(t){case"arrowDown":case"arrowUp":return Ue(i,1);case"circle":return Ue(i,.8);case"square":return Ue(i,.7)}}function je(t){return function(t){const i=Math.ceil(t);return i%2!=0?i-1:i}(Ue(t,1))}function qe(t){return Math.max(Ue(t,.1),3)}function Ye(t,i,s){return i?t:s?Math.ceil(t/2):0}function Ke(t,i,s,n){const e=($e("arrowUp",n)-1)/2*s.LM,r=(Kt(n/2)-1)/2*s.LM;i.beginPath(),t?(i.moveTo(s._t-e,s.ut),i.lineTo(s._t,s.ut-e),i.lineTo(s._t+e,s.ut),i.lineTo(s._t+r,s.ut),i.lineTo(s._t+r,s.ut+e),i.lineTo(s._t-r,s.ut+e),i.lineTo(s._t-r,s.ut)):(i.moveTo(s._t-e,s.ut),i.lineTo(s._t,s.ut+e),i.lineTo(s._t+e,s.ut),i.lineTo(s._t+r,s.ut),i.lineTo(s._t+r,s.ut-e),i.lineTo(s._t-r,s.ut-e),i.lineTo(s._t-r,s.ut)),i.fill()}function Xe(t,i,s,n,e,r){const h=($e("arrowUp",n)-1)/2,a=(Kt(n/2)-1)/2;if(e>=i-a-2&&e<=i+a+2&&r>=(t?s:s-h)-2&&r<=(t?s+h:s)+2)return!0;return(()=>{if(ei+h+3||r<(t?s-h-3:s)||r>(t?s:s+h+3))return!1;const n=Math.abs(e-i);return Math.abs(r-s)+3>=n/2})()}class Ze{constructor(){this.qt=null,this.Ln=new tt,this.W=-1,this.F="",this.wp=""}ht(t){this.qt=t}Nn(t,i){this.W===t&&this.F===i||(this.W=t,this.F=i,this.wp=g(t,i),this.Ln.En())}Yn(t,i){if(null===this.qt||null===this.qt.lt)return null;for(let s=this.qt.lt.from;s{this.et(t)}))}et({context:t,horizontalPixelRatio:i,verticalPixelRatio:s}){if(null!==this.qt&&null!==this.qt.lt){t.textBaseline="middle",t.font=this.wp;for(let n=this.qt.lt.from;n=t&&e<=t+s&&r>=i-h&&r<=i+h}(t.ri._t,t.ri.ut,t.ri.Qi,t.ri.$t,i,s))||function(t,i,s){if(0===t.zr)return!1;switch(t.WM){case"arrowDown":return Xe(!0,t._t,t.ut,t.zr,i,s);case"arrowUp":return Xe(!1,t._t,t.ut,t.zr,i,s);case"circle":return function(t,i,s,n,e){const r=2+$e("circle",s)/2,h=t-n,a=i-e;return Math.sqrt(h*h+a*a)<=r}(t._t,t.ut,t.zr,i,s);case"square":return function(t,i,s,n,e){const r=$e("square",s),h=(r-1)/2,a=t-h,l=i-h;return n>=a&&n<=a+r&&e>=l&&e<=l+r}(t._t,t.ut,t.zr,i,s)}}(t,i,s)}function Qe(t){return"atPriceTop"===t||"atPriceBottom"===t||"atPriceMiddle"===t}function tr(t,i,s,n,e,r,h,l){const o=function(t,i){if(Qe(i.position)&&void 0!==i.price)return i.price;if("value"in(s=t)&&"number"==typeof s.value)return t.value;var s;if(function(t){return"open"in t&&"high"in t&&"low"in t&&"close"in t}(t)){if("inBar"===i.position)return t.close;if("aboveBar"===i.position)return t.high;if("belowBar"===i.position)return t.low}}(s,i);if(void 0===o)return;const _=Qe(i.position),c=l.timeScale(),d=u(i.size)?Math.max(i.size,0):1,f=je(c.options().barSpacing)*d,p=f/2;t.zr=f;switch(i.position){case"inBar":case"atPriceMiddle":return t.ut=a(h.priceToCoordinate(o)),void(void 0!==t.ri&&(t.ri.ut=t.ut+p+r+.6*e));case"aboveBar":case"atPriceTop":{const i=_?0:n.FM;return t.ut=a(h.priceToCoordinate(o))-p-i,void 0!==t.ri&&(t.ri.ut=t.ut-p-.6*e,n.FM+=1.2*e),void(_||(n.FM+=f+r))}case"belowBar":case"atPriceBottom":{const i=_?0:n.HM;return t.ut=a(h.priceToCoordinate(o))+p+i,void 0!==t.ri&&(t.ri.ut=t.ut+p+r+.6*e,n.HM+=1.2*e),void(_||(n.HM+=f+r))}}}class ir{constructor(t,i){this.UM=[],this.St=!0,this.$M=!0,this.Gt=new Ze,this.ge=t,this.lp=i,this.qt={ot:[],lt:null}}renderer(){if(!this.ge.options().visible)return null;this.St&&this.jM();const t=this.lp.options().layout;return this.Gt.Nn(t.fontSize,t.fontFamily),this.Gt.ht(this.qt),this.Gt}qM(t){this.UM=t,this.Pt("data")}Pt(t){this.St=!0,"data"===t&&(this.$M=!0)}jM(){const t=this.lp.timeScale(),i=this.UM;this.$M&&(this.qt.ot=i.map((t=>({wt:t.time,_t:0,ut:0,zr:0,WM:t.shape,R:t.color,Kn:t.id,YM:t.YM,ri:void 0}))),this.$M=!1);const s=this.lp.options().layout;this.qt.lt=null;const n=t.getVisibleLogicalRange();if(null===n)return;const e=new xi(Math.floor(n.from),Math.ceil(n.to));if(null===this.ge.data()[0])return;if(0===this.qt.ot.length)return;let r=NaN;const h=qe(t.options().barSpacing),l={FM:h,HM:h};this.qt.lt=on(this.qt.ot,e,!0);for(let n=this.qt.lt.from;n0&&(o.ri={NM:e.text,_t:0,ut:0,Qi:0,$t:0});const _=this.ge.dataByIndex(e.time,0);null!==_&&tr(o,e,_,l,s.fontSize,h,this.ge,this.lp)}this.St=!1}}class sr{constructor(){this.sh=null,this.UM=[],this.KM=[],this.XM=null,this.ge=null,this.lp=null,this.ZM=!0,this.GM=null,this.JM=null,this.QM=null,this.tb=!0}attached(t){this.ib(),this.lp=t.chart,this.ge=t.series,this.sh=new ir(this.ge,a(this.lp)),this.zM=t.requestUpdate,this.ge.subscribeDataChanged((t=>this.ng(t))),this.tb=!0,this.bM()}bM(){this.zM&&this.zM()}detached(){this.ge&&this.XM&&this.ge.unsubscribeDataChanged(this.XM),this.lp=null,this.ge=null,this.sh=null,this.XM=null}qM(t){this.tb=!0,this.UM=t,this.ib(),this.ZM=!0,this.JM=null,this.bM()}sb(){return this.UM}paneViews(){return this.sh?[this.sh]:[]}updateAllViews(){this.nb()}hitTest(t,i){return this.sh?this.sh.renderer()?.Yn(t,i)??null:null}autoscaleInfo(t,i){if(this.sh){const t=this.eb();if(t)return{priceRange:null,margins:t}}return null}eb(){const t=a(this.lp).timeScale().options().barSpacing;if(this.ZM||t!==this.QM){if(this.QM=t,this.UM.length>0){const i=qe(t),s=1.5*je(t)+2*i,n=this.rb();this.GM={above:Ye(s,n.aboveBar,n.inBar),below:Ye(s,n.belowBar,n.inBar)}}else this.GM=null;this.ZM=!1}return this.GM}rb(){return null===this.JM&&(this.JM=this.UM.reduce(((t,i)=>(t[i.position]||(t[i.position]=!0),t)),{inBar:!1,aboveBar:!1,belowBar:!1,atPriceTop:!1,atPriceBottom:!1,atPriceMiddle:!1})),this.JM}ib(){if(!this.tb||!this.lp||!this.ge)return;const t=this.lp.timeScale(),i=this.ge?.data();if(null==t.getVisibleLogicalRange()||!this.ge||0===i.length)return void(this.KM=[]);const s=t.timeToIndex(a(i[0].time),!0);this.KM=this.UM.map(((i,n)=>{const e=t.timeToIndex(i.time,!0),r=e{this.UM.delete(i),this.ob()}),s),e={...t,_b:n,ub:Date.now()+s};this.UM.set(i,e)}else this.UM.set(i,{...t,_b:void 0,ub:void 0});this.ob()}lb(t){const i=this.UM.get(t);i&&void 0!==i._b&&window.clearTimeout(i._b),this.UM.delete(t),this.ob()}cb(){for(const[t]of this.UM)this.lb(t)}fb(){const t=Date.now(),i=[];for(const[s,n]of this.UM)!n.ub||n.ub>t?i.push({time:n.time,sign:n.sign,value:n.value}):this.lb(s);return i}pb(t){this.hb=t}ob(){this.hb&&this.hb()}}const rr={positiveColor:"#22AB94",negativeColor:"#F7525F",updateVisibilityDuration:5e3};class hr{constructor(t,i,s,n){this.qt=t,this.mb=i,this.wb=s,this.gb=n}draw(t){t.useBitmapCoordinateSpace((t=>{const i=t.context,s=Math.max(1,Math.floor(t.horizontalPixelRatio))%2/2,n=4*t.verticalPixelRatio+s;this.qt.forEach((e=>{const r=Math.round(e._t*t.horizontalPixelRatio)+s;i.beginPath();const h=this.Mb(e.bb);i.fillStyle=h,i.arc(r,e.ut*t.verticalPixelRatio,n,0,2*Math.PI,!1),i.fill(),e.bb&&(i.strokeStyle=h,i.lineWidth=Math.floor(2*t.horizontalPixelRatio),i.beginPath(),i.moveTo((e._t-4.7)*t.horizontalPixelRatio+s,(e.ut-7*e.bb)*t.verticalPixelRatio),i.lineTo(e._t*t.horizontalPixelRatio+s,(e.ut-7*e.bb-7*e.bb*.5)*t.verticalPixelRatio),i.lineTo((e._t+4.7)*t.horizontalPixelRatio+s,(e.ut-7*e.bb)*t.verticalPixelRatio),i.stroke())}))}))}Mb(t){return 0===t?this.mb:t>0?this.gb:this.wb}}class ar{constructor(t,i,s){this.qt=[],this.ge=t,this.uh=i,this.ys=s}Pt(t){this.qt=t.map((t=>{const i=this.ge.priceToCoordinate(t.value);if(null===i)return null;return{_t:a(this.uh.timeToCoordinate(t.time)),ut:i,bb:t.sign}})).filter(v)}renderer(){const t=function(t,i){return function(t,i){return"Area"===i}(0,i)?t.lineColor:t.color}(this.ge.options(),this.ge.seriesType());return new hr(this.qt,t,this.ys.negativeColor,this.ys.positiveColor)}}function lr(t,i){return"Line"===i||"Area"===i}class or{constructor(t){this.lp=void 0,this.ge=void 0,this.MM=[],this.$o=null,this.xb=new Map,this.Sb=new er((()=>this.bM())),this.ys={...rr,...t}}hr(t){this.ys={...this.ys,...t},this.bM()}qM(t){this.Sb.cb();const i=this.$o;i&&t.forEach((t=>{this.Sb.ab(t,i.key(t.time))}))}sb(){return this.Sb.fb()}bM(){this.zM?.()}attached(t){const{chart:i,series:s,requestUpdate:n,horzScaleBehavior:e}=t;this.lp=i,this.ge=s,this.$o=e;const r=this.ge.seriesType();if("Area"!==r&&"Line"!==r)throw new Error("UpDownMarkersPrimitive is only supported for Area and Line series types");this.MM=[new ar(this.ge,this.lp.timeScale(),this.ys)],this.zM=n,this.bM()}detached(){this.lp=void 0,this.ge=void 0,this.zM=void 0}xp(){return h(this.lp)}wo(){return h(this.ge)}updateAllViews(){this.MM.forEach((t=>t.Pt(this.sb())))}paneViews(){return this.MM}ht(t){if(!this.ge)throw new Error("Primitive not attached to series");const i=this.ge.seriesType();this.xb.clear();const s=this.$o;s&&t.forEach((t=>{$s(t)&&lr(0,i)&&this.xb.set(s.key(t.time),t.value)})),h(this.ge).setData(t)}Pt(t,i){if(!this.ge||!this.$o)throw new Error("Primitive not attached to series");const s=this.ge.seriesType(),n=this.$o.key(t.time);if(Us(t)&&this.xb.delete(n),$s(t)&&lr(0,s)){const i=this.xb.get(n);i&&this.Sb.ab({time:t.time,value:t.value,sign:_r(t.value,i)},n,this.ys.updateVisibilityDuration)}h(this.ge).update(t,i)}Cb(){this.Sb.cb()}}function _r(t,i){return t===i?0:t-i>0?1:-1}class ur extends He{setData(t){return this.ah.ht(t)}update(t,i){return this.ah.Pt(t,i)}markers(){return this.ah.sb()}setMarkers(t){return this.ah.qM(t)}clearMarkers(){return this.ah.Cb()}}const cr={...t,color:"#2196f3"};var dr=Object.freeze({__proto__:null,AreaSeries:pe,BarSeries:ge,BaselineSeries:ce,CandlestickSeries:xe,get ColorType(){return Bi},get CrosshairMode(){return $},HistogramSeries:ye,get LastPriceAnimationMode(){return Ri},LineSeries:Jn,get LineStyle(){return s},get LineType(){return i},get MismatchDirection(){return St},get PriceLineSource(){return Di},get PriceScaleMode(){return ui},get TickMarkType(){return Ei},get TrackingModeExitMode(){return Ti},createChart:function(t,i){return Fn(t,new Gi,Gi.Lc(i))},createChartEx:Fn,createImageWatermark:function(t,i,s){return new Pe(t,new Fe(i,s))},createOptionsChart:function(t,i){return Fn(t,new re,i)},createSeriesMarkers:function(t,i){const s=new nr(t,new sr);return i&&s.setMarkers(i),s},createTextWatermark:function(t,i){return new Pe(t,new Ae(i))},createUpDownMarkers:function(t,i={}){return new ur(t,new or(i))},createYieldCurveChart:function(t,i){const s=Wn(t);return new ne(s,i)},customSeriesDefaultOptions:cr,defaultHorzScaleBehavior:function(){return Gi},isBusinessDay:Vi,isUTCTimestamp:Ai,version:function(){return"5.0.6"}});window.LightweightCharts=dr}(); diff --git a/scripts/Symbols.json b/lightweight_charts_esistjosh/scripts/Symbols.json similarity index 100% rename from scripts/Symbols.json rename to lightweight_charts_esistjosh/scripts/Symbols.json diff --git a/scripts/cache.json b/lightweight_charts_esistjosh/scripts/cache.json similarity index 100% rename from scripts/cache.json rename to lightweight_charts_esistjosh/scripts/cache.json diff --git a/run.py b/run.py index afb7c279..b7db0610 100644 --- a/run.py +++ b/run.py @@ -42,7 +42,7 @@ def on_timeframe_selection(chart): df1 = data.iloc[:midpoint] df2 = data.iloc[midpoint+1:] - chart = Chart(toolbox=True, debug=True) + chart = Chart(toolbox=True, debug=True, defaults= "./lightweight_charts_esistjosh/defaults", scripts= "./lightweight_charts_esistjosh/scripts") chart.legend(True) chart.set(df1) diff --git a/setup.py b/setup.py index 21324081..ab93e3e3 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setup( name='lightweight_charts_esistjosh', - version='3.0.3', + version='3.0.4', packages=find_packages(), python_requires='>=3.8', install_requires=[ @@ -14,8 +14,14 @@ 'pywebview>=5.0.5', ], package_data={ - 'lightweight_charts_esistjosh': ['js/*'], + # “**” says “and everything under here, at any depth” + "lightweight_charts_esistjosh": [ + "defaults/**/*", + "scripts/**/*", + "js/*.js", + ], }, + author='EsIstJosh', license='MIT/AGPL-3.0', description="Python framework for TradingView's Lightweight Charts JavaScript library.", diff --git a/src/box/box.ts b/src/box/box.ts index c6b8140e..da669674 100644 --- a/src/box/box.ts +++ b/src/box/box.ts @@ -125,7 +125,7 @@ export class Box extends TwoPointDrawing { } } - protected _mouseIsOverDrawing(param: MouseEventParams, tolerance = 4) { + protected _mouseIsOverTwoPointDrawing(param: MouseEventParams, tolerance = 4) { if (!param.point) return false; const x1 = this._paneViews[0]._p1.x; diff --git a/src/general/handler.ts b/src/general/handler.ts index 847a4ce2..6bbde03d 100644 --- a/src/general/handler.ts +++ b/src/general/handler.ts @@ -737,7 +737,7 @@ createSymbolSeries( } createToolBox() { - this.toolBox = new ToolBox(this, this.id, this.chart, this.series, this.commandFunctions); + this.toolBox = new ToolBox(this, this.chart, this.series, this.commandFunctions); this.div.appendChild(this.toolBox.div); } diff --git a/src/general/toolbox.ts b/src/general/toolbox.ts index 7feb962b..3ac44646 100644 --- a/src/general/toolbox.ts +++ b/src/general/toolbox.ts @@ -7,44 +7,36 @@ import { IChartApi, ISeriesApi, SeriesType } from "lightweight-charts"; import { HorizontalLine } from "../horizontal-line/horizontal-line"; import { RayLine } from "../horizontal-line/ray-line"; import { VerticalLine } from "../vertical-line/vertical-line"; -// Right alongside your existing imports for other drawing classes: -import { Handler } from "./handler"; - -// Import the pitchfork tools import { PitchFork } from "../pitchfork/pitchfork"; +import { Measure } from "../measure/measure"; +import { Handler } from "./handler"; -//import { FibonacciCircleDrawing, -// FibonacciExtensionDrawing, -// FibonacciSegmentDrawing, -// FibonacciSpiralDrawing, -// GannBoxDrawing } from "../technical-analysis/technical-analysis"; interface Icon { div: HTMLDivElement, group: SVGGElement, type: new (...args: any[]) => Drawing } -declare const window: GlobalParams +declare const window: GlobalParams; +export type ToolBoxMode = "static" | "toggle"; export class ToolBox { - private static readonly TREND_SVG: string = ''; - private static readonly HORZ_SVG: string = ''; - private static readonly RAY_SVG: string = ''; - private static readonly BOX_SVG: string = ''; - private static readonly VERT_SVG: string = ToolBox.RAY_SVG; - - // Add new static SVG icons for pitchfork tools: - private static readonly PITCHFORK_SVG: string = ''; - //sprivate static readonly SCHIFF_PITCHFORK_SVG: string = ''; - //sprivate static readonly MODIFIED_SCHIFF_PITCHFORK_SVG: string = ''; - //sprivate static readonly INSIDE_PITCHFORK_SVG: string = ''; - //sprivate static readonly SEGMENT_SVG: string = ''; - //sprivate static readonly EXTENSION_SVG: string = ''; - //sprivate static readonly CIRCLE_SVG: string = ''; - //sprivate static readonly SPIRAL_SVG: string = ''; - //sprivate static readonly GANN_SVG: string = ''; - - div: HTMLDivElement; + private static readonly ICONS: Record = { + trend: '', + horz: '', + ray: '', + box: '', + vert: '', + pitch: '', + measure: '' +}; + + + + + + + public readonly div: HTMLDivElement; private activeIcon: Icon | null = null; private buttons: HTMLDivElement[] = []; @@ -52,179 +44,213 @@ export class ToolBox { private _commandFunctions: Function[]; private _handlerID: string; private _drawingTool: DrawingTool; - private handler: Handler - constructor(handler: Handler, handlerID: string, chart: IChartApi, series: ISeriesApi, commandFunctions: Function[]) { - this._handlerID = handlerID; + constructor( + private handler: Handler, + chart: IChartApi, + series: ISeriesApi, + commandFunctions: Function[], + overlay: boolean = true + ) { + this._handlerID = this.handler.id; this._commandFunctions = commandFunctions; this._drawingTool = new DrawingTool(chart, series, () => this.removeActiveAndSave()); - this.div = this._makeToggleToolBox(); - this.handler = handler; - this.handler.ContextMenu.setupDrawingTools(this.saveDrawings, this._drawingTool); - - commandFunctions.push((event: KeyboardEvent) => { - if ((event.metaKey || event.ctrlKey) && event.code === 'KeyZ') { - const drawingToDelete = this._drawingTool.drawings.pop(); - if (drawingToDelete) this._drawingTool.delete(drawingToDelete); + + // Support undo (Ctrl+Z / Cmd+Z) + commandFunctions.push((e: KeyboardEvent) => { + if ((e.metaKey || e.ctrlKey) && e.code === "KeyZ") { + const last = this._drawingTool.drawings.pop(); + if (last) this._drawingTool.delete(last); return true; } return false; }); - } - toJSON() { - // Exclude the chart attribute from serialization - const { ...serialized} = this; - return serialized; + // Create toolbox according to overlay flag + const mode: ToolBoxMode = overlay ? "toggle" : "static"; + this.div = this._createToolBox(handler, mode); + + handler.ContextMenu.setupDrawingTools(this.saveDrawings, this._drawingTool); + + // Global Alt+Key bindings for each icon + commandFunctions.push((e: KeyboardEvent) => { + if (this.handler.id !== window.handlerInFocus) return false; + if (e.altKey) { + for (const [i, key] of Object.keys(ToolBox.ICONS).entries()) { + const code = ["M","T","H","R","B","V","P"][i]; // map index to M/T/H/R/B/V/P + if (e.code === `Key${code}`) { + e.preventDefault(); + this.buttons[i].click(); + return true; + } + } + } + return false; + }); + } + + private _createToolBox(handler: Handler, mode: ToolBoxMode): HTMLDivElement { + return mode === "toggle" ? this._makeToggleToolBox() : this._makeToolBox(); } - + + private _makeToolBox(): HTMLDivElement { + const container = document.createElement("div"); + container.classList.add("toolbox"); + this._registerIcon(container, "measure"); + this._registerIcon(container, "trend"); + this._registerIcon(container, "horz"); + this._registerIcon(container, "ray"); + this._registerIcon(container, "box"); + this._registerIcon(container, "vert", true); + this._registerIcon(container, "pitch"); + return container; + } + private _makeToggleToolBox(): HTMLDivElement { - const outerDiv = document.createElement('div'); - outerDiv.classList.add('flyout-toolbox'); - - // Position the container absolutely at the top center. - outerDiv.style.position = 'absolute'; - outerDiv.style.top = '0'; - outerDiv.style.left = '50%'; - outerDiv.style.transform = 'translateX(-50%)'; - outerDiv.style.zIndex = '1000'; - outerDiv.style.overflow = 'hidden'; - outerDiv.style.transition = 'height 0.3s ease'; - - // Create the container for the toolbox content (the buttons). - const contentDiv = document.createElement('div'); - contentDiv.classList.add('toolbox-content'); - // Use inline-flex so its width is determined by its content. - contentDiv.style.display = 'inline-flex'; - contentDiv.style.flexDirection = 'row'; - contentDiv.style.justifyContent = 'center'; - contentDiv.style.alignItems = 'center'; - contentDiv.style.padding = '5px'; - contentDiv.style.backgroundColor = 'rgba(0, 0, 0, 0.5)'; - // Initially, content is hidden. - contentDiv.style.display = 'none'; - - // Create toolbox buttons using your existing method. - this.buttons = []; - this.buttons.push(this._makeToolBoxElement(TrendLine, 'KeyT', ToolBox.TREND_SVG)); - this.buttons.push(this._makeToolBoxElement(HorizontalLine, 'KeyH', ToolBox.HORZ_SVG)); - this.buttons.push(this._makeToolBoxElement(RayLine, 'KeyR', ToolBox.RAY_SVG)); - this.buttons.push(this._makeToolBoxElement(Box, 'KeyB', ToolBox.BOX_SVG)); - this.buttons.push(this._makeToolBoxElement(VerticalLine, 'KeyV', ToolBox.VERT_SVG, true)); - this.buttons.push(this._makeToolBoxElement(PitchFork, 'KeyP', ToolBox.PITCHFORK_SVG)); - - // Append each button to the content container. - for (const button of this.buttons) { - contentDiv.appendChild(button); - } - - // Create the toggle tab that will always be visible and is attached to the bottom. - const toggleTab = document.createElement('div'); - toggleTab.textContent = '▼'; // Down arrow for collapsed state. - toggleTab.style.width = '15px'; - toggleTab.style.height = '10px'; - toggleTab.style.backgroundColor = 'rgba(0, 0, 0, 0)' - toggleTab.style.color = '#fff'; - toggleTab.style.textAlign = 'center'; - toggleTab.style.lineHeight = '15px'; - toggleTab.style.cursor = 'pointer'; - // No extra margin needed since we want it attached. - - // Append both content and toggle tab to the outer container. - outerDiv.appendChild(contentDiv); - outerDiv.appendChild(toggleTab); - - // Define heights. - const tabHeight = 15; // Height of the toggle tab. + const outer = document.createElement("div"); + outer.classList.add("flyout-toolbox"); + Object.assign(outer.style, { + position: "absolute", + top: "0", + left: "50%", + transform: "translateX(-50%)", + overflow: "hidden", + transition: "height 0.3s ease", + zIndex: "1000", + }); + + const content = document.createElement("div"); + content.classList.add("toolbox-content"); + Object.assign(content.style, { + display: "none", + inlineFlex: "row", + padding: "5px", + backgroundColor: "rgba(0,0,0,0.5)", + }); + + this._registerIcon(content, "measure"); + this._registerIcon(content, "trend"); + this._registerIcon(content, "horz"); + this._registerIcon(content, "ray"); + this._registerIcon(content, "box"); + this._registerIcon(content, "vert", true); + this._registerIcon(content, "pitch"); + + outer.appendChild(content); + + const tab = document.createElement("div"); + tab.textContent = "▼"; + Object.assign(tab.style, { + width: "15px", + height: "15px", + textAlign: "center", + lineHeight: "15px", + cursor: "pointer", + color: "#fff", + background: "transparent", + }); + let expanded = false; + const tabHeight = 15; + outer.style.height = `${tabHeight}px`; - // When collapsed, outerDiv's height is exactly the toggle tab's height. - outerDiv.style.height = `${tabHeight}px`; - - // Toggle behavior: clicking the tab shows or hides the content. - toggleTab.onclick = () => { + tab.onclick = () => { expanded = !expanded; if (expanded) { - // Show content. - contentDiv.style.display = 'inline-flex'; - // Force reflow to measure the content height. - const contentHeight = contentDiv.scrollHeight; - // Set the outer container's height to content + tab height. - outerDiv.style.height = `${tabHeight + contentHeight}px`; - toggleTab.textContent = '▲'; // Up arrow indicates expanded. + content.style.display = "inline-flex"; + const h = content.scrollHeight; + outer.style.height = `${h + tabHeight}px`; + tab.textContent = "▲"; } else { - // Hide content. - contentDiv.style.display = 'none'; - outerDiv.style.height = `${tabHeight}px`; - toggleTab.textContent = '▼'; // Down arrow indicates collapsed. + content.style.display = "none"; + outer.style.height = `${tabHeight}px`; + tab.textContent = "▼"; } }; - return outerDiv; - } - - - - private _makeToolBoxElement(DrawingType: new (...args: any[]) => Drawing, keyCmd: string, paths: string, rotate=false) { - const elem = document.createElement('div') - elem.classList.add("toolbox-button"); + outer.appendChild(tab); + return outer;} - const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); - svg.setAttribute("width", "29"); - svg.setAttribute("height", "29"); - const group = document.createElementNS("http://www.w3.org/2000/svg", "g"); - group.innerHTML = paths - group.setAttribute("fill", window.pane.color) + private static readonly TOOL_CLASSES: { + [K in keyof typeof ToolBox.ICONS]: new (...args: any[]) => Drawing + } = { + measure: Measure, + trend: TrendLine, + horz: HorizontalLine, + ray: RayLine, + box: Box, + vert: VerticalLine, + pitch: PitchFork, + }; + + // … + private _registerIcon( + container: HTMLElement, + key: keyof typeof ToolBox.ICONS, + rotate = false + ) { + const svgNS = "http://www.w3.org/2000/svg"; + const btn = document.createElement("div"); + btn.classList.add("toolbox-button"); - svg.appendChild(group) - elem.appendChild(svg); + // 1) Create the SVG element with a fixed 28×28 viewport + const svg = document.createElementNS(svgNS, "svg"); + svg.setAttribute("width", "28"); + svg.setAttribute("height", "28"); + svg.setAttribute("viewBox", "0 0 28 28"); - const icon: Icon = {div: elem, group: group, type: DrawingType} + // 2) Create the container and fill it with our icon paths + const g = document.createElementNS(svgNS, "g"); + g.innerHTML = ToolBox.ICONS[key]; + svg.appendChild(g); - elem.addEventListener('click', () => this._onIconClick(icon)); + // 3) Optionally rotate the entire SVG + if (rotate) { + svg.style.transform = "rotate(90deg)"; + svg.style.transformBox = "fill-box"; + svg.style.transformOrigin = "center"; + } - this._commandFunctions.push((event: KeyboardEvent) => { - if (this._handlerID !== window.handlerInFocus) return false; + // 4) Append to the button and into the container + btn.appendChild(svg); + container.appendChild(btn); - if (event.altKey && event.code === keyCmd) { - event.preventDefault() - this._onIconClick(icon); - return true - } - return false; - }) + // 5) Lookup the drawing class (guaranteed by our TOOL_CLASSES map) + const drawingClass = ToolBox.TOOL_CLASSES[key]; - if (rotate == true) { - svg.style.transform = 'rotate(90deg)'; - svg.style.transformBox = 'fill-box'; - svg.style.transformOrigin = 'center'; - } + const icon: Icon = { + div: btn, + group: g, // <-- this is the element + type: drawingClass, + }; - return elem - } + btn.addEventListener("click", () => this._onIconClick(icon)); + this.buttons.push(btn); + } private _onIconClick(icon: Icon) { if (this.activeIcon) { - - this.activeIcon.div.classList.remove('active-toolbox-button'); - window.setCursor('crosshair'); - this._drawingTool?.stopDrawing() + this.activeIcon.div.classList.remove("active-toolbox-button"); + this._drawingTool.stopDrawing(); if (this.activeIcon === icon) { - this.activeIcon = null - return + this.activeIcon = null; + window.setCursor("default"); + return; } } - this.activeIcon = icon - this.activeIcon.div.classList.add('active-toolbox-button') - window.setCursor('crosshair'); - this._drawingTool?.beginDrawing(this.activeIcon.type); + this.activeIcon = icon; + icon.div.classList.add("active-toolbox-button"); + window.setCursor("crosshair"); + this._drawingTool.beginDrawing(icon.type); } - removeActiveAndSave = () => { - window.setCursor('default'); - if (this.activeIcon) this.activeIcon.div.classList.remove('active-toolbox-button') - this.activeIcon = null - this.saveDrawings() + private removeActiveAndSave() { + window.setCursor("default"); + if (this.activeIcon) { + this.activeIcon.div.classList.remove("active-toolbox-button"); + this.activeIcon = null; + } + this.saveDrawings(); } addNewDrawing(d: Drawing) { @@ -270,31 +296,10 @@ export class ToolBox { case "PitchFork": this._drawingTool.addNewDrawing(new PitchFork(d.points[0], d.points[1], d.points[2], d.options)); break; - //case "SchiffPitchfork": - // this._drawingTool.addNewDrawing(new PitchFork(d.points[0], d.points[1], d.points[2], {...d.options, variant: "schiff"})); - // break; - //case "ModifiedSchiffPitchfork": - // this._drawingTool.addNewDrawing(new PitchFork(d.points[0], d.points[1], d.points[2], {...d.options, variant: "modifiedSchiff"})); - // break; - //case "InsidePitchfork": - // this._drawingTool.addNewDrawing(new PitchFork(d.points[0], d.points[1], d.points[2], {...d.options, variant: "inside"})); - // break; - //case "FibonacciSegment": - // this._drawingTool.addNewDrawing(new FibonacciSegmentDrawing(d.points[0], d.points[1], d.options)); - // break; - //case "FibonacciExtension": - // this._drawingTool.addNewDrawing(new FibonacciExtensionDrawing(d.points[0], d.points[1], d.options)); - // break; - //case "FibonacciCircle": - // this._drawingTool.addNewDrawing(new FibonacciCircleDrawing(d.points[0], d.points[1], d.options)); - // break; - //case "FibonacciSpiral": - // this._drawingTool.addNewDrawing(new FibonacciSpiralDrawing(d.points[0], d.points[1], d.options)); - // break; - //case "GannBox": - // this._drawingTool.addNewDrawing(new GannBoxDrawing(d.points[0], d.points[1], d.points[2], d.points[3], d.options)); - // break; + case "Measure": + this._drawingTool.addNewDrawing(new Measure(d.points[0], d.points[1], d.options)); + break; } }); } - } \ No newline at end of file + } diff --git a/src/helpers/series.ts b/src/helpers/series.ts index 95aff4ba..d10473b0 100644 --- a/src/helpers/series.ts +++ b/src/helpers/series.ts @@ -9,13 +9,10 @@ import { findColorOptions } from "./colors"; import { PineTS } from "pinets"; import { convertTime, formattedDateAndTime } from "./time"; import { DefaultOptionsManager } from "../general/defaults"; -import { IsExternal } from "rollup"; import { defaultSymbolSeriesOptions, SymbolSeriesOptions } from "../symbol-series/options"; import { SymbolSeries } from "../symbol-series/symbol-series"; -import { tradeDefaultOptions, TradeData } from "../tx-series/renderer"; import { SymbolSeriesData } from "../symbol-series/data"; import { defaultFillAreaOptions, FillArea } from "../fill-area/fill-area"; -import { base } from "acorn-walk"; export interface ISeriesApiExtended extends ISeriesApi { primitives: { [key: string]: any; // Dictionary for attached primitives diff --git a/src/measure/measure.ts b/src/measure/measure.ts new file mode 100644 index 00000000..1a72fa8d --- /dev/null +++ b/src/measure/measure.ts @@ -0,0 +1,157 @@ +import { + LineStyle, + MouseEventParams, +} from 'lightweight-charts'; + +import { Point } from '../drawing/data-source'; +import { InteractionState } from '../drawing/drawing'; +import { DrawingOptions, defaultOptions } from '../drawing/options'; +import { MeasurePaneView } from './pane-view'; +import { TwoPointDrawing } from '../drawing/two-point-drawing'; + + +export interface MeasureOptions extends DrawingOptions { + fillEnabled: boolean; + fillColor: string; +} + +const defaultBoxOptions = { + fillEnabled: true, + fillColor: 'rgba(255, 255, 255, 0.0)', + + lineColor: '#1E80F0', + lineStyle: LineStyle.Solid, + width: 1, +} + + +export class Measure extends TwoPointDrawing { + _type = "Measure"; + + constructor( + p1: Point, + p2: Point, + options?: Partial + ) { + super(p1, p2, options); + this._options = { + ...defaultBoxOptions, + ...options, + } + this._paneViews = [new MeasurePaneView(this)]; + } + + // autoscaleInfo(startTimePoint: Logical, endTimePoint: Logical): AutoscaleInfo | null { + // const p1Index = this._pointIndex(this._p1); + // const p2Index = this._pointIndex(this._p2); + // if (p1Index === null || p2Index === null) return null; + // if (endTimePoint < p1Index || startTimePoint > p2Index) return null; + // return { + // priceRange: { + // minValue: this._minPrice, + // maxValue: this._maxPrice, + // }, + // }; + // } + + _moveToState(state: InteractionState) { + switch(state) { + case InteractionState.NONE: + document.body.style.cursor = "default"; + this._hovered = false; + this._unsubscribe("mousedown", this._handleMouseDownInteraction); + break; + + case InteractionState.HOVERING: + document.body.style.cursor = "pointer"; + this._hovered = true; + this._unsubscribe("mouseup", this._handleMouseUpInteraction); + this._subscribe("mousedown", this._handleMouseDownInteraction) + this.chart.applyOptions({handleScroll: true}); + break; + + case InteractionState.DRAGGINGP1: + case InteractionState.DRAGGINGP2: + case InteractionState.DRAGGINGP3: + case InteractionState.DRAGGINGP4: + case InteractionState.DRAGGING: + document.body.style.cursor = "grabbing"; + document.body.addEventListener("mouseup", this._handleMouseUpInteraction); + this._subscribe("mouseup", this._handleMouseUpInteraction); + this.chart.applyOptions({handleScroll: false}); + break; + } + this._state = state; + } + + _onDrag(diff: any) { + if (this._state == InteractionState.DRAGGING || this._state == InteractionState.DRAGGINGP1) { + this._addDiffToPoint(this.p1, diff.logical, diff.price); + } + if (this._state == InteractionState.DRAGGING || this._state == InteractionState.DRAGGINGP2) { + this._addDiffToPoint(this.p2, diff.logical, diff.price); + } + if (this._state != InteractionState.DRAGGING) { + if (this._state == InteractionState.DRAGGINGP3) { + this._addDiffToPoint(this.p1, diff.logical, 0); + this._addDiffToPoint(this.p2, 0, diff.price); + } + if (this._state == InteractionState.DRAGGINGP4) { + this._addDiffToPoint(this.p1, 0, diff.price); + this._addDiffToPoint(this.p2, diff.logical, 0); + } + } + } + + protected _onMouseDown() { + this._startDragPoint = null; + const hoverPoint = this._latestHoverPoint; + const p1 = this._paneViews[0]._p1; + const p2 = this._paneViews[0]._p2; + + if (!p1.x || !p2.x || !p1.y || !p2.y) return this._moveToState(InteractionState.DRAGGING); + + const tolerance = 10; + if (Math.abs(hoverPoint.x-p1.x) < tolerance && Math.abs(hoverPoint.y-p1.y) < tolerance) { + this._moveToState(InteractionState.DRAGGINGP1) + } + else if (Math.abs(hoverPoint.x-p2.x) < tolerance && Math.abs(hoverPoint.y-p2.y) < tolerance) { + this._moveToState(InteractionState.DRAGGINGP2) + } + else if (Math.abs(hoverPoint.x-p1.x) < tolerance && Math.abs(hoverPoint.y-p2.y) < tolerance) { + this._moveToState(InteractionState.DRAGGINGP3) + } + else if (Math.abs(hoverPoint.x-p2.x) < tolerance && Math.abs(hoverPoint.y-p1.y) < tolerance) { + this._moveToState(InteractionState.DRAGGINGP4) + } + else { + this._moveToState(InteractionState.DRAGGING); + } + } + + protected _mouseIsOverTwoPointDrawing(param: MouseEventParams, tolerance = 4) { + if (!param.point) return false; + + const x1 = this._paneViews[0]._p1.x; + const y1 = this._paneViews[0]._p1.y; + const x2 = this._paneViews[0]._p2.x; + const y2 = this._paneViews[0]._p2.y; + if (!x1 || !x2 || !y1 || !y2 ) return false; + + const mouseX = param.point.x; + const mouseY = param.point.y; + + const mainX = Math.min(x1, x2); + const mainY = Math.min(y1, y2); + + const width = Math.abs(x1-x2); + const height = Math.abs(y1-y2); + + const halfTolerance = tolerance/2; + + return mouseX > mainX-halfTolerance && mouseX < mainX+width+halfTolerance && + mouseY > mainY-halfTolerance && mouseY < mainY+height+halfTolerance; + } +} + + diff --git a/src/measure/pane-renderer.ts b/src/measure/pane-renderer.ts new file mode 100644 index 00000000..148a0079 --- /dev/null +++ b/src/measure/pane-renderer.ts @@ -0,0 +1,110 @@ +import { ViewPoint } from "../drawing/pane-view"; +import { CanvasRenderingTarget2D } from "fancy-canvas"; +import { TwoPointDrawingPaneRenderer } from "../drawing/pane-renderer"; +import { MeasureOptions } from "./measure"; +import { setLineStyle } from "../helpers/canvas-rendering"; +import { IChartApi, ISeriesApi, SeriesOptionsMap } from "lightweight-charts"; + +export class MeasurePaneRenderer extends TwoPointDrawingPaneRenderer { + declare _options: MeasureOptions; + private series: ISeriesApi; // Declare the property for the box + private chart: IChartApi; // Declare the property for the box + + constructor(series: ISeriesApi, chart: IChartApi, p1: ViewPoint, p2: ViewPoint, options: BoxOptions, showCircles: boolean) { + super(p1, p2, options, showCircles); + this.series = series; + this.chart = chart; + } + + draw(target: CanvasRenderingTarget2D) { + target.useBitmapCoordinateSpace(scope => { + + const ctx = scope.context; + + const scaled = this._getScaledCoordinates(scope); + + if (!scaled) return; + + ctx.lineWidth = this._options.width; + ctx.strokeStyle = this._options.lineColor; + setLineStyle(ctx, this._options.lineStyle); + ctx.fillStyle = this._options.fillColor; + + const mainX = Math.min(scaled.x1, scaled.x2); + const mainY = Math.min(scaled.y1, scaled.y2); + const width = Math.abs(scaled.x1 - scaled.x2); + const height = Math.abs(scaled.y1 - scaled.y2); + + // Draw the rectangle + ctx.strokeRect(mainX, mainY, width, height); + ctx.fillRect(mainX, mainY, width, height); + + // Only proceed if both points have valid data + if (this._p1 && this._p2) { + + if (this._p1.y !== undefined && this._p2.y !== undefined && this._p1.x !== undefined && this._p2.x !== undefined) { + const price1 = this.series.coordinateToPrice(this._p1.y); + const price2 = this.series.coordinateToPrice(this._p2.y); + const time1 =this.chart.timeScale().coordinateToTime(this._p1.x); + const time2 =this.chart.timeScale().coordinateToTime(this._p2.x); + + + // Calculate Price Percentage Difference + const priceDiff = ((price2 - price1) / price1) * 100; + console.log(price1) + console.log(price2) + const priceDiffText = `Price: ${priceDiff.toFixed(2)}%`; + + // Calculate Time Difference + const timeDiffMs = Math.abs(time2 - time1); + const timeDiffText = `Time: ${this._formatTimeDifference(timeDiffMs)}`; + + // Set text styles + ctx.font = "12px Arial"; + ctx.fillStyle = "white"; // You can customize the color + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + + // Calculate positions + const centerX = mainX + width / 2; + const topY = mainY - 10; // 10 pixels above the top edge + const bottomY = mainY + height + 10; // 10 pixels below the bottom edge + + // Draw Price Percentage Difference at the Top + ctx.fillText(priceDiffText, centerX, topY); + + // Draw Time Difference at the Bottom + ctx.fillText(timeDiffText, centerX, bottomY); + } + } + + if (!this._hovered) return; + this._drawEndCircle(scope, mainX, mainY); + this._drawEndCircle(scope, mainX + width, mainY); + this._drawEndCircle(scope, mainX + width, mainY + height); + this._drawEndCircle(scope, mainX, mainY + height); + + + + }); + + } + + /** + * Formats the time difference from milliseconds to a human-readable string. + * You can adjust this function based on your application's requirements. + * @param ms Time difference in milliseconds + * @returns Formatted time difference string + */ + private _formatTimeDifference(ms: number): string { + const seconds = Math.floor(ms); + const minutes = Math.floor(seconds / 60); + const hours = Math.floor(minutes / 60); + const days = Math.floor(hours / 24); + + if (days > 0) return `${days}d ${hours % 24}h`; + if (hours > 0) return `${hours}h ${minutes % 60}m`; + if (minutes > 0) return `${minutes}m ${seconds % 60}s`; + return `${seconds}s`; + } +} \ No newline at end of file diff --git a/src/measure/pane-view.ts b/src/measure/pane-view.ts new file mode 100644 index 00000000..4efa5ac4 --- /dev/null +++ b/src/measure/pane-view.ts @@ -0,0 +1,20 @@ +import { Measure, MeasureOptions } from './measure'; +import { MeasurePaneRenderer } from './pane-renderer'; +import { TwoPointDrawingPaneView } from '../drawing/pane-view'; + +export class MeasurePaneView extends TwoPointDrawingPaneView { + constructor(source: Measure) { + super(source) + } + + renderer() { + return new MeasurePaneRenderer( + this._source._series, // to help convert price coordinates + this._source._chart, // to help convert time coordinates + this._p1, + this._p2, + this._source._options as BoxOptions, + this._source.hovered, + ); + } +} \ No newline at end of file diff --git a/src/tx-series/renderer.ts b/src/tx-series/renderer.ts deleted file mode 100644 index bc2d566e..00000000 --- a/src/tx-series/renderer.ts +++ /dev/null @@ -1,588 +0,0 @@ -import { - BitmapCoordinatesRenderingScope, - CanvasRenderingTarget2D, -} from 'fancy-canvas'; -import { isOHLCData, isSingleValueData } from '../helpers/typeguards'; -import { - customSeriesDefaultOptions, - CustomSeriesOptions, - CustomSeriesPricePlotValues, - ICustomSeriesPaneView, - WhitespaceData, - ICustomSeriesPaneRenderer, - PaneRendererCustomData, - PriceToCoordinateConverter, - Time, - LineStyle, - LineWidth, - ISeriesApi, - SeriesType, - Coordinate, -} from 'lightweight-charts'; -import { setLineStyle } from '../helpers/canvas-rendering'; -import { scaleAlpha } from '../helpers/colors'; -import { ClosestTimeIndexFinder } from '../helpers/closest-index'; - -export interface TradeData { - time: Time; - entry?: number; - stop?: number; - target?: number; - displayInfo?: string; - - action?: 'increase' | 'decrease' | 'close' | 'entry'; - amount?: number; // Relative or absolute depending on mode - - lineWidth?: number; -} - - -export interface TradeSeriesOptions extends CustomSeriesOptions { - side?: 'long' | 'short'; - mode?: 'relative' | 'absolute'; - baseSeries?: ISeriesApi; - auto?: boolean; - entryColor: string; - stopColor: string; - targetColor: string; - backgroundColorStop: string; - backgroundColorTarget: string; - lineWidth: number; - lineStyle: number; // 0 = Solid, 1 = Dotted, 2 = Dashed, etc. - partialClosureLineColor: string; - partialClosureLineWidth: number; - partialClosureLineDash: number[]; - infoTextColor: string; - infoFont: string; - positionChangeColor: string; -} -export const tradeDefaultOptions: TradeSeriesOptions = { - ...customSeriesDefaultOptions, - side: 'long', - mode: 'relative', - auto: false, - entryColor: '#FFFF00', - stopColor: '#FF0000', - targetColor: '#00FF00', - backgroundColorStop: 'rgba(255,0,0,0.25)', - backgroundColorTarget: 'rgba(0,255,0,0.25)', - lineWidth: 1 as LineWidth, - lineStyle: 3 as LineStyle, // Default to solid - partialClosureLineColor: '#FFFFFF', - partialClosureLineWidth: 1, - partialClosureLineDash: [4, 2], - infoTextColor: '#FFFFFF', - infoFont: '12px Arial', - positionChangeColor: '#FFFFFF' -}; - - -export class TradeSeries implements ICustomSeriesPaneView { - private _renderer: TradeSeriesRenderer; - constructor() { - this._renderer = new TradeSeriesRenderer(); - } - - priceValueBuilder(plotRow: TradeData): CustomSeriesPricePlotValues { - const high = Math.max(plotRow.entry ?? NaN, plotRow.stop ?? NaN, plotRow.target ?? NaN); - const low = Math.min(plotRow.entry ?? NaN, plotRow.stop ?? NaN, plotRow.target ?? NaN); - const close = plotRow.entry ?? NaN; - return [high, low, close]; - } - - renderer(): TradeSeriesRenderer { - return this._renderer; - } - - isWhitespace(data: TradeData | WhitespaceData): data is WhitespaceData { - return (data as Partial).entry === undefined; - } - - update( - data: PaneRendererCustomData, - options: TradeSeriesOptions - ): void { - this._renderer.update(data, options); - } - - defaultOptions() { - return tradeDefaultOptions; - } -} -// ------------------------------------- -// Imports -// ------------------------------------- - -// ------------------------------------- -// TradeDataAggregator Class -// ------------------------------------- - -// ------------------------------------- -// TradeDataAggregator Class -// ------------------------------------- - -export class TradeDataAggregator { - private _options: TradeSeriesOptions | null; - - constructor(options: TradeSeriesOptions | null) { - this._options = options; - } - - public aggregate( - data: TradeData[], - priceToCoordinate: PriceToCoordinateConverter - ): Array<{ - entry: number; - stop: number; - target: number; - startIndex: number; - endIndex: number; - isInProgress: boolean; - displayInfo?: string | undefined; - }> { - const aggregatedTrades: Array<{ - entry: number; - stop: number; - target: number; - startIndex: number; - endIndex: number; - isInProgress: boolean; - displayInfo?: string; - }> = []; - let i = 0; - - while (i < data.length) { - const trade = data[i]; - if (trade.action === 'increase' || trade.action === 'entry') { - const startIndex = i; - - // Instead of: - // const endIndex = this._findEndIndex(data, startIndex); - - // Use the cross-based logic: - const endIndex = this._findEndIndexByCross(data, startIndex); - - // If no exit is found, trade is in progress - const isInProgress = endIndex === null; - - const aggregatedTrade = this._aggregateSegment( - data.slice(startIndex, (endIndex ?? data.length - 1) + 1), - startIndex, - endIndex ?? data.length - 1, - priceToCoordinate, - isInProgress - ); - - - - - // Include displayInfo if available in the first trade of the segment - if (data[startIndex].displayInfo) { - aggregatedTrade.displayInfo = data[startIndex].displayInfo; - } - - aggregatedTrades.push(aggregatedTrade); - - // Find the next trade's start index - const nextStartIndex = this._findStartIndex(data, endIndex ?? data.length - 1); - if (nextStartIndex !== null && nextStartIndex > i) { - i = nextStartIndex; - } else { - // Move to the next index if no new trade is found - i = (endIndex ?? data.length - 1) + 1; - } - } else { - // Move to the next trade if no 'increase' or 'entry' is encountered - i++; - } - } - - return aggregatedTrades; - } - - private _aggregateSegment( - segment: TradeData[], - startIndex: number, - endIndex: number, - priceToCoordinate: PriceToCoordinateConverter, - isInProgress: boolean - ): { - entry: number; - stop: number; - target: number; - startIndex: number; - endIndex: number; - isInProgress: boolean; - displayInfo?: string | undefined; - } { - if (segment.length === 0) { - throw new Error('Segment cannot be empty in _aggregateSegment method.'); - } - - // Extract the entry, stop, and target values from the segment - const entry = segment[0].entry ?? NaN; - const stop = segment.reduce( - (maxStop, trade) => Math.max(maxStop, trade.stop ?? 0), - 0 - ); - const target = segment.reduce( - (minTarget, trade) => Math.min(minTarget, trade.target ?? Infinity), - Infinity - ); - - return { - entry: entry, // Raw price value - stop: stop, // Raw price value - target: target, // Raw price value - startIndex, - endIndex, - isInProgress, - displayInfo: segment[0].displayInfo ?? undefined - }; - } - - /** - * Finds the index of the first 'close' action after the given startIndex. - * @param data - Array of TradeData objects. - * @param startIndex - The index to start searching from. - * @returns The index of the 'close' action or null if not found. - */ - private _findEndIndex( - data: TradeData[], - startIndex: number - ): number | null { - for (let i = startIndex + 1; i < data.length; i++) { - if (data[i].action === 'close') { - return i; // Found the closing action - } - } - - return null; // Trade is still open/in progress - } - - /** - * Finds the index of the next trade 'entry' or 'increase' action after the given prevEndIndex. - * @param data - Array of TradeData objects. - * @param prevEndIndex - The index of the previous trade's end. - * @returns The index of the next 'entry' or 'increase' action or null if not found. - */ - private _findStartIndex( - data: TradeData[], - prevEndIndex: number - ): number | null { - for (let i = prevEndIndex + 1; i < data.length; i++) { - const currentAction = data[i].action; - - if (currentAction === 'entry') { - return i; - } - - if (currentAction === 'increase') { - // Determine if this 'increase' signifies a new trade - const isNewTrade = this._isNewTrade(data, i); - if (isNewTrade) { - return i; - } - } - - // Additional logic can be added here for other actions if necessary - } - - return null; // No new trade actions found - } - - /** - * Determines whether an 'increase' action at a given index signifies a new trade. - * This method can be expanded based on more complex trade rules. - * @param data - Array of TradeData objects. - * @param index - The current index to evaluate. - * @returns True if it's a new trade; otherwise, false. - */ - private _isNewTrade(data: TradeData[], index: number): boolean { - // Implement logic to determine if the 'increase' is part of a new trade - // For simplicity, assume it's a new trade if the previous action was 'close' or undefined - if (index === 0) return true; // First action is 'increase' => new trade - - const previousAction = data[index - 1].action; - return previousAction === 'close' || previousAction === undefined; - } - - - private _findEndIndexByCross( - data: TradeData[], - startIndex: number - ): number | null { - const baseBars = this._options?.baseSeries?.data() ?? []; - if (!baseBars.length) return null; - - const trade = data[startIndex]; - const stop = trade.stop; - const target = trade.target; - if (stop == null && target == null) return null; - - // 1) We get the side. If each trade has a side, use `trade.side`; - // otherwise, use `this._options?.side` as fallback - const side = (this._options?.side ?? 'long') as 'long' | 'short'; - - // 2) Match the trade’s start time -> baseBars index - const baseStartIndex = baseBars.findIndex((bar) => bar.time >= trade.time); - if (baseStartIndex < 0) return null; - - // 3) Loop forward in the base series data - for (let i = baseStartIndex; i < baseBars.length; i++) { - const bar = baseBars[i]; - - // If it's an OHLC bar, decide how you read the price - // Usually you'd use `bar.close`, or if it's single-value => `bar.value` - const barPrice = - 'close' in bar ? bar.close : - 'value' in bar ? bar.value : - undefined; - if (barPrice == null) continue; - - // 4) Different crossing logic for 'long' vs. 'short' - if (side === 'long') { - // For a long trade: if barPrice >= target => take profit. if barPrice <= stop => stop out. - if (target != null && barPrice >= target) { - return i; // exit index - } - if (stop != null && barPrice <= stop) { - return i; - } - } else { - // For a short trade: if barPrice <= target => take profit. if barPrice >= stop => stop out. - if (target != null && barPrice <= target) { - return i; - } - if (stop != null && barPrice >= stop) { - return i; - } - } - } - - // If we reach here => never crossed target or stop => trade is open - return null; - } - } - - -// ------------------------------------- -// TradeSeriesRenderer Class -// ------------------------------------- - -/** - * Custom renderer for trade series, utilizing TradeDataAggregator for data aggregation. - */ -// ------------------------------------- -// TradeSeriesRenderer Class -// ------------------------------------- - -export class TradeSeriesRenderer implements ICustomSeriesPaneRenderer { - private _data: PaneRendererCustomData | null = null; - private _options: TradeSeriesOptions | null = null; - private _aggregator: TradeDataAggregator | null = null; - - /** - * Updates the renderer with new data and options. - * @param data - The custom series data to render. - * @param options - The custom series options for styling and behavior. - */ - update( - data: PaneRendererCustomData, - options: TradeSeriesOptions - ): void { - this._data = data; - this._options = options; - this._aggregator = new TradeDataAggregator(options); - } - - /** - * Draws the trade series onto the provided canvas target. - * @param target - The canvas rendering target. - * @param priceConverter - Function to convert price values to canvas coordinates. - */ - draw( - target: CanvasRenderingTarget2D, - priceConverter: PriceToCoordinateConverter - ): void { - if (!this._data || !this._data.bars.length || !this._data.visibleRange || !this._aggregator) { - return; - } - - target.useBitmapCoordinateSpace((scope) => this._drawImpl(scope, priceConverter)); - } - - /** - * Internal implementation of the drawing logic. - * Aggregates trade data and renders the aggregated trades. - * @param renderingScope - The rendering scope containing canvas context and scaling information. - * @param priceToCoordinate - Function to convert price values to canvas coordinates. - */ - private _drawImpl( - renderingScope: BitmapCoordinatesRenderingScope, - priceToCoordinate: PriceToCoordinateConverter - ): void { - if (!this._data || !this._options || !this._aggregator || !this._data.visibleRange) { - return; - } - - const { context: ctx, horizontalPixelRatio, verticalPixelRatio } = renderingScope; - const { from, to } = this._data.visibleRange; - const bars = this._data.bars; - const aggregatedTrades = this._aggregator.aggregate( - bars.map(b => b.originalData).filter(Boolean) as TradeData[], - priceToCoordinate - ); - - ctx.save(); - - aggregatedTrades.forEach(trade => { - // If outside visible bar index range, skip - if (trade.endIndex < from || trade.startIndex > to) { - return; - } - - // Convert bar indices to real chart X - const xStart = bars[trade.startIndex].x * horizontalPixelRatio; - const xEnd = bars[trade.endIndex].x * horizontalPixelRatio; - - // Convert prices to Y - const yEntry = (priceToCoordinate(trade.entry) ?? 0) * verticalPixelRatio; - const yStop = (priceToCoordinate(trade.stop) ?? 0) * verticalPixelRatio; - const yTarget = (priceToCoordinate(trade.target) ?? 0) * verticalPixelRatio; - - // Now xStart/xEnd are correct chart coordinates, so the shape will - // move horizontally as the user pans or zooms the chart. - this._fillArea(ctx, xStart, xEnd, yEntry, yStop, this._options?.backgroundColorStop ?? 'rgba(255,0,0,0.25)'); - this._fillArea(ctx, xStart, xEnd, yEntry, yTarget, this._options?.backgroundColorTarget ?? 'rgba(0,255,0,0.25)'); - - // ...etc. Additional drawing code remains the same... - }); - - ctx.restore(); - } - - /** - * Calculates the current position size for a specific trade. - * @param trade - The aggregated trade data. - * @param mode - Whether the position adjustments are relative or absolute. - * @param tradeDataArray - Array of all trade data. - * @returns The final position size for the trade. - */ - private _calculatePosition( - trade: { - entry: number; - stop: number; - target: number; - startIndex: number; - endIndex: number; - isInProgress: boolean; - displayInfo?: string; - }, - mode: 'relative' | 'absolute', - tradeDataArray: TradeData[] - ): number { - let position = 0; // Initial position - let initialPosition: number | null = null; - - // Iterate over the trade's data between startIndex and endIndex - for (let i = trade.startIndex; i <= trade.endIndex && i < tradeDataArray.length; i++) { - const barData = tradeDataArray[i]; - - if (barData.action === 'increase') { - position = mode === 'relative' - ? position + position * (barData.amount ?? 1) - : position + (barData.amount ?? 1); - - if (initialPosition === null) { - initialPosition = position; - } - } else if (barData.action === 'decrease') { - position = mode === 'relative' - ? position - position * (barData.amount ?? 1) - : position - (barData.amount ?? 1); - } else if (barData.action === 'close') { - position = 0; // Reset position on close - } - } - - console.log(`Trade from index ${trade.startIndex} to ${trade.endIndex}: Initial Position: ${initialPosition}, Final Position: ${position}`); - return position; - } - - /** - * Fills an area between two Y coordinates over a range of X coordinates. - * @param ctx - The canvas rendering context. - * @param xStart - Starting X coordinate. - * @param xEnd - Ending X coordinate. - * @param y1 - First Y coordinate. - * @param y2 - Second Y coordinate. - * @param fillColor - Color to fill the area. - */ - private _fillArea( - ctx: CanvasRenderingContext2D, - xStart: number, - xEnd: number, - y1: number, - y2: number, - fillColor: string - ): void { - const topY = Math.min(y1, y2); - const bottomY = Math.max(y1, y2); - - const gradient = ctx.createLinearGradient(0, topY, 0, bottomY); - const entryAtTop = (y1 === topY); - - if (entryAtTop) { - gradient.addColorStop(0, 'rgba(0,0,0,0)'); - gradient.addColorStop(1, fillColor); - } else { - gradient.addColorStop(0, fillColor); - gradient.addColorStop(1, 'rgba(0,0,0,0)'); - } - - ctx.fillStyle = gradient; - ctx.beginPath(); - ctx.rect(xStart, topY, xEnd - xStart, bottomY - topY); - ctx.fill(); - } - - -private _findEndIndexByCross( - tradeData: TradeData[], - startIndex: number -): number | null { - const baseBars = this._options?.baseSeries?.data() ?? []; - if (!baseBars.length) return null; - - const trade = tradeData[startIndex]; - const stop = trade.stop; - const target = trade.target; - - if (stop == null && target == null) return null; - - // Step 1: find base bar index by time - const baseIndex = baseBars.findIndex((bar) => bar.time >= trade.time); - if (baseIndex < 0) return null; - - // Step 2: loop from baseIndex forward - for (let i = baseIndex; i < baseBars.length; i++) { - const bar = baseBars[i]; - let barPrice = 'close' in bar ? bar.close : bar.value; - if (barPrice == null) continue; - - // target hit - if (target != null && barPrice >= target) { - return i; // we define 'endIndex' in terms of baseBars indices - } - - // stop hit - if (stop != null && barPrice <= stop) { - return i; - } - } - - return null; // never crossed => in progress -} - -} \ No newline at end of file