@tradecanvas/chart 1.80.0 → 1.81.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/dist/{LayoutSession-CX3eWUA1.js → LayoutSession-C4Lp1X6t.js} +2 -2
- package/dist/{LayoutSession-CX3eWUA1.js.map → LayoutSession-C4Lp1X6t.js.map} +1 -1
- package/dist/{LayoutSession-DFvb5ekw.cjs → LayoutSession-CeayqT91.cjs} +2 -2
- package/dist/{LayoutSession-DFvb5ekw.cjs.map → LayoutSession-CeayqT91.cjs.map} +1 -1
- package/dist/{WidgetSymbolSearch-BW7HxOMk.cjs → WidgetSymbolSearch-DeBxGj4a.cjs} +2 -2
- package/dist/{WidgetSymbolSearch-BW7HxOMk.cjs.map → WidgetSymbolSearch-DeBxGj4a.cjs.map} +1 -1
- package/dist/{WidgetSymbolSearch-CYYd9zoA.js → WidgetSymbolSearch-WOskcBJN.js} +24 -24
- package/dist/{WidgetSymbolSearch-CYYd9zoA.js.map → WidgetSymbolSearch-WOskcBJN.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/{symbolCatalog-DffhUQSJ.js → symbolCatalog-B_9kDAjE.js} +30 -27
- package/dist/symbolCatalog-B_9kDAjE.js.map +1 -0
- package/dist/symbolCatalog-CXqRu23x.cjs +2 -0
- package/dist/symbolCatalog-CXqRu23x.cjs.map +1 -0
- package/dist/widget/WidgetLoadingOverlay.d.ts.map +1 -1
- package/dist/widget/index.cjs +21 -61
- package/dist/widget/index.cjs.map +1 -1
- package/dist/widget/index.js +1023 -1027
- package/dist/widget/index.js.map +1 -1
- package/dist/widget/symbolCatalog.d.ts +2 -7
- package/dist/widget/symbolCatalog.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/symbolCatalog-CSbI2R5e.cjs +0 -2
- package/dist/symbolCatalog-CSbI2R5e.cjs.map +0 -1
- package/dist/symbolCatalog-DffhUQSJ.js.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-DFvb5ekw.cjs`),t=require(`../widgetLocales-fhdzLs5l.cjs`),n=require(`../monthView-B-CieFDJ.cjs`),r=require(`../widgetFeatures-BZ8OVPN2.cjs`),i=require(`../focusTrap-DrhhmG0V.cjs`),a=require(`../symbolCatalog-CSbI2R5e.cjs`),o=require(`../settingsControls-Tn8_vJJv.cjs`),s=require(`../i18n-hMXCt55K.cjs`),c=require(`../indicatorInputWords-BfWHWL0K.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-CeayqT91.cjs`),t=require(`../widgetLocales-fhdzLs5l.cjs`),n=require(`../monthView-B-CieFDJ.cjs`),r=require(`../widgetFeatures-BZ8OVPN2.cjs`),i=require(`../focusTrap-DrhhmG0V.cjs`),a=require(`../symbolCatalog-CXqRu23x.cjs`),o=require(`../settingsControls-Tn8_vJJv.cjs`),s=require(`../i18n-hMXCt55K.cjs`),c=require(`../indicatorInputWords-BfWHWL0K.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,
|
|
@@ -800,26 +800,12 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
|
|
|
800
800
|
opacity: 0;
|
|
801
801
|
}
|
|
802
802
|
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
flex-direction: column;
|
|
806
|
-
align-items: center;
|
|
807
|
-
gap: 14px;
|
|
808
|
-
padding: 22px 26px 20px;
|
|
809
|
-
border: 1px solid transparent;
|
|
810
|
-
border-radius: var(--tcw-panel-radius);
|
|
811
|
-
}
|
|
812
|
-
|
|
813
|
-
/* A slow switch: the previous chart stays readable underneath, dimmed, so the
|
|
814
|
-
click visibly registered without blanking the screen. */
|
|
803
|
+
/* A slow switch: the previous chart stays underneath, lightly dimmed and blurred, so the click
|
|
804
|
+
visibly registered without blanking the screen; the candles stand on it with no panel. */
|
|
815
805
|
.tcw-loading-overlay--veil {
|
|
816
|
-
background: color-mix(in srgb, var(--tcw-bg)
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
.tcw-loading-overlay--veil .tcw-loading-card {
|
|
820
|
-
background: var(--tcw-bg-elevated);
|
|
821
|
-
border-color: var(--tcw-border);
|
|
822
|
-
box-shadow: var(--tcw-menu-shadow);
|
|
806
|
+
background: color-mix(in srgb, var(--tcw-bg) 45%, transparent);
|
|
807
|
+
-webkit-backdrop-filter: blur(3px);
|
|
808
|
+
backdrop-filter: blur(3px);
|
|
823
809
|
}
|
|
824
810
|
|
|
825
811
|
.tcw-loading-candles {
|
|
@@ -870,30 +856,6 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
|
|
|
870
856
|
20% { opacity: 1; transform: translateY(-2px); }
|
|
871
857
|
}
|
|
872
858
|
|
|
873
|
-
.tcw-loading-track {
|
|
874
|
-
position: relative;
|
|
875
|
-
width: 100%;
|
|
876
|
-
min-width: 88px;
|
|
877
|
-
height: 2px;
|
|
878
|
-
border-radius: 1px;
|
|
879
|
-
background: var(--tcw-border);
|
|
880
|
-
overflow: hidden;
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
.tcw-loading-track > span {
|
|
884
|
-
position: absolute;
|
|
885
|
-
inset: 0;
|
|
886
|
-
width: 40%;
|
|
887
|
-
border-radius: 1px;
|
|
888
|
-
background: linear-gradient(90deg, transparent, var(--tcw-accent), transparent);
|
|
889
|
-
animation: tcw-loading-sweep 1.6s var(--tcw-ease) infinite;
|
|
890
|
-
}
|
|
891
|
-
|
|
892
|
-
@keyframes tcw-loading-sweep {
|
|
893
|
-
from { transform: translateX(-100%); }
|
|
894
|
-
to { transform: translateX(250%); }
|
|
895
|
-
}
|
|
896
|
-
|
|
897
859
|
/* The status text is announced, not shown — the candles say "loading". */
|
|
898
860
|
.tcw-loading-label {
|
|
899
861
|
position: absolute;
|
|
@@ -904,8 +866,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
|
|
|
904
866
|
white-space: nowrap;
|
|
905
867
|
}
|
|
906
868
|
|
|
907
|
-
.tcw-loading-overlay--error .tcw-loading-candles
|
|
908
|
-
.tcw-loading-overlay--error .tcw-loading-track {
|
|
869
|
+
.tcw-loading-overlay--error .tcw-loading-candles {
|
|
909
870
|
display: none;
|
|
910
871
|
}
|
|
911
872
|
|
|
@@ -923,18 +884,23 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
|
|
|
923
884
|
font-size: var(--tcw-font-size);
|
|
924
885
|
}
|
|
925
886
|
|
|
887
|
+
/* Over a veiled chart the message gets a plate of its own: red text straight on candles and
|
|
888
|
+
gridlines that are only dimmed would be hard to read. */
|
|
889
|
+
.tcw-loading-overlay--veil.tcw-loading-overlay--error .tcw-loading-label {
|
|
890
|
+
padding: var(--tcw-space-3) var(--tcw-space-4);
|
|
891
|
+
background: var(--tcw-bg-elevated);
|
|
892
|
+
border: var(--tcw-border-w) solid var(--tcw-border);
|
|
893
|
+
border-radius: var(--tcw-radius);
|
|
894
|
+
box-shadow: var(--tcw-shadow-md);
|
|
895
|
+
}
|
|
896
|
+
|
|
926
897
|
/* Reduced motion: nothing slides or lifts, but the candles still glow in
|
|
927
|
-
turn
|
|
898
|
+
turn, so the wait never looks frozen. */
|
|
928
899
|
@media (prefers-reduced-motion: reduce) {
|
|
929
900
|
.tcw-loading-candle {
|
|
930
901
|
animation: tcw-candle-glow 2.4s ease-in-out infinite;
|
|
931
902
|
animation-delay: var(--tcw-delay, 0ms);
|
|
932
903
|
}
|
|
933
|
-
.tcw-loading-track > span {
|
|
934
|
-
width: 100%;
|
|
935
|
-
background: var(--tcw-accent);
|
|
936
|
-
animation: tcw-loading-breathe 2.4s ease-in-out infinite;
|
|
937
|
-
}
|
|
938
904
|
}
|
|
939
905
|
|
|
940
906
|
@keyframes tcw-candle-glow {
|
|
@@ -942,11 +908,6 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
|
|
|
942
908
|
25% { opacity: 0.9; }
|
|
943
909
|
}
|
|
944
910
|
|
|
945
|
-
@keyframes tcw-loading-breathe {
|
|
946
|
-
0%, 100% { opacity: 0.15; }
|
|
947
|
-
50% { opacity: 0.7; }
|
|
948
|
-
}
|
|
949
|
-
|
|
950
911
|
/* === On-chart indicator legend (WidgetIndicatorLegend) === */
|
|
951
912
|
|
|
952
913
|
.tcw-ind-legend {
|
|
@@ -3574,8 +3535,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
|
|
|
3574
3535
|
|
|
3575
3536
|
/* Except the loader's slow glow (opacity only): without it a long wait
|
|
3576
3537
|
looks frozen. */
|
|
3577
|
-
.tcw-root .tcw-loading-candle
|
|
3578
|
-
.tcw-root .tcw-loading-track > span {
|
|
3538
|
+
.tcw-root .tcw-loading-candle {
|
|
3579
3539
|
animation-duration: 2.4s !important;
|
|
3580
3540
|
animation-iteration-count: infinite !important;
|
|
3581
3541
|
animation-delay: var(--tcw-delay, 0ms) !important;
|
|
@@ -7845,7 +7805,7 @@ ${r.f()}`,document.head.insertBefore(e,document.head.firstChild)}function pe(){i
|
|
|
7845
7805
|
<button type="button" class="tcw-replay-text-btn" data-act="cancel" data-mode="select" ${t}>${a.u(e.cancel)}</button>
|
|
7846
7806
|
</span>
|
|
7847
7807
|
<span class="tcw-visually-hidden" role="status" aria-live="polite" data-tcw="announce" ${t}></span>
|
|
7848
|
-
`}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)},Lt)}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 zt){let n=e.querySelector(`[data-act="${t}"]`);n&&(n.disabled=this.pending)}}},Vt=864e5,Ht=6e4,Ut=1e3,Wt=150,Gt=5e3,Kt=8,qt=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 Bt({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*Kt),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>=Vt)return s;let c={hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`};return(!Number.isFinite(i)||i<Ht)&&(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(!Jt(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(),Wt)}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?Ut:Ut/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.d(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.f(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(Gt,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||E()||D()||!T(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 Jt(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 Yt=()=>typeof document<`u`&&document.hidden;function O(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Xt=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.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=Zt(e),e.includes(`:`)&&(n.title=e),this.place(n,`symbol`),t.appendChild(n);let r=null;this.options.sparkline&&(r=document.createElement(`canvas`),r.className=`tcw-watchlist-spark`,r.width=64,r.height=22,this.place(r,`spark`),t.appendChild(r));let a=(e,n=``)=>{let r=document.createElement(`span`);return r.className=`tcw-watchlist-${e}`,r.textContent=n,this.place(r,e),t.appendChild(r),r},o=a(`price`,`—`),c=this.options.sparkline?null:a(`move`),l=a(`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:o,moveEl:c,changeEl:l,sparkCanvas:r}),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)){if(n.lastPrice!==void 0&&(t.priceEl.textContent=Qt(n.lastPrice,this.locale)),n.lastPrice!==void 0&&n.refPrice!==void 0&&n.refPrice!==0){let e=n.lastPrice-n.refPrice,r=e/n.refPrice*100,i=e>=0?`+`:`-`,a=e>=0?`tcw-up`:`tcw-down`,o=Math.abs(r).toLocaleString(this.locale,{minimumFractionDigits:2,maximumFractionDigits:2});t.moveEl&&(t.moveEl.textContent=`${i}${$t(Math.abs(e),n.lastPrice,this.locale)}`,t.moveEl.className=`tcw-watchlist-move ${a}`),t.changeEl.textContent=`${i}${o}%`,t.changeEl.className=`tcw-watchlist-change ${a}`}else t.moveEl&&(t.moveEl.textContent=``),t.changeEl.textContent=``;t.sparkCanvas&&n.sparkline&&n.sparkline.length>=2&&en(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 Zt(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 Qt(e,t){if(e===0)return`0`;let n=Math.abs(e);return n>=1e3?e.toLocaleString(t,{minimumFractionDigits:2,maximumFractionDigits:2}):n>=1?e.toLocaleString(t,{minimumFractionDigits:4,maximumFractionDigits:4}):Number(e.toPrecision(4)).toLocaleString(t,{maximumFractionDigits:10})}function $t(e,t,n){let r=Math.abs(t);if(r>=1e3)return e.toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:2});if(r>=1)return e.toLocaleString(n,{minimumFractionDigits:4,maximumFractionDigits:4});let i=r>0?Math.min(10,Math.max(0,3-Math.floor(Math.log10(r)))):4;return e.toLocaleString(n,{maximumFractionDigits:i})}function en(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()}var tn=50,nn=500,rn=60,an=e=>typeof e==`string`&&e.trim().slice(0,rn)||null;function on(e){let t=[];for(let n of e){let e=a.n(n);if(e&&!t.includes(e)&&t.push(e),t.length===nn)break}return t}function sn(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===tn)break;if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`&&t.id&&t.id.length<=160?t.id:null,i=an(t.name);!r||!i||n.some(e=>e.id===r)||n.push({id:r,name:i,symbols:Array.isArray(t.symbols)?on(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 cn=e=>({...e,symbols:[...e.symbols]}),ln=class{lists;active;listeners=new Set;storage;storageKey;constructor(e){this.storage=e.storage??null,this.storageKey=e.storageKey??`tcw:watchlists`;let t=this.load(),n=e.lists?sn({lists:e.lists,active:e.activeList}):null,r=t??n??{lists:[{id:`default`,name:an(e.defaultName)??`Watchlist`,symbols:on(e.symbols??[])}],active:`default`};this.lists=r.lists,this.active=r.active}getLists(){return this.lists.map(cn)}getActive(){return cn(this.activeList())}setActive(e){e===this.active||!this.lists.some(t=>t.id===e)||(this.active=e,this.changed())}replace(e,t){let n=sn({lists:e,active:t??this.active});n&&(this.lists=n.lists,this.active=n.active,this.changed())}create(e){let t=an(e);if(!t||this.lists.length>=tn)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(),cn(r)}rename(e,t){let n=an(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>=nn?!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);return e?sn(JSON.parse(e)):null}catch{return null}}save(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify({lists:this.lists,active:this.active}))}catch{}}},un=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=k(`div`,`tcw-syminfo-symbol`,r);n&&(i.title=e.symbol),t.append(i),e.description&&t.append(k(`div`,`tcw-syminfo-desc`,e.description)),e.meta&&t.append(k(`div`,`tcw-syminfo-meta`,e.meta));let o=document.createElement(`div`);if(o.className=`tcw-syminfo-quote`,e.price&&o.append(k(`span`,`tcw-syminfo-price`,e.price)),e.change){let t=k(`span`,`tcw-syminfo-change`,e.change.text);t.classList.add(e.change.up?`tcw-up`:`tcw-down`),o.append(t)}let s=k(`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(k(`dt`,``,t.label),k(`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=k(`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(k(`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(k(`span`,``,t.title));t.meta&&e.append(k(`div`,`tcw-syminfo-news-meta`,t.meta)),n.append(e)}this.newsEl.replaceChildren(t,n)}destroy(){this.el.remove()}};function k(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}var dn=10,fn=5*6e4,pn=864e5,mn=2;function hn(e){let{info:t,quote:n,t:r,textLocale:i}=e,a=(0,u.symbolTimeZone)(t),o=_n(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=vn(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:bn(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`),xn(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}${yn(Math.abs(m),mn,e.numberLocale)}%)`}`,up:f>=0},status:{state:h.state,text:g},stats:_}}var gn=class{request=0;cache=new Map;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.map(e=>({title:e.title,url:e.url,meta:[e.source,vn(e.time-t,r)].filter(Boolean).join(` · `)}))})},s=this.cache.get(e);if(s&&Date.now()-s.at<fn){o(s.items);return}n({kind:`loading`}),Promise.resolve().then(()=>t(e,dn)).then(t=>{if(a!==this.request||i())return;let n=(0,u.readNews)(t,dn);this.cache.set(e,{at:Date.now(),items:n}),o(n)}).catch(()=>{a===this.request&&!i()&&n({kind:`failed`})})}};function _n(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))/pn)},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 vn(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 yn(e,t,n){try{return(0,u.formatPrice)(e,t,n)}catch{return e.toFixed(t)}}function bn(e,t){try{return new Intl.NumberFormat(t,{notation:`compact`,maximumFractionDigits:2}).format(e)}catch{return String(e)}}function xn(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 Sn={KeyT:`trendLine`,KeyH:`horizontalLine`,KeyJ:`horizontalRay`,KeyV:`verticalLine`,KeyC:`crossLine`,KeyF:`fibRetracement`};function Cn(){let e={};for(let[t,n]of Object.entries(Sn))e[n]=`Alt+${t.replace(/^Key/,``)}`;return e}var wn=300,Tn=80,En=u.PHI**-3,Dn=80,On=class{el;holdTimer=null;repeatTimer=null;pressed=!1;keyboardFocus=!1;onMove=e=>{if(e.pointerType!==`touch`&&!(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)}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(Dn,t.height*En);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)}px`}startHold(e){this.stopHold(),this.actions.scroll(e),this.holdTimer=setTimeout(()=>{this.repeatTimer=setInterval(()=>this.actions.scroll(e),Tn)},wn)}stopHold(){this.holdTimer&&clearTimeout(this.holdTimer),this.repeatTimer&&clearInterval(this.repeatTimer),this.holdTimer=null,this.repeatTimer=null}};function kn(e,t,n,r=!1){let i=e.label??t(`alerts.source.price`),a=Pn.get(e.condition),o=a?t(a):e.condition;if(jn.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?In(e.price):n(e.price):`—`;return`${(c||e.drawingId)&&e.label?`${e.label} `:r?`${i} `:``}${o} ${l}`}var An=[{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`}],jn=[`movesUp`,`movesDown`],Mn={hour:36e5,day:864e5,week:7*864e5,month:30*864e5},Nn=``,Pn=new Map(An.map(e=>[e.value,e.key]));function Fn(e){return Math.round(e*1e6)/1e6}function In(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var Ln=class{el;listEl;priceInput;conditionSelect;sourceSelect;targetSelect;percentInput;barsInput;levelRow;moveRow;closeCheck;expirySelect;messageInput;emptyEl;callbacks;open=!1;alerts=[];sources;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()),o.appendChild(c),o.appendChild(l),this.el.appendChild(o);let u=document.createElement(`form`);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 An){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(),e.appendChild(this.el)}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=jn.includes(this.conditionSelect.value);this.moveRow.hidden=!e,this.levelRow.hidden=e,this.priceInput.hidden=this.targetSelect.value!==Nn}renderTargets(){let e=this.targetSelect.value,t=this.sourceSelect.value||`price`;this.targetSelect.replaceChildren();let n=document.createElement(`option`);n.value=Nn,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:Nn,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(Fn(e))}close(){this.open=!1,this.el.hidden=!0}setAlerts(e){this.alerts=e,this.renderList()}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(jn.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!==Nn)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=Mn[this.expirySelect.value];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&&(this.messageInput.value=``,this.prefillPrice())}markInvalid(e){e.setAttribute(`aria-invalid`,`true`),e.focus(),e.addEventListener(`input`,()=>e.removeAttribute(`aria-invalid`),{once:!0})}describe(e){return kn(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)}}},Rn=`print`,zn=3,Bn=10,Vn=[[3400,1/2],[2560,1/3],[1800,1/6]],Hn=Math.sqrt(u.PHI),Un=3,Wn=.5,Gn=3,Kn=.75,qn=2;function Jn(e){let t=Vn.find(([t])=>e>=t);return t?u.PHI**t[1]:1}function Yn(e,t){if(t===1)return e;let n=e.sizes,r=e=>Math.round(e*t);return{...e,sizes:{toolbar:r(n.toolbar),control:r(n.control),controlSmall:r(n.controlSmall),icon:r(n.icon),sidebar:r(n.sidebar),menuItem:r(n.menuItem)},font:{...e.font,size:r(e.font.size)}}}function A(e,t){return Math.max(Bn,(0,u.phiStep)(e,t,zn))}var Xn=`system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`,Zn=`'JetBrains Mono', 'SF Mono', 'Cascadia Code', 'Fira Code', 'Consolas', ui-monospace, monospace`,Qn=u.SANS_FONT_FAMILY.replace(`'Segoe UI'`,`'Segoe UI Variable Text', 'Segoe UI'`),$n=`'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`,er=`Tahoma, Verdana, 'Segoe UI', 'DejaVu Sans', sans-serif`,tr={print:{radius:{xs:1,sm:2,md:3,lg:5,xl:8},components:{tag:2,toolbar:0,sidebar:0},sizes:{toolbar:42,control:33,controlSmall:26,icon:20,sidebar:42,menuItem:33},density:{compact:{toolbar:33,control:26,controlSmall:20,icon:16,sidebar:32,menuItem:26},spacious:{toolbar:53,control:42,controlSmall:33,icon:26,sidebar:59,menuItem:42}},font:{family:Qn,mono:$n,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', ${Xn}`,mono:Zn,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:39,menuItem:26},font:{family:`'IBM Plex Sans Condensed', 'Roboto Condensed', 'Arial Narrow', ${Xn}`,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:47,menuItem:34},font:{family:`'Sora', 'Manrope', ${Xn}`,mono:Zn,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:37,menuItem:24},font:{family:er,mono:er,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}},nr={compact:{toolbar:38,control:26,controlSmall:20,icon:16,sidebar:32,menuItem:26},spacious:{toolbar:52,control:34,controlSmall:28,icon:20,sidebar:49,menuItem:34}};function rr(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 ir=Object.freeze(Object.fromEntries(Object.keys(tr).map(e=>[e,or(ar(e))])));function ar(e){let{density:t,...n}=tr[e];return{...n,preset:e,density:`comfortable`,scale:`auto`,radius:{...n.radius},components:rr(n.radius,n.components),sizes:{...n.sizes},font:{...n.font},borders:{...n.borders},shadows:{...n.shadows}}}function or(e){for(let t of Object.values(e))t&&typeof t==`object`&&or(t);return Object.freeze(e)}var sr=e=>typeof e==`string`&&Object.prototype.hasOwnProperty.call(tr,e),j=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,cr=e=>typeof e==`string`&&e.trim().length>0&&e.length<=300&&!/[;{}<>\\]|url\s*\(|expression\s*\(|\/\*/i.test(e)&&lr(e);function lr(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 M=(e,t)=>typeof e==`string`&&t.includes(e);function N(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 P(e){let t=typeof e==`string`?{preset:e}:e??{},n=sr(t.preset)?t.preset:Rn,r=tr[n],i=N(r.radius,t.radius,(e,t)=>j(t,0,999)),a=M(t.density,[`compact`,`comfortable`,`spacious`,`airy`])?t.density:`comfortable`,o=a===`airy`?`spacious`:a,s=N(o===`compact`||o===`spacious`?(r.density??nr)[o]:r.sizes,t.sizes,(e,t)=>e===`icon`?j(t,10,32):j(t,16,80)),c=N(r.font,t.font,(e,t)=>e===`family`||e===`mono`?cr(t):e===`size`?j(t,11,20):e===`weight`||e===`strongWeight`?j(t,100,900):e===`labelCase`?t===`none`||t===`uppercase`:j(t,0,.5)),l=c.family===Qn?u.SANS_FONT_FAMILY:c.family,d=a===`airy`&&t.font?.mono===void 0?{...c,mono:l}:c;return{preset:n,density:a,radius:i,components:N(rr(i,r.components),t.components,(e,t)=>j(t,0,999)),sizes:s,font:d,borders:N(r.borders,t.borders,(e,t)=>e===`width`?j(t,0,4):typeof t==`boolean`),shadows:N(r.shadows,t.shadows,(e,t)=>cr(t)),blur:j(t.blur,0,40)?t.blur:r.blur,active:M(t.active,[`tint`,`solid`,`underline`])?t.active:r.active,toolbar:M(t.toolbar,[`docked`,`floating`])?t.toolbar:r.toolbar,sidebar:M(t.sidebar,[`docked`,`floating`])?t.sidebar:r.sidebar,intervals:M(t.intervals,[`plain`,`segmented`])?t.intervals:r.intervals,tagRadius:j(t.tagRadius,0,999)?t.tagRadius:r.tagRadius,iconStroke:t.iconStroke===0||j(t.iconStroke,Wn,Gn)?t.iconStroke:r.iconStroke,scale:typeof t.scale==`number`&&Number.isFinite(t.scale)&&t.scale>=Kn&&t.scale<=qn?t.scale:`auto`}}function ur(e){let t=e=>`${e}px`,n=e.radius,r=e.components,i=e.sizes,a=e.font,o=e.density===`compact`,s=o?1:Hn,c=o?i.control:Math.min(Math.round(i.control*Hn),i.sidebar-2*Un);return{"--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(c),"--tcw-tool-icon":t(2*Math.round(i.icon*s/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(A(a.size,-1)),"--tcw-font-size-xs":t(A(a.size,-2)),"--tcw-font-size-lg":t(A(a.size,1)),"--tcw-font-size-xl":t(A(a.size,2)),"--tcw-font-size-display":t(A(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(A(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 dr(e,t,n={}){let r=n.variables!==!1;for(let[n,i]of Object.entries(ur(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 fr=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=pr,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}},pr=80,mr={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 hr(e,t){let n=`tool.${e}`,r=t?.(n);return r&&r!==n?r:mr[e]??e}function gr(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var _r=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function vr(e){return _r(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 yr(e){if(!_r(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 br=class{constructor(e=`tcw:indicator-defaults`,t=gr()){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(!_r(t))return e;for(let[n,r]of Object.entries(t))_r(r)&&e.set(n,{params:vr(r.params),style:yr(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:vr(t.params),style:yr(t.style)}]]);try{return this.storage.setItem(this.key,JSON.stringify(n)),!0}catch{return!1}}},xr=1,Sr=[`logScale`,`autoScale`],Cr=new Set([`timezone`,`numberLocale`]),wr=new Set([...Sr,`chartTypeOptions`]),Tr=new Set([...Sr,...Cr,`scaleMode`,`invertScale`,`chartTypeOptions`]),Er=new Set([...Sr,...Cr,`scaleMode`]),Dr=new Set,Or=[`renko`,`lineBreak`,`kagi`,`pointAndFigure`,`rangeBars`];function kr(e){return Or.includes(e)}function Ar(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>Pr(e)&&Object.keys(e).length>0))}function jr(){return Object.fromEntries(Or.map(e=>[e,{}]))}var Mr={crosshairMode:[`normal`,`magnet`,`hidden`],scaleMode:[`regular`,`logarithmic`,`percentage`,`indexedTo100`],periodLevelsPeriod:[`day`,`week`]},Nr={marketProfileBuckets:{min:8,max:200,whole:!0},marketProfileOpacity:{min:.05,max:1},depthHeatmapOpacity:{min:.1,max:1},pivotStrength:{min:2,max:20,whole:!0}},Pr=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Fr(e){return e===`local`||t.v(e)!==null}function Ir(e){try{return Intl.NumberFormat.supportedLocalesOf(e).length>0}catch{return!1}}function Lr(e,n){let r=t.h[e];if(e===`chartTypeOptions`)return Pr(n)?(0,u.readChartTypeOptions)(n):void 0;if(typeof n!=typeof r)return;if(typeof n==`number`){if(!Number.isFinite(n))return;let t=Nr[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=Mr[e];return i?i.includes(n)?n:void 0:e===`timezone`?Fr(n)?n:void 0:e===`numberLocale`?Ir(n)?n:void 0:n}function F(e,n=Dr){if(!Pr(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=Lr(i,e[i]);t!==void 0&&(r[i]=t)}return r}function Rr(e,t){return Object.fromEntries(Object.keys(e).filter(e=>!t.has(e)).map(t=>[t,e[t]]))}function zr(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 Br(e,t){return zr({...e,chartTypeOptions:Ar(e.chartTypeOptions)},t,Er)}function Vr(e){return e?(e===!0?void 0:e.key)||`tcw:chart-settings`:null}function Hr(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Ur=class{constructor(e,t=Hr()){this.key=e,this.storage=t}load(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`null`)}catch{return{}}return!Pr(e)||e.v!==xr?{}:F(e.settings,wr)}save(e,t){try{this.storage?.setItem(this.key,JSON.stringify({v:xr,settings:zr(e,t,wr)}))}catch{}}};function Wr(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Gr=80;function Kr(e){let{text:t,...n}=(0,u.sanitizeDrawingStyle)(e);return n}function qr(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 Jr=class{templates=[];constructor(e=`tcw:draw-templates`,t=Wr()){this.storageKey=e,this.storage=t,this.load()}list(e){return this.templates.filter(t=>!t.type||t.type===e).map(qr)}get(e,t){let n=this.templates.find(n=>n.name===e&&n.type===t);return n?qr(n):null}save(e,t,n){let r=e.trim().slice(0,Gr);if(!r)return;let i={name:r,style:Kr(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,Gr),style:Kr(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{}}},Yr=class{defaults={};constructor(e=`tcw:drawing-defaults`,t=Wr()){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{}}},Xr=[`#4c8dff`,`#1fa874`,`#e8505b`,`#f2a93b`,`#a57cff`,`#1398a8`,`#ffffff`,`#7d8696`],Zr=[1,2,3,4],Qr=[`solid`,`dashed`,`dotted`],$r=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 Xr){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 Zr){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 Qr){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)}}},ei={color:`color`,fill:`fillColor`,textColor:`textColor`},ti=10,I=4,ni=4,ri=20,ii=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d\s.,%/+-]+\)|[a-z]+)$/i;function L(e){return typeof e==`string`&&ii.test(e.trim())?e.trim():`#7d8696`}function ai(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.min(t,ri):1}function R(e){return Qr.includes(e)?e:`solid`}var oi=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=[L(t.color),ai(t.lineWidth),R(t.lineStyle),e.locked,e.canDelete,e.canSettings,e.canAlert,e.canFill===!0,e.canText===!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=L(e.style.color),r=ai(e.style.lineWidth),o=R(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`),si(o)),e.canFill?d(`fill`,t(`drawingSettings.fill`),`<span class="tcw-sel-color tcw-sel-fill" style="background:${a.u(L((0,u.ownFillColor)(e.style)??n))}"></span>`):``,e.canText?d(`textColor`,t(`drawingSettings.textColor`),`<span class="tcw-sel-text" style="--c:${a.u(L(e.style.textColor??n))}">T</span>`):``,`<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{rect:t,bounds:n}=e,{w:r,h:i}=this.size??{w:0,h:0};if(this.pinned){let e=Math.max(n.x+I,Math.min(this.pinned.left,n.x+n.width-r-I)),t=Math.max(n.y+I,Math.min(this.pinned.top,n.y+n.height-i-I));this.el.style.left=`${Math.round(e)}px`,this.el.style.top=`${Math.round(t)}px`;return}let a=t.x+t.width/2-r/2;a=Math.max(n.x+I,Math.min(a,n.x+n.width-r-I));let o=t.y-i-ti;o<n.y+I&&(o=Math.min(t.y+t.height+ti,n.y+n.height-i-I)),o=Math.max(o,n.y+I),this.el.style.left=`${Math.round(a)}px`,this.el.style.top=`${Math.round(o)}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===`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+I)}}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=L(e===`fill`?(0,u.ownFillColor)(n)??n.color:e===`textColor`?n.textColor??n.color:n.color).toLowerCase(),i=ai(n.lineWidth),o=R(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=Xr.map(e=>s(`tcw-sel-swatch`,e.toLowerCase()===r,`data-color="${e}" style="background:${e}" aria-label="${e}"`)).join(``):e===`width`?this.pop.innerHTML=Zr.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=Qr.map(e=>s(`tcw-sel-option`,e===o,`data-style="${e}"`,si(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`?ni: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 ei?ei[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:R(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 si(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 z={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}},ci=new Set([`trendLine`,`ray`,`extendedLine`,`infoLine`,`trendAngle`,`arrow`,`horizontalLine`,`horizontalRay`,`verticalLine`,`rectangle`]),li={priceLabel:`#ffffff`},ui=8,di=6,fi=1.3,pi=120,mi=229,hi=500,B=8,gi=400,_i=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<hi){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);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(fi),color:e.color,padding:`${di}px ${ui}px`}),r.addEventListener(`input`,()=>{this.fit(),this.target?.onInput(r.value);let e=this.target?.rect();e&&this.place(e)}),r.addEventListener(`keydown`,e=>{e.stopPropagation(),!(e.isComposing||e.keyCode===mi)&&(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(pi,window.innerWidth-B*2);t.style.maxWidth=`${n}px`,t.style.width=`${Math.min(n,Math.max(pi,e.width))}px`,t.style.minHeight=`${e.height}px`;let r=t.offsetWidth||Math.max(pi,e.width),i=t.offsetHeight||e.height;t.style.left=`${Math.max(B,Math.min(e.x,window.innerWidth-B-r))}px`,t.style.top=`${Math.max(B,Math.min(e.y,window.innerHeight-B-i))}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>gi){this.finish(!0,!1);return}this.place(e),this.follow()})}},vi=[{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`}],yi=[{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 vi.find(t=>t.id===e)?.mode}function xi(...e){return e.filter(e=>e.length>0).flatMap((e,t)=>t===0?[...e]:[`separator`,...e])}function V(e,t){let n=t.keys[e.id];return n?{...e,shortcut:n}:e}function Si(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 Ci=e=>({id:`settings`,label:e(`chartMenu.settings`),icon:`settings`});function wi(e,t){let n=[V({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 xi(Si(e,t),n,r,[...i,Ci(t)])}function Ti(e,t){let n=[{id:`resetPriceScale`,label:t(`chartMenu.resetPriceScale`)},{id:`autoScale`,label:t(`settings.autoScale`),checked:e.autoScale},V({id:`invertScale`,label:t(`chartMenu.invertScale`),checked:e.inverted},e),{id:`leftScale`,label:t(`settings.leftScale`),checked:e.leftScale}],r=vi.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 xi(n,r,[{id:`labels`,label:t(`chartMenu.labels`),submenu:i},{id:`lines`,label:t(`chartMenu.lines`),submenu:a}],Si({...e,canTrade:!1,canDraw:!1},t),[Ci(t)])}function Ei(e,t){let n=[V({id:`resetView`,label:t(`chartMenu.resetTimeScale`)},e)];e.canGoToDate&&n.push(V({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 xi(n,r.length>0?[{id:`timezone`,label:t(`settings.timezone`),submenu:r}]:[])}function Di(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 xi([V({id:`resetView`,label:t(`chartMenu.resetView`)},e)],n,[Ci(t)])}function Oi(e,t,n){switch(e){case`priceAxis`:return Ti(t,n);case`timeAxis`:return Ei(t,n);case`pane`:return Di(t,n);default:return wi(t,n)}}var ki=/^[-+−]/;function H(e,t,n){let r=e.replace(ki,``);return r===n.replace(ki,``)?r:t>0?`+${r}`:t<0?`-${r}`:r}function Ai(e){return e.startsWith(`+`)?`up`:e.startsWith(`-`)?`down`:null}var U=[`positions`,`orders`,`history`],ji=[`order`,`close`,`reverse`,`stopLoss`,`takeProfit`],Mi=[`market`,`limit`,`stop`],Ni=[`gtc`,`day`],W=`—`,Pi=`{pnl}`,Fi=3;function Ii(e,t,n){return e.includes(t??``)?t:n}function Li(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Ri(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 zi(e){let t=document.createElement(`span`);return t.dir=`ltr`,t.textContent=e,t}function Bi(e){let t=Ai(e);return t?`tcw-account-${t}`:``}var Vi=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 U){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,Li(t.positions,e.positions)&&Li(t.orders,e.orders)&&Li(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=U.indexOf(this.tab),n=e.key===`ArrowRight`?t+1:e.key===`ArrowLeft`?t-1:-2;if(n===-2)return;e.preventDefault();let r=U[(n+U.length)%U.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=Ri(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 ${Bi(r)}`.trim();let i=this.t(e),a=i.indexOf(Pi),o=zi(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?W:this.callbacks.formatPrice(e),this.writePnl(t.pnl,Ri(t.position,e))}amount(e){return H(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`${H(t(Math.abs(e)),e,t(0))}%`}writePnl(e,t){if(t===null){e.className=``,e.textContent=W;return}let n=this.amount(t.pnl);e.className=Bi(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?W: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=zi(``);this.writePnl(a,Ri(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?W: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[Fi],pnl:n[t]}))}renderOrders(){let{formatPrice:e}=this.callbacks,t=this.snapshot.orders.map(t=>{let n=Ii(Mi,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.${Ii(Ni,t.timeInForce,`gtc`)}`):W,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=zi(``);return n.pnl===void 0?r.textContent=W:(r.textContent=this.amount(n.pnl),r.className=Bi(r.textContent)),[t(n.time),this.sideCell(n.side,`trade`),String(n.quantity),e(n.price),this.t(`account.reason.${Ii(ji,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`)}},Hi=1e-9;function Ui(e,t){return e.type===`market`?t:e.price}function Wi(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=Ui(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,...Gi(e,n)]}function Gi(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)>Hi)&&n.push(`priceStep`),o&&r!==null&&r>0&&(r>o.ceiling+Hi||r<o.floor-Hi)&&n.push(`priceLimits`),s!==void 0&&s>1&&e.quantity>s&&e.quantity%s!==0&&n.push(`lot`),n}function Ki(e,t){let n={side:e.side,type:e.type,price:e.type===`market`?t??e.price:e.price,quantity:e.quantity};return 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),n}function qi(e,t){let n=Ui(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 Ji(e,t,n,r=1){let i=Ui(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 Yi(e,t,n={}){let r=n.multiplier!==void 0&&n.multiplier>0?n.multiplier:1,i=Ui(e,t),a=i!==null&&i>0&&e.quantity>0?i*e.quantity*r:null,o=Wi(e,t),s=(n,i)=>n===null||o.includes(i)?null:Ji(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?qi(e,t):null}}var Xi=229,Zi=1,Qi=2,$i=.999999999,ea=0,ta=class{backdrop;modal;symbolEl;body;summaryEl;problemsEl;submit;draft=null;lastPrice=null;rules={};step=ra;round=e=>ia(e,e);typed=new Map;returnFocus=null;uid=++ea;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!==Xi){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??ra,this.round=e.round??(e=>ia(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*$i)}writePrice(e){return Number.isFinite(e)?this.step===ra?String(e):e.toFixed((0,u.stepDecimals)(this.step(e))):``}place(){let e=this.draft;!e||Wi(e,this.lastPrice,this.rules).length>0||(this.callbacks.onSubmit(Ki(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),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=na(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=na(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},!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}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`?-Zi:Qi;return this.round(n*(1+(t.side===`buy`?r:-r)/100))}check(){let e=this.draft;if(!e)return;let t=Wi(e,this.lastPrice,this.rules),n=t.map(e=>this.problemText(e));n.join(`
|
|
7808
|
+
`}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)},Lt)}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 zt){let n=e.querySelector(`[data-act="${t}"]`);n&&(n.disabled=this.pending)}}},Vt=864e5,Ht=6e4,Ut=1e3,Wt=150,Gt=5e3,Kt=8,qt=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 Bt({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*Kt),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>=Vt)return s;let c={hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`};return(!Number.isFinite(i)||i<Ht)&&(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(!Jt(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(),Wt)}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?Ut:Ut/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.d(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.f(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(Gt,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||E()||D()||!T(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 Jt(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 Yt=()=>typeof document<`u`&&document.hidden;function O(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Xt=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.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=Zt(e),e.includes(`:`)&&(n.title=e),this.place(n,`symbol`),t.appendChild(n);let r=null;this.options.sparkline&&(r=document.createElement(`canvas`),r.className=`tcw-watchlist-spark`,r.width=64,r.height=22,this.place(r,`spark`),t.appendChild(r));let a=(e,n=``)=>{let r=document.createElement(`span`);return r.className=`tcw-watchlist-${e}`,r.textContent=n,this.place(r,e),t.appendChild(r),r},o=a(`price`,`—`),c=this.options.sparkline?null:a(`move`),l=a(`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:o,moveEl:c,changeEl:l,sparkCanvas:r}),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)){if(n.lastPrice!==void 0&&(t.priceEl.textContent=Qt(n.lastPrice,this.locale)),n.lastPrice!==void 0&&n.refPrice!==void 0&&n.refPrice!==0){let e=n.lastPrice-n.refPrice,r=e/n.refPrice*100,i=e>=0?`+`:`-`,a=e>=0?`tcw-up`:`tcw-down`,o=Math.abs(r).toLocaleString(this.locale,{minimumFractionDigits:2,maximumFractionDigits:2});t.moveEl&&(t.moveEl.textContent=`${i}${$t(Math.abs(e),n.lastPrice,this.locale)}`,t.moveEl.className=`tcw-watchlist-move ${a}`),t.changeEl.textContent=`${i}${o}%`,t.changeEl.className=`tcw-watchlist-change ${a}`}else t.moveEl&&(t.moveEl.textContent=``),t.changeEl.textContent=``;t.sparkCanvas&&n.sparkline&&n.sparkline.length>=2&&en(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 Zt(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 Qt(e,t){if(e===0)return`0`;let n=Math.abs(e);return n>=1e3?e.toLocaleString(t,{minimumFractionDigits:2,maximumFractionDigits:2}):n>=1?e.toLocaleString(t,{minimumFractionDigits:4,maximumFractionDigits:4}):Number(e.toPrecision(4)).toLocaleString(t,{maximumFractionDigits:10})}function $t(e,t,n){let r=Math.abs(t);if(r>=1e3)return e.toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:2});if(r>=1)return e.toLocaleString(n,{minimumFractionDigits:4,maximumFractionDigits:4});let i=r>0?Math.min(10,Math.max(0,3-Math.floor(Math.log10(r)))):4;return e.toLocaleString(n,{maximumFractionDigits:i})}function en(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()}var tn=50,nn=500,rn=60,an=e=>typeof e==`string`&&e.trim().slice(0,rn)||null;function on(e){let t=[];for(let n of e){let e=a.n(n);if(e&&!t.includes(e)&&t.push(e),t.length===nn)break}return t}function sn(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===tn)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=an(t.name);!r||!i||n.some(e=>e.id===r)||n.push({id:r,name:i,symbols:Array.isArray(t.symbols)?on(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 cn=e=>({...e,symbols:[...e.symbols]}),ln=class{lists;active;listeners=new Set;storage;storageKey;constructor(e){this.storage=e.storage??null,this.storageKey=e.storageKey??`tcw:watchlists`;let t=this.load(),n=e.lists?sn({lists:e.lists,active:e.activeList}):null,r=t??n??{lists:[{id:`default`,name:an(e.defaultName)??`Watchlist`,symbols:on(e.symbols??[])}],active:`default`};this.lists=r.lists,this.active=r.active}getLists(){return this.lists.map(cn)}getActive(){return cn(this.activeList())}setActive(e){e===this.active||!this.lists.some(t=>t.id===e)||(this.active=e,this.changed())}replace(e,t){let n=sn({lists:e,active:t??this.active});n&&(this.lists=n.lists,this.active=n.active,this.changed())}create(e){let t=an(e);if(!t||this.lists.length>=tn)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(),cn(r)}rename(e,t){let n=an(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>=nn?!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);return e?sn(JSON.parse(e)):null}catch{return null}}save(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify({lists:this.lists,active:this.active}))}catch{}}},un=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=k(`div`,`tcw-syminfo-symbol`,r);n&&(i.title=e.symbol),t.append(i),e.description&&t.append(k(`div`,`tcw-syminfo-desc`,e.description)),e.meta&&t.append(k(`div`,`tcw-syminfo-meta`,e.meta));let o=document.createElement(`div`);if(o.className=`tcw-syminfo-quote`,e.price&&o.append(k(`span`,`tcw-syminfo-price`,e.price)),e.change){let t=k(`span`,`tcw-syminfo-change`,e.change.text);t.classList.add(e.change.up?`tcw-up`:`tcw-down`),o.append(t)}let s=k(`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(k(`dt`,``,t.label),k(`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=k(`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(k(`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(k(`span`,``,t.title));t.meta&&e.append(k(`div`,`tcw-syminfo-news-meta`,t.meta)),n.append(e)}this.newsEl.replaceChildren(t,n)}destroy(){this.el.remove()}};function k(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}var dn=10,fn=5*6e4,pn=864e5,mn=2;function hn(e){let{info:t,quote:n,t:r,textLocale:i}=e,a=(0,u.symbolTimeZone)(t),o=_n(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=vn(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:bn(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`),xn(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}${yn(Math.abs(m),mn,e.numberLocale)}%)`}`,up:f>=0},status:{state:h.state,text:g},stats:_}}var gn=class{request=0;cache=new Map;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.map(e=>({title:e.title,url:e.url,meta:[e.source,vn(e.time-t,r)].filter(Boolean).join(` · `)}))})},s=this.cache.get(e);if(s&&Date.now()-s.at<fn){o(s.items);return}n({kind:`loading`}),Promise.resolve().then(()=>t(e,dn)).then(t=>{if(a!==this.request||i())return;let n=(0,u.readNews)(t,dn);this.cache.set(e,{at:Date.now(),items:n}),o(n)}).catch(()=>{a===this.request&&!i()&&n({kind:`failed`})})}};function _n(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))/pn)},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 vn(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 yn(e,t,n){try{return(0,u.formatPrice)(e,t,n)}catch{return e.toFixed(t)}}function bn(e,t){try{return new Intl.NumberFormat(t,{notation:`compact`,maximumFractionDigits:2}).format(e)}catch{return String(e)}}function xn(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 Sn={KeyT:`trendLine`,KeyH:`horizontalLine`,KeyJ:`horizontalRay`,KeyV:`verticalLine`,KeyC:`crossLine`,KeyF:`fibRetracement`};function Cn(){let e={};for(let[t,n]of Object.entries(Sn))e[n]=`Alt+${t.replace(/^Key/,``)}`;return e}var wn=300,Tn=80,En=u.PHI**-3,Dn=80,On=class{el;holdTimer=null;repeatTimer=null;pressed=!1;keyboardFocus=!1;onMove=e=>{if(e.pointerType!==`touch`&&!(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)}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(Dn,t.height*En);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)}px`}startHold(e){this.stopHold(),this.actions.scroll(e),this.holdTimer=setTimeout(()=>{this.repeatTimer=setInterval(()=>this.actions.scroll(e),Tn)},wn)}stopHold(){this.holdTimer&&clearTimeout(this.holdTimer),this.repeatTimer&&clearInterval(this.repeatTimer),this.holdTimer=null,this.repeatTimer=null}};function kn(e,t,n,r=!1){let i=e.label??t(`alerts.source.price`),a=Pn.get(e.condition),o=a?t(a):e.condition;if(jn.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?In(e.price):n(e.price):`—`;return`${(c||e.drawingId)&&e.label?`${e.label} `:r?`${i} `:``}${o} ${l}`}var An=[{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`}],jn=[`movesUp`,`movesDown`],Mn={hour:36e5,day:864e5,week:7*864e5,month:30*864e5},Nn=``,Pn=new Map(An.map(e=>[e.value,e.key]));function Fn(e){return Math.round(e*1e6)/1e6}function In(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var Ln=class{el;listEl;priceInput;conditionSelect;sourceSelect;targetSelect;percentInput;barsInput;levelRow;moveRow;closeCheck;expirySelect;messageInput;emptyEl;callbacks;open=!1;alerts=[];sources;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()),o.appendChild(c),o.appendChild(l),this.el.appendChild(o);let u=document.createElement(`form`);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 An){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(),e.appendChild(this.el)}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=jn.includes(this.conditionSelect.value);this.moveRow.hidden=!e,this.levelRow.hidden=e,this.priceInput.hidden=this.targetSelect.value!==Nn}renderTargets(){let e=this.targetSelect.value,t=this.sourceSelect.value||`price`;this.targetSelect.replaceChildren();let n=document.createElement(`option`);n.value=Nn,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:Nn,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(Fn(e))}close(){this.open=!1,this.el.hidden=!0}setAlerts(e){this.alerts=e,this.renderList()}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(jn.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!==Nn)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=Mn[this.expirySelect.value];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&&(this.messageInput.value=``,this.prefillPrice())}markInvalid(e){e.setAttribute(`aria-invalid`,`true`),e.focus(),e.addEventListener(`input`,()=>e.removeAttribute(`aria-invalid`),{once:!0})}describe(e){return kn(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)}}},Rn=`print`,zn=3,Bn=10,Vn=[[3400,1/2],[2560,1/3],[1800,1/6]],Hn=Math.sqrt(u.PHI),Un=3,Wn=.5,Gn=3,Kn=.75,qn=2;function Jn(e){let t=Vn.find(([t])=>e>=t);return t?u.PHI**t[1]:1}function Yn(e,t){if(t===1)return e;let n=e.sizes,r=e=>Math.round(e*t);return{...e,sizes:{toolbar:r(n.toolbar),control:r(n.control),controlSmall:r(n.controlSmall),icon:r(n.icon),sidebar:r(n.sidebar),menuItem:r(n.menuItem)},font:{...e.font,size:r(e.font.size)}}}function A(e,t){return Math.max(Bn,(0,u.phiStep)(e,t,zn))}var Xn=`system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`,Zn=`'JetBrains Mono', 'SF Mono', 'Cascadia Code', 'Fira Code', 'Consolas', ui-monospace, monospace`,Qn=u.SANS_FONT_FAMILY.replace(`'Segoe UI'`,`'Segoe UI Variable Text', 'Segoe UI'`),$n=`'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`,er=`Tahoma, Verdana, 'Segoe UI', 'DejaVu Sans', sans-serif`,tr={print:{radius:{xs:1,sm:2,md:3,lg:5,xl:8},components:{tag:2,toolbar:0,sidebar:0},sizes:{toolbar:42,control:33,controlSmall:26,icon:20,sidebar:42,menuItem:33},density:{compact:{toolbar:33,control:26,controlSmall:20,icon:16,sidebar:32,menuItem:26},spacious:{toolbar:53,control:42,controlSmall:33,icon:26,sidebar:59,menuItem:42}},font:{family:Qn,mono:$n,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', ${Xn}`,mono:Zn,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:39,menuItem:26},font:{family:`'IBM Plex Sans Condensed', 'Roboto Condensed', 'Arial Narrow', ${Xn}`,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:47,menuItem:34},font:{family:`'Sora', 'Manrope', ${Xn}`,mono:Zn,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:37,menuItem:24},font:{family:er,mono:er,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}},nr={compact:{toolbar:38,control:26,controlSmall:20,icon:16,sidebar:32,menuItem:26},spacious:{toolbar:52,control:34,controlSmall:28,icon:20,sidebar:49,menuItem:34}};function rr(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 ir=Object.freeze(Object.fromEntries(Object.keys(tr).map(e=>[e,or(ar(e))])));function ar(e){let{density:t,...n}=tr[e];return{...n,preset:e,density:`comfortable`,scale:`auto`,radius:{...n.radius},components:rr(n.radius,n.components),sizes:{...n.sizes},font:{...n.font},borders:{...n.borders},shadows:{...n.shadows}}}function or(e){for(let t of Object.values(e))t&&typeof t==`object`&&or(t);return Object.freeze(e)}var sr=e=>typeof e==`string`&&Object.prototype.hasOwnProperty.call(tr,e),j=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,cr=e=>typeof e==`string`&&e.trim().length>0&&e.length<=300&&!/[;{}<>\\]|url\s*\(|expression\s*\(|\/\*/i.test(e)&&lr(e);function lr(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 M=(e,t)=>typeof e==`string`&&t.includes(e);function N(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 P(e){let t=typeof e==`string`?{preset:e}:e??{},n=sr(t.preset)?t.preset:Rn,r=tr[n],i=N(r.radius,t.radius,(e,t)=>j(t,0,999)),a=M(t.density,[`compact`,`comfortable`,`spacious`,`airy`])?t.density:`comfortable`,o=a===`airy`?`spacious`:a,s=N(o===`compact`||o===`spacious`?(r.density??nr)[o]:r.sizes,t.sizes,(e,t)=>e===`icon`?j(t,10,32):j(t,16,80)),c=N(r.font,t.font,(e,t)=>e===`family`||e===`mono`?cr(t):e===`size`?j(t,11,20):e===`weight`||e===`strongWeight`?j(t,100,900):e===`labelCase`?t===`none`||t===`uppercase`:j(t,0,.5)),l=c.family===Qn?u.SANS_FONT_FAMILY:c.family,d=a===`airy`&&t.font?.mono===void 0?{...c,mono:l}:c;return{preset:n,density:a,radius:i,components:N(rr(i,r.components),t.components,(e,t)=>j(t,0,999)),sizes:s,font:d,borders:N(r.borders,t.borders,(e,t)=>e===`width`?j(t,0,4):typeof t==`boolean`),shadows:N(r.shadows,t.shadows,(e,t)=>cr(t)),blur:j(t.blur,0,40)?t.blur:r.blur,active:M(t.active,[`tint`,`solid`,`underline`])?t.active:r.active,toolbar:M(t.toolbar,[`docked`,`floating`])?t.toolbar:r.toolbar,sidebar:M(t.sidebar,[`docked`,`floating`])?t.sidebar:r.sidebar,intervals:M(t.intervals,[`plain`,`segmented`])?t.intervals:r.intervals,tagRadius:j(t.tagRadius,0,999)?t.tagRadius:r.tagRadius,iconStroke:t.iconStroke===0||j(t.iconStroke,Wn,Gn)?t.iconStroke:r.iconStroke,scale:typeof t.scale==`number`&&Number.isFinite(t.scale)&&t.scale>=Kn&&t.scale<=qn?t.scale:`auto`}}function ur(e){let t=e=>`${e}px`,n=e.radius,r=e.components,i=e.sizes,a=e.font,o=e.density===`compact`,s=o?1:Hn,c=o?i.control:Math.min(Math.round(i.control*Hn),i.sidebar-2*Un);return{"--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(c),"--tcw-tool-icon":t(2*Math.round(i.icon*s/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(A(a.size,-1)),"--tcw-font-size-xs":t(A(a.size,-2)),"--tcw-font-size-lg":t(A(a.size,1)),"--tcw-font-size-xl":t(A(a.size,2)),"--tcw-font-size-display":t(A(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(A(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 dr(e,t,n={}){let r=n.variables!==!1;for(let[n,i]of Object.entries(ur(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 fr=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=pr,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}},pr=80,mr={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 hr(e,t){let n=`tool.${e}`,r=t?.(n);return r&&r!==n?r:mr[e]??e}function gr(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var _r=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function vr(e){return _r(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 yr(e){if(!_r(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 br=class{constructor(e=`tcw:indicator-defaults`,t=gr()){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(!_r(t))return e;for(let[n,r]of Object.entries(t))_r(r)&&e.set(n,{params:vr(r.params),style:yr(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:vr(t.params),style:yr(t.style)}]]);try{return this.storage.setItem(this.key,JSON.stringify(n)),!0}catch{return!1}}},xr=1,Sr=[`logScale`,`autoScale`],Cr=new Set([`timezone`,`numberLocale`]),wr=new Set([...Sr,`chartTypeOptions`]),Tr=new Set([...Sr,...Cr,`scaleMode`,`invertScale`,`chartTypeOptions`]),Er=new Set([...Sr,...Cr,`scaleMode`]),Dr=new Set,Or=[`renko`,`lineBreak`,`kagi`,`pointAndFigure`,`rangeBars`];function kr(e){return Or.includes(e)}function Ar(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>Pr(e)&&Object.keys(e).length>0))}function jr(){return Object.fromEntries(Or.map(e=>[e,{}]))}var Mr={crosshairMode:[`normal`,`magnet`,`hidden`],scaleMode:[`regular`,`logarithmic`,`percentage`,`indexedTo100`],periodLevelsPeriod:[`day`,`week`]},Nr={marketProfileBuckets:{min:8,max:200,whole:!0},marketProfileOpacity:{min:.05,max:1},depthHeatmapOpacity:{min:.1,max:1},pivotStrength:{min:2,max:20,whole:!0}},Pr=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Fr(e){return e===`local`||t.v(e)!==null}function Ir(e){try{return Intl.NumberFormat.supportedLocalesOf(e).length>0}catch{return!1}}function Lr(e,n){let r=t.h[e];if(e===`chartTypeOptions`)return Pr(n)?(0,u.readChartTypeOptions)(n):void 0;if(typeof n!=typeof r)return;if(typeof n==`number`){if(!Number.isFinite(n))return;let t=Nr[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=Mr[e];return i?i.includes(n)?n:void 0:e===`timezone`?Fr(n)?n:void 0:e===`numberLocale`?Ir(n)?n:void 0:n}function F(e,n=Dr){if(!Pr(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=Lr(i,e[i]);t!==void 0&&(r[i]=t)}return r}function Rr(e,t){return Object.fromEntries(Object.keys(e).filter(e=>!t.has(e)).map(t=>[t,e[t]]))}function zr(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 Br(e,t){return zr({...e,chartTypeOptions:Ar(e.chartTypeOptions)},t,Er)}function Vr(e){return e?(e===!0?void 0:e.key)||`tcw:chart-settings`:null}function Hr(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Ur=class{constructor(e,t=Hr()){this.key=e,this.storage=t}load(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`null`)}catch{return{}}return!Pr(e)||e.v!==xr?{}:F(e.settings,wr)}save(e,t){try{this.storage?.setItem(this.key,JSON.stringify({v:xr,settings:zr(e,t,wr)}))}catch{}}};function Wr(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Gr=80;function Kr(e){let{text:t,...n}=(0,u.sanitizeDrawingStyle)(e);return n}function qr(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 Jr=class{templates=[];constructor(e=`tcw:draw-templates`,t=Wr()){this.storageKey=e,this.storage=t,this.load()}list(e){return this.templates.filter(t=>!t.type||t.type===e).map(qr)}get(e,t){let n=this.templates.find(n=>n.name===e&&n.type===t);return n?qr(n):null}save(e,t,n){let r=e.trim().slice(0,Gr);if(!r)return;let i={name:r,style:Kr(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,Gr),style:Kr(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{}}},Yr=class{defaults={};constructor(e=`tcw:drawing-defaults`,t=Wr()){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{}}},Xr=[`#4c8dff`,`#1fa874`,`#e8505b`,`#f2a93b`,`#a57cff`,`#1398a8`,`#ffffff`,`#7d8696`],Zr=[1,2,3,4],Qr=[`solid`,`dashed`,`dotted`],$r=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 Xr){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 Zr){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 Qr){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)}}},ei={color:`color`,fill:`fillColor`,textColor:`textColor`},ti=10,I=4,ni=4,ri=20,ii=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d\s.,%/+-]+\)|[a-z]+)$/i;function L(e){return typeof e==`string`&&ii.test(e.trim())?e.trim():`#7d8696`}function ai(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.min(t,ri):1}function R(e){return Qr.includes(e)?e:`solid`}var oi=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=[L(t.color),ai(t.lineWidth),R(t.lineStyle),e.locked,e.canDelete,e.canSettings,e.canAlert,e.canFill===!0,e.canText===!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=L(e.style.color),r=ai(e.style.lineWidth),o=R(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`),si(o)),e.canFill?d(`fill`,t(`drawingSettings.fill`),`<span class="tcw-sel-color tcw-sel-fill" style="background:${a.u(L((0,u.ownFillColor)(e.style)??n))}"></span>`):``,e.canText?d(`textColor`,t(`drawingSettings.textColor`),`<span class="tcw-sel-text" style="--c:${a.u(L(e.style.textColor??n))}">T</span>`):``,`<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{rect:t,bounds:n}=e,{w:r,h:i}=this.size??{w:0,h:0};if(this.pinned){let e=Math.max(n.x+I,Math.min(this.pinned.left,n.x+n.width-r-I)),t=Math.max(n.y+I,Math.min(this.pinned.top,n.y+n.height-i-I));this.el.style.left=`${Math.round(e)}px`,this.el.style.top=`${Math.round(t)}px`;return}let a=t.x+t.width/2-r/2;a=Math.max(n.x+I,Math.min(a,n.x+n.width-r-I));let o=t.y-i-ti;o<n.y+I&&(o=Math.min(t.y+t.height+ti,n.y+n.height-i-I)),o=Math.max(o,n.y+I),this.el.style.left=`${Math.round(a)}px`,this.el.style.top=`${Math.round(o)}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===`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+I)}}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=L(e===`fill`?(0,u.ownFillColor)(n)??n.color:e===`textColor`?n.textColor??n.color:n.color).toLowerCase(),i=ai(n.lineWidth),o=R(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=Xr.map(e=>s(`tcw-sel-swatch`,e.toLowerCase()===r,`data-color="${e}" style="background:${e}" aria-label="${e}"`)).join(``):e===`width`?this.pop.innerHTML=Zr.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=Qr.map(e=>s(`tcw-sel-option`,e===o,`data-style="${e}"`,si(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`?ni: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 ei?ei[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:R(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 si(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 z={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}},ci=new Set([`trendLine`,`ray`,`extendedLine`,`infoLine`,`trendAngle`,`arrow`,`horizontalLine`,`horizontalRay`,`verticalLine`,`rectangle`]),li={priceLabel:`#ffffff`},ui=8,di=6,fi=1.3,pi=120,mi=229,hi=500,B=8,gi=400,_i=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<hi){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);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(fi),color:e.color,padding:`${di}px ${ui}px`}),r.addEventListener(`input`,()=>{this.fit(),this.target?.onInput(r.value);let e=this.target?.rect();e&&this.place(e)}),r.addEventListener(`keydown`,e=>{e.stopPropagation(),!(e.isComposing||e.keyCode===mi)&&(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(pi,window.innerWidth-B*2);t.style.maxWidth=`${n}px`,t.style.width=`${Math.min(n,Math.max(pi,e.width))}px`,t.style.minHeight=`${e.height}px`;let r=t.offsetWidth||Math.max(pi,e.width),i=t.offsetHeight||e.height;t.style.left=`${Math.max(B,Math.min(e.x,window.innerWidth-B-r))}px`,t.style.top=`${Math.max(B,Math.min(e.y,window.innerHeight-B-i))}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>gi){this.finish(!0,!1);return}this.place(e),this.follow()})}},vi=[{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`}],yi=[{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 vi.find(t=>t.id===e)?.mode}function xi(...e){return e.filter(e=>e.length>0).flatMap((e,t)=>t===0?[...e]:[`separator`,...e])}function V(e,t){let n=t.keys[e.id];return n?{...e,shortcut:n}:e}function Si(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 Ci=e=>({id:`settings`,label:e(`chartMenu.settings`),icon:`settings`});function wi(e,t){let n=[V({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 xi(Si(e,t),n,r,[...i,Ci(t)])}function Ti(e,t){let n=[{id:`resetPriceScale`,label:t(`chartMenu.resetPriceScale`)},{id:`autoScale`,label:t(`settings.autoScale`),checked:e.autoScale},V({id:`invertScale`,label:t(`chartMenu.invertScale`),checked:e.inverted},e),{id:`leftScale`,label:t(`settings.leftScale`),checked:e.leftScale}],r=vi.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 xi(n,r,[{id:`labels`,label:t(`chartMenu.labels`),submenu:i},{id:`lines`,label:t(`chartMenu.lines`),submenu:a}],Si({...e,canTrade:!1,canDraw:!1},t),[Ci(t)])}function Ei(e,t){let n=[V({id:`resetView`,label:t(`chartMenu.resetTimeScale`)},e)];e.canGoToDate&&n.push(V({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 xi(n,r.length>0?[{id:`timezone`,label:t(`settings.timezone`),submenu:r}]:[])}function Di(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 xi([V({id:`resetView`,label:t(`chartMenu.resetView`)},e)],n,[Ci(t)])}function Oi(e,t,n){switch(e){case`priceAxis`:return Ti(t,n);case`timeAxis`:return Ei(t,n);case`pane`:return Di(t,n);default:return wi(t,n)}}var ki=/^[-+−]/;function H(e,t,n){let r=e.replace(ki,``);return r===n.replace(ki,``)?r:t>0?`+${r}`:t<0?`-${r}`:r}function Ai(e){return e.startsWith(`+`)?`up`:e.startsWith(`-`)?`down`:null}var U=[`positions`,`orders`,`history`],ji=[`order`,`close`,`reverse`,`stopLoss`,`takeProfit`],Mi=[`market`,`limit`,`stop`],Ni=[`gtc`,`day`],W=`—`,Pi=`{pnl}`,Fi=3;function Ii(e,t,n){return e.includes(t??``)?t:n}function Li(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Ri(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 zi(e){let t=document.createElement(`span`);return t.dir=`ltr`,t.textContent=e,t}function Bi(e){let t=Ai(e);return t?`tcw-account-${t}`:``}var Vi=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 U){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,Li(t.positions,e.positions)&&Li(t.orders,e.orders)&&Li(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=U.indexOf(this.tab),n=e.key===`ArrowRight`?t+1:e.key===`ArrowLeft`?t-1:-2;if(n===-2)return;e.preventDefault();let r=U[(n+U.length)%U.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=Ri(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 ${Bi(r)}`.trim();let i=this.t(e),a=i.indexOf(Pi),o=zi(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?W:this.callbacks.formatPrice(e),this.writePnl(t.pnl,Ri(t.position,e))}amount(e){return H(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`${H(t(Math.abs(e)),e,t(0))}%`}writePnl(e,t){if(t===null){e.className=``,e.textContent=W;return}let n=this.amount(t.pnl);e.className=Bi(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?W: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=zi(``);this.writePnl(a,Ri(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?W: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[Fi],pnl:n[t]}))}renderOrders(){let{formatPrice:e}=this.callbacks,t=this.snapshot.orders.map(t=>{let n=Ii(Mi,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.${Ii(Ni,t.timeInForce,`gtc`)}`):W,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=zi(``);return n.pnl===void 0?r.textContent=W:(r.textContent=this.amount(n.pnl),r.className=Bi(r.textContent)),[t(n.time),this.sideCell(n.side,`trade`),String(n.quantity),e(n.price),this.t(`account.reason.${Ii(ji,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`)}},Hi=1e-9;function Ui(e,t){return e.type===`market`?t:e.price}function Wi(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=Ui(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,...Gi(e,n)]}function Gi(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)>Hi)&&n.push(`priceStep`),o&&r!==null&&r>0&&(r>o.ceiling+Hi||r<o.floor-Hi)&&n.push(`priceLimits`),s!==void 0&&s>1&&e.quantity>s&&e.quantity%s!==0&&n.push(`lot`),n}function Ki(e,t){let n={side:e.side,type:e.type,price:e.type===`market`?t??e.price:e.price,quantity:e.quantity};return 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),n}function qi(e,t){let n=Ui(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 Ji(e,t,n,r=1){let i=Ui(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 Yi(e,t,n={}){let r=n.multiplier!==void 0&&n.multiplier>0?n.multiplier:1,i=Ui(e,t),a=i!==null&&i>0&&e.quantity>0?i*e.quantity*r:null,o=Wi(e,t),s=(n,i)=>n===null||o.includes(i)?null:Ji(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?qi(e,t):null}}var Xi=229,Zi=1,Qi=2,$i=.999999999,ea=0,ta=class{backdrop;modal;symbolEl;body;summaryEl;problemsEl;submit;draft=null;lastPrice=null;rules={};step=ra;round=e=>ia(e,e);typed=new Map;returnFocus=null;uid=++ea;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!==Xi){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??ra,this.round=e.round??(e=>ia(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*$i)}writePrice(e){return Number.isFinite(e)?this.step===ra?String(e):e.toFixed((0,u.stepDecimals)(this.step(e))):``}place(){let e=this.draft;!e||Wi(e,this.lastPrice,this.rules).length>0||(this.callbacks.onSubmit(Ki(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),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=na(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=na(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},!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}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`?-Zi:Qi;return this.round(n*(1+(t.side===`buy`?r:-r)/100))}check(){let e=this.draft;if(!e)return;let t=Wi(e,this.lastPrice,this.rules),n=t.map(e=>this.problemText(e));n.join(`
|
|
7849
7809
|
`)!==[...this.problemsEl.children].map(e=>e.textContent).join(`
|
|
7850
|
-
`)&&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:Ji(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=Yi(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:Ai(n)],[`reward`,`ticket.reward`,r,r===null?null:Ai(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 H(this.number(Math.abs(e),t),e,this.number(0,t))}amount(e){return H(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 na(e,t){return t.dataset.ticketField=e,t}function ra(e){let t=Math.abs(e);return t>0?10**Math.floor(Math.log10(t/100)):1}function ia(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 aa=0,oa=class{backdrop;titleEl;input;submit;request=null;returnFocus=null;busy=!1;uid=++aa;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()}}}},sa=0,ca=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-${++sa}`,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}},la=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{}}},ua=[`regular`,`logarithmic`,`percentage`,`indexedTo100`],da=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function fa(e){let{theme:t,timestamp:n,...r}=e;return r}function pa(e){return!da(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:ua.find(t=>t===e.scaleMode)??`regular`,invertScale:e.invertScale===!0,chart:da(e.chart)?fa(e.chart):null,...da(e.settings)?{settings:F(e.settings,Tr)}:{}}}function ma(e){try{return JSON.parse(e)}catch{return null}}function ha(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var ga=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=ha()){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 _a(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 G(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 ya=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}},K={settings:G(()=>Promise.resolve().then(()=>require(`../WidgetSettings-bO72SYQ6.cjs`))),indicatorSettings:G(()=>Promise.resolve().then(()=>require(`../WidgetIndicatorSettings-DhFQasHT.cjs`))),drawingSettings:G(()=>Promise.resolve().then(()=>require(`../WidgetDrawingSettings-B8JKpke1.cjs`))),goToDate:G(()=>Promise.resolve().then(()=>require(`../WidgetGoToDate-BNdngHlg.cjs`))),hotkeySheet:G(()=>Promise.resolve().then(()=>require(`../WidgetHotkeySheet-y5LWKSG6.cjs`))),indicatorPicker:G(()=>Promise.resolve().then(()=>require(`../WidgetIndicatorPicker-B72LdJy1.cjs`))),commandPalette:G(()=>Promise.resolve().then(()=>require(`../WidgetCommandPalette-B1jaXJ-I.cjs`))),symbolSearch:G(()=>Promise.resolve().then(()=>require(`../WidgetSymbolSearch-BW7HxOMk.cjs`)))};async function ba(){await Promise.all(Object.values(K).map(e=>e.load().catch(()=>null)))}var xa=/^(\d{4})-(\d{2})-(\d{2})$/,Sa=/^(\d{2}):(\d{2})$/;function Ca(e,t,n){let r=xa.exec(e),i=t?Sa.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 q(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 J={min:233,default:262,max:377},wa=.382,Ta=e=>!e.hidden&&getComputedStyle(e).display!==`none`,Ea=class{element;panel;rail;handle;pages=new Map;open_=null;width;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(J.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=this.clamp(t.savedWidth?.()??J.default,J.max),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)&&Ta(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(Ta),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?.())}maxNow(){let e=this.options.room?.()??0;return e<=0?J.max:Math.max(J.min,Math.min(J.max,Math.floor(e*wa)))}clamp(e,t=this.maxNow()){return Math.round(Math.min(t,Math.max(J.min,e)))}shownWidth(){return this.clamp(this.width)}setWidth(e){this.width=this.clamp(e),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`?J.min:e.key===`End`?J.max: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(Ta),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())}},Da=[`percent`,`scale`,`pane`,`spread`,`ratio`,`correlation`,`correlationLog`],Oa={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 ka(e){return Da.includes(e)}function Aa(e){return Da.map(t=>({id:t,label:e(Oa[t])}))}function ja(e,t){let n=e.findIndex(e=>e.time>=t);return n<0?e.length:n}function Ma(e,t){let n=e[0]?.time??1/0,r=t.filter(e=>e.time<n);return r.length>0?[...r,...e]:null}function Na(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 Pa(e,t,n,r){let i=e.map(e=>({id:e.id,symbol:e.symbol,way:r(Oa.percent),color:e.color}));for(let e of t){let t=e.params.symbol,a=Na(e,n.has(e.instanceId));!a||typeof t!=`string`||!t||i.push({id:e.instanceId,symbol:t,way:r(Oa[a])})}return i}var Y=8,Fa=4,Ia=3,La=`[title]:not([title=""]), [data-tip]:not([data-tip=""])`,Ra=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`)&&za(this.pressed);let e=this.target;!e||this.source!==`pointer`||!e.hasAttribute(`title`)||(za(e),this.isVisible()&&this.show(e))}),this.observer.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`title`]})}destroy(){this.hide(),this.pressed&&X(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`||(za(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)&&(X(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&&X(this.pressed),this.pressed=t?e:null};onFocus=e=>{let t=this.tipTarget(e.target);!t||!Ha(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`&&X(this.target),this.target=null,this.source=null};tipTarget(e){if(!(e instanceof Element))return null;let t=e.closest(La);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`&&X(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(!Va(e)){this.hide();return}this.el.textContent=Ba(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&&(Va(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=Ua(e);s===`bottom`&&o+n.height+Y+i>t.height?s=`top`:s===`top`&&o-Y-i<0?s=`bottom`:s===`right`&&a+n.width+Y+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+Y:o-Y-i):(c=s===`right`?a+n.width+Y:a-Y-r,l=o+n.height/2-i/2),c=Math.max(Fa,Math.min(t.width-r-Fa,c)),l=Math.max(Fa,Math.min(t.height-i-Fa,l)),this.el.style.left=`${Math.round(c)}px`,this.el.style.top=`${Math.round(l)}px`;let u={top:[0,Ia],bottom:[0,-Ia],left:[Ia,0],right:[-Ia,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 za(e){let t=e.getAttribute(`title`);t!==null&&(e.dataset.tip=t,e.removeAttribute(`title`))}function X(e){e.dataset.tip!==void 0&&!e.hasAttribute(`title`)&&(e.setAttribute(`title`,e.dataset.tip),delete e.dataset.tip)}function Ba(e){return e.dataset.tip??e.getAttribute(`title`)??``}function Va(e){return e.isConnected&&e.getClientRects().length>0&&!e.disabled}function Ha(e){try{return e.matches(`:focus-visible`)}catch{return!1}}function Ua(e){return e.dataset.tipSide||(e.closest(`.tcw-sidebar`)?`right`:e.closest(`.tcw-statusbar, .tcw-replay-bar`)?`top`:`bottom`)}var Wa=2,Ga=1.5,Ka=`tcw-ind-legend-values--no-room`,qa=0,Ja=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)Ya(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),Z(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-${++qa}`;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),Z(e.eye,t.visible?this.labels.hide:this.labels.show,t.label),e.settings&&Z(e.settings,this.labels.settings,t.label),e.more&&(Z(e.more,this.labels.more??`More`,t.label),e.more.setAttribute(`aria-haspopup`,`menu`)),Z(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>=Wa;!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;Z(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 Ya(e,t){let n=(parseFloat(getComputedStyle(e).fontSize)||0)*Ga;e.classList.toggle(Ka,t<n)}function Z(e,t,n){e.title=t,e.setAttribute(`aria-label`,n?`${t} ${n}`:t)}function Xa(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 Za(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 Qa=new Map;function $a(e){let t=Qa.get(e);return t||(t=new Intl.NumberFormat(e,{notation:`compact`,maximumFractionDigits:2}),Qa.set(e,t)),t}function eo(e,t=`en-US`){return Math.abs(e)>=1e6?$a(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()}},no=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 ro(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 io=1e-9,ao=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?ro(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=oo(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=so(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 oo(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:io}function so(e){return e>=1e3?`${Number((e/1e3).toFixed(1))}k`:String(Number(e>=1?e.toFixed(2):e.toPrecision(2)))}var co=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??uo)(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??lo(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 lo(e){if(!Number.isFinite(e))return`—`;let t=Math.abs(e);return t>=1e3?e.toFixed(2):t>=1?e.toFixed(4):e.toPrecision(4)}function uo(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)}var fo=[[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]],po=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-card`;let r=document.createElement(`div`);r.className=`tcw-loading-candles`,r.setAttribute(`aria-hidden`,`true`),fo.forEach(([e,t,n,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`,`${n}px`),s.style.setProperty(`--tcw-wick-h`,`${i}px`),s.style.setProperty(`--tcw-delay`,`${o*110}ms`),r.appendChild(s)}),n.appendChild(r);let i=document.createElement(`div`);i.className=`tcw-loading-track`,i.setAttribute(`aria-hidden`,`true`),i.appendChild(document.createElement(`span`)),n.appendChild(i),this.label=document.createElement(`div`),this.label.className=`tcw-loading-label`,this.label.textContent=t,n.appendChild(this.label),this.el.appendChild(n),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)}},mo=4e3,ho=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(),mo)):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}},go=`host:`;function _o(e,t){return[...e,...e.length>0&&t.length>0?[`separator`]:[],...t.map((e,t)=>({id:`${go}${t}`,label:e.label,icon:e.icon,danger:e.danger,checked:e.checked}))]}function vo(e,t){return e.startsWith(go)?(t[Number(e.slice(5))]?.onSelect(),!0):!1}var yo=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent),bo={ctrl:`ctrl`,control:`ctrl`,cmd:`ctrl`,command:`ctrl`,meta:`ctrl`,mod:`ctrl`,alt:`alt`,option:`alt`,opt:`alt`,shift:`shift`},xo={esc:`escape`,space:` `,spacebar:` `,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`,del:`delete`,return:`enter`,plus:`+`};function So(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=bo[e.toLowerCase()];if(!t)return null;r[t]=!0}let i=n.toLowerCase();if(bo[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=xo[i]??i,r.shift&&r.key.length===1)return null;return r.display=[...r.ctrl?[yo?`⌘`:`Ctrl`]:[],...r.alt?[`Alt`]:[],...r.shift?[`Shift`]:[],r.key===` `?`Space`:n.length===1?n.toUpperCase():n],r}function Co(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 wo=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 To(e){let t=`${e.ctrl?`ctrl+`:``}${e.alt?`alt+`:``}${e.shift?`shift+`:``}${e.char??e.key}`;return wo.has(t)}function Eo(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 Do=[`#b552c9`,`#1398a8`,`#d4622b`,`#e25592`,`#6f7a8c`,`#3e9a4f`],Oo=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:Aa(this.host.t),way:this.compareWay,compared:this.comparedNow(),onAdd:(e,t)=>{ka(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 Pa(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=Do[this.compares.length%Do.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=ja(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=Ma(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)}},ko=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?O():null,r=new ln({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 Xt(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}),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)||Yt())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()})}},Ao=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 kn(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=Xa(this.host.chart.getIndicatorOutput(r)?.series,null)?.[i];return typeof a==`number`&&Number.isFinite(a)?a:null}},jo=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 Mo(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.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 No=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(Mo({selected:a,canConfigure:!0,canAlert:this.host.chart.canAddDrawingAlert(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=_o(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=>{vo(t,l)||this.runDrawingMenuAction(e,s,t)})}runDrawingMenuAction(e,t,n){switch(n){case`settings`:this.host.openDrawingSettings(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(yi.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=_o(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=>{vo(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()}},Po=2,Fo=2;function Io(e,t=`en-US`){return(0,u.formatPrice)(e,Math.max(Po,(0,d.indicatorValuePrecision)(e)),t)}function Lo(e,t=`en-US`){return`${H((0,u.formatPrice)(Math.abs(e),Fo,t),e,(0,u.formatPrice)(0,Fo,t))}%`}function Ro(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:zo(e,t)}:{values:[],offChartType:!0},pane:null}))}function zo(e,t){return[...e.close===null?[]:[{text:Io(e.close,t),color:null}],...e.change===null?[]:[{text:Lo(e.change,t),color:null}]]}var Bo=7,Vo=17,Ho=3;function Uo(e){return!d.SYMBOL_INDICATOR_IDS.has(e.id)&&e.scale!==`left`}var Wo=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=n===null?e:Math.min(Math.max(n,0),e),i=new Map;for(let e of this.host.chart.getIndicatorPanes())(e.instanceIds??[e.instanceId]).forEach((t,n)=>i.set(t,{...e.rect,row:n}));let a=this.host.settingsState.numberLocale||`en-US`,o=Ro(r>=0?this.host.chart.getCompareValues?.(n===null||!t?void 0:r)??[]:[],a,t),s=this.host.chart.getActiveIndicators().map(e=>{let t=i.get(e.instanceId)??null,r=Xa(this.host.chart.getIndicatorOutput(e.instanceId)?.series,n),o=this.host.chart.getIndicatorStyle(e.instanceId),s=e.visible&&e.offChartType===!0,l=e.visible&&e.shown===!1&&!s,u=l||s?[]:Za(e.descriptor,r,o?.colors??[],o?.plots);return{instanceId:e.instanceId,label:c.r(e,this.host.t),visible:e.visible,offInterval:l,offChartType:s,values:u.map(n=>({text:this.host.indicatorValueText(n.value,t===null&&Uo(e),a),color:n.color})),pane:t?{x:t.x+4,y:t.y+Math.min(Bo+t.row*Vo,Math.max(Bo,t.height-Vo)),width:t.width-8}:null}}),l=[...o,...s],u=this.host.chart.getPlotRect(),d=this.host.chart.getMaximizedPane(),f=e=>l.find(t=>t.instanceId===e)?.label??``,p=this.host.chart.getIndicatorPanes().map(e=>({instanceId:e.instanceId,x:e.rect.x+e.rect.width-4,y:e.rect.y+Ho,label:f(e.instanceId),collapsed:this.host.chart.isPaneCollapsed(e.instanceId),maximized:d===e.instanceId,canMoveUp:this.host.chart.canMovePane(e.instanceId,-1),canMoveDown:this.host.chart.canMovePane(e.instanceId,1)}));this.host.indicatorLegend.update(l,{left:u.x+4,top:this.host.chart.getLegendBottom()+1},p)}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=_o(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=>{vo(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)}},Go=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=Cn();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}}},Ko=0,qo=class{backdrop;search;listEl;layouts=[];confirming=null;returnFocus=null;loadSeq=0;uid=++Ko;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()}}},Jo=5,Yo=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 oa(n,r),this.dialog=new qo(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,Jo)}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()}},Xo=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Zo=globalThis.Buffer;function Qo(e){if(Zo)return Zo.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 $o(e){if(Zo)return Zo.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 ts(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function ns(e){return es(Qo(JSON.stringify(e)))}function rs(e){if(!e)return null;try{let t=$o(ts(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:ua.find(e=>e===n.scaleMode)??`regular`,indicators:Array.isArray(n.indicators)?n.indicators:[],drawings:Array.isArray(n.drawings)?n.drawings:[],...Xo(n.settings)?{settings:F(n.settings,Er)}:{}}}catch{return null}}var is=`tcw`;function as(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)!==is))try{return decodeURIComponent(e.slice(t+1))}catch{return null}}return null}function os(e,t){let[n]=e.split(`#`);return`${n}#${is}=${t}`}var ss=[`legendVisible`,`volumeVisible`,`barCountdown`,`indicatorValueLabels`,`alignAxisLabels`],cs=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=as(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=Br(n,{...t.h,...Object.fromEntries(ss.map(e=>[e,this.host.settingsDefaults[e]]))});return ns({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=rs(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,...F(t.settings,Er)}),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=os(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?ma(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:Rr(e,Tr)}}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,...F(e.settings,Tr)});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=pa(ma(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 Yo(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}=q(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}}},ls={alerts:`alerts`,objectTree:`objectTree`,dataWindow:`dataWindow`,symbolInfo:`symbolInfo`,depthLadder:`depthLadder`},us={alerts:`alerts`,objectTree:`objects`,symbolInfo:`symbolInfo`,depthLadder:`trade`},ds=class{constructor(e){this.host=e}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[ls[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)?.series?.[e]??null,r=!o.has(t.instanceId)&&Uo(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`)}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()})}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(`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=us[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||hr(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)}},fs=new Set([`timezone`,`numberLocale`,`chartTypeOptions`,`logScale`,`autoScale`]),ps=80,ms=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function hs(e){return F(e,fs)}function gs(e){let{overrides:n}=(0,u.readChartStyleOverrides)(e);return Object.fromEntries(Object.entries(n).filter(([e,n])=>n!==null&&t.l.includes(e)))}function _s(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var vs=class{constructor(e=`tcw:chart-templates`,t=_s()){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)!ms(n)||typeof n.name!=`string`||!n.name.trim()||t.push({name:n.name.slice(0,ps).trim(),settings:hs(n.settings),style:gs(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,ps).trim();if(!r||!this.storage)return!1;let i=[...this.list().filter(e=>e.name!==r),{name:r,settings:hs(t),style:gs(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{}}},ys=new Set([...Cr,`autoScale`]),bs=class{constructor(e){this.host=e}chartTemplates=new vs;chartTemplatePrompt=null;settingsEdit=null;state=it(t.h);dialogChanging=0;get settingsState(){return this.state.peek()}set settingsState(e){this.state.set(e)}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 oa(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(F(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(F({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?.(),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:Ar(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=>!ys.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.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())}},xs=13;function Ss(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 Cs=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=Ss(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:s.x+i.x,y:s.y+i.y,width:s.width,height:s.height},bounds:{x:o.x+i.x,y:o.y+i.y,width:o.width,height:o.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})}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;if(!n||!r||n.locked||!t&&!this.host.chart.beginDrawingEdit(e))return!1;let i=z[n.type],a=n.style,o=a.text??``,s=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=this.host.chart.getDrawingTextRect(e);if(!t)return null;let n=this.host.chartContainer.getBoundingClientRect();return{x:n.left+t.x,y:n.top+t.y,width:t.width,height:t.height}},text:o,font:{size:a.fontSize||i?.fontSize||xs,bold:a.bold===!0,italic:a.italic===!0,family:this.host.chart.getFont?.()?.family??this.host.ui.font.family},color:a.textColor??li[n.type]??a.color,label:this.host.t(`drawingSettings.text`),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+$/,``);r&&r!==n&&(t?this.host.chart.amendNewDrawing(e,{style:{text:r}}):this.host.chart.updateDrawing(e,{style:{text:r}})),s(r.length>0)},onCancel:()=>s(!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:z[r.type],textColor:li[r.type],textPlace:ci.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 oa(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()}))}})}},ws=200,Ts=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(-ws).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()}},Es=600,Ds=24,Os=[`--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`],ks=48,As=5e4,js=100;function Ms(){return new Promise(e=>{if(typeof requestAnimationFrame!=`function`||document.hidden){setTimeout(e,0);return}let t=setTimeout(e,js);requestAnimationFrame(()=>setTimeout(()=>{clearTimeout(t),e()},0))})}var Ns=864e5,Ps=5e3,Fs=2e3,Is=48,Ls=`rgba(255,255,255,0.03)`,Rs=`rgba(0,0,0,0.03)`,zs=2;function Bs(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 Vs=1e3,Hs=[[`barCountdown`,`barCountdown`],[`logScale`,`logScale`],[`legendVisible`,`legend`],[`volumeVisible`,`volume`]],Us=t.l.filter(e=>u.CHART_STYLE_KEYS[e]!==`color`);function Ws(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 Gs=class{intervals=new Ts(this.intervalsHost());drawingEdit=new Cs(this.drawingEditHost());chartSettings=new bs(this.chartSettingsHost());docking=new ds(this.dockingHost());layouts=new cs(this.layoutsHost());commands=new Go(this.commandsHost());legend=new Wo(this.legendHost());menus=new No(this.menusHost());trading=new jo(this.tradingHost());alerting=new Ao(this.alertingHost());watching=new ko(this.watchingHost());comparing=new Oo(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 la;templatePrompt=null;markerTip=null;dataWindow=null;lastHoverIndex=null;lastHoverBar=null;lastHoverPrevClose=null;legendHoverIndex=null;pointerOnChart=!1;favoritesStore=new ga;indicatorFavorites=new ga(`tcw:indicator-favorites`);indicatorDefaults=new br;timeframeFavorites=new ga(`tcw:tf-favorites`);customTimeframes=new ga(`tcw:tf-custom`);timeframes=[];sessionRefPrice=null;symbolInfoPanel=null;news=new gn;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;constructor(e,t={}){let n=Ws(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}:{},...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=Vr(e.persistSettings);o&&(this.chartSettings.settingsStore=new Ur(o));let c=this.resolveIsDark(e.theme),l=this.resolveTheme(e.theme);this.themeOf={...this.themeOf,[c?`dark`:`light`]:l};let d={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=d.priceAxisAddButton===!0;let f={...d,priceAxisAddButton:this.priceAxisAddDefault&&this.featureState[`menu.priceAxisAdd`]};if(this.canExport=d.dataExport!==!1,this.chartSettings.settingsLocked=new Set(Hs.filter(([,e])=>d[e]===!1).map(([e])=>e)),this.chartSettings.settingsDefaults={...this.chartSettings.settingsState,legendVisible:d.legend!==!1,volumeVisible:d.volume!==!1,barCountdown:d.barCountdown!==!1,indicatorValueLabels:d.indicatorValueLabels===!0,alignAxisLabels:d.alignAxisLabels!==!1},this.chartSettings.settingsState={...this.chartSettings.settingsDefaults},this.timeframes=De(xe(e.timeframes,d.timeframes),this.customTimeframes.list(),d.timeframes),!this.timeframes.some(e=>this.timeframeFavorites.has(e))){let t=Se(this.timeframes,d.defaultTimeframeFavorites,!!e.timeframes?.length);for(let e of t)this.timeframeFavorites.add(e)}let p=e.timeframe??`5m`,m=!d.timeframes?.length||d.timeframes.includes(p)?p:this.timeframes[0]??p;return this.state={symbol:e.symbol??this.symbols[0]??`BTCUSDT`,timeframe:m,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:d,chartFeatures:f}}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:ec(t.locale)?`rtl`:`ltr`;this.root.dir=i,this.portal.dir=i,e.appendChild(this.root),this.tooltip=new Ra(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=_a([this.root,this.portal]),this.stopNarrow=va(this.root,e=>{this.toolbar?.fit(),e||this.sidebar?.closeOverlay(),this.docking.syncRail()}),this.ui=P(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(),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 bt(i,{drawingToolGroups:t.n(t._,this.t),favorites:this.favoritesStore.list(),shortcuts:Cn()},{onDrawingTool:e=>this.handleDrawingTool(e),onCancelDrawing:()=>this.handleCancelDrawing(),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.chartContainer=document.createElement(`div`),this.chartContainer.className=`tcw-chart-container`,this.chartContainer.dir=`ltr`,i.appendChild(this.chartContainer),this.loading=new po(this.chartContainer,this.t(`status.loading`)),this.historyPill=new ho(this.chartContainer,{loading:this.t(`history.loading`),failed:this.t(`history.failed`)}),this.docking.dock=new Ea(i,{labels:{rail:this.t(`dock.rail`),resize:this.t(`dock.resize`)},savedWidth:()=>Qs(),saveWidth:e=>$s(e),railShown:()=>this.docking.railShown(),focusAfterClose:e=>this.docking.panelFocusTarget(e),room:()=>i.clientWidth}),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.c(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 On(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 un(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=()=>{Yt()||this.refreshMarket()},document.addEventListener(`visibilitychange`,this.onPageShown),this.dragDrop=new e.o(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 At(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(()=>{!Yt()&&this.featureState.statusBar&&this.featureState[`statusBar.clock`]&&this.statusBar?.tick()},Vs),this.chart.on(`priceRangeChange`,()=>this.chartSettings.refreshScaleSwitches()),this.chartSettings.refreshScaleSwitches(),this.goToDatePart=this.lazyPart(K.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(K.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(K.symbolSearch,({WidgetSymbolSearch:e})=>new e({onPick:e=>{this.setSymbol(e)},onClose:()=>{}},this.overlayHost,this.t)),this.hotkeySheetPart=this.lazyPart(K.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 Ja(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:4+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 qt(this.replayHost()),this.replay.attach();for(let e of[`resize`,`dataUpdate`,`symbolInfoChange`])this.chart.on(e,()=>this.placeDrawingButton());this.placeDrawingButton(),this.dataWindow=new co(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(`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 Jr,t=new Yr;for(let[e,n]of Object.entries(t.all()))this.chart.setDrawingToolDefaults(e,n??null);this.drawingSettingsPart=this.lazyPart(K.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=>q(e*(0,u.barTimeUnit)(this.chart.getData()),this.displayTimezone()),fromWallTime:(e,t)=>{let n=Ca(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 _i(this.overlayHost),this.chart.on(`drawingDoubleClick`,e=>{let t=e.payload.id,n=this.chart.getDrawings().find(e=>e.id===t)?.type;n&&z[n]&&this.drawingEdit.editTextInPlace(t,!1)||this.drawingEdit.openDrawingSettings(t,n&&z[n]?{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||!z[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,Es),this.drawingEdit.cancelTextPrompt=a}),this.drawingStyle=new $r(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 oi(this.root,{onStyle:e=>{for(let t of this.chart.getSelectedDrawingIds()){let n=this.chart.getDrawings().find(e=>e.id===t)?.type,r=n?z[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)},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(Oi(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(Si(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 ca(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 ta(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 Vi(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}=q(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 ao(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 Ln(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}=q(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 no(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(K.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(K.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 fr(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(K.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:()=>Ys(),add:e=>Xs([e,...Ys().filter(t=>t!==e)])})),this.boundGlobalKeydown=e=>{if(this.handleHostHotkey(e)||this.featureState.hotkeys&&this.replay.isOpen()&&this.replay.handleReplayKey(e))return;let t=T(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||E()||!T(this.root,!0))return;e.preventDefault(),this.layouts.saveLayout()}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&Sn[e.code]){if(e.defaultPrevented||E()||!t||D()||!n(`hotkeys.tools`))return;e.preventDefault(),this.handleDrawingTool(Sn[e.code])}else if(/^[0-9]$/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(e.defaultPrevented||!this.intervals.intervalInput||!n(`intervalTyping`)||E()||D()||!T(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(Bs(e)!==null){if(e.defaultPrevented||!n(`symbolTyping`)||!this.featureState.symbolSearch||E()||D()||!T(this.root,!0))return;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t))return;e.preventDefault(),this.openSymbolSearch(Bs(e))}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&(e.code===`KeyI`||e.code===`KeyG`||e.code===`KeyR`)){if(E()||!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(E()||!t||!n(`hotkeys.help`)||!this.featureState.hotkeySheet)return;e.preventDefault(),this.openHotkeySheet()}},document.addEventListener(`keydown`,this.boundGlobalKeydown),document.addEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys=Nt(this.root,[this.portal])}finishSetup(e){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||ba()},t=globalThis;if(t.requestIdleCallback&&t.cancelIdleCallback){let n=t.requestIdleCallback(e,{timeout:Ps}),r=t.cancelIdleCallback;this.stopPreload=()=>r(n)}else{let t=setTimeout(e,Fs);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)}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(Yt())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.refreshSymbolInfo()}refreshSymbolInfo(){let e=this.symbolInfoPanel;!e?.isOpen()||this.destroyed||e.render(this.symbolInfoView())}symbolInfoView(){let e=this.state.symbol;return hn({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.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=P(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?Jn(e):1}applyLookTokens(){let e=Yn(this.ui,this.uiScale);for(let t of[this.root,this.portal]){if(dr(t,e,{variables:this.uiVariables}),this.uiVariables)continue;let n=ur(e);for(let e of Os)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?Jn(t-Ds):Jn(t+Ds))===this.uiScale)return}this.uiScale=e,this.applyLookTokens(),this.applyLegendFont(),this.applyChartLook(),this.toolbar?.fit()}}getUI(){return P({...this.ui})}applyLegendFont(){this.chart.setLegend({fontFamily:this.ui.font.mono,fontSize:A(Math.round(this.ui.font.size*this.uiScale),-1)})}applyChartLook(){let e=this.options.chartOptions;e?.barLayout||this.chart.setBarLayout(this.ui.density===`compact`?`classic`:`golden`);let t=this.scaledChartSizes();e?.font?.family?Object.keys(t).length>0&&this.chart.setFont(t):this.chart.setFont({family:this.ui.font.mono,...e?.font?.textFamily?{}:{textFamily:this.ui.font.family},...t})}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(`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=So(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;To(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||E()||Eo(e)||D())return!1;let t=this.hostHotkeys.find(t=>Co(e,t.parsed));if(!t)return!1;let n=!t.parsed.ctrl&&!t.parsed.alt;if(!T(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:Is,color:this.state.isDark?Ls:Rs})}keepingLook(e){this.chartSettings.settingsEdit&&this.settings?.close();let t=this.chart.getOverrides?.({layer:`user`})??{},n=Object.fromEntries(Us.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(_o([],i),a,e=>vo(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}=q(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=>q(e*r,n),a=t[t.length-1].time,o=this.chart.getVisibleTimeRange()??{from:t[0].time,to:a},s=q(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)>=Ns),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=Ca(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=Ca(e.from.date,e.from.time,n),a=Ca(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}=q(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 oa(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>=ks||this.baseSeries.length>=As;try{if(t&&(this.loading.begin(this.chart.getData().length>0,!0),await Ms(),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:Ks(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()),zs))}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):eo(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 ya(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()}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.statusBar?.update({connectionState:this.state.connectionState,message:this.state.connectionMessage,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),symbolSearchFn:(...t)=>e.symbolSearchFn(...t),get symbols(){return e.symbols},get t(){return e.t},withSymbolSearch:(...t)=>e.withSymbolSearch(...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),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 Ks(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 qs=`tcw:recentCommands`,Js=10;function Ys(){try{let e=JSON.parse(O()?.getItem(qs)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`).slice(0,Js):[]}catch{return[]}}function Xs(e){try{O()?.setItem(qs,JSON.stringify(e.slice(0,Js)))}catch{}}var Zs=`tcw:dockWidth`;function Qs(){try{let e=Number(O()?.getItem(Zs)??NaN);return Number.isFinite(e)&&e>0?e:null}catch{return null}}function $s(e){try{O()?.setItem(Zs,String(e))}catch{}}function ec(e){return!!e&&/^(ar|he|iw|fa|ur|ps|yi|dv|ckb|sd|ug)(-|$)/i.test(e)}var tc={symbol:!1,interval:!1,crosshair:!0,time:!1,drawings:!1,replay:!1},nc=[`symbol`,`interval`,`crosshair`,`time`,`drawings`,`replay`],Q={"1x1":{cols:1,rows:1},"1x2":{cols:2,rows:1},"2x1":{cols:1,rows:2},"2x2":{cols:2,rows:2},"1x3":{cols:3,rows:1},"3x1":{cols:1,rows:3},"2x3":{cols:3,rows:2},"3x2":{cols:2,rows:3}};function $(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call(Q,e)}function rc(e){return JSON.parse(JSON.stringify(e))}function ic(e,t,n=16){let r=(20-2*(e-1))/e,i=(20-2*(t-1))/t,a=``;for(let n=0;n<t;n++)for(let t=0;t<e;t++)a+=`<rect x="${2+t*(r+2)}" y="${2+n*(i+2)}" width="${r}" height="${i}" rx="1"/>`;return`<svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" aria-hidden="true">${a}</svg>`}function ac(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||t.kind!==`grid`||!$(t.layout)||!Array.isArray(t.cells))return null;let n=t.cells.map(pa);if(n.some(e=>e===null))return null;let r=typeof t.sync==`object`&&t.sync!==null?t.sync:{},i={...tc};for(let e of nc)typeof r[e]==`boolean`&&(i[e]=r[e]);let a=typeof t.active==`number`&&Number.isInteger(t.active)?t.active:0;return{v:1,kind:`grid`,layout:t.layout,sync:i,active:a,cells:n}}var oc=class{root;cellsEl;cells=[];layout;sync;active=0;hovered=null;relayDepth=0;uiTheme=null;styleOverrides={};featureSwitches={};parked=new Map;drawingFrame=0;drawingSource=null;layoutButtons=new Map;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||E()||!T(this.root,!0)||(e.preventDefault(),this.layoutsUI.save())};constructor(e,t={}){this.options=t,this.layout=$(t.layout)?t.layout:`1x2`,this.sync={...tc,...t.sync},this.t=s.n(s.o(t.widget?.locale,t.widget?.messages)),fe(),this.root=document.createElement(`div`),this.root.className=`tcw-root tcw-grid`,this.root.dataset.tcwTheme=t.widget?.theme===`light`?`light`:`dark`,dr(this.root,P(t.widget?.ui),{variables:t.widget?.ui!==void 0}),t.bar!==!1&&this.root.appendChild(this.buildBar()),this.cellsEl=document.createElement(`div`),this.cellsEl.className=`tcw-grid-cells`,this.root.appendChild(this.cellsEl),e.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 n=this.cells[0]?.el.querySelector(`.tcw-root`)?.dataset.tcwTheme;n&&(this.root.dataset.tcwTheme=n),t.layouts!==!1&&this.setupLayouts(t.layouts===!0||t.layouts===void 0?{}:t.layouts),this.unregisterKeys=Nt(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(e){if(e===this.layout||!$(e))return;this.layout=e;let t=this.shapeCount();for(;this.cells.length>t;){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<t;e++){let t=this.createCell(e);this.cells.push(t),this.unpark(e,t)}this.active>=t&&(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=P(e);dr(this.root,t);for(let e of this.cells)e.widget.setUI(t);this.uiTheme=t}getUI(){return P(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=ac(ma(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();for(let e of this.cells)this.destroyCell(e);this.cells=[],this.root.remove(),pe()}}shapeCount(){let{cols:e,rows:t}=Q[this.layout];return e*t}applyShape(){let{cols:e,rows:t}=Q[this.layout];this.cellsEl.style.gridTemplateColumns=`repeat(${e}, minmax(0, 1fr))`,this.cellsEl.style.gridTemplateRows=`repeat(${t}, minmax(0, 1fr))`}createCell(e){let t=document.createElement(`div`);t.className=`tcw-grid-cell`,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,s.r(this.t(`grid.chart`),{n:e+1})),this.cellsEl.appendChild(t);let n=this.options.widget??{},r=this.options.cells?.[e]??{},i=this.cells[this.active]?.widget,a={},o=new Gs(t,{...n,...r,...r.adapter?{feed:void 0}:{},...r.feed?{adapter:void 0}:{},...i&&this.sync.symbol?{symbol:i.getSymbol()}:{},...i&&this.sync.interval?{timeframe:i.getTimeframe()}:{},...this.options.adapter&&!r.adapter&&!r.feed&&!n.feed?{adapter:this.options.adapter(e)}:{},...this.uiTheme?{ui:this.uiTheme}:{},layouts:!1,...r.persistSettings===void 0&&n.persistSettings?{persistSettings:{key:`${Vr(n.persistSettings)}:${e}`}}:{},features:{dock:!1,...n.features,...r.features},onSymbolChange:e=>{r.onSymbolChange?.(e),n.onSymbolChange?.(e),this.sync.symbol&&this.relay(a,t=>void t.setSymbol(e)),this.renderTabs(),this.session?.changed()},onTimeframeChange:e=>{r.onTimeframeChange?.(e),n.onTimeframeChange?.(e),this.sync.interval&&this.relay(a,t=>void t.setTimeframe(e)),this.renderTabs(),this.session?.changed()}});return a.el=t,a.widget=o,Object.keys(this.styleOverrides).length>0&&o.getChart().applyOverrides(this.styleOverrides),Object.keys(this.featureSwitches).length>0&&o.setFeatures(this.featureSwitches),this.wireCell(a),t.addEventListener(`pointerdown`,()=>this.setActive(this.cells.indexOf(a)),!0),t.addEventListener(`pointerenter`,()=>{this.hovered=a}),t.addEventListener(`pointerleave`,()=>{this.hovered===a&&(this.hovered=null)}),this.options.onChartAdd?.(o,e),a}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=sc(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(rc(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(rc(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 e=document.createElement(`div`);e.className=`tcw-grid-bar`,e.setAttribute(`role`,`toolbar`),e.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`)),e.appendChild(this.tabsEl);let t=document.createElement(`div`);t.className=`tcw-grid-group`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,this.t(`grid.layout`));let n=this.options.layoutChoices?.filter($)??Object.keys(Q);for(let e of n){let{cols:n,rows:r}=Q[e],i=n*r===1?this.t(`grid.single`):s.r(this.t(`grid.layoutOption`),{count:n*r,cols:n,rows:r}),a=document.createElement(`button`);a.type=`button`,a.className=`tcw-btn-icon`,a.title=i,a.setAttribute(`aria-label`,i),a.innerHTML=ic(n,r),a.addEventListener(`click`,()=>this.setLayout(e)),this.layoutButtons.set(e,a),t.appendChild(a)}let r=document.createElement(`div`);r.className=`tcw-grid-group`,r.setAttribute(`role`,`group`),r.setAttribute(`aria-label`,this.t(`grid.sync`));let o=document.createElement(`span`);o.className=`tcw-grid-label`,o.innerHTML=`${i.i(`link`,13)}<span>${a.u(this.t(`grid.sync`))}</span>`,r.appendChild(o);for(let e of nc){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),r.appendChild(t)}let c=document.createElement(`span`);return c.className=`tcw-toolbar-spacer`,e.append(t,this.sep(),r,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)}),e.appendChild(this.layoutsButton)),this.renderBar(),e}sep(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-sep`,e}renderBar(){for(let[e,t]of this.layoutButtons){let n=e===this.layout;t.classList.toggle(`tcw-active`,n),t.setAttribute(`aria-pressed`,String(n))}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 Yo(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=q(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 sc(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=Gs,exports.ChartWidgetGrid=oc,exports.DEFAULT_GRID_SYNC=tc,Object.defineProperty(exports,`DRAWING_TOOL_ICONS`,{enumerable:!0,get:function(){return u.DRAWING_TOOL_ICONS}}),exports.EN_MESSAGES=s.c,exports.GRID_SHAPES=Q,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=ir,exports.applyWidgetUI=dr,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=ac,exports.readWatchlists=sn,exports.readWidgetLayout=pa,exports.registerWidgetLocale=s.a,exports.resolveWidgetUI=P,exports.widgetUIVariables=ur;
|
|
7810
|
+
`)&&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:Ji(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=Yi(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:Ai(n)],[`reward`,`ticket.reward`,r,r===null?null:Ai(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 H(this.number(Math.abs(e),t),e,this.number(0,t))}amount(e){return H(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 na(e,t){return t.dataset.ticketField=e,t}function ra(e){let t=Math.abs(e);return t>0?10**Math.floor(Math.log10(t/100)):1}function ia(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 aa=0,oa=class{backdrop;titleEl;input;submit;request=null;returnFocus=null;busy=!1;uid=++aa;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()}}}},sa=0,ca=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-${++sa}`,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}},la=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{}}},ua=[`regular`,`logarithmic`,`percentage`,`indexedTo100`],da=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function fa(e){let{theme:t,timestamp:n,...r}=e;return r}function pa(e){return!da(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:ua.find(t=>t===e.scaleMode)??`regular`,invertScale:e.invertScale===!0,chart:da(e.chart)?fa(e.chart):null,...da(e.settings)?{settings:F(e.settings,Tr)}:{}}}function ma(e){try{return JSON.parse(e)}catch{return null}}function ha(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var ga=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=ha()){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 _a(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 G(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 ya=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}},K={settings:G(()=>Promise.resolve().then(()=>require(`../WidgetSettings-bO72SYQ6.cjs`))),indicatorSettings:G(()=>Promise.resolve().then(()=>require(`../WidgetIndicatorSettings-DhFQasHT.cjs`))),drawingSettings:G(()=>Promise.resolve().then(()=>require(`../WidgetDrawingSettings-B8JKpke1.cjs`))),goToDate:G(()=>Promise.resolve().then(()=>require(`../WidgetGoToDate-BNdngHlg.cjs`))),hotkeySheet:G(()=>Promise.resolve().then(()=>require(`../WidgetHotkeySheet-y5LWKSG6.cjs`))),indicatorPicker:G(()=>Promise.resolve().then(()=>require(`../WidgetIndicatorPicker-B72LdJy1.cjs`))),commandPalette:G(()=>Promise.resolve().then(()=>require(`../WidgetCommandPalette-B1jaXJ-I.cjs`))),symbolSearch:G(()=>Promise.resolve().then(()=>require(`../WidgetSymbolSearch-DeBxGj4a.cjs`)))};async function ba(){await Promise.all(Object.values(K).map(e=>e.load().catch(()=>null)))}var xa=/^(\d{4})-(\d{2})-(\d{2})$/,Sa=/^(\d{2}):(\d{2})$/;function Ca(e,t,n){let r=xa.exec(e),i=t?Sa.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 q(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 J={min:233,default:262,max:377},wa=.382,Ta=e=>!e.hidden&&getComputedStyle(e).display!==`none`,Ea=class{element;panel;rail;handle;pages=new Map;open_=null;width;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(J.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=this.clamp(t.savedWidth?.()??J.default,J.max),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)&&Ta(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(Ta),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?.())}maxNow(){let e=this.options.room?.()??0;return e<=0?J.max:Math.max(J.min,Math.min(J.max,Math.floor(e*wa)))}clamp(e,t=this.maxNow()){return Math.round(Math.min(t,Math.max(J.min,e)))}shownWidth(){return this.clamp(this.width)}setWidth(e){this.width=this.clamp(e),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`?J.min:e.key===`End`?J.max: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(Ta),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())}},Da=[`percent`,`scale`,`pane`,`spread`,`ratio`,`correlation`,`correlationLog`],Oa={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 ka(e){return Da.includes(e)}function Aa(e){return Da.map(t=>({id:t,label:e(Oa[t])}))}function ja(e,t){let n=e.findIndex(e=>e.time>=t);return n<0?e.length:n}function Ma(e,t){let n=e[0]?.time??1/0,r=t.filter(e=>e.time<n);return r.length>0?[...r,...e]:null}function Na(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 Pa(e,t,n,r){let i=e.map(e=>({id:e.id,symbol:e.symbol,way:r(Oa.percent),color:e.color}));for(let e of t){let t=e.params.symbol,a=Na(e,n.has(e.instanceId));!a||typeof t!=`string`||!t||i.push({id:e.instanceId,symbol:t,way:r(Oa[a])})}return i}var Y=8,Fa=4,Ia=3,La=`[title]:not([title=""]), [data-tip]:not([data-tip=""])`,Ra=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`)&&za(this.pressed);let e=this.target;!e||this.source!==`pointer`||!e.hasAttribute(`title`)||(za(e),this.isVisible()&&this.show(e))}),this.observer.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`title`]})}destroy(){this.hide(),this.pressed&&X(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`||(za(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)&&(X(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&&X(this.pressed),this.pressed=t?e:null};onFocus=e=>{let t=this.tipTarget(e.target);!t||!Ha(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`&&X(this.target),this.target=null,this.source=null};tipTarget(e){if(!(e instanceof Element))return null;let t=e.closest(La);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`&&X(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(!Va(e)){this.hide();return}this.el.textContent=Ba(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&&(Va(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=Ua(e);s===`bottom`&&o+n.height+Y+i>t.height?s=`top`:s===`top`&&o-Y-i<0?s=`bottom`:s===`right`&&a+n.width+Y+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+Y:o-Y-i):(c=s===`right`?a+n.width+Y:a-Y-r,l=o+n.height/2-i/2),c=Math.max(Fa,Math.min(t.width-r-Fa,c)),l=Math.max(Fa,Math.min(t.height-i-Fa,l)),this.el.style.left=`${Math.round(c)}px`,this.el.style.top=`${Math.round(l)}px`;let u={top:[0,Ia],bottom:[0,-Ia],left:[Ia,0],right:[-Ia,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 za(e){let t=e.getAttribute(`title`);t!==null&&(e.dataset.tip=t,e.removeAttribute(`title`))}function X(e){e.dataset.tip!==void 0&&!e.hasAttribute(`title`)&&(e.setAttribute(`title`,e.dataset.tip),delete e.dataset.tip)}function Ba(e){return e.dataset.tip??e.getAttribute(`title`)??``}function Va(e){return e.isConnected&&e.getClientRects().length>0&&!e.disabled}function Ha(e){try{return e.matches(`:focus-visible`)}catch{return!1}}function Ua(e){return e.dataset.tipSide||(e.closest(`.tcw-sidebar`)?`right`:e.closest(`.tcw-statusbar, .tcw-replay-bar`)?`top`:`bottom`)}var Wa=2,Ga=1.5,Ka=`tcw-ind-legend-values--no-room`,qa=0,Ja=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)Ya(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),Z(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-${++qa}`;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),Z(e.eye,t.visible?this.labels.hide:this.labels.show,t.label),e.settings&&Z(e.settings,this.labels.settings,t.label),e.more&&(Z(e.more,this.labels.more??`More`,t.label),e.more.setAttribute(`aria-haspopup`,`menu`)),Z(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>=Wa;!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;Z(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 Ya(e,t){let n=(parseFloat(getComputedStyle(e).fontSize)||0)*Ga;e.classList.toggle(Ka,t<n)}function Z(e,t,n){e.title=t,e.setAttribute(`aria-label`,n?`${t} ${n}`:t)}function Xa(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 Za(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 Qa=new Map;function $a(e){let t=Qa.get(e);return t||(t=new Intl.NumberFormat(e,{notation:`compact`,maximumFractionDigits:2}),Qa.set(e,t)),t}function eo(e,t=`en-US`){return Math.abs(e)>=1e6?$a(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()}},no=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 ro(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 io=1e-9,ao=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?ro(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=oo(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=so(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 oo(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:io}function so(e){return e>=1e3?`${Number((e/1e3).toFixed(1))}k`:String(Number(e>=1?e.toFixed(2):e.toPrecision(2)))}var co=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??uo)(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??lo(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 lo(e){if(!Number.isFinite(e))return`—`;let t=Math.abs(e);return t>=1e3?e.toFixed(2):t>=1?e.toFixed(4):e.toPrecision(4)}function uo(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)}var fo=[[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]],po=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`),fo.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)}},mo=4e3,ho=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(),mo)):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}},go=`host:`;function _o(e,t){return[...e,...e.length>0&&t.length>0?[`separator`]:[],...t.map((e,t)=>({id:`${go}${t}`,label:e.label,icon:e.icon,danger:e.danger,checked:e.checked}))]}function vo(e,t){return e.startsWith(go)?(t[Number(e.slice(5))]?.onSelect(),!0):!1}var yo=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent),bo={ctrl:`ctrl`,control:`ctrl`,cmd:`ctrl`,command:`ctrl`,meta:`ctrl`,mod:`ctrl`,alt:`alt`,option:`alt`,opt:`alt`,shift:`shift`},xo={esc:`escape`,space:` `,spacebar:` `,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`,del:`delete`,return:`enter`,plus:`+`};function So(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=bo[e.toLowerCase()];if(!t)return null;r[t]=!0}let i=n.toLowerCase();if(bo[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=xo[i]??i,r.shift&&r.key.length===1)return null;return r.display=[...r.ctrl?[yo?`⌘`:`Ctrl`]:[],...r.alt?[`Alt`]:[],...r.shift?[`Shift`]:[],r.key===` `?`Space`:n.length===1?n.toUpperCase():n],r}function Co(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 wo=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 To(e){let t=`${e.ctrl?`ctrl+`:``}${e.alt?`alt+`:``}${e.shift?`shift+`:``}${e.char??e.key}`;return wo.has(t)}function Eo(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 Do=[`#b552c9`,`#1398a8`,`#d4622b`,`#e25592`,`#6f7a8c`,`#3e9a4f`],Oo=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:Aa(this.host.t),way:this.compareWay,compared:this.comparedNow(),onAdd:(e,t)=>{ka(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 Pa(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=Do[this.compares.length%Do.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=ja(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=Ma(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)}},ko=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?O():null,r=new ln({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 Xt(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}),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)||Yt())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()})}},Ao=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 kn(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=Xa(this.host.chart.getIndicatorOutput(r)?.series,null)?.[i];return typeof a==`number`&&Number.isFinite(a)?a:null}},jo=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 Mo(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.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 No=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(Mo({selected:a,canConfigure:!0,canAlert:this.host.chart.canAddDrawingAlert(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=_o(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=>{vo(t,l)||this.runDrawingMenuAction(e,s,t)})}runDrawingMenuAction(e,t,n){switch(n){case`settings`:this.host.openDrawingSettings(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(yi.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=_o(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=>{vo(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()}},Po=2,Fo=2;function Io(e,t=`en-US`){return(0,u.formatPrice)(e,Math.max(Po,(0,d.indicatorValuePrecision)(e)),t)}function Lo(e,t=`en-US`){return`${H((0,u.formatPrice)(Math.abs(e),Fo,t),e,(0,u.formatPrice)(0,Fo,t))}%`}function Ro(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:zo(e,t)}:{values:[],offChartType:!0},pane:null}))}function zo(e,t){return[...e.close===null?[]:[{text:Io(e.close,t),color:null}],...e.change===null?[]:[{text:Lo(e.change,t),color:null}]]}var Bo=7,Vo=17,Ho=3;function Uo(e){return!d.SYMBOL_INDICATOR_IDS.has(e.id)&&e.scale!==`left`}var Wo=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=n===null?e:Math.min(Math.max(n,0),e),i=new Map;for(let e of this.host.chart.getIndicatorPanes())(e.instanceIds??[e.instanceId]).forEach((t,n)=>i.set(t,{...e.rect,row:n}));let a=this.host.settingsState.numberLocale||`en-US`,o=Ro(r>=0?this.host.chart.getCompareValues?.(n===null||!t?void 0:r)??[]:[],a,t),s=this.host.chart.getActiveIndicators().map(e=>{let t=i.get(e.instanceId)??null,r=Xa(this.host.chart.getIndicatorOutput(e.instanceId)?.series,n),o=this.host.chart.getIndicatorStyle(e.instanceId),s=e.visible&&e.offChartType===!0,l=e.visible&&e.shown===!1&&!s,u=l||s?[]:Za(e.descriptor,r,o?.colors??[],o?.plots);return{instanceId:e.instanceId,label:c.r(e,this.host.t),visible:e.visible,offInterval:l,offChartType:s,values:u.map(n=>({text:this.host.indicatorValueText(n.value,t===null&&Uo(e),a),color:n.color})),pane:t?{x:t.x+4,y:t.y+Math.min(Bo+t.row*Vo,Math.max(Bo,t.height-Vo)),width:t.width-8}:null}}),l=[...o,...s],u=this.host.chart.getPlotRect(),d=this.host.chart.getMaximizedPane(),f=e=>l.find(t=>t.instanceId===e)?.label??``,p=this.host.chart.getIndicatorPanes().map(e=>({instanceId:e.instanceId,x:e.rect.x+e.rect.width-4,y:e.rect.y+Ho,label:f(e.instanceId),collapsed:this.host.chart.isPaneCollapsed(e.instanceId),maximized:d===e.instanceId,canMoveUp:this.host.chart.canMovePane(e.instanceId,-1),canMoveDown:this.host.chart.canMovePane(e.instanceId,1)}));this.host.indicatorLegend.update(l,{left:u.x+4,top:this.host.chart.getLegendBottom()+1},p)}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=_o(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=>{vo(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)}},Go=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=Cn();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}}},Ko=0,qo=class{backdrop;search;listEl;layouts=[];confirming=null;returnFocus=null;loadSeq=0;uid=++Ko;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()}}},Jo=5,Yo=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 oa(n,r),this.dialog=new qo(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,Jo)}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()}},Xo=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Zo=globalThis.Buffer;function Qo(e){if(Zo)return Zo.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 $o(e){if(Zo)return Zo.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 ts(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function ns(e){return es(Qo(JSON.stringify(e)))}function rs(e){if(!e)return null;try{let t=$o(ts(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:ua.find(e=>e===n.scaleMode)??`regular`,indicators:Array.isArray(n.indicators)?n.indicators:[],drawings:Array.isArray(n.drawings)?n.drawings:[],...Xo(n.settings)?{settings:F(n.settings,Er)}:{}}}catch{return null}}var is=`tcw`;function as(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)!==is))try{return decodeURIComponent(e.slice(t+1))}catch{return null}}return null}function os(e,t){let[n]=e.split(`#`);return`${n}#${is}=${t}`}var ss=[`legendVisible`,`volumeVisible`,`barCountdown`,`indicatorValueLabels`,`alignAxisLabels`],cs=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=as(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=Br(n,{...t.h,...Object.fromEntries(ss.map(e=>[e,this.host.settingsDefaults[e]]))});return ns({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=rs(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,...F(t.settings,Er)}),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=os(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?ma(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:Rr(e,Tr)}}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,...F(e.settings,Tr)});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=pa(ma(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 Yo(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}=q(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}}},ls={alerts:`alerts`,objectTree:`objectTree`,dataWindow:`dataWindow`,symbolInfo:`symbolInfo`,depthLadder:`depthLadder`},us={alerts:`alerts`,objectTree:`objects`,symbolInfo:`symbolInfo`,depthLadder:`trade`},ds=class{constructor(e){this.host=e}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[ls[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)?.series?.[e]??null,r=!o.has(t.instanceId)&&Uo(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`)}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()})}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(`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=us[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||hr(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)}},fs=new Set([`timezone`,`numberLocale`,`chartTypeOptions`,`logScale`,`autoScale`]),ps=80,ms=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function hs(e){return F(e,fs)}function gs(e){let{overrides:n}=(0,u.readChartStyleOverrides)(e);return Object.fromEntries(Object.entries(n).filter(([e,n])=>n!==null&&t.l.includes(e)))}function _s(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var vs=class{constructor(e=`tcw:chart-templates`,t=_s()){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)!ms(n)||typeof n.name!=`string`||!n.name.trim()||t.push({name:n.name.slice(0,ps).trim(),settings:hs(n.settings),style:gs(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,ps).trim();if(!r||!this.storage)return!1;let i=[...this.list().filter(e=>e.name!==r),{name:r,settings:hs(t),style:gs(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{}}},ys=new Set([...Cr,`autoScale`]),bs=class{constructor(e){this.host=e}chartTemplates=new vs;chartTemplatePrompt=null;settingsEdit=null;state=it(t.h);dialogChanging=0;get settingsState(){return this.state.peek()}set settingsState(e){this.state.set(e)}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 oa(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(F(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(F({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?.(),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:Ar(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=>!ys.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.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())}},xs=13;function Ss(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 Cs=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=Ss(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:s.x+i.x,y:s.y+i.y,width:s.width,height:s.height},bounds:{x:o.x+i.x,y:o.y+i.y,width:o.width,height:o.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})}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;if(!n||!r||n.locked||!t&&!this.host.chart.beginDrawingEdit(e))return!1;let i=z[n.type],a=n.style,o=a.text??``,s=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=this.host.chart.getDrawingTextRect(e);if(!t)return null;let n=this.host.chartContainer.getBoundingClientRect();return{x:n.left+t.x,y:n.top+t.y,width:t.width,height:t.height}},text:o,font:{size:a.fontSize||i?.fontSize||xs,bold:a.bold===!0,italic:a.italic===!0,family:this.host.chart.getFont?.()?.family??this.host.ui.font.family},color:a.textColor??li[n.type]??a.color,label:this.host.t(`drawingSettings.text`),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+$/,``);r&&r!==n&&(t?this.host.chart.amendNewDrawing(e,{style:{text:r}}):this.host.chart.updateDrawing(e,{style:{text:r}})),s(r.length>0)},onCancel:()=>s(!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:z[r.type],textColor:li[r.type],textPlace:ci.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 oa(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()}))}})}},ws=200,Ts=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(-ws).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()}},Es=600,Ds=24,Os=[`--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`],ks=48,As=5e4,js=100;function Ms(){return new Promise(e=>{if(typeof requestAnimationFrame!=`function`||document.hidden){setTimeout(e,0);return}let t=setTimeout(e,js);requestAnimationFrame(()=>setTimeout(()=>{clearTimeout(t),e()},0))})}var Ns=864e5,Ps=5e3,Fs=2e3,Is=48,Ls=`rgba(255,255,255,0.03)`,Rs=`rgba(0,0,0,0.03)`,zs=2;function Bs(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 Vs=1e3,Hs=[[`barCountdown`,`barCountdown`],[`logScale`,`logScale`],[`legendVisible`,`legend`],[`volumeVisible`,`volume`]],Us=t.l.filter(e=>u.CHART_STYLE_KEYS[e]!==`color`);function Ws(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 Gs=class{intervals=new Ts(this.intervalsHost());drawingEdit=new Cs(this.drawingEditHost());chartSettings=new bs(this.chartSettingsHost());docking=new ds(this.dockingHost());layouts=new cs(this.layoutsHost());commands=new Go(this.commandsHost());legend=new Wo(this.legendHost());menus=new No(this.menusHost());trading=new jo(this.tradingHost());alerting=new Ao(this.alertingHost());watching=new ko(this.watchingHost());comparing=new Oo(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 la;templatePrompt=null;markerTip=null;dataWindow=null;lastHoverIndex=null;lastHoverBar=null;lastHoverPrevClose=null;legendHoverIndex=null;pointerOnChart=!1;favoritesStore=new ga;indicatorFavorites=new ga(`tcw:indicator-favorites`);indicatorDefaults=new br;timeframeFavorites=new ga(`tcw:tf-favorites`);customTimeframes=new ga(`tcw:tf-custom`);timeframes=[];sessionRefPrice=null;symbolInfoPanel=null;news=new gn;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;constructor(e,t={}){let n=Ws(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}:{},...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=Vr(e.persistSettings);o&&(this.chartSettings.settingsStore=new Ur(o));let c=this.resolveIsDark(e.theme),l=this.resolveTheme(e.theme);this.themeOf={...this.themeOf,[c?`dark`:`light`]:l};let d={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=d.priceAxisAddButton===!0;let f={...d,priceAxisAddButton:this.priceAxisAddDefault&&this.featureState[`menu.priceAxisAdd`]};if(this.canExport=d.dataExport!==!1,this.chartSettings.settingsLocked=new Set(Hs.filter(([,e])=>d[e]===!1).map(([e])=>e)),this.chartSettings.settingsDefaults={...this.chartSettings.settingsState,legendVisible:d.legend!==!1,volumeVisible:d.volume!==!1,barCountdown:d.barCountdown!==!1,indicatorValueLabels:d.indicatorValueLabels===!0,alignAxisLabels:d.alignAxisLabels!==!1},this.chartSettings.settingsState={...this.chartSettings.settingsDefaults},this.timeframes=De(xe(e.timeframes,d.timeframes),this.customTimeframes.list(),d.timeframes),!this.timeframes.some(e=>this.timeframeFavorites.has(e))){let t=Se(this.timeframes,d.defaultTimeframeFavorites,!!e.timeframes?.length);for(let e of t)this.timeframeFavorites.add(e)}let p=e.timeframe??`5m`,m=!d.timeframes?.length||d.timeframes.includes(p)?p:this.timeframes[0]??p;return this.state={symbol:e.symbol??this.symbols[0]??`BTCUSDT`,timeframe:m,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:d,chartFeatures:f}}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:ec(t.locale)?`rtl`:`ltr`;this.root.dir=i,this.portal.dir=i,e.appendChild(this.root),this.tooltip=new Ra(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=_a([this.root,this.portal]),this.stopNarrow=va(this.root,e=>{this.toolbar?.fit(),e||this.sidebar?.closeOverlay(),this.docking.syncRail()}),this.ui=P(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(),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 bt(i,{drawingToolGroups:t.n(t._,this.t),favorites:this.favoritesStore.list(),shortcuts:Cn()},{onDrawingTool:e=>this.handleDrawingTool(e),onCancelDrawing:()=>this.handleCancelDrawing(),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.chartContainer=document.createElement(`div`),this.chartContainer.className=`tcw-chart-container`,this.chartContainer.dir=`ltr`,i.appendChild(this.chartContainer),this.loading=new po(this.chartContainer,this.t(`status.loading`)),this.historyPill=new ho(this.chartContainer,{loading:this.t(`history.loading`),failed:this.t(`history.failed`)}),this.docking.dock=new Ea(i,{labels:{rail:this.t(`dock.rail`),resize:this.t(`dock.resize`)},savedWidth:()=>Qs(),saveWidth:e=>$s(e),railShown:()=>this.docking.railShown(),focusAfterClose:e=>this.docking.panelFocusTarget(e),room:()=>i.clientWidth}),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.c(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 On(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 un(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=()=>{Yt()||this.refreshMarket()},document.addEventListener(`visibilitychange`,this.onPageShown),this.dragDrop=new e.o(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 At(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(()=>{!Yt()&&this.featureState.statusBar&&this.featureState[`statusBar.clock`]&&this.statusBar?.tick()},Vs),this.chart.on(`priceRangeChange`,()=>this.chartSettings.refreshScaleSwitches()),this.chartSettings.refreshScaleSwitches(),this.goToDatePart=this.lazyPart(K.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(K.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(K.symbolSearch,({WidgetSymbolSearch:e})=>new e({onPick:e=>{this.setSymbol(e)},onClose:()=>{}},this.overlayHost,this.t)),this.hotkeySheetPart=this.lazyPart(K.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 Ja(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:4+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 qt(this.replayHost()),this.replay.attach();for(let e of[`resize`,`dataUpdate`,`symbolInfoChange`])this.chart.on(e,()=>this.placeDrawingButton());this.placeDrawingButton(),this.dataWindow=new co(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(`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 Jr,t=new Yr;for(let[e,n]of Object.entries(t.all()))this.chart.setDrawingToolDefaults(e,n??null);this.drawingSettingsPart=this.lazyPart(K.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=>q(e*(0,u.barTimeUnit)(this.chart.getData()),this.displayTimezone()),fromWallTime:(e,t)=>{let n=Ca(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 _i(this.overlayHost),this.chart.on(`drawingDoubleClick`,e=>{let t=e.payload.id,n=this.chart.getDrawings().find(e=>e.id===t)?.type;n&&z[n]&&this.drawingEdit.editTextInPlace(t,!1)||this.drawingEdit.openDrawingSettings(t,n&&z[n]?{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||!z[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,Es),this.drawingEdit.cancelTextPrompt=a}),this.drawingStyle=new $r(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 oi(this.root,{onStyle:e=>{for(let t of this.chart.getSelectedDrawingIds()){let n=this.chart.getDrawings().find(e=>e.id===t)?.type,r=n?z[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)},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(Oi(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(Si(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 ca(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 ta(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 Vi(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}=q(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 ao(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 Ln(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}=q(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 no(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(K.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(K.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 fr(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(K.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:()=>Ys(),add:e=>Xs([e,...Ys().filter(t=>t!==e)])})),this.boundGlobalKeydown=e=>{if(this.handleHostHotkey(e)||this.featureState.hotkeys&&this.replay.isOpen()&&this.replay.handleReplayKey(e))return;let t=T(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||E()||!T(this.root,!0))return;e.preventDefault(),this.layouts.saveLayout()}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&Sn[e.code]){if(e.defaultPrevented||E()||!t||D()||!n(`hotkeys.tools`))return;e.preventDefault(),this.handleDrawingTool(Sn[e.code])}else if(/^[0-9]$/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(e.defaultPrevented||!this.intervals.intervalInput||!n(`intervalTyping`)||E()||D()||!T(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(Bs(e)!==null){if(e.defaultPrevented||!n(`symbolTyping`)||!this.featureState.symbolSearch||E()||D()||!T(this.root,!0))return;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t))return;e.preventDefault(),this.openSymbolSearch(Bs(e))}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&(e.code===`KeyI`||e.code===`KeyG`||e.code===`KeyR`)){if(E()||!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(E()||!t||!n(`hotkeys.help`)||!this.featureState.hotkeySheet)return;e.preventDefault(),this.openHotkeySheet()}},document.addEventListener(`keydown`,this.boundGlobalKeydown),document.addEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys=Nt(this.root,[this.portal])}finishSetup(e){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||ba()},t=globalThis;if(t.requestIdleCallback&&t.cancelIdleCallback){let n=t.requestIdleCallback(e,{timeout:Ps}),r=t.cancelIdleCallback;this.stopPreload=()=>r(n)}else{let t=setTimeout(e,Fs);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)}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(Yt())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.refreshSymbolInfo()}refreshSymbolInfo(){let e=this.symbolInfoPanel;!e?.isOpen()||this.destroyed||e.render(this.symbolInfoView())}symbolInfoView(){let e=this.state.symbol;return hn({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.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=P(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?Jn(e):1}applyLookTokens(){let e=Yn(this.ui,this.uiScale);for(let t of[this.root,this.portal]){if(dr(t,e,{variables:this.uiVariables}),this.uiVariables)continue;let n=ur(e);for(let e of Os)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?Jn(t-Ds):Jn(t+Ds))===this.uiScale)return}this.uiScale=e,this.applyLookTokens(),this.applyLegendFont(),this.applyChartLook(),this.toolbar?.fit()}}getUI(){return P({...this.ui})}applyLegendFont(){this.chart.setLegend({fontFamily:this.ui.font.mono,fontSize:A(Math.round(this.ui.font.size*this.uiScale),-1)})}applyChartLook(){let e=this.options.chartOptions;e?.barLayout||this.chart.setBarLayout(this.ui.density===`compact`?`classic`:`golden`);let t=this.scaledChartSizes();e?.font?.family?Object.keys(t).length>0&&this.chart.setFont(t):this.chart.setFont({family:this.ui.font.mono,...e?.font?.textFamily?{}:{textFamily:this.ui.font.family},...t})}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(`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=So(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;To(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||E()||Eo(e)||D())return!1;let t=this.hostHotkeys.find(t=>Co(e,t.parsed));if(!t)return!1;let n=!t.parsed.ctrl&&!t.parsed.alt;if(!T(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:Is,color:this.state.isDark?Ls:Rs})}keepingLook(e){this.chartSettings.settingsEdit&&this.settings?.close();let t=this.chart.getOverrides?.({layer:`user`})??{},n=Object.fromEntries(Us.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(_o([],i),a,e=>vo(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}=q(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=>q(e*r,n),a=t[t.length-1].time,o=this.chart.getVisibleTimeRange()??{from:t[0].time,to:a},s=q(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)>=Ns),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=Ca(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=Ca(e.from.date,e.from.time,n),a=Ca(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}=q(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 oa(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>=ks||this.baseSeries.length>=As;try{if(t&&(this.loading.begin(this.chart.getData().length>0,!0),await Ms(),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:Ks(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()),zs))}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):eo(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 ya(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()}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.statusBar?.update({connectionState:this.state.connectionState,message:this.state.connectionMessage,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),symbolSearchFn:(...t)=>e.symbolSearchFn(...t),get symbols(){return e.symbols},get t(){return e.t},withSymbolSearch:(...t)=>e.withSymbolSearch(...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),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 Ks(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 qs=`tcw:recentCommands`,Js=10;function Ys(){try{let e=JSON.parse(O()?.getItem(qs)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`).slice(0,Js):[]}catch{return[]}}function Xs(e){try{O()?.setItem(qs,JSON.stringify(e.slice(0,Js)))}catch{}}var Zs=`tcw:dockWidth`;function Qs(){try{let e=Number(O()?.getItem(Zs)??NaN);return Number.isFinite(e)&&e>0?e:null}catch{return null}}function $s(e){try{O()?.setItem(Zs,String(e))}catch{}}function ec(e){return!!e&&/^(ar|he|iw|fa|ur|ps|yi|dv|ckb|sd|ug)(-|$)/i.test(e)}var tc={symbol:!1,interval:!1,crosshair:!0,time:!1,drawings:!1,replay:!1},nc=[`symbol`,`interval`,`crosshair`,`time`,`drawings`,`replay`],Q={"1x1":{cols:1,rows:1},"1x2":{cols:2,rows:1},"2x1":{cols:1,rows:2},"2x2":{cols:2,rows:2},"1x3":{cols:3,rows:1},"3x1":{cols:1,rows:3},"2x3":{cols:3,rows:2},"3x2":{cols:2,rows:3}};function $(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call(Q,e)}function rc(e){return JSON.parse(JSON.stringify(e))}function ic(e,t,n=16){let r=(20-2*(e-1))/e,i=(20-2*(t-1))/t,a=``;for(let n=0;n<t;n++)for(let t=0;t<e;t++)a+=`<rect x="${2+t*(r+2)}" y="${2+n*(i+2)}" width="${r}" height="${i}" rx="1"/>`;return`<svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" aria-hidden="true">${a}</svg>`}function ac(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||t.kind!==`grid`||!$(t.layout)||!Array.isArray(t.cells))return null;let n=t.cells.map(pa);if(n.some(e=>e===null))return null;let r=typeof t.sync==`object`&&t.sync!==null?t.sync:{},i={...tc};for(let e of nc)typeof r[e]==`boolean`&&(i[e]=r[e]);let a=typeof t.active==`number`&&Number.isInteger(t.active)?t.active:0;return{v:1,kind:`grid`,layout:t.layout,sync:i,active:a,cells:n}}var oc=class{root;cellsEl;cells=[];layout;sync;active=0;hovered=null;relayDepth=0;uiTheme=null;styleOverrides={};featureSwitches={};parked=new Map;drawingFrame=0;drawingSource=null;layoutButtons=new Map;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||E()||!T(this.root,!0)||(e.preventDefault(),this.layoutsUI.save())};constructor(e,t={}){this.options=t,this.layout=$(t.layout)?t.layout:`1x2`,this.sync={...tc,...t.sync},this.t=s.n(s.o(t.widget?.locale,t.widget?.messages)),fe(),this.root=document.createElement(`div`),this.root.className=`tcw-root tcw-grid`,this.root.dataset.tcwTheme=t.widget?.theme===`light`?`light`:`dark`,dr(this.root,P(t.widget?.ui),{variables:t.widget?.ui!==void 0}),t.bar!==!1&&this.root.appendChild(this.buildBar()),this.cellsEl=document.createElement(`div`),this.cellsEl.className=`tcw-grid-cells`,this.root.appendChild(this.cellsEl),e.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 n=this.cells[0]?.el.querySelector(`.tcw-root`)?.dataset.tcwTheme;n&&(this.root.dataset.tcwTheme=n),t.layouts!==!1&&this.setupLayouts(t.layouts===!0||t.layouts===void 0?{}:t.layouts),this.unregisterKeys=Nt(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(e){if(e===this.layout||!$(e))return;this.layout=e;let t=this.shapeCount();for(;this.cells.length>t;){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<t;e++){let t=this.createCell(e);this.cells.push(t),this.unpark(e,t)}this.active>=t&&(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=P(e);dr(this.root,t);for(let e of this.cells)e.widget.setUI(t);this.uiTheme=t}getUI(){return P(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=ac(ma(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();for(let e of this.cells)this.destroyCell(e);this.cells=[],this.root.remove(),pe()}}shapeCount(){let{cols:e,rows:t}=Q[this.layout];return e*t}applyShape(){let{cols:e,rows:t}=Q[this.layout];this.cellsEl.style.gridTemplateColumns=`repeat(${e}, minmax(0, 1fr))`,this.cellsEl.style.gridTemplateRows=`repeat(${t}, minmax(0, 1fr))`}createCell(e){let t=document.createElement(`div`);t.className=`tcw-grid-cell`,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,s.r(this.t(`grid.chart`),{n:e+1})),this.cellsEl.appendChild(t);let n=this.options.widget??{},r=this.options.cells?.[e]??{},i=this.cells[this.active]?.widget,a={},o=new Gs(t,{...n,...r,...r.adapter?{feed:void 0}:{},...r.feed?{adapter:void 0}:{},...i&&this.sync.symbol?{symbol:i.getSymbol()}:{},...i&&this.sync.interval?{timeframe:i.getTimeframe()}:{},...this.options.adapter&&!r.adapter&&!r.feed&&!n.feed?{adapter:this.options.adapter(e)}:{},...this.uiTheme?{ui:this.uiTheme}:{},layouts:!1,...r.persistSettings===void 0&&n.persistSettings?{persistSettings:{key:`${Vr(n.persistSettings)}:${e}`}}:{},features:{dock:!1,...n.features,...r.features},onSymbolChange:e=>{r.onSymbolChange?.(e),n.onSymbolChange?.(e),this.sync.symbol&&this.relay(a,t=>void t.setSymbol(e)),this.renderTabs(),this.session?.changed()},onTimeframeChange:e=>{r.onTimeframeChange?.(e),n.onTimeframeChange?.(e),this.sync.interval&&this.relay(a,t=>void t.setTimeframe(e)),this.renderTabs(),this.session?.changed()}});return a.el=t,a.widget=o,Object.keys(this.styleOverrides).length>0&&o.getChart().applyOverrides(this.styleOverrides),Object.keys(this.featureSwitches).length>0&&o.setFeatures(this.featureSwitches),this.wireCell(a),t.addEventListener(`pointerdown`,()=>this.setActive(this.cells.indexOf(a)),!0),t.addEventListener(`pointerenter`,()=>{this.hovered=a}),t.addEventListener(`pointerleave`,()=>{this.hovered===a&&(this.hovered=null)}),this.options.onChartAdd?.(o,e),a}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=sc(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(rc(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(rc(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 e=document.createElement(`div`);e.className=`tcw-grid-bar`,e.setAttribute(`role`,`toolbar`),e.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`)),e.appendChild(this.tabsEl);let t=document.createElement(`div`);t.className=`tcw-grid-group`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,this.t(`grid.layout`));let n=this.options.layoutChoices?.filter($)??Object.keys(Q);for(let e of n){let{cols:n,rows:r}=Q[e],i=n*r===1?this.t(`grid.single`):s.r(this.t(`grid.layoutOption`),{count:n*r,cols:n,rows:r}),a=document.createElement(`button`);a.type=`button`,a.className=`tcw-btn-icon`,a.title=i,a.setAttribute(`aria-label`,i),a.innerHTML=ic(n,r),a.addEventListener(`click`,()=>this.setLayout(e)),this.layoutButtons.set(e,a),t.appendChild(a)}let r=document.createElement(`div`);r.className=`tcw-grid-group`,r.setAttribute(`role`,`group`),r.setAttribute(`aria-label`,this.t(`grid.sync`));let o=document.createElement(`span`);o.className=`tcw-grid-label`,o.innerHTML=`${i.i(`link`,13)}<span>${a.u(this.t(`grid.sync`))}</span>`,r.appendChild(o);for(let e of nc){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),r.appendChild(t)}let c=document.createElement(`span`);return c.className=`tcw-toolbar-spacer`,e.append(t,this.sep(),r,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)}),e.appendChild(this.layoutsButton)),this.renderBar(),e}sep(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-sep`,e}renderBar(){for(let[e,t]of this.layoutButtons){let n=e===this.layout;t.classList.toggle(`tcw-active`,n),t.setAttribute(`aria-pressed`,String(n))}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 Yo(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=q(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 sc(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=Gs,exports.ChartWidgetGrid=oc,exports.DEFAULT_GRID_SYNC=tc,Object.defineProperty(exports,`DRAWING_TOOL_ICONS`,{enumerable:!0,get:function(){return u.DRAWING_TOOL_ICONS}}),exports.EN_MESSAGES=s.c,exports.GRID_SHAPES=Q,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=ir,exports.applyWidgetUI=dr,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=ac,exports.readWatchlists=sn,exports.readWidgetLayout=pa,exports.registerWidgetLocale=s.a,exports.resolveWidgetUI=P,exports.widgetUIVariables=ur;
|
|
7851
7811
|
//# sourceMappingURL=index.cjs.map
|