@tradecanvas/chart 1.72.1 → 1.73.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.
Files changed (34) hide show
  1. package/dist/{LayoutSession-DO4bYkUi.cjs → LayoutSession-CrWT8XA4.cjs} +2 -2
  2. package/dist/{LayoutSession-DO4bYkUi.cjs.map → LayoutSession-CrWT8XA4.cjs.map} +1 -1
  3. package/dist/{LayoutSession-qRYG8GTD.js → LayoutSession-DbuO28Ev.js} +2 -2
  4. package/dist/{LayoutSession-qRYG8GTD.js.map → LayoutSession-DbuO28Ev.js.map} +1 -1
  5. package/dist/{WidgetSettings-eOo93L7Z.js → WidgetSettings--XzDx515.js} +21 -8
  6. package/dist/WidgetSettings--XzDx515.js.map +1 -0
  7. package/dist/WidgetSettings-C0fnWGdY.cjs +2 -0
  8. package/dist/WidgetSettings-C0fnWGdY.cjs.map +1 -0
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.js +1 -1
  11. package/dist/widget/ChartWidget.d.ts +37 -3
  12. package/dist/widget/ChartWidget.d.ts.map +1 -1
  13. package/dist/widget/WidgetChartSettings.d.ts +19 -2
  14. package/dist/widget/WidgetChartSettings.d.ts.map +1 -1
  15. package/dist/widget/WidgetCommands.d.ts.map +1 -1
  16. package/dist/widget/WidgetDockArea.d.ts +1 -0
  17. package/dist/widget/WidgetDockArea.d.ts.map +1 -1
  18. package/dist/widget/WidgetDrawingSidebar.d.ts +2 -0
  19. package/dist/widget/WidgetDrawingSidebar.d.ts.map +1 -1
  20. package/dist/widget/WidgetLayouts.d.ts.map +1 -1
  21. package/dist/widget/WidgetSettings.d.ts +2 -0
  22. package/dist/widget/WidgetSettings.d.ts.map +1 -1
  23. package/dist/widget/index.cjs +131 -65
  24. package/dist/widget/index.cjs.map +1 -1
  25. package/dist/widget/index.js +1593 -1468
  26. package/dist/widget/index.js.map +1 -1
  27. package/dist/widget/toolFit.d.ts +26 -0
  28. package/dist/widget/toolFit.d.ts.map +1 -0
  29. package/dist/widget/widgetUI.d.ts +12 -6
  30. package/dist/widget/widgetUI.d.ts.map +1 -1
  31. package/package.json +3 -3
  32. package/dist/WidgetSettings-D7Pq42zW.cjs +0 -2
  33. package/dist/WidgetSettings-D7Pq42zW.cjs.map +0 -1
  34. package/dist/WidgetSettings-eOo93L7Z.js.map +0 -1
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../LayoutSession-DO4bYkUi.cjs`),t=require(`../widgetLocales-BPK5i0Ok.cjs`),n=require(`../monthView-B-CieFDJ.cjs`),r=require(`../widgetFeatures-BZ8OVPN2.cjs`),i=require(`../focusTrap-DrhhmG0V.cjs`),a=require(`../symbolCatalog-Dx1YnZgm.cjs`),o=require(`../settingsControls-Tn8_vJJv.cjs`),s=require(`../i18n-C2nQBZTY.cjs`),c=require(`../indicatorInputWords-CTA4IcJR.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})))}},b=()=>typeof matchMedia==`function`&&matchMedia(`(pointer: coarse)`).matches,x=()=>typeof CSS>`u`||typeof CSS.supports!=`function`||CSS.supports(`selector(::-webkit-calendar-picker-indicator)`);function S(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 C(e){return!(e instanceof HTMLInputElement)||e.type!==`date`||e.dataset.tcwCalendar===`inline`||e.matches(`:disabled`)||e.readOnly?null:e}function te(e,t){let n=new y(t.layer),r=new ee(t.layer,t.labels,t.locale),i=t.native??b,a=t.calendar??x,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=S(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=C(e.target);t&&(e.preventDefault(),r.isOpenFor(t)||r.open(t))},u=e=>{if(i()||!s(e))return;let t=S(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=C(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 ne=`/* === TradeCanvas Widget — Premium Styles === */
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../LayoutSession-CrWT8XA4.cjs`),t=require(`../widgetLocales-BPK5i0Ok.cjs`),n=require(`../monthView-B-CieFDJ.cjs`),r=require(`../widgetFeatures-BZ8OVPN2.cjs`),i=require(`../focusTrap-DrhhmG0V.cjs`),a=require(`../symbolCatalog-Dx1YnZgm.cjs`),o=require(`../settingsControls-Tn8_vJJv.cjs`),s=require(`../i18n-C2nQBZTY.cjs`),c=require(`../indicatorInputWords-CTA4IcJR.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,
@@ -161,7 +161,9 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
161
161
  --tcw-control-h: 26px;
162
162
  --tcw-control-h-sm: 20px;
163
163
  --tcw-icon: 16px;
164
- --tcw-sidebar-w: 42px;
164
+ --tcw-sidebar-w: 53px;
165
+ --tcw-tool-h: 33px;
166
+ --tcw-tool-icon: 20px;
165
167
  --tcw-menu-item-h: 33px;
166
168
  --tcw-font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
167
169
  --tcw-font-size: 13px;
@@ -1177,6 +1179,15 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
1177
1179
 
1178
1180
  /* === Sidebar === */
1179
1181
 
1182
+ /* The drawing tools' button and icon as drawn (the dock's rail has the same): never wider than
1183
+ their column less 6 px a side (a narrow \`sizes.sidebar\` of yours shrinks them), nor taller
1184
+ than a short column leaves room for (\`--tcw-tool-fit\`, set by toolFit.ts on the column); the
1185
+ icon at most four fifths of its button, as a compact look's 16 in 20. */
1186
+ .tcw-root, .tcw-sidebar {
1187
+ --tcw-tool-size: min(var(--tcw-tool-h), calc(var(--tcw-sidebar-w) - 12px), var(--tcw-tool-fit, 999px));
1188
+ --tcw-tool-icon-size: min(var(--tcw-tool-icon), calc(var(--tcw-tool-size) * 0.8));
1189
+ }
1190
+
1180
1191
  .tcw-sidebar {
1181
1192
  width: var(--tcw-sidebar-w);
1182
1193
  flex-shrink: 0;
@@ -1202,12 +1213,19 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
1202
1213
 
1203
1214
  .tcw-tool-group-wrap {
1204
1215
  position: relative;
1216
+ /* The column's width, its button centred: the pointer on its way to the menu, which opens at
1217
+ the column's edge, stays over the group the whole way. */
1218
+ align-self: stretch;
1219
+ display: flex;
1220
+ justify-content: center;
1205
1221
  }
1206
1222
 
1207
1223
  .tcw-sidebar-btn {
1208
- width: var(--tcw-control-h);
1209
- height: var(--tcw-control-h);
1224
+ width: var(--tcw-tool-size);
1225
+ height: var(--tcw-tool-size);
1210
1226
  margin: 1px 0;
1227
+ /* The browser's button padding squeezed a glyph set straight in it (the cursor's) under its size. */
1228
+ padding: 0;
1211
1229
  display: flex;
1212
1230
  align-items: center;
1213
1231
  justify-content: center;
@@ -1226,8 +1244,9 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
1226
1244
  }
1227
1245
 
1228
1246
  .tcw-sidebar-btn svg {
1229
- width: var(--tcw-icon);
1230
- height: var(--tcw-icon);
1247
+ flex: none;
1248
+ width: var(--tcw-tool-icon-size);
1249
+ height: var(--tcw-tool-icon-size);
1231
1250
  }
1232
1251
 
1233
1252
  .tcw-sidebar-btn:hover {
@@ -1260,7 +1279,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
1260
1279
  /* The drawing tools' sections: always a hairline (it groups the tools), even in
1261
1280
  looks that drop the rules between toolbar groups. */
1262
1281
  .tcw-sidebar-divider {
1263
- width: 20px;
1282
+ width: calc(var(--tcw-tool-size) * 0.618);
1264
1283
  height: max(1px, var(--tcw-sep-w));
1265
1284
  background: var(--tcw-divider);
1266
1285
  margin: 5px 0;
@@ -1275,7 +1294,6 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
1275
1294
 
1276
1295
  .tcw-flyout {
1277
1296
  position: absolute;
1278
- margin-inline-start: 6px;
1279
1297
  overflow-y: auto;
1280
1298
  overscroll-behavior: contain;
1281
1299
  min-width: 180px;
@@ -1460,9 +1478,18 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
1460
1478
  letter-spacing: -0.015em;
1461
1479
  }
1462
1480
 
1481
+ /* The close sized from the title, so it holds its own beside it in every look: its target phi times
1482
+ the title (34 at 21), its icon root phi of it (27), whose cross, half the icon's grid, is about the
1483
+ title's capitals, its stroke near 2 px. At 16 the cross was 8 px of 1.2 px lines under a 21 px title.
1484
+ The negative margins keep the header as tall as before and the cross's edge at the text's edge. */
1463
1485
  .tcw-modal-close {
1464
- width: var(--tcw-control-h-sm);
1465
- height: var(--tcw-control-h-sm);
1486
+ --tcw-close-box: calc(var(--tcw-font-size-display) * 1.618);
1487
+ --tcw-close-icon: calc(var(--tcw-font-size-display) * 1.272);
1488
+ flex: none;
1489
+ width: var(--tcw-close-box);
1490
+ height: var(--tcw-close-box);
1491
+ margin-block: calc((var(--tcw-close-box) - var(--tcw-font-size-display) * 1.2) / -2);
1492
+ margin-inline-end: calc((var(--tcw-close-box) - var(--tcw-close-icon) / 2) / -2);
1466
1493
  display: flex;
1467
1494
  align-items: center;
1468
1495
  justify-content: center;
@@ -1479,6 +1506,16 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
1479
1506
  color: var(--tcw-text);
1480
1507
  }
1481
1508
 
1509
+ .tcw-modal-close:focus-visible {
1510
+ outline: none;
1511
+ box-shadow: var(--tcw-ring);
1512
+ }
1513
+
1514
+ .tcw-modal-close svg {
1515
+ width: var(--tcw-close-icon);
1516
+ height: var(--tcw-close-icon);
1517
+ }
1518
+
1482
1519
  .tcw-modal-tabs {
1483
1520
  display: flex;
1484
1521
  /* Four tabs in a long language on a phone: they wrap rather than clip. No overflow here: in the
@@ -2537,8 +2574,8 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
2537
2574
  width: max(44px, var(--tcw-sidebar-w));
2538
2575
  }
2539
2576
  .tcw-sidebar-btn {
2540
- width: max(40px, var(--tcw-control-h));
2541
- height: max(40px, var(--tcw-control-h));
2577
+ width: max(40px, var(--tcw-tool-size));
2578
+ height: max(40px, var(--tcw-tool-size));
2542
2579
  }
2543
2580
  .tcw-modal {
2544
2581
  width: 94vw;
@@ -4867,7 +4904,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
4867
4904
  min-height: 44px;
4868
4905
  }
4869
4906
  }
4870
- `,w=`/* === Base controls: fields, selects, checks, sliders, calendar, scrollbars ===
4907
+ `,se=`/* === Base controls: fields, selects, checks, sliders, calendar, scrollbars ===
4871
4908
  *
4872
4909
  * One look for every form control in the widget, from tokens. Fields are
4873
4910
  * quiet until used: a faint fill and hairline, a firmer line on hover, and
@@ -5541,7 +5578,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
5541
5578
  .tcw-stepper-btn:focus-visible { outline: 2px solid Highlight; outline-offset: -2px; }
5542
5579
  .tcw-stepper:focus-within { outline: 2px solid Highlight; }
5543
5580
  }
5544
- `,re=`/* === The indicators dialog === */
5581
+ `,ce=`/* === The indicators dialog === */
5545
5582
 
5546
5583
  /* 610 wide, a Fibonacci number: the groups take 233 and the list 377 beside them (377 : 233 = phi).
5547
5584
  A fixed height, so the dialog keeps still while a search shortens the list. */
@@ -5552,31 +5589,38 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
5552
5589
  max-height: none;
5553
5590
  }
5554
5591
 
5592
+ /* A dialog's search is a band across it, under its title, with a rule beneath: no box, no ring when
5593
+ focused. The caret and the dialog itself say where typing goes; a lit box around the one field a
5594
+ search dialog has only shouted it. As tall as the field and its margins were, set in as the title. */
5555
5595
  .tcw-ip-search,
5556
5596
  .tcw-ss-search {
5557
5597
  display: flex;
5558
5598
  align-items: center;
5559
- gap: var(--tcw-space-3);
5599
+ gap: var(--tcw-space-4);
5560
5600
  flex: none;
5561
- height: var(--tcw-control-h);
5562
- margin: var(--tcw-space-4) var(--tcw-space-6);
5563
- padding: 0 var(--tcw-space-4);
5564
- border: var(--tcw-border-w) solid var(--tcw-border);
5565
- border-radius: var(--tcw-input-radius);
5566
- background: var(--tcw-bg);
5601
+ height: calc(var(--tcw-control-h) + 2 * var(--tcw-space-4));
5602
+ margin: 0;
5603
+ padding: 0 var(--tcw-space-6);
5604
+ border: none;
5605
+ border-bottom: 1px solid var(--tcw-divider);
5606
+ border-radius: 0;
5607
+ background: transparent;
5567
5608
  color: var(--tcw-text-muted);
5568
- transition: border-color var(--tcw-dur-fast) var(--tcw-ease), box-shadow var(--tcw-dur-fast) var(--tcw-ease);
5609
+ transition: color var(--tcw-dur-fast) var(--tcw-ease);
5569
5610
  }
5570
5611
 
5612
+ /* Focused, only the magnifier takes the text's colour. */
5571
5613
  .tcw-ip-search:focus-within,
5572
5614
  .tcw-ss-search:focus-within {
5573
- border-color: var(--tcw-accent);
5574
- box-shadow: var(--tcw-ring);
5615
+ color: var(--tcw-text);
5575
5616
  }
5576
5617
 
5618
+ /* The magnifier root phi of the typed text (19 at 15), as the close is of the title. */
5577
5619
  .tcw-ip-search svg,
5578
5620
  .tcw-ss-search svg {
5579
5621
  flex: none;
5622
+ width: calc(var(--tcw-font-size-lg) * 1.272);
5623
+ height: calc(var(--tcw-font-size-lg) * 1.272);
5580
5624
  }
5581
5625
 
5582
5626
  .tcw-ip-search input,
@@ -5589,7 +5633,36 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
5589
5633
  background: transparent;
5590
5634
  color: var(--tcw-text);
5591
5635
  font: inherit;
5592
- font-size: var(--tcw-font-size);
5636
+ font-size: var(--tcw-font-size-lg);
5637
+ }
5638
+
5639
+ /* In forced colours the muted and the text's colour may be one: the band keeps an outline there,
5640
+ so the field is still found. */
5641
+ @media (forced-colors: active) {
5642
+ .tcw-ip-search:focus-within,
5643
+ .tcw-ss-search:focus-within {
5644
+ outline: 2px solid Highlight;
5645
+ outline-offset: -2px;
5646
+ }
5647
+ }
5648
+
5649
+ /* The browser's clear button for a search field (bold, and blue in Chrome's light scheme) as the
5650
+ icon set's close, in the muted text, the text's on hover. A mask, so it takes the colour. */
5651
+ .tcw-ip-search input::-webkit-search-cancel-button,
5652
+ .tcw-ss-search input::-webkit-search-cancel-button {
5653
+ -webkit-appearance: none;
5654
+ appearance: none;
5655
+ width: calc(var(--tcw-font-size-lg) * 1.272);
5656
+ height: calc(var(--tcw-font-size-lg) * 1.272);
5657
+ background: var(--tcw-text-muted);
5658
+ -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M6 6L18 18M18 6L6 18' fill='none' stroke='%23000' stroke-width='1.75' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat;
5659
+ mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M6 6L18 18M18 6L6 18' fill='none' stroke='%23000' stroke-width='1.75' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat;
5660
+ cursor: pointer;
5661
+ }
5662
+
5663
+ .tcw-ip-search input::-webkit-search-cancel-button:hover,
5664
+ .tcw-ss-search input::-webkit-search-cancel-button:hover {
5665
+ background: var(--tcw-text);
5593
5666
  }
5594
5667
 
5595
5668
  .tcw-ip-search input::placeholder,
@@ -5602,7 +5675,6 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
5602
5675
  grid-template-columns: 233px minmax(0, 1fr);
5603
5676
  flex: 1;
5604
5677
  min-height: 0;
5605
- border-top: 1px solid var(--tcw-divider);
5606
5678
  }
5607
5679
 
5608
5680
  .tcw-ip-nav,
@@ -5861,11 +5933,6 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
5861
5933
  height: calc(92dvh - var(--tcw-keyboard-inset, 0px));
5862
5934
  }
5863
5935
 
5864
- .tcw-ip-search,
5865
- .tcw-ss-search {
5866
- margin-inline: var(--tcw-space-4);
5867
- }
5868
-
5869
5936
  .tcw-ip-body {
5870
5937
  grid-template-columns: minmax(0, 1fr);
5871
5938
  grid-template-rows: auto minmax(0, 1fr);
@@ -6129,9 +6196,11 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
6129
6196
 
6130
6197
  /* === The symbol search, and the same dialog comparing === */
6131
6198
 
6132
- /* As wide and as still as the indicators dialog: 610, a fixed height while a search shortens the list. */
6199
+ /* As still as the indicators dialog: a fixed height while a search shortens the list. As wide as it,
6200
+ 610, up to a screen 1597 wide; past that a phi share of the screen (1 / phi^2), up to 987, the next
6201
+ Fibonacci number: about 733 at 1920, 978 at 2560, room for ids with a venue before the ticker. */
6133
6202
  .tcw-modal.tcw-ss {
6134
- width: 610px;
6203
+ width: min(987px, max(610px, 38.2vw));
6135
6204
  height: min(610px, 86vh);
6136
6205
  height: min(610px, 86dvh);
6137
6206
  max-height: none;
@@ -6159,9 +6228,15 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
6159
6228
  padding-block: 0;
6160
6229
  }
6161
6230
 
6162
- /* The heads' height, which the rows scroll in below. */
6231
+ /* The heads' height, which the rows scroll in below; the room after a symbol before its name. */
6163
6232
  .tcw-modal.tcw-ss {
6164
6233
  --tcw-ss-head-h: var(--tcw-control-h);
6234
+ --tcw-ss-name-gap: var(--tcw-space-4);
6235
+ }
6236
+
6237
+ [dir='rtl'] .tcw-ss-symbol {
6238
+ padding-right: 0;
6239
+ padding-left: var(--tcw-ss-name-gap);
6165
6240
  }
6166
6241
 
6167
6242
  /* Over the list: the kinds the rows come in, and their exchanges once there are two. The exchanges sit
@@ -6257,11 +6332,12 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
6257
6332
  }
6258
6333
 
6259
6334
  /* What scrolls is one grid, and the heads, the list and each row are its subgrids, so a column is
6260
- as wide in every row: the badge, the symbol up to 144 (89 x phi), the name the rest, the kind and
6261
- the exchange up to 89 each, the check. An empty cell keeps its column. */
6335
+ as wide in every row: the badge, the symbol up to a quarter of the list (144 at 610, 233 in a wide
6336
+ dialog, the next Fibonacci number), the name the rest, the kind and the exchange up to 89 each,
6337
+ the check. An empty cell keeps its column. */
6262
6338
  .tcw-ss-results {
6263
6339
  display: grid;
6264
- grid-template-columns: max-content fit-content(144px) minmax(0, 1fr) fit-content(89px) fit-content(89px) auto;
6340
+ grid-template-columns: max-content fit-content(clamp(144px, 25%, 233px)) minmax(0, 1fr) fit-content(89px) fit-content(89px) auto;
6265
6341
  align-content: start;
6266
6342
  column-gap: var(--tcw-space-4);
6267
6343
  flex: 1;
@@ -6367,13 +6443,16 @@ img.tcw-ss-badge {
6367
6443
  }
6368
6444
 
6369
6445
  /* The figures of a ticker, in the mono face, left to right in any widget, at the start of its column;
6370
- the chart's own in ink. */
6446
+ the chart's own in ink. Padding on the name's side, counted in the column, keeps the longest id a
6447
+ gap twice the columns' from the name ("BINANCE:BTCUSDT" ran into "BTC perpetual"). The cell is
6448
+ left to right itself, so the side is named, not its end. */
6371
6449
  .tcw-ss-symbol {
6372
6450
  grid-column: 2;
6373
6451
  display: flex;
6374
6452
  justify-self: start;
6375
6453
  max-width: 100%;
6376
6454
  min-width: 0;
6455
+ padding-right: var(--tcw-ss-name-gap);
6377
6456
  overflow: hidden;
6378
6457
  color: var(--tcw-text);
6379
6458
  font-family: var(--tcw-font-mono);
@@ -6657,6 +6736,8 @@ img.tcw-ss-badge {
6657
6736
  /* Above the on-screen keyboard: the sheet's top stays on the screen. */
6658
6737
  height: calc(92vh - var(--tcw-keyboard-inset, 0px));
6659
6738
  height: calc(92dvh - var(--tcw-keyboard-inset, 0px));
6739
+ /* The column's room goes to the ticker; the columns' own gap is enough here. */
6740
+ --tcw-ss-name-gap: 0px;
6660
6741
  }
6661
6742
 
6662
6743
  .tcw-ss-way,
@@ -6768,7 +6849,6 @@ img.tcw-ss-badge {
6768
6849
  overflow-y: auto;
6769
6850
  overscroll-behavior: contain;
6770
6851
  padding: 0 var(--tcw-space-6) var(--tcw-space-5);
6771
- border-top: 1px solid var(--tcw-divider);
6772
6852
  }
6773
6853
 
6774
6854
  /* Two columns as tall as their groups, inside the box that scrolls: on the box itself, of a fixed
@@ -6879,10 +6959,6 @@ img.tcw-ss-badge {
6879
6959
  animation: none;
6880
6960
  }
6881
6961
 
6882
- .tcw-cp .tcw-cp-search {
6883
- margin-top: var(--tcw-space-5);
6884
- }
6885
-
6886
6962
  .tcw-cp-results {
6887
6963
  flex: 1;
6888
6964
  min-height: 0;
@@ -6891,7 +6967,6 @@ img.tcw-ss-badge {
6891
6967
  /* A row the arrows reach scrolls in below its group's heading, not under it. */
6892
6968
  scroll-padding-block-start: calc(var(--tcw-space-5) + var(--tcw-space-2) + var(--tcw-font-size-xs) * 1.5);
6893
6969
  padding: 0 var(--tcw-space-4) var(--tcw-space-4);
6894
- border-top: 1px solid var(--tcw-divider);
6895
6970
  }
6896
6971
 
6897
6972
  .tcw-cp-heading {
@@ -6966,7 +7041,6 @@ img.tcw-ss-badge {
6966
7041
  overflow-y: auto;
6967
7042
  overscroll-behavior: contain;
6968
7043
  padding: var(--tcw-space-3) var(--tcw-space-4) var(--tcw-space-5);
6969
- border-top: 1px solid var(--tcw-divider);
6970
7044
  }
6971
7045
 
6972
7046
  .tcw-layouts-list {
@@ -7109,14 +7183,6 @@ img.tcw-ss-badge {
7109
7183
  animation: tcw-modal-in var(--tcw-dur-slow) var(--tcw-ease-out);
7110
7184
  }
7111
7185
 
7112
- .tcw-cp .tcw-cp-search {
7113
- margin-top: var(--tcw-space-3);
7114
- }
7115
-
7116
- :is(.tcw-hotkey-search, .tcw-cp-search, .tcw-layouts-search-row) {
7117
- margin-inline: var(--tcw-space-4);
7118
- }
7119
-
7120
7186
  .tcw-cp-row {
7121
7187
  min-height: 44px;
7122
7188
  }
@@ -7283,7 +7349,7 @@ img.tcw-ss-badge {
7283
7349
  .tcw-ticket-side-btn:focus-visible,
7284
7350
  .tcw-ticket-place:focus-visible { outline: 2px solid Highlight; outline-offset: 2px; }
7285
7351
  }
7286
- `,ie=`/* === The dock: the panels by the chart, and their rail === */
7352
+ `,le=`/* === The dock: the panels by the chart, and their rail === */
7287
7353
 
7288
7354
  /* In the body's row after the chart: the panel of the page open beside the chart, the rail at the outer edge
7289
7355
  (both mirror in a right-to-left widget). */
@@ -7310,8 +7376,8 @@ img.tcw-ss-badge {
7310
7376
  display: inline-grid;
7311
7377
  place-items: center;
7312
7378
  flex: none;
7313
- width: var(--tcw-control-h);
7314
- height: var(--tcw-control-h);
7379
+ width: var(--tcw-tool-size);
7380
+ height: var(--tcw-tool-size);
7315
7381
  padding: 0;
7316
7382
  border: none;
7317
7383
  border-radius: var(--tcw-control-radius);
@@ -7322,8 +7388,8 @@ img.tcw-ss-badge {
7322
7388
  }
7323
7389
 
7324
7390
  .tcw-dock-btn svg {
7325
- width: var(--tcw-icon);
7326
- height: var(--tcw-icon);
7391
+ width: var(--tcw-tool-icon-size);
7392
+ height: var(--tcw-tool-icon-size);
7327
7393
  }
7328
7394
 
7329
7395
  .tcw-dock-btn:hover {
@@ -7694,11 +7760,11 @@ img.tcw-ss-badge {
7694
7760
  .tcw-ladder-cell:focus-visible { outline: 2px solid Highlight; outline-offset: -2px; }
7695
7761
  .tcw-ladder-own { border: 1px solid CanvasText; }
7696
7762
  }
7697
- `,ae=0,oe=`tcw-styles`;function se(){if(ae++,ae>1||document.getElementById(oe))return;let e=document.createElement(`style`);e.id=oe,e.textContent=`${ne}
7698
- ${w}
7699
- ${re}
7700
- ${ie}
7701
- ${r.f()}`,document.head.insertBefore(e,document.head.firstChild)}function ce(){if(ae--,ae>0)return;let e=document.getElementById(oe);e&&e.remove()}var le=class{trigger;panel;_isOpen=!1;onOutsideClick;onEscapeKey;onTriggerClick;layer;align;onAway=()=>this.close();onScroll=e=>{e.target instanceof Node&&this.panel.contains(e.target)||this.close()};constructor(e,t={}){this.trigger=e,this.layer=t.layer??null,this.align=t.align??`left`,this.panel=document.createElement(`div`),this.panel.className=`tcw-dropdown`,this.panel.style.minWidth=t.width??`200px`,this.panel.style.display=`none`,this.layer?(this.layer().appendChild(this.panel),this.panel.addEventListener(`click`,()=>this.close())):(this.align===`right`?this.panel.style.insetInlineEnd=`0px`:this.panel.style.insetInlineStart=`0px`,e.style.position=`relative`,e.appendChild(this.panel)),this.onTriggerClick=()=>{this._isOpen?this.close():this.open()},this.onOutsideClick=e=>{let t=e.target;!this.trigger.contains(t)&&!this.panel.contains(t)&&this.close()},this.onEscapeKey=e=>{e.key===`Escape`&&this.close()},e.addEventListener(`click`,this.onTriggerClick)}setContent(e){this.panel.innerHTML=e}open(){if(!this._isOpen){if(this._isOpen=!0,this.layer){let e=this.layer();this.panel.parentElement!==e&&e.appendChild(this.panel)}this.panel.style.display=``,this.layer&&(this.place(),window.addEventListener(`resize`,this.onAway),document.addEventListener(`scroll`,this.onScroll,{capture:!0,passive:!0})),document.addEventListener(`pointerdown`,this.onOutsideClick),document.addEventListener(`keydown`,this.onEscapeKey)}}close(){this._isOpen&&(this._isOpen=!1,this.panel.style.display=`none`,document.removeEventListener(`pointerdown`,this.onOutsideClick),document.removeEventListener(`keydown`,this.onEscapeKey),window.removeEventListener(`resize`,this.onAway),document.removeEventListener(`scroll`,this.onScroll,{capture:!0}))}isOpen(){return this._isOpen}destroy(){this.close(),this.trigger.removeEventListener(`click`,this.onTriggerClick),this.panel.remove()}place(){_(this.panel,this.trigger,this.align)}},ue=[`1m`,`3m`,`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`1d`,`1w`,`1M`],de=[`1m`,`5m`,`15m`,`1h`,`4h`,`1d`],fe=6;function pe(e){let t=e.slice(-1);return t===`h`||t===`d`||t===`w`?e.slice(0,-1)+t.toUpperCase():e}var me=e=>Number.isFinite((0,u.timeframeToMs)(e))||(0,u.tickBarCount)(e)!==null,he=(e,t)=>{let n=(0,u.tickBarCount)(e),r=(0,u.tickBarCount)(t);return n!==null||r!==null?n===null?1:r===null?-1:n-r:(0,u.timeframeToMs)(e)-(0,u.timeframeToMs)(t)};function ge(e,t){let n=t?.length?t:null,r=e?.length?e:n??ue;return[...new Set(r)].filter(e=>me(e)&&(!n||n.includes(e))).sort(he)}function _e(e,t,n=!1){if(t?.length)return e.filter(e=>t.includes(e));if(n)return[...e];let r=e.filter(e=>de.includes(e));return r.length>0?r:e.slice(0,fe)}var ve=9999,ye={"":`m`,s:`s`,S:`s`,m:`m`,h:`h`,H:`h`,d:`d`,D:`d`,w:`w`,W:`w`,M:`M`},be={s:[`m`,60],m:[`h`,60],h:[`d`,24]};function xe(e){let t=/^(\d+)([a-zA-Z]?)$/.exec(e.trim());if(!t)return null;if(t[2]===`T`||t[2]===`t`){let e=`${Number(t[1])}T`;return Number(t[1])<=ve&&(0,u.tickBarCount)(e)!==null?e:null}let n=Number(t[1]),r=ye[t[2]];if(!r||!Number.isSafeInteger(n)||n<1)return null;for(let e=be[r];e&&n%e[1]===0;e=be[r])n/=e[1],r=e[0];if(n>ve)return null;let i=`${n}${r}`;return(0,u.isTimeFrame)(i)?i:null}function Se(e,t,n){let r=n?.length?n:null,i=t.filter(e=>me(e)&&(!r||r.includes(e)));return[...new Set([...e,...i])].sort(he)}var Ce=[`T`,`s`,`m`,`h`,`d`,`w`,`M`];function we(e){let t=e=>{let t=e.slice(-1);return Ce.includes(t)?t:`m`};return Ce.map(n=>({unit:n,timeframes:e.filter(e=>t(e.value)===n)})).filter(e=>e.timeframes.length>0)}var Te=864e5,Ee=5/7;function De(e){let t=(0,u.timeframeToMs)(e.current),n=(0,u.timeframeToMs)(e.chosen);if(!Number.isFinite(t)||!Number.isFinite(n)||!(e.width>0)||!(e.spanMs>0))return e.current;let r=n=>{if(n===t)return e.barsInSpan;if(n<Te)return e.barsInSpan*t/n;let r=e.spanMs/n;return n===Te?r*(e.dayShare??Ee):r},i=[...new Set([...e.available,e.current])].filter(e=>{let t=(0,u.timeframeToMs)(e);return Number.isFinite(t)&&t>=n}).sort(he);for(let t of i)if(r((0,u.timeframeToMs)(t))*2<=e.width)return t;return i[i.length-1]??e.current}var Oe={ticket:`receipt`,long:`trendingUp`,short:`trendingDown`,ladder:`ladder`,account:`layers`},ke=[`ladder`,`account`];function Ae(e,t){let n=[];e.onOrderTicket&&n.push({id:`ticket`,label:t(`chartMenu.orderTicket`),parts:[`orderTicket`],run:e.onOrderTicket});let r=e.onBracket;return r&&(n.push({id:`long`,label:t(`toolbar.longBracket`),parts:[`bracketOrders`,`toolbar.bracketOrders`],run:()=>r(`buy`)}),n.push({id:`short`,label:t(`toolbar.shortBracket`),parts:[`bracketOrders`,`toolbar.bracketOrders`],run:()=>r(`sell`)})),e.onToggleLadder&&n.push({id:`ladder`,label:t(`toolbar.depthLadder`),parts:[`depthLadder`,`toolbar.depthLadder`],run:e.onToggleLadder}),e.onToggleAccount&&n.push({id:`account`,label:t(`toolbar.account`),parts:[`accountPanel`,`toolbar.accountPanel`],run:e.onToggleAccount}),n}var je=class e{button;menu=null;open=new Set;static create(t,n,r,i){let a=Ae(t,n);return a.length>0?new e(a,n,r,i):null}constructor(e,t,n,o){this.items=e,this.t=t,this.root=n;let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-dropdown-trigger tcw-toolbar-overflow`,s.dataset.role=`trade`,s.dataset.icon=`trendingUp`,s.title=t(`toolbar.trade`),s.setAttribute(`aria-haspopup`,`menu`),s.setAttribute(`aria-expanded`,`false`),r.o(s,`toolbar.trade`),s.innerHTML=`${i.i(`trendingUp`,14)} <span class="tcw-trigger-label">${a.u(t(`toolbar.trade`))}</span> ${i.i(`chevronDown`,12)}`,s.addEventListener(`click`,()=>this.toggle(o(s))),this.button=s}tidy(){this.button.hidden=this.items.every(e=>this.isOff(e.parts))}setOpen(e,t){let n=ke.find(t=>t===e);n&&(t?this.open.add(n):this.open.delete(n))}destroy(){this.menu?.destroy(),this.button.remove()}isOff(e){let t=new Set((this.root().getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean));return e.some(e=>t.has(e))}toggle(e){if(this.menu?.isOpen()){this.menu.close();return}let t=this.items.filter(e=>!this.isOff(e.parts));if(t.length===0)return;let n=t.filter(e=>!ke.includes(e.id)),r=t.filter(e=>ke.includes(e.id)),i=[...n.map(e=>({id:e.id,label:e.label,icon:Oe[e.id]})),...n.length>0&&r.length>0?[`separator`]:[],...r.map(e=>({id:e.id,label:e.label,checked:this.open.has(e.id)}))],a=this.root();this.menu??=new o.f(a,this.t(`toolbar.trade`)),this.menu.openUnder(i,e,e=>{t.find(t=>t.id===e)?.run()})}},Me=0,T=`data-tcw-folded`,Ne=1/64,Pe=[`venue`,`ticker`,`cut`],Fe={T:`toolbar.timeframes.ticks`,s:`toolbar.timeframes.seconds`,m:`toolbar.timeframes.minutes`,h:`toolbar.timeframes.hours`,d:`toolbar.timeframes.days`,w:`toolbar.timeframes.weeks`,M:`toolbar.timeframes.months`};function Ie(e,t){let n=e.querySelector(`.tcw-host-btn-text`)?.textContent??``;n===t?e.removeAttribute(`aria-label`):e.setAttribute(`aria-label`,n?`${t}: ${n}`:t)}var Le=class{config;callbacks;t;el;chartTypeDropdown=null;tfGroup=null;tfDropdown=null;tfFavorites=[];uid=(Me++).toString(36);tfRendered=``;themeBtn=null;fullscreenBtn=null;hostLeft=null;hostRight=null;moreMenu=null;tfCurrent=null;resizeObserver=null;hostObserver=null;moreBtn=null;fitFrame=0;destroyed=!1;undoBtn=null;redoBtn=null;trade=null;layoutShown=``;symbolShown=null;constructor(e,t,n,i,a){if(this.host=e,this.layer=a,this.config=t,this.callbacks=n,this.t=i,this.el=document.createElement(`div`),this.el.className=`tcw-toolbar`,r.o(this.el,`toolbar`),this.build(),e.appendChild(this.el),typeof ResizeObserver<`u`){this.resizeObserver=new ResizeObserver(()=>this.fit()),this.resizeObserver.observe(this.el),this.hostObserver=new ResizeObserver(()=>this.scheduleFit());for(let e of[this.hostLeft,this.hostRight])e&&this.hostObserver.observe(e)}document.fonts?.ready.then(()=>this.scheduleFit())}scheduleFit(){this.destroyed||this.fitFrame||typeof requestAnimationFrame>`u`||(this.fitFrame=requestAnimationFrame(()=>{this.fitFrame=0,this.destroyed||this.fit()}))}menuAnchor(e){return(e.hasAttribute(T)||this.el.closest(`[data-tcw-narrow]`)!==null)&&this.moreBtn?this.moreBtn:e}fit(){let e=this.toolbarFocus(),t=this.foldedState();this.refit(),this.foldedState()!==t&&this.closeStaleMenus(),e&&this.keepFocus(e)}refit(){let{el:e}=this,t=()=>this.fits(),n=[...e.querySelectorAll(`.tcw-toolbar-overflow`)];for(let e of n)e.removeAttribute(T);if(e.classList.remove(`tcw-toolbar--collapsed`,`tcw-toolbar--icons`),delete e.dataset.tcwSqueeze,!(e.clientWidth===0||t())){e.classList.add(`tcw-toolbar--collapsed`);for(let e=n.length-1;e>=0;e--)if(n[e].setAttribute(T,``),t())return;e.classList.add(`tcw-toolbar--icons`);for(let e of n)if(e.removeAttribute(T),!t()){e.setAttribute(T,``);break}for(let n of Pe){if(t())return;e.dataset.tcwSqueeze=n}}}fits(){let{el:e}=this,t=e.getBoundingClientRect(),n=e.offsetWidth>0&&Math.abs(t.width-e.offsetWidth)>=1?t.width/e.offsetWidth:1,r=getComputedStyle(e),i=r.direction===`rtl`,a=e=>parseFloat(e)||0,o=t.width/n-(i?a(r.borderLeftWidth)+a(r.paddingLeft):a(r.borderRightWidth)+a(r.paddingRight)),s=0;for(let r of e.children){if(r.getClientRects().length===0)continue;let e=r.getBoundingClientRect();s=Math.max(s,(i?t.right-e.left:e.right-t.left)/n)}return Math.ceil(s-Ne)<=Math.floor(o+Ne)}foldedState(){let e=[...this.el.querySelectorAll(`.tcw-toolbar-overflow`)];return`${this.el.classList.contains(`tcw-toolbar--collapsed`)}:${e.map(e=>Number(e.hasAttribute(T))).join(``)}`}closeStaleMenus(){this.moreBtn&&o.f.closeAnchoredTo(this.moreBtn);for(let e of this.el.querySelectorAll(`[${T}], [${T}] button`))o.f.closeAnchoredTo(e)}toolbarFocus(){let e=o.f.focusedAnchor();if(e&&this.el.contains(e))return e;let t=document.activeElement;return t instanceof HTMLElement&&this.el.contains(t)?t:null}keepFocus(e){if(o.f.focusedAnchor())return;let t=e;this.shows(e)||(t=(this.moreBtn&&e!==this.moreBtn&&this.shows(this.moreBtn)?this.moreBtn:null)??this.overflowButtons().filter(e=>this.shows(e)).at(-1)),t&&document.activeElement!==t&&t.focus({preventScroll:!0})}overflowButtons(){return[...this.el.querySelectorAll(`button.tcw-toolbar-overflow, .tcw-toolbar-overflow button`)]}shows(e){if(e.closest(`[hidden]`)||e.closest(`[${T}]`)||this.isOff(e))return!1;let t=this.el.closest(`[data-tcw-narrow]`)!==null;return e===this.moreBtn?t||this.el.classList.contains(`tcw-toolbar--collapsed`):!(t&&e.closest(`.tcw-toolbar-overflow`))}isOff(e){let t=new Set((this.rootEl().getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean));for(let n=e;n&&n!==this.el;n=n.parentElement)if((n.dataset.tcwPart??``).split(/\s+/).some(e=>t.has(e)))return!0;return!1}build(){let{config:e,callbacks:t,el:n}=this,o=document.createElement(`button`);if(o.className=`tcw-toolbar-symbol`,o.dataset.role=`symbol`,o.dir=`ltr`,r.o(o,`toolbar.symbol`),o.addEventListener(`click`,t.onSymbolClick),n.appendChild(o),t.onSymbolInfo){let e=this.iconBtn(`info`,this.t(`symbolInfo.title`),t.onSymbolInfo);e.classList.remove(`tcw-toolbar-overflow`),e.dataset.role=`symbolInfo`,r.o(e,`symbolInfo`,`toolbar.symbolInfo`),n.appendChild(e)}if(n.appendChild(this.sep()),this.tfFavorites=[...e.timeframeFavorites??e.timeframes.map(e=>e.value)],this.tfGroup=document.createElement(`div`),this.tfGroup.className=`tcw-toolbar-group tcw-tf-group`,r.o(this.tfGroup,`toolbar.timeframes`),n.appendChild(this.tfGroup),t.onToggleTimeframeFavorite&&e.timeframes.length>0){let e=document.createElement(`div`);e.style.position=`relative`,e.style.display=`inline-flex`,r.o(e,`toolbar.timeframeMenu`);let t=document.createElement(`button`);t.className=`tcw-btn tcw-tf-more`,t.dataset.role=`timeframes`,t.title=this.t(`toolbar.timeframes`),t.setAttribute(`aria-label`,this.t(`toolbar.timeframes`)),this.tfCurrent=document.createElement(`span`),this.tfCurrent.className=`tcw-tf-current`,t.appendChild(this.tfCurrent),t.insertAdjacentHTML(`beforeend`,i.i(`chevronDown`,12)),e.appendChild(t),n.appendChild(e),this.tfDropdown=new le(e,{width:`150px`,layer:this.layer}),n.classList.add(`tcw-toolbar--tf-menu`),this.buildTimeframeMenu()}n.appendChild(this.sep());let s=document.createElement(`div`);s.style.position=`relative`,s.style.display=`inline-flex`,r.o(s,`toolbar.chartType`);let c=document.createElement(`button`);c.className=`tcw-dropdown-trigger`,c.dataset.role=`charttype`,s.appendChild(c),n.appendChild(s),this.chartTypeDropdown=new le(s,{width:`160px`,layer:this.layer}),this.buildChartTypeMenu(),n.appendChild(this.sep());let l=document.createElement(`button`);if(l.type=`button`,l.className=`tcw-dropdown-trigger`,l.dataset.role=`indicators`,l.setAttribute(`aria-haspopup`,`dialog`),l.setAttribute(`aria-expanded`,`false`),r.o(l,`toolbar.indicators`),l.addEventListener(`click`,()=>t.onIndicators()),n.appendChild(l),t.onCompare){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-dropdown-trigger`,e.dataset.role=`compare`,r.o(e,`compare`,`toolbar.compare`);let o=this.t(`objects.compare`);e.setAttribute(`aria-label`,o),e.title=o,e.innerHTML=`${i.i(`plus`,14)} <span class="tcw-trigger-label">${a.u(o)}</span>`,e.addEventListener(`click`,t.onCompare),n.appendChild(e)}if(this.hostLeft=this.hostGroup(),n.appendChild(this.hostLeft),t.onUndo&&t.onRedo&&(n.appendChild(this.sep()),this.undoBtn=this.iconBtn(`undo`,this.t(`drawing.undo`),t.onUndo),this.undoBtn.dataset.role=`undo`,r.o(this.undoBtn,`toolbar.undo`,`sidebar.undo`),this.redoBtn=this.iconBtn(`redo`,this.t(`drawing.redo`),t.onRedo),this.redoBtn.dataset.role=`redo`,r.o(this.redoBtn,`toolbar.redo`,`sidebar.redo`),n.append(this.undoBtn,this.redoBtn),this.setHistory(!1,!1)),n.appendChild(this.spacer()),t.onLayouts){let e=t.onLayouts,i=document.createElement(`button`);i.type=`button`,i.className=`tcw-dropdown-trigger tcw-layouts-btn tcw-toolbar-overflow`,i.dataset.role=`layouts`,i.dataset.icon=`save`,r.o(i,`layouts`,`toolbar.layouts`),i.setAttribute(`aria-haspopup`,`menu`),i.addEventListener(`click`,()=>e(this.menuAnchor(i))),n.appendChild(i),this.setLayout(null,!1)}if(this.hostRight=this.hostGroup(),n.appendChild(this.hostRight),n.appendChild(this.sep()),t.onToggleReplay){let e=this.iconBtn(`play`,this.t(`toolbar.replay`),t.onToggleReplay);e.dataset.role=`replay`,r.o(e,`replay`,`toolbar.replay`),n.appendChild(e)}if(t.onToggleObjects){let e=this.iconBtn(`layers`,this.t(`toolbar.objects`),t.onToggleObjects);e.dataset.role=`objects`,e.setAttribute(`aria-pressed`,`false`),r.o(e,`objectTree`,`toolbar.objectTree`),n.appendChild(e)}if(t.onToggleAlerts){let e=this.iconBtn(`bell`,this.t(`toolbar.priceAlerts`),t.onToggleAlerts);e.dataset.role=`alerts`,e.setAttribute(`aria-pressed`,`false`),r.o(e,`alerts`,`toolbar.alerts`),n.appendChild(e)}this.trade=je.create(t,this.t,()=>this.rootEl(),e=>this.menuAnchor(e)),this.trade&&n.appendChild(this.trade.button),n.appendChild(this.sep());let u=this.iconBtn(`camera`,this.t(`toolbar.screenshot`),t.onScreenshot);r.o(u,`screenshot`,`toolbar.screenshot`),n.appendChild(u);let d=this.iconBtn(`settings`,this.t(`toolbar.settings`),t.onSettings);r.o(d,`settings`,`toolbar.settings`),n.appendChild(d),this.themeBtn=this.iconBtn(`moon`,this.t(`toolbar.toggleTheme`),t.onToggleTheme),this.themeBtn.dataset.role=`theme`,r.o(this.themeBtn,`themeToggle`,`toolbar.themeToggle`),n.appendChild(this.themeBtn),t.onToggleFullscreen&&(this.fullscreenBtn=this.iconBtn(`maximize`,this.t(`toolbar.fullscreen`),t.onToggleFullscreen),this.fullscreenBtn.dataset.role=`fullscreen`,r.o(this.fullscreenBtn,`fullscreen`,`toolbar.fullscreen`),this.fullscreenBtn.setAttribute(`aria-pressed`,`false`),n.appendChild(this.fullscreenBtn));let f=document.createElement(`button`);f.type=`button`,f.className=`tcw-btn-icon tcw-toolbar-more`,f.title=this.t(`toolbar.more`),f.setAttribute(`aria-haspopup`,`menu`),f.setAttribute(`aria-expanded`,`false`),f.innerHTML=i.i(`more`,16),f.addEventListener(`click`,()=>this.toggleMore(f)),n.appendChild(f),this.moreBtn=f}toggleMore(e){if(o.f.closeAnchoredTo(e))return;let t=this.rootEl(),n=this.el.closest(`[data-tcw-narrow]`)!==null,r=[];for(let e of this.el.querySelectorAll(`.tcw-toolbar-overflow`)){if(this.isOff(e)||!n&&!e.hasAttribute(T))continue;let t=e instanceof HTMLButtonElement?[e]:[...e.querySelectorAll(`button`)];r.push(...t.filter(e=>!e.hidden&&!e.disabled&&!this.isOff(e)))}if(r.length===0)return;let i=r.map((e,t)=>{let n=e.getAttribute(`aria-label`)||e.title||e.textContent?.trim()||``,r=e.getAttribute(`aria-pressed`);return r===null?{id:String(t),label:n,icon:e.dataset.icon}:{id:String(t),label:n,icon:e.dataset.icon,checked:r===`true`}});this.moreMenu??=new o.f(t,this.t(`toolbar.more`)),this.moreMenu.openUnder(i,e,e=>r[Number(e)]?.click(),`end`)}addHostButton(e){let t=document.createElement(`button`);t.type=`button`,t.className=`${e.text||!e.icon?`tcw-btn`:`tcw-btn-icon`} tcw-host-btn tcw-toolbar-overflow`,t.dataset.hostButton=e.id,typeof e.icon==`string`&&(t.dataset.icon=e.icon),t.title=e.label,e.toggle&&t.setAttribute(`aria-pressed`,`false`),typeof e.icon==`string`?t.innerHTML=i.i(e.icon,14):e.icon&&t.appendChild(e.icon);let n=e.text??(e.icon?``:e.label);if(n){let e=document.createElement(`span`);e.className=`tcw-host-btn-text`,e.textContent=n,t.appendChild(e)}return Ie(t,e.label),t.addEventListener(`click`,()=>e.onClick(t)),(e.side===`left`?this.hostLeft:this.hostRight)?.appendChild(t),this.scheduleFit(),t}hostSlot(e){return e===`left`?this.hostLeft:this.hostRight}hostGroup(){let e=document.createElement(`div`);return e.className=`tcw-toolbar-host`,e}setSymbolSearch(e){let t=this.el.querySelector(`[data-role="symbol"]`);t&&(e?t.removeAttribute(`aria-disabled`):t.setAttribute(`aria-disabled`,`true`))}tidy(){this.trade?.tidy(),r.d(this.el,`tcw-toolbar-sep`,`tcw-toolbar-spacer`),this.scheduleFit()}setHistory(e,t){this.undoBtn&&(this.undoBtn.disabled=!e),this.redoBtn&&(this.redoBtn.disabled=!t)}rootEl(){return this.el.closest(`.tcw-root`)??this.host}setActive(e,t){this.trade?.setOpen(e,t);let n=this.el.querySelector(`[data-role="${e}"]`);n&&(n.classList.toggle(`tcw-active`,t),n.setAttribute(`aria-pressed`,String(t)))}setRailed(e,t){let n=this.el.querySelector(`[data-role="${e}"]`);n&&(n.hidden=t)}setLayout(e,t){let n=this.el.querySelector(`[data-role="layouts"]`);if(!n)return;let r=e??this.t(`layouts.unnamed`);if(this.layoutShown===`${t}:${r}`)return;this.layoutShown=`${t}:${r}`;let o=`${this.t(`toolbar.layouts`)}: ${r}${t?` (${this.t(`layouts.unsavedChanges`)})`:``}`;n.innerHTML=`${i.i(`save`,14)}<span class="tcw-layouts-label">${a.u(r)}</span>`+(t?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+i.i(`chevronDown`,12),n.title=o,n.setAttribute(`aria-label`,o),this.scheduleFit()}setFullscreen(e){if(!this.fullscreenBtn)return;let t=this.t(e?`toolbar.exitFullscreen`:`toolbar.fullscreen`);this.fullscreenBtn.innerHTML=i.i(e?`minimize`:`maximize`,14),this.fullscreenBtn.title=t,this.fullscreenBtn.setAttribute(`aria-pressed`,String(e))}chartTypeLabel(e){return t.t(e,this.t)}buildChartTypeMenu(){if(!this.chartTypeDropdown)return;let e=this.config.chartTypes.map(e=>`<button class="tcw-dropdown-item tcw-dropdown-item--icon" data-ct="${a.u(e.value)}">${i.r(e.value,16)}<span>${a.u(this.chartTypeLabel(e))}</span></button>`).join(``);this.chartTypeDropdown.setContent(e),this.chartTypeDropdown.panel.querySelectorAll(`.tcw-dropdown-item`).forEach(e=>{e.addEventListener(`click`,e=>{let t=e.currentTarget.dataset.ct;this.callbacks.onChartType(t),this.chartTypeDropdown?.close()})})}setSymbolDescription(e){let t=this.el.querySelector(`[data-role="symbol"]`);t&&(e?t.title=e:t.removeAttribute(`title`))}setTimeframes(e,t){this.config={...this.config,timeframes:e},this.setTimeframeFavorites(t)}setTimeframeFavorites(e){this.tfFavorites=[...e],this.tfRendered=``,this.buildTimeframeMenu()}buildTimeframeMenu(){if(!this.tfDropdown)return;let e=a.u(this.t(`toolbar.timeframes.pin`)),t=a.u(this.t(`toolbar.timeframes.remove`)),n=``;for(let{unit:r,timeframes:o}of we(this.config.timeframes)){n+=`<div class="tcw-tf-section" data-tf-section="${r}" role="group" aria-label="${a.u(this.t(Fe[r]))}"><div class="tcw-dropdown-label">${a.u(this.t(Fe[r]))}</div>`;for(let r of o){let o=this.tfFavorites.includes(r.value),[s,c]=[a.u(r.value),a.u(r.label)];n+=`<div class="tcw-tf-row"><button class="tcw-dropdown-item" data-tf-pick="${s}">${c}</button>`+(r.custom&&this.callbacks.onRemoveTimeframe?`<button class="tcw-tf-remove" data-tf-remove="${s}" title="${t}" aria-label="${t}: ${c}">${i.i(`x`,12)}</button>`:``)+`<button class="tcw-tf-star${o?` tcw-active`:``}" data-tf-star="${s}" aria-pressed="${o}" title="${e}" aria-label="${e}: ${c}">${i.i(`star`,12)}</button></div>`}n+=`</div>`}if(this.callbacks.onAddTimeframe){let e=a.u(this.t(`toolbar.timeframes.custom`)),t=a.u(this.t(`toolbar.timeframes.add`));n+=`<form class="tcw-tf-custom" ${r.c(`customTimeframes`)} novalidate><input class="tcw-tf-custom-input" type="text" autocomplete="off" spellcheck="false" maxlength="6" placeholder="7m, 90m, 2h…" aria-label="${e}" aria-describedby="tcw-tf-hint-${this.uid}"><button type="submit" class="tcw-tf-custom-add" title="${t}" aria-label="${t}">${i.i(`plus`,12)}</button><div class="tcw-tf-custom-hint" id="tcw-tf-hint-${this.uid}" role="status"></div></form>`}this.tfDropdown.setContent(n);let o=this.tfDropdown.panel;o.querySelectorAll(`[data-tf-pick]`).forEach(e=>{e.addEventListener(`click`,()=>this.callbacks.onTimeframe(e.dataset.tfPick))}),o.querySelectorAll(`[data-tf-star]`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onToggleTimeframeFavorite?.(e.dataset.tfStar)})}),o.querySelectorAll(`[data-tf-remove]`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onRemoveTimeframe?.(e.dataset.tfRemove)})});let s=o.querySelector(`.tcw-tf-custom`);s&&this.wireCustomTimeframe(s)}wireCustomTimeframe(e){let t=e.querySelector(`.tcw-tf-custom-input`),n=e.querySelector(`.tcw-tf-custom-hint`);e.addEventListener(`click`,e=>e.stopPropagation()),t.addEventListener(`input`,()=>{t.removeAttribute(`aria-invalid`),n.textContent=``}),e.addEventListener(`submit`,e=>{e.preventDefault(),e.stopPropagation(),this.callbacks.onAddTimeframe?.(t.value)?(t.value=``,n.textContent=``,this.tfDropdown?.close(),this.el.querySelector(`[data-role="timeframes"]`)?.focus()):(t.setAttribute(`aria-invalid`,`true`),n.textContent=this.t(`toolbar.timeframes.invalid`))})}renderTimeframes(e){if(!this.tfGroup)return;let t=this.config.timeframes.filter(t=>this.tfFavorites.includes(t.value)||t.value===e),n=`${t.map(e=>e.value).join(`,`)}|${e}`;n!==this.tfRendered&&(this.tfRendered=n,this.tfCurrent&&(this.tfCurrent.textContent=this.config.timeframes.find(t=>t.value===e)?.label??e),this.tfGroup.replaceChildren(...t.map(t=>{let n=document.createElement(`button`);return n.className=`tcw-btn`,n.textContent=t.label,n.dataset.tf=t.value,n.classList.toggle(`tcw-active`,t.value===e),n.addEventListener(`click`,()=>this.callbacks.onTimeframe(t.value)),n})),(this.tfDropdown?.panel)?.querySelectorAll(`[data-tf-pick]`).forEach(t=>{t.classList.toggle(`tcw-active`,t.dataset.tfPick===e)}))}setIndicatorsOpen(e){this.el.querySelector(`[data-role="indicators"]`)?.setAttribute(`aria-expanded`,String(e))}renderSymbol(e){let t=this.el.querySelector(`[data-role="symbol"]`);if(!t||this.symbolShown===e)return;this.symbolShown=e;let{venue:n,ticker:r}=a.c(e),i=(e,t)=>{let n=document.createElement(`span`);return n.className=e,n.textContent=t,n};t.replaceChildren(...n?[i(`tcw-toolbar-venue`,n)]:[],i(`tcw-toolbar-ticker`,r)),t.classList.toggle(`tcw-toolbar-symbol--venue`,n!==``),t.setAttribute(`aria-label`,e)}update(e){this.renderSymbol(e.symbol),this.renderTimeframes(e.timeframe);let t=this.el.querySelector(`[data-role="charttype"]`);if(t){let n=this.config.chartTypes.find(t=>t.value===e.chartType),r=n?this.chartTypeLabel(n):e.chartType;t.innerHTML=i.r(e.chartType,16),t.title=r,t.setAttribute(`aria-label`,r)}let n=this.el.querySelector(`[data-role="indicators"]`);if(n){let t=[...e.activeIndicators.values()].filter(e=>!d.SYMBOL_INDICATOR_IDS.has(e.id)).length,r=`${i.i(`trendingUp`,14)} <span class="tcw-trigger-label">${a.u(this.t(`toolbar.indicators`))}</span>`;n.setAttribute(`aria-label`,this.t(`toolbar.indicators`)),t>0&&(r+=` <span class="tcw-badge-count">${t}</span>`),n.innerHTML=r}if(this.themeBtn){let t=e.isDark?`moon`:`sun`;this.themeBtn.innerHTML=i.i(t,14),this.themeBtn.dataset.icon=t}this.scheduleFit()}sep(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-sep`,e}spacer(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-spacer`,e}iconBtn(e,t,n){let r=document.createElement(`button`);return r.className=`tcw-btn-icon tcw-toolbar-overflow`,r.dataset.icon=e,r.title=t,r.innerHTML=i.i(e,14),r.addEventListener(`click`,n),r}destroy(){this.destroyed=!0,this.resizeObserver?.disconnect(),this.hostObserver?.disconnect(),this.fitFrame&&cancelAnimationFrame(this.fitFrame),this.chartTypeDropdown?.destroy(),this.tfDropdown?.destroy(),this.moreMenu?.destroy(),this.trade?.destroy(),this.el.remove()}};function Re(e,t,n){e.classList.toggle(`tcw-active`,t),n&&e.setAttribute(`aria-pressed`,String(t))}function ze(e,t,n){let r=n==null?``:String(n),i=e.querySelector(`.tcw-host-btn-text`);return(i?.textContent??``)===r?!1:(i||(i=document.createElement(`span`),i.className=`tcw-host-btn-text`,e.appendChild(i)),i.textContent=r,Ie(e,t),!0)}var Be=100,E=null,Ve=null,He=0,Ue=!1,D=new Set;function We(e){E&&(E.sources.set(e,e.version),e.subs.add(E))}function Ge(e){for(let t of[...e.subs])t.mark()}function Ke(e){for(let t of e.sources.keys())t.subs.delete(e),t instanceof Xe&&t.subs.size===0&&t.release();e.sources.clear()}function qe(e){for(let[t,n]of e.sources)if(t.refresh(),t.version!==n)return!0;return!1}function Je(e,t){Ke(e);let n=E;E=e;try{return t()}finally{E=n}}var Ye=class{version=0;subs=new Set;constructor(e){this.value=e}refresh(){}get(){return We(this),this.value}peek(){return this.value}set(e){Object.is(e,this.value)||(this.value=e,this.version++,tt(()=>Ge(this)))}update(e){this.set(e(this.value))}},Xe=class{version=0;subs=new Set;sources=new Map;dirty=!0;value;computed=!1;constructor(e){this.fn=e}mark(){this.dirty||(this.dirty=!0,Ge(this))}refresh(){if(!this.dirty)return;if(this.computed&&!qe(this)){this.dirty=!1;return}let e=Je(this,this.fn);this.dirty=!1,!(this.computed&&Object.is(e,this.value))&&(this.value=e,this.computed=!0,this.version++)}get(){return this.refresh(),We(this),this.value}peek(){return this.refresh(),this.value}release(){Ke(this),this.dirty=!0,this.computed=!1}},Ze=class{sources=new Map;cleanup=void 0;disposed=!1;constructor(e){this.fn=e}mark(){this.disposed||D.add(this)}run(){let e=this.cleanup;this.cleanup=void 0,e?.(),this.cleanup=Je(this,this.fn)}runIfStale(){!this.disposed&&qe(this)&&this.run()}dispose(){this.disposed||(this.disposed=!0,D.delete(this),Ke(this),this.cleanup?.(),this.cleanup=void 0)}};function Qe(){if(Ue)return;Ue=!0;let e=0,t=null;try{for(;D.size>0;){if(++e>Be)throw D.clear(),Error(`signals: an effect did not settle; it keeps changing what it reads`);let n=[...D];D.clear();for(let e of n)try{e.runIfStale()}catch(e){t??={error:e}}}}finally{Ue=!1}if(t)throw t.error}function $e(e){return new Ye(e)}function et(e){let t=new Ze(e),n=()=>t.dispose();return Ve?.push(n),tt(()=>t.run()),n}function tt(e){He++;try{return e()}finally{He--,He===0&&Qe()}}function nt(){let e=[];return{run(t){let n=Ve;Ve=e;try{return t()}finally{Ve=n}},dispose(){for(let t of e.splice(0))t()}}}var rt=16,it=150,at=4;function ot(e){let t=`sidebar.${e}`;return r.r.includes(t)?t:null}function st(e,t){for(let n of e){let e=n.tools.find(e=>e.value===t);if(e)return e.label}return t}var ct=`--tcw-fab-plot-left`,lt=class{config;callbacks;el;groupWraps=[];groupButtons=[];groupIcons=[];groupTools=[];cursorBtn=null;magnetBtn=null;eraserBtn=null;zoomBtn=null;stayBtn=null;lockAllBtn=null;hideAllBtn=null;drawings={locked:!1,hidden:!1};flyoutEl=null;flyoutIdx=-1;flyoutHideTimer=null;hostEl=null;favoritesEl=null;favoritesDivider=null;favorites=[];fab;fabShows=``;onPressAway=e=>{let t=e.target;t&&(this.el.contains(t)||this.fab.contains(t)||this.flyoutEl?.contains(t))||this.setOpen(!1)};onEscape=e=>{e.key===`Escape`&&!this.flyoutEl&&this.setOpen(!1)};constructor(e,t,n,a=s.t){this.host=e,this.t=a,this.config=t,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-sidebar`,r.o(this.el,`sidebar`),this.build(),this.el.addEventListener(`scroll`,()=>this.hideFlyout(),{passive:!0}),e.appendChild(this.el),this.fab=document.createElement(`button`),this.fab.type=`button`,this.fab.className=`tcw-sidebar-fab`,this.fab.setAttribute(`aria-label`,this.t(`drawing.tools`)),this.fab.setAttribute(`aria-expanded`,`false`),this.fab.innerHTML=i.i(`penLine`,18),r.o(this.fab,`sidebar`),this.fab.addEventListener(`click`,()=>this.setOpen(!this.isOpen())),e.appendChild(this.fab)}setPlotLeft(e){let t=`${Math.max(0,Math.round(e))}px`;this.fab.style.getPropertyValue(ct)!==t&&this.fab.style.setProperty(ct,t)}isNarrow(){return this.el.closest(`[data-tcw-narrow]`)!==null}isOpen(){return this.el.classList.contains(`tcw-sidebar-open`)}setOpen(e){if(e!==this.isOpen())if(this.el.classList.toggle(`tcw-sidebar-open`,e),this.fab.setAttribute(`aria-expanded`,String(e)),e)document.addEventListener(`pointerdown`,this.onPressAway,!0),document.addEventListener(`keydown`,this.onEscape);else{let e=this.el.contains(document.activeElement)||!!this.flyoutEl?.contains(document.activeElement);this.hideFlyout(),document.removeEventListener(`pointerdown`,this.onPressAway,!0),document.removeEventListener(`keydown`,this.onEscape),e&&this.isNarrow()&&this.fab.focus({preventScroll:!0})}}closeOverlay(){this.setOpen(!1)}closeForChart(){this.isNarrow()&&this.setOpen(!1)}pick(e){this.callbacks.onDrawingTool(e),this.closeForChart()}build(){let{config:e,callbacks:t,el:n}=this;this.cursorBtn=document.createElement(`button`),this.cursorBtn.className=`tcw-sidebar-btn`,this.cursorBtn.title=this.t(`drawing.cursor`),this.cursorBtn.innerHTML=i.i(`cursor`,14),this.cursorBtn.addEventListener(`click`,()=>{t.onCancelDrawing(),this.closeForChart()}),r.o(this.cursorBtn,`sidebar.cursor`),n.appendChild(this.cursorBtn),n.appendChild(this.divider()),t.onToggleFavorite&&(this.favorites=[...e.favorites??[]],this.favoritesEl=document.createElement(`div`),this.favoritesEl.className=`tcw-sidebar-favorites`,r.o(this.favoritesEl,`sidebar.favorites`),n.appendChild(this.favoritesEl),this.favoritesDivider=this.divider(),r.o(this.favoritesDivider,`sidebar.favorites`),n.appendChild(this.favoritesDivider),this.renderFavorites());let a;e.drawingToolGroups.forEach((e,t)=>{if(!e.tools[0])return;e.section!==void 0&&a!==void 0&&e.section!==a&&this.appendDivider(),a=e.section;let o=document.createElement(`div`);o.className=`tcw-tool-group-wrap`;let s=ot(e.section);s&&r.o(o,s);let c=document.createElement(`button`);c.className=`tcw-sidebar-btn`;let l=e.tools[0].value;e.tools.length>1?c.setAttribute(`aria-label`,`${e.label}: ${e.tools[0].label}`):c.title=e.label;let u=document.createElement(`span`);if(u.className=`tcw-sidebar-icon`,u.innerHTML=i.a(l,rt),c.appendChild(u),this.groupIcons.push(u),this.groupTools.push(l),e.tools.length>1){let e=document.createElement(`span`);e.className=`tcw-multi-dot`,c.appendChild(e)}c.addEventListener(`click`,()=>{if(this.isNarrow()&&e.tools.length>1){this.flyoutEl&&this.flyoutIdx===t?this.hideFlyout():this.showFlyout(t);return}this.pick(this.groupTools[t])}),o.appendChild(c),o.addEventListener(`mouseenter`,()=>{this.isNarrow()||this.showFlyout(t)}),o.addEventListener(`mouseleave`,()=>{this.isNarrow()||this.scheduleHideFlyout()}),e.tools.length>1&&(c.setAttribute(`aria-haspopup`,`menu`),c.setAttribute(`aria-expanded`,`false`),c.addEventListener(`keydown`,e=>{e.key===`ArrowRight`||e.key===`ArrowDown`?(e.preventDefault(),this.showFlyout(t),this.focusFlyoutItem(0)):e.key===`Escape`&&this.flyoutEl&&(e.stopPropagation(),this.hideFlyout())})),o.addEventListener(`focusout`,e=>{let t=e.relatedTarget;!o.contains(t)&&!this.flyoutEl?.contains(t)&&this.scheduleHideFlyout()}),n.appendChild(o),this.groupWraps.push(o),this.groupButtons.push(c)});let o=document.createElement(`div`);if(o.className=`tcw-sidebar-spacer`,n.appendChild(o),n.appendChild(this.divider()),t.onToggleStyle){let e=document.createElement(`button`);e.className=`tcw-sidebar-btn`,e.title=this.t(`drawing.style`),e.dataset.role=`style`,r.o(e,`sidebar.style`),e.innerHTML=i.i(`palette`,14);let a=t.onToggleStyle;e.addEventListener(`click`,()=>{a(),this.closeForChart()}),n.appendChild(e)}if(t.onToggleMagnet&&(this.magnetBtn=document.createElement(`button`),this.magnetBtn.className=`tcw-sidebar-btn`,this.magnetBtn.title=this.t(`drawing.magnet`),this.magnetBtn.innerHTML=i.i(`magnet`,14),this.magnetBtn.addEventListener(`click`,t.onToggleMagnet),r.o(this.magnetBtn,`sidebar.magnet`),n.appendChild(this.magnetBtn)),t.onToggleEraser){let e=t.onToggleEraser;this.eraserBtn=this.toggleButton(`eraser`,this.t(`drawing.eraser`),()=>{e(),this.closeForChart()}),r.o(this.eraserBtn,`sidebar.eraser`),n.appendChild(this.eraserBtn)}if(t.onToggleZoomArea){let e=t.onToggleZoomArea;this.zoomBtn=this.toggleButton(`zoomIn`,this.t(`drawing.zoomArea`),()=>{e(),this.closeForChart()}),r.o(this.zoomBtn,`sidebar.zoomArea`),n.appendChild(this.zoomBtn)}if(t.onToggleStayInDrawing&&(this.stayBtn=document.createElement(`button`),this.stayBtn.className=`tcw-sidebar-btn`,this.stayBtn.dataset.role=`stay`,this.stayBtn.title=this.t(`drawing.stay`),this.stayBtn.setAttribute(`aria-pressed`,`false`),this.stayBtn.innerHTML=i.i(`repeat`,14),this.stayBtn.addEventListener(`click`,t.onToggleStayInDrawing),r.o(this.stayBtn,`sidebar.stayInDrawing`),n.appendChild(this.stayBtn)),this.hostEl=document.createElement(`div`),this.hostEl.className=`tcw-sidebar-host`,n.appendChild(this.hostEl),this.appendDivider(),t.onLockAll){let e=t.onLockAll;this.lockAllBtn=this.toggleButton(`lock`,this.t(`drawing.lockAll`),()=>e(!this.drawings.locked)),this.lockAllBtn.dataset.role=`lockAll`,r.o(this.lockAllBtn,`sidebar.lockAll`),n.appendChild(this.lockAllBtn)}if(t.onHideAll){let e=t.onHideAll;this.hideAllBtn=this.toggleButton(`eyeOff`,this.t(`drawing.hideAll`),()=>e(!this.drawings.hidden)),this.hideAllBtn.dataset.role=`hideAll`,r.o(this.hideAllBtn,`sidebar.hideAll`),n.appendChild(this.hideAllBtn)}let s=document.createElement(`button`);s.className=`tcw-sidebar-btn tcw-danger`,s.title=this.t(`drawing.clearAll`),s.innerHTML=i.i(`trash`,14),s.setAttribute(`aria-haspopup`,`menu`),s.setAttribute(`aria-expanded`,`false`),s.addEventListener(`click`,()=>t.onClear(s)),r.o(s,`sidebar.clear`),n.appendChild(s)}setDrawingsState(e){if(!(e.locked===this.drawings.locked&&e.hidden===this.drawings.hidden)){this.drawings={...e};for(let[t,n]of[[this.lockAllBtn,e.locked],[this.hideAllBtn,e.hidden]])t?.setAttribute(`aria-pressed`,String(n)),t?.classList.toggle(`tcw-active`,n)}}setFavorites(e){this.favorites=[...e],this.renderFavorites();for(let e of this.flyoutEl?.querySelectorAll(`.tcw-flyout-row`)??[]){let t=this.favorites.includes(e.dataset.toolValue??``);e.classList.toggle(`tcw-flyout-faved`,t),e.querySelector(`[data-pin]`)?.setAttribute(`aria-pressed`,String(t))}}renderFavorites(){if(!this.favoritesEl)return;this.favoritesEl.replaceChildren();let e=this.favorites.length>0;this.favoritesEl.style.display=e?``:`none`,this.favoritesDivider&&(this.favoritesDivider.style.display=e?``:`none`);for(let e of this.favorites){let t=document.createElement(`button`);t.className=`tcw-sidebar-btn`,t.title=s.r(this.t(`sidebar.unpinHint`),{tool:st(this.config.drawingToolGroups,e)}),t.dataset.toolValue=e,t.innerHTML=i.a(e,rt),t.addEventListener(`click`,()=>this.pick(e)),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.callbacks.onToggleFavorite?.(e)}),this.favoritesEl.appendChild(t)}}showFlyout(e){if(this.cancelHideFlyout(),this.flyoutEl&&this.flyoutIdx===e)return;let t=this.config.drawingToolGroups[e];if(!t||t.tools.length<=1){this.hideFlyout();return}this.hideFlyout();let n=document.createElement(`div`);n.className=`tcw-flyout`,n.setAttribute(`role`,`menu`),n.setAttribute(`aria-label`,t.label),n.addEventListener(`keydown`,t=>this.onFlyoutKey(t,e));let a=document.createElement(`div`);a.className=`tcw-flyout-header`,a.textContent=t.label,n.appendChild(a);let o=this.t(`drawing.pinFavorite`);for(let e of t.tools){let t=document.createElement(`div`);t.className=`tcw-flyout-row`,t.setAttribute(`role`,`none`),t.dataset.toolValue=e.value;let a=document.createElement(`button`);a.className=`tcw-flyout-item`,a.setAttribute(`role`,`menuitem`),a.tabIndex=-1,a.innerHTML=i.a(e.value,rt);let s=document.createElement(`span`);s.className=`tcw-flyout-name`,s.textContent=e.label,a.appendChild(s);let c=this.config.shortcuts?.[e.value];if(c){let e=document.createElement(`kbd`);e.className=`tcw-flyout-key`,e.textContent=c,r.o(e,`hotkeys`,`hotkeys.tools`),a.appendChild(e)}if(a.dataset.toolValue=e.value,a.addEventListener(`click`,()=>{this.hideFlyout(),this.pick(e.value)}),t.appendChild(a),this.callbacks.onToggleFavorite){let n=this.favorites.includes(e.value);t.classList.toggle(`tcw-flyout-faved`,n);let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-flyout-pin`,r.dataset.pin=e.value,r.tabIndex=-1,r.title=o,r.setAttribute(`aria-label`,`${o}: ${e.label}`),r.setAttribute(`aria-pressed`,String(n)),r.innerHTML=i.i(`star`,12),r.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onToggleFavorite?.(e.value)}),t.appendChild(r),a.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.callbacks.onToggleFavorite?.(e.value)})}n.appendChild(t)}n.addEventListener(`mouseenter`,()=>this.cancelHideFlyout()),n.addEventListener(`mouseleave`,()=>this.scheduleHideFlyout()),n.addEventListener(`focusout`,t=>{let r=t.relatedTarget;!n.contains(r)&&!this.groupWraps[e].contains(r)&&this.scheduleHideFlyout()}),this.flyoutEl=n,this.flyoutIdx=e,this.host.appendChild(n),this.placeFlyout(n,this.groupButtons[e]),this.groupButtons[e].setAttribute(`aria-expanded`,`true`)}flyoutItems(){return this.flyoutEl?[...this.flyoutEl.querySelectorAll(`.tcw-flyout-item`)]:[]}focusFlyoutItem(e){let t=this.flyoutItems();t.length!==0&&t[(e+t.length)%t.length].focus()}onFlyoutKey(e,t){let n=this.flyoutItems(),r=n.indexOf(document.activeElement);switch(e.key){case`ArrowDown`:this.focusFlyoutItem(r+1);break;case`ArrowUp`:this.focusFlyoutItem(r-1);break;case`Home`:this.focusFlyoutItem(0);break;case`End`:this.focusFlyoutItem(n.length-1);break;case`Escape`:case`ArrowLeft`:e.stopPropagation(),this.hideFlyout(),this.groupButtons[t]?.focus();break;case`Tab`:this.hideFlyout(),this.groupButtons[t]?.focus();return;default:return}e.preventDefault()}placeFlyout(e,t){let n=this.host.getBoundingClientRect(),r=t.getBoundingClientRect();e.style.maxHeight=`${Math.max(0,this.host.clientHeight-at*2)}px`;let i=this.host.clientHeight-e.offsetHeight-at;this.host.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?(e.style.left=``,e.style.right=`${n.right-r.left}px`):(e.style.right=``,e.style.left=`${r.right-n.left}px`),e.style.top=`${Math.max(0,Math.min(r.top-n.top,i))}px`}scheduleHideFlyout(){this.cancelHideFlyout(),this.flyoutHideTimer=setTimeout(()=>{this.flyoutHideTimer=null,this.hideFlyout()},it)}cancelHideFlyout(){this.flyoutHideTimer!==null&&(clearTimeout(this.flyoutHideTimer),this.flyoutHideTimer=null)}hideFlyout(){this.cancelHideFlyout(),this.flyoutEl&&=(this.flyoutEl.remove(),null),this.groupButtons[this.flyoutIdx]?.setAttribute(`aria-expanded`,`false`),this.flyoutIdx=-1}update(e){this.cursorBtn&&this.cursorBtn.classList.toggle(`tcw-active`,e.activeTool===null);let t=e.activeTool??``;t!==this.fabShows&&(this.fabShows=t,this.fab.innerHTML=e.activeTool?i.a(e.activeTool,18):i.i(`penLine`,18)),this.fab.classList.toggle(`tcw-active`,e.activeTool!==null||e.eraser||e.zoomArea);let{drawingToolGroups:n}=this.config;for(let t=0;t<n.length;t++){let r=n[t].tools.some(t=>t.value===e.activeTool);this.groupButtons[t].classList.toggle(`tcw-active`,r),r&&e.activeTool&&e.activeTool!==this.groupTools[t]&&(this.groupTools[t]=e.activeTool,this.groupIcons[t].innerHTML=i.a(e.activeTool,rt),n[t].tools.length>1&&this.groupButtons[t].setAttribute(`aria-label`,`${n[t].label}: ${st(n,e.activeTool)}`))}if(this.flyoutEl&&this.flyoutEl.querySelectorAll(`.tcw-flyout-item`).forEach(t=>{let n=t;n.classList.toggle(`tcw-active`,n.dataset.toolValue===e.activeTool)}),this.magnetBtn){let t=e.magnetEnabled&&e.magnetStrong;this.magnetBtn.classList.toggle(`tcw-active`,e.magnetEnabled),this.magnetBtn.innerHTML=i.i(t?`magnetStrong`:`magnet`,14),this.magnetBtn.title=t?this.t(`drawing.magnetStrong`):e.magnetEnabled?this.t(`drawing.magnetOn`):this.t(`drawing.magnetOff`),this.magnetBtn.setAttribute(`aria-label`,this.magnetBtn.title)}for(let[t,n]of[[this.eraserBtn,e.eraser],[this.zoomBtn,e.zoomArea]])t&&(t.classList.toggle(`tcw-active`,n),t.setAttribute(`aria-pressed`,String(n)));this.stayBtn&&(this.stayBtn.classList.toggle(`tcw-active`,e.stayInDrawing),this.stayBtn.setAttribute(`aria-pressed`,String(e.stayInDrawing)))}addHostButton(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-sidebar-btn tcw-host-btn`,t.dataset.hostButton=e.id,t.title=e.label,t.setAttribute(`aria-label`,e.label),e.toggle&&t.setAttribute(`aria-pressed`,`false`),typeof e.icon==`string`?t.innerHTML=i.i(e.icon,14):t.appendChild(e.icon),t.addEventListener(`click`,()=>e.onClick(t)),this.hostEl?.appendChild(t),this.tidy(),t}hostSlot(){return this.hostEl}tidy(){r.d(this.el,`tcw-sidebar-divider`,`tcw-sidebar-spacer`)}toggleButton(e,t,n){let r=document.createElement(`button`);return r.className=`tcw-sidebar-btn`,r.title=t,r.setAttribute(`aria-label`,t),r.setAttribute(`aria-pressed`,`false`),r.innerHTML=i.i(e,14),r.addEventListener(`click`,n),r}appendDivider(){this.el.lastElementChild?.classList.contains(`tcw-sidebar-divider`)||this.el.appendChild(this.divider())}divider(){let e=document.createElement(`div`);return e.className=`tcw-sidebar-divider`,e}destroy(){this.setOpen(!1),this.hideFlyout(),this.fab.remove(),this.el.remove()}},ut=`data-tcw-folded`,dt=`tcw-statusbar--folded`,ft=`tcw-statusbar--short-market`,pt=1,mt=13,ht=`goto`,gt=`Alt+G`,_t=e=>e.goToKeys?e.goToKeys():gt;function vt(e,t){let n=document.createElement(`span`);return n.className=e,n.textContent=t,n}var yt=class{el;dotEl;messageEl;marketEl;hostLeft;hostRight;clockBtn=null;clockMenu=null;scaleBtns=null;scaleShown=``;marketShown=``;rightEl;rangeEl=null;presetBtns=[];moreBtn=null;goToBtn=null;rangeMenu=null;resizeObserver=null;fitFrame=0;destroyed=!1;constructor(e,t,n={}){this.host=e,this.extras=n,this.el=document.createElement(`div`),this.el.className=`tcw-statusbar`,r.o(this.el,`statusBar`),n.label&&(this.el.setAttribute(`role`,`group`),this.el.setAttribute(`aria-label`,n.label)),t&&this.el.appendChild(this.buildRange(t)),this.hostLeft=this.hostGroup(),this.el.appendChild(this.hostLeft);let i=document.createElement(`div`);i.className=`tcw-status-right`,this.rightEl=i,this.hostRight=this.hostGroup(),i.appendChild(this.hostRight);let a=document.createElement(`div`);a.className=`tcw-status-indicator`,r.o(a,`statusBar.connection`),this.dotEl=document.createElement(`span`),this.dotEl.className=`tcw-status-dot`,a.appendChild(this.dotEl),this.messageEl=document.createElement(`span`),a.appendChild(this.messageEl),this.marketEl=document.createElement(`span`),this.marketEl.className=`tcw-status-market`,this.marketEl.hidden=!0,r.o(this.marketEl,`statusBar.market`),i.appendChild(this.marketEl),i.appendChild(a),n.clock&&i.appendChild(this.buildClock(n.clock)),n.scale&&i.appendChild(this.buildScale(n.scale)),this.el.appendChild(i),e.appendChild(this.el),this.watchWidths(i)}watchWidths(e){if(typeof ResizeObserver<`u`){this.resizeObserver=new ResizeObserver(()=>this.scheduleFit());for(let t of[this.el,e,this.hostLeft])this.resizeObserver.observe(t)}document.fonts?.ready.then(()=>this.scheduleFit())}scheduleFit(){this.destroyed||this.fitFrame||typeof requestAnimationFrame>`u`||(this.fitFrame=requestAnimationFrame(()=>{this.fitFrame=0,this.destroyed||this.fit()}))}fit(){let e=this.foldedCount(),t=this.rangeFocus();this.refit(),this.foldedCount()!==e&&this.rangeMenu?.close(),this.keepFocus(t)}refit(){let e=this.foldSteps(),t=this.goToBtn?[...this.presetBtns,this.goToBtn]:this.presetBtns,n=n=>{let r=new Set(e.slice(0,n));for(let e of t)e.toggleAttribute(ut,r.has(e));this.el.classList.toggle(dt,n>0)};if(n(0),this.el.classList.remove(ft),this.el.clientWidth===0||this.fits())return;let r=0;for(;r<e.length;)if(n(++r),this.fits())return;if(!(this.marketEl.hidden||this.isOff(this.marketEl))){for(this.el.classList.add(ft);r>0;r--)if(n(r-1),!this.fits()){n(r);return}}}fits(){return this.rangeFits()&&this.rightFits()}rangeFits(){let e=this.rangeEl;return!e||e.scrollWidth<=e.clientWidth+pt}rightFits(){if(this.rightEl.offsetParent!==this.el)return!0;let e=getComputedStyle(this.el),t=this.rightEl.offsetLeft;return(e.direction===`rtl`?(parseFloat(e.paddingLeft)||0)-t:t+this.rightEl.offsetWidth-(this.el.clientWidth-(parseFloat(e.paddingRight)||0)))<=pt}foldedCount(){return this.rangeEl?.querySelectorAll(`[${ut}]`).length??0}rangeFocus(){if(this.rangeMenu?.hasFocus())return this.moreBtn;let e=document.activeElement;return e instanceof HTMLElement&&this.rangeEl?.contains(e)?e:null}keepFocus(e){if(!e||this.rangeMenu?.isOpen())return;let t=this.focusAfterRefit(e);t===this.el?this.focusBar():document.activeElement!==t&&t.focus({preventScroll:!0})}focusAfterRefit(e){if(this.shows(e))return e;let t=this.presetBtns.filter(e=>this.shows(e)).at(-1);return[e===this.moreBtn?null:this.moreBtn,this.goToBtn,t].find(e=>e!=null&&this.shows(e))??this.firstOtherControl()??this.el}firstOtherControl(){return[...this.el.querySelectorAll(`button`)].filter(e=>!this.rangeEl?.contains(e)).find(e=>!e.disabled&&e.getClientRects().length>0)??null}focusBar(){if(document.activeElement===this.el)return;let e=()=>this.el.removeAttribute(`tabindex`);this.el.tabIndex=-1,this.el.addEventListener(`blur`,e,{once:!0}),this.el.focus({preventScroll:!0}),document.activeElement!==this.el&&(this.el.removeEventListener(`blur`,e),e())}shows(e){return e===this.moreBtn&&!this.el.classList.contains(dt)?!1:!e.hasAttribute(ut)&&!this.isOff(e)}foldSteps(){if(this.presetBtns.length===0||this.isOff(this.presetBtns[0]))return[];let e=[...this.presetBtns].reverse();return this.goToBtn&&e.push(this.goToBtn),e}isOff(e){let t=((this.el.closest(`.tcw-root`)??this.host).getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean);return(e.dataset.tcwPart??``).split(/\s+/).some(e=>t.includes(e))}update(e){this.dotEl.className=`tcw-status-dot`,e.connectionState===`connected`?this.dotEl.classList.add(`tcw-connected`):e.connectionState===`error`&&this.dotEl.classList.add(`tcw-error`),this.messageEl.textContent=e.message}tick(){if(!this.clockBtn||!this.extras.clock)return;let{time:e,zone:t}=this.extras.clock.now(),n=`${e} ${t}`;this.clockBtn.textContent!==n&&(this.clockBtn.textContent=n)}setScale(e){let t=`${e.mode}|${e.auto}`;!this.scaleBtns||t===this.scaleShown||(this.scaleShown=t,this.scaleBtns.percent?.setAttribute(`aria-pressed`,String(e.mode===`percentage`)),this.scaleBtns.log?.setAttribute(`aria-pressed`,String(e.mode===`logarithmic`)),this.scaleBtns.auto?.setAttribute(`aria-pressed`,String(e.auto)))}setMarket(e,t,n=t){let r=`${e}|${t}|${n}`;if(r===this.marketShown)return;if(this.marketShown=r,this.marketEl.hidden=e===`always`,this.marketEl.dataset.state=e,e===`always`){this.marketEl.replaceChildren(),this.marketEl.removeAttribute(`title`);return}this.marketEl.title=t;let i=vt(`tcw-status-market-short`,n);i.setAttribute(`aria-hidden`,`true`),this.marketEl.replaceChildren(vt(`tcw-status-market-text`,t),i)}addHostItem(e){let t=e.onClick,n=t?document.createElement(`button`):document.createElement(`span`);return n.className=t?`tcw-status-host-item tcw-status-host-btn`:`tcw-status-host-item`,n.dataset.hostItem=e.id,n.dir=`auto`,n.textContent=e.text,e.label&&(n.title=e.label,t||n.setAttribute(`role`,`group`),e.label!==e.text&&n.setAttribute(`aria-label`,`${e.label}: ${e.text}`)),n instanceof HTMLButtonElement&&t&&(n.type=`button`,n.addEventListener(`click`,()=>t(n))),(e.side===`left`?this.hostLeft:this.hostRight).appendChild(n),n}hostSlot(e){return e===`left`?this.hostLeft:this.hostRight}destroy(){this.destroyed=!0,this.resizeObserver?.disconnect(),this.fitFrame&&cancelAnimationFrame(this.fitFrame),this.clockMenu?.destroy(),this.rangeMenu?.destroy(),this.el.remove()}buildClock(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-status-clock`,t.dataset.role=`clock`,t.dir=`auto`,t.title=e.label,t.setAttribute(`aria-haspopup`,`menu`),r.o(t,`statusBar.clock`),t.addEventListener(`click`,()=>this.toggleZones(t,e)),this.clockBtn=t,this.tick(),t}toggleRangeMenu(e,t){if(this.rangeMenu?.isOpen()){this.rangeMenu.close();return}let n=e=>e.hasAttribute(ut)&&!this.isOff(e),r=t.presets.filter((e,t)=>n(this.presetBtns[t])).map(e=>({id:e,label:t.presetLabels?.[e]??e}));if(this.goToBtn&&n(this.goToBtn)&&(r.length>0&&r.push(`separator`),r.push({id:ht,label:t.goToLabel,icon:`calendar`,shortcut:_t(t)})),r.length===0)return;this.rangeMenu??=new o.f(this.host,t.groupLabel);let i=e.getBoundingClientRect(),a=this.host.getBoundingClientRect();this.rangeMenu.open(r,i.left-a.left,i.top-a.top,e=>e===ht?t.onGoTo():t.onPreset(e),e,void 0,i.right-a.left)}toggleZones(e,t){if(this.clockMenu?.isOpen()){this.clockMenu.close();return}let{current:n,list:r}=t.options();this.clockMenu??=new o.f(this.host,t.label);let i=e.getBoundingClientRect(),a=this.host.getBoundingClientRect();this.clockMenu.open(r.map(e=>({id:e.value,label:e.label,checked:e.value===n})),i.left-a.left,i.top-a.top,e=>t.onPick(e),e,void 0,i.right-a.left)}buildScale(e){let t=document.createElement(`div`);t.className=`tcw-status-scale`,t.setAttribute(`role`,`group`),e.labels.group&&t.setAttribute(`aria-label`,e.labels.group),r.o(t,`statusBar.scale`);let n=(n,r,i)=>{let a=document.createElement(`button`);return a.type=`button`,a.className=`tcw-status-scale-btn`,a.dataset.scale=n,a.textContent=r,a.title=e.labels[n],a.setAttribute(`aria-label`,e.labels[n]),a.setAttribute(`aria-pressed`,`false`),a.addEventListener(`click`,i),t.appendChild(a),a};return this.scaleBtns={percent:n(`percent`,`%`,e.onPercent),...e.onLog?{log:n(`log`,e.texts?.log??`log`,e.onLog)}:{},auto:n(`auto`,e.texts?.auto??`auto`,e.onAuto)},t}hostGroup(){let e=document.createElement(`div`);return e.className=`tcw-status-host`,e}buildRange(e){let t=document.createElement(`div`);t.className=`tcw-range-bar`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,e.groupLabel);for(let n of e.presets){let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-range-btn`,i.dataset.range=n,r.o(i,`statusBar.range`),i.textContent=e.presetLabels?.[n]??n,i.addEventListener(`click`,()=>e.onPreset(n)),t.appendChild(i),this.presetBtns.push(i)}let n=this.rangeIconBtn(`tcw-range-more`,`rangeMore`,`more`,e.moreLabel);r.o(n,`statusBar.range`),n.setAttribute(`aria-haspopup`,`menu`),n.setAttribute(`aria-expanded`,`false`),n.addEventListener(`click`,()=>this.toggleRangeMenu(n,e)),t.appendChild(n),this.moreBtn=n;let i=this.rangeIconBtn(`tcw-range-goto`,`goto`,`calendar`,e.goToLabel);r.o(i,`goToDate`,`statusBar.goToDate`);let a=()=>{let t=_t(e);i.title=t?`${e.goToLabel} (${t})`:e.goToLabel};return a(),i.addEventListener(`pointerover`,a),i.addEventListener(`focusin`,a),i.addEventListener(`click`,e.onGoTo),t.appendChild(i),this.goToBtn=i,this.rangeEl=t,t}rangeIconBtn(e,t,n,r){let a=document.createElement(`button`);return a.type=`button`,a.className=`tcw-range-btn ${e}`,a.dataset.role=t,a.title=r,a.setAttribute(`aria-label`,r),a.innerHTML=i.i(n,mt),a}},O=[],bt=new Map,k=null,xt=e=>{let t=e.target instanceof Node?e.target:null;t!==null&&O.some(e=>e.contains(t)||bt.get(e)?.some(e=>e.contains(t)))||(k=null)};function St(e,t=[]){let n=()=>{k=e},r=[e,...t];for(let e of r)e.addEventListener(`pointerdown`,n,!0);return O.length===0&&document.addEventListener(`pointerdown`,xt,!0),O.push(e),bt.set(e,t),()=>{for(let e of r)e.removeEventListener(`pointerdown`,n,!0);let t=O.indexOf(e);t>=0&&O.splice(t,1),bt.delete(e),O.length===0&&document.removeEventListener(`pointerdown`,xt,!0),k===e&&(k=null)}}function A(e,t=!1){let n=k?.isConnected?k:null;if(!n){let e=document.activeElement;n=e?O.find(t=>t.contains(e))??null:null}return!n&&!t&&(n=O.find(e=>e.isConnected)??null),n!==null&&e.contains(n)}function j(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.tagName===`SELECT`||e.isContentEditable)}function M(){let e=document.activeElement;return e instanceof Element&&e.closest(`[role="dialog"], [aria-modal="true"], [role="menu"]`)!==null}var Ct={selectHint:`Click a bar to start the replay`,random:`Random bar`,realtime:`Back to realtime`,play:`Play`,pause:`Pause`,stepBack:`Step back (Shift+←)`,stepForward:`Step forward (Shift+→)`,replay:`Replay`,position:`Replay position`,speed:`Speed`,step:`Step`,loading:`Loading chart...`,selectBar:`Select bar`,cancel:`Cancel`,rate:`{rate}×`,rateHint:`1× plays one bar a second`,playingAt:`Playing at {rate}`,pausedAt:`Paused at {time}`,endedAt:`Replay ended at {time}`},wt=[.1,.2,.3,.5,1,2,3,5,10,20,30,50],Tt=[`full`,`compact`,`stack`],Et=300,Dt=2,Ot=[`random`,`stepBack`,`stepForward`,`seek`,`step`,`selectBar`],kt=class{root=null;scrubber=null;timeLabel=null;playBtn=null;realtimeBtn=null;liveRegion=null;hintText=null;state=`stopped`;mode=`select`;ended=!1;pending=!1;total=0;rate=1;steps=[];step=`bar`;dir=`ltr`;formatRate;where=``;announceTimer=null;widths=new Map;labels;constructor(e,t={}){this.callbacks=e,this.labels={...Ct,...t},this.formatRate=e=>this.labels.rate.replace(`{rate}`,String(e))}mount(e,t){this.root||(this.total=Math.max(0,t.total),this.rate=t.rate??1,this.steps=t.steps??[],this.step=t.step??`bar`,this.dir=t.dir??`ltr`,t.formatRate&&(this.formatRate=t.formatRate),this.state=`paused`,this.mode=t.mode??`select`,this.root=document.createElement(`div`),this.root.className=`tcw-replay-bar`,r.o(this.root,`replay`),this.root.setAttribute(`role`,`group`),this.root.setAttribute(`aria-label`,this.labels.replay),this.root.dataset.fit=`full`,this.root.innerHTML=this.markup(),e.appendChild(this.root),this.wireEvents(),this.syncUi())}unmount(){this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=null,this.root?.remove(),this.root=null,this.hintText=null,this.scrubber=null,this.timeLabel=null,this.playBtn=null,this.realtimeBtn=null,this.liveRegion=null,this.state=`stopped`,this.ended=!1,this.where=``}isMounted(){return this.root!==null}element(){return this.root}getMode(){return this.mode}setMode(e){let t=!!this.root?.contains(document.activeElement);this.mode=e,this.syncUi(),t&&(e===`replay`?(this.playBtn&&!this.playBtn.disabled?this.playBtn:this.realtimeBtn)?.focus():this.root?.querySelector(`[data-act="random"]`)?.focus())}setState(e){e!==this.state&&(this.state=e,this.syncUi(),this.mode===`replay`&&(e===`playing`?this.announce(this.labels.playingAt.replace(`{rate}`,this.formatRate(this.rate))):e===`paused`&&this.where&&this.announce(this.labels.pausedAt.replace(`{time}`,this.where))))}setEnded(e){this.ended!==e&&(this.ended=e,this.syncUi(),e&&this.where&&this.announce(this.labels.endedAt.replace(`{time}`,this.where)))}setPending(e){if(this.pending===e)return;this.pending=e;let t=document.activeElement;e&&t&&t!==this.playBtn&&this.root?.contains(t)&&Ot.includes(t.dataset.act??``)&&this.playBtn?.focus(),this.syncUi(),e&&this.mode===`replay`&&this.announce(this.labels.loading)}isPending(){return this.pending}setSteps(e,t){this.steps=e,this.step=t,this.widths.clear();let n=this.root?.querySelector(`[data-tcw="stepSlot"]`);n&&(n.innerHTML=this.stepMarkup(),this.wireStep(),this.syncUi())}setProgress(e,t,n){this.total=t;let r=n??`${Math.min(e+1,t)} / ${t}`,i=r!==this.where;if(this.where=r,this.scrubber){this.scrubber.max=String(Math.max(0,t-1)),this.scrubber.value=String(e),this.scrubber.setAttribute(`aria-valuetext`,r);let n=t>1?Math.min(e,t-1)/(t-1)*100:0;this.scrubber.style.setProperty(`--tcw-replay-done`,`${Number(n.toFixed(Dt))}%`)}if(this.timeLabel){this.timeLabel.textContent=r;let e=Number.parseFloat(this.timeLabel.style.minInlineSize)||0;r.length>e&&(this.timeLabel.style.minInlineSize=`${r.length}ch`)}let a=this.scrubber!==null&&document.activeElement===this.scrubber;i&&this.mode===`replay`&&this.state!==`playing`&&!a&&this.announce(r)}setRoom(e){let t=this.root;if(t){for(let n of Tt)if(n===`stack`||this.widthIn(n)<=e){t.dataset.fit=n,this.orderFor(n);return}}}orderFor(e){let t=this.root,n=t?.querySelector(`.tcw-replay-timeline`),r=t?.querySelector(`.tcw-replay-transport`),i=this.realtimeBtn;if(!t||!n||!r||!i)return;let a=e===`stack`;if(a===(n.nextElementSibling===i))return;let o=document.activeElement;a?r.before(n,i):(r.nextElementSibling?.after(n),t.querySelector(`[data-act="cancel"]`)?.before(i)),o&&t.contains(o)&&document.activeElement!==o&&o.focus()}getFit(){return this.root?.dataset.fit??`full`}destroy(){this.unmount()}widthIn(e){let t=this.root,n=`${this.mode}|${this.steps.length}|${e}`,r=this.widths.get(n);if(r!==void 0)return r;let i=t.dataset.fit;t.dataset.fit=e,t.dataset.measure=``;let a=t.getBoundingClientRect().width;return delete t.dataset.measure,i&&(t.dataset.fit=i),a>0&&this.widths.set(n,a),a}markup(){let e=this.labels,t=`dir="${this.dir}"`,n=wt.map(e=>`<option value="${e}"${e===this.rate?` selected`:``}>${a.u(this.formatRate(e))}</option>`).join(``),r=(e,t,n,r=`tcw-replay-btn`,i=``)=>`<button type="button" class="${r}" data-act="${e}" title="${a.u(t)}" aria-label="${a.u(t)}"${i}>${n}</button>`;return`
7763
+ `,b=0,ue=`tcw-styles`;function de(){if(b++,b>1||document.getElementById(ue))return;let e=document.createElement(`style`);e.id=ue,e.textContent=`${oe}
7764
+ ${se}
7765
+ ${ce}
7766
+ ${le}
7767
+ ${r.f()}`,document.head.insertBefore(e,document.head.firstChild)}function fe(){if(b--,b>0)return;let e=document.getElementById(ue);e&&e.remove()}var pe=class{trigger;panel;_isOpen=!1;onOutsideClick;onEscapeKey;onTriggerClick;layer;align;onAway=()=>this.close();onScroll=e=>{e.target instanceof Node&&this.panel.contains(e.target)||this.close()};constructor(e,t={}){this.trigger=e,this.layer=t.layer??null,this.align=t.align??`left`,this.panel=document.createElement(`div`),this.panel.className=`tcw-dropdown`,this.panel.style.minWidth=t.width??`200px`,this.panel.style.display=`none`,this.layer?(this.layer().appendChild(this.panel),this.panel.addEventListener(`click`,()=>this.close())):(this.align===`right`?this.panel.style.insetInlineEnd=`0px`:this.panel.style.insetInlineStart=`0px`,e.style.position=`relative`,e.appendChild(this.panel)),this.onTriggerClick=()=>{this._isOpen?this.close():this.open()},this.onOutsideClick=e=>{let t=e.target;!this.trigger.contains(t)&&!this.panel.contains(t)&&this.close()},this.onEscapeKey=e=>{e.key===`Escape`&&this.close()},e.addEventListener(`click`,this.onTriggerClick)}setContent(e){this.panel.innerHTML=e}open(){if(!this._isOpen){if(this._isOpen=!0,this.layer){let e=this.layer();this.panel.parentElement!==e&&e.appendChild(this.panel)}this.panel.style.display=``,this.layer&&(this.place(),window.addEventListener(`resize`,this.onAway),document.addEventListener(`scroll`,this.onScroll,{capture:!0,passive:!0})),document.addEventListener(`pointerdown`,this.onOutsideClick),document.addEventListener(`keydown`,this.onEscapeKey)}}close(){this._isOpen&&(this._isOpen=!1,this.panel.style.display=`none`,document.removeEventListener(`pointerdown`,this.onOutsideClick),document.removeEventListener(`keydown`,this.onEscapeKey),window.removeEventListener(`resize`,this.onAway),document.removeEventListener(`scroll`,this.onScroll,{capture:!0}))}isOpen(){return this._isOpen}destroy(){this.close(),this.trigger.removeEventListener(`click`,this.onTriggerClick),this.panel.remove()}place(){_(this.panel,this.trigger,this.align)}},me=[`1m`,`3m`,`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`1d`,`1w`,`1M`],he=[`1m`,`5m`,`15m`,`1h`,`4h`,`1d`],ge=6;function _e(e){let t=e.slice(-1);return t===`h`||t===`d`||t===`w`?e.slice(0,-1)+t.toUpperCase():e}var ve=e=>Number.isFinite((0,u.timeframeToMs)(e))||(0,u.tickBarCount)(e)!==null,ye=(e,t)=>{let n=(0,u.tickBarCount)(e),r=(0,u.tickBarCount)(t);return n!==null||r!==null?n===null?1:r===null?-1:n-r:(0,u.timeframeToMs)(e)-(0,u.timeframeToMs)(t)};function be(e,t){let n=t?.length?t:null,r=e?.length?e:n??me;return[...new Set(r)].filter(e=>ve(e)&&(!n||n.includes(e))).sort(ye)}function xe(e,t,n=!1){if(t?.length)return e.filter(e=>t.includes(e));if(n)return[...e];let r=e.filter(e=>he.includes(e));return r.length>0?r:e.slice(0,ge)}var Se=9999,Ce={"":`m`,s:`s`,S:`s`,m:`m`,h:`h`,H:`h`,d:`d`,D:`d`,w:`w`,W:`w`,M:`M`},we={s:[`m`,60],m:[`h`,60],h:[`d`,24]};function Te(e){let t=/^(\d+)([a-zA-Z]?)$/.exec(e.trim());if(!t)return null;if(t[2]===`T`||t[2]===`t`){let e=`${Number(t[1])}T`;return Number(t[1])<=Se&&(0,u.tickBarCount)(e)!==null?e:null}let n=Number(t[1]),r=Ce[t[2]];if(!r||!Number.isSafeInteger(n)||n<1)return null;for(let e=we[r];e&&n%e[1]===0;e=we[r])n/=e[1],r=e[0];if(n>Se)return null;let i=`${n}${r}`;return(0,u.isTimeFrame)(i)?i:null}function Ee(e,t,n){let r=n?.length?n:null,i=t.filter(e=>ve(e)&&(!r||r.includes(e)));return[...new Set([...e,...i])].sort(ye)}var De=[`T`,`s`,`m`,`h`,`d`,`w`,`M`];function Oe(e){let t=e=>{let t=e.slice(-1);return De.includes(t)?t:`m`};return De.map(n=>({unit:n,timeframes:e.filter(e=>t(e.value)===n)})).filter(e=>e.timeframes.length>0)}var ke=864e5,Ae=5/7;function je(e){let t=(0,u.timeframeToMs)(e.current),n=(0,u.timeframeToMs)(e.chosen);if(!Number.isFinite(t)||!Number.isFinite(n)||!(e.width>0)||!(e.spanMs>0))return e.current;let r=n=>{if(n===t)return e.barsInSpan;if(n<ke)return e.barsInSpan*t/n;let r=e.spanMs/n;return n===ke?r*(e.dayShare??Ae):r},i=[...new Set([...e.available,e.current])].filter(e=>{let t=(0,u.timeframeToMs)(e);return Number.isFinite(t)&&t>=n}).sort(ye);for(let t of i)if(r((0,u.timeframeToMs)(t))*2<=e.width)return t;return i[i.length-1]??e.current}var Me={ticket:`receipt`,long:`trendingUp`,short:`trendingDown`,ladder:`ladder`,account:`layers`},Ne=[`ladder`,`account`];function Pe(e,t){let n=[];e.onOrderTicket&&n.push({id:`ticket`,label:t(`chartMenu.orderTicket`),parts:[`orderTicket`],run:e.onOrderTicket});let r=e.onBracket;return r&&(n.push({id:`long`,label:t(`toolbar.longBracket`),parts:[`bracketOrders`,`toolbar.bracketOrders`],run:()=>r(`buy`)}),n.push({id:`short`,label:t(`toolbar.shortBracket`),parts:[`bracketOrders`,`toolbar.bracketOrders`],run:()=>r(`sell`)})),e.onToggleLadder&&n.push({id:`ladder`,label:t(`toolbar.depthLadder`),parts:[`depthLadder`,`toolbar.depthLadder`],run:e.onToggleLadder}),e.onToggleAccount&&n.push({id:`account`,label:t(`toolbar.account`),parts:[`accountPanel`,`toolbar.accountPanel`],run:e.onToggleAccount}),n}var Fe=class e{button;menu=null;open=new Set;static create(t,n,r,i){let a=Pe(t,n);return a.length>0?new e(a,n,r,i):null}constructor(e,t,n,o){this.items=e,this.t=t,this.root=n;let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-dropdown-trigger tcw-toolbar-overflow`,s.dataset.role=`trade`,s.dataset.icon=`trendingUp`,s.title=t(`toolbar.trade`),s.setAttribute(`aria-haspopup`,`menu`),s.setAttribute(`aria-expanded`,`false`),r.o(s,`toolbar.trade`),s.innerHTML=`${i.i(`trendingUp`,14)} <span class="tcw-trigger-label">${a.u(t(`toolbar.trade`))}</span> ${i.i(`chevronDown`,12)}`,s.addEventListener(`click`,()=>this.toggle(o(s))),this.button=s}tidy(){this.button.hidden=this.items.every(e=>this.isOff(e.parts))}setOpen(e,t){let n=Ne.find(t=>t===e);n&&(t?this.open.add(n):this.open.delete(n))}destroy(){this.menu?.destroy(),this.button.remove()}isOff(e){let t=new Set((this.root().getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean));return e.some(e=>t.has(e))}toggle(e){if(this.menu?.isOpen()){this.menu.close();return}let t=this.items.filter(e=>!this.isOff(e.parts));if(t.length===0)return;let n=t.filter(e=>!Ne.includes(e.id)),r=t.filter(e=>Ne.includes(e.id)),i=[...n.map(e=>({id:e.id,label:e.label,icon:Me[e.id]})),...n.length>0&&r.length>0?[`separator`]:[],...r.map(e=>({id:e.id,label:e.label,checked:this.open.has(e.id)}))],a=this.root();this.menu??=new o.f(a,this.t(`toolbar.trade`)),this.menu.openUnder(i,e,e=>{t.find(t=>t.id===e)?.run()})}},Ie=0,x=`data-tcw-folded`,Le=1/64,Re=[`venue`,`ticker`,`cut`],ze={T:`toolbar.timeframes.ticks`,s:`toolbar.timeframes.seconds`,m:`toolbar.timeframes.minutes`,h:`toolbar.timeframes.hours`,d:`toolbar.timeframes.days`,w:`toolbar.timeframes.weeks`,M:`toolbar.timeframes.months`};function Be(e,t){let n=e.querySelector(`.tcw-host-btn-text`)?.textContent??``;n===t?e.removeAttribute(`aria-label`):e.setAttribute(`aria-label`,n?`${t}: ${n}`:t)}var Ve=class{config;callbacks;t;el;chartTypeDropdown=null;tfGroup=null;tfDropdown=null;tfFavorites=[];uid=(Ie++).toString(36);tfRendered=``;themeBtn=null;fullscreenBtn=null;hostLeft=null;hostRight=null;moreMenu=null;tfCurrent=null;resizeObserver=null;hostObserver=null;moreBtn=null;fitFrame=0;destroyed=!1;undoBtn=null;redoBtn=null;trade=null;layoutShown=``;symbolShown=null;constructor(e,t,n,i,a){if(this.host=e,this.layer=a,this.config=t,this.callbacks=n,this.t=i,this.el=document.createElement(`div`),this.el.className=`tcw-toolbar`,r.o(this.el,`toolbar`),this.build(),e.appendChild(this.el),typeof ResizeObserver<`u`){this.resizeObserver=new ResizeObserver(()=>this.fit()),this.resizeObserver.observe(this.el),this.hostObserver=new ResizeObserver(()=>this.scheduleFit());for(let e of[this.hostLeft,this.hostRight])e&&this.hostObserver.observe(e)}document.fonts?.ready.then(()=>this.scheduleFit())}scheduleFit(){this.destroyed||this.fitFrame||typeof requestAnimationFrame>`u`||(this.fitFrame=requestAnimationFrame(()=>{this.fitFrame=0,this.destroyed||this.fit()}))}menuAnchor(e){return(e.hasAttribute(x)||this.el.closest(`[data-tcw-narrow]`)!==null)&&this.moreBtn?this.moreBtn:e}fit(){let e=this.toolbarFocus(),t=this.foldedState();this.refit(),this.foldedState()!==t&&this.closeStaleMenus(),e&&this.keepFocus(e)}refit(){let{el:e}=this,t=()=>this.fits(),n=[...e.querySelectorAll(`.tcw-toolbar-overflow`)];for(let e of n)e.removeAttribute(x);if(e.classList.remove(`tcw-toolbar--collapsed`,`tcw-toolbar--icons`),delete e.dataset.tcwSqueeze,!(e.clientWidth===0||t())){e.classList.add(`tcw-toolbar--collapsed`);for(let e=n.length-1;e>=0;e--)if(n[e].setAttribute(x,``),t())return;e.classList.add(`tcw-toolbar--icons`);for(let e of n)if(e.removeAttribute(x),!t()){e.setAttribute(x,``);break}for(let n of Re){if(t())return;e.dataset.tcwSqueeze=n}}}fits(){let{el:e}=this,t=e.getBoundingClientRect(),n=e.offsetWidth>0&&Math.abs(t.width-e.offsetWidth)>=1?t.width/e.offsetWidth:1,r=getComputedStyle(e),i=r.direction===`rtl`,a=e=>parseFloat(e)||0,o=t.width/n-(i?a(r.borderLeftWidth)+a(r.paddingLeft):a(r.borderRightWidth)+a(r.paddingRight)),s=0;for(let r of e.children){if(r.getClientRects().length===0)continue;let e=r.getBoundingClientRect();s=Math.max(s,(i?t.right-e.left:e.right-t.left)/n)}return Math.ceil(s-Le)<=Math.floor(o+Le)}foldedState(){let e=[...this.el.querySelectorAll(`.tcw-toolbar-overflow`)];return`${this.el.classList.contains(`tcw-toolbar--collapsed`)}:${e.map(e=>Number(e.hasAttribute(x))).join(``)}`}closeStaleMenus(){this.moreBtn&&o.f.closeAnchoredTo(this.moreBtn);for(let e of this.el.querySelectorAll(`[${x}], [${x}] button`))o.f.closeAnchoredTo(e)}toolbarFocus(){let e=o.f.focusedAnchor();if(e&&this.el.contains(e))return e;let t=document.activeElement;return t instanceof HTMLElement&&this.el.contains(t)?t:null}keepFocus(e){if(o.f.focusedAnchor())return;let t=e;this.shows(e)||(t=(this.moreBtn&&e!==this.moreBtn&&this.shows(this.moreBtn)?this.moreBtn:null)??this.overflowButtons().filter(e=>this.shows(e)).at(-1)),t&&document.activeElement!==t&&t.focus({preventScroll:!0})}overflowButtons(){return[...this.el.querySelectorAll(`button.tcw-toolbar-overflow, .tcw-toolbar-overflow button`)]}shows(e){if(e.closest(`[hidden]`)||e.closest(`[${x}]`)||this.isOff(e))return!1;let t=this.el.closest(`[data-tcw-narrow]`)!==null;return e===this.moreBtn?t||this.el.classList.contains(`tcw-toolbar--collapsed`):!(t&&e.closest(`.tcw-toolbar-overflow`))}isOff(e){let t=new Set((this.rootEl().getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean));for(let n=e;n&&n!==this.el;n=n.parentElement)if((n.dataset.tcwPart??``).split(/\s+/).some(e=>t.has(e)))return!0;return!1}build(){let{config:e,callbacks:t,el:n}=this,o=document.createElement(`button`);if(o.className=`tcw-toolbar-symbol`,o.dataset.role=`symbol`,o.dir=`ltr`,r.o(o,`toolbar.symbol`),o.addEventListener(`click`,t.onSymbolClick),n.appendChild(o),t.onSymbolInfo){let e=this.iconBtn(`info`,this.t(`symbolInfo.title`),t.onSymbolInfo);e.classList.remove(`tcw-toolbar-overflow`),e.dataset.role=`symbolInfo`,r.o(e,`symbolInfo`,`toolbar.symbolInfo`),n.appendChild(e)}if(n.appendChild(this.sep()),this.tfFavorites=[...e.timeframeFavorites??e.timeframes.map(e=>e.value)],this.tfGroup=document.createElement(`div`),this.tfGroup.className=`tcw-toolbar-group tcw-tf-group`,r.o(this.tfGroup,`toolbar.timeframes`),n.appendChild(this.tfGroup),t.onToggleTimeframeFavorite&&e.timeframes.length>0){let e=document.createElement(`div`);e.style.position=`relative`,e.style.display=`inline-flex`,r.o(e,`toolbar.timeframeMenu`);let t=document.createElement(`button`);t.className=`tcw-btn tcw-tf-more`,t.dataset.role=`timeframes`,t.title=this.t(`toolbar.timeframes`),t.setAttribute(`aria-label`,this.t(`toolbar.timeframes`)),this.tfCurrent=document.createElement(`span`),this.tfCurrent.className=`tcw-tf-current`,t.appendChild(this.tfCurrent),t.insertAdjacentHTML(`beforeend`,i.i(`chevronDown`,12)),e.appendChild(t),n.appendChild(e),this.tfDropdown=new pe(e,{width:`150px`,layer:this.layer}),n.classList.add(`tcw-toolbar--tf-menu`),this.buildTimeframeMenu()}n.appendChild(this.sep());let s=document.createElement(`div`);s.style.position=`relative`,s.style.display=`inline-flex`,r.o(s,`toolbar.chartType`);let c=document.createElement(`button`);c.className=`tcw-dropdown-trigger`,c.dataset.role=`charttype`,s.appendChild(c),n.appendChild(s),this.chartTypeDropdown=new pe(s,{width:`160px`,layer:this.layer}),this.buildChartTypeMenu(),n.appendChild(this.sep());let l=document.createElement(`button`);if(l.type=`button`,l.className=`tcw-dropdown-trigger`,l.dataset.role=`indicators`,l.setAttribute(`aria-haspopup`,`dialog`),l.setAttribute(`aria-expanded`,`false`),r.o(l,`toolbar.indicators`),l.addEventListener(`click`,()=>t.onIndicators()),n.appendChild(l),t.onCompare){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-dropdown-trigger`,e.dataset.role=`compare`,r.o(e,`compare`,`toolbar.compare`);let o=this.t(`objects.compare`);e.setAttribute(`aria-label`,o),e.title=o,e.innerHTML=`${i.i(`plus`,14)} <span class="tcw-trigger-label">${a.u(o)}</span>`,e.addEventListener(`click`,t.onCompare),n.appendChild(e)}if(this.hostLeft=this.hostGroup(),n.appendChild(this.hostLeft),t.onUndo&&t.onRedo&&(n.appendChild(this.sep()),this.undoBtn=this.iconBtn(`undo`,this.t(`drawing.undo`),t.onUndo),this.undoBtn.dataset.role=`undo`,r.o(this.undoBtn,`toolbar.undo`,`sidebar.undo`),this.redoBtn=this.iconBtn(`redo`,this.t(`drawing.redo`),t.onRedo),this.redoBtn.dataset.role=`redo`,r.o(this.redoBtn,`toolbar.redo`,`sidebar.redo`),n.append(this.undoBtn,this.redoBtn),this.setHistory(!1,!1)),n.appendChild(this.spacer()),t.onLayouts){let e=t.onLayouts,i=document.createElement(`button`);i.type=`button`,i.className=`tcw-dropdown-trigger tcw-layouts-btn tcw-toolbar-overflow`,i.dataset.role=`layouts`,i.dataset.icon=`save`,r.o(i,`layouts`,`toolbar.layouts`),i.setAttribute(`aria-haspopup`,`menu`),i.addEventListener(`click`,()=>e(this.menuAnchor(i))),n.appendChild(i),this.setLayout(null,!1)}if(this.hostRight=this.hostGroup(),n.appendChild(this.hostRight),n.appendChild(this.sep()),t.onToggleReplay){let e=this.iconBtn(`play`,this.t(`toolbar.replay`),t.onToggleReplay);e.dataset.role=`replay`,r.o(e,`replay`,`toolbar.replay`),n.appendChild(e)}if(t.onToggleObjects){let e=this.iconBtn(`layers`,this.t(`toolbar.objects`),t.onToggleObjects);e.dataset.role=`objects`,e.setAttribute(`aria-pressed`,`false`),r.o(e,`objectTree`,`toolbar.objectTree`),n.appendChild(e)}if(t.onToggleAlerts){let e=this.iconBtn(`bell`,this.t(`toolbar.priceAlerts`),t.onToggleAlerts);e.dataset.role=`alerts`,e.setAttribute(`aria-pressed`,`false`),r.o(e,`alerts`,`toolbar.alerts`),n.appendChild(e)}this.trade=Fe.create(t,this.t,()=>this.rootEl(),e=>this.menuAnchor(e)),this.trade&&n.appendChild(this.trade.button),n.appendChild(this.sep());let u=this.iconBtn(`camera`,this.t(`toolbar.screenshot`),t.onScreenshot);r.o(u,`screenshot`,`toolbar.screenshot`),n.appendChild(u);let d=this.iconBtn(`settings`,this.t(`toolbar.settings`),t.onSettings);r.o(d,`settings`,`toolbar.settings`),n.appendChild(d),this.themeBtn=this.iconBtn(`moon`,this.t(`toolbar.toggleTheme`),t.onToggleTheme),this.themeBtn.dataset.role=`theme`,r.o(this.themeBtn,`themeToggle`,`toolbar.themeToggle`),n.appendChild(this.themeBtn),t.onToggleFullscreen&&(this.fullscreenBtn=this.iconBtn(`maximize`,this.t(`toolbar.fullscreen`),t.onToggleFullscreen),this.fullscreenBtn.dataset.role=`fullscreen`,r.o(this.fullscreenBtn,`fullscreen`,`toolbar.fullscreen`),this.fullscreenBtn.setAttribute(`aria-pressed`,`false`),n.appendChild(this.fullscreenBtn));let f=document.createElement(`button`);f.type=`button`,f.className=`tcw-btn-icon tcw-toolbar-more`,f.title=this.t(`toolbar.more`),f.setAttribute(`aria-haspopup`,`menu`),f.setAttribute(`aria-expanded`,`false`),f.innerHTML=i.i(`more`,16),f.addEventListener(`click`,()=>this.toggleMore(f)),n.appendChild(f),this.moreBtn=f}toggleMore(e){if(o.f.closeAnchoredTo(e))return;let t=this.rootEl(),n=this.el.closest(`[data-tcw-narrow]`)!==null,r=[];for(let e of this.el.querySelectorAll(`.tcw-toolbar-overflow`)){if(this.isOff(e)||!n&&!e.hasAttribute(x))continue;let t=e instanceof HTMLButtonElement?[e]:[...e.querySelectorAll(`button`)];r.push(...t.filter(e=>!e.hidden&&!e.disabled&&!this.isOff(e)))}if(r.length===0)return;let i=r.map((e,t)=>{let n=e.getAttribute(`aria-label`)||e.title||e.textContent?.trim()||``,r=e.getAttribute(`aria-pressed`);return r===null?{id:String(t),label:n,icon:e.dataset.icon}:{id:String(t),label:n,icon:e.dataset.icon,checked:r===`true`}});this.moreMenu??=new o.f(t,this.t(`toolbar.more`)),this.moreMenu.openUnder(i,e,e=>r[Number(e)]?.click(),`end`)}addHostButton(e){let t=document.createElement(`button`);t.type=`button`,t.className=`${e.text||!e.icon?`tcw-btn`:`tcw-btn-icon`} tcw-host-btn tcw-toolbar-overflow`,t.dataset.hostButton=e.id,typeof e.icon==`string`&&(t.dataset.icon=e.icon),t.title=e.label,e.toggle&&t.setAttribute(`aria-pressed`,`false`),typeof e.icon==`string`?t.innerHTML=i.i(e.icon,14):e.icon&&t.appendChild(e.icon);let n=e.text??(e.icon?``:e.label);if(n){let e=document.createElement(`span`);e.className=`tcw-host-btn-text`,e.textContent=n,t.appendChild(e)}return Be(t,e.label),t.addEventListener(`click`,()=>e.onClick(t)),(e.side===`left`?this.hostLeft:this.hostRight)?.appendChild(t),this.scheduleFit(),t}hostSlot(e){return e===`left`?this.hostLeft:this.hostRight}hostGroup(){let e=document.createElement(`div`);return e.className=`tcw-toolbar-host`,e}setSymbolSearch(e){let t=this.el.querySelector(`[data-role="symbol"]`);t&&(e?t.removeAttribute(`aria-disabled`):t.setAttribute(`aria-disabled`,`true`))}tidy(){this.trade?.tidy(),r.d(this.el,`tcw-toolbar-sep`,`tcw-toolbar-spacer`),this.scheduleFit()}setHistory(e,t){this.undoBtn&&(this.undoBtn.disabled=!e),this.redoBtn&&(this.redoBtn.disabled=!t)}rootEl(){return this.el.closest(`.tcw-root`)??this.host}setActive(e,t){this.trade?.setOpen(e,t);let n=this.el.querySelector(`[data-role="${e}"]`);n&&(n.classList.toggle(`tcw-active`,t),n.setAttribute(`aria-pressed`,String(t)))}setRailed(e,t){let n=this.el.querySelector(`[data-role="${e}"]`);n&&(n.hidden=t)}setLayout(e,t){let n=this.el.querySelector(`[data-role="layouts"]`);if(!n)return;let r=e??this.t(`layouts.unnamed`);if(this.layoutShown===`${t}:${r}`)return;this.layoutShown=`${t}:${r}`;let o=`${this.t(`toolbar.layouts`)}: ${r}${t?` (${this.t(`layouts.unsavedChanges`)})`:``}`;n.innerHTML=`${i.i(`save`,14)}<span class="tcw-layouts-label">${a.u(r)}</span>`+(t?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+i.i(`chevronDown`,12),n.title=o,n.setAttribute(`aria-label`,o),this.scheduleFit()}setFullscreen(e){if(!this.fullscreenBtn)return;let t=this.t(e?`toolbar.exitFullscreen`:`toolbar.fullscreen`);this.fullscreenBtn.innerHTML=i.i(e?`minimize`:`maximize`,14),this.fullscreenBtn.title=t,this.fullscreenBtn.setAttribute(`aria-pressed`,String(e))}chartTypeLabel(e){return t.t(e,this.t)}buildChartTypeMenu(){if(!this.chartTypeDropdown)return;let e=this.config.chartTypes.map(e=>`<button class="tcw-dropdown-item tcw-dropdown-item--icon" data-ct="${a.u(e.value)}">${i.r(e.value,16)}<span>${a.u(this.chartTypeLabel(e))}</span></button>`).join(``);this.chartTypeDropdown.setContent(e),this.chartTypeDropdown.panel.querySelectorAll(`.tcw-dropdown-item`).forEach(e=>{e.addEventListener(`click`,e=>{let t=e.currentTarget.dataset.ct;this.callbacks.onChartType(t),this.chartTypeDropdown?.close()})})}setSymbolDescription(e){let t=this.el.querySelector(`[data-role="symbol"]`);t&&(e?t.title=e:t.removeAttribute(`title`))}setTimeframes(e,t){this.config={...this.config,timeframes:e},this.setTimeframeFavorites(t)}setTimeframeFavorites(e){this.tfFavorites=[...e],this.tfRendered=``,this.buildTimeframeMenu()}buildTimeframeMenu(){if(!this.tfDropdown)return;let e=a.u(this.t(`toolbar.timeframes.pin`)),t=a.u(this.t(`toolbar.timeframes.remove`)),n=``;for(let{unit:r,timeframes:o}of Oe(this.config.timeframes)){n+=`<div class="tcw-tf-section" data-tf-section="${r}" role="group" aria-label="${a.u(this.t(ze[r]))}"><div class="tcw-dropdown-label">${a.u(this.t(ze[r]))}</div>`;for(let r of o){let o=this.tfFavorites.includes(r.value),[s,c]=[a.u(r.value),a.u(r.label)];n+=`<div class="tcw-tf-row"><button class="tcw-dropdown-item" data-tf-pick="${s}">${c}</button>`+(r.custom&&this.callbacks.onRemoveTimeframe?`<button class="tcw-tf-remove" data-tf-remove="${s}" title="${t}" aria-label="${t}: ${c}">${i.i(`x`,12)}</button>`:``)+`<button class="tcw-tf-star${o?` tcw-active`:``}" data-tf-star="${s}" aria-pressed="${o}" title="${e}" aria-label="${e}: ${c}">${i.i(`star`,12)}</button></div>`}n+=`</div>`}if(this.callbacks.onAddTimeframe){let e=a.u(this.t(`toolbar.timeframes.custom`)),t=a.u(this.t(`toolbar.timeframes.add`));n+=`<form class="tcw-tf-custom" ${r.c(`customTimeframes`)} novalidate><input class="tcw-tf-custom-input" type="text" autocomplete="off" spellcheck="false" maxlength="6" placeholder="7m, 90m, 2h…" aria-label="${e}" aria-describedby="tcw-tf-hint-${this.uid}"><button type="submit" class="tcw-tf-custom-add" title="${t}" aria-label="${t}">${i.i(`plus`,12)}</button><div class="tcw-tf-custom-hint" id="tcw-tf-hint-${this.uid}" role="status"></div></form>`}this.tfDropdown.setContent(n);let o=this.tfDropdown.panel;o.querySelectorAll(`[data-tf-pick]`).forEach(e=>{e.addEventListener(`click`,()=>this.callbacks.onTimeframe(e.dataset.tfPick))}),o.querySelectorAll(`[data-tf-star]`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onToggleTimeframeFavorite?.(e.dataset.tfStar)})}),o.querySelectorAll(`[data-tf-remove]`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onRemoveTimeframe?.(e.dataset.tfRemove)})});let s=o.querySelector(`.tcw-tf-custom`);s&&this.wireCustomTimeframe(s)}wireCustomTimeframe(e){let t=e.querySelector(`.tcw-tf-custom-input`),n=e.querySelector(`.tcw-tf-custom-hint`);e.addEventListener(`click`,e=>e.stopPropagation()),t.addEventListener(`input`,()=>{t.removeAttribute(`aria-invalid`),n.textContent=``}),e.addEventListener(`submit`,e=>{e.preventDefault(),e.stopPropagation(),this.callbacks.onAddTimeframe?.(t.value)?(t.value=``,n.textContent=``,this.tfDropdown?.close(),this.el.querySelector(`[data-role="timeframes"]`)?.focus()):(t.setAttribute(`aria-invalid`,`true`),n.textContent=this.t(`toolbar.timeframes.invalid`))})}renderTimeframes(e){if(!this.tfGroup)return;let t=this.config.timeframes.filter(t=>this.tfFavorites.includes(t.value)||t.value===e),n=`${t.map(e=>e.value).join(`,`)}|${e}`;n!==this.tfRendered&&(this.tfRendered=n,this.tfCurrent&&(this.tfCurrent.textContent=this.config.timeframes.find(t=>t.value===e)?.label??e),this.tfGroup.replaceChildren(...t.map(t=>{let n=document.createElement(`button`);return n.className=`tcw-btn`,n.textContent=t.label,n.dataset.tf=t.value,n.classList.toggle(`tcw-active`,t.value===e),n.addEventListener(`click`,()=>this.callbacks.onTimeframe(t.value)),n})),(this.tfDropdown?.panel)?.querySelectorAll(`[data-tf-pick]`).forEach(t=>{t.classList.toggle(`tcw-active`,t.dataset.tfPick===e)}))}setIndicatorsOpen(e){this.el.querySelector(`[data-role="indicators"]`)?.setAttribute(`aria-expanded`,String(e))}renderSymbol(e){let t=this.el.querySelector(`[data-role="symbol"]`);if(!t||this.symbolShown===e)return;this.symbolShown=e;let{venue:n,ticker:r}=a.c(e),i=(e,t)=>{let n=document.createElement(`span`);return n.className=e,n.textContent=t,n};t.replaceChildren(...n?[i(`tcw-toolbar-venue`,n)]:[],i(`tcw-toolbar-ticker`,r)),t.classList.toggle(`tcw-toolbar-symbol--venue`,n!==``),t.setAttribute(`aria-label`,e)}update(e){this.renderSymbol(e.symbol),this.renderTimeframes(e.timeframe);let t=this.el.querySelector(`[data-role="charttype"]`);if(t){let n=this.config.chartTypes.find(t=>t.value===e.chartType),r=n?this.chartTypeLabel(n):e.chartType;t.innerHTML=i.r(e.chartType,16),t.title=r,t.setAttribute(`aria-label`,r)}let n=this.el.querySelector(`[data-role="indicators"]`);if(n){let t=[...e.activeIndicators.values()].filter(e=>!d.SYMBOL_INDICATOR_IDS.has(e.id)).length,r=`${i.i(`trendingUp`,14)} <span class="tcw-trigger-label">${a.u(this.t(`toolbar.indicators`))}</span>`;n.setAttribute(`aria-label`,this.t(`toolbar.indicators`)),t>0&&(r+=` <span class="tcw-badge-count">${t}</span>`),n.innerHTML=r}if(this.themeBtn){let t=e.isDark?`moon`:`sun`;this.themeBtn.innerHTML=i.i(t,14),this.themeBtn.dataset.icon=t}this.scheduleFit()}sep(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-sep`,e}spacer(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-spacer`,e}iconBtn(e,t,n){let r=document.createElement(`button`);return r.className=`tcw-btn-icon tcw-toolbar-overflow`,r.dataset.icon=e,r.title=t,r.innerHTML=i.i(e,14),r.addEventListener(`click`,n),r}destroy(){this.destroyed=!0,this.resizeObserver?.disconnect(),this.hostObserver?.disconnect(),this.fitFrame&&cancelAnimationFrame(this.fitFrame),this.chartTypeDropdown?.destroy(),this.tfDropdown?.destroy(),this.moreMenu?.destroy(),this.trade?.destroy(),this.el.remove()}};function He(e,t,n){e.classList.toggle(`tcw-active`,t),n&&e.setAttribute(`aria-pressed`,String(t))}function Ue(e,t,n){let r=n==null?``:String(n),i=e.querySelector(`.tcw-host-btn-text`);return(i?.textContent??``)===r?!1:(i||(i=document.createElement(`span`),i.className=`tcw-host-btn-text`,e.appendChild(i)),i.textContent=r,Be(e,t),!0)}var We=100,S=null,Ge=null,Ke=0,qe=!1,C=new Set;function Je(e){S&&(S.sources.set(e,e.version),e.subs.add(S))}function Ye(e){for(let t of[...e.subs])t.mark()}function Xe(e){for(let t of e.sources.keys())t.subs.delete(e),t instanceof et&&t.subs.size===0&&t.release();e.sources.clear()}function Ze(e){for(let[t,n]of e.sources)if(t.refresh(),t.version!==n)return!0;return!1}function Qe(e,t){Xe(e);let n=S;S=e;try{return t()}finally{S=n}}var $e=class{version=0;subs=new Set;constructor(e){this.value=e}refresh(){}get(){return Je(this),this.value}peek(){return this.value}set(e){Object.is(e,this.value)||(this.value=e,this.version++,at(()=>Ye(this)))}update(e){this.set(e(this.value))}},et=class{version=0;subs=new Set;sources=new Map;dirty=!0;value;computed=!1;constructor(e){this.fn=e}mark(){this.dirty||(this.dirty=!0,Ye(this))}refresh(){if(!this.dirty)return;if(this.computed&&!Ze(this)){this.dirty=!1;return}let e=Qe(this,this.fn);this.dirty=!1,!(this.computed&&Object.is(e,this.value))&&(this.value=e,this.computed=!0,this.version++)}get(){return this.refresh(),Je(this),this.value}peek(){return this.refresh(),this.value}release(){Xe(this),this.dirty=!0,this.computed=!1}},tt=class{sources=new Map;cleanup=void 0;disposed=!1;constructor(e){this.fn=e}mark(){this.disposed||C.add(this)}run(){let e=this.cleanup;this.cleanup=void 0,e?.(),this.cleanup=Qe(this,this.fn)}runIfStale(){!this.disposed&&Ze(this)&&this.run()}dispose(){this.disposed||(this.disposed=!0,C.delete(this),Xe(this),this.cleanup?.(),this.cleanup=void 0)}};function nt(){if(qe)return;qe=!0;let e=0,t=null;try{for(;C.size>0;){if(++e>We)throw C.clear(),Error(`signals: an effect did not settle; it keeps changing what it reads`);let n=[...C];C.clear();for(let e of n)try{e.runIfStale()}catch(e){t??={error:e}}}}finally{qe=!1}if(t)throw t.error}function rt(e){return new $e(e)}function it(e){let t=new tt(e),n=()=>t.dispose();return Ge?.push(n),at(()=>t.run()),n}function at(e){Ke++;try{return e()}finally{Ke--,Ke===0&&nt()}}function ot(){let e=[];return{run(t){let n=Ge;Ge=e;try{return t()}finally{Ge=n}},dispose(){for(let t of e.splice(0))t()}}}var st=`--tcw-tool-fit`;function ct({button:e,count:t,overflow:n,min:r}){return n<=0||t<=0||e<=r?null:Math.max(r,e-Math.ceil(n/t))}function lt(e){if(e.style.removeProperty(st),e.clientHeight===0)return;let t=[...e.querySelectorAll(`.tcw-sidebar-btn`)].filter(e=>e.offsetHeight>0),n=ct({button:t[0]?.offsetHeight??0,count:t.length,overflow:e.scrollHeight-e.clientHeight,min:parseFloat(getComputedStyle(e).getPropertyValue(`--tcw-control-h`))||0});n!==null&&e.style.setProperty(st,`${n}px`)}function ut(e){let t=0,n=null,r=()=>{t||typeof requestAnimationFrame>`u`||(t=requestAnimationFrame(()=>{t=0,!n&&o&&(n=e.closest(`.tcw-root`),n&&o.observe(n,{attributes:!0})),lt(e)}))},i=typeof ResizeObserver>`u`?null:new ResizeObserver(r);i?.observe(e);let a=typeof MutationObserver>`u`?null:new MutationObserver(r);a?.observe(e,{childList:!0,subtree:!0});let o=typeof MutationObserver>`u`?null:new MutationObserver(r),s=e.ownerDocument.defaultView;return s?.addEventListener(`resize`,r),r(),()=>{s?.removeEventListener(`resize`,r),t&&cancelAnimationFrame(t),i?.disconnect(),a?.disconnect(),o?.disconnect()}}var dt=16,ft=150,pt=4;function mt(e){let t=`sidebar.${e}`;return r.r.includes(t)?t:null}function ht(e,t){for(let n of e){let e=n.tools.find(e=>e.value===t);if(e)return e.label}return t}var gt=`--tcw-fab-plot-left`,_t=class{config;callbacks;el;groupWraps=[];groupButtons=[];groupIcons=[];groupTools=[];cursorBtn=null;magnetBtn=null;eraserBtn=null;zoomBtn=null;stayBtn=null;lockAllBtn=null;hideAllBtn=null;drawings={locked:!1,hidden:!1};flyoutEl=null;flyoutIdx=-1;flyoutHideTimer=null;hostEl=null;favoritesEl=null;favoritesDivider=null;favorites=[];fab;fabShows=``;stopFit;onPressAway=e=>{let t=e.target;t&&(this.el.contains(t)||this.fab.contains(t)||this.flyoutEl?.contains(t))||this.setOpen(!1)};onEscape=e=>{e.key===`Escape`&&!this.flyoutEl&&this.setOpen(!1)};constructor(e,t,n,a=s.t){this.host=e,this.t=a,this.config=t,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-sidebar`,r.o(this.el,`sidebar`),this.build(),this.el.addEventListener(`scroll`,()=>this.hideFlyout(),{passive:!0}),e.appendChild(this.el),this.stopFit=ut(this.el),this.fab=document.createElement(`button`),this.fab.type=`button`,this.fab.className=`tcw-sidebar-fab`,this.fab.setAttribute(`aria-label`,this.t(`drawing.tools`)),this.fab.setAttribute(`aria-expanded`,`false`),this.fab.innerHTML=i.i(`penLine`,18),r.o(this.fab,`sidebar`),this.fab.addEventListener(`click`,()=>this.setOpen(!this.isOpen())),e.appendChild(this.fab)}setPlotLeft(e){let t=`${Math.max(0,Math.round(e))}px`;this.fab.style.getPropertyValue(gt)!==t&&this.fab.style.setProperty(gt,t)}isNarrow(){return this.el.closest(`[data-tcw-narrow]`)!==null}isOpen(){return this.el.classList.contains(`tcw-sidebar-open`)}setOpen(e){if(e!==this.isOpen())if(this.el.classList.toggle(`tcw-sidebar-open`,e),this.fab.setAttribute(`aria-expanded`,String(e)),e)document.addEventListener(`pointerdown`,this.onPressAway,!0),document.addEventListener(`keydown`,this.onEscape);else{let e=this.el.contains(document.activeElement)||!!this.flyoutEl?.contains(document.activeElement);this.hideFlyout(),document.removeEventListener(`pointerdown`,this.onPressAway,!0),document.removeEventListener(`keydown`,this.onEscape),e&&this.isNarrow()&&this.fab.focus({preventScroll:!0})}}closeOverlay(){this.setOpen(!1)}closeForChart(){this.isNarrow()&&this.setOpen(!1)}pick(e){this.callbacks.onDrawingTool(e),this.closeForChart()}build(){let{config:e,callbacks:t,el:n}=this;this.cursorBtn=document.createElement(`button`),this.cursorBtn.className=`tcw-sidebar-btn`,this.cursorBtn.title=this.t(`drawing.cursor`),this.cursorBtn.innerHTML=i.i(`cursor`,14),this.cursorBtn.addEventListener(`click`,()=>{t.onCancelDrawing(),this.closeForChart()}),r.o(this.cursorBtn,`sidebar.cursor`),n.appendChild(this.cursorBtn),n.appendChild(this.divider()),t.onToggleFavorite&&(this.favorites=[...e.favorites??[]],this.favoritesEl=document.createElement(`div`),this.favoritesEl.className=`tcw-sidebar-favorites`,r.o(this.favoritesEl,`sidebar.favorites`),n.appendChild(this.favoritesEl),this.favoritesDivider=this.divider(),r.o(this.favoritesDivider,`sidebar.favorites`),n.appendChild(this.favoritesDivider),this.renderFavorites());let a;e.drawingToolGroups.forEach((e,t)=>{if(!e.tools[0])return;e.section!==void 0&&a!==void 0&&e.section!==a&&this.appendDivider(),a=e.section;let o=document.createElement(`div`);o.className=`tcw-tool-group-wrap`;let s=mt(e.section);s&&r.o(o,s);let c=document.createElement(`button`);c.className=`tcw-sidebar-btn`;let l=e.tools[0].value;e.tools.length>1?c.setAttribute(`aria-label`,`${e.label}: ${e.tools[0].label}`):c.title=e.label;let u=document.createElement(`span`);if(u.className=`tcw-sidebar-icon`,u.innerHTML=i.a(l,dt),c.appendChild(u),this.groupIcons.push(u),this.groupTools.push(l),e.tools.length>1){let e=document.createElement(`span`);e.className=`tcw-multi-dot`,c.appendChild(e)}c.addEventListener(`click`,()=>{if(this.isNarrow()&&e.tools.length>1){this.flyoutEl&&this.flyoutIdx===t?this.hideFlyout():this.showFlyout(t);return}this.pick(this.groupTools[t])}),o.appendChild(c),o.addEventListener(`mouseenter`,()=>{this.isNarrow()||this.showFlyout(t)}),o.addEventListener(`mouseleave`,()=>{this.isNarrow()||this.scheduleHideFlyout()}),e.tools.length>1&&(c.setAttribute(`aria-haspopup`,`menu`),c.setAttribute(`aria-expanded`,`false`),c.addEventListener(`keydown`,e=>{e.key===`ArrowRight`||e.key===`ArrowDown`?(e.preventDefault(),this.showFlyout(t),this.focusFlyoutItem(0)):e.key===`Escape`&&this.flyoutEl&&(e.stopPropagation(),this.hideFlyout())})),o.addEventListener(`focusout`,e=>{let t=e.relatedTarget;!o.contains(t)&&!this.flyoutEl?.contains(t)&&this.scheduleHideFlyout()}),n.appendChild(o),this.groupWraps.push(o),this.groupButtons.push(c)});let o=document.createElement(`div`);if(o.className=`tcw-sidebar-spacer`,n.appendChild(o),n.appendChild(this.divider()),t.onToggleStyle){let e=document.createElement(`button`);e.className=`tcw-sidebar-btn`,e.title=this.t(`drawing.style`),e.dataset.role=`style`,r.o(e,`sidebar.style`),e.innerHTML=i.i(`palette`,14);let a=t.onToggleStyle;e.addEventListener(`click`,()=>{a(),this.closeForChart()}),n.appendChild(e)}if(t.onToggleMagnet&&(this.magnetBtn=document.createElement(`button`),this.magnetBtn.className=`tcw-sidebar-btn`,this.magnetBtn.title=this.t(`drawing.magnet`),this.magnetBtn.innerHTML=i.i(`magnet`,14),this.magnetBtn.addEventListener(`click`,t.onToggleMagnet),r.o(this.magnetBtn,`sidebar.magnet`),n.appendChild(this.magnetBtn)),t.onToggleEraser){let e=t.onToggleEraser;this.eraserBtn=this.toggleButton(`eraser`,this.t(`drawing.eraser`),()=>{e(),this.closeForChart()}),r.o(this.eraserBtn,`sidebar.eraser`),n.appendChild(this.eraserBtn)}if(t.onToggleZoomArea){let e=t.onToggleZoomArea;this.zoomBtn=this.toggleButton(`zoomIn`,this.t(`drawing.zoomArea`),()=>{e(),this.closeForChart()}),r.o(this.zoomBtn,`sidebar.zoomArea`),n.appendChild(this.zoomBtn)}if(t.onToggleStayInDrawing&&(this.stayBtn=document.createElement(`button`),this.stayBtn.className=`tcw-sidebar-btn`,this.stayBtn.dataset.role=`stay`,this.stayBtn.title=this.t(`drawing.stay`),this.stayBtn.setAttribute(`aria-pressed`,`false`),this.stayBtn.innerHTML=i.i(`repeat`,14),this.stayBtn.addEventListener(`click`,t.onToggleStayInDrawing),r.o(this.stayBtn,`sidebar.stayInDrawing`),n.appendChild(this.stayBtn)),this.hostEl=document.createElement(`div`),this.hostEl.className=`tcw-sidebar-host`,n.appendChild(this.hostEl),this.appendDivider(),t.onLockAll){let e=t.onLockAll;this.lockAllBtn=this.toggleButton(`lock`,this.t(`drawing.lockAll`),()=>e(!this.drawings.locked)),this.lockAllBtn.dataset.role=`lockAll`,r.o(this.lockAllBtn,`sidebar.lockAll`),n.appendChild(this.lockAllBtn)}if(t.onHideAll){let e=t.onHideAll;this.hideAllBtn=this.toggleButton(`eyeOff`,this.t(`drawing.hideAll`),()=>e(!this.drawings.hidden)),this.hideAllBtn.dataset.role=`hideAll`,r.o(this.hideAllBtn,`sidebar.hideAll`),n.appendChild(this.hideAllBtn)}let s=document.createElement(`button`);s.className=`tcw-sidebar-btn tcw-danger`,s.title=this.t(`drawing.clearAll`),s.innerHTML=i.i(`trash`,14),s.setAttribute(`aria-haspopup`,`menu`),s.setAttribute(`aria-expanded`,`false`),s.addEventListener(`click`,()=>t.onClear(s)),r.o(s,`sidebar.clear`),n.appendChild(s)}setDrawingsState(e){if(!(e.locked===this.drawings.locked&&e.hidden===this.drawings.hidden)){this.drawings={...e};for(let[t,n]of[[this.lockAllBtn,e.locked],[this.hideAllBtn,e.hidden]])t?.setAttribute(`aria-pressed`,String(n)),t?.classList.toggle(`tcw-active`,n)}}setFavorites(e){this.favorites=[...e],this.renderFavorites();for(let e of this.flyoutEl?.querySelectorAll(`.tcw-flyout-row`)??[]){let t=this.favorites.includes(e.dataset.toolValue??``);e.classList.toggle(`tcw-flyout-faved`,t),e.querySelector(`[data-pin]`)?.setAttribute(`aria-pressed`,String(t))}}renderFavorites(){if(!this.favoritesEl)return;this.favoritesEl.replaceChildren();let e=this.favorites.length>0;this.favoritesEl.style.display=e?``:`none`,this.favoritesDivider&&(this.favoritesDivider.style.display=e?``:`none`);for(let e of this.favorites){let t=document.createElement(`button`);t.className=`tcw-sidebar-btn`,t.title=s.r(this.t(`sidebar.unpinHint`),{tool:ht(this.config.drawingToolGroups,e)}),t.dataset.toolValue=e,t.innerHTML=i.a(e,dt),t.addEventListener(`click`,()=>this.pick(e)),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.callbacks.onToggleFavorite?.(e)}),this.favoritesEl.appendChild(t)}}showFlyout(e){if(this.cancelHideFlyout(),this.flyoutEl&&this.flyoutIdx===e)return;let t=this.config.drawingToolGroups[e];if(!t||t.tools.length<=1){this.hideFlyout();return}this.hideFlyout();let n=document.createElement(`div`);n.className=`tcw-flyout`,n.setAttribute(`role`,`menu`),n.setAttribute(`aria-label`,t.label),n.addEventListener(`keydown`,t=>this.onFlyoutKey(t,e));let a=document.createElement(`div`);a.className=`tcw-flyout-header`,a.textContent=t.label,n.appendChild(a);let o=this.t(`drawing.pinFavorite`);for(let e of t.tools){let t=document.createElement(`div`);t.className=`tcw-flyout-row`,t.setAttribute(`role`,`none`),t.dataset.toolValue=e.value;let a=document.createElement(`button`);a.className=`tcw-flyout-item`,a.setAttribute(`role`,`menuitem`),a.tabIndex=-1,a.innerHTML=i.a(e.value,dt);let s=document.createElement(`span`);s.className=`tcw-flyout-name`,s.textContent=e.label,a.appendChild(s);let c=this.config.shortcuts?.[e.value];if(c){let e=document.createElement(`kbd`);e.className=`tcw-flyout-key`,e.textContent=c,r.o(e,`hotkeys`,`hotkeys.tools`),a.appendChild(e)}if(a.dataset.toolValue=e.value,a.addEventListener(`click`,()=>{this.hideFlyout(),this.pick(e.value)}),t.appendChild(a),this.callbacks.onToggleFavorite){let n=this.favorites.includes(e.value);t.classList.toggle(`tcw-flyout-faved`,n);let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-flyout-pin`,r.dataset.pin=e.value,r.tabIndex=-1,r.title=o,r.setAttribute(`aria-label`,`${o}: ${e.label}`),r.setAttribute(`aria-pressed`,String(n)),r.innerHTML=i.i(`star`,12),r.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onToggleFavorite?.(e.value)}),t.appendChild(r),a.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.callbacks.onToggleFavorite?.(e.value)})}n.appendChild(t)}n.addEventListener(`mouseenter`,()=>this.cancelHideFlyout()),n.addEventListener(`mouseleave`,()=>this.scheduleHideFlyout()),n.addEventListener(`focusout`,t=>{let r=t.relatedTarget;!n.contains(r)&&!this.groupWraps[e].contains(r)&&this.scheduleHideFlyout()}),this.flyoutEl=n,this.flyoutIdx=e,this.host.appendChild(n),this.placeFlyout(n,this.groupButtons[e]),this.groupButtons[e].setAttribute(`aria-expanded`,`true`)}flyoutItems(){return this.flyoutEl?[...this.flyoutEl.querySelectorAll(`.tcw-flyout-item`)]:[]}focusFlyoutItem(e){let t=this.flyoutItems();t.length!==0&&t[(e+t.length)%t.length].focus()}onFlyoutKey(e,t){let n=this.flyoutItems(),r=n.indexOf(document.activeElement);switch(e.key){case`ArrowDown`:this.focusFlyoutItem(r+1);break;case`ArrowUp`:this.focusFlyoutItem(r-1);break;case`Home`:this.focusFlyoutItem(0);break;case`End`:this.focusFlyoutItem(n.length-1);break;case`Escape`:case`ArrowLeft`:e.stopPropagation(),this.hideFlyout(),this.groupButtons[t]?.focus();break;case`Tab`:this.hideFlyout(),this.groupButtons[t]?.focus();return;default:return}e.preventDefault()}placeFlyout(e,t){let n=this.host.getBoundingClientRect(),r=t.getBoundingClientRect(),i=this.el.getBoundingClientRect();e.style.maxHeight=`${Math.max(0,this.host.clientHeight-pt*2)}px`;let a=this.host.clientHeight-e.offsetHeight-pt;this.host.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?(e.style.left=``,e.style.right=`${n.right-i.left}px`):(e.style.right=``,e.style.left=`${i.right-n.left}px`),e.style.top=`${Math.max(0,Math.min(r.top-n.top,a))}px`}scheduleHideFlyout(){this.cancelHideFlyout(),this.flyoutHideTimer=setTimeout(()=>{this.flyoutHideTimer=null,this.hideFlyout()},ft)}cancelHideFlyout(){this.flyoutHideTimer!==null&&(clearTimeout(this.flyoutHideTimer),this.flyoutHideTimer=null)}hideFlyout(){this.cancelHideFlyout(),this.flyoutEl&&=(this.flyoutEl.remove(),null),this.groupButtons[this.flyoutIdx]?.setAttribute(`aria-expanded`,`false`),this.flyoutIdx=-1}update(e){this.cursorBtn&&this.cursorBtn.classList.toggle(`tcw-active`,e.activeTool===null);let t=e.activeTool??``;t!==this.fabShows&&(this.fabShows=t,this.fab.innerHTML=e.activeTool?i.a(e.activeTool,18):i.i(`penLine`,18)),this.fab.classList.toggle(`tcw-active`,e.activeTool!==null||e.eraser||e.zoomArea);let{drawingToolGroups:n}=this.config;for(let t=0;t<n.length;t++){let r=n[t].tools.some(t=>t.value===e.activeTool);this.groupButtons[t].classList.toggle(`tcw-active`,r),r&&e.activeTool&&e.activeTool!==this.groupTools[t]&&(this.groupTools[t]=e.activeTool,this.groupIcons[t].innerHTML=i.a(e.activeTool,dt),n[t].tools.length>1&&this.groupButtons[t].setAttribute(`aria-label`,`${n[t].label}: ${ht(n,e.activeTool)}`))}if(this.flyoutEl&&this.flyoutEl.querySelectorAll(`.tcw-flyout-item`).forEach(t=>{let n=t;n.classList.toggle(`tcw-active`,n.dataset.toolValue===e.activeTool)}),this.magnetBtn){let t=e.magnetEnabled&&e.magnetStrong;this.magnetBtn.classList.toggle(`tcw-active`,e.magnetEnabled),this.magnetBtn.innerHTML=i.i(t?`magnetStrong`:`magnet`,14),this.magnetBtn.title=t?this.t(`drawing.magnetStrong`):e.magnetEnabled?this.t(`drawing.magnetOn`):this.t(`drawing.magnetOff`),this.magnetBtn.setAttribute(`aria-label`,this.magnetBtn.title)}for(let[t,n]of[[this.eraserBtn,e.eraser],[this.zoomBtn,e.zoomArea]])t&&(t.classList.toggle(`tcw-active`,n),t.setAttribute(`aria-pressed`,String(n)));this.stayBtn&&(this.stayBtn.classList.toggle(`tcw-active`,e.stayInDrawing),this.stayBtn.setAttribute(`aria-pressed`,String(e.stayInDrawing)))}addHostButton(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-sidebar-btn tcw-host-btn`,t.dataset.hostButton=e.id,t.title=e.label,t.setAttribute(`aria-label`,e.label),e.toggle&&t.setAttribute(`aria-pressed`,`false`),typeof e.icon==`string`?t.innerHTML=i.i(e.icon,14):t.appendChild(e.icon),t.addEventListener(`click`,()=>e.onClick(t)),this.hostEl?.appendChild(t),this.tidy(),t}hostSlot(){return this.hostEl}tidy(){r.d(this.el,`tcw-sidebar-divider`,`tcw-sidebar-spacer`)}toggleButton(e,t,n){let r=document.createElement(`button`);return r.className=`tcw-sidebar-btn`,r.title=t,r.setAttribute(`aria-label`,t),r.setAttribute(`aria-pressed`,`false`),r.innerHTML=i.i(e,14),r.addEventListener(`click`,n),r}appendDivider(){this.el.lastElementChild?.classList.contains(`tcw-sidebar-divider`)||this.el.appendChild(this.divider())}divider(){let e=document.createElement(`div`);return e.className=`tcw-sidebar-divider`,e}destroy(){this.stopFit(),this.setOpen(!1),this.hideFlyout(),this.fab.remove(),this.el.remove()}},vt=`data-tcw-folded`,yt=`tcw-statusbar--folded`,bt=`tcw-statusbar--short-market`,xt=1,St=13,Ct=`goto`,wt=`Alt+G`,Tt=e=>e.goToKeys?e.goToKeys():wt;function Et(e,t){let n=document.createElement(`span`);return n.className=e,n.textContent=t,n}var Dt=class{el;dotEl;messageEl;marketEl;hostLeft;hostRight;clockBtn=null;clockMenu=null;scaleBtns=null;scaleShown=``;marketShown=``;rightEl;rangeEl=null;presetBtns=[];moreBtn=null;goToBtn=null;rangeMenu=null;resizeObserver=null;fitFrame=0;destroyed=!1;constructor(e,t,n={}){this.host=e,this.extras=n,this.el=document.createElement(`div`),this.el.className=`tcw-statusbar`,r.o(this.el,`statusBar`),n.label&&(this.el.setAttribute(`role`,`group`),this.el.setAttribute(`aria-label`,n.label)),t&&this.el.appendChild(this.buildRange(t)),this.hostLeft=this.hostGroup(),this.el.appendChild(this.hostLeft);let i=document.createElement(`div`);i.className=`tcw-status-right`,this.rightEl=i,this.hostRight=this.hostGroup(),i.appendChild(this.hostRight);let a=document.createElement(`div`);a.className=`tcw-status-indicator`,r.o(a,`statusBar.connection`),this.dotEl=document.createElement(`span`),this.dotEl.className=`tcw-status-dot`,a.appendChild(this.dotEl),this.messageEl=document.createElement(`span`),a.appendChild(this.messageEl),this.marketEl=document.createElement(`span`),this.marketEl.className=`tcw-status-market`,this.marketEl.hidden=!0,r.o(this.marketEl,`statusBar.market`),i.appendChild(this.marketEl),i.appendChild(a),n.clock&&i.appendChild(this.buildClock(n.clock)),n.scale&&i.appendChild(this.buildScale(n.scale)),this.el.appendChild(i),e.appendChild(this.el),this.watchWidths(i)}watchWidths(e){if(typeof ResizeObserver<`u`){this.resizeObserver=new ResizeObserver(()=>this.scheduleFit());for(let t of[this.el,e,this.hostLeft])this.resizeObserver.observe(t)}document.fonts?.ready.then(()=>this.scheduleFit())}scheduleFit(){this.destroyed||this.fitFrame||typeof requestAnimationFrame>`u`||(this.fitFrame=requestAnimationFrame(()=>{this.fitFrame=0,this.destroyed||this.fit()}))}fit(){let e=this.foldedCount(),t=this.rangeFocus();this.refit(),this.foldedCount()!==e&&this.rangeMenu?.close(),this.keepFocus(t)}refit(){let e=this.foldSteps(),t=this.goToBtn?[...this.presetBtns,this.goToBtn]:this.presetBtns,n=n=>{let r=new Set(e.slice(0,n));for(let e of t)e.toggleAttribute(vt,r.has(e));this.el.classList.toggle(yt,n>0)};if(n(0),this.el.classList.remove(bt),this.el.clientWidth===0||this.fits())return;let r=0;for(;r<e.length;)if(n(++r),this.fits())return;if(!(this.marketEl.hidden||this.isOff(this.marketEl))){for(this.el.classList.add(bt);r>0;r--)if(n(r-1),!this.fits()){n(r);return}}}fits(){return this.rangeFits()&&this.rightFits()}rangeFits(){let e=this.rangeEl;return!e||e.scrollWidth<=e.clientWidth+xt}rightFits(){if(this.rightEl.offsetParent!==this.el)return!0;let e=getComputedStyle(this.el),t=this.rightEl.offsetLeft;return(e.direction===`rtl`?(parseFloat(e.paddingLeft)||0)-t:t+this.rightEl.offsetWidth-(this.el.clientWidth-(parseFloat(e.paddingRight)||0)))<=xt}foldedCount(){return this.rangeEl?.querySelectorAll(`[${vt}]`).length??0}rangeFocus(){if(this.rangeMenu?.hasFocus())return this.moreBtn;let e=document.activeElement;return e instanceof HTMLElement&&this.rangeEl?.contains(e)?e:null}keepFocus(e){if(!e||this.rangeMenu?.isOpen())return;let t=this.focusAfterRefit(e);t===this.el?this.focusBar():document.activeElement!==t&&t.focus({preventScroll:!0})}focusAfterRefit(e){if(this.shows(e))return e;let t=this.presetBtns.filter(e=>this.shows(e)).at(-1);return[e===this.moreBtn?null:this.moreBtn,this.goToBtn,t].find(e=>e!=null&&this.shows(e))??this.firstOtherControl()??this.el}firstOtherControl(){return[...this.el.querySelectorAll(`button`)].filter(e=>!this.rangeEl?.contains(e)).find(e=>!e.disabled&&e.getClientRects().length>0)??null}focusBar(){if(document.activeElement===this.el)return;let e=()=>this.el.removeAttribute(`tabindex`);this.el.tabIndex=-1,this.el.addEventListener(`blur`,e,{once:!0}),this.el.focus({preventScroll:!0}),document.activeElement!==this.el&&(this.el.removeEventListener(`blur`,e),e())}shows(e){return e===this.moreBtn&&!this.el.classList.contains(yt)?!1:!e.hasAttribute(vt)&&!this.isOff(e)}foldSteps(){if(this.presetBtns.length===0||this.isOff(this.presetBtns[0]))return[];let e=[...this.presetBtns].reverse();return this.goToBtn&&e.push(this.goToBtn),e}isOff(e){let t=((this.el.closest(`.tcw-root`)??this.host).getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean);return(e.dataset.tcwPart??``).split(/\s+/).some(e=>t.includes(e))}update(e){this.dotEl.className=`tcw-status-dot`,e.connectionState===`connected`?this.dotEl.classList.add(`tcw-connected`):e.connectionState===`error`&&this.dotEl.classList.add(`tcw-error`),this.messageEl.textContent=e.message}tick(){if(!this.clockBtn||!this.extras.clock)return;let{time:e,zone:t}=this.extras.clock.now(),n=`${e} ${t}`;this.clockBtn.textContent!==n&&(this.clockBtn.textContent=n)}setScale(e){let t=`${e.mode}|${e.auto}`;!this.scaleBtns||t===this.scaleShown||(this.scaleShown=t,this.scaleBtns.percent?.setAttribute(`aria-pressed`,String(e.mode===`percentage`)),this.scaleBtns.log?.setAttribute(`aria-pressed`,String(e.mode===`logarithmic`)),this.scaleBtns.auto?.setAttribute(`aria-pressed`,String(e.auto)))}setMarket(e,t,n=t){let r=`${e}|${t}|${n}`;if(r===this.marketShown)return;if(this.marketShown=r,this.marketEl.hidden=e===`always`,this.marketEl.dataset.state=e,e===`always`){this.marketEl.replaceChildren(),this.marketEl.removeAttribute(`title`);return}this.marketEl.title=t;let i=Et(`tcw-status-market-short`,n);i.setAttribute(`aria-hidden`,`true`),this.marketEl.replaceChildren(Et(`tcw-status-market-text`,t),i)}addHostItem(e){let t=e.onClick,n=t?document.createElement(`button`):document.createElement(`span`);return n.className=t?`tcw-status-host-item tcw-status-host-btn`:`tcw-status-host-item`,n.dataset.hostItem=e.id,n.dir=`auto`,n.textContent=e.text,e.label&&(n.title=e.label,t||n.setAttribute(`role`,`group`),e.label!==e.text&&n.setAttribute(`aria-label`,`${e.label}: ${e.text}`)),n instanceof HTMLButtonElement&&t&&(n.type=`button`,n.addEventListener(`click`,()=>t(n))),(e.side===`left`?this.hostLeft:this.hostRight).appendChild(n),n}hostSlot(e){return e===`left`?this.hostLeft:this.hostRight}destroy(){this.destroyed=!0,this.resizeObserver?.disconnect(),this.fitFrame&&cancelAnimationFrame(this.fitFrame),this.clockMenu?.destroy(),this.rangeMenu?.destroy(),this.el.remove()}buildClock(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-status-clock`,t.dataset.role=`clock`,t.dir=`auto`,t.title=e.label,t.setAttribute(`aria-haspopup`,`menu`),r.o(t,`statusBar.clock`),t.addEventListener(`click`,()=>this.toggleZones(t,e)),this.clockBtn=t,this.tick(),t}toggleRangeMenu(e,t){if(this.rangeMenu?.isOpen()){this.rangeMenu.close();return}let n=e=>e.hasAttribute(vt)&&!this.isOff(e),r=t.presets.filter((e,t)=>n(this.presetBtns[t])).map(e=>({id:e,label:t.presetLabels?.[e]??e}));if(this.goToBtn&&n(this.goToBtn)&&(r.length>0&&r.push(`separator`),r.push({id:Ct,label:t.goToLabel,icon:`calendar`,shortcut:Tt(t)})),r.length===0)return;this.rangeMenu??=new o.f(this.host,t.groupLabel);let i=e.getBoundingClientRect(),a=this.host.getBoundingClientRect();this.rangeMenu.open(r,i.left-a.left,i.top-a.top,e=>e===Ct?t.onGoTo():t.onPreset(e),e,void 0,i.right-a.left)}toggleZones(e,t){if(this.clockMenu?.isOpen()){this.clockMenu.close();return}let{current:n,list:r}=t.options();this.clockMenu??=new o.f(this.host,t.label);let i=e.getBoundingClientRect(),a=this.host.getBoundingClientRect();this.clockMenu.open(r.map(e=>({id:e.value,label:e.label,checked:e.value===n})),i.left-a.left,i.top-a.top,e=>t.onPick(e),e,void 0,i.right-a.left)}buildScale(e){let t=document.createElement(`div`);t.className=`tcw-status-scale`,t.setAttribute(`role`,`group`),e.labels.group&&t.setAttribute(`aria-label`,e.labels.group),r.o(t,`statusBar.scale`);let n=(n,r,i)=>{let a=document.createElement(`button`);return a.type=`button`,a.className=`tcw-status-scale-btn`,a.dataset.scale=n,a.textContent=r,a.title=e.labels[n],a.setAttribute(`aria-label`,e.labels[n]),a.setAttribute(`aria-pressed`,`false`),a.addEventListener(`click`,i),t.appendChild(a),a};return this.scaleBtns={percent:n(`percent`,`%`,e.onPercent),...e.onLog?{log:n(`log`,e.texts?.log??`log`,e.onLog)}:{},auto:n(`auto`,e.texts?.auto??`auto`,e.onAuto)},t}hostGroup(){let e=document.createElement(`div`);return e.className=`tcw-status-host`,e}buildRange(e){let t=document.createElement(`div`);t.className=`tcw-range-bar`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,e.groupLabel);for(let n of e.presets){let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-range-btn`,i.dataset.range=n,r.o(i,`statusBar.range`),i.textContent=e.presetLabels?.[n]??n,i.addEventListener(`click`,()=>e.onPreset(n)),t.appendChild(i),this.presetBtns.push(i)}let n=this.rangeIconBtn(`tcw-range-more`,`rangeMore`,`more`,e.moreLabel);r.o(n,`statusBar.range`),n.setAttribute(`aria-haspopup`,`menu`),n.setAttribute(`aria-expanded`,`false`),n.addEventListener(`click`,()=>this.toggleRangeMenu(n,e)),t.appendChild(n),this.moreBtn=n;let i=this.rangeIconBtn(`tcw-range-goto`,`goto`,`calendar`,e.goToLabel);r.o(i,`goToDate`,`statusBar.goToDate`);let a=()=>{let t=Tt(e);i.title=t?`${e.goToLabel} (${t})`:e.goToLabel};return a(),i.addEventListener(`pointerover`,a),i.addEventListener(`focusin`,a),i.addEventListener(`click`,e.onGoTo),t.appendChild(i),this.goToBtn=i,this.rangeEl=t,t}rangeIconBtn(e,t,n,r){let a=document.createElement(`button`);return a.type=`button`,a.className=`tcw-range-btn ${e}`,a.dataset.role=t,a.title=r,a.setAttribute(`aria-label`,r),a.innerHTML=i.i(n,St),a}},w=[],Ot=new Map,T=null,kt=e=>{let t=e.target instanceof Node?e.target:null;t!==null&&w.some(e=>e.contains(t)||Ot.get(e)?.some(e=>e.contains(t)))||(T=null)};function At(e,t=[]){let n=()=>{T=e},r=[e,...t];for(let e of r)e.addEventListener(`pointerdown`,n,!0);return w.length===0&&document.addEventListener(`pointerdown`,kt,!0),w.push(e),Ot.set(e,t),()=>{for(let e of r)e.removeEventListener(`pointerdown`,n,!0);let t=w.indexOf(e);t>=0&&w.splice(t,1),Ot.delete(e),w.length===0&&document.removeEventListener(`pointerdown`,kt,!0),T===e&&(T=null)}}function E(e,t=!1){let n=T?.isConnected?T:null;if(!n){let e=document.activeElement;n=e?w.find(t=>t.contains(e))??null:null}return!n&&!t&&(n=w.find(e=>e.isConnected)??null),n!==null&&e.contains(n)}function D(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.tagName===`SELECT`||e.isContentEditable)}function O(){let e=document.activeElement;return e instanceof Element&&e.closest(`[role="dialog"], [aria-modal="true"], [role="menu"]`)!==null}var jt={selectHint:`Click a bar to start the replay`,random:`Random bar`,realtime:`Back to realtime`,play:`Play`,pause:`Pause`,stepBack:`Step back (Shift+←)`,stepForward:`Step forward (Shift+→)`,replay:`Replay`,position:`Replay position`,speed:`Speed`,step:`Step`,loading:`Loading chart...`,selectBar:`Select bar`,cancel:`Cancel`,rate:`{rate}×`,rateHint:`1× plays one bar a second`,playingAt:`Playing at {rate}`,pausedAt:`Paused at {time}`,endedAt:`Replay ended at {time}`},Mt=[.1,.2,.3,.5,1,2,3,5,10,20,30,50],Nt=[`full`,`compact`,`stack`],Pt=300,Ft=2,It=[`random`,`stepBack`,`stepForward`,`seek`,`step`,`selectBar`],Lt=class{root=null;scrubber=null;timeLabel=null;playBtn=null;realtimeBtn=null;liveRegion=null;hintText=null;state=`stopped`;mode=`select`;ended=!1;pending=!1;total=0;rate=1;steps=[];step=`bar`;dir=`ltr`;formatRate;where=``;announceTimer=null;widths=new Map;labels;constructor(e,t={}){this.callbacks=e,this.labels={...jt,...t},this.formatRate=e=>this.labels.rate.replace(`{rate}`,String(e))}mount(e,t){this.root||(this.total=Math.max(0,t.total),this.rate=t.rate??1,this.steps=t.steps??[],this.step=t.step??`bar`,this.dir=t.dir??`ltr`,t.formatRate&&(this.formatRate=t.formatRate),this.state=`paused`,this.mode=t.mode??`select`,this.root=document.createElement(`div`),this.root.className=`tcw-replay-bar`,r.o(this.root,`replay`),this.root.setAttribute(`role`,`group`),this.root.setAttribute(`aria-label`,this.labels.replay),this.root.dataset.fit=`full`,this.root.innerHTML=this.markup(),e.appendChild(this.root),this.wireEvents(),this.syncUi())}unmount(){this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=null,this.root?.remove(),this.root=null,this.hintText=null,this.scrubber=null,this.timeLabel=null,this.playBtn=null,this.realtimeBtn=null,this.liveRegion=null,this.state=`stopped`,this.ended=!1,this.where=``}isMounted(){return this.root!==null}element(){return this.root}getMode(){return this.mode}setMode(e){let t=!!this.root?.contains(document.activeElement);this.mode=e,this.syncUi(),t&&(e===`replay`?(this.playBtn&&!this.playBtn.disabled?this.playBtn:this.realtimeBtn)?.focus():this.root?.querySelector(`[data-act="random"]`)?.focus())}setState(e){e!==this.state&&(this.state=e,this.syncUi(),this.mode===`replay`&&(e===`playing`?this.announce(this.labels.playingAt.replace(`{rate}`,this.formatRate(this.rate))):e===`paused`&&this.where&&this.announce(this.labels.pausedAt.replace(`{time}`,this.where))))}setEnded(e){this.ended!==e&&(this.ended=e,this.syncUi(),e&&this.where&&this.announce(this.labels.endedAt.replace(`{time}`,this.where)))}setPending(e){if(this.pending===e)return;this.pending=e;let t=document.activeElement;e&&t&&t!==this.playBtn&&this.root?.contains(t)&&It.includes(t.dataset.act??``)&&this.playBtn?.focus(),this.syncUi(),e&&this.mode===`replay`&&this.announce(this.labels.loading)}isPending(){return this.pending}setSteps(e,t){this.steps=e,this.step=t,this.widths.clear();let n=this.root?.querySelector(`[data-tcw="stepSlot"]`);n&&(n.innerHTML=this.stepMarkup(),this.wireStep(),this.syncUi())}setProgress(e,t,n){this.total=t;let r=n??`${Math.min(e+1,t)} / ${t}`,i=r!==this.where;if(this.where=r,this.scrubber){this.scrubber.max=String(Math.max(0,t-1)),this.scrubber.value=String(e),this.scrubber.setAttribute(`aria-valuetext`,r);let n=t>1?Math.min(e,t-1)/(t-1)*100:0;this.scrubber.style.setProperty(`--tcw-replay-done`,`${Number(n.toFixed(Ft))}%`)}if(this.timeLabel){this.timeLabel.textContent=r;let e=Number.parseFloat(this.timeLabel.style.minInlineSize)||0;r.length>e&&(this.timeLabel.style.minInlineSize=`${r.length}ch`)}let a=this.scrubber!==null&&document.activeElement===this.scrubber;i&&this.mode===`replay`&&this.state!==`playing`&&!a&&this.announce(r)}setRoom(e){let t=this.root;if(t){for(let n of Nt)if(n===`stack`||this.widthIn(n)<=e){t.dataset.fit=n,this.orderFor(n);return}}}orderFor(e){let t=this.root,n=t?.querySelector(`.tcw-replay-timeline`),r=t?.querySelector(`.tcw-replay-transport`),i=this.realtimeBtn;if(!t||!n||!r||!i)return;let a=e===`stack`;if(a===(n.nextElementSibling===i))return;let o=document.activeElement;a?r.before(n,i):(r.nextElementSibling?.after(n),t.querySelector(`[data-act="cancel"]`)?.before(i)),o&&t.contains(o)&&document.activeElement!==o&&o.focus()}getFit(){return this.root?.dataset.fit??`full`}destroy(){this.unmount()}widthIn(e){let t=this.root,n=`${this.mode}|${this.steps.length}|${e}`,r=this.widths.get(n);if(r!==void 0)return r;let i=t.dataset.fit;t.dataset.fit=e,t.dataset.measure=``;let a=t.getBoundingClientRect().width;return delete t.dataset.measure,i&&(t.dataset.fit=i),a>0&&this.widths.set(n,a),a}markup(){let e=this.labels,t=`dir="${this.dir}"`,n=Mt.map(e=>`<option value="${e}"${e===this.rate?` selected`:``}>${a.u(this.formatRate(e))}</option>`).join(``),r=(e,t,n,r=`tcw-replay-btn`,i=``)=>`<button type="button" class="${r}" data-act="${e}" title="${a.u(t)}" aria-label="${a.u(t)}"${i}>${n}</button>`;return`
7702
7768
  <span class="tcw-replay-group tcw-replay-picking" data-mode="select">
7703
7769
  <span class="tcw-replay-hint" ${t}>${i.i(`cursor`,14)}<span data-tcw="hint">${a.u(e.selectHint)}</span></span>
7704
7770
  <button type="button" class="tcw-replay-text-btn tcw-replay-ghost" data-act="random" ${t}>${a.u(e.random)}</button>
@@ -7728,7 +7794,7 @@ ${r.f()}`,document.head.insertBefore(e,document.head.firstChild)}function ce(){i
7728
7794
  <button type="button" class="tcw-replay-text-btn" data-act="cancel" data-mode="select" ${t}>${a.u(e.cancel)}</button>
7729
7795
  </span>
7730
7796
  <span class="tcw-visually-hidden" role="status" aria-live="polite" data-tcw="announce" ${t}></span>
7731
- `}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)},Et)}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 Ot){let n=e.querySelector(`[data-act="${t}"]`);n&&(n.disabled=this.pending)}}},At=864e5,jt=6e4,Mt=1e3,Nt=150,Pt=5e3,Ft=8,It=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 kt({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*Ft),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>=At)return s;let c={hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`};return(!Number.isFinite(i)||i<jt)&&(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(!Lt(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(),Nt)}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?Mt:Mt/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(Pt,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||j()||M()||!A(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 Lt(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 Rt=()=>typeof document<`u`&&document.hidden;function N(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var zt=class{el;headerEl;nameBtn;menuEl;listEl;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){this.callbacks=t,this.labels=n,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 r=document.createElement(`button`);r.type=`button`,r.className=`tcw-watchlist-add`,r.innerHTML=i.i(`plus`,14),r.title=n.add,r.setAttribute(`aria-label`,n.add),r.hidden=!t.onAdd,r.addEventListener(`click`,()=>t.onAdd?.());let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-watchlist-close`,a.setAttribute(`aria-label`,n.close??n.title),a.innerHTML=i.i(`x`,14),a.hidden=!t.onClose,a.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,r,a,this.menuEl),this.el.appendChild(this.headerEl),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-watchlist-list`,this.listEl.setAttribute(`role`,`list`),this.el.appendChild(this.listEl),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);if(this.listEl.replaceChildren(...e.map(e=>this.rowMap.get(e).row)),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)}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=Bt(e);let r=document.createElement(`canvas`);r.className=`tcw-watchlist-spark`,r.width=64,r.height=22;let a=document.createElement(`div`);a.className=`tcw-watchlist-stats`;let o=document.createElement(`span`);o.className=`tcw-watchlist-price`,o.textContent=`—`;let c=document.createElement(`span`);if(c.className=`tcw-watchlist-change`,a.append(o,c),t.append(n,r,a),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)}),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,changeEl:c,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=Vt(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=Math.abs(r).toLocaleString(this.locale,{minimumFractionDigits:2,maximumFractionDigits:2});t.changeEl.textContent=`${i}${a}%`,t.changeEl.className=`tcw-watchlist-change ${e>=0?`tcw-up`:`tcw-down`}`}else t.changeEl.textContent=``;n.sparkline&&n.sparkline.length>=2&&Ht(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 Bt(e){for(let t of[`USDT`,`USD`,`BTC`,`ETH`,`EUR`])if(e.length>t.length&&e.endsWith(t))return e.slice(0,-t.length)+`/`+t;return e}function Vt(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 Ht(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 Ut=50,Wt=500,Gt=60,Kt=e=>typeof e==`string`&&e.trim().slice(0,Gt)||null;function qt(e){let t=[];for(let n of e){let e=a.n(n);if(e&&!t.includes(e)&&t.push(e),t.length===Wt)break}return t}function Jt(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===Ut)break;if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`&&t.id&&t.id.length<=64?t.id:null,i=Kt(t.name);!r||!i||n.some(e=>e.id===r)||n.push({id:r,name:i,symbols:Array.isArray(t.symbols)?qt(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 Yt=e=>({...e,symbols:[...e.symbols]}),Xt=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?Jt({lists:e.lists,active:e.activeList}):null,r=t??n??{lists:[{id:`default`,name:Kt(e.defaultName)??`Watchlist`,symbols:qt(e.symbols??[])}],active:`default`};this.lists=r.lists,this.active=r.active}getLists(){return this.lists.map(Yt)}getActive(){return Yt(this.activeList())}setActive(e){e===this.active||!this.lists.some(t=>t.id===e)||(this.active=e,this.changed())}replace(e,t){let n=Jt({lists:e,active:t??this.active});n&&(this.lists=n.lists,this.active=n.active,this.changed())}create(e){let t=Kt(e);if(!t||this.lists.length>=Ut)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(),Yt(r)}rename(e,t){let n=Kt(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>=Wt?!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?Jt(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{}}},Zt=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`,t.append(P(`div`,`tcw-syminfo-symbol`,e.symbol)),e.description&&t.append(P(`div`,`tcw-syminfo-desc`,e.description)),e.meta&&t.append(P(`div`,`tcw-syminfo-meta`,e.meta));let n=document.createElement(`div`);if(n.className=`tcw-syminfo-quote`,e.price&&n.append(P(`span`,`tcw-syminfo-price`,e.price)),e.change){let t=P(`span`,`tcw-syminfo-change`,e.change.text);t.classList.add(e.change.up?`tcw-up`:`tcw-down`),n.append(t)}let r=P(`div`,`tcw-syminfo-status`,e.status.text);r.dataset.state=e.status.state;let i=document.createElement(`dl`);i.className=`tcw-syminfo-stats`;for(let t of e.stats){let e=document.createElement(`div`);e.className=`tcw-syminfo-stat`,e.append(P(`dt`,``,t.label),P(`dd`,``,t.value)),i.append(e)}this.bodyEl.replaceChildren(t,n,r,i)}renderNews(e){if(this.newsEl.hidden=e.kind===`none`,e.kind===`none`){this.newsEl.replaceChildren();return}let t=P(`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(P(`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(P(`span`,``,t.title));t.meta&&e.append(P(`div`,`tcw-syminfo-news-meta`,t.meta)),n.append(e)}this.newsEl.replaceChildren(t,n)}destroy(){this.el.remove()}};function P(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}var Qt=10,$t=5*6e4,en=864e5,tn=2;function nn(e){let{info:t,quote:n,t:r,textLocale:i}=e,a=(0,u.symbolTimeZone)(t),o=an(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=on(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:cn(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`),ln(t,i));let b=(f??0)>=0?`+`:`-`,x=e.names===void 0?t:e.names;return{symbol:e.symbol,description:x?.description,meta:[x?.exchange,x?.type].filter(Boolean).join(` · `)||void 0,price:l===void 0?void 0:c(l),change:f===void 0?void 0:{text:`${b}${c(Math.abs(f))}${m===void 0?``:` (${b}${sn(Math.abs(m),tn,e.numberLocale)}%)`}`,up:f>=0},status:{state:h.state,text:g},stats:_}}var rn=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,on(e.time-t,r)].filter(Boolean).join(` · `)}))})},s=this.cache.get(e);if(s&&Date.now()-s.at<$t){o(s.items);return}n({kind:`loading`}),Promise.resolve().then(()=>t(e,Qt)).then(t=>{if(a!==this.request||i())return;let n=(0,u.readNews)(t,Qt);this.cache.set(e,{at:Date.now(),items:n}),o(n)}).catch(()=>{a===this.request&&!i()&&n({kind:`failed`})})}};function an(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))/en)},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 on(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 sn(e,t,n){try{return(0,u.formatPrice)(e,t,n)}catch{return e.toFixed(t)}}function cn(e,t){try{return new Intl.NumberFormat(t,{notation:`compact`,maximumFractionDigits:2}).format(e)}catch{return String(e)}}function ln(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 un={KeyT:`trendLine`,KeyH:`horizontalLine`,KeyJ:`horizontalRay`,KeyV:`verticalLine`,KeyC:`crossLine`,KeyF:`fibRetracement`};function dn(){let e={};for(let[t,n]of Object.entries(un))e[n]=`Alt+${t.replace(/^Key/,``)}`;return e}var fn=300,pn=80,mn=u.PHI**-3,hn=80,gn=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(hn,t.height*mn);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),pn)},fn)}stopHold(){this.holdTimer&&clearTimeout(this.holdTimer),this.repeatTimer&&clearInterval(this.repeatTimer),this.holdTimer=null,this.repeatTimer=null}};function _n(e,t,n,r=!1){let i=e.label??t(`alerts.source.price`),a=Sn.get(e.condition),o=a?t(a):e.condition;if(yn.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?wn(e.price):n(e.price):`—`;return`${(c||e.drawingId)&&e.label?`${e.label} `:r?`${i} `:``}${o} ${l}`}var vn=[{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`}],yn=[`movesUp`,`movesDown`],bn={hour:36e5,day:864e5,week:7*864e5,month:30*864e5},xn=``,Sn=new Map(vn.map(e=>[e.value,e.key]));function Cn(e){return Math.round(e*1e6)/1e6}function wn(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var Tn=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 vn){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=yn.includes(this.conditionSelect.value);this.moveRow.hidden=!e,this.levelRow.hidden=e,this.priceInput.hidden=this.targetSelect.value!==xn}renderTargets(){let e=this.targetSelect.value,t=this.sourceSelect.value||`price`;this.targetSelect.replaceChildren();let n=document.createElement(`option`);n.value=xn,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:xn,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(Cn(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(yn.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!==xn)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=bn[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 _n(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)}}},En=`print`,Dn=3,On=10,kn=[[3400,1/2],[2560,1/3],[1800,1/6]],An=.75,jn=2;function Mn(e){let t=kn.find(([t])=>e>=t);return t?u.PHI**t[1]:1}function Nn(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 F(e,t){return Math.max(On,(0,u.phiStep)(e,t,Dn))}var Pn=`system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`,Fn=`'JetBrains Mono', 'SF Mono', 'Cascadia Code', 'Fira Code', 'Consolas', ui-monospace, monospace`,In=u.SANS_FONT_FAMILY,Ln=`'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`,Rn=`Tahoma, Verdana, 'Segoe UI', 'DejaVu Sans', sans-serif`,zn={print:{radius:{xs:1,sm:2,md:3,lg:5,xl:8},components:{tag:2,toolbar:0,sidebar:0},sizes:{toolbar:42,control:26,controlSmall:20,icon:16,sidebar:42,menuItem:33},density:{compact:{toolbar:33,control:20,controlSmall:20,icon:16,sidebar:33,menuItem:26},spacious:{toolbar:53,control:33,controlSmall:26,icon:20,sidebar:53,menuItem:42}},font:{family:In,mono:Ln,size:13,weight:400,strongWeight:600,labelCase:`uppercase`,labelTracking:.06},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border), var(--tcw-shadow-md)`,dialog:`0 0 0 1px var(--tcw-border), var(--tcw-shadow-lg)`,tooltip:`var(--tcw-shadow-sm)`},blur:0,active:`solid`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:2},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:48,menuItem:30},font:{family:`'Manrope', 'Inter', ${Pn}`,mono:Fn,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},terminal:{radius:{xs:1,sm:2,md:2,lg:2,xl:3},components:{tag:0,toolbar:0,sidebar:0},sizes:{toolbar:36,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},font:{family:`'IBM Plex Sans Condensed', 'Roboto Condensed', 'Arial Narrow', ${Pn}`,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},capsule:{radius:{xs:6,sm:10,md:999,lg:18,xl:24},components:{tooltip:10,toolbar:999,sidebar:999,toast:999,tag:999},sizes:{toolbar:44,control:32,controlSmall:26,icon:18,sidebar:48,menuItem:34},font:{family:`'Sora', 'Manrope', ${Pn}`,mono:Fn,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},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:36,menuItem:24},font:{family:Rn,mono:Rn,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}},Bn={compact:{toolbar:38,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},spacious:{toolbar:52,control:34,controlSmall:28,icon:20,sidebar:54,menuItem:34}};function Vn(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 Hn=Object.freeze(Object.fromEntries(Object.keys(zn).map(e=>[e,Wn(Un(e))])));function Un(e){let{density:t,...n}=zn[e];return{...n,preset:e,density:`comfortable`,scale:`auto`,radius:{...n.radius},components:Vn(n.radius,n.components),sizes:{...n.sizes},font:{...n.font},borders:{...n.borders},shadows:{...n.shadows}}}function Wn(e){for(let t of Object.values(e))t&&typeof t==`object`&&Wn(t);return Object.freeze(e)}var Gn=e=>typeof e==`string`&&Object.prototype.hasOwnProperty.call(zn,e),I=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,Kn=e=>typeof e==`string`&&e.trim().length>0&&e.length<=300&&!/[;{}<>\\]|url\s*\(|expression\s*\(|\/\*/i.test(e)&&qn(e);function qn(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 L=(e,t)=>typeof e==`string`&&t.includes(e);function R(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 z(e){let t=typeof e==`string`?{preset:e}:e??{},n=Gn(t.preset)?t.preset:En,r=zn[n],i=R(r.radius,t.radius,(e,t)=>I(t,0,999)),a=L(t.density,[`compact`,`comfortable`,`spacious`,`airy`])?t.density:`comfortable`,o=a===`airy`?`spacious`:a,s=R(o===`compact`||o===`spacious`?(r.density??Bn)[o]:r.sizes,t.sizes,(e,t)=>e===`icon`?I(t,10,32):I(t,16,80)),c=R(r.font,t.font,(e,t)=>e===`family`||e===`mono`?Kn(t):e===`size`?I(t,11,20):e===`weight`||e===`strongWeight`?I(t,100,900):e===`labelCase`?t===`none`||t===`uppercase`:I(t,0,.5)),l=a===`airy`&&t.font?.mono===void 0?{...c,mono:c.family}:c;return{preset:n,density:a,radius:i,components:R(Vn(i,r.components),t.components,(e,t)=>I(t,0,999)),sizes:s,font:l,borders:R(r.borders,t.borders,(e,t)=>e===`width`?I(t,0,4):typeof t==`boolean`),shadows:R(r.shadows,t.shadows,(e,t)=>Kn(t)),blur:I(t.blur,0,40)?t.blur:r.blur,active:L(t.active,[`tint`,`solid`,`underline`])?t.active:r.active,toolbar:L(t.toolbar,[`docked`,`floating`])?t.toolbar:r.toolbar,sidebar:L(t.sidebar,[`docked`,`floating`])?t.sidebar:r.sidebar,intervals:L(t.intervals,[`plain`,`segmented`])?t.intervals:r.intervals,tagRadius:I(t.tagRadius,0,999)?t.tagRadius:r.tagRadius,scale:typeof t.scale==`number`&&Number.isFinite(t.scale)&&t.scale>=An&&t.scale<=jn?t.scale:`auto`}}function Jn(e){let t=e=>`${e}px`,n=e.radius,r=e.components,i=e.sizes,a=e.font;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-menu-item-h":t(i.menuItem),"--tcw-font":a.family,"--tcw-font-mono":a.mono,"--tcw-font-size":t(a.size),"--tcw-font-size-sm":t(F(a.size,-1)),"--tcw-font-size-xs":t(F(a.size,-2)),"--tcw-font-size-lg":t(F(a.size,1)),"--tcw-font-size-xl":t(F(a.size,2)),"--tcw-font-size-display":t(F(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-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 Yn(e,t,n={}){let r=n.variables!==!1;for(let[n,i]of Object.entries(Jn(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`}var Xn=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=Zn,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}},Zn=80,Qn={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 $n(e,t){let n=`tool.${e}`,r=t?.(n);return r&&r!==n?r:Qn[e]??e}function er(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var tr=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function nr(e){return tr(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 rr(e){if(!tr(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 ir=class{constructor(e=`tcw:indicator-defaults`,t=er()){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(!tr(t))return e;for(let[n,r]of Object.entries(t))tr(r)&&e.set(n,{params:nr(r.params),style:rr(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:nr(t.params),style:rr(t.style)}]]);try{return this.storage.setItem(this.key,JSON.stringify(n)),!0}catch{return!1}}},ar=1,or=[`logScale`,`autoScale`],sr=new Set([`timezone`,`numberLocale`]),cr=new Set([...or,`chartTypeOptions`]),lr=new Set([...or,...sr,`scaleMode`,`invertScale`,`chartTypeOptions`]),ur=new Set([...or,...sr,`scaleMode`]),dr=new Set,fr=[`renko`,`lineBreak`,`kagi`,`pointAndFigure`,`rangeBars`];function pr(e){return fr.includes(e)}function mr(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>vr(e)&&Object.keys(e).length>0))}function hr(){return Object.fromEntries(fr.map(e=>[e,{}]))}var gr={crosshairMode:[`normal`,`magnet`,`hidden`],scaleMode:[`regular`,`logarithmic`,`percentage`,`indexedTo100`],periodLevelsPeriod:[`day`,`week`]},_r={marketProfileBuckets:{min:8,max:200,whole:!0},marketProfileOpacity:{min:.05,max:1},depthHeatmapOpacity:{min:.1,max:1},pivotStrength:{min:2,max:20,whole:!0}},vr=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function yr(e){return e===`local`||t.v(e)!==null}function br(e){try{return Intl.NumberFormat.supportedLocalesOf(e).length>0}catch{return!1}}function xr(e,n){let r=t.h[e];if(e===`chartTypeOptions`)return vr(n)?(0,u.readChartTypeOptions)(n):void 0;if(typeof n!=typeof r)return;if(typeof n==`number`){if(!Number.isFinite(n))return;let t=_r[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=gr[e];return i?i.includes(n)?n:void 0:e===`timezone`?yr(n)?n:void 0:e===`numberLocale`?br(n)?n:void 0:n}function B(e,n=dr){if(!vr(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=xr(i,e[i]);t!==void 0&&(r[i]=t)}return r}function Sr(e,t){return Object.fromEntries(Object.keys(e).filter(e=>!t.has(e)).map(t=>[t,e[t]]))}function Cr(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 wr(e,t){return Cr({...e,chartTypeOptions:mr(e.chartTypeOptions)},t,ur)}function Tr(e){return e?(e===!0?void 0:e.key)||`tcw:chart-settings`:null}function Er(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Dr=class{constructor(e,t=Er()){this.key=e,this.storage=t}load(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`null`)}catch{return{}}return!vr(e)||e.v!==ar?{}:B(e.settings,cr)}save(e,t){try{this.storage?.setItem(this.key,JSON.stringify({v:ar,settings:Cr(e,t,cr)}))}catch{}}};function Or(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var kr=80;function Ar(e){let{text:t,...n}=(0,u.sanitizeDrawingStyle)(e);return n}function jr(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 Mr=class{templates=[];constructor(e=`tcw:draw-templates`,t=Or()){this.storageKey=e,this.storage=t,this.load()}list(e){return this.templates.filter(t=>!t.type||t.type===e).map(jr)}get(e,t){let n=this.templates.find(n=>n.name===e&&n.type===t);return n?jr(n):null}save(e,t,n){let r=e.trim().slice(0,kr);if(!r)return;let i={name:r,style:Ar(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,kr),style:Ar(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{}}},Nr=class{defaults={};constructor(e=`tcw:drawing-defaults`,t=Or()){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{}}},Pr=[`#4c8dff`,`#1fa874`,`#e8505b`,`#f2a93b`,`#a57cff`,`#1398a8`,`#ffffff`,`#7d8696`],Fr=[1,2,3,4],Ir=[`solid`,`dashed`,`dotted`],Lr=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 Pr){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 Fr){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 Ir){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)}}},Rr={color:`color`,fill:`fillColor`,textColor:`textColor`},zr=10,V=4,Br=4,Vr=20,Hr=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d\s.,%/+-]+\)|[a-z]+)$/i;function H(e){return typeof e==`string`&&Hr.test(e.trim())?e.trim():`#7d8696`}function Ur(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.min(t,Vr):1}function Wr(e){return Ir.includes(e)?e:`solid`}var Gr=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=[H(t.color),Ur(t.lineWidth),Wr(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=H(e.style.color),r=Ur(e.style.lineWidth),o=Wr(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>`,u=(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>`,u(`color`,t(`drawingSettings.color`),`<span class="tcw-sel-color" style="background:${a.u(n)}"></span>`),u(`width`,t(`drawingSettings.lineWidth`),`<span class="tcw-sel-width" style="--w:${r}px"></span><span class="tcw-sel-num">${r}px</span>`),u(`lineStyle`,t(`drawingSettings.lineStyle`),Kr(o)),e.canFill?u(`fill`,t(`drawingSettings.fill`),`<span class="tcw-sel-color tcw-sel-fill" style="background:${a.u(H(e.style.fillColor??n))}"></span>`):``,e.canText?u(`textColor`,t(`drawingSettings.textColor`),`<span class="tcw-sel-text" style="--c:${a.u(H(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 d=this.buttons(),f=d.find(e=>e.dataset.action===c)??(c?d.find(e=>e.dataset.action===`lock`):void 0);this.rove(f??d[0],f!==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+V,Math.min(this.pinned.left,n.x+n.width-r-V)),t=Math.max(n.y+V,Math.min(this.pinned.top,n.y+n.height-i-V));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+V,Math.min(a,n.x+n.width-r-V));let o=t.y-i-zr;o<n.y+V&&(o=Math.min(t.y+t.height+zr,n.y+n.height-i-V)),o=Math.max(o,n.y+V),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+V)}}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=H(e===`fill`?n.fillColor??n.color:e===`textColor`?n.textColor??n.color:n.color).toLowerCase(),i=Ur(n.lineWidth),o=Wr(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=Pr.map(e=>s(`tcw-sel-swatch`,e.toLowerCase()===r,`data-color="${e}" style="background:${e}" aria-label="${e}"`)).join(``):e===`width`?this.pop.innerHTML=Fr.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=Ir.map(e=>s(`tcw-sel-option`,e===o,`data-style="${e}"`,Kr(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`?Br: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 Rr?Rr[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:Wr(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 Kr(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 U={text:{box:!1,border:!1,wrap:0,fontSize:14},note:{box:!0,border:!0,wrap:240,fontSize:13},callout:{box:!0,border:!0,wrap:240,fontSize:13},signpost:{box:!0,border:!0,wrap:200,fontSize:13},balloon:{box:!0,border:!0,wrap:200,fontSize:13},anchoredText:{box:!1,border:!1,wrap:0,fontSize:14},anchoredNote:{box:!0,border:!0,wrap:240,fontSize:13}},qr=new Set([`trendLine`,`ray`,`extendedLine`,`infoLine`,`trendAngle`,`arrow`,`horizontalLine`,`horizontalRay`,`verticalLine`,`rectangle`]),Jr={priceLabel:`#ffffff`},Yr=8,Xr=6,Zr=1.3,Qr=120,$r=229,ei=500,W=8,ti=400,ni=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<ei){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(Zr),color:e.color,padding:`${Xr}px ${Yr}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===$r)&&(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(Qr,window.innerWidth-W*2);t.style.maxWidth=`${n}px`,t.style.width=`${Math.min(n,Math.max(Qr,e.width))}px`,t.style.minHeight=`${e.height}px`;let r=t.offsetWidth||Math.max(Qr,e.width),i=t.offsetHeight||e.height;t.style.left=`${Math.max(W,Math.min(e.x,window.innerWidth-W-r))}px`,t.style.top=`${Math.max(W,Math.min(e.y,window.innerHeight-W-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>ti){this.finish(!0,!1);return}this.place(e),this.follow()})}},ri=[{id:`regularScale`,mode:`regular`,label:`settings.scale.regular`},{id:`logScale`,mode:`logarithmic`,label:`settings.scale.logarithmic`},{id:`percentScale`,mode:`percentage`,label:`settings.scale.percentage`},{id:`indexedScale`,mode:`indexedTo100`,label:`settings.scale.indexedTo100`}],ii=[{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 ai(e){return ri.find(t=>t.id===e)?.mode}function oi(...e){return e.filter(e=>e.length>0).flatMap((e,t)=>t===0?[...e]:[`separator`,...e])}function si(e,t){let n=t.keys[e.id];return n?{...e,shortcut:n}:e}function ci(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 li=e=>({id:`settings`,label:e(`chartMenu.settings`),icon:`settings`});function ui(e,t){let n=[si({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 oi(ci(e,t),n,r,[...i,li(t)])}function di(e,t){let n=[{id:`resetPriceScale`,label:t(`chartMenu.resetPriceScale`)},{id:`autoScale`,label:t(`settings.autoScale`),checked:e.autoScale},si({id:`invertScale`,label:t(`chartMenu.invertScale`),checked:e.inverted},e),{id:`leftScale`,label:t(`settings.leftScale`),checked:e.leftScale}],r=ri.filter(t=>t.mode!==`logarithmic`||e.canLog).map(n=>({id:n.id,label:t(n.label),radio:!0,checked:e.scaleMode===n.mode})),i=[{id:`indicatorValueLabels`,label:t(`settings.indicatorValues`),checked:e.labels.values},{id:`alignAxisLabels`,label:t(`settings.alignAxisLabels`),checked:e.labels.aligned}];e.labels.countdown!==void 0&&i.push({id:`barCountdown`,label:t(`settings.barCountdown`),checked:e.labels.countdown});let a=[{id:`highLowLines`,label:t(`settings.highLowLines`),checked:e.lines.highLow},{id:`lastPriceLine`,label:t(`chartMenu.lastPriceLine`),checked:e.lines.lastPrice}];return oi(n,r,[{id:`labels`,label:t(`chartMenu.labels`),submenu:i},{id:`lines`,label:t(`chartMenu.lines`),submenu:a}],ci({...e,canTrade:!1,canDraw:!1},t),[li(t)])}function fi(e,t){let n=[si({id:`resetView`,label:t(`chartMenu.resetTimeScale`)},e)];e.canGoToDate&&n.push(si({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 oi(n,r.length>0?[{id:`timezone`,label:t(`settings.timezone`),submenu:r}]:[])}function pi(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 oi([si({id:`resetView`,label:t(`chartMenu.resetView`)},e)],n,[li(t)])}function mi(e,t,n){switch(e){case`priceAxis`:return di(t,n);case`timeAxis`:return fi(t,n);case`pane`:return pi(t,n);default:return ui(t,n)}}var hi=/^[-+−]/;function gi(e,t,n){let r=e.replace(hi,``);return r===n.replace(hi,``)?r:t>0?`+${r}`:t<0?`-${r}`:r}function _i(e){return e.startsWith(`+`)?`up`:e.startsWith(`-`)?`down`:null}var vi=[`positions`,`orders`,`history`],yi=[`order`,`close`,`reverse`,`stopLoss`,`takeProfit`],bi=[`market`,`limit`,`stop`],xi=[`gtc`,`day`],G=`—`,Si=`{pnl}`,Ci=3;function wi(e,t,n){return e.includes(t??``)?t:n}function Ti(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Ei(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 Di(e){let t=document.createElement(`span`);return t.dir=`ltr`,t.textContent=e,t}function Oi(e){let t=_i(e);return t?`tcw-account-${t}`:``}var ki=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 vi){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,Ti(t.positions,e.positions)&&Ti(t.orders,e.orders)&&Ti(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=vi.indexOf(this.tab),n=e.key===`ArrowRight`?t+1:e.key===`ArrowLeft`?t-1:-2;if(n===-2)return;e.preventDefault();let r=vi[(n+vi.length)%vi.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=Ei(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 ${Oi(r)}`.trim();let i=this.t(e),a=i.indexOf(Si),o=Di(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?G:this.callbacks.formatPrice(e),this.writePnl(t.pnl,Ei(t.position,e))}amount(e){return gi(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`${gi(t(Math.abs(e)),e,t(0))}%`}writePnl(e,t){if(t===null){e.className=``,e.textContent=G;return}let n=this.amount(t.pnl);e.className=Oi(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?G: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=Di(``);this.writePnl(a,Ei(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?G: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[Ci],pnl:n[t]}))}renderOrders(){let{formatPrice:e}=this.callbacks,t=this.snapshot.orders.map(t=>{let n=wi(bi,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.${wi(xi,t.timeInForce,`gtc`)}`):G,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=Di(``);return n.pnl===void 0?r.textContent=G:(r.textContent=this.amount(n.pnl),r.className=Oi(r.textContent)),[t(n.time),this.sideCell(n.side,`trade`),String(n.quantity),e(n.price),this.t(`account.reason.${wi(yi,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`)}},Ai=1e-9;function ji(e,t){return e.type===`market`?t:e.price}function Mi(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=ji(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,...Ni(e,n)]}function Ni(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)>Ai)&&n.push(`priceStep`),o&&r!==null&&r>0&&(r>o.ceiling+Ai||r<o.floor-Ai)&&n.push(`priceLimits`),s!==void 0&&s>1&&e.quantity>s&&e.quantity%s!==0&&n.push(`lot`),n}function Pi(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 Fi(e,t){let n=ji(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 Ii(e,t,n,r=1){let i=ji(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 Li(e,t,n={}){let r=n.multiplier!==void 0&&n.multiplier>0?n.multiplier:1,i=ji(e,t),a=i!==null&&i>0&&e.quantity>0?i*e.quantity*r:null,o=Mi(e,t),s=(n,i)=>n===null||o.includes(i)?null:Ii(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?Fi(e,t):null}}var Ri=229,zi=1,Bi=2,Vi=.999999999,Hi=0,Ui=class{backdrop;modal;symbolEl;body;summaryEl;problemsEl;submit;draft=null;lastPrice=null;rules={};step=Gi;round=e=>Ki(e,e);typed=new Map;returnFocus=null;uid=++Hi;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!==Ri){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??Gi,this.round=e.round??(e=>Ki(e,e)),this.typed.clear(),this.symbolEl.textContent=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*Vi)}writePrice(e){return Number.isFinite(e)?this.step===Gi?String(e):e.toFixed((0,u.stepDecimals)(this.step(e))):``}place(){let e=this.draft;!e||Mi(e,this.lastPrice,this.rules).length>0||(this.callbacks.onSubmit(Pi(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=Wi(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=Wi(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:Bi;return this.round(n*(1+(t.side===`buy`?r:-r)/100))}check(){let e=this.draft;if(!e)return;let t=Mi(e,this.lastPrice,this.rules),n=t.map(e=>this.problemText(e));n.join(`
7797
+ `}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)},Pt)}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 It){let n=e.querySelector(`[data-act="${t}"]`);n&&(n.disabled=this.pending)}}},Rt=864e5,zt=6e4,Bt=1e3,Vt=150,Ht=5e3,Ut=8,Wt=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 Lt({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*Ut),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>=Rt)return s;let c={hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`};return(!Number.isFinite(i)||i<zt)&&(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(!Gt(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(),Vt)}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?Bt:Bt/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(Ht,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||D()||O()||!E(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 Gt(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 Kt=()=>typeof document<`u`&&document.hidden;function k(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var qt=class{el;headerEl;nameBtn;menuEl;listEl;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){this.callbacks=t,this.labels=n,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 r=document.createElement(`button`);r.type=`button`,r.className=`tcw-watchlist-add`,r.innerHTML=i.i(`plus`,14),r.title=n.add,r.setAttribute(`aria-label`,n.add),r.hidden=!t.onAdd,r.addEventListener(`click`,()=>t.onAdd?.());let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-watchlist-close`,a.setAttribute(`aria-label`,n.close??n.title),a.innerHTML=i.i(`x`,14),a.hidden=!t.onClose,a.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,r,a,this.menuEl),this.el.appendChild(this.headerEl),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-watchlist-list`,this.listEl.setAttribute(`role`,`list`),this.el.appendChild(this.listEl),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);if(this.listEl.replaceChildren(...e.map(e=>this.rowMap.get(e).row)),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)}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=Jt(e);let r=document.createElement(`canvas`);r.className=`tcw-watchlist-spark`,r.width=64,r.height=22;let a=document.createElement(`div`);a.className=`tcw-watchlist-stats`;let o=document.createElement(`span`);o.className=`tcw-watchlist-price`,o.textContent=`—`;let c=document.createElement(`span`);if(c.className=`tcw-watchlist-change`,a.append(o,c),t.append(n,r,a),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)}),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,changeEl:c,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=Yt(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=Math.abs(r).toLocaleString(this.locale,{minimumFractionDigits:2,maximumFractionDigits:2});t.changeEl.textContent=`${i}${a}%`,t.changeEl.className=`tcw-watchlist-change ${e>=0?`tcw-up`:`tcw-down`}`}else t.changeEl.textContent=``;n.sparkline&&n.sparkline.length>=2&&Xt(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 Jt(e){for(let t of[`USDT`,`USD`,`BTC`,`ETH`,`EUR`])if(e.length>t.length&&e.endsWith(t))return e.slice(0,-t.length)+`/`+t;return e}function Yt(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 Xt(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 Zt=50,Qt=500,$t=60,en=e=>typeof e==`string`&&e.trim().slice(0,$t)||null;function tn(e){let t=[];for(let n of e){let e=a.n(n);if(e&&!t.includes(e)&&t.push(e),t.length===Qt)break}return t}function nn(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===Zt)break;if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`&&t.id&&t.id.length<=64?t.id:null,i=en(t.name);!r||!i||n.some(e=>e.id===r)||n.push({id:r,name:i,symbols:Array.isArray(t.symbols)?tn(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 rn=e=>({...e,symbols:[...e.symbols]}),an=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?nn({lists:e.lists,active:e.activeList}):null,r=t??n??{lists:[{id:`default`,name:en(e.defaultName)??`Watchlist`,symbols:tn(e.symbols??[])}],active:`default`};this.lists=r.lists,this.active=r.active}getLists(){return this.lists.map(rn)}getActive(){return rn(this.activeList())}setActive(e){e===this.active||!this.lists.some(t=>t.id===e)||(this.active=e,this.changed())}replace(e,t){let n=nn({lists:e,active:t??this.active});n&&(this.lists=n.lists,this.active=n.active,this.changed())}create(e){let t=en(e);if(!t||this.lists.length>=Zt)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(),rn(r)}rename(e,t){let n=en(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>=Qt?!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?nn(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{}}},on=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`,t.append(A(`div`,`tcw-syminfo-symbol`,e.symbol)),e.description&&t.append(A(`div`,`tcw-syminfo-desc`,e.description)),e.meta&&t.append(A(`div`,`tcw-syminfo-meta`,e.meta));let n=document.createElement(`div`);if(n.className=`tcw-syminfo-quote`,e.price&&n.append(A(`span`,`tcw-syminfo-price`,e.price)),e.change){let t=A(`span`,`tcw-syminfo-change`,e.change.text);t.classList.add(e.change.up?`tcw-up`:`tcw-down`),n.append(t)}let r=A(`div`,`tcw-syminfo-status`,e.status.text);r.dataset.state=e.status.state;let i=document.createElement(`dl`);i.className=`tcw-syminfo-stats`;for(let t of e.stats){let e=document.createElement(`div`);e.className=`tcw-syminfo-stat`,e.append(A(`dt`,``,t.label),A(`dd`,``,t.value)),i.append(e)}this.bodyEl.replaceChildren(t,n,r,i)}renderNews(e){if(this.newsEl.hidden=e.kind===`none`,e.kind===`none`){this.newsEl.replaceChildren();return}let t=A(`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(A(`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(A(`span`,``,t.title));t.meta&&e.append(A(`div`,`tcw-syminfo-news-meta`,t.meta)),n.append(e)}this.newsEl.replaceChildren(t,n)}destroy(){this.el.remove()}};function A(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}var sn=10,cn=5*6e4,ln=864e5,un=2;function dn(e){let{info:t,quote:n,t:r,textLocale:i}=e,a=(0,u.symbolTimeZone)(t),o=pn(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=mn(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:gn(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`),_n(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}${hn(Math.abs(m),un,e.numberLocale)}%)`}`,up:f>=0},status:{state:h.state,text:g},stats:_}}var fn=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,mn(e.time-t,r)].filter(Boolean).join(` · `)}))})},s=this.cache.get(e);if(s&&Date.now()-s.at<cn){o(s.items);return}n({kind:`loading`}),Promise.resolve().then(()=>t(e,sn)).then(t=>{if(a!==this.request||i())return;let n=(0,u.readNews)(t,sn);this.cache.set(e,{at:Date.now(),items:n}),o(n)}).catch(()=>{a===this.request&&!i()&&n({kind:`failed`})})}};function pn(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))/ln)},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 mn(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 hn(e,t,n){try{return(0,u.formatPrice)(e,t,n)}catch{return e.toFixed(t)}}function gn(e,t){try{return new Intl.NumberFormat(t,{notation:`compact`,maximumFractionDigits:2}).format(e)}catch{return String(e)}}function _n(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 vn={KeyT:`trendLine`,KeyH:`horizontalLine`,KeyJ:`horizontalRay`,KeyV:`verticalLine`,KeyC:`crossLine`,KeyF:`fibRetracement`};function yn(){let e={};for(let[t,n]of Object.entries(vn))e[n]=`Alt+${t.replace(/^Key/,``)}`;return e}var bn=300,xn=80,Sn=u.PHI**-3,Cn=80,wn=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(Cn,t.height*Sn);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),xn)},bn)}stopHold(){this.holdTimer&&clearTimeout(this.holdTimer),this.repeatTimer&&clearInterval(this.repeatTimer),this.holdTimer=null,this.repeatTimer=null}};function Tn(e,t,n,r=!1){let i=e.label??t(`alerts.source.price`),a=An.get(e.condition),o=a?t(a):e.condition;if(Dn.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?Mn(e.price):n(e.price):`—`;return`${(c||e.drawingId)&&e.label?`${e.label} `:r?`${i} `:``}${o} ${l}`}var En=[{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`}],Dn=[`movesUp`,`movesDown`],On={hour:36e5,day:864e5,week:7*864e5,month:30*864e5},kn=``,An=new Map(En.map(e=>[e.value,e.key]));function jn(e){return Math.round(e*1e6)/1e6}function Mn(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var Nn=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 En){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=Dn.includes(this.conditionSelect.value);this.moveRow.hidden=!e,this.levelRow.hidden=e,this.priceInput.hidden=this.targetSelect.value!==kn}renderTargets(){let e=this.targetSelect.value,t=this.sourceSelect.value||`price`;this.targetSelect.replaceChildren();let n=document.createElement(`option`);n.value=kn,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:kn,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(jn(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(Dn.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!==kn)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=On[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 Tn(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)}}},Pn=`print`,Fn=3,In=10,Ln=[[3400,1/2],[2560,1/3],[1800,1/6]],Rn=Math.sqrt(u.PHI),zn=.75,Bn=2;function Vn(e){let t=Ln.find(([t])=>e>=t);return t?u.PHI**t[1]:1}function Hn(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 j(e,t){return Math.max(In,(0,u.phiStep)(e,t,Fn))}var Un=`system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`,Wn=`'JetBrains Mono', 'SF Mono', 'Cascadia Code', 'Fira Code', 'Consolas', ui-monospace, monospace`,Gn=u.SANS_FONT_FAMILY,Kn=`'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`,qn=`Tahoma, Verdana, 'Segoe UI', 'DejaVu Sans', sans-serif`,Jn={print:{radius:{xs:1,sm:2,md:3,lg:5,xl:8},components:{tag:2,toolbar:0,sidebar:0},sizes:{toolbar:42,control:26,controlSmall:20,icon:16,sidebar:53,menuItem:33},density:{compact:{toolbar:33,control:20,controlSmall:20,icon:16,sidebar:33,menuItem:26},spacious:{toolbar:53,control:33,controlSmall:26,icon:20,sidebar:62,menuItem:42}},font:{family:Gn,mono:Kn,size:13,weight:400,strongWeight:600,labelCase:`uppercase`,labelTracking:.06},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border), var(--tcw-shadow-md)`,dialog:`0 0 0 1px var(--tcw-border), var(--tcw-shadow-lg)`,tooltip:`var(--tcw-shadow-sm)`},blur:0,active:`solid`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:2},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:58,menuItem:30},font:{family:`'Manrope', 'Inter', ${Un}`,mono:Wn,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},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:53,menuItem:26},font:{family:`'IBM Plex Sans Condensed', 'Roboto Condensed', 'Arial Narrow', ${Un}`,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},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:61,menuItem:34},font:{family:`'Sora', 'Manrope', ${Un}`,mono:Wn,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},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:51,menuItem:24},font:{family:qn,mono:qn,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}},Yn={compact:{toolbar:38,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},spacious:{toolbar:52,control:34,controlSmall:28,icon:20,sidebar:63,menuItem:34}};function Xn(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 Zn=Object.freeze(Object.fromEntries(Object.keys(Jn).map(e=>[e,$n(Qn(e))])));function Qn(e){let{density:t,...n}=Jn[e];return{...n,preset:e,density:`comfortable`,scale:`auto`,radius:{...n.radius},components:Xn(n.radius,n.components),sizes:{...n.sizes},font:{...n.font},borders:{...n.borders},shadows:{...n.shadows}}}function $n(e){for(let t of Object.values(e))t&&typeof t==`object`&&$n(t);return Object.freeze(e)}var er=e=>typeof e==`string`&&Object.prototype.hasOwnProperty.call(Jn,e),M=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,tr=e=>typeof e==`string`&&e.trim().length>0&&e.length<=300&&!/[;{}<>\\]|url\s*\(|expression\s*\(|\/\*/i.test(e)&&nr(e);function nr(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 N=(e,t)=>typeof e==`string`&&t.includes(e);function P(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 F(e){let t=typeof e==`string`?{preset:e}:e??{},n=er(t.preset)?t.preset:Pn,r=Jn[n],i=P(r.radius,t.radius,(e,t)=>M(t,0,999)),a=N(t.density,[`compact`,`comfortable`,`spacious`,`airy`])?t.density:`comfortable`,o=a===`airy`?`spacious`:a,s=P(o===`compact`||o===`spacious`?(r.density??Yn)[o]:r.sizes,t.sizes,(e,t)=>e===`icon`?M(t,10,32):M(t,16,80)),c=P(r.font,t.font,(e,t)=>e===`family`||e===`mono`?tr(t):e===`size`?M(t,11,20):e===`weight`||e===`strongWeight`?M(t,100,900):e===`labelCase`?t===`none`||t===`uppercase`:M(t,0,.5)),l=a===`airy`&&t.font?.mono===void 0?{...c,mono:c.family}:c;return{preset:n,density:a,radius:i,components:P(Xn(i,r.components),t.components,(e,t)=>M(t,0,999)),sizes:s,font:l,borders:P(r.borders,t.borders,(e,t)=>e===`width`?M(t,0,4):typeof t==`boolean`),shadows:P(r.shadows,t.shadows,(e,t)=>tr(t)),blur:M(t.blur,0,40)?t.blur:r.blur,active:N(t.active,[`tint`,`solid`,`underline`])?t.active:r.active,toolbar:N(t.toolbar,[`docked`,`floating`])?t.toolbar:r.toolbar,sidebar:N(t.sidebar,[`docked`,`floating`])?t.sidebar:r.sidebar,intervals:N(t.intervals,[`plain`,`segmented`])?t.intervals:r.intervals,tagRadius:M(t.tagRadius,0,999)?t.tagRadius:r.tagRadius,scale:typeof t.scale==`number`&&Number.isFinite(t.scale)&&t.scale>=zn&&t.scale<=Bn?t.scale:`auto`}}function rr(e){let t=e=>`${e}px`,n=e.radius,r=e.components,i=e.sizes,a=e.font,o=e.density===`compact`?1:Rn;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(Math.round(i.control*o)),"--tcw-tool-icon":t(2*Math.round(i.icon*o/2)),"--tcw-menu-item-h":t(i.menuItem),"--tcw-font":a.family,"--tcw-font-mono":a.mono,"--tcw-font-size":t(a.size),"--tcw-font-size-sm":t(j(a.size,-1)),"--tcw-font-size-xs":t(j(a.size,-2)),"--tcw-font-size-lg":t(j(a.size,1)),"--tcw-font-size-xl":t(j(a.size,2)),"--tcw-font-size-display":t(j(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-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 ir(e,t,n={}){let r=n.variables!==!1;for(let[n,i]of Object.entries(rr(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`}var ar=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=or,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}},or=80,sr={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 cr(e,t){let n=`tool.${e}`,r=t?.(n);return r&&r!==n?r:sr[e]??e}function lr(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var ur=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function dr(e){return ur(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 fr(e){if(!ur(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 pr=class{constructor(e=`tcw:indicator-defaults`,t=lr()){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(!ur(t))return e;for(let[n,r]of Object.entries(t))ur(r)&&e.set(n,{params:dr(r.params),style:fr(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:dr(t.params),style:fr(t.style)}]]);try{return this.storage.setItem(this.key,JSON.stringify(n)),!0}catch{return!1}}},mr=1,hr=[`logScale`,`autoScale`],gr=new Set([`timezone`,`numberLocale`]),_r=new Set([...hr,`chartTypeOptions`]),vr=new Set([...hr,...gr,`scaleMode`,`invertScale`,`chartTypeOptions`]),yr=new Set([...hr,...gr,`scaleMode`]),br=new Set,xr=[`renko`,`lineBreak`,`kagi`,`pointAndFigure`,`rangeBars`];function Sr(e){return xr.includes(e)}function Cr(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>I(e)&&Object.keys(e).length>0))}function wr(){return Object.fromEntries(xr.map(e=>[e,{}]))}var Tr={crosshairMode:[`normal`,`magnet`,`hidden`],scaleMode:[`regular`,`logarithmic`,`percentage`,`indexedTo100`],periodLevelsPeriod:[`day`,`week`]},Er={marketProfileBuckets:{min:8,max:200,whole:!0},marketProfileOpacity:{min:.05,max:1},depthHeatmapOpacity:{min:.1,max:1},pivotStrength:{min:2,max:20,whole:!0}},I=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Dr(e){return e===`local`||t.v(e)!==null}function Or(e){try{return Intl.NumberFormat.supportedLocalesOf(e).length>0}catch{return!1}}function kr(e,n){let r=t.h[e];if(e===`chartTypeOptions`)return I(n)?(0,u.readChartTypeOptions)(n):void 0;if(typeof n!=typeof r)return;if(typeof n==`number`){if(!Number.isFinite(n))return;let t=Er[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=Tr[e];return i?i.includes(n)?n:void 0:e===`timezone`?Dr(n)?n:void 0:e===`numberLocale`?Or(n)?n:void 0:n}function L(e,n=br){if(!I(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=kr(i,e[i]);t!==void 0&&(r[i]=t)}return r}function Ar(e,t){return Object.fromEntries(Object.keys(e).filter(e=>!t.has(e)).map(t=>[t,e[t]]))}function jr(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 Mr(e,t){return jr({...e,chartTypeOptions:Cr(e.chartTypeOptions)},t,yr)}function Nr(e){return e?(e===!0?void 0:e.key)||`tcw:chart-settings`:null}function Pr(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Fr=class{constructor(e,t=Pr()){this.key=e,this.storage=t}load(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`null`)}catch{return{}}return!I(e)||e.v!==mr?{}:L(e.settings,_r)}save(e,t){try{this.storage?.setItem(this.key,JSON.stringify({v:mr,settings:jr(e,t,_r)}))}catch{}}};function Ir(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Lr=80;function Rr(e){let{text:t,...n}=(0,u.sanitizeDrawingStyle)(e);return n}function zr(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 Br=class{templates=[];constructor(e=`tcw:draw-templates`,t=Ir()){this.storageKey=e,this.storage=t,this.load()}list(e){return this.templates.filter(t=>!t.type||t.type===e).map(zr)}get(e,t){let n=this.templates.find(n=>n.name===e&&n.type===t);return n?zr(n):null}save(e,t,n){let r=e.trim().slice(0,Lr);if(!r)return;let i={name:r,style:Rr(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,Lr),style:Rr(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{}}},Vr=class{defaults={};constructor(e=`tcw:drawing-defaults`,t=Ir()){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{}}},Hr=[`#4c8dff`,`#1fa874`,`#e8505b`,`#f2a93b`,`#a57cff`,`#1398a8`,`#ffffff`,`#7d8696`],Ur=[1,2,3,4],Wr=[`solid`,`dashed`,`dotted`],Gr=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 Hr){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 Ur){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 Wr){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)}}},Kr={color:`color`,fill:`fillColor`,textColor:`textColor`},qr=10,R=4,Jr=4,Yr=20,Xr=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d\s.,%/+-]+\)|[a-z]+)$/i;function z(e){return typeof e==`string`&&Xr.test(e.trim())?e.trim():`#7d8696`}function Zr(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.min(t,Yr):1}function Qr(e){return Wr.includes(e)?e:`solid`}var $r=class{el;pop;target=null;built=``;size=null;openPop=null;pinned=null;drag=null;onDragMove=e=>{!this.drag||!this.target||e.pointerId!==this.drag.id||(this.pinned={left:this.drag.left+e.clientX-this.drag.x,top:this.drag.top+e.clientY-this.drag.y},this.place(this.target))};onDragEnd=e=>{e&&this.drag&&e.pointerId!==this.drag.id||(this.drag=null,document.removeEventListener(`pointermove`,this.onDragMove),document.removeEventListener(`pointerup`,this.onDragEnd),document.removeEventListener(`pointercancel`,this.onDragEnd))};onDocDown=e=>{this.openPop&&!this.el.contains(e.target)&&!this.pop.contains(e.target)&&this.closePop()};constructor(e,t,n=s.t){this.host=e,this.callbacks=t,this.t=n,this.el=document.createElement(`div`),this.el.className=`tcw-sel-toolbar`,this.el.setAttribute(`role`,`toolbar`),this.el.setAttribute(`aria-label`,n(`selectionToolbar.label`)),this.el.hidden=!0,this.pop=document.createElement(`div`),this.pop.className=`tcw-sel-pop`,this.pop.setAttribute(`role`,`dialog`),this.pop.hidden=!0,e.append(this.el,this.pop),this.el.addEventListener(`click`,e=>this.onClick(e)),this.el.addEventListener(`keydown`,e=>this.onKey(e)),this.pop.addEventListener(`click`,e=>this.onPick(e)),this.pop.addEventListener(`keydown`,e=>this.onPopKey(e));for(let e of[this.el,this.pop])e.addEventListener(`pointerdown`,e=>e.stopPropagation());this.el.addEventListener(`pointerdown`,e=>{e.target.closest(`.tcw-sel-grip`)&&(e.preventDefault(),this.closePop(),this.drag={id:e.pointerId,x:e.clientX,y:e.clientY,left:parseFloat(this.el.style.left)||0,top:parseFloat(this.el.style.top)||0},document.addEventListener(`pointermove`,this.onDragMove),document.addEventListener(`pointerup`,this.onDragEnd),document.addEventListener(`pointercancel`,this.onDragEnd))}),this.el.addEventListener(`dblclick`,e=>{!e.target.closest(`.tcw-sel-grip`)||!this.target||(this.pinned=null,this.place(this.target))}),document.addEventListener(`pointerdown`,this.onDocDown,!0)}isOpen(){return!this.el.hidden}show(e){this.target=e;let t=e.style,n=[z(t.color),Zr(t.lineWidth),Qr(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=z(e.style.color),r=Zr(e.style.lineWidth),o=Qr(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>`,u=(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>`,u(`color`,t(`drawingSettings.color`),`<span class="tcw-sel-color" style="background:${a.u(n)}"></span>`),u(`width`,t(`drawingSettings.lineWidth`),`<span class="tcw-sel-width" style="--w:${r}px"></span><span class="tcw-sel-num">${r}px</span>`),u(`lineStyle`,t(`drawingSettings.lineStyle`),ei(o)),e.canFill?u(`fill`,t(`drawingSettings.fill`),`<span class="tcw-sel-color tcw-sel-fill" style="background:${a.u(z(e.style.fillColor??n))}"></span>`):``,e.canText?u(`textColor`,t(`drawingSettings.textColor`),`<span class="tcw-sel-text" style="--c:${a.u(z(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 d=this.buttons(),f=d.find(e=>e.dataset.action===c)??(c?d.find(e=>e.dataset.action===`lock`):void 0);this.rove(f??d[0],f!==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+R,Math.min(this.pinned.left,n.x+n.width-r-R)),t=Math.max(n.y+R,Math.min(this.pinned.top,n.y+n.height-i-R));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+R,Math.min(a,n.x+n.width-r-R));let o=t.y-i-qr;o<n.y+R&&(o=Math.min(t.y+t.height+qr,n.y+n.height-i-R)),o=Math.max(o,n.y+R),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+R)}}onKey(e){if(e.key===`Escape`&&this.openPop){e.stopPropagation(),this.closePop(!0);return}let t=this.buttons(),n=t.indexOf(document.activeElement);if(n<0)return;let r=e.key===`ArrowRight`?(n+1)%t.length:e.key===`ArrowLeft`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),this.rove(t[r],!0))}openPopover(e,t){let n=this.target.style,r=z(e===`fill`?n.fillColor??n.color:e===`textColor`?n.textColor??n.color:n.color).toLowerCase(),i=Zr(n.lineWidth),o=Qr(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=Hr.map(e=>s(`tcw-sel-swatch`,e.toLowerCase()===r,`data-color="${e}" style="background:${e}" aria-label="${e}"`)).join(``):e===`width`?this.pop.innerHTML=Ur.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=Wr.map(e=>s(`tcw-sel-option`,e===o,`data-style="${e}"`,ei(e)+a.u(this.t(`drawingSettings.lineStyle.${e}`)))).join(``),this.pop.className=`tcw-sel-pop tcw-sel-pop--${e}`,this.pop.setAttribute(`aria-label`,t.getAttribute(`aria-label`)??``),this.pop.hidden=!1;for(let e of this.el.querySelectorAll(`[aria-expanded="true"]`))e.setAttribute(`aria-expanded`,`false`);t.setAttribute(`aria-expanded`,`true`),this.placePop(),this.pop.querySelector(`.tcw-sel-on, button`)?.focus()}onPopKey(e){if(e.key===`Escape`){e.stopPropagation(),this.closePop(!0);return}let t=[...this.pop.querySelectorAll(`button`)],n=t.indexOf(document.activeElement);if(n<0)return;let r=this.openPop===`color`||this.openPop===`fill`||this.openPop===`textColor`?Jr: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 Kr?Kr[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:Qr(t.dataset.style)}),this.closePop(!0)}closePop(e=!1){if(!this.openPop)return;let t=this.el.querySelector(`[data-action="${this.openPop}"]`);t?.setAttribute(`aria-expanded`,`false`),this.openPop=null,this.pop.hidden=!0,e&&t?.focus()}};function ei(e){return`<svg class="tcw-sel-line" width="22" height="10" viewBox="0 0 22 10" aria-hidden="true"><line x1="1" y1="5" x2="21" y2="5" stroke="currentColor" stroke-width="2"${e===`dashed`?` stroke-dasharray="4 3"`:e===`dotted`?` stroke-dasharray="1 3" stroke-linecap="round"`:``}/></svg>`}var B={text:{box:!1,border:!1,wrap:0,fontSize:14},note:{box:!0,border:!0,wrap:240,fontSize:13},callout:{box:!0,border:!0,wrap:240,fontSize:13},signpost:{box:!0,border:!0,wrap:200,fontSize:13},balloon:{box:!0,border:!0,wrap:200,fontSize:13},anchoredText:{box:!1,border:!1,wrap:0,fontSize:14},anchoredNote:{box:!0,border:!0,wrap:240,fontSize:13}},ti=new Set([`trendLine`,`ray`,`extendedLine`,`infoLine`,`trendAngle`,`arrow`,`horizontalLine`,`horizontalRay`,`verticalLine`,`rectangle`]),ni={priceLabel:`#ffffff`},ri=8,ii=6,ai=1.3,oi=120,si=229,ci=500,V=8,li=400,ui=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<ci){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(ai),color:e.color,padding:`${ii}px ${ri}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===si)&&(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(oi,window.innerWidth-V*2);t.style.maxWidth=`${n}px`,t.style.width=`${Math.min(n,Math.max(oi,e.width))}px`,t.style.minHeight=`${e.height}px`;let r=t.offsetWidth||Math.max(oi,e.width),i=t.offsetHeight||e.height;t.style.left=`${Math.max(V,Math.min(e.x,window.innerWidth-V-r))}px`,t.style.top=`${Math.max(V,Math.min(e.y,window.innerHeight-V-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>li){this.finish(!0,!1);return}this.place(e),this.follow()})}},di=[{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`}],fi=[{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 pi(e){return di.find(t=>t.id===e)?.mode}function mi(...e){return e.filter(e=>e.length>0).flatMap((e,t)=>t===0?[...e]:[`separator`,...e])}function H(e,t){let n=t.keys[e.id];return n?{...e,shortcut:n}:e}function hi(e,t){if(e.price===void 0||!Number.isFinite(e.price))return[];let n=e.formatPrice(e.price),r=[];if(e.canAlert&&r.push({id:`alert`,label:s.r(t(`chartMenu.addAlert`),{price:n}),icon:`bell`}),e.canTrade){let i=e.lastPrice===null||e.price<=e.lastPrice;r.push(i?{id:`buyLimit`,label:s.r(t(`chartMenu.buyLimit`),{price:n}),icon:`trendingUp`}:{id:`buyStop`,label:s.r(t(`chartMenu.buyStop`),{price:n}),icon:`trendingUp`},i?{id:`sellStop`,label:s.r(t(`chartMenu.sellStop`),{price:n}),icon:`trendingDown`}:{id:`sellLimit`,label:s.r(t(`chartMenu.sellLimit`),{price:n}),icon:`trendingDown`}),e.canOrderTicket&&r.push({id:`orderTicket`,label:t(`chartMenu.orderTicket`),icon:`receipt`})}return e.canDraw&&r.push({id:`horizontalLine`,label:s.r(t(`chartMenu.horizontalLine`),{price:n}),icon:`minus`}),r}var gi=e=>({id:`settings`,label:e(`chartMenu.settings`),icon:`settings`});function _i(e,t){let n=[H({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 mi(hi(e,t),n,r,[...i,gi(t)])}function vi(e,t){let n=[{id:`resetPriceScale`,label:t(`chartMenu.resetPriceScale`)},{id:`autoScale`,label:t(`settings.autoScale`),checked:e.autoScale},H({id:`invertScale`,label:t(`chartMenu.invertScale`),checked:e.inverted},e),{id:`leftScale`,label:t(`settings.leftScale`),checked:e.leftScale}],r=di.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 mi(n,r,[{id:`labels`,label:t(`chartMenu.labels`),submenu:i},{id:`lines`,label:t(`chartMenu.lines`),submenu:a}],hi({...e,canTrade:!1,canDraw:!1},t),[gi(t)])}function yi(e,t){let n=[H({id:`resetView`,label:t(`chartMenu.resetTimeScale`)},e)];e.canGoToDate&&n.push(H({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 mi(n,r.length>0?[{id:`timezone`,label:t(`settings.timezone`),submenu:r}]:[])}function bi(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 mi([H({id:`resetView`,label:t(`chartMenu.resetView`)},e)],n,[gi(t)])}function xi(e,t,n){switch(e){case`priceAxis`:return vi(t,n);case`timeAxis`:return yi(t,n);case`pane`:return bi(t,n);default:return _i(t,n)}}var Si=/^[-+−]/;function U(e,t,n){let r=e.replace(Si,``);return r===n.replace(Si,``)?r:t>0?`+${r}`:t<0?`-${r}`:r}function Ci(e){return e.startsWith(`+`)?`up`:e.startsWith(`-`)?`down`:null}var W=[`positions`,`orders`,`history`],wi=[`order`,`close`,`reverse`,`stopLoss`,`takeProfit`],Ti=[`market`,`limit`,`stop`],Ei=[`gtc`,`day`],G=`—`,Di=`{pnl}`,Oi=3;function ki(e,t,n){return e.includes(t??``)?t:n}function Ai(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function ji(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 Mi(e){let t=document.createElement(`span`);return t.dir=`ltr`,t.textContent=e,t}function Ni(e){let t=Ci(e);return t?`tcw-account-${t}`:``}var Pi=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 W){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,Ai(t.positions,e.positions)&&Ai(t.orders,e.orders)&&Ai(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=W.indexOf(this.tab),n=e.key===`ArrowRight`?t+1:e.key===`ArrowLeft`?t-1:-2;if(n===-2)return;e.preventDefault();let r=W[(n+W.length)%W.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=ji(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 ${Ni(r)}`.trim();let i=this.t(e),a=i.indexOf(Di),o=Mi(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?G:this.callbacks.formatPrice(e),this.writePnl(t.pnl,ji(t.position,e))}amount(e){return U(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`${U(t(Math.abs(e)),e,t(0))}%`}writePnl(e,t){if(t===null){e.className=``,e.textContent=G;return}let n=this.amount(t.pnl);e.className=Ni(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?G: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=Mi(``);this.writePnl(a,ji(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?G: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[Oi],pnl:n[t]}))}renderOrders(){let{formatPrice:e}=this.callbacks,t=this.snapshot.orders.map(t=>{let n=ki(Ti,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.${ki(Ei,t.timeInForce,`gtc`)}`):G,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=Mi(``);return n.pnl===void 0?r.textContent=G:(r.textContent=this.amount(n.pnl),r.className=Ni(r.textContent)),[t(n.time),this.sideCell(n.side,`trade`),String(n.quantity),e(n.price),this.t(`account.reason.${ki(wi,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`)}},Fi=1e-9;function Ii(e,t){return e.type===`market`?t:e.price}function Li(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=Ii(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,...Ri(e,n)]}function Ri(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)>Fi)&&n.push(`priceStep`),o&&r!==null&&r>0&&(r>o.ceiling+Fi||r<o.floor-Fi)&&n.push(`priceLimits`),s!==void 0&&s>1&&e.quantity>s&&e.quantity%s!==0&&n.push(`lot`),n}function zi(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 Bi(e,t){let n=Ii(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 Vi(e,t,n,r=1){let i=Ii(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 Hi(e,t,n={}){let r=n.multiplier!==void 0&&n.multiplier>0?n.multiplier:1,i=Ii(e,t),a=i!==null&&i>0&&e.quantity>0?i*e.quantity*r:null,o=Li(e,t),s=(n,i)=>n===null||o.includes(i)?null:Vi(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?Bi(e,t):null}}var Ui=229,Wi=1,Gi=2,Ki=.999999999,qi=0,Ji=class{backdrop;modal;symbolEl;body;summaryEl;problemsEl;submit;draft=null;lastPrice=null;rules={};step=Xi;round=e=>Zi(e,e);typed=new Map;returnFocus=null;uid=++qi;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!==Ui){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??Xi,this.round=e.round??(e=>Zi(e,e)),this.typed.clear(),this.symbolEl.textContent=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*Ki)}writePrice(e){return Number.isFinite(e)?this.step===Xi?String(e):e.toFixed((0,u.stepDecimals)(this.step(e))):``}place(){let e=this.draft;!e||Li(e,this.lastPrice,this.rules).length>0||(this.callbacks.onSubmit(zi(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=Yi(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=Yi(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`?-Wi:Gi;return this.round(n*(1+(t.side===`buy`?r:-r)/100))}check(){let e=this.draft;if(!e)return;let t=Li(e,this.lastPrice,this.rules),n=t.map(e=>this.problemText(e));n.join(`
7732
7798
  `)!==[...this.problemsEl.children].map(e=>e.textContent).join(`
7733
- `)&&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:Ii(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=Li(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:_i(n)],[`reward`,`ticket.reward`,r,r===null?null:_i(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 gi(this.number(Math.abs(e),t),e,this.number(0,t))}amount(e){return gi(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 Wi(e,t){return t.dataset.ticketField=e,t}function Gi(e){let t=Math.abs(e);return t>0?10**Math.floor(Math.log10(t/100)):1}function Ki(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 qi=0,Ji=class{backdrop;titleEl;input;submit;request=null;returnFocus=null;busy=!1;uid=++qi;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()}}}},Yi=0,Xi=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-${++Yi}`,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=xe(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=xe(this.input.value);if(e&&this.onApply(e)){this.close();return}this.input.setAttribute(`aria-invalid`,`true`),this.hint.textContent=this.labels.invalid}},Zi=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{}}},Qi=[`regular`,`logarithmic`,`percentage`,`indexedTo100`],$i=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function ea(e){let{theme:t,timestamp:n,...r}=e;return r}function ta(e){return!$i(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:Qi.find(t=>t===e.scaleMode)??`regular`,invertScale:e.invertScale===!0,chart:$i(e.chart)?ea(e.chart):null,...$i(e.settings)?{settings:B(e.settings,lr)}:{}}}function na(e){try{return JSON.parse(e)}catch{return null}}function ra(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var ia=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=ra()){this.storageKey=e,this.storage=t,this.load()}list(){return[...this.favorites]}has(e){return this.favorites.includes(e)}add(e){!e||this.favorites.includes(e)||(this.favorites=[...this.favorites,e],this.persist())}remove(e){this.favorites.includes(e)&&(this.favorites=this.favorites.filter(t=>t!==e),this.persist())}toggle(e){return this.has(e)?(this.remove(e),!1):(this.add(e),!0)}seedDefaults(e){this.favorites.length>0||(this.favorites=[...new Set(e.filter(Boolean))],this.persist())}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&(this.favorites=[...new Set(t.filter(e=>typeof e==`string`))])}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.favorites))}catch{}}};function aa(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 oa(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 K(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 sa=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}},q={settings:K(()=>Promise.resolve().then(()=>require(`../WidgetSettings-D7Pq42zW.cjs`))),indicatorSettings:K(()=>Promise.resolve().then(()=>require(`../WidgetIndicatorSettings-C7vpco6e.cjs`))),drawingSettings:K(()=>Promise.resolve().then(()=>require(`../WidgetDrawingSettings-Cyl2u_u8.cjs`))),goToDate:K(()=>Promise.resolve().then(()=>require(`../WidgetGoToDate-BNdngHlg.cjs`))),hotkeySheet:K(()=>Promise.resolve().then(()=>require(`../WidgetHotkeySheet-y5LWKSG6.cjs`))),indicatorPicker:K(()=>Promise.resolve().then(()=>require(`../WidgetIndicatorPicker-DuKJFPRC.cjs`))),commandPalette:K(()=>Promise.resolve().then(()=>require(`../WidgetCommandPalette-ZZNbWwCZ.cjs`))),symbolSearch:K(()=>Promise.resolve().then(()=>require(`../WidgetSymbolSearch-C4OR42nZ.cjs`)))};async function ca(){await Promise.all(Object.values(q).map(e=>e.load().catch(()=>null)))}var la=/^(\d{4})-(\d{2})-(\d{2})$/,ua=/^(\d{2}):(\d{2})$/;function da(e,t,n){let r=la.exec(e),i=t?ua.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 J(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 Y={min:233,default:296,max:377},fa=.382,pa=e=>!e.hidden&&getComputedStyle(e).display!==`none`,ma=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(Y.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?.()??Y.default,Y.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)&&pa(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(pa),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?Y.max:Math.max(Y.min,Math.min(Y.max,Math.floor(e*fa)))}clamp(e,t=this.maxNow()){return Math.round(Math.min(t,Math.max(Y.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`?Y.min:e.key===`End`?Y.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(pa),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())}},ha=[`percent`,`scale`,`pane`,`spread`,`ratio`,`correlation`,`correlationLog`],ga={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 _a(e){return ha.includes(e)}function va(e){return ha.map(t=>({id:t,label:e(ga[t])}))}function ya(e,t){let n=e.findIndex(e=>e.time>=t);return n<0?e.length:n}function ba(e,t){let n=e[0]?.time??1/0,r=t.filter(e=>e.time<n);return r.length>0?[...r,...e]:null}function xa(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 Sa(e,t,n,r){let i=e.map(e=>({id:e.id,symbol:e.symbol,way:r(ga.percent),color:e.color}));for(let e of t){let t=e.params.symbol,a=xa(e,n.has(e.instanceId));!a||typeof t!=`string`||!t||i.push({id:e.instanceId,symbol:t,way:r(ga[a])})}return i}var X=8,Ca=4,wa=3,Ta=`[title]:not([title=""]), [data-tip]:not([data-tip=""])`,Ea=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`)&&Da(this.pressed);let e=this.target;!e||this.source!==`pointer`||!e.hasAttribute(`title`)||(Da(e),this.isVisible()&&this.show(e))}),this.observer.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`title`]})}destroy(){this.hide(),this.pressed&&Z(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`||(Da(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)&&(Z(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&&Z(this.pressed),this.pressed=t?e:null};onFocus=e=>{let t=this.tipTarget(e.target);!t||!Aa(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`&&Z(this.target),this.target=null,this.source=null};tipTarget(e){if(!(e instanceof Element))return null;let t=e.closest(Ta);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`&&Z(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(!ka(e)){this.hide();return}this.el.textContent=Oa(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&&(ka(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=ja(e);s===`bottom`&&o+n.height+X+i>t.height?s=`top`:s===`top`&&o-X-i<0?s=`bottom`:s===`right`&&a+n.width+X+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+X:o-X-i):(c=s===`right`?a+n.width+X:a-X-r,l=o+n.height/2-i/2),c=Math.max(Ca,Math.min(t.width-r-Ca,c)),l=Math.max(Ca,Math.min(t.height-i-Ca,l)),this.el.style.left=`${Math.round(c)}px`,this.el.style.top=`${Math.round(l)}px`;let u={top:[0,wa],bottom:[0,-wa],left:[wa,0],right:[-wa,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 Da(e){let t=e.getAttribute(`title`);t!==null&&(e.dataset.tip=t,e.removeAttribute(`title`))}function Z(e){e.dataset.tip!==void 0&&!e.hasAttribute(`title`)&&(e.setAttribute(`title`,e.dataset.tip),delete e.dataset.tip)}function Oa(e){return e.dataset.tip??e.getAttribute(`title`)??``}function ka(e){return e.isConnected&&e.getClientRects().length>0&&!e.disabled}function Aa(e){try{return e.matches(`:focus-visible`)}catch{return!1}}function ja(e){return e.dataset.tipSide||(e.closest(`.tcw-sidebar`)?`right`:e.closest(`.tcw-statusbar, .tcw-replay-bar`)?`top`:`bottom`)}var Ma=2,Na=1.5,Pa=`tcw-ind-legend-values--no-room`,Fa=0,Ia=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)La(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),Q(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-${++Fa}`;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),Q(e.eye,t.visible?this.labels.hide:this.labels.show,t.label),e.settings&&Q(e.settings,this.labels.settings,t.label),e.more&&(Q(e.more,this.labels.more??`More`,t.label),e.more.setAttribute(`aria-haspopup`,`menu`)),Q(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>=Ma;!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;Q(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 La(e,t){let n=(parseFloat(getComputedStyle(e).fontSize)||0)*Na;e.classList.toggle(Pa,t<n)}function Q(e,t,n){e.title=t,e.setAttribute(`aria-label`,n?`${t} ${n}`:t)}function Ra(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 Ba=new Map;function Va(e){let t=Ba.get(e);return t||(t=new Intl.NumberFormat(e,{notation:`compact`,maximumFractionDigits:2}),Ba.set(e,t)),t}function Ha(e,t=`en-US`){return Math.abs(e)>=1e6?Va(t).format(e):(0,u.formatPrice)(e,(0,d.indicatorValuePrecision)(e),t)}var Ua=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()}},Wa=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 Ga(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 Ka=1e-9,qa=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?Ga(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=Ja(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=Ya(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 Ja(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:Ka}function Ya(e){return e>=1e3?`${Number((e/1e3).toFixed(1))}k`:String(Number(e>=1?e.toFixed(2):e.toPrecision(2)))}var Xa=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(b()?`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??Qa)(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??Za(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 Za(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 Qa(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 $a=[[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]],eo=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`),$a.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)}},to=4e3,no=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(),to)):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}},ro=`host:`;function io(e,t){return[...e,...e.length>0&&t.length>0?[`separator`]:[],...t.map((e,t)=>({id:`${ro}${t}`,label:e.label,icon:e.icon,danger:e.danger,checked:e.checked}))]}function ao(e,t){return e.startsWith(ro)?(t[Number(e.slice(5))]?.onSelect(),!0):!1}var oo=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent),so={ctrl:`ctrl`,control:`ctrl`,cmd:`ctrl`,command:`ctrl`,meta:`ctrl`,mod:`ctrl`,alt:`alt`,option:`alt`,opt:`alt`,shift:`shift`},co={esc:`escape`,space:` `,spacebar:` `,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`,del:`delete`,return:`enter`,plus:`+`};function lo(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=so[e.toLowerCase()];if(!t)return null;r[t]=!0}let i=n.toLowerCase();if(so[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=co[i]??i,r.shift&&r.key.length===1)return null;return r.display=[...r.ctrl?[oo?`⌘`:`Ctrl`]:[],...r.alt?[`Alt`]:[],...r.shift?[`Shift`]:[],r.key===` `?`Space`:n.length===1?n.toUpperCase():n],r}function uo(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 fo=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 po(e){let t=`${e.ctrl?`ctrl+`:``}${e.alt?`alt+`:``}${e.shift?`shift+`:``}${e.char??e.key}`;return fo.has(t)}function mo(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 ho=[`#b552c9`,`#1398a8`,`#d4622b`,`#e25592`,`#6f7a8c`,`#3e9a4f`],go=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:va(this.host.t),way:this.compareWay,compared:this.comparedNow(),onAdd:(e,t)=>{_a(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 Sa(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=ho[this.compares.length%ho.length];this.compares.length===0&&this.host.chart.setCompareMode(`percent`),this.host.chart.addCompareSymbol(n,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: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:t,interval:pe(n)}),`error`):this.sayCompareFailed(t,i),null)}}sayCompareFailed(e,t){this.host.say(`${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=ya(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=ba(r.bars,t);i?this.setCompareBars(e,i,n):this.compares=this.compares.map(t=>t.id===e?{...t,atStart:!0}:t)}setCompareBars(e,t,n){this.host.chart.updateCompareData(e,t),this.compares=this.compares.map(r=>r.id===e?{...r,bars:t,timeframe:n,atStart:!1,failedAt:void 0}:r)}compareFailedAt(e,t){this.compares=this.compares.map(n=>n.id===e?{...n,failedAt:t}:n)}},_o=class{constructor(e){this.host=e}watchlist=null;watchlistSparkBuffer=new Map;hostWatchlistRefPrice=new Map;watchlistInterval=null;watchlistStore=null;watchlistFromSymbols=!1;quoteSource=null;stopQuotes=null;quotedKey=``;quotes=new Map;getWatchlists(){return this.watchlistStore?.getLists()??[]}getActiveWatchlist(){return this.watchlistStore?.getActive().id??null}setWatchlists(e,t){this.watchlistFromSymbols=!1,this.watchlistStore?.replace(e,t)}setActiveWatchlist(e){this.watchlistStore?.setActive(e)}addToWatchlist(e,t){this.watchlistStore?.add(e,t)}removeFromWatchlist(e,t){this.watchlistStore?.removeSymbol(e,t)}setQuotes(e){let t=e.map(u.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)}getQuote(e){let t=this.quotes.get(e);return t?{...t}:null}createWatchlist(e,t){let n=t.persist?N():null,r=new Xt({lists:t.lists,activeList:t.activeList,symbols:this.host.symbols,defaultName:this.host.t(`watchlist.title`),storage:n,storageKey:t.storageKey});this.watchlistStore=r,this.watchlistFromSymbols=!t.lists&&!t.persist,this.quoteSource=t.quotes===!1?null:t.quotes??(this.host.options.adapter?.subscribeQuotes?this.host.options.adapter:null);let i=e=>this.host.t(e);this.watchlist=new zt(e,{onSelect:e=>{this.host.setSymbol(e)},onAdd:()=>this.host.withSymbolSearch(()=>!0,e=>e.open({symbols:this.host.symbolEntries(),current:this.host.state.symbol,currentInfo:this.host.chartSymbolInfo(),onPick:e=>r.add(e),search:this.host.symbolSearchFn()})),onRemove:e=>r.removeSymbol(e),onMove:(e,t)=>r.move(e,t),onPickList:e=>r.setActive(e),onCreateList:e=>r.create(e),onRenameList:(e,t)=>r.rename(e,t),onDeleteList:e=>r.remove(e),onClose:()=>this.host.closePanelByHand(`watchlist`)},{close:i(`common.close`),title:i(`watchlist.title`),lists:i(`watchlist.lists`),newList:i(`watchlist.newList`),rename:i(`watchlist.rename`),deleteList:i(`watchlist.deleteList`),confirmDelete:i(`watchlist.confirmDelete`),add:i(`watchlist.add`),remove:i(`watchlist.remove`),empty:i(`watchlist.empty`),listName:i(`watchlist.listName`)}),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)||Rt())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()})}},vo=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 _n(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=Ra(this.host.chart.getIndicatorOutput(r)?.series,null)?.[i];return typeof a==`number`&&Number.isFinite(a)?a:null}},yo=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 bo(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 xo=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(bo({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=io(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=>{ao(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(ii.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=io(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=>{ao(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=ai(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()}},So=2,Co=2;function wo(e,t=`en-US`){return(0,u.formatPrice)(e,Math.max(So,(0,d.indicatorValuePrecision)(e)),t)}function To(e,t=`en-US`){return`${gi((0,u.formatPrice)(Math.abs(e),Co,t),e,(0,u.formatPrice)(0,Co,t))}%`}function Eo(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:Do(e,t)}:{values:[],offChartType:!0},pane:null}))}function Do(e,t){return[...e.close===null?[]:[{text:wo(e.close,t),color:null}],...e.change===null?[]:[{text:To(e.change,t),color:null}]]}var Oo=7,ko=17,Ao=3;function jo(e){return!d.SYMBOL_INDICATOR_IDS.has(e.id)&&e.scale!==`left`}var Mo=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=Eo(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=Ra(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&&jo(e),a),color:n.color})),pane:t?{x:t.x+4,y:t.y+Math.min(Oo+t.row*ko,Math.max(Oo,t.height-ko)),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+Ao,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=io(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=>{ao(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)}},No=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=dn();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:pe(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}),this.host.settings?.refresh(this.host.shownSettings());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}}},Po=0,Fo=class{backdrop;search;listEl;layouts=[];confirming=null;returnFocus=null;loadSeq=0;uid=++Po;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,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()}}},Io=5,Lo=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 Ji(n,r),this.dialog=new Fo(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,Io)}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()}},Ro=e=>typeof e==`object`&&!!e&&!Array.isArray(e),zo=globalThis.Buffer;function Bo(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 Vo(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 Ho(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Uo(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function Wo(e){return Ho(Bo(JSON.stringify(e)))}function Go(e){if(!e)return null;try{let t=Vo(Uo(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:Qi.find(e=>e===n.scaleMode)??`regular`,indicators:Array.isArray(n.indicators)?n.indicators:[],drawings:Array.isArray(n.drawings)?n.drawings:[],...Ro(n.settings)?{settings:B(n.settings,ur)}:{}}}catch{return null}}var Ko=`tcw`;function qo(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)!==Ko))try{return decodeURIComponent(e.slice(t+1))}catch{return null}}return null}function Jo(e,t){let[n]=e.split(`#`);return`${n}#${Ko}=${t}`}var Yo=[`legendVisible`,`volumeVisible`,`barCountdown`,`indicatorValueLabels`,`alignAxisLabels`],Xo=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=qo(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=wr(n,{...t.h,...Object.fromEntries(Yo.map(e=>[e,this.host.settingsDefaults[e]]))});return Wo({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=Go(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,...B(t.settings,ur)}),i=this.host.overViewerTypeOptions(t.chartType,n);return this.host.showLinkSettings(i?{...r,chartTypeOptions:i}:r),this.host.settings?.refresh(this.host.shownSettings()),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=Jo(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?na(t):null,r=n&&typeof n==`object`?ea(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:Sr(e,lr)}}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(ea(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,...B(e.settings,lr)});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=ta(na(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 Lo(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}=J(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}}},Zo={alerts:`alerts`,objectTree:`objectTree`,dataWindow:`dataWindow`,symbolInfo:`symbolInfo`,depthLadder:`depthLadder`},Qo={alerts:`alerts`,objectTree:`objects`,symbolInfo:`symbolInfo`,depthLadder:`trade`},$o=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[Zo[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)&&jo(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.toolbar?.setActive(`alerts`,!0)},onHide:()=>{t.close(),this.host.toolbar?.setActive(`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.toolbar?.setActive(`objects`,!0)},onHide:()=>{n.close(),this.host.toolbar?.setActive(`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=Qo[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||$n(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:e.symbol,color:e.color,way:e.way}));this.host.objectTree.setObjects(e,t,n)}},es=new Set([`timezone`,`numberLocale`,`chartTypeOptions`,`logScale`,`autoScale`]),ts=80,ns=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function rs(e){return B(e,es)}function is(e){let{overrides:n}=(0,u.readChartStyleOverrides)(e);return Object.fromEntries(Object.entries(n).filter(([e,n])=>n!==null&&t.l.includes(e)))}function as(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var os=class{constructor(e=`tcw:chart-templates`,t=as()){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)!ns(n)||typeof n.name!=`string`||!n.name.trim()||t.push({name:n.name.slice(0,ts).trim(),settings:rs(n.settings),style:is(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,ts).trim();if(!r||!this.storage)return!1;let i=[...this.list().filter(e=>e.name!==r),{name:r,settings:rs(t),style:is(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{}}},ss=new Set([...sr,`autoScale`]),cs=class{constructor(e){this.host=e}chartTemplates=new os;chartTemplatePrompt=null;settingsEdit=null;settingsState;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 Ji(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(B(e)));this.claimSettings(Object.keys(t)),this.applySettings(t),this.host.settings?.refresh(this.shownSettings())}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(B({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:mr(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)}}}applySettings(e,n=!0){this.settingsState={...this.settingsState,...e},Object.keys(e).some(e=>!ss.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({...hr(),...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())}},ls=13;function us(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 ds=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=us(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=U[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||ls,bold:a.bold===!0,italic:a.italic===!0,family:this.host.chart.getFont?.()?.family??this.host.ui.font.family},color:a.textColor??Jr[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:U[r.type],textColor:Jr[r.type],textPlace:qr.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 Ji(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()}))}})}},fs=200,ps=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 De({dayShare:n.slice(-fs).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:pe(e),custom:this.host.customTimeframes.has(e)}))}handleAddTimeframe(e){if(!this.host.featureState.customTimeframes)return!1;let t=xe(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=Se(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=Se(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()}},ms=600,hs=24,gs=[`--tcw-toolbar-h`,`--tcw-control-h`,`--tcw-control-h-sm`,`--tcw-icon`,`--tcw-sidebar-w`,`--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`],_s=48,vs=5e4,ys=100;function bs(){return new Promise(e=>{if(typeof requestAnimationFrame!=`function`||document.hidden){setTimeout(e,0);return}let t=setTimeout(e,ys);requestAnimationFrame(()=>setTimeout(()=>{clearTimeout(t),e()},0))})}var xs=864e5,Ss=5e3,Cs=2e3,ws=48,Ts=`rgba(255,255,255,0.03)`,Es=`rgba(0,0,0,0.03)`,Ds=2;function Os(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 ks=1e3,As=[[`barCountdown`,`barCountdown`],[`logScale`,`logScale`],[`legendVisible`,`legend`],[`volumeVisible`,`volume`]],js=t.l.filter(e=>u.CHART_STYLE_KEYS[e]!==`color`);function Ms(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 Ns=class{intervals=new ps(this.intervalsHost());drawingEdit=new ds(this.drawingEditHost());chartSettings=new cs(this.chartSettingsHost());docking=new $o(this.dockingHost());layouts=new Xo(this.layoutsHost());commands=new No(this.commandsHost());legend=new Mo(this.legendHost());menus=new xo(this.menusHost());trading=new yo(this.tradingHost());alerting=new vo(this.alertingHost());watching=new _o(this.watchingHost());comparing=new go(this.comparingHost());chart;state;themeOf={dark:u.DARK_THEME,light:u.LIGHT_THEME};toolbar=null;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 Zi;templatePrompt=null;markerTip=null;dataWindow=null;lastHoverIndex=null;lastHoverBar=null;lastHoverPrevClose=null;legendHoverIndex=null;pointerOnChart=!1;favoritesStore=new ia;indicatorFavorites=new ia(`tcw:indicator-favorites`);indicatorDefaults=new ir;timeframeFavorites=new ia(`tcw:tf-favorites`);customTimeframes=new ia(`tcw:tf-custom`);timeframes=[];sessionRefPrice=null;symbolInfoPanel=null;news=new rn;marketTimer=null;clockTimer=null;onPageShown=null;chartNav=null;visibleBarCount=50;root;chartContainer;loading;historyPill;connectSeq=0;localSeq=0;lastLocalSwitchMs=0;destroyed=!1;scope=nt();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(n,i={}){let c=Ms(i);this.options=c;let l=a.o(c.symbols??t.g);this.symbols=l.names,this.symbolCatalog=l.info;let f=c.chartOptions;if(this.chartSettings.settingsState={...t.h,...f?.crosshair?.mode?{crosshairMode:f.crosshair.mode}:{},...f?.logScale&&f.features?.logScale!==!1?{logScale:!0,scaleMode:`logarithmic`}:{},...f?.numberLocale?{numberLocale:f.numberLocale}:{},...f?.timeZone==null?{}:{timezone:t.b(f.timeZone)},...f?.leftPriceScale===void 0?{}:{leftPriceScale:f.leftPriceScale},...f?.highLowLines===void 0?{}:{highLowLines:f.highLowLines},...f?.extendedHours===void 0?{}:{extendedHours:f.extendedHours},...f?.chartTypeOptions?{chartTypeOptions:(0,u.readChartTypeOptions)(f.chartTypeOptions)}:{}},this.t=s.n(s.o(c.locale,c.messages)),this.featureState=r.u(c),c.persistLayouts){let e=c.persistLayouts===!0?{}:c.persistLayouts;this.layouts.layoutKeyPrefix=e.keyPrefix??`tcw:layout:`,this.layouts.layoutDebounceMs=e.debounceMs??1500}let p=Tr(c.persistSettings);p&&(this.chartSettings.settingsStore=new Dr(p));let m=this.resolveIsDark(c.theme),h=this.resolveTheme(c.theme);this.themeOf={...this.themeOf,[m?`dark`:`light`]:h};let g={drawings:!0,drawingMagnet:!0,drawingUndoRedo:!0,indicators:!0,trading:c.trading!==!1,tradingContextMenu:!1,priceAxisAddButton:this.featureState.alerts||c.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,...c.chartOptions?.features};this.priceAxisAddDefault=g.priceAxisAddButton===!0;let _={...g,priceAxisAddButton:this.priceAxisAddDefault&&this.featureState[`menu.priceAxisAdd`]};if(this.canExport=g.dataExport!==!1,this.chartSettings.settingsLocked=new Set(As.filter(([,e])=>g[e]===!1).map(([e])=>e)),this.chartSettings.settingsDefaults={...this.chartSettings.settingsState,legendVisible:g.legend!==!1,volumeVisible:g.volume!==!1,barCountdown:g.barCountdown!==!1,indicatorValueLabels:g.indicatorValueLabels===!0,alignAxisLabels:g.alignAxisLabels!==!1},this.chartSettings.settingsState={...this.chartSettings.settingsDefaults},this.timeframes=Se(ge(c.timeframes,g.timeframes),this.customTimeframes.list(),g.timeframes),!this.timeframes.some(e=>this.timeframeFavorites.has(e))){let e=_e(this.timeframes,g.defaultTimeframeFavorites,!!c.timeframes?.length);for(let t of e)this.timeframeFavorites.add(t)}let v=c.timeframe??`5m`,y=!g.timeframes?.length||g.timeframes.includes(v)?v:this.timeframes[0]??v;this.state={symbol:c.symbol??this.symbols[0]??`BTCUSDT`,timeframe:y,chartType:c.chartOptions?.chartType??`candlestick`,isDark:m,activeIndicators:new Map,activeTool:null,magnetEnabled:!1,magnetStrong:!1,eraser:!1,zoomArea:!1,stayInDrawing:!1,connectionState:c.adapter?`connecting`:`disconnected`,connectionMessage:c.adapter?this.t(`status.connecting`):``},se(),this.root=document.createElement(`div`),this.root.className=`tcw-root`;let ee=c.dir===`ltr`||c.dir===`rtl`?c.dir:Hs(c.locale)?`rtl`:`ltr`;this.root.dir=ee,this.portal.dir=ee,n.appendChild(this.root),this.tooltip=new Ea(this.root),this.portal.className=`tcw-root tcw-portal`,this.look=$e({dark:m,theme:h});let b=!1;this.scope.run(()=>et(()=>{let{dark:e,theme:t}=this.look.get();this.root.dataset.tcwTheme=this.portal.dataset.tcwTheme=e?`dark`:`light`,b&&(this.keepingLook(()=>this.chart.setTheme(t)),this.paintWatermark())})),b=!0,this.stopKeyboardInset=aa([this.root,this.portal]),this.stopNarrow=oa(this.root,e=>{this.toolbar?.fit(),e||this.sidebar?.closeOverlay(),this.docking.syncRail()}),this.ui=z(c.ui),this.uiVariables=c.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=te([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()}),this.toolbar=new Le(this.root,{symbols:this.symbols,timeframes:this.intervals.timeframeMenu(),timeframeFavorites:this.intervals.pinnedTimeframes(),chartTypes:c.chartTypes?t.m.filter(e=>c.chartTypes.includes(e.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:c.trading===!1?void 0:()=>this.trading.toggleAccountPanel(),onLayouts:c.layouts===!1?void 0:e=>void this.layouts.layoutsUI?.openMenu(e),onBracket:c.trading===!1?void 0:e=>this.trading.startBracket(e),onToggleLadder:c.trading!==!1&&c.depthLadder?()=>this.trading.toggleLadder():void 0,onOrderTicket:c.trading===!1?void 0:()=>this.trading.openOrderTicket(),onCompare:c.adapter&&g.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 x=document.createElement(`div`);x.className=`tcw-body`,c.drawingFavorites&&this.favoritesStore.seedDefaults(c.drawingFavorites),this.sidebar=new lt(x,{drawingToolGroups:t.n(t._,this.t),favorites:this.favoritesStore.list(),shortcuts:dn()},{onDrawingTool:e=>this.handleDrawingTool(e),onCancelDrawing:()=>this.handleCancelDrawing(),onToggleMagnet:g.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`,x.appendChild(this.chartContainer),this.loading=new eo(this.chartContainer,this.t(`status.loading`)),this.historyPill=new no(this.chartContainer,{loading:this.t(`history.loading`),failed:this.t(`history.failed`)}),this.docking.dock=new ma(x,{labels:{rail:this.t(`dock.rail`),resize:this.t(`dock.resize`)},savedWidth:()=>Bs(),saveWidth:e=>Vs(e),railShown:()=>this.docking.railShown(),focusAfterClose:e=>this.docking.panelFocusTarget(e),room:()=>x.clientWidth}),c.watchlist&&this.watching.createWatchlist(x,c.watchlist===!0?{}:c.watchlist),this.root.appendChild(x);let S=document.createElement(`div`);S.className=`tcw-account-dock`,r.o(S,`accountPanel`),this.root.appendChild(S),this.chart=new e.c(this.chartContainer,{chartType:this.state.chartType,theme:h,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}}},...c.chartOptions,features:_}),c.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 gn(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 Zt(this.root,this.t,{onClose:()=>this.docking.closePanelByHand(`symbolInfo`),onToggle:e=>{this.toolbar?.setActive(`symbolInfo`,e),e&&(this.refreshSymbolInfo(),this.loadNews())}}),this.marketTimer=setInterval(()=>this.refreshMarket(),3e4),this.onPageShown=()=>{Rt()||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(),g.drawingMagnet!==!1&&this.chart.setDrawingMagnetMode(`off`),this.statusBar=new yt(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:g.logScale===!1?void 0:()=>this.chartSettings.toggleScaleMode(`logarithmic`),onAuto:()=>this.chartSettings.changeSettings({autoScale:!this.chart.isAutoScale()})}}),this.clockTimer=setInterval(()=>{!Rt()&&this.featureState.statusBar&&this.featureState[`statusBar.clock`]&&this.statusBar?.tick()},ks),this.chart.on(`priceRangeChange`,()=>this.chartSettings.refreshScaleSwitches()),this.chartSettings.refreshScaleSwitches(),this.goToDatePart=this.lazyPart(q.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))),this.settingsPart=this.lazyPart(q.settings,({WidgetSettings:e})=>new e({onChange:e=>this.chartSettings.changeSettings(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:g.barCountdown,logScale:g.logScale,legend:g.legend,volume:g.volume,trading:g.trading!==!1,exchangeZone:()=>this.menus.exchangeChoice()?.zone},this.overlayHost)),this.symbolSearchPart=this.lazyPart(q.symbolSearch,({WidgetSymbolSearch:e})=>new e({onPick:e=>{this.setSymbol(e)},onClose:()=>{}},this.overlayHost,this.t)),this.hotkeySheetPart=this.lazyPart(q.hotkeySheet,({WidgetHotkeySheet:e})=>new e({onClose:()=>{}},this.t,this.overlayHost)),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 Ia(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 It(this.replayHost()),this.replay.attach();for(let e of[`resize`,`dataUpdate`,`symbolInfoChange`])this.chart.on(e,()=>this.placeDrawingButton());this.placeDrawingButton(),this.dataWindow=new Xa(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())});let C=new Mr,ne=new Nr;for(let[e,t]of Object.entries(ne.all()))this.chart.setDrawingToolDefaults(e,t??null);this.drawingSettingsPart=this.lazyPart(q.drawingSettings,({WidgetDrawingSettings:e})=>new e(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=>J(e*(0,u.barTimeUnit)(this.chart.getData()),this.displayTimezone()),fromWallTime:(e,t)=>{let n=da(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,t)=>{this.chart.setDrawingToolDefaults(e,t),ne.set(e,this.chart.getDrawingToolDefaults(e)),this.say(s.r(this.t(`drawingSettings.defaultSaved`),{name:this.drawingToolName(e)}))},templates:{list:e=>C.list(e),save:e=>this.drawingEdit.promptSaveDrawingTemplate(C,e),remove:(e,t)=>C.remove(e,t)}},this.t)),this.drawingEdit.inlineText=new ni(this.overlayHost),this.chart.on(`drawingDoubleClick`,e=>{let t=e.payload.id,n=this.chart.getDrawings().find(e=>e.id===t)?.type;n&&U[n]&&this.drawingEdit.editTextInPlace(t,!1)||this.drawingEdit.openDrawingSettings(t,n&&U[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||!U[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,ms),this.drawingEdit.cancelTextPrompt=a}),this.drawingStyle=new Lr(this.root,{onStyleChange:e=>{this.chart.setDrawingStyle(e),this.chart.setSelectedDrawingStyle(e)},getStyle:()=>this.chart.getDrawingStyle()},C,this.t),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 Gr(this.root,{onStyle:e=>{for(let t of this.chart.getSelectedDrawingIds()){let n=this.chart.getDrawings().find(e=>e.id===t)?.type,r=n?U[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());if(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(mi(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(ci(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 Xi(this.chartContainer,{title:this.t(`interval.title`),hint:this.t(`interval.hint`),invalid:this.t(`interval.invalid`)},e=>this.intervals.selectTypedTimeframe(e)),c.layouts!==!1&&this.layouts.setupLayouts(c.layouts===!0||c.layouts===void 0?{}:c.layouts),c.trading!==!1){this.trading.orderTicket=new Ui(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 ki(S,{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}=J(e,this.displayTimezone());return`${t} ${n}`},formatAmount:e=>this.formatMoney(e),formatNumber:(e,t)=>this.formatNumber(e,t),onToggle:e=>{this.toolbar?.setActive(`account`,e),this.trading.refreshAccount()}},this.t);for(let e of[`ordersChange`,`positionsChange`,`executionFill`,`dataUpdate`,`indicatorUpdate`])this.chart.on(e,()=>this.trading.refreshAccountSoon())}if(c.trading!==!1){if(this.trading.bracketBar=new Ua(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)}))}),c.depthLadder){this.trading.depthLadder=new qa(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.toolbar?.setActive(`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()})}this.alerting.alertsPanel=new Tn(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}=J(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)}))}),c.alertNotifications&&(this.alerting.alertNotifier=new Wa(c.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(q.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.toolbar?.setIndicatorsOpen(!1)},this.t)),this.indicatorSettingsPart=this.lazyPart(q.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 Xn(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:g.compareSymbols===!1?void 0:()=>this.comparing.handleAddCompare(),onRemoveCompare:e=>this.comparing.removeCompared(e)},this.t);let w=()=>{this.objectTree?.isOpen()&&this.docking.refreshObjects()},re=0,ie=()=>{re||!this.objectTree?.isOpen()||(re=requestAnimationFrame(()=>{re=0,this.destroyed||w()}))};this.chart.on(`drawingCreate`,w),this.chart.on(`drawingRemove`,w),this.chart.on(`drawingUpdate`,ie),this.chart.on(`timeframeChange`,ie),this.chart.on(`indicatorAdd`,w),this.chart.on(`indicatorRemove`,w),this.chart.on(`indicatorChange`,w);for(let e of[`indicatorAdd`,`indicatorRemove`,`indicatorChange`])this.chart.on(e,()=>this.comparing.refreshCompareDialog());this.docking.setupDock(),this.commandPalettePart=this.lazyPart(q.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:()=>Ls(),add:e=>Rs([e,...Ls().filter(t=>t!==e)])})),this.boundGlobalKeydown=e=>{if(this.handleHostHotkey(e)||this.featureState.hotkeys&&this.replay.isOpen()&&this.replay.handleReplayKey(e))return;let t=A(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||j()||!A(this.root,!0))return;e.preventDefault(),this.layouts.saveLayout()}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&un[e.code]){if(e.defaultPrevented||j()||!t||M()||!n(`hotkeys.tools`))return;e.preventDefault(),this.handleDrawingTool(un[e.code])}else if(/^[0-9]$/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(e.defaultPrevented||!this.intervals.intervalInput||!n(`intervalTyping`)||j()||M()||!A(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(Os(e)!==null){if(e.defaultPrevented||!n(`symbolTyping`)||!this.featureState.symbolSearch||j()||M()||!A(this.root,!0))return;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t))return;e.preventDefault(),this.openSymbolSearch(Os(e))}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&(e.code===`KeyI`||e.code===`KeyG`||e.code===`KeyR`)){if(j()||!t)return;if(e.code===`KeyI`){if(!n(`hotkeys.invertScale`))return;e.preventDefault(),this.chartSettings.changeSettings({invertScale:!this.chartSettings.settingsState.invertScale}),this.settings?.refresh(this.chartSettings.shownSettings())}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(j()||!t||!n(`hotkeys.help`)||!this.featureState.hotkeySheet)return;e.preventDefault(),this.openHotkeySheet()}},document.addEventListener(`keydown`,this.boundGlobalKeydown),document.addEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys=St(this.root,[this.portal]),this.chartSettings.restoreKeptSettings(),c.adapter?(this.adapter=c.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{c.onReady?.(this.chart,this)}finally{this.destroyed||this.layouts.restoreSharedView()}}),this.preloadDialogsWhenIdle()}preloadDialogsWhenIdle(){let e=()=>{this.destroyed||ca()},t=globalThis;if(t.requestIdleCallback&&t.cancelIdleCallback){let n=t.requestIdleCallback(e,{timeout:Ss}),r=t.cancelIdleCallback;this.stopPreload=()=>r(n)}else{let t=setTimeout(e,Cs);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(Rt())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 nn({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=z(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?Mn(e):1}applyLookTokens(){let e=Nn(this.ui,this.uiScale);for(let t of[this.root,this.portal]){if(Yn(t,e,{variables:this.uiVariables}),this.uiVariables)continue;let n=Jn(e);for(let e of gs)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?Mn(t-hs):Mn(t+hs))===this.uiScale)return}this.uiScale=e,this.applyLookTokens(),this.applyLegendFont(),this.applyChartLook(),this.toolbar?.fit()}}getUI(){return z({...this.ui})}applyLegendFont(){this.chart.setLegend({fontFamily:this.ui.font.mono,fontSize:F(Math.round(this.ui.font.size*this.uiScale),-1)})}applyChartLook(){let e=this.ui.density===`airy`,t=this.options.chartOptions;t?.barLayout||this.chart.setBarLayout(e?`golden`:`classic`);let n=this.scaledChartSizes();t?.font?.family?Object.keys(n).length>0&&this.chart.setFont(n):this.chart.setFont({family:this.ui.font.mono,...n})}scaledChartSizes(){let e=this.options.chartOptions?.font;if(e?.sizeSmall!==void 0||e?.sizeMedium!==void 0||e?.sizeLarge!==void 0)return{};let t=this.chart.getFont?.();if(!t)return{};let n={sizeSmall:t.sizeSmall,sizeMedium:t.sizeMedium,sizeLarge:t.sizeLarge},r=this.drawingEdit.chartFontWritten;if((!r||r.sizeSmall!==n.sizeSmall||r.sizeMedium!==n.sizeMedium||r.sizeLarge!==n.sizeLarge)&&(this.chartFontBase=n),this.uiScale===1&&!r)return{};let i=this.chartFontBase??n,a=e=>this.uiScale===1?e:Math.round(e*this.uiScale),o={sizeSmall:a(i.sizeSmall),sizeMedium:a(i.sizeMedium),sizeLarge:a(i.sizeLarge)};return this.drawingEdit.chartFontWritten=this.uiScale===1?null:o,o}applyChartShapes(){this.chart.setShapes({tagRadius:this.ui.tagRadius})}destroy(){if(!this.destroyed){this.destroyed=!0,this.scope.dispose(),this.stopPreload?.(),this.stopKeyboardInset?.(),this.stopKeyboardInset=null,this.stopNarrow?.(),this.docking.dockObserver?.disconnect(),this.scaleObserver?.disconnect(),this.drawingEdit.inlineText?.close(),this.stopNarrow=null,this.stopFormControls?.(),this.stopFormControls=null,this.boundGlobalKeydown&&document.removeEventListener(`keydown`,this.boundGlobalKeydown),document.removeEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys(),this.tooltip.destroy(),this.legend.legendFrame&&cancelAnimationFrame(this.legend.legendFrame),this.indicatorLegend?.destroy(),this.portal.remove(),document.fullscreenElement===this.root&&document.exitFullscreen().catch(()=>{}),this.layouts.flushActiveLayout(),this.commandPalettePart?.destroy(),this.symbolSearchPart?.destroy(),this.hotkeySheetPart?.destroy(),this.replay.destroy(),this.dragDrop?.detach(),this.alerting.alertsPanel?.destroy(),this.objectTree?.destroy(),this.indicatorSettingsPart?.destroy(),this.indicatorPickerPart?.destroy(),this.drawingStyle?.destroy(),this.drawingSettingsPart?.destroy(),this.menus.drawingMenu?.destroy(),this.menus.clearMenu?.destroy(),this.drawingEdit.cancelTextPrompt?.(),this.drawingEdit.selectionToolbar?.destroy(),this.drawingEdit.selectionToolbarFrame!==null&&cancelAnimationFrame(this.drawingEdit.selectionToolbarFrame),this.menus.chartMenu?.destroy(),this.legend.legendMenu?.destroy();for(let e of this.hostMenus)e.destroy();this.hostMenus.clear(),this.templatePrompt?.destroy(),this.chartSettings.chartTemplatePrompt?.destroy(),this.drawingEdit.drawingTemplatePrompt?.destroy(),this.intervals.intervalInput?.destroy(),this.markerTip?.remove(),this.layouts.layoutSession?.destroy(),this.layouts.layoutsUI?.destroy(),this.chartSettings.settingsListeners.clear(),this.trading.accountPanel?.destroy(),this.trading.orderTicket?.destroy(),this.trading.accountFrame&&cancelAnimationFrame(this.trading.accountFrame),this.trading.bracketBar?.destroy(),this.alerting.alertNotifier?.destroy(),this.trading.depthLadder?.destroy(),this.dataWindow?.destroy(),this.watching.watchlistInterval&&clearInterval(this.watching.watchlistInterval),this.marketTimer&&clearInterval(this.marketTimer),this.clockTimer&&clearInterval(this.clockTimer),this.onPageShown&&document.removeEventListener(`visibilitychange`,this.onPageShown),this.onPageShown=null,this.chartNav?.destroy(),this.symbolInfoPanel?.destroy(),this.docking.dock?.destroy(),this.watching.stopQuotes?.(),this.watching.stopQuotes=null,this.watching.watchlist?.destroy(),this.toolbar?.destroy(),this.sidebar?.destroy(),this.settingsPart?.destroy(),this.statusBar?.destroy(),this.goToDatePart?.destroy(),this.loading.destroy(),this.historyPill.destroy(),this.chart.destroy(),this.root.remove(),ce()}}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=lo(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;po(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||j()||mo(e)||M())return!1;let t=this.hostHotkeys.find(t=>uo(e,t.parsed));if(!t)return!1;let n=!t.parsed.ctrl&&!t.parsed.alt;if(!A(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(this.state.symbol.replace(`USDT`,` / USDT`),{fontSize:ws,color:this.state.isDark?Ts:Es})}keepingLook(e){this.chartSettings.settingsEdit&&this.settings?.close();let t=this.chart.getOverrides?.({layer:`user`})??{},n=Object.fromEntries(js.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=>Re(n,t,e.toggle===!0),setText:t=>void ze(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(io([],i),a,e=>ao(e,i))}});return r.setAttribute(`aria-haspopup`,`menu`),r.setAttribute(`aria-expanded`,`false`),t.tidy(),{element:r,setText:t=>void ze(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=>Re(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}=J(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=>J(e*r,n),a=t[t.length-1].time,o=this.chart.getVisibleTimeRange()??{from:t[0].time,to:a},s=J(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)>=xs),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=da(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=da(e.from.date,e.from.time,n),a=da(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}=J(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 Ji(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>=_s||this.baseSeries.length>=vs;try{if(t&&(this.loading.begin(this.chart.getData().length>0,!0),await bs(),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={...pr(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:Ps(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()),Ds))}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):Ha(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 sa(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}),this.settings?.refresh(this.chartSettings.shownSettings())}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.toolbar?.setIndicatorsOpen(!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.toolbar?.setActive(`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})}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{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 Ps(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 Fs=`tcw:recentCommands`,Is=10;function Ls(){try{let e=JSON.parse(N()?.getItem(Fs)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`).slice(0,Is):[]}catch{return[]}}function Rs(e){try{N()?.setItem(Fs,JSON.stringify(e.slice(0,Is)))}catch{}}var zs=`tcw:dockWidth`;function Bs(){try{let e=Number(N()?.getItem(zs)??NaN);return Number.isFinite(e)&&e>0?e:null}catch{return null}}function Vs(e){try{N()?.setItem(zs,String(e))}catch{}}function Hs(e){return!!e&&/^(ar|he|iw|fa|ur|ps|yi|dv|ckb|sd|ug)(-|$)/i.test(e)}var Us={symbol:!1,interval:!1,crosshair:!0,time:!1,drawings:!1,replay:!1},Ws=[`symbol`,`interval`,`crosshair`,`time`,`drawings`,`replay`],$={"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 Gs(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call($,e)}function Ks(e){return JSON.parse(JSON.stringify(e))}function qs(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 Js(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||t.kind!==`grid`||!Gs(t.layout)||!Array.isArray(t.cells))return null;let n=t.cells.map(ta);if(n.some(e=>e===null))return null;let r=typeof t.sync==`object`&&t.sync!==null?t.sync:{},i={...Us};for(let e of Ws)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 Ys=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||j()||!A(this.root,!0)||(e.preventDefault(),this.layoutsUI.save())};constructor(e,t={}){this.options=t,this.layout=Gs(t.layout)?t.layout:`1x2`,this.sync={...Us,...t.sync},this.t=s.n(s.o(t.widget?.locale,t.widget?.messages)),se(),this.root=document.createElement(`div`),this.root.className=`tcw-root tcw-grid`,this.root.dataset.tcwTheme=t.widget?.theme===`light`?`light`:`dark`,Yn(this.root,z(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=oa(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=St(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||!Gs(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=z(e);Yn(this.root,t);for(let e of this.cells)e.widget.setUI(t);this.uiTheme=t}getUI(){return z(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=Js(na(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(),ce()}}shapeCount(){let{cols:e,rows:t}=$[this.layout];return e*t}applyShape(){let{cols:e,rows:t}=$[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 Ns(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:`${Tr(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=Xs(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(Ks(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(Ks(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=>`${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(Gs)??Object.keys($);for(let e of n){let{cols:n,rows:r}=$[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=qs(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 Ws){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 Lo(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=J(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 Xs(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=Ns,exports.ChartWidgetGrid=Ys,exports.DEFAULT_GRID_SYNC=Us,Object.defineProperty(exports,`DRAWING_TOOL_ICONS`,{enumerable:!0,get:function(){return u.DRAWING_TOOL_ICONS}}),exports.EN_MESSAGES=s.c,exports.GRID_SHAPES=$,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=Hn,exports.applyWidgetUI=Yn,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=Js,exports.readWatchlists=Jt,exports.readWidgetLayout=ta,exports.registerWidgetLocale=s.a,exports.resolveWidgetUI=z,exports.widgetUIVariables=Jn;
7799
+ `)&&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:Vi(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=Hi(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:Ci(n)],[`reward`,`ticket.reward`,r,r===null?null:Ci(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 U(this.number(Math.abs(e),t),e,this.number(0,t))}amount(e){return U(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 Yi(e,t){return t.dataset.ticketField=e,t}function Xi(e){let t=Math.abs(e);return t>0?10**Math.floor(Math.log10(t/100)):1}function Zi(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 Qi=0,$i=class{backdrop;titleEl;input;submit;request=null;returnFocus=null;busy=!1;uid=++Qi;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()}}}},ea=0,ta=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-${++ea}`,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=Te(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=Te(this.input.value);if(e&&this.onApply(e)){this.close();return}this.input.setAttribute(`aria-invalid`,`true`),this.hint.textContent=this.labels.invalid}},na=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{}}},ra=[`regular`,`logarithmic`,`percentage`,`indexedTo100`],ia=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function aa(e){let{theme:t,timestamp:n,...r}=e;return r}function oa(e){return!ia(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:ra.find(t=>t===e.scaleMode)??`regular`,invertScale:e.invertScale===!0,chart:ia(e.chart)?aa(e.chart):null,...ia(e.settings)?{settings:L(e.settings,vr)}:{}}}function sa(e){try{return JSON.parse(e)}catch{return null}}function ca(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var la=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=ca()){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 ua(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 da(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 K(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 fa=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}},q={settings:K(()=>Promise.resolve().then(()=>require(`../WidgetSettings-C0fnWGdY.cjs`))),indicatorSettings:K(()=>Promise.resolve().then(()=>require(`../WidgetIndicatorSettings-C7vpco6e.cjs`))),drawingSettings:K(()=>Promise.resolve().then(()=>require(`../WidgetDrawingSettings-Cyl2u_u8.cjs`))),goToDate:K(()=>Promise.resolve().then(()=>require(`../WidgetGoToDate-BNdngHlg.cjs`))),hotkeySheet:K(()=>Promise.resolve().then(()=>require(`../WidgetHotkeySheet-y5LWKSG6.cjs`))),indicatorPicker:K(()=>Promise.resolve().then(()=>require(`../WidgetIndicatorPicker-DuKJFPRC.cjs`))),commandPalette:K(()=>Promise.resolve().then(()=>require(`../WidgetCommandPalette-ZZNbWwCZ.cjs`))),symbolSearch:K(()=>Promise.resolve().then(()=>require(`../WidgetSymbolSearch-C4OR42nZ.cjs`)))};async function pa(){await Promise.all(Object.values(q).map(e=>e.load().catch(()=>null)))}var ma=/^(\d{4})-(\d{2})-(\d{2})$/,ha=/^(\d{2}):(\d{2})$/;function ga(e,t,n){let r=ma.exec(e),i=t?ha.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 J(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 Y={min:233,default:296,max:377},_a=.382,va=e=>!e.hidden&&getComputedStyle(e).display!==`none`,ya=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(Y.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?.()??Y.default,Y.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)&&va(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(va),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?Y.max:Math.max(Y.min,Math.min(Y.max,Math.floor(e*_a)))}clamp(e,t=this.maxNow()){return Math.round(Math.min(t,Math.max(Y.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`?Y.min:e.key===`End`?Y.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(va),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())}},ba=[`percent`,`scale`,`pane`,`spread`,`ratio`,`correlation`,`correlationLog`],xa={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 Sa(e){return ba.includes(e)}function Ca(e){return ba.map(t=>({id:t,label:e(xa[t])}))}function wa(e,t){let n=e.findIndex(e=>e.time>=t);return n<0?e.length:n}function Ta(e,t){let n=e[0]?.time??1/0,r=t.filter(e=>e.time<n);return r.length>0?[...r,...e]:null}function Ea(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 Da(e,t,n,r){let i=e.map(e=>({id:e.id,symbol:e.symbol,way:r(xa.percent),color:e.color}));for(let e of t){let t=e.params.symbol,a=Ea(e,n.has(e.instanceId));!a||typeof t!=`string`||!t||i.push({id:e.instanceId,symbol:t,way:r(xa[a])})}return i}var X=8,Oa=4,ka=3,Aa=`[title]:not([title=""]), [data-tip]:not([data-tip=""])`,ja=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`)&&Ma(this.pressed);let e=this.target;!e||this.source!==`pointer`||!e.hasAttribute(`title`)||(Ma(e),this.isVisible()&&this.show(e))}),this.observer.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`title`]})}destroy(){this.hide(),this.pressed&&Z(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`||(Ma(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)&&(Z(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&&Z(this.pressed),this.pressed=t?e:null};onFocus=e=>{let t=this.tipTarget(e.target);!t||!Fa(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`&&Z(this.target),this.target=null,this.source=null};tipTarget(e){if(!(e instanceof Element))return null;let t=e.closest(Aa);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`&&Z(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(!Pa(e)){this.hide();return}this.el.textContent=Na(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&&(Pa(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=Ia(e);s===`bottom`&&o+n.height+X+i>t.height?s=`top`:s===`top`&&o-X-i<0?s=`bottom`:s===`right`&&a+n.width+X+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+X:o-X-i):(c=s===`right`?a+n.width+X:a-X-r,l=o+n.height/2-i/2),c=Math.max(Oa,Math.min(t.width-r-Oa,c)),l=Math.max(Oa,Math.min(t.height-i-Oa,l)),this.el.style.left=`${Math.round(c)}px`,this.el.style.top=`${Math.round(l)}px`;let u={top:[0,ka],bottom:[0,-ka],left:[ka,0],right:[-ka,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 Ma(e){let t=e.getAttribute(`title`);t!==null&&(e.dataset.tip=t,e.removeAttribute(`title`))}function Z(e){e.dataset.tip!==void 0&&!e.hasAttribute(`title`)&&(e.setAttribute(`title`,e.dataset.tip),delete e.dataset.tip)}function Na(e){return e.dataset.tip??e.getAttribute(`title`)??``}function Pa(e){return e.isConnected&&e.getClientRects().length>0&&!e.disabled}function Fa(e){try{return e.matches(`:focus-visible`)}catch{return!1}}function Ia(e){return e.dataset.tipSide||(e.closest(`.tcw-sidebar`)?`right`:e.closest(`.tcw-statusbar, .tcw-replay-bar`)?`top`:`bottom`)}var La=2,Ra=1.5,za=`tcw-ind-legend-values--no-room`,Ba=0,Va=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)Ha(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),Q(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-${++Ba}`;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),Q(e.eye,t.visible?this.labels.hide:this.labels.show,t.label),e.settings&&Q(e.settings,this.labels.settings,t.label),e.more&&(Q(e.more,this.labels.more??`More`,t.label),e.more.setAttribute(`aria-haspopup`,`menu`)),Q(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>=La;!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;Q(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 Ha(e,t){let n=(parseFloat(getComputedStyle(e).fontSize)||0)*Ra;e.classList.toggle(za,t<n)}function Q(e,t,n){e.title=t,e.setAttribute(`aria-label`,n?`${t} ${n}`:t)}function Ua(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 Wa(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 Ga=new Map;function Ka(e){let t=Ga.get(e);return t||(t=new Intl.NumberFormat(e,{notation:`compact`,maximumFractionDigits:2}),Ga.set(e,t)),t}function qa(e,t=`en-US`){return Math.abs(e)>=1e6?Ka(t).format(e):(0,u.formatPrice)(e,(0,d.indicatorValuePrecision)(e),t)}var Ja=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()}},Ya=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 Xa(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 Za=1e-9,Qa=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?Xa(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=$a(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=eo(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 $a(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:Za}function eo(e){return e>=1e3?`${Number((e/1e3).toFixed(1))}k`:String(Number(e>=1?e.toFixed(2):e.toPrecision(2)))}var to=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??ro)(n.volume)));for(let t of e.indicators){let e=document.createElement(`div`);e.className=`tcw-datawin-sub`,e.textContent=t.name,this.bodyEl.appendChild(e);for(let e of t.values)this.bodyEl.appendChild(this.row(e.key,e.text??no(e.value)))}}row(e,t,n=``){let r=document.createElement(`div`);r.className=`tcw-datawin-row`;let i=document.createElement(`span`);i.className=`tcw-datawin-label`,i.textContent=e;let a=document.createElement(`span`);return a.className=`tcw-datawin-value${n?` tcw-${n}`:``}`,a.textContent=t,r.appendChild(i),r.appendChild(a),r}};function no(e){if(!Number.isFinite(e))return`—`;let t=Math.abs(e);return t>=1e3?e.toFixed(2):t>=1?e.toFixed(4):e.toPrecision(4)}function ro(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 io=[[34,16,28,26,!1],[30,14,24,26,!0],[26,18,20,30,!0],[30,10,24,22,!1],[20,16,14,28,!0],[14,18,8,30,!0],[18,10,12,20,!1],[8,18,2,30,!0]],ao=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`),io.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)}},oo=4e3,so=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(),oo)):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}},co=`host:`;function lo(e,t){return[...e,...e.length>0&&t.length>0?[`separator`]:[],...t.map((e,t)=>({id:`${co}${t}`,label:e.label,icon:e.icon,danger:e.danger,checked:e.checked}))]}function uo(e,t){return e.startsWith(co)?(t[Number(e.slice(5))]?.onSelect(),!0):!1}var fo=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent),po={ctrl:`ctrl`,control:`ctrl`,cmd:`ctrl`,command:`ctrl`,meta:`ctrl`,mod:`ctrl`,alt:`alt`,option:`alt`,opt:`alt`,shift:`shift`},mo={esc:`escape`,space:` `,spacebar:` `,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`,del:`delete`,return:`enter`,plus:`+`};function ho(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=po[e.toLowerCase()];if(!t)return null;r[t]=!0}let i=n.toLowerCase();if(po[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=mo[i]??i,r.shift&&r.key.length===1)return null;return r.display=[...r.ctrl?[fo?`⌘`:`Ctrl`]:[],...r.alt?[`Alt`]:[],...r.shift?[`Shift`]:[],r.key===` `?`Space`:n.length===1?n.toUpperCase():n],r}function go(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 _o=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 vo(e){let t=`${e.ctrl?`ctrl+`:``}${e.alt?`alt+`:``}${e.shift?`shift+`:``}${e.char??e.key}`;return _o.has(t)}function yo(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 bo=[`#b552c9`,`#1398a8`,`#d4622b`,`#e25592`,`#6f7a8c`,`#3e9a4f`],xo=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:Ca(this.host.t),way:this.compareWay,compared:this.comparedNow(),onAdd:(e,t)=>{Sa(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 Da(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=bo[this.compares.length%bo.length];this.compares.length===0&&this.host.chart.setCompareMode(`percent`),this.host.chart.addCompareSymbol(n,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: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:t,interval:_e(n)}),`error`):this.sayCompareFailed(t,i),null)}}sayCompareFailed(e,t){this.host.say(`${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=wa(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=Ta(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)}},So=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?k():null,r=new an({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 qt(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`)}),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)||Kt())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()})}},Co=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 Tn(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=Ua(this.host.chart.getIndicatorOutput(r)?.series,null)?.[i];return typeof a==`number`&&Number.isFinite(a)?a:null}},wo=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 To(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 Eo=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(To({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=lo(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=>{uo(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(fi.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=lo(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=>{uo(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=pi(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()}},Do=2,Oo=2;function ko(e,t=`en-US`){return(0,u.formatPrice)(e,Math.max(Do,(0,d.indicatorValuePrecision)(e)),t)}function Ao(e,t=`en-US`){return`${U((0,u.formatPrice)(Math.abs(e),Oo,t),e,(0,u.formatPrice)(0,Oo,t))}%`}function jo(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:Mo(e,t)}:{values:[],offChartType:!0},pane:null}))}function Mo(e,t){return[...e.close===null?[]:[{text:ko(e.close,t),color:null}],...e.change===null?[]:[{text:Ao(e.change,t),color:null}]]}var No=7,Po=17,Fo=3;function Io(e){return!d.SYMBOL_INDICATOR_IDS.has(e.id)&&e.scale!==`left`}var Lo=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=jo(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=Ua(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?[]:Wa(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&&Io(e),a),color:n.color})),pane:t?{x:t.x+4,y:t.y+Math.min(No+t.row*Po,Math.max(No,t.height-Po)),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+Fo,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=lo(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=>{uo(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)}},Ro=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=yn();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:_e(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}}},zo=0,Bo=class{backdrop;search;listEl;layouts=[];confirming=null;returnFocus=null;loadSeq=0;uid=++zo;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,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()}}},Vo=5,Ho=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 $i(n,r),this.dialog=new Bo(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,Vo)}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()}},Uo=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Wo=globalThis.Buffer;function Go(e){if(Wo)return Wo.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 Ko(e){if(Wo)return Wo.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 qo(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Jo(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function Yo(e){return qo(Go(JSON.stringify(e)))}function Xo(e){if(!e)return null;try{let t=Ko(Jo(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:ra.find(e=>e===n.scaleMode)??`regular`,indicators:Array.isArray(n.indicators)?n.indicators:[],drawings:Array.isArray(n.drawings)?n.drawings:[],...Uo(n.settings)?{settings:L(n.settings,yr)}:{}}}catch{return null}}var Zo=`tcw`;function Qo(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)!==Zo))try{return decodeURIComponent(e.slice(t+1))}catch{return null}}return null}function $o(e,t){let[n]=e.split(`#`);return`${n}#${Zo}=${t}`}var es=[`legendVisible`,`volumeVisible`,`barCountdown`,`indicatorValueLabels`,`alignAxisLabels`],ts=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=Qo(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=Mr(n,{...t.h,...Object.fromEntries(es.map(e=>[e,this.host.settingsDefaults[e]]))});return Yo({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=Xo(e);if(!t)return!1;t.symbol&&t.symbol!==this.host.state.symbol&&await this.host.setSymbol(t.symbol),t.timeframe&&t.timeframe!==this.host.state.timeframe&&await this.host.setTimeframe(t.timeframe),t.chartType&&this.host.applyChartType(t.chartType);let{chartTypeOptions:n,...r}=this.host.allowedSettings({scaleMode:t.scaleMode,...L(t.settings,yr)}),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=$o(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?sa(t):null,r=n&&typeof n==`object`?aa(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:Ar(e,vr)}}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(aa(e.chart)));let t=e.chart.chartType;typeof t==`string`&&(this.host.state={...this.host.state,chartType:t})}let t=this.host.allowedSettings({scaleMode:e.scaleMode,invertScale:e.invertScale,...L(e.settings,vr)});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=oa(sa(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 Ho(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}=J(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}}},ns={alerts:`alerts`,objectTree:`objectTree`,dataWindow:`dataWindow`,symbolInfo:`symbolInfo`,depthLadder:`depthLadder`},rs={alerts:`alerts`,objectTree:`objects`,symbolInfo:`symbolInfo`,depthLadder:`trade`},is=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[ns[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)&&Io(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=rs[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||cr(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:e.symbol,color:e.color,way:e.way}));this.host.objectTree.setObjects(e,t,n)}},as=new Set([`timezone`,`numberLocale`,`chartTypeOptions`,`logScale`,`autoScale`]),os=80,ss=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function cs(e){return L(e,as)}function ls(e){let{overrides:n}=(0,u.readChartStyleOverrides)(e);return Object.fromEntries(Object.entries(n).filter(([e,n])=>n!==null&&t.l.includes(e)))}function us(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var ds=class{constructor(e=`tcw:chart-templates`,t=us()){this.key=e,this.storage=t}list(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`[]`)}catch{return[]}if(!Array.isArray(e))return[];let t=[];for(let n of e)!ss(n)||typeof n.name!=`string`||!n.name.trim()||t.push({name:n.name.slice(0,os).trim(),settings:cs(n.settings),style:ls(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,os).trim();if(!r||!this.storage)return!1;let i=[...this.list().filter(e=>e.name!==r),{name:r,settings:cs(t),style:ls(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{}}},fs=new Set([...gr,`autoScale`]),ps=class{constructor(e){this.host=e}chartTemplates=new ds;chartTemplatePrompt=null;settingsEdit=null;state=rt(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 $i(this.host.overlayHost(),this.host.t),this.chartTemplatePrompt.open({title:this.host.t(`settings.saveTemplateTitle`),submitLabel:this.host.t(`common.save`),placeholder:this.host.t(`settings.templatePlaceholder`),onSubmit:e=>{if(!this.chartTemplates.save(e,this.settingsState,this.settingsStyle().overrides))throw this.host.say(this.host.t(`templates.saveFailed`),`error`),Error(`The template could not be saved`);this.host.say(s.r(this.host.t(`templates.saved`),{name:e}))}})}getSettings(){return this.syncSettingsFromChart(),JSON.parse(JSON.stringify(this.settingsState))}setSettings(e){let t=this.allowedSettings(this.withoutEarlyFreeze(L(e)));this.claimSettings(Object.keys(t)),this.applySettings(t)}withoutEarlyFreeze(e){return e.autoScale!==!1||this.host.chart.getData().length>0?e:Object.fromEntries(Object.entries(e).filter(([e])=>e!==`autoScale`))}onSettingsChange(e){return this.settingsListeners.add(e),()=>{this.settingsListeners.delete(e)}}syncSettingsFromChart(){let e=this.host.chart,n=e.getTimeZone?.(),r=e.getMarketProfileConfig?.(),i=e.getPivotMarkersConfig?.(),a=this.allowedSettings(L({gridVisible:e.isGridVisible?.(),volumeVisible:e.isVolumeVisible?.(),legendVisible:e.isLegendVisible?.(),barCountdown:e.isBarCountdownVisible?.(),indicatorValueLabels:e.isIndicatorValueLabelsVisible?.(),alignAxisLabels:e.isAxisLabelsAligned?.(),leftPriceScale:e.isLeftPriceScaleVisible?.(),volumeProfileVisible:e.isVolumeProfileVisible?.(),marketProfileVisible:e.isMarketProfileVisible?.(),marketProfileSplit:r?.splitBySession,marketProfileLetters:r?.letters,marketProfileBuckets:r?.buckets,marketProfileOpacity:r?.opacity,depthHeatmapVisible:e.isDepthHeatmapVisible?.(),depthHeatmapOpacity:e.getDepthHeatmapConfig?.()?.opacity,pivotMarkersVisible:e.isPivotMarkersVisible?.(),pivotStrength:i?.left,pivotStructureLabels:i?.structureLabels,sessionShadingVisible:e.isSessionShadingVisible?.(),periodLevelsVisible:e.isPeriodLevelsVisible?.(),periodLevelsPeriod:e.getPeriodLevelsPeriod?.(),crosshairMode:e.getCrosshairMode?.(),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:Cr(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 it(()=>{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){at(()=>this.applySettingsNow(e,t))}applySettingsNow(e,n){this.settingsState={...this.settingsState,...e},Object.keys(e).some(e=>!fs.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({...wr(),...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())}},ms=13;function hs(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 gs=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=hs(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=B[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||ms,bold:a.bold===!0,italic:a.italic===!0,family:this.host.chart.getFont?.()?.family??this.host.ui.font.family},color:a.textColor??ni[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:B[r.type],textColor:ni[r.type],textPlace:ti.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 $i(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()}))}})}},_s=200,vs=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 je({dayShare:n.slice(-_s).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:_e(e),custom:this.host.customTimeframes.has(e)}))}handleAddTimeframe(e){if(!this.host.featureState.customTimeframes)return!1;let t=Te(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=Ee(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=Ee(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()}},ys=600,bs=24,xs=[`--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`],Ss=48,Cs=5e4,ws=100;function Ts(){return new Promise(e=>{if(typeof requestAnimationFrame!=`function`||document.hidden){setTimeout(e,0);return}let t=setTimeout(e,ws);requestAnimationFrame(()=>setTimeout(()=>{clearTimeout(t),e()},0))})}var Es=864e5,Ds=5e3,Os=2e3,ks=48,As=`rgba(255,255,255,0.03)`,js=`rgba(0,0,0,0.03)`,Ms=2;function Ns(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 Ps=1e3,Fs=[[`barCountdown`,`barCountdown`],[`logScale`,`logScale`],[`legendVisible`,`legend`],[`volumeVisible`,`volume`]],Is=t.l.filter(e=>u.CHART_STYLE_KEYS[e]!==`color`);function Ls(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 Rs=class{intervals=new vs(this.intervalsHost());drawingEdit=new gs(this.drawingEditHost());chartSettings=new ps(this.chartSettingsHost());docking=new is(this.dockingHost());layouts=new ts(this.layoutsHost());commands=new Ro(this.commandsHost());legend=new Lo(this.legendHost());menus=new Eo(this.menusHost());trading=new wo(this.tradingHost());alerting=new Co(this.alertingHost());watching=new So(this.watchingHost());comparing=new xo(this.comparingHost());chart;state;themeOf={dark:u.DARK_THEME,light:u.LIGHT_THEME};toolbar=null;openRoles=rt(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 na;templatePrompt=null;markerTip=null;dataWindow=null;lastHoverIndex=null;lastHoverBar=null;lastHoverPrevClose=null;legendHoverIndex=null;pointerOnChart=!1;favoritesStore=new la;indicatorFavorites=new la(`tcw:indicator-favorites`);indicatorDefaults=new pr;timeframeFavorites=new la(`tcw:tf-favorites`);customTimeframes=new la(`tcw:tf-custom`);timeframes=[];sessionRefPrice=null;symbolInfoPanel=null;news=new fn;marketTimer=null;clockTimer=null;onPageShown=null;chartNav=null;visibleBarCount=50;root;chartContainer;loading;historyPill;connectSeq=0;localSeq=0;lastLocalSwitchMs=0;destroyed=!1;scope=ot();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=Ls(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=Nr(e.persistSettings);o&&(this.chartSettings.settingsStore=new Fr(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(Fs.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=Ee(be(e.timeframes,d.timeframes),this.customTimeframes.list(),d.timeframes),!this.timeframes.some(e=>this.timeframeFavorites.has(e))){let t=xe(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){de(),this.root=document.createElement(`div`),this.root.className=`tcw-root`;let i=t.dir===`ltr`||t.dir===`rtl`?t.dir:qs(t.locale)?`rtl`:`ltr`;this.root.dir=i,this.portal.dir=i,e.appendChild(this.root),this.tooltip=new ja(this.root),this.portal.className=`tcw-root tcw-portal`,this.look=rt({dark:n,theme:r});let a=!1;this.scope.run(()=>it(()=>{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=ua([this.root,this.portal]),this.stopNarrow=da(this.root,e=>{this.toolbar?.fit(),e||this.sidebar?.closeOverlay(),this.docking.syncRail()}),this.ui=F(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 Ve(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(()=>it(()=>{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 _t(i,{drawingToolGroups:t.n(t._,this.t),favorites:this.favoritesStore.list(),shortcuts:yn()},{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 ao(this.chartContainer,this.t(`status.loading`)),this.historyPill=new so(this.chartContainer,{loading:this.t(`history.loading`),failed:this.t(`history.failed`)}),this.docking.dock=new ya(i,{labels:{rail:this.t(`dock.rail`),resize:this.t(`dock.resize`)},savedWidth:()=>Gs(),saveWidth:e=>Ks(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 wn(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 on(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=()=>{Kt()||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 Dt(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(()=>{!Kt()&&this.featureState.statusBar&&this.featureState[`statusBar.clock`]&&this.statusBar?.tick()},Ps),this.chart.on(`priceRangeChange`,()=>this.chartSettings.refreshScaleSwitches()),this.chartSettings.refreshScaleSwitches(),this.goToDatePart=this.lazyPart(q.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(q.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(q.symbolSearch,({WidgetSymbolSearch:e})=>new e({onPick:e=>{this.setSymbol(e)},onClose:()=>{}},this.overlayHost,this.t)),this.hotkeySheetPart=this.lazyPart(q.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 Va(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 Wt(this.replayHost()),this.replay.attach();for(let e of[`resize`,`dataUpdate`,`symbolInfoChange`])this.chart.on(e,()=>this.placeDrawingButton());this.placeDrawingButton(),this.dataWindow=new to(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 Br,t=new Vr;for(let[e,n]of Object.entries(t.all()))this.chart.setDrawingToolDefaults(e,n??null);this.drawingSettingsPart=this.lazyPart(q.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=>J(e*(0,u.barTimeUnit)(this.chart.getData()),this.displayTimezone()),fromWallTime:(e,t)=>{let n=ga(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 ui(this.overlayHost),this.chart.on(`drawingDoubleClick`,e=>{let t=e.payload.id,n=this.chart.getDrawings().find(e=>e.id===t)?.type;n&&B[n]&&this.drawingEdit.editTextInPlace(t,!1)||this.drawingEdit.openDrawingSettings(t,n&&B[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||!B[n])return;this.drawingEdit.cancelTextPrompt?.();let i=0,a=()=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,s),clearTimeout(i),this.drawingEdit.cancelTextPrompt=null},o=()=>{a(),!(this.destroyed||!this.chart.getDrawings().some(e=>e.id===t))&&(this.drawingEdit.editTextInPlace(t,!0)||this.drawingEdit.openDrawingSettings(t,{tab:`text`,justDrawn:!0}))},s=()=>setTimeout(o,0);window.addEventListener(`pointerup`,s),window.addEventListener(`pointercancel`,s),i=window.setTimeout(o,ys),this.drawingEdit.cancelTextPrompt=a}),this.drawingStyle=new Gr(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 $r(this.root,{onStyle:e=>{for(let t of this.chart.getSelectedDrawingIds()){let n=this.chart.getDrawings().find(e=>e.id===t)?.type,r=n?B[n]:void 0,i=e.fillColor!==void 0&&r&&!r.box?{...e,textBackground:!0}:e;this.chart.setSelectedDrawingStyle(i,t)}this.drawingEdit.updateSelectionToolbar()},onSettings:()=>{let e=this.chart.getSelectedDrawingIds()[0];e&&this.drawingEdit.openDrawingSettings(e)},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(xi(t,l,this.t),r.t,this.featureState),n,i,{area:t,price:c,time:o})}),this.chart.on(`priceAxisAdd`,e=>{if(!this.featureState[`menu.priceAxisAdd`])return;let{price:t,x:n,y:i}=e.payload,a=this.chart.roundPrice(t),o=r.a(hi(this.menus.chartMenuContext(a),this.t),r.t,this.featureState);this.menus.openChartMenu(o,n,i,{area:`priceAxisAdd`,price:a})}),this.chart.on(`signalMarkerHover`,e=>this.showMarkerTip(e.payload)),this.intervals.intervalInput=new ta(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 Ji(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 Pi(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}=J(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 Ja(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 Qa(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 Nn(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}=J(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 Ya(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(q.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(q.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 ar(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(q.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:()=>Hs(),add:e=>Us([e,...Hs().filter(t=>t!==e)])})),this.boundGlobalKeydown=e=>{if(this.handleHostHotkey(e)||this.featureState.hotkeys&&this.replay.isOpen()&&this.replay.handleReplayKey(e))return;let t=E(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||D()||!E(this.root,!0))return;e.preventDefault(),this.layouts.saveLayout()}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&vn[e.code]){if(e.defaultPrevented||D()||!t||O()||!n(`hotkeys.tools`))return;e.preventDefault(),this.handleDrawingTool(vn[e.code])}else if(/^[0-9]$/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(e.defaultPrevented||!this.intervals.intervalInput||!n(`intervalTyping`)||D()||O()||!E(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(Ns(e)!==null){if(e.defaultPrevented||!n(`symbolTyping`)||!this.featureState.symbolSearch||D()||O()||!E(this.root,!0))return;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t))return;e.preventDefault(),this.openSymbolSearch(Ns(e))}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&(e.code===`KeyI`||e.code===`KeyG`||e.code===`KeyR`)){if(D()||!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(D()||!t||!n(`hotkeys.help`)||!this.featureState.hotkeySheet)return;e.preventDefault(),this.openHotkeySheet()}},document.addEventListener(`keydown`,this.boundGlobalKeydown),document.addEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys=At(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||pa()},t=globalThis;if(t.requestIdleCallback&&t.cancelIdleCallback){let n=t.requestIdleCallback(e,{timeout:Ds}),r=t.cancelIdleCallback;this.stopPreload=()=>r(n)}else{let t=setTimeout(e,Os);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(Kt())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 dn({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=F(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?Vn(e):1}applyLookTokens(){let e=Hn(this.ui,this.uiScale);for(let t of[this.root,this.portal]){if(ir(t,e,{variables:this.uiVariables}),this.uiVariables)continue;let n=rr(e);for(let e of xs)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?Vn(t-bs):Vn(t+bs))===this.uiScale)return}this.uiScale=e,this.applyLookTokens(),this.applyLegendFont(),this.applyChartLook(),this.toolbar?.fit()}}getUI(){return F({...this.ui})}applyLegendFont(){this.chart.setLegend({fontFamily:this.ui.font.mono,fontSize:j(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,...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(),fe()}}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=ho(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;vo(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||D()||yo(e)||O())return!1;let t=this.hostHotkeys.find(t=>go(e,t.parsed));if(!t)return!1;let n=!t.parsed.ctrl&&!t.parsed.alt;if(!E(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(this.state.symbol.replace(`USDT`,` / USDT`),{fontSize:ks,color:this.state.isDark?As:js})}keepingLook(e){this.chartSettings.settingsEdit&&this.settings?.close();let t=this.chart.getOverrides?.({layer:`user`})??{},n=Object.fromEntries(Is.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=>He(n,t,e.toggle===!0),setText:t=>void Ue(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(lo([],i),a,e=>uo(e,i))}});return r.setAttribute(`aria-haspopup`,`menu`),r.setAttribute(`aria-expanded`,`false`),t.tidy(),{element:r,setText:t=>void Ue(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=>He(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}=J(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=>J(e*r,n),a=t[t.length-1].time,o=this.chart.getVisibleTimeRange()??{from:t[0].time,to:a},s=J(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)>=Es),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=ga(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=ga(e.from.date,e.from.time,n),a=ga(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}=J(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 $i(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>=Ss||this.baseSeries.length>=Cs;try{if(t&&(this.loading.begin(this.chart.getData().length>0,!0),await Ts(),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={...Sr(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:zs(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()),Ms))}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):qa(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 fa(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 zs(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 Bs=`tcw:recentCommands`,Vs=10;function Hs(){try{let e=JSON.parse(k()?.getItem(Bs)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`).slice(0,Vs):[]}catch{return[]}}function Us(e){try{k()?.setItem(Bs,JSON.stringify(e.slice(0,Vs)))}catch{}}var Ws=`tcw:dockWidth`;function Gs(){try{let e=Number(k()?.getItem(Ws)??NaN);return Number.isFinite(e)&&e>0?e:null}catch{return null}}function Ks(e){try{k()?.setItem(Ws,String(e))}catch{}}function qs(e){return!!e&&/^(ar|he|iw|fa|ur|ps|yi|dv|ckb|sd|ug)(-|$)/i.test(e)}var Js={symbol:!1,interval:!1,crosshair:!0,time:!1,drawings:!1,replay:!1},Ys=[`symbol`,`interval`,`crosshair`,`time`,`drawings`,`replay`],$={"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 Xs(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call($,e)}function Zs(e){return JSON.parse(JSON.stringify(e))}function Qs(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 $s(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||t.kind!==`grid`||!Xs(t.layout)||!Array.isArray(t.cells))return null;let n=t.cells.map(oa);if(n.some(e=>e===null))return null;let r=typeof t.sync==`object`&&t.sync!==null?t.sync:{},i={...Js};for(let e of Ys)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 ec=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||D()||!E(this.root,!0)||(e.preventDefault(),this.layoutsUI.save())};constructor(e,t={}){this.options=t,this.layout=Xs(t.layout)?t.layout:`1x2`,this.sync={...Js,...t.sync},this.t=s.n(s.o(t.widget?.locale,t.widget?.messages)),de(),this.root=document.createElement(`div`),this.root.className=`tcw-root tcw-grid`,this.root.dataset.tcwTheme=t.widget?.theme===`light`?`light`:`dark`,ir(this.root,F(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=da(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=At(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||!Xs(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=F(e);ir(this.root,t);for(let e of this.cells)e.widget.setUI(t);this.uiTheme=t}getUI(){return F(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=$s(sa(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(),fe()}}shapeCount(){let{cols:e,rows:t}=$[this.layout];return e*t}applyShape(){let{cols:e,rows:t}=$[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 Rs(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:`${Nr(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=tc(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(Zs(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(Zs(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=>`${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(Xs)??Object.keys($);for(let e of n){let{cols:n,rows:r}=$[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=Qs(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 Ys){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 Ho(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=J(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 tc(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=Rs,exports.ChartWidgetGrid=ec,exports.DEFAULT_GRID_SYNC=Js,Object.defineProperty(exports,`DRAWING_TOOL_ICONS`,{enumerable:!0,get:function(){return u.DRAWING_TOOL_ICONS}}),exports.EN_MESSAGES=s.c,exports.GRID_SHAPES=$,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=Zn,exports.applyWidgetUI=ir,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=$s,exports.readWatchlists=nn,exports.readWidgetLayout=oa,exports.registerWidgetLocale=s.a,exports.resolveWidgetUI=F,exports.widgetUIVariables=rr;
7734
7800
  //# sourceMappingURL=index.cjs.map