From 54642f85d5da8831b5f1b0c5f83e010627a5c5bf Mon Sep 17 00:00:00 2001 From: EsIstJosh Date: Wed, 9 Apr 2025 01:30:40 -0700 Subject: [PATCH 1/7] minor fixes --- a | 1 - {src/general/defaults => defaults}/area.json | 0 {src/general/defaults => defaults}/bar.json | 0 .../defaults => defaults}/candlestick.json | 0 {src/general/defaults => defaults}/chart.json | 0 .../defaults => defaults}/histogram.json | 0 {src/general/defaults => defaults}/line.json | 0 {src/general/defaults => defaults}/ohlc.json | 0 .../defaults => defaults}/pitchfork.json | 0 .../defaults => defaults}/trend-trace.json | 0 .../defaults => defaults}/volume-profile.json | 0 lightweight_charts/abstract.py | 216 +- lightweight_charts/chart.py | 15 +- lightweight_charts/js/bundle.js | 5 +- lightweight_charts/js/styles.css | 24 +- lightweight_charts_/js/bundle.js | 1 - lightweight_charts_/js/index.html | 24 - lightweight_charts_/js/lightweight-charts.js | 7 - lightweight_charts_/js/styles.css | 244 -- ohlcv.csv | 2982 +++++++++++++++++ package-lock.json | 12 + run.py | 54 + {src/general/scripts => scripts}/Symbols.json | 0 {src/general/scripts => scripts}/cache.json | 0 setup.py | 2 +- src/general/handler.ts | 6 +- src/trend-trace/trend-trace.ts | 2 +- 27 files changed, 3152 insertions(+), 443 deletions(-) delete mode 100644 a rename {src/general/defaults => defaults}/area.json (100%) rename {src/general/defaults => defaults}/bar.json (100%) rename {src/general/defaults => defaults}/candlestick.json (100%) rename {src/general/defaults => defaults}/chart.json (100%) rename {src/general/defaults => defaults}/histogram.json (100%) rename {src/general/defaults => defaults}/line.json (100%) rename {src/general/defaults => defaults}/ohlc.json (100%) rename {src/general/defaults => defaults}/pitchfork.json (100%) rename {src/general/defaults => defaults}/trend-trace.json (100%) rename {src/general/defaults => defaults}/volume-profile.json (100%) delete mode 100644 lightweight_charts_/js/bundle.js delete mode 100644 lightweight_charts_/js/index.html delete mode 100644 lightweight_charts_/js/lightweight-charts.js delete mode 100644 lightweight_charts_/js/styles.css create mode 100644 ohlcv.csv create mode 100644 run.py rename {src/general/scripts => scripts}/Symbols.json (100%) rename {src/general/scripts => scripts}/cache.json (100%) diff --git a/a b/a deleted file mode 100644 index 8b137891..00000000 --- a/a +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/general/defaults/area.json b/defaults/area.json similarity index 100% rename from src/general/defaults/area.json rename to defaults/area.json diff --git a/src/general/defaults/bar.json b/defaults/bar.json similarity index 100% rename from src/general/defaults/bar.json rename to defaults/bar.json diff --git a/src/general/defaults/candlestick.json b/defaults/candlestick.json similarity index 100% rename from src/general/defaults/candlestick.json rename to defaults/candlestick.json diff --git a/src/general/defaults/chart.json b/defaults/chart.json similarity index 100% rename from src/general/defaults/chart.json rename to defaults/chart.json diff --git a/src/general/defaults/histogram.json b/defaults/histogram.json similarity index 100% rename from src/general/defaults/histogram.json rename to defaults/histogram.json diff --git a/src/general/defaults/line.json b/defaults/line.json similarity index 100% rename from src/general/defaults/line.json rename to defaults/line.json diff --git a/src/general/defaults/ohlc.json b/defaults/ohlc.json similarity index 100% rename from src/general/defaults/ohlc.json rename to defaults/ohlc.json diff --git a/src/general/defaults/pitchfork.json b/defaults/pitchfork.json similarity index 100% rename from src/general/defaults/pitchfork.json rename to defaults/pitchfork.json diff --git a/src/general/defaults/trend-trace.json b/defaults/trend-trace.json similarity index 100% rename from src/general/defaults/trend-trace.json rename to defaults/trend-trace.json diff --git a/src/general/defaults/volume-profile.json b/defaults/volume-profile.json similarity index 100% rename from src/general/defaults/volume-profile.json rename to defaults/volume-profile.json diff --git a/lightweight_charts/abstract.py b/lightweight_charts/abstract.py index f554f6bb..7e5a980c 100644 --- a/lightweight_charts/abstract.py +++ b/lightweight_charts/abstract.py @@ -6,7 +6,8 @@ from typing import Callable, Union, Literal, List, Optional, Any import pandas as pd from webview.errors import JavascriptException - +import shutil +from typing import Optional from .table import Table from .toolbox import ToolBox from .drawings import Box, HorizontalLine, RayLine, TrendLine, TwoPointDrawing, VerticalLine, VerticalSpan @@ -1107,80 +1108,71 @@ def _get_time_or_last_bar(self, time: Optional[Any]) -> str: return self._convert_time(last_bar_time) + 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 = './defaults', scripts: str = './scripts'): + defaults: str = '../../src/general/defaults', scripts: str = '../../src/general/scripts'): Pane.__init__(self, window) + Candlestick.__init__(self, self) self._lines = [] self._scale_candles_only = scale_candles_only self._width = width self._height = height self.events: Events = Events(self) - from lightweight_charts.polygon import PolygonAPI + + # Initialize PolygonAPI instance self.polygon: PolygonAPI = PolygonAPI(self) + # Initialize Lib.Handler JavaScript instance self.run_script( f'{self.id} = new Lib.Handler("{self.id}", {width}, {height}, "{position}", {jbool(autosize)})' ) - Candlestick.__init__(self, self) - self.topbar: TopBar = TopBar(self) if toolbox: self.toolbox: ToolBox = ToolBox(self) - # Ensure the defaults folder exists. - if defaults: - if not os.path.exists(defaults): - os.makedirs(defaults, exist_ok=True) - self.defaults = defaults - self.set_defaults(defaults) - self.win.handlers['save_defaults'] = self._save_defaults - self.events.save_defaults += self._save_defaults - - # Ensure the scripts folder exists. - if scripts: - if not os.path.exists(scripts): - os.makedirs(scripts, exist_ok=True) - self.scripts = scripts - self.set_scripts(scripts) - self.win.handlers['save_script'] = self._save_script - self.events.save_script += self._save_script + # Set and initialize defaults directory + 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) + self.set_defaults(self.defaults) + + # Handlers for defaults + self.win.handlers['save_defaults'] = self._save_defaults + self.events.save_defaults += self._save_defaults + + # Set and initialize scripts directory + 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) + self.set_scripts(self.scripts) + + # Handlers for scripts + self.win.handlers['save_script'] = self._save_script + self.events.save_script += self._save_script + def _save_script(self, key: str, options: str) -> None: - """ - Callback method that receives a key and a JSON string of script options. - It parses the JSON and saves the resulting object in self.exportedScripts. - Then writes it to disk in the scripts folder. If a file named `.json` already exists, - it is overwritten; otherwise, a new file is created. - - This method can be invoked via a JS callback similar to: - window.callbackFunction("save_script__~_") - - :param key: The key under which to store the script. - :param options: A JSON string containing the script options. - """ + """Save script JSON data to memory and disk.""" try: - # Parse the options JSON string. parsed_options = json.loads(options) - # Save to memory. if not hasattr(self, 'exportedScripts'): self.exportedScripts = {} self.exportedScripts[key] = parsed_options - print(f"Saved script for key '{key}' in memory: {parsed_options}") - # Determine the folder to save scripts. - # Use self.scripts if provided; otherwise, default to a folder named "./scripts". - scripts_folder = self.scripts if isinstance(self.scripts, str) and self.scripts != '' else "./scripts" - # Ensure the folder exists. + scripts_folder = self.scripts if isinstance(self.scripts, str) and self.scripts else "./scripts" if not os.path.exists(scripts_folder): os.makedirs(scripts_folder) - # Build the file path. + file_path = os.path.join(scripts_folder, f"{key}.json") - # Write the parsed options to the file (pretty-printed). with open(file_path, "w", encoding="utf-8") as f: json.dump(parsed_options, f, indent=2) print(f"Script for key '{key}' written to disk at: {file_path}") @@ -1188,141 +1180,71 @@ def _save_script(self, key: str, options: str) -> None: print(f"Error saving script for key '{key}': {e}") def _save_defaults(self, key: str, options: str) -> None: - """ - Callback method that receives a key and a JSON string of options. - It parses the JSON and saves the resulting object in self.exportedDefaults. - Then writes it to disk in the defaults folder. If a file named `.json` already exists, - it is overwritten; otherwise, a new file is created. + """Save defaults JSON data to memory and disk.""" + try: + parsed_options = json.loads(options) + if not hasattr(self, 'exportedDefaults'): + self.exportedDefaults = {} + self.exportedDefaults[key] = parsed_options - This method is invoked via a JS callback like: - window.callbackFunction("save_defaults__~_") + defaults_folder = self.defaults if isinstance(self.defaults, str) else "./defaults" + if not os.path.exists(defaults_folder): + os.makedirs(defaults_folder) - :param key: The key under which to store the defaults. - :param options: A JSON string containing the options. - """ - try: - # Parse the options JSON string. - parsed_options = json.loads(options) - # Save to memory. - if not hasattr(self, 'exportedDefaults'): - self.exportedDefaults = {} - self.exportedDefaults[key] = parsed_options - print(f"Saved defaults for key '{key}' in memory: {parsed_options}") - - # Determine the folder to save defaults. - # Here we assume that self.defaults holds the defaults folder path (passed in via the constructor) - # Otherwise, default to a folder named "./defaults". - defaults_folder = self.defaults if isinstance(self.defaults, str) else "./defaults" - # Ensure the folder exists. - if not os.path.exists(defaults_folder): - os.makedirs(defaults_folder) - # Build the file path. - file_path = os.path.join(defaults_folder, f"{key}.json") - # Write the parsed options to the file (pretty-printed). - with open(file_path, "w", encoding="utf-8") as f: - json.dump(parsed_options, f, indent=2) - print(f"Defaults for key '{key}' written to disk at: {file_path}") - except Exception as e: - print(f"Error saving defaults for key '{key}': {e}") + file_path = os.path.join(defaults_folder, f"{key}.json") + with open(file_path, "w", encoding="utf-8") as f: + json.dump(parsed_options, f, indent=2) + print(f"Defaults for key '{key}' written to disk at: {file_path}") + except Exception as e: + print(f"Error saving defaults for key '{key}': {e}") def set_scripts(self, scripts_dir: str) -> None: """ - Recursively loads all JSON script files from the provided directory and applies them - to the chart's scriptsManager via run_script. In addition, if a file with key "chart" - is encountered, its options are applied to the chart via chart.applyOptions. - - Assumes that: - - self has an 'id' property that is used in JS. - - self has a method 'run_script' that executes JS code. - - In the JS environment, the handler instance (referenced by self.id) - already has a 'scriptsManager' property with a set method, - and a 'chart' property with an applyOptions method. - - :param scripts_dir: The directory where JSON script files reside. + Load and apply JSON scripts from directory to the scriptsManager. """ - # Recursively walk through the directory. - for root, dirs, files in os.walk(scripts_dir): + for root, _, files in os.walk(scripts_dir): for filename in files: if filename.endswith('.json'): - # Use the filename (without extension) as the key. key = os.path.splitext(filename)[0] file_path = os.path.join(root, filename) try: with open(file_path, 'r', encoding="utf-8") as f: data = json.load(f) - except Exception as e: - print(f"Error loading {file_path}: {e}") - continue - - # Convert the Python dict to a JSON string. - json_data = json.dumps(data) - # Construct a JS snippet to call scriptsManager.set on the chart's id. - js_code = f''' - {self.id}.scriptsManager.set("{key}", {json_data}); - ''' - try: - # Execute the JS code in the browser/webview. + json_data = json.dumps(data) + js_code = f'{self.id}.scriptsManager.set("{key}", {json_data});' self.run_script(js_code) print(f"Set script for key '{key}' successfully.") except Exception as e: - print(f"Error running script for key '{key}': {e}") + print(f"Error processing script '{file_path}': {e}") def set_defaults(self, defaults_dir: str) -> None: """ - Recursively loads all JSON default files from the provided directory and applies them - to the chart's defaultManager via run_script. In addition, if a file with key "chart" - is encountered, its options are applied to the chart via chart.applyOptions. - - Assumes that: - - self has an 'id' property that is used in JS. - - self has a method 'run_script' that executes JS code. - - In the JS environment, the handler instance (referenced by self.id) - already has a 'defaultManager' property with a set method, - and a 'chart' property with an applyOptions method. - - :param defaults_dir: The directory where JSON default files reside. + Load and apply JSON defaults from directory to the defaultsManager. + Special handling for "chart.json". """ - # Recursively walk through the directory. - for root, dirs, files in os.walk(defaults_dir): + for root, _, files in os.walk(defaults_dir): for filename in files: if filename.endswith('.json'): - # Use the filename (without extension) as the key. key = os.path.splitext(filename)[0] file_path = os.path.join(root, filename) try: - with open(file_path, 'r') as f: + with open(file_path, 'r', encoding="utf-8") as f: data = json.load(f) - except Exception as e: - print(f"Error loading {file_path}: {e}") - continue - - # Convert the Python dict to a JSON string. - json_data = json.dumps(data) - # Construct a JS snippet to call defaultManager.set on the chart's id. - js_code = f''' - {self.id}.defaultsManager.set("{key}", {json_data}); - ''' - try: - # Execute the JS code in the browser/webview. + json_data = json.dumps(data) + js_code = f'{self.id}.defaultsManager.set("{key}", {json_data});' self.run_script(js_code) print(f"Set defaults for key '{key}' successfully.") + + if key.lower() == "chart": + js_apply = f'{self.id}.chart.applyOptions({{ ...{self.id}.defaultsManager.get("chart") }});' + self.run_script(js_apply) + print("Applied chart defaults successfully.") except Exception as e: - print(f"Error running script for key '{key}': {e}") - - # If the key is "chart", apply the chart defaults. - if key.lower() == "chart": - # Using spread syntax to ensure we apply all properties. - js_apply = f''' - {self.id}.chart.applyOptions({{ ...{self.id}.defaultsManager.get("chart") }}); - ''' - try: - self.run_script(js_apply) - print("Applied chart defaults successfully.") - except Exception as e: - print(f"Error applying chart defaults: {e}") + print(f"Error processing defaults '{file_path}': {e}") + def fit(self): """ - Fits the maximum amount of the chart data within the viewport. + Fits chart data within the viewport. """ self.run_script(f'{self.id}.chart.timeScale().fitContent()') diff --git a/lightweight_charts/chart.py b/lightweight_charts/chart.py index d1bee6a1..cf9448e8 100644 --- a/lightweight_charts/chart.py +++ b/lightweight_charts/chart.py @@ -5,9 +5,8 @@ import webview from webview.errors import JavascriptException -from lightweight_charts import abstract from .util import parse_event_message, FLOAT - +from .abstract import AbstractChart, Window, INDEX import os import threading @@ -49,7 +48,7 @@ def create_window( self.windows.append(webview.create_window( title, - url=abstract.INDEX, + url=INDEX, js_api=self.callback_api, width=width, height=height, @@ -147,7 +146,7 @@ def exit(self): self._reset() -class Chart(abstract.AbstractChart): +class Chart(AbstractChart): _main_window_handlers = None WV: WebviewHandler = WebviewHandler() @@ -175,21 +174,21 @@ def __init__( width, height, x, y, screen, on_top, maximize, title ) - window = abstract.Window( + window = Window( script_func=lambda s: Chart.WV.evaluate_js(self._i, s), js_api_code='pywebview.api.callback' ) - abstract.Window._return_q = Chart.WV.return_queue + Window._return_q = Chart.WV.return_queue self.is_alive = True if Chart._main_window_handlers is None: - super().__init__(window, inner_width, inner_height, scale_candles_only, toolbox, position=position, defaults= defaults) + super().__init__(window, inner_width, inner_height, scale_candles_only, toolbox, position=position, defaults= defaults, scripts = scripts) Chart._main_window_handlers = self.win.handlers else: window.handlers = Chart._main_window_handlers - super().__init__(window, inner_width, inner_height, scale_candles_only, toolbox, position=position, defaults= defaults) + super().__init__(window, inner_width, inner_height, scale_candles_only, toolbox, position=position, defaults= defaults, scripts = scripts) def show(self, block: bool = False): """ diff --git a/lightweight_charts/js/bundle.js b/lightweight_charts/js/bundle.js index 3bf62e51..4acc766d 100644 --- a/lightweight_charts/js/bundle.js +++ b/lightweight_charts/js/bundle.js @@ -1,4 +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){const t=e.match(/rgba?\(([^)]+)\)/i),i=e.match(/hsla?\(([^)]+)\)/i);let s=1;if(t){const e=t[1].split(",").map((e=>parseFloat(e.trim())));4===e.length&&(s=e[3])}else if(i){const e=i[1].split(",").map((e=>parseFloat(e.trim())));4===e.length&&(s=e[3])}return s}function p(e,t,i=""){for(const s of Object.keys(e)){const n=i?`${i}.${s}`:s,o=e[s];"object"==typeof o&&null!==o?p(o,t,n):s.toLowerCase().includes("color")&&t(n,o)}}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}}function R(e,t){const i=e.split("."),s={};let n=s;for(let e=0;ee.toUpperCase()))}function $(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 G(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 F(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 j(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 U(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 z(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 H(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 W(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 q(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()}class X{_options;constructor(e){this._options=e}}class J extends X{_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 Y extends X{_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()}}var K=[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],Q=[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],Z="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲊᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꟍꟐꟑꟓꟕ-Ƛꟲ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",ee={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"},te="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",ie={5:te,"5module":te+" export import",6:te+" const class extends export import super"},se=/^in(stanceof)?$/,ne=new RegExp("["+Z+"]"),oe=new RegExp("["+Z+"‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࢗ-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-ᫎᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・]");function re(e,t){for(var i=65536,s=0;se)return!1;if((i+=t[s+1])>=e)return!0}return!1}function ae(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&ne.test(String.fromCharCode(e)):!1!==t&&re(e,Q)))}function le(e,t){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&oe.test(String.fromCharCode(e)):!1!==t&&(re(e,Q)||re(e,K)))))}var ce=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 he(e,t){return new ce(e,{beforeExpr:!0,binop:t})}var pe={beforeExpr:!0},de={startsExpr:!0},ue={};function me(e,t){return void 0===t&&(t={}),t.keyword=e,ue[e]=new ce(e,t)}var ge={num:new ce("num",de),regexp:new ce("regexp",de),string:new ce("string",de),name:new ce("name",de),privateId:new ce("privateId",de),eof:new ce("eof"),bracketL:new ce("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new ce("]"),braceL:new ce("{",{beforeExpr:!0,startsExpr:!0}),braceR:new ce("}"),parenL:new ce("(",{beforeExpr:!0,startsExpr:!0}),parenR:new ce(")"),comma:new ce(",",pe),semi:new ce(";",pe),colon:new ce(":",pe),dot:new ce("."),question:new ce("?",pe),questionDot:new ce("?."),arrow:new ce("=>",pe),template:new ce("template"),invalidTemplate:new ce("invalidTemplate"),ellipsis:new ce("...",pe),backQuote:new ce("`",de),dollarBraceL:new ce("${",{beforeExpr:!0,startsExpr:!0}),eq:new ce("=",{beforeExpr:!0,isAssign:!0}),assign:new ce("_=",{beforeExpr:!0,isAssign:!0}),incDec:new ce("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new ce("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:he("||",1),logicalAND:he("&&",2),bitwiseOR:he("|",3),bitwiseXOR:he("^",4),bitwiseAND:he("&",5),equality:he("==/!=/===/!==",6),relational:he("/<=/>=",7),bitShift:he("<>/>>>",8),plusMin:new ce("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:he("%",10),star:he("*",10),slash:he("/",10),starstar:new ce("**",{beforeExpr:!0}),coalesce:he("??",1),_break:me("break"),_case:me("case",pe),_catch:me("catch"),_continue:me("continue"),_debugger:me("debugger"),_default:me("default",pe),_do:me("do",{isLoop:!0,beforeExpr:!0}),_else:me("else",pe),_finally:me("finally"),_for:me("for",{isLoop:!0}),_function:me("function",de),_if:me("if"),_return:me("return",pe),_switch:me("switch"),_throw:me("throw",pe),_try:me("try"),_var:me("var"),_const:me("const"),_while:me("while",{isLoop:!0}),_with:me("with"),_new:me("new",{beforeExpr:!0,startsExpr:!0}),_this:me("this",de),_super:me("super",de),_class:me("class",de),_extends:me("extends",pe),_export:me("export"),_import:me("import",de),_null:me("null",de),_true:me("true",de),_false:me("false",de),_in:me("in",{beforeExpr:!0,binop:7}),_instanceof:me("instanceof",{beforeExpr:!0,binop:7}),_typeof:me("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:me("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:me("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},fe=/\r\n?|\n|\u2028|\u2029/,ye=new RegExp(fe.source,"g");function be(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 Ie=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,Ae=function(e,t){this.line=e,this.column=t};Ae.prototype.offset=function(e){return new Ae(this.line,this.column+e)};var De=function(e,t,i){this.start=t,this.end=i,null!==e.sourceFile&&(this.source=e.sourceFile)};function Le(e,t){for(var i=1,s=0;;){var n=ve(e,s,t);if(n<0)return new Ae(i,t-s);++i,s=n}}var Ne={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},Oe=!1;function Ve(e){var t={};for(var i in Ne)t[i]=e&&ke(e,i)?e[i]:Ne[i];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!Oe&&"object"==typeof console&&console.warn&&(Oe=!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),Ee(t.onToken)){var s=t.onToken;t.onToken=function(e){return s.push(e)}}return Ee(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 De(this,r,a)),e.ranges&&(l.range=[n,o]),t.push(l)}}(t,t.onComment)),t}var Re=256;function Be(e,t){return 2|(e?4:0)|(t?8:0)}var $e=function(e,t,i){this.options=e=Ve(e),this.sourceFile=e.sourceFile,this.keywords=Pe(ie[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var s="";!0!==e.allowReserved&&(s=ee[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(s+=" await")),this.reservedWords=Pe(s);var n=(s?s+" ":"")+ee.strict;this.reservedWordsStrict=Pe(n),this.reservedWordsStrictBind=Pe(n+" "+ee.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(fe).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=ge.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=[]},Ge={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}};$e.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},Ge.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},Ge.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},Ge.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},Ge.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&Re)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},Ge.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,i=e.inClassFieldInit;return(64&t)>0||i||this.options.allowSuperOutsideMethod},Ge.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},Ge.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},Ge.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,i=e.inClassFieldInit;return(258&t)>0||i},Ge.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&Re)>0},$e.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,_e.lastIndex=e,e+=_e.exec(this.input)[0].length,";"===this.input[e]&&e++}},Fe.eat=function(e){return this.type===e&&(this.next(),!0)},Fe.isContextual=function(e){return this.type===ge.name&&this.value===e&&!this.containsEsc},Fe.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},Fe.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},Fe.canInsertSemicolon=function(){return this.type===ge.eof||this.type===ge.braceR||fe.test(this.input.slice(this.lastTokEnd,this.start))},Fe.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},Fe.semicolon=function(){this.eat(ge.semi)||this.insertSemicolon()||this.unexpected()},Fe.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},Fe.expect=function(e){this.eat(e)||this.unexpected()},Fe.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var Ue=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};Fe.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")}},Fe.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")},Fe.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&s<56320)return!0;if(ae(s,!0)){for(var n=i+1;le(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},ze.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_e.lastIndex=this.pos;var e,t=_e.exec(this.input),i=this.pos+t[0].length;return!(fe.test(this.input.slice(this.pos,i))||"function"!==this.input.slice(i,i+8)||i+8!==this.input.length&&(le(e=this.input.charCodeAt(i+8))||e>55295&&e<56320))},ze.parseStatement=function(e,t,i){var s,n=this.type,o=this.startNode();switch(this.isLet(e)&&(n=ge._var,s="let"),n){case ge._break:case ge._continue:return this.parseBreakContinueStatement(o,n.keyword);case ge._debugger:return this.parseDebuggerStatement(o);case ge._do:return this.parseDoStatement(o);case ge._for:return this.parseForStatement(o);case ge._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(o,!1,!e);case ge._class:return e&&this.unexpected(),this.parseClass(o,!0);case ge._if:return this.parseIfStatement(o);case ge._return:return this.parseReturnStatement(o);case ge._switch:return this.parseSwitchStatement(o);case ge._throw:return this.parseThrowStatement(o);case ge._try:return this.parseTryStatement(o);case ge._const:case ge._var:return s=s||this.value,e&&"var"!==s&&this.unexpected(),this.parseVarStatement(o,s);case ge._while:return this.parseWhileStatement(o);case ge._with:return this.parseWithStatement(o);case ge.braceL:return this.parseBlock(!0,o);case ge.semi:return this.parseEmptyStatement(o);case ge._export:case ge._import:if(this.options.ecmaVersion>10&&n===ge._import){_e.lastIndex=this.pos;var r=_e.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===ge._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===ge.name&&"Identifier"===h.type&&this.eat(ge.colon)?this.parseLabeledStatement(o,c,h,e):this.parseExpressionStatement(o,h)}},ze.parseBreakContinueStatement=function(e,t){var i="break"===t;this.next(),this.eat(ge.semi)||this.insertSemicolon()?e.label=null:this.type!==ge.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var s=0;s=6?this.eat(ge.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},ze.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(He),this.enterScope(0),this.expect(ge.parenL),this.type===ge.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var i=this.isLet();if(this.type===ge._var||this.type===ge._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===ge._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===s.declarations.length?(this.options.ecmaVersion>=9&&(this.type===ge._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 Ue,c=this.start,h=t>-1?this.parseExprSubscripts(l,"await"):this.parseExpression(!0,l);return this.type===ge._in||(r=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===ge._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))},ze.parseFunctionStatement=function(e,t,i){return this.next(),this.parseFunction(e,Xe|(i?0:Je),!1,t)},ze.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(ge._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},ze.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(ge.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},ze.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(ge.braceL),this.labels.push(We),this.enterScope(0);for(var i=!1;this.type!==ge.braceR;)if(this.type===ge._case||this.type===ge._default){var s=this.type===ge._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(ge.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")},ze.parseThrowStatement=function(e){return this.next(),fe.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 qe=[];ze.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(ge.parenR),e},ze.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===ge._catch){var t=this.startNode();this.next(),this.eat(ge.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(ge._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},ze.parseVarStatement=function(e,t,i){return this.next(),this.parseVar(e,!1,t,i),this.semicolon(),this.finishNode(e,"VariableDeclaration")},ze.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(He),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},ze.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")},ze.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},ze.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")},ze.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},ze.parseBlock=function(e,t,i){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(ge.braceL),e&&this.enterScope(0);this.type!==ge.braceR;){var s=this.parseStatement(null);t.body.push(s)}return i&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},ze.parseFor=function(e,t){return e.init=t,this.expect(ge.semi),e.test=this.type===ge.semi?null:this.parseExpression(),this.expect(ge.semi),e.update=this.type===ge.parenR?null:this.parseExpression(),this.expect(ge.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},ze.parseForIn=function(e,t){var i=this.type===ge._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(ge.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,i?"ForInStatement":"ForOfStatement")},ze.parseVar=function(e,t,i,s){for(e.declarations=[],e.kind=i;;){var n=this.startNode();if(this.parseVarId(n,i),this.eat(ge.eq)?n.init=this.parseMaybeAssign(t):s||"const"!==i||this.type===ge._in||this.options.ecmaVersion>=6&&this.isContextual("of")?s||"Identifier"===n.id.type||t&&(this.type===ge._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(ge.comma))break}return e},ze.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var Xe=1,Je=2;function Ye(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 Ke(e,t){var i=e.computed,s=e.key;return!i&&("Identifier"===s.type&&s.name===t||"Literal"===s.type&&s.value===t)}ze.parseFunction=function(e,t,i,s,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!s)&&(this.type===ge.star&&t&Je&&this.unexpected(),e.generator=this.eat(ge.star)),this.options.ecmaVersion>=8&&(e.async=!!s),t&Xe&&(e.id=4&t&&this.type!==ge.name?null:this.parseIdent(),!e.id||t&Je||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(Be(e.async,e.generator)),t&Xe||(e.id=this.type===ge.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&Xe?"FunctionDeclaration":"FunctionExpression")},ze.parseFunctionParams=function(e){this.expect(ge.parenL),e.params=this.parseBindingList(ge.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},ze.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(ge.braceL);this.type!==ge.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&&Ye(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")},ze.parseClassElement=function(e){if(this.eat(ge.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(ge.braceL))return this.parseClassStaticBlock(i),i;this.isClassElementNameStart()||this.type===ge.star?a=!0:s="static"}if(i.static=a,!s&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==ge.star||this.canInsertSemicolon()?s="async":o=!0),!s&&(t>=9||!o)&&this.eat(ge.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===ge.parenL||"method"!==r||n||o){var c=!i.static&&Ke(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},ze.isClassElementNameStart=function(){return this.type===ge.name||this.type===ge.privateId||this.type===ge.num||this.type===ge.string||this.type===ge.bracketL||this.type.keyword},ze.parseClassElementName=function(e){this.type===ge.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)},ze.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&&Ke(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")},ze.parseClassField=function(e){if(Ke(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&Ke(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(ge.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")},ze.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==ge.braceR;){var i=this.parseStatement(null);e.body.push(i)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},ze.parseClassId=function(e,t){this.type===ge.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},ze.parseClassSuper=function(e){e.superClass=this.eat(ge._extends)?this.parseExprSubscripts(null,!1):null},ze.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},ze.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!==ge.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},ze.parseExport=function(e,t){if(this.next(),this.eat(ge.star))return this.parseExportAllDeclaration(e,t);if(this.eat(ge._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!==ge.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")},ze.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")},ze.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},ze.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")},ze.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===ge.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(ge.comma)))return e;if(this.type===ge.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(ge.braceL);!this.eat(ge.braceR);){if(t)t=!1;else if(this.expect(ge.comma),this.afterTrailingComma(ge.braceR))break;e.push(this.parseImportSpecifier())}return e},ze.parseWithClause=function(){var e=[];if(!this.eat(ge._with))return e;this.expect(ge.braceL);for(var t={},i=!0;!this.eat(ge.braceR);){if(i)i=!1;else if(this.expect(ge.comma),this.afterTrailingComma(ge.braceR))break;var s=this.parseImportAttribute(),n="Identifier"===s.key.type?s.key.name:s.key.value;ke(t,n)&&this.raiseRecoverable(s.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(s)}return e},ze.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===ge.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(ge.colon),this.type!==ge.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},ze.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===ge.string){var e=this.parseLiteral(this.value);return Ie.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},ze.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 Qe=$e.prototype;Qe.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(ge._function))return this.overrideContext(et.f_expr),this.parseFunction(this.startNodeAt(o,r),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(ge.arrow))return this.parseArrowExpression(this.startNodeAt(o,r),[l],!1,t);if(this.options.ecmaVersion>=8&&"async"===l.name&&this.type===ge.name&&!a&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return l=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(ge.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(o,r),[l],!0,t)}return l;case ge.regexp:var c=this.value;return(s=this.parseLiteral(c.value)).regex={pattern:c.pattern,flags:c.flags},s;case ge.num:case ge.string:return this.parseLiteral(this.value);case ge._null:case ge._true:case ge._false:return(s=this.startNode()).value=this.type===ge._null?null:this.type===ge._true,s.raw=this.type.keyword,this.next(),this.finishNode(s,"Literal");case ge.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 ge.bracketL:return s=this.startNode(),this.next(),s.elements=this.parseExprList(ge.bracketR,!0,!0,e),this.finishNode(s,"ArrayExpression");case ge.braceL:return this.overrideContext(et.b_expr),this.parseObj(!1,e);case ge._function:return s=this.startNode(),this.next(),this.parseFunction(s,0);case ge._class:return this.parseClass(this.startNode(),!1);case ge._new:return this.parseNew();case ge.backQuote:return this.parseTemplate();case ge._import:return this.options.ecmaVersion>=11?this.parseExprImport(i):this.unexpected();default:return this.parseExprAtomDefault()}},it.parseExprAtomDefault=function(){this.unexpected()},it.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===ge.parenL&&!e)return this.parseDynamicImport(t);if(this.type===ge.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()},it.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(ge.parenR)?e.options=null:(this.expect(ge.comma),this.afterTrailingComma(ge.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(ge.parenR)||(this.expect(ge.comma),this.afterTrailingComma(ge.parenR)||this.unexpected())));else if(!this.eat(ge.parenR)){var t=this.start;this.eat(ge.comma)&&this.eat(ge.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},it.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")},it.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")},it.parseParenExpression=function(){this.expect(ge.parenL);var e=this.parseExpression();return this.expect(ge.parenR),e},it.shouldParseArrow=function(e){return!this.canInsertSemicolon()},it.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 Ue,u=this.yieldPos,m=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==ge.parenR;){if(h?h=!1:this.expect(ge.comma),o&&this.afterTrailingComma(ge.parenR,!0)){p=!0;break}if(this.type===ge.ellipsis){r=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===ge.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(ge.parenR),e&&this.shouldParseArrow(c)&&this.eat(ge.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},it.parseParenItem=function(e){return e},it.parseParenArrowList=function(e,t,i,s){return this.parseArrowExpression(this.startNodeAt(e,t),i,!1,s)};var ot=[];it.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===ge.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(ge.parenL)?e.arguments=this.parseExprList(ge.parenR,this.options.ecmaVersion>=8,!1):e.arguments=ot,this.finishNode(e,"NewExpression")},it.parseTemplateElement=function(e){var t=e.isTagged,i=this.startNode();return this.type===ge.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===ge.backQuote,this.finishNode(i,"TemplateElement")},it.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===ge.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(ge.dollarBraceL),i.expressions.push(this.parseExpression()),this.expect(ge.braceR),i.quasis.push(s=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(i,"TemplateLiteral")},it.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===ge.name||this.type===ge.num||this.type===ge.string||this.type===ge.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===ge.star)&&!fe.test(this.input.slice(this.lastTokEnd,this.start))},it.parseObj=function(e,t){var i=this.startNode(),s=!0,n={};for(i.properties=[],this.next();!this.eat(ge.braceR);){if(s)s=!1;else if(this.expect(ge.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(ge.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")},it.parseProperty=function(e,t){var i,s,n,o,r=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(ge.ellipsis))return e?(r.argument=this.parseIdent(!1),this.type===ge.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===ge.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(ge.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(ge.star),this.parsePropertyName(r)):s=!1,this.parsePropertyValue(r,e,i,s,n,o,t,a),this.finishNode(r,"Property")},it.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")},it.parsePropertyValue=function(e,t,i,s,n,o,r,a){(i||s)&&this.type===ge.colon&&this.unexpected(),this.eat(ge.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,r),e.kind="init"):this.options.ecmaVersion>=6&&this.type===ge.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===ge.comma||this.type===ge.braceR||this.type===ge.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===ge.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))},it.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(ge.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(ge.bracketR),e.key;e.computed=!1}return e.key=this.type===ge.num||this.type===ge.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},it.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},it.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|Be(t,s.generator)|(i?128:0)),this.expect(ge.parenL),s.params=this.parseBindingList(ge.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")},it.parseArrowExpression=function(e,t,i,s){var n=this.yieldPos,o=this.awaitPos,r=this.awaitIdentPos;return this.enterScope(16|Be(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")},it.parseFunctionBody=function(e,t,i,s){var n=t&&this.type!==ge.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()},it.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")},at.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},at.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},at.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},at.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 ct=function(e,t,i){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new De(e,i)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},ht=$e.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}ht.startNode=function(){return new ct(this,this.start,this.startLoc)},ht.startNodeAt=function(e,t){return new ct(this,e,t)},ht.finishNode=function(e,t){return pt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},ht.finishNodeAt=function(e,t,i,s){return pt.call(this,e,t,i,s)},ht.copyNode=function(e){var t=new ct(this,e.start,this.startLoc);for(var i in e)t[i]=e[i];return t};var dt="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",ut=dt+" Extended_Pictographic",mt=ut+" EBase EComp EMod EPres ExtPict",gt={9:dt,10:ut,11:ut,12:mt,13:mt,14:mt},ft={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"},yt="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",bt="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=bt+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",xt=vt+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_t=xt+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",wt=_t+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ct={9:bt,10:vt,11:xt,12:_t,13:wt,14:wt+" 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"},St={};function kt(e){var t=St[e]={binary:Pe(gt[e]+" "+yt),binaryOfStrings:Pe(ft[e]),nonBinary:{General_Category:Pe(yt),Script:Pe(Ct[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 Et=0,Mt=[9,10,11,12,13,14];Et=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=St[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 At(e){return 105===e||109===e||115===e}function Dt(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Lt(e){return e>=65&&e<=90||e>=97&&e<=122}It.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)},It.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},It.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},It.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},It.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},It.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},It.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},It.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},It.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")},Pt.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))},Pt.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 Tt(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")},Pt.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},Pt.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Pt.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Pt.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},Pt.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},Pt.regexp_eatModifiers=function(e){for(var t="",i=0;-1!==(i=e.current())&&At(i);)t+=Te(i),e.advance();return t},Pt.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)},Pt.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Pt.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Dt(t)&&(e.lastIntValue=t,e.advance(),!0)},Pt.regexp_eatPatternCharacters=function(e){for(var t=e.pos,i=0;-1!==(i=e.current())&&!Dt(i);)e.advance();return e.pos!==t},Pt.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)},Pt.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 ae(e,!0)||36===e||95===e}(s)?(e.lastIntValue=s,!0):(e.pos=t,!1)},Pt.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 le(e,!0)||36===e||95===e||8204===e||8205===e}(s)?(e.lastIntValue=s,!0):(e.pos=t,!1)},Pt.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)},Pt.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},Pt.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},Pt.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)},Pt.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Pt.regexp_eatZero=function(e){return 48===e.current()&&!Vt(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Pt.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)},Pt.regexp_eatControlLetter=function(e){var t=e.current();return!!Lt(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Pt.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},Pt.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)},Pt.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 Nt(e){return Lt(e)||95===e}function Ot(e){return Nt(e)||Vt(e)}function Vt(e){return e>=48&&e<=57}function Rt(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Bt(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function $t(e){return e>=48&&e<=55}Pt.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},Pt.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},Pt.regexp_validateUnicodePropertyNameAndValue=function(e,t,i){ke(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(i)||e.raise("Invalid property value")},Pt.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")},Pt.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Nt(t=e.current());)e.lastStringValue+=Te(t),e.advance();return""!==e.lastStringValue},Pt.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ot(t=e.current());)e.lastStringValue+=Te(t),e.advance();return""!==e.lastStringValue},Pt.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Pt.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},Pt.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Pt.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")}}},Pt.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||$t(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)},Pt.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)},Pt.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)}},Pt.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},Pt.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Pt.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},Pt.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},Pt.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Pt.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Pt.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))},Pt.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)},Pt.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Vt(t)&&95!==t)&&(e.lastIntValue=t%32,e.advance(),!0)},Pt.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},Pt.regexp_eatDecimalDigits=function(e){var t=e.pos,i=0;for(e.lastIntValue=0;Vt(i=e.current());)e.lastIntValue=10*e.lastIntValue+(i-48),e.advance();return e.pos!==t},Pt.regexp_eatHexDigits=function(e){var t=e.pos,i=0;for(e.lastIntValue=0;Rt(i=e.current());)e.lastIntValue=16*e.lastIntValue+Bt(i),e.advance();return e.pos!==t},Pt.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},Pt.regexp_eatOctalDigit=function(e){var t=e.current();return $t(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Pt.regexp_eatFixedHexDigits=function(e,t){var i=e.pos;e.lastIntValue=0;for(var s=0;s=this.input.length?this.finishToken(ge.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},Ft.readToken=function(e){return ae(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},Ft.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},Ft.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())},Ft.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&&xe.test(String.fromCharCode(e))))break e;++this.pos}}},Ft.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)},Ft.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(ge.ellipsis)):(++this.pos,this.finishToken(ge.dot))},Ft.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(ge.assign,2):this.finishOp(ge.slash,1)},Ft.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),i=1,s=42===e?ge.star:ge.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++i,s=ge.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(ge.assign,i+1):this.finishOp(s,i)},Ft.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(ge.assign,3);return this.finishOp(124===e?ge.logicalOR:ge.logicalAND,2)}return 61===t?this.finishOp(ge.assign,2):this.finishOp(124===e?ge.bitwiseOR:ge.bitwiseAND,1)},Ft.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(ge.assign,2):this.finishOp(ge.bitwiseXOR,1)},Ft.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&&!fe.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(ge.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(ge.assign,2):this.finishOp(ge.plusMin,1)},Ft.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(ge.assign,i+1):this.finishOp(ge.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(ge.relational,i)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},Ft.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(ge.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(ge.arrow)):this.finishOp(61===e?ge.eq:ge.prefix,1)},Ft.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(ge.questionDot,2)}if(63===t){if(e>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(ge.assign,3);return this.finishOp(ge.coalesce,2)}}return this.finishOp(ge.question,1)},Ft.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,ae(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(ge.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+Te(e)+"'")},Ft.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(ge.parenL);case 41:return++this.pos,this.finishToken(ge.parenR);case 59:return++this.pos,this.finishToken(ge.semi);case 44:return++this.pos,this.finishToken(ge.comma);case 91:return++this.pos,this.finishToken(ge.bracketL);case 93:return++this.pos,this.finishToken(ge.bracketR);case 123:return++this.pos,this.finishToken(ge.braceL);case 125:return++this.pos,this.finishToken(ge.braceR);case 58:return++this.pos,this.finishToken(ge.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(ge.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(ge.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+Te(e)+"'")},Ft.finishOp=function(e,t){var i=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,i)},Ft.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(fe.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 It(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(ge.regexp,{pattern:n,flags:r,value:l})},Ft.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},Ft.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=jt(this.input.slice(t,this.pos)),++this.pos):ae(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(ge.num,i)},Ft.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=jt(this.input.slice(t,this.pos));return++this.pos,ae(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(ge.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")),ae(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(ge.num,r)},Ft.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},Ft.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)):(be(s)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(i,this.pos++),this.finishToken(ge.string,t)};var Ut={};Ft.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==Ut)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},Ft.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw Ut;this.raise(e,t)},Ft.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!==ge.template&&this.type!==ge.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(ge.template,e)):36===i?(this.pos+=2,this.finishToken(ge.dollarBraceL)):(++this.pos,this.finishToken(ge.backQuote));if(92===i)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(be(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}},Ft.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 be(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},Ft.readHexChar=function(e){var t=this.pos,i=this.readInt(16,e);return null===i&&this.invalidStringToken(t,"Bad character escape sequence"),i},Ft.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},Kt=17,Qt={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:Kt,ClassExpression:Kt,FunctionExpression:Kt,ObjectExpression:Kt,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function Zt(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:ai=function(e,t){t.write("..."),this[e.argument.type](e.argument,t)},SpreadElement:ai,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),ti(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:li=function(e,t){const i="in"===e.operator;i&&t.write("("),ti(t,e.left,e,!1),t.write(" "+e.operator+" "),ti(t,e.right,e,!0),i&&t.write(")")},LogicalExpression:li,ConditionalExpression(e,t){const{test:i}=e,s=t.expressionsPrecedence[i.type];s===Kt||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===Kt||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 mi=Object.defineProperty,gi=(e,t,i)=>((e,t,i)=>t in e?mi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class fi{constructor(){gi(this,"scopes",[]),gi(this,"scopeTypes",[]),gi(this,"scopeCounts",new Map),gi(this,"contextBoundVars",new Set),gi(this,"arrayPatternElements",new Set),gi(this,"rootParams",new Set),gi(this,"varKinds",new Map),gi(this,"loopVars",new Set),gi(this,"loopVarNames",new Map),gi(this,"paramIdCounter",0),gi(this,"cacheIdCounter",0),gi(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 yi="$",bi={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:yi},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:yi},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 xi(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 _i(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===yi||"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===yi||"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=yi);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=yi);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)?Ii(i.init,t):Ht(i.init,{parent:i.init},{Identifier(e,i){e.parent=i.parent,wi(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)})),Ii(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:yi},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:yi},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:yi},property:{type:"Identifier",name:"init"},computed:!1},arguments:[l,e]}}o&&(t.pushScope("fn"),Ht(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){_i(e,t)},Identifier(e,t){wi(e,t)},AssignmentExpression(e,t){Ci(e,t)}}),t.popScope()),Object.assign(e,p)}))}function wi(e,t){if(e.name!==yi){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("`"))return;if(t.isLoopVariable(e.name))return;if(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:yi},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:yi},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 Ci(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:yi},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}}Ht(e.right,{parent:e.right,inNamespaceCall:!1},{Identifier(e,i,s){"na"==e.name&&(e.name="NaN"),e.parent=i.parent,wi(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||Ai(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);Ii(e,t),e.arguments.forEach((t=>s(t,{parent:e,inNamespaceCall:n||i.inNamespaceCall})))}})}function Si(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:yi},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)||xi(e,0,t),e):e})),e.argument={type:"ArrayExpression",elements:[e.argument]};else if("BinaryExpression"===e.argument.type)Ht(e.argument,t,{Identifier(e,t){wi(e,t),"Identifier"===e.type&&Ai(e)},MemberExpression(e){xi(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:yi},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:yi},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:yi},property:{type:"Identifier",name:"precision"}},arguments:[e.argument]})}}function ki(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:yi},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:yi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}return e}function Ei(e,t,i){const s=Mi(e.argument,t,i);return{type:"UnaryExpression",operator:e.operator,prefix:e.prefix,argument:s,start:e.start,end:e.end}}function Mi(e,t,i=""){switch(e.type){case"BinaryExpression":return Pi(e,t,i);case"MemberExpression":return{type:"MemberExpression",object:"Identifier"===e.object.type?ki(e.object,t):e.object,property:e.property,computed:e.computed};case"Identifier":if(t.isLoopVariable(e.name))return e;if(e.parent&&"MemberExpression"===e.parent.type&&e.parent.property===e)return e;return{type:"MemberExpression",object:ki(e,t),property:{type:"Literal",value:0},computed:!0};case"UnaryExpression":return Ei(e,t,i)}return e}function Pi(e,t,i){const s=Mi(e.left,t,i),n=Mi(e.right,t,i),o={type:"BinaryExpression",operator:e.operator,left:s,right:n,start:e.start,end:e.end};return Ht(o,t,{CallExpression(e,t){e._transformed||Ii(e,t)},MemberExpression(e){xi(e,0,t)}}),o}function Ti(e,t,i){switch(e?.type){case"BinaryExpression":e=Pi(e,i,t);break;case"LogicalExpression":e=function(e,t,i){const s=Mi(e.left,t,i),n=Mi(e.right,t,i),o={type:"LogicalExpression",operator:e.operator,left:s,right:n,start:e.start,end:e.end};return Ht(o,t,{CallExpression(e,t){e._transformed||Ii(e,t)}}),o}(e,i,t);break;case"ConditionalExpression":return function(e,t,i){return Ht(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,wi(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&&Ai(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);Ii(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,bi,t.nextParamIdArg],_transformed:!0,_isParamCall:!0}}(e,i,t);case"UnaryExpression":e=Ei(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:ki(e.object,i),"Identifier"!==e.property.type||i.isContextBound(e.property.name)||i.isLoopVariable(e.property.name)?e.property:ki(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:yi},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,bi,i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}return"CallExpression"===e?.type&&Ii(e,i),{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:["Identifier"===e.type?ki(e,i):e,bi,i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}function Ii(e,t,i){if(e._transformed)return;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:Ti(e,i,t))),e._transformed=!0}else e.callee&&"Identifier"===e.callee.type&&(e.arguments=e.arguments.map((e=>e._isParamCall?e:Ti(e,yi,t))),e._transformed=!0);e.arguments.forEach((e=>{Ht(e,t,{Identifier(e,i,s){e.parent=i.parent,wi(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&&Ai(e))},CallExpression(e,t,i){e._transformed||Ii(e,t)},MemberExpression(e,i,s){xi(e,0,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})}})}))}function Ai(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 Di(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&&Ht(i.init,t,{Identifier(e,i){t.isLoopVariable(e.name)||(t.pushScope("for"),wi(e,i),t.popScope())},MemberExpression(e){t.pushScope("for"),xi(e,0,t),t.popScope()}})}e.test&&Ht(e.test,t,{Identifier(e,i){t.isLoopVariable(e.name)||e.computed||(t.pushScope("for"),wi(e,i),"Identifier"===e.type&&(e.computed=!0,Ai(e)),t.popScope())},MemberExpression(e){t.pushScope("for"),xi(e,0,t),t.popScope()}}),e.update&&Ht(e.update,t,{Identifier(e,i){t.isLoopVariable(e.name)||(t.pushScope("for"),wi(e,i),t.popScope())}}),t.pushScope("for"),i(e.body,t),t.popScope()}function Li(e,t,i){e.test&&(t.pushScope("if"),function(e,t){Ht(e,t,{MemberExpression(e){xi(e,0,t)},CallExpression(e,t){Ii(e,t)},Identifier(e,i){wi(e,i);const s="if"===t.getCurrentScopeType();t.isContextBound(e.name)&&!t.isRootParam(e.name)&&s&&Ai(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 Ni(e){let t="function"==typeof e?e.toString():e;const i=(s=t.trim(),$e.parse(s,{ecmaVersion:"latest",sourceType:"module"}));var s;!function(e){Ht(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 fi;let o;!function(e,t){zt(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===yi||"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===yi||"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),zt(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"),Ht(e.body,t,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},ReturnStatement(e,t){Si(e,t)},VariableDeclaration(e,t){_i(e,t)},Identifier(e,t){wi(e,t)},CallExpression(e,t){Ii(e,t),e.arguments.forEach((e=>{"BinaryExpression"===e.type&&Ht(e,t,{CallExpression(e,t){Ii(e,t)},MemberExpression(e){xi(e,0,t)}})}))},MemberExpression(e){xi(e,0,t)},AssignmentExpression(e,t){Ci(e,t)},ForStatement(e,t,i){Di(e,t,i)},IfStatement(e,t,i){Li(e,t,i)},BinaryExpression(e,t,i){Ht(e,t,{CallExpression(e,t){Ii(e,t)},MemberExpression(e){xi(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=yi),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){}}),Ht(i,n,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},ReturnStatement(e,t){Si(e,t)},VariableDeclaration(e,t){_i(e,t)},Identifier(e,t){wi(e,t)},CallExpression(e,t){Ii(e,t)},MemberExpression(e){xi(e,0,n)},AssignmentExpression(e,t){Ci(e,t)},FunctionDeclaration(e,t){},ForStatement(e,t,i){Di(e,t,i)},IfStatement(e,t,i){Li(e,t,i)}});const r=function(e,t){const i=new ui(t);return i.generator[e.type](e,i),i.output}(i);return new Function("",`return ${r}`)(this)}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(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,Vi(this,"data",[]),Vi(this,"open",[]),Vi(this,"high",[]),Vi(this,"low",[]),Vi(this,"close",[]),Vi(this,"volume",[]),Vi(this,"hl2",[]),Vi(this,"hlc3",[]),Vi(this,"ohlc4",[]),Vi(this,"openTime",[]),Vi(this,"closeTime",[]),Vi(this,"_periods"),Vi(this,"pineTSCode"),Vi(this,"fn"),Vi(this,"_readyPromise",null),Vi(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 as({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=Ni.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?Bi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Gi{constructor(e){this.context=e,$i(this,"script"),$i(this,"pane",0),$i(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 Fi{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 ji=Object.defineProperty,Ui=(e,t,i)=>((e,t,i)=>t in e?ji(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);class zi{constructor(e){this.context=e,Ui(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 Hi=Object.defineProperty,Wi=(e,t,i)=>((e,t,i)=>t in e?Hi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);const qi=["1","3","5","15","30","45","60","120","180","240","D","W","M"];class Xi{constructor(e){this.context=e,Wi(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=qi.indexOf(this.context.timeframe),u=qi.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=new Ri(this.context.source,l,c,this.context.limit||1e3,this.context.sDate,this.context.eDate),y=await f.run(this.context.pineTSCode);this.context.cache[p]=y;const b=this._findSecContextIdx(m,g,y.data.openTime,y.data.closeTime,n);return-1==b?NaN:y.params[p][b]}_findSecContextIdx(e,t,i,s,n=!1){for(let o=0;o((e,t,i)=>t in e?Ji(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);class Ki{constructor(e){this.context=e,Yi(this,"max_period",null)}updateMaxPeriod(e){(null===this.context.max_period||e>this.context.max_period)&&(this.context.max_period=e)}extractMaxValue(e){return Array.isArray(e)?Math.max(...e):e}get tr(){return this.context.math.max(this.context.data.high[0]-this.context.data.low[0],this.context.math.abs(this.context.data.high[0]-this.context.data.close[1]),this.context.math.abs(this.context.data.low[0]-this.context.data.close[1]))}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])}ema(e,t){const i=Array.isArray(t)?t[0]:t;this.updateMaxPeriod(this.extractMaxValue(t));const s=function(e,t){const i=new Array(e.length).fill(NaN),s=2/(t+1);let n=0;for(let i=0;i2*e-n[t])),r=Math.floor(Math.sqrt(t)),a=es(o,r);return a}(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;this.updateMaxPeriod(this.extractMaxValue(t));const 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;this.updateMaxPeriod(this.extractMaxValue(t));const n=Array.isArray(i)?i[0]:i,o=function(e,t,i=!0){const s=new Array(e.length).fill(NaN),n=Zi(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?ts(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);class ss{constructor(e){this.array=e}}class ns{constructor(e){this.context=e,is(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 ss(Array(e).fill(t))}new_float(e,t=NaN){return new ss(Array(e).fill(t))}new_int(e,t=0){return new ss(Array(e).fill(Math.round(t)))}new_string(e,t=""){return new ss(Array(e).fill(t))}new(e,t){return new ss(Array(e).fill(t))}slice(e,t,i){const s=void 0!==i?i+1:void 0;return new ss(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 ss(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 ss(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 ss(e.array.map((e=>Math.abs(e))))}concat(e,t){return e.array.push(...t.array),e}copy(e){return new ss([...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 ss(i)}standardize(e){const t=this.avg(e),i=this.stdev(e);return new ss(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 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,"symbol"!=typeof t?t+"":t,i);class as{constructor({marketData:e,source:t,tickerId:i,timeframe:s,limit:n,sDate:o,eDate:r,title:a}){rs(this,"data",{open:[],high:[],low:[],close:[],volume:[],hl2:[],hlc3:[],ohlc4:[]}),rs(this,"cache",{}),rs(this,"useTACache",!1),rs(this,"NA",NaN),rs(this,"math"),rs(this,"ta"),rs(this,"input"),rs(this,"request"),rs(this,"array"),rs(this,"core"),rs(this,"lang"),rs(this,"idx",0),rs(this,"params",{}),rs(this,"const",{}),rs(this,"var",{}),rs(this,"let",{}),rs(this,"result"),rs(this,"plots",{}),rs(this,"candles",{}),rs(this,"bars",{}),rs(this,"fills",{}),rs(this,"marketData"),rs(this,"source"),rs(this,"tickerId"),rs(this,"timeframe",""),rs(this,"limit"),rs(this,"sDate"),rs(this,"eDate"),rs(this,"group"),rs(this,"pineTSCode"),rs(this,"max_period"),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 zi(this),this.ta=new Ki(this),this.input=new Fi(this),this.request=new Xi(this),this.array=new ns(this);const l=new Gi(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?e:Array.isArray(e)||"object"!=typeof 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])):e}}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,"symbol"!=typeof t?t+"":t,i);const hs={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 ps{constructor(e=3e5){cs(this,"cache"),cs(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 ds(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(){cs(this,"cacheManager"),this.cacheManager=new ps(3e5)}async getMarketDataInterval(e,t,i,s){try{const n=hs[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 us={...t.customSeriesDefaultOptions,color:"#049981",lineWidth:1,lineStyle:t.LineStyle.Solid,shapeSize:.3,shape:"circles",join:!1,fontSize:.8};function ms(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)=>fs(t,s,i)))):t.map(((e,i)=>fs(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)=>fs(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=fs(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 gs(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,...us,title:e};default:throw new Error(`Unsupported series type: ${e}`)}}function fs(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 ys(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."),ms(e,t))}function xs(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 ws(e,t,i,s="Line",n="overwrite"){const{data:o,group:r,options:a,pane:l}=i,c={...Cs(a)};r&&(c.group=r),t&&(c.title=t);const h="circles"===c.style||"cross"===c.style?"Symbol":s;let p={...gs(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?ds(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=ms(m.series,e.legend)),e.seriesMap.set(t,m.series)}function Cs(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 Ss(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 ks(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)}!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"}(bs||(bs={}));const Es={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 Ms{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,...Es},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 Ps 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}(Es,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 Ts(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=vs(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 Ms(this._handler,this._source,e.p1,e.p2,t??this._options,i),s.onComplete=()=>this.updateViewFromSequence(),this.updateViewFromSequence(),s):(s=new Ms(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,Ps._mouseIsDown)this._handleDragInteraction(e);else if(this._mouseIsOverSequence(e)){if(this._state!=N.NONE)return;this._moveToState(N.HOVERING),Ps.hoveredObject=Ps.lastHoveredObject=this}else{if(this._state==N.NONE)return;this._moveToState(N.NONE),Ps.hoveredObject===this&&(Ps.hoveredObject=null)}}_handleMouseDownOrUp=()=>{this._latestHoverPoint&&(Ps._mouseIsDown=!Ps._mouseIsDown,Ps._mouseIsDown?this._onMouseDown():this._onMouseUp())};_handleMouseMove=e=>{const t=this._eventToPoint(e,this._source);this._latestHoverPoint=t,Ps._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(){Ps._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 Ts{_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 Is(this._plugin,this._plugin._options,!1)}}class Is extends J{_source;_options;constructor(e,t,i){super($(e._sequence.p1,e.chart,e._source),$(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,ks(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-.5*r,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))}}const As={TrendTrace:Ps};class Ds 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}toJSON(){return{points:this.points,_options:this._options,linkedObjects:this.linkedObjects.map((e=>"function"==typeof e.toJSON?e.toJSON():{}))}}fromJSON(e){e&&(e.points&&Array.isArray(e.points)&&e.points.length>=2&&this.updatePoints(e.points[0],e.points[1]),e._options&&(this._options={...this._options,...e._options}),e.linkedObjects&&Array.isArray(e.linkedObjects)&&(this.linkedObjects=e.linkedObjects.map((e=>{const t=e._type;if(!t)return console.warn("Linked object JSON missing _type property."),null;const i=As[t];if(!i)return console.warn(`No constructor found in registry for type: ${t}`),null;const s=new i;return"function"==typeof s.fromJSON&&s.fromJSON(e),s})).filter((e=>null!==e))),this.requestUpdate())}}class Ls 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 Ns{_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 Ls?4:this._drawingType.prototype instanceof Ds?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 Ds;this._drawingType&&this._drawingType.prototype instanceof Ls?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 Os extends J{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,ks(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 Vs{_source;constructor(e){this._source=e}}class Rs extends Vs{_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 Bs extends Vs{_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 $s extends Rs{constructor(e){super(e)}renderer(){return new Os(this._p1,this._p2,this._source._options,this._source.hovered)}}class Gs extends V{_type="TrendLine";constructor(e,t,i){super(e,t,i),this._paneViews=[new $s(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 Fs extends J{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,ks(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 js extends Rs{constructor(e){super(e)}renderer(){return new Fs(this._p1,this._p2,this._source._options,this._source.hovered)}}const Us={fillEnabled:!0,fillColor:"rgba(255, 255, 255, 0.2)",...L};class zs extends V{_type="Box";constructor(e,t,i){super(e,t,i),this._options={...Us,...i},this._paneViews=[new js(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,ks(t,this._options.lineStyle),t.beginPath(),t.moveTo(s,i),t.lineTo(e.bitmapSize.width,i),t.stroke()}))}}class Ws extends Vs{_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 Hs(this._point,this._source._options)}}class qs{_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 Xs 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 Ws(this)],this._priceAxisViews=[new qs(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 Js extends Xs{_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 Ys extends X{_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,ks(t,this._options.lineStyle),t.beginPath(),t.moveTo(i,0),t.lineTo(i,e.bitmapSize.height),t.stroke()}))}}class Ks extends Vs{_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 Ys(this._point,this._source._options)}}class Qs{_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 Zs extends O{_type="VerticalLine";_paneViews;_timeAxisViews;_point;_callbackName;_startDragPoint=null;constructor(e,t,i=null){super(t),this._point=e,this._paneViews=[new Ks(this)],this._callbackName=i,this._timeAxisViews=[new Qs(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 en extends Y{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,ks(i,this.options.lineStyle),ks(i,t.LineStyle.Solid),i.beginPath(),i.moveTo(r,a),i.lineTo(l,c),i.stroke(),ks(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 on{static TREND_SVG='';static HORZ_SVG='';static RAY_SVG='';static BOX_SVG='';static VERT_SVG=on.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 Ns(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(Gs,"KeyT",on.TREND_SVG)),this.buttons.push(this._makeToolBoxElement(Xs,"KeyH",on.HORZ_SVG)),this.buttons.push(this._makeToolBoxElement(Js,"KeyR",on.RAY_SVG)),this.buttons.push(this._makeToolBoxElement(zs,"KeyB",on.BOX_SVG)),this.buttons.push(this._makeToolBoxElement(Zs,"KeyV",on.VERT_SVG,!0)),this.buttons.push(this._makeToolBoxElement(nn,"KeyP",on.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 zs(e.points[0],e.points[1],e.options));break;case"TrendLine":this._drawingTool.addNewDrawing(new Gs(e.points[0],e.points[1],e.options));break;case"HorizontalLine":this._drawingTool.addNewDrawing(new Xs(e.points[0],e.options));break;case"RayLine":this._drawingTool.addNewDrawing(new Js(e.points[0],e.options));break;case"VerticalLine":this._drawingTool.addNewDrawing(new Zs(e.points[0],e.options));break;case"PitchFork":this._drawingTool.addNewDrawing(new nn(e.points[0],e.points[1],e.points[2],e.options))}}))}}const rn={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 an{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,rn,{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,rn,{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,rn,{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,rn,{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,rn,{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,rn,{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,rn,{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,rn,{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)=>ln(e,t[i]))).filter((e=>null!==e))}([...(this.selectedSeries??this.handler.series).data()],[...this.selectedVolumeSeries?this.selectedVolumeSeries.data():[]]),a=new Ri(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,max_period:u}=await a.run(l,void 0,!1);if(console.log("Plots:",c),console.log("Candles:",h),console.log("Bars:",p),c)for(const e in c)c.hasOwnProperty(e)&&ws(this.handler,e,c[e],void 0,"overwrite");if(h)for(const e in h)h.hasOwnProperty(e)&&ws(this.handler,e,h[e],"Candlestick","overwrite");if(p)for(const e in p)p.hasOwnProperty(e)&&ws(this.handler,e,p[e],"Bar","overwrite");if(d)for(const e in d)d.hasOwnProperty(e)&&Ss(this.handler,d[e]);this.scripts[s]={pineTSInstance:a,ohlc:n,volume:o,code:e,n:u};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("N:",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=ln(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}=await a.run(void 0,s);if(console.log("Plots:",l),console.log("Candles:",c),console.log("Bars:",h),l)for(const e in l)l.hasOwnProperty(e)&&ws(this.handler,e,l[e],void 0,"update");if(c)for(const e in c)l.hasOwnProperty(e)&&ws(this.handler,e,c[e],"Candlestick","update");if(h)for(const e in h)l.hasOwnProperty(e)&&ws(this.handler,e,h[e],"Bar","update")}catch(e){console.error("Error executing PineTS code:",e)}}saveScript(){const e=this.getValue(),t=e.match(/^(?!\s*\/\/)(?!\s*\*)(.*indicator\s*\(\s*['"]([^'"]+)['"])/m),i=t?.[2]?t[2].replace(/['"]/g,""):"defaultScript";this.scripts[i]?this.scripts[i].code=e:this.scripts[i]={ohlc:(this.selectedSeries??this.handler.series).options().title,volume:(this.selectedVolumeSeries??this.handler.volumeSeries).options().title,code:e,pineTSInstance:null,n:null},console.log(`Script "${i}" updated in memory.`);const s=this.scripts[i],n=JSON.stringify(s,null,2),o=`save_script_~_${i};;;${n}`;window.callbackFunction(o),console.log(`Script "${i}" sent via callback.`);const r=`save_script_~_cache;;;${n}`;window.callbackFunction(r),console.log('Cache script sent via callback under the name "cache".')}async saveToFile(){const e=this.getValue(),t=prompt("Enter a new script name/title:","MyNewScript");if(!t)return void console.warn("Save To File canceled or no name provided.");this.scripts[t]={ohlc:(this.selectedSeries??this.handler.series).options().title,volume:(this.selectedVolumeSeries??this.handler.volumeSeries).options().title,code:e,pineTSInstance:null,n:null},console.log(`Script saved as "${t}" in memory.`);const i=JSON.stringify(this.scripts[t],null,2),s=`${t}.json`;this.downloadJson(i,s);const n=JSON.stringify(this.scripts[t],null,2);this.downloadJson(n,"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 ln(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 cn{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 hn{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 pn{_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 an(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=pn.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 cn(this.makeButton.bind(this),e,t,i,s,n)}makeChartMenu(e,t,i,s,n,o){return new hn(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 dn={title:"",followMode:"tracking",horizontalDeadzoneWidth:45,verticalDeadzoneHeight:100,verticalSpacing:20,topOffset:20};class un{_chart;_element;_titleElement;_priceElement;_dateElement;_timeElement;_options;_lastTooltipWidth=null;constructor(e,t){this._options={...dn,...t},this._chart=e;const i=document.createElement("div");gn(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");gn(s,{"font-size":"12px","line-height":"24px","font-weight":"590"}),mn(s,this._options.title),i.appendChild(s);const n=document.createElement("div");gn(n,{"font-size":"12px","line-height":"18px","font-weight":"590"}),mn(n,""),i.appendChild(n);const o=document.createElement("div");gn(o,{color:"#787B86"}),mn(o,""),i.appendChild(o);const r=document.createElement("div");gn(r,{color:"#787B86"}),mn(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}`),mn(this._titleElement,e.title)):console.warn("Title element is missing or title data is undefined."),mn(this._priceElement,e.price),mn(this._dateElement,e.date),mn(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 mn(e,t){e&&t!==e.innerText&&(e.innerText=t,e.style.display=t?"block":"none")}function gn(e,t){for(const[i,s]of Object.entries(t))e.style.setProperty(i,s)}function fn(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 yn{_data;constructor(e){this._data=e}draw(e){this._data.visible&&e.useBitmapCoordinateSpace((e=>{const t=e.context,i=fn(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 bn{_data;constructor(e){this._data=e}update(e){this._data=e}renderer(){return new yn(this._data)}zOrder(){return"bottom"}}const vn={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 xn{_options;_tooltip=void 0;_paneViews;_data={x:0,visible:!1,color:"rgba(0, 0, 0, 0.2)",topMargin:0};_attachedParams;constructor(e){this._options={...vn,...e},this._data.color=this._options.lineColor,this._paneViews=[new bn(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?ds(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 un(e,{...this._options.tooltip})}}let _n=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 wn{container;_opacitySlider;_opacity_label;exitButton;color="#ff0000";rgba;opacity;applySelection;customColors;constructor(e,t,i){this.applySelection=t,this.rgba=wn.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 wn.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=wn.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=wn.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 Cn{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"),Cn._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 Sn={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 kn 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=Sn,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={...Sn,...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 En(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,kn._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=()=>{kn._mouseIsDown=!kn._mouseIsDown,kn._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(){kn._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=$(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 En{_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=$(this._source.p1,t,i),this._p2=$(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 Mn({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 Mn extends J{_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),ks(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)",ks(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 Pn(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=Tn(s,t),r=Tn(n,t);return 0===r?100:0===o?0:100-100/(1+o/r)}function An(e,t,i){for(let s=0;s=o?t:i}}function Dn(e,t,i){const s=e&&t in e?e[t]:i;return Array.isArray(s)?s.map((e=>Number(e))):[Number(s)]}function Ln(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}},On=(e,t)=>{let i=0;return e.forEach((e=>{const s=e.close-t;i+=s*s})),Math.sqrt(i/e.length)},Vn={name:"Bollinger Bands",shortName:"BOLL",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray"},multiplier:{defaultValue:[2],type:"numberArray"}},calc(e,t){const i=Dn(t,"length",this.paramMap.length.defaultValue),s=Dn(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=On(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}},Rn={name:"Exponential Moving Average",shortName:"EMA",shouldOhlc:!0,paramMap:{length:{defaultValue:[6,12,20],type:"numberArray"}},calc(e,t){const i=Dn(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}},Bn={name:"Highest High",shortName:"HH",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Dn(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}},$n={name:"Linear Regression",shortName:"LINREG",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Dn(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}},Gn={name:"Lowest Low",shortName:"LL",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Dn(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}},Fn={name:"Median",shortName:"Median",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Dn(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}},jn={name:"Moving Average",shortName:"MA",shouldOhlc:!0,paramMap:{length:{defaultValue:[5,10,30,60],type:"numberArray"}},calc(e,t){const i=Dn(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}},Un={name:"Rolling Moving Average",shortName:"RMA",shouldOhlc:!1,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Dn(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}},zn={name:"Simple Moving Average",shortName:"SMA",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray"},k:{defaultValue:[2],type:"numberArray"}},calc(e,t){const i=Dn(t,"n",this.paramMap.n.defaultValue),s=Dn(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}},Hn={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=Dn(t,"accStart",this.paramMap.accStart.defaultValue),s=Dn(t,"accStep",this.paramMap.accStep.defaultValue),n=Dn(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}},Wn={name:"Super Trend",shortName:"SuperTrend",shouldOhlc:!0,paramMap:{factor:{defaultValue:[3],type:"numberArray"},atrPeriod:{defaultValue:[10],type:"numberArray"}},calc(e,t){const i=Dn(t,"factor",this.paramMap.factor.defaultValue),s=Dn(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}},qn={name:"Symmetrically Weighted Moving Average",shortName:"SWMA",shouldOhlc:!1,paramMap:{window:{defaultValue:[4],type:"numberArray"}},calc(e,t){const i=Dn(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}},Xn={name:"TRIX",shortName:"TRIX",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray"},m:{defaultValue:[9],type:"numberArray"}},calc(e,t){const i=Dn(t,"n",this.paramMap.n.defaultValue),s=Dn(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}},Jn={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=Dn(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}},Yn={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=Dn(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}},Kn={name:"Weighted Moving Average",shortName:"WMA",shouldOhlc:!1,paramMap:{length:{defaultValue:[9],type:"numberArray"}},calc(e,t){const i=Dn(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}},Qn={name:"High & Low",shortName:"HHLL",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Dn(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}},Zn=[Nn,Vn,Rn,Bn,Qn,$n,Gn,Fn,jn,Un,zn,Hn,Wn,qn,Xn,Jn,Yn,Kn],eo={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=Dn(t,"shortPeriod",[5]),s=Dn(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"+Ln(i,r)+(n>1?` #${r+1}`:"");An(d,t?.upColor??"green",t?.downColor??"red"),o.push({key:u,title:m,type:"histogram",data:d,pane:1})}return o}},to={name:"Average True Range",shortName:"ATR",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=Dn(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}},io={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=Dn(t,"period1",[6]),s=Dn(t,"period2",[12]),n=Dn(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}},so={name:"Buy-Ratio Analysis",shortName:"BRAR",shouldOhlc:!0,paramMap:{length:{defaultValue:[26],type:"numberArray",min:1}},calc(e,t){const i=Dn(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}},no={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=Dn(t,"p1",[3]),s=Dn(t,"p2",[6]),n=Dn(t,"p3",[12]),o=Dn(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}},oo={name:"Commodity Channel Index",shortName:"CCI",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray",min:1}},calc(e,t){const i=Dn(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}},ro={name:"Current Ratio",shortName:"CR",shouldOhlc:!0,paramMap:{length:{defaultValue:[26],type:"numberArray",min:1}},calc(e,t){const i=Dn(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}},ao={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=Dn(t,"n1",[10]),s=Dn(t,"n2",[50]),n=Dn(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}},lo={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=Dn(t,"n",[14]),s=Dn(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}},co={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=Dn(t,"n",[12]),s=Dn(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}},ho={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=Dn(t,"n",[12]),s=Dn(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}},po={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=Dn(t,"n",[12]),s=Dn(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}},uo={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=Dn(t,"p1",[14]),s=Dn(t,"p2",[10]),n=Math.max(i.length,s.length),o=e.map((e=>e.close)),r=[];for(let t=0;t{const i=In(o.slice(0,t+1),a);c.push(i);const s=Pn(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}},mo={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=Dn(t,"n",[9]),s=Dn(t,"kPeriod",[3]),n=Dn(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}},go={name:"Variance",shortName:"Variance",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=Dn(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}},fo={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=Dn(t,"p1",[6]),s=Dn(t,"p2",[10]),n=Dn(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}},yo={name:"Change",shortName:"Change",shouldOhlc:!0,paramMap:{length:{defaultValue:[1],type:"numberArray",min:1,max:100}},calc(e,t){const i=Dn(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}},bo={name:"Range",shortName:"Range",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=Dn(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}},vo={name:"Standard Deviation",shortName:"StdDev",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=Dn(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}},xo={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 An(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}]}},_o=[...Zn,...[eo,to,io,so,no,oo,ro,ao,lo,co,xo,ho,po,uo,mo,go,fo,yo,bo,vo]];class wo{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 Oo?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 Oo?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 Oo?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 Co{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 wn("#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 wo({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===h(t)&&0===h(i)),r.appendChild(a);const c=document.createElement("span");c.innerText=e,Object.assign(c.style,{minWidth:"60px"}),r.appendChild(c);const p=document.createElement("div");Object.assign(p.style,{display:"flex",gap:"8px"}),r.appendChild(p);let d=t,u=i;e in this._originalOpacities||(this._originalOpacities[e]={up:h(t)??1,down:h(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}),p.appendChild(m),p.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??h(t)),u=l(u,this._originalOpacities[e].down??h(i)),m.style.border="1px solid #999",g.style.border="1px solid #999"):(this._originalOpacities[e].up=h(d),this._originalOpacities[e].down=h(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===h(d)&&0===h(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 So=null;class ko{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 wn("#ff0000",(()=>null),s&&0!==s.length?s:void 0),this.dataMenu=new wo({contextMenu:this,handler:this.handler}),this.SettingsModal=new Co(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 Ps.hoveredObject?Ps.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),So=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",So===this.div&&(So=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=R(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 wn(t??"#000000",o)),this.colorPicker.openMenu(e,225,o)})),n}currentWidthOptions=[];currentStyleOptions=[];populateSeriesMenu(e,i){const s=vs(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=B(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(B(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=B(t.label);if(!this.constraints[t.label]?.skip)if("boolean"==typeof t.value)this.addCheckbox(B(t.label),Boolean(t.value),(i=>{const s=R(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=R(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=R(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=R(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 wo({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 Ns(this.handler.chart,this.handler._seriesList[0]));for(const e of Object.keys(t._options)){let t;if(e.toLowerCase().includes("color"))t=new _n(this.saveDrawings,e);else{if("lineStyle"!==e)continue;t=new Cn(this.saveDrawings)}const i=e=>t.openMenu(e);this.menuItem(B(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 wo({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 Ps?this.addMenuItem(`${t.title} Options`,(()=>{this.populateTrendTraceMenu(e,t)}),!1,!0):t instanceof kn&&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 kn(this.handler,Sn),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(B(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(B(e.label),e.value,(i=>{const s=R(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(B(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=R(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=gs(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)=>fs(e,i,s))).filter((e=>null!==e));return l.series.setData(c),p(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?(ys(l.series,"LineColor",t),ys(l.series,"color",t)):e?ys(l.series,"LineColor",t):i&&ys(l.series,"color",t)}else ys(l.series,e,t)})),Object.keys(r).forEach((e=>{e.toString().toLowerCase().includes("color")&&p({[e]:r[e]},((e,t)=>{console.log(`Found color option: ${e} = ${t}`)}))})),e.subscribeDataChanged((()=>{const t=e.data().map(((t,s)=>fs(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(B(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(B(e),s,(i=>{const s=R(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(B("Top Color"),t.topColor,"layout.background.topColor",this.handler.chart),this.addColorPickerMenuItem(B("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(B(e.name),t,e.valuePath,this.handler.chart):"select"===e.type?this.addSelectInput(B(e.name),t,e.options,(t=>{const i=e.options.indexOf(t),s=R(e.valuePath,i);this.handler.chart.applyOptions(s),console.log(`Updated ${e.name} to: ${t}`)})):"boolean"===e.type&&this.addCheckbox(B(e.name),t,(t=>{const i=R(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(B(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(B("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(B(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(B(e.name),t,(t=>{const i=R(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(B(e.name),t,(t=>{const i=R(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(B(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"]}[B(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 Ps(this.handler,e,t.p1,t.p2,Es,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 kn(this.handler,Sn,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 wo({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(B(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(B(e.name),e.defaultValue,(i=>{const s=R(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(B(e.name),e.defaultValue,(i=>{const s=R(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(B(e.name),e.defaultValue,i,(i=>{const s=e.options.find((e=>e.label===i));if(s){const i=R(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??Sn.upColor},{name:"Down Color",type:"color",valuePath:"downColor",defaultValue:i.downColor??Sn.downColor},{name:"Border Up Color",type:"color",valuePath:"borderUpColor",defaultValue:i.borderUpColor??Sn.borderUpColor},{name:"Border Down Color",type:"color",valuePath:"borderDownColor",defaultValue:i.borderDownColor??Sn.borderDownColor},{name:"Grid Color",type:"color",valuePath:"gridColor",defaultValue:i.gridColor??Sn.gridColor}),s.forEach((e=>{if("number"===e.type)this.addNumberInput(B(e.name),e.defaultValue,(i=>{const s=R(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(B(e.name),e.defaultValue,(i=>{const s=R(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(B(e.name),e.defaultValue,i,(i=>{const s=e.options.find((e=>e.label===i));if(s){const i=R(e.valuePath,s.value);t.applyOptions(i),console.log(`Updated ${e.name} to: ${s.value}`)}}))}else"color"===e.type&&this.addColorPickerMenuItem(B(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="",_o.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,xs);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 wn(t??"#000000",o)),this.colorPicker.openMenu(e,225,o)})),n}}function Eo(e){return function(e){return Math.max(1,Math.floor(e))}(e)/e}class Mo{_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=h(t),n=h(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 Po{_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 Mo(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=Eo(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)",ks(a,e.lineStyle),a.lineWidth=e.lineWidth??1,e.shape){case"Rectangle":default:G(a,f,y,g,m);break;case"Rounded":F(a,f,y,g,m,s);break;case"Ellipse":j(a,f,y,0,g,m);break;case"Arrow":H(a,f,y,b,g,m,e.high*r,e.low*r,e.isUp);break;case"3d":U(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":z(a,f,y,g,m,e.high*r,e.low*r,e.isUp);break;case"Bar":W(a,f,y,e.high*r,e.low*r,e.open*r,e.close*r);break;case"Slanted":q(a,f,y,g,m,e.isUp)}}a.restore()}}const To={...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 Io{_renderer;constructor(){this._renderer=new Po}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 To}}class Ao{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 Do{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 Lo{_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,ks(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 No{_renderer;constructor(){this._renderer=new Lo}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 us}}M();class Oo{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 Ao,this.scriptsManager=new Do,Oo.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 ko(this,Oo.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{...gs(e),...this.defaultsManager.defaults.get(e.toLowerCase())||{},...t}}createCandlestickSeries(){const e="Candlestick",i={...gs(e),...this.defaultsManager.defaults.get(e.toLowerCase())||{}},s=this.chart.addSeries(t.CandlestickSeries,i);s.priceScale().applyOptions({scaleMargins:{top:.2,bottom:.2}});const n=ms(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=ms(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=ms(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=ms(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=ms(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=ms(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={...To,...this.defaultsManager.defaults.get("ohlc")||{},...t,seriesType:"Ohlc"},{group:n,legendSymbol:o=["⑃","⑂"],seriesType:r,chandelierSize:a,...l}=s,c=new Io,h=ms(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={...us,...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 No,c=ms(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=vs(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=vs(n,this.legend);let r;if("Tooltip"!==t)return void console.warn(`Unknown primitive type: ${t}`);r=new xn({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 on(this,this.id,this.chart,this.series,this.commandFunctions),this.div.appendChild(this.toolBox.div)}createTopBar(){return this._topBar=new pn(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=zs,e.CodeEditor=an,e.FillArea=_,e.Handler=Oo,e.HorizontalLine=Xs,e.Legend=D,e.RayLine=Js,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 ${_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); //# sourceMappingURL=bundle.js.map diff --git a/lightweight_charts/js/styles.css b/lightweight_charts/js/styles.css index e9f784eb..149f35be 100644 --- a/lightweight_charts/js/styles.css +++ b/lightweight_charts/js/styles.css @@ -59,7 +59,7 @@ body { .context-menu { position: absolute; - z-index: 1000; + z-index: 10000; background: rgb(50, 50, 50); color: var(--active-color); display: none; @@ -223,6 +223,28 @@ body { display: none; flex-direction: column; } + +.legend-action-button { + background: none; + border: none; + padding: 0; + font-size: 1em; + cursor: pointer; + + transition: color 0.2s ease, background-color 0.2s ease; + width: 24px; + height: 24px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 4px; +} + +.legend-action-button:hover { + + background-color: #eaeaea; +} + .series-container { display: flex; flex-direction: column; diff --git a/lightweight_charts_/js/bundle.js b/lightweight_charts_/js/bundle.js deleted file mode 100644 index 476269bf..00000000 --- a/lightweight_charts_/js/bundle.js +++ /dev/null @@ -1 +0,0 @@ -var Lib=function(e,t){"use strict";function i(e){if(void 0===e)throw new Error("Value is undefined");return e}class o{_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 i(this._chart)}get series(){return i(this._series)}_fireDataUpdated(e){this.dataUpdated&&this.dataUpdated(e)}toJSON(){return{}}fromJSON(e){}}function n(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,o,n]=3===(s=e).length?[parseInt(s[0]+s[0],16),parseInt(s[1]+s[1],16),parseInt(s[2]+s[2],16)]:[parseInt(s.slice(0,2),16),parseInt(s.slice(2,4),16),parseInt(s.slice(4,6),16)];var s;return`rgba(${i}, ${o}, ${n}, ${t})`}(e,t);{const i=/^rgb(a)?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:,\s*([\d.]+))?\)/i,o=e.match(i);if(o){const e=o[2],i=o[3],n=o[4],s=o[1]?o[5]??"1":"1";return`rgba(${e}, ${i}, ${n}, ${t??s})`}throw new Error("Unsupported color format. Use hex, rgb, or rgba.")}}function s(e,t=.2){let[i,o,n,s=1]=e.startsWith("#")?[...(a=e,3===(a=a.replace(/^#/,"")).length?[parseInt(a[0]+a[0],16),parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16)]:[parseInt(a.slice(0,2),16),parseInt(a.slice(2,4),16),parseInt(a.slice(4,6),16)]),1]:e.match(/\d+(\.\d+)?/g).map(Number);var a;return i=Math.max(0,Math.min(255,i*(1-t))),o=Math.max(0,Math.min(255,o*(1-t))),n=Math.max(0,Math.min(255,n*(1-t))),e.startsWith("#")?`#${((1<<24)+(Math.round(i)<<16)+(Math.round(o)<<8)+Math.round(n)).toString(16).slice(1)}`:`rgba(${Math.round(i)}, ${Math.round(o)}, ${Math.round(n)}, ${s})`}class a{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 o=this._performSearch(e,t);return this.cache.set(i,o),o}_performSearch(e,t){let i=0,o=this.numbers.length-1;if(e<=this.numbers[0].time)return 0;if(e>=this.numbers[o].time)return o;for(;i<=o;){const t=Math.floor((i+o)/2),n=this.numbers[t].time;if(n===e)return t;n>e?o=t-1:i=t+1}return"left"===t?i:o}}var r;function l(e){switch(e.trim().toLowerCase()){case"rectangle":return r.Rectangle;case"rounded":return r.Rounded;case"ellipse":return r.Ellipse;case"arrow":return r.Arrow;case"3d":return r.Cube;case"polygon":return r.Polygon;case"bar":return r.Bar;default:return console.warn(`Unknown CandleShape: ${e}`),r.Rectangle}}function c(e){return e.type===t.ColorType.Solid}function h(e){return e.type===t.ColorType.VerticalGradient}function d(e){return"value"in e}function p(e){return"close"in e&&"open"in e&&"high"in e&&"low"in e}function u(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 m(e){const t=e.options();return"lineColor"in t||"color"in t}function g(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"}(r||(r={}));class y extends o{static type="Fill Area";_paneViews;_originSeries;_destinationSeries;_bandsData=[];options;_timeIndices;constructor(e,t,i){super();const o=n("#0000FF",.25),s=n("#FF0000",.25),r=m(e)?n(e.options().lineColor||o,.3):n(o,.3),l=m(t)?n(t.options().lineColor||s,.3):n(s,.3);this.options={...v,...i,originColor:i.originColor??r,destinationColor:i.destinationColor??l},this._paneViews=[new _(this)],this._timeIndices=new a([]),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 a([...e])}}calculateBands(){const e=this._originSeries.data(),t=this._destinationSeries.data(),i=this._alignDataLengths([...e],[...t]),o=[];for(let e=0;eo){const e=t[o-1];for(;t.lengthi){const t=e[i-1];for(;e.lengthe.lower)).slice(s,a+1)),maxValue:Math.max(...this._bandsData.map((e=>e.upper)).slice(s,a+1))};return{priceRange:{minValue:r.minValue,maxValue:r.maxValue}}}}class f{_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 o=e.context;o.scale(e.horizontalPixelRatio,e.verticalPixelRatio);let n=!1,s=0;for(let e=0;e=s;i--)o.lineTo(t[i].x,t[i].destination);o.closePath(),o.fill()}o.beginPath(),o.moveTo(a.x,a.origin),o.fillStyle=a.isOriginAbove?i.originColor||"rgba(0, 0, 0, 0)":i.destinationColor||"rgba(0, 0, 0, 0)",s=e,n=!0}if(o.lineTo(r.x,r.origin),e===t.length-2||r.isOriginAbove!==a.isOriginAbove){for(let i=e+1;i>=s;i--)o.lineTo(t[i].x,t[i].destination);o.closePath(),o.fill(),n=!1}}i.lineWidth&&(o.lineWidth=i.lineWidth,o.strokeStyle=i.originColor||"rgba(0, 0, 0, 0)",o.stroke())}))}}class _{_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 f(this._data)}zOrder(){return"bottom"}}const v={originColor:null,destinationColor:null,lineWidth:null};function b(e,t){let i,o;if(void 0!==e.close){i=e.close}else void 0!==e.value&&(i=e.value);if(void 0!==t.close){o=t.close}else void 0!==t.value&&(o=t.value);if(void 0!==i&&void 0!==o){if(i{e&&(window.cursor=e),document.body.style.cursor=window.cursor},window.cursor="default",window.textBoxFocused=!1}const C='\n\n \n \n\n',M='\n\n \n \n \n\n';class S{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(),o=`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).`))},s=[];for(let t=0;t{e.seriesList.forEach((e=>{e.series.moveToPane(t)})),console.log(`Moved group "${e.name}" series to existing pane ${t}.`)}});s.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:o,value:o,onChange:e=>{const t=s.find((t=>t.name===e));t&&t.action()},hybridConfig:{defaultAction:n,options:s.map((e=>({name:e.name,action:e.action})))}})}this.contextMenu.separator(),this.contextMenu.addMenuItem("Close Menu",(()=>this.contextMenu.hideMenu())),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 k(e){return e.data()[e.data().length-1]}class P{handler;div;seriesContainer;legendMenu;ohlcEnabled=!1;percentEnabled=!1;linesEnabled=!1;colorBasedOnCandle=!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 S({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 o=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: ${o}`);n.primitives||(n.primitives=[]);let s=this.seriesContainer.querySelector(`[data-series-id="${n.name}"] .primitives-container`);s||(s=document.createElement("div"),s.classList.add("primitives-container"),s.style.display="none",s.style.marginLeft="20px",s.style.flexDirection="column",n.row.insertAdjacentElement("afterend",s));const a=Array.from(s.children).find((e=>e.getAttribute("data-primitive-type")===o));if(a)return console.warn(`Primitive "${o}" already exists under the parent series.`),a;const r=document.createElement("div");r.classList.add("legend-primitive-row"),r.setAttribute("data-primitive-type",o),r.style.display="flex",r.style.justifyContent="space-between",r.style.marginTop="4px";const l=document.createElement("span");l.innerText=o;const c=document.createElement("div");c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center";const h=this.createSvgIcon(C),d=this.createSvgIcon(M);c.appendChild(h.cloneNode(!0));let p=!0;c.addEventListener("click",(()=>{p=!p,c.innerHTML="",c.appendChild(p?h.cloneNode(!0):d.cloneNode(!0)),this.togglePrimitive(t,p)})),r.appendChild(l),r.appendChild(c),s.appendChild(r),s.children.length>0&&(s.style.display="block");const u={name:o,primitive:t,row:r};return this._items.push(u),n.primitives.push(u),r}togglePrimitive(e,t){const i=e.options||e._options;if(!i)return void console.warn("Primitive has no options to update.");const o={};if("visible"in i)return o.visible=t,console.log(`Toggling visible option for primitive: ${e.constructor.name} to ${t}`),void e.applyOptions(o);const n="_originalColors";e[n]||(e[n]={});const s=e[n];for(const e of Object.keys(i))e.toLowerCase().includes("color")&&(t?o[e]=s[e]||i[e]:(s[e]||(s[e]=i[e]),o[e]="rgba(0,0,0,0)"));Object.keys(o).length>0&&(console.log(`Updating visibility for primitive: ${e.constructor.name}`),e.applyOptions(o),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 o=document.createElement("button");o.classList.add("legend-action-button"),o.innerHTML="◇",o.title="Series Actions",o.style.marginRight="0px",o.style.fontSize="1em",o.style.border="none",o.style.background="none",o.style.cursor="pointer",e.colors[0],o.style.color="#ffffff",o.addEventListener("click",(t=>{t.stopPropagation(),t.preventDefault(),"◇"===o.innerHTML?o.innerHTML="◈":o.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="-",o=e.legendSymbol[0]||"▨",s=e.legendSymbol[1]||o,a=e.colors[0]||"#00FF00",r=e.colors[1]||"#FF0000";n.innerHTML=`\n ${o}\n ${s}\n ${e.name}: O ${t}, \n C ${i}\n `}else n.innerHTML=e.legendSymbol.map(((t,i)=>`${t}`)).join(" ")+` ${e.name}`;const s=document.createElement("div");s.classList.add("legend-toggle-switch"),s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center";const a=this.createSvgIcon(C),r=this.createSvgIcon(M);s.appendChild(a.cloneNode(!0));let l=!0;s.addEventListener("click",(t=>{l=!l,e.series.applyOptions({visible:l}),s.innerHTML="",s.appendChild(l?a.cloneNode(!0):r.cloneNode(!0)),s.setAttribute("aria-pressed",l.toString()),s.classList.toggle("inactive",!l),t.stopPropagation()})),s.setAttribute("role","button"),s.setAttribute("aria-label",`Toggle visibility for ${e.name}`),s.setAttribute("aria-pressed",l.toString()),i.appendChild(o),i.appendChild(n),i.appendChild(s),t.appendChild(i),i.addEventListener("contextmenu",(t=>{t.preventDefault(),this.legendMenu.populateLegendMenu(e,t)}));const c={...e,div:n,row:i,toggle:s};return this._lines.push(c),this._items.push(c),i}isLegendGroup(e){return void 0!==e.seriesList}isLegendSeries(e){return void 0!==e.series||void 0!==e.primitives}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 o=this._groups.find((e=>e.name===t));if(o){const n=o.seriesList.findIndex((t=>t.name===e));-1!==n&&(o.seriesList.splice(n,1),0===o.seriesList.length?(this.seriesContainer.removeChild(o.row),this._groups=this._groups.filter((e=>e!==o)),this._items=this._items.filter((e=>e!==o)),console.log(`Group "${t}" is empty and has been removed.`)):this.renderGroup(o,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 o=this._lines[t];this.seriesContainer.removeChild(o.row),this._lines.splice(t,1),this._items=this._items.filter((e=>e!==o)),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=g(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)),o=null;if(-1!==i)o=this._lines[i];else for(const t of this._groups){const i=t.seriesList.findIndex((t=>t.name===e));if(-1!==i){o=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(!o)return void console.warn(`Series "${e}" not found in legend.`);-1!==i?(this.seriesContainer.removeChild(o.row),this._lines.splice(i,1),this._items=this._items.filter((e=>e!==o))):this._items=this._items.filter((e=>e!==o));let n=this.findGroup(t);n?(n.seriesList.push(o),this.makeSeriesRow(o,n.div)):(n={name:t,seriesList:[o],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(o),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 o=document.createElement("button");o.classList.add("legend-action-button"),o.innerHTML="◇",o.title="Group Actions",o.style.marginRight="0px",o.style.fontSize="1em",o.style.border="none",o.style.background="none",o.style.cursor="pointer",e.seriesList[0]?.colors[0],o.style.color="#ffffff",o.addEventListener("click",(t=>{t.stopPropagation(),t.preventDefault(),"◇"===o.innerHTML?o.innerHTML="◈":o.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 s=document.createElement("span");s.classList.add("toggle-button"),s.style.marginLeft="auto",s.style.fontSize="1.2em",s.style.cursor="pointer",s.innerHTML="⌲",s.setAttribute("aria-expanded","true"),s.addEventListener("click",(t=>{t.stopPropagation(),"none"===e.div.style.display?(e.div.style.display="block",s.innerHTML="⌲",s.setAttribute("aria-expanded","true")):(e.div.style.display="none",s.innerHTML="☰",s.setAttribute("aria-expanded","false"))})),i.appendChild(o),i.appendChild(n),i.appendChild(s),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)||k(t.series);if(!i)return;const o=t.seriesType||"Line",n=t.series.options().priceFormat;if("Line"===o||"Area"===o){const e=i;if(null==e.value)return;const o=this.legendItemFormat(e.value,n.precision);t.div.innerHTML=`\n ${t.legendSymbol[0]||"▨"} \n ${t.name}: ${o}`}else if("Bar"===o||"Candlestick"===o||"Ohlc"===o){const{open:e,close:o}=i;if(null==e||null==o)return;const s=this.legendItemFormat(e,n.precision),a=this.legendItemFormat(o,n.precision),r=o>e,l=r?t.colors[0]:t.colors[1],c=r?t.legendSymbol[0]:t.legendSymbol[1];t.div.innerHTML=`\n ${c||"▨"}\n ${t.name}: \n O ${s}, \n C ${a}`}})):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)||k(t.series);if(!i)return;const o=t.seriesType||"Line",n=t.name,s=t.series.options().priceFormat;if(["Bar","Candlestick","Ohlc"].includes(o)){const{open:e,close:o,high:a,low:r}=i;if(null==e||null==o||null==a||null==r)return;const l=this.legendItemFormat(e,s.precision),c=this.legendItemFormat(o,s.precision),h=o>e,d=h?t.colors[0]:t.colors[1],p=h?t.legendSymbol[0]:t.legendSymbol[1];t.div.innerHTML=`\n ${p||"▨"}\n ${n}: \n O ${l}, \n C ${c}\n `}else{const e="value"in i?i.value:void 0;if(null==e)return;const o=this.legendItemFormat(e,s.precision),a=t.colors[0],r=t.legendSymbol[0]||"▨";t.div.innerHTML=`\n ${r}\n ${n}: ${o}\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 T={lineColor:"#1E80F0",lineStyle:t.LineStyle.Solid,width:4};var D;!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"}(D||(D={}));class L extends o{_paneViews=[];_options;_points=[];_state=D.NONE;_startDragPoint=null;_latestHoverPoint=null;static _mouseIsDown=!1;static hoveredObject=null;static lastHoveredObject=null;_listeners=[];constructor(e){super(),this._options={...T,...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,L._mouseIsDown)this._handleDragInteraction(e);else if(this._mouseIsOverDrawing(e)){if(this._state!=D.NONE)return;this._moveToState(D.HOVERING),L.hoveredObject=L.lastHoveredObject=this}else{if(this._state==D.NONE)return;this._moveToState(D.NONE),L.hoveredObject===this&&(L.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=()=>{L._mouseIsDown=!0,this._onMouseDown()};_handleMouseUpInteraction=()=>{L._mouseIsDown=!1,this._moveToState(D.HOVERING)};_handleDragInteraction(e){if(this._state!=D.DRAGGING&&this._state!=D.DRAGGINGP1&&this._state!=D.DRAGGINGP2&&this._state!=D.DRAGGINGP3&&this._state!=D.DRAGGINGP4)return;const t=L._eventToPoint(e,this.series);if(!t)return;this._startDragPoint=this._startDragPoint||t;const i=L._getDiff(t,this._startDragPoint);this._onDrag(i),this.requestUpdate(),this._startDragPoint=t}}function E(e,t){const i=e.split("."),o={};let n=o;for(let e=0;ee.toUpperCase()))}function O(e,i,o){const n=i.timeScale(),s=o??i.addSeries(t.LineSeries);if(!s)return console.warn("No series found. Cannot perform y-axis conversions."),null;if("logical"in e){const t=e,i=n.logicalToCoordinate(t.logical),o=s.priceToCoordinate(t.price);return null===i||null===o?null:{x:i,y:o}}{const t=e,i=n.coordinateToLogical(t.x),o=n.coordinateToTime(t.x),a=s.coordinateToPrice(t.y);return null===i||null===a?null:{time:o,logical:i,price:a}}}function N(e,t,i,o,n){const s=o-n/2,a=o+n/2;e.beginPath(),e.moveTo(t,s),e.lineTo(t,a),e.lineTo(i,a),e.lineTo(i,s),e.closePath(),e.fill(),e.stroke()}function A(e,t,i,o,n,s){const a=i-t,r=s*Math.min(Math.abs(a),Math.abs(n)),l=Math.abs(Math.min(r,a/2,n/2)),c=o-n/2;e.beginPath(),"function"==typeof e.roundRect?e.roundRect(t,c,a,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 V(e,t,i,o,n,s){const a=t+(i-t)/2,r=i-t;e.beginPath(),e.ellipse(a,n,Math.abs(r/2),Math.abs(s/2),0,0,2*Math.PI),e.fill(),e.stroke()}function $(e,t,i,o,n,a,r,l,c,h,d,p){const u=-Math.max(l,1)*(1-p),m=s(c,.666),g=s(c,.333),y=s(c,.2),f=t-r/2,_=f+l+u,v=f-u,b=_-u;let w,x,C,M;d?(w=n,x=o,C=i,M=a):(w=n,x=i,C=o,M=a),e.fillStyle=g,e.strokeStyle=h,e.beginPath(),e.rect(v,C,l+u-r/2,M-C),e.fill(),e.stroke(),e.fillStyle=y,d?(e.fillStyle=m,e.beginPath(),e.moveTo(f,x),e.lineTo(v,M),e.lineTo(b,M),e.lineTo(_,x),e.closePath(),e.fill(),e.stroke(),e.fillStyle=m,e.beginPath(),e.moveTo(f,w),e.lineTo(v,C),e.lineTo(v,M),e.lineTo(f,x),e.closePath(),e.fill(),e.stroke(),e.fillStyle=m,e.beginPath(),e.moveTo(_,w),e.lineTo(b,C),e.lineTo(b,M),e.lineTo(_,x),e.closePath(),e.fill(),e.stroke(),e.fillStyle=y,e.beginPath(),e.moveTo(f,w),e.lineTo(v,C),e.lineTo(b,C),e.lineTo(_,w),e.closePath(),e.fill(),e.stroke()):(e.fillStyle=y,e.beginPath(),e.moveTo(f,w),e.lineTo(v,C),e.lineTo(b,C),e.lineTo(_,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(_,w),e.lineTo(b,C),e.lineTo(b,M),e.lineTo(_,x),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(f,w),e.lineTo(v,C),e.lineTo(v,M),e.lineTo(f,x),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(f,x),e.lineTo(v,M),e.lineTo(b,M),e.lineTo(_,x),e.closePath(),e.fill(),e.stroke())}function R(e,t,i,o,n,s,a,r){const l=o+n/2,c=o-n/2;e.save(),e.beginPath(),r?(e.moveTo(t,l),e.lineTo(i,s),e.lineTo(i,c),e.lineTo(t,a)):(e.moveTo(t,s),e.lineTo(i,l),e.lineTo(i,a),e.lineTo(t,c)),e.closePath(),e.stroke(),e.fill(),e.restore()}function G(e,t,i,o,n,s,a,r,l){e.save(),e.beginPath(),l?(e.moveTo(t,r),e.lineTo(t,n+s/2),e.lineTo(o,a),e.lineTo(i,n+s/2),e.lineTo(i,r),e.lineTo(o,n-s/2),e.lineTo(t,r)):(e.moveTo(t,a),e.lineTo(t,n-s/2),e.lineTo(o,r),e.lineTo(i,n-s/2),e.lineTo(i,a),e.lineTo(o,n+s/2),e.lineTo(t,a)),e.closePath(),e.fill(),e.stroke(),e.restore()}function B(e,t,i,o,n,s,a){const r=(t+i)/2;e.beginPath(),e.moveTo(r,o),e.lineTo(r,n),e.stroke(),e.beginPath(),e.moveTo(t,s),e.lineTo(r,s),e.stroke(),e.beginPath(),e.moveTo(r,a),e.lineTo(i,a),e.stroke()}class F{_options;constructor(e){this._options=e}}class U extends F{_p1;_p2;_hovered;constructor(e,t,i,o){super(i),this._p1=e,this._p2=t,this._hovered=o}_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 H extends F{_p1;_p2;_p3;_hovered;constructor(e,t,i,o,n){super(o),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()}}const W={...t.customSeriesDefaultOptions,side:"long",mode:"relative",auto:!1,entryColor:"#FFFF00",stopColor:"#FF0000",targetColor:"#00FF00",backgroundColorStop:"rgba(255,0,0,0.25)",backgroundColorTarget:"rgba(0,255,0,0.25)",lineWidth:1,lineStyle:3,partialClosureLineColor:"#FFFFFF",partialClosureLineWidth:1,partialClosureLineDash:[4,2],infoTextColor:"#FFFFFF",infoFont:"12px Arial",positionChangeColor:"#FFFFFF"};class z{_renderer;constructor(){this._renderer=new q}priceValueBuilder(e){return[Math.max(e.entry??NaN,e.stop??NaN,e.target??NaN),Math.min(e.entry??NaN,e.stop??NaN,e.target??NaN),e.entry??NaN]}renderer(){return this._renderer}isWhitespace(e){return void 0===e.entry}update(e,t){this._renderer.update(e,t)}defaultOptions(){return W}}class j{_options;constructor(e){this._options=e}aggregate(e,t){const i=[];let o=0;for(;oo?l:(s??e.length-1)+1}else o++}return i}_aggregateSegment(e,t,i,o,n){if(0===e.length)throw new Error("Segment cannot be empty in _aggregateSegment method.");return{entry:e[0].entry??NaN,stop:e.reduce(((e,t)=>Math.max(e,t.stop??0)),0),target:e.reduce(((e,t)=>Math.min(e,t.target??1/0)),1/0),startIndex:t,endIndex:i,isInProgress:n,displayInfo:e[0].displayInfo??void 0}}_findEndIndex(e,t){for(let i=t+1;ie.time>=o.time));if(r<0)return null;for(let e=r;e=s)return e;if(null!=n&&o<=n)return e}else{if(null!=s&&o<=s)return e;if(null!=n&&o>=n)return e}}return null}}class q{_data=null;_options=null;_aggregator=null;update(e,t){this._data=e,this._options=t,this._aggregator=new j(t)}draw(e,t){this._data&&this._data.bars.length&&this._data.visibleRange&&this._aggregator&&e.useBitmapCoordinateSpace((e=>this._drawImpl(e,t)))}_drawImpl(e,t){if(!(this._data&&this._options&&this._aggregator&&this._data.visibleRange))return;const{context:i,horizontalPixelRatio:o,verticalPixelRatio:n}=e,{from:s,to:a}=this._data.visibleRange,r=this._data.bars,l=this._aggregator.aggregate(r.map((e=>e.originalData)).filter(Boolean),t);i.save(),l.forEach((e=>{if(e.endIndexa)return;const l=r[e.startIndex].x*o,c=r[e.endIndex].x*o,h=(t(e.entry)??0)*n,d=(t(e.stop)??0)*n,p=(t(e.target)??0)*n;this._fillArea(i,l,c,h,d,this._options?.backgroundColorStop??"rgba(255,0,0,0.25)"),this._fillArea(i,l,c,h,p,this._options?.backgroundColorTarget??"rgba(0,255,0,0.25)")})),i.restore()}_calculatePosition(e,t,i){let o=0,n=null;for(let s=e.startIndex;s<=e.endIndex&&se.time>=o.time));if(a<0)return null;for(let e=a;e=s)return e;if(null!=n&&o<=n)return e}}return null}}function J(e,t){if(e._isDecorated)return console.warn("Series is already decorated. Skipping decoration."),e;e._isDecorated=!0;const i=e.setData.bind(e),o=[];let n=null;const s=e.detachPrimitive?.bind(e),a=e.attachPrimitive?.bind(e),r=e.data?.bind(e),l=e.seriesType(),c=e.options().title;function h(e){const i=o.indexOf(e);-1!==i&&(o.splice(i,1),n===e&&(n=null),s&&s(e),t&&(t.removeLegendPrimitive(e),console.log(`Removed primitive of type "${e.constructor.name}" from legend.`)))}function d(){for(console.log("Detaching all primitives.");o.length>0;){h(o.pop())}console.log("All primitives detached.")}return Object.assign(e,{setData:function(e){i(e)},primitives:o,sync:function(e){const t=e.options().seriesType??"Line",i=r();if(!i)return void console.warn("Source data is missing for synchronization.");const o=[...e.data()];for(let n=o.length;n{const i=[...r()];if(!i||0===i.length)return void console.warn("Source data is missing for synchronization.");const o=e.data().slice(-1)[0],n=i.length-1;if(!o||i[n].time>=o.time){const i=Y(e,t,n);i&&(e.update(i),console.log(`Updated/added bar via "update()" for series type ${e.seriesType}`))}}))},attachPrimitive:function(i,s,r=!0,l=!1){const c=i.constructor.type||i.constructor.name;if(r)d();else{const e=o.findIndex((e=>e.constructor.type===c));-1!==e&&h(o[e])}a&&a(i),o.push(i),n=i,console.log(`Primitive of type "${c}" attached.`),t&&l&&t.addLegendPrimitive(e,i,s)},detachPrimitive:h,detachPrimitives:d,decorated:!0,_type:l,title:c,get primitive(){return n},toJSON:()=>({options:e.options(),data:r()}),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 o=t;e.applyOptions({[o]:i[o]})}}}})}function X(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"Trade":return{...t,...W};default:throw new Error(`Unsupported series type: ${e}`)}}function Y(e,t,i){const o=e.data();if(!o||0===o.length)return console.warn("No data available in the source series."),null;const n=o[i];switch(t){case"Line":case"Histogram":case"Area":if(p(n))return{time:n.time,value:n.close};if(d(n))return{time:n.time,value:n.value};if(u(n))return{time:n.time};break;case"Bar":case"Candlestick":case"Ohlc":if(p(n))return{time:n.time,open:n.open,high:n.high,low:n.low,close:n.close};if(u(n))return{time:n.time};break;case"Trade":return{time:n.time,action:n.action??void 0};default:return console.error(`Unsupported target type: ${t}`),null}return console.warn("Could not convert data to the target type."),null}var K;function Z(e,t){return(e=>void 0!==e.primitives)(e)?e:(console.log("Decorating the series dynamically."),J(e,t))}function Q(e,t){const i={...e.paramMap,...t},o=[...e.sourceSeries.data()];if(!o||!Array.isArray(o)||0===o.length)return;let n;n=o.every(p)?o:o.map(ee);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 ee(e){return{time:e.time,open:e.value,high:e.value,low:e.value,close:e.value}}function te(e,i){const o={[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(o)}!function(e){e.Line="Line",e.Histogram="Histogram",e.Area="Area",e.Bar="Bar",e.Candlestick="Candlestick",e.Ohlc="Ohlc",e.Trade="Trade"}(K||(K={}));const ie={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:.7,lineStyle:0,lineColor:"#ffffff",width:1};class oe{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,o,n,s){let a,r;this.handler=e,this._options={...n,...ie},Math.min(i.logical,o.logical)===i.logical?(a=i,r=o):(a=o,r=i),this._originalP1={...a},this._originalP2={...r},this.offset=s??0,this.p1=i,this.p2=o,g(t)?(this.series=t,this._originalData=this.series.data().map(((e,t)=>({...e,x1:t,x2:t})))):(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);s&&s>0?(this._originalSlice=this._originalData.slice(c,Math.min(this.series.data().length-1,c+1+s)),console.log("Data Sliced with Offset",l,c,s,"Offset Point:",Math.min(this.series.data().length-1,c+1+s))):(this._originalSlice=this._originalData.slice(l,c+1),console.log("Data Sliced:",l,c)),s&&s>0&&(this._originalSlice=this._originalSlice.map((e=>({...e,x1:e.x1+s,x2:e.x2+s}))),console.log("Adjusted originalSlice with pOffset:",s)),this.transform=this.recalculateSpatial(),this.p1&&this.p2&&this.setPoints(this.p1,this.p2)}setData(e){this._originalSlice=e}setPoints(e,t){let i,o;Math.min(e.logical,t.logical)===e.logical?(i=e,o=t):(i=t,o=e),null===this._originalP1?(this._originalP1={...i},console.log("First point (p1) set:",this._originalP1)):null===this._originalP2&&(this._originalP2={...o},console.log("Second point (p2) set:",this._originalP2)),this.p1=i,this.p2=o,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,o=((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=o),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!==o?Math.round(100*o)/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 o=[];void 0!==i.open&&o.push(i.open),void 0!==i.high&&o.push(i.high),void 0!==i.low&&o.push(i.low),void 0!==i.close&&o.push(i.close),void 0!==i.value&&o.push(i.value);for(const i of o)it&&(t=i)}));const o=t===e?1:t-e,s=this.p1.logical,a=this._originalSlice.map(((t,a)=>{const r=s+a;function l(t,i){if(void 0===t)return;const n=(t-e)/o;return e-i.shift.y+n*i.scale.y*o}const c=l(t.open,i),h=l(t.close,i),d=l(t.high,i),p=l(t.low,i),u=l(t.value,i);if(void 0!==c||void 0!==h||void 0!==d||void 0!==p){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)",o=e?this._options.borderUpColor||n(i,1):this._options.borderDownColor||n(i,1),s=e?this._options.wickUpColor||o:this._options.wickDownColor||o;return{open:c,close:h,high:d,low:p,isUp:e,x1:r+this.offset,x2:r+this.offset,isInProgress:!1,originalData:{...t,x1:a},barSpacing:this._barWidth,color:i,borderColor:o,wickColor:s,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+this.offset,isInProgress:!1,originalData:t,barSpacing:this._options.barSpacing??.8}})),r=this._options.chandelierSize??1;if(r<=1)return a;const l=[];for(let e=0;eMath.max(e,t.high||0)),0),l=e.reduce(((e,t)=>Math.min(e,t.low||1/0)),1/0),c=a>i,h=c?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)",d=c?this._options.borderUpColor||n(h,1):this._options.borderDownColor||n(h,1),p=c?this._options.wickUpColor||d:this._options.wickDownColor||d,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:l,close:a,isUp:c,x1:o,x2:s,isInProgress:t,color:h,borderColor:d,wickColor:p,shape:this._options.shape??"Rounded",lineStyle:u,lineWidth:m}}{const t=e[0].value??0,i=(e[e.length-1].value??0)>t,a=i?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)";i?this._options.borderUpColor||n(a,1):this._options.borderDownColor||n(a,1);i?this._options.wickUpColor:this._options.wickDownColor;const r=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options.lineStyle),l=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options.lineWidth??1);return this._options.shape,{value:t,isUp:i,x1:o,x2:s,color:a,lineStyle:r,lineWidth:l}}}applyOptions(e){this._options={...this._options,...e},this.processSequence()}}class ne extends o{_type="TrendTrace";_paneViews;_sequence;_options;_state=D.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,o,n,s){super(),this._handler=e,this._source=t,this._originalP1={...i},this._originalP2={...o};const a=this._source.options(),r=function(e,t){const i={};for(const o in e)Object.prototype.hasOwnProperty.call(t,o)&&(i[o]=t[o]);return i}(ie,a);this._options={...r,...n},this._sequence=this._createSequence({p1:i,p2:o},this._options,s),this.p1=this._sequence.p1,this.p2=this._sequence.p2,this._subscribeEvents(),this._paneViews=[new se(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=Z(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 o;return"p1"in e&&"p2"in e?(o=new oe(this._handler,this._source,e.p1,e.p2,t??this._options,i),o.onComplete=()=>this.updateViewFromSequence(),this.updateViewFromSequence(),o):(o=new oe(this._handler,e.data,e.data._originalP1,e.data._originalP2,t??this._options,i),o.onComplete=()=>this.updateViewFromSequence(),this.updateViewFromSequence(),o)}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,ne._mouseIsDown)this._handleDragInteraction(e);else if(this._mouseIsOverSequence(e)){if(this._state!=D.NONE)return;this._moveToState(D.HOVERING),ne.hoveredObject=ne.lastHoveredObject=this}else{if(this._state==D.NONE)return;this._moveToState(D.NONE),ne.hoveredObject===this&&(ne.hoveredObject=null)}}_handleMouseDownOrUp=()=>{this._latestHoverPoint&&(ne._mouseIsDown=!ne._mouseIsDown,ne._mouseIsDown?this._onMouseDown():this._onMouseUp())};_handleMouseMove=e=>{const t=this._eventToPoint(e,this._source);this._latestHoverPoint=t,ne._mouseIsDown?this._handleDragInteraction(e):this._mouseIsOverPoint(e,1)||this._mouseIsOverPoint(e,2)||this._mouseIsOverSequence(e)?this._state===D.NONE&&this._moveToState(D.HOVERING):this._state!==D.NONE&&this._moveToState(D.NONE)};_onMouseUp(){ne._mouseIsDown=!1,this.chart.applyOptions({handleScroll:!0}),this._moveToState(D.HOVERING),this._startDragPoint=null}_handleDragInteraction(e){if(this._state!==D.DRAGGING&&this._state!==D.DRAGGINGP1&&this._state!==D.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,o){const n=function(e){if(!e)return null;const t=e.paneSize();return{width:t.width,height:t.height}}(o);if(!n)return!1;const s=n.width,a=n.height,r=s*i,l=a*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),d=Math.abs(t.y-c.y);return h<=r&&d<=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 D.NONE:document.body.style.cursor="default",this._hovered=!1,this.requestUpdate(),this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case D.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 D.DRAGGINGP1:case D.DRAGGINGP2:case D.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!=D.DRAGGING&&this._state!=D.DRAGGINGP1||this._addDiffToPoint(this._sequence.p1,this._options.xScaleLock&&this._state==D.DRAGGINGP1?0:e.logical,this._options.yScaleLock&&this._state==D.DRAGGINGP1?0:e.price),this._state!=D.DRAGGING&&this._state!=D.DRAGGINGP2||this._addDiffToPoint(this._sequence.p2,this._options.xScaleLock&&this._state==D.DRAGGINGP2?0:e.logical,this._options.yScaleLock&&this._state==D.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(D.DRAGGING);Math.abs(e.x-t.x)<20&&Math.abs(e.y-t.y)<20?(this.chart.applyOptions({handleScroll:!1}),this._moveToState(D.DRAGGINGP1)):Math.abs(e.x-i.x)<20&&Math.abs(e.y-i.y)<20?(this.chart.applyOptions({handleScroll:!1}),this._moveToState(D.DRAGGINGP2)):(this.chart.applyOptions({handleScroll:!1}),this._moveToState(D.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 se{_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 ae(this._plugin,this._plugin._options,!1)}}class ae extends U{_source;_options;constructor(e,t,i){super(O(e._sequence.p1,e.chart,e._source),O(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:o}=e,n=this._source._sequence.data,s=this._source.chart.timeScale(),a=this._source._source,r=i.timeScale().getVisibleLogicalRange(),l=i.options().width/((r?.to??n.length)-(r?.from??0));if(console.log("barSpace:",l),!a||!s||0===n.length)return void t.restore();const c=n[0].x1,h=n[n.length-1].x1,d=i.timeScale().logicalToCoordinate(c)??0,p=i.timeScale().logicalToCoordinate(h)??d,u=d*o,m=p*o,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),o=u+(g?1:-1)*((t+1)*((m-u)/n.length)*this._source._sequence.spatial.scale.x),s=e.isUp?g?this._options.upColor:this._options.downColor:g?this._options.downColor:this._options.upColor,a=e.isUp?g?this._options.borderUpColor:this._options.borderDownColor:g?this._options.borderDownColor:this._options.borderUpColor,r=e.isUp?g?this._options.wickUpColor:this._options.wickDownColor:g?this._options.wickDownColor:this._options.wickUpColor;return{...e,scaledX1:g?i:o,scaledX2:g?o:i,color:s,borderColor:a,wickColor:r}})).filter((e=>null!==e));console.log("Scaled bars:",y),this.isOHLCData(n)?(this._options.wickVisible&&this._drawWicks(e,y,l),this._drawCandles(e,y,l)):this.isSingleValueData(n)&&this._drawSingleValueData(e,y),t.restore()}))}_drawSingleValueData(e,t){const{context:i,horizontalPixelRatio:o,verticalPixelRatio:n}=e;i.lineWidth=this._options.lineWidth??1,te(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*o,s=(this._source._source?.priceToCoordinate(e.value??0)??0)*n;i.lineTo(t,s),i.stroke()}))}_drawWicks(e,t,i){const{context:o,verticalPixelRatio:n}=e,s=this._source._sequence._originalP2.price>this._source._sequence._originalP1.price&&this._source._sequence.p2.price>this._source._sequence.p1.price||this._source._sequence._originalP2.price{const t=(this._options.barSpacing??.8)*(e.scaledX2-e.scaledX1),i=e.scaledX1,a=(i+(i+t))/2,r=(this._source.series.priceToCoordinate(e.high??0)??0)*n,l=(this._source.series.priceToCoordinate(e.low??0)??0)*n,c=(this._source.series.priceToCoordinate(e.open??0)??0)*n,h=(this._source.series.priceToCoordinate(e.close??0)??0)*n,d=s?Math.min(c,h):Math.max(c,h),p=s?Math.max(c,h):Math.min(c,h);o.strokeStyle=this._options.visible?e.wickColor??"#ffffff":"rgba(0,0,0,0)",o.beginPath(),o.moveTo(a,r),o.lineTo(a,d),o.stroke(),o.beginPath(),o.moveTo(a,p),o.lineTo(a,l),o.stroke()}))}_drawCandles(e,t,i){const{context:o,horizontalPixelRatio:n,verticalPixelRatio:s}=e;o.save(),t.forEach((e=>{const t=(this._options.barSpacing??.8)*(e.scaledX2-e.scaledX1);if(!e)return;const i=(this._source.series.priceToCoordinate(e.open)??0)*s,n=(this._source.series.priceToCoordinate(e.close)??0)*s,a=(this._source.series.priceToCoordinate(e.high)??0)*s,l=(this._source.series.priceToCoordinate(e.low)??0)*s,c=n>=i,h=Math.min(i,n),d=Math.max(i,n),p=h-d,u=(h+d)/2,m=e.scaledX1,g=m+t,y=(m+g)/2;o.fillStyle=this._options.visible?e.color??"#ffffff":"rgba(0,0,0,0)",o.strokeStyle=this._options.visible?(this._options.borderVisible?e.borderColor:e.color)??"#ffffff":"rgba(0,0,0,0)",o.lineWidth=e.lineWidth??1,te(o,e.lineStyle);const f=this._options?.shape||r.Rounded;switch(console.log("Selected candle shape:",f),f){case r.Rectangle:N(o,m,g,u,p);break;case r.Rounded:A(o,m,g,u,p,5);break;case r.Ellipse:V(o,m,g,0,u,p);break;case r.Arrow:G(o,m,g,y,u,p,a,l,c);break;case r.Polygon:R(o,m,g,u,p,a,l,c);break;case r.Bar:B(o,m,g,a,l,i,n);break;default:console.warn(`Unknown shape '${f}', using default Rectangle`),N(o,m,g,u,p)}o.restore()}))}_drawEndCircle(e,t,i){const o=e.context;o.save(),o.beginPath(),o.arc(t,i,5,0,2*Math.PI),o.fillStyle=this._options.visible?this._options?.color??"#FF0000":"rgba(0,0,0,0)",o.fill(),o.strokeStyle=this._source._sequence._options.lineColor??"#000",o.stroke(),o.restore()}isOHLCData(e){return e.every((e=>void 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))}}const re={TrendTrace:ne};class le extends L{_paneViews=[];_hovered=!1;linkedObjects=[];constructor(e,t,i){super(),this.points.push(e),this.points.push(t),this._options={...T,...i}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}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}toJSON(){return{points:this.points,_options:this._options,linkedObjects:this.linkedObjects.map((e=>"function"==typeof e.toJSON?e.toJSON():{}))}}fromJSON(e){e&&(e.points&&Array.isArray(e.points)&&e.points.length>=2&&this.updatePoints(e.points[0],e.points[1]),e._options&&(this._options={...this._options,...e._options}),e.linkedObjects&&Array.isArray(e.linkedObjects)&&(this.linkedObjects=e.linkedObjects.map((e=>{const t=e._type;if(!t)return console.warn("Linked object JSON missing _type property."),null;const i=re[t];if(!i)return console.warn(`No constructor found in registry for type: ${t}`),null;const o=new i;return"function"==typeof o.fromJSON&&o.fromJSON(e),o})).filter((e=>null!==e))),this.requestUpdate())}}class ce extends L{_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,o){super(),this.points.push(e),this.points.push(t),this.points.push(i),this._options={...T,...o}}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}toJSON(){return{points:this.points,_options:this._options,linkedObjects:this.linkedObjects.map((e=>"function"==typeof e.toJSON?e.toJSON():{}))}}fromJSON(e){e&&(e.points&&Array.isArray(e.points)&&e.points.length>=2&&this.updatePoints(e.points[0],e.points[1]),e._options&&(this._options={...this._options,...e._options}),e.linkedObjects&&Array.isArray(e.linkedObjects)&&(this.linkedObjects=e.linkedObjects.map((e=>{const t=e._type;if(!t)return console.warn("Linked object JSON missing _type property."),null;const i=re[t];if(!i)return console.warn(`No constructor found in registry for type: ${t}`),null;const o=new i;return"function"==typeof o.fromJSON&&o.fromJSON(e),o})).filter((e=>null!==e))),this.requestUpdate())}}class he extends L{_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,o,n){super(),this.points.push(e),this.points.push(t),this.points.push(i),this.points.push(o),this._options={...T,...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 de{_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=L._eventToPoint(e,this._series);if(!t)return;let i;if(this._drawingType)if(i=this._drawingType.prototype instanceof he?4:this._drawingType.prototype instanceof ce?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=L._eventToPoint(e,this._series);if(!t)return;const i=this._drawingType&&this._drawingType.prototype instanceof ce;this._drawingType&&this._drawingType.prototype instanceof he?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 pe extends U{constructor(e,t,i,o){super(e,t,i,o)}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,te(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 ue{_source;constructor(e){this._source=e}}class me extends ue{_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),o=this._getX(this._source.p1),n=this._getX(this._source.p2);this._p1={x:o,y:t},this._p2={x:n,y:i}}_getX(e){return this._source.chart.timeScale().logicalToCoordinate(e.logical)}}class ge extends ue{_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),o=e.priceToCoordinate(this._source.p3.price),n=this._getX(this._source.p1),s=this._getX(this._source.p2),a=this._getX(this._source.p3);this._p1={x:n,y:t},this._p2={x:s,y:i},this._p3={x:a,y:o}}_getX(e){return this._source.chart.timeScale().logicalToCoordinate(e.logical)}}class ye extends me{constructor(e){super(e)}renderer(){return new pe(this._p1,this._p2,this._source._options,this._source.hovered)}}class fe extends le{_type="TrendLine";constructor(e,t,i){super(e,t,i),this._paneViews=[new ye(this)]}_moveToState(e){switch(e){case D.NONE:document.body.style.cursor="default",this._hovered=!1,this.requestUpdate(),this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case D.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 D.DRAGGINGP1:case D.DRAGGINGP2:case D.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._state!=D.DRAGGING&&this._state!=D.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=D.DRAGGING&&this._state!=D.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(D.DRAGGING);Math.abs(e.x-t.x)<10&&Math.abs(e.y-t.y)<10?this._moveToState(D.DRAGGINGP1):Math.abs(e.x-i.x)<10&&Math.abs(e.y-i.y)<10?this._moveToState(D.DRAGGINGP2):this._moveToState(D.DRAGGING)}_mouseIsOverDrawing(e,t=4){if(!e.point)return!1;const i=this._paneViews[0]._p1.x,o=this._paneViews[0]._p1.y,n=this._paneViews[0]._p2.x,s=this._paneViews[0]._p2.y;if(!(i&&n&&o&&s))return!1;const a=e.point.x,r=e.point.y;if(a<=Math.min(i,n)-t||a>=Math.max(i,n)+t)return!1;return Math.abs((s-o)*a-(n-i)*r+n*o-s*i)/Math.sqrt((s-o)**2+(n-i)**2)<=t}}class _e extends U{constructor(e,t,i,o){super(e,t,i,o)}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,te(t,this._options.lineStyle),t.fillStyle=this._options.fillColor;const o=Math.min(i.x1,i.x2),n=Math.min(i.y1,i.y2),s=Math.abs(i.x1-i.x2),a=Math.abs(i.y1-i.y2);t.strokeRect(o,n,s,a),t.fillRect(o,n,s,a),this._hovered&&(this._drawEndCircle(e,o,n),this._drawEndCircle(e,o+s,n),this._drawEndCircle(e,o+s,n+a),this._drawEndCircle(e,o,n+a))}))}}class ve extends me{constructor(e){super(e)}renderer(){return new _e(this._p1,this._p2,this._source._options,this._source.hovered)}}const be={fillEnabled:!0,fillColor:"rgba(255, 255, 255, 0.2)",...T};class we extends le{_type="Box";constructor(e,t,i){super(e,t,i),this._options={...be,...i},this._paneViews=[new ve(this)]}_moveToState(e){switch(e){case D.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case D.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 D.DRAGGINGP1:case D.DRAGGINGP2:case D.DRAGGINGP3:case D.DRAGGINGP4:case D.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!=D.DRAGGING&&this._state!=D.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=D.DRAGGING&&this._state!=D.DRAGGINGP2||this._addDiffToPoint(this.p2,e.logical,e.price),this._state!=D.DRAGGING&&(this._state==D.DRAGGINGP3&&(this._addDiffToPoint(this.p1,e.logical,0),this._addDiffToPoint(this.p2,0,e.price)),this._state==D.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(D.DRAGGING);const o=10;Math.abs(e.x-t.x)l-p&&ac-p&&r{if(null==this._point.y)return;const t=e.context,i=Math.round(this._point.y*e.verticalPixelRatio),o=this._point.x?this._point.x*e.horizontalPixelRatio:0;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,te(t,this._options.lineStyle),t.beginPath(),t.moveTo(o,i),t.lineTo(e.bitmapSize.width,i),t.stroke()}))}}class Ce extends ue{_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 xe(this._point,this._source._options)}}class Me{_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 L{_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 Ce(this)],this._priceAxisViews=[new Me(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 D.NONE:document.body.style.cursor="default",this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case D.HOVERING:document.body.style.cursor="pointer",this._unsubscribe("mouseup",this._childHandleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case D.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 ke 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()}_mouseIsOverDrawing(e,t=4){if(!e.point)return!1;const i=this.series.priceToCoordinate(this._point.price),o=this._point.time?this.chart.timeScale().timeToCoordinate(this._point.time):null;return!(!i||!o)&&(Math.abs(i-e.point.y)o-t)}}class Pe extends F{_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,te(t,this._options.lineStyle),t.beginPath(),t.moveTo(i,0),t.lineTo(i,e.bitmapSize.height),t.stroke()}))}}class Te extends ue{_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 Pe(this._point,this._source._options)}}class De{_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 L{_type="VerticalLine";_paneViews;_timeAxisViews;_point;_callbackName;_startDragPoint=null;constructor(e,t,i=null){super(t),this._point=e,this._paneViews=[new Te(this)],this._callbackName=i,this._timeAxisViews=[new De(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 D.NONE:document.body.style.cursor="default",this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case D.HOVERING:document.body.style.cursor="pointer",this._unsubscribe("mouseup",this._childHandleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case D.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 o;return o=this._point.time?i.timeToCoordinate(this._point.time):i.logicalToCoordinate(this._point.logical),!!o&&Math.abs(o-e.point.x){this._handleMouseUpInteraction(),this._callbackName&&window.callbackFunction(`${this._callbackName}_~_${this._point.price.toFixed(8)}`)}}class Ee extends H{options;variant;constructor(e,t,i,o,n){super(e,t,i,o,n),this.options=o,this.variant=o.variant??"standard"}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,o=this._getScaledCoordinates(e);if(!o)return;const{x1:n,y1:s,x2:a,y2:r,x3:l,y3:c}=o,h=(a+l)/2,d=(r+c)/2;let p,u,m,g,y,f;const _=(this._options.length??1)*(a-n);if("inside"===this.variant){p=h,u=d;const e=(n+a)/2-l,t=(s+r)/2-c;let i=Math.atan2(t,e);Math.cos(i)<0&&(i+=Math.PI),m=p+_*Math.cos(i),g=u+_*Math.sin(i)}else{const{anchorX:e,anchorY:t}=this._computeAnchorPoint(this.variant,n,s,a,r),i=this._lineIntersection(n,s,a,r,h,d,e,t);i?[p,u]=i:(p=n,u=s);const o=h-p;m=p+_,g=u+(Math.abs(o)>1e-9?(d-u)/o:0)*_}if(y=m-p,f=g-u,i.lineWidth=this.options.width,i.strokeStyle=this.options.lineColor,te(i,this.options.lineStyle),te(i,t.LineStyle.Solid),i.beginPath(),i.moveTo(a,r),i.lineTo(l,c),i.stroke(),te(i,this.options.lineStyle),i.beginPath(),i.moveTo(n,s),i.lineTo(a,r),i.stroke(),i.beginPath(),i.moveTo(p,u),i.lineTo(m,g),i.stroke(),i.beginPath(),i.moveTo(a,r),i.lineTo(a+y,r+f),i.stroke(),i.beginPath(),i.moveTo(l,c),i.lineTo(l+y,c+f),i.stroke(),this.options.forkLines&&this.options.forkLines.length>0){const e=this.options.forkLines;for(let t=0;tMath.max(i,n,a)+t)return!1;const h=this._distanceFromSegment(i,o,n,s,l,c),d=this._distanceFromSegment(n,s,a,r,l,c),p=this._distanceFromSegment(i,o,a,r,l,c);return h<=t||d<=t||p<=t}_distanceFromSegment(e,t,i,o,n,s){const a=i-e,r=o-t,l=a*a+r*r;let c,h,d=0!==l?((n-e)*a+(s-t)*r)/l:-1;d<0?(c=e,h=t):d>1?(c=i,h=o):(c=e+d*a,h=t+d*r);const p=n-c,u=s-h;return Math.sqrt(p*p+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 Ae{static TREND_SVG='';static HORZ_SVG='';static RAY_SVG='';static BOX_SVG='';static VERT_SVG=Ae.RAY_SVG;static PITCHFORK_SVG='';div;activeIcon=null;buttons=[];_commandFunctions;_handlerID;_drawingTool;handler;constructor(e,t,i,o,n){this._handlerID=t,this._commandFunctions=n,this._drawingTool=new de(i,o,(()=>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(fe,"KeyT",Ae.TREND_SVG)),this.buttons.push(this._makeToolBoxElement(Se,"KeyH",Ae.HORZ_SVG)),this.buttons.push(this._makeToolBoxElement(ke,"KeyR",Ae.RAY_SVG)),this.buttons.push(this._makeToolBoxElement(we,"KeyB",Ae.BOX_SVG)),this.buttons.push(this._makeToolBoxElement(Le,"KeyV",Ae.VERT_SVG,!0)),this.buttons.push(this._makeToolBoxElement(Ne,"KeyP",Ae.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 o=!1;return e.style.height="15px",i.onclick=()=>{if(o=!o,o){t.style.display="inline-flex";const o=t.scrollHeight;e.style.height=`${15+o}px`,i.textContent="▲"}else t.style.display="none",e.style.height="15px",i.textContent="▼"},e}_makeToolBoxElement(e,t,i,o=!1){const n=document.createElement("div");n.classList.add("toolbox-button");const s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.setAttribute("width","29"),s.setAttribute("height","29");const a=document.createElementNS("http://www.w3.org/2000/svg","g");a.innerHTML=i,a.setAttribute("fill",window.pane.color),s.appendChild(a),n.appendChild(s);const r={div:n,group:a,type:e};return n.addEventListener("click",(()=>this._onIconClick(r))),this._commandFunctions.push((e=>this._handlerID===window.handlerInFocus&&(!(!e.altKey||e.code!==t)&&(e.preventDefault(),this._onIconClick(r),!0)))),1==o&&(s.style.transform="rotate(90deg)",s.style.transformBox="fill-box",s.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 we(e.points[0],e.points[1],e.options));break;case"TrendLine":this._drawingTool.addNewDrawing(new fe(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 ke(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 Ne(e.points[0],e.points[1],e.points[2],e.options))}}))}}class Ve{makeButton;callbackName;div;isOpen=!1;widget;constructor(e,t,i,o,n,s){this.makeButton=e,this.callbackName=t,this.div=document.createElement("div"),this.div.classList.add("topbar-menu"),this.widget=this.makeButton(o+" ↓",null,n,!0,s),this.updateMenuItems(i),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}_~_${e}`),this.div.style.display="none",this.isOpen=!1}}class $e{_handler;_div;left;right;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")}makeSwitcher(e,t,i,o="left"){const n=document.createElement("div");let s;n.style.margin="4px 12px";const a={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&&(s=i,i.classList.add("active-switcher-button"));const o=$e.getClientWidth(i);return i.style.minWidth=o+1+"px",i.addEventListener("click",(()=>a.onItemClicked(i))),n.appendChild(i),i})),onItemClicked:e=>{e!=s&&(s.classList.remove("active-switcher-button"),e.classList.add("active-switcher-button"),s=e,window.callbackFunction(`${a.callbackName}_~_${e.innerText}`))}};return this.appendWidget(n,o,!0),a}makeTextBoxWidget(e,t="left",i=null){if(i){const o=document.createElement("input");return o.classList.add("topbar-textbox-input"),o.value=e,o.style.width=`${o.value.length+2}ch`,o.addEventListener("focus",(()=>{window.textBoxFocused=!0})),o.addEventListener("input",(e=>{e.preventDefault(),o.style.width=`${o.value.length+2}ch`})),o.addEventListener("keydown",(e=>{"Enter"==e.key&&(e.preventDefault(),o.blur())})),o.addEventListener("blur",(()=>{window.callbackFunction(`${i}_~_${o.value}`),window.textBoxFocused=!1})),this.appendWidget(o,t,!0),o}{const i=document.createElement("div");return i.classList.add("topbar-textbox"),i.innerText=e,this.appendWidget(i,t,!0),i}}makeMenu(e,t,i,o,n){return new Ve(this.makeButton.bind(this),o,e,t,i,n)}makeButton(e,t,i,o=!0,n="left",s=!1){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 r={elem:a,callbackName:t};if(t){let e;if(s){let t=!1;e=()=>{t=!t,window.callbackFunction(`${r.callbackName}_~_${t}`),a.style.backgroundColor=t?"var(--active-bg-color)":"",a.style.color=t?"var(--active-color)":""}}else e=()=>window.callbackFunction(`${r.callbackName}_~_${a.innerText}`);a.addEventListener("click",e)}return o&&this.appendWidget(a,n,i),r}makeSliderWidget(e,t,i,o,n,s="left"){const a=document.createElement("div");a.classList.add("topbar-slider-container"),a.style.display="flex",a.style.alignItems="center",a.style.margin="4px 12px";const r=document.createElement("span");r.classList.add("topbar-slider-label"),r.style.marginRight="8px",r.innerText=o.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=o.toString(),l.style.cursor="pointer",l.addEventListener("input",(()=>{r.innerText=l.value,window.callbackFunction(`${n}_~_${l.value}`)})),a.appendChild(r),a.appendChild(l),this.appendWidget(a,s,!0),a}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 o="left"==t?this.left:this.right;i?("left"==t&&o.appendChild(e),this.makeSeparator(t),"right"==t&&o.appendChild(e)):o.appendChild(e),this._handler.reSize()}static getClientWidth(e){document.body.appendChild(e);const t=e.clientWidth;return document.body.removeChild(e),t}}const Re={title:"",followMode:"tracking",horizontalDeadzoneWidth:45,verticalDeadzoneHeight:100,verticalSpacing:20,topOffset:20};class Ge{_chart;_element;_titleElement;_priceElement;_dateElement;_timeElement;_options;_lastTooltipWidth=null;constructor(e,t){this._options={...Re,...t},this._chart=e;const i=document.createElement("div");Fe(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 o=document.createElement("div");Fe(o,{"font-size":"12px","line-height":"24px","font-weight":"590"}),Be(o,this._options.title),i.appendChild(o);const n=document.createElement("div");Fe(n,{"font-size":"12px","line-height":"18px","font-weight":"590"}),Be(n,""),i.appendChild(n);const s=document.createElement("div");Fe(s,{color:"#787B86"}),Be(s,""),i.appendChild(s);const a=document.createElement("div");Fe(a,{color:"#787B86"}),Be(a,""),i.appendChild(a),this._element=i,this._titleElement=o,this._priceElement=n,this._dateElement=s,this._timeElement=a;const r=this._chart.chartElement();r.appendChild(this._element);const l=r.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}`),Be(this._titleElement,e.title)):console.warn("Title element is missing or title data is undefined."),Be(this._priceElement,e.price),Be(this._dateElement,e.date),Be(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(),o=this._lastTooltipWidth?Math.ceil(this._lastTooltipWidth/2):this._options.horizontalDeadzoneWidth;return`calc(${Math.min(Math.max(o,i),t.timeScale().width()-o)}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 Be(e,t){e&&t!==e.innerText&&(e.innerText=t,e.style.display=t?"block":"none")}function Fe(e,t){for(const[i,o]of Object.entries(t))e.style.setProperty(i,o)}function Ue(e,t,i=1,o){const n=Math.round(t*e),s=Math.round(i*t),a=function(e){return Math.floor(.5*e)}(s);return{position:n-a,length:s}}class He{_data;constructor(e){this._data=e}draw(e){this._data.visible&&e.useBitmapCoordinateSpace((e=>{const t=e.context,i=Ue(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 We{_data;constructor(e){this._data=e}update(e){this._data=e}renderer(){return new He(this._data)}zOrder(){return"bottom"}}const ze={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 je{_options;_tooltip=void 0;_paneViews;_data={x:0,visible:!1,color:"rgba(0, 0, 0, 0.2)",topMargin:0};_attachedParams;constructor(e){this._options={...ze,...e},this._data.color=this._options.lineColor,this._paneViews=[new We(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 i=this.chart(),o=this.series(),n=e.logical;if(!n||!i||!o)return void this._hideCrosshair();const s=e.seriesData.get(o);if(!s)return void this._hideCrosshair();const a=this._options.priceExtractor(s),r=i.timeScale().logicalToCoordinate(n),[l,c]=function(e){if(!e)return["",""];const t=new Date(e),i=t.getFullYear(),o=t.toLocaleString("default",{month:"short"});return[`${t.getDate().toString().padStart(2,"0")} ${o} ${i}`,`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}`]}(e.time?function(e){if(t.isUTCTimestamp(e))return 1e3*e;if(t.isBusinessDay(e))return new Date(e.year,e.month,e.day).valueOf();const[i,o,n]=e.split("-").map(parseInt);return new Date(i,o,n).valueOf()}(e.time):void 0);if(this._tooltip){const t=o.options()?.title||"Unknown Series",i=this._tooltip.options(),n="top"===i.followMode?i.topOffset+10:0;this.setData({x:r??0,visible:null!==r,color:this._options.lineColor,topMargin:n}),this._tooltip.updateTooltipContent({title:t,price:a,date:l,time:c}),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 Ge(e,{...this._options.tooltip})}}let qe=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 o=document.createElement("div");o.style.margin="10px",o.style.display="flex",o.style.flexWrap="wrap",e.colors.forEach((e=>o.appendChild(this.makeColorBox(e))));let n=document.createElement("div");n.style.backgroundColor=window.pane.borderColor,n.style.height="1px",n.style.width="130px";let s=document.createElement("div");s.style.margin="10px";let a=document.createElement("div");a.style.color="lightgray",a.style.fontSize="12px",a.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()},s.appendChild(a),s.appendChild(this._opacitySlider),s.appendChild(this._opacityLabel),this._div.appendChild(o),this._div.appendChild(n),this._div.appendChild(s),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 o=e.extractRGBA(t);return i.addEventListener("click",(()=>{this.rgba=o,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 o=i.match(/\d+/g)?.map(Number);if(!o)return[];let n=i.includes("rgba")?parseFloat(i.split(",")[3]):1;return[o[0],o[1],o[2],n]}updateColor(){if(!L.lastHoveredObject||!this.rgba)return;const e=`rgba(${this.rgba[0]}, ${this.rgba[1]}, ${this.rgba[2]}, ${this.opacity})`;L.lastHoveredObject.applyOptions({[this.colorOption]:e}),this.saveDrawings()}openMenu(t){L.lastHoveredObject&&(this.rgba=e.extractRGBA(L.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 Je{container;_opacitySlider;_opacity_label;exitButton;color="#ff0000";rgba;opacity;applySelection;constructor(e,t){this.applySelection=t,this.rgba=Je.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="150px",this.container.style.height="300px",this.container.style.position="relative";const i=this.createColorGrid(),o=this.createOpacityUI();this.exitButton=this.createExitButton(),this.container.appendChild(i),this.container.appendChild(this.createSeparator()),this.container.appendChild(this.createSeparator()),this.container.appendChild(o),this.container.appendChild(this.exitButton)}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 Je.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=Je.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),console.log("Menu attached:",this.container);const o=this.container.offsetWidth||150,n=this.container.offsetHeight||250;console.log("Submenu dimensions:",{submenuWidth:o,submenuHeight:n});const s=e.clientX,a=e.clientY;console.log("Mouse position:",{cursorX:s,cursorY:a});const r=window.innerWidth,l=window.innerHeight;let c=s+t,h=a;const d=c+o>r?s-o:c,p=h+n>l?l-n-10:h;console.log({left:c,top:h,adjustedLeft:d,adjustedTop:p}),this.container.style.left=`${d}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",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 o=i.match(/\d+/g)?.map(Number)||[0,0,0],n=i.includes("rgba")?parseFloat(i.split(",")[3]):1;return[o[0],o[1],o[2],n]}getElement(){return this.container}update(e,t){this.rgba=Je.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 Xe{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"),Xe._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",(()=>{L.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 Ye={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 Ke extends o{p1;p2;_listeners=[];visibleRange=null;_originalData;_currentSlice=null;_vpData;_paneViews;_options;_pendingUpdate=!1;_state=D.NONE;_latestHoverPoint=null;_startDragPoint=null;static _mouseIsDown=!1;_hovered=!1;chart_;series_;constructor(e,t=Ye,i,o){super(),this.chart_=e.chart,this.series_=e.series;const n=this.series_.data(),s=e.volumeSeries.data(),a=this.chart_.timeScale();this.visibleRange=a.getVisibleLogicalRange(),i&&o?(this.p1=i,this.p2=o):(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={...Ye,...t},s.length>0&&s.every((e=>"value"in e))?this._originalData=n.map(((e,t)=>({...e,x1:t,x2:t,volume:s[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 Ze(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,Ke._mouseIsDown?this._handleDragInteraction(e):this._mouseIsOverPointCanvas(e,1)||this._mouseIsOverPointCanvas(e,2)?this._state===D.NONE&&this._moveToState(D.HOVERING):this._state!==D.NONE&&this._moveToState(D.NONE)};_handleMouseDownOrUp=()=>{Ke._mouseIsDown=!Ke._mouseIsDown,Ke._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(D.DRAGGINGP1):t?this._moveToState(D.DRAGGINGP2):this._moveToState(D.DRAGGING)}_onMouseUp(){Ke._mouseIsDown=!1,this._startDragPoint=null,this._moveToState(D.HOVERING),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}_handleDragInteraction(e){if(this._state!==D.DRAGGING&&this._state!==D.DRAGGINGP1&&this._state!==D.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===D.DRAGGING?(this._addDiffToPoint(this.p1,e.logical,e.price),this._addDiffToPoint(this.p2,e.logical,e.price)):this._state===D.DRAGGINGP1?this._addDiffToPoint(this.p1,e.logical,e.price):this._state===D.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=O(1===t?this.p1:this.p2,this.chart_,this.series_),o=e.point.x-i.x,n=e.point.y-i.y;return o*o+n*n<100}_moveToState(e){switch(e){case D.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleDomMouseDown),this._unsubscribe("mouseup",this._handleDomMouseUp);break;case D.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._subscribe("mousedown",this._handleDomMouseDown),this._unsubscribe("mouseup",this._handleDomMouseUp);break;case D.DRAGGING:case D.DRAGGINGP1:case D.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 o=e/20,n=(i-t)/5,s=2*Math.max(1,Math.floor(Math.max(o,n)));return Math.max(5,s)}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 o=[];let s;if(this._currentSlice&&this._currentSlice.length>0){for(const e of this._currentSlice){const o=e.close??e.open;void 0!==o&&(t=Math.min(t,o),i=Math.max(i,o))}t!==Number.POSITIVE_INFINITY&&i!==Number.NEGATIVE_INFINITY||(t=0,i=1);let a=void 0!==this._options.sections&&this._options.sections>0?this._options.sections:this.calculateDynamicSections(e,t,i);const r=(i===t?1:i-t)/a;for(let e=0;e=i&&t=(e.open??0),i=e.volume||0;t?a+=i:l+=i}}const c=a>=l,h=c?this._options.upColor??n(this.series_.options().upColor,.1)??"rgba(0,128,0,0.1)":this._options.downColor??n(this.series_.options().downColor,.1)??"rgba(128,0,0,0.1)",d=c?this._options.borderUpColor??n(this.series_.options().upColor,.5)??"rgba(0,128,0,0.66)":this._options.borderDownColor??n(this.series_.options().downColor,.5)??"rgba(128,0,0,0.66)";o.push({price:i,upData:a,downData:l,color:this._options.visible?h:"rgba(0,0,0,0)",borderColor:this._options.visible?d:"rgba(0,0,0,0)",minPrice:i,maxPrice:s})}s=this._options.rightSide?this._currentSlice[this._currentSlice.length-1].time:this._currentSlice[0].time}else s=Date.now().toString();return this.update(),{time:s,profile:o,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 Ze{_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_,o=t.timeScale();this._x=o.timeToCoordinate(e.time)??null;const n=o.options().barSpacing??1,s=Math.max(0,Math.min(this._source.p1.logical,this._source.p2.logical)),a=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:(a-s)/3)*n,this._p1=O(this._source.p1,t,i),this._p2=O(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),o=i.priceToCoordinate(t.minPrice);if(null==e||null==o){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,s=this._maxVolume>0?this._width*(n/this._maxVolume):0;let a=0,r=0;n>0&&(a=t.upData/n*s,r=t.downData/n*s),this._items.push({y1:e,y2:o,combinedWidth:s,upWidth:a,downWidth:r,color:t.color,borderColor:t.borderColor})}}}renderer(){return new Qe({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 Qe extends U{_data;options;p1;p2;constructor(e,t,i,o,n){super(t,i,o,n),this._data=e,this.options=o,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),te(t,this.options.lineStyle),this._data.items.forEach((i=>{if(null===i.y1||null===i.y2)return;if(null===this._data.x)return;const o=Math.min(i.y1,i.y2)*e.verticalPixelRatio,n=Math.abs(i.y2-i.y1)*e.verticalPixelRatio,s=i.upWidth+i.downWidth,a=s*e.horizontalPixelRatio;let r;r=this.options.rightSide?(this._data.x-s)*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,r,o,a,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?r+(s-c):r,t.beginPath(),this._drawRoundedRect(t,h,o,c,n,l),t.fillStyle=i.color,t.fill()}}))}))}_drawGrid(e,i){const{items:o,x:n}=this._data;if(!o||0===o.length||null===n)return;if(!this.options.drawGrid)return;let s;s=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)",te(e,this.options.gridLineStyle||t.LineStyle.Solid),o.forEach((t=>{if(null===t.y1||null===t.y2)return;const o=(t.upWidth+t.downWidth)*i.horizontalPixelRatio;let a,r;this.options.rightSide?(a=n-s,r=n-o):(a=n+o,r=n+s);const l=t.y1*i.verticalPixelRatio,c=t.y2*i.verticalPixelRatio;e.beginPath(),e.moveTo(a,l),e.lineTo(r,l),e.stroke(),e.beginPath(),e.moveTo(a,c),e.lineTo(r,c),e.stroke()}))}_drawRoundedRect(e,t,i,o,n,s){const a=Math.abs(Math.min(s,o/2,n/2));e.beginPath(),o>0&&s>0&&(this.options.rightSide?(e.moveTo(t+a,i),e.lineTo(t+o,i),e.lineTo(t+o,i+n),e.lineTo(t+a,i+n),e.arcTo(t,i+n,t,i+n-a,a),e.lineTo(t,i+a),e.arcTo(t,i,t+a,i,a)):(e.moveTo(t,i),e.lineTo(t+o-a,i),e.arcTo(t+o,i,t+o,i+a,a),e.lineTo(t+o,i+n-a),e.arcTo(t+o,i+n,t+o-a,i+n,a),e.lineTo(t,i+n),e.lineTo(t,i)),e.closePath())}}function et(e,t,i){for(let o=0;o=s?t:i}}function tt(e,t,i){const o=e&&t in e?e[t]:i;return Array.isArray(o)?o.map((e=>Number(e))):[Number(o)]}function it(e,t){return t{if(s1?`_${t+1}`:""),p="ALMA"+i+(l>1?` #${t+1}`:"");c.push({key:d,title:p,type:"line",data:h})}return c}},nt=(e,t)=>{let i=0;return e.forEach((e=>{const o=e.close-t;i+=o*o})),Math.sqrt(i/e.length)},st={name:"Bollinger Bands",shortName:"BOLL",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray"},multiplier:{defaultValue:[2],type:"numberArray"}},calc(e,t){const i=tt(t,"length",this.paramMap.length.defaultValue),o=tt(t,"multiplier",this.paramMap.multiplier.defaultValue),n=Math.max(i.length,o.length),s=[];for(let t=0;t{if(l+=t.close,i>=a-1){const o=l/a,n=e.slice(i-(a-1),i+1),s=nt(n,o);c.push({time:t.time,value:o+r*s}),h.push({time:t.time,value:o}),d.push({time:t.time,value:o-r*s}),l-=e[i-(a-1)].close}else c.push({time:t.time,value:NaN}),h.push({time:t.time,value:NaN}),d.push({time:t.time,value:NaN})}));const p=n>1?`_${t+1}`:"";s.push({key:`boll_up${p}`,title:`BOLL_UP${a}${p}`,type:"line",data:c}),s.push({key:`boll_mid${p}`,title:`BOLL_MID${a}${p}`,type:"line",data:h}),s.push({key:`boll_dn${p}`,title:`BOLL_DN${a}${p}`,type:"line",data:d})}return s}},at={name:"Exponential Moving Average",shortName:"EMA",shouldOhlc:!0,paramMap:{length:{defaultValue:[6,12,20],type:"numberArray"}},calc(e,t){const i=tt(t,"length",this.paramMap.length.defaultValue),o=[];return i.forEach(((t,n)=>{let s=0,a=0;const r=[];e.forEach(((i,o)=>{if(a+=i.close,o===t-1)s=a/t;else if(o>t-1){const e=2/(t+1);s=(i.close-s)*e+s}o>=t-1?(r.push({time:i.time,value:s}),a-=e[o-(t-1)].close):r.push({time:i.time,value:NaN})}));const l="ema"+(i.length>1?`_${n+1}`:""),c="EMA"+t+(i.length>1?` #${n+1}`:"");o.push({key:l,title:c,type:"line",data:r})})),o}},rt={name:"Highest High",shortName:"HH",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=tt(t,"length",this.paramMap.length.defaultValue),o=[];return i.forEach(((t,n)=>{const s=[];e.forEach(((i,o)=>{if(o1?`_${n+1}`:""),r="HH"+t+(i.length>1?` #${n+1}`:"");o.push({key:a,title:r,type:"line",data:s})})),o}},lt={name:"Linear Regression",shortName:"LINREG",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=tt(t,"length",this.paramMap.length.defaultValue),o=e.map((e=>e.close)),n=[];return i.forEach(((t,s)=>{const a=[];e.forEach(((e,i)=>{if(ie+t),0),r=(n*o.reduce(((e,t,i)=>e+i*t),0)-s*a)/(n*(n*(n-1)*(2*n-1)/6)-s*s);return r*(n-1)/2+(a-r*s)/n+i}(o.slice(i-(t-1),i+1),t,0);a.push({time:e.time,value:n})}));const r="linreg"+(i.length>1?`_${s+1}`:""),l="LINREG"+t+(i.length>1?` #${s+1}`:"");n.push({key:r,title:l,type:"line",data:a})})),n}},ct={name:"Lowest Low",shortName:"LL",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=tt(t,"length",this.paramMap.length.defaultValue),o=[];return i.forEach(((t,n)=>{const s=[];e.forEach(((i,o)=>{if(o1?`_${n+1}`:""),r="LL"+t+(i.length>1?` #${n+1}`:"");o.push({key:a,title:r,type:"line",data:s})})),o}},ht={name:"Median",shortName:"Median",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=tt(t,"length",this.paramMap.length.defaultValue),o=[];return i.forEach(((t,n)=>{const s=[];e.forEach(((i,o)=>{if(oe.close));n.sort(((e,t)=>e-t));const a=Math.floor(n.length/2),r=n.length%2==0?(n[a-1]+n[a])/2:n[a];s.push({time:i.time,value:r})}));const a="median"+(i.length>1?`_${n+1}`:""),r="Median"+t+(i.length>1?` #${n+1}`:"");o.push({key:a,title:r,type:"line",data:s})})),o}},dt={name:"Moving Average",shortName:"MA",shouldOhlc:!0,paramMap:{length:{defaultValue:[5,10,30,60],type:"numberArray"}},calc(e,t){const i=tt(t,"length",this.paramMap.length.defaultValue),o=[];return i.forEach(((t,n)=>{const s=[];let a=0;e.forEach(((i,o)=>{if(a+=i.close,o>=t-1){const n=a/t;s.push({time:i.time,value:n}),a-=e[o-(t-1)].close}else s.push({time:i.time,value:NaN})}));const r="ma"+(i.length>1?`_${n+1}`:""),l="MA"+t+(i.length>1?` #${n+1}`:"");o.push({key:r,title:l,type:"line",data:s})})),o}},pt={name:"Rolling Moving Average",shortName:"RMA",shouldOhlc:!1,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=tt(t,"length",this.paramMap.length.defaultValue),o=[];return i.forEach(((t,n)=>{const s=1/t;let a=0;const r=[];e.forEach(((e,t)=>{a=0===t?e.close:s*e.close+(1-s)*a,r.push({time:e.time,value:a})}));const l="rma"+(i.length>1?`_${n+1}`:""),c="RMA"+t+(i.length>1?` #${n+1}`:"");o.push({key:l,title:c,type:"line",data:r})})),o}},ut={name:"Simple Moving Average",shortName:"SMA",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray"},k:{defaultValue:[2],type:"numberArray"}},calc(e,t){const i=tt(t,"n",this.paramMap.n.defaultValue),o=tt(t,"k",this.paramMap.k.defaultValue),n=Math.max(i.length,o.length),s=[];for(let t=0;t{l+=t.close,i>=a-1?(c=i===a-1?l/a:(t.close*r+c*(a-r))/a,l-=e[i-(a-1)].close,h.push({time:t.time,value:c})):h.push({time:t.time,value:NaN})}));const d="sma"+(n>1?`_${t+1}`:""),p="SMA"+a+","+r+(n>1?` #${t+1}`:"");s.push({key:d,title:p,type:"line",data:h})}return s}},mt={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=tt(t,"accStart",this.paramMap.accStart.defaultValue),o=tt(t,"accStep",this.paramMap.accStep.defaultValue),n=tt(t,"accMax",this.paramMap.accMax.defaultValue),s=Math.max(i.length,o.length,n.length),a=[];for(let t=0;t{0!==i?(1===i&&(u=t.close>e[0].close,d=u?t.high:t.low,p=u?e[0].low:e[0].high,m.push({time:e[0].time,value:p})),p+=h*(d-p),u?t.lowd&&(d=t.high,h=Math.min(h+l,c)):t.high>p?(u=!0,p=d,h=r,d=t.high):t.low1?`_${t+1}`:""),y="SAR"+r+","+l+","+c+(s>1?` #${t+1}`:"");a.push({key:g,title:y,type:"line",data:m})}return a}},gt={name:"Super Trend",shortName:"SuperTrend",shouldOhlc:!0,paramMap:{factor:{defaultValue:[3],type:"numberArray"},atrPeriod:{defaultValue:[10],type:"numberArray"}},calc(e,t){const i=tt(t,"factor",this.paramMap.factor.defaultValue),o=tt(t,"atrPeriod",this.paramMap.atrPeriod.defaultValue),n=Math.max(i.length,o.length),s=[];for(let t=0;t{if(ip||e[i-1].closed?m:d),u=isNaN(h)?1:h===d?t.close>m?-1:1:t.close1?`_${t+1}`:"";s.push({key:"superTrend"+m,title:"SuperTrend"+a+(n>1?` #${t+1}`:""),type:"line",data:l}),s.push({key:"direction"+m,title:"Direction"+(n>1?` #${t+1}`:""),type:"line",data:c})}return s}},yt={name:"Symmetrically Weighted Moving Average",shortName:"SWMA",shouldOhlc:!1,paramMap:{window:{defaultValue:[4],type:"numberArray"}},calc(e,t){const i=tt(t,"window",this.paramMap.window.defaultValue),o=[];return i.forEach(((t,n)=>{const s=[];e.forEach(((i,o)=>{if(o1?`_${n+1}`:""),r="SWMA"+t+(i.length>1?` #${n+1}`:"");o.push({key:a,title:r,type:"line",data:s})})),o}},ft={name:"TRIX",shortName:"TRIX",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray"},m:{defaultValue:[9],type:"numberArray"}},calc(e,t){const i=tt(t,"n",this.paramMap.n.defaultValue),o=tt(t,"m",this.paramMap.m.defaultValue),n=Math.max(i.length,o.length),s=[];for(let t=0;t{d+=e.close,t===a-1?l=d/a:t>a-1&&(l=(2*e.close+(a-1)*l)/(a+1)),t>=a-1&&(t===2*a-2?c=l:t>2*a-2&&(c=(2*l+(a-1)*c)/(a+1)));let i=NaN;if(t>=2*a-2)if(t===3*a-3)h=c;else if(t>3*a-3){const e=h;h=(2*c+(a-1)*e)/(a+1),i=(h-e)/e*100}if(p.push({time:e.time,value:i}),g.push(i),m+=isNaN(i)?0:i,g.length>r){const e=g[g.length-1-r];m-=isNaN(e)?0:e}const o=g.length>=r&&!isNaN(i)?m/r:NaN;u.push({time:e.time,value:o})}));const y=n>1?`_${t+1}`:"";s.push({key:"trix"+y,title:"TRIX"+a+(n>1?` #${t+1}`:""),type:"line",data:p}),s.push({key:"maTrix"+y,title:n>1?`MATRIX #${t+1}`:"MATRIX",type:"line",data:u})}return s}},_t={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 o=tt(t,"anchorInterval",this.paramMap.anchorInterval.defaultValue),n=[];return o.forEach(((t,s)=>{let a=0,r=0;const l=[];e.forEach(((e,o)=>{o%t==0&&(a=0,r=0);const n=i[o]?.value??0,s=(e.high+e.low+e.close)/3;r+=s*n,a+=n;const c=0!==a?r/a:NaN;l.push({time:e.time,value:c})}));const c=o.length>1?`_${s+1}`:"";n.push({key:"vwap"+c,title:"VWAP"+t+(o.length>1?` #${s+1}`:""),type:"line",data:l})})),n}},vt={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 o=tt(t,"length",this.paramMap.length.defaultValue),n=[];return o.forEach(((t,s)=>{let a=0,r=0;const l=[];e.forEach(((o,n)=>{const s=i[n]?.value??0;if(a+=o.close*s,r+=s,n>=t-1){const s=0!==r?a/r:NaN;l.push({time:o.time,value:s});const c=i[n-(t-1)].value??0;a-=e[n-(t-1)].close*c,r-=c}else l.push({time:o.time,value:NaN})}));const c=o.length>1?`_${s+1}`:"";n.push({key:"vwma"+c,title:"VWMA"+t+(o.length>1?` #${s+1}`:""),type:"line",data:l})})),n}},bt={name:"Weighted Moving Average",shortName:"WMA",shouldOhlc:!1,paramMap:{length:{defaultValue:[9],type:"numberArray"}},calc(e,t){const i=tt(t,"length",this.paramMap.length.defaultValue),o=[];return i.forEach(((t,n)=>{const s=[];e.forEach(((i,o)=>{if(o1?`_${n+1}`:"";o.push({key:"wma"+a,title:"WMA"+t+(i.length>1?` #${n+1}`:""),type:"line",data:s})})),o}},wt=[ot,st,at,rt,{name:"High & Low",shortName:"HHLL",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=tt(t,"length",this.paramMap.length.defaultValue),o=[];return i.forEach(((t,n)=>{const s=[],a=[];e.forEach(((i,o)=>{if(o1?`_${n+1}`:"";o.push({key:"hh"+r,title:"HH"+t+(i.length>1?` #${n+1}`:""),type:"line",data:s}),o.push({key:"ll"+r,title:"LL"+t+(i.length>1?` #${n+1}`:""),type:"line",data:a})})),o}},lt,ct,ht,dt,pt,ut,mt,gt,yt,ft,_t,vt,bt],xt={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=tt(t,"shortPeriod",[5]),o=tt(t,"longPeriod",[34]),n=Math.max(i.length,o.length),s=[];for(let a=0;a{const o=(t.high+t.low)/2;h+=o,d+=o;let n=NaN,s=NaN;if(i>=r-1){n=h/r;const t=(e[i-(r-1)].high+e[i-(r-1)].low)/2;h-=t}if(i>=l-1){s=d/l;const t=(e[i-(l-1)].high+e[i-(l-1)].low)/2;d-=t}let a=NaN;i>=c-1&&(a=n-s),p.push({time:t.time,value:a})}));const u="ao"+(n>1?`_${a+1}`:""),m="AO"+it(i,a)+(n>1?` #${a+1}`:"");et(p,t?.upColor??"green",t?.downColor??"red"),s.push({key:u,title:m,type:"histogram",data:p,pane:1})}return s}},Ct={name:"Average True Range",shortName:"ATR",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=tt(t,"length",[14]),o=[];return i.forEach(((t,n)=>{const s=[];let a=0;const r=[];e.forEach(((i,o)=>{if(0===o)return void s.push({time:i.time,value:NaN});const n=e[o-1].close,l=Math.max(i.high-i.low,Math.abs(i.high-n),Math.abs(i.low-n));r.push(l),a+=l,r.length>t&&(a-=r.shift());const c=r.length>=t?a/t:NaN;s.push({time:i.time,value:c})}));const l=i.length>1?`_${n+1}`:"";o.push({key:"atr"+l,title:"ATR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:s,pane:1})})),o}},Mt={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=tt(t,"period1",[6]),o=tt(t,"period2",[12]),n=tt(t,"period3",[24]),s=Math.max(i.length,o.length,n.length),a=[];for(let t=0;t0)),c=r.map(((e,i)=>({key:`bias${i+1}`+(s>1?`_${t+1}`:""),title:`BIAS${e}`+(s>1?` #${t+1}`:""),type:"line",data:[],pane:1})));e.forEach(((t,i)=>{const o=t.close;r.forEach(((n,s)=>{if(l[s]+=o,i>=n-1){const a=l[s]/n,r=(o-a)/a*100;c[s].data.push({time:t.time,value:r}),l[s]-=e[i-(n-1)].close}else c[s].data.push({time:t.time,value:NaN})}))})),a.push(...c)}return a}},St={name:"Buy-Ratio Analysis",shortName:"BRAR",shouldOhlc:!0,paramMap:{length:{defaultValue:[26],type:"numberArray",min:1}},calc(e,t){const i=tt(t,"length",[26]),o=[];return i.forEach(((t,n)=>{let s=0,a=0,r=0,l=0;const c=[],h=[];e.forEach(((i,o)=>{const n=o-1>=0?e[o-1]:i;if(r+=i.high-i.open,l+=i.open-i.low,s+=i.high-n.close,a+=n.close-i.low,o>=t-1){const n=0!==a?s/a*100:0,d=0!==l?r/l*100:0;c.push({time:i.time,value:n}),h.push({time:i.time,value:d});const p=e[o-(t-1)],u=o-t>=0?e[o-t]:p;s-=p.high-u.close,a-=u.close-p.low,r-=p.high-p.open,l-=p.open-p.low}else c.push({time:i.time,value:NaN}),h.push({time:i.time,value:NaN})}));const d=i.length>1?`_${n+1}`:"";o.push({key:"br"+d,title:"BR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:c,pane:1}),o.push({key:"ar"+d,title:"AR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:h,pane:1})})),o}},kt={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=tt(t,"p1",[3]),o=tt(t,"p2",[6]),n=tt(t,"p3",[12]),s=tt(t,"p4",[24]),a=Math.max(i.length,o.length,n.length,s.length),r=[];for(let t=0;t{const o=t.close;if(p.forEach(((t,n)=>{u[n]+=o,i>=t-1&&(m[n]=u[n]/t,u[n]-=e[i-(t-1)].close)})),i>=Math.max(...p)-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 y=a>1?`_${t+1}`:"";r.push({key:"bbi"+y,title:"BBI"+[l,c,h,d].join(",")+(a>1?` #${t+1}`:""),type:"line",data:g,pane:1})}return r}},Pt={name:"Commodity Channel Index",shortName:"CCI",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray",min:1}},calc(e,t){const i=tt(t,"length",[20]),o=[];return i.forEach(((t,n)=>{let s=0;const a=[],r=[];e.forEach(((i,o)=>{const n=(i.high+i.low+i.close)/3;if(s+=n,a.push(n),o>=t-1){const l=s/t;let c=0;for(let e=o-(t-1);e<=o;e++)c+=Math.abs(a[e]-l);const h=c/t,d=0!==h?(n-l)/(.015*h):0;r.push({time:i.time,value:d});const p=(e[o-(t-1)].high+e[o-(t-1)].low+e[o-(t-1)].close)/3;s-=p}else r.push({time:i.time,value:NaN})}));const l=i.length>1?`_${n+1}`:"";o.push({key:"cci"+l,title:"CCI"+t+(i.length>1?` #${n+1}`:""),type:"line",data:r,pane:1})})),o}},Tt={name:"Current Ratio",shortName:"CR",shouldOhlc:!0,paramMap:{length:{defaultValue:[26],type:"numberArray",min:1}},calc(e,t){const i=tt(t,"length",[26]),o=[];return i.forEach(((t,n)=>{let s=0,a=0;const r=[],l=[],c=[];e.forEach(((i,o)=>{const n=o-1>=0?e[o-1]:i,h=(n.high+n.low)/2,d=Math.max(0,i.high-h),p=Math.max(0,h-i.low);s+=d,a+=p,r.push(d),l.push(p);let u=NaN;o>=t-1&&(u=0!==a?s/a*100:0,s-=r[o-(t-1)],a-=l[o-(t-1)]),c.push({time:i.time,value:u})}));const h=i.length>1?`_${n+1}`:"";o.push({key:"cr"+h,title:"CR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:c,pane:1})})),o}},Dt={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=tt(t,"n1",[10]),o=tt(t,"n2",[50]),n=tt(t,"m",[10]),s=Math.max(i.length,o.length,n.length),a=[];for(let t=0;t{d+=t.close,p+=t.close;let o=NaN,n=NaN;if(i>=r-1&&(o=d/r,d-=e[i-(r-1)].close),i>=l-1&&(n=p/l,p-=e[i-(l-1)].close),i>=h-1){const e=o-n;if(y.push(e),m.push({time:t.time,value:e}),u+=e,y.length>c){u-=y[y.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 f=s>1?`_${t+1}`:"";a.push({key:"dma"+f,title:"DMA"+r+"-"+l+(s>1?` #${t+1}`:""),type:"line",data:m,pane:1}),a.push({key:"ama"+f,title:"AMA"+r+"-"+l+(s>1?` #${t+1}`:""),type:"line",data:g,pane:1})}return a}},Lt={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=tt(t,"n",[14]),o=tt(t,"mm",[6]),n=Math.max(i.length,o.length),s=[];for(let t=0;t{const o=i-1>=0?e[i-1]:t,n=t.high-o.high,s=o.low-t.low,f=Math.max(t.high-t.low,Math.abs(t.high-o.close),Math.abs(o.close-t.low));let _=0,v=0;n>0&&n>s&&(_=n),s>0&&s>n&&(v=s),0===i?(l=f,c=_,h=v):(l=(l*(a-1)+f)/a,c=(c*(a-1)+_)/a,h=(h*(a-1)+v)/a);let b=NaN,w=NaN;0!==l&&(b=c/l*100,w=h/l*100),u.push({time:t.time,value:b}),m.push({time:t.time,value:w});let x=NaN;if(isNaN(b)||isNaN(w)||b+w===0||(x=Math.abs(w-b)/(w+b)*100),i1?`_${t+1}`:"";s.push({key:"pdi"+f,title:"PDI"+a+(n>1?` #${t+1}`:""),type:"line",data:u,pane:1}),s.push({key:"mdi"+f,title:"MDI"+a+(n>1?` #${t+1}`:""),type:"line",data:m,pane:1}),s.push({key:"adx"+f,title:"ADX"+a+(n>1?` #${t+1}`:""),type:"line",data:g,pane:1}),s.push({key:"adxr"+f,title:"ADXR"+a+(n>1?` #${t+1}`:""),type:"line",data:y,pane:1})}return s}},Et={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=tt(t,"n",[12]),o=tt(t,"m",[6]),n=Math.max(i.length,o.length),s=[];for(let t=0;t{if(i>=a){const o=e[i-a],n=t.close-o.close;l.push({time:t.time,value:n}),d.push(n),h+=n,d.length>r&&(h-=d[d.length-1-r]);const s=d.length>=r?h/r:NaN;c.push({time:t.time,value:s})}else l.push({time:t.time,value:NaN}),c.push({time:t.time,value:NaN})}));const p=n>1?`_${t+1}`:"";s.push({key:"mtm"+p,title:"MTM"+a+(n>1?` #${t+1}`:""),type:"line",data:l,pane:1}),s.push({key:"maMtm"+p,title:"MAMTM"+a+(n>1?` #${t+1}`:""),type:"line",data:c,pane:1})}return s}},It={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=tt(t,"n",[12]),o=tt(t,"m",[6]),n=Math.max(i.length,o.length),s=[];for(let t=0;t{const o=i-1>=0?e[i-1]:t,n=t.close>o.close?1:0;if(c.push(n),l+=n,i>=a-1){const e=l/a*100;d.push({time:t.time,value:e}),u.push(e),h+=e,u.length>r&&(h-=u[u.length-1-r]);const o=u.length>=r?h/r:NaN;p.push({time:t.time,value:o}),l-=c[i-(a-1)]}else d.push({time:t.time,value:NaN}),p.push({time:t.time,value:NaN})}));const m=n>1?`_${t+1}`:"";s.push({key:"psy"+m,title:"PSY"+a+(n>1?` #${t+1}`:""),type:"line",data:d,pane:1}),s.push({key:"maPsy"+m,title:"MAPSY"+a+(n>1?` #${t+1}`:""),type:"line",data:p,pane:1})}return s}},Ot={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=tt(t,"n",[12]),o=tt(t,"m",[6]),n=Math.max(i.length,o.length),s=[];for(let t=0;t{if(i>=a){const o=e[i-a].close;let n=0;0!==o&&(n=(t.close-o)/o*100),l.push({time:t.time,value:n}),d.push(n),h+=n,d.length>r&&(h-=d[d.length-1-r]);const s=d.length>=r?h/r:NaN;c.push({time:t.time,value:s})}else l.push({time:t.time,value:NaN}),c.push({time:t.time,value:NaN})}));const p=n>1?`_${t+1}`:"";s.push({key:"roc"+p,title:"ROC"+a+(n>1?` #${t+1}`:""),type:"line",data:l,pane:1}),s.push({key:"maRoc"+p,title:"MAROC"+a+(n>1?` #${t+1}`:""),type:"line",data:c,pane:1})}return s}},Nt={name:"Relative Strength Index",shortName:"RSI",shouldOhlc:!0,paramMap:{p1:{defaultValue:[6],type:"numberArray",min:1},p2:{defaultValue:[12],type:"numberArray",min:1},p3:{defaultValue:[24],type:"numberArray",min:1}},calc(e,t){const i=tt(t,"p1",[6]),o=tt(t,"p2",[12]),n=tt(t,"p3",[24]),s=Math.max(i.length,o.length,n.length),a=[];for(let t=0;t0)),c=r.map((()=>0)),h=r.map(((e,i)=>({key:`rsi${i+1}`+(s>1?`_${t+1}`:""),title:`RSI${e}`+(s>1?` #${t+1}`:""),type:"line",data:[],pane:1})));e.forEach(((t,i)=>{const o=i-1>=0?e[i-1]:t,n=t.close-o.close;r.forEach(((o,s)=>{if(n>0?l[s]+=n:c[s]+=Math.abs(n),i>=o-1){const n=0!==c[s]?100-100/(1+l[s]/c[s]):100;h[s].data.push({time:t.time,value:n});const a=e[i-(o-1)].close-(e[i-o]?.close||0);a>0?l[s]-=a:c[s]-=Math.abs(a)}else h[s].data.push({time:t.time,value:NaN})}))})),a.push(...h)}return a}},At={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=tt(t,"n",[9]),o=tt(t,"kPeriod",[3]),n=tt(t,"dPeriod",[3]),s=Math.max(i.length,o.length,n.length),a=[];for(let t=0;t{if(ie.high))),s=Math.min(...o.map((e=>e.low))),a=n===s?100:(t.close-s)/(n-s)*100,g=((l-1)*h+a)/l,y=((c-1)*d+g)/c,f=3*g-2*y;p.push({time:t.time,value:g}),u.push({time:t.time,value:y}),m.push({time:t.time,value:f}),h=g,d=y}));const g=s>1?`_${t+1}`:"";a.push({key:"k"+g,title:"K"+r+(s>1?` #${t+1}`:""),type:"line",data:p,pane:1}),a.push({key:"d"+g,title:"D"+r+(s>1?` #${t+1}`:""),type:"line",data:u,pane:1}),a.push({key:"j"+g,title:"J"+r+(s>1?` #${t+1}`:""),type:"line",data:m,pane:1})}return a}},Vt={name:"Variance",shortName:"Variance",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=tt(t,"length",[14]),o=[];return i.forEach(((t,n)=>{const s=[];e.forEach(((i,o)=>{if(oe.close)),a=n.reduce(((e,t)=>e+t),0)/n.length,r=n.reduce(((e,t)=>e+Math.pow(t-a,2)),0)/n.length;s.push({time:i.time,value:r})}));const a=i.length>1?`_${n+1}`:"";o.push({key:"variance"+a,title:"Variance"+t+(i.length>1?` #${n+1}`:""),type:"line",data:s,pane:1})})),o}},$t={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=tt(t,"p1",[6]),o=tt(t,"p2",[10]),n=tt(t,"p3",[14]),s=Math.max(i.length,o.length,n.length),a=[];for(let t=0;t({key:`wr${i+1}`+(s>1?`_${t+1}`:""),title:`WR${e}`+(s>1?` #${t+1}`:""),type:"line",data:[],pane:1})));e.forEach(((t,i)=>{r.forEach(((o,n)=>{if(i>=o-1){let s=-1/0,a=1/0;for(let t=i-(o-1);t<=i;t++)s=Math.max(s,e[t].high),a=Math.min(a,e[t].low);const r=s!==a?(t.close-s)/(s-a)*100:0;l[n].data.push({time:t.time,value:r})}else l[n].data.push({time:t.time,value:NaN})}))})),a.push(...l)}return a}},Rt={name:"Change",shortName:"Change",shouldOhlc:!0,paramMap:{length:{defaultValue:[1],type:"numberArray",min:1,max:100}},calc(e,t){const i=tt(t,"length",[1]),o=[];return i.forEach(((t,n)=>{const s=[];e.forEach(((i,o)=>{if(o1?`_${n+1}`:"";o.push({key:"change"+a,title:"Change"+t+(i.length>1?` #${n+1}`:""),type:"line",data:s,pane:1})})),o}},Gt={name:"Range",shortName:"Range",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=tt(t,"length",[14]),o=[];return i.forEach(((t,n)=>{const s=[];e.forEach(((i,o)=>{if(oe.high))),r=Math.min(...n.map((e=>e.low)));s.push({time:i.time,value:a-r})}));const a=i.length>1?`_${n+1}`:"";o.push({key:"range"+a,title:"Range"+t+(i.length>1?` #${n+1}`:""),type:"line",data:s,pane:1})})),o}},Bt={name:"Standard Deviation",shortName:"StdDev",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=tt(t,"length",[14]),o=[];return i.forEach(((t,n)=>{const s=[];e.forEach(((i,o)=>{if(oe.close)),a=n.reduce(((e,t)=>e+t),0)/n.length,r=n.reduce(((e,t)=>e+Math.pow(t-a,2)),0)/n.length,l=Math.sqrt(r);s.push({time:i.time,value:l})}));const a=i.length>1?`_${n+1}`:"";o.push({key:"stdDev"+a,title:"StdDev"+t+(i.length>1?` #${n+1}`:""),type:"line",data:s,pane:1})})),o}},Ft=[...wt,...[xt,Ct,Mt,St,kt,Pt,Tt,Dt,Lt,Et,{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[o,n]of Object.entries(e.paramMap)){const e=t?.[o]??n.defaultValue;i[o]=e}return i}(this,t),o=i.shortPeriod,n=i.longPeriod,s=i.signalPeriod;let a=0,r=0,l=0,c=0,h=0;const d=[],p=[],u=[];let m=0;e.forEach(((e,t)=>{m+=e.close,t===o-1?a=m/o:t>o-1&&(a=(2*e.close+(o-1)*a)/(o+1)),t===n-1?r=m/n:t>n-1&&(r=(2*e.close+(n-1)*r)/(n+1)),t>=Math.max(o,n)-1?(l=a-r,d.push({time:e.time,value:l}),h+=l,d.length===s?c=h/s:d.length>s&&(c=(2*l+(s-1)*c)/(s+1)),d.length>=s?(p.push({time:e.time,value:c}),u.push({time:e.time,value:2*(l-c)})):(p.push({time:e.time,value:NaN}),u.push({time:e.time,value:NaN}))):(d.push({time:e.time,value:NaN}),p.push({time:e.time,value:NaN}),u.push({time:e.time,value:NaN}))}));return et(u,t?.upColor??"green",t?.downColor??"red"),[{key:"dif",title:"DIF",type:"line",data:d,pane:1},{key:"dea",title:"DEA",type:"line",data:p,pane:1},{key:"macd",title:"MACD",type:"histogram",data:u,pane:1}]}},It,Ot,Nt,At,Vt,$t,Rt,Gt,Bt]];class Ut{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 o={type:i||e._type||e.constructor.name,object:e.toJSON(),title:e.title},n=JSON.stringify(o,null,2);let s={};e instanceof Zt?s=e.chart.options():void 0!==e.options?s="function"==typeof e.options?e.options():e.options:void 0!==e._options&&(s=e._options);const a={...s},r=JSON.stringify(a,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 d=document.createElement("div");d.style.display="flex",d.style.borderBottom="1px solid #555",d.style.marginBottom="10px";const p=document.createElement("button");p.textContent="Options",p.style.flex="1",p.style.padding="10px",p.style.cursor="pointer",p.style.border="none",p.style.backgroundColor="options"===this.currentTab?"#555":"#333",p.onclick=()=>{this.currentTab="options",p.style.backgroundColor="#555",u.style.backgroundColor="#333",g.value=r,v.style.display="flex",y.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",p.style.backgroundColor="#333",g.value=n,y.style.display="flex",v.style.display="none"},d.appendChild(p),d.appendChild(u),h.appendChild(d);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:r,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 y=document.createElement("div");y.style.display="full"===this.currentTab?"flex":"none",y.style.flexWrap="wrap",y.style.justifyContent="flex-end",y.style.gap="10px";const f=document.createElement("button");f.textContent="Export",f.style.padding="8px 12px",f.style.cursor="pointer",f.style.backgroundColor="#f44336",f.style.color="#fff",f.style.border="none",f.style.borderRadius="4px",f.onclick=()=>{this.downloadJson(n,`${e.title}_full.json`)},y.appendChild(f);const _=document.createElement("button");_.textContent="Import",_.style.padding="8px 12px",_.style.cursor="pointer",_.style.backgroundColor="#4CAF50",_.style.color="#fff",_.style.border="none",_.style.borderRadius="4px",_.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")}},y.appendChild(_);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 b=document.createElement("button");b.textContent="Export Options",b.style.padding="8px 12px",b.style.cursor="pointer",b.style.backgroundColor="#f44336",b.style.color="#fff",b.style.border="none",b.style.borderRadius="4px",b.onclick=()=>{this.downloadJson(r,`${e.title}_options.json`)},v.appendChild(b);const w=document.createElement("button");w.textContent="Import Options",w.style.padding="8px 12px",w.style.cursor="pointer",w.style.backgroundColor="#4CAF50",w.style.color="#fff",w.style.border="none",w.style.borderRadius="4px",w.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],o=new FileReader;o.onload=()=>{try{const t=o.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")}},o.readAsText(i)}})),t.click()},v.appendChild(w);const x=document.createElement("button");x.textContent="Save",x.style.padding="8px 12px",x.style.cursor="pointer",x.style.backgroundColor="#008CBA",x.style.color="#fff",x.style.border="none",x.style.borderRadius="4px",x.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(),this.showNotification("Options saved 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 Zt?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 o;if(e._type&&"custom/custom"===e._type.toLowerCase()){if(o=prompt("Enter save key (e.g., area, line, candlestick):",e.title.toLowerCase())||"",!o)return}else o=e._type?e._type.toLowerCase():e.title.toLowerCase();const n=`save_defaults_~_${o};;;${i}`;window.callbackFunction(n)},this.container.appendChild(C);const M=document.createElement("div");M.style.display="flex",M.style.flexDirection="column",M.style.gap="10px",M.appendChild(y),M.appendChild(v),M.appendChild(x),M.appendChild(C),h.appendChild(M),l.appendChild(h),this.container.appendChild(l)}downloadJson(e,t){try{const i=new Blob([e],{type:"application/json"}),o=URL.createObjectURL(i),n=document.createElement("a");n.href=o,n.download=t,n.click(),URL.revokeObjectURL(o)}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 Zt?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),o=prompt("Enter save key (area, line, trend-trace, candlestick etc):",e.title.toLowerCase());if(!o)return;const n=`save_defaults_${o}_~_${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");const o=JSON.stringify(i,null,2),n=document.createElement("div");n.style.position="fixed",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",n.style.backgroundColor="rgba(0,0,0,0.5)",n.style.display="flex",n.style.justifyContent="center",n.style.alignItems="center",n.style.zIndex="1000";const s=e=>{"Escape"===e.key&&this.close(n,s)};document.addEventListener("keydown",s);const a=document.createElement("div");a.style.backgroundColor="#333",a.style.color="#fff",a.style.padding="20px",a.style.borderRadius="8px",a.style.width="80%",a.style.maxWidth="800px",a.style.maxHeight="90%",a.style.overflowY="auto",a.style.boxShadow="0 2px 10px rgba(0,0,0,0.5)",a.setAttribute("tabindex","-1"),a.focus();const r=document.createElement("h2");r.textContent=`Edit Default Options - "${e}"`,a.appendChild(r);const l=document.createElement("textarea");l.value=o,l.style.width="100%",l.style.height="400px",l.style.resize="vertical",l.style.backgroundColor="#444",l.style.color="#fff",l.style.border="none",l.style.margin="10px 0",l.style.padding="10px",a.appendChild(l);const c=document.createElement("div");c.style.display="flex",c.style.flexWrap="wrap",c.style.gap="10px",c.style.justifyContent="flex-end";const h=document.createElement("button");h.textContent="Export",h.style.padding="8px 12px",h.style.cursor="pointer",h.style.backgroundColor="#f44336",h.style.color="#fff",h.style.border="none",h.style.borderRadius="4px",h.onclick=()=>{this.downloadJson(l.value,`${e}_defaults.json`)},c.appendChild(h);const d=document.createElement("button");d.textContent="Import",d.style.padding="8px 12px",d.style.cursor="pointer",d.style.backgroundColor="#4CAF50",d.style.color="#fff",d.style.border="none",d.style.borderRadius="4px",d.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.");l.value=i.result}catch(e){this.showNotification("Failed to read defaults file: "+e.message,"error")}},i.readAsText(t)}})),e.click()},c.appendChild(d);const p=document.createElement("button");p.textContent="Save",p.style.padding="8px 12px",p.style.cursor="pointer",p.style.backgroundColor="#008CBA",p.style.color="#fff",p.style.border="none",p.style.borderRadius="4px",p.onclick=()=>{try{const i=JSON.parse(l.value);t.set(e,i),this.showNotification(`Defaults for "${e}" saved successfully.`,"success")}catch(e){this.showNotification("Failed to save defaults: "+e.message,"error")}},c.appendChild(p);const u=document.createElement("button");u.textContent="Cancel",u.style.padding="8px 12px",u.style.cursor="pointer",u.style.backgroundColor="#444",u.style.color="#fff",u.style.border="none",u.style.borderRadius="4px",u.onclick=()=>{this.close(n,s)},c.appendChild(u),a.appendChild(c),n.appendChild(a),this.container.appendChild(n)}}class Ht{container;backdrop;isOpen=!1;categories=[];contentArea;activeCategoryId="";handler;colorPicker=null;constructor(e){this.handler=e,this.backdrop=document.createElement("div"),this.backdrop.style.position="fixed",this.backdrop.style.top="0",this.backdrop.style.left="0",this.backdrop.style.width="100%",this.backdrop.style.height="100%",this.backdrop.style.backgroundColor="rgba(0,0,0,0.5)",this.backdrop.style.opacity="0",this.backdrop.style.transition="opacity 0.3s ease",this.backdrop.style.zIndex="9998",this.backdrop.style.display="none",this.backdrop.addEventListener("click",(e=>{e.target===this.backdrop&&this.close(!1)})),document.body.appendChild(this.backdrop),this.container=document.createElement("div"),this.container.style.position="fixed",this.container.style.top="50%",this.container.style.left="50%",this.container.style.transform="translate(-50%, -50%)",this.container.style.width="700px",this.container.style.maxWidth="90%",this.container.style.height="500px",this.container.style.maxHeight="90%",this.container.style.backgroundColor="#2B2B2B",this.container.style.color="#FFF",this.container.style.borderRadius="6px",this.container.style.boxShadow="0 2px 10px rgba(0,0,0,0.8)",this.container.style.zIndex="9999",this.container.style.opacity="0",this.container.style.display="none",this.container.style.transition="opacity 0.3s ease, transform 0.3s ease",document.body.appendChild(this.container);const t=document.createElement("div");t.style.display="flex",t.style.alignItems="center",t.style.justifyContent="space-between",t.style.padding="12px 16px",t.style.borderBottom="1px solid #3C3C3C";const i=document.createElement("div");i.innerText="Settings",i.style.fontSize="16px",i.style.fontWeight="bold",t.appendChild(i);const o=document.createElement("div");o.innerText="×",o.style.fontSize="20px",o.style.cursor="pointer",o.onclick=()=>this.close(!1),t.appendChild(o),this.container.appendChild(t);const n=document.createElement("div");n.style.display="flex",n.style.flex="1 1 auto",n.style.height="calc(100% - 50px)",this.container.appendChild(n);const s=document.createElement("div");s.style.width="150px",s.style.borderRight="1px solid #3C3C3C",s.style.display="flex",s.style.flexDirection="column",n.appendChild(s),this.contentArea=document.createElement("div"),this.contentArea.style.flex="1",this.contentArea.style.padding="16px",this.contentArea.style.overflowY="auto",n.appendChild(this.contentArea);const a=document.createElement("div");a.style.borderTop="1px solid #3C3C3C",a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="space-between",a.style.padding="8px 12px";const r=document.createElement("button");r.innerText="Template ▾",r.style.backgroundColor="#444",r.style.color="#FFF",r.style.border="none",r.style.borderRadius="4px",r.style.padding="6px 12px",a.appendChild(r);const l=document.createElement("div");l.style.display="flex",l.style.gap="8px";const c=document.createElement("button");c.innerText="Cancel",c.style.backgroundColor="#444",c.style.color="#FFF",c.style.border="none",c.style.borderRadius="4px",c.style.padding="6px 12px",c.style.cursor="pointer",c.onclick=()=>this.close(!1),l.appendChild(c);const h=document.createElement("button");h.innerText="Ok",h.style.backgroundColor="#008CBA",h.style.color="#FFF",h.style.border="none",h.style.borderRadius="4px",h.style.padding="6px 12px",h.style.cursor="pointer",h.onclick=()=>this.close(!0),l.appendChild(h),a.appendChild(l),this.container.appendChild(a),this.categories=[{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 Options",buildContent:()=>this.buildTimeScaleOptionsTab()},{id:"price-scale-options",label:"Price Scale Options",buildContent:()=>this.buildPriceScaleOptionsTab()},{id:"series-list",label:"Series List",buildContent:()=>this.buildSeriesListTab()},{id:"defaults-list",label:"Defaults",buildContent:()=>this.buildDefaultsListTab()}],this.categories.forEach((e=>{const t=document.createElement("div");t.innerText=e.label,t.style.padding="8px 16px",t.style.cursor="pointer",t.style.borderBottom="1px solid #3C3C3C",t.addEventListener("click",(()=>this.switchCategory(e.id))),s.appendChild(t)})),this.categories.length>0&&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))}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="14px",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 o=this.handler.chart.options().layout?.background;if(o&&"solid"===o.type){const e=o.color||"#FFFFFF";this.addColorPicker("Background Color",e,(e=>{this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.Solid,color:e}}})}))}else if(o&&o.type===t.ColorType.VerticalGradient){const e=o.topColor||"rgba(255,0,0,0.33)",i=o.bottomColor||"rgba(0,255,0,0.33)";this.addColorPicker("Top Color",e,(e=>{this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.VerticalGradient,topColor:e,bottomColor:i}}})})),this.addColorPicker("Bottom Color",i,(i=>{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="14px",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 o=this.getCurrentOptionValue("grid.horzLines.color")||"#D6DCDE";this.addColorPicker("Horizontal Line Color",o,(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};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 s=!1!==this.getCurrentOptionValue("grid.vertLines.visible");this.addCheckbox("Show Vertical Lines",s,(e=>{this.handler.chart.applyOptions({grid:{vertLines:{visible:e}}})}));const a=!1!==this.getCurrentOptionValue("grid.horzLines.visible");this.addCheckbox("Show Horizontal Lines",a,(e=>{this.handler.chart.applyOptions({grid:{horzLines:{visible:e}}})}))}buildCrosshairOptionsTab(){const e=document.createElement("div");e.innerText="Crosshair Options",e.style.fontSize="14px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const t=this.getCurrentOptionValue("crosshair.vertLine.color")||"#000000";this.addColorPicker("Vertical Line Color",t,(e=>{this.handler.chart.applyOptions({crosshair:{vertLine:{color:e}}})}));const i=this.getCurrentOptionValue("crosshair.horzLine.color")||"#000000";this.addColorPicker("Horizontal Line Color",i,(e=>{this.handler.chart.applyOptions({crosshair:{horzLine:{color:e}}})}))}buildTimeScaleOptionsTab(){const e=document.createElement("div");e.innerText="Time Scale Options",e.style.fontSize="14px",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 o=this.getCurrentOptionValue("timeScale.minBarSpacing")||.1;this.addNumberField("Min Bar Spacing",o,(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 s=this.getCurrentOptionValue("timeScale.fixRightEdge")||!1;this.addCheckbox("Fix Right Edge",s,(e=>{this.handler.chart.applyOptions({timeScale:{fixRightEdge:e}})}));const a=this.getCurrentOptionValue("timeScale.lockVisibleTimeRangeOnResize")||!1;this.addCheckbox("Lock Visible Range on Resize",a,(e=>{this.handler.chart.applyOptions({timeScale:{lockVisibleTimeRangeOnResize:e}})}));const r=this.getCurrentOptionValue("timeScale.visible");this.addCheckbox("Time Scale Visible",!1!==r,(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="14px",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 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}],n=o.map((e=>e.label));this.addDropdown("Price Scale Mode",n,(e=>{const t=o.find((t=>t.label===e));t&&i.applyOptions({mode:t.value})}));const s=void 0===i.options().autoScale||i.options().autoScale;this.addCheckbox("Auto Scale",s,(e=>{i.applyOptions({autoScale:e})}));const a=i.options().invertScale||!1;this.addCheckbox("Invert Scale",a,(e=>{i.applyOptions({invertScale:e})}));const r=void 0===i.options().alignLabels||i.options().alignLabels;this.addCheckbox("Align Labels",r,(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})}))}buildSeriesListTab(){const e=document.createElement("div");e.innerText="Series List",Object.assign(e.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(e);Array.from(this.handler.seriesMap.entries()).forEach((([e,t])=>{this.addButton(e,(()=>this.buildSeriesMenuTab(t)),{backgroundColor:"#444",borderRadius:"8px"})}))}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}),this.handler.seriesMap.has(e.options().title)&&this.handler.seriesMap.delete(e.options().title),this.handler.seriesMap.set(t,e)})),this.addButton("Clone Series ▸",(()=>{alert("Clone Series functionality not implemented in modal demo.")})),this.addButton("Visibility Options ▸",(()=>{alert("Visibility Options not implemented in modal demo.")})),this.addButton("Style Options ▸",(()=>{alert("Style Options not implemented in modal demo.")})),this.addButton("Width Options ▸",(()=>{alert("Width Options not implemented in modal demo.")})),this.addButton("Color Options ▸",(()=>{alert("Color Options not implemented in modal demo.")})),this.addButton("Price Scale Options ▸",(()=>{alert("Price Scale Options not implemented in modal demo.")})),this.addButton("Primitives ▸",(()=>{alert("Primitives not implemented in modal demo.")})),this.addButton("Indicators ▸",(()=>{alert("Indicators not implemented in modal demo.")})),this.addButton("Export/Import Series Data ▸",(()=>{alert("Export/Import Series Data not implemented in modal demo.")})),this.addButton("⤝ Back to Series List",(()=>this.buildSeriesListTab()),{backgroundColor:"#444"})}buildDefaultsListTab(){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(),o=Array.from(i.keys());if(0===o.length){const e=document.createElement("div");return e.innerText="No default configurations found.",e.style.color="#ccc",void this.contentArea.appendChild(e)}o.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){const o=document.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px",fontFamily:"sans-serif",fontSize:"14px"});const n=document.createElement("span");n.innerText=e,o.appendChild(n);const s=document.createElement("input");s.type="color",s.value=t,Object.assign(s.style,{border:"none",borderRadius:"8px",width:"32px",height:"32px",cursor:"pointer",padding:"2px"}),s.oninput=()=>i(s.value),o.appendChild(s),this.contentArea.appendChild(o)}addDropdown(e,t,i){const o=document.createElement("div");o.style.display="flex",o.style.alignItems="center",o.style.marginBottom="8px",o.style.justifyContent="space-between",o.style.marginBottom="8px";const n=document.createElement("span");n.innerText=e,o.appendChild(n);const s=document.createElement("select");s.style.backgroundColor="#444",s.style.color="#fff",s.style.border="1px solid #555",s.style.borderRadius="4px",s.style.outline="none",t.forEach((e=>{const t=document.createElement("option");t.value=e,t.innerText=e,s.appendChild(t)})),s.onchange=()=>i(s.value),o.appendChild(s),this.contentArea.appendChild(o)}addButton(e,t,i){const o=document.createElement("button");o.innerText=e,Object.assign(o.style,{padding:"8px 12px",margin:"4px 0",backgroundColor:"#008CBA",color:"#fff",border:"none",borderRadius:"8px",cursor:"pointer",fontFamily:"sans-serif",fontSize:"14px"}),i&&Object.assign(o.style,i),o.onclick=t,this.contentArea.appendChild(o)}addNumberField(e,t,i){const o=document.createElement("div");o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="space-between",o.style.marginBottom="8px";const n=document.createElement("span");n.innerText=e,o.appendChild(n);const s=document.createElement("input");s.type="number",s.value=t.toString(),s.style.width="60px",s.style.backgroundColor="#444",s.style.color="#fff",s.style.border="1px solid #555",s.style.borderRadius="4px",s.oninput=()=>{const e=parseFloat(s.value);i(isNaN(e)?0:e)},o.appendChild(s),this.contentArea.appendChild(o)}addCheckbox(e,t,i){const o=document.createElement("label");o.style.display="flex",o.style.alignItems="center",o.style.marginBottom="8px";const n=document.createElement("input");n.type="checkbox",n.checked=t,n.style.marginRight="8px",n.onchange=()=>i(n.checked),o.appendChild(n);const s=document.createElement("span");s.innerText=e,o.appendChild(s),this.contentArea.appendChild(o)}getCurrentOptionValue(e){const t=e.split(".");let i=this.handler.chart.options();for(const o of t){if(!i||!(o in i))return console.warn(`Option path "${e}" is invalid.`),null;i=i[o]}return i}toggleBackgroundType(){const e=this.handler.chart.options().layout?.background;let i;i=e&&"solid"===e.type?{type:t.ColorType.VerticalGradient,topColor:"rgba(255,0,0,0.2)",bottomColor:"rgba(0,255,0,0.2)"}:{type:"solid",color:"#000000"},this.handler.chart.applyOptions({layout:{background:i}}),this.buildLayoutOptionsTab()}addTextInput(e,t,i){const o=document.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px",fontFamily:"sans-serif",fontSize:"14px"});const n=document.createElement("span");n.innerText=e,o.appendChild(n);const s=document.createElement("input");s.type="text",s.value=t,Object.assign(s.style,{width:"150px",padding:"4px",backgroundColor:"#444",color:"#fff",border:"1px solid #555",borderRadius:"4px"}),s.oninput=()=>i(s.value),o.appendChild(s),this.contentArea.appendChild(o)}}let Wt=null;class zt{handler;handlerMap;getMouseEventParams;div;hoverItem;items=[];colorPicker=new Je("#ff0000",(()=>null));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)),this.dataMenu=new Ut({contextMenu:this,handler:this.handler}),this.SettingsModal=new Ht(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},dynamicCandles:{skip:!0},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 o=document.createElement("span");o.classList.add("context-menu-item"),this.div.appendChild(o);const n=document.createElement("span");if(n.innerText=e,n.style.pointerEvents="none",o.appendChild(n),i){let e=document.createElement("span");e.innerText="►",e.style.fontSize="8px",e.style.pointerEvents="none",o.appendChild(e)}if(o.addEventListener("mouseover",(()=>{this.hoverItem&&this.hoverItem.closeAction&&this.hoverItem.closeAction(),this.hoverItem={elem:n,action:t,closeAction:i}})),i){let e;o.addEventListener("mouseover",(()=>e=setTimeout((()=>t(o.getBoundingClientRect())),100))),o.addEventListener("mouseout",(()=>clearTimeout(e)))}else o.addEventListener("click",(e=>{t(e),this.div.style.display="none"}));this.items.push(o)}_onClick(e){const t=e.target;[this.colorPicker].forEach((e=>{e.getElement().contains(t)||e.closeMenu()}))}_onRightClick(e){e.preventDefault();const t=this.getMouseEventParams(),i=this.getProximitySeries(this.getMouseEventParams()),o=this.getProximityDrawing(),n=this.getProximityTrendTrace();console.log("Mouse Event Params:",t),console.log("Proximity Series:",i),console.log("Proximity Drawing:",o),this.clearMenu(),this.clearAllMenus(),i?(console.log("Right-click detected on a series (proximity)."),this.populateSeriesMenu(i,e),this.recentSeries=i):o?(console.log("Right-click detected on a drawing."),this.populateDrawingMenu(e,o),this.recentDrawing=o):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 L.hoveredObject?L.hoveredObject:null}getProximityTrendTrace(){return ne.hoveredObject?ne.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 o=this.handler._seriesList[0];if(this.handler.series)i=this.handler.series,console.log("Using handler.series for coordinate conversion.");else{if(!o)return console.warn("No handler.series or referenceSeries available."),null;i=o,console.log("Using referenceSeries for coordinate conversion.")}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 s=[];return e.seriesData.forEach(((e,t)=>{let i;if(d(e)?i=e.value:p(e)&&(i=e.close),void 0!==i&&!isNaN(i)){const e=Math.abs(i-n);if(e/n*100<=3.33){const i=Z(t,this.handler.legend);s.push({distance:e,series:i})}}})),s.sort(((e,t)=>e.distance-t.distance)),s.length>0?(console.log("Closest series found."),s[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),Wt=this.div,console.log("Displaying Menu",t,i),document.addEventListener("mousedown",this.hideMenuOnOutsideClick.bind(this),{once:!0})}hideMenuOnOutsideClick(e){this.div.contains(e.target)||this.hideMenu()}hideMenu(){this.div.style.display="none",Wt===this.div&&(Wt=null)}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,o,n,s){return this.addMenuInput(this.div,{type:"number",label:e,value:t,onChange:i,min:o,max:n,step:s})}addCheckbox(e,t,i){return this.addMenuInput(this.div,{type:"boolean",label:e,value:t,onChange:i})}addSelectInput(e,t,i,o){return this.addMenuInput(this.div,{type:"select",label:e,value:t,onChange:o,options:i})}addMenuInput(e,t,i=""){const o=document.createElement("div");if(o.classList.add("context-menu-item"),o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="space-around",o.style.width="90%",t.label){const e=document.createElement("label");e.innerText=t.label,e.htmlFor=`${i}${t.label.toLowerCase()}`,e.style.flex="0.8",e.style.whiteSpace="nowrap",o.appendChild(e)}let n;switch(t.type){case"hybrid":{if(!t.hybridConfig)throw new Error("Hybrid type requires hybridConfig.");const e=document.createElement("div");e.classList.add("context-menu-item"),e.style.position="relative",e.style.cursor="pointer",e.style.display="flex",e.style.textAlign="center",e.style.marginLeft="auto",e.style.marginRight="8px";const i=document.createElement("span");i.innerText=t.sublabel??"Action",i.style.flex="1",e.appendChild(i);const o=document.createElement("span");o.innerText="▼",o.style.marginLeft="8px",o.style.color="#fff",e.appendChild(o);const s=document.createElement("div");s.style.position="absolute",s.style.backgroundColor="#2b2b2b",s.style.color="#fff",s.style.border="1px solid #444",s.style.borderRadius="4px",s.style.minWidth="100px",s.style.boxShadow="0px 2px 5px rgba(0, 0, 0, 0.5)",s.style.zIndex="10000",s.style.display="none",e.appendChild(s),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(),s.style.display="none",e.action()})),t.addEventListener("mouseenter",(()=>{t.style.backgroundColor="#444"})),t.addEventListener("mouseleave",(()=>{t.style.backgroundColor="#2b2b2b"})),s.appendChild(t)})),e.addEventListener("click",(e=>{e.stopPropagation(),s.style.display="block"===s.style.display?"none":"block"}));const a=document.createElement("div");a.classList.add("context-menu-item"),a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="space-between",a.style.cursor="pointer",a.addEventListener("click",(()=>{t.hybridConfig.defaultAction()})),a.appendChild(e),document.addEventListener("click",(()=>{s.style.display="none"})),n=a;break}case"number":{const e=document.createElement("input");e.type="number",e.value=void 0!==t.value?t.value.toString():"",e.style.backgroundColor="#2b2b2b",e.style.color="#fff",e.style.border="1px solid #444",e.style.borderRadius="4px",e.style.textAlign="center",e.style.marginLeft="auto",e.style.marginRight="8px",e.style.width="40px",void 0!==t.min&&(e.min=t.min.toString()),void 0!==t.max&&(e.max=t.max.toString()),void 0===t.step||isNaN(t.step)?e.step="1":e.step=t.step.toString(),e.addEventListener("input",(e=>{const i=e.target;let o=parseFloat(i.value);isNaN(o)||t.onChange(o)})),n=e;break}case"boolean":{const e=document.createElement("input");e.type="checkbox",e.checked=t.value??!1,e.style.marginLeft="auto",e.style.marginRight="8px",e.addEventListener("change",(e=>{const i=e.target;t.onChange(i.checked)})),n=e;break}case"select":{const e=document.createElement("select");e.id=`${i}${t.label?t.label.toLowerCase():"select"}`,e.style.backgroundColor="#2b2b2b",e.style.color="#fff",e.style.border="1px solid #444",e.style.borderRadius="4px",e.style.marginLeft="auto",e.style.marginRight="8px",e.style.width="80px",t.options?.forEach((i=>{const o=document.createElement("option");o.value=i,o.text=i,o.style.whiteSpace="normal",o.style.textAlign="right",i===t.value&&(o.selected=!0),e.appendChild(o)})),e.addEventListener("change",(e=>{const i=e.target;t.onChange(i.value)})),n=e;break}case"string":{const e=document.createElement("input");e.type="text",e.value=t.value??"",e.style.backgroundColor="#2b2b2b",e.style.color="#fff",e.style.border="1px solid #444",e.style.borderRadius="4px",e.style.marginLeft="auto",e.style.textAlign="center",e.style.marginRight="8px",e.style.width="60px",e.addEventListener("input",(e=>{const i=e.target;t.onChange(i.value)})),n=e;break}case"color":{const e=document.createElement("input");e.type="color",e.value=t.value??"#000000",e.style.marginLeft="auto",e.style.cursor="pointer",e.style.marginRight="8px",e.style.width="100px",e.addEventListener("input",(e=>{const i=e.target;t.onChange(i.value)})),n=e;break}default:throw new Error("Unsupported input type")}return o.style.padding="2px 10px 2px 10px",o.appendChild(n),e.appendChild(o),o}addMenuItem(e,t,i=!0,o=!1,n=1){const s=document.createElement("span");if(s.classList.add("context-menu-item"),s.innerText=e,o){const e=document.createElement("span");e.classList.add("submenu-arrow"),e.innerText="ː".repeat(n),s.appendChild(e)}s.addEventListener("click",(e=>{e.stopPropagation(),t(),i&&this.hideMenu()}));const a=["➩","➯","➱","➬","➫"];return s.addEventListener("mouseenter",(()=>{if(s.style.backgroundColor="royalblue",s.style.color="white",!s.querySelector(".hover-arrow")){const e=document.createElement("span");e.classList.add("hover-arrow");const t=Math.floor(Math.random()*a.length),i=a[t];e.innerText=i,e.style.marginLeft="auto",e.style.fontSize="8px",e.style.color="white",s.appendChild(e)}})),s.addEventListener("mouseleave",(()=>{s.style.backgroundColor="",s.style.color="";const e=s.querySelector(".hover-arrow");e&&s.removeChild(e)})),this.div.appendChild(s),this.items.push(s),s}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,o){const n=document.createElement("span");n.classList.add("context-menu-item"),n.innerText=e,this.div.appendChild(n);const s=e=>{const t=E(i,e);o.applyOptions(t),console.log(`Updated ${i} to ${e}`);if("object"==typeof(n=o)&&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===o));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 Je(t??"#000000",s)),this.colorPicker.openMenu(e,225,s)})),n}currentWidthOptions=[];currentStyleOptions=[];populateSeriesMenu(e,i){const o=Z(e,this.handler.legend),n=e.options();if(!n)return void console.warn("No options found for the selected series.");this.div.innerHTML="";const s=[],a=[],l=[],c=[],h=[];for(const e of Object.keys(n)){const i=n[e];if(this.shouldSkipOption(e))continue;if(e.toLowerCase().includes("base"))continue;const o=I(e).toLowerCase(),p=o.includes("width")||"radius"===o||o.includes("radius");if(o.includes("color"))"string"==typeof i?s.push({label:e,value:i}):console.warn(`Expected string value for color option "${e}".`);else if(p){if("number"==typeof i){let t=1,n=10,s=1;o.includes("radius")&&(t=0,n=1,s=.1),c.push({name:e,label:e,value:i,min:t,max:n,step:s})}}else if(o.includes("visible")||o.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(I(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(o.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(o.includes("shape")){if(d=i,Object.values(r).includes(d)){const t=["Rectangle","Rounded","Ellipse","Arrow","3d","Polygon","Bar"];t&&h.push({name:e,label:e,value:i,options:t})}}else l.push({label:e,value:i})}var d;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 o=this.handler.legend._lines.find((t=>t.series===e));o&&o.series===e&&(o.name=t,console.log(`Updated legend title to: ${t}`)),e.applyOptions(i),console.log(`Updated title to: ${t}`)}));const p=e.getPane().paneIndex(),u=this.handler.chart.panes(),m=`Pane ${p}`,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:m,value:m,onChange:e=>{const t=g.find((t=>t.name===e));t&&t.action()},hybridConfig:{defaultAction:()=>{0===p?u.length>1?(e.moveToPane(1),console.log(`Default: Moved series from pane ${p} to pane 1.`)):(e.moveToPane(u.length),console.log(`Default: Moved series from pane ${p} to a new pane at index ${u.length}.`)):(e.moveToPane(0),console.log(`Default: Moved series from pane ${p} 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),s.length>0&&this.addMenuItem("Color Options ▸",(()=>{this.populateColorOptionsMenu(s,e,i)}),!1,!0),n.enableVolumeOpacity&&this.addNumberInput("Volume Opacity Period",n.volumeOpacityPeriod??21,(t=>{const i={volumeOpacityPeriod:t};e.applyOptions(i),console.log(`Updated Volume Opacity Period to ${t}`)}),1,1e4,1),l.forEach((t=>{const i=I(t.label);if(!this.constraints[t.label]?.skip)if("boolean"==typeof t.value)this.addCheckbox(I(t.label),Boolean(t.value),(i=>{const o=E(t.label,i);e.applyOptions(o),console.log(`Updated ${t.label} to ${i}`)}));else if("string"==typeof t.value){const o=this.getPredefinedOptions(t.label);o&&o.length>0?this.addMenuItem(`${i} ▸`,(()=>{this.div.innerHTML="",this.addSelectInput(i,t.value,o,(i=>{const o=E(t.label,i);e.applyOptions(o),console.log(`Updated ${t.label} to ${i}`)}))}),!1,!0):this.addMenuItem(`${i} ▸`,(()=>{this.div.innerHTML="",this.addTextInput(i,t.value,(i=>{const o=E(t.label,i);e.applyOptions(o),console.log(`Updated ${t.label} to ${i}`)}))}),!1,!0)}else{if("number"!=typeof t.value)return;{const o=this.constraints[t.label]?.min,n=this.constraints[t.label]?.max;this.addNumberInput(i,t.value,(i=>{const o=E(t.label,i);e.applyOptions(o),console.log(`Updated ${t.label} to ${i}`)}),o,n)}}})),this.addMenuItem("Price Scale Options ▸",(()=>{this.populatePriceScaleMenu(i,e.options().priceScaleId??"right",e)}),!1,!0),this.addMenuItem("Primitives ▸",(()=>{this.populatePrimitivesMenu(o,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 Ut({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 de(this.handler.chart,this.handler._seriesList[0]));for(const e of Object.keys(t._options)){let t;if(e.toLowerCase().includes("color"))t=new qe(this.saveDrawings,e);else{if("lineStyle"!==e)continue;t=new Xe(this.saveDrawings)}const i=e=>t.openMenu(e);this.menuItem(I(e),i,(()=>{document.removeEventListener("click",t.closeMenu),t._div.style.display="none"}))}if("PitchFork"===t._type){const i=t._options.variant||"standard",o=["standard","schiff","modifiedSchiff","inside"];this.addSelectInput("Pitchfork Variant",i,o,(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 Ut({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 ne?this.addMenuItem(`${t.title} Options`,(()=>{this.populateTrendTraceMenu(e,t)}),!1,!0):t instanceof Ke&&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(),this.addMenuInput(this.div,{type:"hybrid",label:"Display Volume Profile",sublabel:"Settings",hybridConfig:{defaultAction:()=>{this.volumeProfile?(this.handler.series.detachPrimitive(this.volumeProfile),this.volumeProfile=null,console.log("[ChartMenu] Detached Volume Profile.")):(this.volumeProfile=new Ke(this.handler,Ye),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()}),!1),this.showMenu(e)}populateLayoutMenu(e){this.div.innerHTML="";const t="Text Color",i="layout.textColor",o=this.getCurrentOptionValue(i)||"#000000";this.addColorPickerMenuItem(I(t),o,i,this.handler.chart);const n=this.handler.chart.options().layout?.background;c(n)?this.addColorPickerMenuItem("Background Color",n.color||"#FFFFFF","layout.background.color",this.handler.chart):h(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 o;o=c(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:o}}),this.populateLayoutMenu(e)}populateWidthMenu(e,t){this.div.innerHTML="",this.currentWidthOptions.forEach((e=>{"number"==typeof e.value&&this.addNumberInput(I(e.label),e.value,(i=>{const o=E(e.name,i);t.applyOptions(o),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 o=i?.FillArea??i?.pt;i.FillArea&&this.addMenuItem("Customize Fill Area",(()=>{this.customizeFillAreaOptions(t,o)}),!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(I(e.name),e.value.toString(),i,(i=>{let o=i;if(e.name.toLowerCase().includes("style")){o={Solid:0,Dotted:1,Dashed:2,"Large Dashed":3,"Sparse Dotted":4}[i]??0}else if(e.name.toLowerCase().includes("linetype")){o={Simple:0,WithSteps:1,Curved:2}[i]??0}const n=E(e.name,o);if(t.applyOptions(n),console.log(`Updated ${e.name} to "${i}" =>`,o),e.name.toLowerCase().includes("style")&&"Line"===t.seriesType()){const e=o,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(),o=["Line","Histogram","Area"];if(i&&i.length>0){i.some((e=>p(e)))&&o.push("Bar","Candlestick","Ohlc")}o.forEach((t=>{this.addMenuItem(`Clone as ${t}`,(()=>{const i=function(e,t,i,o){try{const n={...X(i),...o};let s;switch(console.log(`Cloning ${e.seriesType()} as ${i}...`),i){case"Line":s=t.createLineSeries(i,n);break;case"Histogram":s=t.createHistogramSeries(i,n);break;case"Area":s=t.createAreaSeries(i,n);break;case"Bar":s=t.createBarSeries(i,n);break;case"Candlestick":s={name:o.name,series:t.createCandlestickSeries()};break;case"Ohlc":s=t.createCustomOHLCSeries(i,n);break;default:return console.error(`Unsupported series type: ${i}`),null}let a=e.data().map(((t,o)=>Y(e,i,o))).filter((e=>null!==e));return s.series.setData(a),e.applyOptions({visible:!1}),e.subscribeDataChanged((()=>{const t=e.data().map(((t,o)=>Y(e,i,o))).filter((e=>null!==e));s.series.setData(t),console.log(`Updated synced series of type ${i}`)})),s.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 o=document.createElement("div");o.classList.add("context-menu-item"),o.style.display="flex",o.style.alignItems="center",o.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",o.appendChild(n);const s=document.createElement("input");return s.type="text",s.value=t,s.id=`${e.toLowerCase()}-input`,s.style.flex="0 0 100px",s.style.marginLeft="auto",s.style.backgroundColor="#2b2b2b",s.style.color="#fff",s.style.border="1px solid #444",s.style.borderRadius="4px",s.style.cursor="pointer",s.addEventListener("input",(e=>{const t=e.target;i(t.value)})),o.appendChild(s),this.div.appendChild(o),o}populateColorOptionsMenu(e,t,i){this.div.innerHTML="",e.forEach((e=>{this.addColorPickerMenuItem(I(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 o=i[e];"boolean"==typeof o&&this.addCheckbox(I(e),o,(i=>{const o=E(e,i);t.applyOptions(o),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(I("Top Color"),t.topColor,"layout.background.topColor",this.handler.chart),this.addColorPickerMenuItem(I("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(I(e.name),t,e.valuePath,this.handler.chart):"select"===e.type?this.addSelectInput(I(e.name),t,e.options,(t=>{const i=e.options.indexOf(t),o=E(e.valuePath,i);this.handler.chart.applyOptions(o),console.log(`Updated ${e.name} to: ${t}`)})):"boolean"===e.type&&this.addCheckbox(I(e.name),t,(t=>{const i=E(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(I(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(I("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(I(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(I(e.name),t,(t=>{const i=E(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(I(e.name),t,(t=>{const i=E(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(I(e.name),t,e.valuePath,this.handler.chart)}})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populatePriceScaleMenu(e,i="right",o){if(this.div.innerHTML="",o)this.addMenuInput(this.div,{type:"hybrid",label:"Price Scale",value:o.options().priceScaleId||"",onChange:e=>{o.applyOptions({priceScaleId:e}),console.log(`Updated price scale to: ${e}`)},hybridConfig:{defaultAction:()=>{const e="left"===o.options().priceScaleId?"right":"left";o.applyOptions({priceScaleId:e}),console.log(`Series price scale switched to: ${e}`)},options:[{name:"Left",action:()=>o.applyOptions({priceScaleId:"left"})},{name:"Right",action:()=>o.applyOptions({priceScaleId:"right"})},{name:"Volume",action:()=>o.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=o.options().priceScaleId||"",t.addEventListener("change",(()=>{o.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,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}],a=s.map((e=>e.label));this.addSelectInput("Price Scale Mode",s.find((e=>e.value===n))?.label||"Normal",a,(t=>{const n=s.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,o))}));const r=this.handler.chart.priceScale(i).options();[{name:"Auto Scale",value:r.autoScale??!0,action:e=>{this.applyPriceScaleOptions(i,{autoScale:e}),console.log(`Price scale (${i}) autoScale set to: ${e}`)}},{name:"Invert Scale",value:r.invertScale??!1,action:e=>{this.applyPriceScaleOptions(i,{invertScale:e}),console.log(`Price scale (${i}) invertScale set to: ${e}`)}},{name:"Align Labels",value:r.alignLabels??!0,action:e=>{this.applyPriceScaleOptions(i,{alignLabels:e}),console.log(`Price scale (${i}) alignLabels set to: ${e}`)}},{name:"Border Visible",value:r.borderVisible??!0,action:e=>{this.applyPriceScaleOptions(i,{borderVisible:e}),console.log(`Price scale (${i}) borderVisible set to: ${e}`)}},{name:"Ticks Visible",value:r.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,o)}),!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 o of t){if(!i||!(o in i))return console.warn(`Option path "${e}" is invalid.`),null;i=i[o]}return i}setBackgroundType(e,i){const o=this.handler.chart.options().layout?.background;let n;if(i===t.ColorType.Solid)n=c(o)?{type:t.ColorType.Solid,color:o.color}:{type:t.ColorType.Solid,color:"#000000"};else{if(i!==t.ColorType.VerticalGradient)return void console.error(`Unsupported ColorType: ${i}`);n=h(o)?{type:t.ColorType.VerticalGradient,topColor:o.topColor,bottomColor:o.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 y(t,e,{...v}),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"],"Candle Shape":["Rectangle","Rounded","Ellipse","Arrow","3d","Polygon","Bar"]}[I(e)]||null}populateSeriesListMenu(e,t,i){this.div.innerHTML="";let o=[...Array.from(this.handler.seriesMap.entries()).map((([e,t])=>({label:e,value:t})))];if(this.handler.volumeSeries){o=[{label:"Volume",value:this.handler.volumeSeries},...o]}console.log(o),o.forEach((o=>{this.addMenuItem(o.label,(()=>{i(o.value),t?this.hideMenu():(this.div.innerHTML="",this.populateSeriesMenu(o.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:"Axis",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 ne(this.handler,e,t.p1,t.p2,ie,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 Ke(this.handler,Ye,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 Ut({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(),o=[];t._sequence.data.every((e=>void 0!==e.open&&void 0!==e.high&&void 0!==e.low&&void 0!==e.close))?o.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"}):o.push({name:"Line Color",type:"color",valuePath:"lineColor",defaultValue:i.lineColor??"#ffffff"}),o.forEach((e=>{this.addColorPickerMenuItem(I(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(),o=[];t._sequence.data.every((e=>void 0!==e.open&&void 0!==e.high&&void 0!==e.low&&void 0!==e.close))&&o.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:r.Rectangle},{label:"Rounded",value:r.Rounded},{label:"Ellipse",value:r.Ellipse},{label:"Arrow",value:r.Arrow},{label:"Polygon",value:r.Polygon},{label:"Bar",value:r.Bar}]},{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}),o.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}]}),o.push({name:"Line Width",type:"number",valuePath:"lineWidth",defaultValue:i.lineWidth??1,min:.5,max:10,step:.5}),o.push({name:"Visible",type:"boolean",valuePath:"visible",defaultValue:i.visible??!0}),o.forEach((e=>{if("number"===e.type)this.addNumberInput(I(e.name),e.defaultValue,(i=>{const o=E(e.valuePath,i);t.applyOptions(o),console.log(`Updated ${e.name} to: ${i}`)}),e.min,e.max,e.step);else if("boolean"===e.type)this.addCheckbox(I(e.name),e.defaultValue,(i=>{const o=E(e.valuePath,i);t.applyOptions(o),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(I(e.name),e.defaultValue,i,(i=>{const o=e.options.find((e=>e.label===i));if(o){const i=E(e.valuePath,o.value);t.applyOptions(i),console.log(`Updated ${e.name} to: ${o.value}`)}}))}})),this.addMenuItem("⤝ Trend Trace Menu",(()=>this.populateTrendTraceMenu(e,t)),!1),this.showMenu(e)}populateVolumeProfileMenu(e,t){this.div.innerHTML="";const i=t._options,o=[];o.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}]}),o.push({name:"Up Color",type:"color",valuePath:"upColor",defaultValue:i.upColor??Ye.upColor},{name:"Down Color",type:"color",valuePath:"downColor",defaultValue:i.downColor??Ye.downColor},{name:"Border Up Color",type:"color",valuePath:"borderUpColor",defaultValue:i.borderUpColor??Ye.borderUpColor},{name:"Border Down Color",type:"color",valuePath:"borderDownColor",defaultValue:i.borderDownColor??Ye.borderDownColor},{name:"Grid Color",type:"color",valuePath:"gridColor",defaultValue:i.gridColor??Ye.gridColor}),o.forEach((e=>{if("number"===e.type)this.addNumberInput(I(e.name),e.defaultValue,(i=>{const o=E(e.valuePath,i);t.applyOptions(o),console.log(`Updated ${e.name} to: ${i}`)}),e.min,e.max,e.step);else if("boolean"===e.type)this.addCheckbox(I(e.name),e.defaultValue,(i=>{const o=E(e.valuePath,i);t.applyOptions(o),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(I(e.name),e.defaultValue,i,(i=>{const o=e.options.find((e=>e.label===i));if(o){const i=E(e.valuePath,o.value);t.applyOptions(i),console.log(`Updated ${e.name} to: ${o.value}`)}}))}else"color"===e.type&&this.addColorPickerMenuItem(I(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="",Ft.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,o=!1){let n;this.div.innerHTML="";const s="sourceSeries"in e?e:e.series,a=e.indicator,r="paramMap"in e?e.paramMap:{},l={};let c=!1,h=0;Object.entries(a.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&&o&&(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(a.paramMap).forEach((([t,o])=>{const n=t,s=void 0!==r[t]?r[t]:o.defaultValue;if("numberArray"===o.type||"selectArray"===o.type||"booleanArray"===o.type||"stringArray"===o.type){const a=i??e.figureCount,r=o.type.replace("Array","");l[t]=[];for(let e=0;e{l[t]||(l[t]=[]),l[t][e]=i}),o.min,o.max,o.step):"boolean"===r?this.addCheckbox(`${n} ${e+1}`,Boolean(i),(i=>{l[t]||(l[t]=[]),l[t][e]=i})):"select"===r?this.addSelectInput(`${n} ${e+1}`,String(i),o.options||[],(i=>{l[t]||(l[t]=[]),l[t][e]=i})):"string"===r&&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"===o.type?(this.addNumberInput(n,s,(e=>{l[t]=e}),o.min,o.max,o.step),l[t]=s):"boolean"===o.type?(this.addCheckbox(n,Boolean(s),(e=>{l[t]=e})),l[t]=s):"select"===o.type?(this.addSelectInput(n,String(s),o.options||[],(e=>{l[t]=e})),l[t]=s):(this.addMenuInput(this.div,{type:"string",label:n,value:s,onChange:e=>{l[t]=e}}),l[t]=s)})),this.addMenuItem("Apply",(()=>{this.hideMenu(),Object.entries(l).forEach((([e,t])=>{a.paramMap[e]&&(a.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,s),t.name=e.options().title)}))):this.applyIndicator(s,a,l,n)}),!1),this.addMenuItem("Cancel",(()=>{this.hideMenu()}),!1),this.showMenu(t)}applyIndicator(e,t,i,o){const n=[...e.data()];if(!n||0===n.length)return void console.warn("No data found on this series.");let s;s=n.every(p)?n:n.map(ee);const a=this.handler.volumeSeries.data(),r=t.calc([...s],i,a??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),o=t[i[Math.floor(Math.random()*i.length)]];if(e===o.length)return o;const n=[];for(let t=0;t{const a=c[s];let h=null;if("histogram"===n.type){const i=this.handler.createHistogramSeries(n.title,{color:a,base:0,title:n.title,...r.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:a,lineWidth:2,title:n.title,...r.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 s=function(e,t,i,o,n,s,a){const r=Object.assign(e,{sourceSeries:t,indicator:i,figures:o,paramMap:s,figureCount:n,recalculate:function(e){a(this,e)}});return"function"==typeof t.subscribeDataChanged&&t.subscribeDataChanged((()=>{t.data()[t.data().length-1].time>e.data()[e.data().length-1].time&&a(r)})),r}(h,e,t,l,o,i,Q);if(l.set(n.key,s),n.pane&&s.getPane()===e.getPane()){const e=s.getPane().paneIndex();s.moveToPane(e+n.pane)}}})),this.indicatorSeriesMap.set(t.name,l)}populateForkLineMainMenu(e,i){if(this.div.innerHTML="","PitchFork"!==i._type)return;const o=i._options;o.forkLines||(o.forkLines=[]);const n=o.forkLines;n.forEach(((t,o)=>{this.addMenuItem(`Fork Line ${o+1}`,(()=>{this.populateForkLineOptions(e,i,o)}),!1,!0)})),this.addMenuItem("Add Fork Line",(()=>{const o={value:.5,width:1,style:t.LineStyle.Solid,color:"#ffffff",fillColor:void 0};n.push(o),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,o){this.div.innerHTML="";const n=i._options;if(!n.forkLines||!n.forkLines[o])return;const s=n.forkLines[o];this.addNumberInput("Value",s.value,(e=>{s.value=e,this.saveDrawings&&this.saveDrawings()}),0,10,.1),this.addNumberInput("Width",s.width,(e=>{s.width=e,this.saveDrawings&&this.saveDrawings()}),1,10,1);const a=[{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",a.find((e=>e.var===s.style))?.name||a[0].name,a.map((e=>e.name)),(e=>{const t=a.find((t=>t.name===e));t&&(s.style=t.var,this.saveDrawings&&this.saveDrawings())})),this.addForkLineColorPickerMenuItem("Color",s.color,s,"color"),this.addForkLineColorPickerMenuItem("Fill Color",s.fillColor||"",s,"fillColor"),this.addMenuItem("Remove Fork Line",(()=>{n.forkLines.splice(o,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,o){const n=document.createElement("span");n.classList.add("context-menu-item"),n.innerText=e,this.div.appendChild(n);const s=e=>{i[o]=e,console.log(`Updated fork line ${o} to ${e}`),this.saveDrawings&&this.saveDrawings()};return n.addEventListener("click",(e=>{e.stopPropagation(),this.colorPicker||(this.colorPicker=new Je(t??"#000000",s)),this.colorPicker.openMenu(e,225,s)})),n}}function jt(e){return function(e){return Math.max(1,Math.floor(e))}(e)/e}class qt{_options;constructor(e){this._options=e}staticAggregate(e,t){const i=this._options?.chandelierSize??1,o=[];for(let n=0;nvoid 0!==e.volume&&"number"==typeof e.volume))){const e=(this._options.volumeOpacityPeriod??20)*i;o.forEach(((t,i,o)=>{if(null==t.volume)return;const s=Math.max(0,i-e+1),a=o.slice(s,i+1).reduce(((e,t)=>void 0!==t.volume&&t.volume>e?t.volume:e),0),r=(a>0?t.volume/a:1)*(this._options?.maxOpacity??.3);t.isUp?t.color=n(this._options?.upColor||"rgba(0,255,0,0.333)",r):t.color=n(this._options?.downColor||"rgba(255,0,0,0.333)",r)}))}else console.warn("Volume opacity enabled but not all aggregated bars have volume data. Skipping volume-based opacity adjustment.")}return o}dynamicAggregate(e,t){if(0===e.length||"function"!=typeof this._options?.dynamicTrigger||!this._options?.dynamicCandles)return[];const i=[];let o=[];for(let n=0;ne.originalData?.high??e.high)),u=e.map((e=>e.originalData?.low??e.low)),m=p.length>0?Math.max(...p):0,g=u.length>0?Math.min(...u):0,y=o(m)??0,f=o(g)??0,_=e[0].x,v=c>a,b=v?this._options?.upColor||"rgba(0,255,0,0.333)":this._options?.downColor||"rgba(255,0,0,0.333)",w=v?this._options?.borderUpColor||n(b,1):this._options?.borderDownColor||n(b,1),x=v?this._options?.wickUpColor||w:this._options?.wickDownColor||w,C=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options?.lineStyle??1),M=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options?.lineWidth??1),S=e.reduce(((e,t)=>(t.shape?l(t.shape):t.originalData?.shape?l(t.originalData.shape):void 0)??e),this._options?.shape??r.Rectangle);return{open:h,high:y,low:f,close:d,volume:e.reduce(((e,t)=>e+(t.originalData?.volume??t.volume??0)),0),x:_,isUp:v,startIndex:t,endIndex:i,isInProgress:s,color:b,borderColor:w,wickColor:x,shape:S||r.Rectangle,lineStyle:C,lineWidth:M}}}class Jt{_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 qt(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 o;o=this._options.dynamicCandles&&"number"==typeof this._options.volumeMALength&&"number"==typeof this._options.volumeMultiplier?this._aggregator?.dynamicAggregate(i,t)??[]:this._aggregator?.staticAggregate(i,t)??[];const n=this._options.radius,{horizontalPixelRatio:s,verticalPixelRatio:a}=e,r=this._data.barSpacing*s;this._drawCandles(e,o,this._data.visibleRange,n,r,s,a),this._drawWicks(e,o,this._data.visibleRange)}_drawWicks(e,t,i){if(null===this._data||null===this._options)return;if("3d"===this._options.shape)return;const{context:o,horizontalPixelRatio:n,verticalPixelRatio:s}=e,a=this._data.barSpacing*n,r=jt(n);for(const e of t){if(e.startIndexi.to)continue;const t=e.low*s,l=e.high*s,c=Math.min(e.open,e.close)*s,h=Math.max(e.open,e.close)*s;let d=e.x*n;const p=e.endIndex-e.startIndex;p&&p>1&&(d+=a*Math.max(1,p)/2);let u=l,m=c,g=h,y=t;"Polygon"===this._options.shape&&(m=(l+c)/2,g=(t+h)/2),o.fillStyle=e.color,o.strokeStyle=e.wickColor??e.color;const f=(e,t,i,n,s)=>{o.roundRect?o.roundRect(e,t,i,n,s):o.rect(e,t,i,n)},_=m-u;_>0&&(o.beginPath(),f(d-Math.floor(r/2),u,r,_,r/2),o.fill(),o.stroke());const v=y-g;v>0&&(o.beginPath(),f(d-Math.floor(r/2),g,r,v,r/2),o.fill(),o.stroke())}}_drawCandles(e,t,i,o,n,s,a){const{context:r}=e,l=this._options?.barSpacing??.8;r.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*s,d=n*l;if(e.startIndexi.to)continue;const p=Math.min(e.open,e.close)*a,u=Math.max(e.open,e.close)*a,m=p-u,g=(p+u)/2,y=h-d/2,f=y+c,_=y+c/2;switch(r.fillStyle=e.color??this._options?.color??"rgba(255,255,255,1)",r.strokeStyle=e.borderColor??this._options?.borderColor??e.color??"rgba(255,255,255,1)",te(r,e.lineStyle),r.lineWidth=e.lineWidth??1,e.shape){case"Rectangle":default:N(r,y,f,g,m);break;case"Rounded":A(r,y,f,g,m,o);break;case"Ellipse":V(r,y,f,0,g,m);break;case"Arrow":G(r,y,f,_,g,m,e.high*a,e.low*a,e.isUp);break;case"3d":$(r,h,e.high*a,e.low*a,e.open*a,e.close*a,d,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":R(r,y,f,g,m,e.high*a,e.low*a,e.isUp);break;case"Bar":B(r,y,f,e.high*a,e.low*a,e.open*a,e.close*a)}}r.restore()}}const Xt={...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,volumeOpacityPeriod:21,maxOpacity:.3,dynamicCandles:!1,dynamicTrigger:()=>({newBar:!0})};class Yt{_renderer;constructor(){this._renderer=new Jt}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 Xt}}class Kt{defaults;constructor(){this.defaults=new Map}set(e,t){let i;if("string"==typeof t)try{i=JSON.parse(t)}catch(o){console.error(`Error parsing JSON string for key "${e}":`,o),i=t}else i=t;this.defaults.set(e,i),console.log(`Default options for key "${e}" set successfully.`),console.log(i)}get(e){return this.defaults.get(e)}getAll(){return this.defaults}}x();class Zt{id;commandFunctions=[];static handlers=new Map;seriesOriginMap=new WeakMap;wrapper;div;chart;scale;precision=2;series;volumeSeries;legend;_topBar;toolBox;spinner;_seriesList=[];seriesMap=new Map;seriesMetadata;ContextMenu;currentMouseEventParams=null;defaultsManager;constructor(e,t,i,o,n){this.reSize=this.reSize.bind(this),this.id=e,this.scale={width:t,height:i},this.defaultsManager=new Kt,Zt.handlers.set(e,this),this.wrapper=document.createElement("div"),this.wrapper.classList.add("handler"),this.wrapper.style.float=o,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 zt(this,Zt.handlers,(()=>window.MouseEventParams??null)),this.legend=new P(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.reSize(),n&&(window.addEventListener("resize",(()=>this.reSize())),this.chart.subscribeCrosshairMove((e=>{this.currentMouseEventParams=e})))}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{...X(e),...this.defaultsManager.defaults.get(e.toLowerCase())||{},...t}}createCandlestickSeries(){const e="Candlestick",i={...X(e),...this.defaultsManager.defaults.get(e.toLowerCase())||{}},o=this.chart.addSeries(t.CandlestickSeries,i);o.priceScale().applyOptions({scaleMargins:{top:.2,bottom:.2}});const n=J(o,this.legend);n.applyOptions({title:"OHLC"}),this._seriesList.push(n),this.seriesMap.set("OHLC",n),i.upColor,i.downColor;const s={name:"OHLC",series:n,colors:[i.upColor,i.downColor],legendSymbol:["⋰","⋱"],seriesType:"Candlestick",group:void 0};return this.legend.addLegendItem(s),n}createVolumeSeries(){const e=this.chart.addSeries(t.HistogramSeries,{color:"#26a69a",priceFormat:{type:"volume"},priceScaleId:"volume_scale"});e.priceScale().applyOptions({scaleMargins:{top:.2,bottom:0}}),e.moveToPane(1);const i=J(e,this.legend);return i.applyOptions({title:"Volume"}),i}createLineSeries(e,i){const o=this.mergeSeriesOptions("Line",i),n=(()=>{switch(o.lineStyle){case 0:return"―";case 1:return":··";case 2:return"--";case 3:return"- -";case 4:return"· ·";default:return"~"}})(),{group:s,legendSymbol:a=n,...r}=o,l=J(this.chart.addSeries(t.LineSeries,r),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(a)?a:a?[a]:[],seriesType:"Line",group:s};return this.legend.addLegendItem(h),{name:e,series:l}}createHistogramSeries(e,i){const o=this.mergeSeriesOptions("Histogram",i),{group:n,legendSymbol:s="▨",...a}=o,r=J(this.chart.addSeries(t.HistogramSeries,a),this.legend);r.applyOptions({title:e}),this._seriesList.push(r),this.seriesMap.set(e,r);const l=r.options().color||"rgba(255,0,0,1)",c={name:e,series:r,colors:[l.startsWith("rgba")?l.replace(/[^,]+(?=\))/,"1"):l],legendSymbol:Array.isArray(s)?s:[s],seriesType:"Histogram",group:n};return this.legend.addLegendItem(c),{name:e,series:r}}createAreaSeries(e,i){const o=this.mergeSeriesOptions("Area",i),{group:n,legendSymbol:s="▨",...a}=o,r=J(this.chart.addSeries(t.AreaSeries,a),this.legend);this._seriesList.push(r),this.seriesMap.set(e,r);const l=r.options().lineColor||"rgba(255,0,0,1)",c={name:e,series:r,colors:[l.startsWith("rgba")?l.replace(/[^,]+(?=\))/,"1"):l],legendSymbol:Array.isArray(s)?s:s?[s]:[],seriesType:"Area",group:n};return this.legend.addLegendItem(c),{name:e,series:r}}createBarSeries(e,i){const o=this.mergeSeriesOptions("Bar",i),{group:n,legendSymbol:s=["┌","└"],...a}=o,r=J(this.chart.addSeries(t.BarSeries,a),this.legend);r.applyOptions({title:e}),this._seriesList.push(r),this.seriesMap.set(e,r);const l=r.options().upColor||"rgba(0,255,0,1)",c=r.options().downColor||"rgba(255,0,0,1)",h={name:e,series:r,colors:[l,c],legendSymbol:Array.isArray(s)?s:s?[s]:[],seriesType:"Bar",group:n};return this.legend.addLegendItem(h),{name:e,series:r}}createCustomOHLCSeries(e,t={}){const i={...Xt,...this.defaultsManager.defaults.get("ohlc")||{},...t,seriesType:"Ohlc"},{group:o,legendSymbol:n=["⑃","⑂"],chandelierSize:s=1,...a}=i,r=new Yt,l=this.chart.addCustomSeries(r,{...a,chandelierSize:s,title:e}),c=J(l,this.legend);this._seriesList.push(c),this.seriesMap.set(e,c);const h={name:e,series:c,colors:[i.borderUpColor||i.upColor,i.borderDownColor||i.downColor],legendSymbol:Array.isArray(n)?n:n?[n]:[],seriesType:"Ohlc",group:o};return this.legend.addLegendItem(h),{name:e,series:l}}createTradeSeries(e,t={}){const i={...W,...this.defaultsManager.defaults.get("trade"),...t,seriesType:"Trade"},{group:o,legendSymbol:n=["$"],...s}=i,a=new z,r=this.chart.addCustomSeries(a,s),l=J(r,this.legend);this._seriesList.push(l),this.seriesMap.set(e??"Trade",l);const c={name:e,series:l,colors:[i.backgroundColorStop,i.backgroundColorTarget],legendSymbol:Array.isArray(n)?n:[n],seriesType:"Trade",group:o};return this.legend.addLegendItem(c),{name:e,series:r}}createFillArea(e,t,i,o,n){const s=this._seriesList.find((e=>e.options()?.title===t)),a=this._seriesList.find((e=>e.options()?.title===i));if(!s)return void console.warn(`Origin series with title "${t}" not found.`);if(!a)return void console.warn(`Destination series with title "${i}" not found.`);const r=Z(s,this.legend),l=new y(s,a,{originColor:o||null,destinationColor:n||null,lineWidth:null});return r.attachPrimitive(l,e),l}attachPrimitive(e,t,i,o){let n=i;try{if(o&&!i&&(n=this.seriesMap.get(o)),!n)return void console.warn(`Series with the name "${o}" not found.`);const s=Z(n,this.legend);let a;if("Tooltip"!==t)return void console.warn(`Unknown primitive type: ${t}`);a=new je({lineColor:e}),s.attachPrimitive(a,"Tooltip"),this.primitives.set(n,a)}catch(e){console.error(`Failed to attach ${t}:`,e)}}removeSeries(e){let t;if(g(e)){for(const[i,o]of this.seriesMap.entries())if(o===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 Ae(this,this.id,this.chart,this.series,this.commandFunctions),this.div.appendChild(this.toolBox.div)}createTopBar(){return this._topBar=new $e(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 o(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 s=e.chart.timeScale(),a=t.chart.timeScale(),r=e=>{e&&s.setVisibleLogicalRange(e)},l=e=>{e&&a.setVisibleLogicalRange(e)},c=i=>{o(t,n(e.series,i))},h=i=>{o(e,n(t.series,i))};let d=t;function p(e,t,o,n,s,a){e.wrapper.addEventListener("mouseover",(()=>{d!==e&&(d=e,t.chart.unsubscribeCrosshairMove(o),e.chart.subscribeCrosshairMove(n),i||(t.chart.timeScale().unsubscribeVisibleLogicalRangeChange(s),e.chart.timeScale().subscribeVisibleLogicalRangeChange(a)))}))}p(t,e,c,h,l,r),p(e,t,h,c,r,l),t.chart.subscribeCrosshairMove(h);const u=a.getVisibleLogicalRange();u&&s.setVisibleLogicalRange(u),i||t.chart.timeScale().subscribeVisibleLogicalRangeChange(r)}static makeSearchBox(e){const t=document.createElement("div");t.classList.add("searchbox"),t.style.display="none";const i=document.createElement("div");i.innerHTML='';const o=document.createElement("input");return o.type="text",t.appendChild(i),t.appendChild(o),e.div.appendChild(t),e.commandFunctions.push((i=>window.handlerInFocus===e.id&&!window.textBoxFocused&&("none"===t.style.display?!!/^[a-zA-Z0-9]$/.test(i.key)&&(t.style.display="flex",o.focus(),!0):("Enter"===i.key||"Escape"===i.key)&&("Enter"===i.key&&window.callbackFunction(`search${e.id}_~_${o.value}`),t.style.display="none",o.value="",!0)))),o.addEventListener("input",(()=>o.value=o.value.toUpperCase())),{window:t,box:o}}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,o]of Object.entries(this._styleMap))t.setProperty(i,e[o])}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="Lightweight-Charts"}return e.Box=we,e.FillArea=y,e.Handler=Zt,e.HorizontalLine=Se,e.Legend=P,e.RayLine=ke,e.Table=class{_div;callbackName;borderColor;borderWidth;table;rows={};headings;widths;alignments;footer;header;constructor(e,t,i,o,n,s,a=!1,r,l,c,h,d){this._div=document.createElement("div"),this.callbackName=null,this.borderColor=l,this.borderWidth=c,a?(this._div.style.position="absolute",this._div.style.cursor="move"):(this._div.style.position="relative",this._div.style.float=s),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=o.map((e=>100*e+"%")),this.alignments=n;let p=this.table.createTHead().insertRow();for(let e=0;e0?d[e]:r,t.style.color=h[e],p.appendChild(t)}let u,m,g=document.createElement("div");if(g.style.overflowY="auto",g.style.overflowX="hidden",g.style.backgroundColor=r,g.appendChild(this.table),this._div.appendChild(g),window.containerDiv.appendChild(this._div),!a)return;let y=e=>{this._div.style.left=e.clientX-u+"px",this._div.style.top=e.clientY-m+"px"},f=()=>{document.removeEventListener("mousemove",y),document.removeEventListener("mouseup",f)};this._div.addEventListener("mousedown",(e=>{u=e.clientX-this._div.offsetLeft,m=e.clientY-this._div.offsetTop,document.addEventListener("mousemove",y),document.addEventListener("mouseup",f)}))}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 o=0;o{e&&(window.cursor=e),document.body.style.cursor=window.cursor},e}({},LightweightCharts); diff --git a/lightweight_charts_/js/index.html b/lightweight_charts_/js/index.html deleted file mode 100644 index 8f2dd943..00000000 --- a/lightweight_charts_/js/index.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - lightweight-charts-python - - - - - - - -
- - - - diff --git a/lightweight_charts_/js/lightweight-charts.js b/lightweight_charts_/js/lightweight-charts.js deleted file mode 100644 index 10125750..00000000 --- a/lightweight_charts_/js/lightweight-charts.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * @license - * TradingView Lightweight Charts™ v5.0.1 - * 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}(); diff --git a/lightweight_charts_/js/styles.css b/lightweight_charts_/js/styles.css deleted file mode 100644 index e9f784eb..00000000 --- a/lightweight_charts_/js/styles.css +++ /dev/null @@ -1,244 +0,0 @@ -:root { - --bg-color:#0c0d0f; - --hover-bg-color: #3c434c; - --click-bg-color: #50565E; - --active-bg-color: rgba(0, 122, 255, 0.7); - --muted-bg-color: rgba(0, 122, 255, 0.3); - --border-color: #3C434C; - --color: #d8d9db; - --active-color: #ececed; -} - -body { - background-color: rgb(0,0,0); - color: rgba(19, 23, 34, 1); - overflow: hidden; - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, - Cantarell, "Helvetica Neue", sans-serif; -} - -.handler { - display: flex; - flex-direction: column; - position: relative; -} - -.toolbox { - position: absolute; - z-index: 2000; - display: flex; - align-items: center; - top: 25%; - border: 2px solid var(--border-color); - border-left: none; - border-top-right-radius: 4px; - border-bottom-right-radius: 4px; - background-color: rgba(25, 27, 30, 0.5); - flex-direction: column; -} - -.toolbox-button { - margin: 3px; - border-radius: 4px; - display: flex; - background-color: transparent; -} -.toolbox-button:hover { - background-color: rgba(80, 86, 94, 0.7); -} -.toolbox-button:active { - background-color: rgba(90, 106, 104, 0.7); -} - -.active-toolbox-button { - background-color: var(--active-bg-color) !important; -} -.active-toolbox-button g { - fill: var(--active-color); -} - -.context-menu { - position: absolute; - z-index: 1000; - background: rgb(50, 50, 50); - color: var(--active-color); - display: none; - border-radius: 5px; - padding: 3px 3px; - font-size: 13px; - cursor: default; -} -.context-menu-item { - display: flex; - align-items: center; - justify-content: space-between; - padding: 2px 10px; - margin: 1px 0px; - border-radius: 3px; -} -.context-menu-item:hover { - background-color: var(--muted-bg-color); -} - -.color-picker { - max-width: 170px; - background-color: var(--bg-color); - position: absolute; - z-index: 10000; - display: none; - flex-direction: column; - align-items: center; - border: 2px solid var(--border-color); - border-radius: 8px; - cursor: default; -} - - -/* topbar-related */ -.topbar { - background-color: var(--bg-color); - border-bottom: 2px solid var(--border-color); - display: flex; - align-items: center; -} - -.topbar-container { - display: flex; - align-items: center; - flex-grow: 1; -} - -.topbar-button { - border: none; - padding: 2px 5px; - margin: 4px 10px; - font-size: 13px; - border-radius: 4px; - color: var(--color); - background-color: transparent; -} -.topbar-button:hover { - background-color: var(--hover-bg-color) -} - -.topbar-button:active { - background-color: var(--click-bg-color); - color: var(--active-color); - font-weight: 500; -} - -.switcher-button:active { - background-color: var(--click-bg-color); - color: var(--color); - font-weight: normal; -} - -.active-switcher-button { - background-color: var(--active-bg-color) !important; - color: var(--active-color) !important; - font-weight: 500; -} - -.topbar-textbox { - margin: 0px 18px; - font-size: 16px; - color: var(--color); -} - -.topbar-textbox-input { - background-color: var(--bg-color); - color: var(--color); - border: 1px solid var(--color); -} - -.topbar-menu { - position: absolute; - display: none; - z-index: 10000; - background-color: var(--bg-color); - border-radius: 2px; - border: 2px solid var(--border-color); - border-top: none; - align-items: flex-start; - max-height: 80%; - overflow-y: auto; -} - -.topbar-separator { - width: 1px; - height: 20px; - background-color: var(--border-color); -} - -.searchbox { - position: absolute; - top: 0; - bottom: 200px; - left: 0; - right: 0; - margin: auto; - width: 150px; - height: 30px; - padding: 5px; - z-index: 1000; - align-items: center; - background-color: rgba(30 ,30, 30, 0.9); - border: 2px solid var(--border-color); - border-radius: 5px; - display: flex; - -} -.searchbox input { - text-align: center; - width: 100px; - margin-left: 10px; - background-color: var(--muted-bg-color); - color: var(--active-color); - font-size: 20px; - border: none; - outline: none; - border-radius: 2px; -} - -.spinner { - width: 30px; - height: 30px; - border: 4px solid rgba(255, 255, 255, 0.6); - border-top: 4px solid var(--active-bg-color); - border-radius: 50%; - position: absolute; - top: 50%; - left: 50%; - z-index: 1000; - transform: translate(-50%, -50%); - display: none; -} - -.legend { - position: absolute; - z-index: 3000; - pointer-events: none; - top: 10px; - left: 10px; - display: none; - flex-direction: column; -} -.series-container { - display: flex; - flex-direction: column; - pointer-events: auto; - overflow-y: auto; - max-height: 80vh; -} -.series-container::-webkit-scrollbar { - width: 0px; -} -.legend-toggle-switch { - border-radius: 4px; - margin-left: 10px; - pointer-events: auto; -} -.legend-toggle-switch:hover { - cursor: pointer; - background-color: rgba(50, 50, 50, 0.5); -} \ No newline at end of file diff --git a/ohlcv.csv b/ohlcv.csv new file mode 100644 index 00000000..31afc193 --- /dev/null +++ b/ohlcv.csv @@ -0,0 +1,2982 @@ +,time,open,high,low,close,volume +0,2010-06-29,1.2667,1.6667,1.1693,1.5927,277519500 +1,2010-06-30,1.6713,2.028,1.5533,1.5887,253039500 +2,2010-07-01,1.6627,1.728,1.3513,1.464,121461000 +3,2010-07-02,1.47,1.55,1.2473,1.28,75871500 +4,2010-07-06,1.2867,1.3333,1.0553,1.074,101664000 +5,2010-07-07,1.0933,1.1087,0.9987,1.0533,102645000 +6,2010-07-08,1.0567,1.1793,1.038,1.164,114526500 +7,2010-07-09,1.18,1.1933,1.1033,1.16,60061500 +8,2010-07-12,1.1533,1.2047,1.1233,1.1413,32487000 +9,2010-07-13,1.1533,1.2427,1.1267,1.2093,39439500 +10,2010-07-14,1.2067,1.3433,1.184,1.3227,62097000 +11,2010-07-15,1.32,1.4333,1.2667,1.326,55222500 +12,2010-07-16,1.3267,1.42,1.326,1.376,37939500 +13,2010-07-19,1.4,1.4893,1.3867,1.4367,36303000 +14,2010-07-20,1.466,1.4853,1.328,1.3533,26229000 +15,2010-07-21,1.36,1.41,1.3,1.348,18214500 +16,2010-07-22,1.3507,1.4167,1.35,1.4,13924500 +17,2010-07-23,1.416,1.4373,1.4013,1.4193,9603000 +18,2010-07-26,1.4187,1.4513,1.3533,1.3953,13416000 +19,2010-07-27,1.3973,1.412,1.3507,1.37,8658000 +20,2010-07-28,1.3673,1.3933,1.3673,1.3813,6801000 +21,2010-07-29,1.3847,1.392,1.3333,1.3567,8734500 +22,2010-07-30,1.3567,1.3627,1.3033,1.3293,6258000 +23,2010-08-02,1.338,1.4,1.338,1.3807,10417500 +24,2010-08-03,1.384,1.4633,1.3593,1.4633,17827500 +25,2010-08-04,1.4867,1.4867,1.3407,1.4173,13594500 +26,2010-08-05,1.3967,1.442,1.3367,1.3633,11722500 +27,2010-08-06,1.336,1.35,1.3013,1.306,10542000 +28,2010-08-09,1.302,1.3333,1.2967,1.3053,10684500 +29,2010-08-10,1.3067,1.31,1.2547,1.2687,17506500 +30,2010-08-11,1.2447,1.26,1.1833,1.1933,11340000 +31,2010-08-12,1.1933,1.2133,1.1593,1.1733,10168500 +32,2010-08-13,1.1847,1.24,1.1773,1.2213,9385500 +33,2010-08-16,1.2333,1.2533,1.2173,1.25,7186500 +34,2010-08-17,1.25,1.2933,1.25,1.2767,6597000 +35,2010-08-18,1.28,1.306,1.2333,1.2513,8905500 +36,2010-08-19,1.236,1.2833,1.222,1.2527,8290500 +37,2010-08-20,1.2333,1.2787,1.2333,1.2733,4381500 +38,2010-08-23,1.2727,1.3593,1.2667,1.3467,16048500 +39,2010-08-24,1.3267,1.3267,1.2633,1.28,9973500 +40,2010-08-25,1.2667,1.332,1.2373,1.3267,7372500 +41,2010-08-26,1.316,1.3513,1.3067,1.3167,6189000 +42,2010-08-27,1.3333,1.334,1.3,1.3133,5628000 +43,2010-08-30,1.3133,1.346,1.3073,1.32,10831500 +44,2010-08-31,1.292,1.3193,1.2887,1.2987,2956500 +45,2010-09-01,1.308,1.3793,1.3067,1.3633,7306500 +46,2010-09-02,1.3633,1.416,1.354,1.404,7159500 +47,2010-09-03,1.4067,1.4327,1.3773,1.4033,6402000 +48,2010-09-07,1.388,1.4,1.3667,1.3693,3612000 +49,2010-09-08,1.372,1.3967,1.372,1.3933,4281000 +50,2010-09-09,1.3953,1.4033,1.3347,1.3807,5586000 +51,2010-09-10,1.3833,1.3953,1.3173,1.3447,5706000 +52,2010-09-13,1.3733,1.3933,1.3667,1.386,5361000 +53,2010-09-14,1.3693,1.44,1.3687,1.408,9564000 +54,2010-09-15,1.3987,1.4667,1.386,1.4653,9990000 +55,2010-09-16,1.4867,1.544,1.3873,1.396,38347500 +56,2010-09-17,1.4213,1.4233,1.32,1.3487,17478000 +57,2010-09-20,1.35,1.4233,1.344,1.4,13968000 +58,2010-09-21,1.4193,1.4367,1.378,1.3847,11749500 +59,2010-09-22,1.3913,1.3967,1.32,1.3247,13227000 +60,2010-09-23,1.32,1.3427,1.3,1.304,9856500 +61,2010-09-24,1.33,1.346,1.31,1.34,8590500 +62,2010-09-27,1.3467,1.3873,1.3333,1.386,6181500 +63,2010-09-28,1.398,1.4327,1.384,1.4267,17905500 +64,2010-09-29,1.3667,1.4733,1.3667,1.4653,27925500 +65,2010-09-30,1.466,1.4767,1.346,1.3603,31186500 +66,2010-10-01,1.3867,1.4167,1.346,1.3733,7783500 +67,2010-10-04,1.34,1.4113,1.34,1.4,9444000 +68,2010-10-05,1.41,1.4187,1.4007,1.408,4914000 +69,2010-10-06,1.404,1.4173,1.3547,1.364,4617000 +70,2010-10-07,1.3713,1.376,1.354,1.362,2064000 +71,2010-10-08,1.362,1.386,1.3573,1.362,3973500 +72,2010-10-11,1.3667,1.38,1.338,1.34,2497500 +73,2010-10-12,1.3467,1.352,1.3353,1.3493,3405000 +74,2010-10-13,1.3507,1.4233,1.3507,1.3693,4728000 +75,2010-10-14,1.4333,1.4333,1.36,1.3833,4314000 +76,2010-10-15,1.3927,1.3933,1.35,1.3693,4189500 +77,2010-10-18,1.376,1.376,1.348,1.3487,2374500 +78,2010-10-19,1.3467,1.3607,1.3333,1.3367,3601500 +79,2010-10-20,1.344,1.3793,1.336,1.3767,4608000 +80,2010-10-21,1.374,1.3967,1.3633,1.3833,6166500 +81,2010-10-22,1.3787,1.3953,1.37,1.3813,2374500 +82,2010-10-25,1.3947,1.3987,1.382,1.3987,1737000 +83,2010-10-26,1.3867,1.458,1.3673,1.424,9744000 +84,2010-10-27,1.4,1.4,1.4,1.4,0 +85,2011-01-06,1.7907,1.8667,1.7873,1.8467,28846500 +86,2011-01-07,1.8533,1.9053,1.8533,1.876,33460500 +87,2011-01-10,1.8773,1.912,1.87,1.91,19849500 +88,2011-01-11,1.9073,1.914,1.782,1.7973,25282500 +89,2011-01-12,1.8007,1.8267,1.768,1.7973,13564500 +90,2011-01-13,1.7967,1.7993,1.744,1.7533,10503000 +91,2011-01-14,1.7553,1.772,1.7073,1.7193,17412000 +92,2011-01-18,1.74,1.74,1.65,1.7093,23950500 +93,2011-01-19,1.6847,1.698,1.5833,1.602,35040000 +94,2011-01-20,1.6133,1.63,1.4913,1.5167,33759000 +95,2011-01-21,1.5247,1.5727,1.514,1.5333,18036000 +96,2011-01-24,1.5567,1.654,1.5487,1.6333,24352500 +97,2011-01-25,1.6433,1.6593,1.6013,1.6453,18924000 +98,2011-01-26,1.66,1.66,1.6067,1.65,16050000 +99,2011-01-27,1.6567,1.672,1.6353,1.6647,12790500 +100,2011-01-28,1.6533,1.6613,1.5833,1.6,15490500 +101,2011-01-31,1.6393,1.6393,1.5667,1.6007,11974500 +102,2011-02-01,1.6367,1.6487,1.5693,1.594,10473000 +103,2011-02-02,1.594,1.612,1.578,1.596,8454000 +104,2011-02-03,1.588,1.5933,1.5433,1.5807,7540500 +105,2011-02-04,1.5647,1.578,1.548,1.5753,8067000 +106,2011-02-07,1.556,1.5567,1.5253,1.538,13209000 +107,2011-02-08,1.534,1.6833,1.5333,1.6327,51768000 +108,2011-02-09,1.6173,1.6327,1.5193,1.5473,37779000 +109,2011-02-10,1.5333,1.576,1.5207,1.5513,12324000 +110,2011-02-11,1.55,1.5833,1.5293,1.5333,9424500 +111,2011-02-14,1.5487,1.6093,1.5367,1.546,18984000 +112,2011-02-15,1.546,1.5667,1.4973,1.5227,14146500 +113,2011-02-16,1.5333,1.6647,1.5273,1.6487,60928500 +114,2011-02-17,1.6667,1.6993,1.558,1.5833,38383500 +115,2011-02-18,1.5733,1.5733,1.5307,1.5353,35118000 +116,2011-02-22,1.5807,1.5807,1.452,1.458,30369000 +117,2011-02-23,1.496,1.5,1.4073,1.4553,23451000 +118,2011-02-24,1.4667,1.5053,1.4333,1.4813,15372000 +119,2011-02-25,1.5067,1.59,1.5053,1.5687,19941000 +120,2011-02-28,1.5827,1.6067,1.5667,1.574,15580500 +121,2011-03-01,1.5927,1.6213,1.58,1.596,16422000 +122,2011-03-02,1.596,1.6187,1.582,1.6013,9826500 +123,2011-03-03,1.632,1.6527,1.604,1.6207,9478500 +124,2011-03-04,1.628,1.666,1.5853,1.646,22677000 +125,2011-03-07,1.67,1.6933,1.6467,1.6587,30210000 +126,2011-03-08,1.6587,1.664,1.6,1.644,20715000 +127,2011-03-09,1.644,1.666,1.618,1.648,13692000 +128,2011-03-10,1.6293,1.648,1.582,1.6133,14049000 +129,2011-03-11,1.6047,1.6167,1.5687,1.6033,13821000 +130,2011-03-14,1.5733,1.608,1.5467,1.5507,17205000 +131,2011-03-15,1.4927,1.5307,1.4533,1.53,19534500 +132,2011-03-16,1.524,1.55,1.5127,1.5213,17208000 +133,2011-03-17,1.5433,1.562,1.5093,1.5207,12612000 +134,2011-03-18,1.546,1.546,1.5007,1.522,10195500 +135,2011-03-21,1.5333,1.5467,1.5027,1.516,6057000 +136,2011-03-22,1.5153,1.524,1.4667,1.4793,8097000 +137,2011-03-23,1.4707,1.4847,1.4513,1.4807,5943000 +138,2011-03-24,1.48,1.5,1.4653,1.5,6564000 +139,2011-03-25,1.4953,1.5333,1.4933,1.5167,8416500 +140,2011-03-28,1.5307,1.5693,1.5033,1.528,15309000 +141,2011-03-29,1.5533,1.6,1.5473,1.5947,11188500 +142,2011-03-30,1.5933,1.6327,1.534,1.5807,18003000 +143,2011-03-31,1.6093,1.914,1.6093,1.842,163869000 +144,2011-04-01,1.8667,1.8787,1.7713,1.7793,42078000 +145,2011-04-04,1.7687,1.8,1.682,1.7207,38563500 +146,2011-04-05,1.7567,1.8,1.7127,1.78,46600500 +147,2011-04-06,1.778,1.8007,1.72,1.7633,18907500 +148,2011-04-07,1.772,1.8627,1.7633,1.8273,41496000 +149,2011-04-08,1.846,1.846,1.7573,1.7667,28378500 +150,2011-04-11,1.7833,1.7833,1.6667,1.6667,20121000 +151,2011-04-12,1.6707,1.6827,1.62,1.65,20044500 +152,2011-04-13,1.662,1.7127,1.6533,1.6533,17970000 +153,2011-04-14,1.6527,1.6853,1.6133,1.6767,14481000 +154,2011-04-15,1.7,1.7453,1.69,1.6913,13975500 +155,2011-04-18,1.678,1.708,1.624,1.6653,15267000 +156,2011-04-19,1.668,1.684,1.6433,1.6833,8127000 +157,2011-04-20,1.7013,1.7393,1.6867,1.72,12396000 +158,2011-04-21,1.72,1.7987,1.706,1.7647,19473000 +159,2011-04-25,1.78,1.79,1.7313,1.762,11760000 +160,2011-04-26,1.7647,1.8167,1.754,1.7953,20268000 +161,2011-04-27,1.8007,1.824,1.7753,1.8013,14770500 +162,2011-04-28,1.8167,1.846,1.7813,1.83,23356500 +163,2011-04-29,1.846,1.858,1.82,1.82,9780000 +164,2011-05-02,1.8467,1.8533,1.804,1.816,11614500 +165,2011-05-03,1.8267,1.83,1.7667,1.82,13510500 +166,2011-05-04,1.7853,1.9333,1.7167,1.8467,15252000 +167,2011-05-05,1.8167,1.864,1.7447,1.7987,17584500 +168,2011-05-06,1.7833,1.8467,1.7747,1.808,13941000 +169,2011-05-09,1.8527,1.8667,1.79,1.828,13521000 +170,2011-05-10,1.8733,1.93,1.8607,1.8873,22632000 +171,2011-05-11,1.892,1.892,1.78,1.79,14250000 +172,2011-05-12,1.7833,1.85,1.7567,1.85,9286500 +173,2011-05-13,1.86,1.8793,1.82,1.8333,9783000 +174,2011-05-16,1.85,1.866,1.77,1.7787,11152500 +175,2011-05-17,1.85,1.85,1.7147,1.722,18295500 +176,2011-05-18,1.6967,1.7647,1.6967,1.7567,10804500 +177,2011-05-19,1.7793,1.896,1.7733,1.8533,38518500 +178,2011-05-20,1.8867,1.8867,1.8233,1.8653,12024000 +179,2011-05-23,1.8333,1.8413,1.7747,1.776,12774000 +180,2011-05-24,1.8107,1.8333,1.77,1.77,9003000 +181,2011-05-25,1.7987,1.934,1.7447,1.926,69592500 +182,2011-05-26,1.9307,1.984,1.8733,1.9667,48706500 +183,2011-05-27,1.9707,1.978,1.9213,1.964,24933000 +184,2011-05-31,1.9747,2.0187,1.9667,2.0127,48790500 +185,2011-06-01,2.0093,2.0093,1.884,1.904,22666500 +186,2011-06-02,1.908,1.9547,1.8893,1.95,14418000 +187,2011-06-03,1.9367,2.1,1.9327,2,92074500 +188,2011-06-06,2.012,2.0253,1.884,1.9167,34503000 +189,2011-06-07,1.928,1.9593,1.884,1.89,17590500 +190,2011-06-08,1.8813,1.9067,1.8,1.8073,25230000 +191,2011-06-09,1.8313,1.8733,1.8067,1.8553,23793000 +192,2011-06-10,1.8313,1.8867,1.8233,1.868,22432500 +193,2011-06-13,1.8713,1.9253,1.8587,1.8967,25342500 +194,2011-06-14,1.928,1.98,1.9,1.9,23337000 +195,2011-06-15,1.9,1.9,1.8047,1.8533,19891500 +196,2011-06-16,1.8447,1.8667,1.716,1.7487,26997000 +197,2011-06-17,1.778,1.8467,1.7427,1.766,25465500 +198,2011-06-20,1.7733,1.7733,1.7,1.734,22590000 +199,2011-06-21,1.7513,1.8487,1.7333,1.8447,22168500 +200,2011-06-22,1.828,1.8833,1.802,1.802,21912000 +201,2011-06-23,1.8053,1.856,1.7473,1.856,17314500 +202,2011-06-24,1.8427,1.8647,1.8173,1.8373,49531500 +203,2011-06-27,1.8487,1.8853,1.8207,1.8307,16056000 +204,2011-06-28,1.852,1.8833,1.8447,1.874,13153500 +205,2011-06-29,1.8887,1.9393,1.8713,1.8873,21499500 +206,2011-06-30,1.9,1.9553,1.886,1.912,13981500 +207,2011-07-01,1.938,1.9733,1.92,1.9347,12570000 +208,2011-07-05,1.9347,1.968,1.914,1.942,14746500 +209,2011-07-06,1.9633,1.9633,1.9033,1.926,13030500 +210,2011-07-07,1.9427,2,1.934,1.982,19233000 +211,2011-07-08,1.9733,1.9927,1.906,1.916,18363000 +212,2011-07-11,1.9073,1.9073,1.8667,1.8893,14514000 +213,2011-07-12,1.8667,1.9393,1.8667,1.8667,15451500 +214,2011-07-13,1.8953,1.9353,1.86,1.9113,15813000 +215,2011-07-14,1.902,1.9307,1.8167,1.8407,17193000 +216,2011-07-15,1.8527,1.8553,1.8267,1.8353,10407000 +217,2011-07-18,1.832,1.85,1.7753,1.7953,12657000 +218,2011-07-19,1.8153,1.874,1.8153,1.86,14488500 +219,2011-07-20,1.8667,2.0293,1.8533,1.9187,45171000 +220,2011-07-21,1.9,1.944,1.8733,1.914,14995500 +221,2011-07-22,1.9133,1.9693,1.9033,1.9507,8658000 +222,2011-07-25,1.8913,1.9527,1.8733,1.9173,9960000 +223,2011-07-26,1.86,1.918,1.86,1.878,11218500 +224,2011-07-27,1.9,1.9,1.8273,1.842,13981500 +225,2011-07-28,1.846,1.9033,1.836,1.8653,13846500 +226,2011-07-29,1.8533,1.8933,1.8333,1.878,13464000 +227,2011-08-01,1.9233,1.932,1.8807,1.918,16134000 +228,2011-08-02,1.9127,1.9467,1.8,1.8,21258000 +229,2011-08-03,1.8333,1.9333,1.75,1.75,25755000 +230,2011-08-04,1.7567,1.7927,1.6447,1.6833,44475000 +231,2011-08-05,1.6433,1.692,1.522,1.6167,28983000 +232,2011-08-08,1.5167,1.6293,1.496,1.572,38667000 +233,2011-08-09,1.5727,1.6967,1.5667,1.6707,19720500 +234,2011-08-10,1.6907,1.696,1.5753,1.6707,22410000 +235,2011-08-11,1.63,1.7167,1.6,1.6867,12295500 +236,2011-08-12,1.7067,1.8093,1.6907,1.754,14947500 +237,2011-08-15,1.77,1.7833,1.7287,1.7493,10935000 +238,2011-08-16,1.7467,1.7693,1.722,1.7393,7972500 +239,2011-08-17,1.7573,1.7767,1.6847,1.6867,9489000 +240,2011-08-18,1.7,1.7,1.5647,1.6173,15598500 +241,2011-08-19,1.564,1.6173,1.4667,1.49,18744000 +242,2011-08-22,1.498,1.5867,1.4453,1.4633,14208000 +243,2011-08-23,1.48,1.5407,1.4333,1.4633,12903000 +244,2011-08-24,1.5333,1.5953,1.508,1.5307,10108500 +245,2011-08-25,1.5913,1.5913,1.5267,1.55,10123500 +246,2011-08-26,1.514,1.5967,1.4713,1.582,11325000 +247,2011-08-29,1.596,1.6567,1.596,1.6473,11877000 +248,2011-08-30,1.6333,1.652,1.606,1.64,5392500 +249,2011-08-31,1.6453,1.7,1.6187,1.646,12174000 +250,2011-09-01,1.644,1.658,1.5893,1.6,12555000 +251,2011-09-02,1.6,1.6,1.512,1.5713,11379000 +252,2011-09-06,1.5067,1.5467,1.486,1.51,11688000 +253,2011-09-07,1.6,1.6,1.552,1.5893,6774000 +254,2011-09-08,1.572,1.602,1.552,1.5893,6633000 +255,2011-09-09,1.558,1.574,1.5033,1.5313,9963000 +256,2011-09-12,1.4987,1.554,1.4967,1.5253,8395500 +257,2011-09-13,1.5527,1.6067,1.5167,1.6053,10750500 +258,2011-09-14,1.6133,1.656,1.586,1.6227,12340500 +259,2011-09-15,1.6387,1.662,1.622,1.6227,8277000 +260,2011-09-16,1.6533,1.73,1.6327,1.73,20959500 +261,2011-09-19,1.7113,1.7207,1.588,1.7173,17196000 +262,2011-09-20,1.7133,1.7733,1.7113,1.7267,16471500 +263,2011-09-21,1.73,1.7967,1.7133,1.7233,14565000 +264,2011-09-22,1.6933,1.7407,1.6187,1.7093,11467500 +265,2011-09-23,1.6993,1.7747,1.69,1.7547,16702500 +266,2011-09-26,1.768,1.768,1.66,1.7133,13869000 +267,2011-09-27,1.7133,1.7993,1.7013,1.746,9808500 +268,2011-09-28,1.75,1.7667,1.634,1.6393,10636500 +269,2011-09-29,1.6667,1.7213,1.57,1.608,12891000 +270,2011-09-30,1.6533,1.6593,1.566,1.6253,19627500 +271,2011-10-03,1.6127,1.6667,1.55,1.582,15189000 +272,2011-10-04,1.5493,1.6213,1.5287,1.5773,17628000 +273,2011-10-05,1.5967,1.7227,1.5567,1.692,17782500 +274,2011-10-06,1.6913,1.84,1.668,1.7973,24651000 +275,2011-10-07,1.7447,1.84,1.7367,1.7993,19497000 +276,2011-10-10,1.816,1.8787,1.8,1.8587,12903000 +277,2011-10-11,1.834,1.8513,1.8,1.8,8533500 +278,2011-10-12,1.8427,1.8667,1.8133,1.8533,16698000 +279,2011-10-13,1.8353,1.898,1.8293,1.8327,15391500 +280,2011-10-14,1.88,1.9033,1.8173,1.87,20578500 +281,2011-10-17,1.8727,1.8733,1.8173,1.828,11227500 +282,2011-10-18,1.82,1.8953,1.7807,1.89,14308500 +283,2011-10-19,1.8667,1.872,1.82,1.838,11691000 +284,2011-10-20,1.8333,1.8333,1.8,1.8133,14899500 +285,2011-10-21,1.718,1.8867,1.718,1.8687,14001000 +286,2011-10-24,1.8593,1.926,1.85,1.904,13860000 +287,2011-10-25,1.882,1.924,1.8533,1.9033,9043500 +288,2011-10-26,1.882,1.8913,1.8267,1.8653,7510500 +289,2011-10-27,1.892,1.9333,1.8653,1.9333,12655500 +290,2011-10-28,1.9473,2.0167,1.8673,2.0167,18213000 +291,2011-10-31,1.9667,1.9673,1.9167,1.958,16635000 +292,2011-11-01,1.9167,1.958,1.8667,1.9033,9394500 +293,2011-11-02,1.948,2.0553,1.8833,2.0167,12871500 +294,2011-11-03,1.9993,2.1667,1.9687,2.1473,36706500 +295,2011-11-04,2.1167,2.164,2.034,2.1533,43872000 +296,2011-11-07,2.1367,2.1487,2.05,2.09,18619500 +297,2011-11-08,2.0867,2.1333,2.048,2.0947,15342000 +298,2011-11-09,2.08,2.0993,2.02,2.0567,14122500 +299,2011-11-10,2.0747,2.1,2.0433,2.074,11065500 +300,2011-11-11,2.16,2.3,2.038,2.2667,56487000 +301,2011-11-14,2.2347,2.2427,2.1747,2.214,18837000 +302,2011-11-15,2.2,2.2933,2.182,2.2547,13186500 +303,2011-11-16,2.2533,2.3333,2.2267,2.318,26086500 +304,2011-11-17,2.318,2.3267,2.2127,2.2453,20025000 +305,2011-11-18,2.2667,2.274,2.1633,2.1633,13359000 +306,2011-11-21,2.1733,2.1733,2.07,2.108,15288000 +307,2011-11-22,2.1173,2.186,2.07,2.138,10806000 +308,2011-11-23,2.1173,2.1367,2.0833,2.0967,6690000 +309,2011-11-25,2.092,2.1607,2.072,2.1333,3430500 +310,2011-11-28,2.1267,2.2187,2.1207,2.1707,10074000 +311,2011-11-29,2.1707,2.2047,2.1087,2.1707,8560500 +312,2011-11-30,2.1333,2.1953,2.1333,2.182,11122500 +313,2011-12-01,2.1713,2.266,2.132,2.194,14413500 +314,2011-12-02,2.1773,2.246,2.16,2.2053,10338000 +315,2011-12-05,2.236,2.3333,2.2287,2.294,15996000 +316,2011-12-06,2.28,2.332,2.2687,2.3173,14083500 +317,2011-12-07,2.3107,2.326,2.2533,2.2793,9607500 +318,2011-12-08,2.236,2.236,1.974,2.0633,48607500 +319,2011-12-09,2.0867,2.09,2.0187,2.07,18294000 +320,2011-12-12,2.03,2.0413,2.0013,2.0273,11262000 +321,2011-12-13,2.0353,2.062,1.9273,2.0273,14616000 +322,2011-12-14,1.9667,1.9787,1.8667,1.9,17221500 +323,2011-12-15,1.9073,1.9447,1.8747,1.908,10383000 +324,2011-12-16,2.0627,2.0627,1.8653,1.8667,14853000 +325,2011-12-19,1.872,1.9,1.8247,1.85,14272500 +326,2011-12-20,1.8667,1.8967,1.8467,1.888,12039000 +327,2011-12-21,1.88,1.88,1.7353,1.8667,25294500 +328,2011-12-22,1.8327,1.87,1.8,1.866,14973000 +329,2011-12-23,1.8653,1.8667,1.8347,1.8633,8787000 +330,2011-12-27,1.86,1.918,1.8367,1.86,10927500 +331,2011-12-28,1.9267,1.9493,1.8693,1.9047,8535000 +332,2011-12-29,1.906,1.956,1.9007,1.9007,7056000 +333,2011-12-30,1.8993,1.932,1.8833,1.904,4962000 +334,2012-01-03,1.9233,1.9667,1.8433,1.872,13644000 +335,2012-01-04,1.9053,1.9113,1.8333,1.8473,9174000 +336,2012-01-05,1.8507,1.862,1.79,1.808,14919000 +337,2012-01-06,1.814,1.8527,1.7607,1.808,14559000 +338,2012-01-09,1.8,1.8327,1.7413,1.8127,13207500 +339,2012-01-10,1.8293,1.8507,1.8167,1.85,9924000 +340,2012-01-11,1.8587,1.9113,1.82,1.9113,9738000 +341,2012-01-12,1.8987,1.908,1.8533,1.8833,9886500 +342,2012-01-13,1.8933,1.9,1.5093,1.6373,80587500 +343,2012-01-17,1.7033,1.8227,1.6767,1.7667,68454000 +344,2012-01-18,1.7667,1.7993,1.75,1.7873,17664000 +345,2012-01-19,1.8,1.8493,1.774,1.7787,18375000 +346,2012-01-20,1.7933,1.8,1.7507,1.7507,9475500 +347,2012-01-23,1.79,1.814,1.7733,1.788,8737500 +348,2012-01-24,1.7753,1.8453,1.7627,1.8133,12381000 +349,2012-01-25,1.8133,1.8673,1.8033,1.8647,8737500 +350,2012-01-26,1.8667,1.972,1.8647,1.8647,17626500 +351,2012-01-27,1.9,1.9813,1.9,1.9487,10332000 +352,2012-01-30,1.966,1.974,1.902,1.974,10779000 +353,2012-01-31,2,2.0333,1.9247,1.9387,13840500 +354,2012-02-01,1.9333,1.98,1.9207,1.964,7369500 +355,2012-02-02,1.9813,2.0587,1.9727,1.9727,11790000 +356,2012-02-03,2.032,2.0887,2.0167,2.074,11242500 +357,2012-02-06,2.0667,2.1267,2.066,2.12,9498000 +358,2012-02-07,2.1167,2.142,2.0547,2.1067,14199000 +359,2012-02-08,2.1333,2.134,2.086,2.1207,9072000 +360,2012-02-09,2.1287,2.2467,2.0953,2.1853,17317500 +361,2012-02-10,2.158,2.1613,1.9893,2.0733,27693000 +362,2012-02-13,2.0907,2.1373,2.06,2.094,16954500 +363,2012-02-14,2.13,2.2633,2.0933,2.2633,26682000 +364,2012-02-15,2.2667,2.3953,2.1513,2.29,40675500 +365,2012-02-16,2.2667,2.3007,2.1693,2.3007,32883000 +366,2012-02-17,2.3253,2.334,2.2333,2.316,20112000 +367,2012-02-21,2.32,2.3433,2.254,2.3033,16618500 +368,2012-02-22,2.3,2.3147,2.1667,2.27,23985000 +369,2012-02-23,2.266,2.3313,2.2373,2.3013,11665500 +370,2012-02-24,2.2933,2.3013,2.218,2.2533,14241000 +371,2012-02-27,2.244,2.2667,2.2,2.2413,8934000 +372,2012-02-28,2.2427,2.296,2.2113,2.2607,9070500 +373,2012-02-29,2.254,2.2747,2.2087,2.2087,7635000 +374,2012-03-01,2.2373,2.3,2.22,2.294,8875500 +375,2012-03-02,2.2933,2.3,2.2473,2.2727,7927500 +376,2012-03-05,2.2733,2.2933,2.2307,2.2513,6894000 +377,2012-03-06,2.2267,2.2267,2.1747,2.1987,7669500 +378,2012-03-07,2.208,2.2213,2.194,2.208,5398500 +379,2012-03-08,2.2073,2.2327,2.2027,2.2047,8953500 +380,2012-03-09,2.2133,2.354,2.2133,2.3307,22969500 +381,2012-03-12,2.3127,2.4193,2.3067,2.4067,28791000 +382,2012-03-13,2.4007,2.4393,2.3667,2.3793,14412000 +383,2012-03-14,2.4,2.4007,2.32,2.3553,12595500 +384,2012-03-15,2.352,2.3653,2.3187,2.3387,8461500 +385,2012-03-16,2.3287,2.3927,2.322,2.3533,10819500 +386,2012-03-19,2.3507,2.3547,2.3027,2.332,14856000 +387,2012-03-20,2.332,2.3467,2.3047,2.3307,8392500 +388,2012-03-21,2.3293,2.354,2.3067,2.336,8650500 +389,2012-03-22,2.3467,2.3467,2.2867,2.3173,7563000 +390,2012-03-23,2.2833,2.3087,2.21,2.29,16336500 +391,2012-03-26,2.3333,2.5393,2.3333,2.4833,46437000 +392,2012-03-27,2.4833,2.6633,2.4687,2.588,36403500 +393,2012-03-28,2.5547,2.5627,2.474,2.506,13975500 +394,2012-03-29,2.4707,2.546,2.4667,2.4887,10455000 +395,2012-03-30,2.5013,2.5293,2.4453,2.48,11152500 +396,2012-04-02,2.4733,2.5313,2.4353,2.44,13074000 +397,2012-04-03,2.4433,2.5647,2.396,2.4,16107000 +398,2012-04-04,2.41,2.41,2.3127,2.33,66337500 +399,2012-04-05,2.3507,2.3627,2.2927,2.2927,21292500 +400,2012-04-09,2.2733,2.308,2.2,2.2,24487500 +401,2012-04-10,2.2127,2.2567,2.14,2.1653,25423500 +402,2012-04-11,2.1953,2.2193,2.134,2.2007,16089000 +403,2012-04-12,2.2333,2.2987,2.1947,2.2387,14713500 +404,2012-04-13,2.2267,2.2693,2.19,2.2533,9622500 +405,2012-04-16,2.2273,2.2467,2.1393,2.1633,15481500 +406,2012-04-17,2.15,2.2047,2.136,2.1493,16413000 +407,2012-04-18,2.1407,2.188,2.102,2.1773,12088500 +408,2012-04-19,2.1087,2.2287,2.1087,2.198,11424000 +409,2012-04-20,2.2433,2.2567,2.196,2.2107,12180000 +410,2012-04-23,2.2113,2.2113,2.114,2.1293,13161000 +411,2012-04-24,2.1493,2.1493,2.0667,2.1233,9708000 +412,2012-04-25,2.1267,2.1993,2.1267,2.194,10542000 +413,2012-04-26,2.194,2.2367,2.194,2.2367,6229500 +414,2012-04-27,2.3013,2.3013,2.194,2.2227,8539500 +415,2012-04-30,2.218,2.224,2.172,2.22,6088500 +416,2012-05-01,2.216,2.2807,2.2087,2.252,9690000 +417,2012-05-02,2.2233,2.2927,2.2233,2.2627,7291500 +418,2012-05-03,2.2747,2.2747,2.14,2.14,12472500 +419,2012-05-04,2.1573,2.164,2.0933,2.12,18291000 +420,2012-05-07,2.1233,2.172,2.1073,2.1647,16948500 +421,2012-05-08,2.1647,2.186,1.958,2.038,45520500 +422,2012-05-09,2.004,2.1933,1.9667,2.1173,28653000 +423,2012-05-10,2.12,2.312,2.1173,2.1973,82389000 +424,2012-05-11,2.1867,2.2293,2.144,2.18,18039000 +425,2012-05-14,2.1333,2.142,2.0007,2.0107,20400000 +426,2012-05-15,2.024,2.064,1.948,1.9827,22992000 +427,2012-05-16,1.9933,2.012,1.9253,1.9627,18601500 +428,2012-05-17,1.9613,1.986,1.8827,1.8987,16810500 +429,2012-05-18,1.8933,1.8973,1.7887,1.8487,22939500 +430,2012-05-21,1.856,1.9507,1.808,1.918,21505500 +431,2012-05-22,1.974,2.0893,1.966,2.0527,35101500 +432,2012-05-23,2.0527,2.07,1.9667,2.014,18036000 +433,2012-05-24,2.0833,2.0833,1.9793,2.0053,15760500 +434,2012-05-25,2.0267,2.0273,1.9467,1.9753,11173500 +435,2012-05-29,2.0007,2.1287,2.0007,2.1127,23724000 +436,2012-05-30,2.072,2.0947,2.016,2.0267,19323000 +437,2012-05-31,2.0493,2.05,1.9167,1.9913,15906000 +438,2012-06-01,1.94,1.9467,1.8507,1.886,13029000 +439,2012-06-04,1.8533,1.894,1.8073,1.8567,15243000 +440,2012-06-05,1.8607,1.8927,1.8373,1.8607,9331500 +441,2012-06-06,1.872,1.9887,1.872,1.9887,13300500 +442,2012-06-07,1.9993,2,1.9233,1.9293,7242000 +443,2012-06-08,1.9267,2.0127,1.8767,2.0053,12514500 +444,2012-06-11,2.0547,2.0667,1.9227,1.9227,9043500 +445,2012-06-12,1.9413,1.9893,1.9207,1.952,8221500 +446,2012-06-13,1.97,2.0427,1.9647,1.9847,12510000 +447,2012-06-14,2.014,2.0433,1.908,1.9593,12885000 +448,2012-06-15,1.9593,1.9967,1.9207,1.988,8910000 +449,2012-06-18,2.0167,2.1553,1.9667,2.004,17913000 +450,2012-06-19,2.12,2.1773,2.1,2.1507,13380000 +451,2012-06-20,2.1807,2.3,2.1807,2.252,50334000 +452,2012-06-21,2.24,2.2853,2.1227,2.1507,25275000 +453,2012-06-22,2.1733,2.2653,2.1527,2.252,44323500 +454,2012-06-25,2.2927,2.2927,2.1207,2.1267,22111500 +455,2012-06-26,2.138,2.1567,2.092,2.0933,37164000 +456,2012-06-27,2.1307,2.1633,2.1047,2.1307,14725500 +457,2012-06-28,2.1413,2.1413,2.0413,2.094,13173000 +458,2012-06-29,2.1213,2.262,2.0667,2.086,15910500 +459,2012-07-02,2.086,2.12,2.0127,2.0267,19246500 +460,2012-07-03,2.0333,2.0667,2.0267,2.0393,13993500 +461,2012-07-05,2.0733,2.1113,2.0467,2.0833,18108000 +462,2012-07-06,2.088,2.1153,2.0473,2.0473,10950000 +463,2012-07-09,2.0627,2.122,2.0447,2.0993,13303500 +464,2012-07-10,2.094,2.1653,2.0593,2.08,10500000 +465,2012-07-11,2.0907,2.112,2.0673,2.0887,8515500 +466,2012-07-12,2.086,2.2007,2.0533,2.18,15897000 +467,2012-07-13,2.1907,2.2933,2.18,2.2667,19225500 +468,2012-07-16,2.2667,2.4,2.26,2.3973,25431000 +469,2012-07-17,2.354,2.3827,2.1587,2.218,37756500 +470,2012-07-18,2.1967,2.2447,2.0553,2.1333,42406500 +471,2012-07-19,2.1333,2.21,2.1333,2.1433,21282000 +472,2012-07-20,2.1267,2.158,2.0833,2.1207,23131500 +473,2012-07-23,2.1227,2.1227,2.0413,2.1193,20463000 +474,2012-07-24,2.0467,2.0693,1.9747,2.0073,21778500 +475,2012-07-25,1.9733,2.0167,1.8353,1.8827,37428000 +476,2012-07-26,1.932,2.004,1.8427,1.8833,33084000 +477,2012-07-27,1.9107,1.9773,1.8733,1.9673,24735000 +478,2012-07-30,1.9713,2.0167,1.814,1.8367,29761500 +479,2012-07-31,1.8367,1.8647,1.8233,1.8527,20505000 +480,2012-08-01,1.8567,1.866,1.7327,1.7327,21585000 +481,2012-08-02,1.7507,1.79,1.7013,1.74,19086000 +482,2012-08-03,1.7553,1.8367,1.74,1.74,17092500 +483,2012-08-06,1.8227,1.9133,1.8227,1.8873,17017500 +484,2012-08-07,1.8893,2.06,1.8847,2.0167,28341000 +485,2012-08-08,2.0493,2.0527,1.906,1.9393,17298000 +486,2012-08-09,1.9633,2,1.9393,1.9533,9636000 +487,2012-08-10,1.9533,1.996,1.9533,1.996,10066500 +488,2012-08-13,1.9827,2.0867,1.94,2.0633,12691500 +489,2012-08-14,2.0667,2.078,1.9467,1.9467,11076000 +490,2012-08-15,1.9593,1.98,1.9207,1.96,7506000 +491,2012-08-16,1.9687,2.026,1.96,1.96,8028000 +492,2012-08-17,2,2.0473,1.9987,2,7033500 +493,2012-08-20,2.01,2.026,1.94,1.982,13743000 +494,2012-08-21,1.9727,2,1.9333,1.9407,10840500 +495,2012-08-22,1.9453,2.0167,1.93,2.0167,10396500 +496,2012-08-23,2,2.0567,1.9767,2.034,21502500 +497,2012-08-24,2.018,2.0487,1.9607,1.9727,20377500 +498,2012-08-27,1.972,1.98,1.878,1.8833,18559500 +499,2012-08-28,1.8947,1.9587,1.8667,1.9127,20662500 +500,2012-08-29,1.918,1.92,1.868,1.894,12213000 +501,2012-08-30,1.8673,1.916,1.8673,1.894,9609000 +502,2012-08-31,1.8993,1.9227,1.88,1.9007,7690500 +503,2012-09-04,1.9013,1.9327,1.86,1.876,10840500 +504,2012-09-05,1.8767,1.9,1.854,1.8627,9276000 +505,2012-09-06,1.8673,1.9267,1.86,1.9033,12036000 +506,2012-09-07,1.8933,1.9713,1.8933,1.9567,13315500 +507,2012-09-10,1.9467,1.9667,1.82,1.8233,20403000 +508,2012-09-11,1.874,1.8773,1.8267,1.85,12136500 +509,2012-09-12,1.86,1.9053,1.8533,1.9053,16017000 +510,2012-09-13,1.9053,1.9773,1.88,1.9493,20878500 +511,2012-09-14,1.9667,2.0433,1.9653,2.024,21982500 +512,2012-09-17,2.0453,2.2013,2.0453,2.1667,46476000 +513,2012-09-18,2.134,2.1693,2.0453,2.0893,26220000 +514,2012-09-19,2.09,2.116,2.0627,2.07,15385500 +515,2012-09-20,2.08,2.1,2.0453,2.0613,10585500 +516,2012-09-21,2.06,2.1,1.9693,2.0013,24996000 +517,2012-09-24,2,2.0687,1.96,2.044,18555000 +518,2012-09-25,2.0533,2.0533,1.7133,1.8553,78354000 +519,2012-09-26,1.85,1.8933,1.8,1.8427,22567500 +520,2012-09-27,1.85,1.9027,1.84,1.8893,26001000 +521,2012-09-28,1.92,1.9927,1.8667,1.956,64419000 +522,2012-10-01,1.9533,1.9927,1.9333,1.944,12910500 +523,2012-10-02,1.95,1.9927,1.9333,1.9867,10389000 +524,2012-10-03,1.9767,2,1.9493,2,12870000 +525,2012-10-04,1.9793,2.0133,1.91,1.9567,18454500 +526,2012-10-05,1.9733,1.9873,1.9067,1.9253,12109500 +527,2012-10-08,1.9267,1.96,1.9073,1.9467,13128000 +528,2012-10-09,1.9413,1.9413,1.8833,1.91,17464500 +529,2012-10-10,1.9,1.9333,1.8673,1.9133,7413000 +530,2012-10-11,1.906,1.932,1.8833,1.888,6646500 +531,2012-10-12,1.8953,1.9153,1.8333,1.8433,13588500 +532,2012-10-15,1.8473,1.87,1.7907,1.8067,20388000 +533,2012-10-16,1.8447,1.8727,1.8227,1.8707,7063500 +534,2012-10-17,1.8833,1.9227,1.8533,1.9213,9720000 +535,2012-10-18,1.9327,1.9327,1.852,1.8667,9792000 +536,2012-10-19,1.8527,1.88,1.82,1.8493,10015500 +537,2012-10-22,1.8493,1.8667,1.824,1.866,5101500 +538,2012-10-23,1.8267,1.904,1.8247,1.8833,8620500 +539,2012-10-24,1.9053,1.9053,1.812,1.82,12669000 +540,2012-10-25,1.8573,1.8573,1.83,1.8347,8308500 +541,2012-10-26,1.8333,1.8533,1.8013,1.8253,6726000 +542,2012-10-31,1.8333,1.89,1.8247,1.8753,11193000 +543,2012-11-01,1.8833,1.966,1.88,1.9527,14761500 +544,2012-11-02,1.9513,1.97,1.9033,1.9133,14913000 +545,2012-11-05,1.964,2.11,1.9553,2.1,29164500 +546,2012-11-06,2.1033,2.1033,1.9967,2.0813,34033500 +547,2012-11-07,2.09,2.1367,2.054,2.1033,25089000 +548,2012-11-08,2.0947,2.1253,2.0627,2.0873,18096000 +549,2012-11-09,2.068,2.0807,1.99,2.02,12726000 +550,2012-11-12,2.0193,2.1547,2.0107,2.15,8142000 +551,2012-11-13,2.0987,2.1333,2.048,2.1107,14413500 +552,2012-11-14,2.1307,2.1413,2.08,2.1,12508500 +553,2012-11-15,2.1133,2.1133,2.0333,2.06,13594500 +554,2012-11-16,2.06,2.156,2.0393,2.156,12493500 +555,2012-11-19,2.1333,2.2167,2.118,2.2,19404000 +556,2012-11-20,2.2,2.2073,2.1273,2.2073,13012500 +557,2012-11-21,2.1833,2.2313,2.1527,2.1613,12994500 +558,2012-11-23,2.1733,2.1887,2.1133,2.1413,6234000 +559,2012-11-26,2.1433,2.156,2.108,2.156,6823500 +560,2012-11-27,2.1553,2.1773,2.1013,2.1433,10090500 +561,2012-11-28,2.1533,2.286,2.1273,2.26,22344000 +562,2012-11-29,2.2433,2.2667,2.1913,2.234,15483000 +563,2012-11-30,2.24,2.2853,2.2007,2.2533,20268000 +564,2012-12-03,2.2667,2.3333,2.2333,2.316,26139000 +565,2012-12-04,2.3593,2.36,2.2367,2.2633,18213000 +566,2012-12-05,2.2567,2.2793,2.2387,2.2473,7434000 +567,2012-12-06,2.2667,2.32,2.2333,2.2933,9687000 +568,2012-12-07,2.2667,2.2993,2.2567,2.28,9814500 +569,2012-12-10,2.274,2.32,2.274,2.3047,13413000 +570,2012-12-11,2.3067,2.37,2.2973,2.3667,22396500 +571,2012-12-12,2.3427,2.3953,2.33,2.35,29326500 +572,2012-12-13,2.3487,2.3553,2.1833,2.25,31737000 +573,2012-12-14,2.252,2.2933,2.2393,2.2553,14131500 +574,2012-12-17,2.2667,2.3,2.25,2.2933,12079500 +575,2012-12-18,2.294,2.338,2.284,2.306,23095500 +576,2012-12-19,2.3267,2.3507,2.3013,2.3073,18744000 +577,2012-12-20,2.32,2.3207,2.27,2.2953,13641000 +578,2012-12-21,2.3,2.3,2.2387,2.2667,21853500 +579,2012-12-24,2.2,2.29,2.2,2.2853,5562000 +580,2012-12-26,2.264,2.3,2.2333,2.2333,8796000 +581,2012-12-27,2.234,2.2607,2.2,2.246,8053500 +582,2012-12-28,2.2413,2.2433,2.2,2.2,6033000 +583,2012-12-31,2.2027,2.2647,2.2,2.2567,8590500 +584,2013-01-02,2.3253,2.3633,2.3067,2.3567,16518000 +585,2013-01-03,2.3453,2.3633,2.3127,2.3127,10825500 +586,2013-03-14,2.5673,2.6,2.4027,2.4327,29146500 +587,2013-03-15,2.4333,2.4433,2.3473,2.3607,42304500 +588,2013-03-18,2.36,2.404,2.322,2.3467,17931000 +589,2013-03-19,2.366,2.3993,2.3293,2.3313,15828000 +590,2013-03-20,2.3507,2.4167,2.344,2.4147,16198500 +591,2013-03-21,2.4047,2.4707,2.3827,2.4007,15042000 +592,2013-03-22,2.4133,2.4533,2.4013,2.4413,6421500 +593,2013-03-25,2.4467,2.568,2.4467,2.5313,34368000 +594,2013-03-26,2.5067,2.548,2.5067,2.524,22050000 +595,2013-03-27,2.5133,2.5587,2.4873,2.5467,18799500 +596,2013-03-28,2.534,2.5707,2.5167,2.526,11656500 +597,2013-04-01,2.6067,3.112,2.6067,2.9667,201547500 +598,2013-04-02,2.94,3.046,2.846,2.8733,94021500 +599,2013-04-03,2.88,2.9467,2.6807,2.7253,82765500 +600,2013-04-04,2.7633,2.8167,2.7207,2.8,32724000 +601,2013-04-05,2.8,2.816,2.7,2.758,20602500 +602,2013-04-08,2.77,2.8367,2.7673,2.7887,23578500 +603,2013-04-09,2.7927,2.7927,2.6887,2.6933,22929000 +604,2013-04-10,2.714,2.8007,2.7013,2.7907,29934000 +605,2013-04-11,2.8093,2.97,2.7833,2.8667,50419500 +606,2013-04-12,2.906,3.0093,2.8673,2.9167,43282500 +607,2013-04-15,2.8673,2.9213,2.834,2.92,23191500 +608,2013-04-16,2.942,3.076,2.9273,3.032,41016000 +609,2013-04-17,3.0267,3.0633,2.9693,3.03,29680500 +610,2013-04-18,3.0653,3.1733,3.026,3.1627,45765000 +611,2013-04-19,3.1627,3.3253,3.138,3.1633,43929000 +612,2013-04-22,3.2133,3.3467,3.1667,3.346,56449500 +613,2013-04-23,3.346,3.528,3.346,3.3967,53149500 +614,2013-04-24,3.446,3.446,3.2653,3.38,36709500 +615,2013-04-25,3.4,3.4933,3.3653,3.48,40113000 +616,2013-04-26,3.5,3.5827,3.3747,3.3873,52822500 +617,2013-04-29,3.4,3.6667,3.3933,3.6653,52944000 +618,2013-04-30,3.6667,3.8787,3.5767,3.634,79696500 +619,2013-05-01,3.6447,3.7327,3.5333,3.596,37645500 +620,2013-05-02,3.5933,3.6847,3.5333,3.64,44152500 +621,2013-05-03,3.6833,3.7647,3.6233,3.6387,49215000 +622,2013-05-06,3.6727,4.0273,3.6727,4.0127,63787500 +623,2013-05-07,4,4.1893,3.6747,3.7707,145771500 +624,2013-05-08,3.7067,4.866,3.7,4.6,97968000 +625,2013-05-09,4.54,5.0513,4.246,4.59,416440500 +626,2013-05-10,4.6267,5.4,4.5447,5.1267,362424000 +627,2013-05-13,5.104,6.0133,5.0333,6.0007,324441000 +628,2013-05-14,6.0773,6.4747,5.41,5.4667,540166500 +629,2013-05-15,5.4673,6.2253,5.154,6.1333,245694000 +630,2013-05-16,6.1367,6.4267,5.9107,6.14,314040000 +631,2013-05-17,6.2493,6.3333,5.8333,6.0833,275742000 +632,2013-05-20,6.0933,6.1967,5.9087,5.9533,116409000 +633,2013-05-21,5.954,6.0533,5.6853,5.838,129556500 +634,2013-05-22,5.814,6.064,5.7,5.8187,124705500 +635,2013-05-23,5.7673,6.212,5.5367,6.2,173866500 +636,2013-05-24,6.16,6.53,6.1333,6.4967,234340500 +637,2013-05-28,6.53,7.4687,6.53,7.4533,286362000 +638,2013-05-29,7.4667,7.7,6.6,6.9133,365599500 +639,2013-05-30,7.0667,7.3027,6.7467,7,232486500 +640,2013-05-31,6.934,7.096,6.4893,6.4893,216676500 +641,2013-06-03,6.4533,6.7193,5.8833,6.16,279295500 +642,2013-06-04,6.1727,6.428,6.1427,6.3227,128937000 +643,2013-06-05,6.2667,6.5313,5.9407,6.3633,178788000 +644,2013-06-06,6.2867,6.618,6.2867,6.446,139008000 +645,2013-06-07,6.4767,6.86,6.4227,6.8,154503000 +646,2013-06-10,6.7227,6.8347,6.476,6.6,134262000 +647,2013-06-11,6.5713,6.5787,6.27,6.2893,107361000 +648,2013-06-12,6.298,6.6987,6.298,6.522,133843500 +649,2013-06-13,6.4073,6.6333,6.3413,6.5733,87330000 +650,2013-06-14,6.6193,6.8347,6.54,6.69,95694000 +651,2013-06-17,6.8467,6.9833,6.7467,6.794,103032000 +652,2013-06-18,6.8273,6.932,6.6133,6.9073,129123000 +653,2013-06-19,6.8547,7.1113,6.6527,6.934,125938500 +654,2013-06-20,6.9667,7.142,6.63,6.7333,148359000 +655,2013-06-21,6.8667,6.9293,6.5,6.58,171208500 +656,2013-06-24,6.5533,6.858,6.3533,6.8033,104620500 +657,2013-06-25,6.784,6.9467,6.7033,6.7967,85672500 +658,2013-06-26,6.8567,7.0993,6.844,7.0667,95920500 +659,2013-06-27,7.08,7.35,7.0587,7.2833,127455000 +660,2013-06-28,7.3333,7.372,7.114,7.1707,84156000 +661,2013-07-01,7.1973,7.8667,7.1973,7.85,159403500 +662,2013-07-02,7.9,8.126,7.7,7.8667,177274500 +663,2013-07-03,7.834,7.95,7.618,7.6733,70027500 +664,2013-07-05,7.8,8.03,7.6913,8.03,99724500 +665,2013-07-08,7.9847,8.1827,7.9213,8.13,113974500 +666,2013-07-09,8.1587,8.432,8.1273,8.2453,121951500 +667,2013-07-10,8.22,8.3033,8.0527,8.2733,81409500 +668,2013-07-11,8.3333,8.406,8.1567,8.3787,107755500 +669,2013-07-12,8.3127,8.6653,8.3007,8.6547,166258500 +670,2013-07-15,8.6667,8.92,8.4547,8.5153,144150000 +671,2013-07-16,8.5153,8.5833,7.096,7.1133,469743000 +672,2013-07-17,7.1833,8.1493,6.9667,8.1,379722000 +673,2013-07-18,8.114,8.22,7.7453,7.8707,166929000 +674,2013-07-19,8,8.0367,7.7673,7.9813,85578000 +675,2013-07-22,8.0453,8.4453,7.986,8.14,143059500 +676,2013-07-23,8.2133,8.3707,8.1213,8.1867,111156000 +677,2013-07-24,8.2667,8.316,7.9707,8.126,99454500 +678,2013-07-25,8.1,8.3167,8.0127,8.2847,76276500 +679,2013-07-26,8.424,8.8633,8.3,8.6273,139750500 +680,2013-07-29,8.7013,9.0247,8.5273,8.9773,141123000 +681,2013-07-30,9.0133,9.166,8.5453,8.8,190620000 +682,2013-07-31,8.8593,8.998,8.7633,8.9793,92283000 +683,2013-08-01,9,9.1087,8.842,9.0673,77371500 +684,2013-08-02,9.1,9.26,8.9073,9.2467,90321000 +685,2013-08-05,9.2587,9.666,9.1533,9.6467,148099500 +686,2013-08-06,9.71,9.78,9.4067,9.4833,133714500 +687,2013-08-07,9.5167,10.3667,8.824,10.2133,264238500 +688,2013-08-08,10.2953,10.592,9.9467,10.2167,387346500 +689,2013-08-09,10.26,10.3967,10.0833,10.2,129208500 +690,2013-08-12,10.21,10.21,9.47,9.8633,215790000 +691,2013-08-13,9.916,10,9.614,9.62,124554000 +692,2013-08-14,9.65,9.6953,9.2033,9.2347,166930500 +693,2013-08-15,9.3333,9.5733,9,9.3533,147001500 +694,2013-08-16,9.3333,9.594,9.3067,9.462,101158500 +695,2013-08-19,9.4667,9.8253,9.4667,9.7133,116574000 +696,2013-08-20,9.7667,10.01,9.7667,9.9873,90135000 +697,2013-08-21,9.998,10.0727,9.75,9.7867,89446500 +698,2013-08-22,9.8267,10.4987,9.8267,10.496,151780500 +699,2013-08-23,10.4947,10.82,10.3333,10.7833,187560000 +700,2013-08-26,10.7867,11.5333,10.6833,11.0707,350391000 +701,2013-08-27,11.0967,11.2533,10.712,11.1873,248074500 +702,2013-08-28,11.1867,11.4333,10.8833,11.0173,209382000 +703,2013-08-29,11.1573,11.1867,10.834,11.0333,134815500 +704,2013-08-30,11.1167,11.2967,10.9307,11.2893,161145000 +705,2013-09-03,11.3333,11.6587,11.0933,11.272,174235500 +706,2013-09-04,11.3333,11.4413,11.0373,11.3987,164263500 +707,2013-09-05,11.458,11.4993,11.2167,11.3333,95404500 +708,2013-09-06,11.3267,11.3333,11.01,11.0933,122739000 +709,2013-09-09,11.1333,11.1333,10.5673,10.6113,207159000 +710,2013-09-10,10.6487,11.1667,10.632,11.1053,128748000 +711,2013-09-11,11.1367,11.2073,10.8087,10.9247,83227500 +712,2013-09-12,10.934,11.1173,10.5273,10.8267,90027000 +713,2013-09-13,10.9267,11.0913,10.8107,11.0393,75963000 +714,2013-09-16,11.2,11.39,11.036,11.06,109735500 +715,2013-09-17,11.066,11.228,10.8907,11.0933,78295500 +716,2013-09-18,11.094,11.3233,10.9467,11.3,78660000 +717,2013-09-19,11.31,12.0313,11.1,11.8793,224395500 +718,2013-09-20,11.8333,12.3887,11.7947,12.2593,194923500 +719,2013-09-23,12.33,12.3653,11.8073,12.0073,119229000 +720,2013-09-24,12.074,12.3307,11.8433,12.144,90906000 +721,2013-09-25,12.1067,12.42,12.02,12.3727,117744000 +722,2013-09-26,12.4087,12.6453,12.3333,12.5647,95916000 +723,2013-09-27,12.5867,12.7533,12.4287,12.7467,84856500 +724,2013-09-30,12.6933,12.9667,12.5207,12.87,129867000 +725,2013-10-01,12.9067,12.9933,12.558,12.8713,112054500 +726,2013-10-02,12.8167,12.8733,11.6933,11.9033,298063500 +727,2013-10-03,11.7913,11.9793,11.2,11.5193,342652500 +728,2013-10-04,11.5333,12.2333,11.51,12.2307,209007000 +729,2013-10-07,12.3107,12.4487,12.0173,12.1927,166999500 +730,2013-10-08,12.2667,12.3953,11.5333,11.6833,198939000 +731,2013-10-09,11.7,11.8,10.7667,11.2533,220770000 +732,2013-10-10,11.2533,11.7167,11.22,11.5327,129027000 +733,2013-10-11,11.578,11.9993,11.4,11.98,119569500 +734,2013-10-14,11.8033,12.1667,11.61,12.022,112860000 +735,2013-10-15,12.022,12.586,12.022,12.3133,159427500 +736,2013-10-16,12.3333,12.4867,12.1393,12.2133,119692500 +737,2013-10-17,12.2667,12.3333,12.066,12.24,97383000 +738,2013-10-18,12.2873,12.3973,12.0733,12.1627,85054500 +739,2013-10-21,12.2933,12.3127,11.4,11.5593,165351000 +740,2013-10-22,11.6,11.852,11.074,11.396,166023000 +741,2013-10-23,11.38,11.454,10.6767,10.8887,190072500 +742,2013-10-24,10.92,11.8307,10.8553,11.8167,158160000 +743,2013-10-25,11.5407,11.814,11.12,11.2833,110428500 +744,2013-10-28,11.3107,11.4967,10.8073,10.84,112183500 +745,2013-10-29,10.84,11.06,10.2,10.934,205161000 +746,2013-10-30,11.0467,11.1787,10.5333,10.5333,121746000 +747,2013-10-31,10.52,10.8293,10.22,10.71,131301000 +748,2013-11-01,10.75,11.06,10.6627,10.8667,104220000 +749,2013-11-04,10.8667,11.7987,10.8667,11.7533,188814000 +750,2013-11-05,11.68,12.1313,10.2667,10.3333,319066500 +751,2013-11-06,10.44,10.7153,9.7573,10,442978500 +752,2013-11-07,9.8667,10.1333,9.1747,9.2007,319876500 +753,2013-11-08,9.1667,9.3833,8.8213,9.2553,316498500 +754,2013-11-11,9.1,9.6947,9.1,9.66,202396500 +755,2013-11-12,9.7667,9.8,9.0787,9.3933,213652500 +756,2013-11-13,9.39,9.4913,9.0893,9.2707,175584000 +757,2013-11-14,9.3333,9.3847,8.9407,9.1573,175161000 +758,2013-11-15,9.2,9.2627,8.9567,9.0013,143160000 +759,2013-11-18,9.0327,9.1,7.974,7.9893,333507000 +760,2013-11-19,8.0293,8.6,7.7033,8.52,282606000 +761,2013-11-20,8.5,8.5067,7.9373,8.0567,199353000 +762,2013-11-21,8.0727,8.3253,8.0067,8.11,172042500 +763,2013-11-22,8.1533,8.1833,7.862,8.1,162112500 +764,2013-11-25,8.0893,8.3893,8.02,8.046,150082500 +765,2013-11-26,8.098,8.1813,7.74,8.066,201268500 +766,2013-11-27,8.1313,8.5327,7.968,8.5253,178762500 +767,2013-11-29,8.6207,8.706,8.4333,8.4413,142236000 +768,2013-12-02,8.48,8.57,8.258,8.43,110358000 +769,2013-12-03,8.4447,9.6627,8.2867,9.62,374767500 +770,2013-12-04,9.7673,9.7993,9.142,9.2567,191470500 +771,2013-12-05,9.3773,9.5567,9.3,9.334,134154000 +772,2013-12-06,9.412,9.5293,9.0867,9.1387,115554000 +773,2013-12-09,9.2067,9.4947,8.9473,9.45,150270000 +774,2013-12-10,9.3993,9.7247,9.2413,9.4973,172441500 +775,2013-12-11,9.4807,9.5767,9.298,9.32,111934500 +776,2013-12-12,9.37,9.8827,9.2353,9.8133,173362500 +777,2013-12-13,9.8553,10.12,9.8,9.816,174357000 +778,2013-12-16,9.8433,10.03,9.74,9.8227,109501500 +779,2013-12-17,9.822,10.3087,9.7533,10.18,174391500 +780,2013-12-18,10.18,10.3267,9.73,9.8633,182674500 +781,2013-12-19,9.8667,9.9993,9.2733,9.3733,202656000 +782,2013-12-20,9.4007,9.624,9.3767,9.516,123055500 +783,2013-12-23,9.6327,9.7493,9.5067,9.6433,88005000 +784,2013-12-24,9.7567,10.3327,9.686,10.068,159850500 +785,2013-12-26,10.21,10.5333,10.1767,10.4067,118942500 +786,2013-12-27,10.368,10.4527,10.0333,10.0333,93999000 +787,2013-12-30,10.0747,10.3207,10.0333,10.1533,74286000 +788,2013-12-31,10.1993,10.2627,9.9107,10.0327,72408000 +789,2014-01-02,10.04,10.1653,9.77,10.0093,102918000 +790,2014-01-03,10.0067,10.1467,9.9067,9.932,78061500 +791,2014-01-06,10,10.032,9.682,9.776,89131500 +792,2014-01-07,9.8,10.0267,9.6833,9.9207,83844000 +793,2014-01-08,9.9573,10.2467,9.8673,10.1,101304000 +794,2014-01-09,10.0933,10.2287,9.79,9.8567,88711500 +795,2014-01-10,9.874,9.9667,9.4833,9.73,126364500 +796,2014-01-13,9.76,9.8,9.188,9.3167,84717000 +797,2014-01-14,9.2933,11.172,9.1113,11.0167,379350000 +798,2014-01-15,10.98,11.4907,10.8067,10.942,274327500 +799,2014-01-16,11.026,11.5133,10.7773,11.452,160425000 +800,2014-01-17,11.4147,11.5467,11.1967,11.36,124987500 +801,2014-01-21,11.3333,11.8193,11.3,11.7867,130549500 +802,2014-01-22,11.9833,12.0213,11.6507,11.904,90628500 +803,2014-01-23,11.8133,12.1587,11.5613,12,104628000 +804,2014-01-24,11.862,12.0333,11.554,11.5667,101746500 +805,2014-01-27,11.7,11.8613,10.9807,11.1867,115896000 +806,2014-01-28,11.308,11.9593,11.2927,11.9593,80989500 +807,2014-01-29,11.9287,11.9393,11.542,11.7867,77025000 +808,2014-01-30,11.6833,12.3187,11.6833,12.2333,107673000 +809,2014-01-31,12.3333,12.4,11.9007,12.0773,84319500 +810,2014-02-03,11.6667,12.3253,11.6667,11.8187,89644500 +811,2014-02-04,11.8,12.1067,11.7467,11.922,62623500 +812,2014-02-05,11.87,12.0393,11.2907,11.6533,93388500 +813,2014-02-06,11.668,12.0073,11.628,11.8953,73384500 +814,2014-02-07,12.032,12.488,11.9,12.4733,117148500 +815,2014-02-10,12.5627,13.2867,12.42,13.1027,164770500 +816,2014-02-11,13.2,13.48,12.8467,12.9733,140068500 +817,2014-02-12,13.1067,13.218,12.9547,13.0007,66439500 +818,2014-02-13,12.9333,13.5147,12.684,13.1313,105280500 +819,2014-02-14,13.2073,13.4587,13.1273,13.1933,80040000 +820,2014-02-18,13.1333,13.8833,13.1333,13.5567,117477000 +821,2014-02-19,13.6893,15,12.8867,14.5393,202486500 +822,2014-02-20,14.446,14.5667,13.7513,13.968,231760500 +823,2014-02-21,14.0327,14.2653,13.946,13.9947,102037500 +824,2014-02-24,13.98,14.5573,13.876,14.4867,108903000 +825,2014-02-25,14.6533,17.28,14.6533,16.8467,420369000 +826,2014-02-26,16.9333,17.6667,16.3693,17.44,312486000 +827,2014-02-27,17.5333,17.83,16.5553,16.804,223077000 +828,2014-02-28,16.9333,16.94,16.17,16.2567,180037500 +829,2014-03-03,15.4667,16.7767,15.4667,16.6667,165219000 +830,2014-03-04,16.91,17.386,16.8553,16.964,108879000 +831,2014-03-05,17.2,17.2653,16.7867,16.82,72594000 +832,2014-03-06,16.9333,17.1667,16.63,16.86,94290000 +833,2014-03-07,16.8667,16.99,16.294,16.3767,95437500 +834,2014-03-10,16.27,16.4387,15.7373,15.8193,97983000 +835,2014-03-11,15.8333,16.3067,15.4953,15.5033,109213500 +836,2014-03-12,15.4733,16.2993,15.2647,16.1927,123525000 +837,2014-03-13,16.248,16.33,15.6,15.7667,79090500 +838,2014-03-14,15.6467,15.8527,15.2213,15.3333,103077000 +839,2014-03-17,15.51,15.862,15.3667,15.7067,76896000 +840,2014-03-18,15.7047,16.1,15.6,16.0467,78610500 +841,2014-03-19,16.1613,16.2133,15.5673,15.72,62955000 +842,2014-03-20,15.7333,15.95,15.5573,15.6133,47638500 +843,2014-03-21,15.7333,15.76,15.1667,15.18,104617500 +844,2014-03-24,15.3867,15.4173,14.018,14.7233,142279500 +845,2014-03-25,14.746,15.1367,14.5267,14.7193,99859500 +846,2014-03-26,14.8113,14.9333,14.09,14.1793,87933000 +847,2014-03-27,14.1347,14.252,13.5333,13.7153,120972000 +848,2014-03-28,13.7367,14.448,13.734,14.294,125509500 +849,2014-03-31,14.3267,14.4513,13.7593,13.8533,106504500 +850,2014-04-01,13.88,14.544,13.8667,14.528,93630000 +851,2014-04-02,14.5847,15.4787,14.5367,15.4727,138853500 +852,2014-04-03,15.5253,15.7153,14.8,15.0153,140214000 +853,2014-04-04,15.14,15.218,14.0493,14.0867,146892000 +854,2014-04-07,13.954,14.4133,13.5673,13.8593,126373500 +855,2014-04-08,13.9667,14.4327,13.708,14.3327,87385500 +856,2014-04-09,14.4667,14.5633,14.0593,14.5033,65019000 +857,2014-04-10,14.4747,14.5333,13.5067,13.546,89880000 +858,2014-04-11,13.546,13.8,13.24,13.6067,115252500 +859,2014-04-14,13.56,13.9667,12.9607,13.2233,96993000 +860,2014-04-15,13.2067,13.4,12.288,13.0127,174859500 +861,2014-04-16,13.182,13.3327,12.7213,13.1333,87391500 +862,2014-04-17,13.1667,13.486,12.9387,13.2,75393000 +863,2014-04-21,13.234,13.7467,12.9333,13.6933,67105500 +864,2014-04-22,13.7687,14.622,13.6067,14.5073,123586500 +865,2014-04-23,14.6,14.6653,13.8,14.04,91764000 +866,2014-04-24,14.0333,14.1867,13.5467,13.8333,67018500 +867,2014-04-25,13.8507,13.8867,13.1767,13.3027,88900500 +868,2014-04-28,13.2667,13.586,12.7,13.28,90400500 +869,2014-04-29,13.3387,13.81,13.0353,13.7,74610000 +870,2014-04-30,13.666,13.924,13.4187,13.9067,55795500 +871,2014-05-01,13.878,14.268,13.7127,13.8167,68469000 +872,2014-05-02,13.9727,14.1033,13.768,14.0867,51756000 +873,2014-05-05,14.1327,14.5127,13.8673,14.4467,62872500 +874,2014-05-06,14.5333,14.5773,13.7867,13.8173,71347500 +875,2014-05-07,13.8867,14.05,12.254,12.406,127287000 +876,2014-05-08,12.53,12.96,11.8147,11.8427,257352000 +877,2014-05-09,11.95,12.2267,11.8147,12.1333,109512000 +878,2014-05-12,12.1333,12.4793,11.992,12.332,91471500 +879,2014-05-13,12.3873,12.756,12.16,12.6793,91531500 +880,2014-05-14,12.7007,12.8987,12.4733,12.73,70441500 +881,2014-05-15,12.6207,12.844,12.3533,12.5787,79266000 +882,2014-05-16,12.5333,12.8027,12.474,12.77,57685500 +883,2014-05-19,12.7707,13.1333,12.6667,13.1333,59709000 +884,2014-05-20,13.08,13.2887,12.8713,12.9793,72919500 +885,2014-05-21,13,13.3333,12.986,13.326,67347000 +886,2014-05-22,13.348,13.792,13.3033,13.6507,77029500 +887,2014-05-23,13.6867,13.8507,13.5,13.826,49992000 +888,2014-05-27,13.9333,14.258,13.8,14.078,68053500 +889,2014-05-28,14.0387,14.1847,13.684,14,68530500 +890,2014-05-29,14.0133,14.166,13.848,14,46740000 +891,2014-05-30,14.0213,14.32,13.7833,13.8227,72352500 +892,2014-06-02,13.8213,13.9567,13.4447,13.5667,59125500 +893,2014-06-03,13.59,13.8667,13.506,13.64,50698500 +894,2014-06-04,13.6473,13.7507,13.36,13.5433,44190000 +895,2014-06-05,13.5827,13.9467,13.5507,13.8,50929500 +896,2014-06-06,13.9267,14.054,13.812,13.858,39301500 +897,2014-06-09,13.8993,13.9993,13.5867,13.602,34545000 +898,2014-06-10,13.5853,13.798,13.4367,13.484,43896000 +899,2014-06-11,13.44,13.6667,13.2833,13.6333,52020000 +900,2014-06-12,13.6493,13.992,13.514,13.5627,78660000 +901,2014-06-13,13.596,13.816,13.4387,13.7227,91671000 +902,2014-06-16,13.8,15.0327,13.694,15,171028500 +903,2014-06-17,14.9767,15.7027,14.8567,15.3667,169213500 +904,2014-06-18,15.3713,15.4993,15.0747,15.12,89343000 +905,2014-06-19,15.1547,15.6873,15.0667,15.0687,114487500 +906,2014-06-20,15.202,15.4193,15.08,15.2667,63924000 +907,2014-06-23,15.264,15.9327,15.2147,15.846,100888500 +908,2014-06-24,15.82,16.1253,15.442,15.5133,104314500 +909,2014-06-25,15.472,15.8367,15.3493,15.7833,74611500 +910,2014-06-26,15.7853,16.0267,15.614,15.6733,65886000 +911,2014-06-27,15.6667,16,15.5667,15.9573,75367500 +912,2014-06-30,15.868,16.2993,15.868,16.0233,61995000 +913,2014-07-01,16.066,16.2293,15.9133,15.9633,53196000 +914,2014-07-02,15.9667,16.1553,15.138,15.32,102298500 +915,2014-07-03,15.3333,15.5933,14.9333,15.2327,66034500 +916,2014-07-07,15.2113,15.3333,14.6933,14.7833,74419500 +917,2014-07-08,14.8667,14.8667,14.2847,14.598,101098500 +918,2014-07-09,14.6107,14.948,14.5993,14.8667,50980500 +919,2014-07-10,14.8347,14.8667,14.4027,14.62,63258000 +920,2014-07-11,14.6587,14.7927,14.4667,14.502,41347500 +921,2014-07-14,14.6827,15.2527,14.3633,15.1333,92257500 +922,2014-07-15,15.1707,15.2,14.54,14.62,71305500 +923,2014-07-16,14.6533,14.9867,14.4273,14.4387,51513000 +924,2014-07-17,14.4467,14.7033,14.2333,14.3247,57648000 +925,2014-07-18,14.35,14.7473,14.3333,14.68,53826000 +926,2014-07-21,14.6813,14.8807,14.448,14.6993,49165500 +927,2014-07-22,14.836,14.8867,14.6073,14.6407,35058000 +928,2014-07-23,14.628,14.9833,14.628,14.906,39615000 +929,2014-07-24,14.9053,15.0067,14.72,14.8347,39552000 +930,2014-07-25,14.824,15.1313,14.77,14.914,39411000 +931,2014-07-28,14.894,15.4667,14.76,14.9767,84943500 +932,2014-07-29,15.024,15.22,14.944,15.0533,41269500 +933,2014-07-30,15.0333,15.3067,14.6833,15.2867,60807000 +934,2014-07-31,15.3573,15.4713,13.9147,14.8727,96696000 +935,2014-08-01,14.8333,15.8333,14.388,15.54,153400500 +936,2014-08-04,15.6653,16.0333,15.4667,15.8867,75952500 +937,2014-08-05,15.9087,16.1993,15.7127,15.9287,67884000 +938,2014-08-06,15.9467,16.7613,15.8167,16.536,118677000 +939,2014-08-07,16.5667,17.1127,16.5067,16.8033,95010000 +940,2014-08-08,16.752,16.826,16.4333,16.5473,64384500 +941,2014-08-11,16.8327,17.5827,16.5333,17.2627,101056500 +942,2014-08-12,17.3587,17.3813,16.972,17.3333,74634000 +943,2014-08-13,17.39,17.7093,17.3073,17.532,88335000 +944,2014-08-14,17.5867,17.5927,17.236,17.41,51877500 +945,2014-08-15,17.4953,17.5193,17.2333,17.4667,47685000 +946,2014-08-18,17.5333,17.8173,17.2833,17.2833,71943000 +947,2014-08-19,17.3313,17.4,16.7747,17.0787,66840000 +948,2014-08-20,17.0153,17.2493,16.8667,17.0167,38166000 +949,2014-08-21,17.0667,17.2533,16.884,16.96,37018500 +950,2014-08-22,16.9267,17.1413,16.8407,17.116,35620500 +951,2014-08-25,17.2,17.5787,17.1333,17.51,55287000 +952,2014-08-26,17.5333,17.706,17.44,17.468,47110500 +953,2014-08-27,17.5,17.616,17.3527,17.55,38287500 +954,2014-08-28,17.4273,17.632,17.41,17.606,36576000 +955,2014-08-29,17.666,18.1333,17.666,17.9833,82822500 +956,2014-09-02,18.0067,18.9927,18.0067,18.9733,122932500 +957,2014-09-03,18.9967,19.2513,18.6733,18.7067,83658000 +958,2014-09-04,18.8133,19.428,18.62,19.1133,104331000 +959,2014-09-05,19.198,19.2607,18.1673,18.442,136144500 +960,2014-09-08,18.5433,18.992,18.4927,18.8,69922500 +961,2014-09-09,18.8313,19.0327,18.4667,18.5933,57493500 +962,2014-09-10,18.6,18.7647,18.244,18.7533,46741500 +963,2014-09-11,18.8,18.986,18.5753,18.6767,48127500 +964,2014-09-12,18.7193,18.826,18.4667,18.59,41457000 +965,2014-09-15,18.5413,18.5413,16.6087,17,209746500 +966,2014-09-16,17.1153,17.4973,16.828,17.38,106606500 +967,2014-09-17,17.4967,17.6467,17.3,17.434,65944500 +968,2014-09-18,17.5413,17.7067,17.4253,17.55,47353500 +969,2014-09-19,17.6,17.6333,17.0087,17.2307,87552000 +970,2014-09-22,17.2187,17.3133,16.314,16.5333,104559000 +971,2014-09-23,16.4327,16.92,16.2333,16.66,73747500 +972,2014-09-24,16.63,16.856,16.4693,16.7967,48142500 +973,2014-09-25,16.918,16.9973,16.4067,16.48,61905000 +974,2014-09-26,16.4707,16.6487,16.4047,16.4367,49257000 +975,2014-09-29,16.3587,16.576,16.0467,16.3133,61668000 +976,2014-09-30,16.3673,16.51,16.008,16.1933,54453000 +977,2014-10-01,16.1667,16.2333,15.71,16.0573,75615000 +978,2014-10-02,16.0973,16.9867,16.0413,16.724,118692000 +979,2014-10-03,16.8667,17.1,16.7353,17.0667,70530000 +980,2014-10-06,17.0767,17.4993,17.014,17.35,102403500 +981,2014-10-07,17.3547,17.4307,17.0487,17.3267,59218500 +982,2014-10-08,17.3267,17.5253,16.8427,17.352,63711000 +983,2014-10-09,17.466,17.7027,16.96,17.2373,94407000 +984,2014-10-10,16.7993,16.8667,15.68,15.8133,167515500 +985,2014-10-13,15.8067,16.0193,14.6667,14.87,145405500 +986,2014-10-14,15,15.498,14.8667,15.2493,89052000 +987,2014-10-15,15.2013,15.3993,14.488,14.8993,116542500 +988,2014-10-16,14.8667,15.328,14.5,15.1053,66036000 +989,2014-10-17,15.286,15.6513,15.09,15.1633,146335500 +990,2014-10-20,15.2693,15.4933,14.8747,15.388,43081500 +991,2014-10-21,15.4667,15.7167,15.226,15.6333,49818000 +992,2014-10-22,15.6107,15.826,15.3707,15.4567,50922000 +993,2014-10-23,15.554,15.752,15.4067,15.69,44418000 +994,2014-10-24,15.6573,15.8533,15.4133,15.7067,44964000 +995,2014-10-27,15.7107,15.7333,14.6873,14.792,122512500 +996,2014-10-28,14.9333,16.3067,14.9333,16.0307,136755000 +997,2014-10-29,16.1653,16.2667,15.7093,15.8607,64392000 +998,2014-10-30,15.8667,16.0333,15.6407,15.9107,41557500 +999,2014-10-31,16.1267,16.2333,15.9167,16.1127,95433000 +1000,2014-11-03,16.1533,16.504,16.088,16.152,53284500 +1001,2014-11-04,16.2013,16.2267,15.7687,15.9993,45828000 +1002,2014-11-05,16.0967,16.6267,14.4667,16.46,110295000 +1003,2014-11-06,16.4,16.446,15.2333,16.12,199843500 +1004,2014-11-07,16.332,16.332,15.8133,15.9907,66370500 +1005,2014-11-10,16.036,16.192,15.7867,16.152,60531000 +1006,2014-11-11,16.1347,16.788,16.0973,16.74,104346000 +1007,2014-11-12,16.7467,16.8227,16.372,16.6593,74176500 +1008,2014-11-13,16.6767,17.05,16.6067,16.8,83121000 +1009,2014-11-14,16.7813,17.2567,16.4467,17.2233,80746500 +1010,2014-11-17,17.1833,17.2667,16.8013,16.93,106527000 +1011,2014-11-18,16.9573,17.3327,16.8667,17.1733,59107500 +1012,2014-11-19,17.1833,17.1973,16.3733,16.5687,102915000 +1013,2014-11-20,16.4367,16.7287,16.4,16.6327,46186500 +1014,2014-11-21,16.656,16.8667,16.12,16.1513,98868000 +1015,2014-11-24,16.3153,16.5567,16.0427,16.4253,62733000 +1016,2014-11-25,16.5053,16.648,16.4,16.566,41280000 +1017,2014-11-26,16.582,16.6,16.44,16.592,25401000 +1018,2014-11-28,16.486,16.6433,16.168,16.2733,26473500 +1019,2014-12-01,16.162,16.3647,15.2673,15.4993,111850500 +1020,2014-12-02,15.5733,15.8127,15.2,15.4653,77887500 +1021,2014-12-03,15.4933,15.512,15.0333,15.3327,68868000 +1022,2014-12-04,15.3327,15.5033,15.154,15.1913,50370000 +1023,2014-12-05,15.234,15.3653,14.7893,14.9667,79653000 +1024,2014-12-08,14.9193,14.9907,14.1333,14.3193,121050000 +1025,2014-12-09,14.1333,14.5153,13.618,14.4167,124179000 +1026,2014-12-10,14.4833,14.5233,13.8467,13.9407,96352500 +1027,2014-12-11,13.9833,14.362,13.8193,13.8667,86691000 +1028,2014-12-12,13.8387,14.112,13.602,13.86,93274500 +1029,2014-12-15,14.05,14.05,13.5113,13.5667,67555500 +1030,2014-12-16,13.6,13.6,13.0247,13.1667,109290000 +1031,2014-12-17,13.1873,13.7793,12.8333,13.77,95917500 +1032,2014-12-18,13.9627,14.5913,13.9627,14.5507,95482500 +1033,2014-12-19,14.7273,14.8113,14.3,14.6127,91818000 +1034,2014-12-22,14.6667,14.9373,14.5507,14.8367,63783000 +1035,2014-12-23,14.8653,14.9667,14.6347,14.7,58047000 +1036,2014-12-24,14.7313,14.8333,14.6167,14.8307,17316000 +1037,2014-12-26,14.8267,15.2333,14.7647,15.1893,43195500 +1038,2014-12-29,15.1433,15.194,14.9347,15.046,35398500 +1039,2014-12-30,14.9247,15.0667,14.76,14.838,38286000 +1040,2014-12-31,14.838,15.0453,14.8153,14.8267,30895500 +1041,2015-01-02,14.886,14.9333,14.2173,14.62,60666000 +1042,2015-01-05,14.57,14.57,13.8107,13.908,68766000 +1043,2015-01-06,13.9333,14.28,13.614,14.0933,81739500 +1044,2015-01-07,14.1867,14.3187,13.9853,14.0733,38506500 +1045,2015-01-08,14.1613,14.3213,14.0007,14.0633,43804500 +1046,2015-01-09,13.8607,14.0533,13.664,13.75,60375000 +1047,2015-01-12,13.7047,13.7047,13.2833,13.4873,77257500 +1048,2015-01-13,13.4267,13.8407,12.5333,12.7967,56380500 +1049,2015-01-14,12.8013,13.0133,12.2333,12.8533,149176500 +1050,2015-01-15,12.936,13.05,12.6367,12.74,68364000 +1051,2015-01-16,12.7047,12.966,12.3367,12.8953,46059000 +1052,2015-01-20,12.89,13.0193,12.4693,12.84,57217500 +1053,2015-01-21,12.652,13.2453,12.3333,13.104,54037500 +1054,2015-01-22,13.2387,13.5493,13.0133,13.5167,53611500 +1055,2015-01-23,13.4833,13.5667,13.222,13.4093,43978500 +1056,2015-01-26,13.3913,13.908,13.3667,13.782,41752500 +1057,2015-01-27,13.8,13.8687,13.48,13.7933,35581500 +1058,2015-01-28,13.8253,13.8633,13.228,13.3333,40210500 +1059,2015-01-29,13.2673,13.732,13.1,13.6907,42373500 +1060,2015-01-30,13.7333,13.8313,13.5333,13.5667,39295500 +1061,2015-02-02,13.574,14.13,13.5533,14.0007,54160500 +1062,2015-02-03,14.2,14.6913,14.0333,14.5733,62689500 +1063,2015-02-04,14.4907,14.7653,14.4533,14.5167,40846500 +1064,2015-02-05,14.5853,15.032,14.57,14.73,45030000 +1065,2015-02-06,14.6673,14.8933,14.4333,14.45,41568000 +1066,2015-02-09,14.4333,14.5533,14.1327,14.5007,45162000 +1067,2015-02-10,14.4747,14.7,14.268,14.32,70638000 +1068,2015-02-11,14.3267,14.5227,13.4,13.6333,122290500 +1069,2015-02-12,13.6327,13.6327,12.8747,13.5233,202587000 +1070,2015-02-13,13.6667,13.7327,13.394,13.5213,77947500 +1071,2015-02-17,13.7333,13.8087,13.4333,13.6567,48615000 +1072,2015-02-18,13.6627,13.7447,13.5067,13.6,66528000 +1073,2015-02-19,13.626,14.1627,13.5833,14.1067,65745000 +1074,2015-02-20,14.106,14.5067,13.98,14.4767,78301500 +1075,2015-02-23,14.4,14.5467,13.7553,13.7767,112644000 +1076,2015-02-24,13.792,13.8573,13.4467,13.5633,87600000 +1077,2015-02-25,13.5667,13.8093,13.5053,13.59,52257000 +1078,2015-02-26,13.6147,14.0727,13.4813,13.824,86088000 +1079,2015-02-27,13.8267,13.9033,13.52,13.5567,50161500 +1080,2015-03-02,13.5333,13.5733,13.0547,13.1533,101004000 +1081,2015-03-03,13.1867,13.35,13.0213,13.2933,57592500 +1082,2015-03-04,13.2447,13.5013,13.1473,13.45,57156000 +1083,2015-03-05,13.5353,13.746,13.3407,13.3573,65712000 +1084,2015-03-06,13.3347,13.4,12.81,12.978,87417000 +1085,2015-03-09,12.898,12.974,12.55,12.75,87274500 +1086,2015-03-10,12.6667,12.9,12.5067,12.688,69730500 +1087,2015-03-11,12.7,13.0787,12.6953,12.9007,64245000 +1088,2015-03-12,12.9167,12.9633,12.65,12.7573,53023500 +1089,2015-03-13,12.7573,12.7867,12.4733,12.58,67867500 +1090,2015-05-26,16.4667,16.8,16.4333,16.5,43978500 +1091,2015-05-27,16.5733,16.6593,16.37,16.5013,43153500 +1092,2015-05-28,16.4907,16.79,16.3367,16.7773,44253000 +1093,2015-05-29,16.7587,16.858,16.6287,16.7167,49329570 +1094,2015-06-01,16.7987,16.8,16.498,16.63,31530225 +1095,2015-06-02,16.616,16.6667,16.42,16.5467,26885745 +1096,2015-06-03,16.6,16.7147,16.4673,16.6033,22884615 +1097,2015-06-04,16.4807,16.62,16.3667,16.3667,30814980 +1098,2015-06-05,16.384,16.6467,16.3533,16.61,40628865 +1099,2015-06-08,16.6873,17.25,16.58,17.1233,65460270 +1100,2015-06-09,17.0333,17.1827,16.9427,16.9807,32805165 +1101,2015-06-10,17.0667,17.1033,16.5487,16.7133,43567065 +1102,2015-06-11,16.8333,16.9793,16.6953,16.7167,26028345 +1103,2015-06-12,16.7073,16.8973,16.6767,16.7307,18391890 +1104,2015-06-15,16.6947,16.752,16.4007,16.6973,27654165 +1105,2015-06-16,16.6287,16.896,16.606,16.882,24904965 +1106,2015-06-17,16.8833,17.624,16.8,17.4207,70233015 +1107,2015-06-18,17.3647,17.564,17.3333,17.46,35891805 +1108,2015-06-19,17.5147,17.5867,17.34,17.5,32618625 +1109,2015-06-22,17.7,17.7313,17.046,17.3233,60604575 +1110,2015-06-23,17.3713,17.8667,17.238,17.84,50767455 +1111,2015-06-24,17.8547,17.8547,17.5813,17.66,29859885 +1112,2015-06-25,17.732,18.094,17.68,17.9133,37257870 +1113,2015-06-26,17.9067,17.9673,17.7333,17.8173,46306020 +1114,2015-06-29,17.6,17.73,17.3267,17.4833,44892210 +1115,2015-06-30,17.482,18.0613,17.482,17.9167,40032600 +1116,2015-07-01,17.9667,18.2333,17.8567,17.9567,26522145 +1117,2015-07-02,17.956,18.8453,17.9067,18.6507,89596185 +1118,2015-07-06,18.5993,18.7913,18.42,18.6867,51407370 +1119,2015-07-07,18.4233,18.4933,17.3847,17.71,76788555 +1120,2015-07-08,17.5673,17.5993,16.954,17.0147,77151690 +1121,2015-07-09,17.24,17.532,17.1193,17.2667,42350805 +1122,2015-07-10,17.294,17.6467,17.188,17.2787,32995410 +1123,2015-07-13,17.4133,17.5227,17.07,17.46,37339440 +1124,2015-07-14,17.536,17.7867,17.3673,17.6833,23937300 +1125,2015-07-15,17.7853,17.9033,17.4067,17.5213,24810810 +1126,2015-07-16,17.6873,18.0587,17.544,17.9667,19932795 +1127,2015-07-17,18.0193,18.3693,17.8833,18.31,64817235 +1128,2015-07-20,18.4333,19.11,18.1693,18.8267,62984370 +1129,2015-07-21,18.8313,18.8313,17.608,17.6667,76316850 +1130,2015-07-22,17.6333,17.9627,17.3333,17.858,38555175 +1131,2015-07-23,18.0067,18.0067,17.6847,17.8533,28486500 +1132,2015-07-24,17.9267,18.0727,17.5947,17.7067,37048095 +1133,2015-07-27,17.682,17.682,16.7193,16.88,60568065 +1134,2015-07-28,17.0113,17.6933,16.7887,17.6933,48846450 +1135,2015-07-29,17.7187,17.8593,17.4667,17.5753,34009380 +1136,2015-07-30,17.6133,17.8293,17.474,17.7987,26370390 +1137,2015-07-31,17.8767,17.9573,17.674,17.6933,27594270 +1138,2015-08-03,17.7333,17.842,17.138,17.3433,32603745 +1139,2015-08-04,17.338,17.7813,17.2227,17.6833,28507875 +1140,2015-08-05,17.7933,18.4667,16.3333,17,68174265 +1141,2015-08-06,17.0133,17.0493,15.7413,16.3833,189249225 +1142,2015-08-07,16.3533,16.4087,15.8927,16.1673,67028235 +1143,2015-08-10,16.1333,16.198,15.7367,16.04,53537460 +1144,2015-08-11,15.9033,15.9533,15.6293,15.8247,52796445 +1145,2015-08-12,15.7073,15.9847,15.4913,15.9347,46502790 +1146,2015-08-13,16.0133,16.432,15.9267,16.208,58656540 +1147,2015-08-14,16.1967,16.6147,16.118,16.2567,53596260 +1148,2015-08-17,16.3333,17.2587,16.3333,17.02,88423530 +1149,2015-08-18,17.1,17.4,16.904,17.3733,53375535 +1150,2015-08-19,17.4673,17.4673,16.964,16.9867,46379340 +1151,2015-08-20,16.8687,16.9707,16.0007,16.034,62651175 +1152,2015-08-21,16.044,16.2533,15.314,15.3433,83421645 +1153,2015-08-24,14.5667,15.4267,13,14.6667,120938985 +1154,2015-08-25,15.2667,15.5333,14.5667,14.5667,53007090 +1155,2015-08-26,15.1493,15.3333,14.3673,15.02,63997230 +1156,2015-08-27,15.318,16.3167,15.2593,16.2173,98315805 +1157,2015-08-28,16.1307,16.7633,15.9333,16.592,71507475 +1158,2015-08-31,16.2647,16.9967,16.236,16.474,122503890 +1159,2015-09-01,16.3333,16.4,15.798,15.9733,71484615 +1160,2015-09-02,15.9453,17.0327,15.9453,16.9333,61671885 +1161,2015-09-03,16.9167,17.0033,16.2067,16.2333,53779770 +1162,2015-09-04,16.1453,16.2727,15.88,16.1287,47893560 +1163,2015-09-08,16.53,16.75,16.27,16.686,40088835 +1164,2015-09-09,16.6867,16.9627,16.5333,16.6053,43224345 +1165,2015-09-10,16.7107,16.8007,16.3553,16.5933,33505485 +1166,2015-09-11,16.4667,16.6927,16.3153,16.69,30261885 +1167,2015-09-14,16.7313,16.95,16.6033,16.876,37000215 +1168,2015-09-15,16.82,16.9733,16.6333,16.93,37735680 +1169,2015-09-16,16.9453,17.5253,16.8587,17.4993,53034555 +1170,2015-09-17,17.4547,17.7,17.3793,17.4607,44743740 +1171,2015-09-18,17.4533,17.588,17.16,17.3327,46208550 +1172,2015-09-21,17.3153,18.1047,17.0533,17.6667,78873465 +1173,2015-09-22,17.5853,17.5853,17.058,17.3973,47461185 +1174,2015-09-23,17.2933,17.5313,17.172,17.3973,33568950 +1175,2015-09-24,17.3867,17.5667,17.0807,17.5667,43135980 +1176,2015-09-25,17.6,17.8167,17.0767,17.13,49134375 +1177,2015-09-28,17.1893,17.3193,16.4407,16.6053,127229130 +1178,2015-09-29,16.7333,16.982,16.364,16.4467,47435895 +1179,2015-09-30,16.6247,16.926,16.156,16.5633,62164515 +1180,2015-10-01,16.6433,16.6433,15.8087,15.9667,56504925 +1181,2015-10-02,16.038,16.7333,15.5333,16.5667,54307740 +1182,2015-10-05,16.6673,16.7333,16.2753,16.354,48077100 +1183,2015-10-06,16.3327,16.3327,15.7053,15.95,65567505 +1184,2015-10-07,15.7947,15.8667,15.2747,15.46,89247075 +1185,2015-10-08,15.378,15.424,14.754,15,77791965 +1186,2015-10-09,14.7333,14.958,14.5333,14.6933,79845975 +1187,2015-10-12,14.8,14.9067,14.2793,14.3,49668135 +1188,2015-10-13,14.3067,14.8353,14.0753,14.6,67942260 +1189,2015-10-14,14.6173,14.7433,14.362,14.4933,39930165 +1190,2015-10-15,14.59,14.8627,14.2467,14.8627,36025155 +1191,2015-10-16,14.788,15.366,14.788,15.11,56215725 +1192,2015-10-19,15.2293,15.41,14.996,15.15,31590870 +1193,2015-10-20,15.1667,15.24,13.4667,14.1107,197281935 +1194,2015-10-21,14.2267,14.3207,13.92,14.0667,53924745 +1195,2015-10-22,14.134,14.3833,13.96,14.2,35633430 +1196,2015-10-23,14.4527,14.5333,13.846,14,54594090 +1197,2015-10-26,14.0327,14.4667,13.9267,14.38,42132645 +1198,2015-10-27,14.372,14.4733,13.834,14.0233,45352560 +1199,2015-10-28,14.0473,14.23,13.8867,14.1867,34321920 +1200,2015-10-29,14.1333,14.25,13.94,14.0007,23203560 +1201,2015-10-30,14.0933,14.1087,13.5927,13.7927,55364160 +1202,2015-11-02,13.7933,14.3867,13.7933,14.2633,49048695 +1203,2015-11-03,14.26,15.5967,13.5,15.1713,81725865 +1204,2015-11-04,14.998,15.516,14.8,15.4233,164936790 +1205,2015-11-05,15.442,15.6393,15.2793,15.46,57396345 +1206,2015-11-06,15.4333,15.5573,15.3,15.5,62338770 +1207,2015-11-09,15.4507,15.5327,14.954,14.9993,49130655 +1208,2015-11-10,14.99,15,14.4053,14.44,58650945 +1209,2015-11-11,14.5527,14.632,14.242,14.6267,42948015 +1210,2015-11-12,14.5953,14.6,14.16,14.1667,37479450 +1211,2015-11-13,14.16,14.22,13.6947,13.702,42982740 +1212,2015-11-16,13.7667,14.332,13.7,14.28,37396095 +1213,2015-11-17,14.3447,14.4,14.0933,14.2667,27685005 +1214,2015-11-18,14.3267,14.7587,14.168,14.68,36768795 +1215,2015-11-19,14.864,15.0793,14.6867,14.74,30967155 +1216,2015-11-20,14.7867,15,14.2387,14.664,57603405 +1217,2015-11-23,14.6673,14.6673,14.3113,14.4933,31581555 +1218,2015-11-24,14.4,14.7333,14.3333,14.4733,31788765 +1219,2015-11-25,14.5667,15.3887,14.5667,15.3533,51472185 +1220,2015-11-27,15.3913,15.4833,15.134,15.3353,24905370 +1221,2015-11-30,15.4367,15.6187,15.272,15.3667,33631095 +1222,2015-12-01,15.404,15.8667,15.32,15.82,47844060 +1223,2015-12-02,15.81,15.9067,15.4153,15.532,37548885 +1224,2015-12-03,15.56,15.83,15.3333,15.5667,37645980 +1225,2015-12-04,15.6,15.63,15.1773,15.3933,32882220 +1226,2015-12-07,15.3587,15.7087,15.0767,15.3933,40632900 +1227,2015-12-08,15.2667,15.2667,14.9467,15.18,34195545 +1228,2015-12-09,15.0667,15.1667,14.7147,14.9873,39684090 +1229,2015-12-10,14.9993,15.2327,14.9093,15.1653,26159520 +1230,2015-12-11,15.0053,15.05,14.36,14.432,42714765 +1231,2015-12-14,14.6587,14.728,14.3247,14.572,35973795 +1232,2015-12-15,14.7333,14.8287,14.5333,14.7267,28405860 +1233,2015-12-16,14.8333,15.6587,14.7153,15.5833,64146990 +1234,2015-12-17,15.69,15.8507,15.3207,15.4733,40449015 +1235,2015-12-18,15.4,15.7267,15.286,15.3833,38668740 +1236,2015-12-21,15.4667,15.722,15.4,15.5333,24367620 +1237,2015-12-22,15.5333,15.77,15.3087,15.3467,25559175 +1238,2015-12-23,15.4667,15.5633,15.2087,15.3133,18879060 +1239,2015-12-24,15.3133,15.4587,15.2187,15.3713,8807865 +1240,2015-12-28,15.3573,15.4653,15.036,15.2667,22891215 +1241,2015-12-29,15.3167,15.86,15.3027,15.86,31348185 +1242,2015-12-30,15.7387,16.2427,15.7113,15.9133,47373570 +1243,2015-12-31,16,16.23,15.8913,16,35687385 +1244,2016-01-04,15.5733,15.9667,14.6,14.9727,84687525 +1245,2016-01-05,14.934,15.126,14.6667,14.85,39873360 +1246,2016-01-06,14.6047,14.7167,14.3987,14.7167,45644085 +1247,2016-01-07,14.5333,14.5627,14.144,14.334,44442075 +1248,2016-01-08,14.4133,14.696,14.03,14.0753,42351450 +1249,2016-01-11,14.0633,14.2967,13.5333,13.8287,51419670 +1250,2016-01-12,13.9893,14.2493,13.6873,14.066,37346910 +1251,2016-01-13,14.17,14.1767,13.3333,13.4,45447780 +1252,2016-01-14,13.3667,14,12.892,13.8033,78481125 +1253,2016-01-15,13.4667,13.6793,13.1333,13.65,65273250 +1254,2016-01-19,13.992,14.0313,13.3853,13.6647,49873515 +1255,2016-01-20,13.5,13.5,12.75,13.346,71760615 +1256,2016-01-21,13.2,13.5487,13.0013,13.2733,39395805 +1257,2016-01-22,13.56,13.7667,13.2687,13.5033,36423510 +1258,2016-01-25,13.5033,13.5713,13.034,13.0667,32746890 +1259,2016-01-26,13.0767,13.2187,12.592,12.79,61887765 +1260,2016-01-27,12.8007,12.884,12.3847,12.6033,43610685 +1261,2016-01-28,12.6333,12.7933,12.1607,12.4327,58177335 +1262,2016-01-29,12.5853,12.916,12.5193,12.7787,36289005 +1263,2016-02-01,12.7167,13.3013,12.1833,13.088,67881600 +1264,2016-02-02,13.09,13.09,12.0153,12.18,72660375 +1265,2016-02-03,12.2467,12.3267,11.3453,11.572,102199185 +1266,2016-02-04,11.6373,11.732,11.1327,11.37,55556535 +1267,2016-02-05,11.4867,11.5627,10.516,10.8333,121217820 +1268,2016-02-08,10.6,10.6,9.7333,9.75,117036630 +1269,2016-02-09,9.798,10.6527,9.34,9.6667,111349140 +1270,2016-02-10,9.7533,10.9933,9,10.502,114878790 +1271,2016-02-11,10.2,10.884,9.6013,10.1333,187276440 +1272,2016-02-12,10.1333,10.4673,9.58,9.9967,95316150 +1273,2016-02-16,10.0993,10.8633,10.0993,10.3307,72728055 +1274,2016-02-17,10.4987,11.3447,10.4453,11.3447,76193205 +1275,2016-02-18,11.3533,11.5833,10.9847,11.1333,49621590 +1276,2016-02-19,11.0333,11.166,10.8333,11.1233,36965385 +1277,2016-02-22,11.3,11.9273,11.3,11.7967,66003810 +1278,2016-02-23,11.648,12.1153,11.5787,11.7667,69213390 +1279,2016-02-24,11.6733,12,11.1893,11.9993,69879090 +1280,2016-02-25,11.8887,12.568,11.68,12.4907,67942905 +1281,2016-02-26,12.6067,12.8,12.3333,12.6507,78149805 +1282,2016-02-29,12.6,13.09,12.6,12.7533,115657890 +1283,2016-03-01,12.9527,13.0633,12.18,12.3167,87616590 +1284,2016-03-02,12.3953,12.568,12.1,12.458,62262495 +1285,2016-03-03,12.556,13.1613,12.2813,13.0267,63760695 +1286,2016-03-04,13.04,13.602,13.04,13.3833,86046540 +1287,2016-03-07,13.3333,13.98,13.16,13.7,67046235 +1288,2016-03-08,13.6667,13.8333,13.48,13.5233,53949945 +1289,2016-03-09,13.5667,13.9587,13.5193,13.93,41877810 +1290,2016-03-10,13.93,14.2333,13.378,13.6787,67059180 +1291,2016-03-11,13.918,13.9613,13.6887,13.8347,42624135 +1292,2016-03-14,13.88,14.448,13.88,14.3667,50652270 +1293,2016-03-15,14.2667,14.598,14.1,14.5333,80336310 +1294,2016-03-16,14.556,14.8387,14.4533,14.8113,45207405 +1295,2016-03-17,14.8,15.2333,14.6267,15.21,48334365 +1296,2016-03-18,15.1333,15.632,15.1067,15.4733,59588040 +1297,2016-03-21,15.5333,15.992,15.516,15.9,66283815 +1298,2016-03-22,15.9,15.9327,15.5033,15.5333,53471670 +1299,2016-03-23,15.6333,15.68,14.6867,14.6893,62026500 +1300,2016-03-24,14.5127,15.2593,14.2987,15.22,64368510 +1301,2016-03-28,15.226,15.654,15,15.3333,49788900 +1302,2016-03-29,15.4333,15.492,15.022,15.3533,51507480 +1303,2016-03-30,15.46,15.7,15.1,15.1,52204845 +1304,2016-03-31,15.1333,15.828,15.0007,15.54,103025805 +1305,2016-04-01,15.6667,16.7493,15.318,15.83,205378890 +1306,2016-04-04,16.3333,16.808,15.7133,15.76,169088775 +1307,2016-04-05,15.8567,17.1667,15.7767,17.1667,127513170 +1308,2016-04-06,16.86,17.8493,16.8533,17.7533,143856135 +1309,2016-04-07,17.8667,17.956,16.9673,17.0647,111640635 +1310,2016-04-08,17.04,17.434,16.5347,16.6333,92146575 +1311,2016-04-11,16.7847,17.266,16.3533,16.62,119938500 +1312,2016-04-12,16.6333,16.8,16.242,16.49,73495020 +1313,2016-04-13,16.5667,17.0333,16.4887,16.9913,63754965 +1314,2016-04-14,16.8747,17.1227,16.7367,16.788,53539065 +1315,2016-04-15,16.8007,17.004,16.608,16.9267,47150220 +1316,2016-04-18,16.9,17.2207,16.7773,16.848,56465895 +1317,2016-04-19,17.0267,17.0393,16.0833,16.3333,80956815 +1318,2016-04-20,16.5193,16.9107,16.1,16.66,67998930 +1319,2016-04-21,16.6553,16.7313,16.4,16.4887,36160305 +1320,2016-04-22,16.5133,16.9333,16.3807,16.9233,50184240 +1321,2016-04-25,17.02,17.1587,16.7173,16.7667,46018590 +1322,2016-04-26,16.8007,17.0487,16.626,16.772,41643750 +1323,2016-04-27,16.83,17,16.6267,16.7853,41368650 +1324,2016-04-28,16.696,16.8953,16.496,16.5433,31875060 +1325,2016-04-29,16.5167,16.666,15.854,15.9533,67850040 +1326,2016-05-02,16.1167,16.2127,15.6547,16.12,48718935 +1327,2016-05-03,15.9907,16.12,15.4207,15.4387,54099555 +1328,2016-05-04,15.3467,16.1753,14.6933,15.2333,101952825 +1329,2016-05-05,15.3647,15.6,13.986,14.0347,140309865 +1330,2016-05-06,14.0667,14.4247,13.874,14.3267,74756025 +1331,2016-05-09,14.4333,14.534,13.7867,13.8167,62450460 +1332,2016-05-10,14.026,14.0413,13.6667,13.88,51794940 +1333,2016-05-11,13.874,14.3653,13.7367,13.894,61181340 +1334,2016-05-12,13.9933,14.1533,13.5767,13.7767,46360335 +1335,2016-05-13,13.7793,14.08,13.7473,13.82,35990505 +1336,2016-05-16,13.9327,14.21,13.8587,13.888,37083990 +1337,2016-05-17,13.9327,13.988,13.6013,13.6867,34568325 +1338,2016-05-18,13.902,14.354,13.2007,14.0333,69813285 +1339,2016-05-19,14.0467,14.7333,13.82,14.574,86109435 +1340,2016-05-20,14.7313,14.7313,14.194,14.6547,113611050 +1341,2016-05-23,14.726,14.84,14.38,14.38,66618810 +1342,2016-05-24,14.4993,14.5827,14.3453,14.53,37793115 +1343,2016-05-25,14.6327,14.7573,14.41,14.5933,37445070 +1344,2016-05-26,14.666,15.0327,14.6033,15.0327,53304360 +1345,2016-05-27,15.0667,15.0667,14.7167,14.8433,47011290 +1346,2016-05-31,14.926,14.9833,14.7667,14.8733,31549200 +1347,2016-06-01,14.8267,14.8267,14.4593,14.6,38188845 +1348,2016-06-02,14.632,14.7327,14.474,14.702,24582015 +1349,2016-06-03,14.7,14.796,14.534,14.5673,28329450 +1350,2016-06-06,14.6047,14.7267,14.3633,14.7053,28419060 +1351,2016-06-07,14.748,15.6293,14.7327,15.5127,80287470 +1352,2016-06-08,15.5333,16.0567,15.4567,15.7233,76060455 +1353,2016-06-09,15.6467,15.6887,15.07,15.09,58262070 +1354,2016-06-10,14.8733,15.2667,14.4787,14.674,78597060 +1355,2016-06-13,14.5533,15.0513,14.4653,14.5133,53577120 +1356,2016-06-14,14.582,14.8133,14.1687,14.28,44983245 +1357,2016-06-15,14.4333,14.7933,14.342,14.532,36963330 +1358,2016-06-16,14.51,14.658,14.2333,14.5333,31423200 +1359,2016-06-17,14.5353,14.666,14.3,14.33,38441865 +1360,2016-06-20,14.5,14.9167,14.5,14.696,44990895 +1361,2016-06-21,14.7667,14.838,12.608,12.8533,41360595 +1362,2016-06-22,14,14,12.8807,13.1867,288062460 +1363,2016-06-23,13.196,13.196,12.8087,13,122422515 +1364,2016-06-24,12.96,13.008,12.476,12.7333,83003595 +1365,2016-06-27,12.9067,13.254,12.5247,13.22,90248895 +1366,2016-06-28,13.27,13.6033,13.2633,13.4527,69636630 +1367,2016-06-29,13.5467,14.1187,13.5333,14.0167,70308465 +1368,2016-06-30,14.0827,14.2373,13.668,13.7333,56418435 +1369,2016-07-01,13.6393,14.5493,13.5967,14.4133,63605955 +1370,2016-07-05,14.0367,14.3033,13.7,14.0933,64103865 +1371,2016-07-06,13.9587,14.3487,13.9327,14.2433,56001630 +1372,2016-07-07,14.2867,14.5413,14.1667,14.4,41651820 +1373,2016-07-08,14.3667,14.654,14.3,14.4,45595800 +1374,2016-07-11,14.5633,15.1187,14.5633,14.82,66368370 +1375,2016-07-12,14.792,15.1667,14.7667,14.9667,56701455 +1376,2016-07-13,15,15.0667,14.686,14.8667,44640195 +1377,2016-07-14,14.9,15.0667,14.7367,14.7687,32683545 +1378,2016-07-15,14.8333,14.85,14.6067,14.6067,28054815 +1379,2016-07-18,14.6667,15.1393,14.5533,15.0433,43574475 +1380,2016-07-19,15.034,15.2733,14.9833,15.08,36414315 +1381,2016-07-20,15.1347,15.32,15,15.28,31636800 +1382,2016-07-21,15.342,15.3667,14.6067,14.6667,55197015 +1383,2016-07-22,14.714,14.9667,14.592,14.7933,32939685 +1384,2016-07-25,14.8333,15.426,14.758,15.3333,57810465 +1385,2016-07-26,15.4,15.4,15.02,15.2833,39602580 +1386,2016-07-27,15.31,15.5573,15.128,15.22,35585460 +1387,2016-07-28,15.2607,15.3853,15.1067,15.3853,29429970 +1388,2016-07-29,15.3507,15.6853,15.3333,15.6147,38264985 +1389,2016-08-01,15.6907,15.7753,15.276,15.4113,51807975 +1390,2016-08-02,15.3453,15.3453,14.76,15.1333,48089565 +1391,2016-08-03,15.1167,15.5333,14.4333,14.94,49846905 +1392,2016-08-04,15.2,15.3907,14.8033,15.3367,52533225 +1393,2016-08-05,15.3187,15.4667,15.15,15.1653,38675430 +1394,2016-08-08,15.1653,15.3067,15.0667,15.1,27615555 +1395,2016-08-09,15.02,15.436,15,15.2333,26310885 +1396,2016-08-10,15.2953,15.3247,14.9747,15.0667,28483890 +1397,2016-08-11,15.0727,15.1713,14.894,15,24076710 +1398,2016-08-12,14.9993,15.11,14.936,15.0393,20300850 +1399,2016-08-15,15.0667,15.3,14.9867,15.0007,25273980 +1400,2016-08-16,14.9813,15.146,14.8887,14.9067,26379855 +1401,2016-08-17,14.7053,14.9887,14.7053,14.892,21790455 +1402,2016-08-18,14.8827,15.044,14.8193,14.8667,20870070 +1403,2016-08-19,14.8667,15.0133,14.8353,15,19653315 +1404,2016-08-22,15.0067,15.0527,14.8453,14.87,26019900 +1405,2016-08-23,14.9067,15.2327,14.8533,15.1087,63281610 +1406,2016-08-24,15.1067,15.1433,14.8147,14.8147,30888090 +1407,2016-08-25,14.802,14.9327,14.7167,14.7327,21926385 +1408,2016-08-26,14.7567,14.8633,14.588,14.634,28345545 +1409,2016-08-29,14.6,14.6933,14.3333,14.3413,41806380 +1410,2016-08-30,14.3667,14.4073,14.0347,14.064,39825960 +1411,2016-08-31,14.066,14.1733,13.91,14.1,40418205 +1412,2016-09-01,14.1647,14.206,13.35,13.4167,102308160 +1413,2016-09-02,13.5233,13.5467,13.08,13.22,74876685 +1414,2016-09-06,13.3333,13.5667,13.2513,13.5493,54042450 +1415,2016-09-07,13.5627,13.7667,13.3807,13.4633,44694975 +1416,2016-09-08,13.4953,13.4993,13.0907,13.1767,41787750 +1417,2016-09-09,13.144,13.3487,12.9133,12.95,48325905 +1418,2016-09-12,12.8667,13.4247,12.812,13.2567,45839700 +1419,2016-09-13,13.2113,13.25,12.8967,12.9807,44783100 +1420,2016-09-14,13.0233,13.1953,12.99,13.0667,28667115 +1421,2016-09-15,13.1247,13.5013,13.0333,13.3507,36054000 +1422,2016-09-16,13.354,13.7167,13.258,13.694,38842110 +1423,2016-09-19,13.7007,13.962,13.6667,13.766,28640355 +1424,2016-09-20,13.756,13.85,13.594,13.6233,24932340 +1425,2016-09-21,13.6667,13.8,13.4373,13.712,31800480 +1426,2016-09-22,13.7093,13.8187,13.5333,13.6733,29451975 +1427,2016-09-23,13.716,14.012,13.6667,13.8667,33538245 +1428,2016-09-26,13.7833,14.0667,13.7047,13.93,28243755 +1429,2016-09-27,13.9533,14.0133,13.64,13.7253,39862860 +1430,2016-09-28,13.7553,13.8833,13.6333,13.76,27330960 +1431,2016-09-29,13.7353,13.822,13.35,13.3767,35370465 +1432,2016-09-30,13.38,13.6653,13.3033,13.6,33940980 +1433,2016-10-03,13.7933,14.378,13.602,14.2333,80238360 +1434,2016-10-04,14.232,14.3,13.9213,14.1333,45776940 +1435,2016-10-05,14.0927,14.21,13.8747,13.94,23797215 +1436,2016-10-06,13.9107,13.9107,13.3473,13.3773,61862850 +1437,2016-10-07,13.3973,13.4633,13.0533,13.1133,44352930 +1438,2016-10-10,13.4067,13.6093,13.1073,13.4133,43733445 +1439,2016-10-11,13.4133,13.48,13.2207,13.35,30339060 +1440,2016-10-12,13.3367,13.592,13.32,13.426,24088650 +1441,2016-10-13,13.334,13.3933,13.1367,13.3653,28215435 +1442,2016-10-14,13.4013,13.4333,13.0867,13.1327,57088020 +1443,2016-10-17,13.114,13.2307,12.8,12.9833,59920515 +1444,2016-10-18,13.0513,13.298,12.884,13.2867,77545620 +1445,2016-10-19,13.2867,13.7773,13.178,13.6333,94281555 +1446,2016-10-20,13.4667,13.5493,13.1367,13.2367,65298930 +1447,2016-10-21,13.2487,13.438,13.1493,13.3507,37628655 +1448,2016-10-24,13.3667,13.5967,13.35,13.4673,35458005 +1449,2016-10-25,13.522,13.646,13.4047,13.42,28966155 +1450,2016-10-26,13.4707,14.432,13.3333,14.0667,75116040 +1451,2016-10-27,14.0367,14.2467,13.4433,13.5533,175683330 +1452,2016-10-28,13.6007,13.688,13.322,13.366,57461385 +1453,2016-10-31,13.3333,13.556,13.054,13.1667,56721510 +1454,2016-11-01,13.192,13.2667,12.5007,12.5893,89997060 +1455,2016-11-02,12.6487,12.8467,12.4147,12.4827,54515745 +1456,2016-11-03,12.5307,12.7647,12.4693,12.5,32900445 +1457,2016-11-04,12.4747,12.8973,12.3973,12.7467,65781930 +1458,2016-11-07,12.93,12.996,12.67,12.89,50097405 +1459,2016-11-08,12.8893,13.166,12.7507,13.0333,42242490 +1460,2016-11-09,12.232,12.8,12.1333,12.678,103742010 +1461,2016-11-10,12.8,12.8733,12.028,12.3667,84858330 +1462,2016-11-11,12.306,12.592,12.2,12.57,51611205 +1463,2016-11-14,12.648,12.648,11.8793,12.1233,85608450 +1464,2016-11-15,12.2167,12.4287,12.1253,12.2787,50682225 +1465,2016-11-16,12.2433,12.3153,12.0807,12.2167,41321985 +1466,2016-11-17,12.2773,12.9,12.1407,12.6467,57600180 +1467,2016-11-18,12.634,12.8667,12.3273,12.3273,67142955 +1468,2016-11-21,12.3467,12.5927,12.294,12.312,57124485 +1469,2016-11-22,12.3853,12.7647,12.2473,12.7633,73593240 +1470,2016-11-23,12.74,13.0433,12.6,12.8667,62876265 +1471,2016-11-25,12.9,13.1493,12.9,13.11,30619665 +1472,2016-11-28,13.0233,13.29,12.97,13.0847,58714410 +1473,2016-11-29,13.068,13.1333,12.6333,12.6347,57520620 +1474,2016-11-30,12.7273,12.8,12.5,12.6233,45849390 +1475,2016-12-01,12.5927,12.6307,12.0667,12.1533,65228070 +1476,2016-12-02,12.1407,12.3253,12,12.1,51604950 +1477,2016-12-05,12.1673,12.5927,12.1667,12.4667,50948565 +1478,2016-12-06,12.4993,12.5067,12.1787,12.3833,44166465 +1479,2016-12-07,12.43,12.8933,12.3333,12.8167,71439045 +1480,2016-12-08,12.8427,12.8667,12.636,12.8,40960065 +1481,2016-12-09,12.7807,12.9227,12.6833,12.7833,33890505 +1482,2016-12-12,12.7867,12.9613,12.686,12.8287,31229640 +1483,2016-12-13,12.87,13.4187,12.8667,13.2133,89130030 +1484,2016-12-14,13.23,13.5333,13.1173,13.3,54654495 +1485,2016-12-15,13.2493,13.3827,13.1593,13.1653,41365305 +1486,2016-12-16,13.2027,13.506,13.1733,13.4933,49030395 +1487,2016-12-19,13.51,13.63,13.3227,13.4967,45378420 +1488,2016-12-20,13.5593,13.9333,13.5,13.9193,62280810 +1489,2016-12-21,13.8893,14.1487,13.8273,13.852,69526095 +1490,2016-12-22,13.8093,13.9993,13.7667,13.91,40609665 +1491,2016-12-23,13.8667,14.2667,13.8473,14.2533,57488535 +1492,2016-12-27,14.2033,14.8167,14.1867,14.6533,76603605 +1493,2016-12-28,14.6667,14.92,14.48,14.616,48715005 +1494,2016-12-29,14.65,14.6667,14.2747,14.3107,53864715 +1495,2016-12-30,14.338,14.5,14.112,14.236,61296165 +1496,2017-01-03,14.2507,14.6887,13.8,14.1893,76751040 +1497,2017-01-04,14.2,15.2,14.0747,15.1067,148240920 +1498,2017-01-05,14.9253,15.1653,14.7967,15.13,48295200 +1499,2017-01-06,15.1167,15.354,15.03,15.264,72480600 +1500,2017-01-09,15.2667,15.4613,15.2,15.4187,51153120 +1501,2017-01-10,15.4007,15.4667,15.126,15.3,47673600 +1502,2017-01-11,15.2667,15.334,15.112,15.31,45848955 +1503,2017-01-12,15.2687,15.38,15.0387,15.2933,47768535 +1504,2017-01-13,15.3333,15.8567,15.2733,15.85,80412510 +1505,2017-01-17,15.7607,15.9973,15.6247,15.7053,59745210 +1506,2017-01-18,15.7027,15.9807,15.7027,15.9147,48709860 +1507,2017-01-19,16.4073,16.5787,16.05,16.1767,101214150 +1508,2017-01-20,16.3167,16.4,16.2007,16.32,49923165 +1509,2017-01-23,16.31,16.726,16.2733,16.598,78557610 +1510,2017-01-24,16.5553,16.9993,16.5553,16.9993,62280870 +1511,2017-01-25,17.0667,17.2307,16.7867,16.96,65941140 +1512,2017-01-26,16.9887,17.0493,16.7167,16.742,39469215 +1513,2017-01-27,16.798,16.9853,16.568,16.9267,39775995 +1514,2017-01-30,16.8633,17.0193,16.4733,16.688,48218610 +1515,2017-01-31,16.67,17.0593,16.5133,16.8133,52682265 +1516,2017-02-01,16.8767,16.9327,16.6033,16.6167,51352470 +1517,2017-02-02,16.5333,16.828,16.4993,16.684,31979490 +1518,2017-02-03,16.7533,16.8527,16.6453,16.764,24938490 +1519,2017-02-06,16.7907,17.2027,16.6807,17.2027,45616860 +1520,2017-02-07,17.1667,17.3333,17.0947,17.1653,52628640 +1521,2017-02-08,17.1833,17.666,17.08,17.6493,50357010 +1522,2017-02-09,17.638,18.3333,17.472,17.95,101696130 +1523,2017-02-10,18,18.0887,17.7407,17.934,46664505 +1524,2017-02-13,18.0067,18.7333,17.9807,18.73,91768200 +1525,2017-02-14,18.7333,19.1593,18.574,18.732,94881045 +1526,2017-02-15,18.6747,18.816,18.4293,18.6467,63557535 +1527,2017-02-16,18.5707,18.6667,17.734,17.8333,89172345 +1528,2017-02-17,17.5933,18.1927,17.51,18.124,81886155 +1529,2017-02-21,18.22,18.76,18.1487,18.6,71768040 +1530,2017-02-22,18.5333,18.8967,18.1733,18.5113,113085195 +1531,2017-02-23,18.6067,18.6467,17,17,193472580 +1532,2017-02-24,17,17.2167,16.68,17.1133,107111355 +1533,2017-02-27,17.4007,17.4333,16.134,16.3867,150069720 +1534,2017-02-28,16.2933,16.7333,16.26,16.692,78670740 +1535,2017-03-01,16.7927,17,16.6073,16.6553,61044060 +1536,2017-03-02,16.7,16.8853,16.5513,16.6707,44183175 +1537,2017-03-03,16.62,16.8,16.6,16.75,38606160 +1538,2017-03-06,16.7033,16.78,16.3593,16.7567,43940415 +1539,2017-03-07,16.726,16.926,16.4807,16.5333,43656195 +1540,2017-03-08,16.5793,16.6713,16.3547,16.4593,47784270 +1541,2017-03-09,16.4833,16.5773,16.2,16.3533,50291415 +1542,2017-03-10,16.4,16.4933,16.2,16.2473,40420680 +1543,2017-03-13,16.1907,16.506,16.1853,16.4533,38125545 +1544,2017-03-14,16.4373,17.2867,16.38,17.2667,100832040 +1545,2017-03-15,17.2533,17.6467,16.7073,17.402,69533460 +1546,2017-03-16,17.4067,17.7167,17.2707,17.4667,90819975 +1547,2017-03-17,17.48,17.6887,17.4053,17.41,80565870 +1548,2017-03-20,17.4167,17.6367,17.2547,17.4633,46284510 +1549,2017-03-21,17.4867,17.6533,16.6827,16.7253,90363240 +1550,2017-03-22,16.6667,17.0327,16.6333,16.9853,50458350 +1551,2017-03-23,17.0367,17.1787,16.8867,16.972,42898545 +1552,2017-03-24,17.0067,17.5927,17.0007,17.5913,74085210 +1553,2017-03-27,17.5333,18.1267,17.3167,18.1,80728845 +1554,2017-03-28,18.0667,18.712,17.8667,18.5833,102388365 +1555,2017-03-29,18.5947,18.64,18.3693,18.4833,46356210 +1556,2017-03-30,18.484,18.8,18.4807,18.5333,53993670 +1557,2017-03-31,18.512,18.6593,18.4207,18.542,41612610 +1558,2017-04-03,18.75,19.9333,18.5533,19.9013,180777570 +1559,2017-04-04,19.9333,20.3207,19.6353,20.1333,129370695 +1560,2017-04-05,20.2467,20.3253,19.6133,19.6833,99987900 +1561,2017-04-06,19.5933,20.1293,19.534,19.9247,71159910 +1562,2017-04-07,19.9233,20.1967,19.674,20.1753,57513600 +1563,2017-04-10,20.3067,20.9153,20.3067,20.8147,97980315 +1564,2017-04-11,20.8907,20.902,20.3667,20.5533,72841680 +1565,2017-04-12,20.6,20.6433,19.744,19.8187,76993785 +1566,2017-04-13,19.6587,20.4927,19.5667,20.2713,124106325 +1567,2017-04-17,20.2833,20.2833,19.912,20.008,53491485 +1568,2017-04-18,20.0327,20.056,19.8393,20,38393445 +1569,2017-04-19,20.0133,20.4413,20.0133,20.3373,49679670 +1570,2017-04-20,20.4,20.61,20.0153,20.15,78870705 +1571,2017-04-21,20.1867,20.4593,20.028,20.4447,57667530 +1572,2017-04-24,20.6667,20.7033,20.4013,20.5153,65769240 +1573,2017-04-25,20.5667,20.932,20.3907,20.9167,85255320 +1574,2017-04-26,20.876,20.9667,20.6,20.6673,54209820 +1575,2017-04-27,20.66,20.8727,20.5,20.6067,44895480 +1576,2017-04-28,20.6527,21.0073,20.5333,20.9733,58899975 +1577,2017-05-01,20.9993,21.8167,20.938,21.5967,108803550 +1578,2017-05-02,21.492,21.844,21.1,21.1667,67132200 +1579,2017-05-03,21.2167,21.4353,20.0733,20.2467,88490685 +1580,2017-05-04,20.34,20.56,19.384,19.7253,178937325 +1581,2017-05-05,19.7907,20.6,19.7373,20.6,103262310 +1582,2017-05-08,20.6433,20.9193,20.388,20.5053,91822080 +1583,2017-05-09,20.55,21.466,20.55,21.3467,124801560 +1584,2017-05-10,21.6,21.7067,21.208,21.6807,72771405 +1585,2017-05-11,21.7533,21.7533,21.23,21.5327,60381360 +1586,2017-05-12,21.54,21.8,21.4353,21.6653,52982295 +1587,2017-05-15,21.2587,21.3467,20.8353,21.06,98139675 +1588,2017-05-16,21.1133,21.3373,21.0027,21.0333,53030295 +1589,2017-05-17,21.0267,21.0267,20.352,20.4133,84943980 +1590,2017-05-18,20.396,20.9293,20.1667,20.8233,73016490 +1591,2017-05-19,20.8733,21.1167,20.6587,20.6913,59414115 +1592,2017-05-22,20.71,20.958,20.4533,20.6473,53613555 +1593,2017-05-23,20.732,20.732,20.232,20.262,53430645 +1594,2017-08-02,21.4,23.736,20.748,23.334,158508465 +1595,2017-08-03,23.114,23.34,22.8667,23.18,169206135 +1596,2017-08-04,23.1873,23.84,22.8867,23.8187,118611315 +1597,2017-08-07,24,24,23.5167,23.6667,76922280 +1598,2017-08-08,23.6333,24.572,23.6207,24.2547,92226420 +1599,2017-08-09,24.208,24.6667,23.8747,24.2773,86519625 +1600,2017-08-10,24.22,24.444,23.5533,23.5667,88535805 +1601,2017-08-11,23.5447,24.084,23.3333,23.8667,54039555 +1602,2017-08-14,24.0667,24.5107,24.0667,24.28,55720770 +1603,2017-08-15,24.3433,24.38,23.958,24.1307,36768285 +1604,2017-08-16,24.1533,24.4333,24.068,24.2067,39519210 +1605,2017-08-17,24.258,24.26,23.4267,23.4333,59729325 +1606,2017-08-18,23.3333,23.6167,23.0007,23.0707,64878945 +1607,2017-08-21,23.144,23.1867,22.1233,22.4547,80873040 +1608,2017-08-22,22.7793,22.816,22.4913,22.7707,53835240 +1609,2017-08-23,22.72,23.566,22.5413,23.46,59650080 +1610,2017-08-24,23.5327,23.7773,23.316,23.5467,53365110 +1611,2017-08-25,23.6,23.7127,23.1533,23.1813,42063270 +1612,2017-08-28,23.1707,23.2267,22.648,22.8873,43703055 +1613,2017-08-29,22.7333,23.27,22.5627,23.1987,47693040 +1614,2017-08-30,23.2707,23.5653,23.1093,23.5653,39211260 +1615,2017-08-31,23.5733,23.896,23.5213,23.68,47533125 +1616,2017-09-01,23.7333,23.8393,23.5793,23.6673,36370140 +1617,2017-09-05,23.6433,23.6993,23.0593,23.3267,46009875 +1618,2017-09-06,23.3707,23.5,22.7707,22.9773,49117995 +1619,2017-09-07,23.0727,23.4987,22.8967,23.3787,50711130 +1620,2017-09-08,23.3093,23.3187,22.82,22.8953,38831370 +1621,2017-09-11,23.2,24.266,23.2,24.234,93792450 +1622,2017-09-12,24.2733,24.584,24.0267,24.1667,71484885 +1623,2017-09-13,24.19,24.538,23.9727,24.4,51254190 +1624,2017-09-14,24.3333,25.1973,24.1753,24.8987,88268760 +1625,2017-09-15,24.9793,25.36,24.8467,25.3553,65391495 +1626,2017-09-18,25.4,25.974,25.1787,25.6533,88693770 +1627,2017-09-19,25.48,25.4927,24.9047,24.9547,77656125 +1628,2017-09-20,25.0133,25.2167,24.738,24.944,60187995 +1629,2017-09-21,24.928,25.122,24.3007,24.432,58301040 +1630,2017-09-22,24.4,24.66,23.37,23.38,100120800 +1631,2017-09-25,23.378,23.8313,22.8587,23.002,95209215 +1632,2017-09-26,23.08,23.416,22.7267,23.0267,89596305 +1633,2017-09-27,23.2633,23.4327,22.7,22.74,73275165 +1634,2017-09-28,22.7333,22.85,22.36,22.7133,63105405 +1635,2017-09-29,22.768,22.9787,22.5733,22.72,62996130 +1636,2017-10-02,22.872,23.2067,22.34,22.4,63673905 +1637,2017-10-03,22.4667,23.476,22.0853,23.422,127915005 +1638,2017-10-04,23.4,23.908,23.282,23.7253,102388050 +1639,2017-10-05,23.6327,23.8293,23.4233,23.6967,49240515 +1640,2017-10-06,23.6973,24.0067,23.4833,23.5867,52458270 +1641,2017-10-09,23.5587,23.6,22.8407,23.0467,91929060 +1642,2017-10-10,23.086,23.744,23.0353,23.7167,85714425 +1643,2017-10-11,23.7,23.84,23.41,23.6333,54369930 +1644,2017-10-12,23.5793,23.9853,23.4667,23.6633,49478250 +1645,2017-10-13,23.7033,23.8993,23.5787,23.7467,42626325 +1646,2017-10-16,23.5833,23.6667,23.144,23.3833,63696315 +1647,2017-10-17,23.4167,23.748,23.3333,23.69,39478785 +1648,2017-10-18,23.6267,24.2,23.6087,23.9767,58906215 +1649,2017-10-19,23.8,23.8533,23.2133,23.416,60596670 +1650,2017-10-20,23.45,23.6367,22.956,22.9933,58987380 +1651,2017-10-23,23.3133,23.4833,22.4167,22.534,69079140 +1652,2017-10-24,22.4667,22.8533,22.4107,22.5,54037110 +1653,2017-10-25,22.5013,22.53,21.5707,21.75,84060840 +1654,2017-10-26,22.1,22.1,21.5467,21.886,59895495 +1655,2017-10-27,21.6667,21.8893,21.1107,21.3667,82456560 +1656,2017-10-30,21.4073,21.5853,21.15,21.2733,50183595 +1657,2017-10-31,21.3667,22.2,21.3453,22.2,67143015 +1658,2017-11-01,22.2633,22.2667,20.14,20.3267,98873415 +1659,2017-11-02,20.3,21.4053,19.5087,19.9627,239871705 +1660,2017-11-03,19.8573,20.434,19.6753,20.4133,106874280 +1661,2017-11-06,20.4533,20.626,19.934,20.1333,75212505 +1662,2017-11-07,20.1667,20.4333,19.634,20.378,64488030 +1663,2017-11-08,20.334,20.4593,20.0867,20.31,58790550 +1664,2017-11-09,20.2873,20.326,19.7533,20.14,64908075 +1665,2017-11-10,20.1227,20.5573,20.1227,20.1867,55910415 +1666,2017-11-13,20.2667,21.12,19.9067,21.0533,92643630 +1667,2017-11-14,21.08,21.0933,20.46,20.5933,69989505 +1668,2017-11-15,20.548,20.8327,20.1,20.78,74143695 +1669,2017-11-16,20.8833,21.2093,20.7533,20.8373,70739175 +1670,2017-11-17,21.1,21.8333,20.8767,21.0167,170145555 +1671,2017-11-20,21.0333,21.0333,20.3167,20.5567,103487040 +1672,2017-11-21,20.6133,21.2153,20.534,21.1733,91762275 +1673,2017-11-22,21.2067,21.266,20.7893,20.812,62022240 +1674,2017-11-24,20.9,21.094,20.7333,21.0013,41299770 +1675,2017-11-27,21.0367,21.1567,20.634,21.0747,55527705 +1676,2017-11-28,21.0747,21.3333,20.928,21.1227,59546580 +1677,2017-11-29,21.0907,21.2133,20.082,20.4633,101149335 +1678,2017-11-30,20.5033,20.7133,20.3027,20.5333,53600970 +1679,2017-12-01,20.4667,20.688,20.2,20.43,52615485 +1680,2017-12-04,20.52,20.618,20.0407,20.3107,73463115 +1681,2017-12-05,20.2667,20.5333,20.0667,20.22,56832825 +1682,2017-12-06,20.196,20.8927,20,20.8867,78075690 +1683,2017-12-07,20.9,21.2427,20.7333,20.75,56477175 +1684,2017-12-08,20.8,21.132,20.7507,21.0093,42380790 +1685,2017-12-11,20.9067,22.0067,20.8993,22.0067,99929295 +1686,2017-12-12,21.9933,22.7627,21.84,22.746,108343800 +1687,2017-12-13,22.6833,22.948,22.4333,22.6,74635725 +1688,2017-12-14,22.54,23.1627,22.46,22.5113,71098425 +1689,2017-12-15,22.5333,22.9333,22.384,22.8673,85651935 +1690,2017-12-18,22.9667,23.1333,22.5053,22.5933,67302900 +1691,2017-12-19,22.6333,22.7933,22.02,22.0773,79694640 +1692,2017-12-20,22.2067,22.34,21.6693,21.9767,72798450 +1693,2017-12-21,21.924,22.2493,21.814,22.11,54460410 +1694,2017-12-22,22.1333,22.1333,21.6547,21.6573,51109455 +1695,2017-12-26,21.6807,21.6807,21.1053,21.154,52441845 +1696,2017-12-27,21.1867,21.2,20.7167,20.7367,57229200 +1697,2017-12-28,20.7507,21.0547,20.636,21.032,53772345 +1698,2017-12-29,20.9667,21.1333,20.6667,20.7033,45971790 +1699,2018-01-02,20.8,21.474,20.7167,21.37,51439980 +1700,2018-01-03,21.4333,21.6833,20.6,20.7127,53039445 +1701,2018-01-04,20.6827,21.2367,20.34,21,119513085 +1702,2018-01-05,21.04,21.1493,20.8,21.1167,54689490 +1703,2018-01-08,21.1667,22.4907,21.026,22.4173,120026880 +1704,2018-01-09,22.4333,22.5867,21.8267,22.1627,85692555 +1705,2018-01-10,22.0667,22.4667,21.9333,22.3333,46271310 +1706,2018-01-11,22.33,22.9873,22.2173,22.54,80395725 +1707,2018-01-12,22.6627,22.694,22.2447,22.3533,57715995 +1708,2018-01-16,22.3533,23,22.32,22.6333,79779555 +1709,2018-01-17,22.6867,23.2667,22.65,23.1333,83660295 +1710,2018-01-18,23.2,23.4867,22.916,22.9767,67304595 +1711,2018-01-19,23.008,23.4,22.84,23.4,58015335 +1712,2018-01-22,23.3347,23.8553,23.2333,23.4647,76691625 +1713,2018-01-23,23.68,24.1867,23.4,23.5787,66095520 +1714,2018-01-24,23.56,23.7333,22.9013,23.17,62762115 +1715,2018-01-25,23.17,23.324,22.4267,22.7,82199130 +1716,2018-01-26,22.7993,22.9333,22.3807,22.8567,52383270 +1717,2018-01-29,22.76,23.39,22.552,23.2667,55837245 +1718,2018-01-30,23.2167,23.35,22.8113,23.052,51916335 +1719,2018-01-31,23.1653,23.746,23.0127,23.7,68225850 +1720,2018-02-01,23.72,23.9773,23.242,23.3667,48808785 +1721,2018-02-02,23.2467,23.4633,22.7007,22.84,42620370 +1722,2018-02-05,22.6,22.9647,22,22.0333,49498560 +1723,2018-02-06,22.0367,22.4147,21.542,22.3953,58819215 +1724,2018-02-07,22.3327,23.778,22.1893,22.9,81471840 +1725,2018-02-08,22.896,23.2413,20.8667,21.0667,122580555 +1726,2018-02-09,21.4,21.5933,19.6507,20.75,157762590 +1727,2018-02-12,21.066,21.2747,20.4167,21.0487,74060220 +1728,2018-02-13,21.128,21.7327,20.834,21.6333,53357370 +1729,2018-02-14,21.612,21.7447,21.2347,21.5333,46124280 +1730,2018-02-15,21.64,22.324,21.4933,22.3,68946270 +1731,2018-02-16,22.3333,22.8747,22.0867,22.3667,67143360 +1732,2018-02-20,22.3073,22.7227,22.1,22.34,47355345 +1733,2018-02-21,22.3407,22.6427,22.1767,22.1813,37654230 +1734,2018-02-22,22.138,23.1627,22.1333,23.1033,80854995 +1735,2018-02-23,23.2,23.666,23.14,23.4627,69096450 +1736,2018-02-26,23.62,23.9333,23.49,23.8667,52423515 +1737,2018-02-27,23.7893,23.9993,23.334,23.4067,55899915 +1738,2018-02-28,23.4,23.6827,22.8147,22.9467,74032890 +1739,2018-03-01,22.8867,23.2447,22.0047,22.1,82409115 +1740,2018-03-02,22.1333,22.348,21.5313,22.34,59703135 +1741,2018-03-05,22.2813,22.5167,21.9527,22.2633,44503275 +1742,2018-03-06,22.28,22.4247,21.5333,21.5333,51460950 +1743,2018-03-07,21.6133,22.1667,21.4493,22.0967,59825250 +1744,2018-03-08,22.1333,22.3,21.5267,21.7067,41452350 +1745,2018-03-09,21.7673,21.8993,21.4913,21.8053,63614580 +1746,2018-03-12,21.92,23.1473,21.7667,22.9967,100808145 +1747,2018-03-13,22.886,23.0987,22.4173,22.6833,71138010 +1748,2018-03-14,22.758,22.7813,21.5953,21.8333,94350375 +1749,2018-03-15,21.8333,22.19,21.4067,21.6653,76010130 +1750,2018-03-16,21.6973,21.8267,21.2713,21.4367,74099280 +1751,2018-03-19,21.3533,21.3833,20.6447,20.9107,89344530 +1752,2018-03-20,20.9733,21.0833,20.584,20.734,53260785 +1753,2018-03-21,20.73,21.496,20.6127,21.1333,71613060 +1754,2018-03-22,21.05,21.2547,20.5333,20.5333,52637865 +1755,2018-03-23,20.5393,20.8667,20.03,20.15,75360090 +1756,2018-03-26,20.268,20.6,19.424,20.3267,97042815 +1757,2018-03-27,20.3333,20.5,18.074,18.3,158944560 +1758,2018-03-28,18.264,18.5933,16.8067,16.9667,243796575 +1759,2018-03-29,17.0807,18.064,16.5473,17.3,177807180 +1760,2018-04-02,17,17.742,16.306,16.8067,195963285 +1761,2018-04-03,17.0133,18.2233,16.9067,17.88,230425485 +1762,2018-04-04,17.7733,19.2247,16.8,19.2133,246546495 +1763,2018-04-05,19.26,20.4173,19.1333,19.8667,226914720 +1764,2018-04-06,19.8667,20.6187,19.7,19.88,164396325 +1765,2018-04-09,19.9927,20.6333,19.2267,19.4267,124936080 +1766,2018-04-10,19.8933,20.4733,19.5787,20.22,133247355 +1767,2018-04-11,20.1833,20.5987,19.9333,20.1133,84874725 +1768,2018-04-12,19.9853,20.3333,19.5787,19.6667,86663775 +1769,2018-04-13,19.68,20.2653,19.68,19.98,87163425 +1770,2018-04-16,20,20.1,19.2547,19.3667,76768875 +1771,2018-04-17,19.2467,19.6933,18.834,19.584,84747060 +1772,2018-04-18,19.574,20.016,19.2107,19.6413,79921260 +1773,2018-04-19,19.5767,20.0673,19.2367,19.93,71637165 +1774,2018-04-20,19.8667,19.9987,19.3073,19.3167,67236780 +1775,2018-04-23,19.38,19.5533,18.822,18.9333,57966930 +1776,2018-04-24,19.1,19.1927,18.564,18.8667,63192825 +1777,2018-04-25,18.9,19.0107,18.4833,18.8527,45042330 +1778,2018-04-26,18.8253,19.1333,18.4333,19.0853,50144700 +1779,2018-04-27,19.0333,19.6313,18.7867,19.5,49810530 +1780,2018-04-30,19.5513,19.9153,19.454,19.5893,47944485 +1781,2018-05-01,19.5967,20.0767,19.548,20.0667,46620600 +1782,2018-05-02,20.0267,20.7733,18.8147,19.164,100044315 +1783,2018-05-03,19.2667,19.3667,18.3487,18.8667,200230050 +1784,2018-05-04,18.9333,19.7907,18.6347,19.55,97219695 +1785,2018-05-07,19.6107,20.3973,19.55,20.2653,100077990 +1786,2018-05-08,20.2033,20.5167,19.9333,20.12,69679140 +1787,2018-05-09,20.1333,20.4673,19.9533,20.3987,65864130 +1788,2018-05-10,20.4567,20.866,20.2367,20.2367,65703270 +1789,2018-05-11,20.3213,20.592,19.9387,20.04,52073175 +1790,2018-05-14,20.3333,20.4667,19.4,19.4,83199000 +1791,2018-05-15,19.3333,19.3333,18.7,18.8667,109926450 +1792,2018-05-16,18.9153,19.254,18.7707,19.0933,65149395 +1793,2018-05-17,19.0527,19.2793,18.92,19.0367,50506260 +1794,2018-05-18,19.0073,19.0633,18.2667,18.4533,82659480 +1795,2018-05-21,18.7,19.4327,18.6467,18.9333,110223840 +1796,2018-05-22,19.0267,19.2333,18.228,18.342,104515395 +1797,2018-05-23,18.3333,18.6607,18.1653,18.56,68248245 +1798,2018-05-24,18.6047,18.7407,18.326,18.5653,48098295 +1799,2018-05-25,18.5667,18.6427,18.374,18.6,43134090 +1800,2018-05-29,18.6,19.1,18.41,18.8333,68391420 +1801,2018-05-30,18.8667,19.6673,18.7407,19.4133,86829480 +1802,2018-05-31,19.4007,19.4267,18.862,18.9667,65445975 +1803,2018-06-01,18.9873,19.4667,18.922,19.4667,60092265 +1804,2018-06-04,19.47,19.9333,19.466,19.7167,56356245 +1805,2018-06-05,19.7,19.8667,19.116,19.6,67469700 +1806,2018-06-06,19.6067,21.478,19.574,21.2667,223350765 +1807,2018-06-07,21.22,22,20.9053,21.12,173810055 +1808,2018-06-08,21.0407,21.632,20.9,21.1773,97360800 +1809,2018-06-11,21.1773,22.3107,21.1773,22.2153,159962145 +1810,2018-06-12,22.238,23.6647,22.238,22.8413,268792350 +1811,2018-06-13,23,23.3387,22.6,23.1987,115255125 +1812,2018-06-14,23.06,23.9167,22.9993,23.8,133885455 +1813,2018-06-15,23.7167,24.3113,23.4167,23.9,128061330 +1814,2018-06-18,23.7087,24.9153,23.4,24.494,145368480 +1815,2018-06-19,24.3333,24.6667,23.0833,23.414,155148825 +1816,2018-06-20,23.6,24.292,23.4667,24.1833,99665430 +1817,2018-06-21,24.1733,24.4147,23.0673,23.0673,94828470 +1818,2018-06-22,23.0667,23.6807,22.1333,22.2167,120476655 +1819,2018-06-25,22.17,22.5647,21.8333,22.2287,80040690 +1820,2018-06-26,22.15,22.9033,21.7193,22.82,90073035 +1821,2018-06-27,22.6667,23.386,22.4507,23.026,101165250 +1822,2018-06-28,23.16,23.8013,22.932,23.35,100403235 +1823,2018-06-29,23.4467,23.728,22.8207,22.9333,79185540 +1824,2018-07-02,23.8067,24.4467,21.99,22.456,233595795 +1825,2018-07-03,22.4567,22.4667,20.62,20.654,149002155 +1826,2018-07-05,20.7333,21,19.748,20.5007,213613665 +1827,2018-07-06,20.6,20.8047,20.1333,20.6,110289180 +1828,2018-07-09,20.7933,21.2347,20.5333,21.2193,89890020 +1829,2018-07-10,21.2667,21.9653,21.0707,21.1267,113676510 +1830,2018-07-11,21.1733,21.4627,20.9427,21.2333,58766760 +1831,2018-07-12,21.3667,21.562,20.8513,21.076,67817835 +1832,2018-07-13,21.1733,21.306,20.6167,21.2267,73379730 +1833,2018-07-16,21.124,21.1433,20.4167,20.48,96201240 +1834,2018-07-17,20.5733,21.6493,20.4667,21.49,84189390 +1835,2018-07-18,21.5067,21.7267,21.0833,21.612,69456900 +1836,2018-07-19,21.4667,21.5693,20.934,21.3667,72958365 +1837,2018-07-20,21.408,21.5493,20.78,20.904,62980500 +1838,2018-07-23,20.666,20.666,19.524,20.2667,129825210 +1839,2018-07-24,20.266,20.5147,19.5027,19.7987,115360290 +1840,2018-07-25,19.8287,20.6413,19.5333,20.1333,86301735 +1841,2018-07-26,20.214,20.7133,20.214,20.5,56522880 +1842,2018-07-27,20.5667,20.5667,19.6893,19.7993,52540545 +1843,2018-07-30,19.6667,19.8013,19.0753,19.3333,79959210 +1844,2018-07-31,19.27,19.9907,19.27,19.854,60069180 +1845,2018-08-01,19.9567,22.3833,19.3333,21.9327,117020970 +1846,2018-08-02,21.77,23.3333,21.544,23.3213,279512445 +1847,2018-08-03,23.0667,23.6667,22.8353,23.1367,159452790 +1848,2018-08-06,23.0567,23.6653,22.6013,22.6667,102678015 +1849,2018-08-07,22.7373,25.8307,22.61,25.1333,381052725 +1850,2018-08-08,25.266,25.5093,24.4347,24.6333,280429020 +1851,2018-08-09,24.5067,24.5867,23.0487,23.874,199309800 +1852,2018-08-10,23.7333,24.1933,23.0667,23.48,137798880 +1853,2018-08-13,23.54,24.5327,23.268,23.6393,121692615 +1854,2018-08-14,23.8253,23.9467,23.1133,23.1333,82835430 +1855,2018-08-15,23.246,23.3227,22.1427,22.3733,105751815 +1856,2018-08-16,22.5533,22.9567,22.2547,22.34,66955965 +1857,2018-08-17,22.2067,22.2667,20.2033,20.2033,224153370 +1858,2018-08-20,20.2333,20.5993,18.8193,20.4933,202795425 +1859,2018-08-21,20.56,21.6527,20.534,21.2,156089955 +1860,2018-08-22,21.372,21.592,20.978,21.4867,73769700 +1861,2018-08-23,21.4867,21.8213,21.2067,21.3587,63324510 +1862,2018-08-24,21.3593,21.59,21.2933,21.4793,42289110 +1863,2018-08-27,20.6667,21.496,20.2347,21.2273,164076645 +1864,2018-08-28,21.3067,21.3067,20.746,20.8333,94857345 +1865,2018-08-29,20.776,20.8233,20.2333,20.2413,90330150 +1866,2018-08-30,20.2333,20.38,19.848,20.1533,87190275 +1867,2018-08-31,20.1667,20.354,19.9067,20.09,64315245 +1868,2018-09-04,20,20,19.1507,19.1507,100324125 +1869,2018-09-05,19.2,19.2213,18.4787,18.8167,87707505 +1870,2018-09-06,18.83,19.4113,18.592,18.7667,88452450 +1871,2018-09-07,18.7333,18.7333,16.8167,17.6353,264414765 +1872,2018-09-10,17.8667,19.1333,17.866,18.9793,176956905 +1873,2018-09-11,19,19.0327,18.2367,18.62,110538330 +1874,2018-09-12,18.7333,19.5,18.576,19.35,118337070 +1875,2018-09-13,19.3567,19.6667,19.012,19.3167,73748235 +1876,2018-09-14,19.4233,19.822,19.1013,19.6587,79030395 +1877,2018-09-17,19.6467,20.058,19.0813,19.5267,81452700 +1878,2018-09-18,19.8527,20.176,18.3667,18.8067,201292170 +1879,2018-09-19,18.954,20,18.56,19.8833,96540390 +1880,2018-09-20,19.9647,20.3987,19.5553,19.9187,87191865 +1881,2018-09-21,19.8653,20.0387,19.6913,19.828,55254180 +1882,2018-09-24,19.6667,20.2,19.572,19.912,56511855 +1883,2018-09-25,19.9333,20.3067,19.7667,20,52293330 +1884,2018-09-26,20.1333,20.926,20.0667,20.7,91873710 +1885,2018-09-27,20.6333,21,17.6667,18.06,95037525 +1886,2018-09-28,18.2007,18.5333,17.37,17.7333,403081170 +1887,2018-10-01,19.726,21.03,19.4333,20.3333,260729640 +1888,2018-10-02,20.5847,21.166,19.9433,20.2733,139184115 +1889,2018-10-03,20.3333,20.4333,19.438,19.654,96930465 +1890,2018-10-04,19.68,19.68,18.1333,18.35,114758670 +1891,2018-10-05,18.2673,18.35,17.3333,17.53,208825890 +1892,2018-10-08,17.5333,17.8507,16.6,17.03,153828015 +1893,2018-10-09,17,17.7847,16.8347,17.6507,141231210 +1894,2018-10-10,17.6507,17.766,16.518,16.8133,148776810 +1895,2018-10-11,17,17.4833,16.602,17,94547865 +1896,2018-10-12,17.0667,17.466,16.8007,17.2333,83192580 +1897,2018-10-15,17.148,17.552,16.9687,17.3,74660160 +1898,2018-10-16,17.3333,18.6,17.2747,18.6,107659140 +1899,2018-10-17,18.5833,18.8667,17.72,17.9347,101049495 +1900,2018-10-18,18,18.0667,17.5333,17.7213,62268090 +1901,2018-10-19,17.8333,17.99,16.9,17.304,110253090 +1902,2018-10-22,17.3993,17.5133,16.8393,17.3533,61455330 +1903,2018-10-23,17.2667,19.9,17.108,19.8467,224905620 +1904,2018-10-24,19.8,22.1333,19,21.12,235572405 +1905,2018-10-25,21.1333,21.666,20.0673,20.748,246957480 +1906,2018-10-26,20.4867,22.66,20.1247,21.7993,331244850 +1907,2018-10-29,21.6667,23.144,21.596,22.1013,177468000 +1908,2018-10-30,22.1013,22.5267,21.484,22.0333,111830760 +1909,2018-10-31,22.12,22.8,21.94,22.486,88997550 +1910,2018-11-01,22.6433,23.1893,22.3147,22.8,98076885 +1911,2018-11-02,23.1333,23.28,22.7273,23.034,96029265 +1912,2018-11-05,23,23,22.0093,22.7793,93116505 +1913,2018-11-06,22.6733,23.2533,22.406,22.8753,83178450 +1914,2018-11-07,22.9333,23.412,22.72,23.2053,82208655 +1915,2018-11-08,23.2667,23.8387,23.134,23.426,83512380 +1916,2018-11-09,23.2453,23.6,23.0153,23.3667,62071020 +1917,2018-11-12,23.3333,23.372,21.9,21.9,85421925 +1918,2018-11-13,22.1667,22.98,22.1467,22.7167,61718760 +1919,2018-11-14,22.52,23.1407,22.4733,22.8947,61075260 +1920,2018-11-15,23,23.2387,22.6027,23.1333,55608810 +1921,2018-11-16,23.0767,23.7133,22.9333,23.6267,83323110 +1922,2018-11-19,23.6833,24.45,23.4867,23.5933,117911925 +1923,2018-11-20,23.5,23.5,22.2367,23.1653,96513690 +1924,2018-11-21,23.3333,23.6,22.4767,22.56,55336395 +1925,2018-11-23,22.3333,22.5,21.6,21.6,50440110 +1926,2018-11-26,21.7333,23.0813,21.6533,22.8867,98172615 +1927,2018-11-27,22.8333,23.1307,22.3667,23.03,76446435 +1928,2018-11-28,23,23.2187,22.814,23.1327,50226975 +1929,2018-11-29,23.0333,23.1667,22.6367,22.7333,36297450 +1930,2018-11-30,22.6667,23.44,22.5507,23.38,67724880 +1931,2018-12-03,23.8,24.4,23.4667,23.8133,101594700 +1932,2018-12-04,23.7333,24.5787,23.4667,24.168,103683075 +1933,2018-12-06,23.8333,24.492,23.384,24.22,93603030 +1934,2018-12-07,24.522,25.2993,23.8333,24.0667,135610470 +1935,2018-12-10,23.9993,24.4,23.5413,24.2333,78864630 +1936,2018-12-11,24.3133,24.84,24.0153,24.5667,76196595 +1937,2018-12-12,24.638,24.794,24.344,24.526,60857985 +1938,2018-12-13,24.5333,25.1807,24.45,25.03,87478575 +1939,2018-12-14,24.96,25.1913,24.2887,24.4333,75673965 +1940,2018-12-17,24.4733,24.59,22.9253,23.3333,90968295 +1941,2018-12-18,23.5253,23.554,22.246,22.452,85943745 +1942,2018-12-19,22.4707,23.134,21.9827,22.0927,91612320 +1943,2018-12-20,22.08,22.2873,20.7907,20.97,112096500 +1944,2018-12-21,21.1033,21.5647,20.8293,21.1333,97661730 +1945,2018-12-24,21.5333,21.6,19.5333,19.5407,66350835 +1946,2018-12-26,19.4667,21.798,19.4667,21.6233,98012415 +1947,2018-12-27,21.478,21.5967,20.1,20.9,104624100 +1948,2018-12-28,20.9333,22.416,20.9333,22.2,121384305 +1949,2018-12-31,22.3067,22.706,21.684,22.2,78022320 +1950,2019-01-02,21.7333,22.1867,19.92,20.3767,138488085 +1951,2019-01-03,20.4327,20.6267,19.8253,19.9333,85079760 +1952,2019-01-04,20.3,21.2,20.182,21.2,89212035 +1953,2019-01-07,21.3333,22.4493,21.1833,22.3267,89667855 +1954,2019-01-08,22.3333,23,21.8013,22.3793,86465175 +1955,2019-01-09,22.344,22.9007,22.0667,22.5333,63893385 +1956,2019-01-10,22.386,23.026,22.1193,22.9333,72991995 +1957,2019-01-11,22.9333,23.2273,22.5847,23.1167,60942345 +1958,2019-01-14,22.9,22.9,22.228,22.316,63718830 +1959,2019-01-15,22.4267,23.2533,22.3,23.04,73060710 +1960,2019-01-16,22.9927,23.4667,22.9,23.0067,53209815 +1961,2019-01-17,22.95,23.4333,22.92,23.2133,44328525 +1962,2019-01-18,23.3333,23.3333,19.982,20.3133,289579830 +1963,2019-01-22,20.2667,20.5667,19.7,19.9407,146101185 +1964,2019-01-23,19.6267,19.7193,18.7793,19.1713,148002600 +1965,2019-01-24,19.1833,19.5787,18.6187,19.2667,92497140 +1966,2019-01-25,19.4653,19.9013,19.3033,19.7413,83032155 +1967,2019-01-28,19.6867,19.85,19.1833,19.6407,75093600 +1968,2019-01-29,19.6,19.9293,19.4533,19.8727,55303035 +1969,2019-01-30,19.9527,21.2,19.3673,19.6,128510025 +1970,2019-01-31,19.7407,20.7713,19.4767,20.3073,150214920 +1971,2019-02-01,20.396,21.0733,20.2333,20.8,88314525 +1972,2019-02-04,20.7327,21.02,20.1253,20.8213,91278885 +1973,2019-02-05,20.8327,21.496,20.7707,21.4327,80787765 +1974,2019-02-06,21.4233,21.616,21.0413,21.1333,61091385 +1975,2019-02-07,21.0667,21.0807,20.2,20.4027,79000440 +1976,2019-02-08,20.308,20.53,19.9,20.3433,69815910 +1977,2019-02-11,20.3887,21.24,20.3887,20.8333,88060125 +1978,2019-02-12,21.0667,21.2127,20.6413,20.7,65880930 +1979,2019-02-13,20.8147,20.9,20.3713,20.48,59951655 +1980,2019-02-14,20.5147,20.58,20.0667,20.2333,61683570 +1981,2019-02-15,20.3,20.5587,20.26,20.5293,46719975 +1982,2019-02-19,20.4667,20.77,20.3007,20.44,48097965 +1983,2019-02-20,20.4833,20.614,19.9167,20.1467,84401340 +1984,2019-02-21,20.1927,20.24,19.3667,19.4933,107646420 +1985,2019-02-22,19.6,19.7667,19.4153,19.6667,68671965 +1986,2019-02-25,19.7793,20.194,18.8327,19.2,81461385 +1987,2019-02-26,19.2333,20.134,19.164,19.868,104134410 +1988,2019-02-27,19.8307,21.0867,19.8307,21.0307,137486940 +1989,2019-02-28,21.0307,21.578,20.4533,20.6267,128665170 +1990,2019-03-01,20.6667,20.6667,19.46,19.6027,274694670 +1991,2019-03-04,19.8,20.0513,18.852,19.062,200186820 +1992,2019-03-05,19.1587,19.2333,18.0067,18.4833,224784825 +1993,2019-03-06,18.5333,18.7673,18.2927,18.4533,130688295 +1994,2019-03-07,18.4,18.98,18.2833,18.6333,117750495 +1995,2019-03-08,18.5867,19.0393,18.222,18.96,109426785 +1996,2019-03-11,19.0667,19.4187,18.64,19.35,91647090 +1997,2019-03-12,19.35,19.4433,18.7373,18.8567,94183110 +1998,2019-03-13,18.7673,19.466,18.74,19.29,84463050 +1999,2019-03-14,19.3327,19.6927,19.076,19.2467,87638685 +2000,2019-03-15,19.1333,19.1333,18.2933,18.358,181501410 +2001,2019-03-18,18.5,18.5367,17.82,17.9,126356685 +2002,2019-03-19,17.8733,18.22,17.564,17.8767,147554025 +2003,2019-03-20,17.926,18.3313,17.7533,18.2633,87481035 +2004,2019-03-21,18.2607,18.43,17.8967,18.3267,73793190 +2005,2019-03-22,18.324,18.3933,17.6,17.6233,107444580 +2006,2019-03-25,17.5753,17.6,16.964,17.424,125519295 +2007,2019-03-26,17.5153,18.0173,17.5153,17.8833,90114720 +2008,2019-03-27,17.9,18.358,17.764,18.3173,111765915 +2009,2019-03-28,18.322,18.6887,18.2753,18.6267,84429480 +2010,2019-03-29,18.608,18.6773,18.3,18.6533,74496975 +2011,2019-04-01,18.8133,19.28,18.7333,19.2133,100487535 +2012,2019-04-02,19.2067,19.296,18.9253,19.1567,67021665 +2013,2019-04-03,19.252,19.7447,19.0733,19.428,98939940 +2014,2019-04-04,18.322,18.4,17.34,17.8667,265556415 +2015,2019-04-05,17.9733,18.4067,17.7407,18.3267,155499960 +2016,2019-04-08,18.4333,18.744,18.0293,18.2667,129487440 +2017,2019-04-09,18.314,18.3333,17.974,18.154,72568875 +2018,2019-04-10,18.2333,18.65,18.184,18.44,87333435 +2019,2019-04-11,18.3953,18.45,17.5467,17.9267,115465245 +2020,2019-04-12,17.9467,18.13,17.7887,17.8347,83273295 +2021,2019-04-15,17.8333,17.93,17.242,17.7667,121678560 +2022,2019-04-16,17.7973,18.3333,17.648,18.1867,89589750 +2023,2019-04-17,18.3133,18.3267,17.902,18.08,61218300 +2024,2019-04-18,18,18.3227,17.8993,18.1987,65756700 +2025,2019-04-22,17.9933,17.9933,17.4813,17.5033,150683310 +2026,2019-04-23,17.5867,17.7067,17.05,17.5867,131710980 +2027,2019-04-24,17.5733,17.7333,16.7027,17.2167,127073520 +2028,2019-04-25,17.0467,17.2667,16.4047,16.486,265586880 +2029,2019-04-26,16.5467,16.636,15.4087,15.866,272603400 +2030,2019-04-29,15.9127,16.2653,15.478,16.0313,211597680 +2031,2019-04-30,16.0487,16.2807,15.8,15.9233,114634905 +2032,2019-05-01,15.9133,16,15.4333,15.5833,130472910 +2033,2019-05-02,15.596,16.6367,15.3667,16.3667,221207520 +2034,2019-05-03,16.4653,17.1073,16.0667,17,285771600 +2035,2019-05-06,16.6667,17.2233,16.4913,16.9407,129715710 +2036,2019-05-07,17.022,17.2833,16.34,16.4733,121401255 +2037,2019-05-08,16.6487,16.7067,16.208,16.2207,70776975 +2038,2019-05-09,16.1733,16.2453,15.796,16.0773,79827930 +2039,2019-05-10,16.132,16.1973,15.7347,15.9333,85723890 +2040,2019-05-13,15.8213,16.0073,14.9667,15.0833,123465510 +2041,2019-05-14,15.1833,15.6333,15.1653,15.4833,83553315 +2042,2019-05-15,15.5333,15.5727,15.0167,15.4067,87076290 +2043,2019-05-16,15.39,15.5327,15.1,15.18,85589625 +2044,2019-05-17,15.1333,15.1467,13.928,14.0007,213667560 +2045,2019-05-20,14,14.1187,13.0167,13.622,241324890 +2046,2019-05-21,13.5987,13.8267,13.0693,13.4467,221423400 +2047,2019-05-22,13.3867,13.6667,12.7073,12.71,223585785 +2048,2019-05-23,12.6533,13.3067,12.1253,13.0633,313514490 +2049,2019-05-24,13.1993,13.5807,12.5833,12.6467,172574760 +2050,2019-05-28,12.7907,13,12.5233,12.6327,121369680 +2051,2019-05-29,12.5573,12.826,12.336,12.6773,147665835 +2052,2019-05-30,12.6,12.8173,12.468,12.484,96234330 +2053,2019-05-31,12.4533,12.662,12.2,12.396,126511080 +2054,2019-06-03,12.2773,12.4453,11.7993,11.9633,162149595 +2055,2019-06-04,11.9933,12.9867,11.974,12.9473,168287700 +2056,2019-06-05,13.0773,13.4187,12.7893,13.0387,170547300 +2057,2019-06-06,13.2133,14.0667,13.106,13.76,239261910 +2058,2019-06-07,13.8293,14.0567,13.566,13.6107,185291190 +2059,2019-06-10,13.6753,14.4627,13.6753,14.35,120507465 +2060,2019-06-11,14.4333,15.2493,14.2333,15.0207,136661955 +2061,2019-06-12,15.0207,15.0967,13.9067,13.9867,182775390 +2062,2019-06-13,14,14.3267,13.834,14.1653,101617290 +2063,2019-06-14,14.2147,14.4433,13.9413,14.3327,88657065 +2064,2019-06-17,14.4193,15.1333,14.2733,15.0333,149330235 +2065,2019-06-18,15.0833,15.6493,14.8373,15.0133,152172840 +2066,2019-06-19,15.0887,15.1847,14.7373,15.1307,79817250 +2067,2019-06-20,15.2,15.3493,14.4233,14.6333,145668465 +2068,2019-06-21,14.6267,14.812,14.3667,14.7667,91318920 +2069,2019-06-24,14.7667,15.0573,14.7347,14.9533,69803340 +2070,2019-06-25,14.9007,15.0227,14.6327,14.6733,71846805 +2071,2019-06-26,14.7993,15.1487,14.4353,14.5587,101637405 +2072,2019-06-27,14.5593,14.8793,14.4747,14.8533,73779210 +2073,2019-06-28,14.814,15.0113,14.6753,14.93,76459620 +2074,2019-07-01,15.1133,15.54,15.0853,15.2,102639255 +2075,2019-07-02,15.2,16.3327,14.8147,16.0333,112517325 +2076,2019-07-03,15.9333,16.1333,15.6,15.6233,171219210 +2077,2019-07-05,15.6913,15.7147,15.3867,15.5167,85099530 +2078,2019-07-08,15.5333,15.5333,15.244,15.35,71488095 +2079,2019-07-09,15.28,15.4,15.152,15.35,74145135 +2080,2019-07-10,15.4,15.9333,15.3753,15.92,109079265 +2081,2019-07-11,15.9393,16.1,15.72,15.8733,87319530 +2082,2019-07-12,15.902,16.4127,15.902,16.4127,95006310 +2083,2019-07-15,16.4667,16.9613,16.324,16.8533,129415845 +2084,2019-07-16,16.8333,16.902,16.5287,16.7833,94476000 +2085,2019-07-17,16.8253,17.2207,16.8253,16.96,105617190 +2086,2019-07-18,16.972,17.05,16.792,16.9667,56868000 +2087,2019-07-19,16.9973,17.3307,16.9747,17.1913,85749975 +2088,2019-07-22,17.2,17.48,16.946,17.0667,83095470 +2089,2019-07-23,17.1,17.3653,16.9667,17.3127,54661110 +2090,2019-07-24,17.3167,17.88,15.5333,15.7133,130306335 +2091,2019-07-25,15.72,15.8,15.0367,15.1693,270950850 +2092,2019-07-26,15.2453,15.3507,14.8167,15.1407,118829130 +2093,2019-07-29,15.1667,15.7293,15,15.6747,113923785 +2094,2019-07-30,15.6747,16.224,15.4467,16.102,96458760 +2095,2019-07-31,16.1347,16.4453,15.7767,16.0727,111596460 +2096,2019-08-01,16.154,16.3007,15.4513,15.5467,98159715 +2097,2019-10-10,16.2667,16.6187,16.1053,16.3933,71848110 +2098,2019-10-11,16.438,16.7387,16.316,16.5667,99881625 +2099,2019-10-14,16.4853,17.2367,16.4667,17.1507,120297450 +2100,2019-10-15,17.1433,17.3333,16.9413,17.1667,74867415 +2101,2019-10-16,17.1333,17.4733,17.0667,17.32,76111920 +2102,2019-10-17,17.3587,17.652,17.2667,17.46,54637350 +2103,2019-10-18,17.42,17.52,17.0067,17.1067,67372005 +2104,2019-10-21,17.2,17.3,16.6787,16.964,59437185 +2105,2019-10-22,16.9133,17.222,16.7233,17,51015450 +2106,2019-10-23,16.928,20.5667,16.7567,20.4,126354015 +2107,2019-10-24,20.074,20.3287,19.28,19.9333,333785415 +2108,2019-10-25,19.816,22,19.7407,21.828,346900110 +2109,2019-10-28,21.82,22.7227,21.5067,21.8533,217401990 +2110,2019-10-29,21.8,21.8,20.9333,20.972,148391235 +2111,2019-10-30,20.8,21.2527,20.6647,21.0267,110357760 +2112,2019-10-31,21,21.2667,20.85,20.968,57293355 +2113,2019-11-01,21.01,21.158,20.6533,20.87,74996490 +2114,2019-11-04,20.9333,21.4627,20.6173,21.19,107054385 +2115,2019-11-05,21.268,21.5673,21.074,21.1407,80141085 +2116,2019-11-06,21.1267,21.8033,20.9667,21.742,94473615 +2117,2019-11-07,21.8373,22.7667,21.8373,22.412,170876115 +2118,2019-11-08,22.3333,22.4973,22.1667,22.45,70916190 +2119,2019-11-11,22.3873,23.2793,22.3667,23.0087,115064865 +2120,2019-11-12,23.0333,23.358,22.936,23.3133,83768280 +2121,2019-11-13,23.4,23.7867,23.012,23.0667,95754555 +2122,2019-11-14,23.0073,23.5893,22.8607,23.28,73642995 +2123,2019-11-15,23.3467,23.52,23.224,23.4547,53228490 +2124,2019-11-18,23.4547,23.6467,23.0733,23.3327,47569800 +2125,2019-11-19,23.3373,23.9993,23.1867,23.934,88743975 +2126,2019-11-20,23.8533,24.1807,23.3047,23.4733,73837815 +2127,2019-11-21,23.4813,24.056,23.4813,23.8067,67119255 +2128,2019-11-22,23.3933,23.6553,22,22.2067,185281845 +2129,2019-11-25,22.84,23.3073,22.2973,22.4293,136063125 +2130,2019-11-26,22.4613,22.4613,21.8067,21.9867,85639260 +2131,2019-11-27,21.9867,22.262,21.9047,22,60248265 +2132,2019-11-29,22.0713,22.2,21.8333,22.0027,26162310 +2133,2019-12-02,22.0933,22.426,21.9,22.25,65817750 +2134,2019-12-03,22.4087,22.5667,22.0333,22.4253,71516535 +2135,2019-12-04,22.4327,22.5747,22.186,22.2187,52213935 +2136,2019-12-05,22.2347,22.3333,21.8167,22.26,39315060 +2137,2019-12-06,22.2667,22.5907,22.2667,22.3927,87443550 +2138,2019-12-09,22.4,22.9633,22.3387,22.6527,97238610 +2139,2019-12-10,22.6353,23.382,22.4667,23.2667,94475535 +2140,2019-12-11,23.276,23.8127,23.276,23.6387,75745965 +2141,2019-12-12,23.6667,24.1827,23.5487,24.04,86341350 +2142,2019-12-13,24.08,24.3473,23.6427,23.9187,73028070 +2143,2019-12-16,23.9333,25.574,23.9333,25.204,196900605 +2144,2019-12-17,25.3127,25.7,25.06,25.268,88895370 +2145,2019-12-18,25.1333,26.348,25.1333,26.24,159076170 +2146,2019-12-19,26.1447,27.1233,26.12,26.992,195368595 +2147,2019-12-20,27,27.5333,26.6787,27.0667,162292950 +2148,2019-12-23,27.2007,28.134,27.2007,27.9793,147161505 +2149,2019-12-24,28.0653,28.392,27.512,28.3533,92001720 +2150,2019-12-26,28.3533,28.8987,28.3533,28.7667,118997565 +2151,2019-12-27,28.772,29.1453,28.4073,28.7167,110319030 +2152,2019-12-30,28.7847,28.89,27.2833,27.4833,140912100 +2153,2019-12-31,27.6,28.086,26.8053,27.9,115227540 +2154,2020-01-02,28.0607,28.7993,27.8887,28.7867,105742830 +2155,2020-01-03,28.4267,30.2667,28.1007,29.4607,201368895 +2156,2020-01-06,29.2007,30.1333,29.1667,30.1333,114317175 +2157,2020-01-07,30.2633,31.442,30.1673,30.5,200288085 +2158,2020-01-08,31.06,33.2327,30.9187,33.07,348554655 +2159,2020-01-09,32.68,33.2867,31.5247,32.008,308683530 +2160,2020-01-10,32.2667,32.6167,31.58,31.866,142140990 +2161,2020-01-13,32.206,35.496,32.206,35.4413,296673120 +2162,2020-01-14,35.428,36.5,34.9933,35.7653,313603800 +2163,2020-01-15,35.8667,35.8667,34.452,34.65,189689685 +2164,2020-01-16,33.5533,34.2973,32.8113,34.174,234395160 +2165,2020-01-17,34.2687,34.5533,33.2587,33.6067,149312700 +2166,2020-01-21,33.8733,37.0067,33.7733,36.95,189698280 +2167,2020-01-22,37.134,39.6333,37.134,38.1333,324324630 +2168,2020-01-23,37.97,38.8,37.0367,38.0407,203213130 +2169,2020-01-24,38.296,38.6533,36.9507,37.2667,148648650 +2170,2020-01-27,36.92,37.6293,35.9207,37.3333,139065495 +2171,2020-01-28,37.442,38.454,37.2053,38.1,125302140 +2172,2020-01-29,38.148,43.9867,37.8287,43.2333,183743490 +2173,2020-01-30,42.74,43.392,41.2,42.9407,273085440 +2174,2020-01-31,42.6667,43.5333,42.0013,43.05,158981265 +2175,2020-02-03,43.2667,52.4533,43.0067,51.0667,475263390 +2176,2020-02-04,52.3667,64.5993,52.3667,60.2667,552886995 +2177,2020-02-05,56.6667,58.9333,46.9407,48.5,464742915 +2178,2020-02-06,49,53.0553,45.8,49.4,383700900 +2179,2020-02-07,49.2,51.3167,48.2,49.7073,168028710 +2180,2020-02-10,50.3333,54.666,50.16,51.5733,240893220 +2181,2020-02-11,52.2,52.432,50.5333,51.3333,115196955 +2182,2020-02-12,51.9993,52.65,49.55,50.1333,117541665 +2183,2020-02-13,50.0667,54.5333,47.4667,53.3333,259599570 +2184,2020-02-14,53.6,54.2,51.6667,53.5,160881435 +2185,2020-02-18,52.5333,59.3193,51.6673,58.8007,168671805 +2186,2020-02-19,59.3333,62.9853,59.3333,60.47,249771750 +2187,2020-02-20,60.6333,61.08,57.3287,59.3333,181159170 +2188,2020-02-21,60.3133,61.2,58.6,59.9213,149621535 +2189,2020-02-24,58.2327,58.234,54.8133,56.2667,148606905 +2190,2020-02-25,56.3333,57.1067,52.4667,52.7333,168777675 +2191,2020-02-26,52.1707,54.2207,50.6467,51.2667,136474050 +2192,2020-02-27,51.2,51.532,42.8333,43.668,249019995 +2193,2020-02-28,43,46.0347,40.768,44.9987,257814675 +2194,2020-03-02,47.1507,51.3333,44.1333,51.2667,206093775 +2195,2020-03-03,51.8447,54.6793,47.7407,48.7333,250127055 +2196,2020-03-04,50.3333,52.734,48.3153,49.62,154058295 +2197,2020-03-05,49.0733,49.7167,47.4673,48,108482445 +2198,2020-03-06,47.2,47.4667,45.1327,46.05,123425130 +2199,2020-03-09,43.6447,44.2,40,42.3867,175009290 +2200,2020-03-10,42.8873,45.4,40.5333,41.6867,161919360 +2201,2020-03-11,41.6,43.572,40.8667,42.2067,140357565 +2202,2020-03-12,40.566,40.7433,34.08,34.6,197614035 +2203,2020-03-13,37.4667,40.5307,33.4667,35.6,239295285 +2204,2020-03-16,33.7667,33.7667,28.6667,30.2,221492175 +2205,2020-03-17,31.4667,32.1333,26.4,27.1707,261417435 +2206,2020-03-18,26.8667,26.9907,23.3673,24.8667,265132005 +2207,2020-03-19,24.3333,30.1333,23.4,26.2667,328591200 +2208,2020-03-20,28,31.8,27.8387,28.252,307001235 +2209,2020-03-23,27.66,30.2,27.0667,29.692,178044150 +2210,2020-03-24,30.3333,35.6,30.1467,33.9987,237852525 +2211,2020-03-25,36.5333,37.9333,33.9933,36.0007,218541390 +2212,2020-03-26,35.2433,37.3333,34.15,35.1333,179456955 +2213,2020-03-27,34.5307,35.0533,32.9353,33.9333,148377030 +2214,2020-03-30,33.6667,34.76,32.7487,33.5333,119682195 +2215,2020-03-31,33.9333,36.1973,33.0067,34.3667,188997660 +2216,2020-04-01,33.7253,34.264,31.6733,32.3727,138967425 +2217,2020-04-02,32.6,36.5313,29.76,35.6667,203988075 +2218,2020-04-03,35.2,35.4,31.226,31.6667,241104990 +2219,2020-04-06,33.6667,34.7333,33.1973,34.2,150877275 +2220,2020-04-07,35.3333,37.6667,35.2227,36.658,187243695 +2221,2020-04-08,36.5847,37.7333,35.5553,36.7293,135389595 +2222,2020-04-09,37.036,39.8,36.094,39.6333,140315520 +2223,2020-04-13,39.2,45.22,38.414,44.8987,232627920 +2224,2020-04-14,45.3433,49.9993,45.0733,49.7667,300642825 +2225,2020-04-15,49.3993,50.8,47.3333,47.5667,231622050 +2226,2020-04-16,48.7773,52.7333,47.114,51.6667,211446420 +2227,2020-04-17,51.8,52.3587,49.844,50.102,132770940 +2228,2020-04-20,50.08,51.038,47.4807,49.8667,152149290 +2229,2020-04-21,49.2,50.222,44.9193,46.0007,202718685 +2230,2020-04-22,46.8,49.344,45.2327,48.2533,145122495 +2231,2020-04-23,48.4,49.1267,46.4,46.4613,136673115 +2232,2020-04-24,46.4667,48.7153,46.4667,48.3333,139092495 +2233,2020-04-27,49.07,53.7787,48.9673,52.1373,202881945 +2234,2020-04-28,52.4733,53.6667,50.446,51.786,155158260 +2235,2020-04-29,52.1333,59.126,51.0067,58.0667,158846565 +2236,2020-04-30,57.6333,58.4,50.6667,51,272728890 +2237,2020-05-01,50.9733,51.518,45.536,47.2,325839930 +2238,2020-05-04,47.2,51.2667,45.4667,51.2667,191118300 +2239,2020-05-05,52.1333,53.2613,50.812,51.6333,175710750 +2240,2020-05-06,51.9967,52.6533,50.7407,51.9667,113329740 +2241,2020-05-07,52.3407,53.0933,51.1333,52.2333,118667010 +2242,2020-05-08,52.4333,55.0667,52.4327,54.6,160369815 +2243,2020-05-11,54.0333,54.9333,52.3333,54.0807,171898425 +2244,2020-05-12,53.8573,56.2193,52.9933,53.0267,163140435 +2245,2020-05-13,53.5773,55.1733,50.8867,53.3193,197153685 +2246,2020-05-14,53.3333,53.9333,50.9333,53.5333,134271540 +2247,2020-05-15,53.7333,53.7333,52.1633,53.24,107025660 +2248,2020-05-18,54.018,55.6487,53.592,54.1,119931690 +2249,2020-05-19,54.5333,54.8047,53.6667,54.0733,98436405 +2250,2020-05-20,54.4,55.0667,54.12,54.3007,70987260 +2251,2020-05-21,54.078,55.5,53.0667,55.0333,125158530 +2252,2020-05-22,54.4667,55.452,54.1333,54.5067,102896430 +2253,2020-05-26,55.6293,55.92,54.38,54.6653,77548890 +2254,2020-05-27,54.4667,55.1807,52.3333,54.2933,115787835 +2255,2020-05-28,54.2833,54.9833,53.446,53.8,73302210 +2256,2020-05-29,54.1587,56.1833,53.614,56.1833,122263095 +2257,2020-06-01,56.6667,60.2,56.6,59.1333,145189200 +2258,2020-06-02,59.2333,60.5773,58.0667,58.8,132256140 +2259,2020-06-03,58.8,59.8627,58.6733,58.8747,80101050 +2260,2020-06-04,59.0513,59.7167,57.2293,57.7333,88832985 +2261,2020-06-05,58.2907,59.1227,57.7467,58.99,78301965 +2262,2020-06-08,58.6667,63.8327,58.6,62.9667,141366735 +2263,2020-06-09,62.6667,63.6293,61.5953,62.466,115863015 +2264,2020-06-10,62.6,68.8,62.3333,67.3,174956610 +2265,2020-06-11,66.6667,67.9307,64.276,65,156858300 +2266,2020-06-12,63.8627,66.134,60.8373,61.2367,162138555 +2267,2020-06-15,60.2,66.5893,59.7607,66.2707,155522580 +2268,2020-06-16,66.6,67.99,64.1593,65.2667,133777140 +2269,2020-06-17,65.8667,67,65.134,65.7667,100027320 +2270,2020-06-18,66.4,67.9467,66.298,67.466,97189380 +2271,2020-06-19,67.5653,67.9833,66.0667,66.1267,83171715 +2272,2020-06-22,66.7827,67.2587,66.0013,66.6,64500420 +2273,2020-06-23,66.846,67.4667,66.2673,66.4667,64613580 +2274,2020-06-24,66.2673,66.726,63.4,63.4,106925520 +2275,2020-06-25,63.3333,66.1867,62.4767,66.1333,92884695 +2276,2020-06-26,65.7753,66.5333,63.658,63.7267,83687025 +2277,2020-06-29,64.2667,67.4267,63.2347,67.1667,85269270 +2278,2020-06-30,66.9087,72.5127,66.7333,71.6867,166442490 +2279,2020-07-01,72.194,75.95,71.0667,75.866,123111735 +2280,2020-07-02,76.3847,82.1333,76.3847,80.88,154935240 +2281,2020-07-06,83.34,95.7967,82.8673,95.484,175538805 +2282,2020-07-07,95.1933,95.3,89.114,92.0667,167984835 +2283,2020-07-08,92.0773,94.484,87.4227,90.7353,137422935 +2284,2020-07-09,91.6667,93.9047,90.0853,92.9,99822150 +2285,2020-07-10,92.5333,103.5327,91.734,102.8,196613790 +2286,2020-07-13,105.6433,119.666,96.6667,101.9333,293325390 +2287,2020-07-14,102.5353,107.5247,95.4,104.402,191646180 +2288,2020-07-15,105.0667,106.332,97.1327,100.7333,128684670 +2289,2020-07-16,100.32,102.114,96.2673,99.2027,124492275 +2290,2020-07-17,99.8593,102.5007,99.3333,100.452,78639675 +2291,2020-07-20,99.8293,111.7267,99.2,110.8667,137656275 +2292,2020-07-21,112,113.2,103.8667,105.3333,131882220 +2293,2020-07-22,105.6667,114.4313,103.5933,110.4667,106352115 +2294,2020-07-23,112.0013,112.6,98.706,98.966,187476870 +2295,2020-07-24,98.0973,98.132,91.1027,93.4667,157381425 +2296,2020-07-27,94.7667,103.2667,91.6667,102.8667,129609780 +2297,2020-07-28,101.0667,104.314,98.0053,98.084,135868020 +2298,2020-07-29,99.2013,102.3207,98.4327,100.0767,81939615 +2299,2020-07-30,99.52,100.8833,98.008,100.4,65301720 +2300,2020-07-31,99.9733,101.8667,94.732,95.0333,103662660 +2301,2020-08-03,96.6667,100.6547,96.2,99,73760145 +2302,2020-08-04,99.01,101.8273,97.4667,99.4667,72451020 +2303,2020-08-05,100,100.5333,97.8873,98.8,40635945 +2304,2020-08-06,98.5333,101.154,98.1727,99.4933,49976850 +2305,2020-08-07,99,100.1987,94.334,96.7333,72015780 +2306,2020-08-10,96.9987,97.2653,92.3893,94.2,60084135 +2307,2020-08-11,95.1993,99.3333,90.9993,97.5487,67698210 +2308,2020-08-12,97.7433,105.6667,95.6667,104.3333,173744580 +2309,2020-08-13,104.7333,110,104.132,109,165591105 +2310,2020-08-14,108.8667,112.2667,108.4427,109.754,101037135 +2311,2020-08-17,110.82,123.0573,110.82,122.4,156188385 +2312,2020-08-18,123.9253,129.2673,122.376,126.3333,123741405 +2313,2020-08-19,127.2,127.8,122.7473,124.6667,94184685 +2314,2020-08-20,124.6,134.7993,123.7333,133.9993,159074805 +2315,2020-08-21,135.9967,139.6993,134.2013,136.1667,166461210 +2316,2020-08-24,138.6673,142.6667,128.5313,133.3347,150696765 +2317,2020-08-25,135.4667,136.6,130.9333,136.5333,80517750 +2318,2020-08-26,136.9333,144.8833,135.7333,142.8,105153030 +2319,2020-08-27,143.6,153.04,142.5333,149.8,180878220 +2320,2020-08-28,150.666,154.566,145.8373,147.7993,145062675 +2321,2020-08-31,156.0333,172.6667,146.0333,171.5833,248705622 +2322,2020-09-01,176.68,179.5833,156.8367,160.33,177822417 +2323,2020-09-02,162.0067,164.2667,135.04,145.7533,188849097 +2324,2020-09-03,146,146.1,126.6667,126.8,180565761 +2325,2020-09-04,131.5,142.6667,124.0067,130.5,231814941 +2326,2020-09-08,130.3333,131.6667,102.6667,108.05,247260840 +2327,2020-09-09,113.3,125.2667,112.5767,124.9933,168193332 +2328,2020-09-10,122,132.9967,120.1667,125.2,188312610 +2329,2020-09-11,127.3333,129.52,120.1667,124.5833,137663229 +2330,2020-09-14,127.7333,142.9167,124.4333,141.15,181388055 +2331,2020-09-15,142.7733,153.98,141.75,148.6667,210951363 +2332,2020-09-16,151.6667,152.6167,144.4467,148.2467,165125403 +2333,2020-09-17,142.88,147.2533,136,141.2333,170581353 +2334,2020-09-18,142.6667,150.3333,142.1533,149.8333,191458605 +2335,2020-09-21,148.2333,151.9,135.69,141.0133,235264287 +2336,2020-09-22,143.5767,149.3333,130.5033,131.6933,168209415 +2337,2020-09-23,132.9267,141.3767,121.67,122.61,197688879 +2338,2020-09-24,124.62,133.1667,117.1,131.25,219102480 +2339,2020-09-25,130.5,136.4733,128.3667,135.2667,148599174 +2340,2020-09-28,138.68,142.7567,138.3333,139.9333,102743079 +2341,2020-09-29,139.6967,142.8167,135.3333,139.4033,105701094 +2342,2020-09-30,138,144.6433,137.0033,143.9,101027403 +2343,2020-10-01,144.6667,149.6267,144.4467,147.6,108278334 +2344,2020-10-02,143.3233,146.3767,135.8333,137.0667,153489573 +2345,2020-10-05,141.41,144.5467,138.7067,140.7267,95763156 +2346,2020-10-06,140.6667,142.9267,135.35,137.74,106731042 +2347,2020-10-07,139.65,143.3,137.95,142.45,93197385 +2348,2020-10-08,143.5,146.3967,141.7667,143.25,87453252 +2349,2020-10-09,143.25,144.8633,142.1533,144.8233,62810682 +2350,2020-10-12,145.49,149.58,145.0267,147.3967,83716995 +2351,2020-10-13,147.1667,149.63,145.5333,149.3067,73758798 +2352,2020-10-14,149.3333,155.3,148.5,153.45,103619673 +2353,2020-10-15,150.9833,153.3333,147.34,148.9167,76002600 +2354,2020-10-16,149.6267,151.9833,145.6667,146.0667,70403769 +2355,2020-10-19,148.6667,149.5833,142.9567,144.4833,79414086 +2356,2020-10-20,145.3,146.2767,139.6833,141.5333,66908925 +2357,2020-10-21,141.6,147.2833,140.0033,145.4367,65343702 +2358,2020-10-22,145.65,148.6667,141.5033,142.1633,85645152 +2359,2020-10-23,142.28,142.28,135.7933,140.1667,68631111 +2360,2020-10-26,137.6667,141.92,136.6667,138.8333,60391515 +2361,2020-10-27,139,143.5,139,140.55,47481831 +2362,2020-10-28,140,140.4,134.3733,135.8367,50498646 +2363,2020-10-29,137.1333,139.3533,135.1,135.5333,46622136 +2364,2020-10-30,134.3433,136.9433,126.37,129,87711978 +2365,2020-11-02,130.2667,135.66,129,133.6667,62289972 +2366,2020-11-03,134.1033,142.59,134.1033,141.5333,74676897 +2367,2020-11-04,141.3,145.8833,139.0333,140.8,66091209 +2368,2020-11-05,143.0333,146.6667,141.3333,144.1333,59458839 +2369,2020-11-06,142.7867,146.03,141.4267,143.3,47468925 +2370,2020-11-09,146.47,150.8333,140.3333,141.3333,72391911 +2371,2020-11-10,141.3333,141.3433,132.01,136.3333,62105277 +2372,2020-11-11,138.3333,139.5667,136.7833,138.9367,36576201 +2373,2020-11-12,138.8333,141,136.5067,137,39151536 +2374,2020-11-13,136.0233,137.9833,133.8867,136.04,39364200 +2375,2020-11-16,136.6667,155.8333,134.6933,153.9733,52552809 +2376,2020-11-17,150.5667,155.5667,144.3367,146.1,126524304 +2377,2020-11-18,150.4033,165.3333,147.26,160.6633,163818360 +2378,2020-11-19,160.0233,169.54,159.3367,164.3333,130075530 +2379,2020-11-20,166.1167,167.5,163.0033,163.5333,68026170 +2380,2020-11-23,165.16,177.4467,165.16,176.6667,103891680 +2381,2020-11-24,178,188.27,173.7333,187.4667,111214107 +2382,2020-11-25,189.3333,192.1533,181,191.6667,100834929 +2383,2020-11-27,191.3333,199.5933,187.27,194.9233,76762173 +2384,2020-11-30,196.3333,202.6,184.8367,197.3667,131103393 +2385,2020-12-01,197.3667,199.7667,190.6833,191.8267,81546585 +2386,2020-12-02,191.6667,196.8367,180.4033,194.31,96274566 +2387,2020-12-03,195,199.6567,189.6067,197.7233,86454540 +2388,2020-12-04,198.72,200.8967,195.1667,199.5667,59674344 +2389,2020-12-07,199,216.4833,198.3333,216.4133,116487387 +2390,2020-12-08,218.2533,223,204.93,215.4,132180669 +2391,2020-12-09,215.3967,219.64,196,197.0067,137626977 +2392,2020-12-10,199.0333,212.0367,188.78,208.3,139451475 +2393,2020-12-11,205.4333,208,198.9333,202.5467,95785260 +2394,2020-12-14,203.3333,214.25,203.3333,212,110166885 +2395,2020-12-15,213.1,216.0667,207.9333,209.1333,97244397 +2396,2020-12-16,211.6667,211.6667,201.6667,206.8667,87571866 +2397,2020-12-17,206.9,219.6067,205.8333,216,117472365 +2398,2020-12-18,217.1,231.6667,209.5667,225.6667,453121770 +2399,2020-12-21,218.3333,231.6667,215.2033,216.6,115350915 +2400,2020-12-22,217.45,219.5,204.7433,211.4433,104906727 +2401,2020-12-23,212.55,217.1667,207.5233,214.1667,67952889 +2402,2020-12-24,214.1667,222.03,213.6667,220,46317783 +2403,2020-12-28,220.6667,227.1333,219.9,220,66460887 +2404,2020-12-29,221.6667,223.3,218.3333,221.7967,46040676 +2405,2020-12-30,221.7933,232.2,221.3333,231.1333,89297991 +2406,2020-12-31,231.1667,239.5733,230.1633,234.8333,103795989 +2407,2021-01-04,236.3333,248.1633,236.3333,244.5333,100289490 +2408,2021-01-05,243.3767,251.4667,239.7333,250.9667,63907479 +2409,2021-01-06,249.3333,258,248.8867,254.5333,92182257 +2410,2021-01-07,256.3333,278.24,255.7333,276.5,102648621 +2411,2021-01-08,281.6667,294.9633,279.4633,289.1667,150111201 +2412,2021-01-11,288.7933,290.1667,267.8733,272.8333,115961742 +2413,2021-01-12,274,289.3333,274,284,94456524 +2414,2021-01-13,285,287,277.3333,281.0333,66342027 +2415,2021-01-14,280,287.6667,279.22,282.65,63056748 +2416,2021-01-15,283.23,286.6333,273.0333,274.59,78848139 +2417,2021-01-19,279,283.3333,277.6667,281.0833,46853928 +2418,2021-01-20,280.9967,286.7267,279.0933,283.9567,49166334 +2419,2021-01-21,286,286.33,280.3333,280.6633,38889873 +2420,2021-01-22,280.2733,282.6667,276.2067,282.5,37781574 +2421,2021-01-25,283.9633,300.1333,279.6067,291.5,76459485 +2422,2021-01-26,293.16,298.6333,290.5333,295.97,44113677 +2423,2021-01-27,296.11,297.17,266.1433,273.4633,44969781 +2424,2021-01-28,272.8333,282.6667,264.6667,276.4833,43576764 +2425,2021-01-29,274.55,280.8033,260.0333,262.6333,59973315 +2426,2021-02-01,270.6967,280.6667,265.1867,280,44447226 +2427,2021-02-02,281.6667,293.4067,277.3333,292.6667,42602496 +2428,2021-02-03,292.6667,293.2133,283.3333,283.6667,32335680 +2429,2021-02-04,286.2333,286.7433,277.8067,282.1667,28538979 +2430,2021-02-05,283.6133,288.2567,279.6567,284.4967,32859015 +2431,2021-02-08,285.73,292.6267,280.18,286.2067,36266742 +2432,2021-02-09,287.7933,287.8067,280.6667,281.83,25635285 +2433,2021-02-10,283.3333,283.6267,266.6733,269.9633,64580658 +2434,2021-02-11,272.82,276.6267,267.2633,270.3333,38372664 +2435,2021-02-12,269.8767,272.8333,261.7767,272.5167,40260147 +2436,2021-02-16,273.6667,275,263.7333,263.8067,34891947 +2437,2021-02-17,263.3333,266.6133,254.0033,264.55,45436740 +2438,2021-02-18,263.57,264.8967,258.6667,261.0333,32746779 +2439,2021-02-19,260.9267,267.5567,259.1233,260.8333,33005790 +2440,2021-02-22,254.5,256.1667,236.3333,236.87,66209229 +2441,2021-02-23,231.7333,240,206.3333,238.8333,120777558 +2442,2021-02-24,240,248.3333,231.39,246.0667,69555915 +2443,2021-02-25,247.1667,247.34,218.3333,222.6667,69715503 +2444,2021-02-26,226.0067,235.5667,219.8367,223.6,77062926 +2445,2021-03-01,230.8367,241.8133,228.35,241.75,48766533 +2446,2021-03-02,238.8333,241.1167,228.3333,229.5967,40553202 +2447,2021-03-03,233,234.1667,216.3733,217.9767,52144758 +2448,2021-03-04,218.27,222.8167,200,200.0333,120709596 +2449,2021-03-05,203.5,210.74,179.83,198.75,166008762 +2450,2021-03-08,194.4,206.71,184.6667,189,99075645 +2451,2021-03-09,193.72,231.3,192.3333,229.7367,126304164 +2452,2021-03-10,230.5233,239.2833,218.6067,221.52,115159767 +2453,2021-03-11,229,235.2633,225.7267,232.8333,66966033 +2454,2021-03-12,225,232,222.0433,230.9967,60956052 +2455,2021-03-15,229.9667,237.7267,228.0133,234,55377972 +2456,2021-03-16,236.9233,237,223.6667,224.7,59068035 +2457,2021-03-17,224.8667,234.5767,216.67,233.2467,77101338 +2458,2021-03-18,229.2567,230.93,216.8333,216.8533,59758062 +2459,2021-03-19,216.6667,222.8333,208.2067,217.4,81737448 +2460,2021-03-22,220.6667,233.2067,218.29,223.1167,75553839 +2461,2021-03-23,223,227.2,219.17,221,53724156 +2462,2021-03-24,221.3333,225.3333,210,211.3,63886878 +2463,2021-03-25,211.3667,215.1667,201.48,214.2,75643422 +2464,2021-03-26,214.0167,217.0767,200,207.1,59529975 +2465,2021-03-29,203.15,207.36,198.6733,202.6,48334989 +2466,2021-03-30,202,213.3333,197.0033,213.0033,77555175 +2467,2021-03-31,211.5667,224,209.1667,221.1033,64970841 +2468,2021-04-01,225.1833,230.81,219.3333,219.3333,68217258 +2469,2021-04-05,233.3333,238.9,228.2333,230.9,82286721 +2470,2021-04-06,230.1667,232.1833,227.1233,230.8333,57601257 +2471,2021-04-07,230.9567,231.1167,222.6133,224.1333,53050818 +2472,2021-04-08,226.33,229.85,223.88,228.9233,48333639 +2473,2021-04-09,228.2433,229.1667,223.1433,225.6667,39606963 +2474,2021-04-12,228.5667,234.9333,226.2367,233.8367,54284880 +2475,2021-04-13,234.6667,254.5,234.5767,252.5667,86973186 +2476,2021-04-14,254.9067,262.23,242.6767,244.2933,93136587 +2477,2021-04-15,248.3333,249.1133,240.4367,246.0833,53544411 +2478,2021-04-16,245.8767,249.8033,241.5333,246.4167,53036541 +2479,2021-04-19,244.6667,247.21,230.6,240.5333,75574374 +2480,2021-04-20,240.07,245.75,233.9,237.4633,70814043 +2481,2021-04-21,237.2067,248.28,232.6667,246.8667,58436706 +2482,2021-04-22,247.24,251.2567,237.6667,239.5,68573160 +2483,2021-04-23,239.04,245.7867,237.51,243.3667,55616598 +2484,2021-04-26,244.6667,249.7667,238.39,239.9533,56943357 +2485,2021-04-27,240,241.9467,233.63,233.86,54962673 +2486,2021-04-28,233.3333,236.1667,230.5133,231.5,40961961 +2487,2021-04-29,233.84,234.6,222.8667,223.6267,53380290 +2488,2021-04-30,224.3367,238.49,221.0467,236.6667,76883430 +2489,2021-05-03,236.0067,236.21,226.8333,227.1,51935973 +2490,2021-05-04,227.0633,229.5,219.2333,225.1,55854111 +2491,2021-05-05,225.7667,228.4333,222.1667,222.17,42513225 +2492,2021-05-06,224.4567,230.0767,216.6667,221.6667,54950481 +2493,2021-05-07,222.1667,227.84,218.5433,223.1667,45285756 +2494,2021-05-10,223,223.3333,206.7033,206.7033,59311011 +2495,2021-05-11,206.67,209.0333,192.6667,205.25,89671815 +2496,2021-05-12,206.1,206.8033,193.3333,194.1667,64890921 +2497,2021-05-13,193.6667,202.1533,186.6667,191.1667,83126715 +2498,2021-05-14,193.67,199.6267,190.1533,199.3333,65228229 +2499,2021-05-17,196.58,197.6667,187.0667,190.6467,63467550 +2500,2021-05-18,193.0467,198.75,187.7933,190.3333,75257196 +2501,2021-05-19,188.56,189.2833,181.6667,186.0033,77524299 +2502,2021-05-20,187.6667,196.3333,186.6333,196.3,64313097 +2503,2021-05-21,196.7667,201.57,192.7933,192.8333,49913517 +2504,2021-05-24,195.0333,204.8267,191.2167,202.5,72762678 +2505,2021-05-25,203.5,204.6633,198.57,202.4267,57594786 +2506,2021-05-26,203,208.7233,200.5,206.3367,59423178 +2507,2021-05-27,205.5433,210.3767,204.47,209.7433,53587350 +2508,2021-05-28,210,211.8633,207.46,208.1667,45708411 +2509,2021-06-01,208.73,211.2667,206.85,207.2333,35538018 +2510,2021-06-02,206.9967,207.9667,199.7133,200.6733,43231854 +2511,2021-06-03,200.3367,201.5167,190,190.7167,57641328 +2512,2021-06-04,191.9333,200.2033,190.4667,200,47932023 +2513,2021-06-07,199.4967,203.3333,194.2933,200,43852587 +2514,2021-06-08,198.6833,209,198.5,200.4833,52664493 +2515,2021-06-09,201.24,203.93,199.0067,199.3333,34338024 +2516,2021-06-10,199.2733,205.53,197.3333,202.6667,49835202 +2517,2021-06-11,203,205.3333,200.5067,203.5,31935483 +2518,2021-06-14,203.9967,208.42,203.06,205.3333,41926515 +2519,2021-06-15,205.81,206.3367,198.6667,198.7667,36347325 +2520,2021-06-16,199.6267,202.8333,197.67,200.8333,44065245 +2521,2021-06-17,200.3033,207.1567,199.6567,205.53,44940105 +2522,2021-06-18,205.6367,209.45,203.5433,206.9833,50973756 +2523,2021-06-21,207.33,210.4633,202.96,207.0833,50577285 +2524,2021-06-22,206.1333,209.5233,205.1667,208.0167,39783501 +2525,2021-06-23,208.3333,221.5467,208.3333,221,63081165 +2526,2021-06-24,221.6667,232.54,219.4033,227.3333,95330490 +2527,2021-06-25,227.3333,231.27,222.6767,223,68989917 +2528,2021-06-28,222.9,231.5667,222.4333,228.8,43411218 +2529,2021-06-29,229.33,229.3333,225.2967,226.67,35486958 +2530,2021-06-30,227,230.9367,224.6667,226.4667,38338683 +2531,2021-07-01,227.1667,229.5733,224.2667,225.3,35654799 +2532,2021-07-02,225.3,233.3333,224.09,225.7,54561240 +2533,2021-07-06,225.4867,228,217.1333,218.7,41297160 +2534,2021-07-07,220,221.9,212.7733,214.6333,37118532 +2535,2021-07-08,210,218.3333,206.82,216.8667,44881728 +2536,2021-07-09,217.5967,220,214.8967,218.5933,34968744 +2537,2021-07-12,219,229.1667,218.9833,229.0033,51243600 +2538,2021-07-13,228.1333,231.58,220.5067,220.8,42033159 +2539,2021-07-14,223.3333,226.2033,217.6,218.2833,46162458 +2540,2021-07-15,219.0633,222.0467,212.6267,216.4,41483562 +2541,2021-07-16,217.5,218.92,213.66,214.0667,31873818 +2542,2021-07-19,213.6467,216.33,207.0967,215.9267,40264497 +2543,2021-07-20,216.6667,220.8,213.5,220.6667,29554182 +2544,2021-07-21,220.6667,221.62,216.7633,218.2333,26824704 +2545,2021-07-22,219.6333,220.7233,214.8667,216.1667,29336946 +2546,2021-07-23,217.3333,217.3367,212.4333,214.44,27217935 +2547,2021-07-26,215.2,226.1167,213.21,221.3867,50556135 +2548,2021-07-27,222.4967,224.7967,209.08,213.0033,64392234 +2549,2021-07-28,214.3,218.3233,213.1333,215.3333,29813055 +2550,2021-07-29,215.66,227.8967,215.66,222.9967,59894136 +2551,2021-07-30,221.8333,232.51,220.99,229.1933,55456236 +2552,2021-08-02,230.7333,242.3133,230.6667,238.33,65648568 +2553,2021-08-03,238.3333,240.8833,233.67,235.6667,42860139 +2554,2021-08-04,237,241.6333,235.5167,237,32493825 +2555,2021-08-05,237.6667,240.3167,236.94,238.2,24828657 +2556,2021-08-06,238.3367,239,232.2833,232.3333,28781466 +2557,2021-08-09,236,239.6767,234.9633,237.9,29672529 +2558,2021-08-10,238.1,238.8633,233.96,236.1667,26595642 +2559,2021-08-11,236.2167,238.3933,234.7367,235.8033,17842452 +2560,2021-08-12,235.3333,242.0033,233.1333,240.1133,34809909 +2561,2021-08-13,239.97,243.3,238.18,238.9067,32477205 +2562,2021-08-16,238.7267,238.7267,226.02,227.2333,42453582 +2563,2021-08-17,226.8,226.8,216.28,221,43246251 +2564,2021-08-18,223.0033,231.9233,222.7767,228.3333,39414696 +2565,2021-08-19,227,228.85,222.53,224.3333,27499356 +2566,2021-08-20,224.6667,230.71,223.6667,226.7667,27058611 +2567,2021-08-23,228,237.3767,226.9167,236.1,40378269 +2568,2021-08-24,236.8,238.4033,234.2133,235.4333,24506721 +2569,2021-08-25,235.5967,238.99,234.6667,237,24902058 +2570,2021-08-26,236.3367,238.4667,232.54,233.3,24901170 +2571,2021-08-27,235,238.3333,234.0333,237.4667,25801872 +2572,2021-08-30,238,245.7833,237.44,244.6667,35205261 +2573,2021-08-31,244.6667,246.78,242.1467,244.6667,41367243 +2574,2021-09-01,245.5667,247.33,243.3333,243.7333,23279241 +2575,2021-09-02,244.33,246.99,242.0033,244.4333,24648756 +2576,2021-09-03,245.7,245.8333,241.4,244.8333,29042418 +2577,2021-09-07,245.12,253.4,245,250.4367,38376276 +2578,2021-09-08,252,254.8167,246.9233,250.5167,37344477 +2579,2021-09-09,250,254.0333,249.0067,251.2833,27285180 +2580,2021-09-10,251.8533,254.2033,243.7233,244.1667,28766106 +2581,2021-09-13,245.4233,248.26,236.3933,247.6667,45762033 +2582,2021-09-14,246.3333,251.49,245.4067,248.5,35848818 +2583,2021-09-15,248.48,252.2867,246.12,251.93,30442302 +2584,2021-09-16,250.6667,252.97,249.2033,251.8333,26342049 +2585,2021-09-17,252.0033,253.68,250,253.04,59345472 +2586,2021-09-20,250,250,239.54,242.9867,44764014 +2587,2021-09-21,247.3333,248.2467,243.48,245.6667,31419141 +2588,2021-09-22,246.37,251.5333,246.3167,251.5333,28690833 +2589,2021-09-23,252.0133,253.2667,249.3067,250.9333,21861891 +2590,2021-09-24,250,258.3333,248.01,257.9167,41849742 +2591,2021-09-27,258,266.3333,256.1633,262.3267,56626173 +2592,2021-09-28,260.48,265.2133,255.3933,258,50707452 +2593,2021-09-29,261.6667,264.5,256.8933,259.9667,42686520 +2594,2021-09-30,261.6667,263.0467,258,258.3767,36607635 +2595,2021-10-01,256.6667,260.6667,254.53,258.3333,33948654 +2596,2021-10-04,261.6833,268.99,257.76,260.5,62392521 +2597,2021-10-05,261.1233,265.77,258.17,260,36630258 +2598,2021-10-06,257.1267,262.22,255.0533,261.2467,28747782 +2599,2021-10-07,262.75,268.3333,260.2633,263.3333,35731074 +2600,2021-10-08,264.5033,266.1133,260.3033,261.7,31890201 +2601,2021-10-11,261.92,267.08,261,264.2,27505347 +2602,2021-10-12,263.68,270.7733,263.32,268.5,40789215 +2603,2021-10-13,270.0067,271.8033,267.9,271.1667,27633120 +2604,2021-10-14,272.3867,273.4167,269.6833,273.2333,21017235 +2605,2021-10-15,273.3333,283.2633,272.09,283,37482756 +2606,2021-10-18,281.15,291.6767,280.3067,290.6667,46397166 +2607,2021-10-19,291.5667,293.3333,287.5033,287.5533,34256370 +2608,2021-10-20,286.7067,291.8,283.8633,283.9333,26102676 +2609,2021-10-21,285.53,300,283.4333,296.2933,63007014 +2610,2021-10-22,297.1667,303.4067,296.9867,303.0833,44809167 +2611,2021-10-25,304.66,348.34,303.3367,343.3333,120727032 +2612,2021-10-26,342.99,364.98,333.8133,337.9667,116972874 +2613,2021-10-27,340.0667,356.96,336.55,353.67,71864214 +2614,2021-10-28,353.6,362.9333,345.9533,360,51902868 +2615,2021-10-29,360,376.5833,357.7333,376.05,58173909 +2616,2021-11-01,377.4,408.2967,372.26,406.4,103645668 +2617,2021-11-02,397.0367,402.8633,375.1033,387,73600182 +2618,2021-11-03,388.5433,406.33,383.55,405.83,62335545 +2619,2021-11-04,407.7333,416.6667,405.6667,407.4,44871267 +2620,2021-11-05,407.41,413.29,402.6667,405.5,38407929 +2621,2021-11-08,383.6667,399,376.8333,383.3367,55734987 +2622,2021-11-09,388.2333,395.9267,337.1733,341.3333,99305115 +2623,2021-11-10,345.1667,366.3333,329.1033,365.3333,72635043 +2624,2021-11-11,364.5733,373.2433,351.56,353.3333,37079193 +2625,2021-11-12,355.11,357.3333,339.88,343.1667,40773651 +2626,2021-11-15,340,345.3367,326.2,334,55007415 +2627,2021-11-16,334.3333,353,332.0033,352.7333,45724431 +2628,2021-11-17,354.47,373.2133,351.8333,362.6667,54335913 +2629,2021-11-18,366.2567,371.6667,358.34,362.4167,38152728 +2630,2021-11-19,367.07,381.4133,363.3333,380,40460397 +2631,2021-11-22,382.8367,400.65,377.4767,387.02,61802889 +2632,2021-11-23,384.9233,393.5,354.2333,366.9333,66676008 +2633,2021-11-24,371.0833,377.59,354,372.5,40844445 +2634,2021-11-26,363.1667,369.5967,357.05,360,20116359 +2635,2021-11-29,368.3333,380.89,364.3367,380.6567,35464650 +2636,2021-11-30,375.9,389.3333,372.3333,381.67,49770600 +2637,2021-12-01,384.6633,390.9467,361.2567,365.9167,40769319 +2638,2021-12-02,369.79,371.9967,352.2167,357.9967,42563499 +2639,2021-12-03,359.9833,366,333.4033,336,52544382 +2640,2021-12-06,342.3267,343.4633,316.8333,336.6667,46148676 +2641,2021-12-07,345.1267,352.9333,336.3367,352.6633,35199075 +2642,2021-12-08,349.8333,357.46,344.3333,354.2433,24624063 +2643,2021-12-09,352.67,357.2133,332.3333,332.5167,36719553 +2644,2021-12-10,333.03,340.6,324.3333,337.5067,34100466 +2645,2021-12-13,339.6767,341.15,317.17,318.3333,42878616 +2646,2021-12-14,320.4233,322.9433,310,317.78,40971606 +2647,2021-12-15,318.4067,331.6333,309.4167,329.6667,42256527 +2648,2021-12-16,331.9233,334.6067,305.5,306.6,44465637 +2649,2021-12-17,306.4933,320.22,301.6667,310.5,59531019 +2650,2021-12-20,303.6667,307.23,297.81,301.0133,31028196 +2651,2021-12-21,304.3567,313.1667,295.3733,310.1333,40021422 +2652,2021-12-22,314.3333,338.5533,312.1333,334.3333,53675220 +2653,2021-12-23,336.4933,357.66,332.52,356.4333,53221719 +2654,2021-12-27,356.9333,372.3333,356.9033,364,39116811 +2655,2021-12-28,368.6033,373,359.4733,364.5,33759246 +2656,2021-12-29,367.6667,371.8733,354.7133,360.6667,33236880 +2657,2021-12-30,362.9967,365.1833,351.05,355.3333,26776320 +2658,2021-12-31,355.3333,360.6667,351.53,354.3,21442167 +2659,2022-01-03,369.9133,403.3333,368.6667,403.3333,59739450 +2660,2022-01-04,400.3267,403.4033,374.35,380,55300041 +2661,2022-01-05,377.3833,390.1133,357.9333,361.1667,45923958 +2662,2022-01-06,362,362.6667,340.1667,358.67,50920653 +2663,2022-01-07,355.57,367,336.6667,342.3,48486174 +2664,2022-01-10,341.0533,357.7833,326.6667,355.93,50742453 +2665,2022-01-11,356.2667,359.7533,346.2733,353,37721568 +2666,2022-01-12,352.9667,371.6133,352.6667,369.6667,47720787 +2667,2022-01-13,368.0867,371.8667,341.9633,341.9633,56243877 +2668,2022-01-14,346.7333,350.6667,332.53,348.6667,40407246 +2669,2022-01-18,344,356.93,338.6867,341.67,37357950 +2670,2022-01-19,341.57,351.5567,329.7,333,41641410 +2671,2022-01-20,337,347.22,327.4,329.9667,40021428 +2672,2022-01-21,331.9567,334.85,311.6667,312,54432708 +2673,2022-01-24,317.2233,317.45,283.8233,303.3333,83257308 +2674,2022-01-25,301.6667,317,298.1067,307.28,47386206 +2675,2022-01-26,313.4,329.23,293.29,309.9667,59069976 +2676,2022-01-27,310.4333,316.46,273.5967,279,78316839 +2677,2022-01-28,279.3033,285.8333,264.0033,284,73422666 +2678,2022-01-31,286.8633,313.3333,283.7,312.6667,60666141 +2679,2022-02-01,315.01,315.6667,301.6667,312.8333,40608771 +2680,2022-02-02,313.3333,315,293.5333,293.6667,37054980 +2681,2022-02-03,296.6733,312.3333,291.76,302.6,45404325 +2682,2022-02-04,302.7033,312.1667,293.7233,308.6667,41669502 +2683,2022-02-07,308.5967,315.9233,300.9,303.17,34018512 +2684,2022-02-08,303.6667,308.7633,298.2667,308,28583517 +2685,2022-02-09,309.3367,315.4233,306.6667,310,30368949 +2686,2022-02-10,309.48,314.6033,298.9,300.0667,37176897 +2687,2022-02-11,299.9967,305.32,283.5667,285.6667,44144829 +2688,2022-02-14,281.3333,299.6267,277.8867,293.3333,38758287 +2689,2022-02-15,299.33,307.6667,297.79,306,32850735 +2690,2022-02-16,306,309.4967,300.4033,306.2667,28010172 +2691,2022-02-17,304.6667,307.03,290.33,290.4033,30422382 +2692,2022-02-18,294.7067,296.0633,279.2033,284,40040778 +2693,2022-02-22,276.5133,285.58,267.0333,277,47556666 +2694,2022-02-23,280,281.5967,249.3333,249.3333,53536245 +2695,2022-02-24,241.2133,267.6667,230.54,263.8333,81729354 +2696,2022-02-25,266.0633,275.5,260.8,270.3667,43164210 +2697,2022-02-28,263.49,292.2867,262.33,290.8867,59203599 +2698,2022-03-01,289.3333,296.6267,283.6667,288.1967,43701348 +2699,2022-03-02,286.6667,295.4933,281.4233,290.2,41124426 +2700,2022-03-03,290,295.4933,272.8333,273.1833,34345506 +2701,2022-03-04,277.0667,285.2167,275.0533,281.3333,39490536 +2702,2022-03-07,276,288.7133,264.4067,266.6633,41203665 +2703,2022-03-08,268.3333,283.33,260.7233,275.5833,47495559 +2704,2022-03-09,278.7133,288.2133,274.8,285.3333,34494873 +2705,2022-03-10,283.3333,284.8167,270.12,277.33,33274095 +2706,2022-03-11,279.6667,285.3333,264.12,264.6433,37045917 +2707,2022-03-14,265.1167,267.69,252.0133,259.8333,39402378 +2708,2022-03-15,256.0667,268.5233,251.6667,267.2833,37676769 +2709,2022-03-16,268.6667,282.6667,267.2967,279.6667,46220172 +2710,2022-03-17,281,291.6667,275.2367,288.5,37029492 +2711,2022-03-18,288.0267,302.6167,287.5033,302.5433,61952121 +2712,2022-03-21,302.3333,314.2833,299.2233,306.09,46753863 +2713,2022-03-22,306.2967,332.62,306.2967,330.7433,62365338 +2714,2022-03-23,331,346.9,325.37,332.85,68725848 +2715,2022-03-24,334.34,341.4967,329.6,336.5067,39163167 +2716,2022-03-25,337.3333,340.6,332.44,337.05,36286704 +2717,2022-03-28,335.3333,365.96,334.0733,365.2667,56465760 +2718,2022-03-29,366.6133,374.8667,357.7033,364.6867,39172281 +2719,2022-03-30,364.3233,371.3167,361.3333,365.2933,33436668 +2720,2022-03-31,367.1933,368.3333,358.3333,358.5,26907888 +2721,2022-04-01,360.0333,364.9167,355.5467,363.6667,29717751 +2722,2022-04-04,364.3333,383.3033,357.51,380,46320690 +2723,2022-04-05,380.5367,384.29,361.45,362.6667,43596441 +2724,2022-04-06,362,364.6633,342.5667,347.6667,50559519 +2725,2022-04-07,351.8133,358.8633,340.5133,355.5,44438853 +2726,2022-04-08,357.67,359.05,340.3433,340.6667,30800952 +2727,2022-04-11,336.51,337,320.6667,320.6667,32727522 +2728,2022-04-12,322.7767,340.4,320.9667,330.5933,38553336 +2729,2022-04-13,333.2267,342.08,324.3633,341,31495641 +2730,2022-04-14,342.0667,343.3433,327.3967,329.8167,32337318 +2731,2022-04-18,329.0833,338.3067,324.47,337.6733,28905387 +2732,2022-04-19,336.06,344.98,331.7733,339.3333,27618669 +2733,2022-04-20,338.4133,348.9967,324.4967,343.7267,37622106 +2734,2022-04-21,343.87,364.0733,332.1367,337.1333,57751845 +2735,2022-04-22,337.1333,344.95,331.3333,333.4333,37934373 +2736,2022-04-25,333.4,336.2067,320.3333,332.7667,37647819 +2737,2022-04-26,330,334.3333,287.1667,291.67,74006871 +2738,2022-04-27,298.3333,306,292.4533,298.6667,38960505 +2739,2022-04-28,300.4967,305,273.9,284.8333,67646268 +2740,2022-04-29,299.6667,311.4667,289.3333,292.5,48944871 +2741,2022-05-02,296.1567,303.25,281.3333,302.3333,42804726 +2742,2022-05-03,301.0067,308.0267,296.1967,302.3333,37183326 +2743,2022-05-04,302.3333,318.5,295.0933,316.02,49005195 +2744,2022-05-05,314.3,316.91,285.9,292.6667,52158030 +2745,2022-05-06,291.9667,296.6267,281.0333,288,41014902 +2746,2022-05-09,284.4133,284.4133,260.3833,262.2333,49423431 +2747,2022-05-10,269.3333,275.12,258.0833,265.9167,48430737 +2748,2022-05-11,271.0133,272.6667,242.4,244.7,53134143 +2749,2022-05-12,243.8633,253.22,226.6667,247,85963638 +2750,2022-05-13,249.6667,262.45,249.6667,258.5667,55949757 +2751,2022-05-16,255,258.09,239.6933,240.74,52901019 +2752,2022-05-17,248.49,254.8267,242.95,253.6833,47844489 +2753,2022-05-18,250.54,253.5,233.3333,233.3333,52252599 +2754,2022-05-19,232.9367,244.6667,229.8333,238.3333,55037787 +2755,2022-05-20,242.5967,243.52,211,221.8333,85888587 +2756,2022-05-23,227.5267,228,212.6867,219,51265281 +2757,2022-05-24,217.8867,219.6667,206.8567,211.3333,52180665 +2758,2022-05-25,212.2567,223.1067,205.81,218.4333,58653768 +2759,2022-05-26,221.76,239.5567,217.8867,237.6667,66064707 +2760,2022-05-27,236.93,255.9667,235.81,255.0833,56435403 +2761,2022-05-31,253.9067,259.6,244.7433,253.23,64379274 +2762,2022-06-01,253.2533,257.3267,243.64,244.6667,47765442 +2763,2022-06-02,248.4833,264.21,242.0667,261.0667,59789013 +2764,2022-06-03,251.3333,260.3333,233.3333,233.43,70047213 +2765,2022-06-06,241.6667,245,234.35,237.8367,52758504 +2766,2022-06-07,236.7667,239.9967,230.0933,238.3333,46067151 +2767,2022-06-08,237.6,249.9633,237.6,242.7667,47875032 +2768,2022-06-09,248.1567,255.5467,239.3267,239.5033,60465090 +2769,2022-06-10,241.3333,244.1833,227.9133,236.4167,60624126 +2770,2022-06-13,229.63,232.33,214.2167,214.4333,61920003 +2771,2022-06-14,221,226.33,211.7367,223.1167,63877368 +2772,2022-06-15,222.6667,235.6633,218.15,235.4133,76913121 +2773,2022-06-16,227.64,231.9967,208.6933,211.8333,65683083 +2774,2022-06-17,215.3333,220.97,211.48,216.1,61196430 +2775,2022-06-21,222.3333,243.58,219.6833,237.5167,79742895 +2776,2022-06-22,229.8633,246.8233,228.3733,234.1833,67988037 +2777,2022-06-23,234.3333,241.1667,228.6367,234.2333,69978438 +2778,2022-06-24,238.25,246.0667,235.5533,245.4667,62441367 +2779,2022-06-27,248.9433,252.07,242.5633,245.27,56900979 +2780,2022-06-28,245.3333,249.97,231.0067,232.3,58576794 +2781,2022-06-29,232.3333,233.3333,222.2733,227.4667,53105913 +2782,2022-06-30,223.3,229.4567,218.8633,224.3333,61716366 +2783,2022-07-01,222,230.23,220.8367,226.4867,48110886 +2784,2022-07-05,228.3,233.9933,216.1667,232.9733,54336840 +2785,2022-07-06,232.9333,234.5633,227.1867,231.6667,45489657 +2786,2022-07-07,233.6333,245.3633,232.21,243.6667,52164897 +2787,2022-07-08,242.7667,259.3333,240.73,256.4667,66933489 +2788,2022-07-11,250.97,254.6,233.6267,234,61863519 +2789,2022-07-12,231.8467,239.7733,228.3667,232.1,56026785 +2790,2022-07-13,232.9,242.06,223.9033,234.6833,62291388 +2791,2022-07-14,236.0467,239.48,229.3333,239.48,50364726 +2792,2022-07-15,237.3333,243.6233,236.4667,239.6633,40794570 +2793,2022-07-18,244.0033,250.5167,239.6033,241.3367,52663089 +2794,2022-07-19,242.1333,247.8967,236.9767,247.1467,51763212 +2795,2022-07-20,247.0633,259.3333,243.48,251.1,54030141 +2796,2022-07-21,251.87,273.2667,249.3333,269.75,86439174 +2797,2022-07-22,269.2767,280.7867,268.6733,271.6667,60837000 +2798,2022-07-25,272.3167,276.5433,266.67,266.8333,39659769 +2799,2022-07-26,267.0967,268,256.2633,262.3333,42541404 +2800,2022-07-27,263.3333,275.9267,258.86,273.58,55620006 +2801,2022-07-28,273.3333,284.5633,271.6667,284.3333,53337165 +2802,2022-07-29,284.1767,298.32,279.1,296.6,58007934 +2803,2022-08-01,296.6667,311.88,293.3333,298,71199081 +2804,2022-08-02,294.1133,307.8333,291.46,301.3333,59609352 +2805,2022-08-03,301.3667,309.55,301.15,307.7467,49034241 +2806,2022-08-04,308.8467,313.6067,305,309.1667,44030208 +2807,2022-08-05,312.2233,312.2233,285.5433,287.3333,67475064 +2808,2022-08-08,294.3333,305.19,289.0833,292.8,59549943 +2809,2022-08-09,295.2467,295.7233,279.3533,283.8,52285851 +2810,2022-08-10,286.2033,297.9867,283.3333,293.3333,57884541 +2811,2022-08-11,295.1367,298.2367,285.8333,288.1,43055865 +2812,2022-08-12,290.3333,301.5667,285.0333,301.3333,49332492 +2813,2022-08-15,298.39,313.1333,297.7367,309.6667,54710223 +2814,2022-08-16,308.5233,314.6667,302.8833,306.4,55540302 +2815,2022-08-17,306,309.6567,300.0333,303,43278504 +2816,2022-08-18,303.0267,307.5033,301.8533,303.1033,28342434 +2817,2022-08-19,301.9767,303.63,292.5,295.2667,37094298 +2818,2022-08-22,291.6667,294.8333,286.2967,290.5833,33285654 +2819,2022-08-23,290,298.8267,287.9233,296.5333,39575148 +2820,2022-08-24,295.76,308.94,295.5,306.6,11374931 +2821,2022-08-25,307.95,307.95,291.6,295.7,37975857 +2822,2022-08-26,296.77,302,284.3,284.5,41690512 +2823,2022-08-29,281.91,288.09,280,285.7,31229778 +2824,2022-08-30,289.38,292.5,272.65,278.12,36111921 +2825,2022-08-31,279.44,281.25,271.81,272.01,36997072 +2826,2022-09-01,271.57,280.34,266.15,279.7,39657641 +2827,2022-09-02,279.1,282.57,269.08,269.3,36972502 +2828,2022-09-06,276.14,276.14,265.74,273.81,39823707 +2829,2022-09-07,274.75,283.95,272.21,283.45,36023268 +2830,2022-09-08,282.87,290,279.78,290,40320418 +2831,2022-09-09,291.82,299.95,289.98,298.4,40244272 +2832,2022-09-12,300,305.49,298.01,304.65,35331535 +2833,2022-09-13,305.04,307,290.4,291.6,47611133 +2834,2022-09-14,292.6,306,289.3,304.25,51667238 +2835,2022-09-15,304.53,309.12,299.5,300.19,48241149 +2836,2022-09-16,299.65,304.01,295.6,303.9,70185787 +2837,2022-09-19,301.23,309.84,297.8,309.44,44466573 +2838,2022-09-20,308.4,313.33,305.58,307.4,46760937 +2839,2022-09-21,306.21,313.8,299,299.3,46208549 +2840,2022-09-22,301.03,304.5,285.82,288.02,50406357 +2841,2022-09-23,287.78,288.03,272.82,275.75,44530343 +2842,2022-09-26,275.33,284.09,269.8,276.4,40779663 +2843,2022-09-27,282.78,288.67,276.7,287.1,45446685 +2844,2022-09-28,281.45,289,274.77,286.3,40051777 +2845,2022-09-29,283,288.53,265.81,269.21,56781305 +2846,2022-09-30,273.8,275.57,262.47,266.05,49037220 +2847,2022-10-03,256.68,260,241.01,243.7,72670646 +2848,2022-10-04,249.43,257.5,242.01,247.7,82343604 +2849,2022-10-05,247.24,248.09,233.27,240.99,65285626 +2850,2022-10-06,241.8,244.58,235.35,236.7,51843790 +2851,2022-10-07,237.83,239.7,221.75,223.8,62463602 +2852,2022-10-10,223.46,226.99,218,223,51669555 +2853,2022-10-11,221.36,225.75,215,215.2,59920745 +2854,2022-10-12,218.4,219.69,211.51,216.8,51834612 +2855,2022-10-13,216.43,222.99,206.22,220.51,70560950 +2856,2022-10-14,223.4,226.26,203.5,204.43,72262028 +2857,2022-10-17,210.32,222.87,204.99,222.75,64099875 +2858,2022-10-18,225.9,229.82,217.25,224.25,61738061 +2859,2022-10-19,222.09,228.29,206.23,208.16,50898030 +2860,2022-10-20,209.74,215.55,202,206.6,92683950 +2861,2022-10-21,206.08,215,203,214.55,58617759 +2862,2022-10-24,213.4,216.66,198.58,208.8,78968509 +2863,2022-10-25,209.5,224.35,208,217.12,79670683 +2864,2022-10-26,219.56,230.6,218.2,226.5,68562598 +2865,2022-10-27,226.5,233.81,217.55,223.38,49680215 +2866,2022-10-28,221,228.86,215,228.35,56109870 +2867,2022-10-31,228.79,229.85,221.94,227.59,49891734 +2868,2022-11-01,229.19,237.4,226.51,227,49775576 +2869,2022-11-02,229,229.37,213.44,215.87,49853305 +2870,2022-11-03,216.74,221.2,210.14,214.48,44646949 +2871,2022-11-04,220.79,223.8,203.08,209.05,80308864 +2872,2022-11-07,210.6,210.6,196.5,197.3,73397622 +2873,2022-11-08,198.58,198.93,186.75,190,105514188 +2874,2022-11-09,194,195.89,175.51,176.5,102644299 +2875,2022-11-10,178.69,193.64,172.01,191.47,110460759 +2876,2022-11-11,194.48,196.52,182.59,195.65,95853553 +2877,2022-11-14,195.04,195.95,186.34,191.25,77319752 +2878,2022-11-15,194.53,200.83,191.42,193.3,74960504 +2879,2022-11-16,196.22,196.67,184.05,187.8,54096082 +2880,2022-11-17,189.18,189.18,180.9,183.62,52118517 +2881,2022-11-18,183,185.83,176.55,179.3,61891438 +2882,2022-11-21,178.6,179.66,167.54,167.83,73810772 +2883,2022-11-22,167.67,171.35,165.38,170.42,64763513 +2884,2022-11-23,173.11,184.88,170.51,184.8,90934248 +2885,2022-11-25,186.07,188.5,180.63,182.89,41660711 +2886,2022-11-28,181.59,188.5,178,183.9,78408629 +2887,2022-11-29,185.11,186.88,178.75,180.4,68205280 +2888,2022-11-30,182.42,196.6,180.63,195.9,92743086 +2889,2022-12-01,194.24,198.92,191.8,193.93,65844119 +2890,2022-12-02,194.07,196.9,189.55,194.2,60902399 +2891,2022-12-05,192.95,194.3,180.55,182.55,75912778 +2892,2022-12-06,182.89,183.82,175.33,179.05,76040783 +2893,2022-12-07,179.33,179.69,172.21,173.42,69718106 +2894,2022-12-08,174.14,175.7,169.06,173.45,80762690 +2895,2022-12-09,174.92,182.5,172.3,178.5,88081017 +2896,2022-12-12,178.45,179.56,167.52,168.02,90494485 +2897,2022-12-13,169.66,179.14,156.91,161.3,135812432 +2898,2022-12-14,161.75,162.25,155.31,156.9,113815160 +2899,2022-12-15,155.75,160.93,151.33,158.72,101035229 +2900,2022-12-16,156.46,160.99,149,149.06,113741284 +2901,2022-12-19,156.57,158.2,145.82,150.53,118190710 +2902,2022-12-20,148,151.57,137.37,139.07,131775303 +2903,2022-12-21,141,141.5,135.91,138.37,123736453 +2904,2022-12-22,138.5,139.48,122.26,126.85,177342265 +2905,2022-12-23,127.07,128.62,121.02,122.2,141626063 +2906,2022-12-27,123.88,125,106.6,106.69,175910731 +2907,2022-12-28,107.84,116.27,104.22,114,186100201 +2908,2022-12-29,115,123.57,114.47,122.84,189503721 +2909,2022-12-30,122.46,124.48,118.51,123.5,136672797 +2910,2023-01-03,120.02,121.9,104.64,107,191557167 +2911,2023-01-04,108.88,114.59,107.28,113.66,153862552 +2912,2023-01-05,112.5,114.87,107.16,110.35,133687246 +2913,2023-01-06,107.69,114.39,101.2,113.68,184006970 +2914,2023-01-09,114.03,123.52,113.75,119.55,162885492 +2915,2023-01-10,120.6,122.76,115,118.66,144503095 +2916,2023-01-11,118.63,125.95,118.23,123.19,158558924 +2917,2023-01-12,123.22,124.6,117,123,145833294 +2918,2023-01-13,118,123,115.6,122.03,157396482 +2919,2023-01-17,122,132.3,120.6,131.3,160937377 +2920,2023-01-18,132.16,137.5,126.6,126.72,169078250 +2921,2023-01-19,127.47,129.99,124.3,128.36,152223302 +2922,2023-01-20,128.36,133.85,127.34,133.85,123571951 +2923,2023-01-23,133.87,145.39,133.5,144.8,177044569 +2924,2023-01-24,146,146.5,140.64,140.97,140230986 +2925,2023-01-25,142.47,153,138.07,152.35,166419849 +2926,2023-01-26,153.43,161.42,152.35,158.95,200431932 +2927,2023-01-27,159.89,180.68,158,178.99,263157488 +2928,2023-01-30,178.5,180,165.77,165.77,196790466 +2929,2023-01-31,165.89,174.3,162.78,171.82,172099948 +2930,2023-02-01,173.22,184.84,169.97,184.33,187082506 +2931,2023-02-02,185.11,196.76,182.61,184.06,186940474 +2932,2023-02-03,183.47,199,182,192.77,199115506 +2933,2023-02-06,192.91,198.17,189.1,195.14,161365866 +2934,2023-02-07,195.38,197.8,189.55,196.19,162102866 +2935,2023-02-08,196.2,203,194.31,202.49,155395535 +2936,2023-02-09,205,214,201.29,204,181049895 +2937,2023-02-10,206.01,206.73,192.92,194.58,172846466 +2938,2023-02-13,194.54,199.5,187.61,195.62,147807152 +2939,2023-02-14,195.5,212,189.44,211.5,185629204 +2940,2023-02-15,209,216.21,206.11,215.91,152835862 +2941,2023-02-16,216.6,217.82,196.74,198.23,195125412 +2942,2023-02-17,199,209.77,197.5,209,183119234 +2943,2023-02-21,205.95,209.71,195.8,197.35,151695722 +2944,2023-02-22,198.94,203,191.83,202.4,167116119 +2945,2023-02-23,203.45,205.13,196.33,200.43,126002008 +2946,2023-02-24,198.1,201.33,192.8,196.48,121759004 +2947,2023-02-27,198,209.42,195.68,209.09,135811509 +2948,2023-02-28,208.08,212.6,203.75,204.7,129887964 +2949,2023-03-01,207.66,209.05,189,191.3,135485305 +2950,2023-03-02,191.4,193.75,185.42,190.85,154029003 +2951,2023-03-03,191.96,200.48,190.8,198.3,132018423 +2952,2023-03-06,198.45,199.6,192.3,193.03,111186290 +2953,2023-03-07,194.11,194.68,186.1,188.12,127160413 +2954,2023-03-08,187.45,188.2,180,180.62,130599496 +2955,2023-03-09,179.28,185.18,169.65,169.9,142783264 +2956,2023-03-10,171.84,178.29,168.44,174.47,163214327 +2957,2023-03-13,178,179.25,164,174.4,141125454 +2958,2023-03-14,174.72,184.49,173.8,184.15,124651497 +2959,2023-03-15,184.5,185.66,176.03,180.54,124829688 +2960,2023-03-16,180.99,185.81,178.84,183.86,103701677 +2961,2023-03-17,184.14,186.22,177.33,179.05,113188518 +2962,2023-03-20,176.45,186.44,176.29,183.31,111938751 +2963,2023-03-21,184.56,198,183.42,197.5,129806598 +2964,2023-03-22,197.6,200.66,189.8,192.36,127873104 +2965,2023-03-23,194.3,199.31,188.65,192.9,122801841 +2966,2023-03-24,194,194.28,187.15,190.23,100588036 +2967,2023-03-27,190.23,197.39,189.6,192.96,105008001 +2968,2023-03-28,192.36,193.95,185.43,189.65,85183670 +2969,2023-03-29,191.27,195.29,189.44,192.78,107927597 +2970,2023-03-30,194.66,197.33,193.12,195.35,94431494 +2971,2023-03-31,195.35,208,195.15,207.65,146669747 +2972,2023-04-03,204,206.8,192.2,193.2,141493469 +2973,2023-04-04,194.51,198.75,190.32,192.75,105533822 +2974,2023-04-05,192.35,194,183.76,184.19,112676921 +2975,2023-04-06,184.81,187.2,179.83,185,105769070 +2976,2023-04-10,183.56,185.9,176.11,184.4,123177931 +2977,2023-04-11,184.51,189.19,184.15,186.6,100721415 +2978,2023-04-12,186.29,191.59,179.75,179.9,131472591 +2979,2023-04-13,181.25,186.5,180.33,185.95,99401779 +2980,2023-04-14,185.36,186.57,182.01,185,84119837 diff --git a/package-lock.json b/package-lock.json index 5cfb1e24..d15b44b3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4504,9 +4504,15 @@ "license": "MIT" }, "node_modules/vite": { +<<<<<<< Updated upstream "version": "6.2.1", "resolved": "https://registry.npmjs.org/vite/-/vite-6.2.1.tgz", "integrity": "sha512-n2GnqDb6XPhlt9B8olZPrgMD/es/Nd1RdChF6CBD/fHW6pUyUTt2sQW2fPRX5GiD9XEa6+8A6A4f2vT6pSsE7Q==", +======= + "version": "6.2.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.2.5.tgz", + "integrity": "sha512-j023J/hCAa4pRIUH6J9HemwYfjB5llR2Ps0CWeikOtdR8+pAURAk0DoJC5/mm9kd+UgdnIy7d6HE4EAvlYhPhA==", +>>>>>>> Stashed changes "dev": true, "dependencies": { "esbuild": "^0.25.0", @@ -7420,9 +7426,15 @@ "dev": true }, "vite": { +<<<<<<< Updated upstream "version": "6.2.1", "resolved": "https://registry.npmjs.org/vite/-/vite-6.2.1.tgz", "integrity": "sha512-n2GnqDb6XPhlt9B8olZPrgMD/es/Nd1RdChF6CBD/fHW6pUyUTt2sQW2fPRX5GiD9XEa6+8A6A4f2vT6pSsE7Q==", +======= + "version": "6.2.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.2.5.tgz", + "integrity": "sha512-j023J/hCAa4pRIUH6J9HemwYfjB5llR2Ps0CWeikOtdR8+pAURAk0DoJC5/mm9kd+UgdnIy7d6HE4EAvlYhPhA==", +>>>>>>> Stashed changes "dev": true, "requires": { "esbuild": "^0.25.0", diff --git a/run.py b/run.py new file mode 100644 index 00000000..403b5a0d --- /dev/null +++ b/run.py @@ -0,0 +1,54 @@ +import datetime as dt +import yfinance as yf +from lightweight_charts import Chart +import pandas as pd +from time import sleep # ✅ Fix: Needed for sleep() + +def get_bar_data(chart, symbol, timeframe): + # Determine the start date based on the timeframe + if timeframe in ('1m', '5m', '30m'): + days = 7 if timeframe == '1m' else 60 + start_date = (dt.datetime.now() - dt.timedelta(days=days)).strftime('%Y-%m-%d') + else: + start_date = None + + chart.spinner(True) + + # Download the data + data = yf.download(symbol, start=start_date, interval=timeframe) + + chart.spinner(False) + + if data.empty: + return False + + # Set the chart data + chart.set(data) + return True + +def on_search(chart, searched_string): + if get_bar_data(chart, searched_string, chart.topbar['timeframe'].value): + chart.topbar['symbol'].set(searched_string) + +def on_timeframe_selection(chart): + get_bar_data(chart, chart.topbar['symbol'].value, chart.topbar['timeframe'].value) + +if __name__ == '__main__': + data = pd.read_csv('./ohlcv.csv') + midpoint = data.shape[0] // 2 + df1 = data.iloc[:midpoint] + df2 = data.iloc[midpoint+1:] + + # ✅ Initialize the chart first + chart = Chart(toolbox=True, debug=True) + chart.legend(True) + chart.set(df1) + + chart.events.search += on_search + + + chart.show(block=False) + + for _, tick in df2.iterrows(): + chart.update(tick) + sleep(0.2) diff --git a/src/general/scripts/Symbols.json b/scripts/Symbols.json similarity index 100% rename from src/general/scripts/Symbols.json rename to scripts/Symbols.json diff --git a/src/general/scripts/cache.json b/scripts/cache.json similarity index 100% rename from src/general/scripts/cache.json rename to scripts/cache.json diff --git a/setup.py b/setup.py index e2d0fc98..3e12681a 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setup( name='lightweight_charts', - version='2.1', + version='3.0.1', packages=find_packages(), python_requires='>=3.8', install_requires=[ diff --git a/src/general/handler.ts b/src/general/handler.ts index 4a5cddf6..847a4ce2 100644 --- a/src/general/handler.ts +++ b/src/general/handler.ts @@ -748,11 +748,7 @@ createSymbolSeries( } - //toJSON() { - // // Exclude the chart attribute from serialization - // const { chart, ...serialized } = this; - // return serialized; - //} + /** * Extracts data from a series in a format suitable for indicators. * @param series - The series to extract data from. diff --git a/src/trend-trace/trend-trace.ts b/src/trend-trace/trend-trace.ts index dc0d90fa..2e4b041e 100644 --- a/src/trend-trace/trend-trace.ts +++ b/src/trend-trace/trend-trace.ts @@ -933,7 +933,7 @@ export class TrendTracePaneRenderer const candleBodyWidth = (this._options.barSpacing??0.8)*(singleWidth ); const candleGap = singleWidth -candleBodyWidth const offset = .5 - let leftSide = bar.scaledX1-(0.5*singleWidth) + let leftSide = bar.scaledX1 let rightSide = leftSide + ((bar.x2 - bar.x1 + ((this._options.chandelierSize??1) > 1? 1: 0))* singleWidth) - candleGap if (index < bars.length - 1 && bars[index+1].scaledX1) { const nextBar = bars[index + 1]; From 492884712043a0a4b7b06a1e4a0475d42c12b251 Mon Sep 17 00:00:00 2001 From: EsIstJosh Date: Fri, 18 Apr 2025 02:56:44 -0700 Subject: [PATCH 2/7] add python method for symbol series --- lightweight_charts/abstract.py | 152 ++++++++++++++++++++++++++++----- 1 file changed, 133 insertions(+), 19 deletions(-) diff --git a/lightweight_charts/abstract.py b/lightweight_charts/abstract.py index 7e5a980c..9151d72e 100644 --- a/lightweight_charts/abstract.py +++ b/lightweight_charts/abstract.py @@ -1,4 +1,4 @@ -import asyncio +-import asyncio import json import os from base64 import b64decode @@ -491,19 +491,6 @@ def __init__( }} ) null''') - # if round: - # start_time = self._single_datetime_format(start_time) - # end_time = self._single_datetime_format(end_time) - # else: - # start_time, end_time = pd.to_datetime((start_time, end_time)).astype('int64') // 10 ** 9 - - # self.run_script(f''' - # {self._chart.id}.chart.timeScale().applyOptions({{shiftVisibleRangeOnNewBar: false}}) - # {self.id}.series.setData( - # calculateTrendLine({start_time}, {start_value}, {end_time}, {end_value}, - # {self._chart.id}, {jbool(ray)})) - # {self._chart.id}.chart.timeScale().applyOptions({{shiftVisibleRangeOnNewBar: true}}) - # ''') def delete(self): """ @@ -522,6 +509,100 @@ def delete(self): delete {self.id}legendItem delete {self.id} ''') +class Symbols(SeriesCommon): + """ + Represents a custom Symbol series, compatible with the createSymbolSeries JS method. + """ + + SYMBOL_MAP = { + 'circle': '●', + 'circles': '●', + 'cross': '✚', + 'triangleUp': '▲', + 'triangleDown': '▼', + 'arrowUp': '↑', + 'arrowDown': '↓' + } + + def __init__( + self, + chart, + name: str, + color: str, + shape: str, + group: str, + legend_symbol: str = None, + price_scale_id: str = None, + crosshair_marker: bool = True, + price_line: bool = False, + price_label: bool = False, + ): + """ + Initializes a Symbol series with configuration options. + + :param chart: The parent chart instance. + :param name: Series title. + :param color: Color of symbols. + :param shape: Shape of the symbols (circle, cross, triangleUp, triangleDown, arrowUp, arrowDown). + :param group: Legend group identifier. + :param legend_symbol: Optional custom legend symbol; defaults to mapped shape symbol. + :param price_scale_id: Optional price scale ID. + :param crosshair_marker: Whether to display crosshair markers. + :param price_line: Whether to display the price line. + :param price_label: Whether to display the price label. + """ + super().__init__(chart, name) + self.color = color + self.group = group + self.shape = shape + self.legend_symbol = legend_symbol or self.SYMBOL_MAP.get(shape, shape) + + self.run_script(f''' + {self.id} = {self._chart.id}.createSymbolSeries( + "{name}", + {{ + group: '{group}', + color: '{color}', + shape: '{shape}', + crosshairMarkerVisible: {str(crosshair_marker).lower()}, + priceLineVisible: {str(price_line).lower()}, + lastValueVisible: {str(price_label).lower()}, + legendSymbol: '{self.legend_symbol}', + priceScaleId: {f'"{price_scale_id}"' if price_scale_id else 'undefined'} + {"""autoscaleInfoProvider: () => ({ + priceRange: { + minValue: 1_000_000_000, + maxValue: 0, + }, + }),""" if chart._scale_candles_only else ''} + }} + ); + null; + ''') + + def delete(self): + """ + Irreversibly deletes the symbol series, removing it from the chart and legend. + """ + if self in self._chart._lines: + self._chart._lines.remove(self) + + self.run_script(f''' + const legendItem = {self._chart.id}.legend._lines.find( + (line) => line.series === {self.id}.series + ); + + if (legendItem) {{ + {self._chart.id}.legend.div.removeChild(legendItem.row); + {self._chart.id}.legend._lines = {self._chart.id}.legend._lines.filter( + (item) => item !== legendItem + ); + }} + + {self._chart.id}.chart.removeSeries({self.id}.series); + delete legendItem; + delete {self.id}; + ''') class Histogram(SeriesCommon): @@ -1108,11 +1189,7 @@ def _get_time_or_last_bar(self, time: Optional[Any]) -> str: return self._convert_time(last_bar_time) - -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', +-bool = True, position: FLOAT = 'left', defaults: str = '../../src/general/defaults', scripts: str = '../../src/general/scripts'): Pane.__init__(self, window) Candlestick.__init__(self, self) @@ -1283,6 +1360,43 @@ def create_line( )) return self._lines[-1] + + def create_symbols( + self, + name: str, + color: str = 'rgba(214, 237, 255, 0.6)', + shape: str = 'circle', + group: str = '', + legend_symbol: str = '', + price_scale_id: Optional[str] = None, + crosshair_marker: bool = True, + price_line: bool = False, + price_label: bool = False + ) -> Symbols: + """ + Creates and returns a Symbols series object. + """ + + symbol_map = { + 'circle': '●', + 'circles': '●', + 'cross': '✚', + 'triangleUp': '▲', + 'triangleDown': '▼', + 'arrowUp': '↑', + 'arrowDown': '↓' + } + + if legend_symbol == '': + legend_symbol = symbol_map.get(shape, shape) + + symbols_series = Symbols( + self, name, color, shape, group, legend_symbol, price_scale_id, + crosshair_marker, price_line, price_label + ) + self._lines.append(symbols_series) + return symbols_series + def create_histogram( self, name: str = '', From 36d13b225e18f5451b50156d2c090ab471f10fde Mon Sep 17 00:00:00 2001 From: EsIstJosh Date: Fri, 18 Apr 2025 02:58:41 -0700 Subject: [PATCH 3/7] update --- setup.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 3e12681a..a408fe48 100644 --- a/setup.py +++ b/setup.py @@ -5,11 +5,12 @@ setup( name='lightweight_charts', - version='3.0.1', + version='3.0.2', packages=find_packages(), python_requires='>=3.8', install_requires=[ 'pandas', + 'yfinance', 'pywebview>=5.0.5', ], package_data={ From 48688dcf0dfea65de0c2a7b8ce9ac8266478c019 Mon Sep 17 00:00:00 2001 From: EsIstJosh Date: Fri, 18 Apr 2025 03:16:55 -0700 Subject: [PATCH 4/7] fix --- lightweight_charts/abstract.py | 16 +++++++++------- run.py | 25 +++++++++++++++++++++++-- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/lightweight_charts/abstract.py b/lightweight_charts/abstract.py index 9151d72e..defc7c6a 100644 --- a/lightweight_charts/abstract.py +++ b/lightweight_charts/abstract.py @@ -1,4 +1,4 @@ --import asyncio +import asyncio import json import os from base64 import b64decode @@ -1189,11 +1189,13 @@ def _get_time_or_last_bar(self, time: Optional[Any]) -> str: return self._convert_time(last_bar_time) --bool = True, position: FLOAT = 'left', +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'): Pane.__init__(self, window) Candlestick.__init__(self, self) - self._lines = [] self._scale_candles_only = scale_candles_only self._width = width @@ -1278,7 +1280,7 @@ def _save_defaults(self, key: str, options: str) -> None: def set_scripts(self, scripts_dir: str) -> None: """ Load and apply JSON scripts from directory to the scriptsManager. - """ + """lob/dev/run.py for root, _, files in os.walk(scripts_dir): for filename in files: if filename.endswith('.json'): @@ -1329,7 +1331,7 @@ def create_line( self, name: str = '', color: str = 'rgba(214, 237, 255, 0.6)', - style: LINE_STYLE = 'solid', + style: LINE_STYLE = 'solid', lob/dev/run.py width: int = 2, price_line: bool = True, price_label: bool = True, @@ -1361,11 +1363,11 @@ def create_line( return self._lines[-1] - def create_symbols( + def create_symbol( self, name: str, color: str = 'rgba(214, 237, 255, 0.6)', - shape: str = 'circle', + shape: str = '*', group: str = '', legend_symbol: str = '', price_scale_id: Optional[str] = None, diff --git a/run.py b/run.py index 403b5a0d..19f0733c 100644 --- a/run.py +++ b/run.py @@ -34,21 +34,42 @@ def on_timeframe_selection(chart): get_bar_data(chart, chart.topbar['symbol'].value, chart.topbar['timeframe'].value) if __name__ == '__main__': + import pandas as pd + from time import sleep + data = pd.read_csv('./ohlcv.csv') + + # ✅ Add 'HL' (average of High and Low) + data['HL'] = (data['high'] + data['low']) / 2 + + # Split data into two parts midpoint = data.shape[0] // 2 df1 = data.iloc[:midpoint] df2 = data.iloc[midpoint+1:] - # ✅ Initialize the chart first + # ✅ Initialize the chart chart = Chart(toolbox=True, debug=True) chart.legend(True) chart.set(df1) - chart.events.search += on_search + # ✅ Create symbol series with HL values from df1 + symbol_df = df1[['time', 'HL']].copy() + symbol_df.rename(columns={'HL': 'value'}, inplace=True) + symbols_series = chart.create_symbols(name="Symbols", shape='circle', color='#ffffff') + symbols_series.set(symbol_df) + chart.events.search += on_search chart.show(block=False) + # ✅ Update chart + symbol series on each tick for _, tick in df2.iterrows(): chart.update(tick) + + if not pd.isna(tick['HL']): + symbols_series.update({ + 'time': tick['time'], + 'value': tick['HL'] + }) + sleep(0.2) From 34fbb120656c7f88734d2f50820b778b3a126007 Mon Sep 17 00:00:00 2001 From: EsIstJosh Date: Fri, 18 Apr 2025 03:18:32 -0700 Subject: [PATCH 5/7] fix --- lightweight_charts/abstract.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lightweight_charts/abstract.py b/lightweight_charts/abstract.py index defc7c6a..e57114e7 100644 --- a/lightweight_charts/abstract.py +++ b/lightweight_charts/abstract.py @@ -1280,7 +1280,7 @@ def _save_defaults(self, key: str, options: str) -> None: def set_scripts(self, scripts_dir: str) -> None: """ Load and apply JSON scripts from directory to the scriptsManager. - """lob/dev/run.py + """ for root, _, files in os.walk(scripts_dir): for filename in files: if filename.endswith('.json'): From 198ad0d256d3f12faef7574418d44c5ab3664eaf Mon Sep 17 00:00:00 2001 From: EsIstJosh Date: Fri, 18 Apr 2025 03:19:26 -0700 Subject: [PATCH 6/7] f --- lightweight_charts/abstract.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lightweight_charts/abstract.py b/lightweight_charts/abstract.py index e57114e7..ce56e408 100644 --- a/lightweight_charts/abstract.py +++ b/lightweight_charts/abstract.py @@ -1331,7 +1331,7 @@ def create_line( self, name: str = '', color: str = 'rgba(214, 237, 255, 0.6)', - style: LINE_STYLE = 'solid', lob/dev/run.py + style: LINE_STYLE = 'solid', width: int = 2, price_line: bool = True, price_label: bool = True, From 189389760709c1653dfb830591550b20f00d2f12 Mon Sep 17 00:00:00 2001 From: EsIstJosh Date: Fri, 18 Apr 2025 03:53:09 -0700 Subject: [PATCH 7/7] fix --- lightweight_charts/abstract.py | 2 +- lightweight_charts/js/bundle.js | 4 ++-- run.py | 23 +++++++---------------- 3 files changed, 10 insertions(+), 19 deletions(-) diff --git a/lightweight_charts/abstract.py b/lightweight_charts/abstract.py index ce56e408..751a1ae7 100644 --- a/lightweight_charts/abstract.py +++ b/lightweight_charts/abstract.py @@ -556,7 +556,7 @@ def __init__( self.group = group self.shape = shape self.legend_symbol = legend_symbol or self.SYMBOL_MAP.get(shape, shape) - + self.name = name self.run_script(f''' {self.id} = {self._chart.id}.createSymbolSeries( "{name}", diff --git a/lightweight_charts/js/bundle.js b/lightweight_charts/js/bundle.js index 4acc766d..7a4d62d7 100644 --- a/lightweight_charts/js/bundle.js +++ b/lightweight_charts/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){const t=e.match(/rgba?\(([^)]+)\)/i),i=e.match(/hsla?\(([^)]+)\)/i);let s=1;if(t){const e=t[1].split(",").map((e=>parseFloat(e.trim())));4===e.length&&(s=e[3])}else if(i){const e=i[1].split(",").map((e=>parseFloat(e.trim())));4===e.length&&(s=e[3])}return s}function p(e,t,i=""){for(const s of Object.keys(e)){const n=i?`${i}.${s}`:s,o=e[s];"object"==typeof o&&null!==o?p(o,t,n):s.toLowerCase().includes("color")&&t(n,o)}}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===h(t)&&0===h(i)),r.appendChild(a);const c=document.createElement("span");c.innerText=e,Object.assign(c.style,{minWidth:"60px"}),r.appendChild(c);const p=document.createElement("div");Object.assign(p.style,{display:"flex",gap:"8px"}),r.appendChild(p);let d=t,u=i;e in this._originalOpacities||(this._originalOpacities[e]={up:h(t)??1,down:h(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}),p.appendChild(m),p.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??h(t)),u=l(u,this._originalOpacities[e].down??h(i)),m.style.border="1px solid #999",g.style.border="1px solid #999"):(this._originalOpacities[e].up=h(d),this._originalOpacities[e].down=h(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===h(d)&&0===h(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),p(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")&&p({[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=h(t),n=h(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); //# sourceMappingURL=bundle.js.map diff --git a/run.py b/run.py index 19f0733c..1ab0cc1e 100644 --- a/run.py +++ b/run.py @@ -2,10 +2,9 @@ import yfinance as yf from lightweight_charts import Chart import pandas as pd -from time import sleep # ✅ Fix: Needed for sleep() +from time import sleep def get_bar_data(chart, symbol, timeframe): - # Determine the start date based on the timeframe if timeframe in ('1m', '5m', '30m'): days = 7 if timeframe == '1m' else 60 start_date = (dt.datetime.now() - dt.timedelta(days=days)).strftime('%Y-%m-%d') @@ -14,7 +13,6 @@ def get_bar_data(chart, symbol, timeframe): chart.spinner(True) - # Download the data data = yf.download(symbol, start=start_date, interval=timeframe) chart.spinner(False) @@ -22,7 +20,6 @@ def get_bar_data(chart, symbol, timeframe): if data.empty: return False - # Set the chart data chart.set(data) return True @@ -39,37 +36,31 @@ def on_timeframe_selection(chart): data = pd.read_csv('./ohlcv.csv') - # ✅ Add 'HL' (average of High and Low) data['HL'] = (data['high'] + data['low']) / 2 - # Split data into two parts midpoint = data.shape[0] // 2 df1 = data.iloc[:midpoint] df2 = data.iloc[midpoint+1:] - # ✅ Initialize the chart chart = Chart(toolbox=True, debug=True) chart.legend(True) chart.set(df1) - # ✅ Create symbol series with HL values from df1 symbol_df = df1[['time', 'HL']].copy() - symbol_df.rename(columns={'HL': 'value'}, inplace=True) - symbols_series = chart.create_symbols(name="Symbols", shape='circle', color='#ffffff') + symbols_series = chart.create_symbol(name="HL", shape='―', color='#ffffff') symbols_series.set(symbol_df) chart.events.search += on_search chart.show(block=False) - - # ✅ Update chart + symbol series on each tick for _, tick in df2.iterrows(): chart.update(tick) if not pd.isna(tick['HL']): - symbols_series.update({ - 'time': tick['time'], - 'value': tick['HL'] - }) + symbols_series.update(pd.Series( + {'time': tick['time'], 'value': tick['HL']}, + name=tick['time'] + )) sleep(0.2) +