@tradecanvas/chart 2.6.0 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/Chart.d.ts +11 -0
- package/dist/Chart.d.ts.map +1 -1
- package/dist/{LayoutSession-D8TcwPy1.js → LayoutSession-BJLUwx9d.js} +436 -424
- package/dist/LayoutSession-BJLUwx9d.js.map +1 -0
- package/dist/{LayoutSession-DDs1N5h2.cjs → LayoutSession-DiKwrEV8.cjs} +2 -2
- package/dist/LayoutSession-DiKwrEV8.cjs.map +1 -0
- package/dist/{WidgetCommandPalette-B1jLC9oE.js → WidgetCommandPalette-CSIKnTca.js} +2 -2
- package/dist/{WidgetCommandPalette-B1jLC9oE.js.map → WidgetCommandPalette-CSIKnTca.js.map} +1 -1
- package/dist/{WidgetCommandPalette-Cx-UQ9ft.cjs → WidgetCommandPalette-CZ3GhE1O.cjs} +2 -2
- package/dist/{WidgetCommandPalette-Cx-UQ9ft.cjs.map → WidgetCommandPalette-CZ3GhE1O.cjs.map} +1 -1
- package/dist/{WidgetDrawingSettings-ezbzlGqD.js → WidgetDrawingSettings-Cc8PeqEZ.js} +2 -2
- package/dist/{WidgetDrawingSettings-ezbzlGqD.js.map → WidgetDrawingSettings-Cc8PeqEZ.js.map} +1 -1
- package/dist/{WidgetDrawingSettings-BjPR5Wyq.cjs → WidgetDrawingSettings-DutEdVyV.cjs} +2 -2
- package/dist/{WidgetDrawingSettings-BjPR5Wyq.cjs.map → WidgetDrawingSettings-DutEdVyV.cjs.map} +1 -1
- package/dist/{WidgetIndicatorPicker-eK03W3LR.js → WidgetIndicatorPicker-DNjcuBp6.js} +2 -2
- package/dist/{WidgetIndicatorPicker-eK03W3LR.js.map → WidgetIndicatorPicker-DNjcuBp6.js.map} +1 -1
- package/dist/{WidgetIndicatorPicker-DKxoB4Un.cjs → WidgetIndicatorPicker-GCesxFMn.cjs} +2 -2
- package/dist/{WidgetIndicatorPicker-DKxoB4Un.cjs.map → WidgetIndicatorPicker-GCesxFMn.cjs.map} +1 -1
- package/dist/{WidgetIndicatorSettings-Da_T6bmX.cjs → WidgetIndicatorSettings-CBHWj5z5.cjs} +2 -2
- package/dist/{WidgetIndicatorSettings-Da_T6bmX.cjs.map → WidgetIndicatorSettings-CBHWj5z5.cjs.map} +1 -1
- package/dist/{WidgetIndicatorSettings-DR8Z9RfF.js → WidgetIndicatorSettings-XhHlqyvn.js} +3 -3
- package/dist/{WidgetIndicatorSettings-DR8Z9RfF.js.map → WidgetIndicatorSettings-XhHlqyvn.js.map} +1 -1
- package/dist/{WidgetSettings-DCGCymVY.js → WidgetSettings-B1ay0W6I.js} +3 -3
- package/dist/{WidgetSettings-DCGCymVY.js.map → WidgetSettings-B1ay0W6I.js.map} +1 -1
- package/dist/{WidgetSettings-COljE3G_.cjs → WidgetSettings-CBf6hUSV.cjs} +2 -2
- package/dist/{WidgetSettings-COljE3G_.cjs.map → WidgetSettings-CBf6hUSV.cjs.map} +1 -1
- package/dist/{WidgetSymbolSearch-Dnkh_y4h.js → WidgetSymbolSearch-BlQWH3Md.js} +2 -2
- package/dist/{WidgetSymbolSearch-Dnkh_y4h.js.map → WidgetSymbolSearch-BlQWH3Md.js.map} +1 -1
- package/dist/{WidgetSymbolSearch-C_yw9mLo.cjs → WidgetSymbolSearch-CxeLjy63.cjs} +2 -2
- package/dist/{WidgetSymbolSearch-C_yw9mLo.cjs.map → WidgetSymbolSearch-CxeLjy63.cjs.map} +1 -1
- package/dist/i18n-BFGknfTa.cjs +2 -0
- package/dist/i18n-BFGknfTa.cjs.map +1 -0
- package/dist/{i18n-DWLKoOBG.js → i18n-BZdkj80c.js} +7 -1
- package/dist/i18n-BZdkj80c.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/{indicatorInputWords-VWMPRfzM.js → indicatorInputWords-B8lf8reQ.js} +2 -2
- package/dist/{indicatorInputWords-VWMPRfzM.js.map → indicatorInputWords-B8lf8reQ.js.map} +1 -1
- package/dist/{indicatorInputWords-C4Mefhve.cjs → indicatorInputWords-_kxwKob4.cjs} +2 -2
- package/dist/{indicatorInputWords-C4Mefhve.cjs.map → indicatorInputWords-_kxwKob4.cjs.map} +1 -1
- package/dist/widget/WidgetObjectTree.d.ts.map +1 -1
- package/dist/widget/index.cjs +3 -3
- package/dist/widget/index.cjs.map +1 -1
- package/dist/widget/index.js +13 -10
- package/dist/widget/index.js.map +1 -1
- package/dist/widget/locales/ar.d.ts.map +1 -1
- package/dist/widget/locales/cs.d.ts.map +1 -1
- package/dist/widget/locales/da.d.ts.map +1 -1
- package/dist/widget/locales/de.d.ts.map +1 -1
- package/dist/widget/locales/el.d.ts.map +1 -1
- package/dist/widget/locales/en.d.ts +3 -0
- package/dist/widget/locales/en.d.ts.map +1 -1
- package/dist/widget/locales/es.d.ts.map +1 -1
- package/dist/widget/locales/et.d.ts.map +1 -1
- package/dist/widget/locales/fa.d.ts.map +1 -1
- package/dist/widget/locales/fr.d.ts.map +1 -1
- package/dist/widget/locales/he.d.ts.map +1 -1
- package/dist/widget/locales/hu.d.ts.map +1 -1
- package/dist/widget/locales/id.d.ts.map +1 -1
- package/dist/widget/locales/index.cjs +1 -1
- package/dist/widget/locales/index.cjs.map +1 -1
- package/dist/widget/locales/index.js +85 -1
- package/dist/widget/locales/index.js.map +1 -1
- package/dist/widget/locales/it.d.ts.map +1 -1
- package/dist/widget/locales/ja.d.ts.map +1 -1
- package/dist/widget/locales/ko.d.ts.map +1 -1
- package/dist/widget/locales/ms.d.ts.map +1 -1
- package/dist/widget/locales/nb.d.ts.map +1 -1
- package/dist/widget/locales/nl.d.ts.map +1 -1
- package/dist/widget/locales/pl.d.ts.map +1 -1
- package/dist/widget/locales/pt.d.ts.map +1 -1
- package/dist/widget/locales/ro.d.ts.map +1 -1
- package/dist/widget/locales/ru.d.ts.map +1 -1
- package/dist/widget/locales/sk.d.ts.map +1 -1
- package/dist/widget/locales/sv.d.ts.map +1 -1
- package/dist/widget/locales/th.d.ts.map +1 -1
- package/dist/widget/locales/tr.d.ts.map +1 -1
- package/dist/widget/locales/vi.d.ts.map +1 -1
- package/dist/widget/locales/zh.d.ts.map +1 -1
- package/dist/widget/locales/zhHant.d.ts.map +1 -1
- package/dist/widget/widgetConfig.d.ts.map +1 -1
- package/dist/widgetLocales-BdRQu8wS.cjs +2 -0
- package/dist/widgetLocales-BdRQu8wS.cjs.map +1 -0
- package/dist/{widgetLocales-BX7VRdl5.js → widgetLocales-Bgm5-BB5.js} +13 -1
- package/dist/widgetLocales-Bgm5-BB5.js.map +1 -0
- package/package.json +3 -3
- package/dist/LayoutSession-D8TcwPy1.js.map +0 -1
- package/dist/LayoutSession-DDs1N5h2.cjs.map +0 -1
- package/dist/i18n-DWLKoOBG.js.map +0 -1
- package/dist/i18n-fgAwciRT.cjs +0 -2
- package/dist/i18n-fgAwciRT.cjs.map +0 -1
- package/dist/widgetLocales-BX7VRdl5.js.map +0 -1
- package/dist/widgetLocales-C_XTkni5.cjs +0 -2
- package/dist/widgetLocales-C_XTkni5.cjs.map +0 -1
package/dist/widget/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../LayoutSession-DDs1N5h2.cjs`),t=require(`../widgetLocales-C_XTkni5.cjs`),n=require(`../monthView-B-CieFDJ.cjs`),r=require(`../widgetFeatures-DpBWfQ8D.cjs`),i=require(`../focusTrap-DrhhmG0V.cjs`),a=require(`../symbolCatalog-CXqRu23x.cjs`),o=require(`../settingsControls-Tn8_vJJv.cjs`),s=require(`../i18n-fgAwciRT.cjs`),c=require(`../indicatorInputWords-C4Mefhve.cjs`),l=require(`../platformKeys-B82-j1Fs.cjs`);let u=require(`@tradecanvas/commons`),d=require(`@tradecanvas/core`);function f(e,t,n={}){return(0,u.resampleBars)(e,t,{weekStartsOn:n.weekStartsOn??1,timeZone:n.timeZone})}function p(e){if(e.length<2)return 0;let t=[];for(let n=1;n<e.length;n++){let r=e[n].time-e[n-1].time;r>0&&t.push(r)}return t.length===0?0:(t.sort((e,t)=>e-t),t[Math.floor(t.length/2)])}var m=6,h=8,g=120;function _(e,t,n=`left`){let r=e.style,i=t.getBoundingClientRect();r.position=`fixed`,r.margin=`0`,r.top=r.bottom=r.left=r.right=``;let a=window.innerHeight-i.bottom-m-h,o=i.top-m-h;e.scrollHeight<=a||a>=o?(r.top=`${i.bottom+m}px`,r.bottom=`auto`,r.maxHeight=`${Math.max(g,a)}px`):(r.top=`auto`,r.bottom=`${window.innerHeight-i.top+m}px`,r.maxHeight=`${Math.max(g,o)}px`);let s=getComputedStyle(t).direction===`rtl`,c=n===`right`!==s,l=e.offsetWidth,u=c?i.right-l:i.left;r.left=`${Math.max(h,Math.min(u,window.innerWidth-l-h))}px`}var v=700,y=class{select=null;panel=null;rows=[];active=-1;typed=``;typedAt=0;onOutside=e=>{let t=e.target;this.panel?.contains(t)||this.select?.contains(t)||this.close(!1)};onAway=()=>this.close(!1);onScroll=e=>{e.target instanceof Node&&this.panel?.contains(e.target)||this.close(!1)};watch=new MutationObserver(()=>{this.select&&!this.select.isConnected&&this.close(!1)});constructor(e){this.layer=e}isOpenFor(e){return this.select===e}owns(e){return e!==null&&(e===this.select||this.panel?.contains(e)===!0)}open(e){this.close(!1),this.select=e;let t=document.createElement(`div`);t.className=`tcw-dropdown tcw-select-menu`,t.setAttribute(`role`,`listbox`),t.id=`tcw-select-menu-${Math.random().toString(36).slice(2,9)}`;let n=e.getAttribute(`aria-label`)??e.labels?.[0]?.textContent??``;n&&t.setAttribute(`aria-label`,n.trim()),t.style.minWidth=`${e.getBoundingClientRect().width}px`,this.rows=[];for(let n of e.children)if(n instanceof HTMLOptGroupElement){let e=document.createElement(`div`);e.className=`tcw-select-group`,e.textContent=n.label,t.appendChild(e);for(let e of n.querySelectorAll(`option`))this.addRow(t,e,n.disabled)}else n instanceof HTMLOptionElement&&this.addRow(t,n,!1);t.addEventListener(`mousedown`,e=>e.preventDefault());let r=e=>this.rows.findIndex(t=>t.el.contains(e.target));t.addEventListener(`click`,e=>{let t=r(e);t>=0&&this.pick(t)}),t.addEventListener(`mousemove`,e=>{let t=r(e);t>=0&&t!==this.active&&this.enabled(t)&&this.setActive(t,!1)}),this.layer().appendChild(t),this.panel=t,_(t,e),e.setAttribute(`aria-expanded`,`true`),e.setAttribute(`aria-controls`,t.id),this.setActive(this.rows.findIndex(e=>e.option.selected)),document.addEventListener(`pointerdown`,this.onOutside,!0),window.addEventListener(`resize`,this.onAway),document.addEventListener(`scroll`,this.onScroll,{capture:!0,passive:!0}),this.watch.observe(document.documentElement,{childList:!0,subtree:!0})}close(e){let t=this.select;t&&(document.removeEventListener(`pointerdown`,this.onOutside,!0),window.removeEventListener(`resize`,this.onAway),document.removeEventListener(`scroll`,this.onScroll,{capture:!0}),this.watch.disconnect(),this.panel?.remove(),this.panel=null,this.rows=[],this.select=null,t.setAttribute(`aria-expanded`,`false`),t.removeAttribute(`aria-controls`),t.removeAttribute(`aria-activedescendant`),e&&t.isConnected&&t.focus())}key(e){if(!this.select)return!1;switch(e.key){case`ArrowDown`:return this.step(1),!0;case`ArrowUp`:return this.step(-1),!0;case`Home`:return this.setActive(this.nextEnabled(-1,1)),!0;case`End`:return this.setActive(this.nextEnabled(this.rows.length,-1)),!0;case`PageDown`:return this.step(8),!0;case`PageUp`:return this.step(-8),!0;case` `:return this.typed&&Date.now()-this.typedAt<=v?(this.typeahead(` `),!0):(this.active>=0?this.pick(this.active):this.close(!0),!0);case`Enter`:return this.active>=0?this.pick(this.active):this.close(!0),!0;case`Escape`:return this.close(!0),!0;case`Tab`:return this.close(!1),!1;default:return e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey?(this.typeahead(e.key),!0):!1}}destroy(){this.close(!1)}addRow(e,t,n){let r=document.createElement(`div`);r.className=`tcw-select-option`,r.id=`${e.id}-${this.rows.length}`,r.setAttribute(`role`,`option`),r.setAttribute(`aria-selected`,String(t.selected)),(t.disabled||n)&&r.setAttribute(`aria-disabled`,`true`);let i=document.createElement(`span`);i.className=`tcw-select-option-text`,i.textContent=t.label||t.textContent||``,t.dir&&(i.dir=t.dir);let a=document.createElement(`span`);a.className=`tcw-select-check`,a.setAttribute(`aria-hidden`,`true`),r.append(a,i),e.appendChild(r),this.rows.push({option:t,el:r})}enabled(e){return this.rows[e]?.el.getAttribute(`aria-disabled`)!==`true`}nextEnabled(e,t){for(let n=e+t;n>=0&&n<this.rows.length;n+=t)if(this.enabled(n))return n;return-1}step(e){let t=e>0?1:-1,n=this.active;for(let r=0;r<Math.abs(e);r++){let e=this.nextEnabled(n,t);if(e<0)break;n=e}n>=0&&this.setActive(n)}setActive(e,t=!0){this.rows[this.active]?.el.classList.remove(`tcw-active`),this.active=e;let n=this.rows[e];n&&(n.el.classList.add(`tcw-active`),this.select?.setAttribute(`aria-activedescendant`,n.el.id),t&&n.el.scrollIntoView?.({block:`nearest`}))}typeahead(e){let t=Date.now();this.typed=t-this.typedAt>v?e.toLowerCase():this.typed+e.toLowerCase(),this.typedAt=t;let n=e=>this.enabled(e)&&(this.rows[e].el.textContent??``).trim().toLowerCase().startsWith(this.typed),r=this.typed.length===1?this.active+1:Math.max(0,this.active);for(let e=0;e<this.rows.length;e++){let t=(r+e)%this.rows.length;if(n(t)){this.setActive(t);return}}}pick(e){let t=this.select,n=this.rows[e];if(!t||!n||!this.enabled(e))return;let r=!n.option.selected;n.option.selected=!0,this.close(!0),r&&(t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0})))}},ee=class{input=null;view=null;onOutside=e=>{let t=e.target;this.view?.element.contains(t)||this.input?.contains(t)||this.close(!1)};onAway=()=>this.close(!1);onScroll=e=>{e.target instanceof Node&&this.view?.element.contains(e.target)||this.close(!1)};watch=new MutationObserver(()=>{this.input&&!this.input.isConnected&&this.close(!1)});constructor(e,t,n){this.layer=e,this.labels=t,this.locale=n}isOpenFor(e){return this.input===e}owns(e){return e!==null&&(e===this.input||this.view?.element.contains(e)===!0)}open(e){this.close(!1),this.input=e;let t=new n.t(this.labels(),this.locale(),e=>this.pick(e));t.show(e.value,{min:e.min||void 0,max:e.max||void 0});let r=t.element;r.setAttribute(`role`,`dialog`);let i=e.getAttribute(`aria-label`)??e.labels?.[0]?.textContent??``;i&&r.setAttribute(`aria-label`,i.trim()),r.addEventListener(`mousedown`,e=>{e.target.closest(`button`)||e.preventDefault()}),r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Escape`&&(e.preventDefault(),this.close(!0))}),this.view=t,this.layer().appendChild(r),_(r,e),document.addEventListener(`pointerdown`,this.onOutside,!0),window.addEventListener(`resize`,this.onAway),document.addEventListener(`scroll`,this.onScroll,{capture:!0,passive:!0}),this.watch.observe(document.documentElement,{childList:!0,subtree:!0})}close(e){let t=this.input;t&&(document.removeEventListener(`pointerdown`,this.onOutside,!0),window.removeEventListener(`resize`,this.onAway),document.removeEventListener(`scroll`,this.onScroll,{capture:!0}),this.watch.disconnect(),this.view?.element.remove(),this.view=null,this.input=null,e&&t.isConnected&&t.focus())}focusGrid(){this.view?.focusGrid()}destroy(){this.close(!1)}pick(e){let t=this.input;if(!t)return;let n=t.value!==e;t.value=e,this.close(!0),n&&(t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0})))}},te=()=>typeof matchMedia==`function`&&matchMedia(`(pointer: coarse)`).matches,ne=()=>typeof CSS>`u`||typeof CSS.supports!=`function`||CSS.supports(`selector(::-webkit-calendar-picker-indicator)`);function re(e){if(!(e instanceof Element))return null;let t=e.closest(`select`);return!t||t.matches(`:disabled`)||t.multiple||t.size>1?null:t}function ie(e){return!(e instanceof HTMLInputElement)||e.type!==`date`||e.dataset.tcwCalendar===`inline`||e.matches(`:disabled`)||e.readOnly?null:e}function ae(e,t){let n=new y(t.layer),r=new ee(t.layer,t.labels,t.locale),i=t.native??te,a=t.calendar??ne,o=new WeakSet,s=e=>o.has(e)?!1:(o.add(e),!0),c=e=>{if(e.button!==0||i()||!s(e))return;let t=re(e.target);if(t){if(e.preventDefault(),n.isOpenFor(t)){n.close(!0);return}t.focus(),n.open(t)}},l=e=>{if(i()||!a()||!s(e))return;let t=ie(e.target);t&&(e.preventDefault(),r.isOpenFor(t)||r.open(t))},u=e=>{if(i()||!s(e))return;let t=re(e.target);if(t){if(n.isOpenFor(t)){n.key(e)&&(e.preventDefault(),e.stopPropagation());return}(e.key===`Enter`||e.key===` `||e.altKey&&(e.key===`ArrowDown`||e.key===`ArrowUp`)||e.key===`F4`)&&(e.preventDefault(),e.stopPropagation(),n.open(t));return}let o=ie(e.target);!o||!a()||(e.key===`Escape`&&r.isOpenFor(o)?(e.preventDefault(),e.stopPropagation(),r.close(!0)):(e.altKey&&e.key===`ArrowDown`||e.key===`F4`)&&(e.preventDefault(),r.isOpenFor(o)||r.open(o),r.focusGrid()))},d=e=>{if(!s(e))return;let t=e.target instanceof Node?e.target:null,i=e.relatedTarget instanceof Node?e.relatedTarget:null;n.owns(t)&&!n.owns(i)&&n.close(!1),r.owns(t)&&!r.owns(i)&&r.close(!1)};for(let t of e)t.addEventListener(`mousedown`,c,!0),t.addEventListener(`click`,l,!0),t.addEventListener(`keydown`,u,!0),t.addEventListener(`focusout`,d,!0);return()=>{for(let t of e)t.removeEventListener(`mousedown`,c,!0),t.removeEventListener(`click`,l,!0),t.removeEventListener(`keydown`,u,!0),t.removeEventListener(`focusout`,d,!0);n.destroy(),r.destroy()}}var oe=`/* === TradeCanvas Widget — Premium Styles === */
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../LayoutSession-DiKwrEV8.cjs`),t=require(`../widgetLocales-BdRQu8wS.cjs`),n=require(`../monthView-B-CieFDJ.cjs`),r=require(`../widgetFeatures-DpBWfQ8D.cjs`),i=require(`../focusTrap-DrhhmG0V.cjs`),a=require(`../symbolCatalog-CXqRu23x.cjs`),o=require(`../settingsControls-Tn8_vJJv.cjs`),s=require(`../i18n-BFGknfTa.cjs`),c=require(`../indicatorInputWords-_kxwKob4.cjs`),l=require(`../platformKeys-B82-j1Fs.cjs`);let u=require(`@tradecanvas/commons`),d=require(`@tradecanvas/core`);function f(e,t,n={}){return(0,u.resampleBars)(e,t,{weekStartsOn:n.weekStartsOn??1,timeZone:n.timeZone})}function p(e){if(e.length<2)return 0;let t=[];for(let n=1;n<e.length;n++){let r=e[n].time-e[n-1].time;r>0&&t.push(r)}return t.length===0?0:(t.sort((e,t)=>e-t),t[Math.floor(t.length/2)])}var m=6,h=8,g=120;function _(e,t,n=`left`){let r=e.style,i=t.getBoundingClientRect();r.position=`fixed`,r.margin=`0`,r.top=r.bottom=r.left=r.right=``;let a=window.innerHeight-i.bottom-m-h,o=i.top-m-h;e.scrollHeight<=a||a>=o?(r.top=`${i.bottom+m}px`,r.bottom=`auto`,r.maxHeight=`${Math.max(g,a)}px`):(r.top=`auto`,r.bottom=`${window.innerHeight-i.top+m}px`,r.maxHeight=`${Math.max(g,o)}px`);let s=getComputedStyle(t).direction===`rtl`,c=n===`right`!==s,l=e.offsetWidth,u=c?i.right-l:i.left;r.left=`${Math.max(h,Math.min(u,window.innerWidth-l-h))}px`}var v=700,y=class{select=null;panel=null;rows=[];active=-1;typed=``;typedAt=0;onOutside=e=>{let t=e.target;this.panel?.contains(t)||this.select?.contains(t)||this.close(!1)};onAway=()=>this.close(!1);onScroll=e=>{e.target instanceof Node&&this.panel?.contains(e.target)||this.close(!1)};watch=new MutationObserver(()=>{this.select&&!this.select.isConnected&&this.close(!1)});constructor(e){this.layer=e}isOpenFor(e){return this.select===e}owns(e){return e!==null&&(e===this.select||this.panel?.contains(e)===!0)}open(e){this.close(!1),this.select=e;let t=document.createElement(`div`);t.className=`tcw-dropdown tcw-select-menu`,t.setAttribute(`role`,`listbox`),t.id=`tcw-select-menu-${Math.random().toString(36).slice(2,9)}`;let n=e.getAttribute(`aria-label`)??e.labels?.[0]?.textContent??``;n&&t.setAttribute(`aria-label`,n.trim()),t.style.minWidth=`${e.getBoundingClientRect().width}px`,this.rows=[];for(let n of e.children)if(n instanceof HTMLOptGroupElement){let e=document.createElement(`div`);e.className=`tcw-select-group`,e.textContent=n.label,t.appendChild(e);for(let e of n.querySelectorAll(`option`))this.addRow(t,e,n.disabled)}else n instanceof HTMLOptionElement&&this.addRow(t,n,!1);t.addEventListener(`mousedown`,e=>e.preventDefault());let r=e=>this.rows.findIndex(t=>t.el.contains(e.target));t.addEventListener(`click`,e=>{let t=r(e);t>=0&&this.pick(t)}),t.addEventListener(`mousemove`,e=>{let t=r(e);t>=0&&t!==this.active&&this.enabled(t)&&this.setActive(t,!1)}),this.layer().appendChild(t),this.panel=t,_(t,e),e.setAttribute(`aria-expanded`,`true`),e.setAttribute(`aria-controls`,t.id),this.setActive(this.rows.findIndex(e=>e.option.selected)),document.addEventListener(`pointerdown`,this.onOutside,!0),window.addEventListener(`resize`,this.onAway),document.addEventListener(`scroll`,this.onScroll,{capture:!0,passive:!0}),this.watch.observe(document.documentElement,{childList:!0,subtree:!0})}close(e){let t=this.select;t&&(document.removeEventListener(`pointerdown`,this.onOutside,!0),window.removeEventListener(`resize`,this.onAway),document.removeEventListener(`scroll`,this.onScroll,{capture:!0}),this.watch.disconnect(),this.panel?.remove(),this.panel=null,this.rows=[],this.select=null,t.setAttribute(`aria-expanded`,`false`),t.removeAttribute(`aria-controls`),t.removeAttribute(`aria-activedescendant`),e&&t.isConnected&&t.focus())}key(e){if(!this.select)return!1;switch(e.key){case`ArrowDown`:return this.step(1),!0;case`ArrowUp`:return this.step(-1),!0;case`Home`:return this.setActive(this.nextEnabled(-1,1)),!0;case`End`:return this.setActive(this.nextEnabled(this.rows.length,-1)),!0;case`PageDown`:return this.step(8),!0;case`PageUp`:return this.step(-8),!0;case` `:return this.typed&&Date.now()-this.typedAt<=v?(this.typeahead(` `),!0):(this.active>=0?this.pick(this.active):this.close(!0),!0);case`Enter`:return this.active>=0?this.pick(this.active):this.close(!0),!0;case`Escape`:return this.close(!0),!0;case`Tab`:return this.close(!1),!1;default:return e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey?(this.typeahead(e.key),!0):!1}}destroy(){this.close(!1)}addRow(e,t,n){let r=document.createElement(`div`);r.className=`tcw-select-option`,r.id=`${e.id}-${this.rows.length}`,r.setAttribute(`role`,`option`),r.setAttribute(`aria-selected`,String(t.selected)),(t.disabled||n)&&r.setAttribute(`aria-disabled`,`true`);let i=document.createElement(`span`);i.className=`tcw-select-option-text`,i.textContent=t.label||t.textContent||``,t.dir&&(i.dir=t.dir);let a=document.createElement(`span`);a.className=`tcw-select-check`,a.setAttribute(`aria-hidden`,`true`),r.append(a,i),e.appendChild(r),this.rows.push({option:t,el:r})}enabled(e){return this.rows[e]?.el.getAttribute(`aria-disabled`)!==`true`}nextEnabled(e,t){for(let n=e+t;n>=0&&n<this.rows.length;n+=t)if(this.enabled(n))return n;return-1}step(e){let t=e>0?1:-1,n=this.active;for(let r=0;r<Math.abs(e);r++){let e=this.nextEnabled(n,t);if(e<0)break;n=e}n>=0&&this.setActive(n)}setActive(e,t=!0){this.rows[this.active]?.el.classList.remove(`tcw-active`),this.active=e;let n=this.rows[e];n&&(n.el.classList.add(`tcw-active`),this.select?.setAttribute(`aria-activedescendant`,n.el.id),t&&n.el.scrollIntoView?.({block:`nearest`}))}typeahead(e){let t=Date.now();this.typed=t-this.typedAt>v?e.toLowerCase():this.typed+e.toLowerCase(),this.typedAt=t;let n=e=>this.enabled(e)&&(this.rows[e].el.textContent??``).trim().toLowerCase().startsWith(this.typed),r=this.typed.length===1?this.active+1:Math.max(0,this.active);for(let e=0;e<this.rows.length;e++){let t=(r+e)%this.rows.length;if(n(t)){this.setActive(t);return}}}pick(e){let t=this.select,n=this.rows[e];if(!t||!n||!this.enabled(e))return;let r=!n.option.selected;n.option.selected=!0,this.close(!0),r&&(t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0})))}},ee=class{input=null;view=null;onOutside=e=>{let t=e.target;this.view?.element.contains(t)||this.input?.contains(t)||this.close(!1)};onAway=()=>this.close(!1);onScroll=e=>{e.target instanceof Node&&this.view?.element.contains(e.target)||this.close(!1)};watch=new MutationObserver(()=>{this.input&&!this.input.isConnected&&this.close(!1)});constructor(e,t,n){this.layer=e,this.labels=t,this.locale=n}isOpenFor(e){return this.input===e}owns(e){return e!==null&&(e===this.input||this.view?.element.contains(e)===!0)}open(e){this.close(!1),this.input=e;let t=new n.t(this.labels(),this.locale(),e=>this.pick(e));t.show(e.value,{min:e.min||void 0,max:e.max||void 0});let r=t.element;r.setAttribute(`role`,`dialog`);let i=e.getAttribute(`aria-label`)??e.labels?.[0]?.textContent??``;i&&r.setAttribute(`aria-label`,i.trim()),r.addEventListener(`mousedown`,e=>{e.target.closest(`button`)||e.preventDefault()}),r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Escape`&&(e.preventDefault(),this.close(!0))}),this.view=t,this.layer().appendChild(r),_(r,e),document.addEventListener(`pointerdown`,this.onOutside,!0),window.addEventListener(`resize`,this.onAway),document.addEventListener(`scroll`,this.onScroll,{capture:!0,passive:!0}),this.watch.observe(document.documentElement,{childList:!0,subtree:!0})}close(e){let t=this.input;t&&(document.removeEventListener(`pointerdown`,this.onOutside,!0),window.removeEventListener(`resize`,this.onAway),document.removeEventListener(`scroll`,this.onScroll,{capture:!0}),this.watch.disconnect(),this.view?.element.remove(),this.view=null,this.input=null,e&&t.isConnected&&t.focus())}focusGrid(){this.view?.focusGrid()}destroy(){this.close(!1)}pick(e){let t=this.input;if(!t)return;let n=t.value!==e;t.value=e,this.close(!0),n&&(t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0})))}},te=()=>typeof matchMedia==`function`&&matchMedia(`(pointer: coarse)`).matches,ne=()=>typeof CSS>`u`||typeof CSS.supports!=`function`||CSS.supports(`selector(::-webkit-calendar-picker-indicator)`);function re(e){if(!(e instanceof Element))return null;let t=e.closest(`select`);return!t||t.matches(`:disabled`)||t.multiple||t.size>1?null:t}function ie(e){return!(e instanceof HTMLInputElement)||e.type!==`date`||e.dataset.tcwCalendar===`inline`||e.matches(`:disabled`)||e.readOnly?null:e}function ae(e,t){let n=new y(t.layer),r=new ee(t.layer,t.labels,t.locale),i=t.native??te,a=t.calendar??ne,o=new WeakSet,s=e=>o.has(e)?!1:(o.add(e),!0),c=e=>{if(e.button!==0||i()||!s(e))return;let t=re(e.target);if(t){if(e.preventDefault(),n.isOpenFor(t)){n.close(!0);return}t.focus(),n.open(t)}},l=e=>{if(i()||!a()||!s(e))return;let t=ie(e.target);t&&(e.preventDefault(),r.isOpenFor(t)||r.open(t))},u=e=>{if(i()||!s(e))return;let t=re(e.target);if(t){if(n.isOpenFor(t)){n.key(e)&&(e.preventDefault(),e.stopPropagation());return}(e.key===`Enter`||e.key===` `||e.altKey&&(e.key===`ArrowDown`||e.key===`ArrowUp`)||e.key===`F4`)&&(e.preventDefault(),e.stopPropagation(),n.open(t));return}let o=ie(e.target);!o||!a()||(e.key===`Escape`&&r.isOpenFor(o)?(e.preventDefault(),e.stopPropagation(),r.close(!0)):(e.altKey&&e.key===`ArrowDown`||e.key===`F4`)&&(e.preventDefault(),r.isOpenFor(o)||r.open(o),r.focusGrid()))},d=e=>{if(!s(e))return;let t=e.target instanceof Node?e.target:null,i=e.relatedTarget instanceof Node?e.relatedTarget:null;n.owns(t)&&!n.owns(i)&&n.close(!1),r.owns(t)&&!r.owns(i)&&r.close(!1)};for(let t of e)t.addEventListener(`mousedown`,c,!0),t.addEventListener(`click`,l,!0),t.addEventListener(`keydown`,u,!0),t.addEventListener(`focusout`,d,!0);return()=>{for(let t of e)t.removeEventListener(`mousedown`,c,!0),t.removeEventListener(`click`,l,!0),t.removeEventListener(`keydown`,u,!0),t.removeEventListener(`focusout`,d,!0);n.destroy(),r.destroy()}}var oe=`/* === TradeCanvas Widget — Premium Styles === */
|
|
2
2
|
|
|
3
3
|
/*
|
|
4
4
|
* The HTML \`hidden\` attribute only sets \`display: none\` via the UA stylesheet,
|
|
@@ -7952,8 +7952,8 @@ ${r.f()}`,document.head.insertBefore(e,document.head.firstChild)}function pe(){i
|
|
|
7952
7952
|
<button type="button" class="tcw-replay-text-btn" data-act="cancel" data-mode="select" ${t}>${a.u(e.cancel)}</button>
|
|
7953
7953
|
</span>
|
|
7954
7954
|
<span class="tcw-visually-hidden" role="status" aria-live="polite" data-tcw="announce" ${t}></span>
|
|
7955
|
-
`}stepMarkup(){let e=this.labels;if(this.steps.length<=1)return``;let t=this.steps.map(e=>`<option value="${a.u(e.value)}"${e.value===this.step?` selected`:``}>${a.u(e.label)}</option>`).join(``);return`<label class="tcw-replay-chip"><span class="tcw-replay-chip-label" dir="${this.dir}">${a.u(e.step)}</span><select class="tcw-replay-speed tcw-replay-step" data-act="step" dir="ltr">${t}</select></label>`}wireStep(){(this.root?.querySelector(`[data-act="step"]`))?.addEventListener(`change`,e=>{this.step=e.target.value,this.callbacks.onStepChange?.(this.step)})}wireEvents(){let e=this.root;if(!e)return;this.hintText=e.querySelector(`[data-tcw="hint"]`),this.scrubber=e.querySelector(`input[data-act="seek"]`),this.timeLabel=e.querySelector(`[data-tcw="time"]`),this.playBtn=e.querySelector(`button[data-act="play"]`),this.realtimeBtn=e.querySelector(`button[data-act="realtime"]`),this.liveRegion=e.querySelector(`[data-tcw="announce"]`);let t=(t,n)=>e.querySelector(`[data-act="${t}"]`)?.addEventListener(`click`,n);t(`realtime`,()=>this.callbacks.onClose()),t(`random`,()=>this.callbacks.onRandomStart()),t(`stepBack`,()=>this.callbacks.onStepBack()),t(`stepForward`,()=>this.callbacks.onStepForward()),t(`selectBar`,()=>this.callbacks.onSelectBar?.()),t(`cancel`,()=>(this.callbacks.onCancelPick??this.callbacks.onClose)()),t(`play`,()=>this.togglePlay()),this.scrubber?.addEventListener(`input`,()=>this.callbacks.onSeek(Number(this.scrubber.value))),e.querySelector(`[data-act="speed"]`)?.addEventListener(`change`,e=>{let t=Number(e.target.value);this.rate=t,this.callbacks.onSpeedChange(t)}),e.addEventListener(`keydown`,this.onKeydown),this.wireStep()}togglePlay(){this.state===`playing`?this.callbacks.onPause():this.callbacks.onPlay()}onKeydown=e=>{if(e.key!==` `||this.mode!==`replay`||e.defaultPrevented)return;let t=e.target;t!==this.scrubber&&t!==this.root||(e.preventDefault(),e.stopPropagation(),this.playBtn?.disabled||this.togglePlay())};announce(e){this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=setTimeout(()=>{this.announceTimer=null,this.liveRegion&&(this.liveRegion.textContent=e)},Rt)}syncUi(){let e=this.root;if(e){for(let t of e.querySelectorAll(`[data-mode]`))t.hidden=t.dataset.mode!==this.mode;if(e.dataset.mode=this.mode,e.classList.toggle(`tcw-replay-bar--ended`,this.ended),this.syncPending(e),this.playBtn){let e=this.state===`playing`;this.playBtn.innerHTML=i.i(e?`pause`:`play`,14),this.playBtn.title=e?this.labels.pause:this.labels.play,this.playBtn.setAttribute(`aria-label`,this.playBtn.title);let t=this.ended&&!e;t&&document.activeElement===this.playBtn&&this.realtimeBtn?.focus(),this.playBtn.disabled=t}}}syncPending(e){for(let t of e.querySelectorAll(`.tcw-replay-group`))this.pending?t.setAttribute(`aria-busy`,`true`):t.removeAttribute(`aria-busy`);this.hintText&&(this.hintText.textContent=this.pending?this.labels.loading:this.labels.selectHint);for(let t of Bt){let n=e.querySelector(`[data-act="${t}"]`);n&&(n.disabled=this.pending)}}},Ht=864e5,Ut=6e4,Wt=1e3,Gt=150,Kt=5e3,qt=8,Jt=class{replayBar=null;replayPollInterval=null;replaySpeed=1;replayBarsTotal=null;replayStepTime=null;replayStepsKey=null;replayStep=`auto`;replayStartSeq=0;replayPickTime=null;replayStartPending=!1;replayPlayWanted=!1;replayStepsCache=null;replayShade=null;constructor(e){this.host=e,this.replayStep=e.options.replayStep??`auto`}get chart(){return this.host.chart()}get root(){return this.host.root}get chartContainer(){return this.host.chartContainer}get t(){return this.host.t}isOpen(){return this.replayBar?.isMounted()??!1}attach(){this.chart.on(`barClick`,e=>{if(!this.replayBar?.isMounted())return;let{barIndex:t,bar:n}=e.payload;if(typeof t==`number`){if(this.seriesPending()){let e=n?.time??this.chart.getData()[t]?.time;this.replayBar.getMode()===`select`&&typeof e==`number`&&(this.replayPickTime=e);return}if(this.replayBar.getMode()===`select`){this.startReplayAt(t,!1,!0);return}this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeekToBar(t),this.replayBar.setState(`paused`)}}),this.chart.on(`crosshairMove`,e=>{if(this.replayBar?.getMode()!==`select`||!this.replayBar.isMounted())return;let t=e.payload.point;this.positionReplayShade(this.seriesPending()?null:t?.x??null)}),this.chart.on(`replayStep`,e=>{let t=e.payload;this.replayBarsTotal=t.total,this.replayStepTime=typeof t.stepTime==`number`?t.stepTime:t.time,queueMicrotask(()=>{this.host.isDestroyed()||(t.cause===`series`?this.afterReplayCarryOver():this.syncReplayBar())})});for(let e of[`resize`,`paneResize`,`paneChange`])this.chart.on(e,()=>this.layoutReplayBar());this.chart.on(`replayStepsLoad`,e=>{e.payload.state===`error`&&this.host.say(this.t(`replay.stepsFailed`),`error`)}),this.chart.on(`timeframeChange`,()=>this.refreshReplaySteps())}destroy(){this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayShade?.remove(),this.replayBar?.destroy()}toggleReplay(){this.replayBar?.isMounted()?this.exitReplay():this.host.isOn()&&this.enterReplay()}enterReplay(){if(this.replayTotal()<2)return;let e=this.t;this.replayBar=new Vt({onPlay:()=>{if(this.replayBar?.getMode()===`select`){this.seriesPending()||this.startReplayAt(Math.max(1,this.replayTotal()-100),!0);return}this.replayStartPending?this.replayPlayWanted=!0:this.chart.getReplayState()===`paused`&&this.chart.replayResume(),this.syncReplayBar()},onPause:()=>{this.replayPlayWanted=!1,this.chart.replayPause(),this.syncReplayBar()},onStepBack:()=>this.stepReplay(-1),onStepForward:()=>this.stepReplay(1),onSeek:e=>{this.seriesPending()||(this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(e),this.replayBar?.setState(`paused`))},onSpeedChange:e=>{this.replaySpeed=e,this.chart.setReplaySpeed(e)},onRandomStart:()=>{if(this.seriesPending())return;let e=this.replayBarCount(),t=Math.max(1,Math.floor(e*.1)),n=Math.max(t,Math.floor(e*.9));this.startReplayAt(t+Math.floor(Math.random()*(n-t+1)),!1,!0)},onClose:()=>this.exitReplay(),onSelectBar:()=>this.pickReplayBarAgain(),onCancelPick:()=>this.cancelReplayPick(),onStepChange:e=>{if(this.replayStep=e,this.replayBar?.getMode()!==`replay`)return;let t=this.chart.getReplayState()===`playing`;this.startReplayAt(Math.max(0,this.chart.getReplayBarIndex()-1),t)}},{selectHint:e(`replay.selectHint`),loading:e(`status.loading`),random:e(`replay.random`),realtime:e(`replay.realtime`),play:e(`replay.play`),pause:e(`replay.pause`),stepBack:e(`replay.stepBack`),stepForward:e(`replay.stepForward`),replay:e(`replay.label`),position:e(`replay.position`),speed:e(`replay.speed`),step:e(`replay.step`),selectBar:e(`replay.selectBar`),cancel:e(`common.cancel`),rate:e(`replay.rate`),rateHint:e(`replay.rateHint`),playingAt:e(`replay.playingAt`),pausedAt:e(`replay.pausedAt`),endedAt:e(`replay.endedAt`)});let t=this.replayStepMenu();this.replayBar.mount(this.chartContainer,{total:this.replayTotal(),rate:this.replaySpeed,mode:`select`,steps:t,step:this.replayStep,dir:this.root.dir===`rtl`?`rtl`:`ltr`,formatRate:t=>s.r(e(`replay.rate`),{rate:t.toLocaleString(this.host.intlLocale())})}),this.watchReplayBar(),this.host.markActive(!0),this.root.setAttribute(`data-tcw-replay`,``),this.showReplayShade(),this.layoutReplayBar()}showReplayShade(){this.replayShade||(this.replayShade=document.createElement(`div`),this.replayShade.className=`tcw-replay-shade`,this.replayShade.hidden=!0,this.chartContainer.appendChild(this.replayShade),this.chartContainer.addEventListener(`mouseleave`,this.hideReplayShade))}removeReplayShade(){this.replayShade?.remove(),this.replayShade=null,this.chartContainer.removeEventListener(`mouseleave`,this.hideReplayShade)}pickReplayBarAgain(){let e=this.replayBar;!e?.isMounted()||this.seriesPending()||(this.replayPlayWanted=!1,this.chart.getReplayState()===`playing`&&this.chart.replayPause(),e.setState(`paused`),e.setMode(`select`),this.showReplayShade(),this.layoutReplayBar())}cancelReplayPick(){let e=this.replayBar;if(e?.isMounted()){if(!this.chart.isReplayActive()&&!this.replayStartPending){this.exitReplay();return}this.removeReplayShade(),e.setMode(`replay`),this.syncReplayBar(),this.layoutReplayBar()}}layoutReplayBar(){let e=this.replayBar?.element();if(!e||!this.replayBar)return;let t=this.chart.getPlotRect(),n=this.chartContainer,r=e=>`${Math.max(0,Math.round(e))}px`;e.style.setProperty(`--tcw-replay-foot`,r(n.clientHeight-(t.y+t.height))),e.style.setProperty(`--tcw-replay-plot-start`,r(t.x)),e.style.setProperty(`--tcw-replay-plot-end`,r(n.clientWidth-(t.x+t.width))),this.replayBar.setRoom(t.width-2*qt),this.liftOverReplayBar()}liftOverReplayBar(){let e=this.replayBar?.element();if(!e)return;let t=e.getBoundingClientRect().top,n=e=>{if(!e)return;let n=`${Math.max(0,Math.round(e.getBoundingClientRect().bottom-t))}px`;e.style.getPropertyValue(`--tcw-replay-lift`)!==n&&e.style.setProperty(`--tcw-replay-lift`,n)};n(this.root),n(this.host.bodyEl())}replayTimeText(){let e=this.chart.getReplayProgress(),t=(this.chart.getReplayBarIndex()>e.current?e.time:null)??this.replayStepTime;if(t===null)return;let n=this.host.textLocale(),r=this.chart.getTimeZone?.()??null,i=(0,u.timeframeToMs)(this.host.timeframe()),a=(0,u.zonedDateFormatter)(n,{year:`numeric`},r),o={month:`short`,day:`numeric`};a(t)!==a(Date.now())&&(o.year=`numeric`);let s=(0,u.zonedDateFormatter)(n,o,r)(t);if(Number.isFinite(i)&&i>=Ht)return s;let c={hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`};return(!Number.isFinite(i)||i<Ut)&&(c.second=`2-digit`),`${s} · ${(0,u.zonedDateFormatter)(n,c,r)(t)}`}replayBarCount(){return this.chart.isReplayActive()&&this.replayBarsTotal!==null?this.replayBarsTotal:this.chart.getData().length}hideReplayShade=()=>this.positionReplayShade(null);replayFrom(e,t=!1){this.host.isOn()&&(this.replayBar?.isMounted()||this.enterReplay(),this.startReplayAt(e,t))}replayStepMenu(){let e=[{value:`auto`,label:this.t(`replay.step.auto`)},{value:`bar`,label:this.t(`replay.step.bar`)},...this.replayStepOptions().map(e=>({value:e,label:e}))];return e.some(e=>e.value===this.replayStep)||(this.replayStep=`auto`),e}refreshReplaySteps(){if(!this.replayBar?.isMounted())return;let e=this.replayStepMenu();this.replayBar.setSteps(e,this.replayStep)}afterReplayCarryOver(){let e=this.replayBar;!e?.isMounted()||e.getMode()!==`replay`||(this.syncReplayBar(),!(this.replayStep===`bar`||this.chartFetchesReplaySteps())&&this.replayStepsKey!==this.replayStepsKeyNow()&&this.startReplayAt(this.chart.getReplayBarIndex(),this.chart.getReplayState()===`playing`))}startPickedReplay(){let e=this.replayPickTime;if(e===null)return;if(this.host.loading.hasFailed()||this.replayBar?.getMode()!==`select`){this.replayPickTime=null;return}if(this.seriesPending())return;this.replayPickTime=null;let t=this.chart.getData();if(!Yt(t,e))return;let n=0;for(;n+1<t.length&&t[n+1].time<=e;)n++;this.startReplayAt(n,!1,!0)}seriesPending(){return this.host.loading.isActive()&&!this.host.loading.hasFailed()}watchReplayBar(){this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayPollInterval=setInterval(()=>this.syncReplayBar(),Gt)}startReplayAt(e,t=!1,n=!1){let r=this.replayBar;if(!r)return;let i=n?this.replayBarCount():this.replayTotal(),a=Math.max(0,Math.min(Number.isFinite(e)?Math.floor(e):0,i-1)),o=this.chart.getData()[a]?.time;this.removeReplayShade(),r.setMode(`replay`),this.layoutReplayBar();let s=++this.replayStartSeq;this.replayPlayWanted=t;let c=this.host.options.replayAnimate!==!1,l=this.chartFetchesReplaySteps(),u=e=>{this.host.isDestroyed()||this.replayBar!==r||!r.isMounted()||s!==this.replayStartSeq||(this.replayStartPending=!1,this.replayStepsKey=e?this.replayStepsKeyNow():null,this.chart.replayStart({speed:this.replaySpeed,interval:c?Wt:Wt/this.replayStepsPerBar(e?d:null),...o===void 0?{startIndex:a}:{startTime:o},paused:!0,revealMarks:this.host.options.replayRevealMarks!==!1,animate:c,...l?{step:this.replayStep}:{},...e?{steps:e}:{}}),this.replayPlayWanted&&this.chart.replayResume(),this.replayPlayWanted=!1,this.syncReplayBar(),this.watchReplayBar())},d=this.replayStepInterval();if(l||d===null){u(null);return}this.replayStartPending=!0,this.replayStepsFor(d).then(e=>{s===this.replayStartSeq&&(e||this.host.say(this.t(`replay.stepsFailed`),`error`),u(e))})}replayStepsKeyNow(){return`${this.host.symbol()}|${this.host.timeframe()}`}replayStepsPerBar(e){if(e===null)return 1;let t=(0,u.timeframeToMs)(this.host.timeframe())/(0,u.timeframeToMs)(e);return Number.isFinite(t)&&t>=1?Math.round(t):1}replayStepOptions(){return e._(this.host.timeframe(),e=>this.hasReplayStep(e))}hasReplayStep(e){let t=this.host.adapter();if(t)return(0,d.servesTimeframe)(t,e);let n=(0,u.timeframeToMs)(e),r=this.host.baseTimeframeMs();return this.host.baseSeries()!==null&&r>0&&n>=r&&n%r===0}replayStepInterval(){return this.replayStep===`bar`||this.replayStep===`auto`&&this.host.options.replayAnimate===!1?null:e.v(this.replayStep,this.host.timeframe(),e=>this.hasReplayStep(e))}chartFetchesReplaySteps(){let e=this.host.adapter();return this.host.options.replayAnimate===!1||!e||this.replayStep===`bar`?!1:(0,d.withResampling)(e).fetchHistoryBefore!==void 0}async replayStepsFor(e){let t=this.chart.getExchangeTimeZone()??null,n=this.host.symbol(),r=this.host.timeframe(),i=()=>`${n}|${r}|${e}|${t}|${this.builtStepsZone(n,e)}`;if(this.replayStepsCache?.key===i())return this.replayStepsCache.steps;let a=null,o=this.host.adapter(),s=this.host.baseSeries();if(o){let t=Math.max(1,Math.round((0,u.timeframeToMs)(r)/(0,u.timeframeToMs)(e))),i=Math.min(Kt,Math.max(this.chart.getData().length,100)*t);try{a=await(0,d.withResampling)(o).fetchHistory(n,e,i)}catch{a=null}}else s&&(a=(0,u.timeframeToMs)(e)===this.host.baseTimeframeMs()?s:f(s,e,this.host.resampleOptions(t)));return!a||a.length===0?null:(this.replayStepsCache={key:i(),steps:a},a)}builtStepsZone(e,t){let n=this.host.adapter(),r=n?(0,d.withResampling)(n):null;if(!(r instanceof d.ResamplingAdapter))return``;let i=r.bucketFor(e,t);return i?String(i.timeZone??`UTC`):``}replayTotal(){return this.chart.isReplayActive()?this.chart.getReplayProgress().total:this.chart.getData().length}syncReplayBar(){let e=this.replayBar;if(!e?.isMounted()||(e.setPending(this.seriesPending()),this.startPickedReplay(),this.liftOverReplayBar(),e.getMode()!==`replay`))return;if(this.replayStartPending){e.setState(`paused`);return}if(!this.chart.isReplayActive()){this.teardownReplayUi();return}let t=this.chart.getReplayProgress(),n=this.chart.getReplayState();e.setProgress(t.current,t.total,this.replayTimeText()),e.setState(n===`stopped`?`paused`:n),e.setEnded(n!==`playing`&&t.total>0&&t.current>=t.total-1)}stepReplay(e){if(this.replayBar?.getMode()!==`replay`||this.seriesPending())return;let t=this.chart.getReplayProgress();this.chart.getReplayState()===`playing`&&this.chart.replayPause();let n=this.chart.getReplayBarIndex()>t.current?e>0?this.chart.getReplayBarIndex():t.current:t.current+e;this.chart.replaySeek(Math.max(0,Math.min(t.total-1,n))),this.replayBar.setState(`paused`),this.syncReplayBar()}handleReplayKey(e){if(e.defaultPrevented||e.isComposing||e.keyCode===229||O()||k()||!D(this.root,!0))return!1;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t)||t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`||t.isContentEditable))return!1;let n=this.replayBar?.getMode();return e.shiftKey&&(e.key===`ArrowRight`||e.key===`ArrowLeft`)&&n===`replay`?(e.preventDefault(),e.stopPropagation(),this.stepReplay(e.key===`ArrowRight`?1:-1),!0):e.key===` `&&n===`replay`&&this.onChartSurface(t)?(e.preventDefault(),e.stopPropagation(),this.toggleReplayPlay(),!0):e.key===`Escape`&&n===`select`?(this.cancelReplayPick(),!0):!1}onChartSurface(e){return!e||!this.chartContainer.contains(e)?!1:e===this.chartContainer||e.closest(`button, [role="button"], a, .tcw-replay-bar`)===null}toggleReplayPlay(){if(this.replayStartPending){this.replayPlayWanted=!this.replayPlayWanted;return}this.chart.getReplayState()===`playing`?this.chart.replayPause():this.replayBarAtEnd()||this.chart.replayResume(),this.syncReplayBar()}replayBarAtEnd(){let e=this.chart.getReplayProgress();return e.total>0&&e.current>=e.total-1}positionReplayShade(e){let t=this.replayShade;if(!t)return;let n=this.chart.getPlotRect();if(e===null||e<n.x||e>n.x+n.width){t.hidden=!0;return}t.hidden=!1,t.style.left=`${e}px`,t.style.top=`${n.y}px`,t.style.width=`${n.x+n.width-e}px`,t.style.height=`${n.height}px`}exitReplay(){this.teardownReplayUi(),this.chart.replayStop()}teardownReplayUi(){this.replayStartSeq++,this.replayPickTime=null,this.replayStartPending=!1,this.replayPlayWanted=!1,this.replayPollInterval&&=(clearInterval(this.replayPollInterval),null),this.removeReplayShade();let e=!!this.replayBar?.element()?.contains(document.activeElement);this.replayBar?.unmount(),this.replayBar=null,this.replayBarsTotal=null,this.replayStepTime=null,this.host.markActive(!1),this.root.removeAttribute(`data-tcw-replay`),this.root.style.removeProperty(`--tcw-replay-lift`),this.host.bodyEl()?.style.removeProperty(`--tcw-replay-lift`),e&&this.focusAfterReplay()}focusAfterReplay(){let e=e=>!!e&&!e.hidden&&!e.closest(`[hidden]`)&&getComputedStyle(e).display!==`none`,t=this.root.querySelector(`.tcw-toolbar [data-role="replay"]`),n=this.root.querySelector(`.tcw-toolbar .tcw-toolbar-more`);(e(t)?t:e(n)?n:this.chartContainer)?.focus()}};function Yt(e,t){let n=e.length;if(n===0||t<e[0].time)return!1;let r=e[n-1].time;return t<r+(n>1?r-e[n-2].time:0)||t===r}var Xt=()=>typeof document<`u`&&document.hidden;function A(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Zt=class{el;headerEl;nameBtn;menuEl;listEl;headEl;rowMap=new Map;entries=new Map;lists=[];activeList=``;active=null;locale;dragging=null;onOutside=e=>{this.headerEl.contains(e.target)||this.closeMenu()};constructor(e,t,n,r={}){this.callbacks=t,this.labels=n,this.options=r,this.el=document.createElement(`div`),this.el.className=`tcw-watchlist`,this.el.setAttribute(`aria-label`,n.title),this.headerEl=document.createElement(`div`),this.headerEl.className=`tcw-watchlist-header`,this.nameBtn=document.createElement(`button`),this.nameBtn.type=`button`,this.nameBtn.className=`tcw-watchlist-name`,this.nameBtn.setAttribute(`aria-haspopup`,`menu`),this.nameBtn.setAttribute(`aria-expanded`,`false`),this.nameBtn.title=n.lists,this.nameBtn.addEventListener(`click`,()=>this.menuEl.hidden?this.openMenu():this.closeMenu());let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-watchlist-add`,a.innerHTML=i.i(`plus`,14),a.title=n.add,a.setAttribute(`aria-label`,n.add),a.hidden=!t.onAdd,a.addEventListener(`click`,()=>t.onAdd?.());let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-watchlist-close`,o.setAttribute(`aria-label`,n.close??n.title),o.innerHTML=i.i(`x`,14),o.hidden=!t.onClose,o.addEventListener(`click`,()=>t.onClose?.()),this.menuEl=document.createElement(`div`),this.menuEl.className=`tcw-dropdown tcw-watchlist-menu`,this.menuEl.setAttribute(`role`,`menu`),this.menuEl.hidden=!0,this.headerEl.append(this.nameBtn,a,o,this.menuEl),this.el.appendChild(this.headerEl),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-watchlist-list`,this.listEl.setAttribute(`role`,`list`);let s=[`var(--tcw-watchlist-gutter)`,`minmax(0, 1fr)`,`auto`,`auto`,`auto`,...t.onRemove?[`var(--tcw-watchlist-remove)`]:[],`var(--tcw-watchlist-gutter)`];this.listEl.style.setProperty(`--tcw-watchlist-columns`,s.join(` `)),this.el.appendChild(this.listEl),this.headEl=this.makeHead(),e.appendChild(this.el)}get element(){return this.el}setLists(e,t){this.lists=e.map(e=>({...e,symbols:[...e.symbols]})),this.activeList=e.some(e=>e.id===t)?t:e[0]?.id??``;let n=this.shownList();this.nameBtn.textContent=n?.name??this.labels.title,this.renderRows(n?.symbols??[]),this.menuEl.hidden||this.renderMenu()}redraw(){for(let e of this.rowMap.keys())this.renderRow(e)}setLocale(e){this.locale=e;for(let e of this.rowMap.keys())this.renderRow(e)}setActive(e){this.active=e;for(let[t,n]of this.rowMap){let r=t===e;n.row.classList.toggle(`tcw-watchlist-active`,r),r?n.row.setAttribute(`aria-current`,`true`):n.row.removeAttribute(`aria-current`)}}setEntry(e,t){let n=this.entries.get(e)??{symbol:e};this.entries.set(e,{...n,...t,symbol:e}),this.renderRow(e)}destroy(){this.closeMenu(),this.el.remove(),this.rowMap.clear(),this.entries.clear()}shownList(){return this.lists.find(e=>e.id===this.activeList)}renderRows(e){for(let t of[...this.rowMap.keys()])e.includes(t)||(this.rowMap.get(t).row.remove(),this.rowMap.delete(t));for(let t of e)this.rowMap.has(t)||this.makeRow(t);let t=e.map(e=>this.rowMap.get(e).row);if(this.listEl.classList.toggle(`tcw-watchlist-logos`,t.some(e=>e.querySelector(`.tcw-watchlist-symbol-logo`))),this.listEl.replaceChildren(...this.headEl&&t.length?[this.headEl]:[],...t),e.length===0){let e=document.createElement(`div`);e.className=`tcw-watchlist-empty`,e.textContent=this.labels.empty,this.listEl.appendChild(e)}this.active&&this.setActive(this.active)}place(e,t){let n=[`symbol`,...this.options.sparkline?[`spark`,`price`]:[`price`,`move`],`change`,...this.callbacks.onRemove?[`remove`]:[]];e.style.gridColumnStart=String(n.indexOf(t)+2)}makeHead(){let e=this.labels.columns;if(!e)return null;let t=document.createElement(`div`);t.className=`tcw-watchlist-columns`,t.setAttribute(`aria-hidden`,`true`);let n=(e,n)=>{let r=document.createElement(`span`);r.className=`tcw-watchlist-column-${n}`,r.textContent=e,this.place(r,n),t.appendChild(r)};return n(e.symbol,`symbol`),this.options.sparkline&&n(``,`spark`),n(e.price,`price`),this.options.sparkline||n(e.move,`move`),n(e.change,`change`),this.callbacks.onRemove&&n(``,`remove`),t}makeRow(e){let t=document.createElement(`div`);t.className=`tcw-watchlist-row`,t.setAttribute(`role`,`listitem`),t.dataset.symbol=e,t.tabIndex=0,t.draggable=!!this.callbacks.onMove;let n=document.createElement(`div`);n.className=`tcw-watchlist-symbol`,n.textContent=Qt(e),e.includes(`:`)&&(n.title=e);let r=nn(this.options.infoOf?.(e));r&&(n.prepend(r),n.classList.add(`tcw-watchlist-symbol-logo`)),this.place(n,`symbol`),t.appendChild(n);let a=null;this.options.sparkline&&(a=document.createElement(`canvas`),a.className=`tcw-watchlist-spark`,a.width=64,a.height=22,this.place(a,`spark`),t.appendChild(a));let o=(e,n=``)=>{let r=document.createElement(`span`);return r.className=`tcw-watchlist-${e}`,r.textContent=n,this.place(r,e),t.appendChild(r),r},c=o(`price`,`—`),l=this.options.sparkline?null:o(`move`),u=o(`change`);if(this.callbacks.onRemove){t.classList.add(`tcw-watchlist-removable`);let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-watchlist-remove`,n.innerHTML=i.i(`x`,12),n.tabIndex=-1;let r=s.r(this.labels.remove,{symbol:e});n.title=r,n.setAttribute(`aria-label`,r),n.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onRemove?.(e)}),this.place(n,`remove`),t.appendChild(n)}t.addEventListener(`click`,()=>this.callbacks.onSelect(e)),t.addEventListener(`keydown`,t=>this.onRowKey(t,e)),t.addEventListener(`dragstart`,n=>{this.dragging=e,n.dataTransfer?.setData(`text/plain`,e),n.dataTransfer&&(n.dataTransfer.effectAllowed=`move`),t.classList.add(`tcw-watchlist-dragging`)}),t.addEventListener(`dragend`,()=>{this.dragging=null,t.classList.remove(`tcw-watchlist-dragging`)}),t.addEventListener(`dragover`,t=>{this.dragging&&this.dragging!==e&&t.preventDefault()}),t.addEventListener(`drop`,t=>{t.preventDefault();let n=this.dragging;if(this.dragging=null,!n||n===e)return;let r=this.shownList()?.symbols??[];this.callbacks.onMove?.(n,r.indexOf(e))}),this.rowMap.set(e,{row:t,priceEl:c,moveEl:l,changeEl:u,sparkCanvas:a}),this.renderRow(e)}onRowKey(e,t){let n=this.shownList()?.symbols??[],r=n.indexOf(t);if([`Enter`,` `,`Delete`,`Backspace`,`ArrowDown`,`ArrowUp`].includes(e.key)&&e.stopPropagation(),e.key===`Enter`||e.key===` `)e.preventDefault(),this.callbacks.onSelect(t);else if((e.key===`Delete`||e.key===`Backspace`)&&this.callbacks.onRemove){e.preventDefault();let i=n[r+1]??n[r-1];this.callbacks.onRemove(t),i&&this.rowMap.get(i)?.row.focus()}else if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let i=r+(e.key===`ArrowDown`?1:-1);if(i<0||i>=n.length)return;e.altKey?(this.callbacks.onMove?.(t,i),this.rowMap.get(t)?.row.focus()):this.rowMap.get(n[i])?.row.focus()}}renderRow(e){let t=this.rowMap.get(e),n=this.entries.get(e);if(!t||!n)return;let r=this.options.infoOf?.(e)?.pricePrecision,i=r!==void 0&&Number.isInteger(r)&&r>=0?Math.min(r,u.MAX_PRICE_DECIMALS):void 0;if(n.lastPrice!==void 0&&(t.priceEl.textContent=$t(n.lastPrice,this.locale,i)),n.lastPrice!==void 0&&n.refPrice!==void 0&&n.refPrice!==0){let e=n.lastPrice-n.refPrice,r=e/n.refPrice*100,a=e>0?`+`:e<0?`-`:``,o=e>0?` tcw-up`:e<0?` tcw-down`:``,s=Math.abs(r).toLocaleString(this.locale,{minimumFractionDigits:2,maximumFractionDigits:2});t.moveEl&&(t.moveEl.textContent=`${a}${en(Math.abs(e),n.lastPrice,this.locale,i)}`,t.moveEl.className=`tcw-watchlist-move${o}`),t.changeEl.textContent=`${a}${s}%`,t.changeEl.className=`tcw-watchlist-change${o}`}else t.moveEl&&(t.moveEl.textContent=``),t.changeEl.textContent=``;t.sparkCanvas&&n.sparkline&&n.sparkline.length>=2&&tn(t.sparkCanvas,n.sparkline,n.refPrice??n.sparkline[0])}openMenu(){this.renderMenu(),this.menuEl.hidden=!1,this.nameBtn.setAttribute(`aria-expanded`,`true`),document.addEventListener(`mousedown`,this.onOutside)}closeMenu(){this.menuEl.hidden=!0,this.nameBtn.setAttribute(`aria-expanded`,`false`),document.removeEventListener(`mousedown`,this.onOutside)}renderMenu(){let e=(e,t)=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-dropdown-item`,n.setAttribute(`role`,`menuitem`),n.textContent=e,n.addEventListener(`click`,t),n},t=this.lists.map(t=>{let n=e(``,()=>{this.closeMenu(),this.callbacks.onPickList?.(t.id)});n.dataset.list=t.id,n.classList.toggle(`tcw-active`,t.id===this.activeList);let r=document.createElement(`span`);r.textContent=t.name;let i=document.createElement(`span`);return i.className=`tcw-watchlist-count`,i.textContent=String(t.symbols.length),n.append(r,i),n}),n=document.createElement(`div`);if(n.className=`tcw-dropdown-divider`,t.push(n),this.callbacks.onCreateList){let n=e(this.labels.newList,()=>this.editName(``,e=>this.callbacks.onCreateList?.(e)));n.dataset.action=`new`,t.push(n)}let r=this.shownList();if(r&&this.callbacks.onRenameList){let n=e(this.labels.rename,()=>this.editName(r.name,e=>this.callbacks.onRenameList?.(r.id,e)));n.dataset.action=`rename`,t.push(n)}if(r&&this.callbacks.onDeleteList&&this.lists.length>1){let n=!1,i=e(this.labels.deleteList,()=>{if(!n){n=!0,i.textContent=s.r(this.labels.confirmDelete,{name:r.name}),i.classList.add(`tcw-danger`);return}this.closeMenu(),this.callbacks.onDeleteList?.(r.id)});i.dataset.action=`delete`,t.push(i)}this.menuEl.replaceChildren(...t)}editName(e,t){this.closeMenu();let n=document.createElement(`input`);n.className=`tcw-watchlist-input`,n.type=`text`,n.maxLength=60,n.value=e,n.placeholder=this.labels.listName,n.setAttribute(`aria-label`,this.labels.listName),this.nameBtn.hidden=!0,this.headerEl.insertBefore(n,this.nameBtn);let r=!1,i=i=>{if(r)return;r=!0;let a=n.value.trim();n.remove(),this.nameBtn.hidden=!1,i&&a&&a!==e&&t(a),this.nameBtn.focus()};n.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),i(!0)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),i(!1))}),n.addEventListener(`blur`,()=>i(!1)),n.focus()}};function Qt(e){let t=e.slice(e.lastIndexOf(`:`)+1)||e;if(t.includes(`/`))return t;for(let e of[`USDT`,`USD`,`BTC`,`ETH`,`EUR`])if(t.length>e.length&&t.endsWith(e))return t.slice(0,-e.length)+`/`+e;return t}function $t(e,t,n){if(n!==void 0)return e.toLocaleString(t,{minimumFractionDigits:n,maximumFractionDigits:n});if(e===0)return`0`;let r=Math.abs(e);return r>=1e3?e.toLocaleString(t,{minimumFractionDigits:2,maximumFractionDigits:2}):r>=1?e.toLocaleString(t,{minimumFractionDigits:4,maximumFractionDigits:4}):e.toLocaleString(t,{maximumFractionDigits:(0,u.smallValueDecimals)(e)})}function en(e,t,n,r){if(r!==void 0)return e.toLocaleString(n,{minimumFractionDigits:r,maximumFractionDigits:r});let i=Math.abs(t);if(i>=1e3)return e.toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:2});if(i>=1)return e.toLocaleString(n,{minimumFractionDigits:4,maximumFractionDigits:4});let a=i>0?(0,u.smallValueDecimals)(i):4;return e.toLocaleString(n,{maximumFractionDigits:a})}function tn(e,t,n){let r=e.getContext(`2d`);if(!r)return;let i=window.devicePixelRatio||1;e.width!==e.clientWidth*i&&(e.width=(e.clientWidth||64)*i,e.height=(e.clientHeight||22)*i);let a=e.width,o=e.height,s=1/0,c=-1/0;for(let e of t)e<s&&(s=e),e>c&&(c=e);let l=Math.max(c-s,1e-9),u=t[t.length-1]>=n?`#1fa874`:`#e8505b`;r.clearRect(0,0,a,o),r.lineWidth=1.4*i,r.strokeStyle=u,r.beginPath();let d=a/(t.length-1);for(let e=0;e<t.length;e++){let n=e*d,i=o-(t[e]-s)/l*(o-4)-2;e===0?r.moveTo(n,i):r.lineTo(n,i)}r.stroke()}function nn(e){let t=a.i(e?.logo);if(!t)return null;let n=document.createElement(`img`);return n.className=`tcw-watchlist-logo`,n.alt=``,n.draggable=!1,n.setAttribute(`aria-hidden`,`true`),n.setAttribute(`loading`,`lazy`),n.setAttribute(`decoding`,`async`),n.setAttribute(`referrerpolicy`,`no-referrer`),n.addEventListener(`error`,()=>{n.style.visibility=`hidden`},{once:!0}),n.src=t,n}var rn=50,an=200,on=500,sn=60,cn=e=>typeof e==`string`&&e.trim().slice(0,sn)||null;function ln(e){let t=[];for(let n of e){let e=a.n(n);if(e&&!t.includes(e)&&t.push(e),t.length===on)break}return t}function un(e){if(!e||typeof e!=`object`)return null;let t=e;if(!Array.isArray(t.lists))return null;let n=[];for(let e of t.lists){if(n.length===rn)break;if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`&&t.id&&t.id.length<=u.MAX_SYMBOL_LENGTH?t.id:null,i=cn(t.name);!r||!i||n.some(e=>e.id===r)||n.push({id:r,name:i,symbols:Array.isArray(t.symbols)?ln(t.symbols):[]})}return n.length===0?null:{lists:n,active:typeof t.active==`string`&&n.some(e=>e.id===t.active)?t.active:n[0].id}}var dn=e=>({...e,symbols:[...e.symbols]});function fn(e){let t=e?.offered;return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.length>0&&e.length<=u.MAX_SYMBOL_LENGTH).slice(-an):null}var pn=class{lists;active;listeners=new Set;storage;storageKey;offered;constructor(e){this.storage=e.storage??null,this.storageKey=e.storageKey??`tcw:watchlists`;let t=this.load(),n=e.lists?un({lists:e.lists,active:e.activeList}):null,r=n??{lists:[{id:`default`,name:cn(e.defaultName)??`Watchlist`,symbols:ln(e.symbols??[])}],active:`default`};if(this.offered=new Set(n?.lists.map(e=>e.id)),!t){this.lists=r.lists,this.active=r.active;return}this.keepWithHostLists(t,n?.lists??[])&&this.save()}keepWithHostLists(e,t){let n=new Set(e.offered??e.lists.map(e=>e.id)),r=t.filter(t=>!n.has(t.id)&&!e.lists.some(e=>e.id===t.id));return this.lists=[...e.lists,...r].slice(0,rn),this.active=e.active,this.offered=new Set([...n,...this.lists.map(e=>e.id)]),r.length>0}getLists(){return this.lists.map(dn)}getActive(){return dn(this.activeList())}setActive(e){e===this.active||!this.lists.some(t=>t.id===e)||(this.active=e,this.changed())}replace(e,t){let n=un({lists:e,active:t??this.active});n&&(this.lists=n.lists,this.active=n.active,this.changed())}create(e){let t=cn(e);if(!t||this.lists.length>=rn)return null;let n=this.lists.length+1;for(;this.lists.some(e=>e.id===`list-${n}`);)n++;let r={id:`list-${n}`,name:t,symbols:[]};return this.lists=[...this.lists,r],this.active=r.id,this.changed(),dn(r)}rename(e,t){let n=cn(t);n&&this.update(e,e=>({...e,name:n}))}remove(e){this.lists.length<=1||!this.lists.some(t=>t.id===e)||(this.lists=this.lists.filter(t=>t.id!==e),this.active===e&&(this.active=this.lists[0].id),this.changed())}add(e,t=this.active){let n=a.n(e),r=this.lists.find(e=>e.id===t);return!n||!r||r.symbols.includes(n)||r.symbols.length>=on?!1:(this.update(t,e=>({...e,symbols:[...e.symbols,n]})),!0)}removeSymbol(e,t=this.active){this.lists.find(e=>e.id===t)?.symbols.includes(e)&&this.update(t,t=>({...t,symbols:t.symbols.filter(t=>t!==e)}))}move(e,t,n=this.active){let r=this.lists.find(e=>e.id===n);if(!r)return;let i=r.symbols.indexOf(e);if(i<0)return;let a=r.symbols.filter(t=>t!==e),o=Math.max(0,Math.min(Math.round(t),a.length));o!==i&&this.update(n,t=>({...t,symbols:[...a.slice(0,o),e,...a.slice(o)]}))}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}activeList(){return this.lists.find(e=>e.id===this.active)??this.lists[0]}update(e,t){this.lists=this.lists.map(n=>n.id===e?t(n):n),this.changed()}changed(){this.save();for(let e of this.listeners)e()}load(){if(!this.storage)return null;try{let e=this.storage.getItem(this.storageKey);if(!e)return null;let t=JSON.parse(e),n=un(t);return n?{...n,offered:fn(t)}:null}catch{return null}}save(){if(this.storage)try{let e=[...this.offered].slice(-an);this.storage.setItem(this.storageKey,JSON.stringify({lists:this.lists,active:this.active,offered:e}))}catch{}}},mn=class{el;bodyEl;newsEl;shown=!1;constructor(e,t=s.t,n={}){this.t=t,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-syminfo`,r.o(this.el,`symbolInfo`),this.el.setAttribute(`role`,`dialog`),this.el.setAttribute(`aria-label`,t(`symbolInfo.title`)),this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-syminfo-header`;let o=document.createElement(`span`);o.textContent=t(`symbolInfo.title`);let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-syminfo-close`,c.setAttribute(`aria-label`,t(`common.close`)),c.innerHTML=i.i(`x`,14),c.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),a.append(o,c),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-syminfo-body`,this.newsEl=document.createElement(`div`),this.newsEl.className=`tcw-syminfo-news`,this.newsEl.hidden=!0,this.el.append(a,this.bodyEl,this.newsEl),e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.shown}toggle(){this.shown?this.close():this.open()}open(){this.shown||(this.shown=!0,this.el.hidden=!1,this.callbacks.onToggle?.(!0))}close(){this.shown&&(this.shown=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}render(e){let t=document.createElement(`div`);t.className=`tcw-syminfo-head`;let{venue:n,ticker:r}=a.c(e.symbol),i=j(`div`,`tcw-syminfo-symbol`,r);n&&(i.title=e.symbol),t.append(i),e.description&&t.append(j(`div`,`tcw-syminfo-desc`,e.description)),e.meta&&t.append(j(`div`,`tcw-syminfo-meta`,e.meta));let o=document.createElement(`div`);if(o.className=`tcw-syminfo-quote`,e.price&&o.append(j(`span`,`tcw-syminfo-price`,e.price)),e.change){let t=j(`span`,`tcw-syminfo-change`,e.change.text);t.classList.add(e.change.up?`tcw-up`:`tcw-down`),o.append(t)}let s=j(`div`,`tcw-syminfo-status`,e.status.text);s.dataset.state=e.status.state;let c=document.createElement(`dl`);c.className=`tcw-syminfo-stats`;for(let t of e.stats){let e=document.createElement(`div`);e.className=`tcw-syminfo-stat`,e.append(j(`dt`,``,t.label),j(`dd`,``,t.value)),c.append(e)}this.bodyEl.replaceChildren(t,o,s,c)}renderNews(e){if(this.newsEl.hidden=e.kind===`none`,e.kind===`none`){this.newsEl.replaceChildren();return}let t=j(`div`,`tcw-syminfo-news-title`,this.t(`symbolInfo.news`));if(e.kind===`loading`||e.kind===`failed`||e.items.length===0){let t=e.kind===`loading`?`symbolInfo.loading`:e.kind===`failed`?`symbolInfo.newsFailed`:`symbolInfo.noNews`;this.newsEl.replaceChildren(j(`div`,`tcw-syminfo-news-note`,this.t(t)));return}let n=document.createElement(`ul`);n.className=`tcw-syminfo-news-list`;for(let t of e.items){let e=document.createElement(`li`);if(e.className=`tcw-syminfo-news-item`,t.url){let n=document.createElement(`a`);n.href=t.url,n.target=`_blank`,n.rel=`noopener noreferrer`,n.textContent=t.title,e.append(n)}else e.append(j(`span`,``,t.title));t.meta&&e.append(j(`div`,`tcw-syminfo-news-meta`,t.meta)),n.append(e)}this.newsEl.replaceChildren(t,n)}destroy(){this.el.remove()}};function j(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}var hn=10,gn=50,_n=5*6e4,vn=864e5,yn=2;function bn(e){let{info:t,quote:n,t:r,textLocale:i}=e,a=(0,u.symbolTimeZone)(t),o=Sn(e.bars,a),c=e.formatPrice,l=n?.last??o?.close,d=n?.prevClose??o?.prevClose,f=n?.change??(l!==void 0&&d!==void 0?l-d:void 0),p=l!==void 0&&f!==void 0?l-f:void 0,m=n?.changePercent??(f!==void 0&&p?f/p*100:void 0),h=(0,u.marketStatus)(t,e.now),g=r(h.state===`open`?`symbolInfo.open`:h.state===`closed`?`symbolInfo.closed`:`symbolInfo.always`);if(h.state!==`always`&&h.next!==null){let t=Cn(h.next-e.now,i);g+=` · ${s.r(r(h.state===`open`?`symbolInfo.closesIn`:`symbolInfo.opensIn`),{when:t})}`}let _=[],v=(e,t)=>{t&&_.push({label:e,value:t})},y=e=>e===void 0?void 0:c(e);v(r(`dataWindow.open`),y(n?.open??o?.open)),v(r(`dataWindow.high`),y(n?.high??o?.high)),v(r(`dataWindow.low`),y(n?.low??o?.low)),v(r(`symbolInfo.prevClose`),y(d));let ee=n?.volume??o?.volume;v(r(`dataWindow.volume`),ee===void 0?void 0:Tn(ee,e.numberLocale)),v(r(`symbolInfo.bid`),y(n?.bid)),v(r(`symbolInfo.ask`),y(n?.ask)),v(r(`symbolInfo.tick`),t?.minTick===void 0?void 0:String(t.minTick)),v(r(`symbolInfo.currency`),t?.currency),v(r(`symbolInfo.timezone`),a),v(r(`symbolInfo.hours`),En(t,i));let te=(f??0)>=0?`+`:`-`,ne=e.names===void 0?t:e.names;return{symbol:e.symbol,description:ne?.description,meta:[ne?.exchange,ne?.type].filter(Boolean).join(` · `)||void 0,price:l===void 0?void 0:c(l),change:f===void 0?void 0:{text:`${te}${c(Math.abs(f))}${m===void 0?``:` (${te}${wn(Math.abs(m),yn,e.numberLocale)}%)`}`,up:f>=0},status:{state:h.state,text:g},stats:_}}var xn=class{request=0;cache=new Map;pending=new Map;headlines(e,t){let n=this.cache.get(e);if(n&&Date.now()-n.at<_n)return Promise.resolve(n.items);let r=this.pending.get(e);if(r)return r;let i=Promise.resolve().then(()=>t(e,gn)).then(t=>{let n=(0,u.readNews)(t,gn);return this.cache.set(e,{at:Date.now(),items:n}),n}).finally(()=>this.pending.delete(e));return this.pending.set(e,i),i}load(e,t,n,r,i){let a=++this.request;if(!t){n({kind:`none`});return}let o=e=>{let t=Date.now();n({kind:`items`,items:e.slice(0,hn).map(e=>({title:e.title,url:e.url,meta:[e.source,Cn(e.time-t,r)].filter(Boolean).join(` · `)}))})},s=this.cache.get(e);if(s&&Date.now()-s.at<_n){o(s.items);return}n({kind:`loading`}),this.headlines(e,t).then(e=>{a!==this.request||i()||o(e)}).catch(()=>{a===this.request&&!i()&&n({kind:`failed`})})}};function Sn(e,t){if(e.length===0)return null;let n=t&&(0,u.isValidTimeZone)(t)?t:null,r=(0,u.barTimeUnit)(e),i=e=>{let t=e*r;return Math.floor((t+(n?(0,u.zoneOffsetMinutes)(n,t)*6e4:0))/vn)},a=e[e.length-1],o=i(a.time),s=e.length-1;for(;s>0&&i(e[s-1].time)===o;)s--;let c=-1/0,l=1/0,d=0;for(let t=s;t<e.length;t++)c=Math.max(c,e[t].high),l=Math.min(l,e[t].low),d+=e[t].volume??0;return{open:e[s].open,high:c,low:l,close:a.close,volume:d,prevClose:s>0?e[s-1].close:void 0}}function Cn(e,t){let n=e/6e4,[r,i]=Math.abs(n)<60?[Math.round(n)||Math.sign(n)||1,`minute`]:Math.abs(n)<1440?[Math.round(n/60),`hour`]:[Math.round(n/1440),`day`];try{return new Intl.RelativeTimeFormat(t,{numeric:`auto`}).format(r,i)}catch{return new Intl.RelativeTimeFormat(`en`,{numeric:`auto`}).format(r,i)}}function wn(e,t,n){try{return(0,u.formatPrice)(e,t,n)}catch{return e.toFixed(t)}}function Tn(e,t){try{return new Intl.NumberFormat(t,{notation:`compact`,maximumFractionDigits:2}).format(e)}catch{return String(e)}}function En(e,t){let n=e?.sessions??[];if(n.length===0)return;let r;try{let e=new Intl.DateTimeFormat(t,{weekday:`short`,timeZone:`UTC`});r=Array.from({length:7},(t,n)=>e.format(Date.UTC(1970,0,4+n)))}catch{r=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]}let i=e=>{let t=[...new Set((e??[]).filter(e=>Number.isInteger(e)&&e>=0&&e<=6))].sort((e,t)=>e-t);return t.length===0||t.length===7?``:t.every((e,n)=>n===0||e===t[n-1]+1)&&t.length>2?`${r[t[0]]}–${r[t[t.length-1]]}`:t.map(e=>r[e]).join(`, `)};return n.map(e=>[`${e.start}–${e.end}`,i(e.days)].filter(Boolean).join(` `)).join(`, `)}var Dn=`news:`,On=12;function kn(e){return e.map((e,t)=>{let n={id:`${Dn}${e.id??`${e.time}:${t}`}`,time:e.time,kind:`news`,title:e.title};return e.source&&(n.text=e.source),e.url&&(n.url=e.url),n})}var An=class{shown=[];own=[];placing=!1;request=0;constructor(e){this.host=e}start(){this.host.chart.on(`markClick`,e=>this.onClick(e.payload.marks,e.payload.x,e.payload.y)),this.host.chart.on(`marksChange`,e=>{this.makeRoom(e.payload.count),this.keep()}),this.host.chart.on(`markHover`,e=>this.host.hideNavigation(e.payload.marks!==null)),this.host.chart.on(`chartTypeChange`,()=>this.makeRoom(this.host.chart.getMarks()?.length??0)),this.load()}makeRoom(e){let t=e>0&&this.host.marksOn&&this.host.chart.isTimeAligned();this.host.liftNavigation(t?d.MARK_ROW_HEIGHT:0)}keep(){if(this.placing||this.own.length===0)return;let e=new Set((this.host.chart.getMarks()??[]).map(e=>e.id));this.shown.every(t=>e.has(t))||this.place(this.own)}place(e){this.placing=!0;try{this.shown=[];for(let t of e){let e=this.host.chart.addMark(t);e&&this.shown.push(e)}}finally{this.placing=!1}}load(){let e=++this.request;this.own=[];for(let e of this.shown)this.host.chart.removeMark(e);this.shown=[],this.makeRoom(this.host.chart.getMarks()?.length??0);let{options:t}=this.host;if(t.newsMarks===!1||!this.host.marksOn)return;let n=t.adapter,r=t.news??(n?.fetchNews?n.fetchNews.bind(n):null);r&&this.host.news.headlines(this.host.symbol,r).then(t=>{e!==this.request||this.host.destroyed||(this.own=kn(t),this.place(this.own))}).catch(()=>void 0)}onClick(e,t,n){if(!this.host.marksOn||e.length===0)return;if(e.length===1){e[0].url&&this.host.openLink(e[0].url);return}let r=[...e].reverse().slice(0,On).map(e=>({id:e.id,label:e.title,...e.url?{icon:`link`}:{}}));this.host.openMenu(r,t,n,t=>{let n=e.find(e=>e.id===t)?.url;n&&this.host.openLink(n)})}},jn={KeyT:`trendLine`,KeyH:`horizontalLine`,KeyJ:`horizontalRay`,KeyV:`verticalLine`,KeyC:`crossLine`,KeyF:`fibRetracement`};function Mn(){let e={};for(let[t,n]of Object.entries(jn))e[n]=`Alt+${t.replace(/^Key/,``)}`;return e}var Nn=300,Pn=80,Fn=u.PHI**-3,In=80,Ln=class{el;holdTimer=null;repeatTimer=null;pressed=!1;keyboardFocus=!1;lift=0;suppressed=!1;onMove=e=>{if(!(e.pointerType===`touch`||this.suppressed)&&!(this.holdTimer||this.repeatTimer)){if(!this.nearBottom(e)&&!this.keyboardFocus){this.el.classList.remove(`tcw-nav-shown`),this.stopHold();return}this.el.classList.contains(`tcw-nav-shown`)||this.place(),this.el.classList.add(`tcw-nav-shown`)}};onLeave=()=>{this.el.classList.remove(`tcw-nav-shown`),this.stopHold()};constructor(e,t,n=s.t){this.host=e,this.actions=t,this.el=document.createElement(`div`),this.el.className=`tcw-nav`,r.o(this.el,`navigation`),this.el.setAttribute(`role`,`toolbar`),this.el.setAttribute(`aria-label`,n(`nav.label`));let a=[[`zoomOut`,`minus`,n(`nav.zoomOut`),`navigation.zoom`],[`zoomIn`,`plus`,n(`nav.zoomIn`),`navigation.zoom`],[`scrollLeft`,`chevronLeft`,n(`nav.scrollLeft`),`navigation.scroll`],[`scrollRight`,`chevronRight`,n(`nav.scrollRight`),`navigation.scroll`],[`reset`,`reset`,n(`nav.reset`),`navigation.reset`]];for(let[e,n,o,s]of a){let a=document.createElement(`button`);if(a.type=`button`,a.className=`tcw-nav-btn`,a.dataset.nav=e,r.o(a,s),a.title=o,a.setAttribute(`aria-label`,o),a.innerHTML=i.i(n,16),e===`scrollLeft`||e===`scrollRight`){let n=e===`scrollRight`?1:-1;a.addEventListener(`pointerdown`,e=>{if(e.button===0){e.preventDefault();try{a.setPointerCapture(e.pointerId)}catch{}this.startHold(n)}});for(let e of[`pointerup`,`pointercancel`,`pointerleave`])a.addEventListener(e,()=>this.stopHold());a.addEventListener(`click`,e=>{e.detail===0&&t.scroll(n)})}else a.addEventListener(`click`,()=>{e===`zoomIn`?t.zoomIn():e===`zoomOut`?t.zoomOut():t.reset()});this.el.appendChild(a)}for(let e of[`dblclick`,`contextmenu`,`pointerdown`,`mousedown`])this.el.addEventListener(e,e=>e.stopPropagation());this.el.addEventListener(`pointerdown`,()=>{this.pressed=!0},{capture:!0}),this.el.addEventListener(`pointerup`,()=>{this.pressed=!1},{capture:!0}),this.el.addEventListener(`focusin`,()=>{this.keyboardFocus=!this.pressed,this.pressed=!1,this.place(),this.el.classList.add(`tcw-nav-shown`)}),this.el.addEventListener(`focusout`,e=>{this.el.contains(e.relatedTarget)||(this.keyboardFocus=!1,this.el.classList.remove(`tcw-nav-shown`))}),e.appendChild(this.el),e.addEventListener(`pointermove`,this.onMove),e.addEventListener(`pointerleave`,this.onLeave)}setLift(e){let t=Math.max(0,Math.round(e));t!==this.lift&&(this.lift=t,this.el.classList.contains(`tcw-nav-shown`)&&this.place())}setSuppressed(e){this.suppressed=e,e&&!this.keyboardFocus&&(this.el.classList.remove(`tcw-nav-shown`),this.stopHold())}destroy(){this.stopHold(),this.host.removeEventListener(`pointermove`,this.onMove),this.host.removeEventListener(`pointerleave`,this.onLeave),this.el.remove()}nearBottom(e){let t=this.actions.plotRect(),n=this.host.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=Math.max(In,t.height*Fn);return r>=t.x&&r<=t.x+t.width&&i<=t.y+t.height&&i>=t.y+t.height-a}place(){let e=this.actions.plotRect();this.el.style.left=`${Math.round(e.x+e.width/2)}px`,this.el.style.top=`${Math.round(e.y+e.height)-this.lift}px`}startHold(e){this.stopHold(),this.actions.scroll(e),this.holdTimer=setTimeout(()=>{this.repeatTimer=setInterval(()=>this.actions.scroll(e),Pn)},Nn)}stopHold(){this.holdTimer&&clearTimeout(this.holdTimer),this.repeatTimer&&clearInterval(this.repeatTimer),this.holdTimer=null,this.repeatTimer=null}};function Rn(e,t,n,r=!1){let i=e.label??t(`alerts.source.price`),a=Un.get(e.condition),o=a?t(a):e.condition;if(Bn.includes(e.condition))return`${i} ${o} ${s.r(t(`alerts.moveSummary`),{percent:e.percent??0,bars:e.bars??0})}`;if(e.target)return`${i} ${o} ${e.targetLabel??e.target}`;let c=e.channel&&e.channel!==`price`,l=Number.isFinite(e.price)?c?Gn(e.price):n(e.price):`—`;return`${(c||e.drawingId)&&e.label?`${e.label} `:r?`${i} `:``}${o} ${l}`}var zn=[{value:`crossing`,key:`alerts.condition.crossing`},{value:`crossingUp`,key:`alerts.condition.crossingUp`},{value:`crossingDown`,key:`alerts.condition.crossingDown`},{value:`greaterThan`,key:`alerts.condition.greaterThan`},{value:`lessThan`,key:`alerts.condition.lessThan`},{value:`movesUp`,key:`alerts.condition.movesUp`},{value:`movesDown`,key:`alerts.condition.movesDown`}],Bn=[`movesUp`,`movesDown`],Vn={hour:36e5,day:864e5,week:7*864e5,month:30*864e5},Hn=``,Un=new Map(zn.map(e=>[e.value,e.key]));function Wn(e){return Math.round(e*1e6)/1e6}function Gn(e){return Math.abs(e)>=1?e.toFixed(2):e.toFixed((0,u.smallValueDecimals)(e))}var Kn=class{el;listEl;priceInput;conditionSelect;sourceSelect;targetSelect;percentInput;barsInput;levelRow;moveRow;closeCheck;expirySelect;messageInput;emptyEl;callbacks;open=!1;alerts=[];sources;formEl;newBtn;formChoice=null;constructor(e,t,n=s.t){this.t=n,this.callbacks=t,this.sources=[{channel:`price`,label:this.t(`alerts.source.price`)}],this.el=document.createElement(`div`),this.el.className=`tcw-alerts-panel`,r.o(this.el,`alerts`),this.el.hidden=!0;let o=document.createElement(`div`);o.className=`tcw-alerts-header`;let c=document.createElement(`span`);c.textContent=this.t(`alerts.title`);let l=document.createElement(`button`);l.className=`tcw-alerts-close`,l.type=`button`,l.setAttribute(`aria-label`,this.t(`alerts.close`)),l.innerHTML=i.i(`x`,14),l.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),this.newBtn=document.createElement(`button`),this.newBtn.className=`tcw-alerts-new`,this.newBtn.type=`button`,this.newBtn.setAttribute(`aria-label`,this.t(`alerts.add`)),this.newBtn.title=this.t(`alerts.add`),this.newBtn.innerHTML=i.i(`plus`,14),this.newBtn.addEventListener(`click`,()=>this.showForm(this.formEl.hidden)),o.appendChild(c),o.appendChild(this.newBtn),o.appendChild(l),this.el.appendChild(o);let u=document.createElement(`form`);this.formEl=u,u.className=`tcw-alerts-form`,u.noValidate=!0,this.sourceSelect=document.createElement(`select`),this.sourceSelect.className=`tcw-alerts-source`,this.sourceSelect.setAttribute(`aria-label`,this.t(`alerts.source`)),this.sourceSelect.addEventListener(`change`,()=>{this.renderTargets(),this.prefillPrice()}),this.conditionSelect=document.createElement(`select`),this.conditionSelect.className=`tcw-alerts-condition`,this.conditionSelect.setAttribute(`aria-label`,this.t(`alerts.conditionLabel`));for(let e of zn){let t=document.createElement(`option`);t.value=e.value,t.textContent=this.t(e.key),this.conditionSelect.appendChild(t)}this.conditionSelect.addEventListener(`change`,()=>this.showFields()),this.levelRow=document.createElement(`div`),this.levelRow.className=`tcw-alerts-row-fields`,this.targetSelect=document.createElement(`select`),this.targetSelect.className=`tcw-alerts-target`,this.targetSelect.setAttribute(`aria-label`,this.t(`alerts.compareWith`)),this.targetSelect.addEventListener(`change`,()=>this.showFields()),this.priceInput=document.createElement(`input`),this.priceInput.type=`number`,this.priceInput.step=`any`,this.priceInput.placeholder=this.t(`alerts.value`),this.priceInput.setAttribute(`aria-label`,this.t(`alerts.value`)),this.priceInput.className=`tcw-alerts-price`,this.levelRow.append(this.targetSelect,this.priceInput),this.moveRow=document.createElement(`div`),this.moveRow.className=`tcw-alerts-row-fields`,this.percentInput=this.numberField(`tcw-alerts-percent`,this.t(`alerts.percent`),`1`,`0.01`),this.barsInput=this.numberField(`tcw-alerts-bars`,this.t(`alerts.bars`),`10`,`1`),this.barsInput.min=String(d.MIN_ALERT_BARS),this.barsInput.max=String(d.MAX_ALERT_BARS),this.moveRow.append(this.percentInput,this.barsInput);let f=document.createElement(`div`);f.className=`tcw-alerts-row-fields tcw-alerts-options`;let p=document.createElement(`label`);p.className=`tcw-alerts-check`,this.closeCheck=document.createElement(`input`),this.closeCheck.type=`checkbox`,p.append(this.closeCheck,document.createTextNode(this.t(`alerts.onBarClose`))),this.expirySelect=document.createElement(`select`),this.expirySelect.className=`tcw-alerts-expiry`,this.expirySelect.setAttribute(`aria-label`,this.t(`alerts.expires`));for(let e of[`never`,`hour`,`day`,`week`,`month`]){let t=document.createElement(`option`);t.value=e,t.textContent=this.t(`alerts.expires.${e}`),this.expirySelect.appendChild(t)}f.append(p,this.expirySelect),this.messageInput=document.createElement(`input`),this.messageInput.type=`text`,this.messageInput.placeholder=this.t(`alerts.note`),this.messageInput.setAttribute(`aria-label`,this.t(`alerts.note`)),this.messageInput.className=`tcw-alerts-message`;let m=document.createElement(`button`);m.type=`submit`,m.className=`tcw-alerts-add`,m.innerHTML=`${i.i(`plus`,14)}<span>${a.u(this.t(`alerts.add`))}</span>`,u.append(this.sourceSelect,this.conditionSelect,this.levelRow,this.moveRow,f,this.messageInput,m),u.addEventListener(`submit`,e=>{e.preventDefault(),this.submitForm()}),this.el.appendChild(u),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-alerts-list`,this.el.appendChild(this.listEl),this.emptyEl=document.createElement(`div`),this.emptyEl.className=`tcw-alerts-empty`,this.emptyEl.textContent=this.t(`alerts.empty`),this.listEl.appendChild(this.emptyEl),this.renderSources(),this.showFields(),this.placeForm(),e.appendChild(this.el)}placeForm(){let e=this.formChoice??this.alerts.length===0;this.formEl.hidden=!e,this.newBtn.setAttribute(`aria-expanded`,String(e))}showForm(e){this.formChoice=e,this.placeForm(),e&&(this.prefillPrice(),this.priceInput.focus())}numberField(e,t,n,r){let i=document.createElement(`input`);return i.type=`number`,i.step=r,i.min=`0`,i.value=n,i.className=e,i.placeholder=t,i.setAttribute(`aria-label`,t),i}showFields(){let e=Bn.includes(this.conditionSelect.value);this.moveRow.hidden=!e,this.levelRow.hidden=e,this.priceInput.hidden=this.targetSelect.value!==Hn}renderTargets(){let e=this.targetSelect.value,t=this.sourceSelect.value||`price`;this.targetSelect.replaceChildren();let n=document.createElement(`option`);n.value=Hn,n.textContent=this.t(`alerts.compare.value`),this.targetSelect.appendChild(n);for(let e of this.sources){if(e.channel===t)continue;let n=document.createElement(`option`);n.value=e.channel,n.textContent=e.label,this.targetSelect.appendChild(n)}this.targetSelect.value=[...this.targetSelect.options].some(t=>t.value===e)?e:Hn,this.showFields()}setSources(e){this.sources=e.length>0?e:[{channel:`price`,label:this.t(`alerts.source.price`)}],this.renderSources()}renderSources(){let e=this.sourceSelect.value||`price`;this.sourceSelect.replaceChildren();for(let e of this.sources){let t=document.createElement(`option`);t.value=e.channel,t.textContent=e.label,this.sourceSelect.appendChild(t)}this.sourceSelect.value=this.sources.some(t=>t.channel===e)?e:`price`,this.renderTargets()}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.priceInput.value===``&&this.prefillPrice()}prefillPrice(){let e=this.callbacks.getChannelValue(this.sourceSelect.value||`price`);this.priceInput.value=e===null?``:String(Wn(e))}close(){this.open=!1,this.el.hidden=!0}setAlerts(e){this.alerts=e,e.length===0&&(this.formChoice=null),this.renderList(),this.placeForm()}destroy(){this.el.remove()}submitForm(){let e=this.conditionSelect.value,t=this.messageInput.value.trim()||void 0,n=this.sourceSelect.value||`price`,r=this.sources.find(e=>e.channel===n)?.label??this.t(`alerts.source.price`),i={},a=NaN;if(Bn.includes(e)){i.percent=Number(this.percentInput.value),i.bars=Number(this.barsInput.value);let e=Number.isInteger(i.bars)&&i.bars>=d.MIN_ALERT_BARS&&i.bars<=d.MAX_ALERT_BARS;if(!(i.percent>0)||!e){this.markInvalid(i.percent>0?this.barsInput:this.percentInput);return}}else if(this.targetSelect.value!==Hn)i.target=this.targetSelect.value;else if(a=Number(this.priceInput.value),this.priceInput.value.trim()===``||!Number.isFinite(a)){this.markInvalid(this.priceInput);return}this.closeCheck.checked&&(i.onBarClose=!0);let o=Vn[this.expirySelect.value];if(o&&(i.expiresAt=(this.callbacks.now??Date.now)()+o),this.callbacks.onAdd({price:a,condition:e,message:t,channel:n,label:r,options:i})===!1)return;this.messageInput.value=``,this.prefillPrice();let s=this.formEl.contains(document.activeElement);this.formChoice=!1,this.placeForm(),s&&this.newBtn.focus()}markInvalid(e){e.setAttribute(`aria-invalid`,`true`),e.focus(),e.addEventListener(`input`,()=>e.removeAttribute(`aria-invalid`),{once:!0})}describe(e){return Rn(e,this.t,this.callbacks.formatPrice)}renderList(){if(this.listEl.replaceChildren(),this.alerts.length===0){this.listEl.appendChild(this.emptyEl);return}for(let e of[...this.alerts].reverse()){let t=document.createElement(`div`);t.className=`tcw-alerts-row`+(e.triggered?` tcw-alerts-triggered`:``)+(e.expired?` tcw-alerts-expired`:``);let n=document.createElement(`div`);n.className=`tcw-alerts-info`;let r=document.createElement(`div`);r.className=`tcw-alerts-row-main`,r.textContent=this.describe(e),n.appendChild(r);let a=[];if(e.onBarClose&&a.push(this.t(`alerts.onClose`)),e.expiresAt!==void 0&&!e.expired){let t=this.callbacks.formatTime?.(e.expiresAt)??new Date(e.expiresAt).toISOString();a.push(s.r(this.t(`alerts.until`),{time:t}))}if(a.length>0){let e=document.createElement(`div`);e.className=`tcw-alerts-row-meta`,e.textContent=a.join(` · `),n.appendChild(e)}if(e.message){let t=document.createElement(`div`);t.className=`tcw-alerts-row-note`,t.textContent=e.message,n.appendChild(t)}if(e.triggered||e.expired){let t=document.createElement(`span`);t.className=`tcw-alerts-badge`,t.textContent=this.t(e.expired?`alerts.expired`:`alerts.triggered`),r.appendChild(t)}let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-alerts-del`,o.setAttribute(`aria-label`,this.t(`alerts.delete`)),o.innerHTML=i.i(`trash`,14),o.addEventListener(`click`,()=>this.callbacks.onRemove(e.id)),t.appendChild(n),t.appendChild(o),this.listEl.appendChild(t)}}},qn=`print`,Jn=3,Yn=10,Xn=[[3400,1/2],[2560,1/3],[1800,1/6]],Zn=Math.sqrt(u.PHI),Qn=3,$n=1.4,er=[2,4,6,8,12,20,32],tr=[2,3,5,8,13,21,34],nr={even:er[4],classic:tr[3]},rr=`calc-size(max-content, round(up, size, 1px))`,ir={even:[20,16],classic:[19,15]};function ar(e){return e!==`classic`&&e!==`compact`}var or=.5,sr=3,cr=.75,lr=2;function ur(e){let t=Xn.find(([t])=>e>=t);return t?u.PHI**t[1]:1}function dr(e,t){if(t===1)return e;let n=e.sizes,r=ar(e.density),i=e=>r?(0,u.evenPx)(e*t):Math.round(e*t);return{...e,sizes:{toolbar:i(n.toolbar),control:i(n.control),controlSmall:i(n.controlSmall),icon:i(n.icon),sidebar:i(n.sidebar),menuItem:i(n.menuItem)},font:{...e.font,size:Math.round(e.font.size*t)}}}function M(e,t){return Math.max(Yn,(0,u.phiStep)(e,t,Jn))}var fr=`system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`,pr=`'JetBrains Mono', 'SF Mono', 'Cascadia Code', 'Fira Code', 'Consolas', ui-monospace, monospace`,mr=u.SANS_FONT_FAMILY.replace(`'Segoe UI'`,`'Segoe UI Variable Text', 'Segoe UI'`),hr=u.FIGURES_FONT_FAMILY,gr=`Tahoma, Verdana, 'Segoe UI', 'DejaVu Sans', sans-serif`,_r={print:{radius:{xs:1,sm:2,md:3,lg:5,xl:8},components:{tag:2,toolbar:0,sidebar:0},sizes:{toolbar:42,control:34,controlSmall:26,icon:20,sidebar:42,menuItem:34},classic:{control:33,menuItem:33},density:{compact:{toolbar:33,control:26,controlSmall:20,icon:16,sidebar:32,menuItem:26},spacious:{toolbar:54,control:42,controlSmall:34,icon:26,sidebar:60,menuItem:42}},font:{family:mr,mono:hr,size:13,weight:400,strongWeight:500,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-lg)`,dialog:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-lg)`,tooltip:`var(--tcw-shadow-sm)`},blur:0,active:`solid`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:2,iconStroke:1},studio:{radius:{xs:3,sm:5,md:7,lg:11,xl:16},components:{toolbar:0,sidebar:0},sizes:{toolbar:46,control:30,controlSmall:24,icon:18,sidebar:44,menuItem:30},font:{family:`'Manrope', 'Inter', ${fr}`,mono:pr,size:13,weight:500,strongWeight:600,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!1},shadows:{menu:`var(--tcw-shadow-lg)`,dialog:`var(--tcw-shadow-xl)`,tooltip:`var(--tcw-shadow-md)`},blur:0,active:`tint`,toolbar:`docked`,sidebar:`docked`,intervals:`segmented`,tagRadius:4,iconStroke:0},terminal:{radius:{xs:1,sm:2,md:2,lg:2,xl:3},components:{tag:0,toolbar:0,sidebar:0},sizes:{toolbar:36,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},classic:{sidebar:39},font:{family:`'IBM Plex Sans Condensed', 'Roboto Condensed', 'Arial Narrow', ${fr}`,mono:`'IBM Plex Mono', ui-monospace, monospace`,size:12,weight:500,strongWeight:600,labelCase:`uppercase`,labelTracking:.08},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border-strong)`,dialog:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-lg)`,tooltip:`none`},blur:0,active:`underline`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:0,iconStroke:0},capsule:{radius:{xs:6,sm:10,md:999,lg:18,xl:24},components:{tooltip:10,toolbar:999,sidebar:999,toast:999,tag:999},sizes:{toolbar:44,control:32,controlSmall:26,icon:18,sidebar:48,menuItem:34},classic:{sidebar:47},font:{family:`'Sora', 'Manrope', ${fr}`,mono:pr,size:13,weight:500,strongWeight:600,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!1},shadows:{menu:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-xl)`,dialog:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-xl)`,tooltip:`var(--tcw-shadow-lg)`},blur:16,active:`solid`,toolbar:`floating`,sidebar:`floating`,intervals:`segmented`,tagRadius:999,iconStroke:0},desk:{radius:{xs:0,sm:1,md:2,lg:2,xl:3},components:{tag:0,toolbar:0,sidebar:0},sizes:{toolbar:34,control:24,controlSmall:20,icon:16,sidebar:38,menuItem:24},classic:{sidebar:37},font:{family:gr,mono:gr,size:12,weight:400,strongWeight:700,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-sm)`,dialog:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-md)`,tooltip:`0 0 0 1px var(--tcw-border)`},blur:0,active:`tint`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:0,iconStroke:0}},vr={compact:{toolbar:38,control:26,controlSmall:20,icon:16,sidebar:32,menuItem:26},spacious:{toolbar:52,control:34,controlSmall:28,icon:20,sidebar:50,menuItem:34}};function yr(e,t){return t===`classic`?{...e.sizes,...e.classic}:t===`compact`?(e.density??vr).compact:t===`spacious`||t===`airy`?(e.density??vr).spacious:e.sizes}function br(e,t){return{control:e.md,input:e.md,menu:e.lg,dialog:e.xl,panel:e.lg,tooltip:e.sm,tag:e.sm,toast:e.lg,toolbar:0,sidebar:0,...t}}var xr=Object.freeze(Object.fromEntries(Object.keys(_r).map(e=>[e,Cr(Sr(e))])));function Sr(e){let{density:t,classic:n,...r}=_r[e];return{...r,preset:e,density:`comfortable`,scale:`auto`,radius:{...r.radius},components:br(r.radius,r.components),sizes:{...r.sizes},font:{...r.font},borders:{...r.borders},shadows:{...r.shadows}}}function Cr(e){for(let t of Object.values(e))t&&typeof t==`object`&&Cr(t);return Object.freeze(e)}var wr=e=>typeof e==`string`&&Object.prototype.hasOwnProperty.call(_r,e),N=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,Tr=e=>typeof e==`string`&&e.trim().length>0&&e.length<=300&&!/[;{}<>\\]|url\s*\(|expression\s*\(|\/\*/i.test(e)&&Er(e);function Er(e){let t=0,n=``;for(let r of e)if(n)r===n&&(n=``);else if(r===`"`||r===`'`)n=r;else if(r===`(`)t++;else if(r===`)`&&--t<0)return!1;return t===0&&!n}var P=(e,t)=>typeof e==`string`&&t.includes(e);function F(e,t,n){let r={...e};if(!t||typeof t!=`object`)return r;for(let i of Object.keys(e)){let e=t[i];e!==void 0&&n(i,e)&&(r[i]=e)}return r}function I(e){let t=typeof e==`string`?{preset:e}:e??{},n=wr(t.preset)?t.preset:qn,r=_r[n],i=F(r.radius,t.radius,(e,t)=>N(t,0,999)),a=P(t.density,[`compact`,`classic`,`comfortable`,`spacious`,`airy`])?t.density:`comfortable`,o=F(yr(r,a),t.sizes,(e,t)=>e===`icon`?N(t,10,32):N(t,16,80)),s=F(r.font,t.font,(e,t)=>e===`family`||e===`mono`?Tr(t):e===`size`?N(t,11,20):e===`weight`||e===`strongWeight`?N(t,100,900):e===`labelCase`?t===`none`||t===`uppercase`:N(t,0,.5)),c=s.family===mr?u.SANS_FONT_FAMILY:s.family,l=a===`airy`&&t.font?.mono===void 0?{...s,mono:c}:s;return{preset:n,density:a,radius:i,components:F(br(i,r.components),t.components,(e,t)=>N(t,0,999)),sizes:o,font:l,borders:F(r.borders,t.borders,(e,t)=>e===`width`?N(t,0,4):typeof t==`boolean`),shadows:F(r.shadows,t.shadows,(e,t)=>Tr(t)),blur:N(t.blur,0,40)?t.blur:r.blur,active:P(t.active,[`tint`,`solid`,`underline`])?t.active:r.active,toolbar:P(t.toolbar,[`docked`,`floating`])?t.toolbar:r.toolbar,sidebar:P(t.sidebar,[`docked`,`floating`])?t.sidebar:r.sidebar,intervals:P(t.intervals,[`plain`,`segmented`])?t.intervals:r.intervals,tagRadius:N(t.tagRadius,0,999)?t.tagRadius:r.tagRadius,iconStroke:t.iconStroke===0||N(t.iconStroke,or,sr)?t.iconStroke:r.iconStroke,scale:typeof t.scale==`number`&&Number.isFinite(t.scale)&&t.scale>=cr&&t.scale<=lr?t.scale:`auto`}}function Dr(e){let t=e=>`${e}px`,n=e.radius,r=e.components,i=e.sizes,a=e.font,o=e.density===`compact`,s=ar(e.density),c=o?1:Zn,l=s?(0,u.evenPx)(i.control*Zn):Math.round(i.control*Zn),d=o?i.control:Math.min(l,i.sidebar-2*Qn),f=s?er:tr,p=t(s?nr.even:nr.classic),[m,h]=s?ir.even:ir.classic;return{...Object.fromEntries(f.map((e,n)=>[`--tcw-space-${n+1}`,t(e)])),"--tcw-control-pad":p,"--tcw-bar-pad":p,"--tcw-menu-row-pad":p,"--tcw-odd":s?`0px`:`1px`,"--tcw-line-height":String(s?Math.round((0,u.evenPx)(a.size*$n)/a.size*1e5)/1e5:$n),"--tcw-legend-line":t(m),"--tcw-legend-line-pane":t(h),"--tcw-line-xs":s?t((0,u.evenPx)(M(a.size,-2)*$n)):String($n),"--tcw-text-w":s?rr:`auto`,"--tcw-radius-xs":t(n.xs),"--tcw-radius-sm":t(n.sm),"--tcw-radius":t(n.md),"--tcw-radius-lg":t(n.lg),"--tcw-radius-xl":t(n.xl),"--tcw-control-radius":t(r.control),"--tcw-input-radius":t(r.input),"--tcw-menu-radius":t(r.menu),"--tcw-dialog-radius":t(r.dialog),"--tcw-panel-radius":t(r.panel),"--tcw-tooltip-radius":t(r.tooltip),"--tcw-tag-radius":t(r.tag),"--tcw-toast-radius":t(r.toast),"--tcw-toolbar-radius":t(r.toolbar),"--tcw-sidebar-radius":t(r.sidebar),"--tcw-toolbar-h":t(i.toolbar),"--tcw-control-h":t(i.control),"--tcw-control-h-sm":t(i.controlSmall),"--tcw-icon":t(i.icon),"--tcw-sidebar-w":t(i.sidebar),"--tcw-tool-h":t(d),"--tcw-tool-icon":t(2*Math.round(i.icon*c/2)),"--tcw-menu-item-h":t(i.menuItem),"--tcw-icon-stroke":t(e.iconStroke??0),"--tcw-font":a.family,"--tcw-font-mono":a.mono,"--tcw-font-size":t(a.size),"--tcw-font-size-sm":t(M(a.size,-1)),"--tcw-font-size-xs":t(M(a.size,-2)),"--tcw-font-size-lg":t(M(a.size,1)),"--tcw-font-size-xl":t(M(a.size,2)),"--tcw-font-size-display":t(M(a.size,3)),"--tcw-weight":String(a.weight),"--tcw-weight-strong":String(a.strongWeight),"--tcw-label-case":a.labelCase,"--tcw-label-tracking":`${a.labelTracking}em`,"--tcw-label-size":t(M(a.size,a.labelCase===`uppercase`?-2:-1)),"--tcw-border-w":t(e.borders.width),"--tcw-sep-w":e.borders.separators?t(Math.max(1,e.borders.width)):`0px`,"--tcw-menu-shadow":e.shadows.menu,"--tcw-dialog-shadow":e.shadows.dialog,"--tcw-tooltip-shadow":e.shadows.tooltip,"--tcw-blur":t(e.blur),"--tcw-surface-opacity":e.blur>0?`82%`:`100%`}}function Or(e,t,n={}){let r=n.variables!==!1;for(let[n,i]of Object.entries(Dr(t)))r?e.style.setProperty(n,i):e.style.removeProperty(n);e.dataset.tcwUi=t.preset,e.dataset.tcwActive=t.active,e.dataset.tcwToolbar=t.toolbar,e.dataset.tcwSidebar=t.sidebar,e.dataset.tcwIntervals=t.intervals,e.dataset.tcwSeparators=t.borders.separators?`on`:`off`,e.dataset.tcwIconStroke=(t.iconStroke??0)>0?`set`:`drawn`}var kr=class{el;indicatorsEl;drawingsEl;compareEl=null;callbacks;open=!1;drawingIndex=new Map;loose=[];pending=null;renaming=!1;dragging=null;constructor(e,t,n=s.t){this.t=n,this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-tree-panel`,r.o(this.el,`objectTree`),this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-tree-header`;let o=document.createElement(`span`);o.textContent=this.t(`objects.title`);let c=document.createElement(`button`);if(c.type=`button`,c.className=`tcw-tree-close`,c.setAttribute(`aria-label`,this.t(`objects.close`)),c.innerHTML=i.i(`x`,14),c.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),a.appendChild(o),a.appendChild(c),this.el.appendChild(a),this.indicatorsEl=this.makeSection(this.t(`objects.indicators`)),this.drawingsEl=this.makeSection(this.t(`objects.drawings`)),this.callbacks.onAddCompare){this.compareEl=this.makeSection(this.t(`objects.compare`),{label:this.t(`objects.addCompare`),run:()=>this.callbacks.onAddCompare?.()});let e=this.compareEl.parentElement?.querySelector(`.tcw-tree-add`);e&&r.o(e,`compare`)}e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}destroy(){this.pending=null,this.dragging?.stop(),this.el.remove()}setObjects(e,t,n=[]){this.renderIndicators(e),this.renderDrawings(t),this.renderCompares(n)}makeSection(e,t){let n=document.createElement(`div`);n.className=`tcw-tree-section`;let r=document.createElement(`div`);r.className=`tcw-tree-section-head`;let a=document.createElement(`span`);if(a.textContent=e,r.appendChild(a),t){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-tree-add`,e.setAttribute(`aria-label`,t.label),e.title=t.label,e.innerHTML=i.i(`plus`,13),e.addEventListener(`click`,t.run),r.appendChild(e)}let o=document.createElement(`div`);return o.className=`tcw-tree-list`,n.appendChild(r),n.appendChild(o),this.el.appendChild(n),o}renderIndicators(e){if(this.indicatorsEl.replaceChildren(),e.length===0){this.indicatorsEl.appendChild(this.emptyRow(this.t(`objects.noIndicators`)));return}for(let t of e){let e=this.row(t.name,t.title);t.visible||e.classList.add(`tcw-tree-hidden`);let n=document.createElement(`div`);if(n.className=`tcw-tree-actions`,this.callbacks.onToggleIndicatorVisible&&n.appendChild(this.iconButton(t.visible?`eye`:`eyeOff`,t.visible?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleIndicatorVisible?.(t.instanceId,!t.visible))),this.callbacks.onConfigureIndicator){let e=this.iconButton(`settings`,this.t(`objects.indicatorSettings`),``,()=>this.callbacks.onConfigureIndicator?.(t.instanceId));r.o(e,`indicatorSettings`),n.appendChild(e)}n.appendChild(this.iconButton(`trash`,this.t(`objects.removeIndicator`),`tcw-tree-del`,()=>this.callbacks.onRemoveIndicator(t.instanceId))),e.appendChild(n),this.indicatorsEl.appendChild(e)}}renderDrawings(e){if(this.renaming||this.dragging){this.pending=e;return}this.pending=null;let t=document.activeElement?.closest(`.tcw-tree-grip`)?.closest(`[data-drawing-id]`)?.dataset.drawingId;this.drawingIndex=new Map(e.map((e,t)=>[e.id,t]));let n=[...e].reverse();this.loose=n.filter(e=>!e.group).map(e=>e.id),this.drawingsEl.replaceChildren(),this.listDrawings(n),t&&this.drawingsEl.querySelector(`[data-drawing-id="${t}"] .tcw-tree-grip`)?.focus()}flushPending(){this.pending&&!this.renaming&&!this.dragging&&this.renderDrawings(this.pending)}listDrawings(e){if(e.length===0){this.drawingsEl.appendChild(this.emptyRow(this.t(`objects.noDrawings`)));return}let t=new Set;for(let n of e){if(!n.group){this.drawingsEl.appendChild(this.drawingRow(n));continue}if(t.has(n.group.id))continue;t.add(n.group.id);let r=n.group.id,i=e.filter(e=>e.group?.id===r);this.drawingsEl.appendChild(this.groupRow(r,n.group.name,i));for(let e of i){let t=this.drawingRow(e);t.classList.add(`tcw-tree-member`),this.drawingsEl.appendChild(t)}}}groupRow(e,t,n){let r=this.row(t);r.classList.add(`tcw-tree-group`);let a=n.some(e=>e.visible),o=n.every(e=>e.locked);a||r.classList.add(`tcw-tree-hidden`);let s=r.querySelector(`.tcw-tree-name`);s.innerHTML=i.i(`layers`,13),s.append(` ${t}`);let c=document.createElement(`div`);return c.className=`tcw-tree-actions`,this.callbacks.onRenameGroup&&(s.addEventListener(`dblclick`,()=>this.renameGroup(s,e,t)),c.appendChild(this.iconButton(`penLine`,this.t(`objects.renameGroup`),``,()=>this.renameGroup(s,e,t)))),this.callbacks.onToggleGroupVisible&&c.appendChild(this.iconButton(a?`eye`:`eyeOff`,a?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleGroupVisible?.(e,!a))),this.callbacks.onToggleGroupLocked&&c.appendChild(this.iconButton(o?`lock`:`unlock`,o?this.t(`common.unlock`):this.t(`common.lock`),o?`tcw-tree-on`:``,()=>this.callbacks.onToggleGroupLocked?.(e,!o))),this.callbacks.onUngroup&&c.appendChild(this.iconButton(`x`,this.t(`drawingMenu.ungroup`),``,()=>this.callbacks.onUngroup?.(e))),r.appendChild(c),r}renameGroup(e,t,n){this.renameInline(e,n,this.t(`objects.renameGroup`),e=>{e&&e!==n&&this.callbacks.onRenameGroup?.(t,e)})}renameInline(e,t,n,r){if(!e.isConnected)return;this.renaming=!0;let i=document.createElement(`input`);i.type=`text`,i.className=`tcw-tree-rename`,i.value=t,i.maxLength=Ar,i.setAttribute(`aria-label`,n);let a=!1,o=t=>{if(a)return;a=!0;let n=i.value.trim();i.isConnected&&i.replaceWith(e),this.renaming=!1,t&&r(n),this.flushPending()};i.addEventListener(`keydown`,e=>{e.key===`Enter`?o(!0):e.key===`Escape`&&(e.stopPropagation(),o(!1))}),i.addEventListener(`blur`,()=>o(!0)),e.replaceWith(i),i.focus(),i.select()}drawingRow(e){let t=this.row(e.label);t.dataset.drawingId=e.id,(!e.visible||e.offInterval)&&t.classList.add(`tcw-tree-hidden`),e.offInterval&&(t.title=this.t(`indicatorSettings.offInterval`)),this.callbacks.onMoveDrawing&&!e.group&&(t.dataset.reorder=`true`,t.insertBefore(this.grip(e.id),t.firstChild));let n=t.querySelector(`.tcw-tree-name`);this.callbacks.onSelectDrawing&&(n.classList.add(`tcw-tree-pick`),n.addEventListener(`click`,()=>this.callbacks.onSelectDrawing?.(e.id))),this.callbacks.onRenameDrawing&&n.addEventListener(`dblclick`,()=>this.renameInline(n,e.label,this.t(`objects.renameDrawing`),t=>{t!==e.label&&this.callbacks.onRenameDrawing?.(e.id,t)}));let i=document.createElement(`div`);if(i.className=`tcw-tree-actions`,i.appendChild(this.iconButton(e.visible?`eye`:`eyeOff`,e.visible?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleDrawingVisible(e.id,!e.visible))),i.appendChild(this.iconButton(e.locked?`lock`:`unlock`,e.locked?this.t(`common.unlock`):this.t(`common.lock`),e.locked?`tcw-tree-on`:``,()=>this.callbacks.onToggleDrawingLocked(e.id,!e.locked))),this.callbacks.onCloneDrawing&&i.appendChild(this.iconButton(`copy`,this.t(`objects.cloneDrawing`),``,()=>this.callbacks.onCloneDrawing?.(e.id))),this.callbacks.onConfigureDrawing){let t=this.iconButton(`settings`,this.t(`objects.drawingSettings`),``,()=>this.callbacks.onConfigureDrawing?.(e.id));r.o(t,`drawingSettings`),i.appendChild(t)}return i.appendChild(this.iconButton(`trash`,this.t(`objects.removeDrawing`),`tcw-tree-del`,()=>this.callbacks.onRemoveDrawing(e.id))),t.appendChild(i),t}grip(e){let t=this.iconButton(`grip`,this.t(`objects.dragToReorder`),`tcw-tree-grip`,()=>{});return t.setAttribute(`aria-keyshortcuts`,`ArrowUp ArrowDown`),t.addEventListener(`pointerdown`,t=>{t.button===0&&(t.preventDefault(),this.beginRowDrag(e))}),t.addEventListener(`keydown`,t=>{let n=t.key===`ArrowUp`?-1:+(t.key===`ArrowDown`);if(!n)return;t.preventDefault();let r=this.loose[this.loose.indexOf(e)+n],i=r===void 0?void 0:this.drawingIndex.get(r);i!==void 0&&this.callbacks.onMoveDrawing?.(e,i)}),t}beginRowDrag(e){this.dragging?.stop();let t=null,n=n=>{t?.classList.remove(`tcw-tree-drop`),t=n&&n.dataset.drawingId!==e?n:null,t?.classList.add(`tcw-tree-drop`)},r=(e,t)=>[...this.drawingsEl.querySelectorAll(`.tcw-tree-row[data-reorder]`)].find(n=>{let r=n.getBoundingClientRect();return t>=r.top&&t<r.bottom&&e>=r.left&&e<r.right})??null,i=e=>r(e.clientX,e.clientY),a=e=>n(i(e)),o=e=>{e.key===`Escape`&&(e.stopPropagation(),c())},s=r=>{n(i(r));let a=t?this.drawingIndex.get(t.dataset.drawingId??``):void 0;c(),a!==void 0&&this.callbacks.onMoveDrawing?.(e,a)},c=()=>{n(null),document.removeEventListener(`pointermove`,a),document.removeEventListener(`pointerup`,s),document.removeEventListener(`pointercancel`,c),document.removeEventListener(`keydown`,o,!0),this.dragging=null,this.flushPending()};document.addEventListener(`pointermove`,a),document.addEventListener(`pointerup`,s),document.addEventListener(`pointercancel`,c),document.addEventListener(`keydown`,o,!0),this.dragging={id:e,stop:c}}renderCompares(e){if(!this.compareEl)return;if(this.compareEl.replaceChildren(),e.length===0){this.compareEl.appendChild(this.emptyRow(this.t(`objects.noComparisons`)));return}let t=e.some(e=>e.color);for(let n of e){let e=this.row(n.label);if(e.classList.add(`tcw-tree-compare`),t){let t=document.createElement(`span`);t.className=`tcw-tree-dot`,n.color&&(t.style.background=n.color),e.insertBefore(t,e.firstChild)}if(n.way){let t=document.createElement(`span`);t.className=`tcw-tree-way`,t.textContent=n.way,t.title=n.way,e.appendChild(t)}this.callbacks.onRemoveCompare&&e.appendChild(this.iconButton(`trash`,this.t(`objects.removeComparison`),`tcw-tree-del`,()=>this.callbacks.onRemoveCompare?.(n.id))),this.compareEl.appendChild(e)}}row(e,t=e){let n=document.createElement(`div`);n.className=`tcw-tree-row`;let r=document.createElement(`span`);return r.className=`tcw-tree-name`,r.textContent=e,r.title=t,n.appendChild(r),n}emptyRow(e){let t=document.createElement(`div`);return t.className=`tcw-tree-empty`,t.textContent=e,t}iconButton(e,t,n,r){let a=document.createElement(`button`);return a.type=`button`,a.className=`tcw-tree-btn ${n}`.trim(),a.setAttribute(`aria-label`,t),a.title=t,a.innerHTML=i.i(e,14),a.addEventListener(`click`,r),a}},Ar=80,jr={trendLine:`Trend Line`,ray:`Ray`,extendedLine:`Extended Line`,horizontalLine:`Horizontal Line`,horizontalRay:`Horizontal Ray`,crossLine:`Cross Line`,infoLine:`Info Line`,trendAngle:`Trend Angle`,circle:`Circle`,fibChannel:`Fib Channel`,fibSpeedResistanceFan:`Fib Speed Resistance Fan`,schiffPitchfork:`Schiff Pitchfork`,modifiedSchiffPitchfork:`Modified Schiff Pitchfork`,xabcdPattern:`XABCD Pattern`,abcdPattern:`ABCD Pattern`,headAndShoulders:`Head and Shoulders`,dateAndPriceRange:`Date and Price Range`,cyclicLines:`Cyclic Lines`,priceLabel:`Price Label`,verticalLine:`Vertical Line`,rectangle:`Rectangle`,ellipse:`Ellipse`,triangle:`Triangle`,arrow:`Arrow`,parallelChannel:`Parallel Channel`,regressionChannel:`Regression Channel`,pitchfork:`Pitchfork`,fibRetracement:`Fib Retracement`,fibExtension:`Fib Extension`,fibTimeZones:`Fib Time Zones`,gannBox:`Gann Box`,gannFan:`Gann Fan`,elliottWave:`Elliott Wave`,priceRange:`Price Range`,dateRange:`Date Range`,measure:`Measure`,text:`Text`,textAnnotation:`Text`,anchoredVWAP:`Anchored VWAP`,volumeProfileRange:`Volume Profile`,riskReward:`Long/Short Position`,signpost:`Signpost`,balloon:`Balloon`,anchoredText:`Anchored Text`,anchoredNote:`Anchored Note`};function Mr(e,t){let n=`tool.${e}`,r=t?.(n);return r&&r!==n?r:jr[e]??e}function Nr(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Pr=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Fr(e){return Pr(e)?Object.fromEntries(Object.entries(e).filter(([,e])=>typeof e==`number`&&Number.isFinite(e)||typeof e==`string`&&!(0,u.parseIndicatorSource)(e)||typeof e==`boolean`)):{}}function Ir(e){if(!Pr(e))return{};let t={};if(Array.isArray(e.colors)){let n=e.colors.filter(e=>typeof e==`string`&&e.trim()!==``);n.length>0&&(t.colors=n)}if(Array.isArray(e.lineWidths)){let n=e.lineWidths.filter(e=>typeof e==`number`&&Number.isFinite(e)&&e>0);n.length>0&&(t.lineWidths=n)}let n=(0,u.readIndicatorPlotStyles)(e.plots);return n&&(t.plots=n),t}var Lr=class{constructor(e=`tcw:indicator-defaults`,t=Nr()){this.key=e,this.storage=t}all(){let e=new Map,t;try{t=JSON.parse(this.storage?.getItem(this.key)??`{}`)}catch{return e}if(!Pr(t))return e;for(let[n,r]of Object.entries(t))Pr(r)&&e.set(n,{params:Fr(r.params),style:Ir(r.style)});return e}get(e){return this.all().get(e)??null}save(e,t){if(!this.storage)return!1;let n=Object.fromEntries([...this.all(),[e,{params:Fr(t.params),style:Ir(t.style)}]]);try{return this.storage.setItem(this.key,JSON.stringify(n)),!0}catch{return!1}}},Rr=1,zr=[`logScale`,`autoScale`],Br=new Set([`timezone`,`numberLocale`,`crosshairCursor`]),Vr=new Set([...zr,`chartTypeOptions`]),Hr=new Set([...zr,...Br,`scaleMode`,`invertScale`,`chartTypeOptions`]),Ur=new Set([...zr,...Br,`scaleMode`]),Wr=new Set,Gr=[`renko`,`lineBreak`,`kagi`,`pointAndFigure`,`rangeBars`];function Kr(e){return Gr.includes(e)}function qr(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>Zr(e)&&Object.keys(e).length>0))}function Jr(){return Object.fromEntries(Gr.map(e=>[e,{}]))}var Yr={crosshairMode:[`normal`,`magnet`,`hidden`],crosshairCursor:[`cross`,`dot`,`arrow`],scaleMode:[`regular`,`logarithmic`,`percentage`,`indexedTo100`],periodLevelsPeriod:[`day`,`week`]},Xr={marketProfileBuckets:{min:8,max:200,whole:!0},marketProfileOpacity:{min:.05,max:1},depthHeatmapOpacity:{min:.1,max:1},pivotStrength:{min:2,max:20,whole:!0}},Zr=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Qr(e){return e===`local`||t.v(e)!==null}function $r(e){try{return Intl.NumberFormat.supportedLocalesOf(e).length>0}catch{return!1}}function ei(e,n){let r=t.h[e];if(e===`chartTypeOptions`)return Zr(n)?(0,u.readChartTypeOptions)(n):void 0;if(typeof n!=typeof r)return;if(typeof n==`number`){if(!Number.isFinite(n))return;let t=Xr[e];if(!t)return n;let r=Math.min(t.max,Math.max(t.min,n));return t.whole?Math.round(r):r}if(typeof n!=`string`)return n;let i=Yr[e];return i?i.includes(n)?n:void 0:e===`timezone`?Qr(n)?n:void 0:e===`numberLocale`?$r(n)?n:void 0:n}function L(e,n=Wr){if(!Zr(e))return{};let r={};for(let i of Object.keys(t.h)){if(n.has(i)||!Object.prototype.hasOwnProperty.call(e,i))continue;let t=ei(i,e[i]);t!==void 0&&(r[i]=t)}return r}function ti(e,t){return Object.fromEntries(Object.keys(e).filter(e=>!t.has(e)).map(t=>[t,e[t]]))}function ni(e,t,n){return Object.fromEntries(Object.keys(e).filter(r=>!n.has(r)&&JSON.stringify(e[r])!==JSON.stringify(t[r])).map(t=>[t,e[t]]))}function ri(e,t){return ni({...e,chartTypeOptions:qr(e.chartTypeOptions)},t,Ur)}function ii(e){return e?(e===!0?void 0:e.key)||`tcw:chart-settings`:null}function ai(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var oi=class{constructor(e,t=ai()){this.key=e,this.storage=t}load(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`null`)}catch{return{}}return!Zr(e)||e.v!==Rr?{}:L(e.settings,Vr)}save(e,t){try{this.storage?.setItem(this.key,JSON.stringify({v:Rr,settings:ni(e,t,Vr)}))}catch{}}};function si(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var ci=80;function li(e){let{text:t,...n}=(0,u.sanitizeDrawingStyle)(e);return n}function ui(e){let t={name:e.name,style:{...e.style}};return e.type&&(t.type=e.type),e.options&&(t.options=structuredClone(e.options)),t}var di=class{templates=[];constructor(e=`tcw:draw-templates`,t=si()){this.storageKey=e,this.storage=t,this.load()}list(e){return this.templates.filter(t=>!t.type||t.type===e).map(ui)}get(e,t){let n=this.templates.find(n=>n.name===e&&n.type===t);return n?ui(n):null}save(e,t,n){let r=e.trim().slice(0,ci);if(!r)return;let i={name:r,style:li(t)};n&&(i.type=n.type,i.options=structuredClone(n.options)),this.templates=this.templates.filter(e=>!(e.name===r&&e.type===i.type)),this.templates.push(i),this.persist()}remove(e,t){this.templates=this.templates.filter(n=>!(n.name===e&&n.type===t)),this.persist()}clear(){this.templates=[],this.persist()}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;this.templates=t.filter(e=>e&&typeof e.name==`string`&&e.name.trim()!==``).map(e=>{let t={name:e.name.trim().slice(0,ci),style:li(e.style)};return typeof e.type==`string`&&(t.type=e.type),e.options&&typeof e.options==`object`&&!Array.isArray(e.options)&&(t.options=e.options),t})}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.templates))}catch{}}},fi=class{defaults={};constructor(e=`tcw:drawing-defaults`,t=si()){this.storageKey=e,this.storage=t;try{let e=this.storage?.getItem(this.storageKey),t=e?JSON.parse(e):null;if(t&&typeof t==`object`&&!Array.isArray(t))for(let[e,n]of Object.entries(t))n&&typeof n==`object`&&!Array.isArray(n)&&(this.defaults[e]=n)}catch{}}all(){return structuredClone(this.defaults)}set(e,t){t&&Object.keys(t).length>0?this.defaults[e]=structuredClone(t):delete this.defaults[e];try{this.storage?.setItem(this.storageKey,JSON.stringify(this.defaults))}catch{}}},pi=[`#4c8dff`,`#1fa874`,`#e8505b`,`#f2a93b`,`#a57cff`,`#1398a8`,`#ffffff`,`#7d8696`],mi=[1,2,3,4],hi=[`solid`,`dashed`,`dotted`],gi=class{el;templatesEl;nameInput;callbacks;store;open=!1;constructor(e,t,n,r=s.t){this.t=r,this.callbacks=t,this.store=n,this.el=document.createElement(`div`),this.el.className=`tcw-style-panel`,this.el.hidden=!0;let o=document.createElement(`div`);o.className=`tcw-style-header`;let c=document.createElement(`span`);c.textContent=this.t(`drawingStyle.title`);let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-style-close`,l.setAttribute(`aria-label`,this.t(`common.close`)),l.innerHTML=i.i(`x`,14),l.addEventListener(`click`,()=>this.close()),o.appendChild(c),o.appendChild(l),this.el.appendChild(o),this.el.appendChild(this.colorRow()),this.el.appendChild(this.widthRow()),this.el.appendChild(this.lineStyleRow());let u=document.createElement(`div`);u.className=`tcw-style-subhead`,u.textContent=this.t(`drawingStyle.templates`),this.el.appendChild(u);let d=document.createElement(`div`);d.className=`tcw-style-save`,this.nameInput=document.createElement(`input`),this.nameInput.type=`text`,this.nameInput.placeholder=this.t(`drawingStyle.templateName`),this.nameInput.className=`tcw-style-name`;let f=document.createElement(`button`);f.type=`button`,f.className=`tcw-style-savebtn`,f.innerHTML=`${i.i(`plus`,13)}<span>${a.u(this.t(`common.save`))}</span>`,f.addEventListener(`click`,()=>this.saveTemplate()),d.appendChild(this.nameInput),d.appendChild(f),this.el.appendChild(d),this.templatesEl=document.createElement(`div`),this.templatesEl.className=`tcw-style-templates`,this.el.appendChild(this.templatesEl),e.appendChild(this.el),this.renderTemplates()}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.syncActiveControls(),this.renderTemplates()}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}colorRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-colors`;for(let t of pi){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-swatch`,n.style.background=t,n.dataset.color=t,n.setAttribute(`aria-label`,t),n.addEventListener(`click`,()=>this.applyStyle({color:t})),e.appendChild(n)}let t=document.createElement(`input`);return t.type=`color`,t.className=`tcw-style-picker`,t.addEventListener(`input`,()=>this.applyStyle({color:t.value})),e.appendChild(t),e}widthRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-widths`;for(let t of mi){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-width`,n.dataset.width=String(t);let r=document.createElement(`span`);r.style.height=`${t}px`,n.appendChild(r),n.addEventListener(`click`,()=>this.applyStyle({lineWidth:t})),e.appendChild(n)}return e}lineStyleRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-dashes`;for(let t of hi){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-dash`,n.dataset.linestyle=t,n.textContent=t===`solid`?`──`:t===`dashed`?`╌╌`:`┄┄`,n.title=t,n.addEventListener(`click`,()=>this.applyStyle({lineStyle:t})),e.appendChild(n)}return e}applyStyle(e){this.callbacks.onStyleChange(e),this.syncActiveControls()}syncActiveControls(){let e=this.callbacks.getStyle();this.el.querySelectorAll(`.tcw-style-swatch`).forEach(t=>{t.classList.toggle(`tcw-on`,t.dataset.color?.toLowerCase()===e.color?.toLowerCase())}),this.el.querySelectorAll(`.tcw-style-width`).forEach(t=>{t.classList.toggle(`tcw-on`,Number(t.dataset.width)===e.lineWidth)}),this.el.querySelectorAll(`.tcw-style-dash`).forEach(t=>{t.classList.toggle(`tcw-on`,t.dataset.linestyle===e.lineStyle)})}saveTemplate(){let e=this.nameInput.value.trim();e&&(this.store.save(e,this.callbacks.getStyle()),this.nameInput.value=``,this.renderTemplates())}renderTemplates(){this.templatesEl.replaceChildren();let e=this.store.list();if(e.length===0){let e=document.createElement(`div`);e.className=`tcw-style-empty`,e.textContent=this.t(`drawingStyle.noTemplates`),this.templatesEl.appendChild(e);return}for(let t of e){let e=document.createElement(`div`);e.className=`tcw-style-template`;let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-apply`;let r=document.createElement(`span`);r.className=`tcw-style-tdot`,r.style.background=t.style.color??`var(--tcw-text-muted)`;let a=document.createElement(`span`);a.textContent=t.name,n.appendChild(r),n.appendChild(a),n.addEventListener(`click`,()=>{this.callbacks.onStyleChange({...t.style}),this.syncActiveControls()});let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-style-tdel`,o.setAttribute(`aria-label`,this.t(`drawingStyle.deleteTemplate`)),o.innerHTML=i.i(`trash`,13),o.addEventListener(`click`,()=>{this.store.remove(t.name),this.renderTemplates()}),e.appendChild(n),e.appendChild(o),this.templatesEl.appendChild(e)}}},_i={color:`color`,fill:`fillColor`,textColor:`textColor`},vi=32,yi=.618,R=4,bi=4,xi=20,Si=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d\s.,%/+-]+\)|[a-z]+)$/i;function z(e){return typeof e==`string`&&Si.test(e.trim())?e.trim():`#7d8696`}function Ci(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.min(t,xi):1}function wi(e){return hi.includes(e)?e:`solid`}var Ti=class{el;pop;target=null;built=``;size=null;openPop=null;pinned=null;drag=null;onDragMove=e=>{!this.drag||!this.target||e.pointerId!==this.drag.id||(this.pinned={left:this.drag.left+e.clientX-this.drag.x,top:this.drag.top+e.clientY-this.drag.y},this.place(this.target))};onDragEnd=e=>{e&&this.drag&&e.pointerId!==this.drag.id||(this.drag=null,document.removeEventListener(`pointermove`,this.onDragMove),document.removeEventListener(`pointerup`,this.onDragEnd),document.removeEventListener(`pointercancel`,this.onDragEnd))};onDocDown=e=>{this.openPop&&!this.el.contains(e.target)&&!this.pop.contains(e.target)&&this.closePop()};constructor(e,t,n=s.t){this.host=e,this.callbacks=t,this.t=n,this.el=document.createElement(`div`),this.el.className=`tcw-sel-toolbar`,this.el.setAttribute(`role`,`toolbar`),this.el.setAttribute(`aria-label`,n(`selectionToolbar.label`)),this.el.hidden=!0,this.pop=document.createElement(`div`),this.pop.className=`tcw-sel-pop`,this.pop.setAttribute(`role`,`dialog`),this.pop.hidden=!0,e.append(this.el,this.pop),this.el.addEventListener(`click`,e=>this.onClick(e)),this.el.addEventListener(`keydown`,e=>this.onKey(e)),this.pop.addEventListener(`click`,e=>this.onPick(e)),this.pop.addEventListener(`keydown`,e=>this.onPopKey(e));for(let e of[this.el,this.pop])e.addEventListener(`pointerdown`,e=>e.stopPropagation());this.el.addEventListener(`pointerdown`,e=>{e.target.closest(`.tcw-sel-grip`)&&(e.preventDefault(),this.closePop(),this.drag={id:e.pointerId,x:e.clientX,y:e.clientY,left:parseFloat(this.el.style.left)||0,top:parseFloat(this.el.style.top)||0},document.addEventListener(`pointermove`,this.onDragMove),document.addEventListener(`pointerup`,this.onDragEnd),document.addEventListener(`pointercancel`,this.onDragEnd))}),this.el.addEventListener(`dblclick`,e=>{!e.target.closest(`.tcw-sel-grip`)||!this.target||(this.pinned=null,this.place(this.target))}),document.addEventListener(`pointerdown`,this.onDocDown,!0)}isOpen(){return!this.el.hidden}show(e){this.target=e;let t=e.style,n=[z(t.color),Ci(t.lineWidth),wi(t.lineStyle),e.locked,e.canDelete,e.canSettings,e.canAlert,e.canFill===!0,e.canText===!0,e.canType===!0,t.fillColor,t.textColor].join(`|`);n!==this.built&&(this.built=n,this.render(e),this.size=null),this.el.hidden=!1,this.size||={w:this.el.offsetWidth,h:this.el.offsetHeight},this.place(e),this.openPop&&this.placePop()}hide(){this.closePop(),this.el.hidden=!0,this.target=null}destroy(){this.onDragEnd(),document.removeEventListener(`pointerdown`,this.onDocDown,!0),this.el.remove(),this.pop.remove()}render(e){let t=this.t,n=z(e.style.color),r=Ci(e.style.lineWidth),o=wi(e.style.lineStyle),s=e.locked,c=this.el.contains(document.activeElement)?document.activeElement.dataset.action:void 0,l=(e,t,n,r=``)=>`<button type="button" class="tcw-sel-btn${r}" data-action="${e}" aria-label="${a.u(t)}" title="${a.u(t)}">${n}</button>`,d=(e,t,n)=>l(e,t,n,` tcw-sel-has-pop`).replace(`<button `,`<button aria-haspopup="dialog" aria-expanded="false" `);this.el.innerHTML=[`<span class="tcw-sel-grip" aria-hidden="true"></span>`,d(`color`,t(`drawingSettings.color`),`<span class="tcw-sel-color" style="background:${a.u(n)}"></span>`),d(`width`,t(`drawingSettings.lineWidth`),`<span class="tcw-sel-width" style="--w:${r}px"></span><span class="tcw-sel-num">${r}px</span>`),d(`lineStyle`,t(`drawingSettings.lineStyle`),Ei(o)),e.canFill?d(`fill`,t(`drawingSettings.fill`),`<span class="tcw-sel-color tcw-sel-fill" style="background:${a.u(z((0,u.ownFillColor)(e.style)??n))}"></span>`):``,e.canText?d(`textColor`,t(`drawingSettings.textColor`),`<span class="tcw-sel-text" style="--c:${a.u(z(e.style.textColor??n))}">T</span>`):``,e.canType?l(`text`,t(`drawingSettings.text`),i.i(`textEdit`,15)):``,`<span class="tcw-sel-sep" aria-hidden="true"></span>`,e.canSettings?l(`settings`,t(`legend.settings`),i.i(`settings`,15)):``,e.canAlert?l(`alert`,t(`drawingSettings.addAlert`),i.i(`bell`,15)):``,l(`lock`,t(s?`common.unlock`:`common.lock`),i.i(s?`lock`:`unlock`,15),s?` tcw-sel-on`:``).replace(`<button `,`<button aria-pressed="${s}" `),l(`more`,t(`legend.more`),i.i(`more`,15)),e.canDelete?l(`delete`,t(`drawingMenu.delete`),i.i(`trash`,15),` tcw-sel-danger`):``].join(``);let f=this.buttons(),p=f.find(e=>e.dataset.action===c)??(c?f.find(e=>e.dataset.action===`lock`):void 0);this.rove(p??f[0],p!==void 0)}buttons(){return[...this.el.querySelectorAll(`button`)]}rove(e,t){for(let t of this.buttons())t.tabIndex=t===e?0:-1;t&&e?.focus()}place(e){let{bounds:t}=e,{w:n,h:r}=this.size??{w:0,h:0};if(this.pinned){let e=Math.max(t.x+R,Math.min(this.pinned.left,t.x+t.width-n-R)),i=Math.max(t.y+R,Math.min(this.pinned.top,t.y+t.height-r-R));this.el.style.left=`${Math.round(e)}px`,this.el.style.top=`${Math.round(i)}px`;return}let i=Math.max(t.x+R,t.x+(t.width-n)/2),a=n>t.width*yi,o=t.y+t.height-r-R,s=Math.max(t.y+R,a?o:Math.min(t.y+vi,o));this.el.style.left=`${Math.round(i)}px`,this.el.style.top=`${Math.round(s)}px`}onClick(e){let t=e.target.closest(`[data-action]`);if(!t)return;this.rove(t,!1);let n=t.dataset.action;if(n===`color`||n===`width`||n===`lineStyle`||n===`fill`||n===`textColor`){this.openPop===n?this.closePop():this.openPopover(n,t);return}if(this.closePop(),n===`settings`)this.callbacks.onSettings();else if(n===`text`)this.callbacks.onText();else if(n===`alert`)this.callbacks.onAlert();else if(n===`lock`)this.callbacks.onLock(!this.target?.locked);else if(n===`delete`)this.callbacks.onDelete();else if(n===`more`){let e=t.getBoundingClientRect(),n=this.host.getBoundingClientRect();this.callbacks.onMore(e.left-n.left,e.bottom-n.top+R)}}onKey(e){if(e.key===`Escape`&&this.openPop){e.stopPropagation(),this.closePop(!0);return}let t=this.buttons(),n=t.indexOf(document.activeElement);if(n<0)return;let r=e.key===`ArrowRight`?(n+1)%t.length:e.key===`ArrowLeft`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),this.rove(t[r],!0))}openPopover(e,t){let n=this.target.style,r=z(e===`fill`?(0,u.ownFillColor)(n)??n.color:e===`textColor`?n.textColor??n.color:n.color).toLowerCase(),i=Ci(n.lineWidth),o=wi(n.lineStyle),s=(e,t,n,r=``)=>`<button type="button" class="${e}${t?` tcw-sel-on`:``}" aria-pressed="${t}" ${n}>${r}</button>`;this.openPop=e,e===`color`||e===`fill`||e===`textColor`?this.pop.innerHTML=pi.map(e=>s(`tcw-sel-swatch`,e.toLowerCase()===r,`data-color="${e}" style="background:${e}" aria-label="${e}"`)).join(``):e===`width`?this.pop.innerHTML=mi.map(e=>s(`tcw-sel-option`,e===i,`data-width="${e}"`,`<span class="tcw-sel-width" style="--w:${e}px"></span>${e}px`)).join(``):this.pop.innerHTML=hi.map(e=>s(`tcw-sel-option`,e===o,`data-style="${e}"`,Ei(e)+a.u(this.t(`drawingSettings.lineStyle.${e}`)))).join(``),this.pop.className=`tcw-sel-pop tcw-sel-pop--${e}`,this.pop.setAttribute(`aria-label`,t.getAttribute(`aria-label`)??``),this.pop.hidden=!1;for(let e of this.el.querySelectorAll(`[aria-expanded="true"]`))e.setAttribute(`aria-expanded`,`false`);t.setAttribute(`aria-expanded`,`true`),this.placePop(),this.pop.querySelector(`.tcw-sel-on, button`)?.focus()}onPopKey(e){if(e.key===`Escape`){e.stopPropagation(),this.closePop(!0);return}let t=[...this.pop.querySelectorAll(`button`)],n=t.indexOf(document.activeElement);if(n<0)return;let r=this.openPop===`color`||this.openPop===`fill`||this.openPop===`textColor`?bi:1,i=e.key===`ArrowRight`?1:e.key===`ArrowLeft`?-1:e.key===`ArrowDown`?r:e.key===`ArrowUp`?-r:0;i&&(e.preventDefault(),t[(n+i+t.length)%t.length].focus())}placePop(){let e=this.el.querySelector(`[data-action="${this.openPop}"]`);e&&(this.pop.style.left=`${this.el.offsetLeft+e.offsetLeft}px`,this.pop.style.top=`${this.el.offsetTop+this.el.offsetHeight+6}px`)}onPick(e){let t=e.target.closest(`button`);if(!t)return;let n=this.openPop&&this.openPop in _i?_i[this.openPop]:`color`;t.dataset.color?this.callbacks.onStyle({[n]:t.dataset.color}):t.dataset.width?this.callbacks.onStyle({lineWidth:Number(t.dataset.width)}):t.dataset.style&&this.callbacks.onStyle({lineStyle:wi(t.dataset.style)}),this.closePop(!0)}closePop(e=!1){if(!this.openPop)return;let t=this.el.querySelector(`[data-action="${this.openPop}"]`);t?.setAttribute(`aria-expanded`,`false`),this.openPop=null,this.pop.hidden=!0,e&&t?.focus()}};function Ei(e){return`<svg class="tcw-sel-line" width="22" height="10" viewBox="0 0 22 10" aria-hidden="true"><line x1="1" y1="5" x2="21" y2="5" stroke="currentColor" stroke-width="2"${e===`dashed`?` stroke-dasharray="4 3"`:e===`dotted`?` stroke-dasharray="1 3" stroke-linecap="round"`:``}/></svg>`}var B={text:{box:!1,border:!1,wrap:0,fontSize:14},note:{box:!0,border:!0,wrap:240,fontSize:14},callout:{box:!0,border:!0,wrap:240,fontSize:14},signpost:{box:!0,border:!0,wrap:200,fontSize:14},balloon:{box:!0,border:!0,wrap:200,fontSize:14},anchoredText:{box:!1,border:!1,wrap:0,fontSize:14},anchoredNote:{box:!0,border:!0,wrap:240,fontSize:14}},Di=new Set([`trendLine`,`ray`,`extendedLine`,`infoLine`,`trendAngle`,`arrow`,`horizontalLine`,`horizontalRay`,`verticalLine`,`rectangle`]),Oi={priceLabel:`#ffffff`},ki=8,Ai=6,ji=1.3,Mi=120,V=1,Ni=4,Pi=229,Fi=500,H=8,Ii=400,Li=class{wrap=null;area=null;target=null;frame=0;done=!0;openedAt=0;offSince=0;onPressAway=e=>{if(!(!this.area||e.target===this.area)){if(this.area.value===this.target?.text&&performance.now()-this.openedAt<Fi){e.preventDefault(),e.stopPropagation();return}this.finish(!0,!1)}};constructor(e){this.layer=e}isOpen(){return this.area!==null}open(e){this.area&&this.finish(!0,!1);let t=e.rect();if(!t)return!1;this.target=e,this.done=!1;let n=document.createElement(`div`);n.className=`tcw-inline-text`;let r=document.createElement(`textarea`);r.className=`tcw-inline-text-input`,r.value=e.text,r.rows=1,r.spellcheck=!1,r.setAttribute(`aria-label`,e.label),e.placeholder&&(r.placeholder=e.placeholder);let{size:i,bold:a,italic:o,family:s}=e.font;return Object.assign(r.style,{fontSize:`${i}px`,fontWeight:a?`bold`:`normal`,fontStyle:o?`italic`:`normal`,fontFamily:s,lineHeight:String(ji),color:e.color,padding:`${Ai}px ${ki}px`}),r.addEventListener(`input`,()=>{this.fit(),this.target?.onInput(r.value);let e=this.target?.rect();e&&this.place(e),this.fit(),e&&this.place(e)}),r.addEventListener(`keydown`,e=>{e.stopPropagation(),!(e.isComposing||e.keyCode===Pi)&&(e.key===`Escape`?(e.preventDefault(),this.finish(!1,!0)):e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.finish(!0,!0)))}),r.addEventListener(`blur`,()=>this.finish(!0,!1)),n.appendChild(r),this.layer().appendChild(n),this.wrap=n,this.area=r,this.place(t),this.fit(),r.focus(),r.select(),this.openedAt=performance.now(),this.offSince=0,document.addEventListener(`pointerdown`,this.onPressAway,!0),document.addEventListener(`mousedown`,this.onPressAway,!0),this.follow(),!0}commit(){this.finish(!0,!1)}close(){this.done=!0,this.teardown()}finish(e,t){if(this.done||!this.area||!this.target)return;this.done=!0;let n=this.area.value,r=this.target;this.teardown(),e?r.onCommit(n):r.onCancel(),t&&r.returnFocus?.()?.focus({preventScroll:!0})}teardown(){document.removeEventListener(`pointerdown`,this.onPressAway,!0),document.removeEventListener(`mousedown`,this.onPressAway,!0),cancelAnimationFrame(this.frame),this.frame=0,this.wrap?.remove(),this.wrap=null,this.area=null,this.target=null}place(e){let t=this.area;if(!t)return;let n=Math.max(Mi,window.innerWidth-H*2);t.style.maxWidth=`${n}px`;let r=Math.max(Mi,e.width+V*2+Ni);t.style.width=`${Math.min(n,r)}px`,t.style.minHeight=`${e.height+V*2}px`;let i=t.offsetWidth||r,a=t.offsetHeight||e.height+V*2;t.style.left=`${Math.max(H,Math.min(e.x-V,window.innerWidth-H-i))}px`,t.style.top=`${Math.max(H,Math.min(e.y-V,window.innerHeight-H-a))}px`}offWindow(e){return e.x>window.innerWidth||e.x+e.width<0||e.y>window.innerHeight||e.y+e.height<0}fit(){let e=this.area;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)}follow(){this.frame=requestAnimationFrame(()=>{if(!this.target||this.done)return;let e=this.target.rect(),t=e!==null&&this.offWindow(e);if(t?this.offSince===0&&(this.offSince=performance.now()):this.offSince=0,!e||t&&performance.now()-this.offSince>Ii){this.finish(!0,!1);return}this.place(e),this.follow()})}},Ri=[{id:`regularScale`,mode:`regular`,label:`settings.scale.regular`},{id:`logScale`,mode:`logarithmic`,label:`settings.scale.logarithmic`},{id:`percentScale`,mode:`percentage`,label:`settings.scale.percentage`},{id:`indexedScale`,mode:`indexedTo100`,label:`settings.scale.indexedTo100`}],zi=[{action:`resetView`,keys:`Alt+R`,feature:`hotkeys.resetView`},{action:`invertScale`,keys:`Alt+I`,feature:`hotkeys.invertScale`},{action:`goToDate`,keys:`Alt+G`,feature:`hotkeys.goToDate`}];function Bi(e){return Ri.find(t=>t.id===e)?.mode}function Vi(...e){return e.filter(e=>e.length>0).flatMap((e,t)=>t===0?[...e]:[`separator`,...e])}function U(e,t){let n=t.keys[e.id];return n?{...e,shortcut:n}:e}function Hi(e,t){if(e.price===void 0||!Number.isFinite(e.price))return[];let n=e.formatPrice(e.price),r=[];if(e.canAlert&&r.push({id:`alert`,label:s.r(t(`chartMenu.addAlert`),{price:n}),icon:`bell`}),e.canTrade){let i=e.lastPrice===null||e.price<=e.lastPrice;r.push(i?{id:`buyLimit`,label:s.r(t(`chartMenu.buyLimit`),{price:n}),icon:`trendingUp`}:{id:`buyStop`,label:s.r(t(`chartMenu.buyStop`),{price:n}),icon:`trendingUp`},i?{id:`sellStop`,label:s.r(t(`chartMenu.sellStop`),{price:n}),icon:`trendingDown`}:{id:`sellLimit`,label:s.r(t(`chartMenu.sellLimit`),{price:n}),icon:`trendingDown`}),e.canOrderTicket&&r.push({id:`orderTicket`,label:t(`chartMenu.orderTicket`),icon:`receipt`})}return e.canDraw&&r.push({id:`horizontalLine`,label:s.r(t(`chartMenu.horizontalLine`),{price:n}),icon:`minus`}),r}var Ui=e=>({id:`settings`,label:e(`chartMenu.settings`),icon:`settings`});function Wi(e,t){let n=[U({id:`resetView`,label:t(`chartMenu.resetView`)},e)];e.canPaste&&n.push({id:`paste`,label:t(`chartMenu.paste`)});let r=[];e.hasDrawings&&r.push(e.drawingsHidden?{id:`showDrawings`,label:t(`chartMenu.showDrawings`),icon:`eye`}:{id:`hideDrawings`,label:t(`chartMenu.hideDrawings`),icon:`eyeOff`},{id:`removeDrawings`,label:t(`chartMenu.removeDrawings`),icon:`trash`,danger:!0}),e.hasIndicators&&r.push({id:`removeIndicators`,label:t(`chartMenu.removeIndicators`),icon:`trash`,danger:!0});let i=e.canExport?[{id:`exportData`,label:t(`chartMenu.exportData`),icon:`save`}]:[];return Vi(Hi(e,t),n,r,[...i,Ui(t)])}function Gi(e,t){let n=[{id:`resetPriceScale`,label:t(`chartMenu.resetPriceScale`)},{id:`autoScale`,label:t(`settings.autoScale`),checked:e.autoScale},U({id:`invertScale`,label:t(`chartMenu.invertScale`),checked:e.inverted},e),{id:`leftScale`,label:t(`settings.leftScale`),checked:e.leftScale}],r=Ri.filter(t=>t.mode!==`logarithmic`||e.canLog).map(n=>({id:n.id,label:t(n.label),radio:!0,checked:e.scaleMode===n.mode})),i=[{id:`indicatorValueLabels`,label:t(`settings.indicatorValues`),checked:e.labels.values},{id:`alignAxisLabels`,label:t(`settings.alignAxisLabels`),checked:e.labels.aligned}];e.labels.countdown!==void 0&&i.push({id:`barCountdown`,label:t(`settings.barCountdown`),checked:e.labels.countdown});let a=[{id:`highLowLines`,label:t(`settings.highLowLines`),checked:e.lines.highLow},{id:`lastPriceLine`,label:t(`chartMenu.lastPriceLine`),checked:e.lines.lastPrice}];return Vi(n,r,[{id:`labels`,label:t(`chartMenu.labels`),submenu:i},{id:`lines`,label:t(`chartMenu.lines`),submenu:a}],Hi({...e,canTrade:!1,canDraw:!1},t),[Ui(t)])}function Ki(e,t){let n=[U({id:`resetView`,label:t(`chartMenu.resetTimeScale`)},e)];e.canGoToDate&&n.push(U({id:`goToDate`,label:t(`chartMenu.goToDate`),icon:`calendar`},e));let r=e.timezone.options.map(t=>({id:`tz:${t.value}`,label:t.label,radio:!0,checked:t.value===e.timezone.current}));return Vi(n,r.length>0?[{id:`timezone`,label:t(`settings.timezone`),submenu:r}]:[])}function qi(e,t){let n=e.pane?[{id:`paneLog`,label:t(`chartMenu.paneLog`),checked:e.pane.log},{id:`paneInvert`,label:t(`chartMenu.paneInvert`),checked:e.pane.invert},{id:`panePercent`,label:t(`chartMenu.panePercent`),checked:e.pane.percent}]:[];return Vi([U({id:`resetView`,label:t(`chartMenu.resetView`)},e)],n,[Ui(t)])}function Ji(e,t,n){switch(e){case`priceAxis`:return Gi(t,n);case`timeAxis`:return Ki(t,n);case`pane`:return qi(t,n);default:return Wi(t,n)}}var Yi=/^[-+−]/;function W(e,t,n){let r=e.replace(Yi,``);return r===n.replace(Yi,``)?r:t>0?`+${r}`:t<0?`-${r}`:r}function Xi(e){return e.startsWith(`+`)?`up`:e.startsWith(`-`)?`down`:null}var G=[`positions`,`orders`,`history`],Zi=[`order`,`close`,`reverse`,`stopLoss`,`takeProfit`],Qi=[`market`,`limit`,`stop`],$i=[`gtc`,`day`],K=`—`,ea=`{pnl}`,ta=3;function na(e,t,n){return e.includes(t??``)?t:n}function ra(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function ia(e,t){if(t===null)return null;let n=e.quantity-(e.closedQuantity??0),r=e.side===`buy`?1:-1;return{pnl:(t-e.entryPrice)*n*r,pct:e.entryPrice===0?0:(t-e.entryPrice)/e.entryPrice*100*r}}function aa(e){let t=document.createElement(`span`);return t.dir=`ltr`,t.textContent=e,t}function oa(e){let t=Xi(e);return t?`tcw-account-${t}`:``}var sa=class{el;tabButtons=new Map;tabLabels=new Map;tabCounts=new Map;totalsEl;content;tab=`positions`;snapshot={positions:[],orders:[],fills:[],price:null};open=!1;live=[];constructor(e,t,n=s.t){this.callbacks=t,this.t=n,this.el=document.createElement(`section`),this.el.className=`tcw-account`,this.el.hidden=!0,this.el.setAttribute(`aria-label`,this.t(`account.title`));let a=document.createElement(`div`);a.className=`tcw-account-head`;let o=document.createElement(`div`);o.className=`tcw-account-tabs`,o.setAttribute(`role`,`tablist`),o.addEventListener(`keydown`,e=>this.onTabKey(e));for(let e of G){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-account-tab`,t.setAttribute(`role`,`tab`),t.id=`tcw-account-tab-${e}`;let n=document.createElement(`span`);n.className=`tcw-account-tab-label`,n.textContent=this.t(`account.${e}`);let r=document.createElement(`span`);r.className=`tcw-account-count`,t.append(n,r),t.addEventListener(`click`,()=>this.selectTab(e)),this.tabButtons.set(e,t),this.tabLabels.set(e,n.textContent),this.tabCounts.set(e,r),o.appendChild(t)}this.totalsEl=document.createElement(`div`),this.totalsEl.className=`tcw-account-totals`;let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-account-new`,r.o(c,`orderTicket`),c.innerHTML=i.i(`plus`,13),c.append(this.t(`account.newOrder`)),c.addEventListener(`click`,()=>this.callbacks.onNewOrder());let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-tree-close`,l.setAttribute(`aria-label`,this.t(`account.close`)),l.innerHTML=i.i(`x`,14),l.addEventListener(`click`,()=>this.closePanel()),a.append(o,this.totalsEl,c,l),this.content=document.createElement(`div`),this.content.className=`tcw-account-body`,this.content.setAttribute(`role`,`tabpanel`),this.el.append(a,this.content),e.appendChild(this.el),this.renderTabs()}isOpen(){return this.open}toggle(){this.open?this.closePanel():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.render(),this.callbacks.onToggle?.(!0)}closePanel(){this.open&&(this.open=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}update(e){let t=this.snapshot;if(this.snapshot=e,ra(t.positions,e.positions)&&ra(t.orders,e.orders)&&ra(t.fills,e.fills)&&t.realisedPnl===e.realisedPnl){t.price!==e.price&&(this.renderTotals(),this.open&&this.tab===`positions`&&this.patchPrices());return}this.renderTabs(),this.open&&this.render()}destroy(){this.el.remove()}selectTab(e){this.tab=e,this.renderTabs(),this.render()}onTabKey(e){let t=G.indexOf(this.tab),n=e.key===`ArrowRight`?t+1:e.key===`ArrowLeft`?t-1:-2;if(n===-2)return;e.preventDefault();let r=G[(n+G.length)%G.length];this.selectTab(r),this.tabButtons.get(r)?.focus()}renderTabs(){let e={positions:this.snapshot.positions.length,orders:this.snapshot.orders.length,history:this.snapshot.fills.length};for(let[t,n]of this.tabButtons){let r=t===this.tab;this.tabCounts.get(t).textContent=String(e[t]),n.setAttribute(`aria-label`,`${this.tabLabels.get(t)} (${e[t]})`),n.setAttribute(`aria-selected`,String(r)),n.tabIndex=r?0:-1,r&&this.content.setAttribute(`aria-labelledby`,n.id)}this.renderTotals()}renderTotals(){let{positions:e,price:t,fills:n,realisedPnl:r}=this.snapshot,i=[],a=e.reduce((e,n)=>{let r=ia(n,t);return r===null?e:(e??0)+r.pnl},null);a!==null&&i.push(this.total(`account.openPnl`,a)),(n.length>0||r!==void 0&&r!==0)&&i.push(this.total(`account.realised`,r??n.reduce((e,t)=>e+(t.pnl??0),0))),this.totalsEl.replaceChildren(...i)}total(e,t){let n=document.createElement(`span`),r=this.amount(t);n.className=`tcw-account-total ${oa(r)}`.trim();let i=this.t(e),a=i.indexOf(ea),o=aa(r);return a<0?n.append(`${i} `,o):n.append(i.slice(0,a),o,i.slice(a+5)),n}render(){let e=document.activeElement,t=e instanceof HTMLElement&&this.content.contains(e)?e.dataset.focusKey:void 0;this.live=[],this.tab===`positions`?this.renderPositions():this.tab===`orders`?this.renderOrders():this.renderHistory(),t&&[...this.content.querySelectorAll(`[data-focus-key]`)].find(e=>e.dataset.focusKey===t)?.focus()}patchPrices(){let{price:e}=this.snapshot;for(let t of this.live)t.price.textContent=e===null?K:this.callbacks.formatPrice(e),this.writePnl(t.pnl,ia(t.position,e))}amount(e){return W(this.money(Math.abs(e)),e,this.money(0))}money(e){return this.callbacks.formatAmount?this.callbacks.formatAmount(e):e.toFixed(2)}percent(e){let t=e=>this.callbacks.formatNumber?this.callbacks.formatNumber(e,2):e.toFixed(2);return`${W(t(Math.abs(e)),e,t(0))}%`}writePnl(e,t){if(t===null){e.className=``,e.textContent=K;return}let n=this.amount(t.pnl);e.className=oa(n),e.textContent=`${n} · ${this.percent(t.pct)}`}table(e,t,n){if(t.length===0){let e=document.createElement(`p`);return e.className=`tcw-account-empty`,e.textContent=this.t(n),this.content.replaceChildren(e),null}let r=e.map(e=>e.key?this.t(e.key):``),i=document.createElement(`table`);i.className=`tcw-account-table`,i.setAttribute(`role`,`table`);let a=i.createTHead().insertRow();a.setAttribute(`role`,`row`),e.forEach((e,t)=>{let n=document.createElement(`th`);n.scope=`col`,n.setAttribute(`role`,`columnheader`),n.textContent=r[t],e.num&&(n.className=`tcw-num`),a.appendChild(n)});let o=i.createTBody();for(let n of t){let t=o.insertRow();t.setAttribute(`role`,`row`),n.forEach((n,i)=>{let a=t.insertCell();a.setAttribute(`role`,`cell`),a.dataset.label=r[i],e[i].num&&(a.className=`tcw-num`),typeof n==`string`?a.textContent=n:a.appendChild(n)})}return this.content.replaceChildren(i),i}sideCell(e,t=`position`){let n=document.createElement(`span`);return n.className=`tcw-account-side tcw-account-${e}`,n.textContent=this.sideText(e,t),n}sideText(e,t){return t===`trade`?this.t(e===`buy`?`ticket.buy`:`ticket.sell`):this.t(e===`buy`?`account.long`:`account.short`)}actions(...e){let t=document.createElement(`div`);t.className=`tcw-account-actions`;for(let n of e){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-tree-btn${n.danger?` tcw-tree-del`:``}`,e.setAttribute(`aria-label`,n.label),e.title=n.label,e.dataset.focusKey=n.key,e.innerHTML=i.i(n.icon,14),e.addEventListener(`click`,n.run),t.appendChild(e)}return t}price(e){return e===void 0?K:this.callbacks.formatPrice(e)}renderPositions(){let{formatPrice:e}=this.callbacks,{price:t}=this.snapshot,n=[],r=this.snapshot.positions.map(r=>{let i=r.quantity-(r.closedQuantity??0),a=aa(``);this.writePnl(a,ia(r,t)),n.push(a);let o=`${this.sideText(r.side,`position`)} ${i} @ ${e(r.entryPrice)}`;return[this.sideCell(r.side),String(i),e(r.entryPrice),t===null?K:e(t),a,this.price(r.stopLoss),this.price(r.takeProfit),this.actions({icon:`arrowUpDown`,label:`${this.t(`account.reverse`)}: ${o}`,key:`reverse:${r.id}`,run:()=>this.callbacks.onReversePosition(r.id)},{icon:`x`,label:`${this.t(`account.closePosition`)}: ${o}`,key:`close:${r.id}`,run:()=>this.callbacks.onClosePosition(r.id),danger:!0})]}),i=this.table([{key:`account.side`},{key:`account.quantity`,num:!0},{key:`account.entry`,num:!0},{key:`account.price`,num:!0},{key:`account.pnl`,num:!0},{key:`account.stopLoss`,num:!0},{key:`account.takeProfit`,num:!0},{key:null}],r,`account.noPositions`);if(!i)return;let a=[...i.tBodies[0].rows];this.snapshot.positions.forEach((e,t)=>this.live.push({position:e,price:a[t].cells[ta],pnl:n[t]}))}renderOrders(){let{formatPrice:e}=this.callbacks,t=this.snapshot.orders.map(t=>{let n=na(Qi,t.type===`stopLimit`?`stop`:t.type,`limit`),r=`${this.sideText(t.side,`trade`)} ${t.quantity} @ ${e(t.price)}`;return[this.sideCell(t.side,`trade`),this.t(`ticket.type.${n}`),String(t.quantity),e(t.price),this.price(t.stopLoss),this.price(t.takeProfit),t.timeInForce?this.t(`ticket.tif.${na($i,t.timeInForce,`gtc`)}`):K,this.actions({icon:`x`,label:`${this.t(`account.cancelOrder`)}: ${r}`,key:`cancel:${t.id}`,run:()=>this.callbacks.onCancelOrder(t.id),danger:!0})]});this.table([{key:`account.side`},{key:`ticket.type`},{key:`account.quantity`,num:!0},{key:`account.price`,num:!0},{key:`account.stopLoss`,num:!0},{key:`account.takeProfit`,num:!0},{key:`ticket.timeInForce`},{key:null}],t,`account.noOrders`)}renderHistory(){let{formatPrice:e,formatTime:t}=this.callbacks,n=[...this.snapshot.fills].reverse().map(n=>{let r=aa(``);return n.pnl===void 0?r.textContent=K:(r.textContent=this.amount(n.pnl),r.className=oa(r.textContent)),[t(n.time),this.sideCell(n.side,`trade`),String(n.quantity),e(n.price),this.t(`account.reason.${na(Zi,n.reason,`order`)}`),r]});this.table([{key:`account.time`},{key:`account.side`},{key:`account.quantity`,num:!0},{key:`account.price`,num:!0},{key:`account.reason`},{key:`account.pnl`,num:!0}],n,`account.noFills`)}},ca=1e-9;function la(e,t){return e.type===`market`?t:e.price}function ua(e,t,n={}){let r=[];(!(e.quantity>0)||!Number.isFinite(e.quantity))&&r.push(`quantity`),e.type!==`market`&&(!(e.price>0)||!Number.isFinite(e.price))&&r.push(`price`),e.type===`market`&&!((t??e.price)>0)&&r.push(`market`);let i=e.side===`buy`;if(t!==null&&e.type!==`market`&&e.price>0){let n=e.price<t;e.type===`limit`&&n!==i&&e.price!==t&&r.push(`limitSide`),e.type===`stop`&&n===i&&e.price!==t&&r.push(`stopSide`)}let a=e=>e===null||Number.isFinite(e)&&e>0;a(e.stopLoss)||r.push(`stopLoss`),a(e.takeProfit)||r.push(`takeProfit`);let o=la(e,t);return o!==null&&o>0&&(e.stopLoss!==null&&a(e.stopLoss)&&(i?e.stopLoss>=o:e.stopLoss<=o)&&r.push(`stopLossSide`),e.takeProfit!==null&&a(e.takeProfit)&&(i?e.takeProfit<=o:e.takeProfit>=o)&&r.push(`takeProfitSide`)),[...r,...da(e,n)]}function da(e,t){let n=[],r=e.type===`market`?null:e.price,i=[r,e.stopLoss,e.takeProfit].filter(e=>e!==null&&Number.isFinite(e)&&e>0),{roundPrice:a,limits:o,lot:s}=t;return a&&i.some(e=>Math.abs(a(e)-e)>ca)&&n.push(`priceStep`),o&&r!==null&&r>0&&(r>o.ceiling+ca||r<o.floor-ca)&&n.push(`priceLimits`),s!==void 0&&s>1&&e.quantity>s&&e.quantity%s!==0&&n.push(`lot`),n}function fa(e,t){let n={side:e.side,type:e.type,price:e.type===`market`?t??e.price:e.price,quantity:e.quantity};if(e.type===`stop`&&(n.stopPrice=e.price),e.type!==`market`&&(n.timeInForce=e.timeInForce),e.stopLoss!==null&&(n.stopLoss=e.stopLoss),e.takeProfit!==null&&(n.takeProfit=e.takeProfit),e.trailing&&e.stopLoss!==null){let t=ha(n.price,e.stopLoss);t>0&&(n.trailingStop=t)}return n}var pa=12;function ma(e){let t=String(e),n=t.indexOf(`.`);return t.includes(`e`)?pa:n===-1?0:Math.min(pa,t.length-n-1)}function ha(e,t){let n=Math.abs(e-t);return Number.isFinite(n)?Number(n.toFixed(Math.max(ma(e),ma(t)))):NaN}function ga(e,t){let n=la(e,t);if(n===null||e.stopLoss===null||e.takeProfit===null)return null;let r=Math.abs(n-e.stopLoss);return r>0?Math.abs(e.takeProfit-n)/r:null}function _a(e,t,n,r=1){let i=la(e,t);if(i===null||!(i>0)||!Number.isFinite(n)||!(e.quantity>0))return null;let a=e.side===`buy`?1:-1;return{pct:(n-i)/i*100*a,amount:(n-i)*e.quantity*a*r}}function va(e,t,n={}){let r=n.multiplier!==void 0&&n.multiplier>0?n.multiplier:1,i=la(e,t),a=i!==null&&i>0&&e.quantity>0?i*e.quantity*r:null,o=ua(e,t),s=(n,i)=>n===null||o.includes(i)?null:_a(e,t,n,r)?.amount??null,c=s(e.stopLoss,`stopLossSide`),l=s(e.takeProfit,`takeProfitSide`);return{value:a,risk:c,reward:l,ratio:c!==null&&l!==null?ga(e,t):null}}var ya=229,ba=1,xa=2,Sa=.999999999,Ca=0,wa=class{backdrop;modal;symbolEl;body;summaryEl;problemsEl;submit;draft=null;lastPrice=null;rules={};step=Ea;round=e=>Da(e,e);typed=new Map;returnFocus=null;uid=++Ca;constructor(e,t,n=s.t){this.callbacks=t,this.t=n,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let r=!1;this.backdrop.addEventListener(`pointerdown`,e=>{r=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&r&&this.close(),r=!1}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-order-ticket`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-ticket-title-${this.uid}`),this.modal.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&!e.isComposing&&e.keyCode!==ya){e.stopPropagation(),this.close();return}i.n(e,this.modal)});let a=document.createElement(`div`);a.className=`tcw-modal-header`;let o=document.createElement(`div`);o.className=`tcw-ticket-heading`;let c=document.createElement(`h3`);c.id=`tcw-ticket-title-${this.uid}`,c.textContent=this.t(`ticket.title`),this.symbolEl=document.createElement(`span`),this.symbolEl.className=`tcw-ticket-symbol`,o.append(c,this.symbolEl);let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-modal-close`,l.setAttribute(`aria-label`,this.t(`common.close`)),l.innerHTML=i.i(`x`,16),l.addEventListener(`click`,()=>this.close()),a.append(o,l),this.body=document.createElement(`div`),this.body.className=`tcw-modal-body tcw-ticket-body`,this.summaryEl=document.createElement(`div`),this.summaryEl.className=`tcw-ticket-summary`,this.problemsEl=document.createElement(`div`),this.problemsEl.className=`tcw-ticket-problems`,this.problemsEl.setAttribute(`aria-live`,`polite`);let u=document.createElement(`div`);u.className=`tcw-modal-footer`;let d=document.createElement(`button`);d.type=`button`,d.className=`tcw-footer-cancel`,d.textContent=this.t(`common.cancel`),d.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`button`,this.submit.className=`tcw-ticket-place`,this.submit.addEventListener(`click`,()=>this.place());let f=document.createElement(`div`);f.className=`tcw-footer-end`,f.append(d,this.submit),u.append(f),this.modal.append(a,this.body,this.summaryEl,this.problemsEl,u),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.lastPrice=e.lastPrice,this.rules=e.rules??{},this.step=e.step??Ea,this.round=e.round??(e=>Da(e,e)),this.typed.clear(),this.symbolEl.textContent=e.symbol?(0,u.tickerOf)(e.symbol):``;let t=this.round(e.price??e.lastPrice??0),n=e.side??`buy`,r=`market`;e.price!==void 0&&e.lastPrice!==null&&t!==e.lastPrice&&(r=t<e.lastPrice==(n===`buy`)?`limit`:`stop`),this.draft={side:n,type:r,quantity:this.lot(),price:t,stopLoss:null,takeProfit:null,timeInForce:`gtc`},this.problemsEl.replaceChildren(),this.render(),this.backdrop.hidden=!1,this.body.querySelector(`button[aria-pressed="true"]`)?.focus()}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.draft=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}setLastPrice(e){if(!this.draft||e===this.lastPrice)return;this.lastPrice=e;let t=this.body.querySelector(`.tcw-ticket-market`);t&&(t.textContent=this.marketText()),this.check()}destroy(){this.close(),this.backdrop.remove()}lot(){return this.rules.lot!==void 0&&this.rules.lot>1?this.rules.lot:1}quantityStep(e){if(this.rules.lot!==void 0&&this.rules.lot>1)return this.rules.lot;let t=Number.isFinite(e)?(0,u.stepDecimals)(e):0;return t>0?Number((10**-t).toFixed(t)):1}priceStep(e,t){return this.step(t>0?e:e*Sa)}writePrice(e){return Number.isFinite(e)?this.step===Ea?String(e):e.toFixed((0,u.stepDecimals)(this.step(e))):``}place(){let e=this.draft;!e||ua(e,this.lastPrice,this.rules).length>0||(this.callbacks.onSubmit(fa(e,this.lastPrice)),this.close())}set(e,t=!1){this.draft&&(this.draft={...this.draft,...e},t?this.render():this.check())}render(){let e=this.draft;if(!e)return;let t=this.focusedField();if(this.modal.dataset.side=e.side,this.body.replaceChildren(this.sideToggle(e.side),this.row(`ticket.type`,this.choices(`type`,[`market`,`limit`,`stop`],e.type,`ticket.type`,e=>this.set({type:e},!0))),this.row(`ticket.quantity`,this.stepped(`quantity`,e.quantity,e=>this.quantityStep(e),()=>this.lot(),String,e=>this.set({quantity:e})))),e.type===`market`){let e=document.createElement(`span`);e.className=`tcw-ticket-market`,e.textContent=this.marketText(),this.body.append(this.row(`ticket.price`,e))}else this.body.append(this.row(`ticket.price`,this.priceField(`price`,e.price,e=>this.set({price:e}))),this.row(`ticket.timeInForce`,this.choices(`timeInForce`,[`gtc`,`day`],e.timeInForce,`ticket.timeInForce`,e=>this.set({timeInForce:e}))));this.body.append(this.optionalPrice(`stopLoss`,e.stopLoss)),e.stopLoss!==null&&this.body.append(this.trailRow(e.trailing===!0)),this.body.append(this.optionalPrice(`takeProfit`,e.takeProfit)),t&&this.body.querySelector(t)?.focus(),this.check()}focusedField(){let e=document.activeElement;if(!(e instanceof HTMLElement)||!this.body.contains(e))return null;let t=e.dataset.ticketField;return t?`[data-ticket-field="${t}"]`:null}row(e,t){let n=document.createElement(`div`);n.className=`tcw-settings-row tcw-ticket-row`;let r=document.createElement(`span`);return r.className=`tcw-settings-label`,r.textContent=this.t(e),n.append(r,t),n}choices(e,t,n,r,i){let a=e===`type`?`ticket.type`:`ticket.tif`,s=Ta(e,o.a(t.map(e=>({value:e,label:this.t(`${a}.${e}`)})),n,i,this.t(r)));for(let t of s.querySelectorAll(`[role=radio]`))t.dataset.ticketField=`${e}-${t.dataset.value}`;return s}marketText(){let e=this.t(`ticket.type.market`);return this.lastPrice===null?e:`${e} · ${this.callbacks.formatPrice(this.lastPrice)}`}typeFor(e,t){return e.type===`market`||this.lastPrice===null||!(e.price>0)||e.price===this.lastPrice?e.type:e.price<this.lastPrice==(t===`buy`)?`limit`:`stop`}sideToggle(e){let t=document.createElement(`div`);t.className=`tcw-ticket-side`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`${this.t(`ticket.buy`)} / ${this.t(`ticket.sell`)}`);for(let n of[`buy`,`sell`]){let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-ticket-side-btn tcw-ticket-${n}`,r.textContent=this.t(`ticket.${n}`),r.setAttribute(`aria-pressed`,String(e===n)),r.dataset.ticketField=`side-${n}`,r.addEventListener(`click`,()=>{let e=this.draft;!e||e.side===n||this.set({side:n,type:this.typeFor(e,n)},!0)}),t.appendChild(r)}return t}priceField(e,t,n){return this.stepped(e,t,(e,t)=>this.priceStep(e,t),()=>this.lastPrice??this.draft?.price??0,e=>this.writePrice(e),n)}stepped(e,t,n,r,i,a){let c=Ta(e,document.createElement(`input`));c.type=`number`,c.className=`tcw-indi-input`,c.step=`any`,c.min=`0`,c.value=this.typed.get(e)??i(t);let l=this.t(`ticket.${e}`);c.setAttribute(`aria-label`,l),c.addEventListener(`input`,()=>{this.typed.set(e,c.value),a(c.value.trim()===``?NaN:Number(c.value))});let u=o.c(c,{step:n,fallback:r,format:i,labels:{down:s.r(this.t(`ticket.stepDown`),{field:l}),up:s.r(this.t(`ticket.stepUp`),{field:l})}});return u.down.dataset.ticketField=`${e}-down`,u.up.dataset.ticketField=`${e}-up`,u.element}optionalPrice(e,t){let n=e===`stopLoss`?`ticket.stopLoss`:`ticket.takeProfit`,r=document.createElement(`div`);r.className=`tcw-settings-row tcw-ticket-optional`;let i=o.u(t!==null,t=>{this.typed.delete(e),this.set({[e]:t?this.startOf(e):null,...e===`stopLoss`&&!t?{trailing:!1}:{}},!0)});i.setAttribute(`aria-label`,this.t(n)),i.dataset.ticketField=`${e}-switch`;let a=document.createElement(`div`);a.className=`tcw-ticket-optional-name`;let s=document.createElement(`span`);if(s.className=`tcw-settings-label`,s.textContent=this.t(n),a.appendChild(s),r.append(i,a),t!==null){let n=document.createElement(`span`);n.className=`tcw-ticket-away`,n.dataset.for=e,n.dir=`ltr`,a.appendChild(n),r.appendChild(this.priceField(e,t,t=>this.set({[e]:Number.isFinite(t)?t:NaN})))}return r}trailRow(e){let t=document.createElement(`div`);t.className=`tcw-settings-row tcw-ticket-trail`;let n=o.u(e,e=>this.set({trailing:e},!0));n.setAttribute(`aria-label`,this.t(`ticket.trailing`)),n.dataset.ticketField=`trailing-switch`;let r=document.createElement(`span`);return r.className=`tcw-settings-label`,r.textContent=this.t(`ticket.trailing`),t.append(n,r),t}startOf(e){let t=this.draft;if(!t)return NaN;let n=t.type===`market`?this.lastPrice??t.price:t.price;if(!(n>0))return NaN;let r=e===`stopLoss`?-ba:xa;return this.round(n*(1+(t.side===`buy`?r:-r)/100))}check(){let e=this.draft;if(!e)return;let t=ua(e,this.lastPrice,this.rules),n=t.map(e=>this.problemText(e));n.join(`
|
|
7955
|
+
`}stepMarkup(){let e=this.labels;if(this.steps.length<=1)return``;let t=this.steps.map(e=>`<option value="${a.u(e.value)}"${e.value===this.step?` selected`:``}>${a.u(e.label)}</option>`).join(``);return`<label class="tcw-replay-chip"><span class="tcw-replay-chip-label" dir="${this.dir}">${a.u(e.step)}</span><select class="tcw-replay-speed tcw-replay-step" data-act="step" dir="ltr">${t}</select></label>`}wireStep(){(this.root?.querySelector(`[data-act="step"]`))?.addEventListener(`change`,e=>{this.step=e.target.value,this.callbacks.onStepChange?.(this.step)})}wireEvents(){let e=this.root;if(!e)return;this.hintText=e.querySelector(`[data-tcw="hint"]`),this.scrubber=e.querySelector(`input[data-act="seek"]`),this.timeLabel=e.querySelector(`[data-tcw="time"]`),this.playBtn=e.querySelector(`button[data-act="play"]`),this.realtimeBtn=e.querySelector(`button[data-act="realtime"]`),this.liveRegion=e.querySelector(`[data-tcw="announce"]`);let t=(t,n)=>e.querySelector(`[data-act="${t}"]`)?.addEventListener(`click`,n);t(`realtime`,()=>this.callbacks.onClose()),t(`random`,()=>this.callbacks.onRandomStart()),t(`stepBack`,()=>this.callbacks.onStepBack()),t(`stepForward`,()=>this.callbacks.onStepForward()),t(`selectBar`,()=>this.callbacks.onSelectBar?.()),t(`cancel`,()=>(this.callbacks.onCancelPick??this.callbacks.onClose)()),t(`play`,()=>this.togglePlay()),this.scrubber?.addEventListener(`input`,()=>this.callbacks.onSeek(Number(this.scrubber.value))),e.querySelector(`[data-act="speed"]`)?.addEventListener(`change`,e=>{let t=Number(e.target.value);this.rate=t,this.callbacks.onSpeedChange(t)}),e.addEventListener(`keydown`,this.onKeydown),this.wireStep()}togglePlay(){this.state===`playing`?this.callbacks.onPause():this.callbacks.onPlay()}onKeydown=e=>{if(e.key!==` `||this.mode!==`replay`||e.defaultPrevented)return;let t=e.target;t!==this.scrubber&&t!==this.root||(e.preventDefault(),e.stopPropagation(),this.playBtn?.disabled||this.togglePlay())};announce(e){this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=setTimeout(()=>{this.announceTimer=null,this.liveRegion&&(this.liveRegion.textContent=e)},Rt)}syncUi(){let e=this.root;if(e){for(let t of e.querySelectorAll(`[data-mode]`))t.hidden=t.dataset.mode!==this.mode;if(e.dataset.mode=this.mode,e.classList.toggle(`tcw-replay-bar--ended`,this.ended),this.syncPending(e),this.playBtn){let e=this.state===`playing`;this.playBtn.innerHTML=i.i(e?`pause`:`play`,14),this.playBtn.title=e?this.labels.pause:this.labels.play,this.playBtn.setAttribute(`aria-label`,this.playBtn.title);let t=this.ended&&!e;t&&document.activeElement===this.playBtn&&this.realtimeBtn?.focus(),this.playBtn.disabled=t}}}syncPending(e){for(let t of e.querySelectorAll(`.tcw-replay-group`))this.pending?t.setAttribute(`aria-busy`,`true`):t.removeAttribute(`aria-busy`);this.hintText&&(this.hintText.textContent=this.pending?this.labels.loading:this.labels.selectHint);for(let t of Bt){let n=e.querySelector(`[data-act="${t}"]`);n&&(n.disabled=this.pending)}}},Ht=864e5,Ut=6e4,Wt=1e3,Gt=150,Kt=5e3,qt=8,Jt=class{replayBar=null;replayPollInterval=null;replaySpeed=1;replayBarsTotal=null;replayStepTime=null;replayStepsKey=null;replayStep=`auto`;replayStartSeq=0;replayPickTime=null;replayStartPending=!1;replayPlayWanted=!1;replayStepsCache=null;replayShade=null;constructor(e){this.host=e,this.replayStep=e.options.replayStep??`auto`}get chart(){return this.host.chart()}get root(){return this.host.root}get chartContainer(){return this.host.chartContainer}get t(){return this.host.t}isOpen(){return this.replayBar?.isMounted()??!1}attach(){this.chart.on(`barClick`,e=>{if(!this.replayBar?.isMounted())return;let{barIndex:t,bar:n}=e.payload;if(typeof t==`number`){if(this.seriesPending()){let e=n?.time??this.chart.getData()[t]?.time;this.replayBar.getMode()===`select`&&typeof e==`number`&&(this.replayPickTime=e);return}if(this.replayBar.getMode()===`select`){this.startReplayAt(t,!1,!0);return}this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeekToBar(t),this.replayBar.setState(`paused`)}}),this.chart.on(`crosshairMove`,e=>{if(this.replayBar?.getMode()!==`select`||!this.replayBar.isMounted())return;let t=e.payload.point;this.positionReplayShade(this.seriesPending()?null:t?.x??null)}),this.chart.on(`replayStep`,e=>{let t=e.payload;this.replayBarsTotal=t.total,this.replayStepTime=typeof t.stepTime==`number`?t.stepTime:t.time,queueMicrotask(()=>{this.host.isDestroyed()||(t.cause===`series`?this.afterReplayCarryOver():this.syncReplayBar())})});for(let e of[`resize`,`paneResize`,`paneChange`])this.chart.on(e,()=>this.layoutReplayBar());this.chart.on(`replayStepsLoad`,e=>{e.payload.state===`error`&&this.host.say(this.t(`replay.stepsFailed`),`error`)}),this.chart.on(`timeframeChange`,()=>this.refreshReplaySteps())}destroy(){this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayShade?.remove(),this.replayBar?.destroy()}toggleReplay(){this.replayBar?.isMounted()?this.exitReplay():this.host.isOn()&&this.enterReplay()}enterReplay(){if(this.replayTotal()<2)return;let e=this.t;this.replayBar=new Vt({onPlay:()=>{if(this.replayBar?.getMode()===`select`){this.seriesPending()||this.startReplayAt(Math.max(1,this.replayTotal()-100),!0);return}this.replayStartPending?this.replayPlayWanted=!0:this.chart.getReplayState()===`paused`&&this.chart.replayResume(),this.syncReplayBar()},onPause:()=>{this.replayPlayWanted=!1,this.chart.replayPause(),this.syncReplayBar()},onStepBack:()=>this.stepReplay(-1),onStepForward:()=>this.stepReplay(1),onSeek:e=>{this.seriesPending()||(this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(e),this.replayBar?.setState(`paused`))},onSpeedChange:e=>{this.replaySpeed=e,this.chart.setReplaySpeed(e)},onRandomStart:()=>{if(this.seriesPending())return;let e=this.replayBarCount(),t=Math.max(1,Math.floor(e*.1)),n=Math.max(t,Math.floor(e*.9));this.startReplayAt(t+Math.floor(Math.random()*(n-t+1)),!1,!0)},onClose:()=>this.exitReplay(),onSelectBar:()=>this.pickReplayBarAgain(),onCancelPick:()=>this.cancelReplayPick(),onStepChange:e=>{if(this.replayStep=e,this.replayBar?.getMode()!==`replay`)return;let t=this.chart.getReplayState()===`playing`;this.startReplayAt(Math.max(0,this.chart.getReplayBarIndex()-1),t)}},{selectHint:e(`replay.selectHint`),loading:e(`status.loading`),random:e(`replay.random`),realtime:e(`replay.realtime`),play:e(`replay.play`),pause:e(`replay.pause`),stepBack:e(`replay.stepBack`),stepForward:e(`replay.stepForward`),replay:e(`replay.label`),position:e(`replay.position`),speed:e(`replay.speed`),step:e(`replay.step`),selectBar:e(`replay.selectBar`),cancel:e(`common.cancel`),rate:e(`replay.rate`),rateHint:e(`replay.rateHint`),playingAt:e(`replay.playingAt`),pausedAt:e(`replay.pausedAt`),endedAt:e(`replay.endedAt`)});let t=this.replayStepMenu();this.replayBar.mount(this.chartContainer,{total:this.replayTotal(),rate:this.replaySpeed,mode:`select`,steps:t,step:this.replayStep,dir:this.root.dir===`rtl`?`rtl`:`ltr`,formatRate:t=>s.r(e(`replay.rate`),{rate:t.toLocaleString(this.host.intlLocale())})}),this.watchReplayBar(),this.host.markActive(!0),this.root.setAttribute(`data-tcw-replay`,``),this.showReplayShade(),this.layoutReplayBar()}showReplayShade(){this.replayShade||(this.replayShade=document.createElement(`div`),this.replayShade.className=`tcw-replay-shade`,this.replayShade.hidden=!0,this.chartContainer.appendChild(this.replayShade),this.chartContainer.addEventListener(`mouseleave`,this.hideReplayShade))}removeReplayShade(){this.replayShade?.remove(),this.replayShade=null,this.chartContainer.removeEventListener(`mouseleave`,this.hideReplayShade)}pickReplayBarAgain(){let e=this.replayBar;!e?.isMounted()||this.seriesPending()||(this.replayPlayWanted=!1,this.chart.getReplayState()===`playing`&&this.chart.replayPause(),e.setState(`paused`),e.setMode(`select`),this.showReplayShade(),this.layoutReplayBar())}cancelReplayPick(){let e=this.replayBar;if(e?.isMounted()){if(!this.chart.isReplayActive()&&!this.replayStartPending){this.exitReplay();return}this.removeReplayShade(),e.setMode(`replay`),this.syncReplayBar(),this.layoutReplayBar()}}layoutReplayBar(){let e=this.replayBar?.element();if(!e||!this.replayBar)return;let t=this.chart.getPlotRect(),n=this.chartContainer,r=e=>`${Math.max(0,Math.round(e))}px`;e.style.setProperty(`--tcw-replay-foot`,r(n.clientHeight-(t.y+t.height))),e.style.setProperty(`--tcw-replay-plot-start`,r(t.x)),e.style.setProperty(`--tcw-replay-plot-end`,r(n.clientWidth-(t.x+t.width))),this.replayBar.setRoom(t.width-2*qt),this.liftOverReplayBar()}liftOverReplayBar(){let e=this.replayBar?.element();if(!e)return;let t=e.getBoundingClientRect().top,n=e=>{if(!e)return;let n=`${Math.max(0,Math.round(e.getBoundingClientRect().bottom-t))}px`;e.style.getPropertyValue(`--tcw-replay-lift`)!==n&&e.style.setProperty(`--tcw-replay-lift`,n)};n(this.root),n(this.host.bodyEl())}replayTimeText(){let e=this.chart.getReplayProgress(),t=(this.chart.getReplayBarIndex()>e.current?e.time:null)??this.replayStepTime;if(t===null)return;let n=this.host.textLocale(),r=this.chart.getTimeZone?.()??null,i=(0,u.timeframeToMs)(this.host.timeframe()),a=(0,u.zonedDateFormatter)(n,{year:`numeric`},r),o={month:`short`,day:`numeric`};a(t)!==a(Date.now())&&(o.year=`numeric`);let s=(0,u.zonedDateFormatter)(n,o,r)(t);if(Number.isFinite(i)&&i>=Ht)return s;let c={hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`};return(!Number.isFinite(i)||i<Ut)&&(c.second=`2-digit`),`${s} · ${(0,u.zonedDateFormatter)(n,c,r)(t)}`}replayBarCount(){return this.chart.isReplayActive()&&this.replayBarsTotal!==null?this.replayBarsTotal:this.chart.getData().length}hideReplayShade=()=>this.positionReplayShade(null);replayFrom(e,t=!1){this.host.isOn()&&(this.replayBar?.isMounted()||this.enterReplay(),this.startReplayAt(e,t))}replayStepMenu(){let e=[{value:`auto`,label:this.t(`replay.step.auto`)},{value:`bar`,label:this.t(`replay.step.bar`)},...this.replayStepOptions().map(e=>({value:e,label:e}))];return e.some(e=>e.value===this.replayStep)||(this.replayStep=`auto`),e}refreshReplaySteps(){if(!this.replayBar?.isMounted())return;let e=this.replayStepMenu();this.replayBar.setSteps(e,this.replayStep)}afterReplayCarryOver(){let e=this.replayBar;!e?.isMounted()||e.getMode()!==`replay`||(this.syncReplayBar(),!(this.replayStep===`bar`||this.chartFetchesReplaySteps())&&this.replayStepsKey!==this.replayStepsKeyNow()&&this.startReplayAt(this.chart.getReplayBarIndex(),this.chart.getReplayState()===`playing`))}startPickedReplay(){let e=this.replayPickTime;if(e===null)return;if(this.host.loading.hasFailed()||this.replayBar?.getMode()!==`select`){this.replayPickTime=null;return}if(this.seriesPending())return;this.replayPickTime=null;let t=this.chart.getData();if(!Yt(t,e))return;let n=0;for(;n+1<t.length&&t[n+1].time<=e;)n++;this.startReplayAt(n,!1,!0)}seriesPending(){return this.host.loading.isActive()&&!this.host.loading.hasFailed()}watchReplayBar(){this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayPollInterval=setInterval(()=>this.syncReplayBar(),Gt)}startReplayAt(e,t=!1,n=!1){let r=this.replayBar;if(!r)return;let i=n?this.replayBarCount():this.replayTotal(),a=Math.max(0,Math.min(Number.isFinite(e)?Math.floor(e):0,i-1)),o=this.chart.getData()[a]?.time;this.removeReplayShade(),r.setMode(`replay`),this.layoutReplayBar();let s=++this.replayStartSeq;this.replayPlayWanted=t;let c=this.host.options.replayAnimate!==!1,l=this.chartFetchesReplaySteps(),u=e=>{this.host.isDestroyed()||this.replayBar!==r||!r.isMounted()||s!==this.replayStartSeq||(this.replayStartPending=!1,this.replayStepsKey=e?this.replayStepsKeyNow():null,this.chart.replayStart({speed:this.replaySpeed,interval:c?Wt:Wt/this.replayStepsPerBar(e?d:null),...o===void 0?{startIndex:a}:{startTime:o},paused:!0,revealMarks:this.host.options.replayRevealMarks!==!1,animate:c,...l?{step:this.replayStep}:{},...e?{steps:e}:{}}),this.replayPlayWanted&&this.chart.replayResume(),this.replayPlayWanted=!1,this.syncReplayBar(),this.watchReplayBar())},d=this.replayStepInterval();if(l||d===null){u(null);return}this.replayStartPending=!0,this.replayStepsFor(d).then(e=>{s===this.replayStartSeq&&(e||this.host.say(this.t(`replay.stepsFailed`),`error`),u(e))})}replayStepsKeyNow(){return`${this.host.symbol()}|${this.host.timeframe()}`}replayStepsPerBar(e){if(e===null)return 1;let t=(0,u.timeframeToMs)(this.host.timeframe())/(0,u.timeframeToMs)(e);return Number.isFinite(t)&&t>=1?Math.round(t):1}replayStepOptions(){return e._(this.host.timeframe(),e=>this.hasReplayStep(e))}hasReplayStep(e){let t=this.host.adapter();if(t)return(0,d.servesTimeframe)(t,e);let n=(0,u.timeframeToMs)(e),r=this.host.baseTimeframeMs();return this.host.baseSeries()!==null&&r>0&&n>=r&&n%r===0}replayStepInterval(){return this.replayStep===`bar`||this.replayStep===`auto`&&this.host.options.replayAnimate===!1?null:e.v(this.replayStep,this.host.timeframe(),e=>this.hasReplayStep(e))}chartFetchesReplaySteps(){let e=this.host.adapter();return this.host.options.replayAnimate===!1||!e||this.replayStep===`bar`?!1:(0,d.withResampling)(e).fetchHistoryBefore!==void 0}async replayStepsFor(e){let t=this.chart.getExchangeTimeZone()??null,n=this.host.symbol(),r=this.host.timeframe(),i=()=>`${n}|${r}|${e}|${t}|${this.builtStepsZone(n,e)}`;if(this.replayStepsCache?.key===i())return this.replayStepsCache.steps;let a=null,o=this.host.adapter(),s=this.host.baseSeries();if(o){let t=Math.max(1,Math.round((0,u.timeframeToMs)(r)/(0,u.timeframeToMs)(e))),i=Math.min(Kt,Math.max(this.chart.getData().length,100)*t);try{a=await(0,d.withResampling)(o).fetchHistory(n,e,i)}catch{a=null}}else s&&(a=(0,u.timeframeToMs)(e)===this.host.baseTimeframeMs()?s:f(s,e,this.host.resampleOptions(t)));return!a||a.length===0?null:(this.replayStepsCache={key:i(),steps:a},a)}builtStepsZone(e,t){let n=this.host.adapter(),r=n?(0,d.withResampling)(n):null;if(!(r instanceof d.ResamplingAdapter))return``;let i=r.bucketFor(e,t);return i?String(i.timeZone??`UTC`):``}replayTotal(){return this.chart.isReplayActive()?this.chart.getReplayProgress().total:this.chart.getData().length}syncReplayBar(){let e=this.replayBar;if(!e?.isMounted()||(e.setPending(this.seriesPending()),this.startPickedReplay(),this.liftOverReplayBar(),e.getMode()!==`replay`))return;if(this.replayStartPending){e.setState(`paused`);return}if(!this.chart.isReplayActive()){this.teardownReplayUi();return}let t=this.chart.getReplayProgress(),n=this.chart.getReplayState();e.setProgress(t.current,t.total,this.replayTimeText()),e.setState(n===`stopped`?`paused`:n),e.setEnded(n!==`playing`&&t.total>0&&t.current>=t.total-1)}stepReplay(e){if(this.replayBar?.getMode()!==`replay`||this.seriesPending())return;let t=this.chart.getReplayProgress();this.chart.getReplayState()===`playing`&&this.chart.replayPause();let n=this.chart.getReplayBarIndex()>t.current?e>0?this.chart.getReplayBarIndex():t.current:t.current+e;this.chart.replaySeek(Math.max(0,Math.min(t.total-1,n))),this.replayBar.setState(`paused`),this.syncReplayBar()}handleReplayKey(e){if(e.defaultPrevented||e.isComposing||e.keyCode===229||O()||k()||!D(this.root,!0))return!1;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t)||t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`||t.isContentEditable))return!1;let n=this.replayBar?.getMode();return e.shiftKey&&(e.key===`ArrowRight`||e.key===`ArrowLeft`)&&n===`replay`?(e.preventDefault(),e.stopPropagation(),this.stepReplay(e.key===`ArrowRight`?1:-1),!0):e.key===` `&&n===`replay`&&this.onChartSurface(t)?(e.preventDefault(),e.stopPropagation(),this.toggleReplayPlay(),!0):e.key===`Escape`&&n===`select`?(this.cancelReplayPick(),!0):!1}onChartSurface(e){return!e||!this.chartContainer.contains(e)?!1:e===this.chartContainer||e.closest(`button, [role="button"], a, .tcw-replay-bar`)===null}toggleReplayPlay(){if(this.replayStartPending){this.replayPlayWanted=!this.replayPlayWanted;return}this.chart.getReplayState()===`playing`?this.chart.replayPause():this.replayBarAtEnd()||this.chart.replayResume(),this.syncReplayBar()}replayBarAtEnd(){let e=this.chart.getReplayProgress();return e.total>0&&e.current>=e.total-1}positionReplayShade(e){let t=this.replayShade;if(!t)return;let n=this.chart.getPlotRect();if(e===null||e<n.x||e>n.x+n.width){t.hidden=!0;return}t.hidden=!1,t.style.left=`${e}px`,t.style.top=`${n.y}px`,t.style.width=`${n.x+n.width-e}px`,t.style.height=`${n.height}px`}exitReplay(){this.teardownReplayUi(),this.chart.replayStop()}teardownReplayUi(){this.replayStartSeq++,this.replayPickTime=null,this.replayStartPending=!1,this.replayPlayWanted=!1,this.replayPollInterval&&=(clearInterval(this.replayPollInterval),null),this.removeReplayShade();let e=!!this.replayBar?.element()?.contains(document.activeElement);this.replayBar?.unmount(),this.replayBar=null,this.replayBarsTotal=null,this.replayStepTime=null,this.host.markActive(!1),this.root.removeAttribute(`data-tcw-replay`),this.root.style.removeProperty(`--tcw-replay-lift`),this.host.bodyEl()?.style.removeProperty(`--tcw-replay-lift`),e&&this.focusAfterReplay()}focusAfterReplay(){let e=e=>!!e&&!e.hidden&&!e.closest(`[hidden]`)&&getComputedStyle(e).display!==`none`,t=this.root.querySelector(`.tcw-toolbar [data-role="replay"]`),n=this.root.querySelector(`.tcw-toolbar .tcw-toolbar-more`);(e(t)?t:e(n)?n:this.chartContainer)?.focus()}};function Yt(e,t){let n=e.length;if(n===0||t<e[0].time)return!1;let r=e[n-1].time;return t<r+(n>1?r-e[n-2].time:0)||t===r}var Xt=()=>typeof document<`u`&&document.hidden;function A(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Zt=class{el;headerEl;nameBtn;menuEl;listEl;headEl;rowMap=new Map;entries=new Map;lists=[];activeList=``;active=null;locale;dragging=null;onOutside=e=>{this.headerEl.contains(e.target)||this.closeMenu()};constructor(e,t,n,r={}){this.callbacks=t,this.labels=n,this.options=r,this.el=document.createElement(`div`),this.el.className=`tcw-watchlist`,this.el.setAttribute(`aria-label`,n.title),this.headerEl=document.createElement(`div`),this.headerEl.className=`tcw-watchlist-header`,this.nameBtn=document.createElement(`button`),this.nameBtn.type=`button`,this.nameBtn.className=`tcw-watchlist-name`,this.nameBtn.setAttribute(`aria-haspopup`,`menu`),this.nameBtn.setAttribute(`aria-expanded`,`false`),this.nameBtn.title=n.lists,this.nameBtn.addEventListener(`click`,()=>this.menuEl.hidden?this.openMenu():this.closeMenu());let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-watchlist-add`,a.innerHTML=i.i(`plus`,14),a.title=n.add,a.setAttribute(`aria-label`,n.add),a.hidden=!t.onAdd,a.addEventListener(`click`,()=>t.onAdd?.());let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-watchlist-close`,o.setAttribute(`aria-label`,n.close??n.title),o.innerHTML=i.i(`x`,14),o.hidden=!t.onClose,o.addEventListener(`click`,()=>t.onClose?.()),this.menuEl=document.createElement(`div`),this.menuEl.className=`tcw-dropdown tcw-watchlist-menu`,this.menuEl.setAttribute(`role`,`menu`),this.menuEl.hidden=!0,this.headerEl.append(this.nameBtn,a,o,this.menuEl),this.el.appendChild(this.headerEl),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-watchlist-list`,this.listEl.setAttribute(`role`,`list`);let s=[`var(--tcw-watchlist-gutter)`,`minmax(0, 1fr)`,`auto`,`auto`,`auto`,...t.onRemove?[`var(--tcw-watchlist-remove)`]:[],`var(--tcw-watchlist-gutter)`];this.listEl.style.setProperty(`--tcw-watchlist-columns`,s.join(` `)),this.el.appendChild(this.listEl),this.headEl=this.makeHead(),e.appendChild(this.el)}get element(){return this.el}setLists(e,t){this.lists=e.map(e=>({...e,symbols:[...e.symbols]})),this.activeList=e.some(e=>e.id===t)?t:e[0]?.id??``;let n=this.shownList();this.nameBtn.textContent=n?.name??this.labels.title,this.renderRows(n?.symbols??[]),this.menuEl.hidden||this.renderMenu()}redraw(){for(let e of this.rowMap.keys())this.renderRow(e)}setLocale(e){this.locale=e;for(let e of this.rowMap.keys())this.renderRow(e)}setActive(e){this.active=e;for(let[t,n]of this.rowMap){let r=t===e;n.row.classList.toggle(`tcw-watchlist-active`,r),r?n.row.setAttribute(`aria-current`,`true`):n.row.removeAttribute(`aria-current`)}}setEntry(e,t){let n=this.entries.get(e)??{symbol:e};this.entries.set(e,{...n,...t,symbol:e}),this.renderRow(e)}destroy(){this.closeMenu(),this.el.remove(),this.rowMap.clear(),this.entries.clear()}shownList(){return this.lists.find(e=>e.id===this.activeList)}renderRows(e){for(let t of[...this.rowMap.keys()])e.includes(t)||(this.rowMap.get(t).row.remove(),this.rowMap.delete(t));for(let t of e)this.rowMap.has(t)||this.makeRow(t);let t=e.map(e=>this.rowMap.get(e).row);if(this.listEl.classList.toggle(`tcw-watchlist-logos`,t.some(e=>e.querySelector(`.tcw-watchlist-symbol-logo`))),this.listEl.replaceChildren(...this.headEl&&t.length?[this.headEl]:[],...t),e.length===0){let e=document.createElement(`div`);e.className=`tcw-watchlist-empty`,e.textContent=this.labels.empty,this.listEl.appendChild(e)}this.active&&this.setActive(this.active)}place(e,t){let n=[`symbol`,...this.options.sparkline?[`spark`,`price`]:[`price`,`move`],`change`,...this.callbacks.onRemove?[`remove`]:[]];e.style.gridColumnStart=String(n.indexOf(t)+2)}makeHead(){let e=this.labels.columns;if(!e)return null;let t=document.createElement(`div`);t.className=`tcw-watchlist-columns`,t.setAttribute(`aria-hidden`,`true`);let n=(e,n)=>{let r=document.createElement(`span`);r.className=`tcw-watchlist-column-${n}`,r.textContent=e,this.place(r,n),t.appendChild(r)};return n(e.symbol,`symbol`),this.options.sparkline&&n(``,`spark`),n(e.price,`price`),this.options.sparkline||n(e.move,`move`),n(e.change,`change`),this.callbacks.onRemove&&n(``,`remove`),t}makeRow(e){let t=document.createElement(`div`);t.className=`tcw-watchlist-row`,t.setAttribute(`role`,`listitem`),t.dataset.symbol=e,t.tabIndex=0,t.draggable=!!this.callbacks.onMove;let n=document.createElement(`div`);n.className=`tcw-watchlist-symbol`,n.textContent=Qt(e),e.includes(`:`)&&(n.title=e);let r=nn(this.options.infoOf?.(e));r&&(n.prepend(r),n.classList.add(`tcw-watchlist-symbol-logo`)),this.place(n,`symbol`),t.appendChild(n);let a=null;this.options.sparkline&&(a=document.createElement(`canvas`),a.className=`tcw-watchlist-spark`,a.width=64,a.height=22,this.place(a,`spark`),t.appendChild(a));let o=(e,n=``)=>{let r=document.createElement(`span`);return r.className=`tcw-watchlist-${e}`,r.textContent=n,this.place(r,e),t.appendChild(r),r},c=o(`price`,`—`),l=this.options.sparkline?null:o(`move`),u=o(`change`);if(this.callbacks.onRemove){t.classList.add(`tcw-watchlist-removable`);let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-watchlist-remove`,n.innerHTML=i.i(`x`,12),n.tabIndex=-1;let r=s.r(this.labels.remove,{symbol:e});n.title=r,n.setAttribute(`aria-label`,r),n.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onRemove?.(e)}),this.place(n,`remove`),t.appendChild(n)}t.addEventListener(`click`,()=>this.callbacks.onSelect(e)),t.addEventListener(`keydown`,t=>this.onRowKey(t,e)),t.addEventListener(`dragstart`,n=>{this.dragging=e,n.dataTransfer?.setData(`text/plain`,e),n.dataTransfer&&(n.dataTransfer.effectAllowed=`move`),t.classList.add(`tcw-watchlist-dragging`)}),t.addEventListener(`dragend`,()=>{this.dragging=null,t.classList.remove(`tcw-watchlist-dragging`)}),t.addEventListener(`dragover`,t=>{this.dragging&&this.dragging!==e&&t.preventDefault()}),t.addEventListener(`drop`,t=>{t.preventDefault();let n=this.dragging;if(this.dragging=null,!n||n===e)return;let r=this.shownList()?.symbols??[];this.callbacks.onMove?.(n,r.indexOf(e))}),this.rowMap.set(e,{row:t,priceEl:c,moveEl:l,changeEl:u,sparkCanvas:a}),this.renderRow(e)}onRowKey(e,t){let n=this.shownList()?.symbols??[],r=n.indexOf(t);if([`Enter`,` `,`Delete`,`Backspace`,`ArrowDown`,`ArrowUp`].includes(e.key)&&e.stopPropagation(),e.key===`Enter`||e.key===` `)e.preventDefault(),this.callbacks.onSelect(t);else if((e.key===`Delete`||e.key===`Backspace`)&&this.callbacks.onRemove){e.preventDefault();let i=n[r+1]??n[r-1];this.callbacks.onRemove(t),i&&this.rowMap.get(i)?.row.focus()}else if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let i=r+(e.key===`ArrowDown`?1:-1);if(i<0||i>=n.length)return;e.altKey?(this.callbacks.onMove?.(t,i),this.rowMap.get(t)?.row.focus()):this.rowMap.get(n[i])?.row.focus()}}renderRow(e){let t=this.rowMap.get(e),n=this.entries.get(e);if(!t||!n)return;let r=this.options.infoOf?.(e)?.pricePrecision,i=r!==void 0&&Number.isInteger(r)&&r>=0?Math.min(r,u.MAX_PRICE_DECIMALS):void 0;if(n.lastPrice!==void 0&&(t.priceEl.textContent=$t(n.lastPrice,this.locale,i)),n.lastPrice!==void 0&&n.refPrice!==void 0&&n.refPrice!==0){let e=n.lastPrice-n.refPrice,r=e/n.refPrice*100,a=e>0?`+`:e<0?`-`:``,o=e>0?` tcw-up`:e<0?` tcw-down`:``,s=Math.abs(r).toLocaleString(this.locale,{minimumFractionDigits:2,maximumFractionDigits:2});t.moveEl&&(t.moveEl.textContent=`${a}${en(Math.abs(e),n.lastPrice,this.locale,i)}`,t.moveEl.className=`tcw-watchlist-move${o}`),t.changeEl.textContent=`${a}${s}%`,t.changeEl.className=`tcw-watchlist-change${o}`}else t.moveEl&&(t.moveEl.textContent=``),t.changeEl.textContent=``;t.sparkCanvas&&n.sparkline&&n.sparkline.length>=2&&tn(t.sparkCanvas,n.sparkline,n.refPrice??n.sparkline[0])}openMenu(){this.renderMenu(),this.menuEl.hidden=!1,this.nameBtn.setAttribute(`aria-expanded`,`true`),document.addEventListener(`mousedown`,this.onOutside)}closeMenu(){this.menuEl.hidden=!0,this.nameBtn.setAttribute(`aria-expanded`,`false`),document.removeEventListener(`mousedown`,this.onOutside)}renderMenu(){let e=(e,t)=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-dropdown-item`,n.setAttribute(`role`,`menuitem`),n.textContent=e,n.addEventListener(`click`,t),n},t=this.lists.map(t=>{let n=e(``,()=>{this.closeMenu(),this.callbacks.onPickList?.(t.id)});n.dataset.list=t.id,n.classList.toggle(`tcw-active`,t.id===this.activeList);let r=document.createElement(`span`);r.textContent=t.name;let i=document.createElement(`span`);return i.className=`tcw-watchlist-count`,i.textContent=String(t.symbols.length),n.append(r,i),n}),n=document.createElement(`div`);if(n.className=`tcw-dropdown-divider`,t.push(n),this.callbacks.onCreateList){let n=e(this.labels.newList,()=>this.editName(``,e=>this.callbacks.onCreateList?.(e)));n.dataset.action=`new`,t.push(n)}let r=this.shownList();if(r&&this.callbacks.onRenameList){let n=e(this.labels.rename,()=>this.editName(r.name,e=>this.callbacks.onRenameList?.(r.id,e)));n.dataset.action=`rename`,t.push(n)}if(r&&this.callbacks.onDeleteList&&this.lists.length>1){let n=!1,i=e(this.labels.deleteList,()=>{if(!n){n=!0,i.textContent=s.r(this.labels.confirmDelete,{name:r.name}),i.classList.add(`tcw-danger`);return}this.closeMenu(),this.callbacks.onDeleteList?.(r.id)});i.dataset.action=`delete`,t.push(i)}this.menuEl.replaceChildren(...t)}editName(e,t){this.closeMenu();let n=document.createElement(`input`);n.className=`tcw-watchlist-input`,n.type=`text`,n.maxLength=60,n.value=e,n.placeholder=this.labels.listName,n.setAttribute(`aria-label`,this.labels.listName),this.nameBtn.hidden=!0,this.headerEl.insertBefore(n,this.nameBtn);let r=!1,i=i=>{if(r)return;r=!0;let a=n.value.trim();n.remove(),this.nameBtn.hidden=!1,i&&a&&a!==e&&t(a),this.nameBtn.focus()};n.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),i(!0)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),i(!1))}),n.addEventListener(`blur`,()=>i(!1)),n.focus()}};function Qt(e){let t=e.slice(e.lastIndexOf(`:`)+1)||e;if(t.includes(`/`))return t;for(let e of[`USDT`,`USD`,`BTC`,`ETH`,`EUR`])if(t.length>e.length&&t.endsWith(e))return t.slice(0,-e.length)+`/`+e;return t}function $t(e,t,n){if(n!==void 0)return e.toLocaleString(t,{minimumFractionDigits:n,maximumFractionDigits:n});if(e===0)return`0`;let r=Math.abs(e);return r>=1e3?e.toLocaleString(t,{minimumFractionDigits:2,maximumFractionDigits:2}):r>=1?e.toLocaleString(t,{minimumFractionDigits:4,maximumFractionDigits:4}):e.toLocaleString(t,{maximumFractionDigits:(0,u.smallValueDecimals)(e)})}function en(e,t,n,r){if(r!==void 0)return e.toLocaleString(n,{minimumFractionDigits:r,maximumFractionDigits:r});let i=Math.abs(t);if(i>=1e3)return e.toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:2});if(i>=1)return e.toLocaleString(n,{minimumFractionDigits:4,maximumFractionDigits:4});let a=i>0?(0,u.smallValueDecimals)(i):4;return e.toLocaleString(n,{maximumFractionDigits:a})}function tn(e,t,n){let r=e.getContext(`2d`);if(!r)return;let i=window.devicePixelRatio||1;e.width!==e.clientWidth*i&&(e.width=(e.clientWidth||64)*i,e.height=(e.clientHeight||22)*i);let a=e.width,o=e.height,s=1/0,c=-1/0;for(let e of t)e<s&&(s=e),e>c&&(c=e);let l=Math.max(c-s,1e-9),u=t[t.length-1]>=n?`#1fa874`:`#e8505b`;r.clearRect(0,0,a,o),r.lineWidth=1.4*i,r.strokeStyle=u,r.beginPath();let d=a/(t.length-1);for(let e=0;e<t.length;e++){let n=e*d,i=o-(t[e]-s)/l*(o-4)-2;e===0?r.moveTo(n,i):r.lineTo(n,i)}r.stroke()}function nn(e){let t=a.i(e?.logo);if(!t)return null;let n=document.createElement(`img`);return n.className=`tcw-watchlist-logo`,n.alt=``,n.draggable=!1,n.setAttribute(`aria-hidden`,`true`),n.setAttribute(`loading`,`lazy`),n.setAttribute(`decoding`,`async`),n.setAttribute(`referrerpolicy`,`no-referrer`),n.addEventListener(`error`,()=>{n.style.visibility=`hidden`},{once:!0}),n.src=t,n}var rn=50,an=200,on=500,sn=60,cn=e=>typeof e==`string`&&e.trim().slice(0,sn)||null;function ln(e){let t=[];for(let n of e){let e=a.n(n);if(e&&!t.includes(e)&&t.push(e),t.length===on)break}return t}function un(e){if(!e||typeof e!=`object`)return null;let t=e;if(!Array.isArray(t.lists))return null;let n=[];for(let e of t.lists){if(n.length===rn)break;if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`&&t.id&&t.id.length<=u.MAX_SYMBOL_LENGTH?t.id:null,i=cn(t.name);!r||!i||n.some(e=>e.id===r)||n.push({id:r,name:i,symbols:Array.isArray(t.symbols)?ln(t.symbols):[]})}return n.length===0?null:{lists:n,active:typeof t.active==`string`&&n.some(e=>e.id===t.active)?t.active:n[0].id}}var dn=e=>({...e,symbols:[...e.symbols]});function fn(e){let t=e?.offered;return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.length>0&&e.length<=u.MAX_SYMBOL_LENGTH).slice(-an):null}var pn=class{lists;active;listeners=new Set;storage;storageKey;offered;constructor(e){this.storage=e.storage??null,this.storageKey=e.storageKey??`tcw:watchlists`;let t=this.load(),n=e.lists?un({lists:e.lists,active:e.activeList}):null,r=n??{lists:[{id:`default`,name:cn(e.defaultName)??`Watchlist`,symbols:ln(e.symbols??[])}],active:`default`};if(this.offered=new Set(n?.lists.map(e=>e.id)),!t){this.lists=r.lists,this.active=r.active;return}this.keepWithHostLists(t,n?.lists??[])&&this.save()}keepWithHostLists(e,t){let n=new Set(e.offered??e.lists.map(e=>e.id)),r=t.filter(t=>!n.has(t.id)&&!e.lists.some(e=>e.id===t.id));return this.lists=[...e.lists,...r].slice(0,rn),this.active=e.active,this.offered=new Set([...n,...this.lists.map(e=>e.id)]),r.length>0}getLists(){return this.lists.map(dn)}getActive(){return dn(this.activeList())}setActive(e){e===this.active||!this.lists.some(t=>t.id===e)||(this.active=e,this.changed())}replace(e,t){let n=un({lists:e,active:t??this.active});n&&(this.lists=n.lists,this.active=n.active,this.changed())}create(e){let t=cn(e);if(!t||this.lists.length>=rn)return null;let n=this.lists.length+1;for(;this.lists.some(e=>e.id===`list-${n}`);)n++;let r={id:`list-${n}`,name:t,symbols:[]};return this.lists=[...this.lists,r],this.active=r.id,this.changed(),dn(r)}rename(e,t){let n=cn(t);n&&this.update(e,e=>({...e,name:n}))}remove(e){this.lists.length<=1||!this.lists.some(t=>t.id===e)||(this.lists=this.lists.filter(t=>t.id!==e),this.active===e&&(this.active=this.lists[0].id),this.changed())}add(e,t=this.active){let n=a.n(e),r=this.lists.find(e=>e.id===t);return!n||!r||r.symbols.includes(n)||r.symbols.length>=on?!1:(this.update(t,e=>({...e,symbols:[...e.symbols,n]})),!0)}removeSymbol(e,t=this.active){this.lists.find(e=>e.id===t)?.symbols.includes(e)&&this.update(t,t=>({...t,symbols:t.symbols.filter(t=>t!==e)}))}move(e,t,n=this.active){let r=this.lists.find(e=>e.id===n);if(!r)return;let i=r.symbols.indexOf(e);if(i<0)return;let a=r.symbols.filter(t=>t!==e),o=Math.max(0,Math.min(Math.round(t),a.length));o!==i&&this.update(n,t=>({...t,symbols:[...a.slice(0,o),e,...a.slice(o)]}))}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}activeList(){return this.lists.find(e=>e.id===this.active)??this.lists[0]}update(e,t){this.lists=this.lists.map(n=>n.id===e?t(n):n),this.changed()}changed(){this.save();for(let e of this.listeners)e()}load(){if(!this.storage)return null;try{let e=this.storage.getItem(this.storageKey);if(!e)return null;let t=JSON.parse(e),n=un(t);return n?{...n,offered:fn(t)}:null}catch{return null}}save(){if(this.storage)try{let e=[...this.offered].slice(-an);this.storage.setItem(this.storageKey,JSON.stringify({lists:this.lists,active:this.active,offered:e}))}catch{}}},mn=class{el;bodyEl;newsEl;shown=!1;constructor(e,t=s.t,n={}){this.t=t,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-syminfo`,r.o(this.el,`symbolInfo`),this.el.setAttribute(`role`,`dialog`),this.el.setAttribute(`aria-label`,t(`symbolInfo.title`)),this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-syminfo-header`;let o=document.createElement(`span`);o.textContent=t(`symbolInfo.title`);let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-syminfo-close`,c.setAttribute(`aria-label`,t(`common.close`)),c.innerHTML=i.i(`x`,14),c.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),a.append(o,c),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-syminfo-body`,this.newsEl=document.createElement(`div`),this.newsEl.className=`tcw-syminfo-news`,this.newsEl.hidden=!0,this.el.append(a,this.bodyEl,this.newsEl),e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.shown}toggle(){this.shown?this.close():this.open()}open(){this.shown||(this.shown=!0,this.el.hidden=!1,this.callbacks.onToggle?.(!0))}close(){this.shown&&(this.shown=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}render(e){let t=document.createElement(`div`);t.className=`tcw-syminfo-head`;let{venue:n,ticker:r}=a.c(e.symbol),i=j(`div`,`tcw-syminfo-symbol`,r);n&&(i.title=e.symbol),t.append(i),e.description&&t.append(j(`div`,`tcw-syminfo-desc`,e.description)),e.meta&&t.append(j(`div`,`tcw-syminfo-meta`,e.meta));let o=document.createElement(`div`);if(o.className=`tcw-syminfo-quote`,e.price&&o.append(j(`span`,`tcw-syminfo-price`,e.price)),e.change){let t=j(`span`,`tcw-syminfo-change`,e.change.text);t.classList.add(e.change.up?`tcw-up`:`tcw-down`),o.append(t)}let s=j(`div`,`tcw-syminfo-status`,e.status.text);s.dataset.state=e.status.state;let c=document.createElement(`dl`);c.className=`tcw-syminfo-stats`;for(let t of e.stats){let e=document.createElement(`div`);e.className=`tcw-syminfo-stat`,e.append(j(`dt`,``,t.label),j(`dd`,``,t.value)),c.append(e)}this.bodyEl.replaceChildren(t,o,s,c)}renderNews(e){if(this.newsEl.hidden=e.kind===`none`,e.kind===`none`){this.newsEl.replaceChildren();return}let t=j(`div`,`tcw-syminfo-news-title`,this.t(`symbolInfo.news`));if(e.kind===`loading`||e.kind===`failed`||e.items.length===0){let t=e.kind===`loading`?`symbolInfo.loading`:e.kind===`failed`?`symbolInfo.newsFailed`:`symbolInfo.noNews`;this.newsEl.replaceChildren(j(`div`,`tcw-syminfo-news-note`,this.t(t)));return}let n=document.createElement(`ul`);n.className=`tcw-syminfo-news-list`;for(let t of e.items){let e=document.createElement(`li`);if(e.className=`tcw-syminfo-news-item`,t.url){let n=document.createElement(`a`);n.href=t.url,n.target=`_blank`,n.rel=`noopener noreferrer`,n.textContent=t.title,e.append(n)}else e.append(j(`span`,``,t.title));t.meta&&e.append(j(`div`,`tcw-syminfo-news-meta`,t.meta)),n.append(e)}this.newsEl.replaceChildren(t,n)}destroy(){this.el.remove()}};function j(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}var hn=10,gn=50,_n=5*6e4,vn=864e5,yn=2;function bn(e){let{info:t,quote:n,t:r,textLocale:i}=e,a=(0,u.symbolTimeZone)(t),o=Sn(e.bars,a),c=e.formatPrice,l=n?.last??o?.close,d=n?.prevClose??o?.prevClose,f=n?.change??(l!==void 0&&d!==void 0?l-d:void 0),p=l!==void 0&&f!==void 0?l-f:void 0,m=n?.changePercent??(f!==void 0&&p?f/p*100:void 0),h=(0,u.marketStatus)(t,e.now),g=r(h.state===`open`?`symbolInfo.open`:h.state===`closed`?`symbolInfo.closed`:`symbolInfo.always`);if(h.state!==`always`&&h.next!==null){let t=Cn(h.next-e.now,i);g+=` · ${s.r(r(h.state===`open`?`symbolInfo.closesIn`:`symbolInfo.opensIn`),{when:t})}`}let _=[],v=(e,t)=>{t&&_.push({label:e,value:t})},y=e=>e===void 0?void 0:c(e);v(r(`dataWindow.open`),y(n?.open??o?.open)),v(r(`dataWindow.high`),y(n?.high??o?.high)),v(r(`dataWindow.low`),y(n?.low??o?.low)),v(r(`symbolInfo.prevClose`),y(d));let ee=n?.volume??o?.volume;v(r(`dataWindow.volume`),ee===void 0?void 0:Tn(ee,e.numberLocale)),v(r(`symbolInfo.bid`),y(n?.bid)),v(r(`symbolInfo.ask`),y(n?.ask)),v(r(`symbolInfo.tick`),t?.minTick===void 0?void 0:String(t.minTick)),v(r(`symbolInfo.currency`),t?.currency),v(r(`symbolInfo.timezone`),a),v(r(`symbolInfo.hours`),En(t,i));let te=(f??0)>=0?`+`:`-`,ne=e.names===void 0?t:e.names;return{symbol:e.symbol,description:ne?.description,meta:[ne?.exchange,ne?.type].filter(Boolean).join(` · `)||void 0,price:l===void 0?void 0:c(l),change:f===void 0?void 0:{text:`${te}${c(Math.abs(f))}${m===void 0?``:` (${te}${wn(Math.abs(m),yn,e.numberLocale)}%)`}`,up:f>=0},status:{state:h.state,text:g},stats:_}}var xn=class{request=0;cache=new Map;pending=new Map;headlines(e,t){let n=this.cache.get(e);if(n&&Date.now()-n.at<_n)return Promise.resolve(n.items);let r=this.pending.get(e);if(r)return r;let i=Promise.resolve().then(()=>t(e,gn)).then(t=>{let n=(0,u.readNews)(t,gn);return this.cache.set(e,{at:Date.now(),items:n}),n}).finally(()=>this.pending.delete(e));return this.pending.set(e,i),i}load(e,t,n,r,i){let a=++this.request;if(!t){n({kind:`none`});return}let o=e=>{let t=Date.now();n({kind:`items`,items:e.slice(0,hn).map(e=>({title:e.title,url:e.url,meta:[e.source,Cn(e.time-t,r)].filter(Boolean).join(` · `)}))})},s=this.cache.get(e);if(s&&Date.now()-s.at<_n){o(s.items);return}n({kind:`loading`}),this.headlines(e,t).then(e=>{a!==this.request||i()||o(e)}).catch(()=>{a===this.request&&!i()&&n({kind:`failed`})})}};function Sn(e,t){if(e.length===0)return null;let n=t&&(0,u.isValidTimeZone)(t)?t:null,r=(0,u.barTimeUnit)(e),i=e=>{let t=e*r;return Math.floor((t+(n?(0,u.zoneOffsetMinutes)(n,t)*6e4:0))/vn)},a=e[e.length-1],o=i(a.time),s=e.length-1;for(;s>0&&i(e[s-1].time)===o;)s--;let c=-1/0,l=1/0,d=0;for(let t=s;t<e.length;t++)c=Math.max(c,e[t].high),l=Math.min(l,e[t].low),d+=e[t].volume??0;return{open:e[s].open,high:c,low:l,close:a.close,volume:d,prevClose:s>0?e[s-1].close:void 0}}function Cn(e,t){let n=e/6e4,[r,i]=Math.abs(n)<60?[Math.round(n)||Math.sign(n)||1,`minute`]:Math.abs(n)<1440?[Math.round(n/60),`hour`]:[Math.round(n/1440),`day`];try{return new Intl.RelativeTimeFormat(t,{numeric:`auto`}).format(r,i)}catch{return new Intl.RelativeTimeFormat(`en`,{numeric:`auto`}).format(r,i)}}function wn(e,t,n){try{return(0,u.formatPrice)(e,t,n)}catch{return e.toFixed(t)}}function Tn(e,t){try{return new Intl.NumberFormat(t,{notation:`compact`,maximumFractionDigits:2}).format(e)}catch{return String(e)}}function En(e,t){let n=e?.sessions??[];if(n.length===0)return;let r;try{let e=new Intl.DateTimeFormat(t,{weekday:`short`,timeZone:`UTC`});r=Array.from({length:7},(t,n)=>e.format(Date.UTC(1970,0,4+n)))}catch{r=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]}let i=e=>{let t=[...new Set((e??[]).filter(e=>Number.isInteger(e)&&e>=0&&e<=6))].sort((e,t)=>e-t);return t.length===0||t.length===7?``:t.every((e,n)=>n===0||e===t[n-1]+1)&&t.length>2?`${r[t[0]]}–${r[t[t.length-1]]}`:t.map(e=>r[e]).join(`, `)};return n.map(e=>[`${e.start}–${e.end}`,i(e.days)].filter(Boolean).join(` `)).join(`, `)}var Dn=`news:`,On=12;function kn(e){return e.map((e,t)=>{let n={id:`${Dn}${e.id??`${e.time}:${t}`}`,time:e.time,kind:`news`,title:e.title};return e.source&&(n.text=e.source),e.url&&(n.url=e.url),n})}var An=class{shown=[];own=[];placing=!1;request=0;constructor(e){this.host=e}start(){this.host.chart.on(`markClick`,e=>this.onClick(e.payload.marks,e.payload.x,e.payload.y)),this.host.chart.on(`marksChange`,e=>{this.makeRoom(e.payload.count),this.keep()}),this.host.chart.on(`markHover`,e=>this.host.hideNavigation(e.payload.marks!==null)),this.host.chart.on(`chartTypeChange`,()=>this.makeRoom(this.host.chart.getMarks()?.length??0)),this.load()}makeRoom(e){let t=e>0&&this.host.marksOn&&this.host.chart.isTimeAligned();this.host.liftNavigation(t?d.MARK_ROW_HEIGHT:0)}keep(){if(this.placing||this.own.length===0)return;let e=new Set((this.host.chart.getMarks()??[]).map(e=>e.id));this.shown.every(t=>e.has(t))||this.place(this.own)}place(e){this.placing=!0;try{this.shown=[];for(let t of e){let e=this.host.chart.addMark(t);e&&this.shown.push(e)}}finally{this.placing=!1}}load(){let e=++this.request;this.own=[];for(let e of this.shown)this.host.chart.removeMark(e);this.shown=[],this.makeRoom(this.host.chart.getMarks()?.length??0);let{options:t}=this.host;if(t.newsMarks===!1||!this.host.marksOn)return;let n=t.adapter,r=t.news??(n?.fetchNews?n.fetchNews.bind(n):null);r&&this.host.news.headlines(this.host.symbol,r).then(t=>{e!==this.request||this.host.destroyed||(this.own=kn(t),this.place(this.own))}).catch(()=>void 0)}onClick(e,t,n){if(!this.host.marksOn||e.length===0)return;if(e.length===1){e[0].url&&this.host.openLink(e[0].url);return}let r=[...e].reverse().slice(0,On).map(e=>({id:e.id,label:e.title,...e.url?{icon:`link`}:{}}));this.host.openMenu(r,t,n,t=>{let n=e.find(e=>e.id===t)?.url;n&&this.host.openLink(n)})}},jn={KeyT:`trendLine`,KeyH:`horizontalLine`,KeyJ:`horizontalRay`,KeyV:`verticalLine`,KeyC:`crossLine`,KeyF:`fibRetracement`};function Mn(){let e={};for(let[t,n]of Object.entries(jn))e[n]=`Alt+${t.replace(/^Key/,``)}`;return e}var Nn=300,Pn=80,Fn=u.PHI**-3,In=80,Ln=class{el;holdTimer=null;repeatTimer=null;pressed=!1;keyboardFocus=!1;lift=0;suppressed=!1;onMove=e=>{if(!(e.pointerType===`touch`||this.suppressed)&&!(this.holdTimer||this.repeatTimer)){if(!this.nearBottom(e)&&!this.keyboardFocus){this.el.classList.remove(`tcw-nav-shown`),this.stopHold();return}this.el.classList.contains(`tcw-nav-shown`)||this.place(),this.el.classList.add(`tcw-nav-shown`)}};onLeave=()=>{this.el.classList.remove(`tcw-nav-shown`),this.stopHold()};constructor(e,t,n=s.t){this.host=e,this.actions=t,this.el=document.createElement(`div`),this.el.className=`tcw-nav`,r.o(this.el,`navigation`),this.el.setAttribute(`role`,`toolbar`),this.el.setAttribute(`aria-label`,n(`nav.label`));let a=[[`zoomOut`,`minus`,n(`nav.zoomOut`),`navigation.zoom`],[`zoomIn`,`plus`,n(`nav.zoomIn`),`navigation.zoom`],[`scrollLeft`,`chevronLeft`,n(`nav.scrollLeft`),`navigation.scroll`],[`scrollRight`,`chevronRight`,n(`nav.scrollRight`),`navigation.scroll`],[`reset`,`reset`,n(`nav.reset`),`navigation.reset`]];for(let[e,n,o,s]of a){let a=document.createElement(`button`);if(a.type=`button`,a.className=`tcw-nav-btn`,a.dataset.nav=e,r.o(a,s),a.title=o,a.setAttribute(`aria-label`,o),a.innerHTML=i.i(n,16),e===`scrollLeft`||e===`scrollRight`){let n=e===`scrollRight`?1:-1;a.addEventListener(`pointerdown`,e=>{if(e.button===0){e.preventDefault();try{a.setPointerCapture(e.pointerId)}catch{}this.startHold(n)}});for(let e of[`pointerup`,`pointercancel`,`pointerleave`])a.addEventListener(e,()=>this.stopHold());a.addEventListener(`click`,e=>{e.detail===0&&t.scroll(n)})}else a.addEventListener(`click`,()=>{e===`zoomIn`?t.zoomIn():e===`zoomOut`?t.zoomOut():t.reset()});this.el.appendChild(a)}for(let e of[`dblclick`,`contextmenu`,`pointerdown`,`mousedown`])this.el.addEventListener(e,e=>e.stopPropagation());this.el.addEventListener(`pointerdown`,()=>{this.pressed=!0},{capture:!0}),this.el.addEventListener(`pointerup`,()=>{this.pressed=!1},{capture:!0}),this.el.addEventListener(`focusin`,()=>{this.keyboardFocus=!this.pressed,this.pressed=!1,this.place(),this.el.classList.add(`tcw-nav-shown`)}),this.el.addEventListener(`focusout`,e=>{this.el.contains(e.relatedTarget)||(this.keyboardFocus=!1,this.el.classList.remove(`tcw-nav-shown`))}),e.appendChild(this.el),e.addEventListener(`pointermove`,this.onMove),e.addEventListener(`pointerleave`,this.onLeave)}setLift(e){let t=Math.max(0,Math.round(e));t!==this.lift&&(this.lift=t,this.el.classList.contains(`tcw-nav-shown`)&&this.place())}setSuppressed(e){this.suppressed=e,e&&!this.keyboardFocus&&(this.el.classList.remove(`tcw-nav-shown`),this.stopHold())}destroy(){this.stopHold(),this.host.removeEventListener(`pointermove`,this.onMove),this.host.removeEventListener(`pointerleave`,this.onLeave),this.el.remove()}nearBottom(e){let t=this.actions.plotRect(),n=this.host.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=Math.max(In,t.height*Fn);return r>=t.x&&r<=t.x+t.width&&i<=t.y+t.height&&i>=t.y+t.height-a}place(){let e=this.actions.plotRect();this.el.style.left=`${Math.round(e.x+e.width/2)}px`,this.el.style.top=`${Math.round(e.y+e.height)-this.lift}px`}startHold(e){this.stopHold(),this.actions.scroll(e),this.holdTimer=setTimeout(()=>{this.repeatTimer=setInterval(()=>this.actions.scroll(e),Pn)},Nn)}stopHold(){this.holdTimer&&clearTimeout(this.holdTimer),this.repeatTimer&&clearInterval(this.repeatTimer),this.holdTimer=null,this.repeatTimer=null}};function Rn(e,t,n,r=!1){let i=e.label??t(`alerts.source.price`),a=Un.get(e.condition),o=a?t(a):e.condition;if(Bn.includes(e.condition))return`${i} ${o} ${s.r(t(`alerts.moveSummary`),{percent:e.percent??0,bars:e.bars??0})}`;if(e.target)return`${i} ${o} ${e.targetLabel??e.target}`;let c=e.channel&&e.channel!==`price`,l=Number.isFinite(e.price)?c?Gn(e.price):n(e.price):`—`;return`${(c||e.drawingId)&&e.label?`${e.label} `:r?`${i} `:``}${o} ${l}`}var zn=[{value:`crossing`,key:`alerts.condition.crossing`},{value:`crossingUp`,key:`alerts.condition.crossingUp`},{value:`crossingDown`,key:`alerts.condition.crossingDown`},{value:`greaterThan`,key:`alerts.condition.greaterThan`},{value:`lessThan`,key:`alerts.condition.lessThan`},{value:`movesUp`,key:`alerts.condition.movesUp`},{value:`movesDown`,key:`alerts.condition.movesDown`}],Bn=[`movesUp`,`movesDown`],Vn={hour:36e5,day:864e5,week:7*864e5,month:30*864e5},Hn=``,Un=new Map(zn.map(e=>[e.value,e.key]));function Wn(e){return Math.round(e*1e6)/1e6}function Gn(e){return Math.abs(e)>=1?e.toFixed(2):e.toFixed((0,u.smallValueDecimals)(e))}var Kn=class{el;listEl;priceInput;conditionSelect;sourceSelect;targetSelect;percentInput;barsInput;levelRow;moveRow;closeCheck;expirySelect;messageInput;emptyEl;callbacks;open=!1;alerts=[];sources;formEl;newBtn;formChoice=null;constructor(e,t,n=s.t){this.t=n,this.callbacks=t,this.sources=[{channel:`price`,label:this.t(`alerts.source.price`)}],this.el=document.createElement(`div`),this.el.className=`tcw-alerts-panel`,r.o(this.el,`alerts`),this.el.hidden=!0;let o=document.createElement(`div`);o.className=`tcw-alerts-header`;let c=document.createElement(`span`);c.textContent=this.t(`alerts.title`);let l=document.createElement(`button`);l.className=`tcw-alerts-close`,l.type=`button`,l.setAttribute(`aria-label`,this.t(`alerts.close`)),l.innerHTML=i.i(`x`,14),l.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),this.newBtn=document.createElement(`button`),this.newBtn.className=`tcw-alerts-new`,this.newBtn.type=`button`,this.newBtn.setAttribute(`aria-label`,this.t(`alerts.add`)),this.newBtn.title=this.t(`alerts.add`),this.newBtn.innerHTML=i.i(`plus`,14),this.newBtn.addEventListener(`click`,()=>this.showForm(this.formEl.hidden)),o.appendChild(c),o.appendChild(this.newBtn),o.appendChild(l),this.el.appendChild(o);let u=document.createElement(`form`);this.formEl=u,u.className=`tcw-alerts-form`,u.noValidate=!0,this.sourceSelect=document.createElement(`select`),this.sourceSelect.className=`tcw-alerts-source`,this.sourceSelect.setAttribute(`aria-label`,this.t(`alerts.source`)),this.sourceSelect.addEventListener(`change`,()=>{this.renderTargets(),this.prefillPrice()}),this.conditionSelect=document.createElement(`select`),this.conditionSelect.className=`tcw-alerts-condition`,this.conditionSelect.setAttribute(`aria-label`,this.t(`alerts.conditionLabel`));for(let e of zn){let t=document.createElement(`option`);t.value=e.value,t.textContent=this.t(e.key),this.conditionSelect.appendChild(t)}this.conditionSelect.addEventListener(`change`,()=>this.showFields()),this.levelRow=document.createElement(`div`),this.levelRow.className=`tcw-alerts-row-fields`,this.targetSelect=document.createElement(`select`),this.targetSelect.className=`tcw-alerts-target`,this.targetSelect.setAttribute(`aria-label`,this.t(`alerts.compareWith`)),this.targetSelect.addEventListener(`change`,()=>this.showFields()),this.priceInput=document.createElement(`input`),this.priceInput.type=`number`,this.priceInput.step=`any`,this.priceInput.placeholder=this.t(`alerts.value`),this.priceInput.setAttribute(`aria-label`,this.t(`alerts.value`)),this.priceInput.className=`tcw-alerts-price`,this.levelRow.append(this.targetSelect,this.priceInput),this.moveRow=document.createElement(`div`),this.moveRow.className=`tcw-alerts-row-fields`,this.percentInput=this.numberField(`tcw-alerts-percent`,this.t(`alerts.percent`),`1`,`0.01`),this.barsInput=this.numberField(`tcw-alerts-bars`,this.t(`alerts.bars`),`10`,`1`),this.barsInput.min=String(d.MIN_ALERT_BARS),this.barsInput.max=String(d.MAX_ALERT_BARS),this.moveRow.append(this.percentInput,this.barsInput);let f=document.createElement(`div`);f.className=`tcw-alerts-row-fields tcw-alerts-options`;let p=document.createElement(`label`);p.className=`tcw-alerts-check`,this.closeCheck=document.createElement(`input`),this.closeCheck.type=`checkbox`,p.append(this.closeCheck,document.createTextNode(this.t(`alerts.onBarClose`))),this.expirySelect=document.createElement(`select`),this.expirySelect.className=`tcw-alerts-expiry`,this.expirySelect.setAttribute(`aria-label`,this.t(`alerts.expires`));for(let e of[`never`,`hour`,`day`,`week`,`month`]){let t=document.createElement(`option`);t.value=e,t.textContent=this.t(`alerts.expires.${e}`),this.expirySelect.appendChild(t)}f.append(p,this.expirySelect),this.messageInput=document.createElement(`input`),this.messageInput.type=`text`,this.messageInput.placeholder=this.t(`alerts.note`),this.messageInput.setAttribute(`aria-label`,this.t(`alerts.note`)),this.messageInput.className=`tcw-alerts-message`;let m=document.createElement(`button`);m.type=`submit`,m.className=`tcw-alerts-add`,m.innerHTML=`${i.i(`plus`,14)}<span>${a.u(this.t(`alerts.add`))}</span>`,u.append(this.sourceSelect,this.conditionSelect,this.levelRow,this.moveRow,f,this.messageInput,m),u.addEventListener(`submit`,e=>{e.preventDefault(),this.submitForm()}),this.el.appendChild(u),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-alerts-list`,this.el.appendChild(this.listEl),this.emptyEl=document.createElement(`div`),this.emptyEl.className=`tcw-alerts-empty`,this.emptyEl.textContent=this.t(`alerts.empty`),this.listEl.appendChild(this.emptyEl),this.renderSources(),this.showFields(),this.placeForm(),e.appendChild(this.el)}placeForm(){let e=this.formChoice??this.alerts.length===0;this.formEl.hidden=!e,this.newBtn.setAttribute(`aria-expanded`,String(e))}showForm(e){this.formChoice=e,this.placeForm(),e&&(this.prefillPrice(),this.priceInput.focus())}numberField(e,t,n,r){let i=document.createElement(`input`);return i.type=`number`,i.step=r,i.min=`0`,i.value=n,i.className=e,i.placeholder=t,i.setAttribute(`aria-label`,t),i}showFields(){let e=Bn.includes(this.conditionSelect.value);this.moveRow.hidden=!e,this.levelRow.hidden=e,this.priceInput.hidden=this.targetSelect.value!==Hn}renderTargets(){let e=this.targetSelect.value,t=this.sourceSelect.value||`price`;this.targetSelect.replaceChildren();let n=document.createElement(`option`);n.value=Hn,n.textContent=this.t(`alerts.compare.value`),this.targetSelect.appendChild(n);for(let e of this.sources){if(e.channel===t)continue;let n=document.createElement(`option`);n.value=e.channel,n.textContent=e.label,this.targetSelect.appendChild(n)}this.targetSelect.value=[...this.targetSelect.options].some(t=>t.value===e)?e:Hn,this.showFields()}setSources(e){this.sources=e.length>0?e:[{channel:`price`,label:this.t(`alerts.source.price`)}],this.renderSources()}renderSources(){let e=this.sourceSelect.value||`price`;this.sourceSelect.replaceChildren();for(let e of this.sources){let t=document.createElement(`option`);t.value=e.channel,t.textContent=e.label,this.sourceSelect.appendChild(t)}this.sourceSelect.value=this.sources.some(t=>t.channel===e)?e:`price`,this.renderTargets()}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.priceInput.value===``&&this.prefillPrice()}prefillPrice(){let e=this.callbacks.getChannelValue(this.sourceSelect.value||`price`);this.priceInput.value=e===null?``:String(Wn(e))}close(){this.open=!1,this.el.hidden=!0}setAlerts(e){this.alerts=e,e.length===0&&(this.formChoice=null),this.renderList(),this.placeForm()}destroy(){this.el.remove()}submitForm(){let e=this.conditionSelect.value,t=this.messageInput.value.trim()||void 0,n=this.sourceSelect.value||`price`,r=this.sources.find(e=>e.channel===n)?.label??this.t(`alerts.source.price`),i={},a=NaN;if(Bn.includes(e)){i.percent=Number(this.percentInput.value),i.bars=Number(this.barsInput.value);let e=Number.isInteger(i.bars)&&i.bars>=d.MIN_ALERT_BARS&&i.bars<=d.MAX_ALERT_BARS;if(!(i.percent>0)||!e){this.markInvalid(i.percent>0?this.barsInput:this.percentInput);return}}else if(this.targetSelect.value!==Hn)i.target=this.targetSelect.value;else if(a=Number(this.priceInput.value),this.priceInput.value.trim()===``||!Number.isFinite(a)){this.markInvalid(this.priceInput);return}this.closeCheck.checked&&(i.onBarClose=!0);let o=Vn[this.expirySelect.value];if(o&&(i.expiresAt=(this.callbacks.now??Date.now)()+o),this.callbacks.onAdd({price:a,condition:e,message:t,channel:n,label:r,options:i})===!1)return;this.messageInput.value=``,this.prefillPrice();let s=this.formEl.contains(document.activeElement);this.formChoice=!1,this.placeForm(),s&&this.newBtn.focus()}markInvalid(e){e.setAttribute(`aria-invalid`,`true`),e.focus(),e.addEventListener(`input`,()=>e.removeAttribute(`aria-invalid`),{once:!0})}describe(e){return Rn(e,this.t,this.callbacks.formatPrice)}renderList(){if(this.listEl.replaceChildren(),this.alerts.length===0){this.listEl.appendChild(this.emptyEl);return}for(let e of[...this.alerts].reverse()){let t=document.createElement(`div`);t.className=`tcw-alerts-row`+(e.triggered?` tcw-alerts-triggered`:``)+(e.expired?` tcw-alerts-expired`:``);let n=document.createElement(`div`);n.className=`tcw-alerts-info`;let r=document.createElement(`div`);r.className=`tcw-alerts-row-main`,r.textContent=this.describe(e),n.appendChild(r);let a=[];if(e.onBarClose&&a.push(this.t(`alerts.onClose`)),e.expiresAt!==void 0&&!e.expired){let t=this.callbacks.formatTime?.(e.expiresAt)??new Date(e.expiresAt).toISOString();a.push(s.r(this.t(`alerts.until`),{time:t}))}if(a.length>0){let e=document.createElement(`div`);e.className=`tcw-alerts-row-meta`,e.textContent=a.join(` · `),n.appendChild(e)}if(e.message){let t=document.createElement(`div`);t.className=`tcw-alerts-row-note`,t.textContent=e.message,n.appendChild(t)}if(e.triggered||e.expired){let t=document.createElement(`span`);t.className=`tcw-alerts-badge`,t.textContent=this.t(e.expired?`alerts.expired`:`alerts.triggered`),r.appendChild(t)}let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-alerts-del`,o.setAttribute(`aria-label`,this.t(`alerts.delete`)),o.innerHTML=i.i(`trash`,14),o.addEventListener(`click`,()=>this.callbacks.onRemove(e.id)),t.appendChild(n),t.appendChild(o),this.listEl.appendChild(t)}}},qn=`print`,Jn=3,Yn=10,Xn=[[3400,1/2],[2560,1/3],[1800,1/6]],Zn=Math.sqrt(u.PHI),Qn=3,$n=1.4,er=[2,4,6,8,12,20,32],tr=[2,3,5,8,13,21,34],nr={even:er[4],classic:tr[3]},rr=`calc-size(max-content, round(up, size, 1px))`,ir={even:[20,16],classic:[19,15]};function ar(e){return e!==`classic`&&e!==`compact`}var or=.5,sr=3,cr=.75,lr=2;function ur(e){let t=Xn.find(([t])=>e>=t);return t?u.PHI**t[1]:1}function dr(e,t){if(t===1)return e;let n=e.sizes,r=ar(e.density),i=e=>r?(0,u.evenPx)(e*t):Math.round(e*t);return{...e,sizes:{toolbar:i(n.toolbar),control:i(n.control),controlSmall:i(n.controlSmall),icon:i(n.icon),sidebar:i(n.sidebar),menuItem:i(n.menuItem)},font:{...e.font,size:Math.round(e.font.size*t)}}}function M(e,t){return Math.max(Yn,(0,u.phiStep)(e,t,Jn))}var fr=`system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`,pr=`'JetBrains Mono', 'SF Mono', 'Cascadia Code', 'Fira Code', 'Consolas', ui-monospace, monospace`,mr=u.SANS_FONT_FAMILY.replace(`'Segoe UI'`,`'Segoe UI Variable Text', 'Segoe UI'`),hr=u.FIGURES_FONT_FAMILY,gr=`Tahoma, Verdana, 'Segoe UI', 'DejaVu Sans', sans-serif`,_r={print:{radius:{xs:1,sm:2,md:3,lg:5,xl:8},components:{tag:2,toolbar:0,sidebar:0},sizes:{toolbar:42,control:34,controlSmall:26,icon:20,sidebar:42,menuItem:34},classic:{control:33,menuItem:33},density:{compact:{toolbar:33,control:26,controlSmall:20,icon:16,sidebar:32,menuItem:26},spacious:{toolbar:54,control:42,controlSmall:34,icon:26,sidebar:60,menuItem:42}},font:{family:mr,mono:hr,size:13,weight:400,strongWeight:500,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-lg)`,dialog:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-lg)`,tooltip:`var(--tcw-shadow-sm)`},blur:0,active:`solid`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:2,iconStroke:1},studio:{radius:{xs:3,sm:5,md:7,lg:11,xl:16},components:{toolbar:0,sidebar:0},sizes:{toolbar:46,control:30,controlSmall:24,icon:18,sidebar:44,menuItem:30},font:{family:`'Manrope', 'Inter', ${fr}`,mono:pr,size:13,weight:500,strongWeight:600,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!1},shadows:{menu:`var(--tcw-shadow-lg)`,dialog:`var(--tcw-shadow-xl)`,tooltip:`var(--tcw-shadow-md)`},blur:0,active:`tint`,toolbar:`docked`,sidebar:`docked`,intervals:`segmented`,tagRadius:4,iconStroke:0},terminal:{radius:{xs:1,sm:2,md:2,lg:2,xl:3},components:{tag:0,toolbar:0,sidebar:0},sizes:{toolbar:36,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},classic:{sidebar:39},font:{family:`'IBM Plex Sans Condensed', 'Roboto Condensed', 'Arial Narrow', ${fr}`,mono:`'IBM Plex Mono', ui-monospace, monospace`,size:12,weight:500,strongWeight:600,labelCase:`uppercase`,labelTracking:.08},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border-strong)`,dialog:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-lg)`,tooltip:`none`},blur:0,active:`underline`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:0,iconStroke:0},capsule:{radius:{xs:6,sm:10,md:999,lg:18,xl:24},components:{tooltip:10,toolbar:999,sidebar:999,toast:999,tag:999},sizes:{toolbar:44,control:32,controlSmall:26,icon:18,sidebar:48,menuItem:34},classic:{sidebar:47},font:{family:`'Sora', 'Manrope', ${fr}`,mono:pr,size:13,weight:500,strongWeight:600,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!1},shadows:{menu:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-xl)`,dialog:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-xl)`,tooltip:`var(--tcw-shadow-lg)`},blur:16,active:`solid`,toolbar:`floating`,sidebar:`floating`,intervals:`segmented`,tagRadius:999,iconStroke:0},desk:{radius:{xs:0,sm:1,md:2,lg:2,xl:3},components:{tag:0,toolbar:0,sidebar:0},sizes:{toolbar:34,control:24,controlSmall:20,icon:16,sidebar:38,menuItem:24},classic:{sidebar:37},font:{family:gr,mono:gr,size:12,weight:400,strongWeight:700,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-sm)`,dialog:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-md)`,tooltip:`0 0 0 1px var(--tcw-border)`},blur:0,active:`tint`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:0,iconStroke:0}},vr={compact:{toolbar:38,control:26,controlSmall:20,icon:16,sidebar:32,menuItem:26},spacious:{toolbar:52,control:34,controlSmall:28,icon:20,sidebar:50,menuItem:34}};function yr(e,t){return t===`classic`?{...e.sizes,...e.classic}:t===`compact`?(e.density??vr).compact:t===`spacious`||t===`airy`?(e.density??vr).spacious:e.sizes}function br(e,t){return{control:e.md,input:e.md,menu:e.lg,dialog:e.xl,panel:e.lg,tooltip:e.sm,tag:e.sm,toast:e.lg,toolbar:0,sidebar:0,...t}}var xr=Object.freeze(Object.fromEntries(Object.keys(_r).map(e=>[e,Cr(Sr(e))])));function Sr(e){let{density:t,classic:n,...r}=_r[e];return{...r,preset:e,density:`comfortable`,scale:`auto`,radius:{...r.radius},components:br(r.radius,r.components),sizes:{...r.sizes},font:{...r.font},borders:{...r.borders},shadows:{...r.shadows}}}function Cr(e){for(let t of Object.values(e))t&&typeof t==`object`&&Cr(t);return Object.freeze(e)}var wr=e=>typeof e==`string`&&Object.prototype.hasOwnProperty.call(_r,e),N=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,Tr=e=>typeof e==`string`&&e.trim().length>0&&e.length<=300&&!/[;{}<>\\]|url\s*\(|expression\s*\(|\/\*/i.test(e)&&Er(e);function Er(e){let t=0,n=``;for(let r of e)if(n)r===n&&(n=``);else if(r===`"`||r===`'`)n=r;else if(r===`(`)t++;else if(r===`)`&&--t<0)return!1;return t===0&&!n}var P=(e,t)=>typeof e==`string`&&t.includes(e);function F(e,t,n){let r={...e};if(!t||typeof t!=`object`)return r;for(let i of Object.keys(e)){let e=t[i];e!==void 0&&n(i,e)&&(r[i]=e)}return r}function I(e){let t=typeof e==`string`?{preset:e}:e??{},n=wr(t.preset)?t.preset:qn,r=_r[n],i=F(r.radius,t.radius,(e,t)=>N(t,0,999)),a=P(t.density,[`compact`,`classic`,`comfortable`,`spacious`,`airy`])?t.density:`comfortable`,o=F(yr(r,a),t.sizes,(e,t)=>e===`icon`?N(t,10,32):N(t,16,80)),s=F(r.font,t.font,(e,t)=>e===`family`||e===`mono`?Tr(t):e===`size`?N(t,11,20):e===`weight`||e===`strongWeight`?N(t,100,900):e===`labelCase`?t===`none`||t===`uppercase`:N(t,0,.5)),c=s.family===mr?u.SANS_FONT_FAMILY:s.family,l=a===`airy`&&t.font?.mono===void 0?{...s,mono:c}:s;return{preset:n,density:a,radius:i,components:F(br(i,r.components),t.components,(e,t)=>N(t,0,999)),sizes:o,font:l,borders:F(r.borders,t.borders,(e,t)=>e===`width`?N(t,0,4):typeof t==`boolean`),shadows:F(r.shadows,t.shadows,(e,t)=>Tr(t)),blur:N(t.blur,0,40)?t.blur:r.blur,active:P(t.active,[`tint`,`solid`,`underline`])?t.active:r.active,toolbar:P(t.toolbar,[`docked`,`floating`])?t.toolbar:r.toolbar,sidebar:P(t.sidebar,[`docked`,`floating`])?t.sidebar:r.sidebar,intervals:P(t.intervals,[`plain`,`segmented`])?t.intervals:r.intervals,tagRadius:N(t.tagRadius,0,999)?t.tagRadius:r.tagRadius,iconStroke:t.iconStroke===0||N(t.iconStroke,or,sr)?t.iconStroke:r.iconStroke,scale:typeof t.scale==`number`&&Number.isFinite(t.scale)&&t.scale>=cr&&t.scale<=lr?t.scale:`auto`}}function Dr(e){let t=e=>`${e}px`,n=e.radius,r=e.components,i=e.sizes,a=e.font,o=e.density===`compact`,s=ar(e.density),c=o?1:Zn,l=s?(0,u.evenPx)(i.control*Zn):Math.round(i.control*Zn),d=o?i.control:Math.min(l,i.sidebar-2*Qn),f=s?er:tr,p=t(s?nr.even:nr.classic),[m,h]=s?ir.even:ir.classic;return{...Object.fromEntries(f.map((e,n)=>[`--tcw-space-${n+1}`,t(e)])),"--tcw-control-pad":p,"--tcw-bar-pad":p,"--tcw-menu-row-pad":p,"--tcw-odd":s?`0px`:`1px`,"--tcw-line-height":String(s?Math.round((0,u.evenPx)(a.size*$n)/a.size*1e5)/1e5:$n),"--tcw-legend-line":t(m),"--tcw-legend-line-pane":t(h),"--tcw-line-xs":s?t((0,u.evenPx)(M(a.size,-2)*$n)):String($n),"--tcw-text-w":s?rr:`auto`,"--tcw-radius-xs":t(n.xs),"--tcw-radius-sm":t(n.sm),"--tcw-radius":t(n.md),"--tcw-radius-lg":t(n.lg),"--tcw-radius-xl":t(n.xl),"--tcw-control-radius":t(r.control),"--tcw-input-radius":t(r.input),"--tcw-menu-radius":t(r.menu),"--tcw-dialog-radius":t(r.dialog),"--tcw-panel-radius":t(r.panel),"--tcw-tooltip-radius":t(r.tooltip),"--tcw-tag-radius":t(r.tag),"--tcw-toast-radius":t(r.toast),"--tcw-toolbar-radius":t(r.toolbar),"--tcw-sidebar-radius":t(r.sidebar),"--tcw-toolbar-h":t(i.toolbar),"--tcw-control-h":t(i.control),"--tcw-control-h-sm":t(i.controlSmall),"--tcw-icon":t(i.icon),"--tcw-sidebar-w":t(i.sidebar),"--tcw-tool-h":t(d),"--tcw-tool-icon":t(2*Math.round(i.icon*c/2)),"--tcw-menu-item-h":t(i.menuItem),"--tcw-icon-stroke":t(e.iconStroke??0),"--tcw-font":a.family,"--tcw-font-mono":a.mono,"--tcw-font-size":t(a.size),"--tcw-font-size-sm":t(M(a.size,-1)),"--tcw-font-size-xs":t(M(a.size,-2)),"--tcw-font-size-lg":t(M(a.size,1)),"--tcw-font-size-xl":t(M(a.size,2)),"--tcw-font-size-display":t(M(a.size,3)),"--tcw-weight":String(a.weight),"--tcw-weight-strong":String(a.strongWeight),"--tcw-label-case":a.labelCase,"--tcw-label-tracking":`${a.labelTracking}em`,"--tcw-label-size":t(M(a.size,a.labelCase===`uppercase`?-2:-1)),"--tcw-border-w":t(e.borders.width),"--tcw-sep-w":e.borders.separators?t(Math.max(1,e.borders.width)):`0px`,"--tcw-menu-shadow":e.shadows.menu,"--tcw-dialog-shadow":e.shadows.dialog,"--tcw-tooltip-shadow":e.shadows.tooltip,"--tcw-blur":t(e.blur),"--tcw-surface-opacity":e.blur>0?`82%`:`100%`}}function Or(e,t,n={}){let r=n.variables!==!1;for(let[n,i]of Object.entries(Dr(t)))r?e.style.setProperty(n,i):e.style.removeProperty(n);e.dataset.tcwUi=t.preset,e.dataset.tcwActive=t.active,e.dataset.tcwToolbar=t.toolbar,e.dataset.tcwSidebar=t.sidebar,e.dataset.tcwIntervals=t.intervals,e.dataset.tcwSeparators=t.borders.separators?`on`:`off`,e.dataset.tcwIconStroke=(t.iconStroke??0)>0?`set`:`drawn`}var kr=class{el;indicatorsEl;drawingsEl;compareEl=null;callbacks;open=!1;drawingIndex=new Map;loose=[];pending=null;renaming=!1;dragging=null;constructor(e,t,n=s.t){this.t=n,this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-tree-panel`,r.o(this.el,`objectTree`),this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-tree-header`;let o=document.createElement(`span`);o.textContent=this.t(`objects.title`);let c=document.createElement(`button`);if(c.type=`button`,c.className=`tcw-tree-close`,c.setAttribute(`aria-label`,this.t(`objects.close`)),c.innerHTML=i.i(`x`,14),c.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),a.appendChild(o),a.appendChild(c),this.el.appendChild(a),this.indicatorsEl=this.makeSection(this.t(`objects.indicators`)),this.drawingsEl=this.makeSection(this.t(`objects.drawings`)),this.callbacks.onAddCompare){this.compareEl=this.makeSection(this.t(`objects.compare`),{label:this.t(`objects.addCompare`),run:()=>this.callbacks.onAddCompare?.()});let e=this.compareEl.parentElement?.querySelector(`.tcw-tree-add`);e&&r.o(e,`compare`)}e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}destroy(){this.pending=null,this.dragging?.stop(),this.el.remove()}setObjects(e,t,n=[]){this.renderIndicators(e),this.renderDrawings(t),this.renderCompares(n)}makeSection(e,t){let n=document.createElement(`div`);n.className=`tcw-tree-section`;let r=document.createElement(`div`);r.className=`tcw-tree-section-head`;let a=document.createElement(`span`);if(a.textContent=e,r.appendChild(a),t){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-tree-add`,e.setAttribute(`aria-label`,t.label),e.title=t.label,e.innerHTML=i.i(`plus`,13),e.addEventListener(`click`,t.run),r.appendChild(e)}let o=document.createElement(`div`);return o.className=`tcw-tree-list`,n.appendChild(r),n.appendChild(o),this.el.appendChild(n),o}renderIndicators(e){if(this.indicatorsEl.replaceChildren(),e.length===0){this.indicatorsEl.appendChild(this.emptyRow(this.t(`objects.noIndicators`)));return}for(let t of e){let e=this.row(t.name,t.title);t.visible||e.classList.add(`tcw-tree-hidden`);let n=document.createElement(`div`);if(n.className=`tcw-tree-actions`,this.callbacks.onToggleIndicatorVisible&&n.appendChild(this.iconButton(t.visible?`eye`:`eyeOff`,t.visible?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleIndicatorVisible?.(t.instanceId,!t.visible))),this.callbacks.onConfigureIndicator){let e=this.iconButton(`settings`,this.t(`objects.indicatorSettings`),``,()=>this.callbacks.onConfigureIndicator?.(t.instanceId));r.o(e,`indicatorSettings`),n.appendChild(e)}n.appendChild(this.iconButton(`trash`,this.t(`objects.removeIndicator`),`tcw-tree-del`,()=>this.callbacks.onRemoveIndicator(t.instanceId))),e.appendChild(n),this.indicatorsEl.appendChild(e)}}renderDrawings(e){if(this.renaming||this.dragging){this.pending=e;return}this.pending=null;let t=document.activeElement?.closest(`.tcw-tree-grip`)?.closest(`[data-drawing-id]`)?.dataset.drawingId;this.drawingIndex=new Map(e.map((e,t)=>[e.id,t]));let n=[...e].reverse();this.loose=n.filter(e=>!e.group).map(e=>e.id),this.drawingsEl.replaceChildren(),this.listDrawings(n),t&&this.drawingsEl.querySelector(`[data-drawing-id="${t}"] .tcw-tree-grip`)?.focus()}flushPending(){this.pending&&!this.renaming&&!this.dragging&&this.renderDrawings(this.pending)}listDrawings(e){if(e.length===0){this.drawingsEl.appendChild(this.emptyRow(this.t(`objects.noDrawings`)));return}let t=new Set;for(let n of e){if(!n.group){this.drawingsEl.appendChild(this.drawingRow(n));continue}if(t.has(n.group.id))continue;t.add(n.group.id);let r=n.group.id,i=e.filter(e=>e.group?.id===r);this.drawingsEl.appendChild(this.groupRow(r,n.group.name,i));for(let e of i){let t=this.drawingRow(e);t.classList.add(`tcw-tree-member`),this.drawingsEl.appendChild(t)}}}groupRow(e,t,n){let r=this.row(t);r.classList.add(`tcw-tree-group`);let a=n.some(e=>e.visible),o=n.every(e=>e.locked);a||r.classList.add(`tcw-tree-hidden`);let s=r.querySelector(`.tcw-tree-name`);s.innerHTML=i.i(`layers`,13),s.append(` ${t}`);let c=document.createElement(`div`);return c.className=`tcw-tree-actions`,this.callbacks.onRenameGroup&&(s.addEventListener(`dblclick`,()=>this.renameGroup(s,e,t)),c.appendChild(this.iconButton(`penLine`,this.t(`objects.renameGroup`),``,()=>this.renameGroup(s,e,t)))),this.callbacks.onToggleGroupVisible&&c.appendChild(this.iconButton(a?`eye`:`eyeOff`,a?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleGroupVisible?.(e,!a))),this.callbacks.onToggleGroupLocked&&c.appendChild(this.iconButton(o?`lock`:`unlock`,o?this.t(`common.unlock`):this.t(`common.lock`),o?`tcw-tree-on`:``,()=>this.callbacks.onToggleGroupLocked?.(e,!o))),this.callbacks.onUngroup&&c.appendChild(this.iconButton(`x`,this.t(`drawingMenu.ungroup`),``,()=>this.callbacks.onUngroup?.(e))),r.appendChild(c),r}renameGroup(e,t,n){this.renameInline(e,n,this.t(`objects.renameGroup`),e=>{e&&e!==n&&this.callbacks.onRenameGroup?.(t,e)})}renameInline(e,t,n,r){if(!e.isConnected)return;this.renaming=!0;let i=document.createElement(`input`);i.type=`text`,i.className=`tcw-tree-rename`,i.value=t,i.maxLength=Ar,i.setAttribute(`aria-label`,n);let a=!1,o=t=>{if(a)return;a=!0;let n=i.value.trim();i.isConnected&&i.replaceWith(e),this.renaming=!1,t&&r(n),this.flushPending()};i.addEventListener(`keydown`,e=>{e.key===`Enter`?o(!0):e.key===`Escape`&&(e.stopPropagation(),o(!1))}),i.addEventListener(`blur`,()=>o(!0)),e.replaceWith(i),i.focus(),i.select()}drawingRow(e){let t=this.row(e.label);t.dataset.drawingId=e.id,(!e.visible||e.offInterval)&&t.classList.add(`tcw-tree-hidden`),e.offInterval&&(t.title=this.t(`indicatorSettings.offInterval`)),this.callbacks.onMoveDrawing&&!e.group&&(t.dataset.reorder=`true`,t.insertBefore(this.grip(e.id),t.firstChild));let n=t.querySelector(`.tcw-tree-name`);this.callbacks.onSelectDrawing&&(n.classList.add(`tcw-tree-pick`),n.addEventListener(`click`,()=>this.callbacks.onSelectDrawing?.(e.id))),this.callbacks.onRenameDrawing&&n.addEventListener(`dblclick`,()=>this.renameInline(n,e.label,this.t(`objects.renameDrawing`),t=>{t!==e.label&&this.callbacks.onRenameDrawing?.(e.id,t)}));let i=document.createElement(`div`);if(i.className=`tcw-tree-actions`,i.appendChild(this.iconButton(e.visible?`eye`:`eyeOff`,e.visible?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleDrawingVisible(e.id,!e.visible))),i.appendChild(this.iconButton(e.locked?`lock`:`unlock`,e.locked?this.t(`common.unlock`):this.t(`common.lock`),e.locked?`tcw-tree-on`:``,()=>this.callbacks.onToggleDrawingLocked(e.id,!e.locked))),this.callbacks.onCloneDrawing&&i.appendChild(this.iconButton(`copy`,this.t(`objects.cloneDrawing`),``,()=>this.callbacks.onCloneDrawing?.(e.id))),this.callbacks.onConfigureDrawing){let t=this.iconButton(`settings`,this.t(`objects.drawingSettings`),``,()=>this.callbacks.onConfigureDrawing?.(e.id));r.o(t,`drawingSettings`),i.appendChild(t)}return i.appendChild(this.iconButton(`trash`,this.t(`objects.removeDrawing`),`tcw-tree-del`,()=>this.callbacks.onRemoveDrawing(e.id))),t.appendChild(i),t}grip(e){let t=this.iconButton(`grip`,this.t(`objects.dragToReorder`),`tcw-tree-grip`,()=>{});return t.setAttribute(`aria-keyshortcuts`,`ArrowUp ArrowDown`),t.addEventListener(`pointerdown`,t=>{t.button===0&&(t.preventDefault(),this.beginRowDrag(e))}),t.addEventListener(`keydown`,t=>{let n=t.key===`ArrowUp`?-1:+(t.key===`ArrowDown`);if(!n)return;t.preventDefault();let r=this.loose[this.loose.indexOf(e)+n],i=r===void 0?void 0:this.drawingIndex.get(r);i!==void 0&&this.callbacks.onMoveDrawing?.(e,i)}),t}beginRowDrag(e){this.dragging?.stop();let t=null,n=n=>{t?.classList.remove(`tcw-tree-drop`),t=n&&n.dataset.drawingId!==e?n:null,t?.classList.add(`tcw-tree-drop`)},r=(e,t)=>[...this.drawingsEl.querySelectorAll(`.tcw-tree-row[data-reorder]`)].find(n=>{let r=n.getBoundingClientRect();return t>=r.top&&t<r.bottom&&e>=r.left&&e<r.right})??null,i=e=>r(e.clientX,e.clientY),a=e=>n(i(e)),o=e=>{e.key===`Escape`&&(e.stopPropagation(),c())},s=r=>{n(i(r));let a=t?this.drawingIndex.get(t.dataset.drawingId??``):void 0;c(),a!==void 0&&this.callbacks.onMoveDrawing?.(e,a)},c=()=>{n(null),document.removeEventListener(`pointermove`,a),document.removeEventListener(`pointerup`,s),document.removeEventListener(`pointercancel`,c),document.removeEventListener(`keydown`,o,!0),this.dragging=null,this.flushPending()};document.addEventListener(`pointermove`,a),document.addEventListener(`pointerup`,s),document.addEventListener(`pointercancel`,c),document.addEventListener(`keydown`,o,!0),this.dragging={id:e,stop:c}}renderCompares(e){if(!this.compareEl)return;if(this.compareEl.replaceChildren(),e.length===0){this.compareEl.appendChild(this.emptyRow(this.t(`objects.noComparisons`)));return}let t=e.some(e=>e.color);for(let n of e){let e=this.row(n.label);if(e.classList.add(`tcw-tree-compare`),t){let t=document.createElement(`span`);t.className=`tcw-tree-dot`,n.color&&(t.style.background=n.color),e.insertBefore(t,e.firstChild)}if(n.way){let t=document.createElement(`span`);t.className=`tcw-tree-way`,t.textContent=n.way,t.title=n.way,e.appendChild(t)}this.callbacks.onRemoveCompare&&e.appendChild(this.iconButton(`trash`,this.t(`objects.removeComparison`),`tcw-tree-del`,()=>this.callbacks.onRemoveCompare?.(n.id))),this.compareEl.appendChild(e)}}row(e,t=e){let n=document.createElement(`div`);n.className=`tcw-tree-row`;let r=document.createElement(`span`);return r.className=`tcw-tree-name`,r.textContent=e,r.title=t,n.appendChild(r),n}emptyRow(e){let t=document.createElement(`div`);return t.className=`tcw-tree-empty`,t.textContent=e,t}iconButton(e,t,n,r){let a=document.createElement(`button`);return a.type=`button`,a.className=`tcw-tree-btn ${n}`.trim(),a.setAttribute(`aria-label`,t),a.title=t,a.innerHTML=i.i(e,14),a.addEventListener(`click`,r),a}},Ar=80,jr={trendLine:`Trend Line`,ray:`Ray`,extendedLine:`Extended Line`,horizontalLine:`Horizontal Line`,horizontalRay:`Horizontal Ray`,crossLine:`Cross Line`,infoLine:`Info Line`,trendAngle:`Trend Angle`,circle:`Circle`,fibChannel:`Fib Channel`,fibSpeedResistanceFan:`Fib Speed Resistance Fan`,schiffPitchfork:`Schiff Pitchfork`,modifiedSchiffPitchfork:`Modified Schiff Pitchfork`,xabcdPattern:`XABCD Pattern`,abcdPattern:`ABCD Pattern`,headAndShoulders:`Head and Shoulders`,dateAndPriceRange:`Date and Price Range`,cyclicLines:`Cyclic Lines`,priceLabel:`Price Label`,verticalLine:`Vertical Line`,rectangle:`Rectangle`,ellipse:`Ellipse`,triangle:`Triangle`,arrow:`Arrow`,parallelChannel:`Parallel Channel`,regressionChannel:`Regression Channel`,disjointChannel:`Disjoint Channel`,flatTopBottom:`Flat Top/Bottom`,rotatedRectangle:`Rotated Rectangle`,pitchfork:`Pitchfork`,fibRetracement:`Fib Retracement`,fibExtension:`Fib Extension`,fibTimeZones:`Fib Time Zones`,gannBox:`Gann Box`,gannFan:`Gann Fan`,elliottWave:`Elliott Wave`,priceRange:`Price Range`,dateRange:`Date Range`,measure:`Measure`,text:`Text`,textAnnotation:`Text`,anchoredVWAP:`Anchored VWAP`,volumeProfileRange:`Volume Profile`,riskReward:`Long/Short Position`,signpost:`Signpost`,balloon:`Balloon`,anchoredText:`Anchored Text`,anchoredNote:`Anchored Note`};function Mr(e,t){let n=`tool.${e}`,r=t?.(n);return r&&r!==n?r:jr[e]??e}function Nr(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Pr=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Fr(e){return Pr(e)?Object.fromEntries(Object.entries(e).filter(([,e])=>typeof e==`number`&&Number.isFinite(e)||typeof e==`string`&&!(0,u.parseIndicatorSource)(e)||typeof e==`boolean`)):{}}function Ir(e){if(!Pr(e))return{};let t={};if(Array.isArray(e.colors)){let n=e.colors.filter(e=>typeof e==`string`&&e.trim()!==``);n.length>0&&(t.colors=n)}if(Array.isArray(e.lineWidths)){let n=e.lineWidths.filter(e=>typeof e==`number`&&Number.isFinite(e)&&e>0);n.length>0&&(t.lineWidths=n)}let n=(0,u.readIndicatorPlotStyles)(e.plots);return n&&(t.plots=n),t}var Lr=class{constructor(e=`tcw:indicator-defaults`,t=Nr()){this.key=e,this.storage=t}all(){let e=new Map,t;try{t=JSON.parse(this.storage?.getItem(this.key)??`{}`)}catch{return e}if(!Pr(t))return e;for(let[n,r]of Object.entries(t))Pr(r)&&e.set(n,{params:Fr(r.params),style:Ir(r.style)});return e}get(e){return this.all().get(e)??null}save(e,t){if(!this.storage)return!1;let n=Object.fromEntries([...this.all(),[e,{params:Fr(t.params),style:Ir(t.style)}]]);try{return this.storage.setItem(this.key,JSON.stringify(n)),!0}catch{return!1}}},Rr=1,zr=[`logScale`,`autoScale`],Br=new Set([`timezone`,`numberLocale`,`crosshairCursor`]),Vr=new Set([...zr,`chartTypeOptions`]),Hr=new Set([...zr,...Br,`scaleMode`,`invertScale`,`chartTypeOptions`]),Ur=new Set([...zr,...Br,`scaleMode`]),Wr=new Set,Gr=[`renko`,`lineBreak`,`kagi`,`pointAndFigure`,`rangeBars`];function Kr(e){return Gr.includes(e)}function qr(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>Zr(e)&&Object.keys(e).length>0))}function Jr(){return Object.fromEntries(Gr.map(e=>[e,{}]))}var Yr={crosshairMode:[`normal`,`magnet`,`hidden`],crosshairCursor:[`cross`,`dot`,`arrow`],scaleMode:[`regular`,`logarithmic`,`percentage`,`indexedTo100`],periodLevelsPeriod:[`day`,`week`]},Xr={marketProfileBuckets:{min:8,max:200,whole:!0},marketProfileOpacity:{min:.05,max:1},depthHeatmapOpacity:{min:.1,max:1},pivotStrength:{min:2,max:20,whole:!0}},Zr=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Qr(e){return e===`local`||t.v(e)!==null}function $r(e){try{return Intl.NumberFormat.supportedLocalesOf(e).length>0}catch{return!1}}function ei(e,n){let r=t.h[e];if(e===`chartTypeOptions`)return Zr(n)?(0,u.readChartTypeOptions)(n):void 0;if(typeof n!=typeof r)return;if(typeof n==`number`){if(!Number.isFinite(n))return;let t=Xr[e];if(!t)return n;let r=Math.min(t.max,Math.max(t.min,n));return t.whole?Math.round(r):r}if(typeof n!=`string`)return n;let i=Yr[e];return i?i.includes(n)?n:void 0:e===`timezone`?Qr(n)?n:void 0:e===`numberLocale`?$r(n)?n:void 0:n}function L(e,n=Wr){if(!Zr(e))return{};let r={};for(let i of Object.keys(t.h)){if(n.has(i)||!Object.prototype.hasOwnProperty.call(e,i))continue;let t=ei(i,e[i]);t!==void 0&&(r[i]=t)}return r}function ti(e,t){return Object.fromEntries(Object.keys(e).filter(e=>!t.has(e)).map(t=>[t,e[t]]))}function ni(e,t,n){return Object.fromEntries(Object.keys(e).filter(r=>!n.has(r)&&JSON.stringify(e[r])!==JSON.stringify(t[r])).map(t=>[t,e[t]]))}function ri(e,t){return ni({...e,chartTypeOptions:qr(e.chartTypeOptions)},t,Ur)}function ii(e){return e?(e===!0?void 0:e.key)||`tcw:chart-settings`:null}function ai(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var oi=class{constructor(e,t=ai()){this.key=e,this.storage=t}load(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`null`)}catch{return{}}return!Zr(e)||e.v!==Rr?{}:L(e.settings,Vr)}save(e,t){try{this.storage?.setItem(this.key,JSON.stringify({v:Rr,settings:ni(e,t,Vr)}))}catch{}}};function si(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var ci=80;function li(e){let{text:t,...n}=(0,u.sanitizeDrawingStyle)(e);return n}function ui(e){let t={name:e.name,style:{...e.style}};return e.type&&(t.type=e.type),e.options&&(t.options=structuredClone(e.options)),t}var di=class{templates=[];constructor(e=`tcw:draw-templates`,t=si()){this.storageKey=e,this.storage=t,this.load()}list(e){return this.templates.filter(t=>!t.type||t.type===e).map(ui)}get(e,t){let n=this.templates.find(n=>n.name===e&&n.type===t);return n?ui(n):null}save(e,t,n){let r=e.trim().slice(0,ci);if(!r)return;let i={name:r,style:li(t)};n&&(i.type=n.type,i.options=structuredClone(n.options)),this.templates=this.templates.filter(e=>!(e.name===r&&e.type===i.type)),this.templates.push(i),this.persist()}remove(e,t){this.templates=this.templates.filter(n=>!(n.name===e&&n.type===t)),this.persist()}clear(){this.templates=[],this.persist()}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;this.templates=t.filter(e=>e&&typeof e.name==`string`&&e.name.trim()!==``).map(e=>{let t={name:e.name.trim().slice(0,ci),style:li(e.style)};return typeof e.type==`string`&&(t.type=e.type),e.options&&typeof e.options==`object`&&!Array.isArray(e.options)&&(t.options=e.options),t})}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.templates))}catch{}}},fi=class{defaults={};constructor(e=`tcw:drawing-defaults`,t=si()){this.storageKey=e,this.storage=t;try{let e=this.storage?.getItem(this.storageKey),t=e?JSON.parse(e):null;if(t&&typeof t==`object`&&!Array.isArray(t))for(let[e,n]of Object.entries(t))n&&typeof n==`object`&&!Array.isArray(n)&&(this.defaults[e]=n)}catch{}}all(){return structuredClone(this.defaults)}set(e,t){t&&Object.keys(t).length>0?this.defaults[e]=structuredClone(t):delete this.defaults[e];try{this.storage?.setItem(this.storageKey,JSON.stringify(this.defaults))}catch{}}},pi=[`#4c8dff`,`#1fa874`,`#e8505b`,`#f2a93b`,`#a57cff`,`#1398a8`,`#ffffff`,`#7d8696`],mi=[1,2,3,4],hi=[`solid`,`dashed`,`dotted`],gi=class{el;templatesEl;nameInput;callbacks;store;open=!1;constructor(e,t,n,r=s.t){this.t=r,this.callbacks=t,this.store=n,this.el=document.createElement(`div`),this.el.className=`tcw-style-panel`,this.el.hidden=!0;let o=document.createElement(`div`);o.className=`tcw-style-header`;let c=document.createElement(`span`);c.textContent=this.t(`drawingStyle.title`);let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-style-close`,l.setAttribute(`aria-label`,this.t(`common.close`)),l.innerHTML=i.i(`x`,14),l.addEventListener(`click`,()=>this.close()),o.appendChild(c),o.appendChild(l),this.el.appendChild(o),this.el.appendChild(this.colorRow()),this.el.appendChild(this.widthRow()),this.el.appendChild(this.lineStyleRow());let u=document.createElement(`div`);u.className=`tcw-style-subhead`,u.textContent=this.t(`drawingStyle.templates`),this.el.appendChild(u);let d=document.createElement(`div`);d.className=`tcw-style-save`,this.nameInput=document.createElement(`input`),this.nameInput.type=`text`,this.nameInput.placeholder=this.t(`drawingStyle.templateName`),this.nameInput.className=`tcw-style-name`;let f=document.createElement(`button`);f.type=`button`,f.className=`tcw-style-savebtn`,f.innerHTML=`${i.i(`plus`,13)}<span>${a.u(this.t(`common.save`))}</span>`,f.addEventListener(`click`,()=>this.saveTemplate()),d.appendChild(this.nameInput),d.appendChild(f),this.el.appendChild(d),this.templatesEl=document.createElement(`div`),this.templatesEl.className=`tcw-style-templates`,this.el.appendChild(this.templatesEl),e.appendChild(this.el),this.renderTemplates()}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.syncActiveControls(),this.renderTemplates()}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}colorRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-colors`;for(let t of pi){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-swatch`,n.style.background=t,n.dataset.color=t,n.setAttribute(`aria-label`,t),n.addEventListener(`click`,()=>this.applyStyle({color:t})),e.appendChild(n)}let t=document.createElement(`input`);return t.type=`color`,t.className=`tcw-style-picker`,t.addEventListener(`input`,()=>this.applyStyle({color:t.value})),e.appendChild(t),e}widthRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-widths`;for(let t of mi){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-width`,n.dataset.width=String(t);let r=document.createElement(`span`);r.style.height=`${t}px`,n.appendChild(r),n.addEventListener(`click`,()=>this.applyStyle({lineWidth:t})),e.appendChild(n)}return e}lineStyleRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-dashes`;for(let t of hi){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-dash`,n.dataset.linestyle=t,n.textContent=t===`solid`?`──`:t===`dashed`?`╌╌`:`┄┄`,n.title=t,n.addEventListener(`click`,()=>this.applyStyle({lineStyle:t})),e.appendChild(n)}return e}applyStyle(e){this.callbacks.onStyleChange(e),this.syncActiveControls()}syncActiveControls(){let e=this.callbacks.getStyle();this.el.querySelectorAll(`.tcw-style-swatch`).forEach(t=>{t.classList.toggle(`tcw-on`,t.dataset.color?.toLowerCase()===e.color?.toLowerCase())}),this.el.querySelectorAll(`.tcw-style-width`).forEach(t=>{t.classList.toggle(`tcw-on`,Number(t.dataset.width)===e.lineWidth)}),this.el.querySelectorAll(`.tcw-style-dash`).forEach(t=>{t.classList.toggle(`tcw-on`,t.dataset.linestyle===e.lineStyle)})}saveTemplate(){let e=this.nameInput.value.trim();e&&(this.store.save(e,this.callbacks.getStyle()),this.nameInput.value=``,this.renderTemplates())}renderTemplates(){this.templatesEl.replaceChildren();let e=this.store.list();if(e.length===0){let e=document.createElement(`div`);e.className=`tcw-style-empty`,e.textContent=this.t(`drawingStyle.noTemplates`),this.templatesEl.appendChild(e);return}for(let t of e){let e=document.createElement(`div`);e.className=`tcw-style-template`;let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-apply`;let r=document.createElement(`span`);r.className=`tcw-style-tdot`,r.style.background=t.style.color??`var(--tcw-text-muted)`;let a=document.createElement(`span`);a.textContent=t.name,n.appendChild(r),n.appendChild(a),n.addEventListener(`click`,()=>{this.callbacks.onStyleChange({...t.style}),this.syncActiveControls()});let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-style-tdel`,o.setAttribute(`aria-label`,this.t(`drawingStyle.deleteTemplate`)),o.innerHTML=i.i(`trash`,13),o.addEventListener(`click`,()=>{this.store.remove(t.name),this.renderTemplates()}),e.appendChild(n),e.appendChild(o),this.templatesEl.appendChild(e)}}},_i={color:`color`,fill:`fillColor`,textColor:`textColor`},vi=32,yi=.618,R=4,bi=4,xi=20,Si=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d\s.,%/+-]+\)|[a-z]+)$/i;function z(e){return typeof e==`string`&&Si.test(e.trim())?e.trim():`#7d8696`}function Ci(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.min(t,xi):1}function wi(e){return hi.includes(e)?e:`solid`}var Ti=class{el;pop;target=null;built=``;size=null;openPop=null;pinned=null;drag=null;onDragMove=e=>{!this.drag||!this.target||e.pointerId!==this.drag.id||(this.pinned={left:this.drag.left+e.clientX-this.drag.x,top:this.drag.top+e.clientY-this.drag.y},this.place(this.target))};onDragEnd=e=>{e&&this.drag&&e.pointerId!==this.drag.id||(this.drag=null,document.removeEventListener(`pointermove`,this.onDragMove),document.removeEventListener(`pointerup`,this.onDragEnd),document.removeEventListener(`pointercancel`,this.onDragEnd))};onDocDown=e=>{this.openPop&&!this.el.contains(e.target)&&!this.pop.contains(e.target)&&this.closePop()};constructor(e,t,n=s.t){this.host=e,this.callbacks=t,this.t=n,this.el=document.createElement(`div`),this.el.className=`tcw-sel-toolbar`,this.el.setAttribute(`role`,`toolbar`),this.el.setAttribute(`aria-label`,n(`selectionToolbar.label`)),this.el.hidden=!0,this.pop=document.createElement(`div`),this.pop.className=`tcw-sel-pop`,this.pop.setAttribute(`role`,`dialog`),this.pop.hidden=!0,e.append(this.el,this.pop),this.el.addEventListener(`click`,e=>this.onClick(e)),this.el.addEventListener(`keydown`,e=>this.onKey(e)),this.pop.addEventListener(`click`,e=>this.onPick(e)),this.pop.addEventListener(`keydown`,e=>this.onPopKey(e));for(let e of[this.el,this.pop])e.addEventListener(`pointerdown`,e=>e.stopPropagation());this.el.addEventListener(`pointerdown`,e=>{e.target.closest(`.tcw-sel-grip`)&&(e.preventDefault(),this.closePop(),this.drag={id:e.pointerId,x:e.clientX,y:e.clientY,left:parseFloat(this.el.style.left)||0,top:parseFloat(this.el.style.top)||0},document.addEventListener(`pointermove`,this.onDragMove),document.addEventListener(`pointerup`,this.onDragEnd),document.addEventListener(`pointercancel`,this.onDragEnd))}),this.el.addEventListener(`dblclick`,e=>{!e.target.closest(`.tcw-sel-grip`)||!this.target||(this.pinned=null,this.place(this.target))}),document.addEventListener(`pointerdown`,this.onDocDown,!0)}isOpen(){return!this.el.hidden}show(e){this.target=e;let t=e.style,n=[z(t.color),Ci(t.lineWidth),wi(t.lineStyle),e.locked,e.canDelete,e.canSettings,e.canAlert,e.canFill===!0,e.canText===!0,e.canType===!0,t.fillColor,t.textColor].join(`|`);n!==this.built&&(this.built=n,this.render(e),this.size=null),this.el.hidden=!1,this.size||={w:this.el.offsetWidth,h:this.el.offsetHeight},this.place(e),this.openPop&&this.placePop()}hide(){this.closePop(),this.el.hidden=!0,this.target=null}destroy(){this.onDragEnd(),document.removeEventListener(`pointerdown`,this.onDocDown,!0),this.el.remove(),this.pop.remove()}render(e){let t=this.t,n=z(e.style.color),r=Ci(e.style.lineWidth),o=wi(e.style.lineStyle),s=e.locked,c=this.el.contains(document.activeElement)?document.activeElement.dataset.action:void 0,l=(e,t,n,r=``)=>`<button type="button" class="tcw-sel-btn${r}" data-action="${e}" aria-label="${a.u(t)}" title="${a.u(t)}">${n}</button>`,d=(e,t,n)=>l(e,t,n,` tcw-sel-has-pop`).replace(`<button `,`<button aria-haspopup="dialog" aria-expanded="false" `);this.el.innerHTML=[`<span class="tcw-sel-grip" aria-hidden="true"></span>`,d(`color`,t(`drawingSettings.color`),`<span class="tcw-sel-color" style="background:${a.u(n)}"></span>`),d(`width`,t(`drawingSettings.lineWidth`),`<span class="tcw-sel-width" style="--w:${r}px"></span><span class="tcw-sel-num">${r}px</span>`),d(`lineStyle`,t(`drawingSettings.lineStyle`),Ei(o)),e.canFill?d(`fill`,t(`drawingSettings.fill`),`<span class="tcw-sel-color tcw-sel-fill" style="background:${a.u(z((0,u.ownFillColor)(e.style)??n))}"></span>`):``,e.canText?d(`textColor`,t(`drawingSettings.textColor`),`<span class="tcw-sel-text" style="--c:${a.u(z(e.style.textColor??n))}">T</span>`):``,e.canType?l(`text`,t(`drawingSettings.text`),i.i(`textEdit`,15)):``,`<span class="tcw-sel-sep" aria-hidden="true"></span>`,e.canSettings?l(`settings`,t(`legend.settings`),i.i(`settings`,15)):``,e.canAlert?l(`alert`,t(`drawingSettings.addAlert`),i.i(`bell`,15)):``,l(`lock`,t(s?`common.unlock`:`common.lock`),i.i(s?`lock`:`unlock`,15),s?` tcw-sel-on`:``).replace(`<button `,`<button aria-pressed="${s}" `),l(`more`,t(`legend.more`),i.i(`more`,15)),e.canDelete?l(`delete`,t(`drawingMenu.delete`),i.i(`trash`,15),` tcw-sel-danger`):``].join(``);let f=this.buttons(),p=f.find(e=>e.dataset.action===c)??(c?f.find(e=>e.dataset.action===`lock`):void 0);this.rove(p??f[0],p!==void 0)}buttons(){return[...this.el.querySelectorAll(`button`)]}rove(e,t){for(let t of this.buttons())t.tabIndex=t===e?0:-1;t&&e?.focus()}place(e){let{bounds:t}=e,{w:n,h:r}=this.size??{w:0,h:0};if(this.pinned){let e=Math.max(t.x+R,Math.min(this.pinned.left,t.x+t.width-n-R)),i=Math.max(t.y+R,Math.min(this.pinned.top,t.y+t.height-r-R));this.el.style.left=`${Math.round(e)}px`,this.el.style.top=`${Math.round(i)}px`;return}let i=Math.max(t.x+R,t.x+(t.width-n)/2),a=n>t.width*yi,o=t.y+t.height-r-R,s=Math.max(t.y+R,a?o:Math.min(t.y+vi,o));this.el.style.left=`${Math.round(i)}px`,this.el.style.top=`${Math.round(s)}px`}onClick(e){let t=e.target.closest(`[data-action]`);if(!t)return;this.rove(t,!1);let n=t.dataset.action;if(n===`color`||n===`width`||n===`lineStyle`||n===`fill`||n===`textColor`){this.openPop===n?this.closePop():this.openPopover(n,t);return}if(this.closePop(),n===`settings`)this.callbacks.onSettings();else if(n===`text`)this.callbacks.onText();else if(n===`alert`)this.callbacks.onAlert();else if(n===`lock`)this.callbacks.onLock(!this.target?.locked);else if(n===`delete`)this.callbacks.onDelete();else if(n===`more`){let e=t.getBoundingClientRect(),n=this.host.getBoundingClientRect();this.callbacks.onMore(e.left-n.left,e.bottom-n.top+R)}}onKey(e){if(e.key===`Escape`&&this.openPop){e.stopPropagation(),this.closePop(!0);return}let t=this.buttons(),n=t.indexOf(document.activeElement);if(n<0)return;let r=e.key===`ArrowRight`?(n+1)%t.length:e.key===`ArrowLeft`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),this.rove(t[r],!0))}openPopover(e,t){let n=this.target.style,r=z(e===`fill`?(0,u.ownFillColor)(n)??n.color:e===`textColor`?n.textColor??n.color:n.color).toLowerCase(),i=Ci(n.lineWidth),o=wi(n.lineStyle),s=(e,t,n,r=``)=>`<button type="button" class="${e}${t?` tcw-sel-on`:``}" aria-pressed="${t}" ${n}>${r}</button>`;this.openPop=e,e===`color`||e===`fill`||e===`textColor`?this.pop.innerHTML=pi.map(e=>s(`tcw-sel-swatch`,e.toLowerCase()===r,`data-color="${e}" style="background:${e}" aria-label="${e}"`)).join(``):e===`width`?this.pop.innerHTML=mi.map(e=>s(`tcw-sel-option`,e===i,`data-width="${e}"`,`<span class="tcw-sel-width" style="--w:${e}px"></span>${e}px`)).join(``):this.pop.innerHTML=hi.map(e=>s(`tcw-sel-option`,e===o,`data-style="${e}"`,Ei(e)+a.u(this.t(`drawingSettings.lineStyle.${e}`)))).join(``),this.pop.className=`tcw-sel-pop tcw-sel-pop--${e}`,this.pop.setAttribute(`aria-label`,t.getAttribute(`aria-label`)??``),this.pop.hidden=!1;for(let e of this.el.querySelectorAll(`[aria-expanded="true"]`))e.setAttribute(`aria-expanded`,`false`);t.setAttribute(`aria-expanded`,`true`),this.placePop(),this.pop.querySelector(`.tcw-sel-on, button`)?.focus()}onPopKey(e){if(e.key===`Escape`){e.stopPropagation(),this.closePop(!0);return}let t=[...this.pop.querySelectorAll(`button`)],n=t.indexOf(document.activeElement);if(n<0)return;let r=this.openPop===`color`||this.openPop===`fill`||this.openPop===`textColor`?bi:1,i=e.key===`ArrowRight`?1:e.key===`ArrowLeft`?-1:e.key===`ArrowDown`?r:e.key===`ArrowUp`?-r:0;i&&(e.preventDefault(),t[(n+i+t.length)%t.length].focus())}placePop(){let e=this.el.querySelector(`[data-action="${this.openPop}"]`);e&&(this.pop.style.left=`${this.el.offsetLeft+e.offsetLeft}px`,this.pop.style.top=`${this.el.offsetTop+this.el.offsetHeight+6}px`)}onPick(e){let t=e.target.closest(`button`);if(!t)return;let n=this.openPop&&this.openPop in _i?_i[this.openPop]:`color`;t.dataset.color?this.callbacks.onStyle({[n]:t.dataset.color}):t.dataset.width?this.callbacks.onStyle({lineWidth:Number(t.dataset.width)}):t.dataset.style&&this.callbacks.onStyle({lineStyle:wi(t.dataset.style)}),this.closePop(!0)}closePop(e=!1){if(!this.openPop)return;let t=this.el.querySelector(`[data-action="${this.openPop}"]`);t?.setAttribute(`aria-expanded`,`false`),this.openPop=null,this.pop.hidden=!0,e&&t?.focus()}};function Ei(e){return`<svg class="tcw-sel-line" width="22" height="10" viewBox="0 0 22 10" aria-hidden="true"><line x1="1" y1="5" x2="21" y2="5" stroke="currentColor" stroke-width="2"${e===`dashed`?` stroke-dasharray="4 3"`:e===`dotted`?` stroke-dasharray="1 3" stroke-linecap="round"`:``}/></svg>`}var B={text:{box:!1,border:!1,wrap:0,fontSize:14},note:{box:!0,border:!0,wrap:240,fontSize:14},callout:{box:!0,border:!0,wrap:240,fontSize:14},signpost:{box:!0,border:!0,wrap:200,fontSize:14},balloon:{box:!0,border:!0,wrap:200,fontSize:14},anchoredText:{box:!1,border:!1,wrap:0,fontSize:14},anchoredNote:{box:!0,border:!0,wrap:240,fontSize:14}},Di=new Set([`trendLine`,`ray`,`extendedLine`,`infoLine`,`trendAngle`,`arrow`,`horizontalLine`,`horizontalRay`,`verticalLine`,`rectangle`]),Oi={priceLabel:`#ffffff`},ki=8,Ai=6,ji=1.3,Mi=120,V=1,Ni=4,Pi=229,Fi=500,H=8,Ii=400,Li=class{wrap=null;area=null;target=null;frame=0;done=!0;openedAt=0;offSince=0;onPressAway=e=>{if(!(!this.area||e.target===this.area)){if(this.area.value===this.target?.text&&performance.now()-this.openedAt<Fi){e.preventDefault(),e.stopPropagation();return}this.finish(!0,!1)}};constructor(e){this.layer=e}isOpen(){return this.area!==null}open(e){this.area&&this.finish(!0,!1);let t=e.rect();if(!t)return!1;this.target=e,this.done=!1;let n=document.createElement(`div`);n.className=`tcw-inline-text`;let r=document.createElement(`textarea`);r.className=`tcw-inline-text-input`,r.value=e.text,r.rows=1,r.spellcheck=!1,r.setAttribute(`aria-label`,e.label),e.placeholder&&(r.placeholder=e.placeholder);let{size:i,bold:a,italic:o,family:s}=e.font;return Object.assign(r.style,{fontSize:`${i}px`,fontWeight:a?`bold`:`normal`,fontStyle:o?`italic`:`normal`,fontFamily:s,lineHeight:String(ji),color:e.color,padding:`${Ai}px ${ki}px`}),r.addEventListener(`input`,()=>{this.fit(),this.target?.onInput(r.value);let e=this.target?.rect();e&&this.place(e),this.fit(),e&&this.place(e)}),r.addEventListener(`keydown`,e=>{e.stopPropagation(),!(e.isComposing||e.keyCode===Pi)&&(e.key===`Escape`?(e.preventDefault(),this.finish(!1,!0)):e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.finish(!0,!0)))}),r.addEventListener(`blur`,()=>this.finish(!0,!1)),n.appendChild(r),this.layer().appendChild(n),this.wrap=n,this.area=r,this.place(t),this.fit(),r.focus(),r.select(),this.openedAt=performance.now(),this.offSince=0,document.addEventListener(`pointerdown`,this.onPressAway,!0),document.addEventListener(`mousedown`,this.onPressAway,!0),this.follow(),!0}commit(){this.finish(!0,!1)}close(){this.done=!0,this.teardown()}finish(e,t){if(this.done||!this.area||!this.target)return;this.done=!0;let n=this.area.value,r=this.target;this.teardown(),e?r.onCommit(n):r.onCancel(),t&&r.returnFocus?.()?.focus({preventScroll:!0})}teardown(){document.removeEventListener(`pointerdown`,this.onPressAway,!0),document.removeEventListener(`mousedown`,this.onPressAway,!0),cancelAnimationFrame(this.frame),this.frame=0,this.wrap?.remove(),this.wrap=null,this.area=null,this.target=null}place(e){let t=this.area;if(!t)return;let n=Math.max(Mi,window.innerWidth-H*2);t.style.maxWidth=`${n}px`;let r=Math.max(Mi,e.width+V*2+Ni);t.style.width=`${Math.min(n,r)}px`,t.style.minHeight=`${e.height+V*2}px`;let i=t.offsetWidth||r,a=t.offsetHeight||e.height+V*2;t.style.left=`${Math.max(H,Math.min(e.x-V,window.innerWidth-H-i))}px`,t.style.top=`${Math.max(H,Math.min(e.y-V,window.innerHeight-H-a))}px`}offWindow(e){return e.x>window.innerWidth||e.x+e.width<0||e.y>window.innerHeight||e.y+e.height<0}fit(){let e=this.area;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)}follow(){this.frame=requestAnimationFrame(()=>{if(!this.target||this.done)return;let e=this.target.rect(),t=e!==null&&this.offWindow(e);if(t?this.offSince===0&&(this.offSince=performance.now()):this.offSince=0,!e||t&&performance.now()-this.offSince>Ii){this.finish(!0,!1);return}this.place(e),this.follow()})}},Ri=[{id:`regularScale`,mode:`regular`,label:`settings.scale.regular`},{id:`logScale`,mode:`logarithmic`,label:`settings.scale.logarithmic`},{id:`percentScale`,mode:`percentage`,label:`settings.scale.percentage`},{id:`indexedScale`,mode:`indexedTo100`,label:`settings.scale.indexedTo100`}],zi=[{action:`resetView`,keys:`Alt+R`,feature:`hotkeys.resetView`},{action:`invertScale`,keys:`Alt+I`,feature:`hotkeys.invertScale`},{action:`goToDate`,keys:`Alt+G`,feature:`hotkeys.goToDate`}];function Bi(e){return Ri.find(t=>t.id===e)?.mode}function Vi(...e){return e.filter(e=>e.length>0).flatMap((e,t)=>t===0?[...e]:[`separator`,...e])}function U(e,t){let n=t.keys[e.id];return n?{...e,shortcut:n}:e}function Hi(e,t){if(e.price===void 0||!Number.isFinite(e.price))return[];let n=e.formatPrice(e.price),r=[];if(e.canAlert&&r.push({id:`alert`,label:s.r(t(`chartMenu.addAlert`),{price:n}),icon:`bell`}),e.canTrade){let i=e.lastPrice===null||e.price<=e.lastPrice;r.push(i?{id:`buyLimit`,label:s.r(t(`chartMenu.buyLimit`),{price:n}),icon:`trendingUp`}:{id:`buyStop`,label:s.r(t(`chartMenu.buyStop`),{price:n}),icon:`trendingUp`},i?{id:`sellStop`,label:s.r(t(`chartMenu.sellStop`),{price:n}),icon:`trendingDown`}:{id:`sellLimit`,label:s.r(t(`chartMenu.sellLimit`),{price:n}),icon:`trendingDown`}),e.canOrderTicket&&r.push({id:`orderTicket`,label:t(`chartMenu.orderTicket`),icon:`receipt`})}return e.canDraw&&r.push({id:`horizontalLine`,label:s.r(t(`chartMenu.horizontalLine`),{price:n}),icon:`minus`}),r}var Ui=e=>({id:`settings`,label:e(`chartMenu.settings`),icon:`settings`});function Wi(e,t){let n=[U({id:`resetView`,label:t(`chartMenu.resetView`)},e)];e.canPaste&&n.push({id:`paste`,label:t(`chartMenu.paste`)});let r=[];e.hasDrawings&&r.push(e.drawingsHidden?{id:`showDrawings`,label:t(`chartMenu.showDrawings`),icon:`eye`}:{id:`hideDrawings`,label:t(`chartMenu.hideDrawings`),icon:`eyeOff`},{id:`removeDrawings`,label:t(`chartMenu.removeDrawings`),icon:`trash`,danger:!0}),e.hasIndicators&&r.push({id:`removeIndicators`,label:t(`chartMenu.removeIndicators`),icon:`trash`,danger:!0});let i=e.canExport?[{id:`exportData`,label:t(`chartMenu.exportData`),icon:`save`}]:[];return Vi(Hi(e,t),n,r,[...i,Ui(t)])}function Gi(e,t){let n=[{id:`resetPriceScale`,label:t(`chartMenu.resetPriceScale`)},{id:`autoScale`,label:t(`settings.autoScale`),checked:e.autoScale},U({id:`invertScale`,label:t(`chartMenu.invertScale`),checked:e.inverted},e),{id:`leftScale`,label:t(`settings.leftScale`),checked:e.leftScale}],r=Ri.filter(t=>t.mode!==`logarithmic`||e.canLog).map(n=>({id:n.id,label:t(n.label),radio:!0,checked:e.scaleMode===n.mode})),i=[{id:`indicatorValueLabels`,label:t(`settings.indicatorValues`),checked:e.labels.values},{id:`alignAxisLabels`,label:t(`settings.alignAxisLabels`),checked:e.labels.aligned}];e.labels.countdown!==void 0&&i.push({id:`barCountdown`,label:t(`settings.barCountdown`),checked:e.labels.countdown});let a=[{id:`highLowLines`,label:t(`settings.highLowLines`),checked:e.lines.highLow},{id:`lastPriceLine`,label:t(`chartMenu.lastPriceLine`),checked:e.lines.lastPrice}];return Vi(n,r,[{id:`labels`,label:t(`chartMenu.labels`),submenu:i},{id:`lines`,label:t(`chartMenu.lines`),submenu:a}],Hi({...e,canTrade:!1,canDraw:!1},t),[Ui(t)])}function Ki(e,t){let n=[U({id:`resetView`,label:t(`chartMenu.resetTimeScale`)},e)];e.canGoToDate&&n.push(U({id:`goToDate`,label:t(`chartMenu.goToDate`),icon:`calendar`},e));let r=e.timezone.options.map(t=>({id:`tz:${t.value}`,label:t.label,radio:!0,checked:t.value===e.timezone.current}));return Vi(n,r.length>0?[{id:`timezone`,label:t(`settings.timezone`),submenu:r}]:[])}function qi(e,t){let n=e.pane?[{id:`paneLog`,label:t(`chartMenu.paneLog`),checked:e.pane.log},{id:`paneInvert`,label:t(`chartMenu.paneInvert`),checked:e.pane.invert},{id:`panePercent`,label:t(`chartMenu.panePercent`),checked:e.pane.percent}]:[];return Vi([U({id:`resetView`,label:t(`chartMenu.resetView`)},e)],n,[Ui(t)])}function Ji(e,t,n){switch(e){case`priceAxis`:return Gi(t,n);case`timeAxis`:return Ki(t,n);case`pane`:return qi(t,n);default:return Wi(t,n)}}var Yi=/^[-+−]/;function W(e,t,n){let r=e.replace(Yi,``);return r===n.replace(Yi,``)?r:t>0?`+${r}`:t<0?`-${r}`:r}function Xi(e){return e.startsWith(`+`)?`up`:e.startsWith(`-`)?`down`:null}var G=[`positions`,`orders`,`history`],Zi=[`order`,`close`,`reverse`,`stopLoss`,`takeProfit`],Qi=[`market`,`limit`,`stop`],$i=[`gtc`,`day`],K=`—`,ea=`{pnl}`,ta=3;function na(e,t,n){return e.includes(t??``)?t:n}function ra(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function ia(e,t){if(t===null)return null;let n=e.quantity-(e.closedQuantity??0),r=e.side===`buy`?1:-1;return{pnl:(t-e.entryPrice)*n*r,pct:e.entryPrice===0?0:(t-e.entryPrice)/e.entryPrice*100*r}}function aa(e){let t=document.createElement(`span`);return t.dir=`ltr`,t.textContent=e,t}function oa(e){let t=Xi(e);return t?`tcw-account-${t}`:``}var sa=class{el;tabButtons=new Map;tabLabels=new Map;tabCounts=new Map;totalsEl;content;tab=`positions`;snapshot={positions:[],orders:[],fills:[],price:null};open=!1;live=[];constructor(e,t,n=s.t){this.callbacks=t,this.t=n,this.el=document.createElement(`section`),this.el.className=`tcw-account`,this.el.hidden=!0,this.el.setAttribute(`aria-label`,this.t(`account.title`));let a=document.createElement(`div`);a.className=`tcw-account-head`;let o=document.createElement(`div`);o.className=`tcw-account-tabs`,o.setAttribute(`role`,`tablist`),o.addEventListener(`keydown`,e=>this.onTabKey(e));for(let e of G){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-account-tab`,t.setAttribute(`role`,`tab`),t.id=`tcw-account-tab-${e}`;let n=document.createElement(`span`);n.className=`tcw-account-tab-label`,n.textContent=this.t(`account.${e}`);let r=document.createElement(`span`);r.className=`tcw-account-count`,t.append(n,r),t.addEventListener(`click`,()=>this.selectTab(e)),this.tabButtons.set(e,t),this.tabLabels.set(e,n.textContent),this.tabCounts.set(e,r),o.appendChild(t)}this.totalsEl=document.createElement(`div`),this.totalsEl.className=`tcw-account-totals`;let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-account-new`,r.o(c,`orderTicket`),c.innerHTML=i.i(`plus`,13),c.append(this.t(`account.newOrder`)),c.addEventListener(`click`,()=>this.callbacks.onNewOrder());let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-tree-close`,l.setAttribute(`aria-label`,this.t(`account.close`)),l.innerHTML=i.i(`x`,14),l.addEventListener(`click`,()=>this.closePanel()),a.append(o,this.totalsEl,c,l),this.content=document.createElement(`div`),this.content.className=`tcw-account-body`,this.content.setAttribute(`role`,`tabpanel`),this.el.append(a,this.content),e.appendChild(this.el),this.renderTabs()}isOpen(){return this.open}toggle(){this.open?this.closePanel():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.render(),this.callbacks.onToggle?.(!0)}closePanel(){this.open&&(this.open=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}update(e){let t=this.snapshot;if(this.snapshot=e,ra(t.positions,e.positions)&&ra(t.orders,e.orders)&&ra(t.fills,e.fills)&&t.realisedPnl===e.realisedPnl){t.price!==e.price&&(this.renderTotals(),this.open&&this.tab===`positions`&&this.patchPrices());return}this.renderTabs(),this.open&&this.render()}destroy(){this.el.remove()}selectTab(e){this.tab=e,this.renderTabs(),this.render()}onTabKey(e){let t=G.indexOf(this.tab),n=e.key===`ArrowRight`?t+1:e.key===`ArrowLeft`?t-1:-2;if(n===-2)return;e.preventDefault();let r=G[(n+G.length)%G.length];this.selectTab(r),this.tabButtons.get(r)?.focus()}renderTabs(){let e={positions:this.snapshot.positions.length,orders:this.snapshot.orders.length,history:this.snapshot.fills.length};for(let[t,n]of this.tabButtons){let r=t===this.tab;this.tabCounts.get(t).textContent=String(e[t]),n.setAttribute(`aria-label`,`${this.tabLabels.get(t)} (${e[t]})`),n.setAttribute(`aria-selected`,String(r)),n.tabIndex=r?0:-1,r&&this.content.setAttribute(`aria-labelledby`,n.id)}this.renderTotals()}renderTotals(){let{positions:e,price:t,fills:n,realisedPnl:r}=this.snapshot,i=[],a=e.reduce((e,n)=>{let r=ia(n,t);return r===null?e:(e??0)+r.pnl},null);a!==null&&i.push(this.total(`account.openPnl`,a)),(n.length>0||r!==void 0&&r!==0)&&i.push(this.total(`account.realised`,r??n.reduce((e,t)=>e+(t.pnl??0),0))),this.totalsEl.replaceChildren(...i)}total(e,t){let n=document.createElement(`span`),r=this.amount(t);n.className=`tcw-account-total ${oa(r)}`.trim();let i=this.t(e),a=i.indexOf(ea),o=aa(r);return a<0?n.append(`${i} `,o):n.append(i.slice(0,a),o,i.slice(a+5)),n}render(){let e=document.activeElement,t=e instanceof HTMLElement&&this.content.contains(e)?e.dataset.focusKey:void 0;this.live=[],this.tab===`positions`?this.renderPositions():this.tab===`orders`?this.renderOrders():this.renderHistory(),t&&[...this.content.querySelectorAll(`[data-focus-key]`)].find(e=>e.dataset.focusKey===t)?.focus()}patchPrices(){let{price:e}=this.snapshot;for(let t of this.live)t.price.textContent=e===null?K:this.callbacks.formatPrice(e),this.writePnl(t.pnl,ia(t.position,e))}amount(e){return W(this.money(Math.abs(e)),e,this.money(0))}money(e){return this.callbacks.formatAmount?this.callbacks.formatAmount(e):e.toFixed(2)}percent(e){let t=e=>this.callbacks.formatNumber?this.callbacks.formatNumber(e,2):e.toFixed(2);return`${W(t(Math.abs(e)),e,t(0))}%`}writePnl(e,t){if(t===null){e.className=``,e.textContent=K;return}let n=this.amount(t.pnl);e.className=oa(n),e.textContent=`${n} · ${this.percent(t.pct)}`}table(e,t,n){if(t.length===0){let e=document.createElement(`p`);return e.className=`tcw-account-empty`,e.textContent=this.t(n),this.content.replaceChildren(e),null}let r=e.map(e=>e.key?this.t(e.key):``),i=document.createElement(`table`);i.className=`tcw-account-table`,i.setAttribute(`role`,`table`);let a=i.createTHead().insertRow();a.setAttribute(`role`,`row`),e.forEach((e,t)=>{let n=document.createElement(`th`);n.scope=`col`,n.setAttribute(`role`,`columnheader`),n.textContent=r[t],e.num&&(n.className=`tcw-num`),a.appendChild(n)});let o=i.createTBody();for(let n of t){let t=o.insertRow();t.setAttribute(`role`,`row`),n.forEach((n,i)=>{let a=t.insertCell();a.setAttribute(`role`,`cell`),a.dataset.label=r[i],e[i].num&&(a.className=`tcw-num`),typeof n==`string`?a.textContent=n:a.appendChild(n)})}return this.content.replaceChildren(i),i}sideCell(e,t=`position`){let n=document.createElement(`span`);return n.className=`tcw-account-side tcw-account-${e}`,n.textContent=this.sideText(e,t),n}sideText(e,t){return t===`trade`?this.t(e===`buy`?`ticket.buy`:`ticket.sell`):this.t(e===`buy`?`account.long`:`account.short`)}actions(...e){let t=document.createElement(`div`);t.className=`tcw-account-actions`;for(let n of e){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-tree-btn${n.danger?` tcw-tree-del`:``}`,e.setAttribute(`aria-label`,n.label),e.title=n.label,e.dataset.focusKey=n.key,e.innerHTML=i.i(n.icon,14),e.addEventListener(`click`,n.run),t.appendChild(e)}return t}price(e){return e===void 0?K:this.callbacks.formatPrice(e)}renderPositions(){let{formatPrice:e}=this.callbacks,{price:t}=this.snapshot,n=[],r=this.snapshot.positions.map(r=>{let i=r.quantity-(r.closedQuantity??0),a=aa(``);this.writePnl(a,ia(r,t)),n.push(a);let o=`${this.sideText(r.side,`position`)} ${i} @ ${e(r.entryPrice)}`;return[this.sideCell(r.side),String(i),e(r.entryPrice),t===null?K:e(t),a,this.price(r.stopLoss),this.price(r.takeProfit),this.actions({icon:`arrowUpDown`,label:`${this.t(`account.reverse`)}: ${o}`,key:`reverse:${r.id}`,run:()=>this.callbacks.onReversePosition(r.id)},{icon:`x`,label:`${this.t(`account.closePosition`)}: ${o}`,key:`close:${r.id}`,run:()=>this.callbacks.onClosePosition(r.id),danger:!0})]}),i=this.table([{key:`account.side`},{key:`account.quantity`,num:!0},{key:`account.entry`,num:!0},{key:`account.price`,num:!0},{key:`account.pnl`,num:!0},{key:`account.stopLoss`,num:!0},{key:`account.takeProfit`,num:!0},{key:null}],r,`account.noPositions`);if(!i)return;let a=[...i.tBodies[0].rows];this.snapshot.positions.forEach((e,t)=>this.live.push({position:e,price:a[t].cells[ta],pnl:n[t]}))}renderOrders(){let{formatPrice:e}=this.callbacks,t=this.snapshot.orders.map(t=>{let n=na(Qi,t.type===`stopLimit`?`stop`:t.type,`limit`),r=`${this.sideText(t.side,`trade`)} ${t.quantity} @ ${e(t.price)}`;return[this.sideCell(t.side,`trade`),this.t(`ticket.type.${n}`),String(t.quantity),e(t.price),this.price(t.stopLoss),this.price(t.takeProfit),t.timeInForce?this.t(`ticket.tif.${na($i,t.timeInForce,`gtc`)}`):K,this.actions({icon:`x`,label:`${this.t(`account.cancelOrder`)}: ${r}`,key:`cancel:${t.id}`,run:()=>this.callbacks.onCancelOrder(t.id),danger:!0})]});this.table([{key:`account.side`},{key:`ticket.type`},{key:`account.quantity`,num:!0},{key:`account.price`,num:!0},{key:`account.stopLoss`,num:!0},{key:`account.takeProfit`,num:!0},{key:`ticket.timeInForce`},{key:null}],t,`account.noOrders`)}renderHistory(){let{formatPrice:e,formatTime:t}=this.callbacks,n=[...this.snapshot.fills].reverse().map(n=>{let r=aa(``);return n.pnl===void 0?r.textContent=K:(r.textContent=this.amount(n.pnl),r.className=oa(r.textContent)),[t(n.time),this.sideCell(n.side,`trade`),String(n.quantity),e(n.price),this.t(`account.reason.${na(Zi,n.reason,`order`)}`),r]});this.table([{key:`account.time`},{key:`account.side`},{key:`account.quantity`,num:!0},{key:`account.price`,num:!0},{key:`account.reason`},{key:`account.pnl`,num:!0}],n,`account.noFills`)}},ca=1e-9;function la(e,t){return e.type===`market`?t:e.price}function ua(e,t,n={}){let r=[];(!(e.quantity>0)||!Number.isFinite(e.quantity))&&r.push(`quantity`),e.type!==`market`&&(!(e.price>0)||!Number.isFinite(e.price))&&r.push(`price`),e.type===`market`&&!((t??e.price)>0)&&r.push(`market`);let i=e.side===`buy`;if(t!==null&&e.type!==`market`&&e.price>0){let n=e.price<t;e.type===`limit`&&n!==i&&e.price!==t&&r.push(`limitSide`),e.type===`stop`&&n===i&&e.price!==t&&r.push(`stopSide`)}let a=e=>e===null||Number.isFinite(e)&&e>0;a(e.stopLoss)||r.push(`stopLoss`),a(e.takeProfit)||r.push(`takeProfit`);let o=la(e,t);return o!==null&&o>0&&(e.stopLoss!==null&&a(e.stopLoss)&&(i?e.stopLoss>=o:e.stopLoss<=o)&&r.push(`stopLossSide`),e.takeProfit!==null&&a(e.takeProfit)&&(i?e.takeProfit<=o:e.takeProfit>=o)&&r.push(`takeProfitSide`)),[...r,...da(e,n)]}function da(e,t){let n=[],r=e.type===`market`?null:e.price,i=[r,e.stopLoss,e.takeProfit].filter(e=>e!==null&&Number.isFinite(e)&&e>0),{roundPrice:a,limits:o,lot:s}=t;return a&&i.some(e=>Math.abs(a(e)-e)>ca)&&n.push(`priceStep`),o&&r!==null&&r>0&&(r>o.ceiling+ca||r<o.floor-ca)&&n.push(`priceLimits`),s!==void 0&&s>1&&e.quantity>s&&e.quantity%s!==0&&n.push(`lot`),n}function fa(e,t){let n={side:e.side,type:e.type,price:e.type===`market`?t??e.price:e.price,quantity:e.quantity};if(e.type===`stop`&&(n.stopPrice=e.price),e.type!==`market`&&(n.timeInForce=e.timeInForce),e.stopLoss!==null&&(n.stopLoss=e.stopLoss),e.takeProfit!==null&&(n.takeProfit=e.takeProfit),e.trailing&&e.stopLoss!==null){let t=ha(n.price,e.stopLoss);t>0&&(n.trailingStop=t)}return n}var pa=12;function ma(e){let t=String(e),n=t.indexOf(`.`);return t.includes(`e`)?pa:n===-1?0:Math.min(pa,t.length-n-1)}function ha(e,t){let n=Math.abs(e-t);return Number.isFinite(n)?Number(n.toFixed(Math.max(ma(e),ma(t)))):NaN}function ga(e,t){let n=la(e,t);if(n===null||e.stopLoss===null||e.takeProfit===null)return null;let r=Math.abs(n-e.stopLoss);return r>0?Math.abs(e.takeProfit-n)/r:null}function _a(e,t,n,r=1){let i=la(e,t);if(i===null||!(i>0)||!Number.isFinite(n)||!(e.quantity>0))return null;let a=e.side===`buy`?1:-1;return{pct:(n-i)/i*100*a,amount:(n-i)*e.quantity*a*r}}function va(e,t,n={}){let r=n.multiplier!==void 0&&n.multiplier>0?n.multiplier:1,i=la(e,t),a=i!==null&&i>0&&e.quantity>0?i*e.quantity*r:null,o=ua(e,t),s=(n,i)=>n===null||o.includes(i)?null:_a(e,t,n,r)?.amount??null,c=s(e.stopLoss,`stopLossSide`),l=s(e.takeProfit,`takeProfitSide`);return{value:a,risk:c,reward:l,ratio:c!==null&&l!==null?ga(e,t):null}}var ya=229,ba=1,xa=2,Sa=.999999999,Ca=0,wa=class{backdrop;modal;symbolEl;body;summaryEl;problemsEl;submit;draft=null;lastPrice=null;rules={};step=Ea;round=e=>Da(e,e);typed=new Map;returnFocus=null;uid=++Ca;constructor(e,t,n=s.t){this.callbacks=t,this.t=n,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let r=!1;this.backdrop.addEventListener(`pointerdown`,e=>{r=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&r&&this.close(),r=!1}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-order-ticket`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-ticket-title-${this.uid}`),this.modal.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&!e.isComposing&&e.keyCode!==ya){e.stopPropagation(),this.close();return}i.n(e,this.modal)});let a=document.createElement(`div`);a.className=`tcw-modal-header`;let o=document.createElement(`div`);o.className=`tcw-ticket-heading`;let c=document.createElement(`h3`);c.id=`tcw-ticket-title-${this.uid}`,c.textContent=this.t(`ticket.title`),this.symbolEl=document.createElement(`span`),this.symbolEl.className=`tcw-ticket-symbol`,o.append(c,this.symbolEl);let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-modal-close`,l.setAttribute(`aria-label`,this.t(`common.close`)),l.innerHTML=i.i(`x`,16),l.addEventListener(`click`,()=>this.close()),a.append(o,l),this.body=document.createElement(`div`),this.body.className=`tcw-modal-body tcw-ticket-body`,this.summaryEl=document.createElement(`div`),this.summaryEl.className=`tcw-ticket-summary`,this.problemsEl=document.createElement(`div`),this.problemsEl.className=`tcw-ticket-problems`,this.problemsEl.setAttribute(`aria-live`,`polite`);let u=document.createElement(`div`);u.className=`tcw-modal-footer`;let d=document.createElement(`button`);d.type=`button`,d.className=`tcw-footer-cancel`,d.textContent=this.t(`common.cancel`),d.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`button`,this.submit.className=`tcw-ticket-place`,this.submit.addEventListener(`click`,()=>this.place());let f=document.createElement(`div`);f.className=`tcw-footer-end`,f.append(d,this.submit),u.append(f),this.modal.append(a,this.body,this.summaryEl,this.problemsEl,u),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.lastPrice=e.lastPrice,this.rules=e.rules??{},this.step=e.step??Ea,this.round=e.round??(e=>Da(e,e)),this.typed.clear(),this.symbolEl.textContent=e.symbol?(0,u.tickerOf)(e.symbol):``;let t=this.round(e.price??e.lastPrice??0),n=e.side??`buy`,r=`market`;e.price!==void 0&&e.lastPrice!==null&&t!==e.lastPrice&&(r=t<e.lastPrice==(n===`buy`)?`limit`:`stop`),this.draft={side:n,type:r,quantity:this.lot(),price:t,stopLoss:null,takeProfit:null,timeInForce:`gtc`},this.problemsEl.replaceChildren(),this.render(),this.backdrop.hidden=!1,this.body.querySelector(`button[aria-pressed="true"]`)?.focus()}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.draft=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}setLastPrice(e){if(!this.draft||e===this.lastPrice)return;this.lastPrice=e;let t=this.body.querySelector(`.tcw-ticket-market`);t&&(t.textContent=this.marketText()),this.check()}destroy(){this.close(),this.backdrop.remove()}lot(){return this.rules.lot!==void 0&&this.rules.lot>1?this.rules.lot:1}quantityStep(e){if(this.rules.lot!==void 0&&this.rules.lot>1)return this.rules.lot;let t=Number.isFinite(e)?(0,u.stepDecimals)(e):0;return t>0?Number((10**-t).toFixed(t)):1}priceStep(e,t){return this.step(t>0?e:e*Sa)}writePrice(e){return Number.isFinite(e)?this.step===Ea?String(e):e.toFixed((0,u.stepDecimals)(this.step(e))):``}place(){let e=this.draft;!e||ua(e,this.lastPrice,this.rules).length>0||(this.callbacks.onSubmit(fa(e,this.lastPrice)),this.close())}set(e,t=!1){this.draft&&(this.draft={...this.draft,...e},t?this.render():this.check())}render(){let e=this.draft;if(!e)return;let t=this.focusedField();if(this.modal.dataset.side=e.side,this.body.replaceChildren(this.sideToggle(e.side),this.row(`ticket.type`,this.choices(`type`,[`market`,`limit`,`stop`],e.type,`ticket.type`,e=>this.set({type:e},!0))),this.row(`ticket.quantity`,this.stepped(`quantity`,e.quantity,e=>this.quantityStep(e),()=>this.lot(),String,e=>this.set({quantity:e})))),e.type===`market`){let e=document.createElement(`span`);e.className=`tcw-ticket-market`,e.textContent=this.marketText(),this.body.append(this.row(`ticket.price`,e))}else this.body.append(this.row(`ticket.price`,this.priceField(`price`,e.price,e=>this.set({price:e}))),this.row(`ticket.timeInForce`,this.choices(`timeInForce`,[`gtc`,`day`],e.timeInForce,`ticket.timeInForce`,e=>this.set({timeInForce:e}))));this.body.append(this.optionalPrice(`stopLoss`,e.stopLoss)),e.stopLoss!==null&&this.body.append(this.trailRow(e.trailing===!0)),this.body.append(this.optionalPrice(`takeProfit`,e.takeProfit)),t&&this.body.querySelector(t)?.focus(),this.check()}focusedField(){let e=document.activeElement;if(!(e instanceof HTMLElement)||!this.body.contains(e))return null;let t=e.dataset.ticketField;return t?`[data-ticket-field="${t}"]`:null}row(e,t){let n=document.createElement(`div`);n.className=`tcw-settings-row tcw-ticket-row`;let r=document.createElement(`span`);return r.className=`tcw-settings-label`,r.textContent=this.t(e),n.append(r,t),n}choices(e,t,n,r,i){let a=e===`type`?`ticket.type`:`ticket.tif`,s=Ta(e,o.a(t.map(e=>({value:e,label:this.t(`${a}.${e}`)})),n,i,this.t(r)));for(let t of s.querySelectorAll(`[role=radio]`))t.dataset.ticketField=`${e}-${t.dataset.value}`;return s}marketText(){let e=this.t(`ticket.type.market`);return this.lastPrice===null?e:`${e} · ${this.callbacks.formatPrice(this.lastPrice)}`}typeFor(e,t){return e.type===`market`||this.lastPrice===null||!(e.price>0)||e.price===this.lastPrice?e.type:e.price<this.lastPrice==(t===`buy`)?`limit`:`stop`}sideToggle(e){let t=document.createElement(`div`);t.className=`tcw-ticket-side`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`${this.t(`ticket.buy`)} / ${this.t(`ticket.sell`)}`);for(let n of[`buy`,`sell`]){let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-ticket-side-btn tcw-ticket-${n}`,r.textContent=this.t(`ticket.${n}`),r.setAttribute(`aria-pressed`,String(e===n)),r.dataset.ticketField=`side-${n}`,r.addEventListener(`click`,()=>{let e=this.draft;!e||e.side===n||this.set({side:n,type:this.typeFor(e,n)},!0)}),t.appendChild(r)}return t}priceField(e,t,n){return this.stepped(e,t,(e,t)=>this.priceStep(e,t),()=>this.lastPrice??this.draft?.price??0,e=>this.writePrice(e),n)}stepped(e,t,n,r,i,a){let c=Ta(e,document.createElement(`input`));c.type=`number`,c.className=`tcw-indi-input`,c.step=`any`,c.min=`0`,c.value=this.typed.get(e)??i(t);let l=this.t(`ticket.${e}`);c.setAttribute(`aria-label`,l),c.addEventListener(`input`,()=>{this.typed.set(e,c.value),a(c.value.trim()===``?NaN:Number(c.value))});let u=o.c(c,{step:n,fallback:r,format:i,labels:{down:s.r(this.t(`ticket.stepDown`),{field:l}),up:s.r(this.t(`ticket.stepUp`),{field:l})}});return u.down.dataset.ticketField=`${e}-down`,u.up.dataset.ticketField=`${e}-up`,u.element}optionalPrice(e,t){let n=e===`stopLoss`?`ticket.stopLoss`:`ticket.takeProfit`,r=document.createElement(`div`);r.className=`tcw-settings-row tcw-ticket-optional`;let i=o.u(t!==null,t=>{this.typed.delete(e),this.set({[e]:t?this.startOf(e):null,...e===`stopLoss`&&!t?{trailing:!1}:{}},!0)});i.setAttribute(`aria-label`,this.t(n)),i.dataset.ticketField=`${e}-switch`;let a=document.createElement(`div`);a.className=`tcw-ticket-optional-name`;let s=document.createElement(`span`);if(s.className=`tcw-settings-label`,s.textContent=this.t(n),a.appendChild(s),r.append(i,a),t!==null){let n=document.createElement(`span`);n.className=`tcw-ticket-away`,n.dataset.for=e,n.dir=`ltr`,a.appendChild(n),r.appendChild(this.priceField(e,t,t=>this.set({[e]:Number.isFinite(t)?t:NaN})))}return r}trailRow(e){let t=document.createElement(`div`);t.className=`tcw-settings-row tcw-ticket-trail`;let n=o.u(e,e=>this.set({trailing:e},!0));n.setAttribute(`aria-label`,this.t(`ticket.trailing`)),n.dataset.ticketField=`trailing-switch`;let r=document.createElement(`span`);return r.className=`tcw-settings-label`,r.textContent=this.t(`ticket.trailing`),t.append(n,r),t}startOf(e){let t=this.draft;if(!t)return NaN;let n=t.type===`market`?this.lastPrice??t.price:t.price;if(!(n>0))return NaN;let r=e===`stopLoss`?-ba:xa;return this.round(n*(1+(t.side===`buy`?r:-r)/100))}check(){let e=this.draft;if(!e)return;let t=ua(e,this.lastPrice,this.rules),n=t.map(e=>this.problemText(e));n.join(`
|
|
7956
7956
|
`)!==[...this.problemsEl.children].map(e=>e.textContent).join(`
|
|
7957
|
-
`)&&this.problemsEl.replaceChildren(...n.map(e=>{let t=document.createElement(`p`);return t.textContent=e,t}));for(let t of[`stopLoss`,`takeProfit`]){let n=this.body.querySelector(`.tcw-ticket-away[data-for="${t}"]`),r=e[t],i=r===null?null:_a(e,this.lastPrice,r,this.rules.multiplier);n&&(n.textContent=i?`${this.signedNumber(i.pct,2)}% · ${this.amount(i.amount)}`:``)}this.renderSummary(e),this.submit.disabled=t.length>0,this.submit.textContent=this.t(e.side===`buy`?`ticket.placeBuy`:`ticket.placeSell`)}renderSummary(e){let t=va(e,this.lastPrice,this.rules),n=t.risk===null?null:this.amount(t.risk),r=t.reward===null?null:this.amount(t.reward),i=[[`value`,`ticket.value`,t.value===null?null:this.money(t.value),null],[`risk`,`ticket.risk`,n,n===null?null:Xi(n)],[`reward`,`ticket.reward`,r,r===null?null:Xi(r)],[`ratio`,`ticket.rewardRisk`,t.ratio===null?null:this.number(t.ratio,2),null]];this.summaryEl.replaceChildren(...i.filter(([,,e])=>e!==null).map(([e,t,n,r])=>{let i=document.createElement(`div`);i.className=`tcw-ticket-summary-row`,i.dataset.row=e;let a=document.createElement(`span`);a.textContent=this.t(t);let o=document.createElement(`span`);return o.className=`tcw-ticket-figure${r?` tcw-ticket-${r}`:``}`,o.dir=`ltr`,o.textContent=n,i.append(a,o),i}))}number(e,t){return this.callbacks.formatNumber?this.callbacks.formatNumber(e,t):e.toFixed(t)}signedNumber(e,t){return W(this.number(Math.abs(e),t),e,this.number(0,t))}amount(e){return W(this.money(Math.abs(e)),e,this.money(0))}money(e){return(this.callbacks.formatAmount??this.callbacks.formatPrice)(e)}problemText(e){let t=this.t(`ticket.problem.${e}`),{limits:n,lot:r}=this.rules;return e===`priceLimits`&&n?s.r(t,{floor:this.callbacks.formatPrice(n.floor),ceiling:this.callbacks.formatPrice(n.ceiling)}):e===`lot`?s.r(t,{lot:r??1}):t}};function Ta(e,t){return t.dataset.ticketField=e,t}function Ea(e){let t=Math.abs(e);return t>0?10**Math.floor(Math.log10(t/100)):1}function Da(e,t){let n=Math.abs(t),r=n>=10||n===0?2:n>=1?4:Math.min(10,Math.ceil(-Math.log10(n))+3);return Number(e.toFixed(r))}var Oa=0,ka=class{backdrop;titleEl;input;submit;request=null;returnFocus=null;busy=!1;uid=++Oa;constructor(e,t=s.t){this.t=t,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let n=!1;this.backdrop.addEventListener(`pointerdown`,e=>{n=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&n&&this.close(),n=!1});let r=document.createElement(`form`);r.className=`tcw-modal tcw-modal-narrow tcw-name-prompt`,r.noValidate=!0,r.setAttribute(`role`,`dialog`),r.setAttribute(`aria-modal`,`true`),r.setAttribute(`aria-labelledby`,`tcw-name-title-${this.uid}`),r.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.stopPropagation(),this.close();return}i.n(e,r)}),r.addEventListener(`submit`,e=>{e.preventDefault(),this.done()});let a=document.createElement(`div`);a.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-name-title-${this.uid}`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=i.i(`x`,16),o.addEventListener(`click`,()=>this.close()),a.append(this.titleEl,o);let c=document.createElement(`div`);c.className=`tcw-modal-body`;let l=document.createElement(`label`);l.className=`tcw-name-field`;let u=document.createElement(`span`);u.textContent=this.t(`layouts.name`),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`tcw-indi-input`,this.input.maxLength=80,this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.placeholder=this.t(`layouts.namePlaceholder`),this.input.addEventListener(`input`,()=>this.check()),l.append(u,this.input),c.appendChild(l);let d=document.createElement(`div`);d.className=`tcw-modal-footer`;let f=document.createElement(`button`);f.type=`button`,f.className=`tcw-reset-link`,f.textContent=this.t(`common.cancel`),f.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`submit`,this.submit.className=`tcw-done-btn`,d.append(f,this.submit),r.append(a,c,d),this.backdrop.appendChild(r),e.appendChild(this.backdrop)}open(e){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.request=e,this.busy=!1,this.titleEl.textContent=e.title,this.submit.textContent=e.submitLabel,this.input.value=e.value??``,this.input.placeholder=e.placeholder??this.t(`layouts.namePlaceholder`),this.check(),this.backdrop.parentElement?.appendChild(this.backdrop),this.backdrop.hidden=!1,this.input.focus(),this.input.select()}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.request=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}destroy(){this.close(),this.backdrop.remove()}check(){this.submit.disabled=this.busy||e.r(this.input.value)===null}async done(){let t=this.request,n=e.r(this.input.value);if(!(!t||n===null||this.busy)){this.busy=!0,this.check();try{await t.onSubmit(n),this.request===t&&this.close()}catch{}finally{this.busy=!1,this.check()}}}},Aa=0,ja=class{el;input;hint;returnFocus=null;constructor(e,t,n){this.labels=t,this.onApply=n,this.el=document.createElement(`div`),this.el.className=`tcw-interval-input`,this.el.hidden=!0,this.el.setAttribute(`role`,`dialog`),this.el.setAttribute(`aria-label`,t.title),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`tcw-interval-field`,this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.maxLength=6,this.input.setAttribute(`aria-label`,t.title),this.hint=document.createElement(`div`),this.hint.className=`tcw-interval-hint`,this.hint.setAttribute(`role`,`status`),this.hint.id=`tcw-interval-hint-${++Aa}`,this.input.setAttribute(`aria-describedby`,this.hint.id),this.el.append(this.input,this.hint),e.appendChild(this.el),this.input.addEventListener(`input`,()=>this.check()),this.input.addEventListener(`keydown`,e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),this.apply()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.close())}),this.input.addEventListener(`blur`,()=>this.close(!1))}open(e){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.el.hidden=!1,this.input.value=e,this.check(),this.input.focus(),this.input.setSelectionRange(e.length,e.length)}close(e=!0){if(this.el.hidden)return;this.el.hidden=!0;let t=this.returnFocus;this.returnFocus=null,e&&t?.isConnected&&t.focus({preventScroll:!0})}isOpen(){return!this.el.hidden}destroy(){this.el.remove()}check(){let e=Ee(this.input.value)!==null;!e&&this.input.value.trim()!==``?this.input.setAttribute(`aria-invalid`,`true`):this.input.removeAttribute(`aria-invalid`),this.hint.textContent=e||this.input.value.trim()===``?this.labels.hint:this.labels.invalid}apply(){let e=Ee(this.input.value);if(e&&this.onApply(e)){this.close();return}this.input.setAttribute(`aria-invalid`,`true`),this.hint.textContent=this.labels.invalid}},Ma=class{constructor(e=`tcw:indicator-templates`){this.key=e}list(){let e;try{e=JSON.parse(localStorage.getItem(this.key)??`[]`)}catch{return[]}if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let{name:e,indicators:r}=n;if(typeof e!=`string`||!e.trim()||!Array.isArray(r))continue;let i=d.ChartStateManager.deserialize(JSON.stringify({version:2,indicators:r})).indicators;i.length>0&&t.push({name:e.slice(0,60),indicators:i})}return t.sort((e,t)=>e.name.localeCompare(t.name))}get(e){return this.list().find(t=>t.name===e)??null}save(e,t){let n=e.replace(/\s+/g,` `).trim().slice(0,60);if(!n)throw Error(`A template needs a name`);let r=[...this.list().filter(e=>e.name!==n),{name:n,indicators:[...t]}];localStorage.setItem(this.key,JSON.stringify(r))}remove(e){try{localStorage.setItem(this.key,JSON.stringify(this.list().filter(t=>t.name!==e)))}catch{}}},Na=[`regular`,`logarithmic`,`percentage`,`indexedTo100`],Pa=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Fa(e){let{theme:t,timestamp:n,...r}=e;return r}function Ia(e){return!Pa(e)||e.v!==1||typeof e.symbol!=`string`||!e.symbol||typeof e.timeframe!=`string`||!((0,u.isTimeFrame)(e.timeframe)||(0,u.tickBarCount)(e.timeframe)!==null)?null:{v:1,symbol:e.symbol,timeframe:e.timeframe,scaleMode:Na.find(t=>t===e.scaleMode)??`regular`,invertScale:e.invertScale===!0,chart:Pa(e.chart)?Fa(e.chart):null,...Pa(e.settings)?{settings:L(e.settings,Hr)}:{}}}function La(e){try{return JSON.parse(e)}catch{return null}}function Ra(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var za=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=Ra()){this.storageKey=e,this.storage=t,this.load()}list(){return[...this.favorites]}has(e){return this.favorites.includes(e)}add(e){!e||this.favorites.includes(e)||(this.favorites=[...this.favorites,e],this.persist())}remove(e){this.favorites.includes(e)&&(this.favorites=this.favorites.filter(t=>t!==e),this.persist())}toggle(e){return this.has(e)?(this.remove(e),!1):(this.add(e),!0)}seedDefaults(e){this.favorites.length>0||(this.favorites=[...new Set(e.filter(Boolean))],this.persist())}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&(this.favorites=[...new Set(t.filter(e=>typeof e==`string`))])}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.favorites))}catch{}}};function Ba(e){let t=typeof window<`u`?window.visualViewport:null;if(!t)return()=>{};let n=-1,r=()=>{let r=(t.scale??1)>1.01?0:Math.max(0,Math.round(window.innerHeight-t.height-t.offsetTop));if(r!==n){n=r;for(let t of e)t.style.setProperty(`--tcw-keyboard-inset`,`${r}px`)}};return r(),t.addEventListener(`resize`,r),t.addEventListener(`scroll`,r),()=>{t.removeEventListener(`resize`,r),t.removeEventListener(`scroll`,r)}}function Va(e,t){let n=null,r=()=>{let r=e.clientWidth;if(r===0&&n!==null)return;let i=r<641;i!==n&&(n=i,e.toggleAttribute(`data-tcw-narrow`,i),t?.(i))};if(r(),typeof ResizeObserver>`u`)return()=>{};let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()}function q(e){let t=null,n=null;return{get:()=>t,load(){return t?Promise.resolve(t):(n??=e().then(e=>(t=e,n=null,e),e=>{throw n=null,e}),n)}}}var Ha=class{part=null;loading=null;gone=!1;constructor(e,t,n,r=()=>{}){this.module=e,this.build=t,this.dispose=n,this.onError=r}get(){return this.part}now(){let e=this.module.get();return!this.part&&!this.gone&&e&&(this.part=this.build(e)),this.part}isLoading(){return this.loading!==null}load(){if(this.gone)return Promise.resolve(null);let e=this.now();return e?Promise.resolve(e):(this.loading??=this.module.load().then(()=>(this.loading=null,this.now()),e=>(this.loading=null,this.gone||this.onError(e instanceof Error?e:Error(String(e))),null)),this.loading)}destroy(){this.gone=!0,this.part&&this.dispose(this.part),this.part=null}},J={settings:q(()=>Promise.resolve().then(()=>require(`../WidgetSettings-COljE3G_.cjs`))),indicatorSettings:q(()=>Promise.resolve().then(()=>require(`../WidgetIndicatorSettings-Da_T6bmX.cjs`))),drawingSettings:q(()=>Promise.resolve().then(()=>require(`../WidgetDrawingSettings-BjPR5Wyq.cjs`))),goToDate:q(()=>Promise.resolve().then(()=>require(`../WidgetGoToDate-hNVxz-Zb.cjs`))),hotkeySheet:q(()=>Promise.resolve().then(()=>require(`../WidgetHotkeySheet-y5LWKSG6.cjs`))),indicatorPicker:q(()=>Promise.resolve().then(()=>require(`../WidgetIndicatorPicker-DKxoB4Un.cjs`))),commandPalette:q(()=>Promise.resolve().then(()=>require(`../WidgetCommandPalette-Cx-UQ9ft.cjs`))),symbolSearch:q(()=>Promise.resolve().then(()=>require(`../WidgetSymbolSearch-C_yw9mLo.cjs`)))};async function Ua(){await Promise.all(Object.values(J).map(e=>e.load().catch(()=>null)))}var Wa=/^(\d{4})-(\d{2})-(\d{2})$/,Ga=/^(\d{2}):(\d{2})$/;function Ka(e,t,n){let r=Wa.exec(e),i=t?Ga.exec(t):[``,`00`,`00`];if(!r||!i)return null;let[a,o,s,c,l]=[+r[1],+r[2],+r[3],+i[1],+i[2]];if(o<1||o>12||s<1||s>31||c>23||l>59)return null;let d=Date.UTC(a,o-1,s,c,l);return new Date(d).getUTCDate()===s?(0,u.wallToUtc)(d,n):null}function Y(e,t){let n=e=>String(e).padStart(2,`0`),r=(0,u.timeParts)(e,t);return{date:`${r.year}-${n(r.month)}-${n(r.day)}`,time:`${n(r.hours)}:${n(r.minutes)}`}}var X={min:233,default:262,max:377},qa=.382,Ja=e=>!e.hidden&&getComputedStyle(e).display!==`none`,Ya=class{element;panel;rail;handle;pages=new Map;open_=null;width;scale=1;drag=null;observer=null;onMove=e=>{!this.drag||!this.samePointer(e)||this.setWidth(this.drag.width+(this.drag.x-e.clientX)*this.drag.dir)};onUp=e=>{!this.drag||!this.samePointer(e)||(this.drag=null,this.stopDrag(),this.options.saveWidth?.(this.width))};constructor(e,t){this.options=t;let n=document.createElement(`div`);n.className=`tcw-dock`;let i=document.createElement(`div`);i.className=`tcw-dock-panel`,i.hidden=!0,i.addEventListener(`keydown`,e=>this.onPanelKey(e));let a=document.createElement(`div`);a.className=`tcw-dock-resize`,a.setAttribute(`role`,`separator`),a.setAttribute(`aria-orientation`,`vertical`),a.setAttribute(`aria-label`,t.labels.resize),a.setAttribute(`aria-valuemin`,String(X.min)),a.tabIndex=0,a.addEventListener(`pointerdown`,e=>this.startDrag(e)),a.addEventListener(`keydown`,e=>this.onHandleKey(e)),i.appendChild(a);let o=document.createElement(`div`);o.className=`tcw-dock-rail`,o.setAttribute(`role`,`toolbar`),o.setAttribute(`aria-orientation`,`vertical`),o.setAttribute(`aria-label`,t.labels.rail),r.o(o,`dock`),o.addEventListener(`keydown`,e=>this.onRailKey(e)),n.append(i,o),e.appendChild(n),this.element=n,this.panel=i,this.rail=o,this.handle=a,this.width=Math.min(X.max,Math.max(X.min,t.savedWidth?.()??X.default)),this.applyWidth(),t.room&&typeof ResizeObserver<`u`&&(this.observer=new ResizeObserver(()=>this.fit()),this.observer.observe(e))}addPage(e){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-dock-btn`,t.dataset.page=e.id,t.title=e.label,t.setAttribute(`aria-label`,e.label),t.setAttribute(`aria-pressed`,`false`),t.tabIndex=-1,t.innerHTML=i.i(e.icon,18),e.parts?.length&&r.o(t,...e.parts),t.addEventListener(`click`,()=>{this.toggle(e.id)}),t.addEventListener(`focus`,()=>this.rove(t)),this.rail.appendChild(t),e.element.hidden=!0,e.element.classList.add(`tcw-dock-page`),this.panel.appendChild(e.element),this.pages.set(e.id,{page:e,button:t}),this.syncRail()}open(e){let t=this.pages.get(e);!t||this.open_===e||(this.hideCurrent(),this.open_=e,this.panel.hidden=!1,t.page.element.hidden=!1,t.button.setAttribute(`aria-pressed`,`true`),this.fit(),t.page.onShow?.(),this.options.onChange?.(e))}close(){let e=this.open_;if(e===null)return;let t=this.panel.contains(document.activeElement);if(this.hideCurrent(),this.panel.hidden=!0,t){let t=this.pages.get(e)?.button;(t&&(this.options.railShown?.()??!0)&&Ja(t)?t:this.options.focusAfterClose?.(e))?.focus()}this.options.onChange?.(null)}toggle(e){this.open_===e?this.close():this.open(e)}closePage(e){this.open_===e&&this.close()}current(){return this.open_}isOpen(e){return this.open_===e}syncRail(){let e=[...this.pages.values()].map(e=>e.button),t=e.filter(Ja),n=e.find(e=>e.tabIndex===0);if(n&&t.includes(n))return;let r=t.find(e=>e.getAttribute(`aria-pressed`)===`true`)??t[0];for(let t of e)t.tabIndex=t===r?0:-1}fit(){this.applyWidth()}destroy(){this.drag=null,this.stopDrag(),this.observer?.disconnect(),this.element.remove()}hideCurrent(){let e=this.open_===null?null:this.pages.get(this.open_);this.open_=null,e&&(e.page.element.hidden=!0,e.button.setAttribute(`aria-pressed`,`false`),e.page.onHide?.())}setScale(e){let t=Number.isFinite(e)&&e>0?e:1;t!==this.scale&&(this.scale=t,this.handle.setAttribute(`aria-valuemin`,String(this.min())),this.applyWidth())}min(){return Math.round(X.min*this.scale)}maxNow(){let e=this.options.room?.()??0,t=Math.round(X.max*this.scale);return e<=0?t:Math.max(this.min(),Math.min(t,Math.floor(e*qa)))}clamp(e,t=this.maxNow()){return Math.round(Math.min(t,Math.max(this.min(),e)))}shownWidth(){return this.clamp(this.width*this.scale)}setWidth(e){this.width=Math.round(this.clamp(e)/this.scale*100)/100,this.applyWidth()}applyWidth(){let e=this.shownWidth();this.element.style.setProperty(`--tcw-dock-w`,`${e}px`),this.handle.setAttribute(`aria-valuemax`,String(this.maxNow())),this.handle.setAttribute(`aria-valuenow`,String(e))}samePointer(e){let t=e.pointerId;return this.drag?.pointer===void 0||t===void 0||t===this.drag.pointer}startDrag(e){if(e.button!==0)return;e.preventDefault();let t=getComputedStyle(this.element).direction===`rtl`||this.element.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`;this.drag={x:e.clientX,width:this.shownWidth(),dir:t?-1:1,pointer:e.pointerId},document.addEventListener(`pointermove`,this.onMove),document.addEventListener(`pointerup`,this.onUp),document.addEventListener(`pointercancel`,this.onUp)}stopDrag(){document.removeEventListener(`pointermove`,this.onMove),document.removeEventListener(`pointerup`,this.onUp),document.removeEventListener(`pointercancel`,this.onUp)}onHandleKey(e){let[t,n]=this.element.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?[`ArrowRight`,`ArrowLeft`]:[`ArrowLeft`,`ArrowRight`],r=this.shownWidth(),i=e.key===t?r+13:e.key===n?r-13:e.key===`Home`?this.min():e.key===`End`?this.maxNow():null;i!==null&&(e.preventDefault(),this.setWidth(i),this.options.saveWidth?.(this.width))}onPanelKey(e){e.key!==`Escape`||e.defaultPrevented||!this.element.closest(`[data-tcw-narrow]`)||(e.preventDefault(),e.stopPropagation(),this.close())}rove(e){for(let{button:t}of this.pages.values())t.tabIndex=t===e?0:-1}onRailKey(e){let t=[...this.pages.values()].map(e=>e.button).filter(Ja),n=t.indexOf(e.target);if(n<0)return;let r=e.key===`ArrowDown`?(n+1)%t.length:e.key===`ArrowUp`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),t[r].focus())}},Xa=[`percent`,`scale`,`pane`,`spread`,`ratio`,`correlation`,`correlationLog`],Za={percent:`compare.percent`,scale:`compare.ownScale`,pane:`compare.ownPane`,spread:`compare.way.spread`,ratio:`compare.way.ratio`,correlation:`compare.way.correlation`,correlationLog:`compare.way.correlationLog`};function Qa(e){return Xa.includes(e)}function $a(e){return Xa.map(t=>({id:t,label:e(Za[t])}))}function eo(e,t){let n=e.findIndex(e=>e.time>=t);return n<0?e.length:n}function to(e,t){let n=e[0]?.time??1/0,r=t.filter(e=>e.time<n);return r.length>0?[...r,...e]:null}function no(e,t){switch(e.id){case`compareSymbol`:return t?`pane`:`scale`;case`compareSymbolPane`:return`pane`;case`spread`:return e.params.mode===`ratio`?`ratio`:`spread`;case`correlation`:return`correlation`;case`correlationlog`:return`correlationLog`;default:return null}}function ro(e,t,n,r){let i=e.map(e=>({id:e.id,symbol:e.symbol,way:r(Za.percent),color:e.color}));for(let e of t){let t=e.params.symbol,a=no(e,n.has(e.instanceId));!a||typeof t!=`string`||!t||i.push({id:e.instanceId,symbol:t,way:r(Za[a])})}return i}var Z=8,io=4,ao=3,oo=`[title]:not([title=""]), [data-tip]:not([data-tip=""])`,so=class{el;target=null;source=null;pressed=null;showTimer=null;watchFrame=0;warmUntil=0;observer;constructor(e){this.root=e,this.el=document.createElement(`div`),this.el.className=`tcw-tooltip`,this.el.setAttribute(`aria-hidden`,`true`),e.appendChild(this.el),e.addEventListener(`pointerover`,this.onOver),e.addEventListener(`pointerout`,this.onOut),e.addEventListener(`pointerdown`,this.onPress,!0),e.addEventListener(`keydown`,this.onPress,!0),e.addEventListener(`focusin`,this.onFocus),e.addEventListener(`focusout`,this.onBlur),e.addEventListener(`wheel`,this.hide,{passive:!0}),this.observer=new MutationObserver(()=>{this.pressed?.hasAttribute(`title`)&&co(this.pressed);let e=this.target;!e||this.source!==`pointer`||!e.hasAttribute(`title`)||(co(e),this.isVisible()&&this.show(e))}),this.observer.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`title`]})}destroy(){this.hide(),this.pressed&&Q(this.pressed),this.observer.disconnect(),this.root.removeEventListener(`pointerover`,this.onOver),this.root.removeEventListener(`pointerout`,this.onOut),this.root.removeEventListener(`pointerdown`,this.onPress,!0),this.root.removeEventListener(`keydown`,this.onPress,!0),this.root.removeEventListener(`focusin`,this.onFocus),this.root.removeEventListener(`focusout`,this.onBlur),this.root.removeEventListener(`wheel`,this.hide),this.el.remove()}onOver=e=>{if(e.pointerType===`touch`)return;let t=this.tipTarget(e.target);!t||t===this.pressed||t===this.target&&this.source===`pointer`||(co(t),this.schedule(t,`pointer`,Date.now()<this.warmUntil||this.isVisible()))};onOut=e=>{let t=e.relatedTarget,n=e=>!!e&&!!t&&e.contains(t);this.pressed&&!n(this.pressed)&&(Q(this.pressed),this.pressed=null),this.source===`pointer`&&!n(this.target)&&this.hide()};onPress=()=>{let e=this.target,t=this.source===`pointer`;this.warmUntil=0,this.clearTimer(),cancelAnimationFrame(this.watchFrame),this.el.classList.remove(`tcw-tooltip--visible`),this.target=null,this.source=null,this.pressed&&this.pressed!==e&&Q(this.pressed),this.pressed=t?e:null};onFocus=e=>{let t=this.tipTarget(e.target);!t||!fo(t)||t===this.pressed||this.schedule(t,`focus`,!0)};onBlur=e=>{if(this.source!==`focus`)return;let t=e.relatedTarget;this.target&&t&&this.target.contains(t)||this.hide()};hide=()=>{this.clearTimer(),cancelAnimationFrame(this.watchFrame),this.isVisible()&&(this.warmUntil=Date.now()+500),this.el.classList.remove(`tcw-tooltip--visible`),this.target&&this.source===`pointer`&&Q(this.target),this.target=null,this.source=null};tipTarget(e){if(!(e instanceof Element))return null;let t=e.closest(oo);return t&&t!==this.el&&this.root.contains(t)?t:null}schedule(e,t,n){let r=this.target;if(this.clearTimer(),cancelAnimationFrame(this.watchFrame),r&&r!==e&&this.source===`pointer`&&Q(r),this.target=e,this.source=t,n){this.show(e);return}this.el.classList.remove(`tcw-tooltip--visible`),this.showTimer=setTimeout(()=>{this.showTimer=null,this.target===e&&this.show(e)},300)}show(e){if(!uo(e)){this.hide();return}this.el.textContent=lo(e),this.place(e),this.el.classList.add(`tcw-tooltip--visible`),this.watch(e)}watch(e){cancelAnimationFrame(this.watchFrame),this.watchFrame=requestAnimationFrame(()=>{this.target===e&&(uo(e)?this.watch(e):this.hide())})}place(e){let t=this.root.getBoundingClientRect(),n=e.getBoundingClientRect(),r=this.el.offsetWidth,i=this.el.offsetHeight,a=n.left-t.left,o=n.top-t.top,s=po(e);s===`bottom`&&o+n.height+Z+i>t.height?s=`top`:s===`top`&&o-Z-i<0?s=`bottom`:s===`right`&&a+n.width+Z+r>t.width&&(s=`left`);let c,l;s===`top`||s===`bottom`?(c=a+n.width/2-r/2,l=s===`bottom`?o+n.height+Z:o-Z-i):(c=s===`right`?a+n.width+Z:a-Z-r,l=o+n.height/2-i/2),c=Math.max(io,Math.min(t.width-r-io,c)),l=Math.max(io,Math.min(t.height-i-io,l)),this.el.style.left=`${Math.round(c)}px`,this.el.style.top=`${Math.round(l)}px`;let u={top:[0,ao],bottom:[0,-ao],left:[ao,0],right:[-ao,0]}[s];this.el.style.setProperty(`--tcw-tip-dx`,`${u[0]}px`),this.el.style.setProperty(`--tcw-tip-dy`,`${u[1]}px`),this.el.dataset.side=s}isVisible(){return this.el.classList.contains(`tcw-tooltip--visible`)}clearTimer(){this.showTimer!==null&&(clearTimeout(this.showTimer),this.showTimer=null)}};function co(e){let t=e.getAttribute(`title`);t!==null&&(e.dataset.tip=t,e.removeAttribute(`title`))}function Q(e){e.dataset.tip!==void 0&&!e.hasAttribute(`title`)&&(e.setAttribute(`title`,e.dataset.tip),delete e.dataset.tip)}function lo(e){return e.dataset.tip??e.getAttribute(`title`)??``}function uo(e){return e.isConnected&&e.getClientRects().length>0&&!e.disabled}function fo(e){try{return e.matches(`:focus-visible`)}catch{return!1}}function po(e){return e.dataset.tipSide||(e.closest(`.tcw-sidebar`)?`right`:e.closest(`.tcw-statusbar, .tcw-replay-bar`)?`top`:`bottom`)}var mo=2,ho=1.5,go=`tcw-ind-legend-values--no-room`,_o=0,vo=class{stack;toggle;rows=new Map;panes=new Map;collapsed=!1;toggleKey=``;stackKey=``;valuesObserver;stackObserver;constructor(e,t,n){this.host=e,this.callbacks=t,this.labels=n,this.stack=document.createElement(`div`),this.stack.className=`tcw-ind-legend`,r.o(this.stack,`indicatorLegend`),this.toggle=document.createElement(`button`),this.toggle.type=`button`,this.toggle.className=`tcw-ind-legend-toggle`,this.toggle.addEventListener(`click`,()=>{this.setCollapsed(!this.collapsed),this.renderToggle(this.overlayCount())}),this.stack.appendChild(this.toggle),e.appendChild(this.stack),this.stackObserver=typeof ResizeObserver>`u`||!t.onStackResize?null:new ResizeObserver(()=>this.reportStackSize()),this.stackObserver?.observe(this.stack),this.valuesObserver=typeof ResizeObserver>`u`?null:new ResizeObserver(e=>{for(let t of e)yo(t.target,t.contentRect.width)})}update(e,t,n=[]){this.updatePanes(n);let r=`${Math.round(t.left)},${Math.round(t.top)}`;r!==this.stackKey&&(this.stackKey=r,this.stack.style.left=`${Math.round(t.left)}px`,this.stack.style.top=`${Math.round(t.top)}px`);let i=new Set(e.map(e=>e.instanceId));for(let[e,t]of this.rows)i.has(e)||(this.valuesObserver?.unobserve(t.values),t.el.remove(),this.rows.delete(e));let a=!1,o=null;for(let t of e){let e=this.rows.get(t.instanceId)??this.createRow(t.instanceId,t.kind);if(this.fill(e,t),t.pane)e.el.parentElement!==this.host&&this.host.appendChild(e.el);else{let t=o?o.nextElementSibling:this.stack.firstElementChild;e.el.parentElement!==this.stack&&(a=!0),e.el!==t&&this.stack.insertBefore(e.el,t),o=e.el}this.place(e,t.pane)}a&&this.collapsed&&this.setCollapsed(!1),this.renderToggle(e.filter(e=>!e.pane).length)}destroy(){this.valuesObserver?.disconnect(),this.stackObserver?.disconnect();for(let e of this.rows.values())e.el.remove();this.rows.clear();for(let e of this.panes.values())e.el.remove();this.panes.clear(),this.stack.remove()}reportStackSize(){let e=this.stack.offsetWidth,t=this.stack.offsetHeight;this.callbacks.onStackResize?.(e>0&&t>0?{width:e,height:t}:null)}updatePanes(e){if(!this.callbacks.onPaneAction)return;let t=new Set;for(let n of e){t.add(n.instanceId);let e=this.panes.get(n.instanceId)??this.createPane(n.instanceId),r=`${Math.round(n.x)},${Math.round(n.y)}|${n.label}|${n.collapsed}|${n.maximized}|${n.canMoveUp}|${n.canMoveDown}`;if(r===e.key)continue;e.key=r,e.el.style.left=`${Math.round(n.x)}px`,e.el.style.top=`${Math.round(n.y)}px`;let a=this.labels,o=(t,r,a,o)=>{let s=e.buttons.get(t);!r&&document.activeElement===s&&e.buttons.get(`max`).focus(),s.hidden=!r,s.innerHTML=i.i(a,12),$(s,o??t,n.label)};o(`up`,n.canMoveUp&&!n.maximized,`arrowUp`,a.paneUp),o(`down`,n.canMoveDown&&!n.maximized,`arrowDown`,a.paneDown),o(`fold`,!n.maximized,n.collapsed?`chevronDown`:`chevronUp`,n.collapsed?a.paneExpand:a.paneCollapse),o(`max`,!0,n.maximized?`minimize`:`maximize`,n.maximized?a.paneRestore:a.paneMaximize),e.el.dataset.collapsed=String(n.collapsed),e.el.dataset.maximized=String(n.maximized)}for(let[e,n]of this.panes)t.has(e)||(n.el.remove(),this.panes.delete(e))}createPane(e){let t=document.createElement(`div`);t.className=`tcw-pane-controls`,r.o(t,`indicatorLegend`),t.dataset.instance=e;let n=new Map,i=e=>e===`up`||e===`down`?e:e===`fold`?t.dataset.collapsed===`true`?`expand`:`collapse`:t.dataset.maximized===`true`?`restore`:`maximize`,a={up:`pane.move`,down:`pane.move`,fold:`pane.collapse`,max:`pane.maximize`};for(let o of[`up`,`down`,`fold`,`max`]){let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-pane-btn`,s.dataset.act=o,r.o(s,a[o]),s.addEventListener(`click`,()=>this.callbacks.onPaneAction?.(e,i(o))),n.set(o,s),t.appendChild(s)}this.host.appendChild(t);let o={el:t,buttons:n,key:``};return this.panes.set(e,o),o}createRow(e,t){let n=t===`compare`,a=document.createElement(`div`);a.className=n?`tcw-ind-legend-row tcw-ind-legend-row--compare`:`tcw-ind-legend-row`,r.o(a,`indicatorLegend`),a.dataset.instance=e;let o=document.createElement(n?`span`:`button`);o.className=`tcw-ind-legend-name`,o instanceof HTMLButtonElement&&(o.type=`button`,o.addEventListener(`click`,()=>this.callbacks.onSettings(e)));let s=document.createElement(`span`);s.className=`tcw-ind-legend-values`,r.o(s,`indicatorLegend.values`),this.valuesObserver?.observe(s);let c=document.createElement(`span`);c.className=`tcw-ind-legend-actions`;let l=(e,t,n,...a)=>{let o=document.createElement(`button`);return o.type=`button`,o.className=`tcw-ind-legend-act`,o.dataset.act=e,r.o(o,...a),o.innerHTML=i.i(t,13),o.addEventListener(`click`,n),c.appendChild(o),o},u=l(`visible`,`eye`,()=>{this.callbacks.onToggleVisible(e,!g.visible,t)},`indicatorLegend.visibility`),d=n?null:l(`settings`,`settings`,()=>this.callbacks.onSettings(e),`indicatorSettings`,`indicatorLegend.settings`),f=this.callbacks.onMore&&!n?l(`more`,`more`,()=>this.callbacks.onMore?.(e,f),`indicatorLegend.more`):null,p=l(`remove`,`x`,()=>this.callbacks.onRemove(e,t),`indicatorLegend.remove`),m=document.createElement(`span`);m.className=`tcw-visually-hidden`,m.id=`tcw-ind-note-${++_o}`;let h=n?document.createElement(`span`):null;h&&(h.className=`tcw-ind-legend-swatch`,h.setAttribute(`aria-hidden`,`true`),a.append(h)),a.append(o,s,c,m);let g={el:a,name:o,swatch:h,values:s,eye:u,settings:d,more:f,remove:p,note:m,visible:!0,valuesKey:``,state:``,placeKey:``};return this.rows.set(e,g),g}fill(e,t){let n=this.offNote(t),r=`${t.label}|${t.visible}|${n}|${t.swatch??``}`;r!==e.state&&(e.state=r,e.swatch&&(e.swatch.style.backgroundColor=t.swatch??``),e.visible=t.visible,e.name.textContent=t.label,e.settings&&(e.name.title=this.labels.settings),e.el.classList.toggle(`tcw-ind-legend-row--hidden`,!t.visible||n!==null),n?e.el.title=n:e.el.removeAttribute(`title`),this.describe(e,n),e.eye.innerHTML=i.i(t.visible?`eye`:`eyeOff`,13),$(e.eye,t.visible?this.labels.hide:this.labels.show,t.label),e.settings&&$(e.settings,this.labels.settings,t.label),e.more&&($(e.more,this.labels.more??`More`,t.label),e.more.setAttribute(`aria-haspopup`,`menu`)),$(e.remove,this.labels.remove,t.label));let a=t.values.map(e=>`${e.text}${e.color??``}`).join(``);a!==e.valuesKey&&(e.valuesKey=a,e.values.replaceChildren(...t.values.map(e=>{let t=document.createElement(`span`);return t.textContent=e.text,e.color&&(t.style.color=e.color),t})))}describe(e,t){e.note.textContent=t??``;let n=[e.name,e.eye,e.settings,e.more,e.remove].filter(e=>e instanceof HTMLButtonElement);for(let r of n)t?r.setAttribute(`aria-describedby`,e.note.id):r.removeAttribute(`aria-describedby`)}offNote(e){return e.offInterval?this.labels.offInterval??``:e.offChartType?this.labels.offChartType??``:null}place(e,t){let n=t?`${Math.round(t.x)},${Math.round(t.y)},${Math.round(t.width)}`:``;n!==e.placeKey&&(e.placeKey=n,e.el.classList.toggle(`tcw-ind-legend-row--pane`,t!==null),e.el.style.left=t?`${Math.round(t.x)}px`:``,e.el.style.top=t?`${Math.round(t.y)}px`:``,e.el.style.maxWidth=t?`${Math.max(0,Math.round(t.width))}px`:``)}setCollapsed(e){this.collapsed=e,this.stack.classList.toggle(`tcw-ind-legend--collapsed`,e)}overlayCount(){return this.stack.querySelectorAll(`:scope > .tcw-ind-legend-row`).length}renderToggle(e){let t=e>=mo;!t&&this.collapsed&&this.setCollapsed(!1);let n=`${t}|${this.collapsed}|${e}`;if(n===this.toggleKey||(this.toggleKey=n,this.toggle.hidden=!t,!t))return;let r=this.collapsed?this.labels.expand:this.labels.collapse;$(this.toggle,r,this.collapsed?`(${e})`:void 0),this.toggle.setAttribute(`aria-expanded`,String(!this.collapsed));let a=i.i(this.collapsed?`chevronDown`:`chevronUp`,12);this.toggle.innerHTML=this.collapsed?`${a}<span>${e}</span>`:a}};function yo(e,t){let n=(parseFloat(getComputedStyle(e).fontSize)||0)*ho;e.classList.toggle(go,t<n)}function $(e,t,n){e.title=t,e.setAttribute(`aria-label`,n?`${t} ${n}`:t)}function bo(e,t){return!e||e.length===0?null:e[t===null?e.length-1:Math.min(Math.max(t,0),e.length-1)]??null}function xo(e,t,n,r){if(!t)return[];let i=e.plots;if(!i){let e=[];for(let n in t){let r=t[n];typeof r==`number`&&Number.isFinite(r)&&e.push(r)}let r=e.length===1?n[0]??null:null;return e.map(e=>({value:e,color:r}))}let a={colors:[...n],lineWidths:[],opacity:1},o=[];for(let e of i){if(!(0,d.plotShown)(e,{plots:r}))continue;let i=t[e.key];typeof i!=`number`||!Number.isFinite(i)||o.push({value:i,color:n.length?(0,d.plotColor)(e,a,t):null})}return o}var So=new Map;function Co(e){let t=So.get(e);return t||(t=new Intl.NumberFormat(e,{notation:`compact`,maximumFractionDigits:2}),So.set(e,t)),t}function wo(e,t=`en-US`){return Math.abs(e)>=1e6?Co(t).format(e):(0,u.formatPrice)(e,(0,d.indicatorValuePrecision)(e),t)}var To=class{el;labelEl;callbacks;visible=!1;constructor(e,t,n=s.t){this.t=n,this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-bracket-bar`,this.el.setAttribute(`role`,`group`),this.el.hidden=!0,this.labelEl=document.createElement(`span`),this.labelEl.className=`tcw-bracket-label`,this.el.appendChild(this.labelEl);let r=document.createElement(`span`);r.className=`tcw-bracket-hint`,r.textContent=this.t(`bracket.hint`),this.el.appendChild(r);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-bracket-cancel`,o.innerHTML=`${i.i(`x`,14)}<span>${a.u(this.t(`common.cancel`))}</span>`,o.addEventListener(`click`,()=>this.callbacks.onCancel());let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-bracket-confirm`,c.innerHTML=`${i.i(`check`,14)}<span>${a.u(this.t(`bracket.place`))}</span>`,c.addEventListener(`click`,()=>this.callbacks.onConfirm()),this.el.appendChild(o),this.el.appendChild(c),e.appendChild(this.el)}show(e){this.visible=!0;let t=e===`buy`?this.t(`toolbar.longBracket`):this.t(`toolbar.shortBracket`);this.labelEl.textContent=t,this.el.setAttribute(`aria-label`,t),this.el.dataset.side=e,this.el.dir=this.el.closest(`.tcw-root`)?.dir||`auto`,this.el.hidden=!1}hide(){this.visible=!1,this.el.hidden=!0}isVisible(){return this.visible}destroy(){this.el.remove()}},Eo=class{options;audioCtx=null;audioEl=null;permissionAsked=!1;constructor(e={}){if(this.options=e,typeof e.sound==`string`)try{this.audioEl=new Audio(e.sound),this.audioEl.preload=`auto`}catch{this.audioEl=null}e.desktop&&this.ensurePermission()}setOptions(e){this.options={...this.options,...e}}notify(e){this.options.sound&&this.playSound(),this.options.desktop&&this.showDesktop(e)}playSound(){if(this.audioEl){this.audioEl.currentTime=0,this.audioEl.play().catch(()=>{});return}this.beep()}beep(){try{let e=window.AudioContext??window.webkitAudioContext;if(!e)return;this.audioCtx||=new e;let t=this.audioCtx,n=t.currentTime,r=t.createGain();r.gain.setValueAtTime(1e-4,n),r.gain.exponentialRampToValueAtTime(.2,n+.01),r.gain.exponentialRampToValueAtTime(1e-4,n+.35),r.connect(t.destination);let i=t.createOscillator();i.type=`sine`,i.frequency.setValueAtTime(880,n),i.frequency.setValueAtTime(1320,n+.16),i.connect(r),i.start(n),i.stop(n+.36)}catch{}}ensurePermission(){this.permissionAsked||(this.permissionAsked=!0,!(typeof Notification>`u`)&&Notification.permission===`default`&&Notification.requestPermission().catch(()=>{}))}showDesktop(e){if(!(typeof Notification>`u`)){if(Notification.permission!==`granted`){this.ensurePermission();return}try{new Notification(this.options.title??`Price alert`,{body:e})}catch{}}}destroy(){try{this.audioCtx?.close()}catch{}this.audioCtx=null,this.audioEl=null}};function Do(e,t=12){let n=[...e.asks].sort((e,t)=>e.price-t.price).slice(0,t),r=[...e.bids].sort((e,t)=>t.price-e.price).slice(0,t),i=n.length>0?n[0].price:null,a=r.length>0?r[0].price:null,o=i!==null&&a!==null?(i+a)/2:null,s=new Map,c=e=>{let t=s.get(e);return t||(t={price:e,bidVolume:0,askVolume:0},s.set(e,t)),t};for(let e of n)c(e.price).askVolume+=e.volume;for(let e of r)c(e.price).bidVolume+=e.volume;let l=[...s.values()].sort((e,t)=>t.price-e.price),u=0;for(let e of l)u=Math.max(u,e.bidVolume,e.askVolume);return{rows:l,maxVolume:u,mid:o,spread:i!==null&&a!==null?i-a:null,bestBid:a}}var Oo=1e-9,ko=class{el;colsEl;bodyEl;callbacks;open=!1;levels;model=null;orders=[];drawn=[];spreadEl;placed=!1;constructor(e,t,n=12,a=s.t){this.t=a,this.callbacks=t,this.levels=n,this.el=document.createElement(`section`),this.el.className=`tcw-ladder`,this.el.setAttribute(`aria-label`,this.t(`ladder.title`)),r.o(this.el,`depthLadder`),this.el.hidden=!0;let o=document.createElement(`div`);o.className=`tcw-ladder-header`;let c=document.createElement(`h3`);c.className=`tcw-ladder-title`,c.textContent=this.t(`ladder.title`);let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-ladder-close`,l.setAttribute(`aria-label`,this.t(`common.close`)),l.innerHTML=i.i(`x`,14),l.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),o.append(c,l),this.colsEl=document.createElement(`div`),this.colsEl.className=`tcw-ladder-cols`;for(let e of[`ladder.bid`,`ladder.price`,`ladder.ask`]){let t=document.createElement(`span`);t.textContent=this.t(e),this.colsEl.appendChild(t)}this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-ladder-body`,this.spreadEl=document.createElement(`div`),this.spreadEl.className=`tcw-ladder-spread`,this.el.append(o,this.colsEl,this.bodyEl),e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.placed=!1,this.el.hidden=!1,this.render(),this.callbacks.onToggle?.(!0)}close(){this.open&&(this.open=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}setData(e){this.model=e?Do(e,this.levels):null,this.render()}setOrders(e){this.orders=e,this.render()}destroy(){this.el.remove()}render(){if(!this.open)return;let e=this.model;if(!e||e.rows.length===0){let e=document.createElement(`div`);e.className=`tcw-ladder-empty`,e.textContent=this.t(`ladder.empty`),this.bodyEl.replaceChildren(e),this.drawn=[];return}let t=Ao(e.rows);e.rows.length===this.drawn.length&&e.rows.every((e,t)=>e.price===this.drawn[t].price)||(this.drawn=e.rows.map(e=>this.newRow(e.price)),this.bodyEl.replaceChildren(...this.drawn.map(e=>e.row)));let n=e.maxVolume>0?100/e.maxVolume:0;e.rows.forEach((e,r)=>this.fillRow(this.drawn[r],e,n,this.nearness(e.price,t))),this.putSpread(e,t),this.placeSpread()}putSpread(e,t){let{spread:n,bestBid:r}=e,i=n===null||r===null?-1:e.rows.findIndex(e=>e.price<r+t);if(n===null||i<0){this.spreadEl.remove();return}this.spreadEl.textContent=s.r(this.t(`ladder.spread`),{spread:this.callbacks.formatPrice(n)});let a=this.drawn[i].row;this.spreadEl.nextElementSibling!==a&&this.bodyEl.insertBefore(this.spreadEl,a)}nearness(e,t){let n=this.callbacks.priceStep?.(e)??0;return n>0?Math.min(n/2,t):t}newRow(e){let t=document.createElement(`div`);t.className=`tcw-ladder-row`;let n=document.createElement(`div`);n.className=`tcw-ladder-price`;let r=document.createElement(`span`);r.className=`tcw-ladder-figure`,n.appendChild(r);let i=this.newCell(`sell`,e),a=this.newCell(`buy`,e);return t.append(i,n,a),{price:e,row:t,bid:i,ask:a,cell:n,figure:r}}newCell(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-ladder-cell ${e===`sell`?`tcw-ladder-bid`:`tcw-ladder-ask`}`,n.addEventListener(`click`,()=>this.callbacks.onTrade(e,t)),n}fillRow(e,t,n,r){e.cell.className=`tcw-ladder-price ${t.askVolume>0?`tcw-ask`:`tcw-bid`}`,e.figure.textContent=this.callbacks.formatPrice(t.price),this.fillCell(e.bid,`sell`,t.bidVolume,t.price,n),this.fillCell(e.ask,`buy`,t.askVolume,t.price,n);for(let t of e.cell.querySelectorAll(`.tcw-ladder-own`))t.remove();for(let n of[`buy`,`sell`]){let i=this.orders.filter(e=>e.side===n&&Math.abs(e.price-t.price)<r).reduce((e,t)=>e+t.quantity,0);if(i<=0)continue;let a=document.createElement(`span`);a.className=`tcw-ladder-own`,a.dataset.side=n,a.textContent=String(i);let o=`${this.t(n===`buy`?`ticket.buy`:`ticket.sell`)} ${i}`;a.setAttribute(`aria-label`,o),a.title=o,n===`buy`?e.cell.insertBefore(a,e.figure):e.cell.appendChild(a)}}fillCell(e,t,n,r,i){if(!(n>0)){e.disabled=!0,e.textContent=``,e.removeAttribute(`aria-label`),e.title=``,e.style.removeProperty(`--w`);return}e.disabled=!1;let a=jo(n);e.textContent=a,e.style.setProperty(`--w`,`${(n*i).toFixed(1)}%`);let o=s.r(this.t(t===`sell`?`ladder.sellAt`:`ladder.buyAt`),{price:this.callbacks.formatPrice(r)});e.setAttribute(`aria-label`,`${a}, ${o}`),e.title=o}placeSpread(){let e=this.el;if(this.placed||!this.spreadEl.isConnected||e.clientHeight===0)return;let t=e.getBoundingClientRect().top,n=this.colsEl.getBoundingClientRect().bottom-t,r=this.spreadEl.getBoundingClientRect().top-t;e.scrollTop+=r-n-(e.clientHeight-n-this.spreadEl.offsetHeight)/2,this.placed=!0}};function Ao(e){let t=1/0;for(let n=1;n<e.length;n++)t=Math.min(t,Math.abs(e[n-1].price-e[n].price));return Number.isFinite(t)&&t>0?t/2:Oo}function jo(e){return e>=1e3?`${Number((e/1e3).toFixed(1))}k`:String(Number(e>=1?e.toFixed(2):e.toPrecision(2)))}var Mo=class{el;bodyEl;callbacks;open=!1;constructor(e,t,n=s.t){this.t=n,this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-datawin`,r.o(this.el,`dataWindow`),this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-datawin-header`;let o=document.createElement(`span`);o.textContent=this.t(`dataWindow.title`);let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-datawin-close`,c.setAttribute(`aria-label`,this.t(`common.close`)),c.innerHTML=i.i(`x`,14),c.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),a.appendChild(o),a.appendChild(c),this.el.appendChild(a),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-datawin-body`,this.el.appendChild(this.bodyEl),e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}render(e){if(!this.open)return;if(this.bodyEl.replaceChildren(),!e.ohlc){let e=document.createElement(`div`);e.className=`tcw-datawin-empty`,e.textContent=this.t(te()?`dataWindow.touch`:`dataWindow.hover`),this.bodyEl.appendChild(e);return}let t=this.callbacks.formatPrice,n=e.ohlc;this.bodyEl.appendChild(this.row(this.t(`dataWindow.open`),t(n.open))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.high`),t(n.high))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.low`),t(n.low))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.close`),t(n.close)));let r=e.change>0?`up`:e.change<0?`down`:``,i=e.change>0?`+`:``,a=this.callbacks.formatPercent?.(e.changePct)??e.changePct.toFixed(2),o=e.changeText??t(e.change);this.bodyEl.appendChild(this.row(this.t(`dataWindow.change`),`${i}${o} (${i}${a}%)`,r)),this.bodyEl.appendChild(this.row(this.t(`dataWindow.volume`),(this.callbacks.formatVolume??Po)(n.volume)));for(let t of e.indicators){let e=document.createElement(`div`);e.className=`tcw-datawin-sub`,e.textContent=t.name,this.bodyEl.appendChild(e);for(let e of t.values)this.bodyEl.appendChild(this.row(e.key,e.text??No(e.value)))}}row(e,t,n=``){let r=document.createElement(`div`);r.className=`tcw-datawin-row`;let i=document.createElement(`span`);i.className=`tcw-datawin-label`,i.textContent=e;let a=document.createElement(`span`);return a.className=`tcw-datawin-value${n?` tcw-${n}`:``}`,a.textContent=t,r.appendChild(i),r.appendChild(a),r}};function No(e){if(!Number.isFinite(e))return`—`;let t=Math.abs(e);return t>=1e3?e.toFixed(2):t>=1?e.toFixed(4):e.toFixed((0,u.smallValueDecimals)(e))}function Po(e){return e>=1e9?(e/1e9).toFixed(2)+`B`:e>=1e6?(e/1e6).toFixed(2)+`M`:e>=1e3?(e/1e3).toFixed(2)+`K`:e.toFixed(0)}function Fo(e,t,n,r){let i=n?.delayMinutes;return e!==`connected`||i===void 0||!Number.isFinite(i)||i<=0?{message:t,delayed:!1}:{message:s.r(r(`status.delayed`),{minutes:Math.ceil(i)}),delayed:!0}}var Io=[[34,16,28,26,!1],[30,14,24,26,!0],[26,18,20,30,!0],[30,10,24,22,!1],[20,16,14,28,!0],[14,18,8,30,!0],[18,10,12,20,!1],[8,18,2,30,!0]],Lo=class{el;label;showTimer=null;phase=`loading`;constructor(e,t){this.loadingText=t,this.el=document.createElement(`div`),this.el.className=`tcw-loading-overlay`,this.el.setAttribute(`role`,`status`),this.el.setAttribute(`aria-live`,`polite`);let n=document.createElement(`div`);n.className=`tcw-loading-candles`,n.setAttribute(`aria-hidden`,`true`),Io.forEach(([e,t,r,i,a],o)=>{let s=document.createElement(`span`);s.className=a?`tcw-loading-candle tcw-loading-candle--up`:`tcw-loading-candle`,s.style.setProperty(`--tcw-body-top`,`${e}px`),s.style.setProperty(`--tcw-body-h`,`${t}px`),s.style.setProperty(`--tcw-wick-top`,`${r}px`),s.style.setProperty(`--tcw-wick-h`,`${i}px`),s.style.setProperty(`--tcw-delay`,`${o*110}ms`),n.appendChild(s)}),this.el.appendChild(n),this.label=document.createElement(`div`),this.label.className=`tcw-loading-label`,this.label.textContent=t,this.el.appendChild(this.label),e.appendChild(this.el)}begin(e,t=!1){if(this.phase=`loading`,this.clearTimer(),this.label.textContent=this.loadingText,this.el.classList.remove(`tcw-loading-overlay--error`),this.el.classList.toggle(`tcw-loading-overlay--veil`,e),!e||t||this.isShown()){this.el.classList.remove(`tcw-loading-overlay--hidden`);return}this.showTimer=setTimeout(()=>{this.showTimer=null,this.el.classList.remove(`tcw-loading-overlay--hidden`)},200)}end(){this.phase=`idle`,this.clearTimer(),this.el.classList.add(`tcw-loading-overlay--hidden`)}fail(e){this.phase!==`idle`&&(this.phase=`failed`,this.clearTimer(),this.label.textContent=e,this.el.classList.add(`tcw-loading-overlay--error`),this.el.classList.remove(`tcw-loading-overlay--hidden`))}isActive(){return this.phase!==`idle`}hasFailed(){return this.phase===`failed`}isShown(){return!this.el.classList.contains(`tcw-loading-overlay--hidden`)}destroy(){this.clearTimer(),this.el.remove()}clearTimer(){this.showTimer!==null&&(clearTimeout(this.showTimer),this.showTimer=null)}},Ro=4e3,zo=class{el;text;hideTimer=null;constructor(e,t){this.texts=t,this.el=document.createElement(`div`),this.el.className=`tcw-history-pill tcw-history-pill--hidden`,this.el.setAttribute(`aria-hidden`,`true`),this.el.setAttribute(`role`,`status`),this.el.setAttribute(`aria-live`,`polite`);let n=document.createElement(`span`);n.className=`tcw-history-spinner`,n.setAttribute(`aria-hidden`,`true`),this.text=document.createElement(`span`),this.el.append(n,this.text),e.appendChild(this.el)}update(e){this.clearTimer(),e.state===`loading`?this.show(this.texts.loading,!1):e.state===`error`?(this.show(this.texts.failed,!0),this.hideTimer=setTimeout(()=>this.hide(),Ro)):this.hide()}destroy(){this.clearTimer(),this.el.remove()}show(e,t){this.text.textContent=e,this.el.classList.toggle(`tcw-history-pill--error`,t),this.el.classList.remove(`tcw-history-pill--hidden`),this.el.removeAttribute(`aria-hidden`)}hide(){this.hideTimer=null,this.el.classList.add(`tcw-history-pill--hidden`),this.el.setAttribute(`aria-hidden`,`true`),this.text.textContent=``}clearTimer(){this.hideTimer!==null&&clearTimeout(this.hideTimer),this.hideTimer=null}},Bo=`host:`;function Vo(e,t){return[...e,...e.length>0&&t.length>0?[`separator`]:[],...t.map((e,t)=>({id:`${Bo}${t}`,label:e.label,icon:e.icon,danger:e.danger,checked:e.checked}))]}function Ho(e,t){return e.startsWith(Bo)?(t[Number(e.slice(5))]?.onSelect(),!0):!1}var Uo=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent),Wo={ctrl:`ctrl`,control:`ctrl`,cmd:`ctrl`,command:`ctrl`,meta:`ctrl`,mod:`ctrl`,alt:`alt`,option:`alt`,opt:`alt`,shift:`shift`},Go={esc:`escape`,space:` `,spacebar:` `,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`,del:`delete`,return:`enter`,plus:`+`};function Ko(e){let t=e.split(`+`).map(e=>e.trim()),n=t.pop();if(!n)return null;let r={ctrl:!1,alt:!1,shift:!1,display:[]};for(let e of t){let t=Wo[e.toLowerCase()];if(!t)return null;r[t]=!0}let i=n.toLowerCase();if(Wo[i])return null;if(/^[a-z]$/.test(i))r.code=`Key${i.toUpperCase()}`,r.char=i;else if(/^[0-9]$/.test(i))r.code=`Digit${i}`,r.char=i;else if(r.key=Go[i]??i,r.shift&&r.key.length===1)return null;return r.display=[...r.ctrl?[Uo?`⌘`:`Ctrl`]:[],...r.alt?[`Alt`]:[],...r.shift?[`Shift`]:[],r.key===` `?`Space`:n.length===1?n.toUpperCase():n],r}function qo(e,t){if((e.ctrlKey||e.metaKey)!==t.ctrl||e.altKey!==t.alt)return!1;if(t.code!==void 0){if(e.shiftKey!==t.shift)return!1;if(t.alt)return e.code===t.code;let n=e.key.length===1&&/^[a-z0-9]$/i.test(e.key)?e.key.toLowerCase():null;return n===null?e.code===t.code:n===t.char}return t.shift&&!e.shiftKey?!1:e.key.toLowerCase()===t.key}var Jo=new Set(`escape(enter(delete(backspace(arrowleft(arrowright(arrowup(arrowdown(home(end(+(-(=( (,(.(ctrl+z(ctrl+shift+z(ctrl+y(ctrl+c(ctrl+v(ctrl+d(ctrl+g(ctrl+shift+g(ctrl+[(ctrl+]`.split(`(`));function Yo(e){let t=`${e.ctrl?`ctrl+`:``}${e.alt?`alt+`:``}${e.shift?`shift+`:``}${e.char??e.key}`;return Jo.has(t)}function Xo(e){let t=typeof e.composedPath==`function`?e.composedPath()[0]:e.target;return t instanceof HTMLElement?t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName):!1}var Zo=[`#b552c9`,`#1398a8`,`#d4622b`,`#e25592`,`#6f7a8c`,`#3e9a4f`],Qo=class{constructor(e){this.host=e}compares=[];compareWay=`percent`;comparesLoading=new Set;compareScaleHeld=!1;compareFetchSeq=0;compareOlderBusy=!1;compareOlderAgain=!1;compareOlderPassed=!1;async handleAddCompare(){if(this.host.featureState.compare){if(!this.host.adapter){this.host.say(this.host.t(`toast.compareNeedsAdapter`),`error`);return}this.host.withSymbolSearch(()=>this.host.featureState.compare,e=>e.openCompare({symbols:this.host.symbolEntries(),current:this.host.state.symbol,search:this.host.symbolSearchFn(),ways:$a(this.host.t),way:this.compareWay,compared:this.comparedNow(),onAdd:(e,t)=>{Qa(t)&&(this.compareWay=t,this.addCompareSymbol(e,t))},onRemove:e=>this.removeCompared(e)}))}}comparedNow(){let e=new Set(this.host.chart.getIndicatorPanes().flatMap(e=>e.instanceIds));return ro(this.compares,this.host.chart.getActiveIndicators(),e,this.host.t)}refreshCompareDialog(){this.host.symbolSearch?.isComparing()&&this.host.symbolSearch.setCompared(this.comparedNow())}async addCompareSymbol(e,t=`percent`){if(!this.host.adapter){this.host.say(this.host.t(`toast.compareNeedsAdapter`),`error`);return}if(t!==`percent`){await this.addCompareIndicator(this.host.adapter,e,t);return}if(this.host.chart.getFeatures()?.compareSymbols===!1||this.compares.some(t=>t.symbol===e)||this.comparesLoading.has(e))return;let n=`cmp_${e}`;this.comparesLoading.add(e);try{let t=await this.fetchCompareBars(this.host.adapter,e);if(!t||this.compares.some(t=>t.symbol===e))return;let r=this.host.state.timeframe,i=Zo[this.compares.length%Zo.length];this.compares.length===0&&this.host.chart.setCompareMode(`percent`),this.host.chart.addCompareSymbol(n,(0,u.tickerOf)(e),t,i),this.compares=[...this.compares,{id:n,symbol:e,color:i,bars:t,timeframe:r}],this.compares.length===1&&this.holdCompareScale(!0),this.host.scheduleLegend(),this.host.refreshObjects(),this.refreshCompareDialog(),this.host.say(s.r(this.host.t(`toast.comparing`),{symbol:(0,u.tickerOf)(e)}))}finally{this.comparesLoading.delete(e)}}async addCompareIndicator(e,t,n){let r=await this.fetchCompareBars(e,t);r&&(this.host.chart.setSymbolSeries(t,r),n===`scale`?this.host.chart.addIndicator(`compareSymbol`,{symbol:t},`bottom`,{scale:`left`}):n===`pane`?this.host.chart.addIndicator(`compareSymbolPane`,{symbol:t}):n===`correlation`?this.host.chart.addIndicator(`correlation`,{symbol:t}):n===`correlationLog`?this.host.chart.addIndicator(`correlationlog`,{symbol:t}):this.host.chart.addIndicator(`spread`,{symbol:t,mode:n}))}async fetchCompareBars(e,t){for(;;){let n=this.host.state.timeframe,r=null,i=null;try{r=await(0,d.withResampling)(e).fetchHistory(t,n,this.compareDepth())}catch(e){i=e}if(this.host.destroyed)return null;if(n===this.host.state.timeframe)return r&&r.length>0?r:(i===null?this.host.say(s.r(this.host.t(`toast.compareNoBars`),{symbol:(0,u.tickerOf)(t),interval:ve(n)}),`error`):this.sayCompareFailed(t,i),null)}}sayCompareFailed(e,t){this.host.say(`${(0,u.tickerOf)(e)}: ${t instanceof Error?t.message:this.host.t(`toast.loadFailed`)}`,`error`)}removeCompared(e){this.compares.some(t=>t.id===e)?this.handleRemoveCompare(e):this.host.chart.removeIndicator(e)}handleRemoveCompare(e){this.host.chart.removeCompareSymbol(e),this.compares=this.compares.filter(t=>t.id!==e),this.compares.length===0&&this.holdCompareScale(!1),this.host.scheduleLegend(),this.host.refreshObjects(),this.refreshCompareDialog()}removeHostCompare(e){this.host.chart.removeCompareSymbol(e),this.host.scheduleLegend()}isPercentCompare(e){return this.compares.some(t=>t.id===e)}compareDepth(){return Math.max(this.host.chart.getData().length,this.host.options.historyLimit??500)}holdsPercentScale(){return this.compareScaleHeld&&this.compares.length>0&&this.host.settingsState.scaleMode===`regular`&&this.host.chart.isTimeAligned()}holdCompareScale(e){e!==this.compareScaleHeld&&(this.compareScaleHeld=e,this.showHeldScale())}showHeldScale(){this.host.showScaleMode(),this.host.refreshScaleSwitches(),this.host.settings?.refresh(this.host.shownSettings())}async loadSymbolSeries(e){if(!this.host.adapter){this.host.say(this.host.t(`toast.compareNeedsAdapter`),`error`);return}let t=this.host.state.timeframe,n=(this.host.symbolLoads.get(e)??0)+1;this.host.symbolLoads.set(e,n);let r=()=>this.host.destroyed||t!==this.host.state.timeframe||this.host.symbolLoads.get(e)!==n;try{let n=await(0,d.withResampling)(this.host.adapter).fetchHistory(e,t,this.compareDepth());if(r())return;this.host.chart.setSymbolSeries(e,n)}catch(t){if(r())return;this.host.chart.setSymbolSeries(e,this.host.chart.getSymbolSeries(e)),this.sayCompareFailed(e,t)}}async refetchCompares(){for(let e of this.host.chart.getRequiredSymbols?.()??[])this.loadSymbolSeries(e);if(!this.host.adapter||this.compares.length===0)return;let e=this.compares.filter(e=>e.symbol===this.host.state.symbol);for(let t of e)this.handleRemoveCompare(t.id);await this.refetchPercentCompares()}async refetchPercentCompares(){if(!this.host.adapter||this.compares.length===0)return;let e=++this.compareFetchSeq,t=(0,d.withResampling)(this.host.adapter);this.compares=this.compares.map(e=>({...e,failedAt:void 0}));for(let n of this.compares){let r=this.host.state.timeframe;try{let i=await t.fetchHistory(n.symbol,r,this.compareDepth());if(this.host.destroyed||e!==this.compareFetchSeq)return;this.isPercentCompare(n.id)&&this.setCompareBars(n.id,i,r)}catch{!this.host.destroyed&&e===this.compareFetchSeq&&this.compareFailedAt(n.id,r)}}this.compareOlderPassed&&(this.compareOlderPassed=!1,this.extendPercentCompares())}async extendPercentCompares(){if(this.compareOlderBusy){this.compareOlderAgain=!0;return}this.compareOlderBusy=!0;try{do this.compareOlderAgain=!1,await this.fetchOlderCompares();while(this.compareOlderAgain&&!this.host.destroyed)}finally{this.compareOlderBusy=!1}}async fetchOlderCompares(){if(!this.host.adapter||this.compares.length===0)return;let e=(0,d.withResampling)(this.host.adapter),t=this.compareFetchSeq,n=this.host.state.timeframe;for(let r of this.compares){if(r.timeframe!==n){r.failedAt!==n&&(this.compareOlderPassed=!0);continue}let i=r.bars[0]?.time;if(i===void 0||r.atStart)continue;let a=eo(this.host.chart.getData(),i);if(a!==0)try{if(e.fetchHistoryBefore){let o=await e.fetchHistoryBefore(r.symbol,n,i,a);if(this.host.destroyed||t!==this.compareFetchSeq)return;this.prependCompareBars(r.id,o,n)}else{let a=this.compareDepth(),o=await e.fetchHistory(r.symbol,n,a);if(this.host.destroyed||t!==this.compareFetchSeq)return;this.deepenCompareBars(r.id,o,a,i,n)}}catch{}}}deepenCompareBars(e,t,n,r,i){this.isPercentCompare(e)&&(this.setCompareBars(e,t,i),(t.length<n||!(t[0].time<r))&&(this.compares=this.compares.map(t=>t.id===e?{...t,atStart:!0}:t)))}prependCompareBars(e,t,n){let r=this.compares.find(t=>t.id===e);if(!r)return;let i=to(r.bars,t);i?this.setCompareBars(e,i,n):this.compares=this.compares.map(t=>t.id===e?{...t,atStart:!0}:t)}setCompareBars(e,t,n){this.host.chart.updateCompareData(e,t),this.compares=this.compares.map(r=>r.id===e?{...r,bars:t,timeframe:n,atStart:!1,failedAt:void 0}:r)}compareFailedAt(e,t){this.compares=this.compares.map(n=>n.id===e?{...n,failedAt:t}:n)}},$o=class{constructor(e){this.host=e}watchlist=null;watchlistSparkBuffer=new Map;hostWatchlistRefPrice=new Map;watchlistInterval=null;watchlistStore=null;watchlistFromSymbols=!1;quoteSource=null;stopQuotes=null;quotedKey=``;quotes=new Map;getWatchlists(){return this.watchlistStore?.getLists()??[]}getActiveWatchlist(){return this.watchlistStore?.getActive().id??null}setWatchlists(e,t){this.watchlistFromSymbols=!1,this.watchlistStore?.replace(e,t)}setActiveWatchlist(e){this.watchlistStore?.setActive(e)}addToWatchlist(e,t){this.watchlistStore?.add(e,t)}removeFromWatchlist(e,t){this.watchlistStore?.removeSymbol(e,t)}setQuotes(e){let t=e.map(u.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)}getQuote(e){let t=this.quotes.get(e);return t?{...t}:null}createWatchlist(e,t){let n=t.persist?A():null,r=new pn({lists:t.lists,activeList:t.activeList,symbols:this.host.symbols,defaultName:this.host.t(`watchlist.title`),storage:n,storageKey:t.storageKey});this.watchlistStore=r,this.watchlistFromSymbols=!t.lists&&!t.persist,this.quoteSource=t.quotes===!1?null:t.quotes??(this.host.options.adapter?.subscribeQuotes?this.host.options.adapter:null);let i=e=>this.host.t(e);this.watchlist=new Zt(e,{onSelect:e=>{this.host.setSymbol(e)},onAdd:()=>this.host.withSymbolSearch(()=>!0,e=>e.open({symbols:this.host.symbolEntries(),current:this.host.state.symbol,currentInfo:this.host.chartSymbolInfo(),onPick:e=>r.add(e),search:this.host.symbolSearchFn()})),onRemove:e=>r.removeSymbol(e),onMove:(e,t)=>r.move(e,t),onPickList:e=>r.setActive(e),onCreateList:e=>r.create(e),onRenameList:(e,t)=>r.rename(e,t),onDeleteList:e=>r.remove(e),onClose:()=>this.host.closePanelByHand(`watchlist`)},{close:i(`common.close`),title:i(`watchlist.title`),lists:i(`watchlist.lists`),newList:i(`watchlist.newList`),rename:i(`watchlist.rename`),deleteList:i(`watchlist.deleteList`),confirmDelete:i(`watchlist.confirmDelete`),add:i(`watchlist.add`),remove:i(`watchlist.remove`),empty:i(`watchlist.empty`),listName:i(`watchlist.listName`),columns:{symbol:i(`watchlist.columnSymbol`),price:i(`watchlist.columnPrice`),move:i(`watchlist.columnMove`),change:i(`watchlist.columnChange`)}},{sparkline:t.sparkline===!0,infoOf:e=>this.host.symbolInfoOf(e)}),this.watchlist.setActive(this.host.state.symbol),this.watchlist.setLocale(this.host.settingsState.numberLocale||void 0);let a=()=>{this.watchlist?.setLists(r.getLists(),r.getActive().id),this.followQuotes()};r.subscribe(()=>{a(),t.onChange?.(r.getLists(),r.getActive().id)}),a()}followQuotes(){if(!this.quoteSource||!this.watchlistStore||this.host.destroyed)return;let e=this.watchlistStore.getActive().symbols,t=[...e].sort().join(`\0`);if(t!==this.quotedKey&&(this.quotedKey=t,this.stopQuotes?.(),this.stopQuotes=null,e.length!==0))try{this.stopQuotes=this.quoteSource.subscribeQuotes(e,e=>{if(this.host.destroyed||!Array.isArray(e))return;let t=e.map(u.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)})}catch{this.stopQuotes=null}}takeQuotes(e){for(let t of e){let e={...this.quotes.get(t.symbol),...t};this.quotes.set(e.symbol,e);let n=this.watchlistSparkBuffer.get(e.symbol)??[];n.push(e.last),n.length>40&&n.shift(),this.watchlistSparkBuffer.set(e.symbol,n);let r=this.hostWatchlistRefPrice.get(e.symbol);this.watchlist?.setEntry(e.symbol,{lastPrice:e.last,refPrice:r??(e.change===void 0?void 0:e.last-e.change),sparkline:n.slice()})}e.some(e=>e.symbol===this.host.state.symbol)&&this.host.refreshSymbolInfo()}setWatchlistEntry(e,t){t.refPrice!==void 0&&this.hostWatchlistRefPrice.set(e,t.refPrice),this.watchlist?.setEntry(e,t)}tickWatchlist(){if(!this.watchlist||this.quotes.has(this.host.state.symbol)||Xt())return;let e=this.host.chart.getData();if(e.length===0)return;let t=e[e.length-1],n=this.hostWatchlistRefPrice.get(this.host.state.symbol);n===void 0&&this.host.sessionRefPrice===null&&(this.host.sessionRefPrice=e[0].open);let r=this.watchlistSparkBuffer.get(this.host.state.symbol)??[];r.push(t.close),r.length>40&&r.shift(),this.watchlistSparkBuffer.set(this.host.state.symbol,r),this.watchlist.setEntry(this.host.state.symbol,{lastPrice:t.close,refPrice:n??this.host.sessionRefPrice??e[0].open,sparkline:r.slice()})}},es=class{constructor(e){this.host=e}alertsPanel=null;alertNotifier=null;addDrawingAlert(e){if(!this.host.featureState.alerts)return;let t=this.host.chart.getDrawings().find(t=>t.id===e),n=t?this.host.drawingToolName(t.type):``;this.host.chart.addDrawingAlert(e,{label:n})&&this.host.say(s.r(this.host.t(`drawingSettings.alertAdded`),{name:n}))}toggleAlerts(){!this.alertsPanel||!this.host.featureState.alerts||this.host.dock?.toggle(`alerts`)}refreshAlerts(){if(!this.alertsPanel)return;let e=this.buildAlertSources();this.alertsPanel.setSources(e),this.alertsPanel.setAlerts(this.host.chart.getAlerts().map(t=>this.alertListItem(t,e)))}alertListItem(e,t){return{id:e.id,price:e.price,condition:e.condition,message:e.message,triggered:e.triggered,channel:e.channel,label:e.label,drawingId:e.drawingId,target:e.target,targetLabel:e.target?t.find(t=>t.channel===e.target)?.label:void 0,percent:e.percent,bars:e.bars,onBarClose:e.onBarClose,expiresAt:e.expiresAt,expired:e.expired}}alertText(e){return Rn(this.alertListItem(e,this.buildAlertSources()),this.host.t,e=>this.host.formatAlertPrice(e),!0)}buildAlertSources(){let e=[{channel:`price`,label:this.host.t(`alerts.source.price`)}];for(let t of this.host.chart.getActiveIndicators()){let n=this.host.chart.getIndicatorOutput(t.instanceId)?.series,r=n&&n.length>0?n[n.length-1]:null,i=r?Object.keys(r).filter(e=>typeof r[e]==`number`):[];for(let n of i){let r=i.length>1?`${t.descriptor.name} ${n}`:t.descriptor.name;e.push({channel:`${t.instanceId}:${n}`,label:r})}}return e}getAlertChannelValue(e){let t=this.host.chart.getData();if(e===`price`)return t.length>0?this.host.chart.roundPrice(t[t.length-1].close):null;let n=e.indexOf(`:`);if(n<0||t.length===0)return null;let r=e.slice(0,n),i=e.slice(n+1),a=bo(this.host.chart.getIndicatorOutput(r)?.series,null)?.[i];return typeof a==`number`&&Number.isFinite(a)?a:null}},ts=class{constructor(e){this.host=e}accountPanel=null;orderTicket=null;accountFrame=0;bracketBar=null;depthLadder=null;toggleAccountPanel(e){let t=this.accountPanel;!t||e===t.isOpen()||!t.isOpen()&&!this.host.featureState.accountPanel||t.toggle()}openOrderTicket(e){if(!this.host.featureState.orderTicket)return;let t=this.host.chart.getData();this.orderTicket?.open({price:e,lastPrice:t.length>0?t[t.length-1].close:null,rules:this.orderRules(),symbol:this.host.state.symbol,step:e=>this.host.chart.getPriceStep(e),round:e=>this.host.chart.roundPrice(e)})}orderRules(){let e=this.host.chart.getMarket();return e?{roundPrice:e.priceStep!==void 0||(e.priceSteps?.length??0)>0?e=>this.host.chart.roundPrice(e):void 0,limits:this.host.chart.getPriceLimits(),lot:e.volumeUnit,multiplier:e.contractMultiplier}:{}}refreshAccountSoon(){this.accountFrame||!this.accountPanel||(this.accountFrame=requestAnimationFrame(()=>{this.accountFrame=0,this.host.destroyed||this.refreshAccount()}))}refreshAccount(){if(!this.accountPanel)return;let e=this.host.chart.getData(),t=e.length>0?e[e.length-1].close:null;this.accountPanel.update({positions:this.host.chart.getPositions(),orders:this.host.chart.getOrders(),fills:this.host.chart.getFills(),price:t,realisedPnl:this.host.chart.getRealisedPnl()}),this.orderTicket?.setLastPrice(t)}placeOrderAt(e,t){let n=e.startsWith(`buy`)?`buy`:`sell`,r=e.endsWith(`Stop`);this.host.chart.placeOrderIntent(r?{side:n,type:`stop`,price:t,stopPrice:t,quantity:1}:{side:n,type:`limit`,price:t,quantity:1}),this.host.say(s.r(this.host.t(`order.${e}`),{price:this.host.formatAlertPrice(t)}))}toggleLadder(){!this.depthLadder||!this.host.featureState.depthLadder||this.host.dock?.toggle(`depthLadder`)}setDepth(e){this.host.chart.setDepthData(e),this.depthLadder?.setData(e),e&&this.host.chart.pushDepthSnapshot(e)}startBracket(e){this.host.chart.startBracket(e)&&this.bracketBar?.show(e)}};function ns(e,t){let{selected:n}=e,r=n.length===1,i=new Set(n.map(e=>e.groupId)),a=i.size===1&&!i.has(null),o=[];e.canConfigure&&r&&o.push({id:`settings`,label:t(`drawingMenu.settings`),icon:`settings`}),e.canText&&r&&o.push({id:`text`,label:t(`drawingSettings.text`),icon:`textEdit`}),e.canAlert&&r&&o.push({id:`alert`,label:t(`drawingSettings.addAlert`),icon:`bell`}),o.length>0&&o.push(`separator`),r&&o.push({id:`front`,label:t(`drawingMenu.front`)},{id:`forward`,label:t(`drawingMenu.forward`)},{id:`backward`,label:t(`drawingMenu.backward`)},{id:`back`,label:t(`drawingMenu.back`)},`separator`),n.length>1&&!a&&o.push({id:`group`,label:t(`drawingMenu.group`),icon:`layers`}),n.some(e=>e.groupId)&&o.push({id:`ungroup`,label:t(`drawingMenu.ungroup`),icon:`layers`});let s=n.every(e=>e.locked);return o.push(s?{id:`unlock`,label:t(`common.unlock`),icon:`unlock`}:{id:`lock`,label:t(`common.lock`),icon:`lock`},{id:`hide`,label:t(`common.hide`),icon:`eyeOff`}),r&&o.push({id:`duplicate`,label:t(`drawingMenu.duplicate`),icon:`plus`}),s||o.push(`separator`,{id:`delete`,label:t(`drawingMenu.delete`),icon:`trash`,danger:!0}),o}var rs=class{constructor(e){this.host=e}drawingMenu=null;clearMenu=null;chartMenu=null;menuPane=null;openDrawingMenu(e,t,n){if(!this.drawingMenu||!this.host.featureState[`menu.drawing`])return;let i=new Map(this.host.chart.getDrawings().map(e=>[e.id,e])),a=this.host.chart.getSelectedDrawingIds().flatMap(e=>{let t=i.get(e);return t?[{id:t.id,locked:t.locked,groupId:t.group?.id??null}]:[]});if(a.length===0)return;let o=r.a(ns({selected:a,canConfigure:!0,canAlert:this.host.chart.canAddDrawingAlert(e),canText:this.host.canTypeDrawingText(e)},this.host.t),r.n,this.host.featureState),s=a.map(e=>e.id),c=i.get(e),l=c?this.host.options.drawingMenuItems?.({id:e,type:c.type,selected:s})??[]:[],u=Vo(o,l);if(u.length===0)return;let d=this.host.chartContainer.getBoundingClientRect(),f=this.host.root.getBoundingClientRect();this.drawingMenu.open(u,d.left-f.left+t,d.top-f.top+n,t=>{Ho(t,l)||this.runDrawingMenuAction(e,s,t)})}runDrawingMenuAction(e,t,n){switch(n){case`settings`:this.host.openDrawingSettings(e);return;case`text`:this.host.editDrawingText(e);return;case`alert`:this.host.alerting.addDrawingAlert(e);return;case`front`:case`forward`:case`backward`:case`back`:this.host.chart.moveDrawing(e,n);break;case`group`:this.host.chart.groupDrawings(t);break;case`ungroup`:{let e=new Set(this.host.chart.getDrawings().filter(e=>t.includes(e.id)).map(e=>e.group?.id));for(let t of e)t&&this.host.chart.ungroupDrawings(t);break}case`lock`:case`unlock`:this.host.chart.setDrawingsLocked(t,n===`lock`);break;case`hide`:this.host.chart.setDrawingsVisible(t,!1);break;case`duplicate`:this.host.chart.duplicateDrawing(e);break;case`delete`:{let e=this.host.drawingSettings?.editing();e&&t.includes(e)&&this.host.drawingSettings?.close(!0),this.host.chart.removeDrawings(t);break}}this.host.objectTree?.isOpen()&&this.host.refreshObjects()}chartMenuContext(e){let t=this.host.chart.getDrawings(),n=this.host.chart.getData(),r=this.host.settingsState,i=this.host.chart.getFeatures();return{price:e,lastPrice:n.length>0?n[n.length-1].close:null,formatPrice:e=>this.host.formatAlertPrice(e),canAlert:this.host.alerting.alertsPanel!==null,canTrade:this.host.options.trading!==!1,canOrderTicket:this.host.trading.orderTicket!==null,canDraw:!0,hasDrawings:t.length>0,drawingsHidden:t.length>0&&t.every(e=>!e.visible),canPaste:this.host.chart.canPasteDrawings(),hasIndicators:i.indicators!==!1&&this.removableIndicators().length>0,canGoToDate:!0,canExport:this.host.canExport,autoScale:this.host.chart.isAutoScale(),scaleMode:this.host.effectiveScaleMode(),canLog:i.logScale!==!1,inverted:this.host.chart.isInvertScale(),leftScale:r.leftPriceScale,labels:{values:r.indicatorValueLabels,aligned:r.alignAxisLabels,...i.barCountdown===!1?{}:{countdown:r.barCountdown}},lines:{highLow:r.highLowLines,lastPrice:this.host.chart.getStyleValue(`lastPrice.visible`)!==!1},timezone:{current:r.timezone,options:this.timezoneChoices()},keys:Object.fromEntries(zi.filter(e=>this.host.featureState.hotkeys&&this.host.featureState[e.feature]).map(e=>[e.action,e.keys]))}}removableIndicators(){return this.host.chart.getActiveIndicators().filter(e=>!d.SYMBOL_INDICATOR_IDS.has(e.id)).map(e=>e.instanceId)}exchangeChoice(){let e=this.host.chart.getExchangeTimeZone()??null;if(!(e===null&&!this.host.adapter?.resolveSymbol))return{label:this.host.t(`settings.timezone.exchange`),zone:e}}timezoneChoices(){return t.y(this.host.settingsState.timezone,Date.now(),this.host.t(`settings.timezone.local`),this.exchangeChoice()).map(({value:e,label:t})=>({value:e,label:t}))}openChartMenu(e,t,n,r){if(!this.chartMenu)return;let i=this.host.options.chartMenuItems?.(r)??[],a=Vo(e,i);if(a.length===0)return;let o=this.host.chartContainer.getBoundingClientRect(),s=this.host.root.getBoundingClientRect();this.chartMenu.open(a,o.left-s.left+t,o.top-s.top+n,e=>{Ho(e,i)||(e.startsWith(`tz:`)?this.host.changeSettings({timezone:e.slice(3)}):this.runChartMenuAction(e,r))})}runChartMenuAction(e,t){let{price:n}=t,r=n??NaN,i=this.host.settingsState,a=Bi(e);if(a){this.host.changeSettings({scaleMode:a});return}switch(e){case`alert`:this.host.chart.addAlert(r,`crossing`),this.host.say(s.r(this.host.t(`chartMenu.alertAdded`),{price:this.host.formatAlertPrice(r)}));break;case`buyLimit`:case`sellLimit`:case`buyStop`:case`sellStop`:this.host.trading.placeOrderAt(e,r);break;case`orderTicket`:this.host.trading.openOrderTicket(n);break;case`exportData`:this.host.chart.exportAllData(`csv`,`${this.host.state.symbol}-${this.host.state.timeframe}.csv`.replace(/[^\w.-]+/g,`_`));break;case`paneLog`:case`paneInvert`:case`panePercent`:{let t=this.menuPane;if(!t)break;let n=this.host.chart.getPaneScale(t);this.host.chart.setPaneScale(t,e===`paneLog`?{log:!n.log}:e===`paneInvert`?{invert:!n.invert}:{percent:!n.percent});break}case`horizontalLine`:{let e=this.host.chart.getData();e.length>0&&this.host.chart.addDrawing({type:`horizontalLine`,anchors:[{time:e[e.length-1].time,price:r}]});break}case`resetView`:this.host.resetView();break;case`resetPriceScale`:this.host.changeSettings({autoScale:!0});break;case`paste`:this.host.chart.pasteDrawings();break;case`removeIndicators`:this.host.chart.removeIndicators(this.removableIndicators());break;case`hideDrawings`:this.host.chart.setDrawingsVisible(this.host.chart.getDrawings().map(e=>e.id),!1);break;case`showDrawings`:this.host.chart.setDrawingsVisible(this.host.chart.getDrawings().map(e=>e.id),!0);break;case`removeDrawings`:this.host.chart.removeDrawings(this.host.chart.getDrawings().map(e=>e.id));break;case`settings`:this.host.openSettings(t.area===`priceAxis`?`scales`:void 0);break;case`autoScale`:this.host.changeSettings({autoScale:!this.host.chart.isAutoScale()});break;case`invertScale`:this.host.changeSettings({invertScale:!this.host.chart.isInvertScale()});break;case`leftScale`:this.host.changeSettings({leftPriceScale:!i.leftPriceScale});break;case`indicatorValueLabels`:this.host.changeSettings({indicatorValueLabels:!i.indicatorValueLabels});break;case`alignAxisLabels`:this.host.changeSettings({alignAxisLabels:!i.alignAxisLabels});break;case`barCountdown`:this.host.changeSettings({barCountdown:!i.barCountdown});break;case`highLowLines`:this.host.changeSettings({highLowLines:!i.highLowLines});break;case`lastPriceLine`:this.host.changeStyle({"lastPrice.visible":this.host.chart.getStyleValue(`lastPrice.visible`)===!1});break;case`goToDate`:this.host.toggleGoToDate();break}this.host.objectTree?.isOpen()&&this.host.refreshObjects()}openClearMenu(e){if(o.f.closeAnchoredTo(e))return;let t=this.host.chart.getDrawings().filter(e=>!e.locked).length,n=this.host.chart.getActiveIndicators().length,r=[];t>0&&r.push({id:`drawings`,label:this.host.t(`clear.drawings`),icon:`penLine`,count:t}),n>0&&r.push({id:`indicators`,label:this.host.t(`clear.indicators`),icon:`trendingUp`,count:n}),t>0&&n>0&&r.push(`separator`,{id:`all`,label:this.host.t(`clear.all`),icon:`trash`,danger:!0}),r.length!==0&&(this.clearMenu??=new o.f(this.host.root,this.host.t(`drawing.clearAll`)),this.clearMenu.openBeside(r,e,e=>this.removeAll(e)))}removeAll(e){this.host.chart.removeAll(e),this.host.state={...this.host.state,activeTool:null},this.host.updateUI(),this.host.refreshDrawingsState(),this.host.refreshObjects()}},is=2,as=2;function os(e,t=`en-US`){return(0,u.formatPrice)(e,Math.max(is,(0,d.indicatorValuePrecision)(e)),t)}function ss(e,t=`en-US`){return`${W((0,u.formatPrice)(Math.abs(e),as,t),e,(0,u.formatPrice)(0,as,t))}%`}function cs(e,t=`en-US`,n=!0){return e.map(e=>({instanceId:e.id,kind:`compare`,label:e.label,swatch:e.color,visible:e.visible,...n?{values:ls(e,t)}:{values:[],offChartType:!0},pane:null}))}function ls(e,t){return[...e.close===null?[]:[{text:os(e.close,t),color:null}],...e.change===null?[]:[{text:ss(e.change,t),color:null}]]}var us=7,ds=17,fs=3,ps=4;function ms(e){return u.CHART_SPACING[e.getDensity?.()??`comfortable`].legendInset-ps}function hs(e){return!d.SYMBOL_INDICATOR_IDS.has(e.id)&&e.scale!==`left`}var gs=class{constructor(e){this.host=e}legendFrame=0;legendMenu=null;scheduleLegend(){!this.host.indicatorLegend||this.legendFrame||!this.host.featureState.indicatorLegend||(this.legendFrame=requestAnimationFrame(()=>{this.legendFrame=0,this.renderLegend()}))}renderLegend(){if(!this.host.indicatorLegend||this.host.destroyed)return;let e=this.host.chart.getData().length-1,t=this.host.chart.isTimeAligned(),n=this.host.legendHoverIndex,r=ms(this.host.chart),i=n===null?e:Math.min(Math.max(n,0),e),a=new Map;for(let e of this.host.chart.getIndicatorPanes())(e.instanceIds??[e.instanceId]).forEach((t,n)=>a.set(t,{...e.rect,row:n}));let o=this.host.settingsState.numberLocale||`en-US`,s=cs(i>=0?this.host.chart.getCompareValues?.(n===null||!t?void 0:i)??[]:[],o,t),l=this.host.chart.getActiveIndicators().map(e=>{let t=a.get(e.instanceId)??null,i=bo(this.host.chart.getIndicatorOutput(e.instanceId,{drawn:!0})?.series,n),s=this.host.chart.getIndicatorStyle(e.instanceId),l=e.visible&&e.offChartType===!0,u=e.visible&&e.shown===!1&&!l,d=u||l?[]:xo(e.descriptor,i,s?.colors??[],s?.plots);return{instanceId:e.instanceId,label:c.r(e,this.host.t),visible:e.visible,offInterval:u,offChartType:l,values:d.map(n=>({text:this.host.indicatorValueText(n.value,t===null&&hs(e),o),color:n.color})),pane:t?{x:t.x+r,y:t.y+Math.min(us+t.row*ds,Math.max(us,t.height-ds)),width:t.width-2*r}:null}}),u=[...s,...l],d=this.host.chart.getPlotRect(),f=this.host.chart.getMaximizedPane(),p=e=>u.find(t=>t.instanceId===e)?.label??``,m=this.host.chart.getIndicatorPanes().map(e=>({instanceId:e.instanceId,x:e.rect.x+e.rect.width-r,y:e.rect.y+fs,label:p(e.instanceId),collapsed:this.host.chart.isPaneCollapsed(e.instanceId),maximized:f===e.instanceId,canMoveUp:this.host.chart.canMovePane(e.instanceId,-1),canMoveDown:this.host.chart.canMovePane(e.instanceId,1)}));this.host.indicatorLegend.update(u,{left:d.x+r,top:this.host.chart.getLegendBottom()+1},m)}runPaneAction(e,t){t===`up`||t===`down`?this.host.chart.movePane(e,t===`up`?-1:1):t===`collapse`||t===`expand`?this.host.chart.setPaneCollapsed(e,t===`collapse`):this.host.chart.setMaximizedPane(t===`maximize`?e:null),this.scheduleLegend()}openLegendMenu(e,t){let n=this.legendMenu;if(!n)return;if(n.isOpen()){n.close();return}let r=[`price`,...this.host.chart.getIndicatorPanes().map(e=>e.instanceId)],i=1+this.host.chart.getIndicatorPanes().findIndex(t=>t.instanceIds.includes(e)),a=r[i-1],o=r[i+1],s=t=>t!==void 0&&this.host.chart.canMoveIndicatorToPane(e,t),c=[];s(a)&&c.push({id:`move:${a}`,label:this.host.t(a===`price`?`legend.movePrice`:`legend.moveUp`),icon:`arrowUp`}),s(o)&&c.push({id:`move:${o}`,label:this.host.t(`legend.moveDown`),icon:`arrowDown`}),s(`new`)&&c.push({id:`move:new`,label:this.host.t(`legend.moveNew`),icon:`plus`}),a!==`price`&&s(`price`)&&c.push({id:`move:price`,label:this.host.t(`legend.movePrice`),icon:`trendingUp`});let l=[];this.host.featureState.indicatorSettings&&this.host.featureState[`indicatorLegend.settings`]&&l.push({id:`settings`,label:this.host.t(`legend.settings`),icon:`settings`}),this.host.featureState[`indicatorLegend.remove`]&&l.push({id:`remove`,label:this.host.t(`legend.remove`),icon:`trash`,danger:!0}),c.length>0&&l.length>0&&c.push(`separator`),c.push(...l);let u=this.host.chart.getActiveIndicators().find(t=>t.instanceId===e)?.id??``,d=this.host.options.indicatorMenuItems?.({instanceId:e,indicatorId:u})??[],f=Vo(c,d);if(f.length===0)return;let p=t.getBoundingClientRect(),m=this.host.root.getBoundingClientRect();n.open(f,p.left-m.left,p.bottom-m.top+2,t=>{Ho(t,d)||(t===`settings`?this.host.openIndicatorSettings(e):t===`remove`?this.host.handleRemoveIndicator(e):t.startsWith(`move:`)&&this.host.chart.moveIndicatorToPane(e,t.slice(5)),this.scheduleLegend())},t)}},_s=class{constructor(e){this.host=e}toggleCommandPalette(){if(this.host.commandPalette?.isOpen()){this.host.commandPalette.close();return}this.host.cancelWaiting(this.host.commandPalettePart)||this.host.whenLoaded(this.host.commandPalettePart,()=>this.host.featureState.commandPalette,e=>{e.isOpen()||e.open(this.buildCommandItems())})}buildCommandItems(){let e=[];for(let t of this.host.indicatorPickerItems())e.push({id:t.id,label:t.name,category:`indicator`,active:[...this.host.state.activeIndicators.values()].some(e=>e.id===t.id)});for(let n of t.m)e.push({id:n.value,label:t.t(n,this.host.t),category:`chartType`,active:this.host.state.chartType===n.value});let n=Mn();for(let r of t.n(t._,this.host.t))for(let t of r.tools)e.push({id:t.value,label:t.label,category:`drawing`,shortcut:n[t.value]?this.host.keysShown(`hotkeys.tools`,n[t.value]):void 0,active:this.host.state.activeTool===t.value});for(let t of this.host.timeframes)e.push({id:t,label:ve(t),category:`timeframe`,active:this.host.state.timeframe===t});return e.push({id:`symbolSearch`,label:this.host.t(`hotkeys.symbolSearch`),category:`action`,shortcut:this.host.keysShown(`hotkeys.symbolSearch`,`${l.t}+P`)},{id:`compare`,label:this.host.t(`compare.title`),category:`action`},{id:`goToDate`,label:this.host.t(`hotkeys.goToDate`),category:`action`,shortcut:this.host.keysShown(`hotkeys.goToDate`,`Alt+G`)},{id:`resetView`,label:this.host.t(`chartMenu.resetView`),category:`action`,shortcut:this.host.keysShown(`hotkeys.resetView`,`Alt+R`)},{id:`invertScale`,label:this.host.t(`hotkeys.invertScale`),category:`action`,shortcut:this.host.keysShown(`hotkeys.invertScale`,`Alt+I`)},{id:`saveLayout`,label:this.host.t(`hotkeys.saveLayout`),category:`action`,shortcut:this.host.keysShown(`hotkeys.save`,`${l.t}+S`)},{id:`watchlist`,label:this.host.t(`watchlist.title`),category:`action`},{id:`alerts`,label:this.host.t(`alerts.title`),category:`action`},{id:`objectTree`,label:this.host.t(`objects.title`),category:`action`},{id:`dataWindow`,label:this.host.t(`action.dataWindow`),category:`action`},{id:`symbolInfo`,label:this.host.t(`action.symbolInfo`),category:`action`},{id:`screenshot`,label:this.host.t(`action.screenshot`),category:`action`},{id:`copyImage`,label:this.host.t(`action.copyImage`),category:`action`},{id:`shareView`,label:this.host.t(`action.shareView`),category:`action`},{id:`toggleTheme`,label:this.host.t(`action.toggleTheme`),category:`action`},{id:`settings`,label:this.host.t(`action.settings`),category:`action`},{id:`autoFib`,label:this.host.t(`action.autoFib`),category:`action`},{id:`clearDrawings`,label:this.host.t(`action.clearDrawings`),category:`action`},{id:`clearIndicators`,label:this.host.t(`clear.indicators`),category:`action`},{id:`clearAll`,label:this.host.t(`clear.all`),category:`action`},{id:`hotkeys`,label:this.host.t(`hotkeys.title`),category:`action`,shortcut:this.host.keysShown(`hotkeys.help`,`?`)}),e.filter(e=>e.category!==`action`||this.commandOn(e.id)&&this.commandThere(e.id))}commandThere(e){return e===`watchlist`?this.host.watching.watchlist!==null:e===`compare`?this.host.adapter!==null&&this.host.options.chartOptions?.features?.compareSymbols!==!1:e===`saveLayout`?this.host.layoutSession!==null:!0}commandOn(e){let t=r.i(e);return t===void 0||this.host.featureState[t]}handleAction(e){if(this.commandOn(e))switch(e){case`symbolSearch`:this.host.openSymbolSearch();break;case`compare`:this.host.comparing.handleAddCompare();break;case`goToDate`:this.host.toggleGoToDate();break;case`resetView`:this.host.resetView();break;case`invertScale`:this.host.changeSettings({invertScale:!this.host.settingsState.invertScale});break;case`saveLayout`:this.host.saveLayout();break;case`watchlist`:case`alerts`:case`objectTree`:this.host.openPanel(e);break;case`hotkeys`:this.host.openHotkeySheet();break;case`screenshot`:this.host.chart.screenshot();break;case`toggleTheme`:this.host.handleToggleTheme();break;case`settings`:this.host.openSettings();break;case`copyImage`:this.host.copyChartImage();break;case`shareView`:this.host.copyShareLink();break;case`autoFib`:{let e=this.host.chart.autoFib();this.host.say(e?this.host.t(`toast.autoFibAdded`):this.host.t(`toast.noSwing`));break}case`dataWindow`:this.host.toggleDataWindow();break;case`symbolInfo`:this.host.toggleSymbolInfo();break;case`clearDrawings`:this.host.menus.removeAll(`drawings`);break;case`clearIndicators`:this.host.menus.removeAll(`indicators`);break;case`clearAll`:this.host.menus.removeAll(`all`);break}}},vs=0,ys=class{backdrop;search;listEl;layouts=[];confirming=null;returnFocus=null;loadSeq=0;uid=++vs;constructor(e,t,n=s.t){this.callbacks=t,this.t=n,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let r=!1;this.backdrop.addEventListener(`pointerdown`,e=>{r=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&r&&this.close(),r=!1});let a=document.createElement(`div`);a.className=`tcw-modal tcw-layouts-dialog`,a.setAttribute(`role`,`dialog`),a.setAttribute(`aria-modal`,`true`),a.setAttribute(`aria-labelledby`,`tcw-layouts-title-${this.uid}`),a.addEventListener(`keydown`,e=>{if(e.key!==`Escape`){i.n(e,a);return}e.stopPropagation(),this.confirming?this.setConfirming(null):this.close()});let o=document.createElement(`div`);o.className=`tcw-modal-header`;let c=document.createElement(`h3`);c.id=`tcw-layouts-title-${this.uid}`,c.textContent=this.t(`layouts.dialogTitle`);let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-modal-close`,l.setAttribute(`aria-label`,this.t(`common.close`)),l.innerHTML=i.i(`x`,16),l.addEventListener(`click`,()=>this.close()),o.append(c,l);let u=document.createElement(`label`);u.className=`tcw-ss-search tcw-layouts-search-row`,u.innerHTML=i.i(`search`,16),this.search=document.createElement(`input`),this.search.type=`search`,this.search.className=`tcw-layouts-search`,this.search.placeholder=this.t(`layouts.search`),this.search.setAttribute(`aria-label`,this.t(`layouts.search`)),this.search.autocomplete=`off`,this.search.addEventListener(`input`,()=>this.render()),u.appendChild(this.search),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-layouts-list`,this.listEl.setAttribute(`role`,`list`);let d=document.createElement(`div`);d.className=`tcw-layouts-body`,d.appendChild(this.listEl),a.append(o,u,d),this.backdrop.appendChild(a),e.appendChild(this.backdrop)}async open(){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.search.value=``,this.confirming=null,this.backdrop.hidden=!1,this.search.focus(),await this.refresh()}async refresh(){let e=++this.loadSeq,t;try{t=await this.callbacks.list()}catch{t=[]}e===this.loadSeq&&(this.layouts=t,this.render())}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.confirming=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}destroy(){this.close(),this.backdrop.remove()}shown(){let e=this.search.value.trim().toLowerCase();return e?this.layouts.filter(t=>t.name.toLowerCase().includes(e)||(t.symbol??``).toLowerCase().includes(e)):this.layouts}render(){let e=this.shown();if(e.length===0){let e=document.createElement(`p`);e.className=`tcw-account-empty`,e.textContent=this.t(this.layouts.length===0?`layouts.empty`:`layouts.noMatch`),this.listEl.replaceChildren(e);return}let t=this.callbacks.currentId();this.listEl.replaceChildren(...e.map(e=>this.row(e,e.id===t)))}row(e,t){let n=document.createElement(`div`);n.className=`tcw-layouts-row`,n.setAttribute(`role`,`listitem`),n.dataset.id=e.id;let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-layouts-open`,t&&r.setAttribute(`aria-current`,`true`);let a=document.createElement(`span`);a.className=`tcw-layouts-name`,a.textContent=e.name;let o=document.createElement(`span`);if(o.className=`tcw-layouts-meta`,o.textContent=[[e.symbol?(0,u.tickerOf)(e.symbol):``,e.timeframe].filter(Boolean).join(` · `),s.r(this.t(`layouts.updated`),{time:this.callbacks.formatTime(e.updatedAt)})].filter(Boolean).join(` — `),r.append(a,o),t){let e=document.createElement(`span`);e.className=`tcw-layouts-check`,e.innerHTML=i.i(`check`,14);let t=document.createElement(`span`);t.className=`tcw-visually-hidden`,t.textContent=this.t(`layouts.current`),r.prepend(e),r.appendChild(t)}r.addEventListener(`click`,()=>{this.callbacks.onOpen(e.id),this.close()});let c=document.createElement(`div`);if(c.className=`tcw-account-actions`,this.confirming===e.id){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-layouts-confirm`,t.textContent=this.t(`layouts.deleteConfirm`),t.setAttribute(`aria-label`,s.r(this.t(`layouts.deleteNamed`),{name:e.name})),t.addEventListener(`click`,()=>void this.remove(e.id));let n=this.iconButton(`x`,this.t(`common.cancel`),()=>this.setConfirming(null));c.append(t,n)}else c.append(this.iconButton(`penLine`,s.r(this.t(`layouts.renameNamed`),{name:e.name}),()=>this.callbacks.onRename(e)),this.iconButton(`trash`,s.r(this.t(`layouts.deleteNamed`),{name:e.name}),()=>this.setConfirming(e.id),!0));return n.append(r,c),n}iconButton(e,t,n,r=!1){let a=document.createElement(`button`);return a.type=`button`,a.className=`tcw-tree-btn${r?` tcw-tree-del`:``}`,a.setAttribute(`aria-label`,t),a.title=t,a.innerHTML=i.i(e,14),a.addEventListener(`click`,n),a}setConfirming(e){let t=this.confirming;this.confirming=e,this.render();let n=e??t;n&&[...this.listEl.querySelectorAll(`.tcw-layouts-row`)].find(e=>e.dataset.id===n)?.querySelector(e?`.tcw-layouts-confirm`:`.tcw-tree-del`)?.focus()}async remove(e){try{await this.callbacks.onDelete(e)}finally{this.confirming=null,await this.refresh(),this.isOpen()&&this.search.focus()}}},bs=5,xs=class{menu;prompt;dialog;destroyed=!1;constructor(e,t){this.session=e,this.host=t;let{root:n,t:r}=t;this.menu=new o.f(n,r(`toolbar.layouts`)),this.prompt=new ka(n,r),this.dialog=new ys(n,{list:()=>e.list(),currentId:()=>e.current()?.id??null,onOpen:e=>void this.open(e),onRename:e=>this.promptRename(e),onDelete:async t=>{try{await e.remove(t)}catch{this.host.toast(r(`layouts.deleteFailed`),`error`)}},formatTime:t.formatTime},r)}async save(){if(this.prompt.isOpen())return;if(!this.session.current()){this.promptSaveAs();return}let{t:e,toast:t}=this.host;try{let n=await this.session.save();n&&t(s.r(e(`layouts.saved`),{name:n.name}))}catch{t(e(`layouts.saveFailed`),`error`)}}async open(e){try{if(await this.session.open(e))return!0}catch{}return this.destroyed||this.host.toast(this.host.t(`layouts.openFailed`),`error`),!1}promptSaveAs(){let{t:e,toast:t}=this.host,n=this.session.current();this.prompt.open({title:e(`layouts.saveAsTitle`),value:n?s.r(e(`layouts.copyName`),{name:n.name}):``,submitLabel:e(`common.save`),onSubmit:async n=>{try{let r=await this.session.saveAs(n);t(s.r(e(`layouts.saved`),{name:r.name}))}catch(n){throw t(e(`layouts.saveFailed`),`error`),n}}})}promptRename(e=this.session.current()){if(!e)return;let{t,toast:n}=this.host;this.prompt.open({title:t(`layouts.renameTitle`),value:e.name,submitLabel:t(`layouts.renameSubmit`),onSubmit:async r=>{try{await this.session.rename(e.id,r)}catch(e){throw n(t(`layouts.saveFailed`),`error`),e}this.dialog.isOpen()&&this.dialog.refresh()}})}openDialog(){return this.dialog.open()}async openMenu(e){if(this.menu.isOpen()){this.menu.close();return}let{session:t}=this,{t:n}=this.host,r=[];try{r=(await t.list()).slice(0,bs)}catch{}if(this.destroyed)return;let i=t.current(),a=[{id:`save`,label:n(`layouts.save`),icon:`save`,shortcut:this.host.saveKeys?.()},{id:`saveAs`,label:n(`layouts.saveAs`),icon:`plus`}];i&&a.push({id:`rename`,label:n(`layouts.rename`),icon:`penLine`}),a.push({id:`autoSave`,label:n(`layouts.autoSave`),checked:t.isAutoSave()}),r.length>0&&a.push(`separator`,...r.map(e=>({id:`open:${e.id}`,label:e.name,checked:e.id===i?.id}))),a.push(`separator`,{id:`manage`,label:n(`layouts.open`),icon:`folder`}),this.menu.openUnder(a,e,e=>{e===`save`?this.save():e===`saveAs`?this.promptSaveAs():e===`rename`?this.promptRename():e===`autoSave`?t.setAutoSave(!t.isAutoSave()):e===`manage`?this.openDialog():e.startsWith(`open:`)&&this.open(e.slice(5))})}destroy(){this.destroyed=!0,this.menu.destroy(),this.prompt.destroy(),this.dialog.destroy()}},Ss=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Cs=globalThis.Buffer;function ws(e){if(Cs)return Cs.from(e,`utf8`).toString(`base64`);let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function Ts(e){if(Cs)return Cs.from(e,`base64`).toString(`utf8`);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return new TextDecoder().decode(n)}function Es(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Ds(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function Os(e){return Es(ws(JSON.stringify(e)))}function ks(e){if(!e)return null;try{let t=Ts(Ds(e)),n=JSON.parse(t);return!n||n.v!==1||typeof n.symbol!=`string`?null:{v:1,symbol:n.symbol,timeframe:n.timeframe,chartType:n.chartType,scaleMode:Na.find(e=>e===n.scaleMode)??`regular`,indicators:Array.isArray(n.indicators)?n.indicators:[],drawings:Array.isArray(n.drawings)?n.drawings:[],...Ss(n.settings)?{settings:L(n.settings,Ur)}:{}}}catch{return null}}var As=`tcw`;function js(e){let t=e.startsWith(`#`)?e.slice(1):e;for(let e of t.split(`&`)){let t=e.indexOf(`=`);if(!(t<=0||e.slice(0,t)!==As))try{return decodeURIComponent(e.slice(t+1))}catch{return null}}return null}function Ms(e,t){let[n]=e.split(`#`);return`${n}#${As}=${t}`}var Ns=[`legendVisible`,`volumeVisible`,`barCountdown`,`indicatorValueLabels`,`alignAxisLabels`],Ps=class{constructor(e){this.host=e}layoutSession=null;layoutsUI=null;layoutKeyPrefix=null;layoutDebounceMs=1500;activeLayoutKey=null;restoreSharedView(){if(!this.host.options.shareUrl||typeof location>`u`)return;let e=js(location.hash);e&&this.importState(e)}exportState(){let e=this.host.chart.getActiveIndicators().map(e=>({id:e.id,params:e.params})),n=this.host.getSettings(),r=ri(n,{...t.h,...Object.fromEntries(Ns.map(e=>[e,this.host.settingsDefaults[e]]))});return Os({v:1,symbol:this.host.state.symbol,timeframe:this.host.state.timeframe,chartType:this.host.state.chartType,scaleMode:n.scaleMode,indicators:e,drawings:this.host.chart.getDrawings(),...Object.keys(r).length>0?{settings:r}:{}})}async importState(e){let t=ks(e);if(!t)return!1;t.symbol&&t.symbol!==this.host.state.symbol&&await this.host.setSymbol(t.symbol),t.timeframe&&t.timeframe!==this.host.state.timeframe&&await this.host.setTimeframe(t.timeframe),t.chartType&&this.host.applyChartType(t.chartType);let{chartTypeOptions:n,...r}=this.host.allowedSettings({scaleMode:t.scaleMode,...L(t.settings,Ur)}),i=this.host.overViewerTypeOptions(t.chartType,n);return this.host.showLinkSettings(i?{...r,chartTypeOptions:i}:r),this.host.chart.applyIndicatorSetup(t.indicators.map((e,t)=>({id:e.id,instanceId:`shared_${t}`,params:e.params}))),this.host.chart.setDrawings(t.drawings),this.host.updateUI(),!0}async copyShareLink(){let e=Ms(typeof location<`u`?location.href:``,this.exportState());try{await navigator.clipboard.writeText(e),this.host.say(this.host.t(`toast.linkCopied`))}catch{this.host.say(this.host.t(`toast.copyFailed`),`error`)}}getLayoutSession(){return this.layoutSession}captureLayout(){let e=this.host.getSettings(),t=this.host.chart.saveState(),n=t?La(t):null,r=n&&typeof n==`object`?Fa(n):null;return{v:1,symbol:this.host.state.symbol,timeframe:this.host.chosenTimeframe??this.host.state.timeframe,scaleMode:e.scaleMode,invertScale:e.invertScale,chart:r,settings:ti(e,Hr)}}async restoreLayout(e){if(e.symbol!==this.host.state.symbol&&await this.host.setSymbol(e.symbol),e.timeframe!==this.host.state.timeframe&&await this.host.setTimeframe(e.timeframe),this.host.destroyed)return;if(e.chart){this.host.chart.loadState(JSON.stringify(Fa(e.chart)));let t=e.chart.chartType;typeof t==`string`&&(this.host.state={...this.host.state,chartType:t})}let t=this.host.allowedSettings({scaleMode:e.scaleMode,invertScale:e.invertScale,...L(e.settings,Hr)});this.host.claimSettings(Object.keys(t)),this.host.applySettings(t),this.host.syncIndicatorsFromChart(),this.host.updateUI(),this.host.settings?.refresh(this.host.shownSettings(),this.host.state.chartType)}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=Ia(La(e));return t?(await this.restoreLayout(t),!0):!1}setupLayouts(t){let n=new e.t(t.storage??e.i(),{capture:()=>({content:this.getLayoutContent(),symbol:this.host.state.symbol,timeframe:this.host.chosenTimeframe??this.host.state.timeframe}),apply:async e=>{if(!await this.applyLayoutContent(e.content))throw Error(`Not a widget layout`)}},{autoSave:t.autoSave,debounceMs:t.debounceMs,onChange:()=>this.host.toolbar?.setLayout(n.current()?.name??null,n.isDirty()),onError:()=>this.host.say(this.host.t(`layouts.saveFailed`),`error`)});this.layoutSession=n,this.layoutsUI=new xs(n,{root:this.host.root,t:this.host.t,saveKeys:()=>this.host.keysShown(`hotkeys.save`,`${l.t}+S`),toast:(e,t)=>this.host.say(e,t),formatTime:e=>{let{date:t,time:n}=Y(e,this.host.displayTimezone());return`${t} ${n}`}}),this.host.chart.on(`stateChange`,()=>n.changed()),t.openLast&&n.list().then(([e])=>e&&!this.host.destroyed?this.openLayout(e.id):void 0,()=>void 0)}async saveLayout(){await this.layoutsUI?.save()}async openLayout(e){return await this.layoutsUI?.open(e)??!1}clearSavedLayout(e){if(!this.layoutKeyPrefix)return;let t=e??this.host.state.symbol;try{localStorage.removeItem(this.layoutKeyPrefix+t)}catch{}}applySymbolLayout(e){if(!this.layoutKeyPrefix)return;let t=this.layoutKeyPrefix+e;this.activeLayoutKey=t;try{this.host.chart.loadStateFromStorage(t)&&this.host.syncIndicatorsFromChart()}catch{}this.host.chart.setAutoSave(t,this.layoutDebounceMs)}flushActiveLayout(){if(this.activeLayoutKey){try{this.host.chart.saveState(this.activeLayoutKey)}catch{}this.host.chart.disableAutoSave(),this.activeLayoutKey=null}}},Fs={alerts:`alerts`,objectTree:`objectTree`,dataWindow:`dataWindow`,symbolInfo:`symbolInfo`,depthLadder:`depthLadder`},Is={watchlist:`watchlist`,alerts:`alerts`,objectTree:`objects`,symbolInfo:`symbolInfo`,depthLadder:`trade`},Ls=class{dataWindowFrame=0;constructor(e){this.host=e}scheduleDataWindow(){this.dataWindowFrame||!this.host.dataWindow?.isOpen()||(this.dataWindowFrame=requestAnimationFrame(()=>{this.dataWindowFrame=0,this.host.dataWindow?.isOpen()&&this.host.dataWindow.render(this.buildDataWindowModel())}))}dock=null;dockNarrow=null;dockObserver=null;openPanel(e){return!this.hasPanel(e)||!this.dock?!1:(this.dock.open(e),this.dock.current()===e)}hasPanel(e){return e===`watchlist`?this.host.watching.watchlist!==null:e===`depthLadder`&&this.host.trading.depthLadder===null?!1:this.host.featureState[Fs[e]]}closePanel(){this.dock?.close()}getOpenPanel(){return this.dock?.current()??null}hoveredBar(){let e=this.host.lastHoverIndex;if(e===null||e<0)return null;if(!this.host.chart.isTimeAligned()){let e=this.host.lastHoverBar;return e?{bar:e,prevClose:this.host.lastHoverPrevClose??e.open}:null}let t=this.host.chart.getData();return e>=t.length?null:{bar:t[e],prevClose:e>0?t[e-1].close:t[e].open}}buildDataWindowModel(){let e=this.host.lastHoverIndex,t=this.hoveredBar();if(e===null||!t)return{ohlc:null,change:0,changePct:0,indicators:[]};let{bar:n,prevClose:r}=t,i=n.close-r,a=r===0?0:i/r*100,o=new Set(this.host.chart.getIndicatorPanes().flatMap(e=>e.instanceIds??[e.instanceId])),s=this.host.settingsState.numberLocale||`en-US`,c=this.host.chart.getActiveIndicators().map(t=>{let n=this.host.chart.getIndicatorOutput(t.instanceId,{drawn:!0})?.series?.[e]??null,r=!o.has(t.instanceId)&&hs(t),i=t.descriptor.plots?.map(e=>[e.key,e.title])??Object.keys(n??{}).map(e=>[e,e]),a=n?i.filter(([e])=>typeof n[e]==`number`&&Number.isFinite(n[e])).map(([e,t])=>{let i=n[e];return{key:t,value:i,text:this.host.indicatorValueText(i,r,s)}}):[];return{name:t.descriptor.name,values:a}}).filter(e=>e.values.length>0);return{ohlc:{open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume},change:i,changeText:this.host.formatAlertPrice(i,n.close),changePct:a,indicators:c}}toggleDataWindow(){!this.host.dataWindow||!this.host.featureState.dataWindow||this.dock?.toggle(`dataWindow`)}toggleWatchlist(){this.host.watching.watchlist&&this.dock?.toggle(`watchlist`)}toggleObjects(){!this.host.objectTree||!this.host.featureState.objectTree||this.dock?.toggle(`objectTree`)}setupDock(){let e=this.dock;if(!e)return;if(this.host.watching.watchlist){let t=this.host.watching.watchlist;e.addPage({id:`watchlist`,label:this.host.t(`watchlist.title`),icon:`list`,element:t.element,parts:[`dock.watchlist`],onShow:()=>{t.redraw(),this.host.markOpen(`watchlist`,!0)},onHide:()=>this.host.markOpen(`watchlist`,!1)})}let t=this.host.alerting.alertsPanel;t&&e.addPage({id:`alerts`,label:this.host.t(`alerts.title`),icon:`bell`,element:t.element,parts:[`dock.alerts`,`alerts`],onShow:()=>{t.openPanel(),this.host.alerting.refreshAlerts(),this.host.markOpen(`alerts`,!0)},onHide:()=>{t.close(),this.host.markOpen(`alerts`,!1)}});let n=this.host.objectTree;n&&e.addPage({id:`objectTree`,label:this.host.t(`objects.title`),icon:`layers`,element:n.element,parts:[`dock.objectTree`,`objectTree`],onShow:()=>{n.openPanel(),this.refreshObjects(),this.host.markOpen(`objects`,!0)},onHide:()=>{n.close(),this.host.markOpen(`objects`,!1)}});let r=this.host.dataWindow;r&&e.addPage({id:`dataWindow`,label:this.host.t(`dataWindow.title`),icon:`table`,element:r.element,parts:[`dock.dataWindow`,`dataWindow`],onShow:()=>{r.openPanel(),r.render(this.buildDataWindowModel())},onHide:()=>r.close()});let i=this.host.symbolInfoPanel;i&&e.addPage({id:`symbolInfo`,label:this.host.t(`symbolInfo.title`),icon:`info`,element:i.element,parts:[`dock.symbolInfo`,`symbolInfo`],onShow:()=>i.open(),onHide:()=>i.close()});let a=this.host.trading.depthLadder;a&&e.addPage({id:`depthLadder`,label:this.host.t(`ladder.title`),icon:`ladder`,element:a.element,parts:[`dock.depthLadder`,`depthLadder`],onShow:()=>a.openPanel(),onHide:()=>a.close()}),this.syncRail(),this.fitDockToWidth(),typeof ResizeObserver<`u`&&(this.dockObserver=new ResizeObserver(()=>this.fitDockToWidth()),this.dockObserver.observe(this.host.root))}fitDockToWidth(){let e=this.dock,t=this.host.root.clientWidth;if(!e||t===0)return;let n=t<641,r=this.dockNarrow;this.dockNarrow=n,n&&r!==!0&&e.close()}railShown(){return this.host.featureState.dock&&!this.host.root.hasAttribute(`data-tcw-narrow`)}syncRail(){this.dock?.syncRail();let e=this.railShown();this.host.toolbar?.setRailed(`watchlist`,e&&this.host.featureState[`dock.watchlist`]),this.host.toolbar?.setRailed(`alerts`,e&&this.host.featureState[`dock.alerts`]),this.host.toolbar?.setRailed(`objects`,e&&this.host.featureState[`dock.objectTree`]),this.host.toolbar?.fit()}panelFocusTarget(e){let t=Is[e],n=t?this.host.root.querySelector(`.tcw-toolbar [data-role="${t}"]`):null,r=this.host.root.hasAttribute(`data-tcw-narrow`);return n&&!n.hidden&&!(r&&n.classList.contains(`tcw-toolbar-overflow`))?n:this.host.root.querySelector(`.tcw-toolbar-more`)??this.host.chartContainer}closePanelByHand(e){this.dock?.closePage(e)}refreshObjects(){if(this.host.refreshDrawingsState(),!this.host.objectTree)return;let e=this.host.chart.getActiveIndicators().map(e=>({instanceId:e.instanceId,name:c.r(e,this.host.t),title:e.descriptor.name,visible:e.visible})),t=this.host.chart.getDrawings().map(e=>({id:e.id,label:e.name||Mr(e.type,this.host.t),visible:e.visible,offInterval:e.visible&&!this.host.chart.isDrawingShown(e.id),locked:e.locked,group:e.group})),n=this.host.comparing.comparedNow().map(e=>({id:e.id,label:(0,u.tickerOf)(e.symbol),color:e.color,way:e.way}));this.host.objectTree.setObjects(e,t,n)}},Rs=new Set([`timezone`,`numberLocale`,`chartTypeOptions`,`logScale`,`autoScale`]),zs=80,Bs=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Vs(e){return L(e,Rs)}function Hs(e){let{overrides:n}=(0,u.readChartStyleOverrides)(e);return Object.fromEntries(Object.entries(n).filter(([e,n])=>n!==null&&t.l.includes(e)))}function Us(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Ws=class{constructor(e=`tcw:chart-templates`,t=Us()){this.key=e,this.storage=t}list(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`[]`)}catch{return[]}if(!Array.isArray(e))return[];let t=[];for(let n of e)!Bs(n)||typeof n.name!=`string`||!n.name.trim()||t.push({name:n.name.slice(0,zs).trim(),settings:Vs(n.settings),style:Hs(n.style)});return t.sort((e,t)=>e.name.localeCompare(t.name))}get(e){return this.list().find(t=>t.name===e)??null}save(e,t,n){let r=e.replace(/\s+/g,` `).slice(0,zs).trim();if(!r||!this.storage)return!1;let i=[...this.list().filter(e=>e.name!==r),{name:r,settings:Vs(t),style:Hs(n)}];try{return this.storage.setItem(this.key,JSON.stringify(i)),!0}catch{return!1}}remove(e){try{this.storage?.setItem(this.key,JSON.stringify(this.list().filter(t=>t.name!==e)))}catch{}}},Gs=new Set([...Br,`autoScale`]),Ks=class{constructor(e){this.host=e}chartTemplates=new Ws;chartTemplatePrompt=null;settingsEdit=null;state=it(t.h);dialogChanging=0;get settingsState(){return this.state.peek()}set settingsState(e){this.state.set(e)}followCrosshairCursor(){return this.state.get().crosshairCursor}settingsDefaults;settingsStore=null;settingsPublished=null;linkSettings=null;settingsListeners=new Set;settingsLocked=new Set;refreshScaleSwitches(){this.host.statusBar?.setScale({mode:this.host.chart.getScaleMode(),auto:this.host.chart.isAutoScale()})}toggleScaleMode(e){this.changeSettings({scaleMode:this.host.chart.getScaleMode()===e?`regular`:e})}showLinkSettings(e){let t=this.getSettings(),n=Object.keys(e),r=this.linkSettings,i={...Object.fromEntries(n.map(e=>[e,t[e]])),...r?.own};this.applySettings(e,!1),this.linkSettings={shown:{...r?.shown,...e},own:i},this.markSettingsTold()}ownSettings(e){let t=this.linkSettings;if(!t)return e;let n=Object.keys(t.shown).filter(n=>JSON.stringify(e[n])===JSON.stringify(t.shown[n]));return{...e,...Object.fromEntries(n.map(e=>[e,t.own[e]]))}}claimSettings(e){let t=this.linkSettings;if(!t)return;let n=new Set(e),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e))),i=r(t.shown);Object.keys(i).length!==Object.keys(t.shown).length&&(this.linkSettings=Object.keys(i).length>0?{shown:i,own:r(t.own)}:null,this.settingsPublished!==null&&!this.host.destroyed&&this.settingsStore?.save(this.ownSettings(this.getSettings()),this.settingsDefaults))}effectiveScaleMode(){return this.host.comparing.holdsPercentScale()?`percentage`:this.settingsState.scaleMode}userScaleMode(){return this.host.comparing.holdsPercentScale()?this.settingsState.scaleMode:this.host.chart.getScaleMode()}shownSettings(){return{...this.settingsState,scaleMode:this.effectiveScaleMode()}}showScaleMode(){let e=this.effectiveScaleMode();this.host.chart.getScaleMode()!==e&&this.host.chart.setScaleMode(e)}openSettings(e){this.host.whenLoaded(this.host.settingsPart,()=>this.host.featureState.settings,t=>this.showSettings(t,e))}showSettings(e,t){e.isOpen()||(this.syncSettingsFromChart(),this.markSettingsTold(),this.settingsEdit={settings:{...this.settingsState},style:this.settingsStyle(),keys:new Set,styleKeys:new Set,held:this.host.comparing.compareScaleHeld},e.open(this.shownSettings(),this.host.state.chartType,t))}endSettingsEdit(e){let t=this.settingsEdit;if(this.settingsEdit=null,!t)return;let n=[...t.keys],r=e=>Object.fromEntries(n.map(t=>[t,e[t]])),i=[...t.styleKeys],a=r(t.settings),o=i.length>0?{theme:t.style.theme,overrides:Object.fromEntries(i.map(e=>[e,t.style.overrides[e]??null]))}:null,s=t.keys.has(`scaleMode`),c=this.host.comparing.compareScaleHeld;if(!e){this.restoreSettings(a,o,s?t.held:void 0);return}let l=r(this.getSettings()),u=i.length>0?this.settingsStyle(i):null;(JSON.stringify([a,o])!==JSON.stringify([l,u])||s&&t.held!==c)&&this.host.chart.recordUndo({undo:()=>this.restoreSettings(a,o,s?t.held:void 0),redo:()=>this.restoreSettings(l,u,s?c:void 0)}),this.claimSettings(n),this.publishSettings()}touchSettings(e,t=[]){if(!this.settingsEdit){this.claimSettings(e);return}for(let t of e)this.settingsEdit.keys.add(t);for(let e of t)this.settingsEdit.styleKeys.add(e)}applyChartTemplate(e){let n=this.chartTemplates.get(e);if(!n)return;let r=this.allowedSettings(n.settings);this.touchSettings(Object.keys(r),t.l),this.applySettings(r),this.host.chart.resetOverrides([...t.l],{layer:`user`}),this.host.chart.applyOverrides(n.style,{layer:`user`}),this.host.settings?.refresh(this.shownSettings()),this.host.say(s.r(this.host.t(`templates.applied`),{name:e}))}promptSaveChartTemplate(){this.chartTemplatePrompt??=new ka(this.host.overlayHost(),this.host.t),this.chartTemplatePrompt.open({title:this.host.t(`settings.saveTemplateTitle`),submitLabel:this.host.t(`common.save`),placeholder:this.host.t(`settings.templatePlaceholder`),onSubmit:e=>{if(!this.chartTemplates.save(e,this.settingsState,this.settingsStyle().overrides))throw this.host.say(this.host.t(`templates.saveFailed`),`error`),Error(`The template could not be saved`);this.host.say(s.r(this.host.t(`templates.saved`),{name:e}))}})}getSettings(){return this.syncSettingsFromChart(),JSON.parse(JSON.stringify(this.settingsState))}setSettings(e){let t=this.allowedSettings(this.withoutEarlyFreeze(L(e)));this.claimSettings(Object.keys(t)),this.applySettings(t)}withoutEarlyFreeze(e){return e.autoScale!==!1||this.host.chart.getData().length>0?e:Object.fromEntries(Object.entries(e).filter(([e])=>e!==`autoScale`))}onSettingsChange(e){return this.settingsListeners.add(e),()=>{this.settingsListeners.delete(e)}}syncSettingsFromChart(){let e=this.host.chart,n=e.getTimeZone?.(),r=e.getMarketProfileConfig?.(),i=e.getPivotMarkersConfig?.(),a=this.allowedSettings(L({gridVisible:e.isGridVisible?.(),volumeVisible:e.isVolumeVisible?.(),legendVisible:e.isLegendVisible?.(),barCountdown:e.isBarCountdownVisible?.(),indicatorValueLabels:e.isIndicatorValueLabelsVisible?.(),alignAxisLabels:e.isAxisLabelsAligned?.(),leftPriceScale:e.isLeftPriceScaleVisible?.(),volumeProfileVisible:e.isVolumeProfileVisible?.(),marketProfileVisible:e.isMarketProfileVisible?.(),marketProfileSplit:r?.splitBySession,marketProfileLetters:r?.letters,marketProfileBuckets:r?.buckets,marketProfileOpacity:r?.opacity,depthHeatmapVisible:e.isDepthHeatmapVisible?.(),depthHeatmapOpacity:e.getDepthHeatmapConfig?.()?.opacity,pivotMarkersVisible:e.isPivotMarkersVisible?.(),pivotStrength:i?.left,pivotStructureLabels:i?.structureLabels,sessionShadingVisible:e.isSessionShadingVisible?.(),periodLevelsVisible:e.isPeriodLevelsVisible?.(),periodLevelsPeriod:e.getPeriodLevelsPeriod?.(),crosshairMode:e.getCrosshairMode?.(),crosshairCursor:e.getCrosshairCursor?.(),scaleMode:this.userScaleMode(),autoScale:e.isAutoScale?.(),invertScale:e.isInvertScale?.(),timezone:n===void 0?void 0:t.b(n),numberLocale:e.getNumberLocale?.(),highLowLines:e.isHighLowLinesVisible?.(),extendedHours:e.isExtendedHoursVisible?.(),mainSeriesVisible:e.isMainSeriesVisible?.(),chartTypeOptions:e.getChartTypeOptions?.()})),o=a.scaleMode?{logScale:a.scaleMode===`logarithmic`}:{},s=a.chartTypeOptions?{chartTypeOptions:qr(a.chartTypeOptions)}:{};this.settingsState={...this.settingsState,...a,...o,...s}}allowedSettings(e){let t=this.settingsLocked,n=(e,n)=>e===`scaleMode`?n===`logarithmic`&&t.has(`logScale`):n===!0&&t.has(e);return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0&&!n(e,t)))}restoreKeptSettings(){let e=this.allowedSettings(this.settingsStore?.load()??{});Object.keys(e).length>0&&this.applySettings(e),this.settingsPublished=JSON.stringify(this.getSettings())}markSettingsTold(){this.settingsPublished!==null&&(this.settingsPublished=JSON.stringify(this.getSettings()))}publishSettings(){if(this.settingsPublished===null||this.host.destroyed)return;let e=this.getSettings(),t=JSON.stringify(e);if(t!==this.settingsPublished){this.settingsPublished=t,this.settingsStore?.save(this.ownSettings(e),this.settingsDefaults);for(let e of[...this.settingsListeners])try{e(JSON.parse(t))}catch(e){console.error(`[TradeCanvas] An onSettingsChange listener threw:`,e)}}}followSettings(){return at(()=>{this.state.get(),!(this.dialogChanging>0)&&this.host.settings?.follow(this.shownSettings())})}changeFromDialog(e){this.dialogChanging++;try{this.changeSettings(e)}finally{this.dialogChanging--}}applySettings(e,t=!0){ot(()=>this.applySettingsNow(e,t))}applySettingsNow(e,n){this.settingsState={...this.settingsState,...e},Object.keys(e).some(e=>!Gs.has(e))&&this.host.layouts.layoutSession?.changed(),this.host.legend.scheduleLegend(),e.gridVisible!==void 0&&this.host.chart.setGridVisible(e.gridVisible),e.volumeVisible!==void 0&&this.host.chart.setVolumeVisible(e.volumeVisible),e.volumeProfileVisible!==void 0&&this.host.chart.setVolumeProfileVisible(e.volumeProfileVisible),e.marketProfileVisible!==void 0&&this.host.chart.setMarketProfileVisible(e.marketProfileVisible),e.marketProfileSplit!==void 0&&this.host.chart.setMarketProfileConfig({splitBySession:e.marketProfileSplit}),e.marketProfileLetters!==void 0&&this.host.chart.setMarketProfileConfig({letters:e.marketProfileLetters}),e.marketProfileBuckets!==void 0&&this.host.chart.setMarketProfileConfig({buckets:e.marketProfileBuckets}),e.marketProfileOpacity!==void 0&&this.host.chart.setMarketProfileConfig({opacity:e.marketProfileOpacity}),e.depthHeatmapVisible!==void 0&&this.host.chart.setDepthHeatmapVisible(e.depthHeatmapVisible),e.depthHeatmapOpacity!==void 0&&this.host.chart.setDepthHeatmapConfig({opacity:e.depthHeatmapOpacity}),e.sessionShadingVisible!==void 0&&this.host.chart.setSessionShadingVisible(e.sessionShadingVisible),e.pivotMarkersVisible!==void 0&&this.host.chart.setPivotMarkersVisible(e.pivotMarkersVisible),e.pivotStrength!==void 0&&this.host.chart.setPivotMarkersConfig({left:e.pivotStrength,right:e.pivotStrength}),e.pivotStructureLabels!==void 0&&this.host.chart.setPivotMarkersConfig({structureLabels:e.pivotStructureLabels}),e.periodLevelsVisible!==void 0&&this.host.chart.setPeriodLevelsVisible(e.periodLevelsVisible),e.periodLevelsPeriod!==void 0&&this.host.chart.setPeriodLevelsPeriod(e.periodLevelsPeriod),e.legendVisible!==void 0&&this.host.chart.setLegend({visible:e.legendVisible}),e.barCountdown!==void 0&&this.host.chart.setBarCountdownVisible(e.barCountdown),e.indicatorValueLabels!==void 0&&this.host.chart.setIndicatorValueLabelsVisible(e.indicatorValueLabels),e.alignAxisLabels!==void 0&&this.host.chart.setAxisLabelsAligned(e.alignAxisLabels),e.crosshairMode!==void 0&&this.host.chart.setCrosshairMode(e.crosshairMode),e.crosshairCursor!==void 0&&this.host.chart.setCrosshairCursor(e.crosshairCursor),e.autoScale!==void 0&&this.host.chart.setAutoScale(e.autoScale),e.invertScale!==void 0&&this.host.chart.setInvertScale(e.invertScale),e.leftPriceScale!==void 0&&(this.host.chart.setLeftPriceScaleVisible(e.leftPriceScale),this.host.placeDrawingButton()),(e.scaleMode!==void 0||e.autoScale!==void 0)&&queueMicrotask(()=>this.refreshScaleSwitches()),e.timezone!==void 0&&queueMicrotask(()=>this.host.statusBar?.tick()),e.scaleMode===void 0?e.logScale!==void 0&&(this.settingsState={...this.settingsState,scaleMode:e.logScale?`logarithmic`:`regular`},this.showScaleMode()):(this.settingsState={...this.settingsState,logScale:e.scaleMode===`logarithmic`},this.showScaleMode()),e.numberLocale!==void 0&&(this.host.chart.setNumberLocale(e.numberLocale),this.host.watching.watchlist?.setLocale(e.numberLocale||void 0)),e.timezone!==void 0&&this.host.chart.setTimeZone(t.v(e.timezone)),e.highLowLines!==void 0&&this.host.chart.setHighLowLines(e.highLowLines),e.extendedHours!==void 0&&this.host.chart.setExtendedHours(e.extendedHours),e.mainSeriesVisible!==void 0&&this.host.chart.setMainSeriesVisible(e.mainSeriesVisible),e.chartTypeOptions!==void 0&&this.host.chart.setChartTypeOptions({...Jr(),...e.chartTypeOptions}),n&&!this.settingsEdit&&this.publishSettings()}resetSettings(){let e={...this.settingsState},n=this.settingsStyle(),r={...this.settingsDefaults};this.touchSettings(Object.keys(r),t.l),this.applySettings(r),this.host.chart.resetOverrides([...t.l],{layer:`user`});let i={...this.settingsState},a=this.settingsStyle();this.host.settings?.refresh(this.shownSettings()),!(this.settingsEdit||JSON.stringify([e,n])===JSON.stringify([i,a]))&&this.host.chart.recordUndo({undo:()=>this.restoreSettings(e,n),redo:()=>this.restoreSettings(i,a)})}changeStyle(e){let t=Object.keys(e);this.touchSettings([],t);let n=this.settingsStyle(t);this.host.chart.applyOverrides(e,{layer:`user`});let r=this.settingsStyle(t);this.settingsEdit||JSON.stringify(n)===JSON.stringify(r)||this.host.chart.recordUndo({subject:`style:${Object.keys(e).sort().join(`,`)}`,undo:()=>this.restoreSettings({},n),redo:()=>this.restoreSettings({},r)})}changeSettings(e){let t=Object.keys(e);if(t.includes(`scaleMode`)||t.includes(`logScale`))for(let e of[`scaleMode`,`logScale`])t.includes(e)||t.push(e);let n=()=>Object.fromEntries(t.map(e=>[e,this.settingsState[e]]));this.touchSettings(t);let r=n(),i=t.includes(`scaleMode`),a=this.host.comparing.compareScaleHeld;i&&(this.host.comparing.compareScaleHeld=!1),this.applySettings(e);let o=n();this.settingsEdit||JSON.stringify(r)===JSON.stringify(o)&&a===this.host.comparing.compareScaleHeld||this.host.chart.recordUndo({subject:`settings:${Object.keys(e).sort().join(`,`)}`,undo:()=>this.restoreSettings(r,null,i?a:void 0),redo:()=>this.restoreSettings(o,null,i?!1:void 0)})}settingsStyle(e=t.l){let n=this.host.chart.getOverrides?.({layer:`user`})??{},r=Object.fromEntries(e.map(e=>{let t=n[e];return[e,typeof t==`string`||typeof t==`boolean`||typeof t==`number`?t:null]}));return{theme:this.host.chart.getTheme()?.name??``,overrides:r}}restoreSettings(e,t=null,n){n!==void 0&&(this.host.comparing.compareScaleHeld=n&&this.host.comparing.compares.length>0),this.applySettings(e),t&&t.theme===(this.host.chart.getTheme()?.name??``)&&this.host.chart.applyOverrides(t.overrides,{layer:`user`}),this.host.settings?.refresh(this.shownSettings())}},qs=13,Js=8,Ys=6,Xs=1.3,Zs=120,Qs=2,$s=8,ec=20;function tc(e){let t=e.filter(e=>e!==null);if(t.length===0)return null;let n=Math.min(...t.map(e=>e.x)),r=Math.min(...t.map(e=>e.y)),i=Math.max(...t.map(e=>e.x+e.width)),a=Math.max(...t.map(e=>e.y+e.height));return{x:n,y:r,width:i-n,height:a-r}}var nc=class{constructor(e){this.host=e}justDrawnText=null;inlineText=null;inlineTextId=null;inlineTextNew=!1;chartFontWritten=null;cancelTextPrompt=null;selectionToolbar=null;selectionToolbarFrame=null;drawingTemplatePrompt=null;scheduleSelectionToolbar(){this.selectionToolbarFrame!==null||!this.selectionToolbar?.isOpen()||(this.selectionToolbarFrame=requestAnimationFrame(()=>{this.selectionToolbarFrame=null,this.updateSelectionToolbar()}))}updateSelectionToolbar(){let e=this.selectionToolbar;if(!e||this.host.destroyed)return;let t=this.host.chart.getSelectedDrawingIds();if(!this.host.featureState.selectionToolbar||!t?.length){e.hide();return}let n=new Set(t),r=this.host.chart.getDrawings().filter(e=>n.has(e.id)&&this.host.chart.isDrawingShown(e.id));if(this.host.chart.getDrawingTool()!==null||this.host.chart.isEraserMode()||this.host.chart.isZoomAreaMode()||r.length===0){e.hide();return}let i=this.host.chartOffset(),a=r[0],o=(a.paneId===void 0?void 0:this.host.chart.getIndicatorPanes().find(e=>e.instanceId===a.paneId)?.rect)??this.host.chart.getPlotRect(),s=this.host.chart.getPlotRect(),c=tc(r.flatMap(e=>[this.host.chart.getDrawingRect(e.id),this.host.chart.getDrawingTextRect?.(e.id)??null]))??{x:o.x+o.width/2,y:o.y,width:0,height:0};e.show({rect:{x:c.x+i.x,y:c.y+i.y,width:c.width,height:c.height},bounds:{x:s.x+i.x,y:s.y+i.y,width:s.width,height:s.height},style:a.style,locked:r.every(e=>e.locked),canDelete:r.some(e=>!e.locked),canSettings:this.host.featureState.drawingSettings&&r.length===1,canAlert:this.host.featureState.alerts&&r.length===1&&this.host.chart.canAddDrawingAlert(a.id),canFill:this.host.chart.getDrawingToolDescriptor(a.type)?.fill===!0,canText:this.host.chart.getDrawingToolDescriptor(a.type)?.text===!0,canType:r.length===1&&this.canTypeText(a.id)})}canTypeText(e){let t=this.host.chart.getDrawings().find(t=>t.id===e);return t!==void 0&&!t.locked&&(B[t.type]!==void 0||Di.has(t.type))}isOnDrawingText(e,t,n){let r=this.host.chart.getDrawingTextRect(e);return r!=null&&t>=r.x-$s&&t<=r.x+r.width+$s&&n>=r.y-$s&&n<=r.y+r.height+$s}editDrawingText(e){this.canTypeText(e)&&(this.editTextInPlace(e,!1)||this.openDrawingSettings(e,{tab:`text`}))}placedTextRect(e,t,n){let r=this.host.chart.getDrawingTextRect(e);if(r){let t=(this.host.chart.getDrawings().find(t=>t.id===e)?.style.text??``).trim(),i=Math.min(ec,t.split(`
|
|
7957
|
+
`)&&this.problemsEl.replaceChildren(...n.map(e=>{let t=document.createElement(`p`);return t.textContent=e,t}));for(let t of[`stopLoss`,`takeProfit`]){let n=this.body.querySelector(`.tcw-ticket-away[data-for="${t}"]`),r=e[t],i=r===null?null:_a(e,this.lastPrice,r,this.rules.multiplier);n&&(n.textContent=i?`${this.signedNumber(i.pct,2)}% · ${this.amount(i.amount)}`:``)}this.renderSummary(e),this.submit.disabled=t.length>0,this.submit.textContent=this.t(e.side===`buy`?`ticket.placeBuy`:`ticket.placeSell`)}renderSummary(e){let t=va(e,this.lastPrice,this.rules),n=t.risk===null?null:this.amount(t.risk),r=t.reward===null?null:this.amount(t.reward),i=[[`value`,`ticket.value`,t.value===null?null:this.money(t.value),null],[`risk`,`ticket.risk`,n,n===null?null:Xi(n)],[`reward`,`ticket.reward`,r,r===null?null:Xi(r)],[`ratio`,`ticket.rewardRisk`,t.ratio===null?null:this.number(t.ratio,2),null]];this.summaryEl.replaceChildren(...i.filter(([,,e])=>e!==null).map(([e,t,n,r])=>{let i=document.createElement(`div`);i.className=`tcw-ticket-summary-row`,i.dataset.row=e;let a=document.createElement(`span`);a.textContent=this.t(t);let o=document.createElement(`span`);return o.className=`tcw-ticket-figure${r?` tcw-ticket-${r}`:``}`,o.dir=`ltr`,o.textContent=n,i.append(a,o),i}))}number(e,t){return this.callbacks.formatNumber?this.callbacks.formatNumber(e,t):e.toFixed(t)}signedNumber(e,t){return W(this.number(Math.abs(e),t),e,this.number(0,t))}amount(e){return W(this.money(Math.abs(e)),e,this.money(0))}money(e){return(this.callbacks.formatAmount??this.callbacks.formatPrice)(e)}problemText(e){let t=this.t(`ticket.problem.${e}`),{limits:n,lot:r}=this.rules;return e===`priceLimits`&&n?s.r(t,{floor:this.callbacks.formatPrice(n.floor),ceiling:this.callbacks.formatPrice(n.ceiling)}):e===`lot`?s.r(t,{lot:r??1}):t}};function Ta(e,t){return t.dataset.ticketField=e,t}function Ea(e){let t=Math.abs(e);return t>0?10**Math.floor(Math.log10(t/100)):1}function Da(e,t){let n=Math.abs(t),r=n>=10||n===0?2:n>=1?4:Math.min(10,Math.ceil(-Math.log10(n))+3);return Number(e.toFixed(r))}var Oa=0,ka=class{backdrop;titleEl;input;submit;request=null;returnFocus=null;busy=!1;uid=++Oa;constructor(e,t=s.t){this.t=t,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let n=!1;this.backdrop.addEventListener(`pointerdown`,e=>{n=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&n&&this.close(),n=!1});let r=document.createElement(`form`);r.className=`tcw-modal tcw-modal-narrow tcw-name-prompt`,r.noValidate=!0,r.setAttribute(`role`,`dialog`),r.setAttribute(`aria-modal`,`true`),r.setAttribute(`aria-labelledby`,`tcw-name-title-${this.uid}`),r.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.stopPropagation(),this.close();return}i.n(e,r)}),r.addEventListener(`submit`,e=>{e.preventDefault(),this.done()});let a=document.createElement(`div`);a.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-name-title-${this.uid}`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=i.i(`x`,16),o.addEventListener(`click`,()=>this.close()),a.append(this.titleEl,o);let c=document.createElement(`div`);c.className=`tcw-modal-body`;let l=document.createElement(`label`);l.className=`tcw-name-field`;let u=document.createElement(`span`);u.textContent=this.t(`layouts.name`),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`tcw-indi-input`,this.input.maxLength=80,this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.placeholder=this.t(`layouts.namePlaceholder`),this.input.addEventListener(`input`,()=>this.check()),l.append(u,this.input),c.appendChild(l);let d=document.createElement(`div`);d.className=`tcw-modal-footer`;let f=document.createElement(`button`);f.type=`button`,f.className=`tcw-reset-link`,f.textContent=this.t(`common.cancel`),f.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`submit`,this.submit.className=`tcw-done-btn`,d.append(f,this.submit),r.append(a,c,d),this.backdrop.appendChild(r),e.appendChild(this.backdrop)}open(e){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.request=e,this.busy=!1,this.titleEl.textContent=e.title,this.submit.textContent=e.submitLabel,this.input.value=e.value??``,this.input.placeholder=e.placeholder??this.t(`layouts.namePlaceholder`),this.check(),this.backdrop.parentElement?.appendChild(this.backdrop),this.backdrop.hidden=!1,this.input.focus(),this.input.select()}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.request=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}destroy(){this.close(),this.backdrop.remove()}check(){this.submit.disabled=this.busy||e.r(this.input.value)===null}async done(){let t=this.request,n=e.r(this.input.value);if(!(!t||n===null||this.busy)){this.busy=!0,this.check();try{await t.onSubmit(n),this.request===t&&this.close()}catch{}finally{this.busy=!1,this.check()}}}},Aa=0,ja=class{el;input;hint;returnFocus=null;constructor(e,t,n){this.labels=t,this.onApply=n,this.el=document.createElement(`div`),this.el.className=`tcw-interval-input`,this.el.hidden=!0,this.el.setAttribute(`role`,`dialog`),this.el.setAttribute(`aria-label`,t.title),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`tcw-interval-field`,this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.maxLength=6,this.input.setAttribute(`aria-label`,t.title),this.hint=document.createElement(`div`),this.hint.className=`tcw-interval-hint`,this.hint.setAttribute(`role`,`status`),this.hint.id=`tcw-interval-hint-${++Aa}`,this.input.setAttribute(`aria-describedby`,this.hint.id),this.el.append(this.input,this.hint),e.appendChild(this.el),this.input.addEventListener(`input`,()=>this.check()),this.input.addEventListener(`keydown`,e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),this.apply()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.close())}),this.input.addEventListener(`blur`,()=>this.close(!1))}open(e){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.el.hidden=!1,this.input.value=e,this.check(),this.input.focus(),this.input.setSelectionRange(e.length,e.length)}close(e=!0){if(this.el.hidden)return;this.el.hidden=!0;let t=this.returnFocus;this.returnFocus=null,e&&t?.isConnected&&t.focus({preventScroll:!0})}isOpen(){return!this.el.hidden}destroy(){this.el.remove()}check(){let e=Ee(this.input.value)!==null;!e&&this.input.value.trim()!==``?this.input.setAttribute(`aria-invalid`,`true`):this.input.removeAttribute(`aria-invalid`),this.hint.textContent=e||this.input.value.trim()===``?this.labels.hint:this.labels.invalid}apply(){let e=Ee(this.input.value);if(e&&this.onApply(e)){this.close();return}this.input.setAttribute(`aria-invalid`,`true`),this.hint.textContent=this.labels.invalid}},Ma=class{constructor(e=`tcw:indicator-templates`){this.key=e}list(){let e;try{e=JSON.parse(localStorage.getItem(this.key)??`[]`)}catch{return[]}if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let{name:e,indicators:r}=n;if(typeof e!=`string`||!e.trim()||!Array.isArray(r))continue;let i=d.ChartStateManager.deserialize(JSON.stringify({version:2,indicators:r})).indicators;i.length>0&&t.push({name:e.slice(0,60),indicators:i})}return t.sort((e,t)=>e.name.localeCompare(t.name))}get(e){return this.list().find(t=>t.name===e)??null}save(e,t){let n=e.replace(/\s+/g,` `).trim().slice(0,60);if(!n)throw Error(`A template needs a name`);let r=[...this.list().filter(e=>e.name!==n),{name:n,indicators:[...t]}];localStorage.setItem(this.key,JSON.stringify(r))}remove(e){try{localStorage.setItem(this.key,JSON.stringify(this.list().filter(t=>t.name!==e)))}catch{}}},Na=[`regular`,`logarithmic`,`percentage`,`indexedTo100`],Pa=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Fa(e){let{theme:t,timestamp:n,...r}=e;return r}function Ia(e){return!Pa(e)||e.v!==1||typeof e.symbol!=`string`||!e.symbol||typeof e.timeframe!=`string`||!((0,u.isTimeFrame)(e.timeframe)||(0,u.tickBarCount)(e.timeframe)!==null)?null:{v:1,symbol:e.symbol,timeframe:e.timeframe,scaleMode:Na.find(t=>t===e.scaleMode)??`regular`,invertScale:e.invertScale===!0,chart:Pa(e.chart)?Fa(e.chart):null,...Pa(e.settings)?{settings:L(e.settings,Hr)}:{}}}function La(e){try{return JSON.parse(e)}catch{return null}}function Ra(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var za=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=Ra()){this.storageKey=e,this.storage=t,this.load()}list(){return[...this.favorites]}has(e){return this.favorites.includes(e)}add(e){!e||this.favorites.includes(e)||(this.favorites=[...this.favorites,e],this.persist())}remove(e){this.favorites.includes(e)&&(this.favorites=this.favorites.filter(t=>t!==e),this.persist())}toggle(e){return this.has(e)?(this.remove(e),!1):(this.add(e),!0)}seedDefaults(e){this.favorites.length>0||(this.favorites=[...new Set(e.filter(Boolean))],this.persist())}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&(this.favorites=[...new Set(t.filter(e=>typeof e==`string`))])}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.favorites))}catch{}}};function Ba(e){let t=typeof window<`u`?window.visualViewport:null;if(!t)return()=>{};let n=-1,r=()=>{let r=(t.scale??1)>1.01?0:Math.max(0,Math.round(window.innerHeight-t.height-t.offsetTop));if(r!==n){n=r;for(let t of e)t.style.setProperty(`--tcw-keyboard-inset`,`${r}px`)}};return r(),t.addEventListener(`resize`,r),t.addEventListener(`scroll`,r),()=>{t.removeEventListener(`resize`,r),t.removeEventListener(`scroll`,r)}}function Va(e,t){let n=null,r=()=>{let r=e.clientWidth;if(r===0&&n!==null)return;let i=r<641;i!==n&&(n=i,e.toggleAttribute(`data-tcw-narrow`,i),t?.(i))};if(r(),typeof ResizeObserver>`u`)return()=>{};let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()}function q(e){let t=null,n=null;return{get:()=>t,load(){return t?Promise.resolve(t):(n??=e().then(e=>(t=e,n=null,e),e=>{throw n=null,e}),n)}}}var Ha=class{part=null;loading=null;gone=!1;constructor(e,t,n,r=()=>{}){this.module=e,this.build=t,this.dispose=n,this.onError=r}get(){return this.part}now(){let e=this.module.get();return!this.part&&!this.gone&&e&&(this.part=this.build(e)),this.part}isLoading(){return this.loading!==null}load(){if(this.gone)return Promise.resolve(null);let e=this.now();return e?Promise.resolve(e):(this.loading??=this.module.load().then(()=>(this.loading=null,this.now()),e=>(this.loading=null,this.gone||this.onError(e instanceof Error?e:Error(String(e))),null)),this.loading)}destroy(){this.gone=!0,this.part&&this.dispose(this.part),this.part=null}},J={settings:q(()=>Promise.resolve().then(()=>require(`../WidgetSettings-CBf6hUSV.cjs`))),indicatorSettings:q(()=>Promise.resolve().then(()=>require(`../WidgetIndicatorSettings-CBHWj5z5.cjs`))),drawingSettings:q(()=>Promise.resolve().then(()=>require(`../WidgetDrawingSettings-DutEdVyV.cjs`))),goToDate:q(()=>Promise.resolve().then(()=>require(`../WidgetGoToDate-hNVxz-Zb.cjs`))),hotkeySheet:q(()=>Promise.resolve().then(()=>require(`../WidgetHotkeySheet-y5LWKSG6.cjs`))),indicatorPicker:q(()=>Promise.resolve().then(()=>require(`../WidgetIndicatorPicker-GCesxFMn.cjs`))),commandPalette:q(()=>Promise.resolve().then(()=>require(`../WidgetCommandPalette-CZ3GhE1O.cjs`))),symbolSearch:q(()=>Promise.resolve().then(()=>require(`../WidgetSymbolSearch-CxeLjy63.cjs`)))};async function Ua(){await Promise.all(Object.values(J).map(e=>e.load().catch(()=>null)))}var Wa=/^(\d{4})-(\d{2})-(\d{2})$/,Ga=/^(\d{2}):(\d{2})$/;function Ka(e,t,n){let r=Wa.exec(e),i=t?Ga.exec(t):[``,`00`,`00`];if(!r||!i)return null;let[a,o,s,c,l]=[+r[1],+r[2],+r[3],+i[1],+i[2]];if(o<1||o>12||s<1||s>31||c>23||l>59)return null;let d=Date.UTC(a,o-1,s,c,l);return new Date(d).getUTCDate()===s?(0,u.wallToUtc)(d,n):null}function Y(e,t){let n=e=>String(e).padStart(2,`0`),r=(0,u.timeParts)(e,t);return{date:`${r.year}-${n(r.month)}-${n(r.day)}`,time:`${n(r.hours)}:${n(r.minutes)}`}}var X={min:233,default:262,max:377},qa=.382,Ja=e=>!e.hidden&&getComputedStyle(e).display!==`none`,Ya=class{element;panel;rail;handle;pages=new Map;open_=null;width;scale=1;drag=null;observer=null;onMove=e=>{!this.drag||!this.samePointer(e)||this.setWidth(this.drag.width+(this.drag.x-e.clientX)*this.drag.dir)};onUp=e=>{!this.drag||!this.samePointer(e)||(this.drag=null,this.stopDrag(),this.options.saveWidth?.(this.width))};constructor(e,t){this.options=t;let n=document.createElement(`div`);n.className=`tcw-dock`;let i=document.createElement(`div`);i.className=`tcw-dock-panel`,i.hidden=!0,i.addEventListener(`keydown`,e=>this.onPanelKey(e));let a=document.createElement(`div`);a.className=`tcw-dock-resize`,a.setAttribute(`role`,`separator`),a.setAttribute(`aria-orientation`,`vertical`),a.setAttribute(`aria-label`,t.labels.resize),a.setAttribute(`aria-valuemin`,String(X.min)),a.tabIndex=0,a.addEventListener(`pointerdown`,e=>this.startDrag(e)),a.addEventListener(`keydown`,e=>this.onHandleKey(e)),i.appendChild(a);let o=document.createElement(`div`);o.className=`tcw-dock-rail`,o.setAttribute(`role`,`toolbar`),o.setAttribute(`aria-orientation`,`vertical`),o.setAttribute(`aria-label`,t.labels.rail),r.o(o,`dock`),o.addEventListener(`keydown`,e=>this.onRailKey(e)),n.append(i,o),e.appendChild(n),this.element=n,this.panel=i,this.rail=o,this.handle=a,this.width=Math.min(X.max,Math.max(X.min,t.savedWidth?.()??X.default)),this.applyWidth(),t.room&&typeof ResizeObserver<`u`&&(this.observer=new ResizeObserver(()=>this.fit()),this.observer.observe(e))}addPage(e){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-dock-btn`,t.dataset.page=e.id,t.title=e.label,t.setAttribute(`aria-label`,e.label),t.setAttribute(`aria-pressed`,`false`),t.tabIndex=-1,t.innerHTML=i.i(e.icon,18),e.parts?.length&&r.o(t,...e.parts),t.addEventListener(`click`,()=>{this.toggle(e.id)}),t.addEventListener(`focus`,()=>this.rove(t)),this.rail.appendChild(t),e.element.hidden=!0,e.element.classList.add(`tcw-dock-page`),this.panel.appendChild(e.element),this.pages.set(e.id,{page:e,button:t}),this.syncRail()}open(e){let t=this.pages.get(e);!t||this.open_===e||(this.hideCurrent(),this.open_=e,this.panel.hidden=!1,t.page.element.hidden=!1,t.button.setAttribute(`aria-pressed`,`true`),this.fit(),t.page.onShow?.(),this.options.onChange?.(e))}close(){let e=this.open_;if(e===null)return;let t=this.panel.contains(document.activeElement);if(this.hideCurrent(),this.panel.hidden=!0,t){let t=this.pages.get(e)?.button;(t&&(this.options.railShown?.()??!0)&&Ja(t)?t:this.options.focusAfterClose?.(e))?.focus()}this.options.onChange?.(null)}toggle(e){this.open_===e?this.close():this.open(e)}closePage(e){this.open_===e&&this.close()}current(){return this.open_}isOpen(e){return this.open_===e}syncRail(){let e=[...this.pages.values()].map(e=>e.button),t=e.filter(Ja),n=e.find(e=>e.tabIndex===0);if(n&&t.includes(n))return;let r=t.find(e=>e.getAttribute(`aria-pressed`)===`true`)??t[0];for(let t of e)t.tabIndex=t===r?0:-1}fit(){this.applyWidth()}destroy(){this.drag=null,this.stopDrag(),this.observer?.disconnect(),this.element.remove()}hideCurrent(){let e=this.open_===null?null:this.pages.get(this.open_);this.open_=null,e&&(e.page.element.hidden=!0,e.button.setAttribute(`aria-pressed`,`false`),e.page.onHide?.())}setScale(e){let t=Number.isFinite(e)&&e>0?e:1;t!==this.scale&&(this.scale=t,this.handle.setAttribute(`aria-valuemin`,String(this.min())),this.applyWidth())}min(){return Math.round(X.min*this.scale)}maxNow(){let e=this.options.room?.()??0,t=Math.round(X.max*this.scale);return e<=0?t:Math.max(this.min(),Math.min(t,Math.floor(e*qa)))}clamp(e,t=this.maxNow()){return Math.round(Math.min(t,Math.max(this.min(),e)))}shownWidth(){return this.clamp(this.width*this.scale)}setWidth(e){this.width=Math.round(this.clamp(e)/this.scale*100)/100,this.applyWidth()}applyWidth(){let e=this.shownWidth();this.element.style.setProperty(`--tcw-dock-w`,`${e}px`),this.handle.setAttribute(`aria-valuemax`,String(this.maxNow())),this.handle.setAttribute(`aria-valuenow`,String(e))}samePointer(e){let t=e.pointerId;return this.drag?.pointer===void 0||t===void 0||t===this.drag.pointer}startDrag(e){if(e.button!==0)return;e.preventDefault();let t=getComputedStyle(this.element).direction===`rtl`||this.element.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`;this.drag={x:e.clientX,width:this.shownWidth(),dir:t?-1:1,pointer:e.pointerId},document.addEventListener(`pointermove`,this.onMove),document.addEventListener(`pointerup`,this.onUp),document.addEventListener(`pointercancel`,this.onUp)}stopDrag(){document.removeEventListener(`pointermove`,this.onMove),document.removeEventListener(`pointerup`,this.onUp),document.removeEventListener(`pointercancel`,this.onUp)}onHandleKey(e){let[t,n]=this.element.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?[`ArrowRight`,`ArrowLeft`]:[`ArrowLeft`,`ArrowRight`],r=this.shownWidth(),i=e.key===t?r+13:e.key===n?r-13:e.key===`Home`?this.min():e.key===`End`?this.maxNow():null;i!==null&&(e.preventDefault(),this.setWidth(i),this.options.saveWidth?.(this.width))}onPanelKey(e){e.key!==`Escape`||e.defaultPrevented||!this.element.closest(`[data-tcw-narrow]`)||(e.preventDefault(),e.stopPropagation(),this.close())}rove(e){for(let{button:t}of this.pages.values())t.tabIndex=t===e?0:-1}onRailKey(e){let t=[...this.pages.values()].map(e=>e.button).filter(Ja),n=t.indexOf(e.target);if(n<0)return;let r=e.key===`ArrowDown`?(n+1)%t.length:e.key===`ArrowUp`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),t[r].focus())}},Xa=[`percent`,`scale`,`pane`,`spread`,`ratio`,`correlation`,`correlationLog`],Za={percent:`compare.percent`,scale:`compare.ownScale`,pane:`compare.ownPane`,spread:`compare.way.spread`,ratio:`compare.way.ratio`,correlation:`compare.way.correlation`,correlationLog:`compare.way.correlationLog`};function Qa(e){return Xa.includes(e)}function $a(e){return Xa.map(t=>({id:t,label:e(Za[t])}))}function eo(e,t){let n=e.findIndex(e=>e.time>=t);return n<0?e.length:n}function to(e,t){let n=e[0]?.time??1/0,r=t.filter(e=>e.time<n);return r.length>0?[...r,...e]:null}function no(e,t){switch(e.id){case`compareSymbol`:return t?`pane`:`scale`;case`compareSymbolPane`:return`pane`;case`spread`:return e.params.mode===`ratio`?`ratio`:`spread`;case`correlation`:return`correlation`;case`correlationlog`:return`correlationLog`;default:return null}}function ro(e,t,n,r){let i=e.map(e=>({id:e.id,symbol:e.symbol,way:r(Za.percent),color:e.color}));for(let e of t){let t=e.params.symbol,a=no(e,n.has(e.instanceId));!a||typeof t!=`string`||!t||i.push({id:e.instanceId,symbol:t,way:r(Za[a])})}return i}var Z=8,io=4,ao=3,oo=`[title]:not([title=""]), [data-tip]:not([data-tip=""])`,so=class{el;target=null;source=null;pressed=null;showTimer=null;watchFrame=0;warmUntil=0;observer;constructor(e){this.root=e,this.el=document.createElement(`div`),this.el.className=`tcw-tooltip`,this.el.setAttribute(`aria-hidden`,`true`),e.appendChild(this.el),e.addEventListener(`pointerover`,this.onOver),e.addEventListener(`pointerout`,this.onOut),e.addEventListener(`pointerdown`,this.onPress,!0),e.addEventListener(`keydown`,this.onPress,!0),e.addEventListener(`focusin`,this.onFocus),e.addEventListener(`focusout`,this.onBlur),e.addEventListener(`wheel`,this.hide,{passive:!0}),this.observer=new MutationObserver(()=>{this.pressed?.hasAttribute(`title`)&&co(this.pressed);let e=this.target;!e||this.source!==`pointer`||!e.hasAttribute(`title`)||(co(e),this.isVisible()&&this.show(e))}),this.observer.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`title`]})}destroy(){this.hide(),this.pressed&&Q(this.pressed),this.observer.disconnect(),this.root.removeEventListener(`pointerover`,this.onOver),this.root.removeEventListener(`pointerout`,this.onOut),this.root.removeEventListener(`pointerdown`,this.onPress,!0),this.root.removeEventListener(`keydown`,this.onPress,!0),this.root.removeEventListener(`focusin`,this.onFocus),this.root.removeEventListener(`focusout`,this.onBlur),this.root.removeEventListener(`wheel`,this.hide),this.el.remove()}onOver=e=>{if(e.pointerType===`touch`)return;let t=this.tipTarget(e.target);!t||t===this.pressed||t===this.target&&this.source===`pointer`||(co(t),this.schedule(t,`pointer`,Date.now()<this.warmUntil||this.isVisible()))};onOut=e=>{let t=e.relatedTarget,n=e=>!!e&&!!t&&e.contains(t);this.pressed&&!n(this.pressed)&&(Q(this.pressed),this.pressed=null),this.source===`pointer`&&!n(this.target)&&this.hide()};onPress=()=>{let e=this.target,t=this.source===`pointer`;this.warmUntil=0,this.clearTimer(),cancelAnimationFrame(this.watchFrame),this.el.classList.remove(`tcw-tooltip--visible`),this.target=null,this.source=null,this.pressed&&this.pressed!==e&&Q(this.pressed),this.pressed=t?e:null};onFocus=e=>{let t=this.tipTarget(e.target);!t||!fo(t)||t===this.pressed||this.schedule(t,`focus`,!0)};onBlur=e=>{if(this.source!==`focus`)return;let t=e.relatedTarget;this.target&&t&&this.target.contains(t)||this.hide()};hide=()=>{this.clearTimer(),cancelAnimationFrame(this.watchFrame),this.isVisible()&&(this.warmUntil=Date.now()+500),this.el.classList.remove(`tcw-tooltip--visible`),this.target&&this.source===`pointer`&&Q(this.target),this.target=null,this.source=null};tipTarget(e){if(!(e instanceof Element))return null;let t=e.closest(oo);return t&&t!==this.el&&this.root.contains(t)?t:null}schedule(e,t,n){let r=this.target;if(this.clearTimer(),cancelAnimationFrame(this.watchFrame),r&&r!==e&&this.source===`pointer`&&Q(r),this.target=e,this.source=t,n){this.show(e);return}this.el.classList.remove(`tcw-tooltip--visible`),this.showTimer=setTimeout(()=>{this.showTimer=null,this.target===e&&this.show(e)},300)}show(e){if(!uo(e)){this.hide();return}this.el.textContent=lo(e),this.place(e),this.el.classList.add(`tcw-tooltip--visible`),this.watch(e)}watch(e){cancelAnimationFrame(this.watchFrame),this.watchFrame=requestAnimationFrame(()=>{this.target===e&&(uo(e)?this.watch(e):this.hide())})}place(e){let t=this.root.getBoundingClientRect(),n=e.getBoundingClientRect(),r=this.el.offsetWidth,i=this.el.offsetHeight,a=n.left-t.left,o=n.top-t.top,s=po(e);s===`bottom`&&o+n.height+Z+i>t.height?s=`top`:s===`top`&&o-Z-i<0?s=`bottom`:s===`right`&&a+n.width+Z+r>t.width&&(s=`left`);let c,l;s===`top`||s===`bottom`?(c=a+n.width/2-r/2,l=s===`bottom`?o+n.height+Z:o-Z-i):(c=s===`right`?a+n.width+Z:a-Z-r,l=o+n.height/2-i/2),c=Math.max(io,Math.min(t.width-r-io,c)),l=Math.max(io,Math.min(t.height-i-io,l)),this.el.style.left=`${Math.round(c)}px`,this.el.style.top=`${Math.round(l)}px`;let u={top:[0,ao],bottom:[0,-ao],left:[ao,0],right:[-ao,0]}[s];this.el.style.setProperty(`--tcw-tip-dx`,`${u[0]}px`),this.el.style.setProperty(`--tcw-tip-dy`,`${u[1]}px`),this.el.dataset.side=s}isVisible(){return this.el.classList.contains(`tcw-tooltip--visible`)}clearTimer(){this.showTimer!==null&&(clearTimeout(this.showTimer),this.showTimer=null)}};function co(e){let t=e.getAttribute(`title`);t!==null&&(e.dataset.tip=t,e.removeAttribute(`title`))}function Q(e){e.dataset.tip!==void 0&&!e.hasAttribute(`title`)&&(e.setAttribute(`title`,e.dataset.tip),delete e.dataset.tip)}function lo(e){return e.dataset.tip??e.getAttribute(`title`)??``}function uo(e){return e.isConnected&&e.getClientRects().length>0&&!e.disabled}function fo(e){try{return e.matches(`:focus-visible`)}catch{return!1}}function po(e){return e.dataset.tipSide||(e.closest(`.tcw-sidebar`)?`right`:e.closest(`.tcw-statusbar, .tcw-replay-bar`)?`top`:`bottom`)}var mo=2,ho=1.5,go=`tcw-ind-legend-values--no-room`,_o=0,vo=class{stack;toggle;rows=new Map;panes=new Map;collapsed=!1;toggleKey=``;stackKey=``;valuesObserver;stackObserver;constructor(e,t,n){this.host=e,this.callbacks=t,this.labels=n,this.stack=document.createElement(`div`),this.stack.className=`tcw-ind-legend`,r.o(this.stack,`indicatorLegend`),this.toggle=document.createElement(`button`),this.toggle.type=`button`,this.toggle.className=`tcw-ind-legend-toggle`,this.toggle.addEventListener(`click`,()=>{this.setCollapsed(!this.collapsed),this.renderToggle(this.overlayCount())}),this.stack.appendChild(this.toggle),e.appendChild(this.stack),this.stackObserver=typeof ResizeObserver>`u`||!t.onStackResize?null:new ResizeObserver(()=>this.reportStackSize()),this.stackObserver?.observe(this.stack),this.valuesObserver=typeof ResizeObserver>`u`?null:new ResizeObserver(e=>{for(let t of e)yo(t.target,t.contentRect.width)})}update(e,t,n=[]){this.updatePanes(n);let r=`${Math.round(t.left)},${Math.round(t.top)}`;r!==this.stackKey&&(this.stackKey=r,this.stack.style.left=`${Math.round(t.left)}px`,this.stack.style.top=`${Math.round(t.top)}px`);let i=new Set(e.map(e=>e.instanceId));for(let[e,t]of this.rows)i.has(e)||(this.valuesObserver?.unobserve(t.values),t.el.remove(),this.rows.delete(e));let a=!1,o=null;for(let t of e){let e=this.rows.get(t.instanceId)??this.createRow(t.instanceId,t.kind);if(this.fill(e,t),t.pane)e.el.parentElement!==this.host&&this.host.appendChild(e.el);else{let t=o?o.nextElementSibling:this.stack.firstElementChild;e.el.parentElement!==this.stack&&(a=!0),e.el!==t&&this.stack.insertBefore(e.el,t),o=e.el}this.place(e,t.pane)}a&&this.collapsed&&this.setCollapsed(!1),this.renderToggle(e.filter(e=>!e.pane).length)}destroy(){this.valuesObserver?.disconnect(),this.stackObserver?.disconnect();for(let e of this.rows.values())e.el.remove();this.rows.clear();for(let e of this.panes.values())e.el.remove();this.panes.clear(),this.stack.remove()}reportStackSize(){let e=this.stack.offsetWidth,t=this.stack.offsetHeight;this.callbacks.onStackResize?.(e>0&&t>0?{width:e,height:t}:null)}updatePanes(e){if(!this.callbacks.onPaneAction)return;let t=new Set;for(let n of e){t.add(n.instanceId);let e=this.panes.get(n.instanceId)??this.createPane(n.instanceId),r=`${Math.round(n.x)},${Math.round(n.y)}|${n.label}|${n.collapsed}|${n.maximized}|${n.canMoveUp}|${n.canMoveDown}`;if(r===e.key)continue;e.key=r,e.el.style.left=`${Math.round(n.x)}px`,e.el.style.top=`${Math.round(n.y)}px`;let a=this.labels,o=(t,r,a,o)=>{let s=e.buttons.get(t);!r&&document.activeElement===s&&e.buttons.get(`max`).focus(),s.hidden=!r,s.innerHTML=i.i(a,12),$(s,o??t,n.label)};o(`up`,n.canMoveUp&&!n.maximized,`arrowUp`,a.paneUp),o(`down`,n.canMoveDown&&!n.maximized,`arrowDown`,a.paneDown),o(`fold`,!n.maximized,n.collapsed?`chevronDown`:`chevronUp`,n.collapsed?a.paneExpand:a.paneCollapse),o(`max`,!0,n.maximized?`minimize`:`maximize`,n.maximized?a.paneRestore:a.paneMaximize),e.el.dataset.collapsed=String(n.collapsed),e.el.dataset.maximized=String(n.maximized)}for(let[e,n]of this.panes)t.has(e)||(n.el.remove(),this.panes.delete(e))}createPane(e){let t=document.createElement(`div`);t.className=`tcw-pane-controls`,r.o(t,`indicatorLegend`),t.dataset.instance=e;let n=new Map,i=e=>e===`up`||e===`down`?e:e===`fold`?t.dataset.collapsed===`true`?`expand`:`collapse`:t.dataset.maximized===`true`?`restore`:`maximize`,a={up:`pane.move`,down:`pane.move`,fold:`pane.collapse`,max:`pane.maximize`};for(let o of[`up`,`down`,`fold`,`max`]){let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-pane-btn`,s.dataset.act=o,r.o(s,a[o]),s.addEventListener(`click`,()=>this.callbacks.onPaneAction?.(e,i(o))),n.set(o,s),t.appendChild(s)}this.host.appendChild(t);let o={el:t,buttons:n,key:``};return this.panes.set(e,o),o}createRow(e,t){let n=t===`compare`,a=document.createElement(`div`);a.className=n?`tcw-ind-legend-row tcw-ind-legend-row--compare`:`tcw-ind-legend-row`,r.o(a,`indicatorLegend`),a.dataset.instance=e;let o=document.createElement(n?`span`:`button`);o.className=`tcw-ind-legend-name`,o instanceof HTMLButtonElement&&(o.type=`button`,o.addEventListener(`click`,()=>this.callbacks.onSettings(e)));let s=document.createElement(`span`);s.className=`tcw-ind-legend-values`,r.o(s,`indicatorLegend.values`),this.valuesObserver?.observe(s);let c=document.createElement(`span`);c.className=`tcw-ind-legend-actions`;let l=(e,t,n,...a)=>{let o=document.createElement(`button`);return o.type=`button`,o.className=`tcw-ind-legend-act`,o.dataset.act=e,r.o(o,...a),o.innerHTML=i.i(t,13),o.addEventListener(`click`,n),c.appendChild(o),o},u=l(`visible`,`eye`,()=>{this.callbacks.onToggleVisible(e,!g.visible,t)},`indicatorLegend.visibility`),d=n?null:l(`settings`,`settings`,()=>this.callbacks.onSettings(e),`indicatorSettings`,`indicatorLegend.settings`),f=this.callbacks.onMore&&!n?l(`more`,`more`,()=>this.callbacks.onMore?.(e,f),`indicatorLegend.more`):null,p=l(`remove`,`x`,()=>this.callbacks.onRemove(e,t),`indicatorLegend.remove`),m=document.createElement(`span`);m.className=`tcw-visually-hidden`,m.id=`tcw-ind-note-${++_o}`;let h=n?document.createElement(`span`):null;h&&(h.className=`tcw-ind-legend-swatch`,h.setAttribute(`aria-hidden`,`true`),a.append(h)),a.append(o,s,c,m);let g={el:a,name:o,swatch:h,values:s,eye:u,settings:d,more:f,remove:p,note:m,visible:!0,valuesKey:``,state:``,placeKey:``};return this.rows.set(e,g),g}fill(e,t){let n=this.offNote(t),r=`${t.label}|${t.visible}|${n}|${t.swatch??``}`;r!==e.state&&(e.state=r,e.swatch&&(e.swatch.style.backgroundColor=t.swatch??``),e.visible=t.visible,e.name.textContent=t.label,e.settings&&(e.name.title=this.labels.settings),e.el.classList.toggle(`tcw-ind-legend-row--hidden`,!t.visible||n!==null),n?e.el.title=n:e.el.removeAttribute(`title`),this.describe(e,n),e.eye.innerHTML=i.i(t.visible?`eye`:`eyeOff`,13),$(e.eye,t.visible?this.labels.hide:this.labels.show,t.label),e.settings&&$(e.settings,this.labels.settings,t.label),e.more&&($(e.more,this.labels.more??`More`,t.label),e.more.setAttribute(`aria-haspopup`,`menu`)),$(e.remove,this.labels.remove,t.label));let a=t.values.map(e=>`${e.text}${e.color??``}`).join(``);a!==e.valuesKey&&(e.valuesKey=a,e.values.replaceChildren(...t.values.map(e=>{let t=document.createElement(`span`);return t.textContent=e.text,e.color&&(t.style.color=e.color),t})))}describe(e,t){e.note.textContent=t??``;let n=[e.name,e.eye,e.settings,e.more,e.remove].filter(e=>e instanceof HTMLButtonElement);for(let r of n)t?r.setAttribute(`aria-describedby`,e.note.id):r.removeAttribute(`aria-describedby`)}offNote(e){return e.offInterval?this.labels.offInterval??``:e.offChartType?this.labels.offChartType??``:null}place(e,t){let n=t?`${Math.round(t.x)},${Math.round(t.y)},${Math.round(t.width)}`:``;n!==e.placeKey&&(e.placeKey=n,e.el.classList.toggle(`tcw-ind-legend-row--pane`,t!==null),e.el.style.left=t?`${Math.round(t.x)}px`:``,e.el.style.top=t?`${Math.round(t.y)}px`:``,e.el.style.maxWidth=t?`${Math.max(0,Math.round(t.width))}px`:``)}setCollapsed(e){this.collapsed=e,this.stack.classList.toggle(`tcw-ind-legend--collapsed`,e)}overlayCount(){return this.stack.querySelectorAll(`:scope > .tcw-ind-legend-row`).length}renderToggle(e){let t=e>=mo;!t&&this.collapsed&&this.setCollapsed(!1);let n=`${t}|${this.collapsed}|${e}`;if(n===this.toggleKey||(this.toggleKey=n,this.toggle.hidden=!t,!t))return;let r=this.collapsed?this.labels.expand:this.labels.collapse;$(this.toggle,r,this.collapsed?`(${e})`:void 0),this.toggle.setAttribute(`aria-expanded`,String(!this.collapsed));let a=i.i(this.collapsed?`chevronDown`:`chevronUp`,12);this.toggle.innerHTML=this.collapsed?`${a}<span>${e}</span>`:a}};function yo(e,t){let n=(parseFloat(getComputedStyle(e).fontSize)||0)*ho;e.classList.toggle(go,t<n)}function $(e,t,n){e.title=t,e.setAttribute(`aria-label`,n?`${t} ${n}`:t)}function bo(e,t){return!e||e.length===0?null:e[t===null?e.length-1:Math.min(Math.max(t,0),e.length-1)]??null}function xo(e,t,n,r){if(!t)return[];let i=e.plots;if(!i){let e=[];for(let n in t){let r=t[n];typeof r==`number`&&Number.isFinite(r)&&e.push(r)}let r=e.length===1?n[0]??null:null;return e.map(e=>({value:e,color:r}))}let a={colors:[...n],lineWidths:[],opacity:1},o=[];for(let e of i){if(!(0,d.plotShown)(e,{plots:r}))continue;let i=t[e.key];typeof i!=`number`||!Number.isFinite(i)||o.push({value:i,color:n.length?(0,d.plotColor)(e,a,t):null})}return o}var So=new Map;function Co(e){let t=So.get(e);return t||(t=new Intl.NumberFormat(e,{notation:`compact`,maximumFractionDigits:2}),So.set(e,t)),t}function wo(e,t=`en-US`){return Math.abs(e)>=1e6?Co(t).format(e):(0,u.formatPrice)(e,(0,d.indicatorValuePrecision)(e),t)}var To=class{el;labelEl;callbacks;visible=!1;constructor(e,t,n=s.t){this.t=n,this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-bracket-bar`,this.el.setAttribute(`role`,`group`),this.el.hidden=!0,this.labelEl=document.createElement(`span`),this.labelEl.className=`tcw-bracket-label`,this.el.appendChild(this.labelEl);let r=document.createElement(`span`);r.className=`tcw-bracket-hint`,r.textContent=this.t(`bracket.hint`),this.el.appendChild(r);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-bracket-cancel`,o.innerHTML=`${i.i(`x`,14)}<span>${a.u(this.t(`common.cancel`))}</span>`,o.addEventListener(`click`,()=>this.callbacks.onCancel());let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-bracket-confirm`,c.innerHTML=`${i.i(`check`,14)}<span>${a.u(this.t(`bracket.place`))}</span>`,c.addEventListener(`click`,()=>this.callbacks.onConfirm()),this.el.appendChild(o),this.el.appendChild(c),e.appendChild(this.el)}show(e){this.visible=!0;let t=e===`buy`?this.t(`toolbar.longBracket`):this.t(`toolbar.shortBracket`);this.labelEl.textContent=t,this.el.setAttribute(`aria-label`,t),this.el.dataset.side=e,this.el.dir=this.el.closest(`.tcw-root`)?.dir||`auto`,this.el.hidden=!1}hide(){this.visible=!1,this.el.hidden=!0}isVisible(){return this.visible}destroy(){this.el.remove()}},Eo=class{options;audioCtx=null;audioEl=null;permissionAsked=!1;constructor(e={}){if(this.options=e,typeof e.sound==`string`)try{this.audioEl=new Audio(e.sound),this.audioEl.preload=`auto`}catch{this.audioEl=null}e.desktop&&this.ensurePermission()}setOptions(e){this.options={...this.options,...e}}notify(e){this.options.sound&&this.playSound(),this.options.desktop&&this.showDesktop(e)}playSound(){if(this.audioEl){this.audioEl.currentTime=0,this.audioEl.play().catch(()=>{});return}this.beep()}beep(){try{let e=window.AudioContext??window.webkitAudioContext;if(!e)return;this.audioCtx||=new e;let t=this.audioCtx,n=t.currentTime,r=t.createGain();r.gain.setValueAtTime(1e-4,n),r.gain.exponentialRampToValueAtTime(.2,n+.01),r.gain.exponentialRampToValueAtTime(1e-4,n+.35),r.connect(t.destination);let i=t.createOscillator();i.type=`sine`,i.frequency.setValueAtTime(880,n),i.frequency.setValueAtTime(1320,n+.16),i.connect(r),i.start(n),i.stop(n+.36)}catch{}}ensurePermission(){this.permissionAsked||(this.permissionAsked=!0,!(typeof Notification>`u`)&&Notification.permission===`default`&&Notification.requestPermission().catch(()=>{}))}showDesktop(e){if(!(typeof Notification>`u`)){if(Notification.permission!==`granted`){this.ensurePermission();return}try{new Notification(this.options.title??`Price alert`,{body:e})}catch{}}}destroy(){try{this.audioCtx?.close()}catch{}this.audioCtx=null,this.audioEl=null}};function Do(e,t=12){let n=[...e.asks].sort((e,t)=>e.price-t.price).slice(0,t),r=[...e.bids].sort((e,t)=>t.price-e.price).slice(0,t),i=n.length>0?n[0].price:null,a=r.length>0?r[0].price:null,o=i!==null&&a!==null?(i+a)/2:null,s=new Map,c=e=>{let t=s.get(e);return t||(t={price:e,bidVolume:0,askVolume:0},s.set(e,t)),t};for(let e of n)c(e.price).askVolume+=e.volume;for(let e of r)c(e.price).bidVolume+=e.volume;let l=[...s.values()].sort((e,t)=>t.price-e.price),u=0;for(let e of l)u=Math.max(u,e.bidVolume,e.askVolume);return{rows:l,maxVolume:u,mid:o,spread:i!==null&&a!==null?i-a:null,bestBid:a}}var Oo=1e-9,ko=class{el;colsEl;bodyEl;callbacks;open=!1;levels;model=null;orders=[];drawn=[];spreadEl;placed=!1;constructor(e,t,n=12,a=s.t){this.t=a,this.callbacks=t,this.levels=n,this.el=document.createElement(`section`),this.el.className=`tcw-ladder`,this.el.setAttribute(`aria-label`,this.t(`ladder.title`)),r.o(this.el,`depthLadder`),this.el.hidden=!0;let o=document.createElement(`div`);o.className=`tcw-ladder-header`;let c=document.createElement(`h3`);c.className=`tcw-ladder-title`,c.textContent=this.t(`ladder.title`);let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-ladder-close`,l.setAttribute(`aria-label`,this.t(`common.close`)),l.innerHTML=i.i(`x`,14),l.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),o.append(c,l),this.colsEl=document.createElement(`div`),this.colsEl.className=`tcw-ladder-cols`;for(let e of[`ladder.bid`,`ladder.price`,`ladder.ask`]){let t=document.createElement(`span`);t.textContent=this.t(e),this.colsEl.appendChild(t)}this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-ladder-body`,this.spreadEl=document.createElement(`div`),this.spreadEl.className=`tcw-ladder-spread`,this.el.append(o,this.colsEl,this.bodyEl),e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.placed=!1,this.el.hidden=!1,this.render(),this.callbacks.onToggle?.(!0)}close(){this.open&&(this.open=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}setData(e){this.model=e?Do(e,this.levels):null,this.render()}setOrders(e){this.orders=e,this.render()}destroy(){this.el.remove()}render(){if(!this.open)return;let e=this.model;if(!e||e.rows.length===0){let e=document.createElement(`div`);e.className=`tcw-ladder-empty`,e.textContent=this.t(`ladder.empty`),this.bodyEl.replaceChildren(e),this.drawn=[];return}let t=Ao(e.rows);e.rows.length===this.drawn.length&&e.rows.every((e,t)=>e.price===this.drawn[t].price)||(this.drawn=e.rows.map(e=>this.newRow(e.price)),this.bodyEl.replaceChildren(...this.drawn.map(e=>e.row)));let n=e.maxVolume>0?100/e.maxVolume:0;e.rows.forEach((e,r)=>this.fillRow(this.drawn[r],e,n,this.nearness(e.price,t))),this.putSpread(e,t),this.placeSpread()}putSpread(e,t){let{spread:n,bestBid:r}=e,i=n===null||r===null?-1:e.rows.findIndex(e=>e.price<r+t);if(n===null||i<0){this.spreadEl.remove();return}this.spreadEl.textContent=s.r(this.t(`ladder.spread`),{spread:this.callbacks.formatPrice(n)});let a=this.drawn[i].row;this.spreadEl.nextElementSibling!==a&&this.bodyEl.insertBefore(this.spreadEl,a)}nearness(e,t){let n=this.callbacks.priceStep?.(e)??0;return n>0?Math.min(n/2,t):t}newRow(e){let t=document.createElement(`div`);t.className=`tcw-ladder-row`;let n=document.createElement(`div`);n.className=`tcw-ladder-price`;let r=document.createElement(`span`);r.className=`tcw-ladder-figure`,n.appendChild(r);let i=this.newCell(`sell`,e),a=this.newCell(`buy`,e);return t.append(i,n,a),{price:e,row:t,bid:i,ask:a,cell:n,figure:r}}newCell(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-ladder-cell ${e===`sell`?`tcw-ladder-bid`:`tcw-ladder-ask`}`,n.addEventListener(`click`,()=>this.callbacks.onTrade(e,t)),n}fillRow(e,t,n,r){e.cell.className=`tcw-ladder-price ${t.askVolume>0?`tcw-ask`:`tcw-bid`}`,e.figure.textContent=this.callbacks.formatPrice(t.price),this.fillCell(e.bid,`sell`,t.bidVolume,t.price,n),this.fillCell(e.ask,`buy`,t.askVolume,t.price,n);for(let t of e.cell.querySelectorAll(`.tcw-ladder-own`))t.remove();for(let n of[`buy`,`sell`]){let i=this.orders.filter(e=>e.side===n&&Math.abs(e.price-t.price)<r).reduce((e,t)=>e+t.quantity,0);if(i<=0)continue;let a=document.createElement(`span`);a.className=`tcw-ladder-own`,a.dataset.side=n,a.textContent=String(i);let o=`${this.t(n===`buy`?`ticket.buy`:`ticket.sell`)} ${i}`;a.setAttribute(`aria-label`,o),a.title=o,n===`buy`?e.cell.insertBefore(a,e.figure):e.cell.appendChild(a)}}fillCell(e,t,n,r,i){if(!(n>0)){e.disabled=!0,e.textContent=``,e.removeAttribute(`aria-label`),e.title=``,e.style.removeProperty(`--w`);return}e.disabled=!1;let a=jo(n);e.textContent=a,e.style.setProperty(`--w`,`${(n*i).toFixed(1)}%`);let o=s.r(this.t(t===`sell`?`ladder.sellAt`:`ladder.buyAt`),{price:this.callbacks.formatPrice(r)});e.setAttribute(`aria-label`,`${a}, ${o}`),e.title=o}placeSpread(){let e=this.el;if(this.placed||!this.spreadEl.isConnected||e.clientHeight===0)return;let t=e.getBoundingClientRect().top,n=this.colsEl.getBoundingClientRect().bottom-t,r=this.spreadEl.getBoundingClientRect().top-t;e.scrollTop+=r-n-(e.clientHeight-n-this.spreadEl.offsetHeight)/2,this.placed=!0}};function Ao(e){let t=1/0;for(let n=1;n<e.length;n++)t=Math.min(t,Math.abs(e[n-1].price-e[n].price));return Number.isFinite(t)&&t>0?t/2:Oo}function jo(e){return e>=1e3?`${Number((e/1e3).toFixed(1))}k`:String(Number(e>=1?e.toFixed(2):e.toPrecision(2)))}var Mo=class{el;bodyEl;callbacks;open=!1;constructor(e,t,n=s.t){this.t=n,this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-datawin`,r.o(this.el,`dataWindow`),this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-datawin-header`;let o=document.createElement(`span`);o.textContent=this.t(`dataWindow.title`);let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-datawin-close`,c.setAttribute(`aria-label`,this.t(`common.close`)),c.innerHTML=i.i(`x`,14),c.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),a.appendChild(o),a.appendChild(c),this.el.appendChild(a),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-datawin-body`,this.el.appendChild(this.bodyEl),e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}render(e){if(!this.open)return;if(this.bodyEl.replaceChildren(),!e.ohlc){let e=document.createElement(`div`);e.className=`tcw-datawin-empty`,e.textContent=this.t(te()?`dataWindow.touch`:`dataWindow.hover`),this.bodyEl.appendChild(e);return}let t=this.callbacks.formatPrice,n=e.ohlc;this.bodyEl.appendChild(this.row(this.t(`dataWindow.open`),t(n.open))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.high`),t(n.high))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.low`),t(n.low))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.close`),t(n.close)));let r=e.change>0?`up`:e.change<0?`down`:``,i=e.change>0?`+`:``,a=this.callbacks.formatPercent?.(e.changePct)??e.changePct.toFixed(2),o=e.changeText??t(e.change);this.bodyEl.appendChild(this.row(this.t(`dataWindow.change`),`${i}${o} (${i}${a}%)`,r)),this.bodyEl.appendChild(this.row(this.t(`dataWindow.volume`),(this.callbacks.formatVolume??Po)(n.volume)));for(let t of e.indicators){let e=document.createElement(`div`);e.className=`tcw-datawin-sub`,e.textContent=t.name,this.bodyEl.appendChild(e);for(let e of t.values)this.bodyEl.appendChild(this.row(e.key,e.text??No(e.value)))}}row(e,t,n=``){let r=document.createElement(`div`);r.className=`tcw-datawin-row`;let i=document.createElement(`span`);i.className=`tcw-datawin-label`,i.textContent=e;let a=document.createElement(`span`);return a.className=`tcw-datawin-value${n?` tcw-${n}`:``}`,a.textContent=t,r.appendChild(i),r.appendChild(a),r}};function No(e){if(!Number.isFinite(e))return`—`;let t=Math.abs(e);return t>=1e3?e.toFixed(2):t>=1?e.toFixed(4):e.toFixed((0,u.smallValueDecimals)(e))}function Po(e){return e>=1e9?(e/1e9).toFixed(2)+`B`:e>=1e6?(e/1e6).toFixed(2)+`M`:e>=1e3?(e/1e3).toFixed(2)+`K`:e.toFixed(0)}function Fo(e,t,n,r){let i=n?.delayMinutes;return e!==`connected`||i===void 0||!Number.isFinite(i)||i<=0?{message:t,delayed:!1}:{message:s.r(r(`status.delayed`),{minutes:Math.ceil(i)}),delayed:!0}}var Io=[[34,16,28,26,!1],[30,14,24,26,!0],[26,18,20,30,!0],[30,10,24,22,!1],[20,16,14,28,!0],[14,18,8,30,!0],[18,10,12,20,!1],[8,18,2,30,!0]],Lo=class{el;label;showTimer=null;phase=`loading`;constructor(e,t){this.loadingText=t,this.el=document.createElement(`div`),this.el.className=`tcw-loading-overlay`,this.el.setAttribute(`role`,`status`),this.el.setAttribute(`aria-live`,`polite`);let n=document.createElement(`div`);n.className=`tcw-loading-candles`,n.setAttribute(`aria-hidden`,`true`),Io.forEach(([e,t,r,i,a],o)=>{let s=document.createElement(`span`);s.className=a?`tcw-loading-candle tcw-loading-candle--up`:`tcw-loading-candle`,s.style.setProperty(`--tcw-body-top`,`${e}px`),s.style.setProperty(`--tcw-body-h`,`${t}px`),s.style.setProperty(`--tcw-wick-top`,`${r}px`),s.style.setProperty(`--tcw-wick-h`,`${i}px`),s.style.setProperty(`--tcw-delay`,`${o*110}ms`),n.appendChild(s)}),this.el.appendChild(n),this.label=document.createElement(`div`),this.label.className=`tcw-loading-label`,this.label.textContent=t,this.el.appendChild(this.label),e.appendChild(this.el)}begin(e,t=!1){if(this.phase=`loading`,this.clearTimer(),this.label.textContent=this.loadingText,this.el.classList.remove(`tcw-loading-overlay--error`),this.el.classList.toggle(`tcw-loading-overlay--veil`,e),!e||t||this.isShown()){this.el.classList.remove(`tcw-loading-overlay--hidden`);return}this.showTimer=setTimeout(()=>{this.showTimer=null,this.el.classList.remove(`tcw-loading-overlay--hidden`)},200)}end(){this.phase=`idle`,this.clearTimer(),this.el.classList.add(`tcw-loading-overlay--hidden`)}fail(e){this.phase!==`idle`&&(this.phase=`failed`,this.clearTimer(),this.label.textContent=e,this.el.classList.add(`tcw-loading-overlay--error`),this.el.classList.remove(`tcw-loading-overlay--hidden`))}isActive(){return this.phase!==`idle`}hasFailed(){return this.phase===`failed`}isShown(){return!this.el.classList.contains(`tcw-loading-overlay--hidden`)}destroy(){this.clearTimer(),this.el.remove()}clearTimer(){this.showTimer!==null&&(clearTimeout(this.showTimer),this.showTimer=null)}},Ro=4e3,zo=class{el;text;hideTimer=null;constructor(e,t){this.texts=t,this.el=document.createElement(`div`),this.el.className=`tcw-history-pill tcw-history-pill--hidden`,this.el.setAttribute(`aria-hidden`,`true`),this.el.setAttribute(`role`,`status`),this.el.setAttribute(`aria-live`,`polite`);let n=document.createElement(`span`);n.className=`tcw-history-spinner`,n.setAttribute(`aria-hidden`,`true`),this.text=document.createElement(`span`),this.el.append(n,this.text),e.appendChild(this.el)}update(e){this.clearTimer(),e.state===`loading`?this.show(this.texts.loading,!1):e.state===`error`?(this.show(this.texts.failed,!0),this.hideTimer=setTimeout(()=>this.hide(),Ro)):this.hide()}destroy(){this.clearTimer(),this.el.remove()}show(e,t){this.text.textContent=e,this.el.classList.toggle(`tcw-history-pill--error`,t),this.el.classList.remove(`tcw-history-pill--hidden`),this.el.removeAttribute(`aria-hidden`)}hide(){this.hideTimer=null,this.el.classList.add(`tcw-history-pill--hidden`),this.el.setAttribute(`aria-hidden`,`true`),this.text.textContent=``}clearTimer(){this.hideTimer!==null&&clearTimeout(this.hideTimer),this.hideTimer=null}},Bo=`host:`;function Vo(e,t){return[...e,...e.length>0&&t.length>0?[`separator`]:[],...t.map((e,t)=>({id:`${Bo}${t}`,label:e.label,icon:e.icon,danger:e.danger,checked:e.checked}))]}function Ho(e,t){return e.startsWith(Bo)?(t[Number(e.slice(5))]?.onSelect(),!0):!1}var Uo=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent),Wo={ctrl:`ctrl`,control:`ctrl`,cmd:`ctrl`,command:`ctrl`,meta:`ctrl`,mod:`ctrl`,alt:`alt`,option:`alt`,opt:`alt`,shift:`shift`},Go={esc:`escape`,space:` `,spacebar:` `,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`,del:`delete`,return:`enter`,plus:`+`};function Ko(e){let t=e.split(`+`).map(e=>e.trim()),n=t.pop();if(!n)return null;let r={ctrl:!1,alt:!1,shift:!1,display:[]};for(let e of t){let t=Wo[e.toLowerCase()];if(!t)return null;r[t]=!0}let i=n.toLowerCase();if(Wo[i])return null;if(/^[a-z]$/.test(i))r.code=`Key${i.toUpperCase()}`,r.char=i;else if(/^[0-9]$/.test(i))r.code=`Digit${i}`,r.char=i;else if(r.key=Go[i]??i,r.shift&&r.key.length===1)return null;return r.display=[...r.ctrl?[Uo?`⌘`:`Ctrl`]:[],...r.alt?[`Alt`]:[],...r.shift?[`Shift`]:[],r.key===` `?`Space`:n.length===1?n.toUpperCase():n],r}function qo(e,t){if((e.ctrlKey||e.metaKey)!==t.ctrl||e.altKey!==t.alt)return!1;if(t.code!==void 0){if(e.shiftKey!==t.shift)return!1;if(t.alt)return e.code===t.code;let n=e.key.length===1&&/^[a-z0-9]$/i.test(e.key)?e.key.toLowerCase():null;return n===null?e.code===t.code:n===t.char}return t.shift&&!e.shiftKey?!1:e.key.toLowerCase()===t.key}var Jo=new Set(`escape(enter(delete(backspace(arrowleft(arrowright(arrowup(arrowdown(home(end(+(-(=( (,(.(ctrl+z(ctrl+shift+z(ctrl+y(ctrl+c(ctrl+v(ctrl+d(ctrl+g(ctrl+shift+g(ctrl+[(ctrl+]`.split(`(`));function Yo(e){let t=`${e.ctrl?`ctrl+`:``}${e.alt?`alt+`:``}${e.shift?`shift+`:``}${e.char??e.key}`;return Jo.has(t)}function Xo(e){let t=typeof e.composedPath==`function`?e.composedPath()[0]:e.target;return t instanceof HTMLElement?t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName):!1}var Zo=[`#b552c9`,`#1398a8`,`#d4622b`,`#e25592`,`#6f7a8c`,`#3e9a4f`],Qo=class{constructor(e){this.host=e}compares=[];compareWay=`percent`;comparesLoading=new Set;compareScaleHeld=!1;compareFetchSeq=0;compareOlderBusy=!1;compareOlderAgain=!1;compareOlderPassed=!1;async handleAddCompare(){if(this.host.featureState.compare){if(!this.host.adapter){this.host.say(this.host.t(`toast.compareNeedsAdapter`),`error`);return}this.host.withSymbolSearch(()=>this.host.featureState.compare,e=>e.openCompare({symbols:this.host.symbolEntries(),current:this.host.state.symbol,search:this.host.symbolSearchFn(),ways:$a(this.host.t),way:this.compareWay,compared:this.comparedNow(),onAdd:(e,t)=>{Qa(t)&&(this.compareWay=t,this.addCompareSymbol(e,t))},onRemove:e=>this.removeCompared(e)}))}}comparedNow(){let e=new Set(this.host.chart.getIndicatorPanes().flatMap(e=>e.instanceIds));return ro(this.compares,this.host.chart.getActiveIndicators(),e,this.host.t)}refreshCompareDialog(){this.host.symbolSearch?.isComparing()&&this.host.symbolSearch.setCompared(this.comparedNow())}async addCompareSymbol(e,t=`percent`){if(!this.host.adapter){this.host.say(this.host.t(`toast.compareNeedsAdapter`),`error`);return}if(t!==`percent`){await this.addCompareIndicator(this.host.adapter,e,t);return}if(this.host.chart.getFeatures()?.compareSymbols===!1||this.compares.some(t=>t.symbol===e)||this.comparesLoading.has(e))return;let n=`cmp_${e}`;this.comparesLoading.add(e);try{let t=await this.fetchCompareBars(this.host.adapter,e);if(!t||this.compares.some(t=>t.symbol===e))return;let r=this.host.state.timeframe,i=Zo[this.compares.length%Zo.length];this.compares.length===0&&this.host.chart.setCompareMode(`percent`),this.host.chart.addCompareSymbol(n,(0,u.tickerOf)(e),t,i),this.compares=[...this.compares,{id:n,symbol:e,color:i,bars:t,timeframe:r}],this.compares.length===1&&this.holdCompareScale(!0),this.host.scheduleLegend(),this.host.refreshObjects(),this.refreshCompareDialog(),this.host.say(s.r(this.host.t(`toast.comparing`),{symbol:(0,u.tickerOf)(e)}))}finally{this.comparesLoading.delete(e)}}async addCompareIndicator(e,t,n){let r=await this.fetchCompareBars(e,t);r&&(this.host.chart.setSymbolSeries(t,r),n===`scale`?this.host.chart.addIndicator(`compareSymbol`,{symbol:t},`bottom`,{scale:`left`}):n===`pane`?this.host.chart.addIndicator(`compareSymbolPane`,{symbol:t}):n===`correlation`?this.host.chart.addIndicator(`correlation`,{symbol:t}):n===`correlationLog`?this.host.chart.addIndicator(`correlationlog`,{symbol:t}):this.host.chart.addIndicator(`spread`,{symbol:t,mode:n}))}async fetchCompareBars(e,t){for(;;){let n=this.host.state.timeframe,r=null,i=null;try{r=await(0,d.withResampling)(e).fetchHistory(t,n,this.compareDepth())}catch(e){i=e}if(this.host.destroyed)return null;if(n===this.host.state.timeframe)return r&&r.length>0?r:(i===null?this.host.say(s.r(this.host.t(`toast.compareNoBars`),{symbol:(0,u.tickerOf)(t),interval:ve(n)}),`error`):this.sayCompareFailed(t,i),null)}}sayCompareFailed(e,t){this.host.say(`${(0,u.tickerOf)(e)}: ${t instanceof Error?t.message:this.host.t(`toast.loadFailed`)}`,`error`)}removeCompared(e){this.compares.some(t=>t.id===e)?this.handleRemoveCompare(e):this.host.chart.removeIndicator(e)}handleRemoveCompare(e){this.host.chart.removeCompareSymbol(e),this.compares=this.compares.filter(t=>t.id!==e),this.compares.length===0&&this.holdCompareScale(!1),this.host.scheduleLegend(),this.host.refreshObjects(),this.refreshCompareDialog()}removeHostCompare(e){this.host.chart.removeCompareSymbol(e),this.host.scheduleLegend()}isPercentCompare(e){return this.compares.some(t=>t.id===e)}compareDepth(){return Math.max(this.host.chart.getData().length,this.host.options.historyLimit??500)}holdsPercentScale(){return this.compareScaleHeld&&this.compares.length>0&&this.host.settingsState.scaleMode===`regular`&&this.host.chart.isTimeAligned()}holdCompareScale(e){e!==this.compareScaleHeld&&(this.compareScaleHeld=e,this.showHeldScale())}showHeldScale(){this.host.showScaleMode(),this.host.refreshScaleSwitches(),this.host.settings?.refresh(this.host.shownSettings())}async loadSymbolSeries(e){if(!this.host.adapter){this.host.say(this.host.t(`toast.compareNeedsAdapter`),`error`);return}let t=this.host.state.timeframe,n=(this.host.symbolLoads.get(e)??0)+1;this.host.symbolLoads.set(e,n);let r=()=>this.host.destroyed||t!==this.host.state.timeframe||this.host.symbolLoads.get(e)!==n;try{let n=await(0,d.withResampling)(this.host.adapter).fetchHistory(e,t,this.compareDepth());if(r())return;this.host.chart.setSymbolSeries(e,n)}catch(t){if(r())return;this.host.chart.setSymbolSeries(e,this.host.chart.getSymbolSeries(e)),this.sayCompareFailed(e,t)}}async refetchCompares(){for(let e of this.host.chart.getRequiredSymbols?.()??[])this.loadSymbolSeries(e);if(!this.host.adapter||this.compares.length===0)return;let e=this.compares.filter(e=>e.symbol===this.host.state.symbol);for(let t of e)this.handleRemoveCompare(t.id);await this.refetchPercentCompares()}async refetchPercentCompares(){if(!this.host.adapter||this.compares.length===0)return;let e=++this.compareFetchSeq,t=(0,d.withResampling)(this.host.adapter);this.compares=this.compares.map(e=>({...e,failedAt:void 0}));for(let n of this.compares){let r=this.host.state.timeframe;try{let i=await t.fetchHistory(n.symbol,r,this.compareDepth());if(this.host.destroyed||e!==this.compareFetchSeq)return;this.isPercentCompare(n.id)&&this.setCompareBars(n.id,i,r)}catch{!this.host.destroyed&&e===this.compareFetchSeq&&this.compareFailedAt(n.id,r)}}this.compareOlderPassed&&(this.compareOlderPassed=!1,this.extendPercentCompares())}async extendPercentCompares(){if(this.compareOlderBusy){this.compareOlderAgain=!0;return}this.compareOlderBusy=!0;try{do this.compareOlderAgain=!1,await this.fetchOlderCompares();while(this.compareOlderAgain&&!this.host.destroyed)}finally{this.compareOlderBusy=!1}}async fetchOlderCompares(){if(!this.host.adapter||this.compares.length===0)return;let e=(0,d.withResampling)(this.host.adapter),t=this.compareFetchSeq,n=this.host.state.timeframe;for(let r of this.compares){if(r.timeframe!==n){r.failedAt!==n&&(this.compareOlderPassed=!0);continue}let i=r.bars[0]?.time;if(i===void 0||r.atStart)continue;let a=eo(this.host.chart.getData(),i);if(a!==0)try{if(e.fetchHistoryBefore){let o=await e.fetchHistoryBefore(r.symbol,n,i,a);if(this.host.destroyed||t!==this.compareFetchSeq)return;this.prependCompareBars(r.id,o,n)}else{let a=this.compareDepth(),o=await e.fetchHistory(r.symbol,n,a);if(this.host.destroyed||t!==this.compareFetchSeq)return;this.deepenCompareBars(r.id,o,a,i,n)}}catch{}}}deepenCompareBars(e,t,n,r,i){this.isPercentCompare(e)&&(this.setCompareBars(e,t,i),(t.length<n||!(t[0].time<r))&&(this.compares=this.compares.map(t=>t.id===e?{...t,atStart:!0}:t)))}prependCompareBars(e,t,n){let r=this.compares.find(t=>t.id===e);if(!r)return;let i=to(r.bars,t);i?this.setCompareBars(e,i,n):this.compares=this.compares.map(t=>t.id===e?{...t,atStart:!0}:t)}setCompareBars(e,t,n){this.host.chart.updateCompareData(e,t),this.compares=this.compares.map(r=>r.id===e?{...r,bars:t,timeframe:n,atStart:!1,failedAt:void 0}:r)}compareFailedAt(e,t){this.compares=this.compares.map(n=>n.id===e?{...n,failedAt:t}:n)}},$o=class{constructor(e){this.host=e}watchlist=null;watchlistSparkBuffer=new Map;hostWatchlistRefPrice=new Map;watchlistInterval=null;watchlistStore=null;watchlistFromSymbols=!1;quoteSource=null;stopQuotes=null;quotedKey=``;quotes=new Map;getWatchlists(){return this.watchlistStore?.getLists()??[]}getActiveWatchlist(){return this.watchlistStore?.getActive().id??null}setWatchlists(e,t){this.watchlistFromSymbols=!1,this.watchlistStore?.replace(e,t)}setActiveWatchlist(e){this.watchlistStore?.setActive(e)}addToWatchlist(e,t){this.watchlistStore?.add(e,t)}removeFromWatchlist(e,t){this.watchlistStore?.removeSymbol(e,t)}setQuotes(e){let t=e.map(u.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)}getQuote(e){let t=this.quotes.get(e);return t?{...t}:null}createWatchlist(e,t){let n=t.persist?A():null,r=new pn({lists:t.lists,activeList:t.activeList,symbols:this.host.symbols,defaultName:this.host.t(`watchlist.title`),storage:n,storageKey:t.storageKey});this.watchlistStore=r,this.watchlistFromSymbols=!t.lists&&!t.persist,this.quoteSource=t.quotes===!1?null:t.quotes??(this.host.options.adapter?.subscribeQuotes?this.host.options.adapter:null);let i=e=>this.host.t(e);this.watchlist=new Zt(e,{onSelect:e=>{this.host.setSymbol(e)},onAdd:()=>this.host.withSymbolSearch(()=>!0,e=>e.open({symbols:this.host.symbolEntries(),current:this.host.state.symbol,currentInfo:this.host.chartSymbolInfo(),onPick:e=>r.add(e),search:this.host.symbolSearchFn()})),onRemove:e=>r.removeSymbol(e),onMove:(e,t)=>r.move(e,t),onPickList:e=>r.setActive(e),onCreateList:e=>r.create(e),onRenameList:(e,t)=>r.rename(e,t),onDeleteList:e=>r.remove(e),onClose:()=>this.host.closePanelByHand(`watchlist`)},{close:i(`common.close`),title:i(`watchlist.title`),lists:i(`watchlist.lists`),newList:i(`watchlist.newList`),rename:i(`watchlist.rename`),deleteList:i(`watchlist.deleteList`),confirmDelete:i(`watchlist.confirmDelete`),add:i(`watchlist.add`),remove:i(`watchlist.remove`),empty:i(`watchlist.empty`),listName:i(`watchlist.listName`),columns:{symbol:i(`watchlist.columnSymbol`),price:i(`watchlist.columnPrice`),move:i(`watchlist.columnMove`),change:i(`watchlist.columnChange`)}},{sparkline:t.sparkline===!0,infoOf:e=>this.host.symbolInfoOf(e)}),this.watchlist.setActive(this.host.state.symbol),this.watchlist.setLocale(this.host.settingsState.numberLocale||void 0);let a=()=>{this.watchlist?.setLists(r.getLists(),r.getActive().id),this.followQuotes()};r.subscribe(()=>{a(),t.onChange?.(r.getLists(),r.getActive().id)}),a()}followQuotes(){if(!this.quoteSource||!this.watchlistStore||this.host.destroyed)return;let e=this.watchlistStore.getActive().symbols,t=[...e].sort().join(`\0`);if(t!==this.quotedKey&&(this.quotedKey=t,this.stopQuotes?.(),this.stopQuotes=null,e.length!==0))try{this.stopQuotes=this.quoteSource.subscribeQuotes(e,e=>{if(this.host.destroyed||!Array.isArray(e))return;let t=e.map(u.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)})}catch{this.stopQuotes=null}}takeQuotes(e){for(let t of e){let e={...this.quotes.get(t.symbol),...t};this.quotes.set(e.symbol,e);let n=this.watchlistSparkBuffer.get(e.symbol)??[];n.push(e.last),n.length>40&&n.shift(),this.watchlistSparkBuffer.set(e.symbol,n);let r=this.hostWatchlistRefPrice.get(e.symbol);this.watchlist?.setEntry(e.symbol,{lastPrice:e.last,refPrice:r??(e.change===void 0?void 0:e.last-e.change),sparkline:n.slice()})}e.some(e=>e.symbol===this.host.state.symbol)&&this.host.refreshSymbolInfo()}setWatchlistEntry(e,t){t.refPrice!==void 0&&this.hostWatchlistRefPrice.set(e,t.refPrice),this.watchlist?.setEntry(e,t)}tickWatchlist(){if(!this.watchlist||this.quotes.has(this.host.state.symbol)||Xt())return;let e=this.host.chart.getData();if(e.length===0)return;let t=e[e.length-1],n=this.hostWatchlistRefPrice.get(this.host.state.symbol);n===void 0&&this.host.sessionRefPrice===null&&(this.host.sessionRefPrice=e[0].open);let r=this.watchlistSparkBuffer.get(this.host.state.symbol)??[];r.push(t.close),r.length>40&&r.shift(),this.watchlistSparkBuffer.set(this.host.state.symbol,r),this.watchlist.setEntry(this.host.state.symbol,{lastPrice:t.close,refPrice:n??this.host.sessionRefPrice??e[0].open,sparkline:r.slice()})}},es=class{constructor(e){this.host=e}alertsPanel=null;alertNotifier=null;addDrawingAlert(e){if(!this.host.featureState.alerts)return;let t=this.host.chart.getDrawings().find(t=>t.id===e),n=t?this.host.drawingToolName(t.type):``;this.host.chart.addDrawingAlert(e,{label:n})&&this.host.say(s.r(this.host.t(`drawingSettings.alertAdded`),{name:n}))}toggleAlerts(){!this.alertsPanel||!this.host.featureState.alerts||this.host.dock?.toggle(`alerts`)}refreshAlerts(){if(!this.alertsPanel)return;let e=this.buildAlertSources();this.alertsPanel.setSources(e),this.alertsPanel.setAlerts(this.host.chart.getAlerts().map(t=>this.alertListItem(t,e)))}alertListItem(e,t){return{id:e.id,price:e.price,condition:e.condition,message:e.message,triggered:e.triggered,channel:e.channel,label:e.label,drawingId:e.drawingId,target:e.target,targetLabel:e.target?t.find(t=>t.channel===e.target)?.label:void 0,percent:e.percent,bars:e.bars,onBarClose:e.onBarClose,expiresAt:e.expiresAt,expired:e.expired}}alertText(e){return Rn(this.alertListItem(e,this.buildAlertSources()),this.host.t,e=>this.host.formatAlertPrice(e),!0)}buildAlertSources(){let e=[{channel:`price`,label:this.host.t(`alerts.source.price`)}];for(let t of this.host.chart.getActiveIndicators()){let n=this.host.chart.getIndicatorOutput(t.instanceId)?.series,r=n&&n.length>0?n[n.length-1]:null,i=r?Object.keys(r).filter(e=>typeof r[e]==`number`):[];for(let n of i){let r=i.length>1?`${t.descriptor.name} ${n}`:t.descriptor.name;e.push({channel:`${t.instanceId}:${n}`,label:r})}}return e}getAlertChannelValue(e){let t=this.host.chart.getData();if(e===`price`)return t.length>0?this.host.chart.roundPrice(t[t.length-1].close):null;let n=e.indexOf(`:`);if(n<0||t.length===0)return null;let r=e.slice(0,n),i=e.slice(n+1),a=bo(this.host.chart.getIndicatorOutput(r)?.series,null)?.[i];return typeof a==`number`&&Number.isFinite(a)?a:null}},ts=class{constructor(e){this.host=e}accountPanel=null;orderTicket=null;accountFrame=0;bracketBar=null;depthLadder=null;toggleAccountPanel(e){let t=this.accountPanel;!t||e===t.isOpen()||!t.isOpen()&&!this.host.featureState.accountPanel||t.toggle()}openOrderTicket(e){if(!this.host.featureState.orderTicket)return;let t=this.host.chart.getData();this.orderTicket?.open({price:e,lastPrice:t.length>0?t[t.length-1].close:null,rules:this.orderRules(),symbol:this.host.state.symbol,step:e=>this.host.chart.getPriceStep(e),round:e=>this.host.chart.roundPrice(e)})}orderRules(){let e=this.host.chart.getMarket();return e?{roundPrice:e.priceStep!==void 0||(e.priceSteps?.length??0)>0?e=>this.host.chart.roundPrice(e):void 0,limits:this.host.chart.getPriceLimits(),lot:e.volumeUnit,multiplier:e.contractMultiplier}:{}}refreshAccountSoon(){this.accountFrame||!this.accountPanel||(this.accountFrame=requestAnimationFrame(()=>{this.accountFrame=0,this.host.destroyed||this.refreshAccount()}))}refreshAccount(){if(!this.accountPanel)return;let e=this.host.chart.getData(),t=e.length>0?e[e.length-1].close:null;this.accountPanel.update({positions:this.host.chart.getPositions(),orders:this.host.chart.getOrders(),fills:this.host.chart.getFills(),price:t,realisedPnl:this.host.chart.getRealisedPnl()}),this.orderTicket?.setLastPrice(t)}placeOrderAt(e,t){let n=e.startsWith(`buy`)?`buy`:`sell`,r=e.endsWith(`Stop`);this.host.chart.placeOrderIntent(r?{side:n,type:`stop`,price:t,stopPrice:t,quantity:1}:{side:n,type:`limit`,price:t,quantity:1}),this.host.say(s.r(this.host.t(`order.${e}`),{price:this.host.formatAlertPrice(t)}))}toggleLadder(){!this.depthLadder||!this.host.featureState.depthLadder||this.host.dock?.toggle(`depthLadder`)}setDepth(e){this.host.chart.setDepthData(e),this.depthLadder?.setData(e),e&&this.host.chart.pushDepthSnapshot(e)}startBracket(e){this.host.chart.startBracket(e)&&this.bracketBar?.show(e)}};function ns(e,t){let{selected:n}=e,r=n.length===1,i=new Set(n.map(e=>e.groupId)),a=i.size===1&&!i.has(null),o=[];e.canConfigure&&r&&o.push({id:`settings`,label:t(`drawingMenu.settings`),icon:`settings`}),e.canText&&r&&o.push({id:`text`,label:t(`drawingSettings.text`),icon:`textEdit`}),e.canAlert&&r&&o.push({id:`alert`,label:t(`drawingSettings.addAlert`),icon:`bell`}),o.length>0&&o.push(`separator`),r&&o.push({id:`front`,label:t(`drawingMenu.front`)},{id:`forward`,label:t(`drawingMenu.forward`)},{id:`backward`,label:t(`drawingMenu.backward`)},{id:`back`,label:t(`drawingMenu.back`)},`separator`),n.length>1&&!a&&o.push({id:`group`,label:t(`drawingMenu.group`),icon:`layers`}),n.some(e=>e.groupId)&&o.push({id:`ungroup`,label:t(`drawingMenu.ungroup`),icon:`layers`});let s=n.every(e=>e.locked);return o.push(s?{id:`unlock`,label:t(`common.unlock`),icon:`unlock`}:{id:`lock`,label:t(`common.lock`),icon:`lock`},{id:`hide`,label:t(`common.hide`),icon:`eyeOff`}),r&&o.push({id:`duplicate`,label:t(`drawingMenu.duplicate`),icon:`plus`}),s||o.push(`separator`,{id:`delete`,label:t(`drawingMenu.delete`),icon:`trash`,danger:!0}),o}var rs=class{constructor(e){this.host=e}drawingMenu=null;clearMenu=null;chartMenu=null;menuPane=null;openDrawingMenu(e,t,n){if(!this.drawingMenu||!this.host.featureState[`menu.drawing`])return;let i=new Map(this.host.chart.getDrawings().map(e=>[e.id,e])),a=this.host.chart.getSelectedDrawingIds().flatMap(e=>{let t=i.get(e);return t?[{id:t.id,locked:t.locked,groupId:t.group?.id??null}]:[]});if(a.length===0)return;let o=r.a(ns({selected:a,canConfigure:!0,canAlert:this.host.chart.canAddDrawingAlert(e),canText:this.host.canTypeDrawingText(e)},this.host.t),r.n,this.host.featureState),s=a.map(e=>e.id),c=i.get(e),l=c?this.host.options.drawingMenuItems?.({id:e,type:c.type,selected:s})??[]:[],u=Vo(o,l);if(u.length===0)return;let d=this.host.chartContainer.getBoundingClientRect(),f=this.host.root.getBoundingClientRect();this.drawingMenu.open(u,d.left-f.left+t,d.top-f.top+n,t=>{Ho(t,l)||this.runDrawingMenuAction(e,s,t)})}runDrawingMenuAction(e,t,n){switch(n){case`settings`:this.host.openDrawingSettings(e);return;case`text`:this.host.editDrawingText(e);return;case`alert`:this.host.alerting.addDrawingAlert(e);return;case`front`:case`forward`:case`backward`:case`back`:this.host.chart.moveDrawing(e,n);break;case`group`:this.host.chart.groupDrawings(t);break;case`ungroup`:{let e=new Set(this.host.chart.getDrawings().filter(e=>t.includes(e.id)).map(e=>e.group?.id));for(let t of e)t&&this.host.chart.ungroupDrawings(t);break}case`lock`:case`unlock`:this.host.chart.setDrawingsLocked(t,n===`lock`);break;case`hide`:this.host.chart.setDrawingsVisible(t,!1);break;case`duplicate`:this.host.chart.duplicateDrawing(e);break;case`delete`:{let e=this.host.drawingSettings?.editing();e&&t.includes(e)&&this.host.drawingSettings?.close(!0),this.host.chart.removeDrawings(t);break}}this.host.objectTree?.isOpen()&&this.host.refreshObjects()}chartMenuContext(e){let t=this.host.chart.getDrawings(),n=this.host.chart.getData(),r=this.host.settingsState,i=this.host.chart.getFeatures();return{price:e,lastPrice:n.length>0?n[n.length-1].close:null,formatPrice:e=>this.host.formatAlertPrice(e),canAlert:this.host.alerting.alertsPanel!==null,canTrade:this.host.options.trading!==!1,canOrderTicket:this.host.trading.orderTicket!==null,canDraw:!0,hasDrawings:t.length>0,drawingsHidden:t.length>0&&t.every(e=>!e.visible),canPaste:this.host.chart.canPasteDrawings(),hasIndicators:i.indicators!==!1&&this.removableIndicators().length>0,canGoToDate:!0,canExport:this.host.canExport,autoScale:this.host.chart.isAutoScale(),scaleMode:this.host.effectiveScaleMode(),canLog:i.logScale!==!1,inverted:this.host.chart.isInvertScale(),leftScale:r.leftPriceScale,labels:{values:r.indicatorValueLabels,aligned:r.alignAxisLabels,...i.barCountdown===!1?{}:{countdown:r.barCountdown}},lines:{highLow:r.highLowLines,lastPrice:this.host.chart.getStyleValue(`lastPrice.visible`)!==!1},timezone:{current:r.timezone,options:this.timezoneChoices()},keys:Object.fromEntries(zi.filter(e=>this.host.featureState.hotkeys&&this.host.featureState[e.feature]).map(e=>[e.action,e.keys]))}}removableIndicators(){return this.host.chart.getActiveIndicators().filter(e=>!d.SYMBOL_INDICATOR_IDS.has(e.id)).map(e=>e.instanceId)}exchangeChoice(){let e=this.host.chart.getExchangeTimeZone()??null;if(!(e===null&&!this.host.adapter?.resolveSymbol))return{label:this.host.t(`settings.timezone.exchange`),zone:e}}timezoneChoices(){return t.y(this.host.settingsState.timezone,Date.now(),this.host.t(`settings.timezone.local`),this.exchangeChoice()).map(({value:e,label:t})=>({value:e,label:t}))}openChartMenu(e,t,n,r){if(!this.chartMenu)return;let i=this.host.options.chartMenuItems?.(r)??[],a=Vo(e,i);if(a.length===0)return;let o=this.host.chartContainer.getBoundingClientRect(),s=this.host.root.getBoundingClientRect();this.chartMenu.open(a,o.left-s.left+t,o.top-s.top+n,e=>{Ho(e,i)||(e.startsWith(`tz:`)?this.host.changeSettings({timezone:e.slice(3)}):this.runChartMenuAction(e,r))})}runChartMenuAction(e,t){let{price:n}=t,r=n??NaN,i=this.host.settingsState,a=Bi(e);if(a){this.host.changeSettings({scaleMode:a});return}switch(e){case`alert`:this.host.chart.addAlert(r,`crossing`),this.host.say(s.r(this.host.t(`chartMenu.alertAdded`),{price:this.host.formatAlertPrice(r)}));break;case`buyLimit`:case`sellLimit`:case`buyStop`:case`sellStop`:this.host.trading.placeOrderAt(e,r);break;case`orderTicket`:this.host.trading.openOrderTicket(n);break;case`exportData`:this.host.chart.exportAllData(`csv`,`${this.host.state.symbol}-${this.host.state.timeframe}.csv`.replace(/[^\w.-]+/g,`_`));break;case`paneLog`:case`paneInvert`:case`panePercent`:{let t=this.menuPane;if(!t)break;let n=this.host.chart.getPaneScale(t);this.host.chart.setPaneScale(t,e===`paneLog`?{log:!n.log}:e===`paneInvert`?{invert:!n.invert}:{percent:!n.percent});break}case`horizontalLine`:{let e=this.host.chart.getData();e.length>0&&this.host.chart.addDrawing({type:`horizontalLine`,anchors:[{time:e[e.length-1].time,price:r}]});break}case`resetView`:this.host.resetView();break;case`resetPriceScale`:this.host.changeSettings({autoScale:!0});break;case`paste`:this.host.chart.pasteDrawings();break;case`removeIndicators`:this.host.chart.removeIndicators(this.removableIndicators());break;case`hideDrawings`:this.host.chart.setDrawingsVisible(this.host.chart.getDrawings().map(e=>e.id),!1);break;case`showDrawings`:this.host.chart.setDrawingsVisible(this.host.chart.getDrawings().map(e=>e.id),!0);break;case`removeDrawings`:this.host.chart.removeDrawings(this.host.chart.getDrawings().map(e=>e.id));break;case`settings`:this.host.openSettings(t.area===`priceAxis`?`scales`:void 0);break;case`autoScale`:this.host.changeSettings({autoScale:!this.host.chart.isAutoScale()});break;case`invertScale`:this.host.changeSettings({invertScale:!this.host.chart.isInvertScale()});break;case`leftScale`:this.host.changeSettings({leftPriceScale:!i.leftPriceScale});break;case`indicatorValueLabels`:this.host.changeSettings({indicatorValueLabels:!i.indicatorValueLabels});break;case`alignAxisLabels`:this.host.changeSettings({alignAxisLabels:!i.alignAxisLabels});break;case`barCountdown`:this.host.changeSettings({barCountdown:!i.barCountdown});break;case`highLowLines`:this.host.changeSettings({highLowLines:!i.highLowLines});break;case`lastPriceLine`:this.host.changeStyle({"lastPrice.visible":this.host.chart.getStyleValue(`lastPrice.visible`)===!1});break;case`goToDate`:this.host.toggleGoToDate();break}this.host.objectTree?.isOpen()&&this.host.refreshObjects()}openClearMenu(e){if(o.f.closeAnchoredTo(e))return;let t=this.host.chart.getDrawings().filter(e=>!e.locked).length,n=this.host.chart.getActiveIndicators().length,r=[];t>0&&r.push({id:`drawings`,label:this.host.t(`clear.drawings`),icon:`penLine`,count:t}),n>0&&r.push({id:`indicators`,label:this.host.t(`clear.indicators`),icon:`trendingUp`,count:n}),t>0&&n>0&&r.push(`separator`,{id:`all`,label:this.host.t(`clear.all`),icon:`trash`,danger:!0}),r.length!==0&&(this.clearMenu??=new o.f(this.host.root,this.host.t(`drawing.clearAll`)),this.clearMenu.openBeside(r,e,e=>this.removeAll(e)))}removeAll(e){this.host.chart.removeAll(e),this.host.state={...this.host.state,activeTool:null},this.host.updateUI(),this.host.refreshDrawingsState(),this.host.refreshObjects()}},is=2,as=2;function os(e,t=`en-US`){return(0,u.formatPrice)(e,Math.max(is,(0,d.indicatorValuePrecision)(e)),t)}function ss(e,t=`en-US`){return`${W((0,u.formatPrice)(Math.abs(e),as,t),e,(0,u.formatPrice)(0,as,t))}%`}function cs(e,t=`en-US`,n=!0){return e.map(e=>({instanceId:e.id,kind:`compare`,label:e.label,swatch:e.color,visible:e.visible,...n?{values:ls(e,t)}:{values:[],offChartType:!0},pane:null}))}function ls(e,t){return[...e.close===null?[]:[{text:os(e.close,t),color:null}],...e.change===null?[]:[{text:ss(e.change,t),color:null}]]}var us=7,ds=17,fs=3,ps=4;function ms(e){return u.CHART_SPACING[e.getDensity?.()??`comfortable`].legendInset-ps}function hs(e){return!d.SYMBOL_INDICATOR_IDS.has(e.id)&&e.scale!==`left`}var gs=class{constructor(e){this.host=e}legendFrame=0;legendMenu=null;scheduleLegend(){!this.host.indicatorLegend||this.legendFrame||!this.host.featureState.indicatorLegend||(this.legendFrame=requestAnimationFrame(()=>{this.legendFrame=0,this.renderLegend()}))}renderLegend(){if(!this.host.indicatorLegend||this.host.destroyed)return;let e=this.host.chart.getData().length-1,t=this.host.chart.isTimeAligned(),n=this.host.legendHoverIndex,r=ms(this.host.chart),i=n===null?e:Math.min(Math.max(n,0),e),a=new Map;for(let e of this.host.chart.getIndicatorPanes())(e.instanceIds??[e.instanceId]).forEach((t,n)=>a.set(t,{...e.rect,row:n}));let o=this.host.settingsState.numberLocale||`en-US`,s=cs(i>=0?this.host.chart.getCompareValues?.(n===null||!t?void 0:i)??[]:[],o,t),l=this.host.chart.getActiveIndicators().map(e=>{let t=a.get(e.instanceId)??null,i=bo(this.host.chart.getIndicatorOutput(e.instanceId,{drawn:!0})?.series,n),s=this.host.chart.getIndicatorStyle(e.instanceId),l=e.visible&&e.offChartType===!0,u=e.visible&&e.shown===!1&&!l,d=u||l?[]:xo(e.descriptor,i,s?.colors??[],s?.plots);return{instanceId:e.instanceId,label:c.r(e,this.host.t),visible:e.visible,offInterval:u,offChartType:l,values:d.map(n=>({text:this.host.indicatorValueText(n.value,t===null&&hs(e),o),color:n.color})),pane:t?{x:t.x+r,y:t.y+Math.min(us+t.row*ds,Math.max(us,t.height-ds)),width:t.width-2*r}:null}}),u=[...s,...l],d=this.host.chart.getPlotRect(),f=this.host.chart.getMaximizedPane(),p=e=>u.find(t=>t.instanceId===e)?.label??``,m=this.host.chart.getIndicatorPanes().map(e=>({instanceId:e.instanceId,x:e.rect.x+e.rect.width-r,y:e.rect.y+fs,label:p(e.instanceId),collapsed:this.host.chart.isPaneCollapsed(e.instanceId),maximized:f===e.instanceId,canMoveUp:this.host.chart.canMovePane(e.instanceId,-1),canMoveDown:this.host.chart.canMovePane(e.instanceId,1)}));this.host.indicatorLegend.update(u,{left:d.x+r,top:this.host.chart.getLegendBottom()+1},m)}runPaneAction(e,t){t===`up`||t===`down`?this.host.chart.movePane(e,t===`up`?-1:1):t===`collapse`||t===`expand`?this.host.chart.setPaneCollapsed(e,t===`collapse`):this.host.chart.setMaximizedPane(t===`maximize`?e:null),this.scheduleLegend()}openLegendMenu(e,t){let n=this.legendMenu;if(!n)return;if(n.isOpen()){n.close();return}let r=[`price`,...this.host.chart.getIndicatorPanes().map(e=>e.instanceId)],i=1+this.host.chart.getIndicatorPanes().findIndex(t=>t.instanceIds.includes(e)),a=r[i-1],o=r[i+1],s=t=>t!==void 0&&this.host.chart.canMoveIndicatorToPane(e,t),c=[];s(a)&&c.push({id:`move:${a}`,label:this.host.t(a===`price`?`legend.movePrice`:`legend.moveUp`),icon:`arrowUp`}),s(o)&&c.push({id:`move:${o}`,label:this.host.t(`legend.moveDown`),icon:`arrowDown`}),s(`new`)&&c.push({id:`move:new`,label:this.host.t(`legend.moveNew`),icon:`plus`}),a!==`price`&&s(`price`)&&c.push({id:`move:price`,label:this.host.t(`legend.movePrice`),icon:`trendingUp`});let l=[];this.host.featureState.indicatorSettings&&this.host.featureState[`indicatorLegend.settings`]&&l.push({id:`settings`,label:this.host.t(`legend.settings`),icon:`settings`}),this.host.featureState[`indicatorLegend.remove`]&&l.push({id:`remove`,label:this.host.t(`legend.remove`),icon:`trash`,danger:!0}),c.length>0&&l.length>0&&c.push(`separator`),c.push(...l);let u=this.host.chart.getActiveIndicators().find(t=>t.instanceId===e)?.id??``,d=this.host.options.indicatorMenuItems?.({instanceId:e,indicatorId:u})??[],f=Vo(c,d);if(f.length===0)return;let p=t.getBoundingClientRect(),m=this.host.root.getBoundingClientRect();n.open(f,p.left-m.left,p.bottom-m.top+2,t=>{Ho(t,d)||(t===`settings`?this.host.openIndicatorSettings(e):t===`remove`?this.host.handleRemoveIndicator(e):t.startsWith(`move:`)&&this.host.chart.moveIndicatorToPane(e,t.slice(5)),this.scheduleLegend())},t)}},_s=class{constructor(e){this.host=e}toggleCommandPalette(){if(this.host.commandPalette?.isOpen()){this.host.commandPalette.close();return}this.host.cancelWaiting(this.host.commandPalettePart)||this.host.whenLoaded(this.host.commandPalettePart,()=>this.host.featureState.commandPalette,e=>{e.isOpen()||e.open(this.buildCommandItems())})}buildCommandItems(){let e=[];for(let t of this.host.indicatorPickerItems())e.push({id:t.id,label:t.name,category:`indicator`,active:[...this.host.state.activeIndicators.values()].some(e=>e.id===t.id)});for(let n of t.m)e.push({id:n.value,label:t.t(n,this.host.t),category:`chartType`,active:this.host.state.chartType===n.value});let n=Mn();for(let r of t.n(t._,this.host.t))for(let t of r.tools)e.push({id:t.value,label:t.label,category:`drawing`,shortcut:n[t.value]?this.host.keysShown(`hotkeys.tools`,n[t.value]):void 0,active:this.host.state.activeTool===t.value});for(let t of this.host.timeframes)e.push({id:t,label:ve(t),category:`timeframe`,active:this.host.state.timeframe===t});return e.push({id:`symbolSearch`,label:this.host.t(`hotkeys.symbolSearch`),category:`action`,shortcut:this.host.keysShown(`hotkeys.symbolSearch`,`${l.t}+P`)},{id:`compare`,label:this.host.t(`compare.title`),category:`action`},{id:`goToDate`,label:this.host.t(`hotkeys.goToDate`),category:`action`,shortcut:this.host.keysShown(`hotkeys.goToDate`,`Alt+G`)},{id:`resetView`,label:this.host.t(`chartMenu.resetView`),category:`action`,shortcut:this.host.keysShown(`hotkeys.resetView`,`Alt+R`)},{id:`invertScale`,label:this.host.t(`hotkeys.invertScale`),category:`action`,shortcut:this.host.keysShown(`hotkeys.invertScale`,`Alt+I`)},{id:`saveLayout`,label:this.host.t(`hotkeys.saveLayout`),category:`action`,shortcut:this.host.keysShown(`hotkeys.save`,`${l.t}+S`)},{id:`watchlist`,label:this.host.t(`watchlist.title`),category:`action`},{id:`alerts`,label:this.host.t(`alerts.title`),category:`action`},{id:`objectTree`,label:this.host.t(`objects.title`),category:`action`},{id:`dataWindow`,label:this.host.t(`action.dataWindow`),category:`action`},{id:`symbolInfo`,label:this.host.t(`action.symbolInfo`),category:`action`},{id:`screenshot`,label:this.host.t(`action.screenshot`),category:`action`},{id:`copyImage`,label:this.host.t(`action.copyImage`),category:`action`},{id:`shareView`,label:this.host.t(`action.shareView`),category:`action`},{id:`toggleTheme`,label:this.host.t(`action.toggleTheme`),category:`action`},{id:`settings`,label:this.host.t(`action.settings`),category:`action`},{id:`autoFib`,label:this.host.t(`action.autoFib`),category:`action`},{id:`clearDrawings`,label:this.host.t(`action.clearDrawings`),category:`action`},{id:`clearIndicators`,label:this.host.t(`clear.indicators`),category:`action`},{id:`clearAll`,label:this.host.t(`clear.all`),category:`action`},{id:`hotkeys`,label:this.host.t(`hotkeys.title`),category:`action`,shortcut:this.host.keysShown(`hotkeys.help`,`?`)}),e.filter(e=>e.category!==`action`||this.commandOn(e.id)&&this.commandThere(e.id))}commandThere(e){return e===`watchlist`?this.host.watching.watchlist!==null:e===`compare`?this.host.adapter!==null&&this.host.options.chartOptions?.features?.compareSymbols!==!1:e===`saveLayout`?this.host.layoutSession!==null:!0}commandOn(e){let t=r.i(e);return t===void 0||this.host.featureState[t]}handleAction(e){if(this.commandOn(e))switch(e){case`symbolSearch`:this.host.openSymbolSearch();break;case`compare`:this.host.comparing.handleAddCompare();break;case`goToDate`:this.host.toggleGoToDate();break;case`resetView`:this.host.resetView();break;case`invertScale`:this.host.changeSettings({invertScale:!this.host.settingsState.invertScale});break;case`saveLayout`:this.host.saveLayout();break;case`watchlist`:case`alerts`:case`objectTree`:this.host.openPanel(e);break;case`hotkeys`:this.host.openHotkeySheet();break;case`screenshot`:this.host.chart.screenshot();break;case`toggleTheme`:this.host.handleToggleTheme();break;case`settings`:this.host.openSettings();break;case`copyImage`:this.host.copyChartImage();break;case`shareView`:this.host.copyShareLink();break;case`autoFib`:{let e=this.host.chart.autoFib();this.host.say(e?this.host.t(`toast.autoFibAdded`):this.host.t(`toast.noSwing`));break}case`dataWindow`:this.host.toggleDataWindow();break;case`symbolInfo`:this.host.toggleSymbolInfo();break;case`clearDrawings`:this.host.menus.removeAll(`drawings`);break;case`clearIndicators`:this.host.menus.removeAll(`indicators`);break;case`clearAll`:this.host.menus.removeAll(`all`);break}}},vs=0,ys=class{backdrop;search;listEl;layouts=[];confirming=null;returnFocus=null;loadSeq=0;uid=++vs;constructor(e,t,n=s.t){this.callbacks=t,this.t=n,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let r=!1;this.backdrop.addEventListener(`pointerdown`,e=>{r=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&r&&this.close(),r=!1});let a=document.createElement(`div`);a.className=`tcw-modal tcw-layouts-dialog`,a.setAttribute(`role`,`dialog`),a.setAttribute(`aria-modal`,`true`),a.setAttribute(`aria-labelledby`,`tcw-layouts-title-${this.uid}`),a.addEventListener(`keydown`,e=>{if(e.key!==`Escape`){i.n(e,a);return}e.stopPropagation(),this.confirming?this.setConfirming(null):this.close()});let o=document.createElement(`div`);o.className=`tcw-modal-header`;let c=document.createElement(`h3`);c.id=`tcw-layouts-title-${this.uid}`,c.textContent=this.t(`layouts.dialogTitle`);let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-modal-close`,l.setAttribute(`aria-label`,this.t(`common.close`)),l.innerHTML=i.i(`x`,16),l.addEventListener(`click`,()=>this.close()),o.append(c,l);let u=document.createElement(`label`);u.className=`tcw-ss-search tcw-layouts-search-row`,u.innerHTML=i.i(`search`,16),this.search=document.createElement(`input`),this.search.type=`search`,this.search.className=`tcw-layouts-search`,this.search.placeholder=this.t(`layouts.search`),this.search.setAttribute(`aria-label`,this.t(`layouts.search`)),this.search.autocomplete=`off`,this.search.addEventListener(`input`,()=>this.render()),u.appendChild(this.search),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-layouts-list`,this.listEl.setAttribute(`role`,`list`);let d=document.createElement(`div`);d.className=`tcw-layouts-body`,d.appendChild(this.listEl),a.append(o,u,d),this.backdrop.appendChild(a),e.appendChild(this.backdrop)}async open(){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.search.value=``,this.confirming=null,this.backdrop.hidden=!1,this.search.focus(),await this.refresh()}async refresh(){let e=++this.loadSeq,t;try{t=await this.callbacks.list()}catch{t=[]}e===this.loadSeq&&(this.layouts=t,this.render())}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.confirming=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}destroy(){this.close(),this.backdrop.remove()}shown(){let e=this.search.value.trim().toLowerCase();return e?this.layouts.filter(t=>t.name.toLowerCase().includes(e)||(t.symbol??``).toLowerCase().includes(e)):this.layouts}render(){let e=this.shown();if(e.length===0){let e=document.createElement(`p`);e.className=`tcw-account-empty`,e.textContent=this.t(this.layouts.length===0?`layouts.empty`:`layouts.noMatch`),this.listEl.replaceChildren(e);return}let t=this.callbacks.currentId();this.listEl.replaceChildren(...e.map(e=>this.row(e,e.id===t)))}row(e,t){let n=document.createElement(`div`);n.className=`tcw-layouts-row`,n.setAttribute(`role`,`listitem`),n.dataset.id=e.id;let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-layouts-open`,t&&r.setAttribute(`aria-current`,`true`);let a=document.createElement(`span`);a.className=`tcw-layouts-name`,a.textContent=e.name;let o=document.createElement(`span`);if(o.className=`tcw-layouts-meta`,o.textContent=[[e.symbol?(0,u.tickerOf)(e.symbol):``,e.timeframe].filter(Boolean).join(` · `),s.r(this.t(`layouts.updated`),{time:this.callbacks.formatTime(e.updatedAt)})].filter(Boolean).join(` — `),r.append(a,o),t){let e=document.createElement(`span`);e.className=`tcw-layouts-check`,e.innerHTML=i.i(`check`,14);let t=document.createElement(`span`);t.className=`tcw-visually-hidden`,t.textContent=this.t(`layouts.current`),r.prepend(e),r.appendChild(t)}r.addEventListener(`click`,()=>{this.callbacks.onOpen(e.id),this.close()});let c=document.createElement(`div`);if(c.className=`tcw-account-actions`,this.confirming===e.id){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-layouts-confirm`,t.textContent=this.t(`layouts.deleteConfirm`),t.setAttribute(`aria-label`,s.r(this.t(`layouts.deleteNamed`),{name:e.name})),t.addEventListener(`click`,()=>void this.remove(e.id));let n=this.iconButton(`x`,this.t(`common.cancel`),()=>this.setConfirming(null));c.append(t,n)}else c.append(this.iconButton(`penLine`,s.r(this.t(`layouts.renameNamed`),{name:e.name}),()=>this.callbacks.onRename(e)),this.iconButton(`trash`,s.r(this.t(`layouts.deleteNamed`),{name:e.name}),()=>this.setConfirming(e.id),!0));return n.append(r,c),n}iconButton(e,t,n,r=!1){let a=document.createElement(`button`);return a.type=`button`,a.className=`tcw-tree-btn${r?` tcw-tree-del`:``}`,a.setAttribute(`aria-label`,t),a.title=t,a.innerHTML=i.i(e,14),a.addEventListener(`click`,n),a}setConfirming(e){let t=this.confirming;this.confirming=e,this.render();let n=e??t;n&&[...this.listEl.querySelectorAll(`.tcw-layouts-row`)].find(e=>e.dataset.id===n)?.querySelector(e?`.tcw-layouts-confirm`:`.tcw-tree-del`)?.focus()}async remove(e){try{await this.callbacks.onDelete(e)}finally{this.confirming=null,await this.refresh(),this.isOpen()&&this.search.focus()}}},bs=5,xs=class{menu;prompt;dialog;destroyed=!1;constructor(e,t){this.session=e,this.host=t;let{root:n,t:r}=t;this.menu=new o.f(n,r(`toolbar.layouts`)),this.prompt=new ka(n,r),this.dialog=new ys(n,{list:()=>e.list(),currentId:()=>e.current()?.id??null,onOpen:e=>void this.open(e),onRename:e=>this.promptRename(e),onDelete:async t=>{try{await e.remove(t)}catch{this.host.toast(r(`layouts.deleteFailed`),`error`)}},formatTime:t.formatTime},r)}async save(){if(this.prompt.isOpen())return;if(!this.session.current()){this.promptSaveAs();return}let{t:e,toast:t}=this.host;try{let n=await this.session.save();n&&t(s.r(e(`layouts.saved`),{name:n.name}))}catch{t(e(`layouts.saveFailed`),`error`)}}async open(e){try{if(await this.session.open(e))return!0}catch{}return this.destroyed||this.host.toast(this.host.t(`layouts.openFailed`),`error`),!1}promptSaveAs(){let{t:e,toast:t}=this.host,n=this.session.current();this.prompt.open({title:e(`layouts.saveAsTitle`),value:n?s.r(e(`layouts.copyName`),{name:n.name}):``,submitLabel:e(`common.save`),onSubmit:async n=>{try{let r=await this.session.saveAs(n);t(s.r(e(`layouts.saved`),{name:r.name}))}catch(n){throw t(e(`layouts.saveFailed`),`error`),n}}})}promptRename(e=this.session.current()){if(!e)return;let{t,toast:n}=this.host;this.prompt.open({title:t(`layouts.renameTitle`),value:e.name,submitLabel:t(`layouts.renameSubmit`),onSubmit:async r=>{try{await this.session.rename(e.id,r)}catch(e){throw n(t(`layouts.saveFailed`),`error`),e}this.dialog.isOpen()&&this.dialog.refresh()}})}openDialog(){return this.dialog.open()}async openMenu(e){if(this.menu.isOpen()){this.menu.close();return}let{session:t}=this,{t:n}=this.host,r=[];try{r=(await t.list()).slice(0,bs)}catch{}if(this.destroyed)return;let i=t.current(),a=[{id:`save`,label:n(`layouts.save`),icon:`save`,shortcut:this.host.saveKeys?.()},{id:`saveAs`,label:n(`layouts.saveAs`),icon:`plus`}];i&&a.push({id:`rename`,label:n(`layouts.rename`),icon:`penLine`}),a.push({id:`autoSave`,label:n(`layouts.autoSave`),checked:t.isAutoSave()}),r.length>0&&a.push(`separator`,...r.map(e=>({id:`open:${e.id}`,label:e.name,checked:e.id===i?.id}))),a.push(`separator`,{id:`manage`,label:n(`layouts.open`),icon:`folder`}),this.menu.openUnder(a,e,e=>{e===`save`?this.save():e===`saveAs`?this.promptSaveAs():e===`rename`?this.promptRename():e===`autoSave`?t.setAutoSave(!t.isAutoSave()):e===`manage`?this.openDialog():e.startsWith(`open:`)&&this.open(e.slice(5))})}destroy(){this.destroyed=!0,this.menu.destroy(),this.prompt.destroy(),this.dialog.destroy()}},Ss=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Cs=globalThis.Buffer;function ws(e){if(Cs)return Cs.from(e,`utf8`).toString(`base64`);let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function Ts(e){if(Cs)return Cs.from(e,`base64`).toString(`utf8`);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return new TextDecoder().decode(n)}function Es(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Ds(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function Os(e){return Es(ws(JSON.stringify(e)))}function ks(e){if(!e)return null;try{let t=Ts(Ds(e)),n=JSON.parse(t);return!n||n.v!==1||typeof n.symbol!=`string`?null:{v:1,symbol:n.symbol,timeframe:n.timeframe,chartType:n.chartType,scaleMode:Na.find(e=>e===n.scaleMode)??`regular`,indicators:Array.isArray(n.indicators)?n.indicators:[],drawings:Array.isArray(n.drawings)?n.drawings:[],...Ss(n.settings)?{settings:L(n.settings,Ur)}:{}}}catch{return null}}var As=`tcw`;function js(e){let t=e.startsWith(`#`)?e.slice(1):e;for(let e of t.split(`&`)){let t=e.indexOf(`=`);if(!(t<=0||e.slice(0,t)!==As))try{return decodeURIComponent(e.slice(t+1))}catch{return null}}return null}function Ms(e,t){let[n]=e.split(`#`);return`${n}#${As}=${t}`}var Ns=[`legendVisible`,`volumeVisible`,`barCountdown`,`indicatorValueLabels`,`alignAxisLabels`],Ps=class{constructor(e){this.host=e}layoutSession=null;layoutsUI=null;layoutKeyPrefix=null;layoutDebounceMs=1500;activeLayoutKey=null;restoreSharedView(){if(!this.host.options.shareUrl||typeof location>`u`)return;let e=js(location.hash);e&&this.importState(e)}exportState(){let e=this.host.chart.getActiveIndicators().map(e=>({id:e.id,params:e.params})),n=this.host.getSettings(),r=ri(n,{...t.h,...Object.fromEntries(Ns.map(e=>[e,this.host.settingsDefaults[e]]))});return Os({v:1,symbol:this.host.state.symbol,timeframe:this.host.state.timeframe,chartType:this.host.state.chartType,scaleMode:n.scaleMode,indicators:e,drawings:this.host.chart.getDrawings(),...Object.keys(r).length>0?{settings:r}:{}})}async importState(e){let t=ks(e);if(!t)return!1;t.symbol&&t.symbol!==this.host.state.symbol&&await this.host.setSymbol(t.symbol),t.timeframe&&t.timeframe!==this.host.state.timeframe&&await this.host.setTimeframe(t.timeframe),t.chartType&&this.host.applyChartType(t.chartType);let{chartTypeOptions:n,...r}=this.host.allowedSettings({scaleMode:t.scaleMode,...L(t.settings,Ur)}),i=this.host.overViewerTypeOptions(t.chartType,n);return this.host.showLinkSettings(i?{...r,chartTypeOptions:i}:r),this.host.chart.applyIndicatorSetup(t.indicators.map((e,t)=>({id:e.id,instanceId:`shared_${t}`,params:e.params}))),this.host.chart.setDrawings(t.drawings),this.host.updateUI(),!0}async copyShareLink(){let e=Ms(typeof location<`u`?location.href:``,this.exportState());try{await navigator.clipboard.writeText(e),this.host.say(this.host.t(`toast.linkCopied`))}catch{this.host.say(this.host.t(`toast.copyFailed`),`error`)}}getLayoutSession(){return this.layoutSession}captureLayout(){let e=this.host.getSettings(),t=this.host.chart.saveState(),n=t?La(t):null,r=n&&typeof n==`object`?Fa(n):null;return{v:1,symbol:this.host.state.symbol,timeframe:this.host.chosenTimeframe??this.host.state.timeframe,scaleMode:e.scaleMode,invertScale:e.invertScale,chart:r,settings:ti(e,Hr)}}async restoreLayout(e){if(e.symbol!==this.host.state.symbol&&await this.host.setSymbol(e.symbol),e.timeframe!==this.host.state.timeframe&&await this.host.setTimeframe(e.timeframe),this.host.destroyed)return;if(e.chart){this.host.chart.loadState(JSON.stringify(Fa(e.chart)));let t=e.chart.chartType;typeof t==`string`&&(this.host.state={...this.host.state,chartType:t})}let t=this.host.allowedSettings({scaleMode:e.scaleMode,invertScale:e.invertScale,...L(e.settings,Hr)});this.host.claimSettings(Object.keys(t)),this.host.applySettings(t),this.host.syncIndicatorsFromChart(),this.host.updateUI(),this.host.settings?.refresh(this.host.shownSettings(),this.host.state.chartType)}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=Ia(La(e));return t?(await this.restoreLayout(t),!0):!1}setupLayouts(t){let n=new e.t(t.storage??e.i(),{capture:()=>({content:this.getLayoutContent(),symbol:this.host.state.symbol,timeframe:this.host.chosenTimeframe??this.host.state.timeframe}),apply:async e=>{if(!await this.applyLayoutContent(e.content))throw Error(`Not a widget layout`)}},{autoSave:t.autoSave,debounceMs:t.debounceMs,onChange:()=>this.host.toolbar?.setLayout(n.current()?.name??null,n.isDirty()),onError:()=>this.host.say(this.host.t(`layouts.saveFailed`),`error`)});this.layoutSession=n,this.layoutsUI=new xs(n,{root:this.host.root,t:this.host.t,saveKeys:()=>this.host.keysShown(`hotkeys.save`,`${l.t}+S`),toast:(e,t)=>this.host.say(e,t),formatTime:e=>{let{date:t,time:n}=Y(e,this.host.displayTimezone());return`${t} ${n}`}}),this.host.chart.on(`stateChange`,()=>n.changed()),t.openLast&&n.list().then(([e])=>e&&!this.host.destroyed?this.openLayout(e.id):void 0,()=>void 0)}async saveLayout(){await this.layoutsUI?.save()}async openLayout(e){return await this.layoutsUI?.open(e)??!1}clearSavedLayout(e){if(!this.layoutKeyPrefix)return;let t=e??this.host.state.symbol;try{localStorage.removeItem(this.layoutKeyPrefix+t)}catch{}}applySymbolLayout(e){if(!this.layoutKeyPrefix)return;let t=this.layoutKeyPrefix+e;this.activeLayoutKey=t;try{this.host.chart.loadStateFromStorage(t)&&this.host.syncIndicatorsFromChart()}catch{}this.host.chart.setAutoSave(t,this.layoutDebounceMs)}flushActiveLayout(){if(this.activeLayoutKey){try{this.host.chart.saveState(this.activeLayoutKey)}catch{}this.host.chart.disableAutoSave(),this.activeLayoutKey=null}}},Fs={alerts:`alerts`,objectTree:`objectTree`,dataWindow:`dataWindow`,symbolInfo:`symbolInfo`,depthLadder:`depthLadder`},Is={watchlist:`watchlist`,alerts:`alerts`,objectTree:`objects`,symbolInfo:`symbolInfo`,depthLadder:`trade`},Ls=class{dataWindowFrame=0;constructor(e){this.host=e}scheduleDataWindow(){this.dataWindowFrame||!this.host.dataWindow?.isOpen()||(this.dataWindowFrame=requestAnimationFrame(()=>{this.dataWindowFrame=0,this.host.dataWindow?.isOpen()&&this.host.dataWindow.render(this.buildDataWindowModel())}))}dock=null;dockNarrow=null;dockObserver=null;openPanel(e){return!this.hasPanel(e)||!this.dock?!1:(this.dock.open(e),this.dock.current()===e)}hasPanel(e){return e===`watchlist`?this.host.watching.watchlist!==null:e===`depthLadder`&&this.host.trading.depthLadder===null?!1:this.host.featureState[Fs[e]]}closePanel(){this.dock?.close()}getOpenPanel(){return this.dock?.current()??null}hoveredBar(){let e=this.host.lastHoverIndex;if(e===null||e<0)return null;if(!this.host.chart.isTimeAligned()){let e=this.host.lastHoverBar;return e?{bar:e,prevClose:this.host.lastHoverPrevClose??e.open}:null}let t=this.host.chart.getData();return e>=t.length?null:{bar:t[e],prevClose:e>0?t[e-1].close:t[e].open}}buildDataWindowModel(){let e=this.host.lastHoverIndex,t=this.hoveredBar();if(e===null||!t)return{ohlc:null,change:0,changePct:0,indicators:[]};let{bar:n,prevClose:r}=t,i=n.close-r,a=r===0?0:i/r*100,o=new Set(this.host.chart.getIndicatorPanes().flatMap(e=>e.instanceIds??[e.instanceId])),s=this.host.settingsState.numberLocale||`en-US`,c=this.host.chart.getActiveIndicators().map(t=>{let n=this.host.chart.getIndicatorOutput(t.instanceId,{drawn:!0})?.series?.[e]??null,r=!o.has(t.instanceId)&&hs(t),i=t.descriptor.plots?.map(e=>[e.key,e.title])??Object.keys(n??{}).map(e=>[e,e]),a=n?i.filter(([e])=>typeof n[e]==`number`&&Number.isFinite(n[e])).map(([e,t])=>{let i=n[e];return{key:t,value:i,text:this.host.indicatorValueText(i,r,s)}}):[];return{name:t.descriptor.name,values:a}}).filter(e=>e.values.length>0);return{ohlc:{open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume},change:i,changeText:this.host.formatAlertPrice(i,n.close),changePct:a,indicators:c}}toggleDataWindow(){!this.host.dataWindow||!this.host.featureState.dataWindow||this.dock?.toggle(`dataWindow`)}toggleWatchlist(){this.host.watching.watchlist&&this.dock?.toggle(`watchlist`)}toggleObjects(){!this.host.objectTree||!this.host.featureState.objectTree||this.dock?.toggle(`objectTree`)}setupDock(){let e=this.dock;if(!e)return;if(this.host.watching.watchlist){let t=this.host.watching.watchlist;e.addPage({id:`watchlist`,label:this.host.t(`watchlist.title`),icon:`list`,element:t.element,parts:[`dock.watchlist`],onShow:()=>{t.redraw(),this.host.markOpen(`watchlist`,!0)},onHide:()=>this.host.markOpen(`watchlist`,!1)})}let t=this.host.alerting.alertsPanel;t&&e.addPage({id:`alerts`,label:this.host.t(`alerts.title`),icon:`bell`,element:t.element,parts:[`dock.alerts`,`alerts`],onShow:()=>{t.openPanel(),this.host.alerting.refreshAlerts(),this.host.markOpen(`alerts`,!0)},onHide:()=>{t.close(),this.host.markOpen(`alerts`,!1)}});let n=this.host.objectTree;n&&e.addPage({id:`objectTree`,label:this.host.t(`objects.title`),icon:`layers`,element:n.element,parts:[`dock.objectTree`,`objectTree`],onShow:()=>{n.openPanel(),this.refreshObjects(),this.host.markOpen(`objects`,!0)},onHide:()=>{n.close(),this.host.markOpen(`objects`,!1)}});let r=this.host.dataWindow;r&&e.addPage({id:`dataWindow`,label:this.host.t(`dataWindow.title`),icon:`table`,element:r.element,parts:[`dock.dataWindow`,`dataWindow`],onShow:()=>{r.openPanel(),r.render(this.buildDataWindowModel())},onHide:()=>r.close()});let i=this.host.symbolInfoPanel;i&&e.addPage({id:`symbolInfo`,label:this.host.t(`symbolInfo.title`),icon:`info`,element:i.element,parts:[`dock.symbolInfo`,`symbolInfo`],onShow:()=>i.open(),onHide:()=>i.close()});let a=this.host.trading.depthLadder;a&&e.addPage({id:`depthLadder`,label:this.host.t(`ladder.title`),icon:`ladder`,element:a.element,parts:[`dock.depthLadder`,`depthLadder`],onShow:()=>a.openPanel(),onHide:()=>a.close()}),this.syncRail(),this.fitDockToWidth(),typeof ResizeObserver<`u`&&(this.dockObserver=new ResizeObserver(()=>this.fitDockToWidth()),this.dockObserver.observe(this.host.root))}fitDockToWidth(){let e=this.dock,t=this.host.root.clientWidth;if(!e||t===0)return;let n=t<641,r=this.dockNarrow;this.dockNarrow=n,n&&r!==!0&&e.close()}railShown(){return this.host.featureState.dock&&!this.host.root.hasAttribute(`data-tcw-narrow`)}syncRail(){this.dock?.syncRail();let e=this.railShown();this.host.toolbar?.setRailed(`watchlist`,e&&this.host.featureState[`dock.watchlist`]),this.host.toolbar?.setRailed(`alerts`,e&&this.host.featureState[`dock.alerts`]),this.host.toolbar?.setRailed(`objects`,e&&this.host.featureState[`dock.objectTree`]),this.host.toolbar?.fit()}panelFocusTarget(e){let t=Is[e],n=t?this.host.root.querySelector(`.tcw-toolbar [data-role="${t}"]`):null,r=this.host.root.hasAttribute(`data-tcw-narrow`);return n&&!n.hidden&&!(r&&n.classList.contains(`tcw-toolbar-overflow`))?n:this.host.root.querySelector(`.tcw-toolbar-more`)??this.host.chartContainer}closePanelByHand(e){this.dock?.closePage(e)}refreshObjects(){if(this.host.refreshDrawingsState(),!this.host.objectTree)return;let e=this.host.chart.getActiveIndicators().map(e=>({instanceId:e.instanceId,name:c.r(e,this.host.t),title:e.descriptor.name,visible:e.visible})),t=this.host.chart.getDrawings().map(e=>({id:e.id,label:e.name||Mr(e.type,this.host.t),visible:e.visible,offInterval:e.visible&&!this.host.chart.isDrawingShown(e.id),locked:e.locked,group:e.group})),n=this.host.comparing.comparedNow().map(e=>({id:e.id,label:(0,u.tickerOf)(e.symbol),color:e.color,way:e.way}));this.host.objectTree.setObjects(e,t,n)}},Rs=new Set([`timezone`,`numberLocale`,`chartTypeOptions`,`logScale`,`autoScale`]),zs=80,Bs=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Vs(e){return L(e,Rs)}function Hs(e){let{overrides:n}=(0,u.readChartStyleOverrides)(e);return Object.fromEntries(Object.entries(n).filter(([e,n])=>n!==null&&t.l.includes(e)))}function Us(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Ws=class{constructor(e=`tcw:chart-templates`,t=Us()){this.key=e,this.storage=t}list(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`[]`)}catch{return[]}if(!Array.isArray(e))return[];let t=[];for(let n of e)!Bs(n)||typeof n.name!=`string`||!n.name.trim()||t.push({name:n.name.slice(0,zs).trim(),settings:Vs(n.settings),style:Hs(n.style)});return t.sort((e,t)=>e.name.localeCompare(t.name))}get(e){return this.list().find(t=>t.name===e)??null}save(e,t,n){let r=e.replace(/\s+/g,` `).slice(0,zs).trim();if(!r||!this.storage)return!1;let i=[...this.list().filter(e=>e.name!==r),{name:r,settings:Vs(t),style:Hs(n)}];try{return this.storage.setItem(this.key,JSON.stringify(i)),!0}catch{return!1}}remove(e){try{this.storage?.setItem(this.key,JSON.stringify(this.list().filter(t=>t.name!==e)))}catch{}}},Gs=new Set([...Br,`autoScale`]),Ks=class{constructor(e){this.host=e}chartTemplates=new Ws;chartTemplatePrompt=null;settingsEdit=null;state=it(t.h);dialogChanging=0;get settingsState(){return this.state.peek()}set settingsState(e){this.state.set(e)}followCrosshairCursor(){return this.state.get().crosshairCursor}settingsDefaults;settingsStore=null;settingsPublished=null;linkSettings=null;settingsListeners=new Set;settingsLocked=new Set;refreshScaleSwitches(){this.host.statusBar?.setScale({mode:this.host.chart.getScaleMode(),auto:this.host.chart.isAutoScale()})}toggleScaleMode(e){this.changeSettings({scaleMode:this.host.chart.getScaleMode()===e?`regular`:e})}showLinkSettings(e){let t=this.getSettings(),n=Object.keys(e),r=this.linkSettings,i={...Object.fromEntries(n.map(e=>[e,t[e]])),...r?.own};this.applySettings(e,!1),this.linkSettings={shown:{...r?.shown,...e},own:i},this.markSettingsTold()}ownSettings(e){let t=this.linkSettings;if(!t)return e;let n=Object.keys(t.shown).filter(n=>JSON.stringify(e[n])===JSON.stringify(t.shown[n]));return{...e,...Object.fromEntries(n.map(e=>[e,t.own[e]]))}}claimSettings(e){let t=this.linkSettings;if(!t)return;let n=new Set(e),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e))),i=r(t.shown);Object.keys(i).length!==Object.keys(t.shown).length&&(this.linkSettings=Object.keys(i).length>0?{shown:i,own:r(t.own)}:null,this.settingsPublished!==null&&!this.host.destroyed&&this.settingsStore?.save(this.ownSettings(this.getSettings()),this.settingsDefaults))}effectiveScaleMode(){return this.host.comparing.holdsPercentScale()?`percentage`:this.settingsState.scaleMode}userScaleMode(){return this.host.comparing.holdsPercentScale()?this.settingsState.scaleMode:this.host.chart.getScaleMode()}shownSettings(){return{...this.settingsState,scaleMode:this.effectiveScaleMode()}}showScaleMode(){let e=this.effectiveScaleMode();this.host.chart.getScaleMode()!==e&&this.host.chart.setScaleMode(e)}openSettings(e){this.host.whenLoaded(this.host.settingsPart,()=>this.host.featureState.settings,t=>this.showSettings(t,e))}showSettings(e,t){e.isOpen()||(this.syncSettingsFromChart(),this.markSettingsTold(),this.settingsEdit={settings:{...this.settingsState},style:this.settingsStyle(),keys:new Set,styleKeys:new Set,held:this.host.comparing.compareScaleHeld},e.open(this.shownSettings(),this.host.state.chartType,t))}endSettingsEdit(e){let t=this.settingsEdit;if(this.settingsEdit=null,!t)return;let n=[...t.keys],r=e=>Object.fromEntries(n.map(t=>[t,e[t]])),i=[...t.styleKeys],a=r(t.settings),o=i.length>0?{theme:t.style.theme,overrides:Object.fromEntries(i.map(e=>[e,t.style.overrides[e]??null]))}:null,s=t.keys.has(`scaleMode`),c=this.host.comparing.compareScaleHeld;if(!e){this.restoreSettings(a,o,s?t.held:void 0);return}let l=r(this.getSettings()),u=i.length>0?this.settingsStyle(i):null;(JSON.stringify([a,o])!==JSON.stringify([l,u])||s&&t.held!==c)&&this.host.chart.recordUndo({undo:()=>this.restoreSettings(a,o,s?t.held:void 0),redo:()=>this.restoreSettings(l,u,s?c:void 0)}),this.claimSettings(n),this.publishSettings()}touchSettings(e,t=[]){if(!this.settingsEdit){this.claimSettings(e);return}for(let t of e)this.settingsEdit.keys.add(t);for(let e of t)this.settingsEdit.styleKeys.add(e)}applyChartTemplate(e){let n=this.chartTemplates.get(e);if(!n)return;let r=this.allowedSettings(n.settings);this.touchSettings(Object.keys(r),t.l),this.applySettings(r),this.host.chart.resetOverrides([...t.l],{layer:`user`}),this.host.chart.applyOverrides(n.style,{layer:`user`}),this.host.settings?.refresh(this.shownSettings()),this.host.say(s.r(this.host.t(`templates.applied`),{name:e}))}promptSaveChartTemplate(){this.chartTemplatePrompt??=new ka(this.host.overlayHost(),this.host.t),this.chartTemplatePrompt.open({title:this.host.t(`settings.saveTemplateTitle`),submitLabel:this.host.t(`common.save`),placeholder:this.host.t(`settings.templatePlaceholder`),onSubmit:e=>{if(!this.chartTemplates.save(e,this.settingsState,this.settingsStyle().overrides))throw this.host.say(this.host.t(`templates.saveFailed`),`error`),Error(`The template could not be saved`);this.host.say(s.r(this.host.t(`templates.saved`),{name:e}))}})}getSettings(){return this.syncSettingsFromChart(),JSON.parse(JSON.stringify(this.settingsState))}setSettings(e){let t=this.allowedSettings(this.withoutEarlyFreeze(L(e)));this.claimSettings(Object.keys(t)),this.applySettings(t)}withoutEarlyFreeze(e){return e.autoScale!==!1||this.host.chart.getData().length>0?e:Object.fromEntries(Object.entries(e).filter(([e])=>e!==`autoScale`))}onSettingsChange(e){return this.settingsListeners.add(e),()=>{this.settingsListeners.delete(e)}}syncSettingsFromChart(){let e=this.host.chart,n=e.getTimeZone?.(),r=e.getMarketProfileConfig?.(),i=e.getPivotMarkersConfig?.(),a=this.allowedSettings(L({gridVisible:e.isGridVisible?.(),volumeVisible:e.isVolumeVisible?.(),legendVisible:e.isLegendVisible?.(),barCountdown:e.isBarCountdownVisible?.(),indicatorValueLabels:e.isIndicatorValueLabelsVisible?.(),alignAxisLabels:e.isAxisLabelsAligned?.(),leftPriceScale:e.isLeftPriceScaleVisible?.(),volumeProfileVisible:e.isVolumeProfileVisible?.(),marketProfileVisible:e.isMarketProfileVisible?.(),marketProfileSplit:r?.splitBySession,marketProfileLetters:r?.letters,marketProfileBuckets:r?.buckets,marketProfileOpacity:r?.opacity,depthHeatmapVisible:e.isDepthHeatmapVisible?.(),depthHeatmapOpacity:e.getDepthHeatmapConfig?.()?.opacity,pivotMarkersVisible:e.isPivotMarkersVisible?.(),pivotStrength:i?.left,pivotStructureLabels:i?.structureLabels,sessionShadingVisible:e.isSessionShadingVisible?.(),periodLevelsVisible:e.isPeriodLevelsVisible?.(),periodLevelsPeriod:e.getPeriodLevelsPeriod?.(),crosshairMode:e.getCrosshairMode?.(),crosshairCursor:e.getCrosshairCursor?.(),scaleMode:this.userScaleMode(),autoScale:e.isAutoScale?.(),invertScale:e.isInvertScale?.(),timezone:n===void 0?void 0:t.b(n),numberLocale:e.getNumberLocale?.(),highLowLines:e.isHighLowLinesVisible?.(),extendedHours:e.isExtendedHoursVisible?.(),mainSeriesVisible:e.isMainSeriesVisible?.(),chartTypeOptions:e.getChartTypeOptions?.()})),o=a.scaleMode?{logScale:a.scaleMode===`logarithmic`}:{},s=a.chartTypeOptions?{chartTypeOptions:qr(a.chartTypeOptions)}:{};this.settingsState={...this.settingsState,...a,...o,...s}}allowedSettings(e){let t=this.settingsLocked,n=(e,n)=>e===`scaleMode`?n===`logarithmic`&&t.has(`logScale`):n===!0&&t.has(e);return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0&&!n(e,t)))}restoreKeptSettings(){let e=this.allowedSettings(this.settingsStore?.load()??{});Object.keys(e).length>0&&this.applySettings(e),this.settingsPublished=JSON.stringify(this.getSettings())}markSettingsTold(){this.settingsPublished!==null&&(this.settingsPublished=JSON.stringify(this.getSettings()))}publishSettings(){if(this.settingsPublished===null||this.host.destroyed)return;let e=this.getSettings(),t=JSON.stringify(e);if(t!==this.settingsPublished){this.settingsPublished=t,this.settingsStore?.save(this.ownSettings(e),this.settingsDefaults);for(let e of[...this.settingsListeners])try{e(JSON.parse(t))}catch(e){console.error(`[TradeCanvas] An onSettingsChange listener threw:`,e)}}}followSettings(){return at(()=>{this.state.get(),!(this.dialogChanging>0)&&this.host.settings?.follow(this.shownSettings())})}changeFromDialog(e){this.dialogChanging++;try{this.changeSettings(e)}finally{this.dialogChanging--}}applySettings(e,t=!0){ot(()=>this.applySettingsNow(e,t))}applySettingsNow(e,n){this.settingsState={...this.settingsState,...e},Object.keys(e).some(e=>!Gs.has(e))&&this.host.layouts.layoutSession?.changed(),this.host.legend.scheduleLegend(),e.gridVisible!==void 0&&this.host.chart.setGridVisible(e.gridVisible),e.volumeVisible!==void 0&&this.host.chart.setVolumeVisible(e.volumeVisible),e.volumeProfileVisible!==void 0&&this.host.chart.setVolumeProfileVisible(e.volumeProfileVisible),e.marketProfileVisible!==void 0&&this.host.chart.setMarketProfileVisible(e.marketProfileVisible),e.marketProfileSplit!==void 0&&this.host.chart.setMarketProfileConfig({splitBySession:e.marketProfileSplit}),e.marketProfileLetters!==void 0&&this.host.chart.setMarketProfileConfig({letters:e.marketProfileLetters}),e.marketProfileBuckets!==void 0&&this.host.chart.setMarketProfileConfig({buckets:e.marketProfileBuckets}),e.marketProfileOpacity!==void 0&&this.host.chart.setMarketProfileConfig({opacity:e.marketProfileOpacity}),e.depthHeatmapVisible!==void 0&&this.host.chart.setDepthHeatmapVisible(e.depthHeatmapVisible),e.depthHeatmapOpacity!==void 0&&this.host.chart.setDepthHeatmapConfig({opacity:e.depthHeatmapOpacity}),e.sessionShadingVisible!==void 0&&this.host.chart.setSessionShadingVisible(e.sessionShadingVisible),e.pivotMarkersVisible!==void 0&&this.host.chart.setPivotMarkersVisible(e.pivotMarkersVisible),e.pivotStrength!==void 0&&this.host.chart.setPivotMarkersConfig({left:e.pivotStrength,right:e.pivotStrength}),e.pivotStructureLabels!==void 0&&this.host.chart.setPivotMarkersConfig({structureLabels:e.pivotStructureLabels}),e.periodLevelsVisible!==void 0&&this.host.chart.setPeriodLevelsVisible(e.periodLevelsVisible),e.periodLevelsPeriod!==void 0&&this.host.chart.setPeriodLevelsPeriod(e.periodLevelsPeriod),e.legendVisible!==void 0&&this.host.chart.setLegend({visible:e.legendVisible}),e.barCountdown!==void 0&&this.host.chart.setBarCountdownVisible(e.barCountdown),e.indicatorValueLabels!==void 0&&this.host.chart.setIndicatorValueLabelsVisible(e.indicatorValueLabels),e.alignAxisLabels!==void 0&&this.host.chart.setAxisLabelsAligned(e.alignAxisLabels),e.crosshairMode!==void 0&&this.host.chart.setCrosshairMode(e.crosshairMode),e.crosshairCursor!==void 0&&this.host.chart.setCrosshairCursor(e.crosshairCursor),e.autoScale!==void 0&&this.host.chart.setAutoScale(e.autoScale),e.invertScale!==void 0&&this.host.chart.setInvertScale(e.invertScale),e.leftPriceScale!==void 0&&(this.host.chart.setLeftPriceScaleVisible(e.leftPriceScale),this.host.placeDrawingButton()),(e.scaleMode!==void 0||e.autoScale!==void 0)&&queueMicrotask(()=>this.refreshScaleSwitches()),e.timezone!==void 0&&queueMicrotask(()=>this.host.statusBar?.tick()),e.scaleMode===void 0?e.logScale!==void 0&&(this.settingsState={...this.settingsState,scaleMode:e.logScale?`logarithmic`:`regular`},this.showScaleMode()):(this.settingsState={...this.settingsState,logScale:e.scaleMode===`logarithmic`},this.showScaleMode()),e.numberLocale!==void 0&&(this.host.chart.setNumberLocale(e.numberLocale),this.host.watching.watchlist?.setLocale(e.numberLocale||void 0)),e.timezone!==void 0&&this.host.chart.setTimeZone(t.v(e.timezone)),e.highLowLines!==void 0&&this.host.chart.setHighLowLines(e.highLowLines),e.extendedHours!==void 0&&this.host.chart.setExtendedHours(e.extendedHours),e.mainSeriesVisible!==void 0&&this.host.chart.setMainSeriesVisible(e.mainSeriesVisible),e.chartTypeOptions!==void 0&&this.host.chart.setChartTypeOptions({...Jr(),...e.chartTypeOptions}),n&&!this.settingsEdit&&this.publishSettings()}resetSettings(){let e={...this.settingsState},n=this.settingsStyle(),r={...this.settingsDefaults};this.touchSettings(Object.keys(r),t.l),this.applySettings(r),this.host.chart.resetOverrides([...t.l],{layer:`user`});let i={...this.settingsState},a=this.settingsStyle();this.host.settings?.refresh(this.shownSettings()),!(this.settingsEdit||JSON.stringify([e,n])===JSON.stringify([i,a]))&&this.host.chart.recordUndo({undo:()=>this.restoreSettings(e,n),redo:()=>this.restoreSettings(i,a)})}changeStyle(e){let t=Object.keys(e);this.touchSettings([],t);let n=this.settingsStyle(t);this.host.chart.applyOverrides(e,{layer:`user`});let r=this.settingsStyle(t);this.settingsEdit||JSON.stringify(n)===JSON.stringify(r)||this.host.chart.recordUndo({subject:`style:${Object.keys(e).sort().join(`,`)}`,undo:()=>this.restoreSettings({},n),redo:()=>this.restoreSettings({},r)})}changeSettings(e){let t=Object.keys(e);if(t.includes(`scaleMode`)||t.includes(`logScale`))for(let e of[`scaleMode`,`logScale`])t.includes(e)||t.push(e);let n=()=>Object.fromEntries(t.map(e=>[e,this.settingsState[e]]));this.touchSettings(t);let r=n(),i=t.includes(`scaleMode`),a=this.host.comparing.compareScaleHeld;i&&(this.host.comparing.compareScaleHeld=!1),this.applySettings(e);let o=n();this.settingsEdit||JSON.stringify(r)===JSON.stringify(o)&&a===this.host.comparing.compareScaleHeld||this.host.chart.recordUndo({subject:`settings:${Object.keys(e).sort().join(`,`)}`,undo:()=>this.restoreSettings(r,null,i?a:void 0),redo:()=>this.restoreSettings(o,null,i?!1:void 0)})}settingsStyle(e=t.l){let n=this.host.chart.getOverrides?.({layer:`user`})??{},r=Object.fromEntries(e.map(e=>{let t=n[e];return[e,typeof t==`string`||typeof t==`boolean`||typeof t==`number`?t:null]}));return{theme:this.host.chart.getTheme()?.name??``,overrides:r}}restoreSettings(e,t=null,n){n!==void 0&&(this.host.comparing.compareScaleHeld=n&&this.host.comparing.compares.length>0),this.applySettings(e),t&&t.theme===(this.host.chart.getTheme()?.name??``)&&this.host.chart.applyOverrides(t.overrides,{layer:`user`}),this.host.settings?.refresh(this.shownSettings())}},qs=13,Js=8,Ys=6,Xs=1.3,Zs=120,Qs=2,$s=8,ec=20;function tc(e){let t=e.filter(e=>e!==null);if(t.length===0)return null;let n=Math.min(...t.map(e=>e.x)),r=Math.min(...t.map(e=>e.y)),i=Math.max(...t.map(e=>e.x+e.width)),a=Math.max(...t.map(e=>e.y+e.height));return{x:n,y:r,width:i-n,height:a-r}}var nc=class{constructor(e){this.host=e}justDrawnText=null;inlineText=null;inlineTextId=null;inlineTextNew=!1;chartFontWritten=null;cancelTextPrompt=null;selectionToolbar=null;selectionToolbarFrame=null;drawingTemplatePrompt=null;scheduleSelectionToolbar(){this.selectionToolbarFrame!==null||!this.selectionToolbar?.isOpen()||(this.selectionToolbarFrame=requestAnimationFrame(()=>{this.selectionToolbarFrame=null,this.updateSelectionToolbar()}))}updateSelectionToolbar(){let e=this.selectionToolbar;if(!e||this.host.destroyed)return;let t=this.host.chart.getSelectedDrawingIds();if(!this.host.featureState.selectionToolbar||!t?.length){e.hide();return}let n=new Set(t),r=this.host.chart.getDrawings().filter(e=>n.has(e.id)&&this.host.chart.isDrawingShown(e.id));if(this.host.chart.getDrawingTool()!==null||this.host.chart.isEraserMode()||this.host.chart.isZoomAreaMode()||r.length===0){e.hide();return}let i=this.host.chartOffset(),a=r[0],o=(a.paneId===void 0?void 0:this.host.chart.getIndicatorPanes().find(e=>e.instanceId===a.paneId)?.rect)??this.host.chart.getPlotRect(),s=this.host.chart.getPlotRect(),c=tc(r.flatMap(e=>[this.host.chart.getDrawingRect(e.id),this.host.chart.getDrawingTextRect?.(e.id)??null]))??{x:o.x+o.width/2,y:o.y,width:0,height:0};e.show({rect:{x:c.x+i.x,y:c.y+i.y,width:c.width,height:c.height},bounds:{x:s.x+i.x,y:s.y+i.y,width:s.width,height:s.height},style:a.style,locked:r.every(e=>e.locked),canDelete:r.some(e=>!e.locked),canSettings:this.host.featureState.drawingSettings&&r.length===1,canAlert:this.host.featureState.alerts&&r.length===1&&this.host.chart.canAddDrawingAlert(a.id),canFill:this.host.chart.getDrawingToolDescriptor(a.type)?.fill===!0,canText:this.host.chart.getDrawingToolDescriptor(a.type)?.text===!0,canType:r.length===1&&this.canTypeText(a.id)})}canTypeText(e){let t=this.host.chart.getDrawings().find(t=>t.id===e);return t!==void 0&&!t.locked&&(B[t.type]!==void 0||Di.has(t.type))}isOnDrawingText(e,t,n){let r=this.host.chart.getDrawingTextRect(e);return r!=null&&t>=r.x-$s&&t<=r.x+r.width+$s&&n>=r.y-$s&&n<=r.y+r.height+$s}editDrawingText(e){this.canTypeText(e)&&(this.editTextInPlace(e,!1)||this.openDrawingSettings(e,{tab:`text`}))}placedTextRect(e,t,n){let r=this.host.chart.getDrawingTextRect(e);if(r){let t=(this.host.chart.getDrawings().find(t=>t.id===e)?.style.text??``).trim(),i=Math.min(ec,t.split(`
|
|
7958
7958
|
`).length)*n,a=r.height>i+Qs,o=a?Math.hypot(r.width,r.height):r.width,s=a?i:r.height;return{x:r.x+(r.width-o)/2-Js,y:r.y+(r.height-s)/2-Ys,width:o+Js*2,height:s+Ys*2}}let i=this.host.chart.getDrawingRect(e);if(!i)return null;let a=n+Ys*2;return{x:i.x+(i.width-Zs)/2,y:t===`rectangle`?i.y:i.y+i.height/2-a,width:Zs,height:a}}editTextInPlace(e,t){if(e===this.inlineTextId&&this.inlineText?.isOpen())return!0;let n=this.host.chart.getDrawings().find(t=>t.id===e),r=this.inlineText,i=n?B[n.type]:void 0,a=n!==void 0&&!i&&Di.has(n.type);if(!n||!r||n.locked||!i&&!a||!t&&!this.host.chart.beginDrawingEdit(e))return!1;let o=n.style,s=(a?this.host.chart.getDrawingTextSize(e):null)||o.fontSize||i?.fontSize||qs,c=o.text??``,l=n=>{this.inlineTextId=null,t?n||this.host.chart.takeBackDrawing(e):this.host.chart.endDrawingEdit(e,{cancel:!n}),this.host.docking.refreshObjects()};return r.open({rect:()=>{let t=a?this.placedTextRect(e,n.type,s*Xs):this.host.chart.getDrawingTextRect(e);if(!t)return null;let r=this.host.chartContainer.getBoundingClientRect();return{x:r.left+t.x,y:r.top+t.y,width:t.width,height:t.height}},text:c,font:{size:s,bold:o.bold===!0,italic:o.italic===!0,family:this.host.chart.getFont?.()?.family??this.host.ui.font.family},color:o.textColor??Oi[n.type]??o.color,label:this.host.t(`drawingSettings.text`),placeholder:a?this.host.t(`drawingSettings.text`):this.host.drawingToolName(n.type),onInput:n=>t?this.host.chart.amendNewDrawing(e,{style:{text:n}}):this.host.chart.updateDrawing(e,{style:{text:n}}),onCommit:n=>{let r=n.replace(/\s+$/,``);if(a){if(r===c){l(!1);return}r!==n&&this.host.chart.updateDrawing(e,{style:{text:r}}),l(!0);return}r&&r!==n&&(t?this.host.chart.amendNewDrawing(e,{style:{text:r}}):this.host.chart.updateDrawing(e,{style:{text:r}})),l(r.length>0)},onCancel:()=>l(!1),returnFocus:()=>this.host.chartContainer.querySelector(`[tabindex]`)??this.host.chartContainer})?(this.inlineTextId=e,this.inlineTextNew=t,!0):(t||this.host.chart.endDrawingEdit(e,{cancel:!0}),!1)}openDrawingSettings(e,t={}){this.host.whenLoaded(this.host.drawingSettingsPart,()=>this.host.featureState.drawingSettings,n=>this.showDrawingSettings(n,e,t))}showDrawingSettings(e,t,n){let r=this.host.chart.getDrawings().find(e=>e.id===t),i=r?this.host.chart.getDrawingToolDescriptor(r.type):null;!r||!i||(e.open({id:t,type:r.type,name:this.host.drawingToolName(r.type),style:{...r.style},options:this.host.chart.getDrawingOptions(t),defs:i.options??{},anchors:r.anchors.map(e=>({...e})),fill:i.fill===!0,text:i.text===!0,textLayout:B[r.type],textColor:Oi[r.type],textPlace:Di.has(r.type),coordinates:i.anchoring!==`screen`,intervals:r.intervals??null},{tab:n.tab}),n.justDrawn&&e.isOpen()&&(this.justDrawnText=t))}promptSaveDrawingTemplate(e,t){this.drawingTemplatePrompt??=new ka(this.host.root,this.host.t),this.drawingTemplatePrompt.open({title:this.host.t(`drawingSettings.saveTemplateTitle`),submitLabel:this.host.t(`common.save`),placeholder:this.host.drawingToolName(t.type),onSubmit:n=>{e.save(n,t.style,{type:t.type,options:t.options}),this.host.say(s.r(this.host.t(`templates.saved`),{name:n.trim()}))}})}},rc=200,ic=class{constructor(e){this.host=e}intervalInput=null;rangeSeq=0;rangeQueue=Promise.resolve();applyRangePreset(e){let t=++this.rangeSeq;return this.rangeQueue=this.rangeQueue.then(()=>this.runRangePreset(e,t)).catch(e=>{this.host.say(e instanceof Error?e.message:String(e),`error`)}),this.rangeQueue}async runRangePreset(e,t){let n=()=>t===this.rangeSeq&&!this.host.destroyed;if(!n())return;this.host.chosenTimeframe??=this.host.state.timeframe;let r=this.host.featureState[`statusBar.rangeTimeframe`]?this.timeframeForPreset(e):this.host.state.timeframe;r!==this.host.state.timeframe&&(await this.host.switchTimeframe(r),!n()||this.host.adapter&&this.host.state.connectionState===`error`)||this.host.chart.setVisibleRangePreset(e)}timeframeForPreset(e){let t=this.host.state.timeframe,n=this.host.chart.getData();if(n.length<2)return t;let r=(0,u.barTimeUnit)(n),i=n[n.length-1].time*r,a=e===`All`?n[0].time*r:(0,d.rangePresetStart)(e,i,this.host.displayTimezone());if(a===null)return t;let o=n.length-1;for(;o>0&&n[o-1].time*r>=a;)o--;let s=this.host.displayTimezone();return Me({dayShare:n.slice(-rc).some(e=>{let t=e.time*r,n=new Date(t+(0,u.offsetAt)(s,t)*6e4).getUTCDay();return n===0||n===6})?1:5/7,spanMs:i-a,barsInSpan:n.length-o,width:this.host.chart.getPlotRect().width,current:t,chosen:this.host.chosenTimeframe??t,available:this.host.timeframes.filter(e=>this.host.chart.isTimeframeAllowed(e)&&this.canShowTimeframe(e))})}canShowTimeframe(e){if(this.host.adapter)return(0,d.servesTimeframe)(this.host.adapter,e);if(this.host.options.resampleTimeframes===!1)return!1;let t=this.host.chart.getData();if(t.length<2)return!1;let n=this.host.baseSeries?this.host.baseTimeframeMs:p(t);return!(n>0)||(0,u.timeframeToMs)(e)>=n}pinnedTimeframes(){let e=this.host.timeframeFavorites.list();return this.host.timeframes.filter(t=>e.includes(t))}timeframeMenu(){return this.host.timeframes.map(e=>({value:e,label:ve(e),custom:this.host.customTimeframes.has(e)}))}handleAddTimeframe(e){if(!this.host.featureState.customTimeframes)return!1;let t=Ee(e);return!t||!this.host.chart.isTimeframeAllowed(t)||this.host.adapter&&!(0,d.servesTimeframe)(this.host.adapter,t)||!this.host.adapter&&(0,u.tickBarCount)(t)!==null?!1:(this.host.timeframes.includes(t)||(this.host.customTimeframes.add(t),this.host.timeframeFavorites.add(t),this.host.timeframes=De(this.host.timeframes,[t]),this.host.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes())),this.host.handleTimeframe(t),!0)}selectTypedTimeframe(e){return!this.host.chart.isTimeframeAllowed(e)||!this.host.timeframes.includes(e)&&!this.host.featureState.customTimeframes||this.host.adapter&&!(0,d.servesTimeframe)(this.host.adapter,e)?!1:(this.host.timeframes.includes(e)||(this.host.customTimeframes.add(e),this.host.timeframes=De(this.host.timeframes,[e]),this.host.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes())),this.host.handleTimeframe(e),!0)}handleRemoveTimeframe(e){this.host.customTimeframes.has(e)&&(this.host.customTimeframes.remove(e),this.host.timeframeFavorites.remove(e),this.host.timeframes=this.host.timeframes.filter(t=>t!==e),this.host.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes()),this.host.updateUI())}handleToggleTimeframeFavorite(e){this.host.timeframeFavorites.toggle(e),this.host.toolbar?.setTimeframeFavorites(this.pinnedTimeframes()),this.host.updateUI()}},ac=600,oc=24,sc=[`--tcw-toolbar-h`,`--tcw-control-h`,`--tcw-control-h-sm`,`--tcw-icon`,`--tcw-sidebar-w`,`--tcw-tool-h`,`--tcw-tool-icon`,`--tcw-menu-item-h`,`--tcw-font-size`,`--tcw-font-size-sm`,`--tcw-font-size-xs`,`--tcw-font-size-lg`,`--tcw-font-size-xl`,`--tcw-font-size-display`,`--tcw-line-height`,`--tcw-line-xs`,`--tcw-label-size`],cc=48,lc=5e4,uc=100;function dc(){return new Promise(e=>{if(typeof requestAnimationFrame!=`function`||document.hidden){setTimeout(e,0);return}let t=setTimeout(e,uc);requestAnimationFrame(()=>setTimeout(()=>{clearTimeout(t),e()},0))})}var fc=864e5,pc=5e3,mc=2e3,hc=48,gc=`rgba(255,255,255,0.03)`,_c=`rgba(0,0,0,0.03)`,vc=2;function yc(e){if(e.ctrlKey||e.metaKey||e.altKey||e.isComposing||e.keyCode===229||e.getModifierState?.(`AltGraph`))return null;if(/^[a-z]$/i.test(e.key))return e.key;let t=/^Key([A-Z])$/.exec(e.code??``);return t&&[...e.key].length===1&&!/[\s\d]/.test(e.key)?t[1].toLowerCase():null}var bc=1e3,xc=[[`barCountdown`,`barCountdown`],[`logScale`,`logScale`],[`legendVisible`,`legend`],[`volumeVisible`,`volume`]],Sc=t.l.filter(e=>u.CHART_STYLE_KEYS[e]!==`color`);function Cc(e){if(!e.feed)return e;if(e.adapter)throw TypeError(`A widget takes an adapter or a feed, not both`);return{...e,adapter:(0,d.adapterFromFeed)(e.feed),feed:void 0}}var wc=class{intervals=new ic(this.intervalsHost());drawingEdit=new nc(this.drawingEditHost());chartSettings=new Ks(this.chartSettingsHost());docking=new Ls(this.dockingHost());layouts=new Ps(this.layoutsHost());commands=new _s(this.commandsHost());legend=new gs(this.legendHost());menus=new rs(this.menusHost());trading=new ts(this.tradingHost());alerting=new es(this.alertingHost());marking=new An(this.markingHost());watching=new $o(this.watchingHost());comparing=new Qo(this.comparingHost());chart;state;themeOf={dark:u.DARK_THEME,light:u.LIGHT_THEME};toolbar=null;openRoles=it(new Set);sidebar=null;settingsPart=null;get settings(){return this.settingsPart?.get()??null}statusBar=null;goToDatePart=null;get goToDate(){return this.goToDatePart?.get()??null}tooltip;indicatorLegend=null;portal=document.createElement(`div`);stopKeyboardInset=null;stopNarrow=null;stopFormControls=null;overlayHost=()=>{let e=document.fullscreenElement===this.root?this.root:document.body;return this.portal.parentElement!==e&&e.appendChild(this.portal),this.portal};unregisterKeys=()=>{};onFullscreenChange=()=>{this.drawingEdit.inlineText?.commit(),this.toolbar?.setFullscreen(document.fullscreenElement===this.root),this.portal.isConnected&&this.overlayHost()};commandPalettePart=null;get commandPalette(){return this.commandPalettePart?.get()??null}symbolSearchPart=null;get symbolSearch(){return this.symbolSearchPart?.get()??null}typedWhileLoading=``;hotkeySheetPart=null;get hotkeySheet(){return this.hotkeySheetPart?.get()??null}replay;dragDrop=null;objectTree=null;indicatorSettingsPart=null;get indicatorSettings(){return this.indicatorSettingsPart?.get()??null}indicatorPickerPart=null;get indicatorPicker(){return this.indicatorPickerPart?.get()??null}drawingStyle=null;drawingSettingsPart=null;get drawingSettings(){return this.drawingSettingsPart?.get()??null}canExport=!0;symbolLoads=new Map;ui;uiScale=1;uiVariables=!1;chartFontBase=null;scaleObserver=null;templates=new Ma;templatePrompt=null;markerTip=null;dataWindow=null;lastHoverIndex=null;lastHoverBar=null;lastHoverPrevClose=null;legendHoverIndex=null;pointerOnChart=!1;favoritesStore=new za;indicatorFavorites=new za(`tcw:indicator-favorites`);indicatorDefaults=new Lr;timeframeFavorites=new za(`tcw:tf-favorites`);customTimeframes=new za(`tcw:tf-custom`);timeframes=[];sessionRefPrice=null;symbolInfoPanel=null;news=new xn;marketTimer=null;clockTimer=null;onPageShown=null;chartNav=null;visibleBarCount=50;root;chartContainer;loading;historyPill;connectSeq=0;localSeq=0;lastLocalSwitchMs=0;destroyed=!1;scope=st();stopPreload=null;waitingShow=new Map;look;options;symbols;symbolCatalog;chartInfoAtSwitch=null;t;adapter=null;boundGlobalKeydown=null;baseSeries=null;baseTimeframeMs=0;builtInZone=void 0;chosenTimeframe=null;featureState;hostHotkeys=[];hostMenus=new Set;hostLayer=null;priceAxisAddDefault=!1;marksDefault=!0;constructor(e,t={}){let n=Cc(t);this.options=n;let{isDark:r,resolvedTheme:i,features:a,chartFeatures:o}=this.readOptions(n);this.buildRoot(e,n,r,i),this.buildToolbar(n,a);let s=this.buildBody(n,a);this.buildChart(n,i,a,o),this.buildStatusBar(a),this.buildDialogs(a),this.followChart(),this.wireDrawingEditing(),this.wireChartMenus(),this.buildTrading(n,s),this.buildAlerts(n),this.buildPanels(a),this.buildCommandPalette(),this.finishSetup(n)}readOptions(e){let n=a.o(e.symbols??t.g);this.symbols=n.names,this.symbolCatalog=n.info;let i=e.chartOptions;if(this.chartSettings.settingsState={...t.h,...i?.crosshair?.mode?{crosshairMode:i.crosshair.mode}:{},...(0,d.isCrosshairCursor)(i?.crosshair?.cursor)?{crosshairCursor:i.crosshair.cursor}:{},...i?.logScale&&i.features?.logScale!==!1?{logScale:!0,scaleMode:`logarithmic`}:{},...i?.numberLocale?{numberLocale:i.numberLocale}:{},...i?.timeZone==null?{}:{timezone:t.b(i.timeZone)},...i?.leftPriceScale===void 0?{}:{leftPriceScale:i.leftPriceScale},...i?.highLowLines===void 0?{}:{highLowLines:i.highLowLines},...i?.extendedHours===void 0?{}:{extendedHours:i.extendedHours},...i?.chartTypeOptions?{chartTypeOptions:(0,u.readChartTypeOptions)(i.chartTypeOptions)}:{}},this.t=s.n(s.o(e.locale,e.messages)),this.featureState=r.u(e),e.persistLayouts){let t=e.persistLayouts===!0?{}:e.persistLayouts;this.layouts.layoutKeyPrefix=t.keyPrefix??`tcw:layout:`,this.layouts.layoutDebounceMs=t.debounceMs??1500}let o=ii(e.persistSettings);o&&(this.chartSettings.settingsStore=new oi(o));let c=this.resolveIsDark(e.theme),l=this.resolveTheme(e.theme);this.themeOf={...this.themeOf,[c?`dark`:`light`]:l};let f={drawings:!0,drawingMagnet:!0,drawingUndoRedo:!0,indicators:!0,trading:e.trading!==!1,tradingContextMenu:!1,priceAxisAddButton:this.featureState.alerts||e.trading!==!1||this.featureState.sidebar,volume:!0,legend:!0,crosshair:!0,crosshairTooltip:!1,keyboard:!0,screenshot:!0,alerts:!0,barCountdown:!0,logScale:!0,watermark:!0,...e.chartOptions?.features};this.priceAxisAddDefault=f.priceAxisAddButton===!0;let p={...f,priceAxisAddButton:this.priceAxisAddDefault&&this.featureState[`menu.priceAxisAdd`],marks:f.marks!==!1&&this.featureState.marks};if(this.marksDefault=f.marks!==!1,this.canExport=f.dataExport!==!1,this.chartSettings.settingsLocked=new Set(xc.filter(([,e])=>f[e]===!1).map(([e])=>e)),this.chartSettings.settingsDefaults={...this.chartSettings.settingsState,legendVisible:f.legend!==!1,volumeVisible:f.volume!==!1,barCountdown:f.barCountdown!==!1,indicatorValueLabels:f.indicatorValueLabels===!0,alignAxisLabels:f.alignAxisLabels!==!1},this.chartSettings.settingsState={...this.chartSettings.settingsDefaults},this.timeframes=De(xe(e.timeframes,f.timeframes),this.customTimeframes.list(),f.timeframes),!this.timeframes.some(e=>this.timeframeFavorites.has(e))){let t=Se(this.timeframes,f.defaultTimeframeFavorites,!!e.timeframes?.length);for(let e of t)this.timeframeFavorites.add(e)}let m=e.timeframe??`5m`,h=!f.timeframes?.length||f.timeframes.includes(m)?m:this.timeframes[0]??m;return this.state={symbol:e.symbol??this.symbols[0]??`BTCUSDT`,timeframe:h,chartType:e.chartOptions?.chartType??`candlestick`,isDark:c,activeIndicators:new Map,activeTool:null,magnetEnabled:!1,magnetStrong:!1,eraser:!1,zoomArea:!1,stayInDrawing:!1,connectionState:e.adapter?`connecting`:`disconnected`,connectionMessage:e.adapter?this.t(`status.connecting`):``},{isDark:c,resolvedTheme:l,features:f,chartFeatures:p}}buildRoot(e,t,n,r){fe(),this.root=document.createElement(`div`),this.root.className=`tcw-root`;let i=t.dir===`ltr`||t.dir===`rtl`?t.dir:Nc(t.locale)?`rtl`:`ltr`;this.root.dir=i,this.portal.dir=i,e.appendChild(this.root),this.tooltip=new so(this.root),this.portal.className=`tcw-root tcw-portal`,this.look=it({dark:n,theme:r});let a=!1;this.scope.run(()=>at(()=>{let{dark:e,theme:t}=this.look.get();this.root.dataset.tcwTheme=this.portal.dataset.tcwTheme=e?`dark`:`light`,a&&(this.keepingLook(()=>this.chart.setTheme(t)),this.paintWatermark())})),a=!0,this.stopKeyboardInset=Ba([this.root,this.portal]),this.stopNarrow=Va(this.root,e=>{this.toolbar?.fit(),e||this.sidebar?.closeOverlay(),this.docking.syncRail()}),this.ui=I(t.ui),this.uiVariables=t.ui!==void 0,this.uiScale=this.scaleNow(),this.applyLookTokens(),typeof ResizeObserver<`u`&&(this.scaleObserver=new ResizeObserver(()=>this.fitScale()),this.scaleObserver.observe(this.root)),this.markSwitchedOff(),this.stopFormControls=ae([this.root,this.portal],{layer:this.overlayHost,labels:()=>({prevMonth:this.t(`calendar.prevMonth`),nextMonth:this.t(`calendar.nextMonth`),today:this.t(`calendar.today`)}),locale:()=>this.intlLocale()})}buildToolbar(e,n){this.toolbar=new He(this.root,{symbols:this.symbols,timeframes:this.intervals.timeframeMenu(),timeframeFavorites:this.intervals.pinnedTimeframes(),chartTypes:e.chartTypes?t.m.filter(t=>e.chartTypes.includes(t.value)):t.m},{onSymbolClick:()=>this.handleSymbolClick(),onSymbolInfo:()=>this.toggleSymbolInfo(),onTimeframe:e=>this.handleTimeframe(e),onToggleTimeframeFavorite:e=>this.intervals.handleToggleTimeframeFavorite(e),onAddTimeframe:e=>this.intervals.handleAddTimeframe(e),onRemoveTimeframe:e=>this.intervals.handleRemoveTimeframe(e),onChartType:e=>this.handleChartType(e),onIndicators:()=>this.toggleIndicatorPicker(),onScreenshot:()=>this.chart.screenshot(),onSettings:()=>this.chartSettings.openSettings(),onToggleTheme:()=>this.handleToggleTheme(),onToggleReplay:()=>this.toggleReplay(),onToggleAlerts:()=>this.alerting.toggleAlerts(),onToggleObjects:()=>this.docking.toggleObjects(),onToggleWatchlist:e.watchlist?()=>this.docking.toggleWatchlist():void 0,onToggleAccount:e.trading===!1?void 0:()=>this.trading.toggleAccountPanel(),onLayouts:e.layouts===!1?void 0:e=>void this.layouts.layoutsUI?.openMenu(e),onBracket:e.trading===!1?void 0:e=>this.trading.startBracket(e),onToggleLadder:e.trading!==!1&&e.depthLadder?()=>this.trading.toggleLadder():void 0,onOrderTicket:e.trading===!1?void 0:()=>this.trading.openOrderTicket(),onCompare:e.adapter&&n.compareSymbols!==!1?()=>this.comparing.handleAddCompare():void 0,onUndo:()=>this.chart.undo(),onRedo:()=>this.chart.redo(),onToggleFullscreen:typeof document<`u`&&document.fullscreenEnabled?()=>this.toggleFullscreen():void 0},this.t,this.overlayHost);let r=new Set;this.scope.run(()=>at(()=>{let e=this.openRoles.get();for(let t of new Set([...r,...e]))r.has(t)!==e.has(t)&&(t===`indicators`?this.toolbar?.setIndicatorsOpen(e.has(t)):this.toolbar?.setActive(t,e.has(t)));r=e}))}buildBody(e,n){let i=document.createElement(`div`);i.className=`tcw-body`,e.drawingFavorites&&this.favoritesStore.seedDefaults(e.drawingFavorites),this.sidebar=new xt(i,{drawingToolGroups:t.n(t._,this.t),favorites:this.favoritesStore.list(),shortcuts:Mn()},{onDrawingTool:e=>this.handleDrawingTool(e),onCancelDrawing:()=>this.handleCancelDrawing(),onCrosshairCursor:e=>this.setCrosshairCursor(e),onToggleMagnet:n.drawingMagnet===!1?void 0:()=>this.handleToggleMagnet(),onToggleEraser:()=>this.chart.setEraserMode(!this.chart.isEraserMode()),onToggleZoomArea:()=>this.chart.setZoomAreaMode(!this.chart.isZoomAreaMode()),onToggleFavorite:e=>this.handleToggleFavorite(e),onClear:e=>this.menus.openClearMenu(e),onToggleStyle:()=>this.drawingStyle?.toggle(),onToggleStayInDrawing:()=>this.handleToggleStayInDrawing(),onLockAll:e=>{this.chart.setDrawingsLocked(this.chart.getDrawings().map(e=>e.id),e),this.refreshDrawingsState(),this.docking.refreshObjects()},onHideAll:e=>{this.chart.setDrawingsVisible(this.chart.getDrawings().map(e=>e.id),!e),this.refreshDrawingsState(),this.docking.refreshObjects()}},this.t),this.scope.run(()=>at(()=>{let e=this.chartSettings.followCrosshairCursor();this.sidebar?.showCrosshairCursor(e)})),this.chartContainer=document.createElement(`div`),this.chartContainer.className=`tcw-chart-container`,this.chartContainer.dir=`ltr`,i.appendChild(this.chartContainer),this.loading=new Lo(this.chartContainer,this.t(`status.loading`)),this.historyPill=new zo(this.chartContainer,{loading:this.t(`history.loading`),failed:this.t(`history.failed`)}),this.docking.dock=new Ya(i,{labels:{rail:this.t(`dock.rail`),resize:this.t(`dock.resize`)},savedWidth:()=>jc(),saveWidth:e=>Mc(e),railShown:()=>this.docking.railShown(),focusAfterClose:e=>this.docking.panelFocusTarget(e),room:()=>i.clientWidth}),this.docking.dock.setScale(this.uiScale),e.watchlist&&this.watching.createWatchlist(i,e.watchlist===!0?{}:e.watchlist),this.root.appendChild(i);let a=document.createElement(`div`);return a.className=`tcw-account-dock`,r.o(a,`accountPanel`),this.root.appendChild(a),a}buildChart(t,n,r,i){this.chart=new e.h(this.chartContainer,{chartType:this.state.chartType,theme:n,autoScale:!0,crosshair:{mode:`magnet`},a11y:{labels:{role:this.t(`a11y.role`),summary:this.t(`a11y.summary`),empty:this.t(`a11y.empty`),view:this.t(`a11y.view`),bar:this.t(`a11y.bar`),keys:this.t(`a11y.keys`),typeName:e=>{let t=`chartType.${e}`,n=this.t(t);return n===t?e:n}}},...t.chartOptions,features:i}),t.chartOptions?.shapes||this.applyChartShapes(),this.chartInfoAtSwitch=this.chart.getSymbolInfo(),this.applyLegendFont(),this.applyChartLook();for(let[e,t]of this.indicatorDefaults.all())this.chart.setIndicatorDefaults(e,t.style);this.chart.on(`visibleRangeChange`,e=>{let{from:t,to:n}=e.payload;Number.isFinite(t)&&Number.isFinite(n)&&(this.visibleBarCount=Math.max(1,n-t))}),this.chartNav=new Ln(this.chartContainer,{zoomIn:()=>this.chart.zoomIn(),zoomOut:()=>this.chart.zoomOut(),scroll:e=>this.chart.scrollBars(e*Math.max(1,Math.round(this.visibleBarCount/10))),reset:()=>this.resetView(),plotRect:()=>this.chart.getPlotRect()},this.t),this.chart.on(`dataUpdate`,e=>this.handleDataUpdate(e.payload)),this.chart.on(`historyLoad`,e=>{let t=e.payload;this.historyPill.update(t),t.state===`loaded`&&this.comparing.extendPercentCompares()}),this.chart.on(`symbolInfoChange`,()=>{this.refreshSymbolTitle(),this.refreshMarket(),this.rebuildForZone(),this.refreshPriceTexts()}),this.chart.on(`marketChange`,()=>this.rebuildForZone()),this.refreshSymbolTitle(),this.symbolInfoPanel=new mn(this.root,this.t,{onClose:()=>this.docking.closePanelByHand(`symbolInfo`),onToggle:e=>{this.markOpen(`symbolInfo`,e),e&&(this.refreshSymbolInfo(),this.loadNews())}}),this.marketTimer=setInterval(()=>this.refreshMarket(),3e4),this.onPageShown=()=>{Xt()||this.refreshMarket()},document.addEventListener(`visibilitychange`,this.onPageShown),this.dragDrop=new e.p(this.chartContainer,{onData:(e,t,n)=>{this.setData(e);let r=s.r(this.t(`toast.fileLoaded`),{count:t.data.length,file:n.name});this.say(t.skipped>0?`${r} (${s.r(this.t(`toast.fileSkipped`),{count:t.skipped})})`:r)},onError:(e,t)=>{this.say(`${t.name}: ${e.message}`,`error`)}}),this.featureState.dragDropImport&&this.dragDrop.attach(),r.drawingMagnet!==!1&&this.chart.setDrawingMagnetMode(`off`)}buildStatusBar(e){this.statusBar=new jt(this.root,{presets:d.RANGE_PRESETS,presetLabels:{All:this.t(`range.all`)},groupLabel:this.t(`range.presets`),goToLabel:this.t(`range.goTo`),moreLabel:this.t(`toolbar.more`),onPreset:e=>void this.intervals.applyRangePreset(e),onGoTo:()=>this.toggleGoToDate(),goToKeys:()=>this.keysShown(`hotkeys.goToDate`,`Alt+G`)},{label:this.t(`statusBar.label`),clock:{label:this.t(`settings.timezone`),now:()=>this.clockNow(),options:()=>({current:this.chartSettings.settingsState.timezone,list:t.y(this.chartSettings.settingsState.timezone,Date.now(),this.t(`settings.timezone.local`),this.menus.exchangeChoice())}),onPick:e=>this.chartSettings.changeSettings({timezone:e})},scale:{labels:{group:this.t(`settings.priceScale`),percent:this.t(`settings.scale.percentage`),log:this.t(`settings.scale.logarithmic`),auto:this.t(`settings.autoScale`)},texts:{log:this.t(`statusBar.log`),auto:this.t(`statusBar.auto`)},onPercent:()=>this.chartSettings.toggleScaleMode(`percentage`),onLog:e.logScale===!1?void 0:()=>this.chartSettings.toggleScaleMode(`logarithmic`),onAuto:()=>this.chartSettings.changeSettings({autoScale:!this.chart.isAutoScale()})}}),this.clockTimer=setInterval(()=>{!Xt()&&this.featureState.statusBar&&this.featureState[`statusBar.clock`]&&this.statusBar?.tick()},bc),this.chart.on(`priceRangeChange`,()=>this.chartSettings.refreshScaleSwitches()),this.chartSettings.refreshScaleSwitches(),this.goToDatePart=this.lazyPart(J.goToDate,({WidgetGoToDate:e})=>new e(this.overlayHost,()=>({title:this.t(`goTo.title`),date:this.t(`range.date`),range:this.t(`goTo.range`),from:this.t(`goTo.from`),to:this.t(`goTo.to`),time:this.t(`range.time`),submit:this.t(`range.goToSubmit`),cancel:this.t(`range.cancel`),close:this.t(`common.close`),calendar:{prevMonth:this.t(`calendar.prevMonth`),nextMonth:this.t(`calendar.nextMonth`),today:this.t(`calendar.today`)}}),()=>this.intlLocale(),e=>this.goTo(e)))}buildDialogs(e){this.settingsPart=this.lazyPart(J.settings,({WidgetSettings:t})=>new t({onChange:e=>this.chartSettings.changeFromDialog(e),onReset:()=>this.chartSettings.resetSettings(),onClose:()=>this.chartSettings.endSettingsEdit(!0),onCancel:()=>this.chartSettings.endSettingsEdit(!1),templates:{list:()=>this.chartSettings.chartTemplates.list().map(e=>e.name),apply:e=>this.chartSettings.applyChartTemplate(e),remove:e=>this.chartSettings.chartTemplates.remove(e),save:()=>this.chartSettings.promptSaveChartTemplate()},styleValue:e=>this.chart.getStyleValue?.(e)??null,onStyleChange:e=>this.chartSettings.changeStyle(e)},this.t,{barCountdown:e.barCountdown,logScale:e.logScale,legend:e.legend,volume:e.volume,trading:e.trading!==!1,exchangeZone:()=>this.menus.exchangeChoice()?.zone},this.overlayHost)),this.symbolSearchPart=this.lazyPart(J.symbolSearch,({WidgetSymbolSearch:e})=>new e({onPick:e=>{this.setSymbol(e)},onClose:()=>{}},this.overlayHost,this.t)),this.hotkeySheetPart=this.lazyPart(J.hotkeySheet,({WidgetHotkeySheet:e})=>new e({onClose:()=>{}},this.t,this.overlayHost)),this.scope.run(()=>this.chartSettings.followSettings())}followChart(){this.chart.on(`drawingToolChange`,e=>{let t=e.payload.tool;t!==this.state.activeTool&&(this.state={...this.state,activeTool:t},this.updateUI())}),this.chart.on(`toolModeChange`,e=>{let{eraser:t,zoomArea:n}=e.payload;this.state={...this.state,eraser:t??this.state.eraser,zoomArea:n??this.state.zoomArea},this.updateUI()}),this.chart.on(`indicatorAdd`,()=>this.syncIndicatorsFromChart()),this.chart.on(`indicatorRemove`,()=>this.syncIndicatorsFromChart()),this.chart.on(`legendResize`,()=>this.legend.scheduleLegend()),this.chart.setPaneTitlesVisible(!this.featureState.indicatorLegend),this.indicatorLegend=new vo(this.chartContainer,{onToggleVisible:(e,t,n)=>{n===`compare`?this.chart.setCompareVisible(e,t):this.chart.setIndicatorVisible(e,t),this.legend.scheduleLegend(),this.objectTree?.isOpen()&&this.docking.refreshObjects()},onSettings:e=>{this.featureState[`indicatorLegend.settings`]&&this.openIndicatorSettings(e)},onRemove:(e,t)=>{this.comparing.isPercentCompare(e)?this.comparing.handleRemoveCompare(e):t===`compare`?this.comparing.removeHostCompare(e):this.handleRemoveIndicator(e)},onMore:(e,t)=>this.legend.openLegendMenu(e,t),onPaneAction:(e,t)=>this.legend.runPaneAction(e,t),onStackResize:e=>this.chart.setLegendStack?.(e?{width:ms(this.chart)+e.width,height:1+e.height}:null)},{show:this.t(`legend.show`),hide:this.t(`legend.hide`),settings:this.t(`legend.settings`),remove:this.t(`legend.remove`),collapse:this.t(`legend.collapse`),expand:this.t(`legend.expand`),more:this.t(`legend.more`),paneUp:this.t(`pane.moveUp`),paneDown:this.t(`pane.moveDown`),paneCollapse:this.t(`pane.collapse`),paneExpand:this.t(`pane.expand`),paneMaximize:this.t(`pane.maximize`),paneRestore:this.t(`pane.restore`),offInterval:this.t(`indicatorSettings.offInterval`),offChartType:this.t(`legend.offChartType`)}),this.legend.legendMenu=new o.f(this.root,this.t(`legend.more`)),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.pointerOnChart=!0,this.legendHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.legend.scheduleLegend()}),this.chart.on(`crosshairLeave`,()=>{this.pointerOnChart=!1,this.legendHoverIndex=null,this.legend.scheduleLegend()}),this.chart.on(`crosshairSync`,e=>{if(this.pointerOnChart)return;let t=e.payload;this.legendHoverIndex=t.bar&&t.barIndex!==null?t.barIndex:null,this.legend.scheduleLegend()});for(let e of[`indicatorUpdate`,`indicatorChange`,`dataUpdate`,`resize`,`paneResize`,`paneChange`,`themeChange`,`timeframeChange`,`visibleRangeChange`,`compareChange`])this.chart.on(e,()=>this.legend.scheduleLegend());this.chart.on(`chartTypeChange`,()=>{this.comparing.compareScaleHeld&&this.comparing.showHeldScale(),this.legend.scheduleLegend()}),this.replay=new Jt(this.replayHost()),this.replay.attach();for(let e of[`resize`,`dataUpdate`,`symbolInfoChange`])this.chart.on(e,()=>this.placeDrawingButton());this.placeDrawingButton(),this.dataWindow=new Mo(this.root,{formatPrice:e=>this.formatAlertPrice(e),formatPercent:e=>this.formatNumber(e,2),formatVolume:e=>this.formatVolume(e),onClose:()=>this.docking.closePanelByHand(`dataWindow`)},this.t),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.lastHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.lastHoverBar=t.bar??null,this.lastHoverPrevClose=typeof t.prevClose==`number`?t.prevClose:null,this.dataWindow?.isOpen()&&this.dataWindow.render(this.docking.buildDataWindowModel())}),this.chart.on(`indicatorUpdate`,()=>this.docking.scheduleDataWindow()),this.chart.on(`crosshairSync`,e=>{if(this.pointerOnChart)return;let t=e.payload;this.lastHoverIndex=t.bar&&t.barIndex!==null?t.barIndex:null,this.lastHoverBar=t.bar??null,this.lastHoverPrevClose=typeof t.prevClose==`number`?t.prevClose:null,this.dataWindow?.isOpen()&&this.dataWindow.render(this.docking.buildDataWindowModel())})}wireDrawingEditing(){let e=new di,t=new fi;for(let[e,n]of Object.entries(t.all()))this.chart.setDrawingToolDefaults(e,n??null);this.drawingSettingsPart=this.lazyPart(J.drawingSettings,({WidgetDrawingSettings:n})=>new n(this.root,{onBegin:e=>this.chart.beginDrawingEdit(e),onChange:(e,t)=>this.chart.updateDrawing(e,t),onEnd:(e,t)=>{this.chart.endDrawingEdit(e,{cancel:t}),t&&e===this.drawingEdit.justDrawnText&&this.chart.takeBackDrawing(e),this.drawingEdit.justDrawnText=null,this.docking.refreshObjects()},toWallTime:e=>Y(e*(0,u.barTimeUnit)(this.chart.getData()),this.displayTimezone()),fromWallTime:(e,t)=>{let n=Ka(e,t,this.displayTimezone());return n===null?null:n/(0,u.barTimeUnit)(this.chart.getData())},roundPrice:e=>this.chart.roundPrice(e),priceStep:()=>this.chart.getPriceStep(),onSaveDefault:(e,n)=>{this.chart.setDrawingToolDefaults(e,n),t.set(e,this.chart.getDrawingToolDefaults(e)),this.say(s.r(this.t(`drawingSettings.defaultSaved`),{name:this.drawingToolName(e)}))},templates:{list:t=>e.list(t),save:t=>this.drawingEdit.promptSaveDrawingTemplate(e,t),remove:(t,n)=>e.remove(t,n)}},this.t)),this.drawingEdit.inlineText=new Li(this.overlayHost),this.chart.on(`drawingDoubleClick`,e=>{let{id:t,x:n,y:r}=e.payload,i=this.chart.getDrawings().find(e=>e.id===t)?.type;i&&B[i]&&this.drawingEdit.editTextInPlace(t,!1)||i&&Di.has(i)&&this.drawingEdit.isOnDrawingText(t,n,r)&&this.drawingEdit.editTextInPlace(t,!1)||this.drawingEdit.openDrawingSettings(t,i&&B[i]?{tab:`text`}:{})}),this.chart.on(`drawingRemove`,e=>{let t=e.payload.id;t===this.drawingEdit.inlineTextId&&(this.drawingEdit.inlineText?.close(),this.drawingEdit.inlineTextNew||this.chart.endDrawingEdit(t),this.drawingEdit.inlineTextId=null)}),this.chart.on(`drawingCreate`,e=>{let{id:t,type:n,drawn:r}=e.payload;if(!r||!B[n])return;this.drawingEdit.cancelTextPrompt?.();let i=0,a=()=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,s),clearTimeout(i),this.drawingEdit.cancelTextPrompt=null},o=()=>{a(),!(this.destroyed||!this.chart.getDrawings().some(e=>e.id===t))&&(this.drawingEdit.editTextInPlace(t,!0)||this.drawingEdit.openDrawingSettings(t,{tab:`text`,justDrawn:!0}))},s=()=>setTimeout(o,0);window.addEventListener(`pointerup`,s),window.addEventListener(`pointercancel`,s),i=window.setTimeout(o,ac),this.drawingEdit.cancelTextPrompt=a}),this.drawingStyle=new gi(this.root,{onStyleChange:e=>{this.chart.setDrawingStyle(e),this.chart.setSelectedDrawingStyle(e)},getStyle:()=>this.chart.getDrawingStyle()},e,this.t)}wireChartMenus(){this.menus.drawingMenu=new o.f(this.root,this.t(`drawingMenu.label`)),this.chart.on(`drawingContextMenu`,e=>{let{id:t,x:n,y:r}=e.payload;this.menus.openDrawingMenu(t,n,r)}),this.drawingEdit.selectionToolbar=new Ti(this.root,{onStyle:e=>{for(let t of this.chart.getSelectedDrawingIds()){let n=this.chart.getDrawings().find(e=>e.id===t)?.type,r=n?B[n]:void 0,i=e.fillColor!==void 0&&r&&!r.box?{...e,textBackground:!0}:e;this.chart.setSelectedDrawingStyle(i,t)}this.drawingEdit.updateSelectionToolbar()},onSettings:()=>{let e=this.chart.getSelectedDrawingIds()[0];e&&this.drawingEdit.openDrawingSettings(e)},onText:()=>{let e=this.chart.getSelectedDrawingIds()[0];e&&this.drawingEdit.editDrawingText(e)},onAlert:()=>{let e=this.chart.getSelectedDrawingIds()[0];e&&this.alerting.addDrawingAlert(e)},onLock:e=>{this.chart.setDrawingsLocked(this.chart.getSelectedDrawingIds(),e),this.docking.refreshObjects(),this.drawingEdit.updateSelectionToolbar()},onMore:(e,t)=>{let n=this.chart.getSelectedDrawingIds()[0];if(!n)return;let r=this.chartOffset();this.menus.openDrawingMenu(n,e-r.x,t-r.y)},onDelete:()=>{this.chart.removeDrawings(this.chart.getSelectedDrawingIds()),this.docking.refreshObjects(),this.drawingEdit.updateSelectionToolbar()}},this.t);for(let e of[`drawingCreate`,`drawingUpdate`,`drawingRemove`])this.chart.on(e,()=>this.refreshDrawingsState());this.chart.on(`historyChange`,e=>{let{canUndo:t,canRedo:n}=e.payload;this.toolbar?.setHistory(t,n)});for(let e of[`drawingSelect`,`drawingToolChange`,`toolModeChange`])this.chart.on(e,()=>this.drawingEdit.updateSelectionToolbar());for(let e of[`drawingUpdate`,`drawingRemove`,`historyChange`,`visibleRangeChange`,`priceRangeChange`,`zoomChange`,`resize`,`paneResize`,`paneChange`,`dataUpdate`,`replayStep`,`chartTypeChange`])this.chart.on(e,()=>this.drawingEdit.scheduleSelectionToolbar());this.menus.chartMenu=new o.f(this.root,this.t(`chartMenu.label`),this.t(`common.back`)),this.chart.on(`symbolSeriesRequest`,e=>void this.comparing.loadSymbolSeries(e.payload.symbol)),this.chart.on(`chartContextMenu`,e=>{if(!this.featureState[`menu.chart`])return;let{area:t,x:n,y:i,price:a,time:o,pane:s}=e.payload,c=a===void 0?void 0:this.chart.roundPrice(a),l={...this.menus.chartMenuContext(c),...s?{pane:this.chart.getPaneScale(s)}:{}};this.menus.menuPane=s??null,this.menus.openChartMenu(r.a(Ji(t,l,this.t),r.t,this.featureState),n,i,{area:t,price:c,time:o})}),this.chart.on(`priceAxisAdd`,e=>{if(!this.featureState[`menu.priceAxisAdd`])return;let{price:t,x:n,y:i}=e.payload,a=this.chart.roundPrice(t),o=r.a(Hi(this.menus.chartMenuContext(a),this.t),r.t,this.featureState);this.menus.openChartMenu(o,n,i,{area:`priceAxisAdd`,price:a})}),this.chart.on(`signalMarkerHover`,e=>this.showMarkerTip(e.payload)),this.intervals.intervalInput=new ja(this.chartContainer,{title:this.t(`interval.title`),hint:this.t(`interval.hint`),invalid:this.t(`interval.invalid`)},e=>this.intervals.selectTypedTimeframe(e))}buildTrading(e,t){if(e.layouts!==!1&&this.layouts.setupLayouts(e.layouts===!0||e.layouts===void 0?{}:e.layouts),e.trading!==!1){this.trading.orderTicket=new wa(this.root,{onSubmit:e=>{this.chart.placeOrderIntent(e),this.say(s.r(this.t(`ticket.sent`),{side:this.t(e.side===`buy`?`ticket.buy`:`ticket.sell`),quantity:e.quantity??1,price:this.formatAlertPrice(e.price)}))},formatPrice:e=>this.formatAlertPrice(e),formatAmount:e=>this.formatMoney(e),formatNumber:(e,t)=>this.formatNumber(e,t)},this.t),this.trading.accountPanel=new sa(t,{onClosePosition:e=>this.chart.closePositionIntent(e),onReversePosition:e=>this.chart.reversePositionIntent(e),onCancelOrder:e=>this.chart.cancelOrderIntent(e),onNewOrder:()=>this.trading.openOrderTicket(),formatPrice:e=>this.formatAlertPrice(e),formatTime:e=>{let{date:t,time:n}=Y(e,this.displayTimezone());return`${t} ${n}`},formatAmount:e=>this.formatMoney(e),formatNumber:(e,t)=>this.formatNumber(e,t),onToggle:e=>{this.markOpen(`account`,e),this.trading.refreshAccount()}},this.t);for(let e of[`ordersChange`,`positionsChange`,`executionFill`,`dataUpdate`,`indicatorUpdate`])this.chart.on(e,()=>this.trading.refreshAccountSoon())}if(e.trading!==!1){if(this.trading.bracketBar=new To(this.chartContainer,{onConfirm:()=>this.chart.confirmBracket(),onCancel:()=>{this.chart.cancelBracket(),this.trading.bracketBar?.hide()}},this.t),this.chart.on(`bracketPlace`,e=>{let t=e.payload;this.trading.bracketBar?.hide(),this.say(s.r(this.t(t.side===`buy`?`bracket.longPlaced`:`bracket.shortPlaced`),{rr:t.riskReward.toFixed(2)}))}),e.depthLadder){this.trading.depthLadder=new ko(this.root,{onTrade:(e,t)=>{this.chart.placeOrderIntent({side:e,type:`limit`,price:t}),this.say(s.r(this.t(e===`buy`?`order.buyLimit`:`order.sellLimit`),{price:this.formatAlertPrice(t)}))},formatPrice:e=>this.formatAlertPrice(e),priceStep:e=>this.chart.getPriceStep(e),onToggle:e=>this.markOpen(`ladder`,e),onClose:()=>this.docking.closePanelByHand(`depthLadder`)},void 0,this.t);let e=this.trading.depthLadder;this.chart.on(`ordersChange`,()=>e.setOrders(this.chart.getOrders()))}this.chart.on(`dataUpdate`,e=>{e.payload.kind===`bracket`&&this.trading.bracketBar?.hide()})}}buildAlerts(e){this.alerting.alertsPanel=new Kn(this.root,{onClose:()=>this.docking.closePanelByHand(`alerts`),onAdd:({price:e,condition:t,message:n,channel:r,label:i,options:a})=>{try{return this.chart.addAlert(e,t,n,r,i,a),!0}catch{return this.say(this.t(`alerts.invalid`),`error`),!1}},formatTime:e=>{let{date:t,time:n}=Y(e,this.displayTimezone());return`${t} ${n}`},onRemove:e=>this.chart.removeAlert(e),onClear:()=>this.chart.clearAlerts(),getChannelValue:e=>this.alerting.getAlertChannelValue(e),formatPrice:e=>this.formatAlertPrice(e)},this.t),this.chart.on(`alertAdd`,()=>this.alerting.refreshAlerts()),this.chart.on(`alertRemove`,()=>this.alerting.refreshAlerts()),this.chart.on(`alertUpdate`,()=>this.alerting.refreshAlerts()),this.chart.on(`alertExpired`,e=>{let t=e.payload;this.alerting.refreshAlerts(),this.featureState.alerts&&this.say(s.r(this.t(`alerts.expiredToast`),{text:t.message??this.alerting.alertText(t)}))}),e.alertNotifications&&(this.alerting.alertNotifier=new Eo(e.alertNotifications)),this.chart.on(`alertTriggered`,e=>{let t=e.payload;if(this.alerting.refreshAlerts(),!this.featureState.alerts)return;let n=`${this.alerting.alertText(t)}${t.message?` — ${t.message}`:``}`;this.say(s.r(this.t(`alerts.fired`),{text:n}),`info`,`bell`),this.alerting.alertNotifier?.notify(n)}),this.indicatorPickerPart=this.lazyPart(J.indicatorPicker,({WidgetIndicatorPicker:e})=>new e(this.overlayHost,{onAdd:e=>this.handleAddIndicator(e),onFavorite:(e,t)=>t?this.indicatorFavorites.add(e):this.indicatorFavorites.remove(e),templates:{onApply:e=>this.applyIndicatorTemplate(e),onDelete:e=>{this.templates.remove(e),this.indicatorPicker?.setTemplates(this.templateNames())},onSave:()=>this.promptSaveIndicatorTemplate()},onClose:()=>this.markOpen(`indicators`,!1)},this.t))}buildPanels(e){this.indicatorSettingsPart=this.lazyPart(J.indicatorSettings,({WidgetIndicatorSettings:e})=>new e(this.root,{onApply:(e,t)=>{this.chart.updateIndicator(e,t),this.syncIndicatorsFromChart()},onStyle:(e,t)=>this.chart.updateIndicatorStyle(e,t),onLevels:(e,t)=>this.chart.setIndicatorLevels(e,t),onScale:(e,t)=>this.chart.setIndicatorScale(e,t),onIntervals:(e,t)=>this.chart.setIndicatorIntervals(e,t),onSaveDefault:(e,t)=>this.saveIndicatorDefault(e,t),onClose:()=>this.chart.endIndicatorEdit()},this.t)),this.objectTree=new kr(this.root,{onClose:()=>this.docking.closePanelByHand(`objectTree`),onRemoveIndicator:e=>this.handleRemoveIndicator(e),onConfigureIndicator:e=>this.openIndicatorSettings(e),onToggleIndicatorVisible:(e,t)=>{this.chart.setIndicatorVisible(e,t),this.docking.refreshObjects(),this.legend.scheduleLegend()},onRemoveDrawing:e=>{this.drawingSettings?.editing()===e&&this.drawingSettings.close(!0),this.chart.removeDrawing(e),this.docking.refreshObjects()},onConfigureDrawing:e=>this.drawingEdit.openDrawingSettings(e),onToggleDrawingVisible:(e,t)=>{this.chart.setDrawingVisible(e,t),this.docking.refreshObjects()},onToggleDrawingLocked:(e,t)=>{this.chart.setDrawingLocked(e,t),this.docking.refreshObjects()},onToggleGroupVisible:(e,t)=>{this.chart.setDrawingGroupVisible(e,t),this.docking.refreshObjects()},onToggleGroupLocked:(e,t)=>{this.chart.setDrawingGroupLocked(e,t),this.docking.refreshObjects()},onUngroup:e=>{this.chart.ungroupDrawings(e),this.docking.refreshObjects()},onRenameGroup:(e,t)=>{this.chart.renameDrawingGroup(e,t),this.docking.refreshObjects()},onSelectDrawing:e=>this.chart.selectDrawing(e),onRenameDrawing:(e,t)=>{this.chart.updateDrawing(e,{name:t||null}),this.docking.refreshObjects()},onCloneDrawing:e=>{this.chart.duplicateDrawing(e),this.docking.refreshObjects()},onMoveDrawing:(e,t)=>{this.chart.moveDrawing(e,t),this.docking.refreshObjects()},onAddCompare:e.compareSymbols===!1?void 0:()=>this.comparing.handleAddCompare(),onRemoveCompare:e=>this.comparing.removeCompared(e)},this.t);let t=()=>{this.objectTree?.isOpen()&&this.docking.refreshObjects()},n=0,r=()=>{n||!this.objectTree?.isOpen()||(n=requestAnimationFrame(()=>{n=0,this.destroyed||t()}))};this.chart.on(`drawingCreate`,t),this.chart.on(`drawingRemove`,t),this.chart.on(`drawingUpdate`,r),this.chart.on(`timeframeChange`,r),this.chart.on(`indicatorAdd`,t),this.chart.on(`indicatorRemove`,t),this.chart.on(`indicatorChange`,t);for(let e of[`indicatorAdd`,`indicatorRemove`,`indicatorChange`])this.chart.on(e,()=>this.comparing.refreshCompareDialog());this.docking.setupDock()}buildCommandPalette(){this.commandPalettePart=this.lazyPart(J.commandPalette,({WidgetCommandPalette:e})=>new e({onIndicator:e=>this.handleAddIndicator(e),onChartType:e=>this.handleChartType(e),onDrawingTool:e=>this.handleDrawingTool(e),onTimeframe:e=>this.handleTimeframe(e),onAction:e=>this.commands.handleAction(e),onClose:()=>{}},this.overlayHost,this.t,{list:()=>Oc(),add:e=>kc([e,...Oc().filter(t=>t!==e)])})),this.boundGlobalKeydown=e=>{if(this.handleHostHotkey(e)||this.featureState.hotkeys&&this.replay.isOpen()&&this.replay.handleReplayKey(e))return;let t=D(this.root),n=e=>this.featureState.hotkeys&&this.featureState[e];if((e.ctrlKey||e.metaKey)&&e.key===`k`){if(!t||!n(`hotkeys.commandPalette`)||!this.featureState.commandPalette)return;e.preventDefault(),this.commands.toggleCommandPalette()}else if((e.ctrlKey||e.metaKey)&&(e.key===`p`||e.key===`P`)){if(!t||!n(`hotkeys.symbolSearch`)||!this.featureState.symbolSearch)return;e.preventDefault(),this.openSymbolSearch()}else if((e.ctrlKey||e.metaKey)&&!e.altKey&&!e.shiftKey&&(e.key===`s`||e.key===`S`)){if(!this.layouts.layoutSession||!n(`hotkeys.save`)||!this.featureState.layouts||O()||!D(this.root,!0))return;e.preventDefault(),this.layouts.saveLayout()}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&jn[e.code]){if(e.defaultPrevented||O()||!t||k()||!n(`hotkeys.tools`))return;e.preventDefault(),this.handleDrawingTool(jn[e.code])}else if(/^[0-9]$/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(e.defaultPrevented||!this.intervals.intervalInput||!n(`intervalTyping`)||O()||k()||!D(this.root,!0))return;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t))return;e.preventDefault(),this.intervals.intervalInput.open(e.key)}else if(yc(e)!==null){if(e.defaultPrevented||!n(`symbolTyping`)||!this.featureState.symbolSearch||O()||k()||!D(this.root,!0))return;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t))return;e.preventDefault(),this.openSymbolSearch(yc(e))}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&(e.code===`KeyI`||e.code===`KeyG`||e.code===`KeyR`)){if(O()||!t)return;if(e.code===`KeyI`){if(!n(`hotkeys.invertScale`))return;e.preventDefault(),this.chartSettings.changeSettings({invertScale:!this.chartSettings.settingsState.invertScale})}else if(e.code===`KeyR`){if(!n(`hotkeys.resetView`))return;e.preventDefault(),this.resetView()}else n(`hotkeys.goToDate`)&&this.featureState.goToDate&&(e.preventDefault(),this.toggleGoToDate())}else if(e.key===`?`&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(O()||!t||!n(`hotkeys.help`)||!this.featureState.hotkeySheet)return;e.preventDefault(),this.openHotkeySheet()}},document.addEventListener(`keydown`,this.boundGlobalKeydown),document.addEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys=Pt(this.root,[this.portal])}finishSetup(e){this.marking.start(),this.chartSettings.restoreKeptSettings(),e.adapter?(this.adapter=e.adapter,this.connectStream()):this.chart.setDataTimeframe(this.state.timeframe),this.watching.watchlist&&(this.watching.watchlistInterval=setInterval(()=>this.watching.tickWatchlist(),1e3)),this.markSwitchedOff(),requestAnimationFrame(()=>{this.destroyed||(this.toolbar?.tidy(),this.sidebar?.tidy())}),this.refreshMarket(),this.updateUI(),queueMicrotask(()=>{if(!this.destroyed)try{e.onReady?.(this.chart,this)}finally{this.destroyed||this.layouts.restoreSharedView()}}),this.preloadDialogsWhenIdle()}preloadDialogsWhenIdle(){let e=()=>{this.destroyed||Ua()},t=globalThis;if(t.requestIdleCallback&&t.cancelIdleCallback){let n=t.requestIdleCallback(e,{timeout:pc}),r=t.cancelIdleCallback;this.stopPreload=()=>r(n)}else{let t=setTimeout(e,mc);this.stopPreload=()=>clearTimeout(t)}}setSymbols(e){let t=a.o(e);this.symbols=t.names,this.symbolCatalog=t.info;let n=this.watching.watchlistStore;n&&this.watching.watchlistFromSymbols&&n.replace(n.getLists().map(e=>e.id===`default`?{...e,symbols:t.names}:e)),this.refreshSymbolTitle(),this.refreshSymbolInfo()}symbolEntries(){return this.symbols.map(e=>this.symbolCatalog.get(e)??e)}symbolInfoOf(e){return this.symbolCatalog.get(e)}chartSymbolInfo(){let e=this.chart.getSymbolInfo(),t=e&&e!==this.chartInfoAtSwitch?e:a.t(this.state.symbol,e);return t?a.r(t,this.state.symbol):null}displayInfo(){return a.a(this.symbolCatalog.get(this.state.symbol),this.chartSymbolInfo())??null}refreshSymbolTitle(){this.toolbar?.setSymbolDescription(a.l(this.displayInfo()))}getWatchlists(){return this.watching.getWatchlists()}getActiveWatchlist(){return this.watching.getActiveWatchlist()}setWatchlists(e,t){return this.watching.setWatchlists(e,t)}setActiveWatchlist(e){return this.watching.setActiveWatchlist(e)}addToWatchlist(e,t){return this.watching.addToWatchlist(e,t)}removeFromWatchlist(e,t){return this.watching.removeFromWatchlist(e,t)}setQuotes(e){return this.watching.setQuotes(e)}getQuote(e){return this.watching.getQuote(e)}openPanel(e){return this.docking.openPanel(e)}closePanel(){return this.docking.closePanel()}getOpenPanel(){return this.docking.getOpenPanel()}toggleSymbolInfo(e){let t=this.symbolInfoPanel;if(!t)return;let n=e??!t.isOpen();n&&!this.featureState.symbolInfo||(n?this.docking.dock?.open(`symbolInfo`):this.docking.dock?.closePage(`symbolInfo`))}refreshMarket(){if(Xt())return;let e=(0,u.marketStatus)(this.chart.getSymbolInfo(),Date.now()),t=e.state===`open`;this.statusBar?.setMarket(e.state,this.t(t?`symbolInfo.open`:`symbolInfo.closed`),this.t(t?`statusBar.marketOpen`:`statusBar.marketClosed`)),this.showConnection(),this.refreshSymbolInfo()}refreshSymbolInfo(){let e=this.symbolInfoPanel;!e?.isOpen()||this.destroyed||e.render(this.symbolInfoView())}symbolInfoView(){let e=this.state.symbol;return bn({symbol:e,info:this.chart.getSymbolInfo(),names:this.displayInfo(),quote:this.watching.quotes.get(e),bars:this.chart.getData(),formatPrice:e=>this.formatAlertPrice(e),t:this.t,textLocale:this.textLocale(),numberLocale:this.intlLocale(),now:Date.now()})}loadNews(){let e=this.symbolInfoPanel;if(!e?.isOpen())return;let t=this.options.adapter,n=this.options.news??(t?.fetchNews?t.fetchNews.bind(t):null);this.news.load(this.state.symbol,n,t=>e.renderNews(t),this.textLocale(),()=>this.destroyed)}intlLocale(){return this.chartSettings.settingsState.numberLocale||this.options.locale||`en`}textLocale(){return this.options.locale||`en`}async setSymbol(e){this.layouts.flushActiveLayout(),e!==this.state.symbol&&(this.chart.clearFills(),this.chartInfoAtSwitch=this.chart.getSymbolInfo()),this.state={...this.state,symbol:e},this.sessionRefPrice=null,this.options.onSymbolChange?.(e),this.updateUI(),this.refreshSymbolTitle(),this.watching.watchlist?.setActive(e),this.refreshMarket(),this.loadNews(),this.marking.load(),this.layouts.layoutSession?.changed(),this.adapter&&await this.connectStream()}setWatchlistEntry(e,t){return this.watching.setWatchlistEntry(e,t)}async setTimeframe(e){this.chart.isTimeframeAllowed(e)&&(this.chosenTimeframe=e,this.intervals.rangeSeq++,await this.switchTimeframe(e))}async switchTimeframe(e){if(this.state={...this.state,timeframe:e},this.options.onTimeframeChange?.(e),this.updateUI(),this.layouts.layoutSession?.changed(),this.adapter){await this.connectStream();return}if(this.chart.setDataTimeframe(e),this.options.resampleTimeframes!==!1){if(!this.baseSeries){let e=this.chart.getData();e.length>0&&(this.baseSeries=e,this.baseTimeframeMs=p(e))}await this.switchLocalTimeframe()}}setTheme(e){let t=this.resolveIsDark(e),n=this.resolveTheme(e);this.themeOf={...this.themeOf,[t?`dark`:`light`]:n},this.state={...this.state,isDark:t},this.look.set({dark:t,theme:n}),this.updateUI()}getChart(){return this.chart}setUI(e){this.ui=I(e),this.uiVariables=!0,this.uiScale=this.scaleNow(),this.applyLookTokens(),this.applyChartShapes(),this.applyLegendFont(),this.applyChartLook()}scaleNow(){if(this.ui.scale!==`auto`&&this.ui.scale!==void 0)return this.ui.scale;let e=this.root.clientWidth;return e>0?ur(e):1}applyLookTokens(){let e=dr(this.ui,this.uiScale);this.docking?.dock?.setScale(this.uiScale);for(let t of[this.root,this.portal]){if(Or(t,e,{variables:this.uiVariables}),this.uiVariables)continue;let n=Dr(e);for(let e of sc)this.uiScale===1?t.style.removeProperty(e):t.style.setProperty(e,n[e])}}fitScale(){if(this.destroyed)return;let e=this.scaleNow();if(e!==this.uiScale){if(this.ui.scale===`auto`){let t=this.root.clientWidth;if((e>this.uiScale?ur(t-oc):ur(t+oc))===this.uiScale)return}this.uiScale=e,this.applyLookTokens(),this.applyLegendFont(),this.applyChartLook(),this.toolbar?.fit()}}getUI(){return I({...this.ui})}applyLegendFont(){this.chart.setLegend({fontFamily:this.ui.font.mono,fontSize:M(Math.round(this.ui.font.size*this.uiScale),-1)})}applyChartLook(){let e=this.options.chartOptions,t=this.ui.density===`compact`||this.ui.density===`classic`;e?.density||this.chart.setDensity(t?`compact`:`comfortable`),e?.barLayout||this.chart.setBarLayout(this.ui.density===`compact`?`classic`:`golden`);let n=this.scaledChartSizes();e?.font?.family?Object.keys(n).length>0&&this.chart.setFont(n):this.chart.setFont({family:this.ui.font.mono,...e?.font?.textFamily?{}:{textFamily:this.ui.font.family},...n})}scaledChartSizes(){let e=this.options.chartOptions?.font;if(e?.sizeSmall!==void 0||e?.sizeMedium!==void 0||e?.sizeLarge!==void 0)return{};let t=this.chart.getFont?.();if(!t)return{};let n={sizeSmall:t.sizeSmall,sizeMedium:t.sizeMedium,sizeLarge:t.sizeLarge},r=this.drawingEdit.chartFontWritten;if((!r||r.sizeSmall!==n.sizeSmall||r.sizeMedium!==n.sizeMedium||r.sizeLarge!==n.sizeLarge)&&(this.chartFontBase=n),this.uiScale===1&&!r)return{};let i=this.chartFontBase??n,a=e=>this.uiScale===1?e:Math.round(e*this.uiScale),o={sizeSmall:a(i.sizeSmall),sizeMedium:a(i.sizeMedium),sizeLarge:a(i.sizeLarge)};return this.drawingEdit.chartFontWritten=this.uiScale===1?null:o,o}applyChartShapes(){this.chart.setShapes({tagRadius:this.ui.tagRadius})}destroy(){if(!this.destroyed){this.destroyed=!0,this.scope.dispose(),this.stopPreload?.(),this.stopKeyboardInset?.(),this.stopKeyboardInset=null,this.stopNarrow?.(),this.docking.dockObserver?.disconnect(),this.scaleObserver?.disconnect(),this.drawingEdit.inlineText?.close(),this.stopNarrow=null,this.stopFormControls?.(),this.stopFormControls=null,this.boundGlobalKeydown&&document.removeEventListener(`keydown`,this.boundGlobalKeydown),document.removeEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys(),this.tooltip.destroy(),this.legend.legendFrame&&cancelAnimationFrame(this.legend.legendFrame),this.indicatorLegend?.destroy(),this.portal.remove(),document.fullscreenElement===this.root&&document.exitFullscreen().catch(()=>{}),this.layouts.flushActiveLayout(),this.commandPalettePart?.destroy(),this.symbolSearchPart?.destroy(),this.hotkeySheetPart?.destroy(),this.replay.destroy(),this.dragDrop?.detach(),this.alerting.alertsPanel?.destroy(),this.objectTree?.destroy(),this.indicatorSettingsPart?.destroy(),this.indicatorPickerPart?.destroy(),this.drawingStyle?.destroy(),this.drawingSettingsPart?.destroy(),this.menus.drawingMenu?.destroy(),this.menus.clearMenu?.destroy(),this.drawingEdit.cancelTextPrompt?.(),this.drawingEdit.selectionToolbar?.destroy(),this.drawingEdit.selectionToolbarFrame!==null&&cancelAnimationFrame(this.drawingEdit.selectionToolbarFrame),this.menus.chartMenu?.destroy(),this.legend.legendMenu?.destroy();for(let e of this.hostMenus)e.destroy();this.hostMenus.clear(),this.templatePrompt?.destroy(),this.chartSettings.chartTemplatePrompt?.destroy(),this.drawingEdit.drawingTemplatePrompt?.destroy(),this.intervals.intervalInput?.destroy(),this.markerTip?.remove(),this.layouts.layoutSession?.destroy(),this.layouts.layoutsUI?.destroy(),this.chartSettings.settingsListeners.clear(),this.trading.accountPanel?.destroy(),this.trading.orderTicket?.destroy(),this.trading.accountFrame&&cancelAnimationFrame(this.trading.accountFrame),this.trading.bracketBar?.destroy(),this.alerting.alertNotifier?.destroy(),this.trading.depthLadder?.destroy(),this.dataWindow?.destroy(),this.watching.watchlistInterval&&clearInterval(this.watching.watchlistInterval),this.marketTimer&&clearInterval(this.marketTimer),this.clockTimer&&clearInterval(this.clockTimer),this.onPageShown&&document.removeEventListener(`visibilitychange`,this.onPageShown),this.onPageShown=null,this.chartNav?.destroy(),this.symbolInfoPanel?.destroy(),this.docking.dock?.destroy(),this.watching.stopQuotes?.(),this.watching.stopQuotes=null,this.watching.watchlist?.destroy(),this.toolbar?.destroy(),this.sidebar?.destroy(),this.settingsPart?.destroy(),this.statusBar?.destroy(),this.goToDatePart?.destroy(),this.loading.destroy(),this.historyPill.destroy(),this.chart.destroy(),this.root.remove(),pe()}}handleSymbolClick(){this.featureState.symbolSearch&&this.openSymbolSearch()}openSymbolSearch(e){let t=e===void 0?``:(this.symbolSearchPart?.isLoading()?this.typedWhileLoading:``)+e;this.typedWhileLoading=t,this.whenLoaded(this.symbolSearchPart,()=>this.featureState.symbolSearch,n=>{this.typedWhileLoading=``,n.open({symbols:this.symbolEntries(),current:this.state.symbol,currentInfo:this.chartSymbolInfo(),search:this.symbolSearchFn(),query:e===void 0?void 0:t,hint:this.sheetKeyOn(`symbolTyping`)?this.t(`symbolSearch.typeHint`):void 0})})}withSymbolSearch(e,t){this.typedWhileLoading=``,this.whenLoaded(this.symbolSearchPart,e,t)}symbolSearchFn(){if(this.options.searchSymbols)return this.options.searchSymbols;let e=this.adapter;if(e?.searchSymbols)return(t,n)=>e.searchSymbols(t,{signal:n,limit:50})}handleTimeframe(e){this.setTimeframe(e)}toggleFullscreen(){if(document.fullscreenElement===this.root){document.exitFullscreen().catch(()=>{});return}this.root.requestFullscreen().catch(e=>{this.say(e instanceof Error?e.message:this.t(`toast.fullscreenUnavailable`),`error`)})}drawingToolName(e){let t=`tool.${e}`,n=this.t(t);return n===t?this.chart.getDrawingToolDescriptor(e)?.name??e:n}chartOffset(){let e=this.chartContainer.getBoundingClientRect(),t=this.root.getBoundingClientRect();return{x:e.left-t.left,y:e.top-t.top}}setFeatures(e){let t=this.featureState;this.featureState={...t,...r.l(e)};let n=e=>t[e]!==this.featureState[e];this.markSwitchedOff(),this.closeSwitchedOff(e=>t[e]&&!this.featureState[e]),n(`selectionToolbar`)&&this.drawingEdit.updateSelectionToolbar(),n(`indicatorLegend`)&&(this.chart.setPaneTitlesVisible(!this.featureState.indicatorLegend),this.legend.scheduleLegend()),n(`menu.priceAxisAdd`)&&this.chart.setFeatures({priceAxisAddButton:this.priceAxisAddDefault&&this.featureState[`menu.priceAxisAdd`]}),n(`marks`)&&(this.chart.setFeatures({marks:this.marksDefault&&this.featureState.marks}),this.marking.load()),n(`dragDropImport`)&&(this.featureState.dragDropImport?this.dragDrop?.attach():this.dragDrop?.detach()),[`toolbar`,`sidebar`,`statusBar`,`accountPanel`].some(n)&&this.chart.resize()}getFeatures(){return{...this.featureState}}isFeatureOn(e){return this.featureState[e]===!0}closeSwitchedOff(e){e(`replay`)&&this.replay.isOpen()&&this.replay.exitReplay();let t=[[`alerts`,()=>this.docking.dock?.closePage(`alerts`)],[`objectTree`,()=>this.docking.dock?.closePage(`objectTree`)],[`symbolInfo`,()=>this.docking.dock?.closePage(`symbolInfo`)],[`dataWindow`,()=>this.docking.dock?.closePage(`dataWindow`)],[`accountPanel`,()=>this.trading.toggleAccountPanel(!1)],[`orderTicket`,()=>this.trading.orderTicket?.close()],[`depthLadder`,()=>this.docking.dock?.closePage(`depthLadder`)],[`goToDate`,()=>this.goToDate?.close()],[`settings`,()=>this.settings?.close()],[`indicatorSettings`,()=>this.indicatorSettings?.close()],[`toolbar.indicators`,()=>this.indicatorPicker?.close()],[`drawingSettings`,()=>this.drawingSettings?.close(!1)],[`sidebar`,()=>this.drawingStyle?.close()],[`commandPalette`,()=>this.commandPalette?.close()],[`hotkeySheet`,()=>this.hotkeySheet?.close()],[`symbolSearch`,()=>this.symbolSearch?.close()],[`compare`,()=>{this.symbolSearch?.isComparing()&&this.symbolSearch.close()}],[`menu.chart`,()=>this.menus.chartMenu?.close()],[`menu.priceAxisAdd`,()=>this.menus.chartMenu?.close()],[`menu.drawing`,()=>this.menus.drawingMenu?.close()],[`indicatorLegend`,()=>this.legend.legendMenu?.close()],[`indicatorLegend.more`,()=>this.legend.legendMenu?.close()]];for(let[n,r]of t)e(n)&&r()}addHotkey(e){let t=Ko(e.keys);if(!t)return console.warn(`[ChartWidget] Can't read the shortcut "${e.keys}": modifiers (Ctrl, Alt, Shift) and a key, joined by +.`),null;Yo(t)&&console.warn(`[ChartWidget] The chart answers ${e.keys} itself (drawings, scrolling or zoom): both will run.`);let n={spec:e,parsed:t};return this.hostHotkeys=[...this.hostHotkeys,n],{remove:()=>{this.hostHotkeys=this.hostHotkeys.filter(e=>e!==n)}}}handleHostHotkey(e){if(this.hostHotkeys.length===0||!this.featureState.hotkeys||e.isComposing||e.keyCode===229||e.getModifierState?.(`AltGraph`)||e.defaultPrevented||O()||Xo(e)||k())return!1;let t=this.hostHotkeys.find(t=>qo(e,t.parsed));if(!t)return!1;let n=!t.parsed.ctrl&&!t.parsed.alt;if(!D(this.root,n))return!1;let r=document.activeElement;return n&&r&&r!==document.body&&!this.root.contains(r)?!1:(e.preventDefault(),t.spec.onPress(e),!0)}paintWatermark(){this.chart.setWatermark(a.c(this.state.symbol).ticker.replace(`USDT`,` / USDT`),{fontSize:hc,color:this.state.isDark?gc:_c})}keepingLook(e){this.chartSettings.settingsEdit&&this.settings?.close();let t=this.chart.getOverrides?.({layer:`user`})??{},n=Object.fromEntries(Sc.filter(e=>t[e]!==void 0).map(e=>[e,t[e]]));e(),Object.keys(n).length>0&&this.chart.applyOverrides(n,{layer:`user`})}sheetKeyOn(e){let t=this.featureState;if(!t.hotkeys||!t[e])return!1;switch(e){case`hotkeys.commandPalette`:return t.commandPalette;case`hotkeys.symbolSearch`:return t.symbolSearch;case`hotkeys.goToDate`:return t.goToDate;case`hotkeys.save`:return t.layouts&&this.layouts.layoutSession!==null;case`hotkeys.help`:return t.hotkeySheet;case`intervalTyping`:return this.intervals.intervalInput!==null;case`symbolTyping`:return t.symbolSearch;default:return!0}}markSwitchedOff(){let e=r.s(this.featureState);for(let t of[this.root,this.portal])e?t.dataset.tcwOff=e:delete t.dataset.tcwOff;this.toolbar?.setSymbolSearch(this.featureState.symbolSearch),this.toolbar?.tidy(),this.sidebar?.tidy(),this.docking.syncRail(),this.statusBar?.fit()}addToolbarButton(e){if(!this.toolbar)return null;let t=this.toolbar,n=t.addHostButton(e);return t.tidy(),{element:n,setActive:t=>Ue(n,t,e.toggle===!0),setText:t=>void We(n,e.label,t),remove:()=>{n.remove(),t.tidy()}}}addToolbarDropdown(e){let t=this.toolbar;if(!t)return null;let n=new o.f(this.root,e.label);this.hostMenus.add(n);let r=t.addHostButton({id:e.id,label:e.label,icon:e.icon,text:e.text,side:e.side,onClick:r=>{if(n.isOpen()){n.close();return}let i=e.items();if(i.length===0)return;let a=t.menuAnchor(r);n.openUnder(Vo([],i),a,e=>Ho(e,i))}});return r.setAttribute(`aria-haspopup`,`menu`),r.setAttribute(`aria-expanded`,`false`),t.tidy(),{element:r,setText:t=>void We(r,e.label,t),remove:()=>{n.destroy(),this.hostMenus.delete(n),r.remove(),t.tidy()}}}addSidebarButton(e){let t=this.sidebar;if(!t)return null;let n=t.addHostButton(e);return{element:n,setActive:t=>Ue(n,t,e.toggle===!0),remove:()=>{n.remove(),t.tidy()}}}addStatusBarItem(e){if(!this.statusBar)return null;let t=this.statusBar.addHostItem(e);return{element:t,setText:n=>{t.textContent=n,e.label&&e.label!==n?t.setAttribute(`aria-label`,`${e.label}: ${n}`):t.removeAttribute(`aria-label`)},remove:()=>t.remove()}}getSlot(e){switch(e){case`toolbar.left`:return this.toolbar?.hostSlot(`left`)??null;case`toolbar.right`:return this.toolbar?.hostSlot(`right`)??null;case`sidebar`:return this.sidebar?.hostSlot()??null;case`statusBar.left`:return this.statusBar?.hostSlot(`left`)??null;case`statusBar.right`:return this.statusBar?.hostSlot(`right`)??null;case`chart`:return this.hostLayer||(this.hostLayer=document.createElement(`div`),this.hostLayer.className=`tcw-host-layer`,this.chartContainer.appendChild(this.hostLayer)),this.hostLayer;default:return null}}toggleAccountPanel(e){return this.trading.toggleAccountPanel(e)}clockNow(){let e=Date.now(),t=this.displayTimezone(),n=e=>String(e).padStart(2,`0`),{time:r}=Y(e,t);return{time:`${r}:${n(new Date(e).getUTCSeconds())}`,zone:(0,u.tzLabel)((0,u.offsetAt)(t,e))}}refreshDrawingsState(){let e=this.chart.getDrawings()??[],t=e.length>0;this.sidebar?.setDrawingsState({locked:t&&e.every(e=>e.locked),hidden:t&&e.every(e=>!e.visible)})}displayTimezone(){let e=t.v(this.chartSettings.settingsState.timezone);return e===`exchange`?this.chart.getEffectiveTimeZone():e}toggleGoToDate(){this.whenLoaded(this.goToDatePart,()=>this.featureState.goToDate,e=>this.toggleLoadedGoToDate(e))}toggleLoadedGoToDate(e){if(e.isOpen()){e.close();return}let t=this.chart.getData();if(t.length===0)return;let n=this.displayTimezone(),r=(0,u.barTimeUnit)(t),i=e=>Y(e*r,n),a=t[t.length-1].time,o=this.chart.getVisibleTimeRange()??{from:t[0].time,to:a},s=Y(Date.now(),n).date;e.open({date:i(a),range:{from:i(o.from),to:i(o.to)},withTime:!((0,u.timeframeToMs)(this.state.timeframe)>=fc),max:s,today:s})}goTo(e){let t=this.chart.getData(),n=this.displayTimezone();if(t.length===0)return;let r=(0,u.barTimeUnit)(t);if(e.kind===`date`){let i=Ka(e.date,e.time,n);if(i===null)return;this.chart.goToTime(i/r),i/r<t[0].time&&this.say(this.t(`range.beforeData`));return}let i=Ka(e.from.date,e.from.time,n),a=Ka(e.to.date,e.to.time,n);i===null||a===null||(this.chart.setVisibleRange(i/r,a/r),Math.min(i,a)/r<t[0].time&&this.say(this.t(`range.beforeData`)))}showMarkerTip(e){let{marker:t}=e;if(!t){this.markerTip&&(this.markerTip.hidden=!0);return}this.markerTip||(this.markerTip=document.createElement(`div`),this.markerTip.className=`tcw-marker-tip`,this.markerTip.setAttribute(`role`,`tooltip`),this.chartContainer.appendChild(this.markerTip));let n=t.direction===`long`?this.t(`account.long`):t.direction===`short`?this.t(`account.short`):this.t(`markers.neutral`),r=document.createElement(`strong`);r.textContent=t.label?`${t.label} · ${t.source}`:t.source;let i=document.createElement(`div`);i.textContent=`${n} · ${this.formatAlertPrice(t.price)} · ${s.r(this.t(`markers.confidence`),{pct:Math.round(t.confidence*100)})}`;let a=document.createElement(`div`),{date:o,time:c}=Y(t.time,this.displayTimezone());a.textContent=`${o} ${c}`,this.markerTip.replaceChildren(r,i,a),this.markerTip.hidden=!1;let l=this.chartContainer.getBoundingClientRect(),u=Math.min(e.x+12,Math.max(0,l.width-this.markerTip.offsetWidth-4)),d=Math.max(0,e.y-this.markerTip.offsetHeight-10);this.markerTip.style.left=`${u}px`,this.markerTip.style.top=`${d}px`}applyIndicatorTemplate(e){if(!this.featureState.indicatorTemplates)return;let t=this.templates.get(e);t&&(this.chart.applyIndicatorSetup(t.indicators),this.syncIndicatorsFromChart(),this.updateUI(),this.say(s.r(this.t(`templates.applied`),{name:t.name})))}promptSaveIndicatorTemplate(){if(this.featureState.indicatorTemplates){if(this.chart.getActiveIndicators().length===0){this.say(this.t(`templates.nothing`),`error`);return}this.templatePrompt??=new ka(this.root,this.t),this.templatePrompt.open({title:this.t(`templates.saveTitle`),submitLabel:this.t(`common.save`),placeholder:this.t(`templates.namePlaceholder`),onSubmit:e=>{try{this.templates.save(e,this.chart.getIndicatorSetup())}catch(e){throw this.say(this.t(`templates.saveFailed`),`error`),e}this.indicatorPicker?.setTemplates(this.templateNames()),this.say(s.r(this.t(`templates.saved`),{name:e}))}})}}setData(e){this.localSeq++,this.baseSeries=e,this.baseTimeframeMs=p(e),this.applyTimeframeData(),this.adapter||this.loading.end()}async switchLocalTimeframe(){if(!this.baseSeries)return;let e=++this.localSeq,t=this.lastLocalSwitchMs>=cc||this.baseSeries.length>=lc;try{if(t&&(this.loading.begin(this.chart.getData().length>0,!0),await dc(),e!==this.localSeq||this.destroyed))return;this.applyTimeframeData()}finally{e===this.localSeq&&this.loading.end()}}applyTimeframeData(){if(!this.baseSeries)return;let e=performance.now(),t=(0,u.timeframeToMs)(this.state.timeframe);if(this.baseTimeframeMs>0&&t>this.baseTimeframeMs){let e=this.chart.getExchangeTimeZone()??null;this.chart.setData(f(this.baseSeries,this.state.timeframe,this.resampleOptions(e))),this.builtInZone=e}else this.chart.setData(this.baseSeries),this.builtInZone=void 0;this.lastLocalSwitchMs=performance.now()-e}resampleOptions(e){return{weekStartsOn:this.options.weekStartsOn??1,timeZone:e??void 0}}rebuildForZone(){if(this.adapter||this.builtInZone===void 0)return;let e=this.chart.getExchangeTimeZone()??null;if(e===this.builtInZone)return;if(!(0,u.timeframeFollowsDays)(this.state.timeframe)){this.builtInZone=e;return}let t=this.timeToKeepInView();this.applyTimeframeData(),t!==null&&this.chart.scrollTo(t)}timeToKeepInView(){if(!this.chart.isTimeAligned())return null;let e=this.chart.getVisibleTimeRange(),t=this.chart.getData();if(!e||t.length<2||e.to>=t[t.length-1].time)return null;let n=t.findIndex(t=>t.time===e.from);return n<0?null:e.from-(t[n+1].time-e.from)/2}handleDataUpdate(e){if(e.kind===`bars`){e.length>0&&this.loading.isActive()&&(this.loading.end(),this.state.connectionState===`error`&&this.setConnectionState(`connected`,this.t(`status.live`)));return}if(e.kind===`error`){this.loading.isActive()&&(this.loading.fail(this.t(`status.connectionFailed`)),this.setConnectionState(`error`,e.error||this.t(`status.connectionFailed`)));return}if(e.kind===`connection`)switch(e.connection.state){case`connected`:this.loading.hasFailed()&&this.loading.end(),!this.loading.isActive()&&this.state.connectionState!==`connected`&&this.setConnectionState(`connected`,this.t(`status.live`));break;case`reconnecting`:this.loading.isActive()||this.setConnectionState(`connecting`,this.t(`status.connecting`));break;case`error`:this.loading.isActive()||this.setConnectionState(`error`,this.t(`status.connectionFailed`));break}}setConnectionState(e,t){this.state={...this.state,connectionState:e,connectionMessage:t},this.updateUI()}handleToggleFavorite(e){let t=this.favoritesStore.toggle(e);this.sidebar?.setFavorites(this.favoritesStore.list()),this.say(t?this.t(`toast.pinned`):this.t(`toast.unpinned`))}exportState(){return this.layouts.exportState()}async importState(e){return this.layouts.importState(e)}overViewerTypeOptions(e,t){let n={...Kr(e)?{[e]:{}}:{},...t};if(Object.keys(n).length!==0)return{...this.chartSettings.getSettings().chartTypeOptions,...n}}async copyChartImage(){let e=await this.chart.copyScreenshot();this.say(e?this.t(`toast.imageCopied`):this.t(`toast.imageCopyFailed`),e?`info`:`error`)}async copyShareLink(){return this.layouts.copyShareLink()}setDepth(e){return this.trading.setDepth(e)}startBracket(e){return this.trading.startBracket(e)}openIndicatorSettings(e){this.whenLoaded(this.indicatorSettingsPart,()=>this.featureState.indicatorSettings,t=>this.showIndicatorSettings(t,e))}showIndicatorSettings(e,t){let n=this.chart.getActiveIndicators(),r=n.find(e=>e.instanceId===t);if(!r)return;let i=this.chart.getIndicatorStyle(t),a=r.descriptor.placement===`panel`||!!r.pane,o=(this.chart.getIndicatorSetup()??[]).find(e=>e.instanceId===t)?.levels!==void 0;this.chart.beginIndicatorEdit(t),e.open({instanceId:t,indicatorId:r.id,name:r.descriptor.name,defaults:r.descriptor.defaultConfig,params:r.params,inputs:r.descriptor.inputs,lineSources:Tc(t,n,this.t),plots:r.descriptor.plots,colors:i?.colors,lineWidth:i?.lineWidths[0],plotStyles:i?.plots,intervals:this.chart.getIndicatorIntervals(t)??null,levels:a?this.chart.getIndicatorLevels(t):void 0,defaultLevels:r.descriptor.levels,ownLevels:o,scale:a?void 0:this.chart.getIndicatorScale(t)})}async addCompareSymbol(e,t=`percent`){return this.comparing.addCompareSymbol(e,t)}refreshPriceTexts(){this.alerting.refreshAlerts(),this.trading.refreshAccountSoon(),this.dataWindow?.isOpen()&&this.dataWindow.render(this.docking.buildDataWindowModel())}formatMoney(e){return this.formatNumber(e,Math.min((0,u.stepDecimals)(this.chart.getPriceStep()),vc))}formatVolume(e){return(0,u.formatVolumeLoc)(e,this.chartSettings.settingsState.numberLocale||`en-US`)}formatNumber(e,t){let n=this.chartSettings.settingsState.numberLocale||void 0;return e.toLocaleString(n,{minimumFractionDigits:t,maximumFractionDigits:t})}formatAlertPrice(e,t=e){if(this.chart.getPriceFormatter?.()||this.chartSetsDecimals())return this.chart.formatPrice(e);let n=Math.abs(t),r=n>=1e3?2:n>=1?4:6,i=this.chartSettings.settingsState.numberLocale||void 0;return e.toLocaleString(i,{minimumFractionDigits:2,maximumFractionDigits:r})}indicatorValueText(e,t,n){return t?this.chart.formatPrice(e):wo(e,n)}chartSetsDecimals(){return this.chart.getMarket?.()?.pricePrecision!=null||this.chart.getSymbolInfo?.()?.pricePrecision!=null}handleChartType(e){let t=this.state.chartType;e!==t&&(this.applyChartType(e),this.chart.recordUndo({subject:`chartType`,undo:()=>this.applyChartType(t),redo:()=>this.applyChartType(e)}))}applyChartType(e){this.state={...this.state,chartType:e},this.chart.setChartType(e),this.settings?.refresh(this.chartSettings.shownSettings(),e),this.updateUI()}handleAddIndicator(e){return this.chart.addIndicator(e,this.indicatorDefaults.get(e)?.params??{})!==null}saveIndicatorDefault(e,t){if(!this.indicatorDefaults.save(e,t)){this.say(this.t(`indicatorSettings.defaultSaveFailed`),`error`);return}this.chart.setIndicatorDefaults(e,t.style);let n=this.chart.getAvailableIndicators()?.find(t=>t.id===e)?.shortName??e.toUpperCase();this.say(s.r(this.t(`indicatorSettings.defaultSaved`),{name:n}))}handleRemoveIndicator(e){this.chart.removeIndicator(e)}keysShown(e,t){if(this.sheetKeyOn(e))return this.hostHotkeys.some(e=>e.parsed.display.join(`+`).toLowerCase()===t.toLowerCase())?void 0:t}openHotkeySheet(){this.whenLoaded(this.hotkeySheetPart,()=>this.featureState.hotkeySheet,e=>e.open({isOn:e=>this.sheetKeyOn(e),extra:this.hostHotkeys.map(e=>({keys:e.parsed.display,text:e.spec.label}))}))}handleDrawingTool(e){this.state={...this.state,activeTool:e},this.chart.setDrawingTool(e),this.updateUI()}handleCancelDrawing(){this.state={...this.state,activeTool:null},this.chart.setDrawingTool(null),this.chart.setEraserMode(!1),this.chart.setZoomAreaMode(!1),this.updateUI()}handleToggleStayInDrawing(){let e=!this.state.stayInDrawing;this.state={...this.state,stayInDrawing:e},this.chart.setStayInDrawingMode(e),this.updateUI()}handleToggleMagnet(){let e=this.state.magnetEnabled?this.state.magnetStrong?`off`:`strong`:`weak`;this.state={...this.state,magnetEnabled:e!==`off`,magnetStrong:e===`strong`},this.chart.setDrawingMagnetMode(e),this.updateUI()}handleToggleTheme(){if(!this.featureState.themeToggle)return;let e=!this.state.isDark;this.state={...this.state,isDark:e},this.look.set({dark:e,theme:e?this.themeOf.dark:this.themeOf.light}),this.updateUI()}lazyPart(e,t){return new Ha(e,t,e=>e.destroy(),()=>this.say(this.t(`common.partFailed`),`error`))}whenLoaded(e,t,n){if(!e||!t())return;let r=e.now();if(r){n(r);return}let i=e.isLoading();this.waitingShow.set(e,n),!i&&e.load().then(n=>{let r=this.waitingShow.get(e);this.waitingShow.delete(e),n&&r&&!this.destroyed&&t()&&r(n)})}cancelWaiting(e){return e!==null&&e.isLoading()&&this.waitingShow.delete(e)}resetView(){this.chart.fitContent(),this.chartSettings.changeSettings({autoScale:!0})}toast(e,t=`info`,n){let r=document.createElement(`div`);r.className=`tcw-toast ${t===`error`?`tcw-toast-error`:``}`,r.setAttribute(`role`,t===`error`?`alert`:`status`);let a=n?i.i(n,14):``;if(a){let e=document.createElement(`span`);e.className=`tcw-toast-icon`,e.innerHTML=a,r.appendChild(e)}r.appendChild(document.createTextNode(e));let o=e=>e.querySelector(`.tcw-modal-backdrop:not([hidden])`)!==null,s=o(this.portal)?this.portal:this.root;r.classList.toggle(`tcw-toast-over`,s===this.portal||o(this.root)),s.appendChild(r),requestAnimationFrame(()=>r.classList.add(`tcw-toast-in`)),setTimeout(()=>{r.classList.remove(`tcw-toast-in`),r.addEventListener(`transitionend`,()=>r.remove(),{once:!0}),setTimeout(()=>r.remove(),400)},3500)}say(e,t=`info`,n){(this.featureState.toasts||t===`error`)&&this.toast(e,t,n)}getLayoutSession(){return this.layouts.getLayoutSession()}getSymbol(){return this.state.symbol}getTimeframe(){return this.state.timeframe}captureLayout(){return this.layouts.captureLayout()}async restoreLayout(e){return this.layouts.restoreLayout(e)}getLayoutContent(){return this.layouts.getLayoutContent()}async applyLayoutContent(e){return this.layouts.applyLayoutContent(e)}getSettings(){return this.chartSettings.getSettings()}setCrosshairCursor(e){(0,d.isCrosshairCursor)(e)&&this.setSettings({crosshairCursor:e})}getCrosshairCursor(){return this.chartSettings.settingsState.crosshairCursor}setSettings(e){return this.chartSettings.setSettings(e)}onSettingsChange(e){return this.chartSettings.onSettingsChange(e)}async saveLayout(){return this.layouts.saveLayout()}async openLayout(e){return this.layouts.openLayout(e)}clearSavedLayout(e){return this.layouts.clearSavedLayout(e)}syncIndicatorsFromChart(){let e=new Map;for(let t of this.chart.getActiveIndicators())e.set(t.instanceId,{id:t.id,label:c.r(t,this.t)});this.state={...this.state,activeIndicators:e},this.updateUI(),this.indicatorPicker?.setCounts(this.indicatorCounts())}toggleIndicatorPicker(){if(this.indicatorPicker?.isOpen()){this.indicatorPicker.close();return}this.cancelWaiting(this.indicatorPickerPart)||this.whenLoaded(this.indicatorPickerPart,()=>this.featureState[`toolbar.indicators`],e=>{e.isOpen()||(e.open({items:this.indicatorPickerItems(),favorites:this.indicatorFavorites.list(),templates:this.featureState.indicatorTemplates?this.templateNames():null,counts:this.indicatorCounts()}),this.markOpen(`indicators`,!0))})}indicatorPickerItems(){return(this.chart.getAvailableIndicators()??[]).filter(e=>!d.SYMBOL_INDICATOR_IDS.has(e.id)&&this.chart.isIndicatorAllowed(e.id)!==!1).map(e=>({id:e.id,name:e.name,shortName:e.shortName??e.id.toUpperCase(),placement:e.placement===`panel`?`panel`:`overlay`,category:(0,d.indicatorCategory)(e)}))}indicatorCounts(){let e=new Map;for(let{id:t}of this.state.activeIndicators.values())e.set(t,(e.get(t)??0)+1);return e}templateNames(){return this.templates.list().map(e=>e.name)}toggleReplay(){this.replay.toggleReplay()}replayFrom(e,t=!1){this.replay.replayFrom(e,t)}replayHost(){return{chart:()=>this.chart,root:this.root,chartContainer:this.chartContainer,options:this.options,t:e=>this.t(e),isOn:()=>this.featureState.replay,isDestroyed:()=>this.destroyed,loading:this.loading,symbol:()=>this.state.symbol,timeframe:()=>this.state.timeframe,adapter:()=>this.adapter,baseSeries:()=>this.baseSeries,baseTimeframeMs:()=>this.baseTimeframeMs,resampleOptions:e=>this.resampleOptions(e),textLocale:()=>this.textLocale(),intlLocale:()=>this.intlLocale(),say:(e,t)=>this.say(e,t),markActive:e=>this.markOpen(`replay`,e),bodyEl:()=>this.bodyEl()}}placeDrawingButton(){let e=this.bodyEl();if(!this.sidebar||!e)return;let t=this.chartContainer.getBoundingClientRect().left-e.getBoundingClientRect().left;this.sidebar.setPlotLeft(t+this.chart.getPlotRect().x)}bodyEl(){return this.root.querySelector(`:scope > .tcw-body`)}async connectStream(){if(!this.adapter)return;let e=++this.connectSeq;this.state={...this.state,connectionState:`connecting`,connectionMessage:this.t(`status.connecting`)},this.updateUI(),this.loading.begin(this.chart.getData().length>0);try{if(this.chart.disconnectStream(),await this.chart.connect({adapter:this.adapter,symbol:this.state.symbol,timeframe:this.state.timeframe,historyLimit:this.options.historyLimit??500,historyPageSize:this.options.historyPageSize}),e!==this.connectSeq||this.destroyed)return;this.paintWatermark(),this.layouts.applySymbolLayout(this.state.symbol),this.loading.hasFailed()?this.state={...this.state,connectionState:`error`}:(this.loading.end(),this.state={...this.state,connectionState:`connected`,connectionMessage:this.t(`status.live`)}),this.comparing.refetchCompares()}catch(t){if(e!==this.connectSeq||this.destroyed)return;this.loading.fail(this.t(`status.connectionFailed`)),this.state={...this.state,connectionState:`error`,connectionMessage:t instanceof Error?t.message:this.t(`status.connectionFailed`)}}this.updateUI()}updateUI(){this.refreshDrawingsState(),this.legend.scheduleLegend(),this.toolbar?.update(this.state),this.sidebar?.update(this.state),this.showConnection()}showConnection(){let e=Fo(this.state.connectionState,this.state.connectionMessage,this.chart.getSymbolInfo?.(),this.t);this.statusBar?.update({connectionState:this.state.connectionState,message:e.message,delayed:e.delayed,symbol:this.state.symbol,timeframe:this.state.timeframe})}markOpen(e,t){let n=this.openRoles.peek();if(n.has(e)===t)return;let r=new Set(n);t?r.add(e):r.delete(e),this.openRoles.set(r)}resolveIsDark(e){return e===void 0||e===`dark`?!0:e===`light`?!1:typeof e==`object`&&e.background?this.isColorDark(e.background):!0}resolveTheme(e){return e===void 0||e===`dark`?u.DARK_THEME:e===`light`?u.LIGHT_THEME:typeof e==`object`?e:u.DARK_THEME}isColorDark(e){if(e.startsWith(`#`)&&e.length>=7){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return t+n+r<384}return!0}comparingHost(){let e=this;return{get adapter(){return e.adapter},get chart(){return e.chart},get destroyed(){return e.destroyed},get featureState(){return e.featureState},get options(){return e.options},refreshObjects:(...t)=>e.docking.refreshObjects(...t),refreshScaleSwitches:(...t)=>e.chartSettings.refreshScaleSwitches(...t),say:(...t)=>e.say(...t),scheduleLegend:(...t)=>e.legend.scheduleLegend(...t),get settings(){return e.settings},get settingsState(){return e.chartSettings.settingsState},showScaleMode:(...t)=>e.chartSettings.showScaleMode(...t),shownSettings:(...t)=>e.chartSettings.shownSettings(...t),get state(){return e.state},symbolEntries:(...t)=>e.symbolEntries(...t),get symbolLoads(){return e.symbolLoads},get symbolSearch(){return e.symbolSearch},symbolSearchFn:(...t)=>e.symbolSearchFn(...t),get t(){return e.t},withSymbolSearch:(...t)=>e.withSymbolSearch(...t)}}watchingHost(){let e=this;return{get chart(){return e.chart},chartSymbolInfo:(...t)=>e.chartSymbolInfo(...t),closePanelByHand:(...t)=>e.docking.closePanelByHand(...t),get destroyed(){return e.destroyed},get options(){return e.options},refreshSymbolInfo:(...t)=>e.refreshSymbolInfo(...t),get sessionRefPrice(){return e.sessionRefPrice},set sessionRefPrice(t){e.sessionRefPrice=t},setSymbol:(...t)=>e.setSymbol(...t),get settingsState(){return e.chartSettings.settingsState},get state(){return e.state},symbolEntries:(...t)=>e.symbolEntries(...t),symbolInfoOf:(...t)=>e.symbolInfoOf(...t),symbolSearchFn:(...t)=>e.symbolSearchFn(...t),get symbols(){return e.symbols},get t(){return e.t},withSymbolSearch:(...t)=>e.withSymbolSearch(...t)}}markingHost(){let e=this;return{get chart(){return e.chart},get options(){return e.options},get marksOn(){return e.marksDefault&&e.featureState.marks},get symbol(){return e.state.symbol},get destroyed(){return e.destroyed},get news(){return e.news},openMenu:(t,n,r,i)=>{let a=e.chartContainer.getBoundingClientRect(),o=e.root.getBoundingClientRect();e.menus.chartMenu?.open(t,a.left-o.left+n,a.top-o.top+r,i)},openLink:e=>{window.open(e,`_blank`,`noopener,noreferrer`)},liftNavigation:t=>e.chartNav?.setLift(t),hideNavigation:t=>e.chartNav?.setSuppressed(t)}}alertingHost(){let e=this;return{get chart(){return e.chart},get dock(){return e.docking.dock},drawingToolName:(...t)=>e.drawingToolName(...t),get featureState(){return e.featureState},formatAlertPrice:(...t)=>e.formatAlertPrice(...t),say:(...t)=>e.say(...t),get t(){return e.t}}}tradingHost(){let e=this;return{get chart(){return e.chart},get destroyed(){return e.destroyed},get dock(){return e.docking.dock},get featureState(){return e.featureState},formatAlertPrice:(...t)=>e.formatAlertPrice(...t),say:(...t)=>e.say(...t),get state(){return e.state},get t(){return e.t}}}menusHost(){let e=this;return{get adapter(){return e.adapter},get alerting(){return e.alerting},get canExport(){return e.canExport},changeSettings:(...t)=>e.chartSettings.changeSettings(...t),changeStyle:(...t)=>e.chartSettings.changeStyle(...t),get chart(){return e.chart},get chartContainer(){return e.chartContainer},get drawingSettings(){return e.drawingSettings},effectiveScaleMode:(...t)=>e.chartSettings.effectiveScaleMode(...t),get featureState(){return e.featureState},formatAlertPrice:(...t)=>e.formatAlertPrice(...t),get objectTree(){return e.objectTree},openDrawingSettings:(...t)=>e.drawingEdit.openDrawingSettings(...t),editDrawingText:(...t)=>e.drawingEdit.editDrawingText(...t),canTypeDrawingText:(...t)=>e.drawingEdit.canTypeText(...t),openSettings:(...t)=>e.chartSettings.openSettings(...t),get options(){return e.options},refreshDrawingsState:(...t)=>e.refreshDrawingsState(...t),refreshObjects:(...t)=>e.docking.refreshObjects(...t),resetView:(...t)=>e.resetView(...t),get root(){return e.root},say:(...t)=>e.say(...t),get settingsState(){return e.chartSettings.settingsState},get state(){return e.state},set state(t){e.state=t},get t(){return e.t},toggleGoToDate:(...t)=>e.toggleGoToDate(...t),get trading(){return e.trading},updateUI:(...t)=>e.updateUI(...t)}}legendHost(){let e=this;return{get chart(){return e.chart},get destroyed(){return e.destroyed},get featureState(){return e.featureState},handleRemoveIndicator:(...t)=>e.handleRemoveIndicator(...t),get indicatorLegend(){return e.indicatorLegend},indicatorValueText:(...t)=>e.indicatorValueText(...t),get legendHoverIndex(){return e.legendHoverIndex},openIndicatorSettings:(...t)=>e.openIndicatorSettings(...t),get options(){return e.options},get root(){return e.root},get settingsState(){return e.chartSettings.settingsState},get t(){return e.t}}}commandsHost(){let e=this;return{get adapter(){return e.adapter},cancelWaiting:(...t)=>e.cancelWaiting(...t),changeSettings:(...t)=>e.chartSettings.changeSettings(...t),get chart(){return e.chart},get commandPalette(){return e.commandPalette},get commandPalettePart(){return e.commandPalettePart},get comparing(){return e.comparing},copyChartImage:(...t)=>e.copyChartImage(...t),copyShareLink:(...t)=>e.layouts.copyShareLink(...t),get featureState(){return e.featureState},handleToggleTheme:(...t)=>e.handleToggleTheme(...t),indicatorPickerItems:(...t)=>e.indicatorPickerItems(...t),keysShown:(...t)=>e.keysShown(...t),get layoutSession(){return e.layouts.layoutSession},get menus(){return e.menus},openHotkeySheet:(...t)=>e.openHotkeySheet(...t),openPanel:(...t)=>e.docking.openPanel(...t),openSettings:(...t)=>e.chartSettings.openSettings(...t),openSymbolSearch:(...t)=>e.openSymbolSearch(...t),get options(){return e.options},resetView:(...t)=>e.resetView(...t),saveLayout:(...t)=>e.layouts.saveLayout(...t),say:(...t)=>e.say(...t),get settings(){return e.settings},get settingsState(){return e.chartSettings.settingsState},shownSettings:(...t)=>e.chartSettings.shownSettings(...t),get state(){return e.state},get t(){return e.t},get timeframes(){return e.timeframes},toggleDataWindow:(...t)=>e.docking.toggleDataWindow(...t),toggleGoToDate:(...t)=>e.toggleGoToDate(...t),toggleSymbolInfo:(...t)=>e.toggleSymbolInfo(...t),get watching(){return e.watching},whenLoaded:(...t)=>e.whenLoaded(...t)}}layoutsHost(){let e=this;return{allowedSettings:(...t)=>e.chartSettings.allowedSettings(...t),applyChartType:(...t)=>e.applyChartType(...t),applySettings:(...t)=>e.chartSettings.applySettings(...t),get chart(){return e.chart},get chosenTimeframe(){return e.chosenTimeframe},claimSettings:(...t)=>e.chartSettings.claimSettings(...t),get destroyed(){return e.destroyed},displayTimezone:(...t)=>e.displayTimezone(...t),getSettings:(...t)=>e.chartSettings.getSettings(...t),keysShown:(...t)=>e.keysShown(...t),get options(){return e.options},overViewerTypeOptions:(...t)=>e.overViewerTypeOptions(...t),get root(){return e.root},say:(...t)=>e.say(...t),setSymbol:(...t)=>e.setSymbol(...t),setTimeframe:(...t)=>e.setTimeframe(...t),get settings(){return e.settings},get settingsDefaults(){return e.chartSettings.settingsDefaults},showLinkSettings:(...t)=>e.chartSettings.showLinkSettings(...t),shownSettings:(...t)=>e.chartSettings.shownSettings(...t),get state(){return e.state},set state(t){e.state=t},syncIndicatorsFromChart:(...t)=>e.syncIndicatorsFromChart(...t),get t(){return e.t},get toolbar(){return e.toolbar},updateUI:(...t)=>e.updateUI(...t)}}dockingHost(){let e=this;return{markOpen:(...t)=>e.markOpen(...t),get alerting(){return e.alerting},get chart(){return e.chart},get chartContainer(){return e.chartContainer},get comparing(){return e.comparing},get dataWindow(){return e.dataWindow},get featureState(){return e.featureState},formatAlertPrice:(...t)=>e.formatAlertPrice(...t),indicatorValueText:(...t)=>e.indicatorValueText(...t),get lastHoverBar(){return e.lastHoverBar},get lastHoverIndex(){return e.lastHoverIndex},get lastHoverPrevClose(){return e.lastHoverPrevClose},get objectTree(){return e.objectTree},refreshDrawingsState:(...t)=>e.refreshDrawingsState(...t),get root(){return e.root},get settingsState(){return e.chartSettings.settingsState},get symbolInfoPanel(){return e.symbolInfoPanel},get t(){return e.t},get toolbar(){return e.toolbar},get trading(){return e.trading},get watching(){return e.watching}}}chartSettingsHost(){let e=this;return{get chart(){return e.chart},get comparing(){return e.comparing},get destroyed(){return e.destroyed},get featureState(){return e.featureState},get layouts(){return e.layouts},get legend(){return e.legend},get overlayHost(){return e.overlayHost},placeDrawingButton:(...t)=>e.placeDrawingButton(...t),say:(...t)=>e.say(...t),get settings(){return e.settings},get settingsPart(){return e.settingsPart},get state(){return e.state},get statusBar(){return e.statusBar},get t(){return e.t},get watching(){return e.watching},whenLoaded:(...t)=>e.whenLoaded(...t)}}drawingEditHost(){let e=this;return{get chart(){return e.chart},get chartContainer(){return e.chartContainer},chartOffset:(...t)=>e.chartOffset(...t),get destroyed(){return e.destroyed},get docking(){return e.docking},get drawingSettingsPart(){return e.drawingSettingsPart},drawingToolName:(...t)=>e.drawingToolName(...t),get featureState(){return e.featureState},get root(){return e.root},say:(...t)=>e.say(...t),get t(){return e.t},get ui(){return e.ui},whenLoaded:(...t)=>e.whenLoaded(...t)}}intervalsHost(){let e=this;return{get adapter(){return e.adapter},get baseSeries(){return e.baseSeries},get baseTimeframeMs(){return e.baseTimeframeMs},get chart(){return e.chart},get chosenTimeframe(){return e.chosenTimeframe},set chosenTimeframe(t){e.chosenTimeframe=t},get customTimeframes(){return e.customTimeframes},get destroyed(){return e.destroyed},displayTimezone:(...t)=>e.displayTimezone(...t),get featureState(){return e.featureState},handleTimeframe:(...t)=>e.handleTimeframe(...t),get options(){return e.options},say:(...t)=>e.say(...t),get state(){return e.state},switchTimeframe:(...t)=>e.switchTimeframe(...t),get timeframeFavorites(){return e.timeframeFavorites},get timeframes(){return e.timeframes},set timeframes(t){e.timeframes=t},get toolbar(){return e.toolbar},updateUI:(...t)=>e.updateUI(...t)}}};function Tc(e,t,n){let r=e=>{let t=(0,d.sourceParam)(e.descriptor);return t&&(0,u.parseIndicatorSource)(e.params[t])?.instanceId||null},i=new Set([e]);for(let e=!0;e;){e=!1;for(let n of t){let t=r(n);t&&i.has(t)&&!i.has(n.instanceId)&&(i.add(n.instanceId),e=!0)}}let a=[];for(let e of t){if(i.has(e.instanceId))continue;let t=c.r(e,n);for(let n of e.descriptor.plots??[])a.push({value:(0,u.indicatorSource)(e.instanceId,n.key),label:`${t}: ${n.title}`})}return a}var Ec=`tcw:recentCommands`,Dc=10;function Oc(){try{let e=JSON.parse(A()?.getItem(Ec)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`).slice(0,Dc):[]}catch{return[]}}function kc(e){try{A()?.setItem(Ec,JSON.stringify(e.slice(0,Dc)))}catch{}}var Ac=`tcw:dockWidth`;function jc(){try{let e=Number(A()?.getItem(Ac)??NaN);return Number.isFinite(e)&&e>0?e:null}catch{return null}}function Mc(e){try{A()?.setItem(Ac,String(e))}catch{}}function Nc(e){return!!e&&/^(ar|he|iw|fa|ur|ps|yi|dv|ckb|sd|ug)(-|$)/i.test(e)}var Pc=2,Fc=20,Ic=2,Lc=16,Rc=2,zc=4,Bc={left:`grid.layoutBigLeft`,right:`grid.layoutBigRight`,top:`grid.layoutBigTop`,bottom:`grid.layoutBigBottom`};function Vc(e,t,n){let r=(Fc-Ic*(n-1))/n;return[Pc+e*(r+Ic),t*r+(t-1)*Ic]}function Hc(t,n=Lc){return`<svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" aria-hidden="true">${e.c(t).map(([e,n,r,i])=>{let[a,o]=Vc(e,r,t.cols),[s,c]=Vc(n,i,t.rows);return`<rect x="${a}" y="${s}" width="${o}" height="${c}" rx="1"/>`}).join(``)}</svg>`}function Uc(t,n){let r=e.s[t],i=e.l(r);if(i===1)return n(`grid.single`);let a=e.u(r);return a?s.r(n(Bc[a]),{count:i}):s.r(n(`grid.layoutOption`),{count:i,cols:r.cols,rows:r.rows})}var Wc=class{button;panel=null;choices;onDocPointer=e=>{let t=e.target;!this.panel?.contains(t)&&!this.button.contains(t)&&this.close(!1)};onAway=()=>this.close(this.panel?.contains(document.activeElement)===!0);constructor(t){this.options=t;let n=new Set(t.choices);this.choices=e.o.filter(e=>n.has(e)),this.button=document.createElement(`button`),this.button.type=`button`,this.button.className=`tcw-dropdown-trigger tcw-grid-layout-btn`,this.button.setAttribute(`aria-haspopup`,`menu`),this.button.setAttribute(`aria-expanded`,`false`),this.button.addEventListener(`click`,()=>this.isOpen()?this.close():this.open()),this.button.addEventListener(`keydown`,e=>{e.key!==`ArrowDown`&&e.key!==`ArrowUp`||this.isOpen()||(e.preventDefault(),this.open())}),this.render()}render(){let{t,current:n}=this.options,r=n(),a=`${t(`grid.layout`)}: ${Uc(r,t)}`;this.button.innerHTML=Hc(e.s[r])+i.i(`chevronDown`,12),this.button.title=a,this.button.setAttribute(`aria-label`,a);for(let e of this.items())e.setAttribute(`aria-checked`,String(e.dataset.layout===r))}isOpen(){return this.panel!==null&&!this.panel.hidden}open(){let e=this.panel??this.build();this.render(),e.hidden=!1,this.button.setAttribute(`aria-expanded`,`true`),this.place(e),document.addEventListener(`pointerdown`,this.onDocPointer,!0),window.addEventListener(`resize`,this.onAway),window.addEventListener(`blur`,this.onAway);let t=this.items();(t.find(e=>e.getAttribute(`aria-checked`)===`true`)??t[0])?.focus({preventScroll:!0})}close(e=!0){this.isOpen()&&(this.panel.hidden=!0,this.button.setAttribute(`aria-expanded`,`false`),document.removeEventListener(`pointerdown`,this.onDocPointer,!0),window.removeEventListener(`resize`,this.onAway),window.removeEventListener(`blur`,this.onAway),e&&this.button.focus({preventScroll:!0}))}destroy(){this.close(!1),this.panel?.remove(),this.panel=null,this.button.remove()}build(){let{t:e,host:t}=this.options,n=document.createElement(`div`);n.className=`tcw-context-menu tcw-grid-picker`,n.setAttribute(`role`,`menu`),n.setAttribute(`aria-label`,e(`grid.layout`)),n.hidden=!0;for(let[e,t]of this.byCount())n.appendChild(this.group(e,t));return n.addEventListener(`keydown`,e=>this.onKeyDown(e)),t.appendChild(n),this.panel=n,n}byCount(){let t=new Map;for(let n of this.choices){let r=e.l(e.s[n]);t.set(r,[...t.get(r)??[],n])}return t}group(e,t){let{t:n}=this.options,r=document.createElement(`div`);r.className=`tcw-grid-picker-group`,r.setAttribute(`role`,`group`),r.setAttribute(`aria-label`,e===1?n(`grid.single`):s.r(n(`grid.layoutCount`),{count:e}));let i=document.createElement(`span`);i.className=`tcw-grid-picker-count`,i.setAttribute(`aria-hidden`,`true`),i.textContent=String(e);let a=document.createElement(`div`);return a.className=`tcw-grid-picker-row`,a.append(...t.map(e=>this.item(e))),r.append(i,a),r}item(t){let n=Uc(t,this.options.t),r=document.createElement(`button`);return r.type=`button`,r.className=`tcw-btn-icon tcw-grid-picker-item`,r.setAttribute(`role`,`menuitemradio`),r.setAttribute(`aria-checked`,`false`),r.tabIndex=-1,r.dataset.layout=t,r.title=n,r.setAttribute(`aria-label`,n),r.innerHTML=Hc(e.s[t]),r.addEventListener(`click`,()=>this.pick(t)),r}pick(e){this.close(),this.options.onPick(e),this.render()}place(e){let{host:t}=this.options,n=this.button.getBoundingClientRect(),r=t.getBoundingClientRect(),i=t.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`,a=e.offsetWidth,o=i?n.right-r.left-a:n.left-r.left,s=t.clientWidth-a-zc;e.style.left=`${Math.max(0,Math.min(o,s))}px`,e.style.top=`${n.bottom-r.top+Rc}px`,e.style.maxHeight=`${Math.max(0,t.clientHeight-(n.bottom-r.top)-Rc-zc)}px`}items(){return this.panel?[...this.panel.querySelectorAll(`[role="menuitemradio"]`)]:[]}rows(){return this.panel?[...this.panel.querySelectorAll(`.tcw-grid-picker-row`)].map(e=>[...e.querySelectorAll(`[role="menuitemradio"]`)]):[]}onKeyDown(e){let t=document.activeElement;if(e.key===`Escape`||e.key===`Tab`){e.preventDefault(),e.stopPropagation(),this.close();return}if((e.key===`Enter`||e.key===` `)&&t?.dataset.layout){e.preventDefault(),this.pick(t.dataset.layout);return}let n=this.moveFrom(t,e.key);n&&(e.preventDefault(),n.focus({preventScroll:!0}))}moveFrom(e,t){let n=this.items(),r=Math.max(0,n.indexOf(e)),[i,a]=this.options.host.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?[`ArrowLeft`,`ArrowRight`]:[`ArrowRight`,`ArrowLeft`];if(t===i)return n[(r+1)%n.length];if(t===a)return n[(r-1+n.length)%n.length];if(t===`Home`)return n[0];if(t===`End`)return n[n.length-1];if(t!==`ArrowDown`&&t!==`ArrowUp`)return null;let o=this.rows(),s=o.findIndex(e=>e.includes(n[r])),c=o[s].indexOf(n[r]),l=o[(s+(t===`ArrowDown`?1:-1)+o.length)%o.length];return l[Math.min(c,l.length-1)]}},Gc={symbol:!1,interval:!1,crosshair:!0,time:!1,drawings:!1,replay:!1},Kc=[`symbol`,`interval`,`crosshair`,`time`,`drawings`,`replay`],qc=e.s;function Jc(e){return JSON.parse(JSON.stringify(e))}function Yc(t){if(typeof t!=`object`||!t)return null;let n=t;if(n.v!==1||n.kind!==`grid`||!e.d(n.layout)||!Array.isArray(n.cells))return null;let r=n.cells.map(Ia);if(r.some(e=>e===null))return null;let i=typeof n.sync==`object`&&n.sync!==null?n.sync:{},a={...Gc};for(let e of Kc)typeof i[e]==`boolean`&&(a[e]=i[e]);let o=typeof n.active==`number`&&Number.isInteger(n.active)?n.active:0;return{v:1,kind:`grid`,layout:n.layout,sync:a,active:o,cells:r}}var Xc=class{root;cellsEl;cells=[];layout;sync;active=0;hovered=null;relayDepth=0;uiTheme=null;styleOverrides={};featureSwitches={};parked=new Map;drawingFrame=0;drawingSource=null;layoutPicker=null;syncButtons=new Map;layoutsButton=null;tabsEl=null;stopNarrow=()=>{};session=null;layoutsUI=null;t;destroyed=!1;unregisterKeys=()=>{};onKeyDown=e=>{!(e.ctrlKey||e.metaKey)||e.altKey||e.shiftKey||e.key!==`s`&&e.key!==`S`||!this.layoutsUI||O()||!D(this.root,!0)||(e.preventDefault(),this.layoutsUI.save())};constructor(t,n={}){this.options=n,this.layout=e.d(n.layout)?n.layout:`1x2`,this.sync={...Gc,...n.sync},this.t=s.n(s.o(n.widget?.locale,n.widget?.messages)),fe(),this.root=document.createElement(`div`),this.root.className=`tcw-root tcw-grid`,this.root.dataset.tcwTheme=n.widget?.theme===`light`?`light`:`dark`,Or(this.root,I(n.widget?.ui),{variables:n.widget?.ui!==void 0}),n.bar!==!1&&this.root.appendChild(this.buildBar()),this.cellsEl=document.createElement(`div`),this.cellsEl.className=`tcw-grid-cells`,this.root.appendChild(this.cellsEl),t.appendChild(this.root),this.stopNarrow=Va(this.root),this.applyShape();for(let e=0;e<this.shapeCount();e++)this.cells.push(this.createCell(e));this.markActive();let r=this.cells[0]?.el.querySelector(`.tcw-root`)?.dataset.tcwTheme;r&&(this.root.dataset.tcwTheme=r),n.layouts!==!1&&this.setupLayouts(n.layouts===!0||n.layouts===void 0?{}:n.layouts),this.unregisterKeys=Pt(this.root),document.addEventListener(`keydown`,this.onKeyDown)}get relaying(){return this.relayDepth>0}quietly(e){this.relayDepth++;try{return e()}finally{this.relayDepth--}}getWidget(e){return this.cells[e]?.widget??null}getWidgets(){return this.cells.map(e=>e.widget)}getActiveIndex(){return this.active}getActiveWidget(){return this.cells[this.active].widget}setActive(e){e<0||e>=this.cells.length||e===this.active||(this.active=e,this.markActive(),this.options.onActiveChange?.(e,this.cells[e].widget),this.session?.changed())}getLayout(){return this.layout}setLayout(t){if(t===this.layout||!e.d(t))return;this.layout=t;let n=this.shapeCount();for(;this.cells.length>n;){let e=this.cells.length-1,t=this.cells.pop();this.parked.set(e,t.widget.captureLayout()),this.destroyCell(t)}this.applyShape();for(let e=this.cells.length;e<n;e++){let t=this.createCell(e);this.cells.push(t),this.unpark(e,t)}this.active>=n&&(this.active=0,this.options.onActiveChange?.(0,this.cells[0].widget)),this.markActive(),this.renderBar(),this.session?.changed()}getSync(){return{...this.sync}}setUI(e){let t=I(e);Or(this.root,t);for(let e of this.cells)e.widget.setUI(t);this.uiTheme=t}getUI(){return I(this.uiTheme??this.options.widget?.ui)}setSync(e){let t=this.sync;if(this.sync={...this.sync,...e},t.crosshair&&!this.sync.crosshair)for(let e of this.cells)e.widget.getChart().setCrosshairTime(null);let n=this.cells[this.active];if(n&&!this.relaying){let e=n.widget.getSymbol(),r=n.widget.getTimeframe();!t.symbol&&this.sync.symbol&&this.relay(n,t=>void t.setSymbol(e)),!t.interval&&this.sync.interval&&this.relay(n,e=>void e.setTimeframe(r)),!t.drawings&&this.sync.drawings&&this.mergeDrawings()}this.renderBar(),this.session?.changed()}applyOverrides(e){for(let t of this.cells)t.widget.getChart().applyOverrides(e);let t={...this.styleOverrides};for(let[n,r]of Object.entries(e))r==null?delete t[n]:t[n]=r;this.styleOverrides=t}setFeatures(e){let t=r.l(e);for(let e of this.cells)e.widget.setFeatures(t);this.featureSwitches={...this.featureSwitches,...t}}setTheme(e){for(let t of this.cells)t.widget.setTheme(e);this.followTheme()}getLayoutSession(){return this.session}captureLayout(){let e=[...this.parked.entries()].sort(([e],[t])=>e-t).map(([,e])=>e);return{v:1,kind:`grid`,layout:this.layout,sync:{...this.sync},active:this.active,cells:[...this.cells.map(e=>e.widget.captureLayout()),...e]}}async restoreLayout(e){this.relayDepth++;let t;try{this.parked.clear(),this.setLayout(e.layout),this.sync={...e.sync},this.renderBar();let n=this.cells.length;e.cells.slice(n).forEach((e,t)=>this.parked.set(n+t,e)),t=await Promise.allSettled(this.cells.map((t,n)=>e.cells[n]?t.widget.restoreLayout(e.cells[n]):Promise.resolve()))}finally{this.relayDepth--}if(this.destroyed)return;this.setActive(Math.min(Math.max(0,e.active),this.cells.length-1)),this.renderTabs();let n=t.find(e=>e.status===`rejected`);if(n)throw n.reason}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=Yc(La(e));return t?(await this.restoreLayout(t),!0):!1}destroy(){if(!this.destroyed){this.destroyed=!0,document.removeEventListener(`keydown`,this.onKeyDown),this.unregisterKeys(),this.stopNarrow(),this.drawingFrame&&cancelAnimationFrame(this.drawingFrame),this.session?.destroy(),this.layoutsUI?.destroy(),this.layoutPicker?.destroy();for(let e of this.cells)this.destroyCell(e);this.cells=[],this.root.remove(),pe()}}shapeCount(){return e.l(e.s[this.layout])}applyShape(){let t=e.s[this.layout];this.cellsEl.style.gridTemplateColumns=`repeat(${t.cols}, minmax(0, 1fr))`,this.cellsEl.style.gridTemplateRows=`repeat(${t.rows}, minmax(0, 1fr))`;let n=e.c(t);this.cells.forEach((t,r)=>e.f(t.el,n[r]))}createCell(t){let n=document.createElement(`div`);n.className=`tcw-grid-cell`,n.setAttribute(`role`,`region`),n.setAttribute(`aria-label`,s.r(this.t(`grid.chart`),{n:t+1})),e.f(n,e.c(e.s[this.layout])[t]),this.cellsEl.appendChild(n);let r=this.options.widget??{},i=this.options.cells?.[t]??{},a=this.cells[this.active]?.widget,o={},c=new wc(n,{...r,...i,...i.adapter?{feed:void 0}:{},...i.feed?{adapter:void 0}:{},...a&&this.sync.symbol?{symbol:a.getSymbol()}:{},...a&&this.sync.interval?{timeframe:a.getTimeframe()}:{},...this.options.adapter&&!i.adapter&&!i.feed&&!r.feed?{adapter:this.options.adapter(t)}:{},...this.uiTheme?{ui:this.uiTheme}:{},layouts:!1,...i.persistSettings===void 0&&r.persistSettings?{persistSettings:{key:`${ii(r.persistSettings)}:${t}`}}:{},features:{dock:!1,...r.features,...i.features},onSymbolChange:e=>{i.onSymbolChange?.(e),r.onSymbolChange?.(e),this.sync.symbol&&this.relay(o,t=>void t.setSymbol(e)),this.renderTabs(),this.session?.changed()},onTimeframeChange:e=>{i.onTimeframeChange?.(e),r.onTimeframeChange?.(e),this.sync.interval&&this.relay(o,t=>void t.setTimeframe(e)),this.renderTabs(),this.session?.changed()}});return o.el=n,o.widget=c,Object.keys(this.styleOverrides).length>0&&c.getChart().applyOverrides(this.styleOverrides),Object.keys(this.featureSwitches).length>0&&c.setFeatures(this.featureSwitches),this.wireCell(o),n.addEventListener(`pointerdown`,()=>this.setActive(this.cells.indexOf(o)),!0),n.addEventListener(`pointerenter`,()=>{this.hovered=o}),n.addEventListener(`pointerleave`,()=>{this.hovered===o&&(this.hovered=null)}),this.options.onChartAdd?.(c,t),o}wireCell(e){let t=e.widget.getChart(),n=()=>this.cells.filter(t=>t!==e);t.on(`crosshairMove`,e=>{let t=e.payload.bar?.time;if(!(!this.sync.crosshair||t===void 0))for(let e of n())e.widget.getChart().setCrosshairTime(t)}),t.on(`crosshairLeave`,()=>{if(this.sync.crosshair)for(let e of n())e.widget.getChart().setCrosshairTime(null)}),t.on(`visibleRangeChange`,n=>{if(!this.sync.time||this.relaying||(this.hovered??this.cells[this.active])!==e)return;let{from:r,to:i}=n.payload,a=t.getData(),o=a[r]?.time,s=a[i]?.time;o===void 0||s===void 0||this.relay(e,e=>e.getChart().setVisibleRange(o,s))});for(let n of[`drawingCreate`,`drawingUpdate`,`drawingRemove`])t.on(n,()=>{this.sync.drawings&&!this.relaying&&this.copyDrawingsSoon(e)});t.on(`replayStep`,t=>{if(!this.sync.replay||this.relaying||t.payload.cause===`series`)return;let{until:n}=t.payload;this.relay(e,e=>{let t=e.getChart();if(t.isReplayActive()){t.replaySeekToTime(n);return}let r=Zc(t.getData(),n);r>=0&&t.replayStart({startIndex:r,paused:!0})})}),t.on(`replayState`,t=>{!this.sync.replay||this.relaying||t.payload.state!==`stopped`||this.relay(e,e=>{e.getChart().isReplayActive()&&e.getChart().replayStop()})}),t.on(`stateChange`,()=>this.session?.changed()),e.widget.onSettingsChange(()=>this.session?.changed()),t.on(`themeChange`,()=>{this.relaying||this.followTheme(e)})}destroyCell(e){this.hovered===e&&(this.hovered=null),this.drawingSource===e&&(this.drawingSource=null),this.quietly(()=>e.widget.destroy()),e.el.remove()}relay(e,t){this.relaying||this.quietly(()=>{for(let n of this.cells)n!==e&&t(n.widget)})}unpark(e,t){let n=this.parked.get(e);if(!n)return;this.parked.delete(e);let r=this.cells[this.active]?.widget,i={...n,...r&&this.sync.symbol?{symbol:r.getSymbol()}:{},...r&&this.sync.interval?{timeframe:r.getTimeframe()}:{}};this.relayDepth++,t.widget.restoreLayout(i).catch(()=>t.widget.toast(this.t(`layouts.openFailed`),`error`)).finally(()=>{this.relayDepth--})}copyDrawingsSoon(e){this.drawingSource=e,!this.drawingFrame&&(this.drawingFrame=requestAnimationFrame(()=>{this.drawingFrame=0;let e=this.drawingSource;this.drawingSource=null,e&&!this.destroyed&&!this.relaying&&this.copyDrawings(e)}))}copyDrawings(e){let t=e.widget.getSymbol(),n=e.widget.getChart().getDrawings();this.quietly(()=>{for(let r of this.cells)r!==e&&r.widget.getSymbol()===t&&r.widget.getChart().setDrawings(Jc(n))})}mergeDrawings(){let e=new Map;for(let t of this.cells)e.set(t.widget.getSymbol(),[...e.get(t.widget.getSymbol())??[],t]);this.quietly(()=>{for(let t of e.values()){if(t.length<2)continue;let e=new Map;for(let n of t)for(let t of n.widget.getChart().getDrawings())e.has(t.id)||e.set(t.id,t);let n=[...e.values()];for(let e of t)e.widget.getChart().setDrawings(Jc(n))}})}followTheme(e=this.cells[this.active]){let t=e?.el.querySelector(`.tcw-root`)?.dataset.tcwTheme;t&&(this.root.dataset.tcwTheme=t,this.quietly(()=>{for(let n of this.cells)n!==e&&n.el.querySelector(`.tcw-root`)?.dataset.tcwTheme!==t&&n.widget.setTheme(t)}))}markActive(){this.cells.forEach((e,t)=>{e.el.classList.toggle(`tcw-grid-cell-active`,t===this.active&&this.cells.length>1),e.el.classList.toggle(`tcw-grid-cell-current`,t===this.active)}),this.renderTabs()}renderTabs(){let e=this.tabsEl;if(!e)return;let t=this.cells.map(e=>`${(0,u.tickerOf)(e.widget.getSymbol())} · ${e.widget.getTimeframe()}`);for(;e.children.length>t.length;)e.lastElementChild?.remove();for(;e.children.length<t.length;){let t=e.children.length,n=document.createElement(`button`);n.type=`button`,n.className=`tcw-btn tcw-grid-tab`,n.addEventListener(`click`,()=>this.setActive(t)),e.appendChild(n)}t.forEach((t,n)=>{let r=e.children[n];r.textContent!==t&&(r.textContent=t);let i=n===this.active;r.classList.toggle(`tcw-active`,i),r.setAttribute(`aria-pressed`,String(i))})}buildBar(){let t=document.createElement(`div`);t.className=`tcw-grid-bar`,t.setAttribute(`role`,`toolbar`),t.setAttribute(`aria-label`,this.t(`grid.bar`)),this.tabsEl=document.createElement(`div`),this.tabsEl.className=`tcw-grid-group tcw-grid-tabs`,this.root.classList.add(`tcw-grid-has-tabs`),this.tabsEl.setAttribute(`role`,`group`),this.tabsEl.setAttribute(`aria-label`,this.t(`grid.charts`));let n=document.createElement(`div`);n.className=`tcw-grid-group`,n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,this.t(`grid.layout`));let r=this.options.layoutChoices?.filter(e.d)??e.o;r.length>0&&(this.layoutPicker=new Wc({host:this.root,t:this.t,choices:r,current:()=>this.layout,onPick:e=>this.setLayout(e)}),n.appendChild(this.layoutPicker.button)),t.appendChild(n),t.appendChild(this.tabsEl);let o=document.createElement(`div`);o.className=`tcw-grid-group`,o.setAttribute(`role`,`group`),o.setAttribute(`aria-label`,this.t(`grid.sync`));let s=document.createElement(`span`);s.className=`tcw-grid-label`,s.innerHTML=`${i.i(`link`,13)}<span>${a.u(this.t(`grid.sync`))}</span>`,o.appendChild(s);for(let e of Kc){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-btn tcw-grid-sync`,t.textContent=this.t(`grid.sync.${e}`),t.title=this.t(`grid.sync.${e}.hint`),t.addEventListener(`click`,()=>this.setSync({[e]:!this.sync[e]})),this.syncButtons.set(e,t),o.appendChild(t)}let c=document.createElement(`span`);return c.className=`tcw-toolbar-spacer`,t.append(this.sep(),o,c),this.options.layouts!==!1&&(this.layoutsButton=document.createElement(`button`),this.layoutsButton.type=`button`,this.layoutsButton.className=`tcw-dropdown-trigger tcw-layouts-btn`,this.layoutsButton.setAttribute(`aria-haspopup`,`menu`),this.layoutsButton.addEventListener(`click`,()=>{this.layoutsButton&&this.layoutsUI?.openMenu(this.layoutsButton)}),t.appendChild(this.layoutsButton)),this.renderBar(),t}sep(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-sep`,e}renderBar(){this.layoutPicker?.render();for(let[e,t]of this.syncButtons)t.classList.toggle(`tcw-active`,this.sync[e]),t.setAttribute(`aria-pressed`,String(this.sync[e]));this.renderLayoutsButton()}renderLayoutsButton(){let e=this.layoutsButton;if(!e)return;let t=this.session?.current()?.name??this.t(`layouts.unnamed`),n=this.session?.isDirty()??!1,r=`${this.t(`toolbar.layouts`)}: ${t}${n?` (${this.t(`layouts.unsavedChanges`)})`:``}`;e.innerHTML=`${i.i(`save`,14)}<span class="tcw-layouts-label">${a.u(t)}</span>`+(n?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+i.i(`chevronDown`,12),e.title=r,e.setAttribute(`aria-label`,r)}setupLayouts(t){let n=new e.t(t.storage??e.i(`tcw:grid-layouts:`),{capture:()=>{let e=this.cells[this.active].widget;return{content:this.getLayoutContent(),symbol:e.getSymbol(),timeframe:e.getTimeframe()}},apply:async e=>{if(!await this.applyLayoutContent(e.content))throw Error(`Not a grid layout`)}},{autoSave:t.autoSave,debounceMs:t.debounceMs,kind:`grid`,onChange:()=>this.renderLayoutsButton(),onError:()=>this.toast(this.t(`layouts.saveFailed`),`error`)});this.session=n,this.layoutsUI=new xs(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=Y(e,null);return`${t} ${n}`}}),this.renderLayoutsButton(),t.openLast&&n.list().then(([e])=>e&&!this.destroyed?this.layoutsUI?.open(e.id):void 0,()=>void 0)}toast(e,t=`info`){this.cells[this.active]?.widget.toast(e,t)}};function Zc(e,t){let n=-1;for(let r=0;r<e.length&&e[r].time<t;r++)n=r;return n}Object.defineProperty(exports,`CHART_TYPE_ICONS`,{enumerable:!0,get:function(){return u.CHART_TYPE_ICONS}}),exports.ChartWidget=wc,exports.ChartWidgetGrid=Xc,exports.DEFAULT_GRID_SYNC=Gc,Object.defineProperty(exports,`DRAWING_TOOL_ICONS`,{enumerable:!0,get:function(){return u.DRAWING_TOOL_ICONS}}),exports.EN_MESSAGES=s.c,exports.GRID_SHAPES=qc,exports.LayoutSession=e.t,exports.MAX_LAYOUT_NAME=e.n,Object.defineProperty(exports,`UI_ICONS`,{enumerable:!0,get:function(){return u.UI_ICONS}}),exports.VI_MESSAGES=s.s,exports.WIDGET_FEATURES=r.r,exports.WIDGET_UI_PRESETS=xr,exports.applyWidgetUI=Or,exports.cleanLayoutName=e.r,exports.createChartTypeIcon=i.r,exports.createIcon=i.i,exports.createToolIcon=i.a,exports.findWidgetLocale=s.i,Object.defineProperty(exports,`iconSvg`,{enumerable:!0,get:function(){return u.iconSvg}}),exports.localStorageLayouts=e.i,exports.memoryLayouts=e.a,exports.readGridLayout=Yc,exports.readWatchlists=un,exports.readWidgetLayout=Ia,exports.registerWidgetLocale=s.a,exports.resolveWidgetUI=I,exports.widgetUIVariables=Dr;
|
|
7959
7959
|
//# sourceMappingURL=index.cjs.map
|