(self.webpackChunktradingview=self.webpackChunktradingview||[]).push([[48108],{254355:e=>{e.exports={screen:"screen-otjoFNF2",fade:"fade-otjoFNF2",screenfade:"screenfade-otjoFNF2"}},784516:e=>{e.exports={}},460682:e=>{e.exports={css_value_currency_label_radius:"4",css_wrapper_margin:"4",css_row_left_right_padding:"3",css_fade_height:"10","price-axis-currency-label-wrapper":"price-axis-currency-label-wrapper-y5H41VPj",hidden:"hidden-y5H41VPj","price-axis-currency-label":"price-axis-currency-label-y5H41VPj",row:"row-y5H41VPj",expanded:"expanded-y5H41VPj","price-axis-currency-label-arrow-down":"price-axis-currency-label-arrow-down-y5H41VPj","price-axis-currency-label-text":"price-axis-currency-label-text-y5H41VPj"}},647184:e=>{e.exports={}},100658:e=>{e.exports={}},877825:e=>{e.exports={"css-value-chart-controls-bar-height-with-border":"39px","css-value-chart-controls-bar-border":"1px"}},237218:e=>{e.exports={}},100366:(e,t,i)=>{"use strict";async function s(){return(await Promise.all([i.e(85866),i.e(50690),i.e(20139)]).then(i.bind(i,254543))).ErrorCardRenderer}i.d(t,{getErrorCardRenderer:()=>s})},113610:(e,t,i)=>{"use strict";i.d(t,{getChartStorage:()=>m});var s=i(120780),o=i(895370),r=i(175203),n=i(652171),a=i(198303),l=i(266325),c=i(474759);function h(){const e=document.querySelector('link[rel~="chart-storage"]'),t=new URL((null==e?void 0:e.href)||"/charts-storage/",location.href);return t.pathname.endsWith("/")||(t.pathname+="/"),t}function d(e){const{charts:t={},countSourcesTotal:i=0,limitBytesTotal:s=0,sizeBytesTotal:o=0}=e,r=new Map;for(const e in t){const i=t[e].symbols,s=new Map;for(const e in i||{}){const t=i[e];s.set(e,{countSources:t.countSources,sizeBytes:t.sizeBytes,ids:t.ids})}r.set(e,s)}return{charts:r,countSourcesTotal:i,limitBytesTotal:s,sizeBytesTotal:o}}const u={sources:new Map,groups:new Map};class _{constructor(){this._lastSaveRequest=Promise.resolve(),this._requestsCounter=0,this._lastSharedToolsLoadingRequest=Promise.resolve(u)}async saveLineToolsAndGroups(e,t,i,d,u){if(""===e||void 0===e)return Promise.reject("Unnamed chart cannot be saved");const _=`${e}.${t}.${this._requestsCounter++}`,p=`ChartStorage.Save.TotallyProcessing.${_}`,m=(0,o.perfMeasureOperation)(p,(()=>this._lastSaveRequest.then((async()=>{if(null==u?void 0:u.aborted)throw(0,l.createAbortError)();const p=`ChartStorage.Save.GettingToken.${_}`,m=await(0,o.perfMeasureOperation)(p,(()=>(0,n.getStorageTarget)(e,t,d,u))),g=new URL(m.path,h());m.chartId&&g.searchParams.append("chart_id",m.chartId),g.searchParams.append("jwt",m.token);const S=(0,c.stringifyLineToolsAndGroupsDTO)(i),v=`ChartStorage.Save.GettingResponse.${_}`;return(0,o.perfMeasureOperation)(v,(()=>(0,s.fetch)(g.toString(),{signal:u,method:"PUT",headers:{"Content-Type":"application/json","X-BUILD-TIME":window.BUILD_TIME},credentials:"include",body:S}).then((e=>{if(!e.ok){const t=429===e.status;throw new a.SavingLineToolsError(t,`Response status is not success: ${e.status}`)}const t=e.json();return r.telemetry.sendLineToolsStorageReport("line_tools_save_success"),t })).then((s=>({content:s,savedDto:i,layoutId:e,chartId:t,sharingMode:d})))))}))));return this._lastSaveRequest=m.catch((e=>{r.telemetry.sendLineToolsStorageReport("line_tools_save_error")})),m}async loadLineToolsAndGroups(e,t,i){if(""===e||void 0===e)return u;const a=`${e}.${t}.${i.requestType}.${this._requestsCounter++}`,l=`ChartStorage.Load.GettingToken.${a}`,d=await(0,o.perfMeasureOperation)(l,(()=>(0,n.getStorageTarget)(e,t,i.sharingMode))),_=`get/${d.path}`,p=new URL(_,h());switch(d.chartId&&p.searchParams.append("chart_id",d.chartId),window.user.is_superuser&&2===i.sharingMode&&p.searchParams.append("layout_id",e),p.searchParams.append("jwt",d.token),i.requestType){case"mainSeriesLineTools":p.searchParams.append("symbol",i.symbol),0===i.sharingMode&&p.searchParams.append("includeOwnerSource",i.seriesSourceId),p.searchParams.append("brokerName",i.brokerName);break;case"studiesLineTools":p.searchParams.append("excludeOwnerSource",i.seriesSourceId);break;case"lineToolsWithoutSymbol":p.searchParams.append("symbol",""),0===i.sharingMode&&p.searchParams.append("includeOwnerSource",i.seriesSourceId)}const m=`ChartStorage.Load.GettingResponse.${a}`,g=()=>(0,s.fetch)(p.toString(),{method:"GET",credentials:"include"}).then((e=>{if(!e.ok)throw new Error("Response status is not success");const t=e.headers.get("X-Request-Id");return e.json().then((e=>{if(null===e)throw new Error("Body is null");if(!e.success)throw new Error("Response is not success");const i=(0,c.parseLineToolsAndGroupsDTO)(e.payload||{},t);return r.telemetry.sendLineToolsStorageReport("line_tools_load_success"),i}))})),S=0===i.sharingMode?g:()=>this._lastSharedToolsLoadingRequest.then(g),v=(0,o.perfMeasureOperation)(m,S).catch((e=>{throw r.telemetry.sendLineToolsStorageReport("line_tools_load_error"),e}));return 0!==i.sharingMode&&(this._lastSharedToolsLoadingRequest=v.catch((()=>u))),v}async removeLineTools(e,t,i,a){if(""===e||void 0===e)return!1;const l=`${e}.${t}.${this._requestsCounter++}`,c=`ChartStorage.Remove.GettingToken.${l}`,d=await(0,o.perfMeasureOperation)(c,(()=>(0,n.getStorageTarget)(e,t,i))),u=new URL(d.path,h());d.chartId&&u.searchParams.append("chart_id",d.chartId),u.searchParams.append("jwt",d.token),u.searchParams.append("symbol",a);const _=`ChartStorage.Remove.GettingResponse.${l}`;return(0,o.perfMeasureOperation)(_,(()=>(0,s.fetch)(u.toString(),{method:"DELETE",credentials:"include"}).then((e=>{if(!e.ok)throw new Error("Response status is not success");return e.json().then((e=>{if(null===e)throw new Error("Body is null");if(!e.success)throw new Error("Response is not success");return r.telemetry.sendLineToolsStorageReport("line_tools_remove_by_symbol_success"),!0}))})))).catch((e=>{throw r.telemetry.sendLineToolsStorageReport("line_tools_remove_by_symbol_error"),e}))}async getLayoutDrawingsSizeInfo(e,t){if(""===e||void 0===e)return{charts:new Map,countSourcesTotal:0,limitBytesTotal:0,sizeBytesTotal:0};const i=`${e}.${t}.${this._requestsCounter++}`,s=`ChartStorage.GetSizes.GettingToken.${i}`,a=await(0,o.perfMeasureOperation)(s,(()=>(0, n.getStorageTarget)(e,t,0))),l=new URL(`layout/${e}/sizes`,h());return l.searchParams.append("jwt",a.token),this._fetchData(`ChartStorage.GetSizes.GettingResponse.${i}`,l,{method:"GET",credentials:"include"}).then((e=>(r.telemetry.sendLineToolsStorageReport("line_tools_size_info_success"),d(e||{})))).catch((e=>{throw r.telemetry.sendLineToolsStorageReport("line_tools_size_info_error"),e}))}async getUserGlobalDrawingsSizeInfo(e){if(""===e||void 0===e)return{charts:new Map,countSourcesTotal:0,limitBytesTotal:0,sizeBytesTotal:0};const t=this._requestsCounter++,i=await(0,o.perfMeasureOperation)(`ChartStorage.GetGlobalSizes.GettingToken.${t}`,(()=>(0,n.getStorageTarget)(e,"",2))),s=new URL("user/sizes",h());return s.searchParams.append("jwt",i.token),this._fetchData(`ChartStorage.GetGlobalSizes.GettingResponse.${t}`,s,{credentials:"include"}).then((e=>(r.telemetry.sendLineToolsStorageReport("global_line_tools_size_info_success"),d(e||{})))).catch((e=>{throw r.telemetry.sendLineToolsStorageReport("global_line_tools_size_info_error"),e}))}async _fetchData(e,t,i){const r=await(0,o.perfMeasureOperation)(e,(()=>(0,s.fetch)(t.toString(),i)));if(!r.ok)throw new Error("Response status is not success");const n=await r.json();if(null===n)throw new Error("Body is null");if(!n.success)throw new Error("Response is not success");return n.payload}}let p=null;async function m(){return null===p&&(p=new _),p}},474759:(e,t,i)=>{"use strict";function s(e){const t={};return e.sources&&(t.sources={},e.sources.forEach(((e,i)=>{t.sources[i]=e}))),t.drawing_groups={},e.groups.forEach(((e,i)=>{t.drawing_groups[i]=e})),t.clientId=e.clientId,JSON.stringify(t)}function o(e,t){const i={sources:null,groups:new Map};if(null!==e.sources){i.sources=new Map;for(const t in e.sources||{}){const s=e.sources[t];i.sources.set(t,s)}}for(const t in e.drawing_groups||{}){const s=e.drawing_groups[t];i.groups.set(t,s)}return null!==t&&(i.serverRequestId=t),i.clientId=e.clientId,i.symbol=e.symbol,i}i.d(t,{parseLineToolsAndGroupsDTO:()=>o,stringifyLineToolsAndGroupsDTO:()=>s})},198303:(e,t,i)=>{"use strict";i.d(t,{SavingLineToolsError:()=>s});class s extends Error{constructor(e,t){super(t),this.shouldBeCooled=e}}Error},652171:(e,t,i)=>{"use strict";i.d(t,{getStorageTarget:()=>a,globallySharedChartId:()=>n,sharedChartId:()=>r});var s=i(175203),o=i(266325);const r="_shared",n="UserSync";async function a(e,t,i,n){try{const a=new URL("/chart-token/",location.href);a.searchParams.append("image_url",e);const l=window.user.id||-1;a.searchParams.append("user_id",""+l);const c=await fetch(a.toString(),{signal:n});if(!c.ok)throw new Error(`Http response is not ok: ${c.status}}`);const h=await c.json();if(s.telemetry.sendLineToolsStorageReport("line_tools_token_request_success"),null==n?void 0:n.aborted)throw(0,o.createAbortError)();let d=t;return 2===i?d=void 0:1===i&&(d=r),{token:h.token,chartId:d,path:2===i?"user/sources":`layout/${e}/sources`}}catch(e){throw(0,o.isAbortError)(e)||s.telemetry.sendLineToolsStorageReport("line_tools_token_request_error"),e}}},709404:(e,t,i)=>{ "use strict";i.d(t,{getExchanges:()=>o});var s=i(279274);function o(){return s}},456335:(e,t,i)=>{"use strict";i.d(t,{featureCheck:()=>n});var s=i(778016),o=i(833813);function r(e,t,i){return t.value||(0,s.enabled)(e,i)}function n(e,t,i){switch(e){case o.ProductFeatures.SCREENER_INTERVALS:return function(e,t){const i=(0,s.getConfig)(o.ProductFeatures.SCREENER_INTERVALS,t);return!(!i||!i.interval)&&i.interval.includes(e.interval)}(t,i);case o.ProductFeatures.SCREENER_AUTO_REFRESH:return r(o.ProductFeatures.SCREENER_AUTO_REFRESH,t,i);case o.ProductFeatures.ALERTS_NO_EXPIRATION:return r(o.ProductFeatures.ALERTS_NO_EXPIRATION,t,i);default:return(0,s.enabled)(e,i)}}},31214:(e,t,i)=>{"use strict";i.d(t,{reloginOrGoPro:()=>c,runOrGoPro:()=>l,runOrGoProWithoutSync:()=>a});var s=i(526225),o=i(960337),r=i(456335),n=i(781666);function a(e,t,i,s){(0,r.featureCheck)(t,s)?e():(0,o.createGoProDialog)({...i,runOrGoproWithFeatureCheckOptions:{featureCheck:()=>(0,r.featureCheck)(t,s),signInSuccess:e}})}async function l(e,t,i,o={}){const r=window.is_authenticated;window.is_authenticated&&window.user.is_pro&&await(0,s.syncUserData)("gopro"),r===window.is_authenticated?a(e,t,i,o):(0,n.showSignModal)({source:i.goproSource,feature:i.feature,signinSuccess:e})}async function c(e){const t=window.is_authenticated;window.is_authenticated&&window.user.is_pro&&await(0,s.syncUserData)("gopro"),t===window.is_authenticated?(0,o.createGoProDialog)(e):(0,n.showSignModal)({source:e.goproSource,feature:e.feature})}},515312:(e,t,i)=>{"use strict";i.d(t,{isNativeUIInteraction:()=>s.isNativeUIInteraction,isTextEditingField:()=>s.isTextEditingField});var s=i(607423)},895370:(e,t,i)=>{"use strict";i.d(t,{addPerfMark:()=>c,perfMeasureOperation:()=>h});var s=i(541558);function o(){}const r=console.timeStamp?console.timeStamp.bind(console):o,n=window.performance&&performance.mark?performance.mark.bind(performance):o,a=window.performance&&performance.measure?performance.measure.bind(performance):o,l=window.performance&&performance.clearMarks?performance.clearMarks.bind(performance):o;function c(e){r(e),n(e)}async function h(e,t){const i=`measure-${e}-${(0,s.randomHash)()}`;n(i);try{return await t()}finally{a(e,i),l(i)}}},963568:(e,t,i)=>{"use strict";i.d(t,{retries:()=>r,retriesWithDelays:()=>n});var s=i(266325);async function o(e,t,i){let s;for(let o=0;oPromise.resolve()))}async function n(e,t){return o(e,t.length+1,(e=>e{"use strict";i.d(t,{showThemeAction:()=>n,showThemeSwitcher:()=>r});var s=i(638456),o=i(347402);function r(){return!(0,s.isDesktopApp)()||(0,o.desktopVersionIsLess)("1.0.10")}function n(){return(0,s.isDesktopApp)()&&!(0,o.desktopVersionIsLess)("1.0.11")}},247001:(e,t,i)=>{"use strict";i.d(t,{trackStudies:()=>r});var s=i(776734),o=i(526075);function r(e,t){ const i=e.metaInfo(),r=!e.isPine()||e.isStandardPine()?i.description:i.scriptIdPart,n=i.productId,a=o.StudyMetaInfo.isScriptStrategy(i),l=window.user&&window.user.pro_plan||"";(0,s.getTracker)().then((e=>{e&&e.trackStudiesAnalytics(r,n,t,a,l)}))}},484400:(e,t,i)=>{"use strict";i.d(t,{DEFAULT_THEME:()=>s});const s="light"},514811:(e,t,i)=>{"use strict";i.d(t,{themes:()=>l});var s=i(86746),o=i(444372) ;const r=JSON.parse('{"color-header-bg":"color-black","color-body-bg":"color-black","color-body-secondary-bg":"color-cold-gray-900","color-bg-primary":"color-cold-gray-850","color-bg-primary-hover":"color-cold-gray-800","color-bg-secondary":"color-cold-gray-900","color-bg-highlight":"color-cold-gray-900","color-bg-scroll-buttons":"color-cold-gray-800","color-legacy-bg-scroll-buttons":"color-cold-gray-550","color-legacy-bg-widget":"color-cold-gray-900","color-text-primary":"color-cold-gray-200","color-text-secondary":"color-cold-gray-450","color-text-tertiary":"color-cold-gray-400","color-text-disabled":"color-cold-gray-650","color-accent-content":"color-white","color-divider":"color-cold-gray-700","color-divider-hover":"color-cold-gray-800","color-divider-secondary":"color-cold-gray-800","color-box-shadow":"color-cold-gray-900","color-active-hover-text":"color-cold-gray-200","color-alert-text":"color-cold-gray-200","color-border":"color-cold-gray-750","color-border-chat-fields":"color-cold-gray-750","color-border-hover":"color-cold-gray-650","color-border-table":"color-cold-gray-800","color-brand":"color-tv-blue-500","color-brand-hover":"color-tv-blue-600","color-brand-active":"color-tv-blue-700","color-button-hover-bg":"color-cold-gray-850","color-chart-page-bg":"color-cold-gray-800","color-common-tooltip-bg":"color-cold-gray-750","color-danger":"color-ripe-red-600","color-danger-hover":"color-ripe-red-500","color-danger-active":"color-ripe-red-400","color-depthrenderer-fill-style":"color-cold-gray-150","color-depthrenderer-stroke-style":"color-cold-gray-650","color-disabled-border-and-color":"color-cold-gray-800","color-disabled-input":"color-cold-gray-750","color-empty-container-message":"color-cold-gray-450","color-halal":"color-iguana-green-400","color-continuous":"color-cold-gray-500","color-highlight-new":"color-tv-blue-a800","color-icons":"color-cold-gray-450","color-input-bg":"color-cold-gray-800","color-input-textarea-readonly":"color-cold-gray-650","color-input-placeholder-text":"color-cold-gray-700","color-input-publish-bg":"color-cold-gray-900","color-item-active-blue":"color-tv-blue-a900","color-item-hover-active-bg":"color-cold-gray-800","color-item-hover-bg":"color-cold-gray-800","color-item-hover-blue":"color-tv-blue-a800","color-item-selected-blue":"color-tv-blue-a800","color-item-active-text":"color-cold-gray-200","color-item-active-bg":"color-tv-blue-500","color-link":"color-tv-blue-500","color-link-hover":"color-tv-blue-600","color-link-active":"color-tv-blue-700","color-list-item":"color-cold-gray-450","color-list-nth-child-bg":"color-cold-gray-850","color-news-highlight":"color-cold-gray-800","color-pane-bg":"color-cold-gray-900","color-pane-secondary-bg":"color-cold-gray-850","color-placeholder":"color-cold-gray-650","color-popup-menu-item-hover-bg":"color-cold-gray-800","color-popup-menu-separator":"color-cold-gray-700","color-primary-symbol":"color-sky-blue-500","color-row-hover-active-bg":"color-cold-gray-800","color-sb-scrollbar-body-bg":"color-cold-gray-650","color-screener-description":"color-cold-gray-200","color-section-separator-border":"color-cold-gray-750","color-search-button-hover":"color-cold-gray-700","color-separator-table-chat":"color-cold-gray-750","color-success":"color-minty-green-700","color-success-hover":"color-minty-green-600","color-success-active":"color-minty-green-500","color-tag-active-bg":"color-cold-gray-750","color-tag-hover-bg":"color-cold-gray-800","color-text-regular":"color-cold-gray-200","color-toolbar-button-text":"color-cold-gray-200","color-toolbar-button-text-hover":"color-cold-gray-200","color-toolbar-button-text-active":"color-tv-blue-500","color-toolbar-button-text-active-hover":"color-tv-blue-600","color-toolbar-button-background-hover":"color-cold-gray-800","color-toolbar-button-background-secondary-hover":"color-cold-gray-750","color-toolbar-button-background-active":"color-tv-blue-a900","color-toolbar-button-background-active-hover":"color-tv-blue-a800","color-toolbar-toggle-button-background-active":"color-tv-blue-500","color-toolbar-toggle-button-background-active-hover":"color-tv-blue-600","color-toolbar-toggle-button-icon":"color-cold-gray-650","color-toolbar-interactive-element-text-normal":"color-cold-gray-200","color-toolbar-opened-element-bg":"color-cold-gray-800","color-toolbar-divider-background":"color-cold-gray-700","color-popup-background":"color-cold-gray-850","color-popup-element-text":"color-cold-gray-200","color-popup-element-text-hover":"color-cold-gray-250","color-popup-element-background-hover":"color-cold-gray-800","color-popup-element-secondary-text":"color-cold-gray-500","color-popup-element-hint-text":"color-cold-gray-600","color-popup-element-text-active":"color-cold-gray-200","color-popup-element-background-active":"color-tv-blue-500","color-popup-element-toolbox-text":"color-cold-gray-500","color-popup-element-toolbox-text-hover":"color-cold-gray-200","color-popup-element-toolbox-text-active-hover":"color-tv-blue-200","color-popup-element-toolbox-background-hover":"color-cold-gray-750","color-popup-element-toolbox-background-active-hover":"color-tv-blue-700","color-tooltip-bg":"color-cold-gray-750","color-tv-button-checked":"color-cold-gray-450","color-tv-dialog-caption":"color-cold-gray-50","color-tv-dropdown-item-hover-bg":"color-cold-gray-800","color-underlined-text":"color-cold-gray-450","color-widget-pages-bg":"color-cold-gray-900","color-warning":"color-tan-orange-700","color-forex-icon":"color-white","color-list-item-active-bg":"color-tv-blue-500","color-list-item-hover-bg":"color-cold-gray-800","color-list-item-text":"color-cold-gray-200","color-price-axis-label-back":"color-cold-gray-800","color-price-axis-label-text":"color-cold-gray-500","color-price-axis-gear":"color-cold-gray-200","color-price-axis-gear-hover":"color-cold-gray-400","color-price-axis-highlight":"color-cold-gray-800","color-bid":"color-tv-blue-500","color-scroll-bg":"color-cold-gray-750","color-scroll-border":"color-cold-gray-850","color-widget-border":"color-cold-gray-800","color-scroll-buttons-arrow":"color-white","color-control-intent-default":"color-cold-gray-650","color-control-intent-success":"color-minty-green-500","color-control-intent-primary":"color-tv-blue-500","color-control-intent-warning":"color-tan-orange-500","color-control-intent-danger":"color-ripe-red-500","color-growing":"color-minty-green-500","color-falling":"color-ripe-red-500","color-goto-label-background":"color-cold-gray-650","color-pre-market":"color-tan-orange-600","color-pre-market-bg":"color-tan-orange-400","color-post-market":"color-tv-blue-500","color-post-market-bg":"color-tv-blue-400","color-market-open":"color-minty-green-500","color-market-open-bg":"color-minty-green-400","color-market-closed":"color-cold-gray-400","color-market-holiday":"color-cold-gray-400","color-market-expired":"color-ripe-red-500","color-invalid-symbol":"color-ripe-red-400","color-invalid-symbol-hover":"color-ripe-red-500","color-delisted-symbol":"color-ripe-red-600","color-delisted-symbol-hover":"color-ripe-red-800","color-replay-mode":"color-tv-blue-500","color-replay-mode-point-select":"color-cold-gray-250","color-replay-mode-icon":"color-tv-blue-50","color-replay-mode-hover":"color-tv-blue-600","color-notaccurate-mode":"color-berry-pink-600","color-delay-mode":"color-tan-orange-700","color-delay-mode-bg":"color-tan-orange-400","color-eod-mode":"color-grapes-purple-700","color-eod-mode-bg":"color-grapes-purple-400","color-data-problem":"color-ripe-red-600","color-data-problem-bg":"color-ripe-red-400","color-data-problem-hover":"color-ripe-red-500","color-list-item-bg-highlighted":"color-tv-blue-a900","color-list-item-bg-selected":"color-tv-blue-a800","color-list-item-bg-highlighted-hover":"color-tv-blue-a800","color-list-item-bg-selected-hover":"color-tv-blue-a700","color-screener-header-bg":"color-cold-gray-850","color-screener-header-bg-hover":"color-cold-gray-800","color-overlay":"color-cold-gray-950","color-boost-button-content-selected":"color-tv-blue-100","color-boost-button-content-hover":"color-white","color-boost-button-bg-hover":"color-cold-gray-750","color-boost-button-border-hover":"color-cold-gray-750","color-boost-button-border-default":"color-cold-gray-700","color-x-twitter-content":"color-white","color-card-border":"color-cold-gray-700","color-card-border-hover":"color-cold-gray-600","color-background-special-primary":"color-black","color-stroke-special-primary":"color-cold-gray-800","color-selection-bg":"color-tv-blue-a700","color-default-gray":"color-cold-gray-450","color-featured-broker-badge-bg":"color-white","color-featured-broker-badge-bg-hover":"color-cold-gray-100","color-featured-broker-badge-text":"color-cold-gray-900"}'),n=JSON.parse('{"color-toolbar-button-text-active":"color-seeking-alpha-brand"}') ;var a=i(790188);const l={[s.StdTheme.Light]:{name:s.StdTheme.Light,label:()=>o.t(null,{context:"colorThemeName"},i(669841)),order:2,getThemedColor:e=>(0,a.getHexColorByName)(e)},[s.StdTheme.Dark]:{name:s.StdTheme.Dark,label:()=>o.t(null,{context:"colorThemeName"},i(14642)),order:1,getThemedColor:e=>{const t=r[e]||e;return(0,a.getHexColorByName)(t)}}};l.sa={isPrivate:!0,noChartTheme:!0,name:"sa",getThemedColor:e=>{const t=n[e]||e;return(0,a.getHexColorByName)(t)}}},787703:(e,t,i)=>{"use strict";i.r(t),i.d(t,{isThemeExist:()=>h,loadTheme:()=>n,loadThemes:()=>a,removeTheme:()=>c,saveTheme:()=>l});var s=i(120780);const o=(0,i(201089).getLogger)("Themes.Provider");let r=null;function n(e){return(0,s.fetch)("/theme/?themeName="+encodeURIComponent(e),{credentials:"include",method:"GET"}).then((e=>e.json())).then((e=>{const t={};return e.content&&(t.content=JSON.parse(e.content)),t}))}function a(){return r||(0,s.fetch)("/themes/",{credentials:"include",method:"GET"}).then((e=>(r=e.json(),r)))}function l(e,t){const i=new FormData;return i.append("content",JSON.stringify(t)),i.append("name",e),r=null,(0,s.fetch)("/save-theme/",{credentials:"include",method:"POST",body:i}).then((e=>e.json()),(e=>o.logError(e)))}function c(e){const t=new FormData;return t.append("name",e),r=null,(0,s.fetch)("/remove-theme/",{credentials:"include",method:"POST",body:t}).then((e=>e.json()),(e=>o.logError(e)))}function h(e){return n(e).then((e=>Boolean(e.content)))}},278855:(e,t,i)=>{"use strict";function s(){return/(?:^|;)\s*theme=(dark|light)(?:;|$)|$/.exec(document.cookie)[1]}function o(e){const t=function(){const e=location.hostname.split(".").filter(Boolean);return e.every(isFinite)?location.host:e.slice(-2).join(".")}(),i=void 0===e?-1:3e8;document.cookie=`theme=${e};path=/;domain=${t};max-age=${i}`}i.d(t,{getThemeFromCookie:()=>s,setThemeToCookie:()=>o})},560420:(e,t,i)=>{"use strict";i.d(t,{activateKeyPressHandler:()=>u,showDialog:()=>_});var s=i(449628),o=i(826531),r=i(244842),n=i(230296),a=i(868683),l=i(34831),c=i(345848);let h=null;function d(e){if(!(0,o.globalKeypressMatches)(e))return!1;e.preventDefault();const t=String.fromCharCode(e.charCode);return r.enabled("show_interval_dialog_on_key_press")&&function(e){return/[1-9]/.test(e)}(t)?(0,n.showChangeIntervalDialogAsync)({initVal:t}):r.enabled("symbol_search_hot_key")&&(_({defaultValue:t,selectSearchOnInit:!1,source:"keyboard",trackResultsOptions:{trackResults:!r.enabled("widget"),emptySearchType:"empty_result__supercharts"}}),(0,c.trackEvent)("GUI","SS","hotkey")),!0}function u(){(0,a.loadChangeIntervalDialog)(),s.pushBackListener("symbolEdit",d)}function _(e){const t=h=(0,l.loadNewSymbolSearch)().then((i=>{t===h&&i.showDefaultSearchDialog(e)}));return t}},711496:(e,t,i)=>{"use strict";i.d(t,{hasFinancialsByAvailabilityFlags:()=>h,hasFinancialsByTypespecs:()=>c});var s=i(519073);const o=new Set(["stock","dr","right","warrant","structured","bond"]),r=new Set(["mutual","unit","trust","reit","closedend","etn"]),n=new Set(["etn"]),a=new Set(["convertible","corporate"]),l=new Set(["cfd"]) ;function c(e,t){return!(e&&t&&(0,s.isEtf)(e,t))&&("structured"===e&&(null==t?void 0:t.length)?t.filter((e=>n.has(e))).length>0:"fund"===e&&(null==t?void 0:t.length)?t.filter((e=>r.has(e))).length>0:"bond"===e&&(null==t?void 0:t.length)?t.filter((e=>a.has(e))).length>0:"stock"===e&&(null==t?void 0:t.length)?0===t.filter((e=>l.has(e))).length:Boolean(e&&o.has(e)))}function h(e,t,i){if(t&&i&&(0,s.isEtf)(t,i))return!1;const{dividendsAvailability:o,earningsAvailability:r,financialsAvailability:n}=e;return 1===n||1===o||1===r}},2606:(e,t,i)=>{"use strict";i.d(t,{isDetailsReady:()=>s});const s=new(i(401580).WatchedValue)(!1)},396231:(e,t,i)=>{"use strict";i.d(t,{createSymbolNote:()=>S,showMindsPage:()=>g,showSymbolIdeas:()=>m,showSymbolNews:()=>p,showSymbolNotes:()=>_});var s=i(2606),o=i(421219),r=i(777453),n=i(731380),a=i(442731),l=i(881607),c=i(544855),h=i(515828);let d=null;function u(e,t){if(d&&s.isDetailsReady.unsubscribe(d),d=()=>{var i,s,o;(null===(o=null===(s=null===(i=null===window||void 0===window?void 0:window.widgetbar)||void 0===i?void 0:i.layout)||void 0===s?void 0:s.getWidgetByType("detail"))||void 0===o?void 0:o.widgetObject).navigate(e,t)},s.isDetailsReady.value())return d(),void(d=null);s.isDetailsReady.subscribe(d,{once:!0})}function _(e=null,t){const i=(0,o.pathToGroup)(null!=e?e:"");t?(0,n.showNotesDialog)(i):u(i)}function p(e,t){const i=(0,r.newsPathToGroup)(null!=e?e:"");t?(0,a.showNewsDialog)(i):u(i)}function m(e,t){const i=(0,l.ideasPathToGroup)(null!=e?e:"");t?(0,c.showIdeasDialog)(i):u(i)}function g(e,t,i){u((0,h.createMindsPath)(null!=e?e:"",t,i))}function S(e=null,t){const i=(0,o.pathToGroup)(null!=e?e:"")+"?new="+performance.now();t&&(0,n.showNotesDialog)(i),u(i)}},881607:(e,t,i)=>{"use strict";i.d(t,{IDEAS_GROUP_PATH_PATTERN:()=>s,ideasPathToGroup:()=>o});const s="/ideas/groups/:symbol/";function o(e){return s.replace(":symbol",encodeURIComponent(e))}},777453:(e,t,i)=>{"use strict";i.d(t,{NEWS_GROUP_PATH_PATTERN:()=>s,newsPathToGroup:()=>o});const s="/news/groups/:symbol/";function o(e){return s.replace(":symbol",encodeURIComponent(e))}},421219:(e,t,i)=>{"use strict";i.d(t,{GROUP_PATH_PATTERN:()=>o,NOTES_PATH_PATTERN:()=>s,UNATTENDED_PATH_PATTERN:()=>r,pathToGroup:()=>n});const s="/notes/",o="/notes/groups/:symbol/",r="/notes/unattended/";function n(e){return e?o.replace(":symbol",encodeURIComponent(e)):r}},834698:(e,t,i)=>{"use strict";i.d(t,{CompareDialogRenderer:()=>r});var s=i(111393);var o=i(251954);class r extends s.DialogRenderer{constructor(e){super(),this._dialog=null,this._subscribe=e=>{this._setVisibility(e)},this._chartWidgetCollection=e}show(e){this._load().then((t=>{var i,s;null===(i=this._dialog)||void 0===i||i.hide(),null===(s=this._dialog)||void 0===s||s.visible().unsubscribe(this._subscribe),this._dialog=t,t.visible().subscribe(this._subscribe),t.show(e),o.emit("compare_add")}))}hide(){var e;null===(e=this._dialog)||void 0===e||e.hide()}_load(){ return Promise.all([Promise.all([i.e(78596),i.e(11165),i.e(57271)]).then(i.bind(i,910261)),Promise.all([i.e(78596),i.e(11165),i.e(44335),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(93502),i.e(66639),i.e(30006),i.e(88194),i.e(38669),i.e(5145),i.e(35649),i.e(72639),i.e(89842),i.e(25190),i.e(26855),i.e(91033),i.e(58056),i.e(21625),i.e(61631),i.e(90684),i.e(40866),i.e(99916),i.e(40812),i.e(36956),i.e(77807),i.e(56388),i.e(9227),i.e(58289),i.e(77474),i.e(21895),i.e(56949),i.e(73353),i.e(91070),i.e(50690),i.e(30979),i.e(88087),i.e(111),i.e(80870),i.e(46513),i.e(32046),i.e(99144),i.e(30731)]).then(i.bind(i,635647))]).then((([e,t])=>{const i=new e.CompareModel(this._chartWidgetCollection);return t.getCompareDialogRenderer(i)}))}}},105580:(e,t,i)=>{"use strict";i.d(t,{showDetailsDialog:()=>n});var s=i(111393);let o;class r extends s.DialogRenderer{constructor(){super(...arguments),this._dialog=null,this._promise=null,this._subscribe=e=>{this._setVisibility(e)}}show(e){const t=this._promise=Promise.all([i.e(78596),i.e(11165),i.e(68716),i.e(93193),i.e(22309),i.e(37729),i.e(19515),i.e(9643),i.e(122),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(30006),i.e(38669),i.e(5145),i.e(35649),i.e(89842),i.e(25190),i.e(68992),i.e(88548),i.e(81643),i.e(36747),i.e(58056),i.e(21625),i.e(61631),i.e(67080),i.e(52567),i.e(57215),i.e(94345),i.e(58666),i.e(54234),i.e(66886),i.e(80345),i.e(25626),i.e(96821),i.e(50254),i.e(39760),i.e(10690),i.e(28345),i.e(32883),i.e(45932),i.e(17194),i.e(20996),i.e(96234),i.e(50690),i.e(88087),i.e(93869),i.e(51004),i.e(61536),i.e(28778),i.e(86026),i.e(83433),i.e(29508),i.e(44246),i.e(66446),i.e(41537),i.e(6827),i.e(6925),i.e(90803),i.e(76855),i.e(26720)]).then(i.bind(i,863308)).then((i=>{this._promise===t&&(this._dialog&&(this._dialog.hide(),this._dialog.visible().unsubscribe(this._subscribe)),this._dialog=new i.DetailsDialogRenderer,this._dialog.visible().subscribe(this._subscribe),this._dialog.show(e))}))}hide(){var e,t;null===(e=this._dialog)||void 0===e||e.hide(),null===(t=this._dialog)||void 0===t||t.visible().unsubscribe(this._subscribe)}static getInstance(){return o||(o=new r),o}}function n(e){r.getInstance().show(e)}},544855:(e,t,i)=>{"use strict";async function s(e){(await Promise.all([i.e(62253),i.e(22666),i.e(92108),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(38669),i.e(5145),i.e(89842),i.e(25190),i.e(88548),i.e(36747),i.e(58056),i.e(21625),i.e(61631),i.e(45896),i.e(15518),i.e(52567),i.e(42244),i.e(80345),i.e(71793),i.e(35306),i.e(98535),i.e(47768),i.e(50690),i.e(72966),i.e(62526),i.e(94673)]).then(i.bind(i,790348))).renderIdeasDialog(e)}i.d(t,{showIdeasDialog:()=>s})},442731:(e,t,i)=>{"use strict";async function s(e){ (await Promise.all([i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(30006),i.e(38669),i.e(5145),i.e(35649),i.e(89842),i.e(25190),i.e(88548),i.e(13423),i.e(36747),i.e(58056),i.e(21625),i.e(61631),i.e(67080),i.e(15518),i.e(52567),i.e(58666),i.e(54234),i.e(80345),i.e(96821),i.e(45932),i.e(91729),i.e(50690),i.e(49769),i.e(69098),i.e(66446),i.e(84482)]).then(i.bind(i,23154))).renderNewsDialog(e)}i.d(t,{showNewsDialog:()=>s})},731380:(e,t,i)=>{"use strict";async function s(e){Promise.all([i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(34465),i.e(69121),i.e(38669),i.e(5145),i.e(35649),i.e(89842),i.e(25190),i.e(10990),i.e(58056),i.e(21625),i.e(61631),i.e(15518),i.e(73954),i.e(34186),i.e(90592),i.e(58961),i.e(28345),i.e(98535),i.e(70235),i.e(86102),i.e(50690),i.e(88087),i.e(61536),i.e(44810),i.e(87566),i.e(6925),i.e(72465),i.e(50996)]).then(i.bind(i,768175)).then((t=>{t.renderNotesDialog(e)}))}i.d(t,{showNotesDialog:()=>s})},597101:(e,t,i)=>{"use strict";i.d(t,{hideStateChange:()=>s});const s=new(i(707957).Delegate)},161590:(e,t,i)=>{"use strict";i.d(t,{GeneralChartPropertiesRenderer:()=>o});var s=i(111393);class o extends s.DialogRenderer{constructor(e){super(),this._dialog=null,this._subscribe=e=>{this._setVisibility(e)},this._chartWidgetCollection=e}show(e){const t=this._chartWidgetCollection,s=t.activeChartWidget.value();return s.generalPropertiesDefinitions().then((o=>Promise.all([i.e(78596),i.e(11165),i.e(44335),i.e(88601),i.e(52540),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(93502),i.e(66639),i.e(30006),i.e(88194),i.e(38669),i.e(5145),i.e(35649),i.e(72639),i.e(36884),i.e(89842),i.e(25190),i.e(68992),i.e(46036),i.e(10990),i.e(81643),i.e(13152),i.e(26855),i.e(91033),i.e(84281),i.e(58056),i.e(21625),i.e(8740),i.e(61631),i.e(90684),i.e(40866),i.e(99916),i.e(40812),i.e(73954),i.e(36956),i.e(77807),i.e(56388),i.e(9227),i.e(52251),i.e(89434),i.e(98149),i.e(24215),i.e(58289),i.e(77474),i.e(18511),i.e(26053),i.e(21895),i.e(45166),i.e(22333),i.e(54474),i.e(15886),i.e(36740),i.e(75058),i.e(85256),i.e(18182),i.e(27074),i.e(24534),i.e(14127),i.e(10524),i.e(42616),i.e(63616),i.e(69523),i.e(50690),i.e(30979),i.e(88087),i.e(111),i.e(14473),i.e(80870),i.e(46513),i.e(49829),i.e(32046),i.e(59703),i.e(99144),i.e(12716),i.e(48037),i.e(36403),i.e(51408),i.e(33127),i.e(37078)]).then(i.bind(i,100773)).then((i=>{var r,n;const a=new i.GeneralChartPropertiesDialogRenderer({chartWidgetCollection:t,propertyPages:o,activePageId:this._activePageId,model:s.model()});return null===(r=this._dialog)||void 0===r||r.hide(),null===(n=this._dialog)||void 0===n||n.visible().unsubscribe(this._subscribe),this._dialog=a,a.visible().subscribe(this._subscribe),a.show(e),this._activePageId=void 0,a}))))}hide(){var e;null===(e=this._dialog)||void 0===e||e.hide()}isVisible(){return this.visible().value()}focusOnText(){}setActivePage(e){this._activePageId=e}}},826939:(e,t,i)=>{"use strict";i.d(t,{ WATCHLIST_WIDGET_ID:()=>s});const s="watchlist-widget"},104436:(e,t,i)=>{"use strict";var s;i.d(t,{ToolboxType:()=>s}),function(e){e[e.Delete=0]="Delete"}(s||(s={}))},581501:e=>{e.exports={chartsSplitter:"chartsSplitter-L0xapso5",hovered:"hovered-L0xapso5","i-active":"i-active-L0xapso5"}},871332:e=>{e.exports={"css-value-pane-controls-padding-left":"1px","css-value-pane-controls-padding-right":"4px"}},630383:e=>{e.exports={paneSeparator:"paneSeparator-uqBaC1Ki",handle:"handle-uqBaC1Ki",hovered:"hovered-uqBaC1Ki",active:"active-uqBaC1Ki"}},758035:e=>{e.exports={priceScaleModeButtons:"priceScaleModeButtons-PEm49B2T",priceScaleModeButtons__buttonWrapper:"priceScaleModeButtons__buttonWrapper-PEm49B2T",priceScaleModeButtons__button:"priceScaleModeButtons__button-PEm49B2T",priceScaleModeButtons__button_activated:"priceScaleModeButtons__button_activated-PEm49B2T"}},364123:e=>{e.exports={"css-value-small-size":"18px","css-value-medium-size":"22px","css-value-large-size":"28px","css-value-border-radius-small-size":"9px","css-value-border-radius-medium-size":"11px","css-value-border-radius-large-size":"8px",statuses:"statuses-Lgtz1OtS",statusItem:"statusItem-Lgtz1OtS",statuses_hidden:"statuses_hidden-Lgtz1OtS",small:"small-Lgtz1OtS",medium:"medium-Lgtz1OtS",large:"large-Lgtz1OtS",blinking:"blinking-Lgtz1OtS","blinking-animation":"blinking-animation-Lgtz1OtS",marketStatusOpen:"marketStatusOpen-Lgtz1OtS",marketStatusClose:"marketStatusClose-Lgtz1OtS",marketStatusPre:"marketStatusPre-Lgtz1OtS",marketStatusPost:"marketStatusPost-Lgtz1OtS",marketStatusHoliday:"marketStatusHoliday-Lgtz1OtS",marketStatusDelisted:"marketStatusDelisted-Lgtz1OtS",marketStatusExpired:"marketStatusExpired-Lgtz1OtS",marketStatusCustom:"marketStatusCustom-Lgtz1OtS",invalidSymbol:"invalidSymbol-Lgtz1OtS",replayModeAutoPlay:"replayModeAutoPlay-Lgtz1OtS",replayModePause:"replayModePause-Lgtz1OtS",replayModePointSelect:"replayModePointSelect-Lgtz1OtS","blinking-animation-custom":"blinking-animation-custom-Lgtz1OtS",notAccurate:"notAccurate-Lgtz1OtS",delay:"delay-Lgtz1OtS",eod:"eod-Lgtz1OtS",dataProblemHigh:"dataProblemHigh-Lgtz1OtS",dataProblemLow:"dataProblemLow-Lgtz1OtS"}},538660:(e,t,i)=>{"use strict";i.d(t,{ChartSession:()=>c});var s=i(707957),o=i(650151),r=i(401580),n=i(541558);const a=(0,i(201089).getLogger)("ChartApi.AbstractSession");var l=i(389137);class c extends class{constructor(e,t,i){this._isConnected=new r.WatchedValue(!1),this._state=0,this._isConnectForbidden=!1,this._sessionId="",this._sessionIdChanged=new s.Delegate,this._chartApi=e,this._sessionPrefix=t,this._shouldReconnectAfterCriticalError=i}destroy(){this._logNormal("Destroying session"),this._isConnected.unsubscribe(),this.disconnect(),this._sessionIdChanged.destroy(),delete this._chartApi,this._logNormal("Session has been destroyed")}isConnected(){return this._isConnected}sessionId(){return this._sessionId}onSessionIdChanged(){return this._sessionIdChanged}connect(){0===this._state&&((0,o.assert)(!this._isConnectForbidden,"Cannot call connect because it is forbidden at this moment"), this._setSessionId(`${this._sessionPrefix}_${(0,n.randomHash)()}`),this._logNormal("Connecting session - wait until transport stay connected"),this._state=1,this._chartApi.createSession(this._sessionId,this))}disconnect(){0!==this._state&&((0,o.assert)(""!==this._sessionId,"sessionId must not be invalid"),this._logNormal("Disconnecting session..."),this._forbidConnectWhile((()=>{this._chartApi.connected()&&this._sendRemoveSession(),this._processDestroyingOnServer()})))}onMessage(e){switch(e.method){case"connected":return void this._onChartApiConnected();case"disconnected":return void this._onChartApiDisconnected();case"critical_error":const t=String(e.params[0]),i=String(e.params[1]);return void this._onCriticalError(t,i)}this._onMessage(e)}_getChartApi(){return this._chartApi}_generateLogMessage(e){return`[${this._sessionId}] ${e}`}_onCriticalError(e,t){this._logError(`Critical error. Reason=${e}, info=${t}.`),this._forbidConnectWhile((()=>{this._processDestroyingOnServer()})),this._shouldReconnectAfterCriticalError?(this._logNormal("Reconnecting after critical error..."),this.connect()):this._logNormal("Reconnecting after critical error skipped")}_onChartApiConnected(){(0,o.assert)(1===this._state,"Session is not registered"),this._logNormal("Transport is connected. Creating session on the server"),this._sendCreateSession(),this._state=2,this._isConnected.setValue(!0)}_onChartApiDisconnected(){this._logNormal("Transport is disconnected. Reconnecting..."),this._forbidConnectWhile((()=>{this._processDestroyingOnServer()})),this.connect()}_setSessionId(e){const t=this._sessionId;this._logNormal(`Changing sessionId: old=${t}, new=${e}`),this._sessionId=e,this._sessionIdChanged.fire(e,t)}_logNormal(e){a.logNormal(this._generateLogMessage(e))}_logError(e){a.logError(this._generateLogMessage(e))}_processDestroyingOnServer(){this._state=0,this._isConnected.setValue(!1),this._chartApi.removeSession(this._sessionId),this._setSessionId("")}_forbidConnectWhile(e){this._isConnectForbidden=!0,e(),this._isConnectForbidden=!1}}{constructor(e,t=!1){super(e,"cs",!1),this._sessionDisabled=!1,this._handler=null,this._criticalError=new s.Delegate,this._symbolResolveMap=new Map,this._lastSymbolResolveInfoMap=new Map,this._disableStatistics=t}destroy(){this._criticalError.destroy(),this._handler=null,this._symbolResolveMap.clear(),super.destroy()}serverTime(){return this._getChartApi().serverTime()}switchTimezone(e){return this._getChartApi().switchTimezone(this.sessionId(),e)}defaultResolutions(){return this._getChartApi().defaultResolutions()}availableCurrencies(){return this._getChartApi().availableCurrencies()}availableUnits(){return this._getChartApi().availableUnits()}availablePriceSources(e){return this._getChartApi().availablePriceSources(e)}resolveSymbol(e,t,i){if(this._symbolResolveMap.has(t)){const[e,s]=this._symbolResolveMap.get(t);return Array.isArray(s)?s.push(i):s.then(i),e}{const s=[i];return this._getChartApi().resolveSymbol(this.sessionId(),e,t,(i=>{if("symbol_error"===i.method)this._symbolResolveMap.delete(t);else{ this._symbolResolveMap.set(t,[e,Promise.resolve(i)]);const[,s]=i.params,o={pro_name:s.pro_name,ticker:s.ticker};this._lastSymbolResolveInfoMap.set(t,o),o.pro_name&&this._lastSymbolResolveInfoMap.set(o.pro_name,o),s.full_name&&this._lastSymbolResolveInfoMap.set(s.full_name,o),o.ticker&&this._lastSymbolResolveInfoMap.set(o.ticker,o)}s.forEach((e=>e(i)))})),this._symbolResolveMap.set(t,[e,s]),e}}requestFirstBarTime(e,t,i){return this._getChartApi().requestFirstBarTime(this.sessionId(),e,t,i)}lastSymbolResolveInfo(e){var t;return null!==(t=this._lastSymbolResolveInfoMap.get(e))&&void 0!==t?t:null}createSeries(e,t,i,s,o,r,n){return this._getChartApi().createSeries(this.sessionId(),e,t,i,s,o,r,n)}modifySeries(e,t,i,s,o,r,n){return this._getChartApi().modifySeries(this.sessionId(),e,t,i,s,o,r,n)}removeSeries(e){return!!this.isConnected().value()&&this._getChartApi().removeSeries(this.sessionId(),e)}requestMoreData(e,t,i){return"number"==typeof e?this._getChartApi().requestMoreData(this.sessionId(),e):this._getChartApi().requestMoreData(this.sessionId(),e,t,i)}requestMoreTickmarks(e,t,i){return(0,l.isNumber)(e)?this._getChartApi().requestMoreTickmarks(this.sessionId(),e):this._getChartApi().requestMoreTickmarks(this.sessionId(),e,t,i)}canCreateStudy(e,t){return this._getChartApi().canCreateStudy(this.sessionId(),e,t)}getStudyCounter(){return this._getChartApi().getStudyCounter(this.sessionId())}getFundamentalCounter(){return this._getChartApi().getFundamentalCounter(this.sessionId())}createStudy(e,t,i,s,o,r,n){return this._getChartApi().createStudy(this.sessionId(),e,t,i,s,o,r,n)}modifyStudy(e,t,i,s,o){return this._getChartApi().modifyStudy(this.sessionId(),e,t,i,s,o)}removeStudy(e){return this._getChartApi().removeStudy(this.sessionId(),e)}createPointset(e,t,i,s,o,r){return this._getChartApi().createPointset(this.sessionId(),e,t,i,s,o,r)}modifyPointset(e,t,i,s){return this._getChartApi().modifyPointset(this.sessionId(),e,t,i,s)}removePointset(e){return this._getChartApi().removePointset(this.sessionId(),e)}setVisibleTimeRange(e,t,i,s,o,r){0}criticalError(){return this._criticalError}connect(e=null){null!==e&&(this._handler=e),this._symbolResolveMap.clear(),super.connect()}setHandler(e){this._handler=e}connected(){return this.isConnected().value()&&!this._sessionDisabled}disable(){this._sessionDisabled=!0}chartApi(){return this._getChartApi()}_sendCreateSession(){Object.keys(this).forEach((e=>{/^(s|st|symbol_)\d+$/.test(e)&&delete this[e]})),this._getChartApi().chartCreateSession(this.sessionId(),this._disableStatistics)}_sendRemoveSession(){this._getChartApi().chartDeleteSession(this.sessionId())}_onMessage(e){this._handler&&this._handler(e)}_onCriticalError(e,t){this._criticalError.fire(e,t),super._onCriticalError(e,t)}}},15458:(e,t,i)=>{"use strict";i.r(t),i.d(t,{availableTimezones:()=>l,timezoneIsAvailable:()=>u,timezoneIsSupported:()=>_,timezoneTitle:()=>p,updateAvailableTimezones:()=>d});var s=i(444372),o=i(245302);const r=[{id:"Etc/UTC",title:s.t(null,void 0,i(850406))},{id:"exchange",title:s.t(null,void 0,i(777295)) }],n=[{id:"Africa/Cairo",title:s.t(null,void 0,i(994099)),offset:0},{id:"Africa/Casablanca",title:s.t(null,void 0,i(753705)),offset:0},{id:"Africa/Johannesburg",title:s.t(null,void 0,i(387469)),offset:0},{id:"Africa/Lagos",title:s.t(null,void 0,i(89155)),offset:0},{id:"Africa/Nairobi",title:s.t(null,void 0,i(679023)),offset:0},{id:"Africa/Tunis",title:s.t(null,void 0,i(193855)),offset:0},{id:"America/Anchorage",title:s.t(null,void 0,i(399873)),offset:0},{id:"America/Argentina/Buenos_Aires",title:s.t(null,void 0,i(882446)),offset:0},{id:"America/Bogota",title:s.t(null,void 0,i(54173)),offset:0},{id:"America/Caracas",title:s.t(null,void 0,i(846837)),offset:0},{id:"America/Chicago",title:s.t(null,void 0,i(228244)),offset:0},{id:"America/El_Salvador",title:s.t(null,void 0,i(768553)),offset:0},{id:"America/Juneau",title:s.t(null,void 0,i(124435)),offset:0},{id:"America/Lima",title:s.t(null,void 0,i(725846)),offset:0},{id:"America/Los_Angeles",title:s.t(null,void 0,i(687604)),offset:0},{id:"America/Mexico_City",title:s.t(null,void 0,i(185095)),offset:0},{id:"America/New_York",title:s.t(null,void 0,i(291203)),offset:0},{id:"America/Phoenix",title:s.t(null,void 0,i(219093)),offset:0},{id:"America/Santiago",title:s.t(null,void 0,i(965412)),offset:0},{id:"America/Sao_Paulo",title:s.t(null,void 0,i(913538)),offset:0},{id:"America/Toronto",title:s.t(null,void 0,i(83836)),offset:0},{id:"America/Vancouver",title:s.t(null,void 0,i(115771)),offset:0},{id:"US/Mountain",title:s.t(null,void 0,i(257701)),offset:0},{id:"Asia/Almaty",title:s.t(null,void 0,i(14452)),offset:0},{id:"Asia/Ashkhabad",title:s.t(null,void 0,i(559340)),offset:0},{id:"Asia/Bahrain",title:s.t(null,void 0,i(53260)),offset:0},{id:"Asia/Bangkok",title:s.t(null,void 0,i(732376)),offset:0},{id:"Asia/Chongqing",title:s.t(null,void 0,i(649648)),offset:0},{id:"Asia/Colombo",title:s.t(null,void 0,i(115168)),offset:0},{id:"Asia/Dhaka",title:s.t(null,void 0,i(724477)),offset:0},{id:"Asia/Dubai",title:s.t(null,void 0,i(822429)),offset:0},{id:"Asia/Ho_Chi_Minh",title:s.t(null,void 0,i(587338)),offset:0},{id:"Asia/Hong_Kong",title:s.t(null,void 0,i(532918)),offset:0},{id:"Asia/Jakarta",title:s.t(null,void 0,i(652707)),offset:0},{id:"Asia/Jerusalem",title:s.t(null,void 0,i(642890)),offset:0},{id:"Asia/Karachi",title:s.t(null,void 0,i(202693)),offset:0},{id:"Asia/Kathmandu",title:s.t(null,void 0,i(303155)),offset:0},{id:"Asia/Kolkata",title:s.t(null,void 0,i(916245)),offset:0},{id:"Asia/Kuwait",title:s.t(null,void 0,i(872374)),offset:0},{id:"Asia/Manila",title:s.t(null,void 0,i(290271)),offset:0},{id:"Asia/Muscat",title:s.t(null,void 0,i(442769)),offset:0},{id:"Asia/Nicosia",title:s.t(null,void 0,i(733566)),offset:0},{id:"Asia/Qatar",title:s.t(null,void 0,i(619056)),offset:0},{id:"Asia/Riyadh",title:s.t(null,void 0,i(152588)),offset:0},{id:"Asia/Seoul",title:s.t(null,void 0,i(605961)),offset:0},{id:"Asia/Shanghai",title:s.t(null,void 0,i(969240)),offset:0},{id:"Asia/Singapore",title:s.t(null,void 0,i(156683)),offset:0},{id:"Asia/Taipei",title:s.t(null,void 0,i(438788)),offset:0},{ id:"Asia/Tehran",title:s.t(null,void 0,i(16267)),offset:0},{id:"Asia/Tokyo",title:s.t(null,void 0,i(294284)),offset:0},{id:"Asia/Yangon",title:s.t(null,void 0,i(769293)),offset:0},{id:"Atlantic/Reykjavik",title:s.t(null,void 0,i(626833)),offset:0},{id:"Australia/Adelaide",title:s.t(null,void 0,i(717365)),offset:0},{id:"Australia/Brisbane",title:s.t(null,void 0,i(511741)),offset:0},{id:"Australia/Perth",title:s.t(null,void 0,i(635590)),offset:0},{id:"Australia/Sydney",title:s.t(null,void 0,i(111020)),offset:0},{id:"Europe/Amsterdam",title:s.t(null,void 0,i(688010)),offset:0},{id:"Europe/Athens",title:s.t(null,void 0,i(921983)),offset:0},{id:"Europe/Belgrade",title:s.t(null,void 0,i(254861)),offset:0},{id:"Europe/Berlin",title:s.t(null,void 0,i(326825)),offset:0},{id:"Europe/Bratislava",title:s.t(null,void 0,i(605262)),offset:0},{id:"Europe/Brussels",title:s.t(null,void 0,i(690204)),offset:0},{id:"Europe/Bucharest",title:s.t(null,void 0,i(537728)),offset:0},{id:"Europe/Budapest",title:s.t(null,void 0,i(787143)),offset:0},{id:"Europe/Copenhagen",title:s.t(null,void 0,i(743432)),offset:0},{id:"Europe/Dublin",title:s.t(null,void 0,i(609497)),offset:0},{id:"Europe/Helsinki",title:s.t(null,void 0,i(899820)),offset:0},{id:"Europe/Istanbul",title:s.t(null,void 0,i(537885)),offset:0},{id:"Europe/Lisbon",title:s.t(null,void 0,i(450091)),offset:0},{id:"Europe/London",title:s.t(null,void 0,i(50286)),offset:0},{id:"Europe/Luxembourg",title:s.t(null,void 0,i(164352)),offset:0},{id:"Europe/Madrid",title:s.t(null,void 0,i(758038)),offset:0},{id:"Europe/Malta",title:s.t(null,void 0,i(334190)),offset:0},{id:"Europe/Moscow",title:s.t(null,void 0,i(118665)),offset:0},{id:"Europe/Oslo",title:s.t(null,void 0,i(782906)),offset:0},{id:"Europe/Paris",title:s.t(null,void 0,i(595995)),offset:0},{id:"Europe/Prague",title:s.t(null,void 0,i(546298)),offset:0},{id:"Europe/Riga",title:s.t(null,void 0,i(605871)),offset:0},{id:"Europe/Rome",title:s.t(null,void 0,i(974214)),offset:0},{id:"Europe/Stockholm",title:s.t(null,void 0,i(248767)),offset:0},{id:"Europe/Tallinn",title:s.t(null,void 0,i(939108)),offset:0},{id:"Europe/Vienna",title:s.t(null,void 0,i(732166)),offset:0},{id:"Europe/Vilnius",title:s.t(null,void 0,i(475354)),offset:0},{id:"Europe/Warsaw",title:s.t(null,void 0,i(48474)),offset:0},{id:"Europe/Zurich",title:s.t(null,void 0,i(984301)),offset:0},{id:"Pacific/Auckland",title:s.t(null,void 0,i(824143)),offset:0},{id:"Pacific/Chatham",title:s.t(null,void 0,i(59884)),offset:0},{id:"Pacific/Fakaofo",title:s.t(null,void 0,i(520466)),offset:0},{id:"Pacific/Honolulu",title:s.t(null,void 0,i(961351)),offset:0},{id:"Pacific/Norfolk",title:s.t(null,void 0,i(99203)),offset:0}];function a(e,t,i){const s=function(e){return e.map((({id:e,title:t})=>{const{string:i,offset:s}=(0,o.parseTzOffset)(e);return{id:e,offset:s,title:`(${i}) ${t}`}}))}(e),r=i.filter((({alias:e})=>Boolean(e))).map((({title:e,alias:t,id:i})=>{const{string:s,offset:r}=(0,o.parseTzOffset)(t);return{id:i,offset:r,title:`(${s}) ${e}`,alias:t}})),n=function(e){return e.sort(((e,t)=>{ const i=e.offset-t.offset;return 0!==i?i:e.title.localeCompare(t.title)}))}(s.concat(r));return t.concat(n)}const l=a(n,r,[]),c=new Map;l.forEach((e=>{c.set(e.id,!0)}));const h=new Map;r.concat(n).forEach((e=>{h.set(e.id,!0)}));const d=e=>{l.splice(0,l.length,...a(n,r,e)),l.forEach((e=>{c.set(e.id,!0)}))};function u(e){return c.has(e)}function _(e){return h.get(e)||!1}function p(e){for(const{id:t,title:i}of n)if(t===e){return`${i} (${(0,o.parseTzOffset)(e).string})`}for(const{id:t,title:i}of l)if(t===e)return`${i}`;return e}},245302:(e,t,i)=>{"use strict";i.d(t,{parseTzOffset:()=>o});var s=i(988124);function o(e,t=Date.now()){const i=(0,s.get_timezone)(e).offset_utc(t);let o="";const r=i/1e3/60/60;r%1&&(o=":"+Math.round(Math.abs(r%1*60)).toString().padStart(2,"0"));let n="";return n=r>0?"+"+(r-r%1)+o:0===r?"":String(r-r%1+o),{offset:i,string:"UTC"+n}}},747971:(e,t,i)=>{"use strict";i.d(t,{ActionWithStandardIcon:()=>r});var s=i(373571),o=i(982368);class r extends s.Action{constructor(e){var t,i;const{options:s,customActionOptions:r}=e;s.iconId&&(s.icon=null!==(t=s.icon)&&void 0!==t?t:o.icons.get(s.iconId)),r&&r.iconId&&(r.icon=null!==(i=r.icon)&&void 0!==i?i:o.icons.get(r.iconId)),super(e)}}},982368:(e,t,i)=>{"use strict";i.d(t,{icons:()=>k});var s=i(539706),o=i(472382),r=i(198083),n=i(80465),a=i(748040),l=i(324020),c=i(527409),h=i(845437),d=i(428026),u=i(625923),_=i(270068),p=i(789795),m=i(439970),g=i(634369),S=i(139267),v=i(535149),f=i(484959),b=i(437924),y=i(677067),C=i(416911),w=i(225191),P=i(854190),T=i(706862),M=i(397874),x=i(902872),I=i(201457),A=i(593379);let L=[["Chart.Reset",S],["Chart.RemoveSelectedObject",v],["Settings",g],["Chart.Hide",f],["Chart.SymbolInfo",b],["Chart.VisualOrder",y],["Chart.ShowObject",C],["Chart.PriceScale",w],["Chart.Move",P],["Chart.ApplyIndicator",T],["Chart.UnlockObject",M],["Chart.LockObject",x],["Chart.Clone",I],["Chart.AddHorzLine",A]];L=L.concat([["TextNote.Add",l],["Platform.ColorTheme",c],["Watchlist.AddSymbol",h],["Watchlist.CreateNew",h],["Chart.Financials",d],["Alert.Add",u],["Alert.Edit",_],["Alert.Restart",p],["Alert.Stop",m]]),L=L.concat([["Chart.ShowDataWindow",s],["Trading.Sell",o],["Trading.Buy",r],["ObjectsTree.CreateGroup",n],["ObjectsTree.RenameItem",a]]);const k=new Map(L)},394093:(e,t,i)=>{"use strict";var s;i.d(t,{AlertEditorAbortReason:()=>s}),function(e){e.AlertIsInvalid="alert-is-invalid",e.AlertsMaintenance="alerts-maintenance",e.ChartModelNotFound="chart-model-not-found",e.IsAlreadyPresent="is-already-present",e.MainSeriesIsATR="main-series-is-atr",e.MainSeriesIsInReplay="main-series-is-in-replay",e.MainSeriesIsOffline="main-series-is-offline",e.SourceIsDangerous="source-is-dangerous",e.SymbolInfoTimeout="symbol-info-timeout",e.SymbolIsInvalid="symbol-is-invalid",e.SymbolCurrencyConverted="symbol-currency-converted",e.SymbolUnitConverted="symbol-unit-converted",e.SymbolCurrencyAndUnitConverted="symbol-currency-and-unit-converted",e.SymbolIsEconomics="symbol-is-economics",e.UnsupportedResolution="unsupported-resolution",e.ManualAbort="manual-abort", e.MisleadingPriceScale="misleading-price-scale",e.ResolutionIsTicks="resolution-is-ticks"}(s||(s={}))},862297:(e,t,i)=>{"use strict";i.d(t,{ensureResolvedSymbolInfo:()=>f,ensureSeriesIsNotOffline:()=>v,getAlertDialogType:()=>_,shouldAbortAlertEditor:()=>p,showAbortExplainingDialog:()=>g});var s=i(444372),o=i(779923),r=i(394093),n=i(444331),a=i(223699),l=i(583912),c=i(537133),h=i(781310),d=i(31214);const u=(0,i(594949).getAlertsTrackers)().maintenance;function _(e){return e.alert||e.facadeAlert?e.type||"edit_alert":"create_alert"}function p(e){var t;if(u.value())return r.AlertEditorAbortReason.AlertsMaintenance;if(!e.alert&&!e.facadeAlert&&!e.dataSourceHub)return r.AlertEditorAbortReason.ChartModelNotFound;if(!c.alertEditorInvocationHandler.isAllowedToInvoke(e))return r.AlertEditorAbortReason.IsAlreadyPresent;const i=null===(t=e.dataSourceHub)||void 0===t?void 0:t.mainSeries();if(i&&m(i))return r.AlertEditorAbortReason.MainSeriesIsOffline;if(i&&function(e){return 4===e.status()}(i))return r.AlertEditorAbortReason.SymbolIsInvalid;if(i&&i.isConvertedToOtherCurrency()&&i.isConvertedToOtherUnit())return r.AlertEditorAbortReason.SymbolCurrencyAndUnitConverted;if(i&&i.isConvertedToOtherCurrency())return r.AlertEditorAbortReason.SymbolCurrencyConverted;if(i&&i.isConvertedToOtherUnit())return r.AlertEditorAbortReason.SymbolUnitConverted;const s=_(e);if("create_alert"===s&&i&&function(e){const t=e.stateForAlert().styleInputs;return"style"in t&&"ATR"===t.style}(i))return r.AlertEditorAbortReason.MainSeriesIsATR;if("create_alert"===s&&i&&function(e){return e.isInReplay()}(i))return r.AlertEditorAbortReason.MainSeriesIsInReplay;if("create_alert"===s&&i&&function(e){return(0,n.isEconomicSymbol)(e.symbolInfo())}(i))return r.AlertEditorAbortReason.SymbolIsEconomics;const o=i?i.interval():l.linking.interval.value();return"create_alert"===s&&a.Interval.isTicks(o)?r.AlertEditorAbortReason.ResolutionIsTicks:"create_alert"!==s||(0,h.canPlaceAlertOnResolution)(o)?null:r.AlertEditorAbortReason.UnsupportedResolution}function m(e){return 0===e.status()}function g(e,t){if(S.has(e))return;S.add(e);const n=()=>S.delete(e),a=function(e){return new Map([[r.AlertEditorAbortReason.UnsupportedResolution,"alertsOnSeconds"]]).get(e)||null}(e);if(a)return void(0,d.reloginOrGoPro)({feature:a,actionAfterClose:n});const l=function(e,t){const o=s.t(null,void 0,i(900850)),n=s.t(null,void 0,i(488322)),a=s.t(null,void 0,i(468988));return new Map([[r.AlertEditorAbortReason.AlertsMaintenance,{title:s.t(null,void 0,i(243322)),text:s.t(null,void 0,i(98333)),buttonText:a}],[r.AlertEditorAbortReason.MainSeriesIsOffline,{title:o,text:("create_alert"===t?s.t(null,void 0,i(680644)):s.t(null,void 0,i(878717)))+". "+s.t(null,void 0,i(443167))+".",buttonText:a}],[r.AlertEditorAbortReason.SymbolIsInvalid,{title:o,text:"create_alert"===t?s.t(null,void 0,i(396472)):s.t(null,void 0,i(601230)),buttonText:a}],[r.AlertEditorAbortReason.SymbolCurrencyAndUnitConverted,{title:s.t(null,void 0,i(535871)),text:"create_alert"===t?s.t(null,void 0,i(39546)):s.t(null,void 0,i(588989)), buttonText:s.t(null,void 0,i(875139))}],[r.AlertEditorAbortReason.SymbolCurrencyConverted,{title:s.t(null,void 0,i(203470)),text:"create_alert"===t?s.t(null,void 0,i(499303)):s.t(null,void 0,i(8180)),buttonText:s.t(null,void 0,i(875139))}],[r.AlertEditorAbortReason.SymbolUnitConverted,{title:s.t(null,void 0,i(806212)),text:"create_alert"===t?s.t(null,void 0,i(433335)):s.t(null,void 0,i(615119)),buttonText:s.t(null,void 0,i(875139))}],[r.AlertEditorAbortReason.SymbolIsEconomics,{title:s.t(null,void 0,i(282076)),text:s.t(null,void 0,i(914407)),buttonText:s.t(null,void 0,i(875139))}],[r.AlertEditorAbortReason.MainSeriesIsATR,{title:s.t(null,void 0,i(347599)),text:s.t(null,void 0,i(862688)),buttonText:a}],[r.AlertEditorAbortReason.MainSeriesIsInReplay,{title:s.t(null,void 0,i(198447)),text:s.t(null,void 0,i(881565)),buttonText:s.t(null,void 0,i(875139))}],[r.AlertEditorAbortReason.ResolutionIsTicks,{title:s.t(null,void 0,i(915469)),text:s.t(null,void 0,i(867501)),buttonText:s.t(null,void 0,i(875139))}]]).get(e)||{title:o,text:n,buttonText:a}}(e,t);(0,o.showWarning)({...l,onClose:n})}const S=new Set;function v(e){return new Promise((t=>{if(!m(e))return void t();const i=()=>{m(e)||(e.onStatusChanged().unsubscribe(null,i),t())};e.onStatusChanged().subscribe(null,i)}))}function f(e){return new Promise((t=>{if(e.symbolInfo())return void t();e.dataEvents().symbolResolved().subscribe(null,(()=>{e.symbolInfo()&&t()}),!0)}))}},794389:(e,t,i)=>{"use strict";i.d(t,{Animation:()=>n});var s=i(81979),o=i(764005);const r={duration:250,easing:s.easingFunc.easeOutCubic};class n{constructor(e){this._onFinishCalled=!1,this._options={...r,...e},this._startTime=performance.now()}getStartPosition(){return this._options.from}getPosition(e){const t=this._calculateProgress(e);return 1===t?(this._options.onFinish&&!this._onFinishCalled&&(this._options.onFinish(!0),this._onFinishCalled=!0),this._options.to):(0,o.lerp)(this._options.from,this._options.to,this._options.easing(t))}finished(e){return 1===this._calculateProgress(e)}onFinish(e){var t,i;this._onFinishCalled||(null===(i=(t=this._options).onFinish)||void 0===i||i.call(t,e),this._onFinishCalled=!0)}_calculateProgress(e){const t=e-this._startTime;return t>=this._options.duration?1:t/this._options.duration}}},237872:(e,t,i)=>{"use strict";i.d(t,{ChartHotkeysListener:()=>v,globalEnvironmentState:()=>S,modifierPressed:()=>g,shiftPressed:()=>m});var s,o,r,n=i(799786),a=i(470316),l=i(515312),c=i(401580),h=i(950740);const d=new c.WatchedValue(Boolean((null!==(s=n.pressedKeys.value())&&void 0!==s?s:0)&a.Modifiers.Shift)),u=new c.WatchedValue(Boolean((null!==(o=n.pressedKeys.value())&&void 0!==o?o:0)&a.Modifiers.Mod)),_=new c.WatchedValue(Boolean((null!==(r=n.pressedKeys.value())&&void 0!==r?r:0)&a.Modifiers.Alt)),p=[a.Modifiers.None,a.Modifiers.Alt,a.Modifiers.Mod,a.Modifiers.Alt+a.Modifiers.Shift];function m(){return d}function g(){return u}function S(){return new h.EnvironmentState({altKey:_.value(),ctrlKey:g().value(),metaKey:g().value(),shiftKey:m().value()})}n.pressedKeys.subscribe(((e=0)=>{ d.setValue(Boolean(e&a.Modifiers.Shift)),u.setValue(Boolean(e&a.Modifiers.Mod)),_.setValue(Boolean(e&a.Modifiers.Alt))}));class v{constructor(e,t){this._pressedKeyCode=null,this._boundKeydownHandler=null,this._boundKeyupHandler=null,this._chartWidget=e,this._parent=t,this._boundKeydownHandler=this._keydownHandler.bind(this),this._boundKeyupHandler=this._keyupHandler.bind(this),this._parent.ownerDocument.addEventListener("keydown",this._boundKeydownHandler),this._parent.ownerDocument.addEventListener("keyup",this._boundKeyupHandler)}destroy(){null!==this._boundKeydownHandler&&(this._parent.ownerDocument.removeEventListener("keydown",this._boundKeydownHandler),this._boundKeydownHandler=null),null!==this._boundKeyupHandler&&(this._parent.ownerDocument.removeEventListener("keyup",this._boundKeyupHandler),this._boundKeyupHandler=null)}_keydownHandler(e){this._chartWidget.hasModel()&&window.document.activeElement===window.document.body&&this._chartWidget.isActive().value()&&(this._handleMoveDrawingsKeyDown(e)||this._handleScrollKeyDown(e)||this._handleZoomKeyDown(e))&&e.preventDefault()}_keyupHandler(e){this._chartWidget.hasModel()&&this._handleScrollKeyUp(e)}_handleMoveDrawingsKeyDown(e){const t=255&(0,a.hashFromEvent)(e),i=this._chartWidget.model();switch(t){case 37:return i.moveSelectedToolsLeft();case 39:return i.moveSelectedToolsRight();case 38:return i.moveSelectedToolsUp();case 40:return i.moveSelectedToolsDown()}return!1}_handleScrollKeyDown(e){if(null!==this._pressedKeyCode)return!1;const t=(0,a.hashFromEvent)(e),i=255&t,s=(0,a.modifiersFromEvent)(e);let o;if(37===i)o=1;else{if(39!==i)return!1;o=-1}return!(a.isMacKeyboard&&s===a.Modifiers.Mod||!p.includes(s))&&(!(0,l.isNativeUIInteraction)(t,e.target)&&(this._pressedKeyCode=i,s===a.Modifiers.None?this._chartWidget.scrollHelper().moveByBar(o):s===a.Modifiers.Alt||s===a.Modifiers.Mod?this._chartWidget.scrollHelper().move(o):-1===o?this._chartWidget.model().timeScale().scrollToRealtime(!0):this._chartWidget.model().timeScale().scrollToFirstBar(),!0))}_handleScrollKeyUp(e){if(null===this._pressedKeyCode)return!1;const t=(0,a.hashFromEvent)(e);if((0,l.isNativeUIInteraction)(t,e.target))return!1;return(255&t)===this._pressedKeyCode&&(this._pressedKeyCode=null,this._chartWidget.scrollHelper().stopMove(),!0)}_handleZoomKeyDown(e){const t=(0,a.hashFromEvent)(e),i=255&t;if((0,a.modifiersFromEvent)(e)!==a.Modifiers.Mod||(0,l.isNativeUIInteraction)(t,e.target))return!1;const s=this._chartWidget.model();if(38===i)s.zoomIn();else{if(40!==i)return!1;s.zoomOut()}return!0}}},931212:(e,t,i)=>{"use strict";i.d(t,{ChartWidgetBase:()=>Ks});var s=i(327714),o=i(895171),r=i(650151),n=i(591800),a=i(444372),l=i(251954),c=i(583912),h=i(638456),d=i(62802),u=i(429874),_=i(345848),p=i(246733),m=i(201089),g=i(568247),S=i(167975),v=i(268222);function f(e,t){const i=Object.create(Object.getPrototypeOf(e));for(const s of t)Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=e[s]);return i}var b=i(560420),y=i(951713),C=i(111393);let w;class P extends C.DialogRenderer{constructor(){super(), this._dialog=null,this._subscribe=e=>{this._setVisibility(e)}}show(){this._load().then((e=>e.show()))}hide(){var e;null===(e=this._dialog)||void 0===e||e.hide()}static getInstance(){return w||(w=new P),w}_load(){return Promise.all([i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(30006),i.e(88194),i.e(38669),i.e(5145),i.e(35649),i.e(25190),i.e(91033),i.e(36747),i.e(58056),i.e(67080),i.e(15518),i.e(98149),i.e(36842),i.e(36752),i.e(35542),i.e(45166),i.e(51494),i.e(89150),i.e(29030),i.e(50690),i.e(30979),i.e(29594),i.e(93869),i.e(58510),i.e(31984),i.e(19359),i.e(33950),i.e(39418),i.e(61421),i.e(34862)]).then(i.bind(i,272935)).then((e=>{var t,i;return null===(t=this._dialog)||void 0===t||t.hide(),null===(i=this._dialog)||void 0===i||i.visible().unsubscribe(this._subscribe),this._dialog=new e.ObjectTreeDialogRenderer,this._dialog.visible().subscribe(this._subscribe),this._dialog}))}}var T=i(389137),M=i(62745),x=i(190973);async function I(e,t,s,o,r,n="default"){let l,c=[];const h=e.model().model(),d=(0,T.clone)(t),u=new x.default({inputs:d}),_=function(e,t){return"symbol"===t?e.inputs.filter((t=>t.id===e.symbolInputId())):e.inputs.filter((e=>e.confirm))}(s,n),p=()=>{l&&h.removeCustomSource(l)},m=()=>{p(),r()},g=e=>{o({inputs:e,parentSources:c}),p()},S=_.filter(M.isTimeOrPriceNotHiddenInput);if(S.length>0)try{const t=await Promise.all([i.e(78596),i.e(11165),i.e(44335),i.e(88601),i.e(99410),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(93502),i.e(66639),i.e(30006),i.e(88194),i.e(38669),i.e(5145),i.e(35649),i.e(72639),i.e(36884),i.e(89842),i.e(25190),i.e(68992),i.e(10990),i.e(81643),i.e(13152),i.e(26855),i.e(91033),i.e(84281),i.e(58056),i.e(21625),i.e(8740),i.e(61631),i.e(90684),i.e(40866),i.e(99916),i.e(40812),i.e(73954),i.e(36956),i.e(77807),i.e(56388),i.e(9227),i.e(89434),i.e(24215),i.e(58289),i.e(77474),i.e(18511),i.e(21895),i.e(22333),i.e(54474),i.e(15886),i.e(36740),i.e(27074),i.e(71762),i.e(50690),i.e(30979),i.e(88087),i.e(111),i.e(80870),i.e(46513),i.e(49829),i.e(32046),i.e(59703),i.e(99144),i.e(12716),i.e(48037),i.e(36403),i.e(53030)]).then(i.bind(i,280881)),o=await t.selectInputValuesOnChart(e,S,u,s.shortDescription,s.inputs);if(l=o.customSourceId,o.destPane){const e=o.destPane.mainDataSource();c=e===h.mainSeries()?[]:[e]}else c=[]}catch(e){return void m()} S.length!==_.length?Promise.all([i.e(78596),i.e(11165),i.e(44335),i.e(88601),i.e(99410),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(93502),i.e(66639),i.e(30006),i.e(88194),i.e(38669),i.e(5145),i.e(35649),i.e(72639),i.e(36884),i.e(89842),i.e(25190),i.e(68992),i.e(10990),i.e(81643),i.e(13152),i.e(26855),i.e(91033),i.e(84281),i.e(58056),i.e(21625),i.e(8740),i.e(61631),i.e(90684),i.e(40866),i.e(99916),i.e(40812),i.e(73954),i.e(36956),i.e(77807),i.e(56388),i.e(9227),i.e(89434),i.e(24215),i.e(58289),i.e(77474),i.e(18511),i.e(21895),i.e(22333),i.e(54474),i.e(15886),i.e(36740),i.e(27074),i.e(71762),i.e(50690),i.e(30979),i.e(88087),i.e(111),i.e(80870),i.e(46513),i.e(49829),i.e(32046),i.e(59703),i.e(99144),i.e(12716),i.e(48037),i.e(36403),i.e(53030)]).then(i.bind(i,49294)).then((t=>{const o=new t.ConfirmInputsDialogRenderer(function(e){if("symbol"===e)return a.t(null,void 0,i(345743));return a.t(null,void 0,i(846689))}(n),_,u,n,s,e.model(),g,m);return o.show(),o})):g(u.state().inputs||{})}let A=null;var L=i(941285),k=i(674981),E=i(66732),D=i(15458),N=i(707957),B=i(244842);function R(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function O(e){return e.reduce(((e,t)=>{for(const i in t)if(R(t,i)){const s=t[i],o=e[i];o?o.push(s):e[i]=[s]}return e}),{})}var V=i(809796),W=i(401580),F=i(373571),H=i(747971),z=i(982368),U=i(199471),G=i(237872);const q=new V.TranslatedString("move left",a.t(null,void 0,i(415086))),j=new V.TranslatedString("move right",a.t(null,void 0,i(461711)));class Y{constructor(e){this._chartModel=null,this._animation=null,this._chart=e,this._chart.withModel(this,(()=>{this._chartModel=this._chart.model()}))}destroy(){var e;null===(e=this._animation)||void 0===e||e.stop()}move(e){if(null!==this._chartModel){if(this._chartModel.timeScale().isEmpty())return;const t=.003,i=1.1,s=Math.round(i/t);this._moveImpl(e,((o,r,n)=>{const a=Math.min(r,s),l=e*t*Math.pow(a,2)/2;if(r<=s)return o+l;const c=Number.isFinite(n)?Math.max(0,s-n):0;return o+l+e*(r-a-c)*i+e*(i*c-t*Math.pow(c,2)/2)}),(e=>Math.max(0,s-e)+s))}}moveByBar(e){if(null!==this._chartModel){const t=this._chartModel.timeScale(),i=t.visibleBarsStrictRange();if(t.isEmpty()||null===i)return;const s=300,o=i.lastBar();this._moveImpl(e,((i,r)=>{const n=Math.floor(Math.max(0,r-s)/100)+1,a=o+e*n,l=t.indexToCoordinate(o);return i+(t.indexToCoordinate(a)-l)}),(()=>0),!0)}}stopMove(){var e;null===(e=this._animation)||void 0===e||e.stop(),this._animation=null}scrollToRealtime(e){null!==this._chartModel&&this._chartModel.timeScale().scrollToRealtime(e)}_moveImpl(e,t,i,s){if(null===this._chartModel)return;const o=this._chartModel.timeScale();if(o.isEmpty())return;if(this._chartModel.changeTimeScale(1===e?q:j),s&&null!==o.visibleBarsStrictRange()){const e=o.indexToCoordinate(o.visibleBarsStrictRange().lastBar())+o.barSpacing()/2;Math.abs(o.width()-e)>o.barSpacing()/6&&o.setRightOffset(Math.round(o.rightOffset()))}const r=performance.now();let n=1/0;this._animation={getStartPosition:()=>0, getPosition:e=>(e=Math.min(n,e),t(0,e-r,n-e)),finished:e=>e>=n,stop:()=>{const e=performance.now()-r;n=performance.now()+i(e)}},this._chartModel.model().stopTimeScaleAnimation(),this._chartModel.model().setTimeScaleAnimation(this._animation)}}var K=i(794349);function Z(e,t,s,o,r){return Promise.all([i.e(78596),i.e(11165),i.e(44335),i.e(88601),i.e(96461),i.e(52540),i.e(22751),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(93502),i.e(66639),i.e(30006),i.e(88194),i.e(38669),i.e(5145),i.e(35649),i.e(72639),i.e(36884),i.e(89842),i.e(25190),i.e(68992),i.e(46036),i.e(10990),i.e(81643),i.e(13152),i.e(26855),i.e(91033),i.e(84281),i.e(58056),i.e(21625),i.e(49205),i.e(8740),i.e(61631),i.e(90684),i.e(40866),i.e(99916),i.e(40812),i.e(73954),i.e(36956),i.e(77807),i.e(56388),i.e(9227),i.e(52251),i.e(22486),i.e(89434),i.e(98149),i.e(24215),i.e(58289),i.e(77474),i.e(12494),i.e(18511),i.e(26053),i.e(21895),i.e(22333),i.e(54474),i.e(15886),i.e(36740),i.e(75058),i.e(85256),i.e(18182),i.e(27074),i.e(24534),i.e(14127),i.e(42616),i.e(47391),i.e(61455),i.e(50690),i.e(30979),i.e(88087),i.e(29594),i.e(93869),i.e(111),i.e(14473),i.e(80870),i.e(46513),i.e(49829),i.e(32046),i.e(59703),i.e(99144),i.e(12716),i.e(48037),i.e(36403),i.e(51408),i.e(33127),i.e(80068),i.e(46265)]).then(i.bind(i,568348)).then((i=>{const n=new(0,i.EditObjectDialogRenderer)(e,t,o,r);return n.show(s),n}))}var $=i(427937);let X=null;var J=i(224153),Q=i(924788),ee=i(364615),te=i(713473);const ie={[K.TabNames.symbol]:"symbol",[K.TabNames.legend]:"legend",[K.TabNames.scales]:"scales",[K.TabNames.trading]:"trading",[K.TabNames.events]:"events",[K.TabNames.eventsAndAlerts]:"events",[K.TabNames.timezoneSessions]:"canvas",[K.TabNames.text]:"text",[K.TabNames.style]:"style",[K.TabNames.visibility]:"visibility"},se={[K.TabNames.style]:"style",[K.TabNames.visibility]:"visibilities"};async function oe(e,t,s={},o,r){const n=o.activeChartWidget.value(),{initialTab:a,tabName:l}=s;if(l&&!a&&(s.initialTab=se[l]),(0,te.isStudyLineTool)(e)&&function(e){return[J.LineToolVbPFixed,ee.LineToolAnchoredVolumeProfile].filter(T.notNull).some((t=>e instanceof t))}(e))return n.propertiesDefinitionsForSource(e).then((i=>null!==i?Z(e,t,s,r,i):null));if((0,$.isStudy)(e)&&function(e){const{shortId:t}=e.metaInfo();return"Overlay"===t}(e)||(0,te.isLineTool)(e))return n.propertiesDefinitionsForSource(e).then((o=>{if(null!==o){return function(e){ return Promise.all([i.e(78596),i.e(11165),i.e(44335),i.e(88601),i.e(52540),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(93502),i.e(66639),i.e(30006),i.e(88194),i.e(38669),i.e(5145),i.e(35649),i.e(72639),i.e(36884),i.e(89842),i.e(25190),i.e(68992),i.e(46036),i.e(10990),i.e(81643),i.e(13152),i.e(26855),i.e(91033),i.e(84281),i.e(58056),i.e(21625),i.e(8740),i.e(61631),i.e(90684),i.e(40866),i.e(99916),i.e(40812),i.e(73954),i.e(36956),i.e(77807),i.e(56388),i.e(9227),i.e(52251),i.e(22486),i.e(89434),i.e(98149),i.e(24215),i.e(58289),i.e(77474),i.e(18511),i.e(26053),i.e(21895),i.e(22333),i.e(54474),i.e(15886),i.e(36740),i.e(75058),i.e(85256),i.e(18182),i.e(27074),i.e(24534),i.e(14127),i.e(42616),i.e(47391),i.e(98904),i.e(50690),i.e(30979),i.e(88087),i.e(29594),i.e(93869),i.e(111),i.e(14473),i.e(80870),i.e(46513),i.e(49829),i.e(32046),i.e(59703),i.e(99144),i.e(12716),i.e(48037),i.e(36403),i.e(51408),i.e(33127),i.e(80068),i.e(46780)]).then(i.bind(i,757381)).then((t=>{const i=new(0,t.SourcePropertiesEditorRenderer)(e);return null!==X&&X.hide(),i.show({shouldReturnFocus:e.shouldReturnFocus}),X=i,i}))}({propertyPages:o,model:t,source:e,activePageId:l&&ie[l],shouldReturnFocus:s.shouldReturnFocus})}return null}));if((0,$.isStudy)(e)&&!(0,Q.isLollipopDataSource)(e))return Z(e,t,s,r);{const t=(0,Q.isLollipopDataSource)(e)?"events":l&&ie[l],i=o.getChartPropertiesDialogRenderer();return i.setActivePage(t),i.show(s)}}var re=i(790188),ne=i(331633),ae=i(61499),le=i(100366),ce=i(1500),he=i(444331);const de=(0,re.getHexColorByName)("color-cold-gray-700"),ue=(0,re.getHexColorByName)("color-cold-gray-400");class _e{constructor(e){this._container=null,this._errorCardRenderer=null,this._mainSeriesErrorMessage=null,this._banErrorMessage=new W.WatchedValue(null).spawn(),this._errorMessageHandler=e=>{this._chartWidget.hasModel()?this._updatePaneWidgets(e):this._renderErrorWithoutModel(e)},this._chartWidget=e,this._subscribeToMainSeriesErrors()}destroy(){var e,t;null===(e=this._mainSeriesErrorMessage)||void 0===e||e.destroy(),this._banErrorMessage.destroy(),null===(t=this._errorCardRenderer)||void 0===t||t.then((e=>{e.container.remove(),e.destroy()}))}updatePaneWidgets(){this._updatePaneWidgets()}setContainer(e){var t;if(this._container!==e){this._container=e,null===(t=this._errorCardRenderer)||void 0===t||t.then((e=>e.container.remove()));const i=this._getErrorMessage();i&&this._errorMessageHandler(i)}}_updatePaneWidgets(e=this._getErrorMessage()){this._chartWidget.paneWidgets().forEach((t=>t.setErrorMessage(e)))}async _renderErrorWithoutModel(e){if(null===this._container||null===e&&null===this._errorCardRenderer)return;const t=await this._getErrorCardRenderer();this._container.contains(t.container)||this._container.appendChild(t.container),t.update(this._createErrorCardRendererState(e))}async _getErrorCardRenderer(){return this._errorCardRenderer||(this._errorCardRenderer=this._createErrorCardRenderer())}async _createErrorCardRenderer(){return new(await(0, le.getErrorCardRenderer)())}_createErrorCardRendererState(e){return e?{message:e.message,icon:e.icon,textColor:ne.watchedTheme.value()===ae.StdTheme.Dark?ue:de,backgroundColor:ne.watchedTheme.value()===ae.StdTheme.Dark?"#131722":"#FFF",solutionId:e.solutionId}:{message:null}}_subscribeToMainSeriesErrors(){const e=this._chartWidget;this._banErrorMessage=(0,E.combine)((e=>{if(!e)return null;let t;if("banned by ip"===e.reason)t=a.t(null,void 0,i(311884));else t=a.t(null,void 0,i(115078));return{message:t,solutionId:ce.solutionIds.WHY_IS_MY_ACCOUNT_BANNED,icon:"stop-hand"}}),window.ChartApiInstance.connectionBanInfo().weakReference()),this._banErrorMessage.subscribe(this._errorMessageHandler,{callWithLast:!0}),e.withModel(this,(()=>{const t=e.model().model().mainSeries();this._mainSeriesErrorMessage=(0,E.combine)(((e,t)=>{if(e)return e;switch(t){case"invalid_symbol":return{message:a.t(null,void 0,i(132619)),icon:"ghost"};case"no_data":return{message:a.t(null,void 0,i(395222)),icon:"ghost"};case null:return null}}),this._banErrorMessage.weakReference(),(0,he.getSeriesDisplayErrorWV)(t).ownership()),this._mainSeriesErrorMessage.subscribe(this._errorMessageHandler,{callWithLast:!0})}))}_getErrorMessage(){var e;return this._banErrorMessage.value()||(null===(e=this._mainSeriesErrorMessage)||void 0===e?void 0:e.value())||null}}var pe=i(109154),me=i(572230),ge=i(86121),Se=i(533422),ve=i(792795),fe=i(826989),be=i(254355);class ye{constructor(e,t){this._showed=!1,this._cw=e,this._element=document.createElement("div"),this._element.classList.add(be.screen),t.appendChild(this._element),this._cw.withModel(this,this._connectToModel)}show(e){if(e){const e=this._cw.model().mainSeries().status();if(1!==e&&2!==e)return}this._cw.setInLoadingState(!0),this._showed||(this._showed=!0,this._show())}hide(){this._cw.setInLoadingState(!1),this._showed&&this._hide()}isShown(){return this._showed}_connectToModel(){const e=this._cw.model().mainSeries().dataEvents();e.symbolError().subscribe(this,(e=>{e!==fe.permissionDenied&&this.hide()})),e.seriesError().subscribe(this,(()=>{(0,B.enabled)("hide_loading_screen_on_series_error")&&this.hide()})),e.completed().subscribe(this,this.hide)}_show(){const e=this._cw.properties().childs().paneProperties.childs();let t;if(e.backgroundType.value()===ve.ColorType.Solid)t=e.background.value();else{t=`linear-gradient(${e.backgroundGradientStartColor.value()},${e.backgroundGradientEndColor.value()})`}this._element.style.background=t,this._element.classList.add(be.fade)}_hide(){this._showed=!1,this._element.classList.remove(be.fade)}}function Ce(e,t){let{deltaX:i,deltaY:s}=e;switch(i/=100,s/=100,t.deltaMode){case t.DOM_DELTA_PAGE:i*=120,s*=120;break;case t.DOM_DELTA_LINE:i*=32,s*=32}return{deltaX:i,deltaY:s}}class we{constructor(){this._totalDeltaX=0,this._totalDeltaY=0,this._prevWheelTime=0}processWheel(e){e.timeStamp-this._prevWheelTime>100&&this._reset(),this._totalDeltaX+=e.deltaX,this._totalDeltaY+=e.deltaY,this._prevWheelTime=e.timeStamp;const t={deltaX:e.deltaX,deltaY:e.deltaY} ;return 0===this._totalDeltaX||0===this._totalDeltaY||(Math.abs(this._totalDeltaX)>=Math.abs(3*this._totalDeltaY)&&(t.deltaY=0),Math.abs(this._totalDeltaY)>=Math.abs(3*this._totalDeltaX)&&(t.deltaX=0)),Ce(t,e)}_reset(){this._totalDeltaX=0,this._totalDeltaY=0}}var Pe=i(724377),Te=i(678515),Me=i(431912),xe=i(866319),Ie=i(630383);class Ae{constructor(e,t,i){this._handleEl=null,this._resizeInfo=null,this._colorCache={lineColor:"",backgroundColor:"",color:""},this._chart=e,this._topPaneIndex=t,this._bottomPaneIndex=i,this._element=document.createElement("div"),this._element.classList.add(Ie.paneSeparator),this._element.style.background=this._color(),this.adjustSize(),this._element.addEventListener("click",(()=>{}));const s=document.createElement("div");s.classList.add(Ie.handle),this._element.appendChild(s),this._mouseEventHandler=new Me.MouseEventHandler(s,this,{treatVertTouchDragAsPageScroll:!1,treatHorzTouchDragAsPageScroll:!0}),this._handleEl=s,xe.PLATFORM_ACCESSIBILITY_ENABLED&&this._element.setAttribute("aria-hidden","true")}destroy(){this._mouseEventHandler.destroy(),this._element.parentElement&&this._element.parentElement.removeChild(this._element)}getElement(){return this._element}hide(){this._element.classList.add("js-hidden")}show(){this._element.classList.remove("js-hidden")}adjustSize(){this._element.style.height=Ae.height()+"px"}mouseEnterEvent(e){const{topPane:t,bottomPane:i}=this._topBottomPane(!0);null!==t&&null!==i&&(0,r.ensureNotNull)(this._handleEl).classList.add(Ie.hovered)}mouseLeaveEvent(e){(0,r.ensureNotNull)(this._handleEl).classList.remove(Ie.hovered)}mouseDownEvent(e){this._mouseDownOrTouchStartEvent(e)}touchStartEvent(e){this._mouseDownOrTouchStartEvent(e)}pressedMouseMoveEvent(e){this._pressedMouseOrTouchMoveEvent(e)}touchMoveEvent(e){this._pressedMouseOrTouchMoveEvent(e)}mouseUpEvent(e){this._mouseUpOrTouchEndEvent(e)}touchEndEvent(e){this._mouseUpOrTouchEndEvent(e)}update(){this._element.style.background=this._color().toString()}paint(){}image(){const{topPane:e}=this._topBottomPane(!1),t=e.leftPriceAxisesContainer().getWidth(),i=e.width(),o=e.rightPriceAxisesContainer().getWidth(),r=this._color(),n=(0,U.createDisconnectedCanvas)(document,(0,s.size)({width:t,height:1})),a=(0,U.getPrescaledContext2D)(n);a.fillStyle=r,a.fillRect(0,0,t,1);const l=(0,U.createDisconnectedCanvas)(document,(0,s.size)({width:i,height:1})),c=(0,U.getPrescaledContext2D)(l);c.fillStyle=r,c.fillRect(0,0,i,1);const h=(0,U.createDisconnectedCanvas)(document,(0,s.size)({width:o,height:1})),d=(0,U.getPrescaledContext2D)(h);return d.fillStyle=r,d.fillRect(0,0,o,1),{type:"separator",leftAxis:{content:n.toDataURL(),canvas:n,contentWidth:t,contentHeight:1},rightAxis:{content:h.toDataURL(),canvas:h,contentWidth:o,contentHeight:1},content:l.toDataURL(),canvas:l,contentWidth:i,contentHeight:1}}static height(){const e=window.devicePixelRatio||1;return e>=1?1:1/e}_mouseDownOrTouchStartEvent(e){const{topPane:t,bottomPane:i}=this._topBottomPane(!0);if(null===t||null===i)return ;const s=t.state().stretchFactor()+i.state().stretchFactor(),o=s/(t.height()+i.height()),n=30*o;s<=2*n||(this._resizeInfo={startY:e.pageY,prevStretchTopPane:t.state().stretchFactor(),maxPaneStretch:s-n,totalStretch:s,pixelStretchFactor:o,minPaneStretch:n},(0,r.ensureNotNull)(this._handleEl).classList.add(Ie.active))}_pressedMouseOrTouchMoveEvent(e){const{topPane:t,bottomPane:i}=this._topBottomPane(!0),s=this._resizeInfo;if(null===s||null===t||null===i)return;const o=(e.pageY-s.startY)*s.pixelStretchFactor,r=(0,Te.clamp)(s.prevStretchTopPane+o,s.minPaneStretch,s.maxPaneStretch);t.state().setStretchFactor(r),i.state().setStretchFactor(s.totalStretch-r),this._chart.model().model().fullUpdate()}_mouseUpOrTouchEndEvent(e){const{topPane:t,bottomPane:i}=this._topBottomPane(!0),s=this._resizeInfo;null!==s&&null!==t&&null!==i&&(this._chart.model().addPaneStretchFactorUndoCommand(t.state(),i.state(),s.prevStretchTopPane,t.state().stretchFactor()),this._resizeInfo=null,(0,r.ensureNotNull)(this._handleEl).classList.remove(Ie.active))}_color(){const e=this._chart.properties().childs().paneProperties.childs().separatorColor.value(),t=this._chart.model().model().backgroundColor().value();if(this._colorCache.lineColor!==e||this._colorCache.backgroundColor!==t){const i=(0,Pe.parseRgba)(t),s=(0,Pe.parseRgba)(e),o=0===i[3]&&0===s[3]?"rgba(0,0,0,0)":(0,Pe.rgbaToString)((0,Pe.blendRgba)(i,s));this._colorCache={lineColor:e,backgroundColor:t,color:o}}return this._colorCache.color}_topBottomPane(e){const t=this._chart.paneWidgets();let i=null,s=null;for(let s=this._topPaneIndex;s>=0;--s){const o=t[s];if(!e||!o.state().collapsed().value()){i=o;break}}for(let i=this._bottomPaneIndex;i{this.update(),this._textWidthCache.reset()},this._timeAxisWidget=a,this._isLeft="left"===e;const{rendererOptionsProvider:l,sourcesTitlesProvider:c,contextMenuItemsProvider:h,backgroundBasedTheme:d,onActiveOrHoveredChart:u=new W.WatchedValue(!1).ownership(),requestRepaint:_,getBackgroundTopColor:p,getBackgroundBottomColor:m,showHorizontalBorder:g}=r;this._rendererOptionsProvider=l,this._sourcesTitlesProvider=c,this._contextMenuItemsProvider=h,this._backgroundBasedTheme=d,this._onActiveOrHoveredChart=u, this._requestRepaint=_,this._getBackgroundTopColor=p,this._getBackgroundBottomColor=m,this._showHorizontalBorder=Boolean(g),this._properties=t,this._axisInfo=o,this._labelOptions={...Ke,...n},this._properties.lineColor.subscribe(this,this._onPropertyChanged),this._cell=document.createElement("div"),this._labelOptions.enableTooltip&&this._cell.classList.add("apply-common-tooltip"),this._cell.style.width="25px",this._cell.style.height="100%",this._cell.style.position="absolute",this._cell.style.left="0",this._cell.style.overflow="hidden",this._labelOptions.showLabels&&(this._labelOptions.enableTooltip&&(0,Ge.setTooltipData)(this._cell,"text",(e=>this._tooltipContent())),i.e(72616).then(i.bind(i,500477)).then((e=>{this._destroyed||(this._gearRenderer=e.svgRenderer(je),_())})),this._onActiveOrHoveredChart.subscribe(_)),this._mouseEventHandler=new Me.MouseEventHandler(this._cell,this,{treatHorzTouchDragAsPageScroll:!0,treatVertTouchDragAsPageScroll:!0}),this._canvasBinding=(0,U.createBoundCanvas)(this._cell,(0,s.size)({width:16,height:16})),this._canvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const S=this._canvasBinding.canvasElement;S.style.position="absolute",S.style.left="0",S.style.top="0",xe.PLATFORM_ACCESSIBILITY_ENABLED&&this._cell.setAttribute("aria-hidden","true")}destroy(){this._canvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._canvasBinding.dispose(),this._properties.lineColor.unsubscribe(this,this._onPropertyChanged),this._mouseEventHandler.destroy(),this._backgroundBasedTheme.release(),this._onActiveOrHoveredChart.unsubscribe(this._requestRepaint),this._onActiveOrHoveredChart.release(),this._destroyed=!0}mouseEnterEvent(e){this._mouseOrTouchEnterEvent(e)}touchStartEvent(e){this._mouseOrTouchEnterEvent(e)}mouseLeaveEvent(e){this._mouseOrTouchLeaveEvent(e)}touchEndEvent(e){this._mouseOrTouchLeaveEvent(e)}mouseClickEvent(e){this._mouseClickOrTapEvent(e)}tapEvent(e){this._mouseClickOrTapEvent(e)}update(){}getElement(){return this._cell}onLabelHovered(){return this._onLabelHovered}setSizeAndOffset(e,t){(0,s.equalSizes)(this._size,e)||(this._size=e,this._canvasBinding.resizeCanvasElement(e),this._cell.style.width=`${e.width}px`,this._cell.style.minWidth=`${e.width}px`,this._cell.style.height=`${e.height}px`,this._invalidated=!0),this._offset!==t&&(this._offset=t,this._cell.style.left=`${t}px`)}paint(e){e{e.fillText(o.label,h.x/t,h.y/t+i)}))}else if(null!==this._gearRenderer&&!i&&this._onActiveOrHoveredChart.value()){const i=this._gearRenderer.viewBox(),o=Math.round(h.x-i.width*t/2),r=Math.round(h.y-i.height*t/2);e.fillStyle=u.themes[s].getThemedColor("color-text-primary"),e.imageSmoothingQuality="high",this._gearRenderer.render(e,{targetViewBox:{x:o,y:r,width:i.width*t,height:i.height*t},doNotApplyColors:!0})}}_vertBorderColor(){return this._properties.lineColor.value()}_horzBorderColor(){var e,t;return null!==(t=null===(e=this._timeAxisWidget)||void 0===e?void 0:e.lineColor())&&void 0!==t?t:this._vertBorderColor()}_tooltipContent(){return this._sourcesTitlesProvider().join("\n")}_mouseOrTouchEnterEvent(e){this._labelOptions.showLabels&&this._labelOptions.enableHighlight&&this._setHighlighted(!0)}_mouseOrTouchLeaveEvent(e){this._labelOptions.showLabels&&this._labelOptions.enableHighlight&&this._setHighlighted(!1)}_mouseClickOrTapEvent(e){if(e.preventDefault(), null!==this._fixedLabelMode||1===this._labelMode||!this._labelOptions.enableMenu||!this._labelOptions.showLabels)return void Ue.ContextMenuManager.hideAll();this._fixedLabelMode=this._labelMode,this.setLabelMode(0);const t=this._cell.getBoundingClientRect();Ue.ContextMenuManager.showMenu(this._contextMenuItemsProvider(),{clientX:this._isLeft?t.left:t.right,clientY:t.top,attachToXBy:this._isLeft?"left":"right",attachToYBy:"bottom"},{statName:"PriceScaleLabelContextMenu",doNotCloseOn:this.getElement()},{menuName:"PriceScaleLabelContextMenu"},(()=>{this.setLabelMode((0,r.ensureNotNull)(this._fixedLabelMode)),this._fixedLabelMode=null}))}}var Xe=i(175070);class Je{constructor(e,t,i,o,r,n=null){this._axises=[],this._stubs=[],this._size=(0,s.size)({width:0,height:0}),this._onLabelHovered=new N.Delegate,this._scalesProperties=e,this._priceAxisWidgetFactory=i,this._timeAxisWidget=n,this._rendererOptionsProvider=o.rendererOptionsProvider,this._titlesProvider=o.titlesProvider,this._stubContextMenuProvider=o.stubContextMenuProvider,this._backgroundBasedTheme=o.backgroundBasedTheme,this._onActiveOrHoveredChart=o.onActiveOrHoveredChart,this._getBackgroundTopColor=o.getBackgroundTopColor,this._getBackgroundBottomColor=o.getBackgroundBottomColor,this._requestRepaint=o.requestRepaint,this._showHorisontalBorder=Boolean(o.showHorizontalBorder),this._labelsOptions={...Ke,...r};const a=this._scalesProperties.childs();this._stubProperties={lineColor:a.lineColor,fontSize:a.fontSize},this._side=t,this._cell=document.createElement("div"),this._cell.classList.add("chart-markup-table","price-axis-container"),this._cell.style.width="25px",this._cell.style.position="relative"}destroy(){var e;this.setScales([],0,0,0),this._backgroundBasedTheme.release(),null===(e=this._onActiveOrHoveredChart)||void 0===e||e.release()}onLabelHovered(){return this._onLabelHovered}setScales(e,t,i,s){for(;e.length>this._axises.length&&this._axises.lengthn;){const e=(0,r.ensureDefined)(this._stubs.pop());e.onLabelHovered().unsubscribeAll(this),this._cell.removeChild(e.getElement()),e.destroy()}for(;this._stubs.length{this._labelsOptions.showLabels&&this._labelsOptions.enableHighlight&&this._onLabelHovered.fire({owner:t,axis:(0,r.ensureNotNull)(e)},i)})),this._stubs.push(t), this._cell.appendChild(t.getElement())}const a=this._labelsOptions.enableMenu;1===s?this._stubs.forEach(((e,t)=>e.setLabelMode(a?0:1))):this._stubs.forEach(((e,t)=>e.setLabelMode(te.updateCurrencyLabel()))}optimalWidths(){return this._axises.map((e=>e.optimalWidth()))}setSizes(e,t){this._size=(0,s.size)({width:t.reduce(((e,t)=>e+t),0),height:e}),this._cell.style.width=this._size.width+"px",this._cell.style.minWidth=this._size.width+"px",this._cell.style.height=this._size.height+"px",t.length!==this._axises.length+this._stubs.length&&(0,r.assert)(t.length===this._axises.length+this._stubs.length,"Widgets count should be the same as widths one");let i=0;this._forEachWidgetFromLeft(((o,r)=>{const n=t[r];o.setSizeAndOffset((0,s.size)({width:n,height:e}),i),i+=n}))}update(){this._axises.forEach((e=>e.update())),this._stubs.forEach((e=>e.update()))}paint(e){this._axises.forEach(((t,i)=>t.paint(e(i)))),this._stubs.forEach(((t,i)=>t.paint(e(i))))}paintStubs(e){this._stubs.forEach((t=>t.paint(e)))}restoreDefaultCursor(){this._axises.forEach((e=>e.restoreDefaultCursor()))}getWidth(){return this._size.width}findAxisWidgetForScale(e){const t=this._axises.find((t=>t.priceScale()===e));return void 0===t?null:t}getScreenshotData(){const e=this._getImage();return{canvas:e,content:e.toDataURL(),contentHeight:this._size.height,contentWidth:this._size.width}}getImage(){return this._getImage()}slotsCount(){return this._axises.length+this._stubs.length}highlightPriceAxisByLabel(e){this._axises.forEach((t=>{const i=t.axisInfo();t.setHighlighted(null!==i&&i.equals(e))}))}axes(){return this._axises}_stubParams(e){var t;return{rendererOptionsProvider:this._rendererOptionsProvider,backgroundBasedTheme:this._backgroundBasedTheme.spawnOwnership(),onActiveOrHoveredChart:null===(t=this._onActiveOrHoveredChart)||void 0===t?void 0:t.spawnOwnership(),sourcesTitlesProvider:()=>this._titlesProvider(this._side,e),contextMenuItemsProvider:()=>this._stubContextMenuProvider(this._side,e),getBackgroundTopColor:this._getBackgroundTopColor,getBackgroundBottomColor:this._getBackgroundBottomColor,requestRepaint:this._requestRepaint,showHorizontalBorder:this._showHorisontalBorder}}_getImage(){const e=(0,U.createDisconnectedCanvas)(document,this._size),t=(0,U.getPrescaledContext2D)(e);let i=0;return this._forEachWidgetFromLeft(((e,s)=>{const o=e.getWidth();0!==o&&0!==this._size.height&&(t.drawImage(e.getImage(),i,0,o,this._size.height),i+=o)})),e}_forEachWidgetFromLeft(e){const t=[...this._axises,...this._stubs],i="left"===this._side,s=i?-1:t.length,o=i?-1:1;for(let r=i?t.length-1:0;r!==s;r+=o)e(t[r],r,t)}}var Qe=i(346825),et=i(855824),tt=i(460682);class it{constructor(){this._width=null,this._labelBottom=null,this._currencyInfo=null,this._unitInfo=null,this._measureUnitIdInfo=null,this._fontSize=0,this._currencyAndUnitLabelsWrapper=document.createElement("div"),this._currencyAndUnitLabelsWrapper.className=tt["price-axis-currency-label-wrapper"], this._currencyAndUnitLabelsWrapper.setAttribute("data-name","currency-unit-label-wrapper"),this._controlsContainer=document.createElement("div"),this._controlsContainer.className=tt["price-axis-currency-label"],this._currencyAndUnitLabelsWrapper.appendChild(this._controlsContainer),this._currencyLabelDiv=document.createElement("div"),this._currencyLabelDiv.className=tt.row,this._currencyLabelDiv.classList.add("apply-common-tooltip"),(0,Ge.setTooltipData)(this._currencyLabelDiv,"text",(e=>this._currencyTooltipContent())),this._currencyText=document.createElement("div"),this._currencyText.className=tt["price-axis-currency-label-text"],this._currencyLabelDiv.appendChild(this._currencyText),this._currencyArrowDown=document.createElement("div"),this._currencyArrowDown.className=tt["price-axis-currency-label-arrow-down"],this._currencyArrowDown.innerHTML=et,this._currencyLabelDiv.appendChild(this._currencyArrowDown),this._measureUnitIdLabelDiv=document.createElement("div"),this._measureUnitIdLabelDiv.className=tt.row,this._measureUnitIdLabelDiv.classList.add("apply-common-tooltip"),this._measureUnitIdLabelDiv.classList.add("readonly"),(0,Ge.setTooltipData)(this._measureUnitIdLabelDiv,"text",(e=>this._measureUnitIdTooltipContent())),this._measureUnitIdText=document.createElement("div"),this._measureUnitIdText.className=tt["price-axis-currency-label-text"],this._measureUnitIdLabelDiv.appendChild(this._measureUnitIdText),this._unitLabelDiv=document.createElement("div"),this._unitLabelDiv.className=tt.row,this._unitLabelDiv.classList.add("apply-common-tooltip"),(0,Ge.setTooltipData)(this._unitLabelDiv,"text",(e=>this._unitTooltipContent())),this._unitText=document.createElement("div"),this._unitText.className=tt["price-axis-currency-label-text"],this._unitLabelDiv.appendChild(this._unitText),this._unitArrowDown=document.createElement("div"),this._unitArrowDown.className=tt["price-axis-currency-label-arrow-down"],this._unitArrowDown.innerHTML=et,this._unitLabelDiv.appendChild(this._unitArrowDown),this._controlsContainer.appendChild(this._currencyLabelDiv),this._controlsContainer.appendChild(this._measureUnitIdLabelDiv),this._controlsContainer.appendChild(this._unitLabelDiv),this.disableCurrency(),this.disableUnit()}element(){return this._currencyAndUnitLabelsWrapper}currencyLabelElement(){return this._currencyLabelDiv}unitLabelElement(){return this._unitLabelDiv}isEnabled(){return this.currencyLabelEnabled()||this.unitLabelEnabled()||this.measureUnitIdLableEnabled()}isHidden(){return this._currencyAndUnitLabelsWrapper.classList.contains(tt.hidden)}setCurrencyExpanded(e){this._currencyLabelDiv.classList.toggle(tt.expanded,e)}setUnitExpanded(e){this._unitLabelDiv.classList.toggle(tt.expanded,e)}width(){if(null!==this._width)return this._width;let e=0;if(this.currencyLabelEnabled()){const t=this._currencyText.getBoundingClientRect(),i=this._currencyArrowDown.getBoundingClientRect();e=Math.max(e,t.width+i.width+2*this._textMarginAndPadding())}if(this.measureUnitIdLableEnabled()){ const t=this._measureUnitIdText.getBoundingClientRect();e=Math.max(e,t.width+2*this._textMarginAndPadding())}if(this.unitLabelEnabled()){const t=this._unitText.getBoundingClientRect(),i=this._unitArrowDown.getBoundingClientRect();e=Math.max(e,t.width+i.width+2*this._textMarginAndPadding())}return this._width=e}drawLabel(e,t,i){var s,o,r;if(!this.isEnabled())return;const n=Math.round(Number(tt.css_wrapper_margin)*i),a=(0,Te.ceiledEven)(t*i)-2*n,l=Math.round(this.labelBottom()*i),c=l-2*n,h=Math.round(Number(tt.css_value_currency_label_radius)*i);e.fillStyle=getComputedStyle(this._currencyAndUnitLabelsWrapper).backgroundColor,e.fillRect(0,0,Math.ceil(t*i),l);const d=[];d.push(this.currencyLabelEnabled()&&null!==(s=this._currencyText.textContent)&&void 0!==s?s:""),d.push(this.measureUnitIdLableEnabled()&&null!==(o=this._measureUnitIdText.textContent)&&void 0!==o?o:""),d.push(this.unitLabelEnabled()&&null!==(r=this._unitText.textContent)&&void 0!==r?r:""),e.font=(0,He.makeFont)(this._fontSize,qe.CHART_FONT_FAMILY);const u=new ze.TextWidthCache;let _=0;const p=[];d.forEach((t=>{let i=0;""!==t&&(i=u.yMidCorrection(e,t),_++),p.push(i)}));const m=c/_;e.beginPath();const g=getComputedStyle(this._controlsContainer);e.fillStyle=g.backgroundColor,e.strokeStyle=g.borderColor,(0,Fe.drawRoundRect)(e,n,n,a,c,h),e.fill(),e.stroke(),e.fillStyle=getComputedStyle(this._currencyLabelDiv).color,e.textBaseline="middle",e.textAlign="left";const S=Math.round(this._textMarginAndPadding()*i)+n,v=m/2;let f=n+v;d.forEach(((t,s)=>{""!==t&&((0,U.drawScaled)(e,i,i,(()=>{e.fillText(t,S/i,(f+p[s])/i)})),f=Math.ceil(f+2*v))}))}setHidden(e){this._currencyAndUnitLabelsWrapper.classList.toggle(tt.hidden,e)}enableCurrency(){this._currencyLabelDiv.classList.remove("js-hidden"),this._resetSizesAndVisibility()}disableCurrency(){this._currencyLabelDiv.classList.add("js-hidden"),this._resetSizesAndVisibility()}enableUnit(){this._unitLabelDiv.classList.remove("js-hidden"),this._resetSizesAndVisibility()}disableUnit(){this._unitLabelDiv.classList.add("js-hidden"),this._resetSizesAndVisibility()}enableMeasureUnitId(){this._measureUnitIdLabelDiv.classList.remove("js-hidden"),this._resetSizesAndVisibility()}disableMeasureUnitId(){this._measureUnitIdLabelDiv.classList.add("js-hidden"),this._resetSizesAndVisibility()}currencyLabelEnabled(){return!this._currencyLabelDiv.classList.contains("js-hidden")}unitLabelEnabled(){return!this._unitLabelDiv.classList.contains("js-hidden")}measureUnitIdLableEnabled(){return!this._measureUnitIdLabelDiv.classList.contains("js-hidden")}currencyConversionAvailable(){return!this._currencyLabelDiv.classList.contains("readonly")}unitConversionAvailable(){return!this._unitLabelDiv.classList.contains("readonly")}setCurrencyInfo(e){if(this._currencyInfo===e)return!1;this._currencyInfo=e;const t=null===e.selectedCurrency?a.t(null,void 0,i(795093)):(0,r.ensureDefined)(e.displayedValues.get(e.selectedCurrency));return this._currencyText.textContent!==t&&(this._currencyText.textContent=t,this._width=null), this._currencyArrowDown.classList.contains("js-hidden")!==e.readOnly&&(this._currencyArrowDown.classList.toggle("js-hidden",e.readOnly),this._currencyLabelDiv.classList.toggle("readonly",e.readOnly),this._width=null),!0}setUnitInfo(e){if(null!==this._unitInfo&&this._unitInfo.selectedUnit===e.selectedUnit&&0===this._unitInfo.availableGroups.size==(0===e.availableGroups.size)&&this._unitInfo.originalUnits.size===e.originalUnits.size)return this._unitInfo=e,!1;this._unitInfo=e;const t=null===e.selectedUnit?a.t(null,void 0,i(795093)):(0,r.ensureDefined)(e.names.get(e.selectedUnit));return this._unitText.textContent!==t&&(this._unitText.textContent=t,this._width=null),this._unitArrowDown.classList.contains("js-hidden")!==(0===e.availableGroups.size)&&(this._unitArrowDown.classList.toggle("js-hidden",0===e.availableGroups.size),this._unitLabelDiv.classList.toggle("readonly",0===e.availableGroups.size),this._width=null),!0}setMeasureUnitIdInfo(e){if(this._measureUnitIdInfo===e)return!1;this._measureUnitIdInfo=e;const t=null===e.selectedMeasureUnitId?a.t(null,void 0,i(795093)):(0,r.ensureDefined)(e.names.get(e.selectedMeasureUnitId));return this._measureUnitIdText.textContent!==t&&(this._measureUnitIdText.textContent=t,this._width=null),this._measureUnitIdLabelDiv.classList.contains("js-hidden")!==(0===e.names.size)&&(this._measureUnitIdLabelDiv.classList.toggle("js-hidden",0===e.names.size),this._width=null),!0}currencyInfo(){return this._currencyInfo}unitInfo(){return this._unitInfo}measureUnitIdInfo(){return this._measureUnitIdInfo}setFontSize(e){this._fontSize!==e&&(this._fontSize=e,this._currencyLabelDiv.style.fontSize=e+"px",this._measureUnitIdLabelDiv.style.fontSize=e+"px",this._unitLabelDiv.style.fontSize=e+"px",this._width=null,this._labelBottom=null)}labelBottom(){if(null!==this._labelBottom)return this._labelBottom;const e=this._controlsContainer.getBoundingClientRect(),t=this._currencyAndUnitLabelsWrapper.getBoundingClientRect(),i=e.y-t.y;return this._labelBottom=e.height+2*i}_resetSizesAndVisibility(){this._width=null,this._labelBottom=null,this._updateVisibility()}_textMarginAndPadding(){return Number(tt.css_wrapper_margin)+Number(tt.css_row_left_right_padding)+2}_currencyTooltipContent(){const e=this._currencyInfo;return null===e?"":null===e.selectedCurrency?Array.from(e.currencies).map((t=>(0,r.ensureDefined)(e.displayedValues.get(t)))).join(", "):e.displayedValues.get(e.selectedCurrency)||""}_unitTooltipContent(){const e=this._unitInfo;return null===e?"":null===e.selectedUnit?Array.from(e.units).map((t=>(0,r.ensureDefined)(e.names.get(t)))).join(", "):e.descriptions.get(e.selectedUnit)||""}_measureUnitIdTooltipContent(){const e=this._measureUnitIdInfo;return null===e?"":null===e.selectedMeasureUnitId?Array.from(e.measureUnitIds).map((t=>(0,r.ensureDefined)(e.names.get(t)))).join(", "):e.descriptions.get(e.selectedMeasureUnitId)||""}_updateVisibility(){const e=this.isEnabled();this._currencyAndUnitLabelsWrapper.classList.toggle("js-hidden",!e)}}async function st(e,t,s,o){ const{UnitConversionRenderer:r}=await Promise.all([i.e(62253),i.e(22666),i.e(92108),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(30006),i.e(38669),i.e(5145),i.e(25190),i.e(46036),i.e(90684),i.e(40866),i.e(36752),i.e(96025),i.e(17111),i.e(50690),i.e(62526),i.e(32704)]).then(i.bind(i,300203));return new r(e,s,t,o)}var ot=i(470316),rt=i(608415),nt=i(327453),at=i(621618),lt=i(261066),ct=i(480059),ht=i(497754),dt=i.n(ht),ut=i(758035);class _t{constructor({setMode:e,className:t=""}){const s=this._wrapper=document.createElement("div");s.classList.add(t),s.addEventListener("dblclick",this._stopPropagation,{capture:!0}),s.addEventListener("touchstart",this._stopPropagation,{capture:!0});const o=s.appendChild(document.createElement("div"));o.className=ut.priceScaleModeButtons;const[r,n]=this._createButton({title:a.t(null,{context:'The first letter of the "auto" word'},i(9846)),tooltip:a.t(null,void 0,i(550834)),onClick:()=>e("auto"),ariaLabel:xe.PLATFORM_ACCESSIBILITY_ENABLED?a.t(null,void 0,i(974327)):void 0});this._autoScaleButton=n,o.appendChild(r);const[l,c]=this._createButton({title:a.t(null,{context:'The first letter of the "logarithmic" word'},i(655765)),tooltip:a.t(null,void 0,i(512285)),onClick:()=>e("log"),ariaLabel:xe.PLATFORM_ACCESSIBILITY_ENABLED?a.t(null,void 0,i(184112)):void 0});this._logarithmButton=c,o.appendChild(l)}destroy(){this._wrapper.removeEventListener("dblclick",this._stopPropagation),this._wrapper.removeEventListener("touchstart",this._stopPropagation),this._wrapper.remove()}element(){return this._wrapper}width(){return 52}updateMode(e){const{log:t,autoScale:i}=e;this._logarithmButton.classList.toggle(ut.priceScaleModeButtons__button_activated,!!t),this._autoScaleButton.classList.toggle(ut.priceScaleModeButtons__button_activated,!!i)}_createButton(e){const{ariaLabel:t,title:i,tooltip:s,onClick:o,className:r}=e,n=document.createElement("div");n.className=ut.priceScaleModeButtons__buttonWrapper;const a=document.createElement("button");a.className=dt()(ut.priceScaleModeButtons__button,r,"apply-common-tooltip"),a.textContent=i,a.dataset.tooltip=s;let l=a;return h.CheckMobile.any()&&(l=n),l.addEventListener("click",o),t&&l.setAttribute("aria-label",t),n.appendChild(a),[n,a]}_stopPropagation(e){e.stopPropagation()}}i(647184);const pt=new V.TranslatedString("change no overlapping labels",a.t(null,void 0,i(783935))),mt=new V.TranslatedString("toggle auto scale",a.t(null,void 0,i(863060))),gt=new V.TranslatedString("toggle log scale",a.t(null,void 0,i(160166))),St=a.t(null,void 0,i(375633)),vt=a.t(null,void 0,i(194420)),ft=a.t(null,void 0,i(881520)),bt=a.t(null,void 0,i(125933)),yt=a.t(null,void 0,i(417258)),Ct=a.t(null,void 0,i(550834)),wt=a.t(null,{context:"scale_menu"},i(670361)),Pt=a.t(null,{context:"scale_menu"},i(547807)),Tt=a.t(null,{context:"scale_menu"},i(934727)),Mt=a.t(null,{context:"scale_menu"},i(172116)),xt=a.t(null,{context:"scale_menu"},i(19238)),It=a.t(null,{context:"scale_menu"},i(454138));const At=function(e){const t=new nt.LimitedPrecisionNumericFormatter(e);return(e,i)=>(0, T.isNumber)(i)&&!e.isLog()?t.format(i):""}(4),Lt={contextMenuEnabled:!0,currencyConversionEnabled:!1,unitConversionEnabled:!1,countdownEnabled:!0,contextMenu:{general:!0,source:!0},pressedMouseMoveScale:!0,mouseWheelScale:!0,pinchScale:!0,croppedTickMarks:!0};class kt{constructor(e,t,i,o,r,n,a,l,c){this._actions=null,this._priceScale=null,this._scaleModeButtons=null,this._widthCache=new ze.TextWidthCache(1e3),this._color=null,this._fontSize=null,this._currencyFontSize=0,this._currencyLabelWidth=null,this._isVisible=!0,this._currencyMenu=null,this._unitMenu=null,this._size=(0,s.size)({width:0,height:0}),this._currentCursorClassName="",this._destroyed=!1,this._highlighted=!1,this._highlightColorCache=null,this._mouseWheelHelper=null,this._dragScaleActive=!1,this._offset=NaN,this._pinching=!1,this._lastHittestResult=null,this._isHovered=new W.WatchedValue(!1),this._recalcCurrencyAndUnitVisibility=()=>{if(null===this._currencyLabel)return;let e=!0;switch((0,lt.currencyUnitVisibilityProperty)().value()){case"alwaysOff":e=!1;break;case"visibleOnMouseOver":const t=this._chart.anyPriceAxisHovered().value(),i=null!==this._currencyMenu&&this._currencyMenu.isOpened(),s=null!==this._unitMenu&&this._unitMenu.isOpened();e=t||i||s}this._currencyLabel.setHidden(!e)},this._handleAutoLogButtonsVisibilityProperty=e=>{const t=e.value();"alwaysOff"===t?this._scaleModeButtons&&this._destroyScaleModeButtons():(this._scaleModeButtons||this._createScaleModeButtons(),"alwaysOn"===t?(this._isHovered.unsubscribe(this._updatePriceScaleModeButtonsVisibility),this._updatePriceScaleModeButtonsVisibility(!0)):this._isHovered.subscribe(this._updatePriceScaleModeButtonsVisibility,{callWithLast:!0}))},this._updatePriceScaleModeButtonsVisibility=e=>{var t;null===(t=this._scaleModeButtons)||void 0===t||t.element().classList.toggle("price-axis__modeButtons_hidden",!e)},this._updateScaleModeButtons=()=>{var e;this._priceScale&&(null===(e=this._scaleModeButtons)||void 0===e||e.updateMode(this._priceScale.mode()))},this._chart=e,this._pane=t,this._undoModel=i,this._properties=o,this._isLeft="left"===n,this._options=(0,T.merge)((0,T.clone)(Lt),a),this._rendererOptionsProvider=r,this._backgroundBasedTheme=c,this._cell=document.createElement("div"),this._cell.className="price-axis",this._cell.style.width="25px",this._cell.style.left="0",this._canvasConfiguredHandler=()=>{this._undoModel.model().lightUpdate()},this._canvasBinding=(0,U.createBoundCanvas)(this._cell,(0,s.size)({width:16,height:16})),this._canvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const h=this._canvasBinding.canvasElement;h.style.position="absolute",h.style.zIndex="1",h.style.left="0",h.style.top="0",this._topCanvasBinding=(0,U.createBoundCanvas)(this._cell,(0,s.size)({width:16,height:16})),this._topCanvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const d=this._topCanvasBinding.canvasElement;d.style.position="absolute",d.style.zIndex="2",d.style.left="0",d.style.top="0", xe.PLATFORM_ACCESSIBILITY_ENABLED&&this._cell.setAttribute("aria-hidden","true"),this._mouseEventHandler=new Me.MouseEventHandler(this._cell,this,{treatVertTouchDragAsPageScroll:!1,treatHorzTouchDragAsPageScroll:!0}),this._options.currencyConversionEnabled||this._options.unitConversionEnabled?(this._currencyLabel=new it,this._cell.appendChild(this._currencyLabel.element())):this._currencyLabel=null,this._properties.childs().fontSize.subscribe(this,this._onFontSizeChanged),this._options.mouseWheelScale&&(this._mouseWheelHelper=new we,this._cell.addEventListener("wheel",this._onMousewheel.bind(this),{passive:!1})),this._axisInfo=l,this._offset=0,this.restoreDefaultCursor(),(0,lt.currencyUnitVisibilityProperty)().subscribe(this,this._recalcCurrencyAndUnitVisibility),(0,ct.autoLogButtonsVisibilityProperty)().subscribe(this,this._handleAutoLogButtonsVisibilityProperty),this._handleAutoLogButtonsVisibilityProperty((0,ct.autoLogButtonsVisibilityProperty)()),this._chart.anyPriceAxisHovered().subscribe(this._recalcCurrencyAndUnitVisibility,{callWithLast:!0}),this.update()}getContextMenuActions(){var e;this._initActions();const t=(0,r.ensureNotNull)(this._actions),i=this._chart.actions(),s=[];return(null===(e=this._priceScale)||void 0===e?void 0:e.resetScaleAvailable().value())&&s.push(t.reset,new F.Separator),s.push(this._autoScaleAction()),this._isMainSeriesAxis()&&s.push(this._lockScaleAction()),s.push(i.scaleSeriesOnly,this._invertAction(),new F.Separator,this._regularScaleAction(),this._percentageAction(),this._indexedTo100Action(),this._logAction(),new F.Separator),h.CheckMobile.any()||(s.push(this._createMergeScalesAction()),s.push(new F.Separator)),B.enabled("fundamental_widget")||s.push(new F.Action({actionId:"Chart.PriceScale.Labels",options:{label:vt,subItems:[i.showSymbolLabelsAction,i.showSeriesLastValue,i.showSeriesPrevCloseValue,i.showPrePostMarketPriceLabel,i.showHighLowPriceLabels,B.enabled("show_average_close_price_line_and_label")?i.showAverageClosePriceLabel:null,this._undoModel.model().hasCustomSource("bidask")&&i.showBidAskLabels,i.showStudyPlotNamesAction,i.showStudyLastValue,t.alignLabels].filter(Boolean)}})),s.push((0,at.createLinesAction)(this._chart)),this._options.countdownEnabled&&s.push(i.showCountdown),this._undoModel.crossHairSource().isMenuEnabled()&&s.push(i.addPlusButton),!(0,h.onWidget)()&&B.enabled("show_chart_property_page")&&B.enabled("chart_property_page_scales")&&i.scalesProperties&&s.push(new F.Separator,i.scalesProperties),s}getElement(){return this._cell}onOptimalWidthNeedToBeRecalculated(e){(this._size.width1e-14){const n=o.formatPrice(Math.floor(Math.min(e,i))+.11111111111111,r),a=o.formatPrice(Math.ceil(Math.max(e,i))-.11111111111111,r);s=Math.max(s,this._widthCache.measureText(t,n),this._widthCache.measureText(t,a))}}}let n=0;this._isCurrencyLabelEnabled()&&(null===this._currencyLabelWidth&&(this._currencyLabelWidth=(0,r.ensureNotNull)(this._currencyLabel).width()),n=Math.round(this._currencyLabelWidth));const a=s||34;let l=Math.max(n,null!==(i=null===(t=this._scaleModeButtons)||void 0===t?void 0:t.width())&&void 0!==i?i:0,Math.ceil(o.borderSize+o.additionalPaddingInner+o.paddingInner+o.paddingOuter+a+4));return l+=l%2,l}setSizeAndOffset(e,t){(0,s.equalSizes)(this._size,e)||(this._size=e,this._canvasBinding.resizeCanvasElement(e),this._topCanvasBinding.resizeCanvasElement(e),this._cell.style.width=e.width+"px",this._cell.style.height=e.height+"px",this._cell.style.minWidth=e.width+"px"),this._offset!==t&&(this._offset=t,this._cell.style.left=t+"px")}getWidth(){return this._size.width}getImage(){const e=this._size,t=(0,U.createDisconnectedCanvas)(document,e);return(0,U.getPrescaledContext2D)(t).drawImage(this._canvasBinding.canvasElement,0,0,e.width,e.height),null===this._currencyLabel||this._currencyLabel.isHidden()||this._currencyLabel.drawLabel((0,U.getContext2D)(t),e.width,(0,pe.getCanvasDevicePixelRatio)(t)),t}update(){null!==this._priceScale&&(this._priceScale.marks(),this._updateCurrencyLabelFont(),this.rendererOptions())}paint(e){if(!this._isVisible||0===this._size.width||0===this._size.height)return;if(e===me.InvalidationLevel.None)return;const t=this._pane.state(),i=!t.maximized().value()&&t.collapsed().value(),s=this._pane.hasState();(0,U.tryApplySuggestedCanvasBitmapSize)(this._canvasBinding),(0,U.tryApplySuggestedCanvasBitmapSize)(this._topCanvasBinding);const o=this._groupedSources(),n=null!==this._currencyLabel&&!this._currencyLabel.isHidden(),a=(e,t,i)=>{if(n){e.save(),e.beginPath();const i=(0,r.ensureNotNull)(this._currencyLabel).labelBottom();e.rect(0,i*t,this._size.width*t,this._size.height*t),e.clip()}i(),n&&e.restore()};if(e>me.InvalidationLevel.Cursor){const e=(0,U.getContext2D)(this._canvasBinding.canvasElement),t=(0,U.getBindingPixelRatio)(this._canvasBinding);i||this._alignLabels(),s&&this.updateCurrencyLabel(),this._drawBackground(e,t),a(e,t,(()=>{this._drawDrawingsHighlight(e,t)})),this._drawBorder(e,t),s&&(this._scaleModeButtons&&(this._scaleModeButtons.element().style.background=this._highlighted?this._highlightColor():this.backgroundColor()),i||a(e,t,(()=>{this._drawTickMarks(e,t),this._drawLabels(this._views(0,o),e,t)})))}if(s&&!i){const e=(0, U.getContext2D)(this._topCanvasBinding.canvasElement),t=(0,U.getBindingPixelRatio)(this._topCanvasBinding);e.clearRect(0,0,Math.ceil(this._size.width*t)+1,Math.ceil(this._size.height*t)+1),a(e,t,(()=>{this._drawLabels(this._views(1,o),e,t),this._drawCrossHairLabel(e,t)}))}}restoreDefaultCursor(){this._setCursor("")}priceScale(){return(0,r.ensureNotNull)(this._priceScale)}setPriceScale(e){this._priceScale!==e&&(null!==this._priceScale&&(this._priceScale.onMarksChanged().unsubscribe(this,this.onOptimalWidthNeedToBeRecalculated),this._priceScale.modeChanged().unsubscribeAll(this)),this._priceScale=e,null!==e&&(e.onMarksChanged().subscribe(this,this.onOptimalWidthNeedToBeRecalculated),e.modeChanged().subscribe(this,(()=>this.onOptimalWidthNeedToBeRecalculated(!0))),this.onOptimalWidthNeedToBeRecalculated(),this._scaleModeButtons&&(e.modeChanged().subscribe(this,this._updateScaleModeButtons),this._updateScaleModeButtons())))}isVisible(){return this._isVisible}setVisible(e){(e=!!e)!==this._isVisible&&(this._cell.style.display=e?"table-cell":"none",this._isVisible=e)}destroy(){null!==this._currencyMenu&&(this._currencyMenu.close(),this._currencyMenu=null),null!==this._unitMenu&&(this._unitMenu.close(),this._unitMenu=null),this._topCanvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._topCanvasBinding.dispose(),this._canvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._canvasBinding.dispose(),null!==this._priceScale&&(this._priceScale.onMarksChanged().unsubscribe(this,this.onOptimalWidthNeedToBeRecalculated),this._priceScale.modeChanged().unsubscribeAll(this)),this._priceScale=null,this._mouseEventHandler.destroy(),this._properties.childs().fontSize.unsubscribe(this,this._onFontSizeChanged),null!==this._actions&&this._actions.reset&&this._actions.reset.destroy(),(0,lt.currencyUnitVisibilityProperty)().unsubscribeAll(this),this._chart.anyPriceAxisHovered().unsubscribe(this._recalcCurrencyAndUnitVisibility),(0,ct.autoLogButtonsVisibilityProperty)().unsubscribeAll(this),this._chart.setPriceAxisHovered(this,!1),this._destroyScaleModeButtons(),this._destroyed=!0}axisInfo(){return this._axisInfo}setHighlighted(e){this._highlighted=e}backgroundColor(){return this._pane.state().model().backgroundColor().value()}backgroundTopColor(){return this._pane.state().model().backgroundTopColor().value()}lineColor(){return this._properties.childs().lineColor.value()}textColor(){return this._properties.childs().textColor.value()}fontSize(){return this._properties.childs().fontSize.value()}baseFont(){return(0,He.makeFont)(this.fontSize(),qe.CHART_FONT_FAMILY,"")}rendererOptions(){let e=this._rendererOptionsProvider.options();return this._color===e.color&&this._fontSize===e.fontSize||(this._color=e.color),this._fontSize!==e.fontSize&&(this._widthCache.reset(),this._fontSize=e.fontSize,this._currencyLabelWidth=null,this._currencyFontSize=0,this._updateCurrencyLabelFont(),this.onOptimalWidthNeedToBeRecalculated()),this._hasAlertLabel()&&(e=Object.assign({},e,{ paddingInner:Math.max(e.paddingInner,Qe.ALERT_LABEL_WIDTH)})),e}mouseEnterEvent(e){this._chart.setPriceAxisHovered(this,!0),this._isHovered.setValue(!0),this._applyLightUpdateIfRequired(),this._mouseEnterOrTouchStartEvent(e)}mouseMoveEvent(e){this._mouseOrTouchMoveEvent(e)}mouseDownEvent(e){this._mouseDownOrTouchStartEvent(e)}touchStartEvent(e){this._mouseOrTouchMoveEvent(e),this._mouseEnterOrTouchStartEvent(e),this._mouseDownOrTouchStartEvent(e)}pressedMouseMoveEvent(e){this._pressedMouseOrTouchMoveEvent(e)}touchMoveEvent(e){this._pressedMouseOrTouchMoveEvent(e)}pinchStartEvent(e,t,i,s){return s.bothPointsOnTargetElement}pinchEvent(e,t,i){if(this._zoomAvailable()&&this._options.pinchScale){if(this._dragScaleActive&&this._finishScale(),!this._pinching)return this._pinching=!0,void this._undoModel.startTwoPointsScalePrice(this._pane.state(),this.priceScale(),t.y,i.y);this._undoModel.twoPointsScalePriceTo(this._pane.state(),this.priceScale(),t.y,i.y)}}pinchEndEvent(){this._pinching=!1,this._undoModel.endTwoPointsScalePrice(this._pane.state(),this.priceScale())}mouseDownOutsideEvent(){this._finishScale()}touchStartOutsideEvent(){this._finishScale()}mouseUpEvent(e){this._mouseUpOrTouchEndEvent(e)}touchEndEvent(e){this._mouseLeaveOrTouchEndEvent(e),this._mouseUpOrTouchEndEvent(e)}mouseClickEvent(e){this._mouseClickOrTapEvent(e)}tapEvent(e){this._mouseClickOrTapEvent(e)}mouseLeaveEvent(e){this._chart.setPriceAxisHovered(this,!1),this._isHovered.setValue(!1),this._applyLightUpdateIfRequired(),this._mouseLeaveOrTouchEndEvent(e)}mouseDoubleClickEvent(e){this._mouseDoubleClickOrDoubleTapEvent(e)}doubleTapEvent(e){this._mouseDoubleClickOrDoubleTapEvent(e)}contextMenuEvent(e){this._contextMenuOrTouchContextMenuEvent(e)}touchContextMenuEvent(e){this._contextMenuOrTouchContextMenuEvent(e)}dataSourceAtPoint(e,t){const i=this._pane.state();if(!i.maximized().value()&&i.collapsed().value())return null;const s=this._groupedSources(),o=[...s.sources,...s.topLevelSources,...i.customSources()];let r=null,n=null;if(!this._priceScale)return null;const a=(e,t)=>{var i;const s=null!==(i=null==n?void 0:n.target())&&void 0!==i?i:0;e.target()>s&&(n=e,r=t)},l=new Ee.Point(e,t);for(let e=o.length-1;e>=0;--e){const t=o[e],s=t.priceAxisViews(i,this._priceScale);if(s&&0!==s.length)for(let e=s.length-1;e>=0;--e){const i=s[e].renderer();if(void 0!==i.hitTest){const e=i.hitTest(l,this._size.width,this._isLeft?"left":"right");null!==e&&a(e,t)}}}return this._lastHittestResult=n,r}reset(){const e=this._pane.state(),t=this.priceScale();this._undoModel.resetPriceScale(e,t),this.onOptimalWidthNeedToBeRecalculated(!0)}updateCurrencyLabel(){if(null===this._currencyLabel)return;let e=!1;if(this._options.currencyConversionEnabled){const t=this.priceScale().currency(this._undoModel.model().availableCurrencies());null===t||"alwaysOff"===(0,lt.currencyUnitVisibilityProperty)().value()?(e=this._currencyLabel.currencyLabelEnabled(),this._currencyLabel.disableCurrency()):(e=!this._currencyLabel.currencyLabelEnabled(),this._currencyLabel.enableCurrency(), e=this._currencyLabel.setCurrencyInfo(t)||e)}else this._currencyLabel.disableCurrency();if(this._options.unitConversionEnabled){const t="alwaysOff"===(0,lt.currencyUnitVisibilityProperty)().value(),i=this._undoModel.model().availableUnits(),s=this.priceScale().unit(i);null===s||t?(e=e||this._currencyLabel.unitLabelEnabled(),this._currencyLabel.disableUnit()):(e=e||!this._currencyLabel.unitLabelEnabled(),this._currencyLabel.enableUnit(),e=this._currencyLabel.setUnitInfo(s)||e);const o=this.priceScale().measureUnitId(i);null===o||t?(e=e||this._currencyLabel.measureUnitIdLableEnabled(),this._currencyLabel.disableMeasureUnitId()):(e=e||!this._currencyLabel.measureUnitIdLableEnabled(),this._currencyLabel.enableMeasureUnitId(),e=this._currencyLabel.setMeasureUnitIdInfo(o)||e)}else this._currencyLabel.disableUnit(),this._currencyLabel.disableMeasureUnitId();this._updateCurrencyLabelFont(),e&&(this._currencyLabelWidth=null)}_groupedSources(){var e;const t=this._pane.state(),i=t.model(),s=this._pane.state().sourcesByGroup(),o=this._isLeft?s.leftPriceScalesSources():s.rightPriceScalesSources(),r=this._priceScale===t.defaultPriceScale(),n=new Set(t.customSources()),a=e=>!!n.has(e)||(e.priceScale()===this._priceScale||r&&t.isOverlay(e)),l={sources:[...o.filter(a),...t.customSources()],topLevelSources:new Set};if(r){const e=this._pane.state().dataSources();for(const i of e)t.isOverlay(i)&&l.sources.push(i)}const c=null!==(e=i.lineBeingEdited())&&void 0!==e?e:i.lineBeingCreated();c&&a(c)&&(l.topLevelSources.add(c),l.lineBeingEditedOrCreated=c);const h=i.customSourceBeingMoved();h&&a(h)&&(l.topLevelSources.add(h),l.customSourceBeingMoved=h);const d=i.sourcesBeingMoved().filter(a);d.length>0&&(i.sourcesBeingMoved().forEach((e=>l.topLevelSources.add(e))),l.sourcesBeingMoved=d);const u=i.selection().allSources().filter(a);u.length>0&&(u.forEach((e=>l.topLevelSources.add(e))),l.selectedSources=u);const _=i.hoveredSource();return _&&a(_)&&(l.topLevelSources.add(_),l.hoveredSource=_),l}_isCurrencyLabelEnabled(){return null!==this._currencyLabel&&this._currencyLabel.isEnabled()}_updateCurrencyLabelFont(){if(null===this._currencyLabel)return;const e=this.fontSize();e!==this._currencyFontSize&&(this._currencyLabel.setFontSize(e),this._currencyFontSize=e,this._currencyLabelWidth=null,this.onOptimalWidthNeedToBeRecalculated())}_alignLabels(){var e,t,i,s,o;const r=this._size.height;let n=r/2;const a=[],l=this.priceScale(),c=l.orderedSources().slice(),h=this._pane.state(),d=this.rendererOptions();if(l===h.defaultPriceScale()){const e=h.priceDataSources();for(let t=0;t{if(e.ignoreAlignment()||!e.isVisible())return!1;const{total:t}=e.topBottomTotalHeight(d),i=e.floatCoordinate();return i>-t&&ie.floatCoordinate()<=n)),p=a.filter((e=>e.floatCoordinate()>n));_.sort(((e,t)=>t.floatCoordinate()-e.floatCoordinate())),_.length>0&&p.length>0&&p.push(_[0]),p.sort(((e,t)=>e.floatCoordinate()-t.floatCoordinate()));for(const e of a)e.setFixedCoordinate(e.coordinate());if(l.properties().childs().alignLabels.value()){if(p.length>0||_.length>0){{const e=null!==(s=_[0])&&void 0!==s?s:p[0],t=e.getFixedCoordinate(),{top:i,bottom:o,total:n}=e.topBottomTotalHeight(d);n0&&e.setFixedCoordinate(i)}{const e=null!==(o=p[0])&&void 0!==o?o:_[0],t=e.getFixedCoordinate(),{top:i,bottom:s,total:n}=e.topBottomTotalHeight(d);nr&&e.setFixedCoordinate(r-s)}}for(let e=1;e<_.length;e++){const t=_[e],i=_[e-1],{top:s,bottom:o,total:r}=t.topBottomTotalHeight(d),n=t.getFixedCoordinate(),a=i.getFixedCoordinate();if(n>a-r)t.setFixedCoordinate(a-r);else if(a>0&&n-s<0&&n+o>0){const{top:e}=i.topBottomTotalHeight(d);t.setFixedCoordinate(Math.min(a-e-o,s))}}for(let e=1;er&&t.setFixedCoordinate(Math.max(a+s+e,r-i))}}}}_drawTickMarks(e,t){const i=this.priceScale().marks();e.save(),e.font=this.baseFont();const s=this.rendererOptions(),o=this._isLeft?Math.floor((this._size.width-s.additionalPaddingInner)*t):0,n=this._isLeft?Math.round(o-s.paddingInner*t):Math.round(o+(s.additionalPaddingInner+s.paddingInner)*t),a=this.fontSize(),l=this._isCurrencyLabelEnabled()?(0,r.ensureNotNull)(this._currencyLabel).labelBottom():0,c=i.map((t=>{if(this._options.croppedTickMarks)return{visible:!0,yCorrection:this._widthCache.yMidCorrection(e,t.label)};const i=t.coord-a/2,s=t.coord+a/2,o=!(s>this._size.height||ithis._size.height||i{for(let s=i.length;s--;){if(!c[s].visible)continue;const o=i[s];e.fillText(o.label,n/t,o.coord+c[s].yCorrection)}})),e.restore()}_hasAlertLabel(){return this.priceScale().dataSources().some((e=>(0,Qe.isAlertLabel)(e)))}async _showCurrenciesContextMenu(){var e;if(null!==this._currencyMenu&&this._currencyMenu.isOpened())return void this._currencyMenu.close();(0,_.trackEvent)("GUI","Currency conversion");const{currencyActions:t}=await Promise.all([i.e(62253),i.e(22666),i.e(92108),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(30006),i.e(38669),i.e(5145),i.e(25190),i.e(46036),i.e(90684),i.e(40866),i.e(36752),i.e(96025),i.e(17111),i.e(50690),i.e(62526),i.e(32704)]).then(i.bind(i,87423)),s=await st(ft,(()=>t(this._undoModel,(0,r.ensureNotNull)(this._currencyLabel).currencyInfo(),this.priceScale())),(0,r.ensureNotNull)(this._currencyLabel).currencyLabelElement(),(()=>{var e;this._recalcCurrencyAndUnitVisibility(), null===(e=this._currencyLabel)||void 0===e||e.setCurrencyExpanded(!1)}));null===(e=this._currencyLabel)||void 0===e||e.setCurrencyExpanded(!0),this._destroyed?s.close():this._currencyMenu=s}async _showUnitsContextMenu(){var e;if(null!==this._unitMenu&&this._unitMenu.isOpened())return void this._unitMenu.close();(0,_.trackEvent)("GUI","Unit conversion");const{unitActions:t}=await Promise.all([i.e(62253),i.e(22666),i.e(92108),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(30006),i.e(38669),i.e(5145),i.e(25190),i.e(46036),i.e(90684),i.e(40866),i.e(36752),i.e(96025),i.e(17111),i.e(50690),i.e(62526),i.e(32704)]).then(i.bind(i,63189)),s=await st(bt,(()=>t(this._undoModel,(0,r.ensureNotNull)(this._currencyLabel).unitInfo(),this.priceScale())),(0,r.ensureNotNull)(this._currencyLabel).unitLabelElement(),(()=>{var e;this._recalcCurrencyAndUnitVisibility(),null===(e=this._currencyLabel)||void 0===e||e.setUnitExpanded(!1)}));null===(e=this._currencyLabel)||void 0===e||e.setUnitExpanded(!0),this._destroyed?s.close():this._unitMenu=s}_onFontSizeChanged(){this._currencyLabelWidth=null,this._currencyFontSize=0,this._updateCurrencyLabelFont(),this.onOptimalWidthNeedToBeRecalculated()}_mouseOrTouchMoveEvent(e){var t,i,s,o;if(!this._priceScale)return;if(e.localX<0||e.localY<0||e.localX>=this._size.width||e.localY>=this._size.height)return;let r=!0;const n=this.dataSourceAtPoint(e.localX,e.localY);n?(this._setCursorClassName("pointer"),(null===(i=null===(t=this._lastHittestResult)||void 0===t?void 0:t.data())||void 0===i?void 0:i.hoverModelFromAxis)&&(this._undoModel.model().setHoveredSource(n,null!==(o=null===(s=this._lastHittestResult)||void 0===s?void 0:s.data())&&void 0!==o?o:null),r=!1)):this._setResizeCursor(),r&&this._undoModel.model().setHoveredSource(null,null)}_mouseDownOrTouchStartEvent(e){this._zoomAvailable()&&this._options.pressedMouseMoveScale&&!this._pinching&&(this._dragScaleActive=!0,this._undoModel.startScalePrice(this._pane.state(),this.priceScale(),e.localY))}_mouseEnterOrTouchStartEvent(e){this._setResizeCursor()}_pressedMouseOrTouchMoveEvent(e){if(this._dragScaleActive){const t=this.priceScale();this._undoModel.scalePriceTo(this._pane.state(),t,e.localY)}}_mouseUpOrTouchEndEvent(e){this._finishScale()}_finishScale(){this._dragScaleActive&&(this._undoModel.endScalePrice(this._pane.state(),this.priceScale()),this.restoreDefaultCursor(),this._dragScaleActive=!1)}_mouseClickOrTapEvent(e){if(this._currencyLabel){if(this._currencyLabel.currencyConversionAvailable()&&this._currencyLabel.currencyLabelElement().contains(e.target))return this._showCurrenciesContextMenu(),void e.preventDefault();if(this._currencyLabel.unitConversionAvailable()&&this._currencyLabel.unitLabelElement().contains(e.target))return this._showUnitsContextMenu(),void e.preventDefault()}const t=this.dataSourceAtPoint(e.localX,e.localY);t&&this._undoModel.selectionMacro((e=>{var i,s,o;e.selection().isSelected(t)&&this._undoModel.model().lastSelectedHittestData()===(null===(i=this._lastHittestResult)||void 0===i?void 0:i.data())||(e.clearSelection(), e.addSourceToSelection(t,null!==(o=null===(s=this._lastHittestResult)||void 0===s?void 0:s.data())&&void 0!==o?o:null))}))}_mouseLeaveOrTouchEndEvent(e){this._setCursorClassName("")}_mouseDoubleClickOrDoubleTapEvent(e){var t,i,s;if((null===(t=this._currencyLabel)||void 0===t?void 0:t.currencyLabelElement().contains(e.target))||(null===(i=this._currencyLabel)||void 0===i?void 0:i.unitLabelElement().contains(e.target)))return;const o=this.dataSourceAtPoint(e.localX,e.localY);o?this._pane.processDoubleClickOnSource(o,null!==(s=this._lastHittestResult)&&void 0!==s?s:void 0,{origin:"price_scale"}):(this.reset(),(0,_.trackEvent)("GUI","Double click price scale"))}_contextMenuOrTouchContextMenuEvent(e){if(this._options.contextMenuEnabled){const t=this.dataSourceAtPoint(e.localX,e.localY);if(null!==t&&this._options.contextMenu.source){return void this._undoModel.model().selectionMacro((i=>{i.selection().isSelected(t)||(i.clearSelection(),i.addSourceToSelection(t)),this._pane.showContextMenuForSelection(e,{origin:"price_scale"})}))}this._options.contextMenu.general&&Ue.ContextMenuManager.showMenu(this.getContextMenuActions(),e,{statName:"PriceScaleContextMenu"},{menuName:"PriceScaleContextMenu"})}}_setResizeCursor(){const e=this.priceScale();e.isPercentage()||e.isIndexedTo100()?this._setCursorClassName(""):this._zoomAvailable()&&(this._options.pressedMouseMoveScale||this._options.mouseWheelScale)&&this._setCursorClassName("ns-resize")}_setCursorClassName(e){let t="";e&&(t="price-axis--cursor-"+e),this._currentCursorClassName!==t&&(this._currentCursorClassName&&this._cell.classList.remove(this._currentCursorClassName),t&&this._cell.classList.add(t),this._currentCursorClassName=t)}_zoomAvailable(){return!this.priceScale().isEmpty()&&this._undoModel.model().zoomEnabled()}_onMousewheel(e){if(!this._zoomAvailable()||!this._options.mouseWheelScale)return;const t=(0,r.ensureNotNull)(this._mouseWheelHelper).processWheel(e).deltaY;if(0===t)return;e.cancelable&&e.preventDefault();const i=this._undoModel,s=this._pane.state(),o=this.priceScale(),n=this._cell.getBoundingClientRect(),a=e.clientY-n.top,l=a+15*t;i.startScalePrice(s,this.priceScale(),a,!0),i.scalePriceTo(s,o,l),i.endScalePrice(s,o),e.stopPropagation()}_drawCrossHairLabel(e,t){const i=this._pane.state(),s=i.model(),o=this.priceScale(),r=s.crossHairSource().priceAxisViews(i,o);r&&r.length>0&&this._drawLabels(r,e,t)}_drawBackground(e,t){const i=Math.ceil(this._size.width*t),s=Math.ceil(this._size.height*t),o=this.backgroundTopColor(),r=this.backgroundColor();if(o===r?(0,U.clearRect)(e,0,0,i+1,s+1,this.backgroundColor()):(0,Fe.clearRectWithGradient)(e,0,0,i+1,s+1,o,r),this._highlighted){e.globalAlpha=.5;const t=u.themes[this._backgroundBasedTheme.value()].getThemedColor("color-price-axis-highlight");(0,U.fillRect)(e,0,0,i+1,s+1,t),e.globalAlpha=1}}_drawDrawingsHighlight(e,t){const i=this._pane.state().model(),s=this.priceScale(),o=i.selection().lineDataSources().filter((e=>e.priceScale()===s)).reduce(((e,t)=>{const i=t.priceAxisPoints();return 0===i.length?e:e.concat(i)}),[]) ;o.length>0&&this._hightlightBackground(e,o,this.priceScale().mainSource(),t);const r=i.crossHairSource();r.startMeasurePoint()&&this._hightlightBackground(e,r.measurePoints(),this.priceScale().mainSource(),t)}_drawBorder(e,t){e.save(),e.fillStyle=this.lineColor();const i=Math.max(1,Math.floor(this.rendererOptions().borderSize*t)),s=this._isLeft?Math.floor(this._size.width*t)-i:0;e.fillRect(s,0,i,Math.ceil(this._size.height*t)+1),e.restore()}_drawLabels(e,t,i){const s=this.rendererOptions(),o=this._isLeft?"right":"left";for(const r of e)r.isAxisLabelVisible()&&(t.save(),r.renderer().draw(t,s,this._widthCache,this._size.width,this._size.height,o,i),t.restore())}_hightlightBackground(e,t,i,s){if(!i)return;const o=i.firstValue();if(null===o)return;let r=t[0].price,n=t[0].price;for(let e=1;e=r&&(r=e,a=i),e<=t&&(t=e,n=i)}}return a&&n?[a,n]:[]}}_views(e,t){var i,s;const o=this._pane.state(),r=this.priceScale(),n=[];if(1!==e)for(const e of t.sources)t.topLevelSources.has(e)||n.push(...null!==(i=e.priceAxisViews(o,r))&&void 0!==i?i:[]);if(0!==e){const e=new Set,i=t=>!e.has(t),a=t=>{const s=t.filter(i);n.push(...this._viewsOrMaxMinViews(s));for(const t of s)e.add(t)};t.customSourceBeingMoved&&a([t.customSourceBeingMoved]),t.sourcesBeingMoved&&a(t.sourcesBeingMoved),t.selectedSources&&a(t.selectedSources),t.hoveredSource&&a([t.hoveredSource]),t.lineBeingEditedOrCreated&&a([t.lineBeingEditedOrCreated]);for(const e of[...t.sources,...o.customSources()])e.topPriceAxisViews&&n.push(...null!==(s=e.topPriceAxisViews(o,r))&&void 0!==s?s:[])}return n}_initActions(){if(!this._pane.hasState()||null!==this._actions)return;const e=this._undoModel,t=new H.ActionWithStandardIcon({actionId:"Chart.PriceScale.Reset",options:{label:yt,iconId:"Chart.Reset",shortcutHint:(0,ot.humanReadableHash)(ot.Modifiers.Alt+82),statName:"ResetScale",onExecute:()=>this.reset()}}),i=new F.Action({actionId:"Chart.PriceScale.ToggleAutoScale",options:{label:Ct,checkable:!0,checked:!0,statName:"ToggleAutoScale",onExecute:()=>{e.togglePriceScaleAutoScaleMode(this.priceScale()),this._updateScalesActions()}}}),s=new F.Action({actionId:"Chart.PriceScale.TogglePercentage",options:{label:wt,checkable:!0,checked:this.priceScale().isPercentage(),statName:"TogglePercantage",onExecute:()=>{e.togglePriceScalePercentageScaleMode(this.priceScale()),this._updateScalesActions()}}}),o=new F.Action({actionId:"Chart.PriceScale.ToggleIndexedTo100",options:{label:Pt, checkable:!0,checked:this.priceScale().isIndexedTo100(),statName:"ToggleIndexedTo100",onExecute:()=>{e.togglePriceScaleIndexedTo100ScaleMode(this.priceScale()),this._updateScalesActions()}}}),r=new F.Action({actionId:"Chart.PriceScale.ToggleLogarithmic",options:{label:Tt,checkable:!0,checked:this.priceScale().isLog(),statName:"ToggleLogScale",onExecute:()=>{e.togglePriceScaleLogScaleMode(this.priceScale()),this._updateScalesActions()}}}),n=new F.Action({actionId:"Chart.PriceScale.ToggleRegular",options:{label:Mt,checkable:!0,checked:this.priceScale().isRegular(),statName:"ToggleRegularScale",onExecute:()=>{e.setPriceScaleRegularScaleMode(this.priceScale()),this._updateScalesActions()}}}),a=new F.Action({actionId:"Chart.PriceScale.Labels.ToggleNoOverlappingLabelsVisibility",options:{label:xt,checkable:!0,checked:this.priceScale().properties().childs().alignLabels.value(),statName:"TogglePreciseLabels"}});a.setBinding(new rt.ActionBinder(a,this.priceScale().properties().childs().alignLabels,e,pt));const l=new F.Action({actionId:"Chart.PriceScale.ToggleInvertScale",options:{label:It,checkable:!0,checked:this.priceScale().isInverted(),statName:"Invert Scale",onExecute:()=>{e.invertPriceScale(this.priceScale()),this._updateScalesActions()}}});this._actions={reset:t,setAutoScale:i,setPercentage:s,setIndexedTo100:o,setLog:r,setRegular:n,alignLabels:a,invertScale:l},this._updateScalesActions()}_logAction(){return this._isMainSeriesAxis()?this._chart.actions().logSeriesScale:(0,r.ensureNotNull)(this._actions).setLog}_percentageAction(){return this._isMainSeriesAxis()?this._chart.actions().percentSeriesScale:(0,r.ensureNotNull)(this._actions).setPercentage}_indexedTo100Action(){return this._isMainSeriesAxis()?this._chart.actions().indexedTo100SeriesScale:(0,r.ensureNotNull)(this._actions).setIndexedTo100}_autoScaleAction(){return this._isMainSeriesAxis()?this._chart.actions().autoSeriesScale:(0,r.ensureNotNull)(this._actions).setAutoScale}_regularScaleAction(){return this._isMainSeriesAxis()?this._chart.actions().regularSeriesScale:(0,r.ensureNotNull)(this._actions).setRegular}_lockScaleAction(){const e=this._chart.actions().lockSeriesScale,t=At(this.priceScale(),this._undoModel.model().mainSeriesScaleRatio());return e.update({hint:t}),e}_invertAction(){return this._isMainSeriesAxis()?this._chart.actions().invertSeriesScale:(0,r.ensureNotNull)(this._actions).invertScale}_isMainSeriesAxis(){return this.priceScale().hasMainSeries()}_updateScalesActions(){const e=this.priceScale(),t=this._isMainSeriesAxis(),i=(0,r.ensureNotNull)(e.mainSource()).properties(),s=t&&e.isLockScale(),o=t&&6===i.style.value(),n=(0,r.ensureNotNull)(this._actions);n.setRegular.update({checked:e.isRegular(),disabled:s||o}),n.setPercentage.update({checked:e.isPercentage(),disabled:s||o}),n.setIndexedTo100.update({checked:e.isIndexedTo100(),disabled:s||o}),n.setLog.update({checked:e.isLog(),disabled:s||o}),n.setAutoScale.update({checked:e.isAutoScale(),disabled:e.properties().childs().autoScaleDisabled.value()})}_createMergeScalesAction(){ const e=this._chart.actions(),t=this._undoModel.model().priceScaleSlotsCount();if(t.left+t.right===1)return 0===t.left?e.moveScaleToLeft:e.moveScaleToRight;const i=[];return i.push(e.mergeLeftScalesAction),i.push(e.mergeRightScalesAction),new F.Action({actionId:"Chart.PriceScale.MergeAllScales",options:{label:St,subItems:i}})}_setCursor(e){let t="";"grabbing"!==e&&"ns-resize"!==e||(t="price-axis--cursor-"+e),this._currentCursorClassName!==t&&(this._currentCursorClassName&&this._cell.classList.remove(this._currentCursorClassName),t&&this._cell.classList.add(t),this._currentCursorClassName=t,this._cell.style.cursor)}_createScaleModeButtons(){var e;const t=this._scaleModeButtons=new _t({className:"price-axis__modeButtons",setMode:e=>{this._priceScale&&("log"===e?this._chart.model().setPriceScaleMode({log:!this._priceScale.isLog()},this._priceScale,gt):this._chart.model().setPriceScaleMode({autoScale:!this._priceScale.isAutoScale()},this._priceScale,mt))}});return t.element().style.background=this.backgroundColor(),this._cell.appendChild(t.element()),null===(e=this._priceScale)||void 0===e||e.modeChanged().subscribe(this,this._updateScaleModeButtons),this._updateScaleModeButtons(),t}_destroyScaleModeButtons(){var e;this._scaleModeButtons&&(this._isHovered.unsubscribe(this._updatePriceScaleModeButtonsVisibility),null===(e=this._priceScale)||void 0===e||e.modeChanged().unsubscribe(this,this._updateScaleModeButtons),this._scaleModeButtons.destroy(),this._scaleModeButtons=null)}_highlightColor(){const e=this.backgroundColor(),t=this._backgroundBasedTheme.value();if(null===this._highlightColorCache||this._highlightColorCache.backgroundColor!==e||this._highlightColorCache.theme!==t){const i=(0,p.applyTransparency)(u.themes[this._backgroundBasedTheme.value()].getThemedColor("color-price-axis-highlight"),50),s=(0,Pe.rgbaToString)((0,Pe.blendRgba)((0,Pe.parseRgba)(this.backgroundColor()),(0,Pe.parseRgba)(i)));this._highlightColorCache={theme:t,backgroundColor:e,resultColor:s}}return this._highlightColorCache.resultColor}_applyLightUpdateIfRequired(){"visibleOnMouseOver"===(0,lt.currencyUnitVisibilityProperty)().value()&&this._undoModel.model().lightUpdate()}}var Et=i(104415),Dt=i(89820),Nt=i(371764),Bt=i(547871),Rt=i(974655),Ot=i(558793),Vt=i(606097),Wt=i(779196),Ft=i(458527),Ht=i(616117),zt=i(147354),Ut=i(673747),Gt=i(451798);function qt(e){return"startMoving"in e&&"move"in e&&"endMoving"in e&&"convertYCoordinateToPriceForMoving"in e}var jt=i(440617),Yt=i(731042),Kt=i(964824),Zt=i(871332);i(784516);const $t=parseInt(Zt["css-value-pane-controls-padding-left"]),Xt=parseInt(Zt["css-value-pane-controls-padding-right"]),Jt=(0,re.getHexColorByName)("color-cold-gray-700"),Qt=(0,re.getHexColorByName)("color-cold-gray-400");let ei;Wt.performanceTestMode&&(async()=>{ei=await i.e(6316).then(i.bind(i,122331))})();const ti=new V.TranslatedString("scroll",a.t(null,void 0,i(468193))),ii=a.t(null,void 0,i(482232)),si=a.t(null,void 0,i(398478));function oi(e,t,i){e.drawBackground&&e.drawBackground(t,i)}function ri(e,t,i){e.draw(t,i)} function ni(e,t){return e.paneViews(t)}function ai(e,t){var i,s;return null!==(s=null===(i=e.topPaneViews)||void 0===i?void 0:i.call(e))&&void 0!==s?s:[]}function li(e,t){return e.labelPaneViews(t)}function ci(e,t){const i=e.strategyOrdersPaneView();return null===i?null:[i]}function hi(e,t){return null===e||e.source!==t?null:e.hittest.data()}function di(e,t,i,s,o){var r,n;const a=null!==(n=null===(r=e.result)||void 0===r?void 0:r.hittest.target())&&void 0!==n?n:0;t.target()>a&&(e.result={hittest:t,source:i,renderer:s,isCustom:o})}const ui={contextMenuEnabled:!0,contextMenu:at.defaultContextMenuOptions,priceScaleContextMenuEnabled:!0,legendWidgetEnabled:!0,controlsEnabled:!0,propertyPagesEnabled:!0,sourceSelectionEnabled:!0,countdownEnabled:!0},_i=new Map([[Ne.AreaName.Text,"Text"],[Ne.AreaName.Style,"Style"]]),pi=!B.enabled("display_legend_on_all_charts");let mi=null;function gi(e,t){return!(0,Ne.shouldDefaultActionBeExecuted)(e,t,"pressedMouseMoveHandler","touchMoveHandler")}class Si{constructor(e,t,i,o){this._legendWidget=null,this._paneControls=null,this._isDestroyed=!1,this._trackCrosshairOnlyAfterLongTap=(0,ge.lastMouseOrTouchEventInfo)().isTouch,this._startTrackPoint=null,this._exitTrackingModeOnNextTry=!1,this._startMoveSourceParams=null,this._startChangeLineToolParams=null,this._preventSourceChange=!1,this._preventScrollUntilNextMouseDownOrTouchStart=!1,this._clonningAtMoveLineTools=null,this._startCloningPoint=null,this._size=(0,s.size)({width:0,height:0}),this._themedTopColor=null,this._initCrossHairPosition=null,this._firstZoomPoint=null,this._editDialog=null,this._processing=!1,this._pressedMoveStage=0,this._touchMove=!1,this._startTouchPoint=null,this._isSelecting=!1,this._prevHoveredHittest=null,this._contextMenuX=0,this._contextMenuY=0,this._startScrollingPos=null,this._isScrolling=!1,this._scrollPriceScale=null,this._scrollXAnimation=null,this._prevPinchScale=1,this._pinching=!1,this._wasPinched=!1,this._longTap=!1,this._contextMenuOpenedOnLastTap=!1,this._paneControlsResizeObserver=null,this._lastClickedSource=null,this._customLegendWidgetsFactoryMap=new Map,this._prevMoveEventPosition=null,this._onMagnetStateChangedListener=this._onMagnetStateChanged.bind(this),this._onShiftKeyStateChangedListener=this._onShiftKeyStateChanged.bind(this),this._currentCursorClassName="",this._lastFinishedToolId=null,this._needResetMeasureLater=!1,this._currentChangingLineToolHitTest=null,this._currentMovingHitTest=null,this._prevTooltipData=null,this._errorRenderer=null,this._highlightedPriceAxis=new W.WatchedValue({owner:"",axis:null}),this._visuallyCollapsed=new W.WatchedValue(!1),this._endOfSeriesDataBanner=null,this._canvasConfiguredHandler=()=>this._state&&this._chartModel().lightUpdate(),this._updateVisuallyCollapsed=()=>{this._visuallyCollapsed.setValue(!this.state().maximized().value()&&this.state().collapsed().value())},this._chart=e,this._state=t,this._options=(0,T.merge)((0,T.clone)(ui),i),this._paneWidgetsSharedState=o,this._state&&this._subscribeToState();const n={ contextMenuEnabled:this._options.priceScaleContextMenuEnabled,pressedMouseMoveScale:this._options.handleScale.axisPressedMouseMove.price,mouseWheelScale:this._options.handleScale.mouseWheel,currencyConversionEnabled:this._options.currencyConversionEnabled,unitConversionEnabled:this._options.unitConversionEnabled,countdownEnabled:this._options.countdownEnabled,croppedTickMarks:this._options.croppedTickMarks};void 0!==this._options.priceScaleContextMenu&&(n.contextMenu=this._options.priceScaleContextMenu);const a=(e,t,i,s,o)=>new kt(this._chart,this,this._chartUndoModel(),i,t,e,n,s,o),l=e.properties().childs().scalesProperties,c=this._chartModel().rendererOptionsProvider(),h={backgroundBasedTheme:e.backgroundBasedTheme().spawnOwnership(),stubContextMenuProvider:()=>[],titlesProvider:()=>[],rendererOptionsProvider:c,getBackgroundTopColor:()=>this._chartModel().backgroundTopColor().value(),getBackgroundBottomColor:()=>this._chartModel().backgroundColor().value(),requestRepaint:()=>this._chartModel().lightUpdate()},d={showLabels:!1};this._lhsPriceAxisesContainer=new Je(l,"left",a,h,d),this._rhsPriceAxisesContainer=new Je(l,"right",a,h,d),this._paneCell=document.createElement("div"),this._paneCell.classList.add("chart-markup-table","pane"),this._div=document.createElement("div"),this._div.classList.add("chart-gui-wrapper"),this._div.setAttribute("data-name","pane-widget-chart-gui-wrapper"),this._paneCell.appendChild(this._div),this._canvasBinding=(0,U.createBoundCanvas)(this._div,(0,s.size)({width:16,height:16})),this._canvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const u=this._canvasBinding.canvasElement;u.style.position="absolute",u.style.left="0",u.style.top="0",this._topCanvasBinding=(0,U.createBoundCanvas)(this._div,(0,s.size)({width:16,height:16})),this._topCanvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const _=this._topCanvasBinding.canvasElement;if(_.style.position="absolute",_.style.left="0",_.style.top="0",this._rowElement=document.createElement("div"),this._rowElement.style.display="flex",this._rowElement.appendChild(this._lhsPriceAxisesContainer.getElement()),this._rowElement.appendChild(this._paneCell),this._rowElement.appendChild(this._rhsPriceAxisesContainer.getElement()),xe.PLATFORM_ACCESSIBILITY_ENABLED){u.setAttribute("aria-hidden","true");const e=this._chartModel().mainSeries();e.dataEvents().symbolResolved().subscribe(this,this._updateAccesibilityAttr),e.onIntervalChanged().subscribe(this,this._updateAccesibilityAttr),this._updateAccesibilityAttr()}this._options.legendWidgetEnabled&&(this._options.customLegendWidgetFactories&&(this._customLegendWidgetsFactoryMap=this._options.customLegendWidgetFactories),this._loadAndCreateLegendWidget()),this._state&&!this._chart.readOnly()&&this._options.controlsEnabled&&this._loadAndCreatePaneControlsWidget(),(0,Gt.magnetEnabled)().subscribe(this._onMagnetStateChangedListener),(0,G.shiftPressed)().subscribe(this._onShiftKeyStateChangedListener),this._paneCell.addEventListener("dragover",(e=>{ e.dataTransfer&&Array.from(e.dataTransfer.files).some(Vt.blobImageFilter)&&e.preventDefault()})),this._paneCell.addEventListener("drop",(e=>{if(window.user.id&&e.dataTransfer&&this._state){const t=Array.from(e.dataTransfer.files).find(Vt.blobImageFilter);if(t){e.preventDefault();const i=(0,Vt.uploadImage)(t),s=URL.createObjectURL(t);this._chartUndoModel().pasteImageAsLineTool(i,s,this._state),i.catch((e=>{this._chart.chartWidgetCollection().getToasts().then((t=>{(0,r.ensureNotNull)(t).showSimpleToast({title:si,text:e.message,role:"alert",intent:ke.ToastIntent.Warning})}))}))}}})),this.setCursorForTool(),this._mouseEventHandler=new Me.MouseEventHandler(this._topCanvasBinding.canvasElement,this,{treatVertTouchDragAsPageScroll:!this._options.handleScroll.vertTouchDrag,treatHorzTouchDragAsPageScroll:!this._options.handleScroll.horzTouchDrag}),this._prevHoveredHittest=null,this._highlightedPriceAxis.subscribe((e=>this._highlightPriceAxisByLabel(e.axis))),this._prevPinchScale=0,this._isDestroyed=!1}destroy(){var e;if(this._chart.onPaneWidgetDestroyed(this),xe.PLATFORM_ACCESSIBILITY_ENABLED){const e=this._chartModel().mainSeries();e.dataEvents().symbolResolved().unsubscribeAll(this),e.onIntervalChanged().unsubscribeAll(this)}this._customLegendWidgetsFactoryMap.clear(),this._topCanvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._topCanvasBinding.dispose(),this._canvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._canvasBinding.dispose(),this._legendWidget&&(this._legendWidget.destroy(),this._legendWidget=null),null!==this._paneControlsResizeObserver&&this._paneControlsResizeObserver.disconnect(),null!==this._paneControls&&(this._paneControls.destroy(),this._paneControls=null),this._lhsPriceAxisesContainer.destroy(),this._rhsPriceAxisesContainer.destroy(),this.hasState()&&this._unsubscribeFromState(),(0,Gt.magnetEnabled)().unsubscribe(this._onMagnetStateChangedListener),(0,G.shiftPressed)().unsubscribe(this._onShiftKeyStateChangedListener),this._paneWidgetsSharedState.onPaneDestroyed(this),this._errorRenderer&&this._errorRenderer.then((e=>{e.destroy(),this._errorRenderer=null})),this._prevHoveredHittest=null,this._mouseEventHandler.destroy(),null===(e=this._rowElement.parentElement)||void 0===e||e.removeChild(this._rowElement),this._isDestroyed=!0}size(){return this._size}setSize(e){(0,s.equalSizes)(this._size,e)||(this._size=e,this._canvasBinding.resizeCanvasElement(e),this._topCanvasBinding.resizeCanvasElement(e),this._paneCell.style.width=e.width+"px",this._paneCell.style.height=e.height+"px",this._div.style.width=e.width+"px",this._div.style.height=e.height+"px",this._rowElement.classList.toggle("js-hidden",0===e.height),null!==this._legendWidget&&this._legendWidget.updateWidgetModeBySize(e),null!==this._paneControls&&this._paneControls.updateWidgetModeByWidth(e.width))}width(){return this._size.width}height(){return this._size.height}backgroundColor(){return this._chartModel().backgroundColor().value()}highlightedPriceAxis(){ return this._highlightedPriceAxis}processDoubleClickOnSource(e,t,i){if((0,Qe.isAlertLabel)(e)){const t=e.alert(),s=t.id().value();if(t.isNew()||!s)return;(0,Ot.getChartAlertsFacade)().then((e=>{var t;(0,_.trackEvent)("chart_alert","edit",`double_click_on_${null!==(t=null==i?void 0:i.origin)&&void 0!==t?t:"line"}`),e.openEditDialog(s,{actionSource:"alert_label_double_click"})}))}else(0,Oe.isDataSource)(e)&&e.id()!==this._lastFinishedToolId&&this._showEditDialogForSource(e,t)}stretchFactor(){return this._state?this._state.stretchFactor():0}setStretchFactor(e){this.hasState()&&this.state().setStretchFactor(e)}setCursorForTool(e,t,i){if(t&&t.mod()&&e&&e!==this._chartModel().crossHairSource())return void this._setCursorClassName("pointer");if(void 0!==i){switch(i){case zt.PaneCursorType.VerticalResize:this._setCursorClassName("ns-resize");break;case zt.PaneCursorType.HorizontalResize:this._setCursorClassName("ew-resize");break;case zt.PaneCursorType.DiagonalNeSwResize:this._setCursorClassName("nesw-resize");break;case zt.PaneCursorType.DiagonalNwSeResize:this._setCursorClassName("nwse-resize");break;case zt.PaneCursorType.Default:this._setCursorClassName("default");break;case zt.PaneCursorType.Pointer:this._setCursorClassName("pointer");break;case zt.PaneCursorType.Grabbing:this._setCursorClassName("grabbing")}return}const s=Ve.tool.value();if((0,Ve.toolIsCursor)(s)){if(null!==this._paneWidgetsSharedState.draggingSource()||this._isScrolling||this._chartUndoModel()&&this._chartUndoModel().model().sourcesBeingMoved().length)return void this._setCursorClassName("grabbing");if(e&&this._options.sourceSelectionEnabled)return void this._setCursorClassName("pointer")}if("eraser"===s)return void this._setCursorClassName("eraser");if("performance"===s)return void this._setCursorClassName("performance");if("zoom"===s)return void this._setCursorClassName("zoom-in");const o=Ve.cursorTool.value();"dot"!==o?"arrow"!==o?this._setCursorClassName(""):this._setCursorClassName("default"):this._setCursorClassName("dot")}showContextMenuForSelection(e,t,i){const s=this._chartUndoModel().selection();if(s.isEmpty())return;const o=s.dataSources().filter((e=>e.hasContextMenu()));this.showContextMenuForSources(o,e,void 0,t,i)}async showContextMenuForSources(e,t,i,s,o){var r,n,a,l,c;if(!e.length)return Promise.resolve(null);const h=e[0],d=(0,T.merge)((0,T.clone)(this._options.contextMenu),i||{}),u=new at.ActionsProvider(this._chart,d);if(h===this._chartUndoModel().crossHairSource())return h.handleContextMenuEvent(t),Promise.resolve(null);{const i=await u.contextMenuActionsForSources(e,t,null==s?void 0:s.origin,null===(r=null==o?void 0:o.data())||void 0===r?void 0:r.customActions);if(0===i.length)return Promise.resolve(null);{let e;return e=h instanceof jt.Series?{menuName:null!==(n=null==s?void 0:s.origin)&&void 0!==n?n:"ObjectTreeContextMenu",detail:{type:"series",id:h.instanceId()}}:(0,te.isLineTool)(h)?{menuName:null!==(a=null==s?void 0:s.origin)&&void 0!==a?a:"ObjectTreeContextMenu",detail:{type:"shape", id:null!==(l=null==h?void 0:h.id())&&void 0!==l?l:null}}:{menuName:null!==(c=null==s?void 0:s.origin)&&void 0!==c?c:"ObjectTreeContextMenu",detail:{type:"study",id:(null==h?void 0:h.id())||null}},Ue.ContextMenuManager.createMenu(i,void 0,e).then((e=>(e.show(t),e)))}}}leftPriceAxisesContainer(){return this._lhsPriceAxisesContainer}rightPriceAxisesContainer(){return this._rhsPriceAxisesContainer}setPriceAxisSizes(e,t,i){this._priceAxisesContainer(e).setSizes(t,i)}state(){return(0,r.ensureNotNull)(this._state)}hasState(){return null!==this._state}setState(e){this._state!==e&&(this.hasState()&&this._unsubscribeFromState(),this._state=e,this.hasState()&&(this._subscribeToState(),this.updatePriceAxisWidgetsStates()))}getScreenshotData(e){var t,i,s,o;const r=[],n=[];let a,l=[];const c=this.state().sourcesByGroup().priceSources().slice().reverse(),h=this._chart.properties().childs().paneProperties.childs().legendProperties.childs();for(const d of c){const c=d.statusView();if((0,$.isStudy)(d)&&(h.showLegend.value()||(null==e?void 0:e.showCollapsedStudies))){const s=h.showStudyTitles.value(),o=!0;if(d.properties().childs().visible.value()&&c&&o){r.push(s?d.statusProvider(null==e?void 0:e.status).text():"");const o=B.enabled("use_last_visible_bar_value_in_legend")&&null!==(i=null===(t=this._chartModel().timeScale().visibleBarsStrictRange())||void 0===t?void 0:t.lastBar())&&void 0!==i?i:null,a=d.valuesProvider().getValues(o);n.push(a)}}else if(d===this._chartModel().mainSeries()&&c&&h.showSeriesTitle.value()){a=d.statusProvider((null==e?void 0:e.status)||{}).text();const t=B.enabled("use_last_visible_bar_value_in_legend")&&null!==(o=null===(s=this._chartModel().timeScale().visibleBarsStrictRange())||void 0===s?void 0:s.lastBar())&&void 0!==o?o:null;l=d.valuesProvider().getValues(t)}}return{type:"pane",leftAxis:this._lhsPriceAxisesContainer.getScreenshotData(),rightAxis:this._rhsPriceAxisesContainer.getScreenshotData(),content:this._canvasBinding.canvasElement.toDataURL(),canvas:this._canvasBinding.canvasElement,contentWidth:this._size.width,contentHeight:this._size.height,studies:r,studiesValues:n,containsMainSeries:this.containsMainSeries(),mainSeriesText:a,mainSeriesValues:l}}updatePriceAxisWidgetsStates(){if(!this.hasState())return;const e=this._chartModel(),t=e.paneForSource(e.mainSeries());if(!t)return;const i=e.priceScaleSlotsCount(),s=this.state(),o=s.visibleLeftPriceScales(),r=s.visibleRightPriceScales();this._lhsPriceAxisesContainer.setScales(o,i.left,t.leftPriceScales().length,i.left+i.right),this._rhsPriceAxisesContainer.setScales(r,i.right,t.rightPriceScales().length,i.left+i.right)}updatePriceAxisWidgets(){this._lhsPriceAxisesContainer.update(),this._rhsPriceAxisesContainer.update()}update(){this.hasState()&&(this.updatePriceAxisWidgets(),null!==this._legendWidget&&this._legendWidget.update(),this.updateControls())}updateStatusWidget(e){this.hasState()&&null!==this._legendWidget&&(e.legendWidgetLayoutInvalidated()?this._legendWidget.updateLayout():this._legendWidget.update())}updateControls(){ this.hasState()&&null!==this._paneControls&&this._paneControls.update()}updateThemedColors(e){this._themedTopColor=e.topColor,this._updateByThemedColors()}statusWidget(){return this._legendWidget}getElement(){return this._rowElement}canvasElement(){return this._canvasBinding.canvasElement}hasCanvas(e){return this._canvasBinding.canvasElement===e||this._topCanvasBinding.canvasElement===e}pinchStartEvent(){return null===this._paneWidgetsSharedState.scrollingPane()&&null===this._paneWidgetsSharedState.pinchingPane()&&(this._onTouchEvent(),!!this._options.handleScale.pinch&&(this._chartModel().stopTimeScaleAnimation(),this._prevPinchScale=1,this._pinching=!0,this._wasPinched=!0,this._paneWidgetsSharedState.setPinchingPane(this),!0))}pinchEvent(e,t,i,s){if(null!==this._paneWidgetsSharedState.scrollingPane()||this._paneWidgetsSharedState.pinchingPane()!==this)return;if(this._onTouchEvent(),!this._options.handleScale.pinch)return;const o=10*(s-this._prevPinchScale);this._prevPinchScale=s,this._chartModel().zoomTime(e.x,o,!0),this._prevPinchScale=s}pinchEndEvent(){null===this._paneWidgetsSharedState.scrollingPane()&&this._paneWidgetsSharedState.pinchingPane()===this&&(this._onTouchEvent(),this._pinching=!1,this._paneWidgetsSharedState.setPinchingPane(null))}mouseClickEvent(e){this._onMouseEvent(),this._mouseClickOrTapEvent(e)}tapEvent(e){this._preventTouchEventsExceptPinch()||(this._onTouchEvent(),this._mouseClickOrTapEvent(e))}mouseDownEvent(e){this._onMouseEvent(),this.hasState()&&this._mouseDownOrTouchStartEvent(e,this._dataSourceAtPoint(e.localX,e.localY))}touchStartEvent(e){if(this._paneWidgetsSharedState.startTouch(this),this._preventTouchEventsExceptPinch())return;const t=!this._trackCrosshairOnlyAfterLongTap&&null!==mi&&mi.stateId===this.state().id()&&Math.abs(mi.x-e.localX)+Math.abs(mi.y-e.localY)<5;this._onTouchEvent(),this._chart.setActivePaneWidget(this);const i=this._dataSourceAtPoint(e.localX,e.localY);if(t){const t=this._chartModel().crossHairSource();null!==i&&i.source===t||t.selectPointMode().value()!==Ve.SelectPointMode.None?this.startTrackingMode(new Ee.Point(e.localX,e.localY),new Ee.Point(e.localX,e.localY)):!this._chart.readOnly()&&null!==i&&((0,te.isLineTool)(i.source)&&i.source.userEditEnabled()||(0,Qe.isAlertLabel)(i.source))&&this._chartUndoModel().selectionMacro((e=>{e.clearSelection(),e.addSourceToSelection(i.source,i.hittest.data())}))}this._mouseDownOrTouchStartEvent(e,i),this._mouseOrTouchMoveEvent(e)}mouseUpEvent(e){this._onMouseEvent(),this._mouseUpOrTouchEndEvent(e)}touchEndEvent(e){this._paneWidgetsSharedState.endTouch(this),this._preventTouchEventsExceptPinch()||(this._onTouchEvent(),this._mouseOrTouchLeaveEvent(e),this._mouseUpOrTouchEndEvent(e))}mouseMoveEvent(e){this._onMouseEvent(),this._mouseOrTouchMoveEvent(e)}pressedMouseMoveEvent(e){this._onMouseEvent(),this._pressedMouseOrTouchMoveEvent(e)}touchMoveEvent(e){this._preventTouchEventsExceptPinch()||(this._onTouchEvent(),this._pressedMouseOrTouchMoveEvent(e))}mouseLeaveEvent(e){this._onMouseEvent(), this._updateHoveredSource(null,new Re.EnvironmentState(e)),this._mouseOrTouchLeaveEvent(e)}mouseDoubleClickEvent(e){this._onMouseEvent(),this._mouseDoubleClickOrDoubleTapEvent(e)}wheelClickEvent(e){if(this._chart.readOnly())return;const t=this._dataSourceAtPoint(e.localX,e.localY);if(null===t||t.isCustom)return;if((t.hittest.target()||0)<=Ne.HitTarget.MovePointBackground)return;const i=new Re.EnvironmentState(e),s=t.hittest.eraseMarker();if(i.mod()&&void 0!==s&&t.source.processErase)return void t.source.processErase(this._chartUndoModel(),s);const o=this._chartUndoModel();o.selection().isSelected(t.source)||o.selectionMacro((e=>{e.clearSelection();const i=(0,r.ensureNotNull)(t.source);e.addSourceToSelection(i,hi(t,i))})),this._chart.removeSelectedSources()}doubleTapEvent(e){this._preventTouchEventsExceptPinch()||(this._onTouchEvent(),this._mouseDoubleClickOrDoubleTapEvent(e))}longTapEvent(e){if(null===this._state||this._preventTouchEventsExceptPinch())return;if(this._onTouchEvent(),this._longTap=!0,null!==this._startTrackPoint||!this._trackingModeShouldBeActive())return;const t=this._chartModel().selection();if(!t.isEmpty()){const i=this._dataSourceAtPoint(e.localX,e.localY);if(null!==i&&t.isSelected(i.source))return}this.startTrackingMode(new Ee.Point(e.localX,e.localY),new Ee.Point(e.localX,e.localY),new Re.EnvironmentState(e))}mouseEnterEvent(e){if(this._onMouseEvent(),!this.hasState())return;this._chart.setActivePaneWidget(this);const t=this._dataSourceAtPoint(e.localX,e.localY);this._updateHoveredSource(t,new Re.EnvironmentState(e)),this.setCursorPosition(e.localX,e.localY,new Re.EnvironmentState(e))}contextMenuEvent(e){this._onMouseEvent(),this._contextMenuEvent(e)}touchContextMenuEvent(e){this._preventTouchEventsExceptPinch()||(this._onTouchEvent(),this._contextMenuEvent(e))}mouseDownOutsideEvent(e){this._processOutsideClick(null,e)}touchStartOutsideEvent(e){this._processOutsideClick(null,e)}cancelZoom(){this._chartModel().crossHairSource().clearSelection(),this._firstZoomPoint=null,this._preventCrossHairMove()&&this._clearCursorPosition()}startTrackingMode(e,t,i){this._startChangeLineToolParams=null,this._startMoveSourceParams=null,this._currentChangingLineToolHitTest=null,this._currentMovingHitTest=null,this._chartUndoModel().selectionMacro((e=>e.clearSelection())),this._startTrackPoint=e,this._exitTrackingModeOnNextTry=!1,this.setCursorPosition(t.x,t.y,i),this._initCrossHairPosition=this._chartModel().crossHairSource().currentPoint()}setDragToAnotherPaneCursor(){this._setCursorClassName("grabbing")}cloneLineTools(e,t){return this._chartUndoModel().cloneLineTools(e,t)}exitTrackingMode(){null!==this._state&&null!==this._startTrackPoint&&(this._exitTrackingModeOnNextTry=!0,this._tryExitTrackingMode())}trackingModeEnabled(){return null!==this._state&&null!==this._startTrackPoint}addCustomWidgetToLegend(e,t){this._options.legendWidgetEnabled&&(this._customLegendWidgetsFactoryMap.set(e,t),null!==this._legendWidget&&this._legendWidget.addCustomWidgetToLegend(e,t))}containsMainSeries(){ return!!this.hasState()&&this.state().containsMainSeries()}paint(e){if(!this._chartUndoModel()||!this.hasState()||0===this._size.width||0===this._size.height)return;(0,U.tryApplySuggestedCanvasBitmapSize)(this._canvasBinding),(0,U.tryApplySuggestedCanvasBitmapSize)(this._topCanvasBinding),this._state&&(e.priceScaleSideMaxLevel("left")>me.InvalidationLevel.Cursor||e.priceScaleSideMaxLevel("right")>me.InvalidationLevel.Cursor)&&(this._recalculatePriceScales((0,Kt.viewportChangeEvent)()),null!==mi&&mi.stateId===this.state().id()&&this.setCursorPosition(mi.x,mi.y,mi.envState));const t=e.fullInvalidation();if(t>me.InvalidationLevel.Cursor&&null!==mi&&mi.stateId===this.state().id()){const e=this._dataSourceAtPoint(mi.x,mi.y);this._updateHoveredSource(e,(0,G.globalEnvironmentState)())}if(this._lhsPriceAxisesContainer.paint(e.getterForPriceScaleInvalidationLevelBySide("left")),this._rhsPriceAxisesContainer.paint(e.getterForPriceScaleInvalidationLevelBySide("right")),t===me.InvalidationLevel.None)return;const i=this._state&&(this._state.maximized().value()||!this._state.collapsed().value());if(t>me.InvalidationLevel.Cursor){const e=(0,r.ensureNotNull)(this._canvasBinding.canvasElement.getContext("2d"));e.setTransform(1,0,0,1,0,0),this._makeSureIsUpdated();const t=this._canvasRenderParams();this._drawBackground(e,t),i&&this._drawSources(e,t)}if(null!==this._state){const e=(0,r.ensureNotNull)(this._topCanvasBinding.canvasElement.getContext("2d"));e.setTransform(1,0,0,1,0,0);const t=this._topCanvasRenderParams();e.clearRect(0,0,Math.ceil(this._size.width*t.pixelRatio),Math.ceil(this._size.height*t.pixelRatio)),i&&this._drawTopViews(e,t),this._drawCrossHair(e,t),i&&this._drawActiveLineTools(e,t)}this._updateEndOfSeriesBanner()}cancelCreatingLineTool(){const e=this._chartUndoModel(),t=this._chartUndoModel().lineBeingCreated();if(t)if(t.pointsCount()<=0&&!(0,Ht.isLineDrawnWithPressedButton)(t.toolname)){const i=t.points();if(i.length>2){const s=i[i.length-2];e.continueCreatingLine(s),this._finishTool(t)}else e.cancelCreatingLine()}else e.cancelCreatingLine();null!==this._firstZoomPoint&&this.cancelZoom(),this.setCursorForTool()}drawRightThere(e){if((0,Ht.isLineToolName)(e)&&this.hasState()){const t=this._chartUndoModel(),i=t.crossHairSource(),s=t.model().magnet().align(i.price,i.index,this.state());t.createLineTool({pane:this.state(),point:{index:i.index,price:s},linetool:e})}}cancelMeasuring(){this._chartUndoModel().crossHairSource().clearMeasure(),(0,Ve.resetToCursor)(),this.setCursorForTool()}async setErrorMessage(e){var t,i,s;e&&!this._errorRenderer&&(this._errorRenderer=this._createErrorBlock()),null===(t=await this._errorRenderer)||void 0===t||t.update({message:null==e?void 0:e.message,icon:(null===(i=this._state)||void 0===i?void 0:i.containsMainSeries())||(null===(s=this._state)||void 0===s?void 0:s.maximized().value())?null==e?void 0:e.icon:void 0,backgroundColor:`linear-gradient(${this._chartModel().backgroundTopColor().value()}, ${this._chartModel().backgroundColor().value()})`, textColor:this._chartModel().dark().value()?Qt:Jt,solutionId:null==e?void 0:e.solutionId})}collapsedHeight(){var e,t;return Math.max(Math.ceil(null!==(t=null===(e=this._paneControls)||void 0===e?void 0:e.bottomWithMargin())&&void 0!==t?t:0),33)}setCursorPosition(e,t,i){this._updateLastCrosshairPosition(e,t,i),this._chartModel().setAndSaveCurrentPosition(this._correctXCoord(e),this._correctYCoord(t),this.state(),i)}_topCanvasRenderParams(){return{pixelRatio:(0,U.getBindingPixelRatio)(this._topCanvasBinding),physicalWidth:this._topCanvasBinding.canvasElement.width,physicalHeight:this._topCanvasBinding.canvasElement.height,cssWidth:this._chartModel().timeScale().width(),cssHeight:this.height()}}_canvasRenderParams(){return{pixelRatio:(0,U.getBindingPixelRatio)(this._canvasBinding),physicalWidth:this._canvasBinding.canvasElement.width,physicalHeight:this._canvasBinding.canvasElement.height,cssWidth:this._chartModel().timeScale().width(),cssHeight:this.height()}}_tryExitTrackingMode(e){this._exitTrackingModeOnNextTry&&(this._startTrackPoint=null,e||this._clearCursorPosition())}_tryStartMeasure(e,t,i,s,o){return!(!(0,Ve.toolIsMeasure)(Ve.tool.value())||t.startMeasurePoint())&&(e.isTouch||this._preventCrossHairMove()||this.setCursorPosition(e.localX,e.localY,i),s=this._chartModel().magnet().align(s,o,this.state()),t.startMeasuring({price:s,index:o},this.state()),!0)}_tryFinishMeasure(e,t){if(t.startMeasurePoint()&&!t.endMeasurePoint()){let i=t.price;const s=t.index;return i=this._chartModel().magnet().align(i,s,this.state()),t.finishMeasure({price:i,index:s}),e.isTouch?(0,Ve.resetToCursor)():this._needResetMeasureLater=!0,this._preventCrossHairMove()&&this._clearCursorPosition(),!0}return!1}_tryStartZoom(e,t,i,s){const o=this._chart.model().model().zoomEnabled();if("zoom"===Ve.tool.value()&&o){const o=this._chartUndoModel(),r=o.timeScale().indexToCoordinate(i)-.5*o.timeScale().barSpacing();return this._firstZoomPoint={price:t,index:i,x:r,y:e.localY},this._preventCrossHairMove()||this.setCursorPosition(e.localX,e.localY,s),this._chartModel().crossHairSource().startSelection(this.state()),!0}return!1}_finishZoom(e){const t=this.state(),i=t.defaultPriceScale(),s=(0,r.ensureNotNull)(t.mainDataSource()).firstValue(),o=i.coordinateToPrice(e.localY,(0,r.ensureNotNull)(s)),n=this._chartUndoModel(),a=Math.round(n.timeScale().coordinateToIndex(e.localX)),l=(0,r.ensureNotNull)(this._firstZoomPoint);a!==l.index&&n.zoomToViewport(l.index,a,l.price,o,t),this._chartModel().crossHairSource().clearSelection(),this._firstZoomPoint=null,(0,Ve.resetToCursor)(),this._preventCrossHairMove()&&this._clearCursorPosition()}_tryFinishZoom(e){return null!==this._firstZoomPoint&&(this._finishZoom(e),!0)}_tryHandleEraserMouseDown(e,t){if(!("eraser"!==Ve.tool.value()||e.isCustom||(i=e.source,i&&i.customization&&i.customization.disableErasing))){const i=this._chartUndoModel();if((0,te.isLineTool)(e.source)||(0,$.isStudy)(e.source)){const s=e.hittest.eraseMarker() ;return t.mod()&&void 0!==s&&e.source.processErase?e.source.processErase(i,s):i.removeSource(e.source,!1),!0}}var i;return!1}_tryStartChangingLineTool(e,t,i,s){var o,n,a;if(e.isTouch&&null!==this._startTrackPoint)return!1;const l=t.hittest;if((!e.isTouch||!this._preventSourceChange)&&l&&(0,te.isLineTool)(t.source)&&l.target()===Ne.HitTarget.ChangePoint){const c=this._chartUndoModel(),h=(0,r.ensure)(null===(o=this.state().mainDataSource())||void 0===o?void 0:o.firstValue()),d=(0,r.ensureNotNull)(t.source.priceScale()).coordinateToPrice(e.localY,h);c.selectionMacro((e=>{e.clearSelection(),e.addSourceToSelection(t.source,l.data())}));let u=d;t.source.priceScale()===c.mainSeries().priceScale()&&(u=c.model().magnet().align(d,s,this.state()));const _=null===(n=l.data())||void 0===n?void 0:n.nonDiscreteIndex;_&&(s=c.timeScale().coordinateToFloatIndex(e.localX));const p=null===(a=l.data())||void 0===a?void 0:a.pointIndex;return this._startChangeLineToolParams={source:t.source,startPoint:{index:s,price:u,nonDiscreteIndex:_},screenPoint:{x:e.localX,y:e.localY},pointIndex:p,envState:i},!0}return this._startChangeLineToolParams=null,!1}_tryStartCloning(e,t,i,s){if(i.mod()){const t=this._chartUndoModel().selection().dataSources().filter((e=>e.cloneable()));if(s&&s.cloneable()&&t.push(s),t.length>0)return this._clonningAtMoveLineTools=t.map((e=>e.id())),this._startCloningPoint=new Ee.Point(e.localX,e.localY),!0}return!1}_tryFinishClonning(e,t,i){const s=this._chartUndoModel(),o=this._chartModel();if(t.mod()&&this._clonningAtMoveLineTools){const n=new Ee.Point(e.localX,e.localY),a=(0,r.ensureNotNull)(this._startCloningPoint).subtract(n).length(),l=[];for(const e of this._clonningAtMoveLineTools){const t=o.dataSourceForId(e);null!==t&&l.push(t)}if(0===l.length)return!1;if(a>8){const o=this.cloneLineTools(l,!0).map((e=>(0,r.ensureNotNull)(s.model().dataSourceForId(e))));s.selectionMacro((e=>{e.clearSelection();let t=null;o.forEach((s=>{null===t&&(t=hi(i,s)),e.addSourceToSelection(s,t)}))}));const n=new Ee.Point(e.localX,e.localY),a=(0,r.ensureNotNull)(o[0].priceScale()),c=(0,r.ensureNotNull)(this.state().mainDataSource()).firstValue(),h={index:s.timeScale().coordinateToIndex(e.localX),price:a.coordinateToPrice(e.localY,(0,r.ensureNotNull)(c))};s.startMovingSources(o,{logical:h,screen:n},null,t),this._clonningAtMoveLineTools=null,this._startCloningPoint=null}return!0}return!1}_mouseDownEventForLineTool(e,t,i,s){var o,n;const a=Ve.tool.value();if(!this.hasState()||(0,Ht.isLineToolDrawWithoutPoints)(a))return;const l=this._chartUndoModel();let c=!1,h=null;(0,Ve.hideAllDrawings)().value()&&(0,y.toggleHideMode)(),(0,Ve.lockDrawings)().setValue(!1),e.isTouch&&!e.stylus&&((0,Ht.isLineToolName)(a)&&!(0,Ht.isLineDrawnWithPressedButton)(a)||l.lineBeingCreated())&&this._initToolCreationModeParams(e);const d=l.lineBeingCreated();if(d&&!(0,Ht.isLineDrawnWithPressedButton)(d.toolname)){const a=(0,r.ensure)(null===(o=d.ownerSource())||void 0===o?void 0:o.firstValue());if(e.isTouch&&!e.stylus){if(!this._startTouchPoint){ this._startTouchPoint=new Ee.Point(e.pageX,e.pageY);const t=d.points(),i=t[t.length-1],s=l.timeScale().indexToCoordinate(i.index),o=(0,r.ensureNotNull)(d.priceScale()).priceToCoordinate(i.price,a);return void(this._initCrossHairPosition=new Ee.Point(s,o))}}else if(!e.isTouch){h=d;const o=l.model().paneForSource(d);if(o!==this._state&&null!==o){const i=this._externalPaneXCoord(o,e.localX),s=this._externalPaneYCoord(o,e.localY);c=l.continueCreatingLine({index:Math.round(l.timeScale().coordinateToIndex(i)),price:(0,r.ensure)(null===(n=d.priceScale())||void 0===n?void 0:n.coordinateToPrice(s,a))},t)}else{const e=l.model().magnet().align(s,i,this.state());c=l.continueCreatingLine({index:i,price:e},t)}}}else if(!e.isTouch||e.stylus||(0,Ht.isLineDrawnWithPressedButton)(a)){const e={index:i,price:l.model().magnet().align(s,i,this.state())};h=l.createLineTool({pane:this.state(),point:e,linetool:a}),l.lineBeingCreated()||(c=!0)}const u=this._dataSourceAtPoint(e.localX,e.localY);h&&l.selectionMacro((e=>{e.addSourceToSelection((0,r.ensureNotNull)(h),null==u?void 0:u.hittest.data())})),c&&h&&(this._finishTool(h,u),e.preventDefault())}_handleSelectionMouseDownAndGetJustDeselectedSource(e,t,i){const s=this._chartUndoModel();let o=null;return(null===t||t.source.isSelectionEnabled())&&s.selectionMacro((s=>{!this._preventSourceChange&&null!==t&&(e.isTouch?t.hittest.target()>=Ne.HitTarget.MovePointBackground:t.hittest.target()>Ne.HitTarget.MovePointBackground)?(i.mod()||s.selection().isSelected(t.source)||s.clearSelection(),i.mod()&&s.selection().isSelected(t.source)?(o=t.source,s.removeSourceFromSelection(t.source)):s.addSourceToSelection(t.source,t.hittest.data()),s.selection().allSources().length>1&&(0,_.trackEvent)("GUI","Multiselect","Click Select")):i.mod()||s.clearSelection()})),o}_processMouseMoveWhileZoom(e,t){this._preventCrossHairMove()||this.setCursorPosition(e.localX,e.localY,t)}_updateCommonTooltip(e,t){let i=null;if(null!==e&&null!==e.hittest){const t=e.hittest.data();t&&(i=t.tooltip||null)}if(null===this._prevTooltipData&&null===i)return;if(null===i||""===i.text)return this._prevTooltipData=null,void(0,Ut.hide)(t);if(this._prevTooltipData&&(0,Le.default)(i,this._prevTooltipData))return;this._prevTooltipData=i;const s=(0,T.clone)(i);if(void 0!==s.rect){const e=this._paneCell.getBoundingClientRect();s.rect.x+=e.left,s.rect.y+=e.top}(0,Ut.show)(s)}_setCursorPositionOnExternalPane(e,t,i,s){t=this._externalPaneXCoord(e,t),i=this._externalPaneYCoord(e,i);this._chart.paneByState(e).setCursorPosition(t,i,s)}_updateLastCrosshairPosition(e,t,i){const s=this.state().id();mi={x:e,y:t,envState:i,stateId:s}}_setCursorClassName(e){let t="";e&&(t="pane--cursor-"+e),this._currentCursorClassName!==t&&(this._currentCursorClassName&&this._paneCell.classList.remove(this._currentCursorClassName),t&&this._paneCell.classList.add(t),this._currentCursorClassName=t,this._paneCell.style.cursor)}_processMouseUpOrTouchEndHandler(e){const t=this._dataSourceAtPoint(e.localX,e.localY);null!==t&&t.hittest.tryCallMouseUpOrTouchEndHandler(e)} _crossHairShouldBeVisible(){const e=this._chartModel().crossHairSource();return(0,Ht.isLineToolName)(Ve.tool.value())||(0,Ve.toolIsMeasure)(Ve.tool.value())||e.startMeasurePoint()&&!e.endMeasurePoint()||null!==this._firstZoomPoint||null!==this._chartModel().lineBeingEdited()||null!==this._chartModel().lineBeingCreated()}_clearCursorPosition(){mi=null,this._chartModel().clearCurrentPosition()}_dataSourceAtPoint(e,t){var i,s;if(!this.hasState())return null;const o={result:null},r=this._chartUndoModel();if((0,Ht.isLineToolName)(Ve.tool.value())||null!==r.lineBeingCreated())return o.result;if(this._currentChangingLineToolHitTest)return this._currentChangingLineToolHitTest;const n=new Set;if(this._currentMovingHitTest&&this._currentMovingHitTest.sourceAtPoint.hittest.data()){if(!(null===(i=this._currentMovingHitTest.cancelledContainer)||void 0===i?void 0:i.cancelled))return this._currentMovingHitTest.sourceAtPoint;n.add(this._currentMovingHitTest.sourceAtPoint.source.id())}if(this._currentMovingHitTest&&this._currentMovingHitTest.sourceAtPoint.hittest.data()&&!(null===(s=this._currentMovingHitTest.cancelledContainer)||void 0===s?void 0:s.cancelled))return this._currentMovingHitTest.sourceAtPoint;const a=this.state();this._makeSureIsUpdated();const l=di.bind(null,o),c=this._canvasRenderParams(),h=new Ee.Point(e,t);if(!a.maximized().value()&&a.collapsed().value()||(0,ge.lastMouseOrTouchEventInfo)().isTouch&&(Ve.activePointSelectionMode.value()!==Ve.SelectPointMode.None||null!==this._startTrackPoint))return this._hitTestSources(c,[r.crossHairSource()],h,l,!1,n),o.result;const d=a.sourcesByGroup(),u=r.selection();this._hitTestSources(c,u.dataSources(),h,l,!1,n),this._hitTestSources(c,u.customSources(),h,l,!0,n),u.allSources().forEach((e=>n.add(e.id()))),this._hitTestSources(c,[r.crossHairSource()],h,l,!1,n),this._hitTestSources(c,a.customSources(Be.CustomSourceLayer.Topmost),h,l,!0,n),this._hitTestSources(c,d.tradingSources(),h,l,!1,n),this._hitTestSources(c,a.customSources(Be.CustomSourceLayer.Foreground),h,l,!0,n);const _=[...this._chartModel().multiPaneSources(a),...d.hitTestSources()];if(this._hitTestSources(c,_,h,l,!1,n),this.containsMainSeries()){const e=r.activeStrategySource().value();if(null!==e&&!n.has(e.id())){const t=e.strategyOrdersPaneView();if(null!==t){const i=t.renderer(c);if(null!==i){const t=i.hitTest(h,c);t&&di(o,t,e,i,!1)}}}}return null===o.result&&this._hitTestSources(c,a.customSources(Be.CustomSourceLayer.Background),h,l,!0,n),o.result}_hitTestSources(e,t,i,s,o,n){const a=(0,r.ensureNotNull)(this._state);for(let r=t.length-1;r>=0;--r){const l=t[r];if(n.has(l.id()))continue;const c=l.paneViews(a);if(null!==c&&0!==c.length)for(let t=c.length-1;t>=0;--t){const r=c[t].renderer(e);if(r&&r.hitTest){const t=r.hitTest(i,e);null!==t&&s(t,l,r,o)}}}}_tryStartMovingLineTool(e,t,i,s){var o;if(null===t.source||!t.source.movable()||null!==this._startTrackPoint)return!1;if(!this._preventSourceChange){const n=this._chartUndoModel(),a=(0,r.ensureNotNull)((0, r.ensureNotNull)(this._state).mainDataSource()).firstValue(),l=(0,r.ensureNotNull)(t.source.priceScale()).coordinateToPrice(e.localY,(0,r.ensureNotNull)(a));let c=(t.source.isSelectionEnabled()?n.selection().allSources():[t.source]).filter(qt);const h=c.filter(te.isLineTool);c=h.length>0?h:c.includes(t.source)?[t.source]:[c[0]];const d=new Ee.Point(e.localX,e.localY),u={index:s,price:l},_=null===(o=t.hittest.data())||void 0===o?void 0:o.activeItem;return this._startMoveSourceParams={source:c,startPoint:{logical:u,screen:d},activeItem:void 0===_?null:_,envState:i},!0}return this._startMoveSourceParams=null,!1}_chartModel(){return this._chart.model().model()}_chartUndoModel(){return this._chart.model()}_externalPaneXCoord(e,t){t+=this._div.getBoundingClientRect().left+document.body.scrollLeft;const i=(0,r.ensureNotNull)(this._chart.paneByState(e)),s=i._div.getBoundingClientRect().left+document.body.scrollLeft;return i._correctXCoord(t-s)}_externalPaneYCoord(e,t){t+=this._div.getBoundingClientRect().top+document.body.scrollTop;const i=(0,r.ensureNotNull)(this._chart.paneByState(e)),s=i._div.getBoundingClientRect().top+document.body.scrollTop;return i._correctYCoord(t-s)}_correctXCoord(e){return Math.max(0,Math.min(e,this._size.width-1))}_correctYCoord(e){return Math.max(0,Math.min(e,this._size.height-1))}_processScroll(e){if(!this._chart.model().model().scrollEnabled())return;const t=performance.now();this._startScrollingPos||this._preventScroll()||(this._startScrollingPos={x:e.clientX,y:e.clientY,timestamp:t,localX:e.localX,localY:e.localY});const i=this._chartUndoModel();let s=this.state().defaultPriceScale();if(this._startScrollingPos&&!this._isScrolling&&(this._startScrollingPos.x!==e.clientX||this._startScrollingPos.y!==e.clientY))return i.beginUndoMacro(ti,!0),null===this._scrollXAnimation&&this._options.useKineticScroll&&(this._scrollXAnimation=new Et.KineticAnimation(.2,7,.997,15),this._scrollXAnimation.addPosition(e.clientX,this._startScrollingPos.timestamp)),i.selection().isEmpty()||(s=i.selection().allSources()[0].priceScale()),null===s||s.isEmpty()||(this._scrollPriceScale=s,i.startScrollPrice(this.state(),s,e.localY)),i.startScrollTime(e.localX),this._isScrolling=!0,this.setCursorForTool(),void this._paneWidgetsSharedState.setScrollingPane(this);this._isScrolling&&(null!==this._scrollPriceScale&&i.scrollPriceTo(this.state(),this._scrollPriceScale,e.localY),i.scrollTimeTo(e.localX),null!==this._scrollXAnimation&&this._scrollXAnimation.addPosition(e.clientX,t))}_finishScroll(){const e=this._chartUndoModel();e.endScrollTime(),null!==this._scrollPriceScale&&e.endScrollPrice(this.state(),this._scrollPriceScale),e.endUndoMacro(),this._isScrolling=!1,this._startScrollingPos=null,this._scrollPriceScale=null,this.setCursorForTool(),this._paneWidgetsSharedState.setScrollingPane(null)}_endScroll(e){if(!this._isScrolling)return!1;this._finishScroll();const t=this._scrollUndoCommandInStack(),i=performance.now();return null!==this._scrollXAnimation&&(this._scrollXAnimation.start(e.clientX,i), this._scrollXAnimation.finished(i)||(this._chartModel().stopTimeScaleAnimation(),this._chartModel().setTimeScaleAnimation(this._scrollXAnimation),this._scrollXAnimation=null)),t}_preventScroll(){return this._trackCrosshairOnlyAfterLongTap&&this._longTap||this._contextMenuOpenedOnLastTap||(0,Ht.isLineToolName)(Ve.tool.value())||Boolean(this._chartUndoModel().lineBeingCreated())||null!==this._startTrackPoint||this._preventScrollUntilNextMouseDownOrTouchStart}_isSelectPointModeEnabled(){return this._chartUndoModel().crossHairSource().selectPointMode().value()!==Ve.SelectPointMode.None}_preventCrossHairMove(){return!!this._trackCrosshairOnlyAfterLongTap&&(null===this._chart.trackingModePaneWidget()&&(!!this._contextMenuOpenedOnLastTap||!this._crossHairShouldBeVisible()&&null===this._startTrackPoint))}_finishTool(e,t=null){const i=this._chartUndoModel(),s=e.toolname;if(s===Ve.tool.value()&&(0,Ve.resetToCursor)(),this._preventCrossHairMove()&&this._clearCursorPosition(),i.selectionMacro((i=>{i.addSourceToSelection(e,hi(t,e))})),(0,te.isEditableTextLineTool)(e))e.activateTextEditingOn(this._div);else if((0,Ht.isTextToolName)(s)){const t=i.createUndoCheckpoint();this._chart.showChartPropertiesForSource(e,K.TabNames.text,void 0,t)}this._lastFinishedToolId=e.id(),(0,l.emit)("drawing_event",e.id(),"create"),(0,Ft.trackDrawingCreated)(e)}_alignSourcesThatBeingMoved(e,t,i,s){const o=this._chartUndoModel(),r=o.timeScale().coordinateToIndex(t);o.model().sourcesBeingMoved().forEach((e=>{var n;let a=r,l=e.convertYCoordinateToPriceForMoving(i,this.state().mainDataSource());if(null!==l){if((0,$.isStudy)(e)){const e=o.mainSeries(),t=e.bars().firstIndex(),i=e.bars().lastIndex();null!==t&&null!==i&&(a=Math.min(Math.max(r,t),i)),l=this._chartModel().magnet().align(l,r,this.state())}null!==this._currentMovingHitTest&&void 0!==(null===(n=this._currentMovingHitTest.sourceAtPoint.hittest.data())||void 0===n?void 0:n.cursorType)||this.setCursorForTool(),o.moveSources({screen:new Ee.Point(t,i),logical:{index:a,price:l}},s)}}))}_resetMeasureIfRequired(){this._needResetMeasureLater&&((0,Ve.resetToCursor)(),this._needResetMeasureLater=!1)}_makeSureIsUpdated(){var e;const t=this.state(),i=[...t.dataSources(),...t.customSources()],s=t.height(),o=t.width();for(const r of i){const i=r.paneViews(t);if(null!==i)for(const t of i)null===(e=t.makeSureIsUpdated)||void 0===e||e.call(t,s,o)}}_drawBackground(e,t){const i=Math.ceil(t.pixelRatio*this._size.width),s=Math.ceil(t.pixelRatio*this._size.height),o=this._chartModel(),r=o.backgroundTopColor().value(),n=o.backgroundColor().value();r===n?(0,U.clearRect)(e,0,0,i+1,s+1,n):(0,Fe.clearRectWithGradient)(e,0,0,i+1,s+1,r,n)}_drawWatermark(e,t){const i=this._chartModel().watermarkSource();if(null===i)return;if(!this.state().containsMainSeries())return;const s=i.paneViews();for(const i of s){e.save();const s=i.renderer(t);s&&s.draw(e,t),e.restore()}}_drawCrossHair(e,t){const i=this._chartUndoModel().crossHairSource();i.invalidateLockPosition(),i.visible||null===Ve.crosshairLock.value()||i.updateAllViews((0, Kt.sourceChangeEvent)(i.id())),this._drawSourceImpl(e,t,ni,ri,i)}_drawActiveLineTools(e,t){const i=this._chartModel(),s=[i.lineBeingCreated(),i.lineBeingEdited(),...i.sourcesBeingMoved(),i.customSourceBeingMoved()].filter((e=>!!e));for(const o of s){(i.paneForSource(o)===this.state()||(0,Oe.isDataSource)(o)&&o.isMultiPaneEnabled())&&this._drawSourceImpl(e,t,ni,ri,o)}}_drawTopViews(e,t){for(const i of this.state().sourcesByGroup().all())i.topPaneViews&&this._drawSourceImpl(e,t,ai,ri,i)}_drawSources(e,t){const i=this.state(),s=i.model(),o=i.sourcesByGroup(),r=o.tradingSources(),n=[...s.multiPaneSources(i),...o.generalSources()],a=o.phantomSources(),l=i.customSources(Be.CustomSourceLayer.Background).slice(),c=i.customSources(Be.CustomSourceLayer.Foreground).slice(),h=i.customSources(Be.CustomSourceLayer.Topmost).slice(),d=s.activeStrategySource().value();this._drawSourceImpl(e,t,ni,ri,s.gridSource()),this._drawWatermark(e,t);for(const i of l)this._drawSourceImpl(e,t,ni,oi,i);for(const i of n)this._drawSourceImpl(e,t,ni,oi,i);for(const i of c)this._drawSourceImpl(e,t,ni,oi,i);for(const i of a)this._drawSourceImpl(e,t,ni,oi,i);const u=new Set;[s.lineBeingCreated(),s.lineBeingEdited(),...s.sourcesBeingMoved(),s.customSourceBeingMoved()].filter(T.notNull).forEach((e=>u.add(e.id())));let _=s.hoveredSource();null!==_&&((0,Oe.isDataSource)(_)&&!_.showOnTopOnHovering()||u.has(_.id())||(0,Oe.isDataSource)(_)&&!n.includes(_)?_=null:u.add(_.id()));const p=s.selection().allSources().filter((e=>!((0,Oe.isDataSource)(e)&&!n.includes(e))&&!u.has(e.id())));p.forEach((e=>u.add(e.id())));for(const i of l)this._drawSourceImpl(e,t,ni,ri,i,u);for(const i of n)this._drawSourceImpl(e,t,ni,ri,i,u);for(const i of c)this._drawSourceImpl(e,t,ni,ri,i,u);d&&this.containsMainSeries()&&this._drawSourceImpl(e,t,ci,ri,d,u);for(const i of r)this._drawSourceImpl(e,t,ni,oi,i);for(const i of h)this._drawSourceImpl(e,t,ni,oi,i);for(const i of n)this._drawSourceImpl(e,t,li,ri,i,u);for(const i of c)this._drawSourceImpl(e,t,li,ri,i,u);for(const i of r)this._drawSourceImpl(e,t,ni,ri,i,u);for(const i of h)this._drawSourceImpl(e,t,ni,ri,i,u);for(const i of p)this._drawSourceImpl(e,t,ni,ri,i),i===d&&this.containsMainSeries()&&this._drawSourceImpl(e,t,ci,ri,d);for(const i of p)this._drawSourceImpl(e,t,li,ri,i);_&&(this._drawSourceImpl(e,t,ni,ri,_),_===d&&this.containsMainSeries()&&this._drawSourceImpl(e,t,ci,ri,d),this._drawSourceImpl(e,t,li,ri,_));for(const i of a)this._drawSourceImpl(e,t,ni,ri,i,u)}_drawSourceImpl(e,t,i,s,o,r){if(r&&r.has(o.id()))return;const n=i(o,this.state());if(n)for(const i of n){const o=i.renderer(t);o&&(e.save(),s(o,e,t),e.restore())}}_updateByThemedColors(){null!==this._legendWidget&&this._legendWidget.updateThemedColors(this._themedTopColor),null!==this._paneControls&&this._paneControls.updateThemedColors(this._themedTopColor)}_scrollUndoCommandInStack(){const e=this._chartUndoModel().undoHistory().undoStack();if(e.isEmpty())return!1;const t=e.head();if(!(t instanceof We.UndoMacroCommand))return!1;if(t.isEmpty())return!1 ;const i=t.commands()[0];return i instanceof Nt.PriceScaleChangeUndoCommand||i instanceof Dt.TimeScaleChangeUndoCommand}_onStateDestroyed(){this.setState(null)}_onDataSourcesCollectionChanged(){this._startMoveSourceParams=null}_processMouseEnterLeaveMoveHandlers(e,t){var i,s,o,r;null===this._prevHoveredHittest||this._prevHoveredHittest.renderer===(null==e?void 0:e.renderer)&&(null===(i=this._prevHoveredHittest.hittest.data())||void 0===i?void 0:i.activeItem)===(null===(s=e.hittest.data())||void 0===s?void 0:s.activeItem)||((0,Ne.tryCallHandler)(t,null===(o=this._prevHoveredHittest.hittest.data())||void 0===o?void 0:o.mouseLeaveHandler),this._prevHoveredHittest=null),t.isTouch||null!==e&&((null===(r=this._prevHoveredHittest)||void 0===r?void 0:r.renderer)!==e.renderer&&(e.hittest.tryCallMouseEnterHandler(t),this._prevHoveredHittest=e),e.hittest.tryCallMouseMoveHandler(t))}_startChangeOrMoveLineToolIfNeeded(){if(null!==this._startChangeLineToolParams){const e=this._startChangeLineToolParams;this._chartUndoModel().startChangingLinetool(e.source,e.startPoint,e.pointIndex,e.envState)}if(null!==this._startMoveSourceParams){const e=this._startMoveSourceParams;this._chartUndoModel().startMovingSources(e.source,e.startPoint,e.activeItem,e.envState)}this._startMoveSourceParams=null,this._startChangeLineToolParams=null}_trackingModeShouldBeActive(){return!(!this._trackCrosshairOnlyAfterLongTap||this._contextMenuOpenedOnLastTap||this._crossHairShouldBeVisible())&&this._longTap}_processOutsideClick(e,t){var i;let s=null;const o=this._chartModel();if(null!==e&&(s=e.isCustom?o.customSourceName(e.source):e.source.id()),null!==this._lastClickedSource&&this._lastClickedSource.id!==s){const e=this._lastClickedSource.id;let i=this._lastClickedSource.isCustom?o.customSourceForName(e):o.dataSourceForId(e);null!==i||this._lastClickedSource.isCustom||(i=o.dataSourceForId(e)),null!==i&&i.onClickOutside&&(i.onClickOutside(t),this._chartModel().updateSource(i))}this._lastClickedSource=null!==s?{id:s,isCustom:null!==(i=null==e?void 0:e.isCustom)&&void 0!==i&&i}:null}_mouseClickOrTapEvent(e){var t;if(!this.hasState())return;Wt.performanceTestMode&&"performance"===Ve.tool.value()&&ei&&ei.confetti(e.pageX,e.pageY);const i=this._dataSourceAtPoint(e.localX,e.localY),s=i&&i.source,o=this._chartUndoModel(),n=Boolean(null===(t=null==i?void 0:i.hittest.data())||void 0===t?void 0:t.hideCrosshairLinesOnHover);this._processOutsideClick(i,e),!this._isSelectPointModeEnabled()||n||e.isTouch&&this.trackingModeEnabled()&&!this._exitTrackingModeOnNextTry||o.crossHairSource().trySelectCurrentPoint(),null!==i&&i.hittest.tryCallClickOrTapHandler(e)&&o.model().updateSource((0,r.ensureNotNull)(s)),!e.isTouch||this._isSelectPointModeEnabled()||i&&i.source===o.crossHairSource()||this._tryExitTrackingMode(),s&&(0,te.isLineTool)(s)&&this._lastFinishedToolId!==s.id()&&(0,l.emit)("drawing_event",s.id(),"click"),this._resetMeasureIfRequired()}_mouseDownOrTouchStartEvent(e,t){var i,s,o,n,a,c;if(this._pressedMoveStage=1,this._preventScrollUntilNextMouseDownOrTouchStart=!1, e.isTouch&&(this._longTap=!1,this._exitTrackingModeOnNextTry=null!==this._startTrackPoint,this._paneWidgetsSharedState.clearDraggingSource()),this._contextMenuOpenedOnLastTap=!1,this._lastFinishedToolId=null,this._chartModel().stopTimeScaleAnimation(),e.isTouch&&this._switchTrackingModeFromAnotherPaneIfNeeded(e),document.activeElement!==document.body&&document.activeElement!==document.documentElement)document.activeElement&&document.activeElement.blur?document.activeElement.blur():document.body.focus();else{const e=document.getSelection();null!==e&&e.removeAllRanges()}(0,l.emit)("mouse_down",{clientX:e.clientX,clientY:e.clientY,pageX:e.pageX,pageY:e.pageY,screenX:e.screenX,screenY:e.screenY}),this._updateCommonTooltip(null);const h=this._chartUndoModel(),d=new Re.EnvironmentState(e);h.mainSeries().clearGotoDateResult();const u=this.state().defaultPriceScale();if(u.isEmpty()||h.timeScale().isEmpty())return;const _=h.crossHairSource();if(!e.isTouch&&!(0,Ht.isLineDrawnWithPressedButton)(Ve.tool.value())){const t=h.lineBeingCreated(),i=null!==t?h.model().paneForSource(t):null;null!==i&&i!==this._state?this._setCursorPositionOnExternalPane(i,e.localX,e.localY,d):this.setCursorPosition(e.localX,e.localY,d)}e.isTouch&&(0,Ht.isLineToolName)(Ve.tool.value())&&((0,Ht.isLineDrawnWithPressedButton)(Ve.tool.value())||null!==_.pane?(0,Ht.isLineDrawnWithPressedButton)(Ve.tool.value())&&this._clearCursorPosition():this._chart.updateCrossHairPositionIfNeeded());const p=(0,r.ensureNotNull)(this.state().mainDataSource()).firstValue();if(null===p)return void(this._chart.readOnly()||(this._handleSelectionMouseDownAndGetJustDeselectedSource(e,t,d),null!==t&&(0,Rt.isPriceDataSource)(t.source)&&t.source.isDraggable()&&this._paneWidgetsSharedState.trySetDraggingSource(t.source,this)));let m=u.coordinateToPrice(e.localY,p),g=this._chartModel().timeScale().coordinateToIndex(e.localX);if(_.startMeasurePoint()&&_.endMeasurePoint()&&_.clearMeasure(),d.shift()&&(null===t||!(null===(s=null===(i=t.hittest.data())||void 0===i?void 0:i.hasOwnShortcutsBehaviourFor)||void 0===s?void 0:s.shiftKey))&&(0,Ve.toolIsCursor)(Ve.tool.value())&&h.selection().isEmpty()&&Ve.tool.setValue("measure"),(e.isTouch&&!e.stylus||!this._tryStartMeasure(e,_,d,m,g))&&(e.isTouch&&!e.stylus||!this._tryFinishMeasure(e,_))&&!this._tryFinishZoom(e)&&!this._tryStartZoom(e,m,g,d)){if(e.isTouch&&(null!==this._startTrackPoint?(this._initCrossHairPosition=_.currentPoint(),this._startTrackPoint=new Ee.Point(e.localX,e.localY)):this._isSelectPointModeEnabled()&&null===this._chart.trackingModePaneWidget()&&this.startTrackingMode(new Ee.Point(e.localX,e.localY),new Ee.Point(e.localX,e.localY),new Re.EnvironmentState(e))),e.isTouch&&(this._preventSourceChange=null===t||!h.selection().isSelected(t.source)),!this._isSelectPointModeEnabled()&&!this._isScrolling){if(e.isTouch&&!e.stylus&&((0,Ve.toolIsMeasure)(Ve.tool.value())||null!==_.measurePane().value()))return void this._initToolCreationModeParams(e);if((0, Ht.isLineToolName)(Ve.tool.value())||h.lineBeingCreated())return d.shift()||h.selectionMacro((e=>e.clearSelection())),void this._mouseDownEventForLineTool(e,d,g,m)}if(null!==t&&t.hittest.tryCallMouseDownOrTouchStartHandler(e),!this._chart.readOnly()){const i=this._handleSelectionMouseDownAndGetJustDeselectedSource(e,t,d);if(null!==t&&!this._preventSourceChange){const i=t.hittest.data();if(t.isCustom){if(t.hittest.hasPressedMoveHandler(e))return h.model().setMovingCustomSource(t.source,i),this._preventScrollUntilNextMouseDownOrTouchStart=!0,this._currentMovingHitTest={sourceAtPoint:t,cancelledContainer:null!==(o=h.model().customSourceMovingHitTestData())&&void 0!==o?o:void 0},void h.selectionMacro((e=>{e.clearSelection(),e.addSourceToSelection((0,r.ensureNotNull)(t.source),(0,r.ensureNotNull)(i))}))}else if((null==i?void 0:i.areaName)===Ne.AreaName.SourceItemMove){const s=null==i?void 0:i.activeItem;if(void 0!==s)return h.startCustomMoving(t.source,s,e),this._currentMovingHitTest={sourceAtPoint:t},void h.selectionMacro((e=>{e.clearSelection(),e.addSourceToSelection((0,r.ensureNotNull)(t.source),(0,r.ensureNotNull)(i))}))}}if(null!==t&&this._tryHandleEraserMouseDown(t,d))return;const s=null!==t&&(0,te.isLineTool)(t.source)&&t.source.isLocked&&t.source.isLocked();if(!((0,Ve.lockDrawings)().value()||s)&&null!==t&&!t.isCustom){if(!t.source.userEditEnabled())return;const s=null===(n=t.hittest.data())||void 0===n?void 0:n.snappingPrice,o=null===(a=t.hittest.data())||void 0===a?void 0:a.snappingIndex;let l=e.localY,h=e.localX;if(void 0!==s&&(l=(0,r.ensure)(null===(c=t.source)||void 0===c?void 0:c.priceScale()).priceToCoordinate(s,p),m=s),void 0!==o&&(h=this._chartModel().timeScale().indexToCoordinate(o),g=o),l===e.localY&&h===e.localX||(e={...e,localY:l,localX:h},this.setCursorPosition(e.localX,e.localY,d)),this._tryStartChangingLineTool(e,t,d,g))return void(this._currentChangingLineToolHitTest=t);if(this._currentChangingLineToolHitTest=null,(S=t.hittest.target())===Ne.HitTarget.MovePoint||S===Ne.HitTarget.MovePointBackground&&(0,ge.lastMouseOrTouchEventInfo)().isTouch){if(this._tryStartCloning(e,t,d,i))return;if(this._tryStartMovingLineTool(e,t,d,g))return void(this._currentMovingHitTest={sourceAtPoint:t});this._currentMovingHitTest=null}}if(null!==t&&(0,Rt.isPriceDataSource)(t.source)&&t.source.isDraggable()&&this._paneWidgetsSharedState.trySetDraggingSource(t.source,this))return}var S;null!==t&&t.hittest.target()===Ne.HitTarget.Regular||(this._processing=!0)}}_mouseUpOrTouchEndEvent(e){var t,i;if(!this.hasState())return;this._pressedMoveStage=0;const s=e.isTouch&&null!==this._startTrackPoint,o=e.isTouch&&this._wasPinched;e.isTouch&&(this._wasPinched=!1,this._longTap=!1),this._startMoveSourceParams=null,this._startChangeLineToolParams=null,this._currentChangingLineToolHitTest=null,this._currentMovingHitTest=null;const n=this._chartUndoModel(),a=n.model().customSourceMovingHitTestData();null!==a||n.customMoveBeingProcessed()||this._processMouseUpOrTouchEndHandler(e),this._isSelecting=!1 ;const c=n.model(),h=c.crossHairSource(),d=this._dataSourceAtPoint(e.localX,e.localY);if(h.selection()&&null===this._firstZoomPoint){const e=this.state().lineToolsForArea(h.selection(),this._canvasRenderParams());n.selectionMacro((t=>{let i=null;e.forEach((e=>{null===i&&(i=hi(d,e)),t.addSourceToSelection(e,i)}))})),h.clearSelection(),(0,_.trackEvent)("GUI","Multiselect","Area Select")}(0,l.emit)("mouse_up",{clientX:e.clientX,clientY:e.clientY,pageX:e.pageX,pageY:e.pageY,screenX:e.screenX,screenY:e.screenY});const u=e.isTouch&&this._touchMove;e.isTouch&&(this._touchMove=!1);const p=new Re.EnvironmentState(e),m=Ve.tool.value();if(e.isTouch&&((0,Ve.toolIsMeasure)(m)||null!==h.measurePane().value())){if(!u&&!e.stylus&&null===h.measurePane().value()&&h.pane!==this._state)return void this.setCursorPosition(e.localX,e.localY);if(!u&&!e.stylus&&this._tryStartMeasure(e,h,p,h.price,h.index))return;if((!u||e.stylus)&&this._tryFinishMeasure(e,h))return}if(e.isTouch&&!u&&!(0,Ht.isLineDrawnWithPressedButton)(m)&&(0,Ht.isLineToolName)(m)&&!n.lineBeingCreated()){if(this._chart.justActivated())return;if(h.pane!==this._state)return void this.setCursorPosition(e.localX,e.localY,p);const i=h.currentPoint(),s=this.state().defaultPriceScale(),o=(0,r.ensure)(null===(t=this.state().mainDataSource())||void 0===t?void 0:t.firstValue()),a={index:Math.round(n.timeScale().coordinateToIndex(i.x)),price:s.coordinateToPrice(i.y,o)},l=(0,r.ensureNotNull)(n.createLineTool({pane:this.state(),point:a,linetool:m}));return n.selectionMacro((e=>{e.addSourceToSelection(l)})),n.lineBeingCreated()||(this._finishTool(l,d),e.preventDefault()),void(this._startTouchPoint=null)}const g=n.lineBeingCreated();if(g&&!(0,Ht.isLineDrawnWithPressedButton)(g.toolname)&&e.isTouch&&(this._startTouchPoint||e.stylus)){if(this._startTouchPoint=null,!u||e.stylus){const t=g.points()[g.points().length-1],i=n.continueCreatingLine({index:t.index,price:t.price},new Re.EnvironmentState(e));this._initCrossHairPosition=null,i&&(this._finishTool(g,d),e.preventDefault())}return}if(null!==this._firstZoomPoint&&this._firstZoomPoint.draggingMode)return void this._finishZoom(e);if(this._processing=!1,n.customMoveBeingProcessed())return void n.endCustomMoving();if(null!==a&&(a.beingMoved&&!a.cancelled&&((0,Ne.tryCallHandler)(e,a.mouseUpHandler,a.touchEndHandler),this.setCursorForTool()),c.setMovingCustomSource(null,null),gi(e,a)))return;if(c.lineBeingEdited())return n.endChangingLinetool(!1),void(this._preventCrossHairMove()&&this._clearCursorPosition());if((0,Ht.isLineDrawnWithPressedButton)(m)&&!this._isSelectPointModeEnabled()){const t=n.lineBeingCreated();null!==t&&((0,Ft.trackDrawingCreated)(t),t.finish(),"LineToolBrush"===t.toolname&&(0,l.emit)("drawing_event",t.id(),"create"));const s=this.state().defaultPriceScale();if(s.isEmpty())return;if(!t)return;const o=(0,r.ensure)(null===(i=t.ownerSource())||void 0===i?void 0:i.firstValue()),a=s.coordinateToPrice(e.localY,o),c={index:Math.round(n.timeScale().coordinateToIndex(e.localX)),price:a};return void n.continueCreatingLine(c)} if(c.sourcesBeingMoved().length)return n.endMovingSource(!1,!1),c.sourcesBeingMoved().filter(te.isLineTool).forEach((e=>{this.setCursorForTool(e)})),void c.invalidate(me.InvalidationMask.cursor());if(!this._chart.readOnly()){const t=e.localX>=0&&e.localXNe.HitTarget.MovePointBackground||(0,ge.lastMouseOrTouchEventInfo)().isTouch)&&n.selectionMacro((e=>{e.clearSelection();const t=(0,r.ensureNotNull)(d.source);e.addSourceToSelection(t,hi(d,t))})),e.isTouch&&(this._touchMove=!1)}_mouseOrTouchMoveEvent(e){if(!this.hasState())return;this._resetMeasureIfRequired();const t=this._dataSourceAtPoint(e.localX,e.localY);this._processMouseEnterLeaveMoveHandlers(t,e);const i=this._chartUndoModel();if(!i)return;const s=e.localX,o=e.localY;this._prevMoveEventPosition=new Ee.Point(s,o);const r=new Re.EnvironmentState(e);if(null===this._firstZoomPoint){if(this._updateHoveredSource(t,r,e),!e.isTouch&&i.lineBeingCreated()){const e=i.lineBeingCreated(),t=null===e?null:i.model().paneForSource(e);if(null!==t&&t!==this._state)return void this._setCursorPositionOnExternalPane(t,s,o,r)}e.isTouch||this.setCursorPosition(s,o,r)}else this._processMouseMoveWhileZoom(e,r)}_pressedMouseOrTouchMoveEvent(e){var t;if(!this.hasState()||this._pinching||e.isTouch&&this._contextMenuOpenedOnLastTap)return;this._pressedMoveStage=2,this._resetMeasureIfRequired(),this._startChangeOrMoveLineToolIfNeeded(),e.isTouch&&(this._touchMove=!0,this._preventSourceChange=!1);const i=new Re.EnvironmentState(e),s=this._chartUndoModel(),o=s.crossHairSource(),n=e.localX,a=e.localY;if(this._prevMoveEventPosition=new Ee.Point(n,a),null!==this._firstZoomPoint)return this._processMouseMoveWhileZoom(e),void(this._firstZoomPoint.draggingMode=!0);const l=Ve.tool.value();if(e.isTouch&&this._startTouchPoint&&(0,Ht.isLineToolName)(l)&&!(0, Ht.isLineDrawnWithPressedButton)(l)&&!s.lineBeingCreated()&&!this._isSelectPointModeEnabled())return void this._updateCrosshairPositionInToolCreationMode(e,this.state());const c=o.measurePane().value();if(e.isTouch&&(this._startTouchPoint||e.stylus)&&((0,Ve.toolIsMeasure)(l)||null!==c))return void(e.stylus?this.setCursorPosition(e.localX,e.localY,new Re.EnvironmentState(e)):this._updateCrosshairPositionInToolCreationMode(e,c||this.state()));const h=s.lineBeingCreated();if(e.isTouch&&!e.stylus&&h&&!(0,Ht.isLineDrawnWithPressedButton)(h.toolname)){if(this._startTouchPoint){const t=(0,r.ensureNotNull)(s.lineBeingCreated()),i=(0,r.ensureNotNull)(s.model().paneForSource(t));this._updateCrosshairPositionInToolCreationMode(e,i)}return}if(e.isTouch&&null!==this._startTrackPoint){this._exitTrackingModeOnNextTry=!1;const e=(0,r.ensureNotNull)(this._initCrossHairPosition),t=new Ee.Point(n,a).subtract(this._startTrackPoint),s=e.add(t);this.setCursorPosition(s.x,s.y,i)}else e.isTouch&&this._preventCrossHairMove()||this.setCursorPosition(n,a,i);const d=this._isSelectPointModeEnabled();if((0,Ht.isLineToolName)(l)&&!(0,Ht.isLineDrawnWithPressedButton)(l)&&!d&&!i.mod())return;if((0,Ht.isLineDrawnWithPressedButton)(l)&&!d){const i=this.state().defaultPriceScale();if(i.isEmpty())return;const o=s.lineBeingCreated();if(!o)return;const n=new Ee.Point(e.localX,e.localY),a=(0,r.ensure)(null===(t=o.ownerSource())||void 0===t?void 0:t.firstValue());return n.price=i.coordinateToPrice(e.localY,a),n.index=Math.round(s.timeScale().coordinateToIndex(e.localX)),void s.continueCreatingLine(n)}if(null!==this._paneWidgetsSharedState.draggingSource()){const t=e.target,i=this._chart.paneByCanvas(t);i&&(i!==this?i.setDragToAnotherPaneCursor():i.setCursorForTool());const s=this._chart.timeAxisByCanvas(t);s&&s.setCursor("grabbing")}if(s.timeScale().isEmpty())return;const u=this._options.handleScroll;if((!u.pressedMouseMove||e.isTouch)&&(!u.horzTouchDrag&&!u.vertTouchDrag||!e.isTouch))return;if(s.customMoveBeingProcessed())return void s.processCustomMove(e);const _=s.model().customSourceMovingHitTestData();if(null!==_&&(this._updateCommonTooltip(null,!0),_.cancelled||(s.model().processingCustomSourceMove(),(0,Ne.tryCallHandler)(e,_.pressedMouseMoveHandler,_.touchMoveHandler)),gi(e,_)))return;if(s.model().lineBeingEdited())return void this.setCursorPosition(n,a,i);if(s.model().sourcesBeingMoved().length)return void this._alignSourcesThatBeingMoved(s.model().sourcesBeingMoved(),e.localX,e.localY,i);const p=this._dataSourceAtPoint(e.localX,e.localY);if(this._tryFinishClonning(e,new Re.EnvironmentState(e),p))return;const m=(0,Ve.toolIsMeasure)(l)||o.startMeasurePoint()&&o.endMeasurePoint();this._chart.readOnly()||!i.mod()||(0,Ht.isLineToolName)(l)||m||d?(this._processScroll(e),this._preventScroll()&&!this._preventCrossHairMove()&&null===this._startTrackPoint&&this.setCursorPosition(e.localX,e.localY,new Re.EnvironmentState(e))):this._isSelecting||(o.startSelection(this.state()),this._isSelecting=!0)}_mouseOrTouchLeaveEvent(e){var t;if(!this.hasState())return ;const i=this._chartUndoModel();if(!i)return;const s=i.crossHairSource();e.isTouch||null!==s.measurePane().value()&&null===s.endMeasurePoint()||this._clearCursorPosition(),i.model().setHoveredSource(null,null),null!==this._prevHoveredHittest&&((0,Ne.tryCallHandler)(e,null===(t=this._prevHoveredHittest.hittest.data())||void 0===t?void 0:t.mouseLeaveHandler),this._prevHoveredHittest=null),this._updateCommonTooltip(null),this._chart.unsetActivePaneWidget()}_mouseDoubleClickOrDoubleTapEvent(e){if(!this.hasState())return;const t=!this._chart.readOnly()&&!(0,Ht.isLineToolName)(Ve.tool.value())&&this._dataSourceAtPoint(e.localX,e.localY)||null;if(null!==t&&t.isCustom)t.hittest.tryCallDblClickOrDblTapHandler(e);else if(null!==t&&(e.isTouch||t.hittest.target()>Ne.HitTarget.MovePointBackground))t.hittest.tryCallDblClickOrDblTapHandler(e)&&!(0,Ne.shouldDefaultActionBeExecuted)(e,(0,r.ensureNotNull)(t.hittest.data()),"doubleClickHandler","doubleTapHandler")||this.processDoubleClickOnSource(t.source,t.hittest?t.hittest:void 0);else if(!this._chart.readOnly()&&!(0,Ht.isLineToolName)(Ve.tool.value())&&!this._chartUndoModel().lineBeingCreated()&&this._chartUndoModel().selection().isEmpty()){const t=this.state();new Re.EnvironmentState(e).mod()&&!t.maximized().value()?(t.collapsed().value()||this._chartModel().paneCollapsingAvailable().value())&&this._chartUndoModel().toggleCollapsedPane(this.state()):this._chart.toggleMaximizePane(this)}}_contextMenuEvent(e){const t=this._chartUndoModel();if(t.crossHairSource().startMeasurePoint()&&!this._trackCrosshairOnlyAfterLongTap)return t.crossHairSource().clearMeasure(),void(0,Ve.resetToCursor)(!0);if(this._pinching)return;if(null===this._firstZoomPoint||this._trackCrosshairOnlyAfterLongTap||this.cancelZoom(),!(0,Ve.toolIsCursor)(Ve.tool.value())||this._isSelectPointModeEnabled()){if(e.isTouch)return;return(0,Ve.resetToCursor)(!0),this.setCursorForTool(),void(t.lineBeingCreated()&&t.cancelCreatingLine())}if(!this._options.contextMenuEnabled)return;const i=this._dataSourceAtPoint(e.localX,e.localY),s=i?i.source:null;if(e.isTouch&&null!==this._startTrackPoint){if(this._preventSourceChange)return;this._clearCursorPosition()}e.isTouch&&(this._contextMenuOpenedOnLastTap=!0,this._startTrackPoint=null),this._contextMenuX=e.localX,this._contextMenuY=e.localY;const o=i&&i.hittest?i.hittest.target():0,r=o>=Ne.HitTarget.Regular||o>=Ne.HitTarget.MovePointBackground&&e.isTouch;this._chart.updateActions(),t.selectionMacro((t=>{null!==s&&r?t.selection().isSelected(s)||(t.clearSelection(),t.addSourceToSelection(s,hi(i,s))):(this._options.contextMenu.general&&this._showContextMenu(e),t.clearSelection())})),null!==i&&r&&null!==s&&((0,Oe.isDataSource)(s)&&s.hasContextMenu()?s.isSelectionEnabled()?this.showContextMenuForSelection(e,void 0,i.hittest):this.showContextMenuForSources([s],e,void 0,void 0,i.hittest):i.hittest.tryCallContextMenuHandler(e))}_onMouseEvent(){this._preventSourceChange=!1,this._startTrackPoint=null,this._trackCrosshairOnlyAfterLongTap=!1}_onTouchEvent(){ this._trackCrosshairOnlyAfterLongTap=!0}_switchTrackingModeFromAnotherPaneIfNeeded(e){const t=this._chart.trackingModePaneWidget();if(null!==t&&t!==this){const i=this._chartModel().crossHairSource().currentPoint();t._exitTrackingModeOnNextTry=!0,t._tryExitTrackingMode(!0),this.startTrackingMode(new Ee.Point(e.localX,e.localY),new Ee.Point(i.x,e.localY),new Re.EnvironmentState(e))}}async _showContextMenu(e){const t=e=>e instanceof F.Separator,i=this._customActions(),s=(await this._initActions(e)).filter((e=>null!==e));i.remove.forEach((e=>{for(let t=0;t0;e--)t(o[e])&&t(o[e-1])&&o.splice(e,1);o.length&&t(o[0])&&o.splice(0,1),o.length&&t(o[o.length-1])&&o.splice(o.length-1,1),Ue.ContextMenuManager.showMenu(o,e,{statName:"ChartContextMenu"},{menuName:"ChartContextMenu"})}async _initActions(e){var t,i;const s=this._chart.actions(),o=[];if(this._chart.model().model().resetScalesAvailable().value()&&(o.push(s.chartReset),o.push(new F.Separator)),!this.state().isEmpty()&&B.enabled("datasource_copypaste")){const t=(0,at.createActionCopyPrice)(this.state(),e.localY),i=(0,at.createPasteAction)(this._chart,this.state());(t||i)&&(t&&o.push(t),i&&o.push(i),o.push(new F.Separator))}if(B.enabled("alerts")&&(o.length&&o.push(new F.Separator),(0,r.ensureNotNull)(this.state().mainDataSource()).alertCreationAvailable().value())){const t=(await(0,Bt.getAlertsChartActionCreators)()).createAlert(this._chart,{localY:e.localY,pane:this.state()});null!==t&&o.push(t)}this._options.contextMenu.mainSeriesTrade&&this.containsMainSeries()&&o.push((0,at.createActionTrade)(this._chart,this.state(),e)),o[o.length-1]instanceof F.Separator||o.push(new F.Separator);return Boolean(null===(t=window.widgetbar)||void 0===t?void 0:t.widget("watchlist"))&&s.addToWatchlist&&o.push(s.addToWatchlist),B.enabled("text_notes")&&o.push(s.addToTextNotes),o[o.length-1]instanceof F.Separator||o.push(new F.Separator),s.moveChartAction&&!s.moveChartAction.isDisabled()&&o.push(s.moveChartAction,new F.Separator),o.push(this._createLockTimeAxisAction(e)),o.push(new F.Separator),s.paneObjectTree&&o.push(s.paneObjectTree),!B.enabled("charting_library_base")&&s.applyColorTheme&&o.push(s.applyColorTheme),o[o.length-1]instanceof F.Separator||o.push(new F.Separator),this._chart.applyIndicatorsToAllChartsAvailable()&&(o.push(s.applyStudiesToAllCharts),o.push(new F.Separator)),o.push(s.paneRemoveAllDrawingTools),o.push(s.paneRemoveAllStudies),o.push(new F.Separator),(null===(i=window.pro)||void 0===i?void 0:i.hasPackage("mtp-mtpredictor"))&&this.state().containsMainSeries()&&o.push((0,at.createMTPredictorActions)(this._chart,this.state(),this._contextMenuX,this._contextMenuY),new F.Separator),B.enabled("show_chart_property_page")&&o.push(s.chartProperties),o[o.length-1]instanceof F.Separator&&o.pop(),o}_loadAndCreateLegendWidget(){ Promise.all([i.e(1283),i.e(62253),i.e(22666),i.e(92108),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(34465),i.e(69121),i.e(66639),i.e(30006),i.e(88194),i.e(35649),i.e(89842),i.e(26855),i.e(99916),i.e(40812),i.e(36956),i.e(56388),i.e(9227),i.e(48450),i.e(61572),i.e(50690),i.e(88087),i.e(59255),i.e(8010),i.e(34654),i.e(62526),i.e(80870),i.e(46513),i.e(5093)]).then(i.bind(i,49555)).then((e=>{if(this._isDestroyed)return;const t=e.LegendWidget,i=(0,De.deepExtend)({},this._options.legendWidget);i.canShowSourceCode=!this._chart.onWidget()&&!h.CheckMobile.any(),i.readOnlyMode=i.readOnlyMode||this._chart.readOnly(),i.statusesWidgets={sourceStatusesEnabled:this._options.sourceStatusesWidgetEnabled,sourceStatuses:this._options.sourceStatusesWidget||{},marketStatusEnabled:this._options.marketStatusWidgetEnabled,dataUpdateModeEnabled:this._options.chartWarningWidgetEnabled,dataUpdateMode:this._options.chartWarningWidget||{},dataProblemEnabled:this._options.dataProblemWidgetEnabled};const s=(0,E.combine)(((e,t)=>pi&&this._chart!==e&&!t),this._chart.chartWidgetCollection().activeChartWidget.weakReference(),this._chart.chartWidgetCollection().lock.crosshair.weakReference()),o=(0,E.combine)(((e,t)=>null!==e?e===this._state:(0,Ve.toolIsMeasure)(t)),this._chartModel().crossHairSource().measurePane().weakReference(),Ve.tool.weakReference());this._legendWidget=new t(this._chartUndoModel(),this,this._chart.backgroundTopTheme().spawnOwnership(),s.ownership(),this._visuallyCollapsed.spawnOwnership(),o.ownership(),i,{showContextMenuForSelection:this.showContextMenuForSelection.bind(this),showContextMenuForSources:this.showContextMenuForSources.bind(this),updateActions:this._chart.updateActions.bind(this._chart),showChartPropertiesForSource:this._chart.showChartPropertiesForSource.bind(this._chart),showGeneralChartProperties:this._chart.showGeneralChartProperties.bind(this._chart),showObjectsTreeDialog:this._chart.showObjectsTreeDialog.bind(this._chart)}),this._div.appendChild(this._legendWidget.getElement()),this._legendWidget.updateLayout(),this._legendWidget.updateWidgetModeBySize(this._size),this._legendWidget.updateThemedColors(this._themedTopColor);for(const e of Array.from(this._customLegendWidgetsFactoryMap.keys()))this._legendWidget.addCustomWidgetToLegend(e,(0,r.ensureDefined)(this._customLegendWidgetsFactoryMap.get(e)))}))}_loadAndCreatePaneControlsWidget(){ Promise.all([Promise.all([i.e(1283),i.e(62253),i.e(22666),i.e(92108),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(34465),i.e(69121),i.e(66639),i.e(30006),i.e(88194),i.e(35649),i.e(89842),i.e(26855),i.e(99916),i.e(40812),i.e(36956),i.e(56388),i.e(9227),i.e(48450),i.e(61572),i.e(50690),i.e(88087),i.e(59255),i.e(8010),i.e(34654),i.e(62526),i.e(80870),i.e(46513),i.e(5093)]).then(i.bind(i,580723)),Promise.all([i.e(1283),i.e(62253),i.e(22666),i.e(92108),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(34465),i.e(69121),i.e(66639),i.e(30006),i.e(88194),i.e(35649),i.e(89842),i.e(26855),i.e(99916),i.e(40812),i.e(36956),i.e(56388),i.e(9227),i.e(48450),i.e(61572),i.e(50690),i.e(88087),i.e(59255),i.e(8010),i.e(34654),i.e(62526),i.e(80870),i.e(46513),i.e(5093)]).then(i.bind(i,159255))]).then((([e,t])=>{var i;if(this._isDestroyed)return;const s=e.PaneControlsWidget;this._paneControls=new s(this._chartUndoModel(),this,{backgroundThemeName:this._chart.backgroundTopTheme()},{toggleMaximizePane:this._chart.toggleMaximizePane.bind(this._chart)},this._div),this._paneControls.updateWidgetModeByWidth(this._size.width),this._paneControls.updateThemedColors(this._themedTopColor),this._paneControlsResizeObserver=new t.default(this._handleRestrictLegendWidth.bind(this)),this._paneControlsResizeObserver.observe(this._paneControls.getElement()),(null===(i=this._state)||void 0===i?void 0:i.collapsed().value())&&this._chartModel().fullUpdate()}))}_handleRestrictLegendWidth(e){if(null===this._legendWidget||null===this._paneControls)return;const t=e[e.length-1].contentRect.width,i=0===t?0:t+$t+Xt;this._legendWidget.addMargin(i)}_onMagnetStateChanged(){this._chart.isActive().value()&&(this._isSelectPointModeEnabled()||this._isToolActionActiveOnPane(!0))&&this._chartModel().crossHairSource().visible&&this._updateLineToolUsingMagnetOrShift()}_onShiftKeyStateChanged(){this._chart.isActive().value()&&this._isToolActionActiveOnPane(!1)&&this._chartModel().crossHairSource().visible&&this._updateLineToolUsingMagnetOrShift(Re.EnvironmentState.create((0,G.shiftPressed)().value()))}_isToolActionActiveOnPane(e){const t=this._chartModel(),i=t.lineBeingCreated()||t.lineBeingEdited()||t.sourcesBeingMoved().length>0&&t.sourcesBeingMoved()[0];return i?t.paneForSource(i)===this._state:e&&(0,Ht.isLineToolName)(Ve.tool.value())&&t.crossHairSource().pane===this._state}_updateLineToolUsingMagnetOrShift(e){if(null===this._prevMoveEventPosition)return;const{x:t,y:i}=this._prevMoveEventPosition,s=this._chartModel().sourcesBeingMoved();s.length>0?(Ve.isStudyEditingNow.value()&&this.setCursorPosition(t,i,e),this._alignSourcesThatBeingMoved(s,t,i,e)):this.setCursorPosition(t,i,e)}_showEditDialogForSource(e,t){if(this._options.propertyPagesEnabled&&e.userEditEnabled())if(e===this._chartUndoModel().mainSeries())this._chart.showGeneralChartProperties(K.TabNames.symbol);else if((0,te.isLineTool)(e)||(0,$.isStudy)(e)||(0,Q.isLollipopDataSource)(e)){let i;const s=null==t?void 0:t.data();if(null!=s){const e=s.areaName;void 0!==e&&(i=_i.get(e))} this._chart.showChartPropertiesForSource(e,i).then((e=>{this._editDialog=e}))}}_initToolCreationModeParams(e){this._startTouchPoint=new Ee.Point(e.pageX,e.pageY),this._initCrossHairPosition=this._chartModel().crossHairSource().currentPoint()}_updateCrosshairPositionInToolCreationMode(e,t){if(t!==this._state){const i=this._chart.paneByState(t);return i._startTouchPoint=this._startTouchPoint,i._initCrossHairPosition=this._initCrossHairPosition,void i._updateCrosshairPositionInToolCreationMode(e,t)}const i=this._chartModel().crossHairSource();this._chart.justActivated()&&(this._initCrossHairPosition=i.currentPoint());const s=e.pageX,o=e.pageY,n=(0,r.ensureNotNull)(this._initCrossHairPosition),a=new Ee.Point(s,o).subtract((0,r.ensureNotNull)(this._startTouchPoint)),l=n.add(a);this.setCursorPosition(l.x,l.y,new Re.EnvironmentState(e))}_priceAxisesContainer(e){return"left"===e?this._lhsPriceAxisesContainer:this._rhsPriceAxisesContainer}_recalculatePriceScales(e){const t=this.state();for(const i of t.leftPriceScales())t.recalculatePriceScale(i,e);for(const i of t.rightPriceScales())t.recalculatePriceScale(i,e);for(const i of t.sourcesByGroup().overlayPriceScaleSources())(0,te.isLineTool)(i)||t.recalculatePriceScale(i.priceScale(),e)}_createLockTimeAxisAction(e){var t;const i=0===(null===(t=Ve.crosshairLock.value())||void 0===t?void 0:t.type);return new F.Action({actionId:"Chart.Crosshair.LockVerticalCursor",options:{label:ii,statName:"LockCursorInTime",checkable:!0,checked:i,onExecute:()=>this._toggleLockTimeAxis(e.localX,!i)}})}_toggleLockTimeAxis(e,t){if(t){const t=this._chartUndoModel().timeScale(),i=t.coordinateToIndex(e),s=t.points().roughTime(i);if(null!==s)return void Ve.crosshairLock.setValue({type:0,time:s})}Ve.crosshairLock.setValue(null)}_preventTouchEventsExceptPinch(){return this._paneWidgetsSharedState.hasTouchesOnOtherPanes(this)||null!==this._paneWidgetsSharedState.pinchingPane()}_updateHoveredSource(e,t,i){var s,o;const r=this._chartUndoModel(),n=r.model();let a=!1;const l=e&&e.source,c=this._chart.readOnly();if(n.crossHairSource().isReplaySelection())this._setCursorClassName("none");else if(!(!c||e&&(0,te.isLineTool)(e.source))||this._editDialog&&this._editDialog.visible().value())c&&(n.setHoveredSource(null,null),this.setCursorForTool());else{const h=Ve.tool.value();let d=null;if(!this._processing&&((0,Ve.toolIsCursor)(h)||"eraser"===h&&!c||t.mod()||!r.lineBeingCreated())){const t=null==e?void 0:e.hittest;a=Boolean(null===(s=null==t?void 0:t.data())||void 0===s?void 0:s.hideCrosshairLinesOnHover),t&&t.target()>Ne.HitTarget.MovePointBackground?(d=l,!(null==l?void 0:l.isHoveredEnabled())||"eraser"===h&&l===r.mainSeries()?n.setHoveredSource(null,null):n.setHoveredSource(l,t.data())):n.setHoveredSource(null,null)}c?this.setCursorForTool(d,t,zt.PaneCursorType.Default):this._options.sourceSelectionEnabled&&(this._isSelectPointModeEnabled()?this._setCursorClassName("pointer"):this.setCursorForTool(d,t,null===(o=null==e?void 0:e.hittest.data())||void 0===o?void 0:o.cursorType)) ;const u=n.customSourceBeingMoved(),_=null!==u?[u]:n.sourcesBeingMoved();if((!_.length||null!==e&&-1===_.indexOf(e.source))&&this._updateCommonTooltip(e),!c&&null!==e&&i&&e.hittest.hasPressedMoveHandler(i)){switch((e.hittest.data()||{}).cursorType){case zt.PaneCursorType.VerticalResize:this._setCursorClassName("ns-resize");break;case zt.PaneCursorType.HorizontalResize:this._setCursorClassName("we-resize");break;case zt.PaneCursorType.DiagonalNeSwResize:this._setCursorClassName("nesw-resize");break;case zt.PaneCursorType.DiagonalNwSeResize:this._setCursorClassName("nwse-resize")}}}this._preventCrossHairMove()&&this._clearCursorPosition(),1!==this._pressedMoveStage&&n.crossHairSource().setLinesShouldBeHidden(a)}async _createErrorBlock(){const e=new(await(0,le.getErrorCardRenderer)());return this._div.insertBefore(e.container,this._topCanvasBinding.canvasElement.nextSibling),e}_customActions(){const e={top:[],bottom:[],remove:[]},t=this._chartUndoModel().timeScale(),i=this._state&&this._state.defaultPriceScale();if(!B.enabled("custom_items_in_context_menu"))return e;const s=t.isEmpty()?void 0:t.indexToUserTime(t.coordinateToIndex(this._contextMenuX));let o;if(i&&!i.isEmpty()){const e=(0,r.ensureNotNull)(this.state().mainDataSource()).firstValue();o=i.coordinateToPrice(this._contextMenuY,(0,r.ensureNotNull)(e))}return(0,l.emit)("onContextMenu",{unixtime:null!=s?s.getTime()/1e3:void 0,price:o,callback:t=>{[...t].forEach((t=>{if(t.text)if(t.text.length>1&&"-"===t.text[0])e.remove.push(t.text.slice(1));else{let i;i="-"===t.text?new F.Separator:new F.Action({actionId:"Chart.ExternalActionId",options:{label:t.text,onExecute:t.click}}),t.position&&"top"===t.position?e.top.push(i):e.bottom.push(i)}}))}}),e}_highlightPriceAxisByLabel(e){this._lhsPriceAxisesContainer.highlightPriceAxisByLabel(e),this._rhsPriceAxisesContainer.highlightPriceAxisByLabel(e)}_subscribeToState(){const e=this.state();e.onDestroyed().subscribe(this,this._onStateDestroyed,!0),e.dataSourcesCollectionChanged().subscribe(this,this._onDataSourcesCollectionChanged),e.maximized().subscribe(this._updateVisuallyCollapsed),e.collapsed().subscribe(this._updateVisuallyCollapsed)}_unsubscribeFromState(){const e=this.state();e.onDestroyed().unsubscribeAll(this),e.dataSourcesCollectionChanged().unsubscribeAll(this),e.maximized().unsubscribe(this._updateVisuallyCollapsed),e.collapsed().unsubscribe(this._updateVisuallyCollapsed)}_updateAccesibilityAttr(){if(this.state().isMainPane()){const e=this._chartModel().mainSeries(),t=e.symbol(),s=(0,Yt.getTranslatedResolutionModel)(e.interval()).hint,o=a.t(null,{replace:{symbol:t,interval:s}},i(88732));this._topCanvasBinding.canvasElement.setAttribute("aria-label",o)}else this._topCanvasBinding.canvasElement.setAttribute("aria-hidden","true")}async _updateEndOfSeriesBanner(){var e,t,s,o;{const n=()=>{var e,t;if(window.user.is_pro)return null;const i=this._state;if(!i)return null===(e=this._endOfSeriesDataBanner)||void 0===e||e.setVisible(!1),null;if(!this._chart.isActive().value())return null;const s=i.model().mainSeries() ;if(!s)return null;if(!i.isMainPane())return null;if(2===s.status()||s.requestMoreDataAvailable())return null===(t=this._endOfSeriesDataBanner)||void 0===t||t.setVisible(!1),null;const o=s.bars().firstIndex();return null===o?null:{state:i,series:s,firstIndex:o}},a=()=>{if(this._legendWidget){const e=this._legendWidget.getElement().getBoundingClientRect();return e.bottom-e.top}return 0};let l=n();if(!l||"end"===l.series.endOfDataType())return void(null===(e=this._endOfSeriesDataBanner)||void 0===e||e.setVisible(!1));l.series.doNotShowLastAvailableBar(!1);const c=l.series.endOfDataType(),h=(0,r.ensureNotNull)(this._state).model().timeScale().indexToCoordinate(l.firstIndex)-l.state.model().timeScale().barSpacing();if(!this._endOfSeriesDataBanner&&!B.enabled("widget")){const e=await Promise.all([i.e(62253),i.e(22666),i.e(92108),i.e(92191),i.e(32109),i.e(9817),i.e(66639),i.e(26855),i.e(92706),i.e(50690),i.e(62526),i.e(66849)]).then(i.bind(i,939651));if(l=n(),!l)return;this._endOfSeriesDataBanner||(this._endOfSeriesDataBanner=new e.EndOfSeriesBanner,this._div.appendChild(this._endOfSeriesDataBanner.element()))}const d=a();null===(t=this._endOfSeriesDataBanner)||void 0===t||t.setVisible(!0),null===(s=this._endOfSeriesDataBanner)||void 0===s||s.update(l.state,d,h,c);const u=null===(o=this._endOfSeriesDataBanner)||void 0===o?void 0:o.currentSize();l.series.doNotShowLastAvailableBar(null!==u&&0!==u)}}}class vi{constructor(){this._draggingSource=null,this._activeTouchPanes=new Set,this._scrollingPane=null,this._pinchingPane=null}onPaneDestroyed(e){this._activeTouchPanes.delete(e),this._scrollingPane===e&&(this._scrollingPane=null),this._pinchingPane===e&&(this._pinchingPane=null)}startTouch(e){this._activeTouchPanes.add(e)}endTouch(e){this._activeTouchPanes.delete(e)}hasTouchesOnOtherPanes(e){return this._activeTouchPanes.size>1||1===this._activeTouchPanes.size&&!this._activeTouchPanes.has(e)}trySetDraggingSource(e,t){return!this.hasTouchesOnOtherPanes(t)&&((0,r.assert)(null===this._draggingSource||this._draggingSource===e),this._draggingSource=e,!0)}clearDraggingSource(){null!==this._draggingSource&&(this._draggingSource=null)}draggingSource(){return this._draggingSource}setScrollingPane(e){(0,r.assert)(null===e||null===this._scrollingPane||this._scrollingPane===e),this._scrollingPane=e}scrollingPane(){return this._scrollingPane}setPinchingPane(e){(0,r.assert)(null===e||null===this._pinchingPane||this._pinchingPane===e),this._pinchingPane=e}pinchingPane(){return this._pinchingPane}}var fi=i(970109),bi=i(30574);i(100658);const yi={contextMenuEnabled:!0,timezoneMenuEnabled:!0,pressedMouseMoveScale:!0},Ci=new V.TranslatedString("change session",a.t(null,void 0,i(765303))),wi=a.t(null,void 0,i(25866));class Pi{constructor(e,t,i,o,r){this._rendererOptions=null,this._onLabelHovered=new N.Delegate,this._mousedown=!1,this._currentCursorClassName="invalid",this._options=(0,T.merge)((0,T.clone)(yi),t||{}),this.chart=e,this._properties=e.properties().childs().scalesProperties,this._element=document.createElement("div"), this._element.style.display="flex",this._backgroundBasedTheme=r;const n=e.model().model().rendererOptionsProvider(),a=()=>this.backgroundColor(),l=()=>{throw new Error("Time axis does not support real price scales")},c={titlesProvider:i,stubContextMenuProvider:(e,t)=>{const i=o(e,t),s=this.getContextMenuActions(!0);return 0===s.length?i:i.concat(new F.Separator,s)},backgroundBasedTheme:r.spawnOwnership(),onActiveOrHoveredChart:(0,E.combine)(((e,t)=>e||t),this.chart.isActive().weakReference(),this.chart.isHovered().weakReference()).ownership(),rendererOptionsProvider:n,getBackgroundTopColor:a,getBackgroundBottomColor:a,requestRepaint:()=>this.chart.model().model().lightUpdate(),showHorizontalBorder:!0};this._lhsStubContainer=new Je(this._properties,"left",l,c,this._options.priceAxisLabelsOptions,this),this._lhsStubContainer.onLabelHovered().subscribe(this,((e,t)=>{this._onLabelHovered.fire(e,t)})),this._rhsStubContainer=new Je(this._properties,"right",l,c,this._options.priceAxisLabelsOptions,this),this._rhsStubContainer.onLabelHovered().subscribe(this,((e,t)=>{this._onLabelHovered.fire(e,t)})),this._element.appendChild(this._lhsStubContainer.getElement()),this._cell=document.createElement("div"),this._element.appendChild(this._cell),this._cell.classList.add("chart-markup-table","time-axis"),this._cell.style.height="25px",this._dv=document.createElement("div"),this._dv.style.width="100%",this._dv.style.height="100%",this._dv.style.position="relative",this._dv.style.overflow="hidden",this._cell.appendChild(this._dv),this._canvasConfiguredHandler=()=>this.chart.model().model().lightUpdate(),this._canvasBinding=(0,U.createBoundCanvas)(this._dv,(0,s.size)({width:16,height:16})),this._canvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const h=this._canvasBinding.canvasElement;h.style.position="absolute",h.style.zIndex="1",h.style.left="0",h.style.top="0",this._topCanvasBinding=(0,U.createBoundCanvas)(this._dv,(0,s.size)({width:16,height:16})),this._topCanvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const d=this._topCanvasBinding.canvasElement;d.style.position="absolute",d.style.zIndex="2",d.style.left="0",d.style.top="0",xe.PLATFORM_ACCESSIBILITY_ENABLED&&this._dv.setAttribute("aria-hidden","true"),this._element.appendChild(this._rhsStubContainer.getElement()),this.restoreDefaultCursor(),this.update(),this._minVisibleSpan=fi.MINUTE_SPAN,this._mouseEventHandler=new Me.MouseEventHandler(this._topCanvasBinding.canvasElement,this,{treatVertTouchDragAsPageScroll:!0,treatHorzTouchDragAsPageScroll:!1}),this.size=(0,s.size)({width:0,height:0})}destroy(){this._mouseEventHandler.destroy(),this._topCanvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._topCanvasBinding.dispose(),this._canvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._canvasBinding.dispose(),this._rhsStubContainer.onLabelHovered().unsubscribeAll(this),this._lhsStubContainer.onLabelHovered().unsubscribeAll(this), this._lhsStubContainer.destroy(),this._rhsStubContainer.destroy(),this.chart.properties().childs().paneProperties.childs().background.unsubscribeAll(this),this._backgroundBasedTheme.release()}setCursor(e){let t="";"grabbing"!==e&&"ew-resize"!==e||(t="time-axis--cursor-"+e),this._currentCursorClassName!==t&&(this._currentCursorClassName&&this._cell.classList.remove(this._currentCursorClassName),t&&this._cell.classList.add(t),this._currentCursorClassName=t,this._cell.style.cursor)}restoreDefaultCursor(){this.setCursor("")}getElement(){return this._element}optimalHeight(){const e=this.rendererOptions();return Math.ceil(e.borderSize+e.offsetSize+e.fontSize+e.paddingTop+e.paddingBottom+e.labelBottomOffset)}setSizes(e,t,i){this.size&&(0,s.equalSizes)(this.size,e)||(this.size=e,this._canvasBinding.resizeCanvasElement(e),this._topCanvasBinding.resizeCanvasElement(e),this._cell.style.width=e.width+"px",this._cell.style.height=e.height+"px"),this._lhsStubContainer.setSizes(e.height,t),this._rhsStubContainer.setSizes(e.height,i)}rendererOptions(){if(!this._rendererOptions||this._rendererOptions.fontSize!==this.fontSize()){const e=this.fontSize();this._rendererOptions={borderSize:1,offsetSize:5,fontSize:e,font:(0,He.makeFont)(e,qe.CHART_FONT_FAMILY,""),widthCache:new ze.TextWidthCache,paddingTop:3*e/12,paddingBottom:3*e/12,paddingHorizontal:9*e/12,labelBottomOffset:4*e/12}}return this._rendererOptions}backgroundColor(){return this.chart.model().model().backgroundColor().value()}lineColor(){const e=this._properties.childs().lineColor.value();if(0===(0,Pe.parseRgba)(e)[3]){const e=this.chart.model().model().lastPane();if(e&&(e.collapsed().value()||e.isMainPane()&&this._areEventsEnabled()))return this.chart.properties().childs().paneProperties.childs().separatorColor.value()}return e}textColor(){return this._properties.childs().textColor.value()}fontSize(){return this._properties.childs().fontSize.value()}baseFont(){return(0,He.makeFont)(this.fontSize(),qe.CHART_FONT_FAMILY)}baseBoldFont(){return(0,He.makeFont)(this.fontSize(),qe.CHART_FONT_FAMILY,"","bold")}hasCanvas(e){return this._canvasBinding.canvasElement===e||this._topCanvasBinding.canvasElement===e}onLabelHovered(){return this._onLabelHovered}getScreenshotData(){return{content:this._canvasBinding.canvasElement.toDataURL(),canvas:this._canvasBinding.canvasElement,contentWidth:this.size.width,contentHeight:this.size.height,lhsStub:this._lhsStubContainer.getScreenshotData(),rhsStub:this._rhsStubContainer.getScreenshotData()}}getContextMenuActions(e){var t;const i=this.chart;i.updateActions();const s=i.actions(),o=[];if(e||(i.model().timeScale().resetAvailable().value()&&(o.push(s.timeScaleReset),o.push(new F.Separator)),this._options.timezoneMenuEnabled&&o.push(s.applyTimeZone),o.push(s.sessionBreaks)),!i.model().mainSeries().isDWM()){const e=null===(t=i.model())||void 0===t?void 0:t.mainSeries().symbolInfo();if(e){const t=i.model().mainSeries().properties().childs().sessionId,s=(e.subsessions||[]).filter((e=>!e.private));if(s.length>1){const e=s.map((e=>new F.Action({ actionId:"Chart.SetSession",options:{label:(0,bi.translateSessionDescription)(e.description),checkable:!0,checked:t.value()===e.id,statName:"SetSession",onExecute:()=>{i.model().setProperty(t,e.id,Ci)}}}))),r=new F.Action({actionId:"Chart.SetSession",options:{label:wi,statName:"SetSession",subItems:e}});o.push(r)}}}return o}update(){if(!this.chart.hasModel())return;const e=this.chart.model().timeScale().marks();if(e){this._minVisibleSpan=fi.YEAR_SPAN;for(const t of e)this._minVisibleSpan=Math.min(t.span,this._minVisibleSpan)}}updatePriceAxisStubs(){const e=this.chart.model().model(),t=this.chart.isMaximizedPane()?(0,r.ensureNotNull)(this.chart.maximizedPaneWidget()).state():e.paneForSource(e.mainSeries());if(!t)return;const i=e.priceScaleSlotsCount();this._lhsStubContainer.setScales([],i.left,t.leftPriceScales().length,i.left+i.right),this._rhsStubContainer.setScales([],i.right,t.rightPriceScales().length,i.left+i.right)}paint(e){if(e===me.InvalidationLevel.None||0===this.size.width||0===this.size.height)return;(0,U.tryApplySuggestedCanvasBitmapSize)(this._canvasBinding),(0,U.tryApplySuggestedCanvasBitmapSize)(this._topCanvasBinding);const t=(0,U.getContext2D)(this._topCanvasBinding.canvasElement);if(e>me.InvalidationLevel.Cursor){const i=(0,U.getContext2D)(this._canvasBinding.canvasElement),s=(0,U.getBindingPixelRatio)(this._canvasBinding);this.drawBackground(i,s),this.chart.hasModel()&&(this.drawBorder(i,s),this.drawTickMarks(i,s),this.drawBackLabels(i,s),this.drawCrossHairLabel(t,s)),this._lhsStubContainer.paintStubs(e),this._rhsStubContainer.paintStubs(e)}this.drawCrossHairLabel(t,(0,U.getBindingPixelRatio)(this._topCanvasBinding))}drawBackground(e,t){if((0,U.clearRect)(e,0,0,Math.ceil(this.size.width*t)+1,Math.ceil(this.size.height*t)+1,this.backgroundColor()),!this.chart.hasModel())return;const i=this.chart.model();if(!i.timeScale().isEmpty()){const s=i.model().selection().lineDataSources().reduce(((e,t)=>{const i=t.timeAxisPoints();return 0===i.length?e:e.concat(i)}),[]);s.length>0&&this._hightlightBackground(e,s,t)}const s=i.model().crossHairSource();s.startMeasurePoint()&&this._hightlightBackground(e,s.measurePoints(),t)}drawBorder(e,t){e.save(),e.fillStyle=this.lineColor();const i=Math.max(1,Math.floor(this.rendererOptions().borderSize*t)),s=Math.ceil(this.size.width*t);e.fillRect(0,0,s+1,i),e.restore()}drawTickMarks(e,t){const i=this.chart.model().timeScale().marks();if(!i||0===i.length)return;let s=i.reduce(((e,t)=>e.span>t.span?e:t),i[0]).span;s>30&&s<40&&(s=30),e.save(),e.strokeStyle=this.lineColor();const o=this.rendererOptions(),r=o.borderSize+o.offsetSize+o.paddingTop+o.fontSize/2;e.textAlign="center",e.textBaseline="middle",e.fillStyle=this.textColor(),(0,U.drawScaled)(e,t,t,(()=>{e.font=this.baseFont();for(let t=0;t=s&&e.fillText(o.label,o.coord,r)}})),e.restore()}drawBackLabels(e,t){var i;e.save();const s=new Set,o=this.chart.model().model() ;let r=o.dataSources();const n=o.selection().allSources();for(const e of n)s.add(e);o.hoveredSource()&&s.add(o.hoveredSource());for(const e of o.sourcesBeingMoved())s.add(e);const a=o.customSourceBeingMoved();null!==a&&s.add(a);const l=null!==(i=o.lineBeingEdited())&&void 0!==i?i:o.lineBeingCreated();l&&s.add(l),s.add(this.chart.model().crossHairSource()),r=r.concat(o.customSources());const c=this.rendererOptions();for(let i=0;i=s&&(s=a,r=n),a<=i&&(i=a,o=n)}}return r&&t.push(r),o&&t.push(o),t}_zoomAvailable(){return!this.chart.model().timeScale().isEmpty()&&this.chart.model().model().zoomEnabled()&&this._options.pressedMouseMoveScale}_mouseDownOrTouchStartEvent(e){if(this._mousedown||!this._zoomAvailable())return;this._mousedown=!0;const t=this.chart.model();t.timeScale().isEmpty()||t.startScaleTime(e.localX)}_pressedMouseOrTouchMoveEvent(e){this._zoomAvailable()&&this.chart.model().scaleTimeTo(e.localX)}_mouseUpOrTouchEndEvent(e){this._zoomAvailable()&&(this._mousedown=!1,this.chart.model().endScaleTime(),this.restoreDefaultCursor())}_contextMenuOrTouchContextMenuEvent(e){this._options.contextMenuEnabled&&Ue.ContextMenuManager.showMenu(this.getContextMenuActions(),e,{statName:"TimeScaleContextMenu"},{menuName:"TimeScaleContextMenu"})}_mouseOrTouchEnterEvent(e){this._zoomAvailable()&&this.setCursor("ew-resize")}_mouseOrTouchLeaveEvent(e){this.restoreDefaultCursor()}_mouseDoubleClickOrDoubleTapEvent(e){(0,_.trackEvent)("GUI","Double click time scale"),this.chart.model().resetTimeScale()}_areEventsEnabled(){var e;{const t=this.chart.model().mainSeries();switch(null===(e=t.symbolInfo())||void 0===e?void 0:e.type){case"forex":case"cfd":return!B.enabled("widget")&&this.chart.model().model().properties().childs().chartEventsSourceProperties.childs().visible.value();case"stock":case"fund":if(!B.enabled("widget")||B.enabled("esdonwidget")){const{esdShowDividends:e,esdShowSplits:i,esdShowEarnings:s}=t.properties().childs();return e.value()||i.value()||s.value()}return!1;default:return!1}}}}var Ti=i(466743);var Mi=i(853965),xi=i(982217),Ii=i(347710),Ai=i(553582),Li=i(359663),ki=i(709404),Ei=i(31214),Di=i(67302),Ni=i(776734),Bi=i(405117),Ri=i(234271);class Oi{constructor(){this._session={startDate:(new Date).toISOString(),url:window.location.href,entries:[]}}addPersistentLogEntry(e,t,i){this._session.entries.push({date:(new Date).toISOString(),level:t,message:e,category:i})}async getLastSessions(e){return[this._session]}pendingEntries(){return this._session.entries}}var Vi=i(33900),Wi=i(232650),Fi=i(72368),Hi=i(105580),zi=i(700134),Ui=i(74439),Gi=i(147675),qi=i(786559);const ji=a.t(null,void 0,i(123536));function Yi(e){if("replaced_to_exchange"===e.type)return{text:ji,warningIcon:qi,warningType:"notaccurate",solutionId:ce.solutionIds.WHAT_IS_CBOE_BZX_EXCHANGE}}class Ki{constructor(e){this._activeHint=null,this._deferredPromise=null,this._chart=e;e.model().mainSeries().dataEvents().symbolResolved().subscribe(this,this._onSymbolResolved)}destroy(){this._destroyActiveHint();this._chart.model().mainSeries().dataEvents().symbolResolved().unsubscribe(this,this._onSymbolResolved)}_destroyActiveHint(){null!==this._activeHint&&(this._activeHint.destroy(),this._activeHint=null),this._deferredPromise=null}async _createHint(){if(null===this._deferredPromise){const e=(0,v.createDeferredPromise)();this._deferredPromise=e, Promise.all([i.e(32109),i.e(6209),i.e(28497),i.e(50690),i.e(83129)]).then(i.bind(i,629981)).then((t=>{e.resolve(new t.ChartWarningHintRenderer(this._chart))}))}return this._deferredPromise.promise}_onSymbolResolved(e){const t=function(e){const t=(0,Gi.firstReplacedByBatsExchange)(e);return null!==t?{type:"replaced_to_exchange",exchange:t}:null}(e),i=t&&function(e){return`warning.noSubsc_${e.exchange}`}(t);if(null===t||null===i||Boolean(d.getBool(i)))return void this._destroyActiveHint();const s={...Yi(t),onClose:()=>{d.setValue(i,!0,{forceFlush:!0}),this._destroyActiveHint()}};null!==this._activeHint?this._activeHint.show(s):this._createHint().then((e=>{this._activeHint=e,this._activeHint.show(s)}))}}var Zi=i(125226),$i=i(833813);function Xi(e){return e.hasModel()?e.model().mainSeries().proSymbol():e.symbolWV().value()}var Ji=i(167222);function Qi(e,t){return{...t,iconId:"Watchlist.AddSymbol",icon:z.icons.get("Watchlist.AddSymbol"),statName:"AddToWatchlist",hotkeyHash:ot.Modifiers.Alt+87,onExecute:()=>{(0,Ji.runOrSigninWithFeature)((()=>{var t;if(window.widgetbar){const i=null===(t=(0,r.ensureNotNull)(window.widgetbar.setPage("base")).widget("watchlist"))||void 0===t?void 0:t.widgetObject;if(!i)return;i.addSymbols([Xi(e)])}}),{feature:"watchList",source:"add symbol to watchlist"})}}}var es=i(306388),ts=i(826939),is=i(440498);class ss extends F.Action{constructor(e,t){super({actionId:"Chart.AddSymbolToWatchList",options:{...Qi(e,t),subItems:[new F.Loader("Loading")]}}),this._hadSymbolOnInit=!1,this._isMobile=(0,Fi.isMobile)(),this._onRequest=null,this._unsubscribe=null,this._chart=e,this._load()}updateLabel(e){this.update({label:a.t(null,void 0,i(655980)).format({symbol:e})})}request(){var e;this._hadSymbolOnInit=!1,this._isMobile=(0,Fi.isMobile)(),this.update({subItems:[new F.Loader("Loading")]}),null===(e=this._onRequest)||void 0===e||e.call(this)}destroy(){var e;super.destroy(),null===(e=this._unsubscribe)||void 0===e||e.call(this),this._chart=null,this._onRequest=null}async _load(){const[e,t,s,o,r,n,l]=await Promise.all([Promise.resolve().then(i.t.bind(i,50959,19)),(0, es.initSymbolListService)(),Promise.all([i.e(62253),i.e(22666),i.e(92108),i.e(92191),i.e(32109),i.e(9817),i.e(34465),i.e(69121),i.e(66639),i.e(30006),i.e(88194),i.e(26855),i.e(40812),i.e(50690),i.e(88087),i.e(29594),i.e(8010),i.e(34654),i.e(62526),i.e(80870),i.e(5069),i.e(65973),i.e(1026)]).then(i.bind(i,38506)),Promise.all([i.e(62253),i.e(22666),i.e(92108),i.e(92191),i.e(32109),i.e(9817),i.e(34465),i.e(69121),i.e(66639),i.e(30006),i.e(88194),i.e(26855),i.e(40812),i.e(50690),i.e(88087),i.e(29594),i.e(8010),i.e(34654),i.e(62526),i.e(80870),i.e(5069),i.e(65973),i.e(1026)]).then(i.bind(i,244692)),Promise.all([i.e(51495),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(93502),i.e(66639),i.e(30006),i.e(88194),i.e(35649),i.e(36884),i.e(89842),i.e(88548),i.e(46036),i.e(26855),i.e(91033),i.e(36747),i.e(58056),i.e(21625),i.e(49205),i.e(8740),i.e(67080),i.e(54712),i.e(15518),i.e(99916),i.e(40812),i.e(36956),i.e(56388),i.e(9227),i.e(52251),i.e(98149),i.e(58289),i.e(12494),i.e(35542),i.e(56949),i.e(59185),i.e(51494),i.e(60682),i.e(21770),i.e(1793),i.e(20733),i.e(40153),i.e(61094),i.e(50690),i.e(30979),i.e(88087),i.e(29594),i.e(93869),i.e(61536),i.e(58510),i.e(80870),i.e(46513),i.e(65973),i.e(41537),i.e(6925),i.e(39418),i.e(38859),i.e(63270),i.e(91196)]).then(i.bind(i,15814)),Promise.all([i.e(51495),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(93502),i.e(66639),i.e(30006),i.e(88194),i.e(35649),i.e(36884),i.e(89842),i.e(88548),i.e(46036),i.e(26855),i.e(91033),i.e(36747),i.e(58056),i.e(21625),i.e(49205),i.e(8740),i.e(67080),i.e(54712),i.e(15518),i.e(99916),i.e(40812),i.e(36956),i.e(56388),i.e(9227),i.e(52251),i.e(98149),i.e(58289),i.e(12494),i.e(35542),i.e(56949),i.e(59185),i.e(51494),i.e(60682),i.e(21770),i.e(1793),i.e(20733),i.e(40153),i.e(61094),i.e(50690),i.e(30979),i.e(88087),i.e(29594),i.e(93869),i.e(61536),i.e(58510),i.e(80870),i.e(46513),i.e(65973),i.e(41537),i.e(6925),i.e(39418),i.e(38859),i.e(63270),i.e(91196)]).then(i.bind(i,436779)),Promise.all([i.e(51495),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(93502),i.e(66639),i.e(30006),i.e(88194),i.e(35649),i.e(36884),i.e(89842),i.e(88548),i.e(46036),i.e(26855),i.e(91033),i.e(36747),i.e(58056),i.e(21625),i.e(49205),i.e(8740),i.e(67080),i.e(54712),i.e(15518),i.e(99916),i.e(40812),i.e(36956),i.e(56388),i.e(9227),i.e(52251),i.e(98149),i.e(58289),i.e(12494),i.e(35542),i.e(56949),i.e(59185),i.e(51494),i.e(60682),i.e(21770),i.e(1793),i.e(20733),i.e(40153),i.e(61094),i.e(50690),i.e(30979),i.e(88087),i.e(29594),i.e(93869),i.e(61536),i.e(58510),i.e(80870),i.e(46513),i.e(65973),i.e(41537),i.e(6925),i.e(39418),i.e(38859),i.e(63270),i.e(91196)]).then(i.bind(i,631530))]);if(this._destroyed)return;const{store:c}=t;this._onRequest=()=>c.dispatch(s.getCustomWatchlistsThunk(null)),this._unsubscribe=c.subscribe((()=>{if(!this._chart)return;const t=c.getState() ;if(null===r.getCustomListsState(t).timestamp)return;const s=Xi(this._chart),h=r.getCustomLists(t),{activeSymbolList:d}=t,u=h.find((e=>e.id===d));this._hadSymbolOnInit||(this._hadSymbolOnInit=!!u&&u.symbols.includes(s));const _=B.enabled("multiple_watchlists")?h.filter((e=>e.id!==d)).sort(n.sortComparator):[];let p=u?[u,..._]:_;p=p.filter((e=>!(0,is.isDeletedSymbolsList)(e.id)));const m=p.map((t=>{const i=t.symbols.includes(s),r={shortcutHint:t.id===d?(0,ot.humanReadableHash)(ot.Modifiers.Alt+87):void 0,invisibleHotkey:t.id===d?i:void 0,doNotCloseOnClick:!0,onExecute:()=>{const e=i?o.removeSymbolsThunk(ts.WATCHLIST_WIDGET_ID,s,t.id,!0):o.addSymbolsToCustomListThunk(ts.WATCHLIST_WIDGET_ID,t.id,[s]);t.id!==d||window.is_authenticated||this._hadSymbolOnInit?c.dispatch(e):window.runOrSignIn((()=>{c.dispatch(e)}),{source:"Chart context menu"})}};return new F.Action({actionId:"Watchlist.Actions",options:{...r,label:t.name,checkable:!0,checked:i},customActionOptions:{...r,jsxLabel:e.createElement(l.ContextMenuWatchlistItem,{title:t.name,isChecked:i,isSmallSize:this._isMobile})}})})),g=new F.Action({actionId:"Watchlist.Create",options:{label:(0,S.appendEllipsis)(a.t(null,void 0,i(732340))),iconId:this._isMobile?"Watchlist.CreateNew":void 0,onExecute:()=>{(0,Ei.runOrGoPro)((()=>{c.dispatch(o.userCreateWatchlistThunk(null,{symbols:[s]}))}),$i.ProductFeatures.MULTIPLE_WATCHLISTS,{feature:"multipleWatchLists",featureLocation:"moveSymbolsToNew"})}}});this.update({subItems:[...m,new F.Separator,g]})}))}}var os=i(634447);function rs(){const e=window.widgetbar;if(e){const t=(0,r.ensureNotNull)(e.setPage("object_tree")),i=(0,r.ensureNotNull)(t.widget("object_tree"));(0,r.ensureDefined)(i.properties).setValue({selectedPage:"data-window"})}else;}var ns=i(521506);i(586463);const as=a.t(null,void 0,i(858018));class ls extends class{constructor(e){this._lastResolvedSymbol=null,this._chart=e,this._chart.withModel(this,this._connectToModel)}_getPopupContent(){const e=this._getProSymbol(),t=new URL("https://www.tradingview.com/chart/");t.searchParams.append("symbol",e),t.searchParams.append("utm_source","www.tradingview.com"),t.searchParams.append("utm_medium","widget"),t.searchParams.append("utm_campaign","chart"),t.searchParams.append("utm_term",e);return as.format({linkStart:``,linkEnd:""})}_onPopupClosed(){const e=this._chart.defaultSymbol(),t=this._getSymbol();let i;i=this._lastResolvedSymbol?this._lastResolvedSymbol:e!==t?e:"AAPL",this._chart.setSymbol(i)}_getProSymbol(){return this._chart.model().mainSeries().proSymbol()}_getSymbol(){return this._chart.model().mainSeries().actualSymbol()}_connectToModel(){const e=this._chart.model().mainSeries();e.dataEvents().symbolResolved().subscribe(this,this._onSymbolResolved),e.dataEvents().symbolGroupNotPermitted().subscribe(this,this._onSymbolGroupNotPermitted),e.dataEvents().symbolNotPermitted().subscribe(this,this.show)}_onSymbolResolved(){this._lastResolvedSymbol=this._getSymbol()}_onSymbolGroupNotPermitted(){this.show()}}{show(){(0, Vi.createNoticeDialog)({content:this._getPopupContent()}).then((e=>{e.on("destroy",this._onPopupClosed.bind(this)),e.open()}))}}var cs=i(538660),hs=i(42292),ds=i(223699),us=i(395098),_s=i(547944);var ps=i(370552),ms=(i(237218),i(534741),i(12481)),gs=i(833713),Ss=i(895370),vs=i(198303),fs=i(113610);const bs=(0,m.getLogger)("Chart.LinkKeyResolver");class ys{constructor(e,t,i){this._pendingRequests=new Map,this._startRequestingDebounced=(0,ms.default)((()=>this._startNextRequest()),500),this._layoutId=e,this._chartId=t,this._ownerSourceId=i}resolveLinkKey(e,t,i){var s;const o=function(e,t){return JSON.stringify([e,t])}(e,i),r=null!==(s=this._pendingRequests.get(o))&&void 0!==s?s:new Map;if(r.has(t))return r.get(t).promise;const n=(0,v.createDeferredPromise)();return r.set(t,n),this._pendingRequests.set(o,r),this._startRequestingDebounced(),n.promise}async _startNextRequest(){if(0===this._pendingRequests.size)return;const e=await(0,fs.getChartStorage)(),t=this._pendingRequests.entries().next().value,{symbol:i,brokerName:s}=function(e){const t=JSON.parse(e);return{symbol:t[0],brokerName:t[1]}}(t[0]),o=t[1],r={requestType:"mainSeriesLineTools",seriesSourceId:this._ownerSourceId,symbol:i,brokerName:s,sharingMode:0};try{const t=await e.loadLineToolsAndGroups(this._layoutId,this._chartId,r,i);null!==t&&null!==t.sources&&(t.sources.forEach(((e,t)=>{if(null===e)return;const i=e.state.linkKey;if(!i)return;const s=o.get(i);null==s||s.resolve(e.id),o.delete(i)})),t.serverRequestId&&console.log(`PROCESSED:${t.serverRequestId}`))}catch(e){bs.logError(`Error requesting line tools: ${e}`)}o.forEach((e=>{e.resolve(null)})),this._pendingRequests.delete(t[0]),await this._startNextRequest()}}var Cs=i(558105),ws=i(731327),Ps=i(978137),Ts=i(963568);const Ms=[500,1e4,6e4],xs=new Li.FeatureToggleWatchedValue("disable_retry_load_linetools_from_storage",!1);var Is=i(459711),As=i(266325);const Ls=(0,m.getLogger)("LineToolsSynchronizer");function ks(e,t){return{id:e.id,name:e.name().value(),symbol:e.symbol(),currencyId:e.currencyId(),unitId:e.unitId()}}function Es(e){return void 0===e?0:e}function Ds(e,t,i){const s=new Map,o=new Set(null==i?void 0:i.keys());return e.forEach(((e,r)=>{const n=!i||i.has(r);(e.timestamp>t||!n)&&(s.set(r,e),o.delete(r))})),{stillInvalidated:s,validated:Array.from(o)}}function Ns(e){return(0,te.isLineTool)(e)||(0,Is.isStudyLineToolStub)(e)}const Bs=/(\w+)\/(\w+)\/(\w+)/;class Rs{constructor(e,t,i,s,o){this._invalidatedLineToolsAndStudyStubs=new Map,this._allLineToolsAndStudyStubs=new Map,this._originalLineToolSharingMode=new Map,this._invalidatedLineToolGroups=new Map,this._originalLineToolGroupsSharingMode=new Map,this._ignoreInvalidatingEventsDepth=0,this._saveChartService=null,this._debouncedSave=(0,ms.default)((()=>this._saveInvalidatedIfRequired(!1)),500),this._currentlyLoadedSymbol=new Map,this._linkKeyResolver=null,this._brokerName="",this._hasChanges=new W.WatchedValue(!1),this._lastBanTime=null,this._invalidateViaSync=0,this._savingAbortControllersBySharingMode=new Map, this._savingExternalChartsAbortControllers=new Map,this._onChangeAutosave=e=>{e&&this._debouncedSave()},this._origin=e,this._chartModel=t,this._options=i,this._duplicateOperationsForSerializedCharts=s,this._deserializedChartsIds=o,this._assignAllLineTools(this._chartModel.panes()),this._chartModel.panesCollectionChanged().subscribe(this,this._processPanesCollectionChanged.bind(this)),this._chartModel.dataSourceCollectionChanged().subscribe(this,this._processDataSourceCollectionChanged.bind(this)),this._chartModel.lineToolsGroupModel().onChanged().subscribe(this,this._processLineToolsGroupModelChanged.bind(this)),this._chartModel.mainSeries().dataEvents().symbolResolved().subscribe(this,this._onSymbolResolved.bind(this)),this._chartModel.sourcePropertiesChanged().subscribe(this,this._processPropertiesChanged.bind(this)),this._chartModel.sourceZOrderChanged().subscribe(this,this._processPropertiesChanged.bind(this)),this._linkKeyResolver=new ys(e.layoutId,e.chartId,t.mainSeries().id()),this._brokerIdSession=new Li.FeatureToggleWatchedValue("broker_id_session",!1),this._saveSharedLineTools=new Li.FeatureToggleWatchedValue("save_shared_line_tools",false),this._doNotSaveSharedLineToolsToChartsImpl=new Li.FeatureToggleWatchedValue("do_not_save_shared_line_tools_to_charts",false),this._doNotSaveSharedLineToolsToCharts=(0,E.combine)(((e,t)=>e&&t),this._doNotSaveSharedLineToolsToChartsImpl.weakReference(),this._saveSharedLineTools.weakReference()),this._sharingModesToUse().forEach((e=>{0===e&&this._loadAndMergeLineToolsOnStudies(e,!1),this._loadAndMergeLineToolsWithoutSymbol(e,!1)}))}destroy(){this._brokerIdSession.destroy(),this._saveSharedLineTools.destroy(),this._doNotSaveSharedLineToolsToChartsImpl.destroy(),this._doNotSaveSharedLineToolsToCharts.destroy(),this._chartModel.mainSeries().dataEvents().symbolResolved().unsubscribeAll(this),this._chartModel.sourcePropertiesChanged().unsubscribeAll(this),this._chartModel.sourceZOrderChanged().unsubscribeAll(this),this._chartModel.panesCollectionChanged().unsubscribeAll(this),this._chartModel.dataSourceCollectionChanged().unsubscribeAll(this),this._chartModel.lineToolsGroupModel().onChanged().unsubscribeAll(this)}reloadAllLineTools(){this._currentlyLoadedSymbol.clear(),this._sharingModesToUse().forEach((e=>{0===e&&this._loadAndMergeLineToolsOnStudies(e,!0),this._loadAndMergeLineToolsWithoutSymbol(e,!0)}));const e=this._chartModel.mainSeries().symbolInfo();e&&this._onSymbolResolved(e)}hasChanges(){return this._hasChanges}setSaveChartService(e){this._saveChartService&&this._saveChartService.autoSaveEnabled().unsubscribe(this._onChangeAutosave),this._saveChartService=e,this._saveChartService.autoSaveEnabled().subscribe(this._onChangeAutosave)}prepareDTO(e=!1){const t=new Map;return this._sharingModesToUse().forEach((i=>{t.set(i,this._prepareDTOItem(e,i))})),t}getDTO(e=0,t=!1,i=!1){return i&&this.invalidateAll(),this._prepareDTOItem(t,e)}async applyDTO(e,t=0){this.resetInvalidated(Date.now().valueOf(),e,t),await this._applyLineToolsAndGroupsDTO(e,t)}deserializedChartsIdsProvider(){ return this._deserializedChartsIds}markAsValidatedBecauseOfSavingToContent(e){this._invalidatedLineToolsAndStudyStubs.forEach((t=>{t.savedToChartContent=e})),this._invalidatedLineToolGroups.forEach((t=>{t.savedToChartContent=e})),this._recalculateHasChanges()}resetInvalidated(e,t,i){const s=(e,t,s,o)=>{var r,n;if(!s.has(o)||s.get(o)){if(s.has(o)){const s=e.get(o);if(0===i){t(o,{sharingMode:this._doNotSaveSharedLineToolsToCharts.value()?i:null!==(r=null==s?void 0:s.sharingMode)&&void 0!==r?r:i,duplicatedInChart:!this._doNotSaveSharedLineToolsToCharts.value()})}else t(o,{sharingMode:i,duplicatedInChart:null!==(n=null==s?void 0:s.duplicatedInChart)&&void 0!==n&&n})}}else{const s=e.get(o);s&&(s.sharingMode===i?t(o,null):0===i&&t(o,{...s,duplicatedInChart:!1}))}};if(null===t.sources)return;const{groups:o,sources:r,lineToolsToValidate:n,groupsToValidate:a}=t,l=Ds(this._invalidatedLineToolsAndStudyStubs,e,new Set(null!=n?n:r.keys()));this._invalidatedLineToolsAndStudyStubs=l.stillInvalidated,l.validated.forEach(s.bind(this,this._originalLineToolSharingMode,this._setOriginalLineToolSharingMode.bind(this),r));const c=Ds(this._invalidatedLineToolGroups,e,new Set(null!=a?a:o.keys()));l.validated.forEach(s.bind(this,this._originalLineToolGroupsSharingMode,this._setOriginalLineToolGroupsSharingMode.bind(this),o)),this._invalidatedLineToolGroups=c.stillInvalidated,this._recalculateHasChanges()}applyLineToolUpdateNotification(e,t){var i;const s=function(e){const t=Bs.exec(e);return 4===(null==t?void 0:t.length)?{layoutId:t[1],chartId:t[2],clientId:t[3]}:{layoutId:"",chartId:"",clientId:e}}(null!==(i=e.clientId)&&void 0!==i?i:"");s.clientId===this._origin.clientId&&s.chartId===this._origin.chartId||(this._chartModel.dataSources(),void 0!==e.symbol&&null===e.sources?this._withoutInvalidating((()=>{const i=this._chartModel.dataSources().filter(te.isLineTool).filter((i=>i.sharingMode().value()===t&&i.symbol()===e.symbol));i.length>0&&this._chartModel.undoModel().removeSources(i,!0,null)})):this._applyLineToolsAndGroupsDTO(e,t,s))}startApplyingLineToolUpdateNotification(){this._ignoreInvalidatingEventsDepth++}endApplyingLineToolUpdateNotification(){this._ignoreInvalidatingEventsDepth--,this._ignoreInvalidatingEventsDepth<0&&(Ls.logError("Logic error, startApplyingLineToolUpdateNotification/endApplyingLineToolUpdateNotification mismatch, autofixing"),this._ignoreInvalidatingEventsDepth=0)}applyAlertIdByExternalSource(e,t){this._withoutInvalidating((()=>{const i=this._chartModel.dataSourceForId(e);i&&(0,te.isLineTool)(i)&&i.setAlert(t)}))}deleteAlertByExternalSource(e){this._withoutInvalidating((()=>{const t=this._chartModel.dataSourceForId(e);t&&(0,te.isLineTool)(t)&&t.removeAlert()}))}async markSyncedLineToolAsDeleted(e,t){if(this._linkKeyResolver){const i=await this._linkKeyResolver.resolveLinkKey(t,e,this._brokerName);if(null!==i){const t=(0,te.lineToolByLinkKey)(this._chartModel,e);null===t?this._invalidateLineToolOrStudyStub(i,performance.now()):this._withoutInvalidating((()=>{const e=(0, r.ensureNotNull)(this._chartModel.paneForSource(t)),i=this._allLineToolsAndStudyStubs.get(e.id())||new Map;t.detachAlert(),this._chartModel.removeSource(t),i.delete(t.id())})),this._debouncedSave()}return i}return null}invalidateAll(){const e=performance.now();this._allLineToolsAndStudyStubs.forEach((t=>{t.forEach(((t,i)=>{this._invalidateLineToolOrStudyStub(i,e)}))})),this._chartModel.lineToolsGroupModel().groupsForAllSymbols().forEach((t=>{this._invalidateLineToolGroup(t.id,e)})),this.markAsValidatedBecauseOfSavingToContent(!0)}executeSyncedAction(e){this._invalidateViaSync+=1;try{e()}finally{this._invalidateViaSync-=1}}invalidateViaSync(){return this._invalidateViaSync>0}flushPendingSavings(){return this._invalidatedLineToolGroups.size||this._invalidatedLineToolsAndStudyStubs.size?this._saveInvalidatedIfRequired(!1,!0):null}_assignAllLineTools(e){e.forEach((e=>{const t=e.dataSources().filter(Ns).map((e=>[e.id(),e.linkKey().value()])),i=new Map(t);this._allLineToolsAndStudyStubs.set(e.id(),i)}))}_processPropertiesChanged(e,t){Ns(t)&&this._invalidateLineToolOrStudyStub(t.id(),performance.now())}_processLineToolsGroupModelChanged(e,t){const i=performance.now();this._invalidateLineToolGroup(e,i),t&&(t.affectedLineTools||[]).forEach((e=>this._invalidateLineToolOrStudyStub(e,i)))}_processPanesCollectionChanged(e){const t=e.map((e=>e.id())),i=new Set(t),s=performance.now();Array.from(this._allLineToolsAndStudyStubs.keys()).filter((e=>!i.has(e))).forEach((e=>{Array.from((0,r.ensureDefined)(this._allLineToolsAndStudyStubs.get(e)).keys()).forEach((e=>{this._invalidateLineToolOrStudyStub(e,s)}))})),e.filter((e=>!this._allLineToolsAndStudyStubs.has(e.id()))).forEach((e=>{e.dataSources().filter(Ns).forEach((e=>this._invalidateLineToolOrStudyStub(e.id(),s)))})),this._assignAllLineTools(e)}_processDataSourceCollectionChanged(e){const t=e.dataSources().filter(Ns),i=t.map((e=>[e.id(),e.linkKey().value()])),s=new Map(i);let o;const n=performance.now();if(this._allLineToolsAndStudyStubs.has(e.id())){const i=(0,r.ensureDefined)(this._allLineToolsAndStudyStubs.get(e.id()));o=t.filter((e=>!i.has(e.id()))),o.forEach((e=>this._invalidateLineToolOrStudyStub(e.id(),n))),Array.from(i.entries()).filter((e=>!s.has(e[0]))).forEach((e=>{null!==e[1]&&this._debouncedSave(),this._invalidateLineToolOrStudyStub(e[0],n)}))}else o=t,t.forEach((e=>this._invalidateLineToolOrStudyStub(e.id(),n)));o.forEach((e=>{if((0,te.isLineTool)(e)){this._setOriginalLineToolSharingMode(e.id(),{sharingMode:e.sharingMode().value(),duplicatedInChart:!1});const t=this._chartModel.lineToolsGroupModel().groupForLineTool(e);t&&this._setOriginalLineToolGroupsSharingMode(t.id,{sharingMode:e.sharingMode().value(),duplicatedInChart:!1})}})),this._allLineToolsAndStudyStubs.set(e.id(),s)}_unloadLineTools(e,t,i){const s=e.filter((e=>!this._invalidatedLineToolsAndStudyStubs.has(e))).map((e=>this._chartModel.dataSourceForId(e))).filter(te.isLineTool).filter(T.notNull).filter((e=>e.sharingMode().value()===i)).filter(t).filter((e=>{ const t=this._chartModel.lineToolsGroupModel().groupForLineTool(e);return null===t||!this._invalidatedLineToolGroups.has(t.id)}));this._withoutInvalidating((()=>{s.forEach((e=>{var t;e.hasAlert().value()&&e.detachAlert();const i=(0,r.ensureNotNull)(this._chartModel.paneForSource(e));this._chartModel.removeSource(e);(null!==(t=this._allLineToolsAndStudyStubs.get(i.id()))&&void 0!==t?t:new Map).delete(e.id())})),this._chartModel.lineToolsGroupModel().removeLineTools(s)}))}_unloadLinesOnSeries(e,t,i){const s=this._chartModel.mainSeries();if(!(null==i?void 0:i.size))return;const o=Array.from(i.keys()).filter((t=>!e(t)));this._unloadLineTools(o,(e=>e.boundToSymbol()&&e.ownerSource()===s),t)}_isAutosaveEnabled(){return Boolean(this._saveChartService&&this._saveChartService.autoSaveEnabled().value())}async _saveInvalidatedIfRequired(e,t){if(null!==this._lastBanTime){if(!(performance.now()-this._lastBanTime>=3e5))return Promise.resolve();this._lastBanTime=null}if(!this._isAutosaveEnabled()&&!t||this._options.readOnlyMode||!window.is_authenticated||""===this._origin.layoutId)return;const i=this.prepareDTO(e),s=this._sharingModesToUse().map((e=>{var t,s;const o=i.get(e);if(!o||null===o.sources)return null;const n=null!==(t=o.lineToolsToValidate)&&void 0!==t?t:Array.from(o.sources.keys()),a=null!==(s=o.groupsToValidate)&&void 0!==s?s:Array.from(o.groups.keys());if(0===n.length&&0===a.length)return null;const l=performance.now();if(o.sources.size||o.groups.size){this._applyToolsAndGroupsDTOToNonDeserializedCharts(o,e);const t=this._savingAbortControllersBySharingMode.get(e);t&&t.abort();const i=new AbortController;return this._savingAbortControllersBySharingMode.set(e,i),o.sources.forEach(((t,i)=>{t&&this._setOriginalLineToolSharingMode(i,{sharingMode:e,duplicatedInChart:!1})})),(0,r.ensureNotNull)(this._saveChartService).saveChartLineTools(this._origin.chartId,o,e,i.signal).then((()=>{this.resetInvalidated(l,o,e)})).catch((async t=>{if(t instanceof vs.SavingLineToolsError&&t.shouldBeCooled&&(this._lastBanTime=performance.now()),!(0,As.isAbortError)(t))throw t;Ls.logDebug(`Save request has been aborted. ChartId: ${this._origin.chartId} sharingMode: ${e}`)}))}return this.resetInvalidated(l,o,e),null})).filter(T.notNull);return s.length?Promise.all(s).then((()=>{})):void 0}async _savePromise(e,t){var i,s;return this._isAutosaveEnabled()?null!==(s=null===(i=this._debouncedSave)||void 0===i?void 0:i.flush())&&void 0!==s?s:Promise.resolve():this._saveInvalidatedIfRequired(e,t)}_seriesLineToolsUnloader(e,t,i){const s=this._chartModel.mainSeries();"mainSeriesLineTools"===e.requestType&&s.symbolSameAsCurrent(e.symbol)&&(this._unloadLinesOnSeries(i,e.sharingMode,t),this._currentlyLoadedSymbol.set(e.sharingMode,e.symbol))}_mainPaneLineToolsAndStubs(){const e=this._chartModel.mainSeries(),t=(0,r.ensureNotNull)(this._chartModel.paneForSource(e));return new Map(this._allLineToolsAndStudyStubs.get(t.id()))}_onSymbolResolved(e){const t=this._sharingModesToUse().map((t=>{const i={requestType:"mainSeriesLineTools", seriesSourceId:this._chartModel.mainSeries().id(),symbol:e.pro_name,brokerName:"",sharingMode:t},s=this._seriesLineToolsUnloader.bind(this,i,this._mainPaneLineToolsAndStubs());return this._makeLoadRequestAndMerge(i,s,e.pro_name||e.ticker||e.full_name)}));this._saveSharedLineTools.value()&&Promise.all(t).then((()=>{this._withoutInvalidating((()=>{this._chartModel.dataSources().filter(te.isLineTool).filter((e=>0===e.sharingMode().value()&&e.linkKey().value())).forEach((e=>{if(e.share(1),this._options.migrateSyncedLineTools){this._invalidateLineToolOrStudyStub(e.id(),performance.now(),!0);const t=this._chartModel.lineToolsGroupModel().groupForLineTool(e);t&&this._invalidateLineToolGroup(t.id,performance.now(),!0)}}))}))}))}async _makeLoadRequestAndMerge(e,t,i){var s;const o=this._chartModel.mainSeries(),r=null!==(s=this._currentlyLoadedSymbol.get(e.sharingMode))&&void 0!==s?s:"";if(!!o.symbolSameAsCurrent(r))return;this._currentlyLoadedSymbol.delete(e.sharingMode);const n=await(0,fs.getChartStorage)();return this._savePromise("mainSeriesLineTools"===e.requestType).catch((()=>{})).then((()=>async function(e,t,i,s,o){const r=async()=>e.loadLineToolsAndGroups(t,i,s,o);return r().catch((()=>xs.value()?null:(0,Ts.retriesWithDelays)((async()=>(await(0,Ps.waitForOnline)(),r())),Ms)))}(n,this._origin.layoutId,this._origin.chartId,e,i))).then((async i=>{if(null!==i&&null!==i.sources){const s=i.sources;t((e=>s.has(e))),await this._applyLineToolsAndGroupsDTO(i,e.sharingMode),i.serverRequestId&&console.log(`PROCESSED:${i.serverRequestId}`)}}))}_restoreGroups(e,t,i,s){const o=new Map;return(t.groups||new Map).forEach(((t,n)=>{const a=this._chartModel.lineToolsGroupModel().groupForId(n);if(null===t){if(a){const e=s&&s.layoutId===this._origin.layoutId&&s.chartId===this._origin.chartId;(a.lineTools()[0].sharingMode().value()===i||0===i&&!this._doNotSaveSharedLineToolsToCharts.value())&&(e&&0!==i||(new ws.ExcludeLineToolsFromGroupUndoCommand(this._chartModel,a,a.lineTools()).redo(),this._setOriginalLineToolGroupsSharingMode(n,null)))}}else{if(a&&t.serverUpdateTime){const i=(0,r.ensureDefined)(t.serverUpdateTime);if(null!==e&&e>=i)return;a.setName(t.name)}else o.set(n,t);const s=this._originalLineToolGroupsSharingMode.get(n),l=!(!s||s.sharingMode===i&&!s.duplicatedInChart);this._setOriginalLineToolGroupsSharingMode(n,{sharingMode:i,duplicatedInChart:l})}})),o}_createNewLineTool(e){const t=this._chartModel.dataSourceForId(e.ownerSource);if(null===t)return null;const i=(0,r.ensureNotNull)(this._chartModel.paneForSource(t)),s=this._chartModel.panes().indexOf(i),o=this._chartModel.restoreSource(!1,s,null,e.state,null);if(null!==o){const e=this._allLineToolsAndStudyStubs.get(i.id())||new Map;e.set(o.id(),o.linkKey().value()),this._allLineToolsAndStudyStubs.set(i.id(),e)}return o}_migrateStateFromMetainfo(e){const t=void 0!==e.symbol&&e.symbol!==e.state.state.symbol;t&&(e.state.state.symbol=e.symbol);const i=void 0!==e.currencyId&&e.currencyId!==e.state.state.currencyId;i&&(e.state.state.currencyId=e.currencyId) ;const s=void 0!==e.unitId&&e.unitId!==e.state.state.unitId;return s&&(e.state.state.unitId=e.unitId),t||i||s}_restoreLineTool(e,t,i,s){var o;if((null!==(o=t.state.points)&&void 0!==o?o:[]).some((e=>!(0,T.isNumber)(e.time_t))))return null;let r=this._chartModel.dataSourceForId(t.id);if(null===r&&t.state.linkKey&&(r=(0,te.lineToolByLinkKey)(this._chartModel,t.state.linkKey)),null!==r&&!(0,te.isLineTool)(r))return null;if(this._origin.clientId===(null==s?void 0:s.clientId)&&!r)return null;if(r&&t.serverUpdateTime){const o=t.serverUpdateTime,n=r.serverUpdateTime();if(null!==e&&e>=o||null!==n&&n>=o){if(this._saveSharedLineTools.value()&&0!==i){r.share(i);const e=this._originalLineToolSharingMode.get(r.id()),t=!(!e||e.sharingMode===i&&!e.duplicatedInChart);this._setOriginalLineToolSharingMode(r.id(),{sharingMode:i,duplicatedInChart:t})}return null}this._origin.clientId!==(null==s?void 0:s.clientId)&&(this._chartModel.restoreLineToolState(r,t.state,!1),r.calcIsActualSymbol())}0!==i&&(t.ownerSource=this._chartModel.mainSeries().id(),t.state.ownerSource=this._chartModel.mainSeries().id());const n=this._migrateStateFromMetainfo(t);let a=r||this._createNewLineTool(t);if(a&&(n&&this._invalidateLineToolOrStudyStub(t.id,performance.now(),!0),t.serverUpdateTime&&a.setServerUpdateTime(t.serverUpdateTime),t.state.alertId?a.setAlert(+t.state.alertId,{syncFocusFromAlert:!0}):a.detachAlert(),(0!==i||this._doNotSaveSharedLineToolsToCharts.value())&&a.share(i),void 0===s&&(0,te.isEditableTextLineTool)(a))){this._removeTextLineToolIfEmpty(a)&&(a=null)}return a}_removeLineTool(e){const t=this._chartModel.dataSourceForId(e);null!==t&&new Cs.RemoveSourcesUndoCommand(this._chartModel,[t],null).redo()}_removeTextLineToolIfEmpty(e){return 0===e.properties().childs().text.value().trim().length&&(this._chartModel.removeSource(e),this._invalidateLineToolOrStudyStub(e.id(),performance.now(),!0),!0)}_restoreLineDTO(e,t,i,s,o,n){if(!this._invalidatedLineToolsAndStudyStubs.get(t))if(null===e){const e=this._chartModel.dataSourceForId(t);if(!e)return;if(!(0,te.isLineTool)(e))return;const i=n&&n.layoutId===this._origin.layoutId&&n.chartId===this._origin.chartId;(e.sharingMode().value()===o||0===o&&!this._doNotSaveSharedLineToolsToCharts.value())&&(0===o||this._doNotSaveSharedLineToolsToCharts.value()||(e.share(0),i||this._invalidateLineToolOrStudyStub(t,performance.now(),!0)),this._origin.clientId!==(null==n?void 0:n.clientId)&&(i&&0!==o&&!this._doNotSaveSharedLineToolsToCharts.value()||(this._removeLineTool(t),this._setOriginalLineToolSharingMode(t,null))))}else{const a=this._restoreLineTool(s,e,o,n);if(a){if(e.groupId){const t=this._chartModel.lineToolsGroupModel().groupForLineTool(a),s=this._chartModel.lineToolsGroupModel().groupForId(e.groupId);if(null!==t&&s===t)return;if(null!==t&&(t.excludeLineTool(a),0===t.lineTools().length&&this._chartModel.lineToolsGroupModel().removeGroup(t)),s&&!s.containsLineTool(a))s.addLineTools([a]);else if(!s&&i.has(e.groupId)){const t=(0,r.ensureDefined)(i.get(e.groupId)) ;this._chartModel.lineToolsGroupModel().createGroup([a],t.name,t.id)}}else{this._chartModel.lineToolsGroupModel().removeLineTools([a]).forEach((e=>{this._invalidateLineToolGroup(e,performance.now(),!0)}))}const s=this._originalLineToolSharingMode.get(t);(void 0===s||0!==o&&!this._doNotSaveSharedLineToolsToCharts.value())&&this._setOriginalLineToolSharingMode(t,{sharingMode:o,duplicatedInChart:!1});const n=!(!s||s.sharingMode===o&&!s.duplicatedInChart);(0,r.ensureDefined)(this._originalLineToolSharingMode.get(t)).duplicatedInChart=n}}}async _applyLineToolsAndGroupsDTO(e,t,i){const s=this._chartModel.chartSaveTime(),o=this._withoutInvalidating((()=>this._restoreGroups(s,e,t,i))),r=`ChartStorage.Synchronizer.ApplyingDTO.${`${this._origin.layoutId}.${this._origin.chartId}`}`,n=new Set;(e.sources||new Map).forEach((e=>{e&&n.add(e.state.type)})),await Promise.all(Array.from(n).map((e=>(0,te.initLineTool)(e)))),(0,Ss.perfMeasureOperation)(r,(()=>this._withoutInvalidating((()=>{(e.sources||new Map).forEach(((e,r)=>{try{this._restoreLineDTO(e,r,o,s,t,i)}catch(e){Ls.logError(`Error restoring line tool ${r}: ${e}`)}})),(e.groups||new Map).forEach(((e,t)=>{this._invalidatedLineToolGroups.delete(t)})),this._recalculateHasChanges()}))))}_withoutInvalidating(e){try{return this._ignoreInvalidatingEventsDepth++,e()}finally{this._ignoreInvalidatingEventsDepth--}}_invalidateLineToolOrStudyStub(e,t,i){var s;if(this._ignoreInvalidatingEventsDepth>0&&!i)return;const o=null===(s=this._invalidatedLineToolsAndStudyStubs.get(e))||void 0===s?void 0:s.invalidatedViaSyncOnly,r=(void 0===o||o)&&this.invalidateViaSync();this._invalidatedLineToolsAndStudyStubs.set(e,{timestamp:t,invalidatedViaSyncOnly:r}),this._hasChanges.setValue(!0),this._debouncedSave()}_invalidateLineToolGroup(e,t,i){this._ignoreInvalidatingEventsDepth>0&&!i||(this._invalidatedLineToolGroups.set(e,{timestamp:t,invalidatedViaSyncOnly:this.invalidateViaSync()}),this._hasChanges.setValue(!0),this._debouncedSave())}_prepareDTOItem(e,t){const i=new Map,s=new Map,o=[],n=[];return this._invalidatedLineToolsAndStudyStubs.forEach(((n,a)=>{var l,c;if(0!==t&&n.invalidatedViaSyncOnly)return void o.push(a);const h=this._chartModel.dataSourceForId(a);if((0,Is.isStudyLineToolStub)(h))return;const d=()=>{var e;this._doNotSaveSharedLineToolsToCharts.value()&&0===t&&(null===(e=this._originalLineToolSharingMode.get(a))||void 0===e?void 0:e.duplicatedInChart)&&i.set(a,null)};if(null===h){((null===(l=this._originalLineToolSharingMode.get(a))||void 0===l?void 0:l.sharingMode)===t||0===t&&!this._doNotSaveSharedLineToolsToCharts.value())&&i.set(a,null),d()}else{if(h===this._chartModel.lineBeingCreated()||h===this._chartModel.lineBeingEdited()||!h.isSavedInChart())return;const o=h.ownerSource()===this._chartModel.mainSeries(),n=!e||o,l=h.sharingMode().value()===t||0===t&&!this._doNotSaveSharedLineToolsToCharts.value();if(n){const e=this._chartModel.lineToolsGroupModel().groupForLineTool(h);if(l)i.set(a,function(e,t){const i=t.lineToolsGroupModel().groupForLineTool(e),s={id:e.id(),ownerSource:(0, r.ensureNotNull)(e.ownerSource()).id(),state:e.state(!1)};return e.boundToSymbol()&&(s.symbol=e.symbol()),s.currencyId=e.properties().childs().currencyId.value(),s.unitId=e.properties().childs().unitId.value(),null!==i&&(s.groupId=i.id),s}(h,this._chartModel)),null!==e&&s.set(e.id,ks(e,this._chartModel));else{const o=null===(c=this._originalLineToolSharingMode.get(a))||void 0===c?void 0:c.sharingMode;o===t&&i.set(a,null),null!==e&&o===t&&s.set(e.id,null)}}0!==h.sharingMode().value()&&d()}})),this._invalidatedLineToolGroups.forEach(((e,i)=>{if(0!==t&&e.invalidatedViaSyncOnly)n.push(i);else if(!s.has(i)){const e=this._chartModel.lineToolsGroupModel().groupForId(i);if(null===e)s.set(i,null);else{(e.sharingMode().value()===t||0===t&&!this._doNotSaveSharedLineToolsToCharts.value())&&s.set(i,ks(e,this._chartModel))}}})),{sources:i,groups:s,clientId:this._generateOrigin(),lineToolsToValidate:Array.from(i.keys()).concat(o),groupsToValidate:Array.from(s.keys()).concat(n)}}_setOriginalLineToolSharingMode(e,t){t?this._originalLineToolSharingMode.set(e,t):this._originalLineToolSharingMode.delete(e)}_setOriginalLineToolGroupsSharingMode(e,t){t?this._originalLineToolGroupsSharingMode.set(e,t):this._originalLineToolGroupsSharingMode.delete(e)}_sharingModesToUse(){return this._saveSharedLineTools.value()?[0,1,2]:[0]}_loadAndMergeLineToolsOnStudies(e,t){const i={requestType:"studiesLineTools",seriesSourceId:this._chartModel.mainSeries().id(),sharingMode:e},s=this._chartModel.mainSeries();this._makeLoadRequestAndMerge(i,(i=>{const o=t?(0,gs.default)(Array.from(this._allLineToolsAndStudyStubs.values()).map((e=>Array.from(e.keys())))).filter((e=>!i(e))):[];this._unloadLineTools(o,(e=>e.ownerSource()!==s),e)}),void 0)}_loadAndMergeLineToolsWithoutSymbol(e,t){const i={requestType:"lineToolsWithoutSymbol",seriesSourceId:this._chartModel.mainSeries().id(),sharingMode:e},s=this._chartModel.mainSeries(),o=(0,r.ensureNotNull)(this._chartModel.paneForSource(s)),n=this._allLineToolsAndStudyStubs.get(o.id());this._makeLoadRequestAndMerge(i,(i=>{const o=t&&n?Array.from(n.keys()).filter((e=>!i(e))):[];this._unloadLineTools(o,(e=>!e.boundToSymbol()&&e.ownerSource()===s),e)}),void 0)}_recalculateHasChanges(){const e=Array.from(this._invalidatedLineToolsAndStudyStubs.values()).some((e=>!e.savedToChartContent)),t=Array.from(this._invalidatedLineToolGroups.values()).some((e=>!e.savedToChartContent));this._hasChanges.setValue(e||t)}_applyToolsAndGroupsDTOToNonDeserializedCharts(e,t){var i,s;if(null!==e.sources&&0===t&&this._duplicateOperationsForSerializedCharts()&&this._deserializedChartsIds().length>0){const t=new Map;for(const[o,r]of e.sources)null!==r&&"_seriesId"===r.ownerSource&&0!==Es(null===(i=this._originalLineToolSharingMode.get(o))||void 0===i?void 0:i.sharingMode)&&0===Es(r.state.sharingMode)?t.set(o,null):(null===r&&0!==Es(null===(s=this._originalLineToolSharingMode.get(o))||void 0===s?void 0:s.sharingMode)||null!==r&&"_seriesId"===r.ownerSource&&0!==Es(r.state.sharingMode))&&t.set(o,r);if(t.size>0){const i={groups:new Map,sources:t, clientId:e.clientId};for(const e of this._deserializedChartsIds()){const t=this._savingExternalChartsAbortControllers.get(e);t&&t.abort();const s=new AbortController;this._savingExternalChartsAbortControllers.set(e,s),(0,r.ensureNotNull)(this._saveChartService).saveChartLineTools(e,i,0,s.signal).catch((e=>{}))}}}}_generateOrigin(){return`${this._origin.layoutId}/${this._origin.chartId}/${this._origin.clientId}`}}const Os=(0,m.getLogger)("ChartWidget",{color:"#606"}),Vs=B.enabled("chart_content_overrides_by_defaults"),Ws=new V.TranslatedString("hide {title}",a.t(null,void 0,i(470301))),Fs=(0,Zi.isFeatureEnabled)("do_not_wait_meta_info");let Hs=null;if(location.search.toLowerCase().includes("logcanvassaverestoreleaks")){if(!h.isChrome)throw new Error("CanvasRenderingContext2D save/restore leak detection is available for now in Chrome only");i.e(15803).then(i.bind(i,128151)).then((e=>{e.enableCanvasRenderingContext2DSaveRestoreLeaksDetection(),Hs=e.reportCanvasRenderingContext2DSaveRestoreLeaks}))}const zs={addToWatchlistEnabled:!0,showFinancialsEnabled:!1,sourceSelectionEnabled:!0,propertyPagesEnabled:!0,paneContextMenuEnabled:!0,priceScaleContextMenuEnabled:!0,currencyConversionEnabled:!1,unitConversionEnabled:!1,goToDateEnabled:!1,marketStatusWidgetEnabled:!0,chartWarningWidgetEnabled:!0,dataProblemWidgetEnabled:!0,paneControlsEnabled:!0,isSymbolAvailable:e=>Promise.resolve(!0),legendWidgetEnabled:!0,chartEventsEnabled:!0,newsNotificationsEnabled:!0,esdEnabled:!1,latestUpdatesEnabled:{news:!1,minds:!1},continuousContractSwitchesEnabled:!1,futuresContractExpirationEnabled:!1,croppedTickMarks:!0,countdownEnabled:!0,lastPriceAnimationEnabled:!0,useKineticScroll:h.CheckMobile.any(),indicatorsDialogShortcutEnabled:!0,handleScale:{mouseWheel:!0,pinch:!0,axisPressedMouseMove:{time:!0,price:!0}},handleScroll:{mouseWheel:!0,pressedMouseMove:!0,horzTouchDrag:!0,vertTouchDrag:!0}},Us={requestingIntradayWhenNotSupported:!1,requestingResolutionLessThanFrequency:!1};function Gs(e,t,i,s=0){const o=t.mainSeries().syncModel(),r=e.mainSeries().syncModel();let n=i;if(null!==o&&null!==r){const t=e.createSyncPoint(o.syncSourceTarget(),r.syncSourceTarget());0!==s&&(i=o.projectTime(i,s)),n=t.sourceTimeToTargetTime(i)}return e.timeScale().points().roughIndex(n,r&&r.distance.bind(r))}const qs=["Overlay@tv-basicstudies","CorrelationCoefficient@tv-basicstudies","Correlation Coeff@tv-basicstudies","Spread@tv-basicstudies","Ratio@tv-basicstudies"];const js=new Set(["Volume@tv-basicstudies","Compare@tv-basicstudies","Overlay@tv-basicstudies","Dividends@tv-basicstudies","Earnings@tv-basicstudies","Splits@tv-basicstudies","BarSetContinuousRollDates@tv-corestudies","Sessions@tv-basicstudies","VbPSessionsRough@tv-volumebyprice","AnchoredVWAP@tv-basicstudies","RegressionTrend@tv-basicstudies","VbPAnchored@tv-basicstudies","VbPFixed@tv-basicstudies","VbPFixed@tv-volumebyprice"]),Ys=(0,o.default)((()=>{window.ChartApiInstance.setIsNonCountedStudyFn((e=>js.has(e)||e.endsWith("@mtp-mtpredictor")))}));class Ks{constructor(e,t,s){this.activePaneWidget=null, this._model=null,this._paneWidgets=[],this._maximizedPaneWidget=null,this._timeAxisWidget=null,this._paneSeparators=[],this._controlBarNavigation=null,this._lineToolsSynchronizer=null,this._modelCreated=new N.Delegate,this._isDestroyed=!1,this._customLegendWidgetsFactoryMap=new Map,this._backgroundTopTheme=new W.WatchedValue("light"),this._backgroundBasedTheme=new W.WatchedValue("light"),this._backgroundBottomTheme=new W.WatchedValue("light"),this._lhsAxesWidth=0,this._rhsAxesWidth=0,this._lhsPriceAxisWidthChanged=new N.Delegate,this._rhsPriceAxisWidthChanged=new N.Delegate,this._mainDiv=null,this._parent=null,this._elTooltipDiv=null,this._hotkeysListener=null,this._mouseWheelHelper=null,this._onWheelBound=null,this._justActivated=!1,this._inited=!1,this._containsData=!1,this._initialLoading=!1,this._defTimeframe=void 0,this._removeMaximizeHotkey=null,this._invalidationMask=null,this._drawPlanned=!1,this._drawRafId=0,this._inLoadingState=!1,this._timingsMeter=null,this._tagsChanged=new N.Delegate,this._redraw=new N.Delegate,this._isVisible=new W.WatchedValue(!0),this._collapsed=new W.WatchedValue(!1),this._dataWindowWidget=null,this._resizeHandler=null,this._spinner=null,this._properties=null,this._symbolWV=new W.WatchedValue,this._resolutionWV=new W.WatchedValue,this._updateThemedColorBound=this._updateThemedColor.bind(this),this._disconnected=new N.Delegate,this._reconnectBailout=new N.Delegate,this._connected=new N.Delegate,this._chartWidgetInitialized=new N.Delegate,this._saveChartService=null,this._objectTreeDialogController=null,this._chartPaintedPromise=null,this._noExchangeSubscrptionWarning=null,this._paneWidgetsSharedState=new vi,this._onZoom=new N.Delegate,this._onScroll=new N.Delegate,this._availableScreen=null,this._hoveredPriceAxes=new Set,this._anyAxisHovered=new W.WatchedValue(!1),this._linkingGroupIndex=new W.WatchedValue(null),this._showDataWindowAction=null,this._isHovered=new W.WatchedValue(!1),this._activeHint=null,this._eventHintDeferredPromise=null,this._warningHintDeferredPromise=null,this._setSymbolIntervalContentOverrides={},this._ariaPriceDescription=null,this._invalidationHandler=e=>{if(!(e instanceof me.InvalidationMask))throw new Error("Invalid mask");null!==this._invalidationMask?this._invalidationMask.merge(e):this._invalidationMask=e,this._drawPlanned||(this._drawPlanned=!0,this._options.visible.when((()=>{const e=!document.hidden,t=this.screen&&this.screen.isShown();null!==this._timingsMeter&&e&&!t&&this._timingsMeter.startWaitingDraw();const i=(0,r.ensureNotNull)((0,r.ensureNotNull)(this._parent).ownerDocument.defaultView);this._drawRafId=i.requestAnimationFrame(this._invalidationRAFCallback.bind(this))})))},this._onChartSessionIsConnectedChanged=e=>{e?this._onConnection():this._onDisconnect()},this._subscribeToBanInfo=e=>{var t,i;e?null===(t=this._spinner)||void 0===t||t.stop():null===(i=this._spinner)||void 0===i||i.spin()},this._id=t,this._layoutId=s,this._options=(0,T.merge)((0,T.clone)(zs),e),this._chartWidgetCollection=this._options.chartWidgetCollection, this._isActive=new W.WatchedValue(!!this._options.isActive),this._options.customLegendWidgetFactories&&(this._customLegendWidgetsFactoryMap=this._options.customLegendWidgetFactories),this._subscribeToDrawingState(),this.withModel(this,(()=>{const e=this.model().model();e.backgroundTopColor().subscribe(this._updateThemedColorBound),e.backgroundColor().subscribe(this._updateThemedColorBound)})),this._errorRenderer=new _e(this),this._scrollHelper=new Y(this),this._objectTreeDialogController=P.getInstance(),this._properties=new Mi.DefaultProperty("chartproperties",void 0,void 0,this._options.useUserChartPreferences),this._properties.addExclusion("scalesProperties.axisHighlightColor"),this._properties.addExclusion("scalesProperties.axisLineToolLabelBackgroundColorActive"),this._properties.addExclusion("scalesProperties.axisLineToolLabelBackgroundColorCommon"),this._properties.addExclusion("scalesProperties.showPriceScaleCrosshairLabel"),this._properties.addExclusion("scalesProperties.showTimeScaleCrosshairLabel"),this._properties.addExclusion("scalesProperties.crosshairLabelBgColorLight"),this._properties.addExclusion("scalesProperties.crosshairLabelBgColorDark"),this._startSpinner(this._options.container.value()),window.ChartApiInstance.connectionBanInfo().subscribe(this._subscribeToBanInfo,{callWithLast:!0}),this._chartSession=new cs.ChartSession(window.ChartApiInstance),Ys(),this._isMultipleLayout=(0,E.combine)((e=>(0,Se.isMultipleLayout)(e)),this._chartWidgetCollection.layout.weakReference()),(0,h.onWidget)()||(this._persistentLogSwitcher=new Li.FeatureToggleWatchedValue("support_persistent_logs",!1),this._persistentLogSwitcher.subscribe((async e=>{var t;if(e){if((0,Ri.getPersistentLogger)())return;(0,Ri.setPersistentLogger)(new Oi);const{initPersistentLogger:e}=await i.e(94882).then(i.bind(i,327629));(null===(t=this._persistentLogSwitcher)||void 0===t?void 0:t.value())?e():(0,Ri.setPersistentLogger)(null)}else(0,Ri.setPersistentLogger)(null)}),{callWithLast:!0}))}destroy(){var e,t,i;null===(e=this._lineToolsSynchronizer)||void 0===e||e.destroy(),null===(t=this._noExchangeSubscrptionWarning)||void 0===t||t.destroy(),window.loginStateChange.unsubscribe(this,this._handleLoginStateChanged),null!==this._model&&(this._model.model().backgroundTopColor().unsubscribe(this._updateThemedColorBound),this._model.model().backgroundColor().unsubscribe(this._updateThemedColorBound),this._model.model().crossHairSource().moved().unsubscribe(this,this._updateAriaPriceDescription),this._model.destroy()),window.ChartApiInstance.connectionBanInfo().unsubscribe(this._subscribeToBanInfo),this._ariaPriceDescription=null,this._customLegendWidgetsFactoryMap.clear(),this._scrollHelper.destroy(),this._errorRenderer.destroy(),this._chartSession.criticalError().unsubscribe(this,this._onChartSessionCriticalError),this._chartSession.isConnected().unsubscribe(this._onChartSessionIsConnectedChanged),this._chartSession.destroy(),null===(i=this._persistentLogSwitcher)||void 0===i||i.destroy(),this._isDestroyed=!0}emulateCriticalError(){ this._chartSession.removeSeries("-1")}chartSession(){return this._chartSession}onDisconnected(){return this._disconnected}onReconnectBailout(){return this._reconnectBailout}onConnected(){return this._connected}chartWidgetInitialized(){return this._chartWidgetInitialized}setVisibleTimeRange(e,t,i,s){throw new Error("Not implemented")}lineToolsSynchronizer(){return this._lineToolsSynchronizer}requestFullscreen(){this.getResizerDetacher().requestFullscreen()}exitFullscreen(){this.getResizerDetacher().exitFullscreen()}inFullscreen(){return this.getResizerDetacher().fullscreen.value()}model(){return(0,r.ensureNotNull)(this._model)}id(){return this._id}layoutId(){return this._chartWidgetCollection.metaInfo.uid.value()}isActive(){return this._isActive.readonly()}isHovered(){return this._isHovered.readonly()}crossHairSyncEnabled(){return this._chartWidgetCollection.lock.crosshair.value()}isVisible(){return this._isVisible.value()}setVisible(e){this._isVisible.setValue(e)}isCollapsed(){return this._collapsed.value()}setCollapsed(e){this._collapsed.setValue(e)}isJustClonedChart(){return!!(this._options||{}).justCloned}removeAllDrawingTools(){this.model().removeAllDrawingTools()}removeAllStudies(){this.model().removeAllStudies()}removeAllStudiesDrawingTools(){this.model().removeAllStudiesAndDrawingTools()}getSymbol(e){var t,i,s,o;let r;return r=this._model?this._model.mainSeries().properties().childs():this.properties().childs().mainSeriesProperties.childs(),r?e&&r.shortName&&r.shortName.value()?null!==(i=null===(t=r.shortName)||void 0===t?void 0:t.value())&&void 0!==i?i:"":null!==(o=null===(s=r.symbol)||void 0===s?void 0:s.value())&&void 0!==o?o:"":""}setSymbol(e){this._model?(this._symbolWV.setValue(e),this._model.setSymbol(this._model.mainSeries(),e)):(this.properties().childs().mainSeriesProperties.merge({symbol:e}),this._symbolWV.setValue(e),this._setSymbolIntervalContentOverrides.symbol=e)}setResolution(e){this._model?(this._resolutionWV.setValue(e),this._model.setResolution(this._model.mainSeries(),e)):(this.properties().childs().mainSeriesProperties.merge({interval:e}),this._resolutionWV.setValue(e),this._setSymbolIntervalContentOverrides.interval=e)}getResolution(){return this._model?this._model.mainSeries().properties().childs().interval.value():this.properties().childs().mainSeriesProperties.childs().interval.value()}symbolWV(){return this._symbolWV.readonly()}resolutionWV(){return this._resolutionWV.readonly()}loadRange(e){if(this._model){this.screen.show();this._model.loadRange(e)||this.screen.hide()}}async showGeneralChartProperties(e,t){if(!B.enabled("show_chart_property_page"))return Promise.resolve(null);const s=await this._showChartProperties(this.model().mainSeries(),e,{doNotCloseOnBgClick:!0,onResetToDefault:async()=>{this.model().restorePreferences();const e=await i.e(83767).then(i.bind(i,429874)),t=e.getCurrentTheme().name;e.loadTheme(this.chartWidgetCollection(),{themeName:t,standardTheme:!0})},shouldReturnFocus:null==t?void 0:t.shouldReturnFocus});if(null===s)return null;const o=()=>{s.hide(), this._chartWidgetCollection.activeChartWidget.unsubscribe(o)};return this._chartWidgetCollection.activeChartWidget.subscribe(o),s}showChartPropertiesForSource(e,t,i,s){return B.enabled("property_pages")&&e.userEditEnabled()?e===this.model().model().mainSeries()?this.showGeneralChartProperties(t):((i=i||{}).onResetToDefault=()=>{((0,te.isLineTool)(e)||(0,$.isStudy)(e))&&this.model().restorePropertiesForSource.bind(this._model,e)},this._showChartProperties(e,t,i,s)):Promise.resolve(null)}async showChartPropertiesForSources(e){if(!B.enabled("property_pages"))return Promise.resolve(null);const{sources:t,title:s,tabName:o,renamable:n}=e,l=(0,r.ensureNotNull)(this._model),c=O(t.map((e=>e.properties().childs()))),h=O(t.map((e=>e.properties().childs().intervalsVisibilities))),[{createPropertyPage:d},{getSelectionStylePropertiesDefinitions:u},{getSelectionIntervalsVisibilitiesPropertiesDefinition:_},{getSelectionCoordinatesPropertyDefinition:p}]=await Promise.all([Promise.all([i.e(96461),i.e(82790),i.e(30154),i.e(82375),i.e(18537)]).then(i.bind(i,402417)),Promise.all([i.e(96461),i.e(82790),i.e(30154),i.e(82375),i.e(18537)]).then(i.bind(i,136172)),Promise.all([i.e(96461),i.e(82790),i.e(30154),i.e(82375),i.e(18537)]).then(i.bind(i,46622)),Promise.all([i.e(96461),i.e(82790),i.e(30154),i.e(82375),i.e(18537)]).then(i.bind(i,678904))]);return async function(e){const{SourcesPropertiesEditorRenderer:t}=await Promise.all([i.e(78596),i.e(11165),i.e(44335),i.e(88601),i.e(52540),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(93502),i.e(66639),i.e(30006),i.e(88194),i.e(38669),i.e(5145),i.e(35649),i.e(72639),i.e(36884),i.e(89842),i.e(25190),i.e(68992),i.e(46036),i.e(10990),i.e(81643),i.e(13152),i.e(26855),i.e(91033),i.e(84281),i.e(58056),i.e(21625),i.e(8740),i.e(61631),i.e(90684),i.e(40866),i.e(99916),i.e(40812),i.e(73954),i.e(36956),i.e(77807),i.e(56388),i.e(9227),i.e(52251),i.e(22486),i.e(89434),i.e(98149),i.e(24215),i.e(58289),i.e(77474),i.e(18511),i.e(26053),i.e(21895),i.e(22333),i.e(54474),i.e(15886),i.e(36740),i.e(75058),i.e(85256),i.e(18182),i.e(27074),i.e(24534),i.e(14127),i.e(42616),i.e(47391),i.e(98904),i.e(50690),i.e(30979),i.e(88087),i.e(29594),i.e(93869),i.e(111),i.e(14473),i.e(80870),i.e(46513),i.e(49829),i.e(32046),i.e(59703),i.e(99144),i.e(12716),i.e(48037),i.e(36403),i.e(51408),i.e(33127),i.e(80068),i.e(46780)]).then(i.bind(i,578569)),s=new t(e);return null!==A&&(A.hide(),A=s),s.show(),s}({sources:t,propertyPages:[d(u(c,l),"style",a.t(null,void 0,i(394969))),d({definitions:[p(t,l)]},"displacement",a.t(null,void 0,i(962764))),d(_(h,l),"visibility",a.t(null,void 0,i(221852)))],undoModel:l,title:s,activeTabId:o,renamable:n})}getPriceAxisWidthChangedByName(e){return"left"===e?this._lhsPriceAxisWidthChanged:this._rhsPriceAxisWidthChanged}getPriceAxisMaxWidthByName(e){return"left"===e?this._lhsAxesWidth:this._rhsAxesWidth}timeAxisHeight(){return null!==this._timeAxisWidget?this._timeAxisWidget.size.height:0}withModel(e,t){ null!==this._model?t.call(e):this.modelCreated().subscribe(e,t,!0)}hasModel(){return null!==this._model}onRedraw(){return this._redraw}copyLineToOtherCharts(){const e=(0,r.ensureNotNull)(this._model),t=e.selection().lineDataSources().filter((e=>e.isSynchronizable()));e.model().copyToOtherCharts(t,!0)}hideDataSources(e){if(e.length){const t=e.map((e=>e.properties().visible)),i=e.map((()=>!1));this.model().setProperties(t,i,Ws.format({title:new V.TranslatedString(e[0].name(),e[0].title(xi.TitleDisplayTarget.StatusLine))}))}}hideSelectedObject(){this.hideDataSources(this.model().selection().dataSources().filter((e=>!(0,Qe.isAlertLabel)(e))))}unlinkSelectedLine(){const e=(0,r.ensureNotNull)(this._model),t=e.selection().lineDataSources();e.unlinkLines(t)}selectPointMode(){return(0,r.ensureNotNull)(this._model).model().selectPointMode()}cancelRequestSelectPoint(){const e=(0,r.ensureNotNull)(this._model);e.model().cancelRequestSelectPoint(),e.model().setReplayStatus(e.model().isInReplay()?Ui.ReplayStatus.Pause:Ui.ReplayStatus.Undefined),this.model().model().clearCurrentPosition()}requestSelectPoint(e,t){const i=(0,r.ensureNotNull)(this._model);return e.selectPointMode===Ve.SelectPointMode.Replay&&i.model().setReplayStatus(Ui.ReplayStatus.PointSelect),new Promise(((s,o)=>{const r=()=>!!this.isVisible()||(o("Chartwidget must be visible"),this.cancelRequestSelectPoint(),!1);if(!r())return;(0,Ve.resetToCursor)(!0),i.lineBeingCreated()&&i.cancelCreatingLine();let n=!1;const a={};i.model().onPointSelected().subscribe(a,((e,t)=>{n=!0,this._isVisible.unsubscribe(r),this._hideHint(),s({point:e,pane:t})}),!0),i.model().requestSelectPoint(e),this.startTrackingMode(),void 0!==t&&this._showEventHint(t),this._isVisible.subscribe(r),this.selectPointMode().subscribe((()=>{setTimeout((()=>{n||(this.selectPointMode().value()===Ve.SelectPointMode.None&&this._hideHint(),i.model().onPointSelected().unsubscribeAll(a),this._isVisible.unsubscribe(r),o("cancelled"))}))}),{once:!0})}))}onScroll(){return this._onScroll}onZoom(){return this._onZoom}images(e){window.TradingView.printing=!0;const t=this.model().selection().allSources();this.model().selectionMacro((e=>e.clearSelection())),this.model().model().recalculateAllPanes((0,Kt.globalChangeEvent)());const i=(t,i)=>{t.paint(i);const s={showCollapsedStudies:Boolean(null==e?void 0:e.showCollapsedStudies),status:null==e?void 0:e.status};return t.getScreenshotData(s)},s=[];if(null!==this._maximizedPaneWidget){const e=this._paneWidgets.indexOf(this._maximizedPaneWidget);s.push(i(this._maximizedPaneWidget,me.InvalidationMask.light().invalidateForPane(e)))}else for(let e=0;e{t.forEach((t=>{e.addSourceToSelection(t)}))})), this.model().model().recalculateAllPanes((0,Kt.globalChangeEvent)()),this.model().model().lightUpdate();const r=this.mainSeriesQuotesAndMetainfo();return{panes:s,timeAxis:o,colors:{text:this.properties().childs().scalesProperties.childs().textColor.value(),bg:this.properties().childs().paneProperties.childs().background.value(),scales:this.properties().childs().scalesProperties.childs().lineColor.value()},meta:r.meta,ohlc:r.ohlc,quotes:r.quotes}}insertStudy(e,t,i,s){if(i){const s=this.model().model().chartApi().canCreateStudy({id:"java"===e.type?e.studyId:"",child:t.length>0,fundamental:i.isFundamental});if(!s.success)return(0,os.showStudiesLimitGoProDialog)(this.model().model(),s),Promise.resolve(null)}return new Promise((o=>{0!==t.length?window.runOrSignIn((()=>{o(this._insertStudy(e,t,i,s))}),{source:"study on study"}):o(this._insertStudy(e,t,i,s))})).catch((()=>null))}addOverlayStudy(e,t,i){const s=this.model();return this._options&&this._options.isSymbolAvailable?this._options.isSymbolAvailable(e).then((o=>{if(!o)return null;const r=s.createStudyInserter({type:"java",studyId:"Overlay@tv-basicstudies"},[]),n={allowExtendTimeScale:i};if(B.enabled("use_overrides_for_overlay")){const e=(0,hs.factoryDefaults)("study_Overlay@tv-basicstudies.style");n.style=e}return r.setPropertiesState(n),r.setForceOverlay(t),r.insert((()=>Promise.resolve({inputs:{symbol:e},parentSources:[]})))})):Promise.resolve(null)}addCompareStudy(e){const t=this.model();return this._options&&this._options.isSymbolAvailable?this._options.isSymbolAvailable(e).then((i=>i?t.createStudyInserter({type:"java",studyId:"Compare@tv-basicstudies"},[]).insert((()=>Promise.resolve({inputs:{symbol:e},parentSources:[]}))):null)):Promise.resolve(null)}showIndicators(e,t){if(window.studyMarket)return window.studyMarket.visible().value()?void window.studyMarket.hide():(window.studyMarket.show(e,t),window.studyMarket)}setSaveChartService(e){this._saveChartService=e,null!==this._lineToolsSynchronizer&&this._lineToolsSynchronizer.setSaveChartService(e)}getSaveChartService(){return this._saveChartService}mainSeriesQuotesAndMetainfo(){let e,t,i;const s=this._model&&this._model.mainSeries();if(s){const o=e=>null==e?"":s.formatter().format(e,void 0,void 0,!0,!1)+"",r=e=>null==e?"":e+"";e={resolution:s.interval(),symbol:s.symbol(),values:s.valuesProvider().getValues(null)};const n=s.symbolInfo();n&&(e.symbol=n.full_name,e.description=n.description,e.exchange=n.exchange);const a=s.bars().last();null!==a&&(t=a.value.slice(1,5).map(o));const l=s.quotes();l&&(i={change:o(l.change),changePercent:r(l.change_percent),last:o(l.last_price)})}return{meta:e,ohlc:t,quotes:i}}isMultipleLayout(){return this._isMultipleLayout}updateCrossHairPositionIfNeeded(){if(this._model){const e=Ve.tool.value();this._model.model().setCurrentTool(e);const t=(0,ge.lastMouseOrTouchEventInfo)();if(t.isTouch){const e=this._maximizedPaneWidget||this._paneWidgets[0];if(e.hasState()&&(!t.stylus&&(this._isLineToolModeExceptBrush()||(0, Ve.toolIsMeasure)(Ve.tool.value()))||this.selectPointMode().value()!==Ve.SelectPointMode.None)){const t=.5*this._model.model().timeScale().width(),i=.5*e.state().defaultPriceScale().height();e.setCursorPosition(t,i)}const i=this._model.model().crossHairSource();i.updateAllViews((0,Kt.sourceChangeEvent)(i.id()))}}}trackingModePaneWidget(){if(!(0,ge.lastMouseOrTouchEventInfo)().isTouch)return null;for(const e of this.paneWidgets())if(e.trackingModeEnabled())return e;return null}startTrackingMode(){if((0,ge.lastMouseOrTouchEventInfo)().isTouch){this.exitTrackingMode(),this.updateCrossHairPositionIfNeeded();const e=this._maximizedPaneWidget||this._paneWidgets[0],t=this.model().model().crossHairSource().currentPoint();e.startTrackingMode(t,t)}}exitTrackingMode(){(0,ge.lastMouseOrTouchEventInfo)().isTouch&&this.paneWidgets().some((e=>e.trackingModeEnabled()))&&(this.paneWidgets().forEach((e=>e.exitTrackingMode())),this.model().model().clearCurrentPosition())}onToolChanged(){this.model().lineBeingCreated()&&this._cancelCreatingLine(),this.selectPointMode().value()!==Ve.SelectPointMode.None&&this.cancelRequestSelectPoint(),this.exitTrackingMode()}setInLoadingState(e){this._inLoadingState=e}paint(e){const t=null!=e?e:me.InvalidationMask.full();t.validationActions().forEach((e=>e())),this._paneWidgets.forEach(((e,i)=>{null!==this._maximizedPaneWidget&&this._maximizedPaneWidget!==e||e.paint(t.invalidateForPane(i))})),this._timeAxisWidget&&this._timeAxisWidget.paint(t.invalidateForTimeScale()),null==Hs||Hs(),this._redraw.fire()}GUIResetScales(){(0,_.trackEvent)("GUI","Reset Scales"),null!==this._model&&this._model.resetScales()}toggleMaximizePane(e){var t;if(!(this._paneWidgets.length<2)){this._maximizedPaneWidget?(this._maximizedPaneWidget.state().maximized().setValue(!1),this._maximizedPaneWidget=null,this._paneSeparators.forEach((e=>e.show()))):(this._maximizedPaneWidget=e,this._maximizedPaneWidget.state().maximized().setValue(!0),this._paneSeparators.forEach((e=>e.hide())));for(let e=this._paneWidgets.length;e--;)this._paneWidgets[e].updateControls(),this._paneWidgets[e].updatePriceAxisWidgetsStates();this._errorRenderer.updatePaneWidgets(),null===(t=this._timeAxisWidget)||void 0===t||t.updatePriceAxisStubs(),this._adjustSize(),this.updateCrossHairPositionIfNeeded()}}maximizedPaneWidget(){return this._maximizedPaneWidget}isMaximizedPane(){return null!==this._maximizedPaneWidget}setActive(e){(0,ge.lastMouseOrTouchEventInfo)().isTouch&&(e&&this.selectPointMode().value()!==Ve.SelectPointMode.None?this.startTrackingMode():this.exitTrackingMode());for(const e of this._paneWidgets)e.update();e||this.model().selectionMacro((e=>{e.clearSelection()})),this._isActive.setValue(e)}justActivated(){return this._justActivated}unsetActivePaneWidget(){this.activePaneWidget=null}setActivePaneWidget(e){this.activePaneWidget=e}onPaneWidgetDestroyed(e){this.activePaneWidget===e&&(this.activePaneWidget=null)}backgroundTopTheme(){return this._backgroundTopTheme.readonly()}backgroundBasedTheme(){return this._backgroundBasedTheme.readonly()} backgroundBottomTheme(){return this._backgroundBottomTheme.readonly()}lineToolsAndGroupsDTO(){return(0,r.ensureNotNull)(this._lineToolsSynchronizer).prepareDTO()}resetLineToolsInvalidated(e,t,i){(0,r.ensureNotNull)(this._lineToolsSynchronizer).resetInvalidated(e,t,i)}applyLineToolUpdateNotification(e,t){(0,r.ensureNotNull)(this._lineToolsSynchronizer).applyLineToolUpdateNotification(e,t)}reloadAllLineTools(){(0,r.ensureNotNull)(this._lineToolsSynchronizer).reloadAllLineTools()}startApplyingLineToolUpdateNotification(){var e;null===(e=this._lineToolsSynchronizer)||void 0===e||e.startApplyingLineToolUpdateNotification()}endApplyingLineToolUpdateNotification(){var e;null===(e=this._lineToolsSynchronizer)||void 0===e||e.endApplyingLineToolUpdateNotification()}applyAlertIdByExternalSource(e,t){var i;null===(i=this._lineToolsSynchronizer)||void 0===i||i.applyAlertIdByExternalSource(e,t)}deleteAlertByExternalSource(e,t){var i;null===(i=this._lineToolsSynchronizer)||void 0===i||i.deleteAlertByExternalSource(e)}shouldBeSavedEvenIfHidden(){return this._model?this.model().model().shouldBeSavedEvenIfHidden():!!this._options.content.shouldBeSavedEvenIfHidden}showObjectsTreePanelOrDialog(){let e=!1;const t=window.widgetbar;if(t&&t.isVisible()){const i=(0,r.ensureNotNull)(t.setPage("object_tree")),s=(0,r.ensureNotNull)(i.widget("object_tree"));(0,r.ensureDefined)(s.properties).setValue({selectedPage:"object_tree"}),e="object_tree"===i.name}e||this.showObjectsTreeDialog()}showObjectsTreeDialog(){var e;null===(e=this._objectTreeDialogController)||void 0===e||e.show()}addCustomWidgetToLegend(e,t){this._customLegendWidgetsFactoryMap.set(e,t);for(const i of this.paneWidgets())i.addCustomWidgetToLegend(e,t)}applyIndicatorsToAllChartsAvailable(){if(!this.chartWidgetCollection().applyIndicatorsToAllChartsAvailable())return!1;for(const e of this.model().model().panes()){if(e.sourcesByGroup().all().some((e=>(0,$.isStudy)(e)&&!(0,Q.isLollipopDataSource)(e))))return!0}return!1}restoreState(e,t,s){this._adjustSize();const o=(0,r.ensureNotNull)(this._model),n=o.restoreState(this._content,t,s),a=o.mainSeries().properties().childs();this._symbolWV.setValue(a.symbol.value()),this._resolutionWV.setValue(a.interval.value()),this._setActions(),n&&n.lines_limit_exceeded&&!this.readOnly()&&Promise.all([i.e(63987),i.e(1888),i.e(35213),i.e(63830),i.e(33371),i.e(54712),i.e(25977),i.e(33904),i.e(88913),i.e(90609)]).then(i.bind(i,215079)).then((({showLinetoolsLimitExceededDialog:e})=>{e(this)}))}addCompareAsOverlay(e,t,i){const s=this.model();return(0,r.ensureDefined)(this._options.isSymbolAvailable)(e).then((o=>{if(!o)return null;const r=s.createStudyInserter({type:"java",studyId:"Overlay@tv-basicstudies"},[]);return r.setForceOverlay(!0),r.setPreferredPriceScale("as-series"),!0!==i&&r.setTargetPriceScaleMode({percentage:!0}),void 0!==t&&r.setPropertiesState({allowExtendTimeScale:t}),r.insert((async()=>({inputs:{symbol:e},parentSources:[]})))}))}scrollHelper(){return this._scrollHelper}chartPainted(){ return this._drawPlanned?(null===this._chartPaintedPromise&&(this._chartPaintedPromise=(0,v.createDeferredPromise)()),this._chartPaintedPromise.promise):Promise.resolve()}setDataWindowWidget(e){this._dataWindowWidget=e}removeDataWindowWidget(){this._dataWindowWidget=null}showSelectedSourcesProperties(e){const t=(0,r.ensureNotNull)(this._model).selection().dataSources();if(1===t.length)this.showSourceProperties(t[0],e);else{const i=t.filter(te.isLineTool);i.length>0&&this.showChartPropertiesForSources({sources:i,tabName:e})}}connect(){this._chartSession.isConnected().subscribe(this._onChartSessionIsConnectedChanged),this._chartSession.criticalError().subscribe(this,this._onChartSessionCriticalError),this._chartSession.connect(this._onData.bind(this))}finishInitWithoutConnect(){this._chartSession.disable(),this._init(),this._chartWidgetInitialized.fire()}reconnect(){this._chartSession.disconnect(),this._chartSession.connect()}update(){if(this.hasModel()){for(const e of this._paneWidgets)e.update();this._timeAxisWidget&&this._timeAxisWidget.update()}}setPriceAxisHovered(e,t){t?this._hoveredPriceAxes.add(e):this._hoveredPriceAxes.delete(e),this._anyAxisHovered.setValue(this._hoveredPriceAxes.size>0)}anyPriceAxisHovered(){return this._anyAxisHovered.readonly()}linkingGroupIndex(){return this._linkingGroupIndex}offsetInDocument(e){const t=this._paneWidgets.find((t=>t.state()===e));if(void 0===t)return{left:NaN,top:NaN};const i=t.getElement().getBoundingClientRect();return{left:Math.round(i.left+document.body.scrollLeft),top:Math.round(i.top+document.body.scrollTop)}}showHint(e,...t){0===e?this._showEventHint(...t):1===e&&this._showWarningHint(...t)}_registerLineToolHotkeys(){if(!this.readOnly()){const e=(e,t)=>{this.activePaneWidget&&("drawRightThere"===t.action?this.activePaneWidget.drawRightThere(e):Ve.tool.setValue(e))},t=(t,i)=>()=>e(t,i);Object.entries(ns.lineToolsSelectHotkeys).map((([e,i])=>({desc:i.description,hotkey:i.hash,handler:t(e,i)}))).forEach((e=>this._hotkeys.add(e)))}}_createShowDataWindowAction(){return this._showDataWindowAction=new H.ActionWithStandardIcon({actionId:"Chart.DataWindow.Show",options:{label:(0,S.appendEllipsis)(a.t(null,void 0,i(409068))),statName:"DataWindow",hotkeyGroup:this._hotkeys,hotkeyHash:n.Modifiers.Alt+68,iconId:"Chart.ShowDataWindow",onExecute:rs}}),this._showDataWindowAction}_createChartResetAction(){return new H.ActionWithStandardIcon({actionId:"Chart.Scales.Reset",options:{label:a.t(null,void 0,i(834301)),iconId:"Chart.Reset",statName:"ResetChart",onExecute:this.GUIResetScales.bind(this),hotkeyGroup:this._hotkeys,hotkeyHash:n.Modifiers.Alt+82}})}_createApplyColorThemeAction(){return!((0,Di.showThemeSwitcher)()||(0,Di.showThemeAction)()||window.is_authenticated)?null:new F.Action({actionId:"Chart.Theme.Apply",options:{name:"apply-color-theme",label:a.t(null,void 0,i(132409)),iconId:"Platform.ColorTheme",icon:z.icons.get("Platform.ColorTheme"),subItems:[new F.Action({actionId:"Loading",options:{label:a.t(null,void 0,i(25911))}})],statName:"ColorTheme"}})} _createRemoveSelectedObjectAction(){return new H.ActionWithStandardIcon({actionId:"Chart.SelectedObject.Remove",options:{label:a.t(null,void 0,i(734596)),iconId:"Chart.RemoveSelectedObject",statName:"RemoveSelectedObject",onExecute:()=>{var e;(null!==(e=this._chartWidgetCollection.activeChartWidget.value())&&void 0!==e?e:this).removeSelectedSources()},hotkeyGroup:this._hotkeys,hotkeyHash:n.isMacKeyboard?8:46}})}_createResetTimescaleAction(){return new H.ActionWithStandardIcon({actionId:"Chart.TimeScale.Reset",options:{label:a.t(null,void 0,i(825333)),iconId:"Chart.Reset",statName:"ResetScale",onExecute:()=>{this.model().resetTimeScale()},hotkeyGroup:this._hotkeys,hotkeyHash:n.Modifiers.Mod+n.Modifiers.Alt+81}})}_createChartPropertiesAction(){return new H.ActionWithStandardIcon({actionId:"Chart.Dialogs.ShowGeneralSettings",options:{label:(0,S.appendEllipsis)(a.t(null,void 0,i(389517))),iconId:"Settings",statName:"ChartProperties",onExecute:()=>{this.showGeneralChartProperties()}}})}_createMainSeriesPropertiesAction(){return new H.ActionWithStandardIcon({actionId:"Chart.Dialogs.ShowGeneralSettings.SymbolTab",options:{label:(0,S.appendEllipsis)(a.t(null,void 0,i(389517))),iconId:"Settings",statName:"MainSeriesProperties",onExecute:()=>{this.showGeneralChartProperties(K.TabNames.symbol)}}})}_createScalesPropertiesAction(){return new H.ActionWithStandardIcon({actionId:"Chart.Dialogs.ShowGeneralSettings.ScalesTab",options:{label:(0,S.appendEllipsis)(a.t(null,void 0,i(389517))),iconId:"Settings",statName:"ScalesProperties",onExecute:()=>{this.showGeneralChartProperties(K.TabNames.scales)}}})}_createSelectedSourcePropertiesAction(){return new H.ActionWithStandardIcon({actionId:"Chart.SelectedObject.ShowSettingsDialog",options:{label:(0,S.appendEllipsis)(a.t(null,void 0,i(389517))),iconId:"Settings",statName:"EditSelectedObject",onExecute:()=>{this.showSelectedSourcesProperties()}}})}_createHideSelectedObjectAction(){return new H.ActionWithStandardIcon({actionId:"Chart.SelectedObject.Hide",options:{label:a.t(null,void 0,i(831971)),iconId:"Chart.Hide",statName:"HideSelectedObject",onExecute:this.hideSelectedObject.bind(this)}})}_createShowSymbolInfoDialogAction(){return new H.ActionWithStandardIcon({actionId:"Chart.Dialogs.ShowSymbolInfo",options:{label:(0,S.appendEllipsis)((0,Fi.isMobile)()?a.t(null,void 0,i(358021)):a.t(null,void 0,i(979758))),iconId:"Chart.SymbolInfo",checkable:!1,statName:"SymbolInfo",onExecute:()=>{if((0,Fi.isMobile)())B.enabled("mobile_app_action_open_details_webview")&&this._options.onDetailsWebviewOpen?this._options.onDetailsWebviewOpen():(0,Hi.showDetailsDialog)(),(0,_.trackEvent)("ContextMenuClick","Mobile","SymbolInfo");else{const e=this.model().model(),t=e.mainSeries().symbolInfo();if(t){const i=e.availableUnits(),s={symbolInfo:t,showUnit:e.unitConversionEnabled(),unitDescription:e=>e?i.description(e):"",dateFormatter:e.dateFormatter()};(0,g.showSymbolInfoDialog)(s)}}}}})}_createShowFinancialsAction(){return new H.ActionWithStandardIcon({actionId:"Chart.Dialogs.ShowInsertFinancials",options:{ label:(0,S.appendEllipsis)(a.t(null,void 0,i(677720))),iconId:"Chart.Financials",statName:"Financials",onExecute:()=>{B.enabled("mobile_app_action_open_financials_webview")?(0,Wi.openFinancialsWebview)(new URLSearchParams):(0,zi.showFinancialsDialog)(),window.matchMedia("screen and (max-width: 430px)").matches&&(0,_.trackEvent)("ContextMenuClick","","Financials"),(0,Ni.getTracker)().then((e=>{null==e||e.trackFinancialsDialog(c.linking.ensuredProSymbol.value(),"contextMenu")}))}}})}_createAddToWatchlistAction(){if(!this._options.addToWatchlistEnabled)return null;const e={hotkeyGroup:this._hotkeys};return new ss(this,e)}_clearSelectionHotkey(){return{desc:"Cancel selection",hotkey:27,handler:()=>{var e,t,i,s;if(this.selectPointMode().value()!==Ve.SelectPointMode.None)return this.selectPointMode().value()===Ve.SelectPointMode.Replay&&this._chartWidgetCollection.getAll().forEach((e=>{e!==this&&e.selectPointMode().value()===Ve.SelectPointMode.Replay&&e.cancelRequestSelectPoint()})),void this.cancelRequestSelectPoint();null===(e=this._model)||void 0===e||e.selectionMacro((e=>{this._cancelCreatingLine(),e.clearSelection()}));const o=null===(t=this._model)||void 0===t?void 0:t.model().customSourceMovingHitTestData();o&&o.cancelMoveHandler&&o.cancelMoveHandler()&&(o.cancelled=!0,null===(i=this._model)||void 0===i||i.model().setMovingCustomSource(null,null),null===(s=this._model)||void 0===s||s.model().lightUpdate())},isDisabled:()=>{const e=this._model;if(!e)return!0;const t=0===e.selection().allSources().length,i=null===e.crossHairSource().measurePane().value(),s=this.selectPointMode().value()===Ve.SelectPointMode.None;return t&&i&&s}}}_insertStudy(e,t,s,o){const n=(0,r.ensureNotNull)(this._model).createStudyInserter(e,t,s);n.setForceOverlay("java"===e.type&&"Volume@tv-basicstudies"===e.studyId&&B.enabled("volume_force_overlay"));const l=n.insert(((e,i,s)=>new Promise(((r,n)=>{var a;this.selectPointMode().value()!==Ve.SelectPointMode.None&&this.cancelRequestSelectPoint(),o?r(o(e,i,s)):!function(e){return qs.includes(e.id)}(s)?(null!=(a=i)?a:[]).some((e=>e.confirm))?((0,_.trackEvent)("GUI","Confirmation dialogs","Inputs confirmation dialog"),I(this,e,s,r,n)):r({inputs:{},parentSources:t}):((0,_.trackEvent)("GUI","Confirmation dialogs","Symbol confirmation dialog"),I(this,e,s,r,n,"symbol"))}))));return l.then((()=>{(0,Ve.hideAllIndicators)().value()&&(0,y.toggleHideMode)()})).catch((e=>{e===ps.InsertionErrorCode.StudyCannotBeChild&&(0,Vi.showNoticeDialog)({type:"modal",title:a.t(null,void 0,i(900850)),content:a.t(null,void 0,i(465943))}),e===ps.InsertionErrorCode.CannotCompilePub&&(0,Vi.showNoticeDialog)({type:"modal",title:a.t(null,void 0,i(900850)),content:a.t(null,void 0,i(81214))}),e===ps.InsertionErrorCode.CannotGetMetainfo&&(0,Vi.showNoticeDialog)({type:"modal",title:a.t(null,void 0,i(900850)),content:a.t(null,void 0,i(164968))})})),l}async _showChartProperties(e,t,i,s){if(!this._model)return null;t&&((0,d.setValue)("properties_dialog.active_tab.chart",t),i.tabName=t) ;const o=await oe(e,this._model,i,this._options.chartWidgetCollection,s);return(null==o?void 0:o.visible().value())?o:null}_createLineToolsSynchronizerIfNeeded(){var e;{const t={readOnlyMode:this.readOnly(),migrateSyncedLineTools:this===this._options.chartWidgetCollection.getAll()[0]},i=Rs;this._lineToolsSynchronizer=new i({layoutId:this.layoutId(),chartId:this._id,clientId:this._chartWidgetCollection.clientId},this.model().model(),t,(()=>this._chartWidgetCollection.isFirstChartInLayout(this)),(()=>this._chartWidgetCollection.deserializedChartIds())),null!==this._saveChartService&&this._lineToolsSynchronizer.setSaveChartService(this._saveChartService),this._lineToolsSynchronizer.invalidateAll(),null===(e=this._model)||void 0===e||e.model().setLineToolsSynchronizer(this._lineToolsSynchronizer)}}_updateThemedColor(){const e=this.model().model(),t=e.backgroundColorAtYPercentFromTop(.5);let i=e.backgroundTopColor().value(),s=e.backgroundColor().value();const o=(0,p.isColorDark)(t),r=(0,p.isColorDark)(i),n=(0,p.isColorDark)(s);this.widget().classList.toggle("chart-widget--themed-dark",o),this.widget().classList.toggle("chart-widget--themed-light",!o),this.widget().classList.toggle("chart-widget__top--themed-dark",r),this.widget().classList.toggle("chart-widget__top--themed-light",!r),this.widget().classList.toggle("chart-widget__bottom--themed-dark",n),this.widget().classList.toggle("chart-widget__bottom--themed-light",!n),this._backgroundTopTheme.setValue(r?"dark":"light"),this._backgroundBasedTheme.setValue(o?"dark":"light"),this._backgroundBottomTheme.setValue(n?"dark":"light"),i===s&&(0,u.isStdThemedDefaultValue)("chartProperties.paneProperties.background",i,this._backgroundBasedTheme.value())&&(i=null,s=null);for(const e of this._paneWidgets)e.updateThemedColors({topColor:i,bottomColor:s})}_isLineToolModeExceptBrush(){const e=Ve.tool.value();return(0,Ht.isLineToolName)(e)&&!(0,Ht.isLineDrawnWithPressedButton)(e)&&this.selectPointMode().value()===Ve.SelectPointMode.None}_cancelCreatingLine(){const e=(0,r.ensureNotNull)(this._model).model(),t=e.lineBeingCreated();if(null!==t){const i=(0,r.ensureNotNull)(e.paneForSource(t));(0,r.ensureNotNull)(this.paneByState(i)).cancelCreatingLineTool(),t.toolname===Ve.tool.value()&&(0,Ve.resetToCursor)()}const i=e.crossHairSource().measurePane().value();if(null!==i){(0,r.ensureNotNull)(this.paneByState(i)).cancelMeasuring()}}_adjustSize(e){var t;let i=0;const o=null===this._model?null:this._model.model().priceScaleSlotsCount(),r=new Uint32Array(null===o?0:o.left),n=new Uint32Array(null===o?0:o.right),a=(0,pe.getCanvasDevicePixelRatio)(document.body),c=(e,t)=>e+t,h=(e,t)=>{t.forEach(((t,i)=>{e[i]=Math.max(e[i],t)}))},d=this._width(),u=this._height(),_=this._paneSeparators.length,p=this.isMaximizedPane()?0:Ae.height()*_,m=null!==this._timeAxisWidget?this._timeAxisWidget.optimalHeight():0;let g=u-m>=61?m:0;g%2&&(g+=1);const S=Math.max(1,Math.floor((u-p-g)/this._paneWidgets.length));let v=0,f=null ;for(const e of this._paneWidgets)if(!this._maximizedPaneWidget||this._maximizedPaneWidget===e){e.leftPriceAxisesContainer().updateCurrencyLabels();const t=e.leftPriceAxisesContainer().optimalWidths();e.rightPriceAxisesContainer().updateCurrencyLabels();const s=e.rightPriceAxisesContainer().optimalWidths();h(r,t),h(n,s),this._maximizedPaneWidget!==e&&e.state().collapsed().value()?v+=Math.min(S,e.collapsedHeight()):(i+=e.stretchFactor(),f=e)}let b=r.reduce(c,0),y=n.reduce(c,0),C=Math.max(d-b-y,0);if(C<=102){b=0,y=0,C=d;for(let e=0;e0){const e=new Ae(this,o-1,o);this._paneSeparators.push(e),this._timeAxisWidget?this._elMainTable.insertBefore(e.getElement(),this._timeAxisWidget.getElement()):this._elMainTable.appendChild(e.getElement())}this._timeAxisWidget?this._elMainTable.insertBefore(i.getElement(),this._timeAxisWidget.getElement()):this._elMainTable.appendChild(i.getElement())}for(let i=0;ime.InvalidationLevel.Cursor&&(null===(i=this._timeAxisWidget)||void 0===i||i.update(),this._paneWidgets.forEach((e=>{e.updatePriceAxisWidgets()})),this._applyTimeScaleInvalidations(e,t),(null===(s=this._invalidationMask)||void 0===s?void 0:s.fullInvalidation())===me.InvalidationLevel.Full&&(this._invalidationMask.merge(e),this._adjustSize(this._invalidationMask.isVisibleTimeRangeLockedOnResize()),this._applyTimeScaleInvalidations(this._invalidationMask,t),e=this._invalidationMask,this._invalidationMask=null)),this.paint(e),this._dataWindowWidget){const t=e.maxPaneInvalidation();t===me.InvalidationLevel.Full?this._dataWindowWidget.fullUpdate():t>me.InvalidationLevel.None&&this._dataWindowWidget.update()}for(let t=0;tthis._justActivated=!1),0)}_requestActive(){this._beginRequestActive(),this._endRequestActive()}_updateGui(e){this._model&&(this._makeTimeAxisWidget(),this._makePaneWidgetsAndSeparators(),this._elMainTable.style.userSelect="none",this._adjustSize(e))}_setElement(e){if(this._mainDiv){this._mainDiv.remove();const e=document.createRange();e.selectNodeContents((0,r.ensureNotNull)(this._parent)),e.deleteContents()}this._controlBarNavigation&&(this._controlBarNavigation.destroy(),this._controlBarNavigation=null),null!==this._removeMaximizeHotkey&&this._removeMaximizeHotkey(),this._removeMaximizeHotkey=this._initMaximizeHotkey(e);const t=e.ownerDocument,s=t.createElement("div");s.classList.add("chart-container-border"),e.insertBefore(s,e.firstChild),this._parent=s;const o=t.createElement("div");if(o.classList.add("chart-widget"),this._mainDiv=o,this._elTooltipDiv=t.createElement("div"),this._elTooltipDiv.className="tooltip-wrapper",this._mainDiv.appendChild(this._elTooltipDiv),this._elMainTable=t.createElement("div"),this._elMainTable.className="chart-markup-table",this._mainDiv.appendChild(this._elMainTable),xe.PLATFORM_ACCESSIBILITY_ENABLED&&(o.setAttribute("role","region"),o.setAttribute("aria-label",a.t(null,{replace:{index:this.id()}},i(886715)))),this._hotkeysListener&&this._hotkeysListener.destroy(),this._errorRenderer.setContainer(this._parent),this._hotkeysListener=new G.ChartHotkeysListener(this,this._mainDiv),(this._options.controlBarEnabled||B.enabled("control_bar"))&&this._createControlBar(),this._options.handleScale.mouseWheel||this._options.handleScroll.mouseWheel){this._mouseWheelHelper=new we;const e=this._onMousewheel.bind(this);this._onWheelBound=e,this._mainDiv.addEventListener("wheel",e,{passive:!1})}this._mainDiv.addEventListener("mouseenter",(()=>this._isHovered.setValue(!0))),this._mainDiv.addEventListener("mouseleave",(()=>this._isHovered.setValue(!1))),this.resize(),this._justActivated=!1,this.withModel(this,(()=>{s.appendChild(o),o.addEventListener("mousedown",this._beginRequestActive.bind(this)),o.addEventListener("mouseup",this._endRequestActive.bind(this)),o.addEventListener("touchstart",this._beginRequestActive.bind(this)),o.addEventListener("touchmove",this._endRequestActive.bind(this)),o.addEventListener("touchend",this._endRequestActive.bind(this)),o.addEventListener("click",this._requestActive.bind(this))})), this._inited&&(null!==this._timeAxisWidget&&(this._timeAxisWidget.destroy(),this._timeAxisWidget=null),this._paneWidgets.forEach((e=>{e.destroy()})),this._paneWidgets.length=0,this._paneSeparators.forEach((e=>{e.destroy()})),this._paneSeparators.length=0,this._update(me.InvalidationMask.full(),performance.now()))}_init(){this.hasModel()&&this.model().mainSeries().clearData(),this._initColors(),this._makeDefaultGui();this._makeDefaultModel(),(()=>{this._checkObsoleteTimezone(),this._chartSession&&this._chartSession.connected()&&this.model().model().restart(),this._content&&(this._initColors(),this._updateGui(),this.update()),this._resizeHandler=()=>{this._invalidationHandler(me.InvalidationMask.full())},this._resizeHandler(),(0,r.ensureNotNull)(this._parent).appendChild((0,r.ensureNotNull)(this._mainDiv)),this._spinner&&(this._spinner.stop(),this._spinner=null),this._activateSymbolSearchHotkeys(),this.model().timeScale().onScroll().subscribe(this,(()=>this._onScroll.fire())),this._inited=!0})()}_makeDefaultModel(){let e;if(this._content&&this._content.timeScale.points){const t=this._content.timeScale.points.items[0];e={startDate:t}}const t=()=>{var t,i;const s={readOnly:this.readOnly(),isSnapshot:!!this._containsData,...f(this._options,["timeScale","crossHair","chartEventsEnabled","newsNotificationsEnabled","esdEnabled","latestUpdatesEnabled","continuousContractSwitchesEnabled","futuresContractExpirationEnabled","countdownEnabled","lastPriceAnimationEnabled","currencyConversionEnabled","unitConversionEnabled","watermarkEnabled","shiftVisibleRangeOnNewBar","hideIdeas","onWidget"])},o=function(e,t,i,s,o,r,n,a,l,c,h){const d=new Ti.ChartUndoModel(e,t,i,s,o,r,n,a,l,c,h);return d.model().fullUpdate(),d}(this._chartSession,this._invalidationHandler,this.properties(),e,this,this._options.undoHistory,this._options.barsMarksContainersFactory,s,this._collapsed,this._linkingGroupIndex,null!==(i=null===(t=this._saveChartService)||void 0===t?void 0:t.autoSaveEnabled())&&void 0!==i?i:new W.WatchedValue(!0));return this._createSessions(o.model()),this._createPrePostMarket(o.model()),o};B.enabled("lean_chart_load")?this._model=this._model||t():this._model=t(),this._model.model().setChartSaveTime(1e3*this._chartWidgetCollection.metaInfo.lastModified.value()),this._createVolumeIfNeeded();if(this._content){let e=this._setSymbolIntervalContentOverrides;Vs&&this._initialLoading&&(e={...e,symbol:this._defSymbol,interval:this._defInterval,style:this._defStyle}),this.restoreState(this._content,this._containsData,e),this._setSymbolIntervalContentOverrides={},Vs&&this._defSymbol&&this.model().model().recalculatePriceRangeOnce()}else this._setActions();this._createLineToolsSynchronizerIfNeeded(),(()=>{const e=(0,r.ensureNotNull)(this._model);e.onTagsChanged().subscribe(this,(()=>this.onModelTagsChanged())),this._initBackgroundColor(),this._updateGui(),this._modelCreated.fire(e),this._tagsChanged.fire();const t=e.mainSeries(),s=t.properties().childs();this._defTimeframe&&t.setDefaultTimeframe(this._defTimeframe), t.dataEvents().symbolNotPermitted().subscribe(null,(e=>t.setSymbolParams({symbol:e}))),this._symbolWV.setValue(s.symbol.value()),s.symbol.subscribe(this,(e=>this._symbolWV.setValue(e.value()))),this._resolutionWV.setValue(s.interval.value()),s.interval.subscribe(this,(e=>this._resolutionWV.setValue(e.value()))),window.loginStateChange.subscribe(this,this._handleLoginStateChanged),this._handleLoginStateChanged(),t.dataEvents().symbolResolved().subscribe(this,(e=>{const i=e.pro_name,s=e.pro_perm;i&&this._options.isSymbolAvailable&&this._options.isSymbolAvailable(i,s).then((e=>{e||t.setSymbolParams({symbol:window.DEFAULT_SYMBOL})}))})),void 0!==this._options.requestFallbackSymbol&&t.dataEvents().symbolGroupNotPermitted().subscribe(this,(e=>{(0,r.ensureDefined)(this._options.requestFallbackSymbol)(s.symbol.value(),{type:"group_not_permitted",symbolGroup:e}).then((e=>{e&&t.setSymbolParams({symbol:e})}))})),(0,r.ensureDefined)(t.onInReplayStateChanged).bind(t)().subscribe(this.screen,this.screen.show),s.style.unsubscribe(this,this._onChartStyleChanged),s.style.subscribe(this,this._onChartStyleChanged),t.dataEvents().completed().subscribe(this,(()=>this._addPerfMark("SeriesCompleted")),!0),t.dataEvents().barReceived().subscribe(this,(()=>this._addPerfMark("SeriesFirstDataReceived")),!0);const o=this._options;t.dataEvents().chartTypeNotPermitted().subscribe(null,(()=>{t.setSymbolParams({interval:"D"}),o.muteSessionErrors||((0,Bi.trackGoProFeature)("kagiRenko"),(0,Ei.reloginOrGoPro)({feature:"kagiRenko"}))})),t.dataEvents().intradaySpreadNotPermitted().subscribe(null,(()=>{t.setSymbolParams({interval:"D"}),o.muteSessionErrors||(0,Ei.reloginOrGoPro)({feature:"intradaySpread"})})),t.dataEvents().customIntervalNotPermitted().subscribe(null,(i=>{const s=e.model().defaultResolutions(),r=s.find((e=>(0,Yt.compareResolutions)(e,i)>=0)),n=null!=r?r:s[s.length-1];t.setSymbolParams({interval:n}),o.muteSessionErrors||(0,Ei.reloginOrGoPro)({feature:"customIntervals"})}));const n=a.t(null,void 0,i(993213));t.dataEvents().secondsIntervalNotPermitted().subscribe(null,(()=>{const e=t.getSupportedResolution("1",!1);t.setSymbolParams({interval:e}),o.muteSessionErrors||(0,Ei.reloginOrGoPro)({feature:"secondsIntervals",forceUpgradeBtn:!0})})),t.dataEvents().ticksIntervalNotPermitted().subscribe(null,(()=>{const e=t.getSupportedResolution("1",!1);t.setSymbolParams({interval:e}),o.muteSessionErrors||(0,Ei.reloginOrGoPro)({feature:"tickIntervals",forceUpgradeBtn:!0,isTrialAvailable:!1})})),t.dataEvents().intradayExchangeNotPermitted().subscribe(null,(()=>{if(t.setSymbolParams({interval:"D"}),!o.muteSessionErrors){let e=(0,r.ensureNotNull)(t.symbolInfo()).listed_exchange;(0,ki.getExchanges)().forEach((t=>{t.value===e&&(e=t.name)})),(0,Ei.reloginOrGoPro)({feature:"intradayExchange"})}})),t.requestingTicksWhenNotSupported.subscribe(null,(()=>{if(!o.muteSessionErrors){const e=document.createElement("div"),t=a.t(null,void 0,i(687826)).format({p_start:"

",p_end:"

"});e.innerHTML=t,(0,Vi.showNoticeDialog)({title:n,content:e})}})), t.requestingIntradayWhenNotSupported.subscribe(null,(()=>{if(!o.muteSessionErrors&&!Us.requestingIntradayWhenNotSupported){Us.requestingIntradayWhenNotSupported=!0;const e=document.createElement("div"),t=a.t(null,void 0,i(687692)).format({p_start:"

",p_end:"

",b_start:"",b_end:""});e.innerHTML=t,(0,Vi.showNoticeDialog)({title:n,content:e,onDialogClosed:()=>Us.requestingIntradayWhenNotSupported=!1})}})),t.requestingResolutionLessThanFrequency.subscribe(null,((e,t)=>{if(!o.muteSessionErrors&&!Us.requestingResolutionLessThanFrequency){Us.requestingResolutionLessThanFrequency=!0;const s=document.createElement("div"),o=a.t(null,void 0,i(15795)).format({p_start:"

",p_end:"

",b_start:"",b_end:"",data_frequency:e,min_interval:t});s.innerHTML=o,(0,Vi.showNoticeDialog)({title:n,content:s,onDialogClosed:()=>Us.requestingResolutionLessThanFrequency=!1})}})),t.requestingStyleIsNotSupported.subscribe(null,(()=>{const i=t.interval(),s=e.model().defaultResolutions(),o=(0,he.getLastUsedSingleValueBasedStyle)(),r=(0,Yt.getResolutionByChartStyle)(o,i,s);t.setChartStyleWithIntervalIfNeeded(o,r)})),t.requestingStyleSupportRecovered.subscribe(null,(i=>{const s=t.interval(),o=e.model().defaultResolutions(),r=(0,Yt.getResolutionByChartStyle)(i,s,o);t.setChartStyleWithIntervalIfNeeded(i,r)}))})()}_startSpinner(e){this._spinner||e&&(this._spinner=(new L.Spinner).spin(e))}_handleLoginStateChanged(){B.enabled("popup_hints")&&window.user&&window.user.is_pro?this._noExchangeSubscrptionWarning=new Ki(this):null!==this._noExchangeSubscrptionWarning&&(this._noExchangeSubscrptionWarning.destroy(),this._noExchangeSubscrptionWarning=null)}_checkObsoleteTimezone(){const e=this.properties().childs().timezone.value();(0,D.timezoneIsAvailable)(e)||this.properties().childs().timezone.setValue({UTC:"Etc/UTC",EST:"America/New_York",CST:"America/Chicago",PST:"America/Los_Angeles"}[e]||"exchange")}_initColors(){const e=this.properties().childs(),t=e.scalesProperties.childs();t.lineColor.listeners().subscribe(this,this._updateAndPaint),t.textColor.listeners().subscribe(this,this._updateAndPaint),e.paneProperties.childs().separatorColor.listeners().subscribe(this,this._setPaneSeparatorLineColor)}_setPaneSeparatorLineColor(){this._paneSeparators.forEach((e=>e.update())),this._updateAndPaint()}_updateAndPaint(){this.update(),this.paint()}_makeDefaultGui(){this._makeLoadingScreen(),this.onWidget()&&this._makeAvailableOnTVPopup(),this.hasModel()&&(this._makeTimeAxisWidget(),this._makePaneWidgetsAndSeparators()),this._adjustSize(),this._updateScalesActions(),(0,U.disableSelection)(this._elMainTable),this._updateAndPaint()}_makeLoadingScreen(){if(B.enabled("lean_chart_load")){if(this.screen)return;this.screen=new ye(this,(0,r.ensureNotNull)(this._parent))}else this.screen=new ye(this,(0,r.ensureNotNull)(this._mainDiv))}_makeAvailableOnTVPopup(){this._availableScreen||(this._availableScreen=new ls(this))}_activateSymbolSearchHotkeys(){this.readOnly()||this._options.hideSymbolSearch||(0,b.activateKeyPressHandler)()}_makeTimeAxisWidget(){ if(this._timeAxisWidget)return void this._timeAxisWidget.updatePriceAxisStubs();const e=this.model();this._timeAxisWidget=new Pi(this,this._options.timeScaleWidget,this._titlesProvider.bind(this),this._menuItemsProvider.bind(this),this._backgroundBasedTheme.spawnOwnership()),this._elMainTable.appendChild(this._timeAxisWidget.getElement()),this._timeAxisWidget.updatePriceAxisStubs(),this._timeAxisWidget.onLabelHovered().subscribe(this,((t,i)=>{const s=this._maximizedPaneWidget?this._maximizedPaneWidget.state():e.paneForSource(e.mainSeries()),o=(0,r.ensureNotNull)(this.paneByState((0,r.ensureNotNull)(s))).highlightedPriceAxis(),n=o.value();(i||n.owner===t.owner)&&(o.setValue({owner:t.owner,axis:i?t.axis:null}),this.model().model().lightUpdate())}))}_updateAriaPriceDescription(e){}_titlesProvider(e,t){const i=this.model(),s=(0,r.ensureNotNull)(this._maximizedPaneWidget?this._maximizedPaneWidget.state():i.paneForSource(i.mainSeries())),o="right"===e?s.rightPriceScales():s.leftPriceScales();if(o.lengthe===i.mainSeries()||(0,$.isStudy)(e)));return n.reverse(),n=(0,k.moveToHead)(n,i.mainSeries()),n.map((e=>e.title(xi.TitleDisplayTarget.StatusLine,!0,void 0,!1)))}_menuItemsProvider(e,t){const i=this.model(),s=(0,r.ensureNotNull)(this._maximizedPaneWidget?this._maximizedPaneWidget.state():i.paneForSource(i.mainSeries())),o="right"===e?s.visibleRightPriceScales():s.visibleLeftPriceScales();if(o.length{const i=this._model;if(null===i)return;const s=i.model();e.model!==s&&(this._lineToolsSynchronizer?this._lineToolsSynchronizer.executeSyncedAction((()=>t(s,i))):t(s,i))};Ve.createdLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const s=(0,r.ensureNotNull)(e.paneForSource(e.mainSeries()));let o,n=null;if(void 0===t.pointPositionPercents){if(n=Gs(e,t.model,t.point.timeStamp),null===n)return;o=t.point.price}else{const i=t.pointPositionPercents.x*e.timeScale().width(),s=e.mainSeries().priceScale(),r=t.pointPositionPercents.y*s.height(),a=e.mainSeries().firstValue();if(null===a)return;n=e.timeScale().coordinateToIndex(i),o=s.coordinateToPrice(r,a)}const a={index:(0,r.ensureNotNull)(n),price:o},l=i.createLineTool({pane:s,point:a,linetool:t.linetool,properties:t.properties,linkKey:t.linkKey,ownerSource:e.mainSeries(),disableSynchronization:!0,id:t.id,sharingMode:t.sharingMode});null!==l&&!Boolean(this.model().lineBeingCreated())&&t.finalState&&l.restoreExternalPoints(t.finalState,{indexesChanged:!0,pricesChanged:!0})}))})),Ve.continuedLineTool.subscribe(null,(t=>{e(t,((e,i)=>{var s;const o=Gs(e,t.model,t.point.timeStamp);if(null===o)return;const r={index:o,price:t.point.price},n=e.lineBeingCreated();if(null===n)return;i.continueExternalLine(r,null!==(s=t.envState)&&void 0!==s?s:void 0,!!t.finalState)&&t.finalState&&n.restoreExternalPoints(t.finalState,{indexesChanged:!0,pricesChanged:!0})}))})),Ve.cancelledLineTool.subscribe(null,(t=>{e(t,((e,t)=>{e.cancelCreatingLine()}))})),Ve.beenSetLineToolLastPoint.subscribe(null,(t=>{e(t,((e,i)=>{const s=e.lineBeingCreated();if(null===s||s.linkKey().value()!==t.linkKey)return;const o=Gs(e,t.model,t.point.timeStamp);if(null===o)return;const r={index:o, price:t.point.price};s.setLastPoint(r),s.updateAllViews((0,Kt.sourceChangeEvent)(s.id())),e.lightUpdate()}))})),Ve.startedMovingLineTool.subscribe(null,(t=>{e(t,((e,i)=>{var s;const o=t.linkKeys.map(te.lineToolByLinkKey.bind(null,e)).filter(T.notNull);if(o.length){const i=Gs(e,t.model,t.point.timeStamp);if(null===i)return;const r={index:i,price:t.point.price},n=null!==(s=t.activeItem)&&void 0!==s?s:null,a=o[0].pointToScreenPoint(r);a&&e.startMovingSources(o,{logical:r,screen:a},n,t.pointPositionPercents,null===t.envState?void 0:t.envState,!0)}}))})),Ve.movedLineTool.subscribe(null,(t=>{e(t,((e,i)=>{var s;const o=e.sourcesBeingMoved().filter(te.isLineTool).filter((e=>(e=>t.linkKeys.some((t=>e.linkKey().value()===t)))(e)));if(!o.length)return;const r=Gs(e,t.model,t.point.timeStamp);if(null===r)return;const n={index:r,price:t.point.price},a=o[0].pointToScreenPoint(n);a&&e.moveSources({logical:n,screen:a},t.pointPositionPercents,null!==(s=t.envState)&&void 0!==s?s:void 0,!0)}))})),Ve.finishedMovingLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const s=e.sourcesBeingMoved().filter(te.isLineTool);if(0===s.length)return;s.forEach((i=>{const s=(e=>{for(let i=0;i{e(t,((e,i)=>{var s;const o=(0,te.lineToolByLinkKey)(e,t.linkKey);if(null!==o){const i=o.getPoint(t.pointIndex),r=i?i.index:Gs(e,t.model,t.point.timeStamp);if(null===r)return;if(o.isActualSymbol()&&o.isActualCurrency()&&o.isActualUnit()){const i={index:r,price:t.point.price};e.startChangingLinetool(o,i,t.pointIndex,null!==(s=t.envState)&&void 0!==s?s:void 0,!0)}}}))})),Ve.changedLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const s=e.lineBeingEdited();if(null===s||s.linkKey().value()!==t.linkKey)return;let o=null;if(o=t.changes.indexesChanged?Gs(e,t.model,t.point.timeStamp):(0,r.ensureNotNull)(e.linePointBeingChanged()).index,null!==o&&s.isActualSymbol()&&s.isActualCurrency()&&s.isActualUnit()){const i={index:o,price:t.point.price};e.changeLinePoint(i,void 0,!0)}}))})),Ve.finishedChangingLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const s=(0,te.lineToolByLinkKey)(e,t.linkKey);null!==s&&s.isActualSymbol()&&s.isActualCurrency()&&s.isActualUnit()&&null!==e.lineBeingEdited()&&e.endChangingLinetool(!!t.finalState,!0),null!==s&&t.finalState&&s.restoreExternalPoints(t.finalState,t.changes)}))})),Ve.removedLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const{withUndo:s,unlink:o,linkKey:r}=t,n=(0,te.lineToolByLinkKey)(e,r);if(null!==n)o&&n.detachAlert(),s?i.removeSource(n,!1):(e.lineToolsGroupModel().removeLineTools([n]),e.removeSource(n));else if(this._lineToolsSynchronizer){const{sourceTitle:e,symbol:n,lineToolState:a}=t;i.removeUnloadedLineTool({state:a,unlink:o,sourceTitle:e,linkKey:r,symbol:n,withUndo:s})}}))})), Ve.finishedLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const s=(0,te.lineToolByLinkKey)(e,t.linkKey);null!==s&&(0,Ht.isLineToolFinishRequiredWhenCreatedByApi)(s.toolname)&&s.finish()}))})),Ve.changedLineStyle.subscribe(null,(t=>{e(t,((e,i)=>{const s=(0,te.lineToolByLinkKey)(e,t.linkKey);null!==s&&(s.restoreExternalState(t.state),s.propertiesChanged(!0),t.alertId&&s.syncAlert(t.alertId))}))})),Ve.restoredLineToolState.subscribe(null,(t=>{e(t,((e,i)=>{const s=(0,te.lineToolByLinkKey)(e,t.linkKey);if(null!==s){const i={...t.state};i.indexes=t.state.points.map((i=>({index:Gs(e,t.model,i.time_t),price:i.price}))),e.restoreLineToolState(s,i,!1)}}))})),Ve.restoredLineTool.subscribe(null,(t=>{e(t,((e,i)=>{e.restoreSource(t.state.restorePane,t.state.paneIndex,t.state.paneState,t.state.sourceState,null)}))})),Ve.copiedLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const s=(0,r.ensureNotNull)(e.paneForSource(e.mainSeries()));let o;const n={...t.state,intervalsVisibilities:(0,us.mergeIntervalVisibilitiesDefaults)(t.state.intervalsVisibilities)},a=(0,te.createLineToolProperties)(t.linetool,n,e),l=e.dataSourceForId(t.id);if(l){if(!(0,te.isLineTool)(l))return void Os.logError(`Error sync creating line tool. Object with id ${t.id} is already in use and it is not a line tool`);if(l.toolname!==t.linetool)return void Os.logError(`Error sync creating line tool. Object with id ${t.id} is already in use and its type differs: ${l.toolname} and ${t.linetool}`)}if(l&&(l.linkKey().setValue(t.linkKey),l.share(t.sharingMode)),t.pointPositionPercents){const e={index:0,price:0};if(o=null!=l?l:i.createLineTool({pane:s,point:e,linetool:t.linetool,properties:a,linkKey:t.linkKey,disableSynchronization:!0,id:t.id}),null===o)return;o.restorePositionPercents((0,r.ensureDefined)(t.pointPositionPercents))}else{const n=t.points.map((i=>({index:(0,r.ensureNotNull)(Gs(e,t.model,i.timeStamp)),price:i.price}))),c=n[0];if(l)o=l;else if(t.withUndo)o=i.createLineTool({pane:s,point:c,linetool:t.linetool,properties:a,linkKey:t.linkKey,sharingMode:t.sharingMode,disableSynchronization:!0,id:t.id});else{const e=new Ai.CreateLineToolUndoCommand({model:i.model(),pane:s,lineTool:t.linetool,ownerSource:(0,r.ensureNotNull)(s.mainDataSource()),drawOnAllChartsMode:t.sharingMode,id:t.id});e.redo(),e.startCreatingLine(c,a,t.linkKey||null,t.sharingMode),o=(0,r.ensureNotNull)(e.line())}if(null===o)return;const h=(e,s)=>{t.withUndo?i.continueCreatingLine(e,new Re.EnvironmentState(void 0,!0),s,!0):i.model().continueCreatingLine(e,new Re.EnvironmentState(void 0,!0),s,!0)},d=(0,Ht.isLineToolFinishRequiredWhenCreatedByApi)(t.linetool);if(e.lineBeingCreated())if(n.length>1)for(let e=1;e0){const i=Math.ceil(e.timeScale().width()/t.barCount);e.timeScale().setBarSpacing(i)}}_createEventHint(){if(null===this._eventHintDeferredPromise){const e=(0,v.createDeferredPromise)();this._eventHintDeferredPromise=e,Promise.all([i.e(9817),i.e(93280),i.e(50690),i.e(26166)]).then(i.bind(i,410837)).then((t=>{e.resolve(new t.ChartEventHintRenderer(this._chartWidgetCollection.getContainer()))}))}return this._eventHintDeferredPromise.promise}async _createWarningHint(){if(null===this._warningHintDeferredPromise){const e=(0,v.createDeferredPromise)();this._warningHintDeferredPromise=e,Promise.all([i.e(32109),i.e(6209),i.e(28497),i.e(50690),i.e(83129)]).then(i.bind(i,629981)).then((t=>{e.resolve(new t.ChartWarningHintRenderer(this))}))}return this._warningHintDeferredPromise.promise}_showEventHint(e){B.enabled("popup_hints")&&(null!==this._activeHint&&0===this._activeHint.type?this._activeHint.show(e):(this._hideHint(),this._createEventHint().then((t=>{this._activeHint=t,void 0!==e&&this._activeHint.show(e)}))))}_showWarningHint(e){ B.enabled("popup_hints")&&(null!==this._activeHint&&1===this._activeHint.type?this._activeHint.show(e):(this._hideHint(),this._createWarningHint().then((t=>{if(null!==t){if(this._activeHint=t,void 0===e)return;this._activeHint.show(e)}}))))}_hideHint(){null!==this._activeHint&&this._activeHint.hide()}}},749765:(e,t,i)=>{"use strict";i.r(t),i.d(t,{activeLinkingGroupWV:()=>Di,allInitialModelsCreated:()=>pi,allInitialSymbolsResolved:()=>_i,allLinkingGroupsWV:()=>Bi,applyIndicatorToAllChartsImpl:()=>yt,applyIndicatorsToAllChartsImpl:()=>bt,applyLineToolUpdateNotificationImpl:()=>At,applyThemeImpl:()=>Si,chartsSymbolsImpl:()=>Dt,checkProFeatureImpl:()=>mi,combinedTrackTimeLock:()=>Fi,computeContentBoxImpl:()=>Gt,copyScreenshotToClipboard:()=>Wt,createBroadcastChannel:()=>hi,createChartStorageSubscriptionsIfRequired:()=>Nt,createChartWidgetCollectionNewsNotifier:()=>Bt,createClipboardHandler:()=>kt,createLeftBottomChartWidgetWV:()=>Ht,deserializedChartIds:()=>xt,destroyBroadcastChannel:()=>di,downloadScreenshot:()=>Vt,generateNewChartId:()=>Xt,getAllLinkingGroups:()=>Ni,getAsyncStateForChartImpl:()=>Tt,getChartWidgetsForIntervalLock:()=>Li,getClientSnapshot:()=>Ut,getLinkingGroupCharts:()=>Ri,getSnapshot:()=>zt,getStateForChartImpl:()=>Pt,getVisuallyAdjacentDefImpl:()=>Zt,handleConnectionLimitReachedChanged:()=>Vi,handleDateRangeLockChange:()=>wi,handleInternalDateRangeLockChange:()=>Ci,handleInternalIntervalLockChange:()=>bi,handleInternalSymbolLockChange:()=>vi,handleInternalTrackTimeLockChange:()=>Pi,handleIntervalLockChange:()=>yi,handleSymbolLockChange:()=>fi,handleTrackTimeLockChange:()=>Ti,hideChartImpl:()=>ii,isFirstChartInLayout:()=>Mt,lineToolsAndGroupsDTOsImpl:()=>wt,removeChartWidgetSubscriptionsImpl:()=>si,resetLineToolsInvalidatedImpl:()=>It,setBrokerImpl:()=>Et,setChartLayoutWithUndoImpl:()=>gi,setChartStyleToWidget:()=>Ii,setLayoutImpl:()=>ai,setResolution:()=>ki,setSymbol:()=>Mi,setSymbolAll:()=>xi,someOfWidgetsAreInSelectingReplayPointMode:()=>Wi,subscribeToCompletedEventForDateRangeUpdate:()=>Hi,subscribeToEventsForDateRangeSync:()=>qi,syncChartsDateRangesWithActiveChartRange:()=>Ki,syncCrosshairImpl:()=>ci,syncScrollImpl:()=>ui,takeScreenshot:()=>Rt,takeServerScreenshot:()=>Ot,unsubscribeFromEventsForDateRangeSync:()=>ji,updateLayoutImpl:()=>Kt,updateLayoutPartialImpl:()=>Yt,updateLinkingGroupCharts:()=>Oi});var s=i(650151),o=i(86441),r=i(201089),n=i(444372),a=i(912445),l=i(638456),c=i(809796),h=i(244842);function d(e){const t={};return{promise:new Promise(((i,s)=>{e.subscribe(t,i,!0)})),destroy:()=>{e.unsubscribeAll(t)}}}var u=i(401580),_=i(270294),p=i(142257);class m extends p.UndoCommand{constructor(e,t){super(null),this._chartModel=e,this._targetIndex=t}redo(){const e=this._chartModel.createPane(this._targetIndex,void 0,this._paneId);this._paneId=e.id()}undo(){const e=(0,s.ensureDefined)(this._paneId),t=this._chartModel.panes().find((t=>t.id()===e));void 0!==t&&this._chartModel.removePane(t)}createdPaneId(){return this._paneId}}class g extends p.UndoCommand{constructor(e,t,i,s){super(s), this._setter=e,this._oldValue=t,this._newValue=i}redo(){this._setter(this._newValue)}undo(){this._setter(this._oldValue)}}class S extends g{constructor(e,t,i,s){super((e=>this._vwState.setValue(e)),t,i,s),this._vwState=e}}var v=i(919476),f=i(963239),b=i(793993);const y=(0,r.getLogger)("Clipboard");class C{constructor(e){this._e=e}write(e){return(0,f.writeImpl)(this._toRaw(e),this._e)}_toRaw(e){const t={files:[]};t.text=e.text,void 0!==e.app?t.html=this._serializeAppData(e.app,e.text):e.html&&(t.html=e.html);for(const i of e.files||[])t.files.push(i);return t}_serializeAppData(e,t){return`${t?(0,v.htmlEscape)(t.slice(0,256)):"📈"}`}}class w{constructor(e){this._e=e}async read(){this._e&&0===this._e.eventPhase&&(y.logWarn("Cannot use an already dispatched ClipboardEvent for reading"),this._e=null);const e=this._e?this._readUsingEvent(this._e):await this._readUsingApi();return this._fromRaw(e)}_readUsingEvent(e){const t=(0,s.ensure)(e.clipboardData);e.preventDefault();const i={files:[]};for(let e=0;e0&&(t.files=e.files),t}_parseAppData(e){if(-1===e.slice(0,1024).indexOf("data-tradingview-clip"))return;const t=(new DOMParser).parseFromString(e,"text/html").querySelector("[data-tradingview-clip]");return t?t.getAttribute("data-tradingview-clip")||"":void 0}_readBlobAsText(e){return new Promise(((t,i)=>{const s=new FileReader;s.onloadend=()=>{t(s.result)},s.onerror=()=>{i(s.error)},s.readAsText(e)}))}}var P=i(515312);function T(e){const t=e.target;return null!==t&&1===t.nodeType&&(0,P.isTextEditingField)(t)}function M(e){const t=e.target;if(null===t)return!1;const i=(t.ownerDocument||t).getSelection();return null!==i&&!i.isCollapsed}class x extends class{constructor(e){this._callbacks=Object.assign({},e),this._boundOnCopy=this._onCopyEv.bind(this),this._boundOnCut=this._onCutEv.bind(this),this._boundOnPaste=this._onPasteEv.bind(this)}listen(){document.addEventListener("copy",this._boundOnCopy),document.addEventListener("cut",this._boundOnCut),document.addEventListener("paste",this._boundOnPaste)}async peek(){if("granted"!==(await navigator.permissions.query({name:"clipboard-read" })).state)throw new Error("clipboard-read is not granted");return new w(null).read()}uiRequestCopy(e){this._callbacks.copyRequested&&this._callbacks.copyRequested(new C(null),e)}uiRequestCut(e){this._callbacks.cutRequested&&this._callbacks.cutRequested(new C(null),e)}uiRequestPaste(e){this._callbacks.pasteRequested&&this._callbacks.pasteRequested(new w(null),e)}destroy(){document.removeEventListener("copy",this._boundOnCopy),document.removeEventListener("cut",this._boundOnCut),document.removeEventListener("paste",this._boundOnPaste)}_onCopyEv(e){e.defaultPrevented||this._callbacks.copyRequested&&this._callbacks.copyRequested(new C(e))}_onCutEv(e){e.defaultPrevented||this._callbacks.cutRequested&&this._callbacks.cutRequested(new C(e))}_onPasteEv(e){e.defaultPrevented||this._callbacks.pasteRequested&&this._callbacks.pasteRequested(new w(e))}}{_onCopyEv(e){if(!T(e)&&!M(e))return super._onCopyEv(e)}_onCutEv(e){if(!T(e)&&!M(e))return super._onCutEv(e)}_onPasteEv(e){if(!T(e))return super._onPasteEv(e)}}const I=()=>i.e(54389).then(i.bind(i,425471));function A(e,t={}){return I().then((i=>i.copyToClipboardImageOfChart(e,t)))}function L(e,t={}){return I().then((i=>i.getImageOfChartSilently(e,t)))}var k=i(470316),E=i(410864),D=i(588948),N=i(572230);const B=(0,r.getLogger)("TimingsMeter.Service"),R=(0,r.getLogger)("TimingsMeter.Stats",{maxCount:160});function O(){return{[N.InvalidationLevel.None]:{count:0,lastTime:0,maxTime:0,totalTime:0},[N.InvalidationLevel.Cursor]:{count:0,lastTime:0,maxTime:0,totalTime:0},[N.InvalidationLevel.Light]:{count:0,lastTime:0,maxTime:0,totalTime:0},[N.InvalidationLevel.Full]:{count:0,lastTime:0,maxTime:0,totalTime:0}}}function V(e,t){e.lastTime=t,e.totalTime+=t,++e.count,t>e.maxTime&&(e.maxTime=t)}function W(e){return e.toFixed(2)}function F(e){const t=e.count;if(0===t)return"no events";const i=e.totalTime/t,s=W(e.maxTime);return`count=${t}, last=${W(e.lastTime)}, max=${s}, avg=${W(i)}`}class H{constructor(e){this._waitDrawStartTime=-1,this._startDrawTime=-1,this._currentDrawLevel=N.InvalidationLevel.Full,this._currentDrawItems=O(),this._currentWaitingItem={count:0,lastTime:0,maxTime:0,totalTime:0},this._dumpTimingsStatsInterval=0,this._logPrefix=`[${e}]`}destroy(){this.stopCollect()}startCollect(){0!==this._dumpTimingsStatsInterval&&(B.logWarn(`${this._logPrefix} Multiple start detected`),this.stopCollect()),this._clearCurrentState(),this._dumpTimingsStatsInterval=setInterval(this._dumpTimingsStats.bind(this),15e3),B.logNormal(`${this._logPrefix} Collecting started`)}stopCollect(){0!==this._dumpTimingsStatsInterval&&(clearInterval(this._dumpTimingsStatsInterval),this._dumpTimingsStatsInterval=0,B.logNormal(`${this._logPrefix} Collecting stopped. Dumping last state...`),this._dumpTimingsStats())}startWaitingDraw(){this._waitDrawStartTime=window.performance.now()}startDraw(e){this._startDrawTime=window.performance.now(),this._currentDrawLevel=e}stopDraw(){const e=window.performance.now();if(-1===this._startDrawTime||-1===this._waitDrawStartTime)return ;const t=this._startDrawTime-this._waitDrawStartTime;V(this._currentWaitingItem,t),this._waitDrawStartTime=-1;const i=e-this._startDrawTime;V(this._currentDrawItems[this._currentDrawLevel],i),this._startDrawTime=-1}_dumpTimingsStats(){const e=[this._logPrefix," awaiting:",F(this._currentWaitingItem),"; cursor:",F(this._currentDrawItems[N.InvalidationLevel.Cursor]),"; light:",F(this._currentDrawItems[N.InvalidationLevel.Light]),"; full:",F(this._currentDrawItems[N.InvalidationLevel.Full])].join("");R.logNormal(e),this._clearCurrentState()}_clearCurrentState(){this._currentDrawItems=O(),this._currentWaitingItem={count:0,lastTime:0,maxTime:0,totalTime:0}}}var z=i(922850),U=i(616117);function G(e){return{...e,panes:(t=e.panes,t.map((e=>{return{...e,sources:(t=e.sources,t.filter((e=>!(0,U.isLineToolName)(e.type))))};var t})))};var t}function q(e,t){var i;const s=e.find((e=>e.tools.includes(t)));return null!==(i=null==s?void 0:s.id)&&void 0!==i?i:null}function j(e){var t,i;const o=e.panes.map((e=>e.sources.filter((e=>(0,U.isLineToolName)(e.type))))).reduce(((e,t)=>t.concat(e)),[]),r=null!==(i=null===(t=e.lineToolsGroups)||void 0===t?void 0:t.groups)&&void 0!==i?i:[],n=new Map;o.forEach((e=>{const t=e.id;n.set(t,function(e,t){var i;return{id:e.id,symbol:e.state.symbol,ownerSource:(0,s.ensureDefined)(e.ownerSource),state:e,groupId:null!==(i=q(t,e.id))&&void 0!==i?i:void 0}}(e,r))}));const a=new Map;return r.forEach((e=>{const t=function(e,t){var i,s;if(0===e.tools.length)return null;const o=e.tools[0];return null!==(s=null===(i=t.get(o))||void 0===i?void 0:i.symbol)&&void 0!==s?s:null}(e,n);null!==t&&a.set(e.id,{id:e.id,name:e.name,symbol:t})})),{sources:n,groups:a}}var Y=i(531005),K=i(405117),Z=i(778016),$=i(833813),X=i(960337),J=i(371927),Q=i(154765),ee=i(1500),te=i(500521),ie=i(175203),se=i(314802),oe=i(125226),re=i(368654),ne=i(652171),ae=i(474759),le=i(944454),ce=i(266325),he=i(930003);const de=new class{constructor(){this._timerWorker=null,this._timerIdCounter=1,this._timersMap=new Map,this._rejectsToCall=new Set,this._processMessage=e=>{const t=this._timersMap.get(e.data.turnaround);switch(e.data.type){case"timerCreated":t&&(t.scheduledForRemoving?("interval"===t.type?this._getTimerWorker().postMessage({type:"clearInterval",id:e.data.id}):this._getTimerWorker().postMessage({type:"clearTimeout",id:e.data.id}),this._deleteTimerFromMap(e.data.turnaround)):t.workerTimerId=e.data.id);break;case"timerFired":t&&(t.callback(),"timeout"===t.type&&this._deleteTimerFromMap(e.data.turnaround))}}}destroy(){var e;this._rejectsToCall.forEach((e=>e((0,ce.createAbortError)()))),null===(e=this._timerWorker)||void 0===e||e.terminate(),this._timerWorker=null,this._timersMap.clear()}setTimeout(e,t){return this._setTimeoutImpl(e,t,"timeout")}clearTimeout(e){const t=this._timersMap.get(e);t&&(t.workerTimerId?(this._getTimerWorker().postMessage({type:"clearTimeout",id:t.workerTimerId}),this._deleteTimerFromMap(e)):t.scheduledForRemoving=!0)}setInterval(e,t){const i=this._nextTimerId();return this._timersMap.set(i,{callback:e,type:"interval" }),this._getTimerWorker().postMessage({type:"setInterval",delay:t,turnaround:i}),i}clearInterval(e){const t=this._timersMap.get(e);t&&(t.workerTimerId?(this._getTimerWorker().postMessage({type:"clearInterval",id:t.workerTimerId}),this._deleteTimerFromMap(e)):t.scheduledForRemoving=!0)}async createTimeout(e,t){let i;return new Promise(((s,o)=>{var r;i=o,this._rejectsToCall.add(i);const n=this.setTimeout(s,e);null===(r=null==t?void 0:t.signal)||void 0===r||r.addEventListener("abort",(()=>{this.clearTimeout(n),o((0,ce.createAbortError)())}))})).finally((()=>{this._rejectsToCall.delete(i)}))}async*createInterval(e,t){let i=()=>{},s=e=>{};const o=this.setInterval((()=>{i()}),e);t.signal.addEventListener("abort",(()=>{this.clearInterval(o),s((0,ce.createAbortError)())}));try{for(;;)await new Promise(((e,t)=>{i=e,this._rejectsToCall.delete(s),s=t,this._rejectsToCall.add(s)})),yield}catch(e){if(!(0,ce.isAbortError)(e))throw e}}_getTimerWorker(){return null===this._timerWorker&&(this._timerWorker=new he.Worker(new URL(i.p+i.u(77050),i.b),{name:"Timer worker"}),this._timerWorker.onmessage=this._processMessage),this._timerWorker}_setTimeoutImpl(e,t,i){const s=this._nextTimerId();return this._timersMap.set(s,{callback:e,type:i}),this._getTimerWorker().postMessage({type:"setTimeout",delay:t,turnaround:s}),s}_deleteTimerFromMap(e){if(this._timersMap.delete(e),0===this._timersMap.size){const e=this._setTimeoutImpl((()=>{var t;1===this._timersMap.size&&this._timersMap.has(e)&&(this._timersMap.delete(e),null===(t=this._timerWorker)||void 0===t||t.terminate(),this._timerWorker=null)}),6e4,"terminal_timer")}}_nextTimerId(){return this._timerIdCounter++}};var ue=i(707957);const _e=new Set(["chart_storage_hibernation_delay_60min","chart_storage_hibernation_delay_10min","chart_storage_hibernation_delay_5min"]);const pe=new u.WatchedValue(me());function me(){return(0,oe.isFeatureEnabled)("chart_storage_hibernation_delay_60min")?36e5:(0,oe.isFeatureEnabled)("chart_storage_hibernation_delay_10min")?6e5:(0,oe.isFeatureEnabled)("chart_storage_hibernation_delay_5min")?3e5:6e4}(0,oe.onFeaturesStateChanged)().subscribe(null,(e=>{if(!function(e){return _e.has(e)}(e))return;const t=me();pe.setValue(t,!1)}));const ge=pe.readonly();function Se(e){const t=document.querySelector('link[rel~="chart-storage-notifications"]');return(null==t?void 0:t.href)?e?new URL(e,t.href):new URL(t.href):null}function ve(e,t){return Boolean(e.metaInfo.uid.value())&&!t.containsData&&!t.onWidget&&function(){if(!(0,se.isOnMobileAppPage)("new"))return!0;const e=/TradingView\/(\d+)\.(\d+)\.(\d+)\.?/.exec(navigator.userAgent);if(null===e)return!0;const t=Number(e[1])-1,i=Number(e[2])-15,s=Number(e[3])-0;if(t>0||0===t&&i>0||0===t&&0===i&&s>0)return!0;return!1}()&&null!==Se()}const fe=(0,r.getLogger)("ChartStorageChangesSubscription");class be extends re.PersistentEventSourceTransport{constructor(e,t){super((e=>this._onMessage(e))),this._destroyed=!1,this._onChangeVisibilityBound=this._onChangeVisibility.bind(this),this._hibernateTimerId=null,this._hibernateDelay=ge.spawn(), this._beforeUnhibernating=new ue.Delegate,this._haveEverBeenHibernated=!1,this._chartWidgetsCollection=e,this._layoutVisibility=e.resizerBridge().visible.spawn(),this._layoutVisibility.subscribe(this._onChangeVisibilityBound,{callWithLast:!0}),ie.telemetry.sendLineToolsStorageReport("line_tools_subscription_initial_connect"),this._connectionStatus.subscribe((e=>{e===le.ConnectionStatus.Closed&&ie.telemetry.sendLineToolsStorageReport("line_tools_subscription_disconnected")})),this._subscribeForSharingLayout=t,this.connect(),this._hibernateDelay.subscribe((e=>{null!==this._hibernateTimerId&&this._scheduleHibernation(e)}))}destroy(){this._layoutVisibility.destroy(),this._hibernateDelay.destroy(),this.disconnect(),this._destroyed=!0}beforeUnhibernating(){return this._beforeUnhibernating}async _prepareParamsForConnection(e){const t=this._chartWidgetsCollection.metaInfo.uid.value();if(this._destroyed)return Promise.reject("Subscription is being destroyed");const i=await(0,ne.getStorageTarget)(t,"",0),s=Se(`/charts-storage/layout/${t}/subscribe`);null!==s?(s.searchParams.delete("jwt"),s.searchParams.append("jwt",i.token),this._subscribeForSharingLayout&&window.user.id&&window.user.is_pro&&s.searchParams.append("id",""+window.user.id),this._url=s.toString()):this._url=""}_tryReconnectImpl(){super._tryReconnectImpl(),ie.telemetry.sendLineToolsStorageReport("line_tools_subscription_reconnecting")}_onMessage(e){if("string"!=typeof e)throw new Error("Wrong message type, expected string");const t=JSON.parse(e);Object.entries(t).forEach((e=>{const t=(0,ae.parseLineToolsAndGroupsDTO)(e[1],""),i=e[0];let s=0;i===ne.sharedChartId?s=1:i===ne.globallySharedChartId&&(s=2),this._chartWidgetsCollection.applyLineToolUpdateNotification(i,t,s)}))}_onChangeVisibility(){const e=this._layoutVisibility.value();e&&this.connectionStatus().value()===le.ConnectionStatus.Closed?(this.connect(),this._beforeUnhibernating.fire(),this._haveEverBeenHibernated&&(fe.logNormal("Connect due to becoming visible"),ie.telemetry.sendLineToolsStorageReport("line_tools_unhibenate_subscription"))):e||this._scheduleHibernation(ge.value())}_scheduleHibernation(e){null!==this._hibernateTimerId&&de.clearTimeout(this._hibernateTimerId),this._hibernateTimerId=de.setTimeout((()=>this._disconnectIfInvisible()),e)}_disconnectIfInvisible(){this._hibernateTimerId=null,!this._layoutVisibility.value()&&(0,oe.isFeatureEnabled)("hibernate_line_tool_notifications")&&(fe.logNormal("Disconnect due to becoming invisible"),this.disconnect(),ie.telemetry.sendLineToolsStorageReport("line_tools_hibenate_subscription"),this._haveEverBeenHibernated=!0)}}var ye=i(850775),Ce=i(743354),we=i(988124),Pe=i(444331),Te=i(429874),Me=i(228018),xe=i(674981),Ie=i(541558),Ae=i(533422),Le=i(251954),ke=i(581996),Ee=i(300426),De=i(208044),Ne=i(103221),Be=i(431912),Re=i(237872);const Oe=new c.TranslatedString("change chart layout to {title}",n.t(null,void 0,i(130501)));class Ve extends p.UndoCommand{constructor(e,t){super(Oe.format({title:Ae.layouts[t].title})),this._chartWidgetCollection=e, this._newLayoutType=t,this._oldLayoutType=e.layout.value()}redo(){this._chartWidgetCollection.setLayout(this._newLayoutType)}undo(){this._chartWidgetCollection.setLayout(this._oldLayoutType)}}var We=i(389137),Fe=i(331633);const He=new c.TranslatedString("apply toolbars theme",n.t(null,void 0,i(558570)));class ze extends p.UndoCommand{constructor(e,t,i=!0){super(He),this._prevThemeName=e,this._themeName=t,this._syncState=i}undo(){(0,Te.isStdThemeName)(this._prevThemeName)&&((0,Fe.setTheme)(this._prevThemeName),this._syncState&&(0,Te.syncTheme)())}redo(){(0,Te.isStdThemeName)(this._themeName.toLowerCase())&&((0,Fe.setTheme)(this._themeName.toLowerCase()),this._syncState&&(0,Te.syncTheme)())}}var Ue=i(66732),Ge=i(784547),qe=i(885482),je=i(938550),Ye=i(223699),Ke=i(779923),Ze=i(731042),$e=i(866319),Xe=i(581501);i(877825);const Je=!l.CheckMobile.any(),Qe=(0,r.getLogger)("ChartWidgetCollectionBase"),et=new c.TranslatedString("apply indicators to entire layout",n.t(null,void 0,i(744547))),tt=new c.TranslatedString("sync time",n.t(null,void 0,i(260635))),it=new c.TranslatedString("resize layout",n.t(null,void 0,i(113034))),st=new c.TranslatedString("reset layout sizes",n.t(null,void 0,i(830910))),ot=new c.TranslatedString("apply chart theme",n.t(null,void 0,i(766568))),rt=new c.TranslatedString("symbol lock",n.t(null,void 0,i(292831))),nt=new c.TranslatedString("interval lock",n.t(null,void 0,i(128916))),at=new c.TranslatedString("date range lock",n.t(null,void 0,i(390621))),lt=new c.TranslatedString("track time",n.t(null,void 0,i(247122))),ct=new c.TranslatedString("change series style",n.t(null,void 0,i(53438))),ht=n.t(null,void 0,i(46669)),dt=n.t(null,void 0,i(398478)),ut=n.t(null,void 0,i(834004)),_t=n.t(null,void 0,i(796260)),pt=n.t(null,void 0,i(838641)),mt=n.t(null,void 0,i(110160)),gt=n.t(null,void 0,i(219149)),St=n.t(null,void 0,i(838660)),vt=n.t(null,void 0,i(947228)),ft=n.t(null,void 0,i(219149));function bt(e,t){const i=t.model().model().studyTemplate();e.undoHistory.beginUndoMacro(et);for(let s=0;se.id()===r)))}const l=await t.pasteSourceFromClip(n,i,!0);if(l&&1===l.length){const e=l[0];if(o.asCompare){const i=(0,s.ensureNotNull)(t.mainSeries().priceScale());t.moveToScale(e,(0,s.ensureDefined)(n),i,r),t.setPriceScaleMode({percentage:!0},i,null)}}t.model().lightUpdate()}}e.undoHistory.endUndoMacro()}function Ct(e){let t=1;for(;e.has(""+t);)t++;return""+t}function wt(e){ const t=new Map,i=e.chartsCountToSave(),s=new Set;for(let o=0;o(0,s.ensureDefined)(e.content.chartId)))}function It(e,t,i){const s=e.chartsCountToSave();i.forEach((i=>{const s=(o=i.chartId,null!==(n=null===(r=e.chartWidgetsDefs.find((e=>e.chartWidget.id()===o)))||void 0===r?void 0:r.chartWidget)&&void 0!==n?n:null);var o,r,n;null==s||s.resetLineToolsInvalidated(t,i.savedDto,i.sharingMode)}));for(let t=e.chartWidgetsDefs.length;te.chartWidget)).filter((e=>e.hasModel())).filter((e=>e.id()===t||0!==s));try{o.forEach((e=>e.startApplyingLineToolUpdateNotification())),o.forEach((e=>e.applyLineToolUpdateNotification(i,s)))}finally{o.forEach((e=>e.endApplyingLineToolUpdateNotification()))}}function Lt(e){return e instanceof Error?e.message:null}function kt(e){return new x({copyRequested:(t,i)=>{e.activeChartWidget.value().model().clipboardCopy(t,i).catch((t=>{var i;null===(i=e.toastsFactory)||void 0===i||i.getChartToasts().then((e=>{var i;(0,s.ensureNotNull)(e).showSimpleToast({title:dt,text:null!==(i=Lt(t))&&void 0!==i?i:ht.format({keystroke:(0,k.humanReadableHash)(k.Modifiers.Mod+67)}),role:"alert",intent:E.ToastIntent.Warning})}))}))},cutRequested:(t,i)=>{e.activeChartWidget.value().model().clipboardCut(t,i).catch((t=>{var i;null===(i=e.toastsFactory)||void 0===i||i.getChartToasts().then((e=>{var i;(0,s.ensureNotNull)(e).showSimpleToast({title:ut,text:null!==(i=Lt(t))&&void 0!==i?i:ht.format({keystroke:(0,k.humanReadableHash)(k.Modifiers.Mod+88)}),role:"alert",intent:E.ToastIntent.Warning})}))}))},pasteRequested:(t,i)=>{(i?i.model().undoModel():e.activeChartWidget.value().model()).clipboardPaste(t,i).catch((t=>{var i;null===(i=e.toastsFactory)||void 0===i||i.getChartToasts().then((e=>{var i;(0,s.ensureNotNull)(e).showSimpleToast({title:_t,text:null!==(i=Lt(t))&&void 0!==i?i:ht.format({keystroke:(0,k.humanReadableHash)(k.Modifiers.Mod+86)}),role:"alert",intent:E.ToastIntent.Warning})}))}))}})}function Et(e,t){(0,Y.setBroker)(t)}function Dt(e){const t={} ;return e.chartWidgetsDefs.map((e=>e.chartWidget)).forEach((e=>t[e.id()]=function(e){var t,i,o,r,n;const a={};if(!e.hasModel()){const r=e.options().content;if(!r)return a;const n=(0,s.ensureNotNull)(r.panes.reduce(((e,t)=>{var i;return null!==(i=null!=e?e:t.sources.find((e=>"MainSeries"===e.type)))&&void 0!==i?i:null}),null));return a.resolution=null===(t=n.state)||void 0===t?void 0:t.interval,a.symbol=null===(i=n.state)||void 0===i?void 0:i.symbol,a.short_name=null===(o=n.state)||void 0===o?void 0:o.shortName,a}const l=e.model().mainSeries(),c=l.properties().childs(),h=l.symbolInfo();a.resolution=c.interval.value(),a.symbol_type=null!==h&&h.type||"",a.exchange=null!==h&&h.exchange||"",a.listed_exchange=null!==h&&h.listed_exchange||"";const d=null!==(r=null==h?void 0:h.legs)&&void 0!==r?r:[];if(null!==h&&l.isSpread()){const e=d[0];let t=h.base_name[0];t=t.split(":")[1],a.symbol=e,a.short_name=t,a.expression=h.full_name}else a.symbol=null!==h&&h.ticker||c.symbol.value(),a.short_name=c.shortName.value();const u=null!==(n=null==h?void 0:h.base_name)&&void 0!==n?n:[];return a.legs=d.map(((e,t)=>({symbol:e,pro_symbol:u[t]}))),a}(e))),t}function Nt(e,t){if(ve(e,t.widgetOptions)){const i=new be(e,!e.readOnly());i.beforeUnhibernating().subscribe(e,(()=>{!function(e){e.chartWidgetsDefs.map((e=>e.chartWidget)).forEach((e=>e.reloadAllLineTools()))}(t)})),t.setChartStorageNotificationSubscription(i)}}async function Bt(e,t){if(t.widgetOptions.newsNotificationsEnabled){return new((await Promise.all([i.e(32109),i.e(4015),i.e(88548),i.e(56400),i.e(58666),i.e(54234),i.e(80345),i.e(96821),i.e(80926),i.e(66446),i.e(56370)]).then(i.bind(i,300777))).ChartWidgetCollectionNewsNotifier)(e)}return null}function Rt(e,t){const i={snapshotUrl:e};return i.asyncSave=!window.TVD,L(t,i).then((e=>((0,Le.emit)("onScreenshotReady",e),e)))}function Ot(e,t){const i={snapshotUrl:e};i.asyncSave=!window.TVD;const s=(0,se.isOnMobileAppPage)("any");return(s?L:A)(t,i).then((e=>((0,Le.emit)("onScreenshotReady",e),s||(0,Le.emit)("onServerScreenshotCopiedToClipboard"),e)))}function Vt(e){return function(e){return I().then((t=>t.downloadClientScreenshot(e)))}(e)}function Wt(e){return function(e){return I().then((t=>t.copyToClipboardClientScreenshot(e)))}(e).then((()=>{(0,Le.emit)("onClientScreenshotCopiedToClipboard")}))}const Ft={s:0,"2h":0,"2v":1,"2-1":1,"3s":0,"3h":0,"3v":2,4:1,6:1,8:1,"1-2":1,"3r":1,"4h":0,"4v":3,"4s":0,"5h":0,"6h":0,"7h":0,"8h":0,"1-3":1,"2-2":3,"2-3":2,"1-4":1,"5s":0,"6c":4,"8c":6,"10c5":1,"12c6":1,"12c4":3,"14c7":1,"16c8":1,"16c4":3};function Ht(e,t,i,s){let o=0;const r=(0,Ge.createWVFromGetterAndSubscriptions)((()=>++o),[i,s]);return(0,Ue.combine)((t=>{var i;return null!==(i=e()[Ft[t]])&&void 0!==i?i:null}),t.weakReference(),r.ownership())}function zt(e,t,i,s){const o=Math.max(1,window.devicePixelRatio||1),r=e.getAll();let n;{const s=t||"TradingView.com";let o=e.activeChartWidget.value().properties().childs().timezone.value();if("exchange"===o){const t=e.activeChartWidget.value().model().mainSeries().symbolInfo();o=t?t.timezone:o} const r={timezone:o,dateFormat:"MMM dd, yyyy"},a=new Ce.DateTimeWithTzFormatter(r).format(window.ChartApiInstance.serverTime()/1e3),l=e.metaInfo.username.value(),c=!l||e.readOnly()||i?mt:pt,h=[c.split(/{date}/)[0].format({userName:l,customer:s}).trim(),a],d=[c.format({userName:l,customer:s,date:a}).trim()];n="phone-vertical"===ye.mediaState.device?h:d}const a=e.maximizedChartWidget().value();if(s&&s.onlyActiveChart||a)return{layout:"s",hidpiRatio:o,theme:(0,Te.getCurrentTheme)().name,charts:[e.activeChartWidget.value().images(s)],publishedBy:n};const l=[],c=Ae.layouts[e.layout.value()].count,h={showCollapsedStudies:(s=s||{}).showCollapsedStudies,status:s.status};for(let e=0;e{const t=this._state.currentLayoutResizeAction.value();t&&this._applyMouseMove(t.delta,e)},this._state=e,this._splitterElement=t,this._splitter=i,(0,Re.shiftPressed)().subscribe(this._onShiftPressed)}destroy(){(0,Re.shiftPressed)().unsubscribe(this._onShiftPressed)}mouseDownEvent(e){this._mouseDownOrTouchStartEvent(e)}touchStartEvent(e){this._mouseDownOrTouchStartEvent(e)}pressedMouseMoveEvent(e){this._pressedMouseOrTouchMoveEvent(e)}touchMoveEvent(e){this._pressedMouseOrTouchMoveEvent(e)}mouseUpEvent(e){this._mouseUpOrTouchEndEvent(e)}touchEndEvent(e){this._mouseUpOrTouchEndEvent(e)}mouseEnterEvent(e){this._highlightSplitters(e.shiftKey)}mouseLeaveEvent(e){const t=qt(this._splitter.className);Array.from(this._state.parent.getElementsByClassName(t)).forEach((e=>e.classList.remove(Xe.hovered)))}mouseDoubleClickEvent(e){const t=(0,De.layoutInitialSizingState)(this._state.layoutTemplate.value().expression);this._state.undoHistory.beginUndoMacro(st),this._state.undoHistory.pushUndoCommand(new S(this._state.sizingState,this._state.sizingState.value(),t,st));const i=this._state.layoutTemplate.value().layoutType;this._state.undoHistory.pushUndoCommand(new g((e=>e?this._state.allLayoutSizesState.set(i,e):this._state.allLayoutSizesState.delete(i)),this._state.allLayoutSizesState.get(this._state.layoutTemplate.value().layoutType),t,st)),this._state.undoHistory.endUndoMacro()}_highlightSplitters(e){const t=qt(this._splitter.className) ;Array.from(this._state.parent.getElementsByClassName(t)).forEach((e=>e.classList.remove(Xe.hovered)));(e?Array.from(this._state.parent.getElementsByClassName(t)):[this._splitterElement]).forEach((e=>e.classList.add(Xe.hovered)))}_mouseDownOrTouchStartEvent(e){const t=new o.Point(e.localX+this._splitterElement.offsetLeft,e.localY+this._splitterElement.offsetTop),i=(0,Ne.deepCopy)(this._state.sizingState.value());this._state.currentLayoutResizeAction.setValue({point:t,splitter:this._splitter,initialState:i,alignedState:this._state.layoutTemplate.value().syncSublayoutsBySplitter(this._splitter,(0,Ne.deepCopy)(i)),shiftState:e.shiftKey,delta:0}),this._splitterElement.classList.add(Xe["i-active"]),this._highlightSplitters(e.shiftKey)}_pressedMouseOrTouchMoveEvent(e){const t=this._state.currentLayoutResizeAction.value();if(!t)return;t.shiftState!==e.shiftKey&&(this._highlightSplitters(e.shiftKey),t.shiftState=e.shiftKey);const i=new o.Point(e.localX+this._splitterElement.offsetLeft,e.localY+this._splitterElement.offsetTop);t.delta="v"===t.splitter.orientation?i.y-t.point.y:i.x-t.point.x,this._applyMouseMove(t.delta,e.shiftKey)}_mouseUpOrTouchEndEvent(e){const t=this._state.currentLayoutResizeAction.value();if(t&&(this._splitterElement.classList.remove(Xe["i-active"]),this._state.currentLayoutResizeAction.setValue(null),t.currentState)){this._state.undoHistory.beginUndoMacro(it),this._state.undoHistory.pushUndoCommand(new S(this._state.sizingState,t.initialState,t.currentState,it));const e=this._state.layoutTemplate.value().layoutType;this._state.undoHistory.pushUndoCommand(new g((t=>t?this._state.allLayoutSizesState.set(e,t):this._state.allLayoutSizesState.delete(e)),this._state.allLayoutSizesState.get(this._state.layoutTemplate.value().layoutType),this._state.sizingState.value(),st)),this._state.undoHistory.endUndoMacro(),this._state.layoutSizesChanged.setValue(!0)}}_applyMouseMove(e,t){var i;const o=(0,s.ensureNotNull)(this._state.currentLayoutResizeAction.value()),r=t?o.alignedState:o.initialState,n=null!==(i=this._state.options.padding)&&void 0!==i?i:2,a=Gt(this._state);o.currentState=this._state.layoutTemplate.value().resizeApplier(a,n,e,o.splitter,(0,Ne.deepCopy)(r),t),this._state.sizingState.setValue(o.currentState)}}function Yt(e,t,i,s,o){var r,n;const a=null!==(r=e.options.padding)&&void 0!==r?r:2,l=null!==(n=e.options.border)&&void 0!==n?n:0;o=null!=o?o:e.layoutTemplate.value();const c=Gt(e),h=o.sizer(c,i,s,a+l,Je?e.sizingState.value():void 0);h.width=Math.max(Math.round(h.width),0),h.height=Math.max(Math.round(h.height),0),h.top=Math.round(h.top),h.left=Math.round(h.left),t.metrics=h;const d=t.container.value();if(d){d.style.width=h.width+"px",d.style.height=h.height+"px",d.style.top=h.top+"px",d.style.left=h.left+"px";const e=1===s;d.classList.toggle("single-visible",e);const t=Math.round(c.width),i=0===h.top&&0===h.left,o=0===h.top&&h.left+h.width===t,r=0===h.top&&h.width===t;d.classList.toggle("top-left-chart",!e&&!r&&i),d.classList.toggle("top-right-chart",!e&&!r&&o), d.classList.toggle("top-full-width-chart",e||r)}t.width.setValue(h.width),t.height.setValue(h.height)}function Kt(e){var t,i,s;let o;const r=e.layoutTemplate.value(),n=e.maximizedChartDef.value();if(o=n?[n]:e.chartWidgetsDefs.slice(0,r.count).filter((e=>!e.hiddenInLayout.value())),o.forEach(((t,i)=>Yt(e,t,i,o.length))),Je&&!e.maximizedChartDef.value()){const o=Gt(e),n=null!==(t=e.options.padding)&&void 0!==t?t:2,a=null!==(i=e.options.border)&&void 0!==i?i:0,l=r.splitters(o,n+a,e.sizingState.value()),c=null!==(s=e.splitters.value())&&void 0!==s?s:[];c.forEach(((e,t)=>{t>=l.length&&(e.splitterElement.remove(),e.mouseHandler.destroy(),e.mouseListener.destroy())}));const h=l.map(((t,i)=>{const s=i({def:t,metrics:e.layoutTemplate.value().sizer({top:0,left:0,width:256,height:256},i,s.length,0)}))).sort(((e,t)=>e.metrics.top-t.metrics.top||e.metrics.left-t.metrics.left)).map((e=>e.def));if(s.length<2)return null;let o=s.indexOf(t);return-1===o?null:(o=(o+(i?s.length-1:1))%s.length,s[o])}function $t(e,t){return e.chartWidgetsDefs.some((e=>{var i;return(null===(i=e.chartWidget)||void 0===i?void 0:i.id())===t}))}function Xt(e){let t=1;for(;e(""+t);)t++;return""+t}function Jt(e){const t=e.activeChartWidget.value();if(t){const i=t.state();return i.chartId=Xt((t=>$t(e,t))),i.shouldBeSavedEvenIfHidden=!1,i.panes.forEach((e=>{e.sources.forEach((e=>{"alertId"in e&&(e.alertId=void 0)}))})),{content:i}}}function Qt(e,t,i){const s=[];if(null==i?void 0:i.publishedChartsEnabled){const i=new z.PublishedChartsTimeline(e,(e=>function(e,t){e={...e,chartWidgetCollection:t},(0,te.pushChartPage)(e)}(e,t)));s.push(i)}return s}function ei(e,t,i){var o,r;const{toastsFactory:n,chartWidgetsDefs:a,customLegendWidgetsFactoriesMap:c}=e;let h={chartWidgetCollection:t,isActive:0===a.length,barsMarksContainersFactory:i=>Qt(i,t,e.options),undoHistory:e.undoHistory,readOnly:e.readOnly,initialLoading:e.initialLoading,getToasts:n?()=>n.getChartToasts():void 0,...null!=i?i:{}};void 0!==c&&(h.customLegendWidgetFactories=new Map(c));const d=document.createElement("div");d.classList.add("chart-container"),d.style.position="absolute",d.style.overflow="hidden",e.parent.appendChild(d), l.isEdge&&(d.style.touchAction="none",d.style.msTouchAction="none"),h.className&&d.classList.add(h.className);const _={alive:new u.WatchedValue(!0),container:new u.WatchedValue(d),width:new u.WatchedValue,height:new u.WatchedValue,collapsed:new u.WatchedValue(!1),hiddenInLayout:new u.WatchedValue(!1),visible:new u.WatchedValue,rdState:new ke.ResizerDetacherState,requestFullscreen:()=>{e.globalDetachable.value()&&(e.setMaximized(_),e.activeChartWidget.setValue((0,s.ensureNotNull)(_.chartWidget)))},exitFullscreen:()=>{e.activeChartWidget.value()===_.chartWidget&&e.setMaximized(null)},detachable:e.globalDetachable,fullscreenable:e.globalDetachable,fullscreen:new u.WatchedValue,chartWidget:null};_.rdState.pushOwner(_),a.push(_);const p=()=>{_.visible.setValue(!_.hiddenInLayout.value()&&e.options.resizerBridge.visible.value())};_.hiddenInLayout.subscribe((()=>{(0,s.ensureNotNull)(_.chartWidget).setVisible(!_.hiddenInLayout.value()),p()})),_.collapsed.subscribe((()=>(0,s.ensureNotNull)(_.chartWidget).setCollapsed(_.collapsed.value()))),e.options.resizerBridge.visible.subscribe(p),p(),function(e,t){let i=0,s=0;const o=t.layoutTemplate.value();for(let r=0;r$t(e,t))),g=_.chartWidget=new Ee.ChartWidget(h,m,t.metaInfo.uid.value());e.saveChartService&&g.setSaveChartService(e.saveChartService),e.readOnly||(_.timingsMeter=new H(String(a.length-1)),g.setTimingsMeter(_.timingsMeter)),h.containsData?g.finishInitWithoutConnect():g.connect(),g.withModel(null,(()=>{const t=g.model().model();e.customSources.forEach(((e,i)=>{t.addCustomSource(i,e.factory,e.layer)}))})),e.updateWatchedValue(),e.updateActivityView();const S=null!==(r=null===(o=null==h?void 0:h.content)||void 0===o?void 0:o.linkingGroup)&&void 0!==r?r:null;g.linkingGroupIndex().setValue(S),g.linkingGroupIndex().subscribe(e.updateLinkingGroupCharts);const v=Ri(e,S).value();return v.length>0&&(e.symbolLock.value()&&g.setSymbol(v[0].symbolWV().value()),e.intervalLock.value()&&g.setResolution(v[0].resolutionWV().value())),e.updateLinkingGroupCharts(),e.chartWidgetCreatedDelegate.fire(g),_}function ti(e,t,i,s){const o={...e.widgetOptions,...e.savedChartWidgetOptions.shift()||Jt(e),...0===i||e.symbolLock.value()?void 0:{defSymbol:null}},r=ei(e,t,o),{chartWidget:n}=r;return n.modelCreated().subscribe(null,(()=>{s?s():e.checkAllPendingModelsAlreadyCreated(),e.dateRangeLock.value()&&n===e.activeChartWidget.value()&&e.subscribeToCompletedEventForDateRangeSync(n,!0)}),!0),r}function ii(e){e.hiddenInLayout.setValue(!0);const t=e.container.value();t.parentNode&&t.parentNode.removeChild(t),e.fullscreen.setValue(!1)}function si(e,t){e.chartWidgetsDefs.forEach((i=>{const o=(0,s.ensureNotNull)(i.chartWidget);o.onZoom().unsubscribeAll(t),o.onScroll().unsubscribeAll(t),o.withModel(null,(()=>{const t=o.lineToolsSynchronizer();null!==t&&(t.hasChanges().unsubscribe(e.recalcHasChanges),e.recalcHasChanges())}))}))}function oi(e,t){ e.chartWidgetsDefs.forEach((i=>{const o=(0,s.ensureNotNull)(i.chartWidget);o.onZoom().subscribe(t,(t=>e.onZoom.fire(t))),o.onScroll().subscribe(t,(()=>e.onScroll.fire())),o.withModel(null,(()=>{const t=o.lineToolsSynchronizer();null!==t&&(t.hasChanges().subscribe(e.recalcHasChanges),e.recalcHasChanges())}))}))}const ri=["2-3","5h","6h","7h","8h"],ni=["10c5","12c6","12c4","14c7","16c8","16c4"];async function ai(e,t,i){var o,r;(0,D.getInitData)().is_mobile_new&&(ri.includes(t)&&!(0,h.enabled)("mobile_app_supports_new_layout_types")||ni.includes(t)&&!(0,h.enabled)("mobile_app_supports_new_layout_types_2"))&&(t="s");try{const t=e.chartWidgetsDefs.map((e=>{var t,i,s;return null!==(s=null===(i=null===(t=e.chartWidget)||void 0===t?void 0:t.lineToolsSynchronizer())||void 0===i?void 0:i.flushPendingSavings())&&void 0!==s?s:null})).filter(We.notNull);t.length&&await Promise.all(t)}catch(e){Qe.logError(`Error flushing line tools: ${e}`)}(t=e.checkProFeature(t))in Ae.layouts||(t="s"),si(e,i);const n=e.layoutType,a=Ae.layouts[t].count;(0,Le.emit)("layout_about_to_be_changed",t),(null!==(o=e.splitters.value())&&void 0!==o?o:[]).forEach(((e,t)=>{e.splitterElement.remove(),e.mouseHandler.destroy()})),e.splitters.setValue([]);const l=Ae.layouts[t];e.layoutTemplate.setValue(l);const c=null!==(r=e.allLayoutSizesState.get(l.layoutType))&&void 0!==r?r:(0,De.layoutInitialSizingState)(l.expression);e.allLayoutSizesState.set(l.layoutType,c),e.sizingState.setValue(c);const d=e.maximizedChartDef.value();if(e.isPhoneSize.value()&&e.viewMode.value()===_.CollectionViewMode.ForceFullscreen)if(d){const t=e.chartWidgetsDefs.indexOf(d);(t<0||t>=a)&&e.maximizedChartDef.setValue(e.chartWidgetsDefs[0])}else e.maximizedChartDef.setValue(e.chartWidgetsDefs[0]);else n!==t&&e.maximizedChartDef.value()&&e.maximizedChartDef.setValue(null);d&&e.activeChartWidget.setValue((0,s.ensureNotNull)(d.chartWidget));for(let t=0;t=a;if(o=e.maximizedChartDef.value()?e.maximizedChartDef.value()===r:t1),r.fullscreen.setValue(e.maximizedChartDef.value()===r),r.collapsed.setValue(n)}else r?(ii(r),r.collapsed.setValue(n)):e.isPhoneSize.value()&&e.viewMode.value()===_.CollectionViewMode.ForceFullscreen&&(ti(e,i,t,void 0),ii(e.chartWidgetsDefs[t]),e.chartWidgetsDefs[t].collapsed.setValue(n))}e.sizingState.setValue(c),Kt(e),e.layoutWV.setValue(t),e.setLayoutType(t),e.updateWatchedValue(),function(e){const t=e.layoutTemplate.value().count;e.inlineChartsCount.setValue(t),e.globalDetachable.setValue(t>1)}(e),e.checkAllPendingModelsAlreadyCreated(),oi(e,i),e.initialLoading||e.updateViewMode(), e.inlineChartsCount.value()<1&&a>0&&e.chartWidgetsDefs[a-1].rdState.bridge().attach()}function li(e,t,i,s,o){const r=e.actualLayoutCount();return e.chartWidgetsDefs.slice(0,r).filter((e=>e.rdState.bridge().visible.value())).map((e=>e.chartWidget)).filter((t=>t.id()!==i&&(!!t.hasModel()&&(t.selectPointMode().value()===qe.SelectPointMode.Replay&&"AllCharts"===Q.replayModeProperty.value()||(s||e.crosshairLockRaw))))).forEach((e=>e.model().model().setExternalPosition(t,o))),!0}function ci(e,t,i,s,o){if(li(e,t,i,s,o)){const i=e.crossHairSyncBroadcast;if(i){const e={type:"crosshair",payload:{point:t,envState:o,sourceUniqueId:i.uniqueId}};i.channel.postMessage(e)}}}function hi(e){const t=new BroadcastChannel("ChartWidgetsCollection");return t.onmessage=t=>{const i=t.data,s=e();if(s.crossHairSyncBroadcast&&"crosshair"===i.type)s.crossHairSyncBroadcast.uniqueId!==i.payload.sourceUniqueId&&li(s,i.payload.point,null,!1,i.payload.envState)},{channel:t,uniqueId:(0,Ie.randomHashN)(6)}}function di(e){var t;null===(t=e.crossHairSyncBroadcast)||void 0===t||t.channel.close()}function ui(e,t,i){if(!e.combinedTrackTimeLock.value()||e.dateRangeLock.value())return;const s=e.layoutTemplate.value().count;e.undoHistory.beginUndoMacro(tt),e.chartWidgetsDefs.slice(0,s).filter((e=>e.chartWidget.hasModel()&&e.chartWidget.model().model()!==i)).forEach((e=>{const i=e.chartWidget.model().model(),s=i.mainSeries().syncModel();s&&i.syncTimeWithModel(s.syncSourceTarget(),t)})),e.undoHistory.endUndoMacro(),(0,Le.emit)("sync_time",t)}function _i(e){return Promise.all(e.map((e=>{const t=e.model().mainSeries();return t.symbolResolvingActive().value()?d(t.dataEvents().symbolResolved()).promise:t.symbolInfo()})))}function pi(e){return e.chartWidgetsDefs.every((e=>e.chartWidget.hasModel()))?Promise.resolve(e.chartWidgetsDefs.map((e=>e.chartWidget))):Promise.all(e.chartWidgetsDefs.map((e=>e.chartWidget.hasModel()||d(e.chartWidget.modelCreated()).promise))).then((()=>pi(e)))}function mi(e,t){var i,o,r;if((0,h.enabled)("charting_library_base"))return t;if("s"===t||e.widgetOptions.containsData||e.readOnly||(0,Z.enabled)($.ProductFeatures.MULTIPLE_CHARTS)&&(0,s.ensure)(null===(i=(0,Z.getConfig)($.ProductFeatures.MULTIPLE_CHARTS))||void 0===i?void 0:i.limit)>=Ae.layouts[t].count)return t;let n="s";{let t=1;const i=null!==(r=null===(o=(0,Z.getConfig)($.ProductFeatures.MULTIPLE_CHARTS))||void 0===o?void 0:o.limit)&&void 0!==r?r:0;for(const e of Object.keys(Ae.layouts)){const s=Ae.layouts[e].count;s<=i&&s>t&&(n=e,t=s)}pi(e).then(_i).then((()=>{(0,K.trackGoProFeature)("multipleCharts"),(0,X.createGoProDialog)({feature:"multipleCharts"})}))}return n}async function gi(e,t,i){if(i=mi(e,i),e.layoutWV.value()===i)return!1;{const t=e.chartWidgetsDefs.map((e=>{var t,i,s;return null!==(s=null===(i=null===(t=e.chartWidget)||void 0===t?void 0:t.lineToolsSynchronizer())||void 0===i?void 0:i.flushPendingSavings())&&void 0!==s?s:null})).filter(We.notNull);if(t.length)try{await Promise.all(t)}catch(e){Qe.logError(`Error flushing line tools: ${e}`)}} return e.undoHistory.pushUndoCommand(new Ve(t,i)),!0}async function Si(e,t,i){const{theme:s,onlyActiveChart:o,restoreNonThemeDefaults:r,themeName:n,standardTheme:a,syncState:l=!0,noUndo:c}=i,h=(0,Te.getCurrentTheme)().name;let d;o?d=[e.activeChartWidget.value()]:(si(e,t),await Promise.all(e.savedChartWidgetOptions.map(((i,s)=>new Promise((i=>{ii(ti(e,t,s,i))}))))),d=e.chartWidgetsDefs.map((e=>e.chartWidget)),oi(e,t)),c?(a&&new ze(h,n,l).redo(),d.forEach((e=>{e.model().model().restoreTheme(s,r,c)}))):(e.undoHistory.beginUndoMacro(ot),a&&e.undoHistory.pushUndoCommand(new ze(h,n,l)),d.forEach((e=>{e.model().model().restoreTheme(s,r)})),e.undoHistory.endUndoMacro()),await Promise.all(d.map((e=>e.model().model().colorStudiesPropertiesReady())))}function vi(e,t){e.symbolLock.setValue(t)}function fi(e,t){const{internalSymbolLock:i,activeChartWidget:s,undoHistory:o,dateRangeLock:r,loadingContent:n,linkingGroupsCharts:l,chartWidgetsDefs:c}=e;if(t!==i.value())if(n)i.setValue(t);else{if(e.undoHistory.beginUndoMacro(rt),t){const t=s.value(),i=c.map((e=>e.chartWidget));l.forEach(((s,o)=>{const n=t.linkingGroupIndex().value()===o?t:i.find((e=>e.linkingGroupIndex().value()===o));if(void 0!==n){(0,a.muteLinkingGroup)(o,!0);for(const t of s.value())t!==n&&t.symbolWV().value()!==n.symbolWV().value()&&(t.setSymbol(n.symbolWV().value()),r.value()&&e.subscribeToCompletedEventForDateRangeSync(t,!0));(0,a.muteLinkingGroup)(o,!1)}}))}o.setWatchedValue(i,t,rt),o.endUndoMacro()}}function bi(e,t){e.intervalLock.setValue(t)}function yi(e,t){const{internalIntervalLock:i,activeChartWidget:s,undoHistory:o,dateRangeLock:r,loadingContent:n,chartWidgetsDefs:l,linkingGroupsCharts:c}=e;if(t!==i.value())if(n)i.setValue(t);else{if(o.beginUndoMacro(nt),t&&t){const t=s.value(),i=l.map((e=>e.chartWidget));c.forEach(((s,o)=>{const n=t.linkingGroupIndex().value()===o?t:i.find((e=>e.linkingGroupIndex().value()===o));if(void 0!==n){(0,a.muteLinkingGroup)(o,!0);for(const t of s.value())t!==n&&t.resolutionWV().value()!==n.resolutionWV().value()&&(t.setResolution(n.resolutionWV().value()),r.value()&&e.subscribeToCompletedEventForDateRangeSync(t,!0));(0,a.muteLinkingGroup)(o,!1)}}))}o.setWatchedValue(i,t,nt),o.endUndoMacro()}}function Ci(e,t){const i=e.activeChartWidget.value();if(i&&i.hasModel()){const s=i.model();t?(e.subscribeToEventsForDateRangeSync(s),e.syncChartsDateRangesWithActiveChartRange()):e.unsubscribeFromEventsForDateRangeSync(s)}e.dateRangeLock.setValue(t)}function wi(e,t){const{internalDateRangeLock:i,undoHistory:s,loadingContent:o}=e;o?i.setValue(t):s.setWatchedValue(i,t,at)}function Pi(e,t){e.trackTimeLock.setValue(t)}function Ti(e,t){const{internalTrackTimeLock:i,undoHistory:s,loadingContent:o}=e;o?i.setValue(t):s.setWatchedValue(i,t,lt)}function Mi(e,t,i){e.symbolLock.value()?xi(e,t,i):e.activeChartWidget.value().setSymbol(t)}function xi(e,t,i){const s=e.activeChartWidget.value();void 0===i&&(i=s.linkingGroupIndex().value());for(const s of e.chartWidgetsDefs){const e=s.chartWidget ;(e.hasModel()?e.model().mainSeries().symbolSameAsResolved(t):e.symbolWV().value()===t)||void 0!==i&&e.linkingGroupIndex().value()!==i||e.setSymbol(t)}}async function Ii(e,t=this.activeChartWidget.value()){if(!t)return!1;{if(Ye.Interval.isTicks(t.resolutionWV().value())&&(4===e||7===e||5===e||6===e))return t.showHint(1,{text:vt.format({chartStyle:(0,Pe.getTranslatedChartStyleName)(e)}),solutionId:ee.solutionIds.WHY_RENKO_NOT_WORK,solutionText:n.t(null,void 0,i(639571))}),!1;let s=!1;const o=Li(this.innerState());for(const t of o){const i=t.model().model();if(i.isInReplay()&&!i.mainSeries().isStyleSupported(e)){s=!0;break}}const r=this.innerState().flags;return!s||r.isConfirmationAboutReplayLocked?(Ai(t,e),!0):new Promise((i=>{(0,Ke.showConfirm)({text:ft,onConfirm:s=>{r.isConfirmationAboutReplayLocked=!0,Ai(t,e),r.isConfirmationAboutReplayLocked=!1,s.dialogClose(),i(!0)},onClose:()=>i(!1),onCancel:e=>{e.dialogClose(),i(!1)}})}))}}function Ai(e,t){const i=e.model(),s=i.mainSeries().properties().childs().style;i.setChartStyleProperty(s,t,ct)}function Li(e){return(e.intervalLock.value()?e.chartWidgetsDefs.map((e=>e.chartWidget)):[e.activeChartWidget.value()]).filter((e=>e.hasModel()))}async function ki(e,t,s,o){if(e.flags.loadingChart||e.flags.setTimeFrameActive||e.flags.setNewResolution)return!1;{const o=Ye.Interval.isTicks(t),r=Li(e);if(o)for(const e of r){const t=e.model().model().mainSeries().style();if(4===t||7===t||5===t||6===t)return e.showHint(1,{text:vt.format({chartStyle:(0,Pe.getTranslatedChartStyleName)(t)}),solutionId:ee.solutionIds.WHY_RENKO_NOT_WORK,solutionText:n.t(null,void 0,i(639571))}),!1}let a="",l=!1;const c=Ye.Interval.isRange(t);if(c||o)for(const e of r){const t=e.model().model();if(t.isInReplay()){if(c&&11!==t.mainSeries().style()){l=!0,a=gt;break}o&&(l=!0,a=St)}}const h=r.filter((e=>e.model().isInReplay()));if(h.length){if(!(await Promise.all(h.map((e=>e.model().canChangeResolution(t))))).every(Boolean))return!1}return!l||e.flags.isConfirmationAboutReplayLocked?(Ei(e,t,s),!0):new Promise((i=>{(0,Ke.showConfirm)({text:a,onConfirm:o=>{e.flags.isConfirmationAboutReplayLocked=!0,Ei(e,t,s),e.flags.isConfirmationAboutReplayLocked=!1,o.dialogClose(),i(!0)},onClose:()=>i(!1),onCancel:e=>{e.dialogClose(),i(!1)}})}))}}function Ei(e,t,i,s){if((0,Ze.setLastUsedResolution)(t),e.flags.setNewResolution=!0,s=null!=s?s:e.activeChartWidget.value(),void 0===i&&(i=s.linkingGroupIndex().value()),e.intervalLock.value())for(const s of e.chartWidgetsDefs){const e=s.chartWidget;e.resolutionWV().value()===t||void 0!==i&&e.linkingGroupIndex().value()!==i||e.setResolution(t)}else s.setResolution(t);e.flags.setNewResolution=!1}function Di(e){const t=new u.WatchedValue(null),i=()=>{t.setValue(e.value().linkingGroupIndex().value())};e.value()&&i();const s=e.spawn();let o;return s.subscribe((e=>{null==o||o.destroy(),o=e.linkingGroupIndex().spawn(),o.subscribe(i),i()})),t.spawn((()=>{s.destroy(),null==o||o.destroy()}))}function Ni(e){const t=new Set(e.map((e=>e.chartWidget.linkingGroupIndex().value()))) ;return Array.from(t).sort(((e,t)=>(null!=e?e:-1)-(null!=t?t:-1)))}function Bi(e){const t=new je.WatchedObject(Ni(e.chartWidgetsDefs)),i=()=>{t.setValue(Ni(e.chartWidgetsDefs))};e.chartWidgetsDefs.forEach((e=>e.chartWidget.linkingGroupIndex().subscribe(i)));const s=e=>{e.linkingGroupIndex().subscribe(i),i()};return e.chartWidgetCreatedDelegate.subscribe(null,s),t.spawn((()=>{e.chartWidgetsDefs.forEach((e=>e.chartWidget.linkingGroupIndex().unsubscribe(i))),e.chartWidgetCreatedDelegate.unsubscribe(null,s)}))}function Ri(e,t){let i=e.linkingGroupsCharts.get(t);return void 0===i&&(i=new je.WatchedObject([],xe.compareTwoCollectionsByIds),e.linkingGroupsCharts.set(t,i)),i}function Oi(e){var t;const i=new Map;for(const t of e.chartWidgetsDefs){const e=t.chartWidget.linkingGroupIndex().value();let s=i.get(e);void 0===s&&(s=[],i.set(e,s)),s.push(t.chartWidget)}for(const s of(0,xe.join)(new Set(e.linkingGroupsCharts.keys()),new Set(i.keys())))Ri(e,s).setValue(null!==(t=i.get(s))&&void 0!==t?t:[])}function Vi(e){if(e){const e=function(){var e,t,i,o;const r=null!==(t=null===(e=(0,Z.getConfig)($.ProductFeatures.BACKEND_CONNECTIONS))||void 0===e?void 0:e.limit)&&void 0!==t?t:0,n=(0,s.ensureDefined)(window.pro),a=n.getProductsByType(n.PRODUCT_TYPES.pro_plan);for(const e of a)if((null!==(o=null===(i=(0,Z.getConfig)($.ProductFeatures.BACKEND_CONNECTIONS,(0,s.ensureDefined)(e.id)))||void 0===i?void 0:i.limit)&&void 0!==o?o:0)>r)return{connectionCount:r,moreConnectionsPlanAvailable:!0};return{connectionCount:r,moreConnectionsPlanAvailable:!1}}(),t=[{text:n.t(null,void 0,i(881492)),action:J.PredefinedAction.Close,variant:"secondary",color:"gray",compactMode:!0,onClick:()=>window.ChartApiInstance.connect()}];e.moreConnectionsPlanAvailable&&t.push({action:J.PredefinedAction.OpenGopro,text:n.t(null,void 0,i(834805)),compactMode:!0}),(0,X.createGoProDialog)({feature:"connectionsLimit",actionButtonsLayout:J.ActionButtonsLayout.Row,actions:t,customParams:e})}}function Wi(e,t){let i=[];const s={},o=()=>{i.forEach((e=>e.unsubscribe(a))),i=t.filter((e=>e.chartWidget.hasModel())).map((e=>e.chartWidget.selectPointMode())),i.forEach((e=>e.subscribe(a))),t.forEach((e=>{e.chartWidget.hasModel()||e.chartWidget.withModel(s,(()=>{o(),a()}))}))};o();const r=()=>i.some((e=>e.value()===qe.SelectPointMode.Replay))&&"AllCharts"===Q.replayModeProperty.value(),n=new u.WatchedValue(r()),a=()=>n.setValue(r()),l=()=>{o(),a()};e.subscribe(l),Q.replayModeProperty.subscribe(n,a);return n.spawn((()=>{Q.replayModeProperty.unsubscribe(n,a),e.unsubscribe(l),i.forEach((e=>e.subscribe(a)))}))}function Fi(e,t,i){return(0,Ue.combine)(((e,t)=>e||t),t.weakReference(),Wi(e,i).ownership())}function Hi(e,t,i){const s=t.id();if(e.chartWidgetIdToCompletedCallbackMap.has(s))return;const o=()=>{e.chartWidgetIdToCompletedCallbackMap.has(s)&&(e.chartWidgetIdToCompletedCallbackMap.delete(s),Ki(e,i?t:void 0))};t.model().mainSeries().dataEvents().completed().subscribe(null,o,!0),e.chartWidgetIdToCompletedCallbackMap.set(s,{cw:t,callback:o})}function zi(e){Ki(e)}const Ui=new Map ;function Gi(e){var t;const i=null!==(t=Ui.get(e.id()))&&void 0!==t?t:{};return Ui.set(e.id(),i),i}function qi(e,t){t.timeScale().visibleBarsStrictRangeChanged().subscribe(Gi(t),zi.bind(null,e))}function ji(e,t){t.timeScale().visibleBarsStrictRangeChanged().unsubscribeAll(Gi(t)),e.chartWidgetIdToCompletedCallbackMap.forEach((e=>{const t=e.cw,i=e.callback;t.model().mainSeries().dataEvents().completed().unsubscribe(null,i)})),e.chartWidgetIdToCompletedCallbackMap.clear()}function Yi(e,t,i){e.model().model().gotoTimeRange(t,i),(0,Le.emit)("sync_date_range",t,i)}function Ki(e,t){if(!e.dateRangeLock.value()||null!==e.currentLayoutResizeAction.value())return;const i=e.activeChartWidget.value(),o=i.model().mainSeries();if(!(0,Pe.isTimeBasedStyle)(o.style()))return;const r=i.model().timeScale(),n=r.visibleBarsStrictRange();if(null===n)return;const a=(0,s.ensureNotNull)(r.points().range().value());let l=r.indexToTimePoint(n.firstBar());null===l&&o.endOfData()&&(l=r.indexToTimePoint(a.firstIndex));let c=r.indexToTimePoint(n.lastBar());if(null===c&&(c=r.indexToTimePoint(a.lastIndex)),null===l||null===c)return void Hi(e,i,!1);e.chartWidgetIdToCompletedCallbackMap.delete(i.id());let h=1e3*l,d=1e3*c;if(o.isDWM()){const e=new Date(h),t=new Date(d);(0,we.set_hms)(e,0,0,0,0),(0,we.set_hms)(t,0,0,0,0),h=e.getTime(),d=t.getTime()}for(let s=0;s{"use strict";var s=i(809796).TranslatedString,o=i(650151).assert,r=i(440617).Series,n=i(244842),a=i(608415).ActionBinder,l=i(62802).setValue,c=i(794349).TabNames,h=i(277774).showGoToDateDialog,d=i(470316),u=i(799786),_=i(419250).createAddNoteAction,p=i(854798).Version,m=i(663554).showDeleteStudyTreeConfirm,g=i(779923).showConfirm,S=i(992393).confirmDatasourceRemoving,v=i(67302).showThemeSwitcher,f=i(67302).showThemeAction,b=i(514315).updateThemeActions,y=i(263955).showScriptInfoErrorNoticeDialog,C=i(807218).Study,w=i(306682).StudyStub,P=i(427937).isStudy,T=i(821979).LineDataSource,M=i(713473),x=M.isLineTool,I=M.isStudyLineTool,A=i(368135).STUDYPLOTDISPLAYTARGET,L=i(347710).studyMetaInfoRepository,k=i(373571).Action,E=i(607509).ACTION_ID,D=i(885482),N=i(223699).Interval,B=i(444331),R=B.getDefaultStyle,O=B.hasVolume,V=i(572230).InvalidationMask,W=i(583912).linking,F=i(230296).showChangeIntervalDialogAsync,H=i(72368).isMobile,z=i(993294).createSymbolSearchAction,U=i(15458),G=U.availableTimezones,q=U.timezoneIsAvailable,j=i(951713).toggleHideMode,Y=i(526075).StudyMetaInfo,K=i(345848).trackEvent,Z=i(42292);const{viewportChangeEvent:$}=i(964824);var X=i(707957).Delegate,J=i(201089).getLogger("ChartWidget",{color:"#606"}),Q=i(167975).appendEllipsis,ee=i(895370).addPerfMark,te=i(197050).combineProperty,ie=i(931212).ChartWidgetBase,se=i(638456).CheckMobile.any(),oe=i(315347).TIMEFRAMETYPE,re=i(360758).addPlusButtonProperty ;var ne=new s("change timezone",i.tf(null,void 0,i(820505))),ae=new s("scale price chart only",i.tf(null,void 0,i(599042))),le=new s("stay in drawing mode",i.tf(null,void 0,i(52010))),ce=new s("hide all drawing tools",i.tf(null,void 0,i(454781))),he=new s("hide marks on bars",i.tf(null,void 0,i(744974))),de=new s("change symbol last value visibility",i.tf(null,void 0,i(253150))),ue=new s("change symbol previous close value visibility",i.tf(null,void 0,i(112707))),_e=new s("change previous close price line visibility",i.tf(null,void 0,i(259883))),pe=new s("change symbol labels visibility",i.tf(null,void 0,i(109402))),me=new s("change indicators and financials name labels visibility",i.tf(null,void 0,i(559820))),ge=new s("change indicators and financials value labels visibility",i.tf(null,void 0,i(90512))),Se=new s("change bid and ask labels visibility",i.tf(null,void 0,i(805100))),ve=new s("change bid and ask lines visibility",i.tf(null,void 0,i(432311))),fe=new s("change pre/post market price label visibility",i.tf(null,void 0,i(549889))),be=new s("change pre/post market price line visibility",i.tf(null,void 0,i(16750))),ye=new s("change high and low price lines visibility",i.tf(null,void 0,i(992556))),Ce=new s("change high and low price labels visibility",i.tf(null,void 0,i(466805))),we=(new s("change average close price line visibility",i.tf(null,void 0,i(498866))),new s("change average close price label visibility",i.tf(null,void 0,i(739402))),new s("change countdown to bar close visibility",i.tf(null,void 0,i(58108)))),Pe=new s("change plus button visibility",i.tf(null,void 0,i(450190))),Te=new s("change price line visibility",i.tf(null,void 0,i(867761))),Me=new s("unlock {title}",i.tf(null,void 0,i(192421))),xe=new s("lock {title}",i.tf(null,void 0,i(850193))),Ie=new s("change session breaks visibility",i.tf(null,void 0,i(115403))),Ae=i.tf(null,void 0,i(615241)),Le=i.tf(null,void 0,i(529404)),ke=i.tf(null,void 0,i(844302)),Ee=i.tf(null,void 0,i(994338));e.exports.ChartWidget=class extends ie{constructor(e,t,i){super(e,t,i),this._options.timeScaleWidget&&(this._options.timeScaleWidget.pressedMouseMoveScale=this._options.handleScale.axisPressedMouseMove.time);var s=this,o=this._options.content,r=this._options.readOnly;this._removeMaximizeHotkey=null,s._hotkeys=u.createGroup({desc:"Chart actions",isDisabled:()=>!this.isActive().value()});var n=this._options.containsData,a=this._options.onWidget,l=this._options.onCmeWidget;l&&J.logWarn("[ChartWidget] 'onCmeWidget' option is depricated");var c=this._options.widgetCustomer,h=this._options.timezone,d=this._options.hideSymbolSearch,_=this._options.defSymbol,p=N.isValid(this._options.defInterval)?this._options.defInterval:void 0,m=parseInt(this._options.defStyle),g=B.isValidStyle(m)?m:void 0,S=this._options.defSessionId,v=void 0!==this._options.defTimeframe?"string"==typeof this._options.defTimeframe?{value:this._options.defTimeframe.toUpperCase(),type:oe.PeriodBack}:{...this._options.defTimeframe,type:oe.TimeRange}:void 0;this._content=o, this._initialLoading=this._options.initialLoading,this._readOnly=r,this._containsData=n,this._defSymbol=_,this._defInterval=p,this._defTimeframe=v,this._defStyle=g,this._onWidget=!!a,this._compareSymbols=this._options.compareSymbols,this._onWidget&&(l?this._widgetCustomer="cme":c&&(this._widgetCustomer=c)),this._hideSymbolSearch=d,this._frameTime=30,this._model=null,this._metaInfo={},this._drawRafId=0,this._compareDialog=this._chartWidgetCollection.getCompareDialogRenderer();var f=this._contentSeriesProperties();f&&(_=f.symbol,p=f.interval),void 0===this._options.useUserChartPreferences&&(this._options.useUserChartPreferences=!0);var b="chartproperties.mainSeriesProperties",y=this._options.useUserChartPreferences?Z.defaults(b):Z.factoryDefaults(b);this._properties.mainSeriesProperties.merge(y),this._properties.mainSeriesProperties.hasChild("esdBreaksStyle")&&this._properties.mainSeriesProperties.removeProperty("esdBreaksStyle"),p=p||y.interval||"D",B.isValidStyle(g)||(g=B.isValidStyle(y.style)?y.style:R(N.isRange(p))),this._properties.mainSeriesProperties.merge({visible:!0,symbol:_||DEFAULT_SYMBOL,shortName:"",timeframe:"",onWidget:this._onWidget,interval:p,currencyId:null,unitId:null,style:g,sessionId:S}),this._symbolWV.setValue(this.getSymbol()),this._resolutionWV.setValue(this.getResolution()),this._containsData&&this._properties.mainSeriesProperties.merge({showCountdown:!1}),h&&q(h)&&this._properties.timezone.setValue(h),this._tagsChanged=new X,this._timingsMeter=null,this._options.container.subscribe((function(e){s._setElement(e)}),{callWithLast:!0});var C=function(){s.resize()};this._options.width.subscribe(C),this._options.height.subscribe(C),this._options.visible.subscribe(this._updateTimingsMeterState.bind(this)),this._aboutToBeDestroyed=new X,this._actions=null,this._definitionsViewModel=null,this._backgroundTopColorSpawn=null,this._backgroundBottomColorSpawn=null}isInitialized(){return Boolean(this._inited)}compareSymbols(){return this._compareSymbols}async _getChartPropertyDefinitionsViewModel(){if(null===this._definitionsViewModel){const{ChartPropertyDefinitionsViewModel:e}=await Promise.all([i.e(88601),i.e(76169),i.e(20128),i.e(30154),i.e(47924),i.e(83596)]).then(i.bind(i,3775));if(this._isDestroyed)throw new Error("Chart widget already destroyed");await new Promise((e=>this.withModel(null,e))),null===this._definitionsViewModel&&(this._definitionsViewModel=new e(this.model(),this.properties(),this._options))}return this._definitionsViewModel}_initMaximizeHotkey(e){var t=this;function i(e){e.defaultPrevented||d.modifiersFromEvent(e)===d.Modifiers.Alt&&e.stopPropagation()}function s(e){e.defaultPrevented||d.modifiersFromEvent(e)===d.Modifiers.Alt&&(e.preventDefault(),e.stopPropagation(),t.toggleFullscreen())}return e.addEventListener("mousedown",i,!0),e.addEventListener("click",s,!0),function(){e.removeEventListener("mousedown",i,!0),e.removeEventListener("click",s,!0)}}toggleFullscreen(){var e=this.getResizerDetacher() ;e.fullscreenable.value()&&(e.fullscreen.value()?e.exitFullscreen():e.requestFullscreen())}setTimezone(e){e&&q(e)?this._properties.timezone.setValue(e):console.warn("Incorrect timezone: "+JSON.stringify(e))}getTimezone(){return this._properties.timezone.value()}refreshMarks(){this.model().barsMarksSources().forEach((function(e){e.refreshData()}))}clearMarks(e){this.model().barsMarksSources().forEach((function(t){t.clearMarks(e)}))}_initBackgroundColor(){null===this._backgroundTopColorSpawn&&(this._backgroundTopColorSpawn=this._model.model().backgroundTopColor().spawn(),this._backgroundTopColorSpawn.subscribe(this._onBackgroundColorChanged.bind(this))),null===this._backgroundBottomColorSpawn&&(this._backgroundBottomColorSpawn=this._model.model().backgroundColor().spawn(),this._backgroundBottomColorSpawn.subscribe(this._onBackgroundColorChanged.bind(this)))}paneWidgets(){return this._paneWidgets}paneByCanvas(e){for(var t=0;t{null!==e&&t()}))}));var t=new k({actionId:E.ChartSeriesPriceScaleToggleInvertPriceScale,options:{label:i.tf(null,void 0,i(353239)),statName:"Invert Scale",checkable:!0,onExecute:function(){e._model.invertPriceScale(e._model.mainSeries().priceScale())},hotkeyGroup:this._hotkeys,hotkeyHash:u.Modifiers.Alt+73}}),s=new k({actionId:E.ChartSeriesPriceScaleToggleAutoScale,options:{label:i.tf(null,void 0,i(550834)),checkable:!0,onExecute:function(){var t=e._model.mainSeries().priceScale();e._model.togglePriceScaleAutoScaleMode(t),s.update({checked:t.isAutoScale()})}}}),o=new k({actionId:E.ChartScalesToggleLockPriceToBarRatio,options:{label:i.tf(null,void 0,i(518219)),checkable:!0,statName:"ToggleLockScale",onExecute:function(){e._model.togglePriceScaleLockScaleMode(e._model.mainSeries().priceScale())}}}),r=new k({actionId:E.ChartSeriesPriceScaleToggleRegular,options:{label:i.tf(null,{context:"scale_menu"},i(172116)),checkable:!0,statName:"ToggleRegularScale",onExecute:function(){var t=e._model.mainSeries().priceScale();e._model.setPriceScaleRegularScaleMode(t),r.update({checked:t.isRegular()})}}}),c=new k({actionId:E.ChartSeriesPriceScaleTogglePercentage,options:{label:i.tf(null,void 0,i(351102)),checkable:!0,statName:"TogglePercantage",onExecute:function(){e._model.togglePriceScalePercentageScaleMode(e._model.mainSeries().priceScale())},hotkeyGroup:this._hotkeys,hotkeyHash:u.Modifiers.Alt+80}}),p=new k({actionId:E.ChartSeriesPriceScaleToggleIndexedTo100,options:{label:i.tf(null,void 0,i(520062)),checkable:!0,statName:"ToggleIndexedTo100",onExecute:function(){e._model.togglePriceScaleIndexedTo100ScaleMode(e._model.mainSeries().priceScale())}}}),m=new k({actionId:E.ChartSeriesPriceScaleToggleLogarithmic,options:{label:i.tf(null,void 0,i(512285)),statName:"ToggleLogScale",checkable:!0,onExecute:function(){e._model.togglePriceScaleLogScaleMode(e._model.mainSeries().priceScale())},hotkeyGroup:this._hotkeys,hotkeyHash:u.Modifiers.Alt+76}}),g=new k({actionId:E.ChartUndo,options:{label:i.tf(null,void 0,i(881320)),onExecute:function(){K("GUI","Undo"),e._model.undoHistory().undo()},disabled:!0,hotkeyGroup:this._hotkeys,hotkeyHash:u.Modifiers.Mod+90,isRepeatAccepted:!0}}),S=new k({actionId:E.ChartRedo,options:{label:i.tf(null,void 0,i(641615)),onExecute:function(){K("GUI","Redo"),e._model.undoHistory().redo()},disabled:!0,hotkeyGroup:this._hotkeys,hotkeyHash:u.Modifiers.Mod+89,isRepeatAccepted:!0}});e.withModel(null,(function(){e._model.undoHistory().undoStack().onChange().subscribe(e,e.updateUndoRedo),e._model.undoHistory().redoStack().onChange().subscribe(e,e.updateUndoRedo)}));var v=new k({actionId:E.ChartChangeTimeZone,options:{label:i.tf(null,void 0,i(164375)),statName:"TimeZone"}}),f=z();l("symboledit.dialog_last_entry","");var b={ label:Q(i.tf(null,void 0,i(699374))),statName:"ChangeInterval",onExecute:function(){F({initVal:W.interval.value(),selectOnInit:!0})}};!n.enabled("show_interval_dialog_on_key_press")||this.readOnly()||this._hideSymbolSearch||(b.shortcutHint=",",b.hotkeyGroup=this._hotkeys,b.hotkeyHash=188);var y,C=new k({actionId:E.ChartDialogsShowChangeInterval,options:b});TradingView.onWidget()||(y=_(this,{hotkeyGroup:this._hotkeys},H()));var w=this._createResetTimescaleAction(),P=new k({actionId:E.ChartRemoveAllIndicators,options:{label:i.tf(null,void 0,i(413951)),statName:"RemoveAllIndicators",onExecute:this.removeAllStudies.bind(this)}}),T=new k({actionId:E.ChartRemoveAllLineTools,options:{label:i.tf(null,void 0,i(801434)),statName:"RemoveAllDrawingTools",onExecute:this.removeAllDrawingTools.bind(this)}}),M=new k({actionId:E.ChartRemoveAllIndicatorsAndLineTools,options:{label:i.tf(null,void 0,i(897305)),statName:"RemoveAllIndicatorsAndDrawingTools",onExecute:this.removeAllStudiesDrawingTools.bind(this)}}),x=this.chartWidgetCollection(),I=new k({actionId:E.ChartApplyIndicatorsToAllCharts,options:{label:i.tf(null,void 0,i(295910)),statName:"ApplyIndicatorsToAllCharts",onExecute:function(){x.applyIndicatorsToAllCharts(e)}}}),A={label:Q(i.tf(null,void 0,i(398767))),statName:"InsertIndicator",onExecute:function(){e.showIndicators()}};this._options.indicatorsDialogShortcutEnabled&&(A.hotkeyGroup=this._hotkeys,A.hotkeyHash=191,this._hotkeys.add({handler:function(){this.showIndicators()}.bind(this),desc:"Show insert indicator dialog",hotkey:111}));var L,N=new k({actionId:E.ChartDialogsShowInsertIndicators,options:A}),B=new k({actionId:E.ChartDialogsShowCompareOrAddSymbol,options:{label:Q(i.tf(null,void 0,i(220229))),statName:"CompareOrAddSymbol",onExecute:this.toggleCompareOrAdd.bind(this)}}),R=new k({actionId:E.ChartObjectTreeShow,options:{label:Q(i.tf(null,void 0,i(500675))),statName:"ObjectsTree",onExecute:this.showObjectsTreePanelOrDialog.bind(this)}}),O=this._createChartPropertiesAction(),U=this._createMainSeriesPropertiesAction(),G=this._createScalesPropertiesAction(),q=new k({actionId:E.ChartSelectedObjectToggleLocked,options:{label:i.tf(null,void 0,i(101441)),statName:"ToggleLockSelectedObject",onExecute:this.toggleLockSelectedObject.bind(this)}}),Y=this._createHideSelectedObjectAction();n.enabled("property_pages")&&(L=this._createSelectedSourcePropertiesAction()),this.withModel(null,(function(){var t=e.model().mainSeries(),i=t.properties();i.priceAxisProperties.subscribe(e,e._updateScalesActions),t.priceScaleAboutToBeChanged().subscribe(e,(function(){i.priceAxisProperties.unsubscribeAll(e)})),t.priceScaleChanged().subscribe(e,(function(){i.priceAxisProperties.subscribe(e,e._updateScalesActions),e._updateScalesActions()}))}));var Z=new k({actionId:E.ChartPriceScaleToggleAutoScaleSeriesOnly,options:{label:i.tf(null,void 0,i(937207)),checkable:!0,statName:"ScalePriceChartOnly"}});Z.binder=new a(Z,this._properties.scalesProperties.scaleSeriesOnly,this.model(),ae);var X=this.model().model() ;this._properties.scalesProperties.scaleSeriesOnly.listeners().subscribe(null,(function(){X.recalculateAllPanes($()),X.invalidate(V.full())}));var J=new k({actionId:E.ChartDrawingToolbarToggleVisibility,options:{label:i.tf(null,void 0,i(222903)),checkable:!0,statName:"ToggleDrawingToolbar"}}),ee=this._options.isDrawingToolbarVisible;ee&&(ee.subscribe((function(e){J.update({checked:e})}),{callWithLast:!0}),J.update({onExecute:function(){ee.setValue(!ee.value())}}));var ie,se=new k({actionId:"",options:{label:i.tf(null,void 0,i(593161)),checkable:!0,statName:"ToggleStayInDrawingMode"}});se.binder=new a(se,D.properties().stayInDrawingMode,this.model(),le),(ie=new k({actionId:E.ChartToggleVisibilityAllLineTools,options:{label:i.tf(null,void 0,i(647617)),checkable:!0,statName:"ToggleHideAllDrawingTools",hotkeyHash:u.Modifiers.Mod+u.Modifiers.Alt+72,hotkeyGroup:this._hotkeys}})).binder=new a(ie,D.hideAllDrawings(),this.model(),ce,(function(){j()}));var oe=new k({actionId:E.ChartMarksToggleVisibility,options:{label:i.tf(null,void 0,i(2441)),checkable:!0,statName:"ToggleHideMarksOnBars"}});oe.binder=new a(oe,D.hideMarksOnBars(),this.model(),he,(function(){D.hideMarksOnBars().setValue(this.value())}));const ne=this.properties().scalesProperties;var Me=new k({actionId:E.ChartPriceScaleLabelsToggleSeriesLastValueVisibility,options:{label:i.tf(null,void 0,i(752054)),checkable:!0,checked:!1,statName:"ToggleSymbolLastValue"}});Me.binder=new a(Me,ne.showSeriesLastValue,this.model(),de);var xe=new k({actionId:E.ChartPriceScaleLabelsToggleSymbolPrevCloseValueVisibility,options:{label:i.tf(null,void 0,i(590537)),checkable:!0,checked:!1,statName:"ToggleSymbolPrevCloseValue"}});xe.binder=new a(xe,ne.showSeriesPrevCloseValue,this.model(),ue);var Ie=new k({actionId:E.ChartLinesToggleSeriesPrevCloseLineVisibility,options:{label:i.tf(null,void 0,i(336857)),checkable:!0,checked:!1,statName:"ToggleSymbolPrevCloseLine"}});Ie.binder=new a(Ie,this.model().mainSeries().properties().showPrevClosePriceLine,this.model(),_e),this.model().mainSeries().onRestarted().subscribe(this,(function(){this.updateActionForIntradayOnly(xe),this.updateActionForIntradayOnly(Ie)}));var De=new k({actionId:E.ChartPriceScaleLabelsToggleSymbolNameLabelsVisibility,options:{label:i.tf(null,void 0,i(390932)),checkable:!0,checked:!1,statName:"ToggleSymbolLabels"}});De.binding=new a(De,ne.showSymbolLabels,this.model(),pe);const Ne=te(((e,t)=>e||t),ne.showStudyLastValue.weakReference(),ne.showFundamentalLastValue.weakReference());var Be=new k({actionId:E.ChartPriceScaleLabelsToggleIndicatorsValueLabelsVisibility,options:{label:i.tf(null,void 0,i(192945)),checkable:!0,checked:!1,statName:"ToggleStudiesAndFundamentalsPriceLabels"}});Be.binder=new a(Be,Ne,this.model(),null,(()=>{const e=!Ne.value();this.model().beginUndoMacro(ge),this.model().setProperty(ne.showStudyLastValue,e,null),this.model().setProperty(ne.showFundamentalLastValue,e,null),this.model().endUndoMacro()})) ;const Re=te(((e,t)=>e||t),ne.showStudyPlotLabels.weakReference(),ne.showFundamentalNameLabel.weakReference());var Oe=new k({actionId:E.ChartPriceScaleLabelsToggleIndicatorsNameLabelsVisibility,options:{label:i.tf(null,void 0,i(47587)),checkable:!0,checked:!1,statName:"ToggleStudiesAndFundamentalsNameLabels"}});Oe.binding=new a(Oe,Re,this.model(),null,(()=>{const e=!Re.value();this.model().beginUndoMacro(me),this.model().setProperty(ne.showStudyPlotLabels,e,null),this.model().setProperty(ne.showFundamentalNameLabel,e,null),this.model().endUndoMacro()}));var Ve=new k({actionId:E.ChartPriceScaleLabelsToggleBidAskLabelsVisibility,options:{label:i.tf(null,void 0,i(665287)),checkable:!0,checked:!1,statName:"ToggleBidAskLabels"}});Ve.binding=new a(Ve,ne.showBidAskLabels,this.model(),Se);var We=new k({actionId:E.ChartLinesToggleBidAskLinesVisibility,options:{label:i.tf(null,void 0,i(240548)),checkable:!0,checked:!1,statName:"ToggleBidAskLines"}});We.binding=new a(We,this.model().mainSeries().properties().bidAsk.visible,this.model(),ve);var Fe=new k({actionId:E.ChartPriceScaleLabelsTogglePrePostMarketLabelsVisibility,options:{label:i.tf(null,void 0,i(11240)),checkable:!0,checked:!1,statName:"TogglePrePostMarketPriceLabel"}});Fe.binding=new a(Fe,ne.showPrePostMarketPriceLabel,this.model(),fe);var He=new k({actionId:E.ChartChangeTimeZone,options:{label:i.tf(null,void 0,i(296768)),checkable:!0,checked:!1,statName:"TogglePrePostMarketPriceLine"}});He.binding=new a(He,this.model().mainSeries().properties().prePostMarket.visible,this.model(),be),this.model().mainSeries().isPrePostMarketPricesAvailableProperty().subscribe(this,(function(e){Fe.update({disabled:!e.value()}),He.update({disabled:!e.value()})}));var ze=this.model().mainSeries().properties().highLowAvgPrice,Ue=new k({actionId:E.ChartPriceScaleLabelsToggleHighLowPriceLabelsVisibility,options:{label:i.tf(null,void 0,i(953150)),checkable:!0,checked:!1,statName:"ToggleHighLowPriceLabels"}});Ue.binding=new a(Ue,ze.highLowPriceLabelsVisible,this.model(),Ce);var Ge,qe,je=new k({actionId:E.ChartLinesToggleHighLowLinesVisibility,options:{label:i.tf(null,void 0,i(321803)),checkable:!0,checked:!1,statName:"ToggleHighLowPriceLine"}});je.binding=new a(je,ze.highLowPriceLinesVisible,this.model(),ye);var Ye=new k({actionId:E.ChartPriceScaleToggleCountdownToBarCloseVisibility,options:{label:i.tf(null,void 0,i(894370)),checkable:!0,checked:!1,statName:"ToggleCountdown"}});Ye.binder=new a(Ye,this.model().mainSeries().properties().showCountdown,this.model(),we);var Ke=new k({actionId:E.ChartPriceScaleToggleAddOrderPlusButtonVisibility,options:{label:i.tf(null,void 0,i(897378)),checkable:!0,checked:re.value(),statName:"ToggleAddOrderPlusButton"}});Ke.binder=new a(Ke,re,this.model(),Pe);var Ze=null;this._options.goToDateEnabled&&(Ze=new k({actionId:E.ChartDialogsShowGoToDate,options:{label:Q(i.tf(null,void 0,i(475190))),statName:"GoToDate",onExecute:function(){var t=e._chartWidgetCollection.activeChartWidget.value();h(t)},hotkeyGroup:this._hotkeys,hotkeyHash:u.Modifiers.Alt+71}})) ;var $e,Xe=this._createShowSymbolInfoDialogAction(),Je=new k({actionId:E.ChartPriceScaleMergeAllScalesToLeft,options:{label:Ae,statName:"MergeAllScalesToLeft",onExecute:function(){e.model().mergeAllScales("left")}}}),Qe=new k({actionId:E.ChartPriceScaleMergeAllScalesToRight,options:{label:Le,statName:"MergeAllScalesToRight",onExecute:function(){e.model().mergeAllScales("right")}}}),et=new k({actionId:E.ChartPriceScaleMoveToLeft,options:{label:ke,statName:"MoveScaleToLeft",onExecute:function(){e.model().mergeAllScales("left")}}}),tt=new k({actionId:E.ChartPriceScaleMoveToRight,options:{label:Ee,statName:"MoveScaleToRight",onExecute:function(){e.model().mergeAllScales("right")}}});$e=new k({actionId:E.ChartMoveChartInLayout,options:{label:i.tf(null,void 0,i(456462)),subItems:[new k({actionId:E.ChartMoveChartInLayoutForward,options:{label:i.tf(null,void 0,i(472781)),statName:"MoveChartRight",onExecute:function(){e._chartWidgetCollection.moveActiveChartWithUndo(!1)}}}),new k({actionId:E.ChartMoveChartInLayoutBack,options:{label:i.tf(null,void 0,i(762592)),statName:"MoveChartLeft",onExecute:function(){e._chartWidgetCollection.moveActiveChartWithUndo(!0)}}})]}});var it=n.enabled("show_object_tree");let st;this._options.showFinancialsEnabled&&(st=this._createShowFinancialsAction()),this._actions={chartProperties:O,mainSeriesPropertiesAction:U,scalesProperties:G,timeScaleReset:w,invertSeriesScale:t,logSeriesScale:m,autoSeriesScale:s,lockSeriesScale:o,regularSeriesScale:r,percentSeriesScale:c,indexedTo100SeriesScale:p,compareOrAdd:B,paneObjectTree:it?R:void 0,insertIndicator:N,symbolSearch:f,showSymbolInfoDialog:Xe,changeInterval:C,seriesHide:Y,studyHide:Y,lineToggleLock:q,lineHide:Y,scaleSeriesOnly:Z,drawingToolbarAction:J,stayInDrawingModeAction:se,hideAllMarks:oe,applyTimeZone:v,showCountdown:Ye,addPlusButton:Ke,showSeriesLastValue:Me,showSeriesPrevCloseValue:xe,showSeriesPrevCloseLine:Ie,showBidAskLabels:Ve,showBidAskLines:We,showPrePostMarketPriceLabel:Fe,showPrePostMarketPriceLine:He,showHighLowPriceLabels:Ue,showHighLowPriceLines:je,showAverageClosePriceLabel:Ge,showAverageClosePriceLine:qe,showSymbolLabelsAction:De,showStudyLastValue:Be,showStudyPlotNamesAction:Oe,undo:g,redo:S,mergeLeftScalesAction:Je,mergeRightScalesAction:Qe,moveScaleToLeft:et,moveScaleToRight:tt,moveChartAction:$e};{const e=this._createShowDataWindowAction();e&&(this._actions.showDataWindow=e)}this._actions.chartReset=this._createChartResetAction();const ot=this._createApplyColorThemeAction();ot&&(this._actions.applyColorTheme=ot);const rt=this._createAddToWatchlistAction();if(rt&&(this._actions.addToWatchlist=rt),st&&(this._actions.showFinancials=st),ie&&(this._actions.hideAllDrawingsAction=ie),n.enabled("show_source_code")&&(this._actions.viewSourceCode=new k({actionId:E.ChartIndicatorPineSource,options:{label:Q(i.tf(null,void 0,i(966324))),statName:"OpenSelectedObjectSource",onExecute:this.openSelectedObjectSource.bind(this)}})),!TradingView.onWidget()&&n.enabled("text_notes")&&(this._actions.addToTextNotes=y), null!==Ze&&(this._actions.gotoDate=Ze),this.createSessionBreaksActions(),!this.readOnly()){var nt=this._createRemoveSelectedObjectAction();this._hotkeys.add({handler:function(){this.removeSelectedSources()}.bind(this),desc:"Remove selected source",hotkey:d.isMacKeyboard?46:8}),this._actions.paneRemoveAllStudies=P,this._actions.paneRemoveAllDrawingTools=T,this._actions.paneRemoveAllStudiesDrawingTools=M,this._actions.applyStudiesToAllCharts=I,this._actions.studyRemove=nt,this._actions.lineRemove=nt,n.enabled("property_pages")&&(this._actions.format=L)}this._actions.showPriceLine=new k({actionId:E.ChartLinesToggleSeriesPriceLineVisibility,options:{label:i.tf(null,void 0,i(491492)),checkable:!0,statName:"TogglePriceLine"}}),this._actions.showPriceLine.binding=new a(this._actions.showPriceLine,this.model().mainSeries().properties().showPriceLine,this.model(),Te),this._registerLineToolHotkeys(),this._updateScalesActions()}options(){return this._options}executeActionById(e){if("takeScreenshot"===e)return console.warn('Action "takeScreenshot" is deprecated. Use method "takeScreenshot" instead'),void this._chartWidgetCollection.takeScreenshot();"hideAllDrawingsAction"===e&&console.warn('Action "hideAllDrawingsAction" is deprecated. Use method "hideAllDrawingTools" instead'),e in this._actions?this._actions[e]instanceof k&&this._actions[e].execute():console.warn("Unknown action id: "+e)}getCheckableActionState(e){if(e in this._actions){var t=this._actions[e];if(t instanceof k&&t.isCheckable())return t.isChecked();console.warn("Action "+e+" has no state")}else console.warn("Unknown action id: "+e);return null}_updateScalesActions(){if(null!==this._actions){var e=this.model().mainSeries(),t=e.priceScale(),i=e.properties(),s=t.isLockScale(),o=i.style.value()===r.STYLE_PNF;this._actions.percentSeriesScale.update({disabled:s||o,checked:t.isPercentage()}),this._actions.logSeriesScale.update({disabled:s||o,checked:t.isLog()}),this._actions.regularSeriesScale.update({disabled:s||o,checked:t.isRegular()}),this._actions.indexedTo100SeriesScale.update({disabled:s||o,checked:t.isIndexedTo100()}),this._actions.invertSeriesScale.update({checked:t.isInverted()}),this._actions.lockSeriesScale.update({checked:t.isLockScale()}),this._actions.autoSeriesScale.update({checked:t.isAutoScale(),disabled:t.properties().autoScaleDisabled.value()})}}defaultSymbol(){return this._defSymbol}widget(){return this._mainDiv}_onBackgroundColorChanged(){for(var e=0;e{var t=p.parse(e.version),i=e.lastVersionMaj?p.parse(e.lastVersionMaj):new p(0,0),o={scriptSource:e.source,scriptIdPart:s.scriptIdPart,scriptName:e.scriptName,scriptTitle:e.scriptTitle,version:e.version,isOld:!i.isZero()&&i.major()!==t.major()};TradingView.bottomWidgetBar.activateScriptEditorTab(o)})).fail(y)}}tags(){return this._model?this._model.calculateDefaultTags():[]}state(e,t,i,s){if(this._model){const o=this._model.state(e,t,i,s);return o.chartId=this.id(),o}return this._content?this._content:{}}metaInfo(){var e=this._metaInfo;return this._model&&(e.systemTags=this._model.calculateDefaultTags()),e}onTagsChanged(){return this._tagsChanged}onModelTagsChanged(){this._tagsChanged.fire()}onAboutToBeDestroyed(){return this._aboutToBeDestroyed}destroy(){this._aboutToBeDestroyed.fire(),null!==this._removeMaximizeHotkey&&(this._removeMaximizeHotkey(),this._removeMaximizeHotkey=null),0!==this._drawRafId&&this._parent.ownerDocument.defaultView.cancelAnimationFrame(this._drawRafId),null!==this._backgroundTopColorSpawn&&this._backgroundTopColorSpawn.destroy(),null!==this._backgroundBottomColorSpawn&&this._backgroundBottomColorSpawn.destroy(),null!==this._timingsMeter&&(this._timingsMeter.stopCollect(),this._timingsMeter=null);for(var e=0;e0;)for(var t=this._content.panes[e].sources,i=t.length;i-- >0;)if("MainSeries"===t[i].type)return t[i].state}updateUndoRedo(){this._model&&(this.actions().undo.update({disabled:this._model.undoHistory().undoStack().isEmpty()}),this.actions().redo.update({disabled:this._model.undoHistory().redoStack().isEmpty()}))}createSessionBreaksActions(){var e=new k({actionId:E.ChartSessionBreaksToggleVisibility,options:{label:i.tf(null,void 0,i(259827)),checkable:!0,statName:"ToggleSessionBreaks"}});e.binder=new a(e,this._model.chartModel().sessions().properties().graphics.vertlines.sessBreaks.visible,this.model(),Ie),this._actions.sessionBreaks=e}updateActionForIntradayOnly(e){e&&e instanceof k&&e.update({disabled:this.model().mainSeries().isDWM()})}containsVolume(){return this.model().dataSources().some((function(e){return e instanceof C&&"Volume"===e.metaInfo().shortId}))}containsStudyByPredicate(e){return!!this._model&&this._model.dataSources().some((function(t){if(!(t instanceof C))return!1;var i=t.metaInfo();return e(i)}))}containsStudy(e){return this.containsStudyByPredicate((function(t){return t.id===e||t.fullId===e}))}isSmall(){return this._width()<550||this._height()<300}onWidget(){return this._onWidget}onCmeWidget(){return"cme"===this.widgetCustomer()}widgetCustomer(){return this._widgetCustomer}resize(){var e=this._height()+"px",t=this._width()+"px";this._mainDiv.style.height=e,this._mainDiv.style.width=t,this._elMainTable.style.height=e,this._elMainTable.style.width=t,this._resizeHandler&&this._mainDiv&&this._resizeHandler()}applyOverrides(e){var t={};for(var i in e)i.startsWith("mainSeriesProperties.priceAxisProperties")||(t[i]=e[i]);if(applyPropertiesOverrides(this.properties(),null,!1,t,null),this._model){applyPropertiesOverrides(this._model.model().properties(),null,!1,t),applyPropertiesOverrides(this._model.mainSeries().properties(),null,!1,t,"mainSeriesProperties"),this._model.model().sessions().applyOverrides(t);const e=this._model.chartModel().watermarkSource();null!==e&&e.applyOverrides(t)}}applyStudiesOverrides(e){Y.mergeDefaultsOverrides(e),this._applyStudiesOverrides()}showReplayOrderConfirmationDialog(){return this.model().isInReplay()?new Promise((function(e,t){g({text:i.tf(null,void 0,i(180623)),onConfirm:function(t){e(),t.dialogClose()},onClose:t})})):Promise.resolve()}_addPerfMark(e){ee("ChartWidget."+this._id+"."+e)}getResizerDetacher(){return this._options}}},325050:(e,t,i)=>{"use strict" ;var s=i(650151).assert,o=i(533422).layouts,r=i(176019).createUndoHistory,n=i(885482),a=i(799786),l=i(470316),c=i(251954),h=i(244842),d=i(401580).WatchedValue,u=i(201089).getLogger("Chart.ChartWidgetCollection"),_=i(777466).preventDefaultForContextMenu,p=i(339315),m=i(161590).GeneralChartPropertiesRenderer,g=i(834698).CompareDialogRenderer,S=i(314802).isOnMobileAppPage,v=i(707957).Delegate;const{isSupportedLayout:f,tryGuessingTheMostSuitableLayout:b}=i(533422);var y=i(270294).CollectionViewMode,C=i(850775).mediaState,w=i(744728).SwapChartsUndoCommand,P=i(394905).ToastsFactory,T=i(531005).reconnectChartApi,M=i(397245).marketStatusText;const x=i(541558).randomHash;var I=i(749765),A=I.applyIndicatorsToAllChartsImpl,L=I.applyIndicatorToAllChartsImpl,k=I.lineToolsAndGroupsDTOsImpl,E=I.getStateForChartImpl,D=I.resetLineToolsInvalidatedImpl,N=I.applyLineToolUpdateNotificationImpl,B=I.createClipboardHandler,R=I.chartsSymbolsImpl,O=I.updateLayoutImpl,V=I.computeContentBoxImpl,W=I.getVisuallyAdjacentDefImpl,F=I.setLayoutImpl,H=I.removeChartWidgetSubscriptionsImpl,z=I.generateNewChartId,U=I.syncCrosshairImpl,G=I.createBroadcastChannel,q=I.destroyBroadcastChannel,j=I.syncScrollImpl,Y=I.allInitialModelsCreated,K=I.allInitialSymbolsResolved,Z=I.applyThemeImpl,$=I.isFirstChartInLayout,X=I.deserializedChartIds,J=I.handleDateRangeLockChange,Q=I.handleInternalDateRangeLockChange,ee=I.handleTrackTimeLockChange,te=I.handleInternalTrackTimeLockChange,ie=I.handleIntervalLockChange,se=I.handleInternalIntervalLockChange,oe=I.handleSymbolLockChange,re=I.handleInternalSymbolLockChange,ne=I.handleConnectionLimitReachedChanged,ae=I.createLeftBottomChartWidgetWV,le=I.subscribeToEventsForDateRangeSync,ce=I.unsubscribeFromEventsForDateRangeSync,he=I.syncChartsDateRangesWithActiveChartRange,de=I.subscribeToCompletedEventForDateRangeUpdate,ue=new Map,_e=I.setBrokerImpl,pe={saveChartEnabled:!0,takeScreenshotEnabled:!0,publishedChartsEnabled:!0};e.exports=function(e){var t=this,me=Object.assign({},pe,e),ge=new d,Se=me.readOnly||!1,ve=!1,fe=x(),be=[],ye=0,Ce=new d,we=new d,Pe=new d,Te="s",Me=new d(null),xe=new Map,Ie=new d([]),Ae=new d;Ae.setValue(y.ForceFullscreen);var Le=[];const ke={isConfirmationAboutReplayLocked:!1,loadingChart:!1,setTimeFrameActive:!1,setNewResolution:!1};var Ee=!1,De=!1,Ne=new d(!1),Be=new d(null),Re=new d(!1),Oe=new d(!1);Oe.subscribe((e=>oe(Mt(),e)));var Ve=new d(Oe.value());Ve.subscribe((e=>re(Mt(),e)));var We=new d(!1);We.subscribe((e=>ie(Mt(),e)));var Fe=new d(We.value());Fe.subscribe((e=>se(Mt(),e)));var He=new d(Te),ze=new d(!1);ze.subscribe((e=>ee(Mt(),e)));var Ue=I.combinedTrackTimeLock(He,ze,be);ze.subscribe((e=>ee(Mt(),e)));var Ge=new d(Ue.value());Ge.subscribe((e=>te(Mt(),e)));var qe=new d(!1);qe.subscribe((e=>J(Mt(),e))),Me.subscribe(si);var je=new d(qe.value());je.subscribe((e=>Q(Mt(),e)));var Ye=new d(TVSettings.getBool("chart.syncCrosshair",!0)),Ke=a.createGroup({desc:"Layout"}),Ze=null,$e=null,Xe=null,Je=null,Qe=null;if(window.TVD){var et=window.TVD.crosshairSyncEnabled;et?(et.value()&&(Je=G(Mt)), Qe=et.subscribe((e=>{e?Je=G(Mt):(q(Mt()),Je=null)}))):Je=G(Mt)}var tt=Ye.value();Ye.subscribe((function(e){tt=e=!!e,TVSettings.setValue("chart.syncCrosshair",e);for(var t=0;t{rt.setValue(null===e?null:e.chartWidget)}));var nt=me.widgetOptions||{},at=me.metaInfo||{},lt={id:new d(at.id||null),name:new d(at.name),description:new d(at.description),username:new d(at.username),uid:new d(at.uid),lastModified:new d(at.lastModified)},ct=r();ct.onChange().subscribe(null,(function(e){c.emit("undo_redo_state_changed",e)}));var ht=me.resizerBridge.container.value();ht.addEventListener("contextmenu",_);var dt,ut=new v,_t=new v,pt=new v,mt=new d(!1),gt=new d(null),St=null,vt=null;me.seriesControlBarEnabled&&(dt="0px",gt.setValue(document.createElement("div")),gt.value().style.left=dt,gt.value().style.right=dt,gt.value().style.bottom=dt,gt.value().classList.add("chart-toolbar","chart-controls-bar"),gt.value().setAttribute("data-is-chart-toolbar-component","true"),ht.appendChild(gt.value()),Promise.all([i.e(52576),i.e(22666),i.e(5993),i.e(4015),i.e(53842),i.e(66639),i.e(30006),i.e(5145),i.e(35649),i.e(46036),i.e(91033),i.e(58056),i.e(67080),i.e(15518),i.e(99916),i.e(45166),i.e(64619),i.e(79497),i.e(50690),i.e(33950),i.e(47260)]).then(i.bind(i,648393)).then((({BottomToolbarRenderer:e})=>{var i=me.resizerBridge,s=[i.container.spawn(),i.width.spawn(),i.height.spawn()],o=i.container.value(),r=function(){var e=o.getBoundingClientRect(),t=V(Mt());return t.top=e.top+t.top,t.left=e.left+t.left,t},n=new v,a=function(){n.fire()};s.forEach((function(e){e.subscribe(a)}));var l=function(){s.forEach((function(e){e.destroy()})),n.destroy(),window.ChartApiInstance.connectionsLimitReached().unsubscribe(ne)};St=new e(gt.value(),n,r,t,ChartApiInstance,nt,me.seriesControlBar),vt=function(){null!==St&&(St.destroy(),St=null,gt.value().remove(),gt.setValue(null)),l()}})));var ft=new m(t),bt=new g(t),yt=null;function Ct(){mt.setValue(be.some((e=>{const t=e.chartWidget.lineToolsSynchronizer();return null!==t&&t.hasChanges().value()})))}function wt(e){return I.checkProFeatureImpl(Mt(),e)}yt=new P(me.resizerBridge,(function(){return gt.value()?gt.offsetHeight:0})),window.ChartApiInstance.connectionsLimitReached().subscribe(ne,{callWithLast:!0}),Be.subscribe((()=>kt()));const Pt=new Map,Tt=()=>I.updateLinkingGroupCharts(Mt());function Mt(){return{undoHistory:ct,chartWidgetsDefs:be,chartsCountToSave:xt,actualLayoutCount:It,savedChartWidgetOptions:Le,activeChartWidget:ge,options:me,parent:ht,toastsFactory:yt,crosshairLockRaw:tt,crossHairSyncBroadcast:Je,setChartStorageNotificationSubscription:e=>{$e=e},maximizedChartDef:ot,setMaximized:Ft,layoutTemplate:Pe,widthWV:it,heightWV:st,checkProFeature:wt,lineToolsSynchronizerHasChanges:mt,recalcHasChanges:Ct,onZoom:_t,onScroll:pt,layoutType:Te,layoutWV:He,setLayoutType:e=>{Te=e},isPhoneSize:Ne,viewMode:Ae,updateViewMode:zt, loadingContent:Ee,setLoadingContent:e=>{Ee=e},initialLoading:De,inlineChartsCount:we,updateWatchedValue:Ut,checkAllPendingModelsAlreadyCreated:Ht,readOnly:Se,symbolLock:Oe,internalSymbolLock:Ve,intervalLock:We,internalIntervalLock:Fe,dateRangeLock:je,internalDateRangeLock:je,trackTimeLock:ze,internalTrackTimeLock:Ge,crosshairLock:Ye,customLegendWidgetsFactoriesMap:ui,globalDetachable:Ce,saveChartService:Ze,customSources:hi,updateActivityView:Gt,chartWidgetCreatedDelegate:ut,sizingState:Be,currentLayoutResizeAction:Me,allLayoutSizesState:xe,splitters:Ie,widgetOptions:nt,bottomToolbar:gt,replayContainer:di,layoutSizesChanged:Re,subscribeToCompletedEventForDateRangeSync:(e,t)=>de(Mt(),e,t),subscribeToEventsForDateRangeSync:e=>le(Mt(),e),unsubscribeFromEventsForDateRangeSync:e=>ce(Mt(),e),syncChartsDateRangesWithActiveChartRange:e=>he(Mt(),e),combinedTrackTimeLock:Ue,chartWidgetIdToCompletedCallbackMap:ue,flags:ke,linkingGroupsCharts:Pt,updateLinkingGroupCharts:Tt}}function xt(){return be.length+Le.length}function It(){return o[Te].count}function At(e,t,i,s,o){return E(Mt(),e,t,i,s,o)}function Lt(e){return e.value()?1:0}function kt(){O(Mt())}it.subscribe(kt),st.subscribe(kt),this.updateLayout=kt;const Et=I.activeLinkingGroupWV(ge),Dt=I.allLinkingGroupsWV(Mt());var Nt;Ne.setValue(!1);var Bt=["phone","phone-vertical"];function Rt(e,t){me.mobileForceChartMaximizeEnabled&&(!Bt.includes(C.device)||t&&Bt.includes(t)?Bt.includes(C.device)||t&&!Bt.includes(t)||Ne.setValue(!1):Ne.setValue(!0))}function Ot(){if(window.is_authenticated){var e=h.enabled("app_phone");!h.enabled("app_tablet")&&(e||Ne.value())?Ae.value()===y.ForceFullscreen&&(Nt=ot.value(),ge.value().requestFullscreen()):Nt||(Ft(null),zt())}}function Vt(e){return e.rdState.owner.value()!==e}function Wt(e){return F(Mt(),e,t)}function Ft(e){ot.value()!==e&&(ot.setValue(e),Wt(Te))}function Ht(){be.every((e=>e.chartWidget.hasModel()))&&(Ut(),c.emit("layout_changed"))}function zt(){"s"===Te||ot.value()?Ae.setValue(y.ForceFullscreen):Ae.setValue(y.Multichart)}function Ut(){var e=Math.min(Pe.value().count,be.length)-1;if(e<0)ge.deleteValue();else{var t=ye;t<0&&(t=0),t>e&&(t=e),ge.setValue(be[t].chartWidget)}}function Gt(){for(var e=be.length;e--;){var t=e===ye;be[e].container.value().classList.toggle("active",t),be[e].container.value().classList.toggle("inactive",!t)}}function qt(e){0}function jt(e,t){return W(Mt(),e,t)}function Yt(e){var t=jt(be[ye],e);qt(t?t.chartWidget:ge.value()),t&&(ge.setValue(t.chartWidget),ot.value()&&Wt(Te))}const Kt=new v;function Zt(e,t){var i=be.findIndex((function(t){return t.chartWidget===e})),s=be.findIndex((function(e){return e.chartWidget===t}));if(-1===i||-1===s)throw new Error("chart is not in the layout");var o=be[i],r=be[s];be[i]=r,be[s]=o,ye===i?ye=s:ye===s&&(ye=i),kt(),Kt.fire()}var $t=new v,Xt=new d,Jt=new d([]),Qt=null;function ei(e){var t=e.mainSeries().properties();t.style.subscribe(null,ti),ti(t.style),e.model().onSelectedSourceChanged().subscribe(null,ii),qe.value()&&(le(Mt(),e),he(Mt())),ii(e.selection().allSources())} function ti(e){Xt.setValue(e.value())}function ii(){var e=Qt.model();Jt.setValue(e.selection().allSources())}function si(e){qe.value()&&null===e&&he(Mt())}ge.subscribe((function(e){if(e){for(var t,i=be.length;i--;)if(be[i].chartWidget===e){t=i;break}if(!isFinite(t))throw new Error("Cannot make detached ChartWidget active");if(ye!==t){ot.value()&&(Vt(be[t])||ot.setValue(be[t])),ye=t,Gt();for(i=be.length;i--;)be[i].chartWidget!==e&&be[i].chartWidget.setActive(!1);Ci(),e.setActive(!0),n.activePointSelectionMode.setValue(e.selectPointMode().value())}!function(e){if(Qt!==e){if(Qt&&(Qt.modelCreated().unsubscribe(null,ei),Qt.hasModel())){var t=Qt.model();qe.value()&&ce(Mt(),t),t.mainSeries().properties().style.unsubscribe(null,ti),t.model().onSelectedSourceChanged().unsubscribe(null,ii),Qt=null}e&&(Qt=e,e.hasModel()?ei(e.model()):e.modelCreated().subscribe(null,ei))}}(e)}}),{callWithLast:!0});var oi=new v;function ri(){me.resizerBridge.requestFullscreen()}function ni(){me.resizerBridge.exitFullscreen()}function ai(){return me.resizerBridge.fullscreenable}function li(){return me.resizerBridge.fullscreen}function ci(e){if(0!==be.length){for(var t=be.length;t--;)be[t].chartWidget.setActive(!1);be[ye].chartWidget.setActive(e)}}Se||(Ke.add({desc:"Switch active chart",hotkey:h.enabled("accessible_keyboard_shortcuts")?l.Modifiers.Shift+39:9,handler:function(){Yt(!1)}}),Ke.add({desc:"Switch active chart",hotkey:h.enabled("accessible_keyboard_shortcuts")?l.Modifiers.Shift+37:l.Modifiers.Shift+9,handler:function(){Yt(!0)}})),Ke.add({desc:"Fullscreen mode",hotkey:l.Modifiers.Shift+70,isDisabled:h.enabled("widget")||!ai().value(),handler:function(){li().value()?ni():ri()}}),me.takeScreenshotEnabled&&(Ke.add({desc:"Screenshot server",hotkey:l.Modifiers.Alt+83,handler:I.takeServerScreenshot.bind(this,me.snapshotUrl,t)}),S("any")||(Ke.add({desc:"Download client screenshot",hotkey:l.Modifiers.Mod+l.Modifiers.Alt+83,handler:I.downloadScreenshot.bind(this,t)}),Ke.add({desc:"Copy client screenshot",hotkey:l.Modifiers.Mod+l.Modifiers.Shift+83,handler:I.copyScreenshotToClipboard.bind(this,t)}))),me.saveChartEnabled&&Ke.add({desc:"Save Chart Layout",hotkey:l.Modifiers.Mod+83,handler:function(){$t.fire()}});var hi=new Map,di=null,ui=new Map;const _i=B(Mt());me.globalEvents&&_i.listen();const pi=Oe.spawn(),mi=We.spawn(),gi=qe.spawn(),Si=ze.spawn(),vi=Ye.spawn(),fi=()=>be.map((e=>e.chartWidget)),bi=ae(fi,He.readonly(),Kt,ut);function yi(e,t){if(Ee=!0,De=Boolean(t),Le.splice(0),e){if(e.charts||(e={layout:"s",charts:[e]}),e.layoutsSizes)for(const t of Object.keys(e.layoutsSizes))xe.set(t,e.layoutsSizes[t]);var i=new Set;e.charts.forEach((function(e){e.chartId&&i.add(e.chartId)})),e.charts.forEach((function(e){if(!e.chartId){var t=z((function(e){return i.has(e)}));i.add(t),e.chartId=t}}));let t=e.layout;if(!f(t)){const e=b(t);u.logError(`Loading unsupported layout ${t}. Force migration to ${e}`),t=e}Te=wt(t||"s");for(var s=0;srt.readonly(),leftBottomChartWidget:()=>bi,activeLinkingGroup:()=>Et,allLinkingGroups:()=>Dt,linkingGroupsCharts:e=>I.getLinkingGroupCharts(Mt(),e).readonly(),destroy:function(){if(oi.fire(),ci(!1),null!==vt&&(vt(),vt=null),H(Mt()),pi.destroy(),mi.destroy(),Si.destroy(),gi.destroy(),Ue.destroy(),vi.destroy(),Me.unsubscribe(si),be.forEach((function(e){void 0!==e.timingsMeter&&e.timingsMeter.destroy(),e.chartWidget.linkingGroupIndex().unsubscribe(Tt),e.chartWidget.destroy()})),me.resizerBridge.remove(),Ie.value().forEach((e=>{e.mouseHandler.destroy(),e.mouseListener.destroy()})),window.removeEventListener("resize",kt),C.off("changeDevice",Rt),me.mobileForceChartMaximizeEnabled&&!me.handleMaximizedChartOnResizeDisabled&&C.off("changeDevice",Ot),n.tool.unsubscribe(Ci),n.tool.unsubscribe(wi),ht.remove(),hi.clear(),ui.clear(),Ke.destroy(),$e&&$e.destroy(),_i&&_i.destroy(),Xe&&Xe.destroy(),Et.destroy(),Dt.destroy(),window.TVD){const e=window.TVD.crosshairSyncEnabled;e&&e.unsubscribe(Qe),q(Mt())}bi.destroy(),ve=!0},onAboutToBeDestroyed:oi,layout:He.readonly(),setLayout:Wt,activeChartWidget:ge,viewMode:Ae,activeChartStyle:Xt.readonly(),setChartStyleToWidget:I.setChartStyleToWidget.bind(this),selectedSources:Jt.readonly(),metaInfo:lt,state:function(e,i,s,o){for(var r=[],n=xt(),a=0;a{c.layoutsSizes[t]=e})),c},lineToolsAndGroupsDTOs:function(){return k(Mt())},resetLineToolsInvalidated:function(e,t){return D(Mt(),e,t)},applyLineToolUpdateNotification:N.bind(null,be),readOnly:function(){return Se},onZoom:function(){return _t},onScroll:function(){return pt},resizerBridge:function(){return me.resizerBridge},lock:{symbol:pi,interval:mi,dateRange:gi,crosshair:vi,trackTime:Si},setSymbol:(e,t)=>I.setSymbol(Mt(),e,t),setSymbolAll:(e,t)=>I.setSymbolAll(Mt(),e,t),setResolution:(e,t,i)=>I.setResolution(Mt(),e,t,i),setTimeFrame:function(e){ke.loadingChart||ke.setTimeFrameActive||(ke.setTimeFrameActive=!0,We.value()?be.forEach((function(t){t.chartWidget.loadRange(e)})):ge.value().loadRange(e),ke.setTimeFrameActive=!1)},updateLayout:kt,setChartLayoutWithUndo:function(e){ return I.setChartLayoutWithUndoImpl(Mt(),this,e)},images:I.getSnapshot.bind(this,this,me.widgetOptions.customerReadableName,nt.onWidget),clientSnapshot:I.getClientSnapshot.bind(this,this,me.widgetOptions.customerReadableName,nt.onWidget),tags:function(){for(var e=[],t=0;tU(Mt(),e,t,i,s),syncScroll:function(e,t){return j(Mt(),e,t)},clearChartMetaInfo:function(){lt.id.setValue(null),lt.uid.setValue(void 0),lt.name.setValue(void 0)},takeScreenshot:I.takeScreenshot.bind(this,me.snapshotUrl,this),takeServerScreenshot:I.takeServerScreenshot.bind(this,me.snapshotUrl,this),loadContent:yi,purgeUnusedWidgets:function(){for(var e=o[Te].count;e1},applyIndicatorToAllCharts:async function(e,t,i,s){await L(Mt(),e,t,i,s)},setActive:ci,inlineChartsCount:we.readonly(),revertToInline:function(){if(!Ne.value()||Ae.value()!==y.ForceFullscreen){Ft(null);for(var e=0;ekt())),kt()},destroyReplayWidget:function(){s(null!==di,"Cannot remove replay container, container is not created"),di.remove(),di=null,kt()},setViewMode:function(e){Ae.setValue(e)},moveActiveChartWithUndo:function(e){var t=be[ye],i=jt(t,e);i&&ct.pushUndoCommand(new w(Zt,t.chartWidget,i.chartWidget))},activeChartCanBeMoved:function(){return!(Se||we.value()<2||Vt(be[ye]))},generalPropertiesDefinitions:function(){return ge.value().generalPropertiesDefinitions()},reconnectChartApi:function(e){T(e)},setBroker:function(e){_e(Mt(),e)},setSaveChartService:function(e){Ze=e;for(var t=0;tRe,clientId:fe,ariaDescribeChart:qt}),I.createChartStorageSubscriptionsIfRequired(this,Mt()),yi(me.content,!0),I.createChartWidgetCollectionNewsNotifier(this,Mt()).then((e=>{ve||(Xe=e)})),He.subscribe((function(){Gt()})),He.hook=function(e){return e===this.value()?e:wt(e)},Se&&(He.writeLock=!0),window.addEventListener("resize",kt),me.mobileForceChartMaximizeEnabled&&(C.on("changeDevice",Rt),me.handleMaximizedChartOnResizeDisabled||C.on("changeDevice",Ot),Rt(),Ot());var Pi=0;function Ti(){0===--Pi&&c.emitOnce("onChartReady")}be.forEach((function(e){if(e){Pi++;var t=e.chartWidget;t.withModel(null,(function(){me.metaInfo&&t.model().model().setChartSaveTime(1e3*me.metaInfo.lastModified);var e=t.model().mainSeries();if(e.bars().size()>0||e.isFailed())Ti();else{var i=e.dataEvents(),s=function(){Ti(),i.barReceived().unsubscribe(null,s),i.completed().unsubscribe(null,s),i.error().unsubscribe(null,s)};i.barReceived().subscribe(null,s),i.completed().subscribe(null,s),i.error().subscribe(null,s)}}))}})),Y(Mt()).then(K).then((function(){window.saver&&window.is_authenticated&&me.widgetOptions.justCloned&&window.saver.saveChartSilently()})).catch(u.logError.bind(u))}},228018:(e,t,i)=>{"use strict";i.d(t,{clientSnapshot:()=>I,widgetClientSnapshot:()=>L});var s,o,r=i(327714),n=i(650151),a=i(86441),l=i(724377),c=i(86746),h=i(674981),d=i(199471),u=i(422333),_=i(511131),p=i(429874),m=i(934976),g=(i(244842),i(776351));const S=Boolean(null===(o=null===(s=window.initData)||void 0===s?void 0:s.logo)||void 0===o?void 0:o.no_powered_by);function v(e,t=null,i=null){let s={};if("number"==typeof e)return{relativePositions:{[e]:{l:t,t:i}},nextElementLeft:e,nextElementTop:e} ;const[o,...r]=e;if("v"===o){let e=null;for(const o of r){const r=v(o,t,i);s={...s,...r.relativePositions},i=r.nextElementTop,e=r.nextElementLeft}t=e}if("h"===o){let e=null;for(const o of r){const r=v(o,t,i);s={...s,...r.relativePositions},t=r.nextElementLeft,e=r.nextElementTop}i=e}return{relativePositions:s,nextElementTop:i,nextElementLeft:t}}const f=function(e){const t={};for(const i of Object.keys(e)){const s=v(e[i]).relativePositions;t[i]=s}return t}(m);function b(e,t,i,s){let o=Math.round(10*s),r=Math.round(10*s);const n=i[e];if(null!==n.l){const e=b(n.l,t,i,s);o=e.x+e.width+Math.round(5*s)}if(null!==n.t){const e=b(n.t,t,i,s);r=e.y+e.height+Math.round(5*s)}const a=t[e];return{x:o,y:r,width:a.width,height:a.height}}function y(e,t,i){var s;const o=(new DOMParser).parseFromString(g,"image/svg+xml");null===(s=null==o?void 0:o.firstElementChild)||void 0===s||s.setAttribute("color",i);const r=URL.createObjectURL(new Blob([(new XMLSerializer).serializeToString(o)],{type:"image/svg+xml"}));return new Promise((i=>{const s=new Image;s.width=e,s.height=t,s.onload=()=>{i({image:s,width:e,height:t})},s.src=r}))}function C(e,t,i,s,o){e.save(),e.drawImage(s.image,t,i,s.width,s.height),e.textBaseline="bottom";const r=(t+s.width)/o+3,n=(i+s.height)/o;(0,d.drawScaled)(e,o,o,(()=>{e.fillText("TradingView",r,n)})),e.restore()}function w(e,t,i,s){return(0,d.drawScaled)(e,s,s,(()=>{e.fillText(i,t.x/s,t.y/s)})),e.measureText(i).width*s}function P(e,t,i,s,o,r){const n=o.map((e=>e.text)).join("");let l=i.x;const c=function(e,t,i,s){if(e.measureText(t).width*s<=i)return{text:t,elided:!1};const o=e.measureText("...").width*s,r=[];for(let e=0;ee.measureText(t.slice(0,n+1)).width*s+o>i));return{text:(t=t.slice(0,n)).trim(),elided:!0}}(e,n,s-l,t);if(c.elided&&!r)return null;const d=[];let u=0;for(const e of o){if(u+e.text.length>c.text.length)break;d.push(e.text),u+=e.text.length}const _=d.join("").trim().length;u=0;for(const s of o){if(u+s.text.length>_)break;s.color&&(e.save(),e.fillStyle=s.color),l+=w(e,new a.Point(l,i.y),s.text,t),s.color&&e.restore(),u+=s.text.length}return c.elided&&(l+=w(e,new a.Point(l,i.y),"...",t)),l}function T(e){return e.map((e=>({...e,title:""})))}function M(e,t){const i=[{text:e.trim()}];for(const e of t)e.visible&&(""!==i[i.length-1].text&&i.push({text:" "}),e.title&&i.push({text:e.title}),i.push({text:e.value,color:e.color}));return i}class x{constructor(e,t){this._logoTextColor=null,this._snapshotData=e,t=t||{},this._options={backgroundColor:p.themes[e.theme].getThemedColor("color-bg-primary"),borderColor:p.themes[e.theme].getThemedColor("color-border"),font:u.CHART_FONT_FAMILY,fontSize:12,legendMode:"vertical",hideResolution:!1,showHeaderPublishedBy:!1,showHeaderMainSymbol:!1,...t};const i=f[e.layout],s=e.charts.map((e=>function(e){const t=e.panes[0],i=t.canvas.width+t.leftAxis.canvas.width+t.rightAxis.canvas.width;let s=0;for(const t of e.panes)s+=t.canvas.height ;return void 0!==e.timeAxis&&0!==e.timeAxis.contentHeight&&(s+=e.timeAxis.canvas.height),(0,r.size)({width:i,height:s})}(e)));if(this._pixelRatio=e.hidpiRatio,this._chartsGeometry=e.charts.map(((e,t)=>b(t,s,i,this._pixelRatio))),!S){let i=e.theme;void 0!==t.backgroundColor&&(i="black"===(0,l.rgbToBlackWhiteString)((0,l.parseRgb)(t.backgroundColor),150)?c.StdTheme.Dark:c.StdTheme.Light),this._logoTextColor=p.themes[i].getThemedColor("color-text-primary")}this._headerDefaultTextColor=p.themes[e.theme].getThemedColor("color-text-primary")}async getImage(){const e=this._pixelRatio;let t=0,i=0,s=0;const o=this._headerItems();if(o.length>0){s=Math.ceil(1.4*this._options.fontSize*e)*o.length}i+=s;let n=0,l=0;for(const e of this._chartsGeometry)n=Math.max(n,e.x+e.width),l=Math.max(l,e.y+e.height);const c=i;t+=n,i+=l,t+=Math.round(10*e);const h=S?Math.round(10*e):Math.round(35*e),p=i;i+=h;const m=(0,d.createDisconnectedCanvas)(document,(0,r.size)({width:t,height:i}),1),g=(0,d.getContext2D)(m);g.font=(0,_.makeFont)(this._options.fontSize,this._options.font),g.textBaseline="top",g.fillStyle=this._options.backgroundColor,g.fillRect(0,0,t,i),o.length>0&&this._drawHeader(g,o,t,new a.Point(Math.round(10*e),Math.round(10*e)));for(let e=0;e0&&t.leftAxis.contentHeight>0&&(i.drawImage(t.leftAxis.canvas,s,o),s+=t.leftAxis.canvas.width),i.drawImage(t.canvas,s,o),s+=t.canvas.width,t.rightAxis.contentWidth>0&&t.rightAxis.contentHeight>0&&i.drawImage(t.rightAxis.canvas,s,o),"pane"===t.type&&(i.fillStyle=e.colors.text,this._drawLegend(t,i,new a.Point(r,l),n)),o+=t.canvas.height}if(void 0!==e.timeAxis&&0!==e.timeAxis.contentHeight){let t=0;e.timeAxis.lhsStub.contentWidth>0&&e.timeAxis.lhsStub.contentHeight>0&&(i.drawImage(e.timeAxis.lhsStub.canvas,t,o),t+=e.timeAxis.lhsStub.canvas.width),i.drawImage(e.timeAxis.canvas,t,o),t+=e.timeAxis.canvas.width,e.timeAxis.rhsStub.contentWidth>0&&e.timeAxis.rhsStub.contentHeight>0&&i.drawImage(e.timeAxis.rhsStub.canvas,t,o)}i.strokeStyle=this._options.borderColor,i.strokeRect(0,0,t.width,t.height),i.restore()}_headerItems(){var e,t,i,s;const o=[];if(this._options.showHeaderPublishedBy&&this._snapshotData.publishedBy)for(const e of this._snapshotData.publishedBy)o.push([{text:e}]);if(this._options.showHeaderMainSymbol){const r=this._snapshotData.charts[0],n=`${null===(e=r.meta)||void 0===e?void 0:e.symbol}, ${null===(t=r.meta)||void 0===t?void 0:t.resolution}` ;o.push(M(n,null!==(s=null===(i=r.meta)||void 0===i?void 0:i.values)&&void 0!==s?s:[]))}return o}_drawHeader(e,t,i,s){e.save(),e.fillStyle=this._headerDefaultTextColor;const o=Math.ceil(1.4*this._options.fontSize*this._pixelRatio);t.forEach(((t,r)=>{P(e,this._pixelRatio,new a.Point(s.x,s.y+o*r),i,t,!0)})),e.restore()}_drawLegend(e,t,i,s){let o=!0;const r=Math.ceil(1.4*this._options.fontSize*this._pixelRatio);let l=i.x,c=i.y;if(e.mainSeriesText&&c+r0){o=Math.ceil(1.4*this._options.fontSize*e)*n.length}s+=o;const l=s,c=this._widgetSnapshot.canvas.width,h=this._widgetSnapshot.canvas.height;i+=c+2*t,s+=h+t;const p=Math.round(35*e),m=s;s+=p;const g=(0,d.createDisconnectedCanvas)(document,(0,r.size)({width:i,height:s}),1),S=(0,d.getContext2D)(g);if(S.font=(0,_.makeFont)(this._options.fontSize,this._options.font),S.textBaseline="top",S.fillStyle=this._options.backgroundColor,S.fillRect(0,0,i,s),n.length>0&&this._drawHeader(S,n,i,new a.Point(t,t)),S.drawImage(this._widgetSnapshot.canvas,t,t+l),S.strokeStyle=this._options.borderColor,S.strokeRect(t,t+l,c,h),null!==this._logoTextColor){const i=await y(Math.round(20*e),Math.round(15*e),this._logoTextColor);S.fillStyle=this._logoTextColor,S.font=(0,_.makeFont)(13,u.CHART_FONT_FAMILY);C(S,t,m+Math.round(p/2-i.height/2),i,e)}return g}_headerItems(){const e=[];if(this._options.showHeaderPublishedBy&&this._widgetSnapshot.publishedBy)for(const t of this._widgetSnapshot.publishedBy)e.push([{text:t}]);return e}_drawHeader(e,t,i,s){e.save(),e.fillStyle=this._headerDefaultTextColor;const o=Math.ceil(1.4*this._options.fontSize*this._pixelRatio);t.forEach(((t,r)=>{ P(e,this._pixelRatio,new a.Point(s.x,s.y+o*r),i,t,!0)})),e.restore()}}async function L(e,t){return new A(e,t).getImage()}},783375:(e,t,i)=>{"use strict";i.d(t,{ContextMenuManager:()=>s});var s,o=i(674981),r=i(373571),n=i(224743);!function(e){let t=null,s=null;const a=[],l={createAction:e=>new r.Action({actionId:"Chart.CustomActionId",options:e}),createAsyncAction:e=>new r.Action({actionId:"Chart.CustomActionId",options:{},optionsLoader:e}),createSeparator:()=>new r.Separator};async function c(e,r={},n={menuName:""},c){null!==t&&(e=await t(e,l,n));let d=null;const u=()=>{const e=(0,o.indexOf)(a,(e=>e.renderer===d));-1!==e&&a.splice(e,1),void 0!==c&&c()};let _=!1;if(null!==s&&(d=await s(e,n,u)),d)_=!0,h();else{const t=await Promise.all([i.e(53842),i.e(93502),i.e(66639),i.e(35649),i.e(99916),i.e(36956),i.e(98149),i.e(36752),i.e(3982),i.e(50690),i.e(21065),i.e(91584)]).then(i.bind(i,639051));d=new t.ContextMenuRenderer(e,r,u,h)}return a.push({renderer:d,isExternal:_}),d}function h(){(0,n.globalCloseMenu)(),a.forEach((e=>{e.isExternal&&e.renderer.isShown()&&e.renderer.hide()}))}e.createMenu=c,e.showMenu=function(e,t,i={},s,o){return c(e,i,s,o).then((e=>e.show(t)))},e.setCustomRendererFactory=function(e){s=e},e.setCustomItemsProcessor=function(e){t=e},e.hideAll=h,e.getShown=function(){for(let e=0;e{"use strict";i.d(t,{createAddNoteAction:()=>l});var s=i(444372),o=i(373571),r=i(470316),n=i(396231),a=i(982368);function l(e,t,l){return new o.Action({actionId:"Note.Create",options:{iconId:"TextNote.Add",icon:a.icons.get("TextNote.Add"),label:s.t(null,void 0,i(534999)),statName:"AddToTextNotes",onExecute:()=>{window.runOrSignIn((()=>{var t;null===(t=window.widgetbar)||void 0===t||t.setPage("base"),(0,n.createSymbolNote)(e.symbolWV().value(),l)}),{source:"Add text note in chart context menu"})},hotkeyHash:r.Modifiers.Alt+78,...t}})}},993294:(e,t,i)=>{"use strict";i.d(t,{createSymbolSearchAction:()=>l});var s=i(444372),o=i(373571),r=i(167975),n=i(560420),a=i(244842);function l(){return new o.Action({actionId:"Chart.Dialogs.ShowChangeSymbol",options:{label:(0,r.appendEllipsis)(s.t(null,void 0,i(128089))),statName:"ChangeSymbol",onExecute:()=>{(0,n.showDialog)({defaultValue:"",trackResultsOptions:{trackResults:!a.enabled("widget"),emptySearchType:"empty_result__supercharts"}})}}})}},794349:(e,t,i)=>{"use strict";var s;i.d(t,{TabNames:()=>s}),function(e){e.background="Background",e.coordinates="Coordinates",e.drawings="Drawings",e.events="Events",e.eventsAndAlerts="Events & Alerts",e.inputs="Inputs",e.properties="Properties",e.scales="Scales",e.legend="Legend",e.sourceCode="Source Code",e.style="Style",e.symbol="Symbol",e.timezoneSessions="Timezone/Sessions",e.trading="Trading",e.visibility="Visibility",e.text="Text"}(s||(s={}))},175070:(e,t,i)=>{"use strict";i.d(t,{getPriceAxisNameInfo:()=>n});const s=["Z","Y","X","W","V","U","T","S"],o=["A","B","C","D","E","F","G","H"];class r{constructor(e){this.label=e}equals(e){ return null!==e&&this.label===e.label}}function n(e,t){const i="left"===e?s:o;return new r(t{"use strict";i.d(t,{KineticAnimation:()=>n});var s=i(650151);function o(e,t){return e.position-t.position}function r(e,t,i){const s=(e.position-t.position)/(e.time-t.time);return Math.sign(s)*Math.min(Math.abs(s),i)}class n{constructor(e,t,i,s){this._position1=null,this._position2=null,this._position3=null,this._position4=null,this._animationStartPosition=null,this._durationMsecs=0,this._speedPxPerMsec=0,this._minSpeed=e,this._maxSpeed=t,this._dumpingCoeff=i,this._minMove=s}addPosition(e,t){if(null!==this._position1){if(this._position1.time===t)return void(this._position1.position=e);if(Math.abs(this._position1.position-e)50)return;let i=0;const s=r(this._position1,this._position2,this._maxSpeed),n=o(this._position1,this._position2),a=[s],l=[n];if(i+=n,null!==this._position3){const e=r(this._position2,this._position3,this._maxSpeed);if(Math.sign(e)===Math.sign(s)){const t=o(this._position2,this._position3);if(a.push(e),l.push(t),i+=t,null!==this._position4){const e=r(this._position3,this._position4,this._maxSpeed);if(Math.sign(e)===Math.sign(s)){const t=o(this._position3,this._position4);a.push(e),l.push(t),i+=t}}}}let c=0;for(let e=0;e{"use strict";i.d(t,{icons:()=>s});const s=["🔶","🍀","💧","❤️","💩"]},453817:(e,t,i)=>{"use strict";i.d(t,{LayoutChartsSyncContextMenuAction:()=>a});var s=i(861814),o=i(444372),r=i(373571),n=i(12943);class a extends r.Action{constructor(e,t){const a={icon:s,statName:"SetLayoutChartsSyncGroup",label:o.t(null,void 0,i(680818))};super({actionId:"Chart.LinkingGroupSync",options:{...a,subItems:n.icons.map(((t,i)=>new r.Action({actionId:"Chart.LinkingGroupSync.ChangeGroup",options:{label:t,checkable:!0,checked:e.value()===i,onExecute:()=>this._setLinkingGroupIndexImpl(i)}})))},customActionOptions:{...a,subItems:[new r.Action({actionId:"Chart.LinkingGroupSync.ChangeGroup",options:{},optionsLoader:async()=>{ const[e,{LayoutChartsSyncContextMenuItem:t}]=await Promise.all([Promise.resolve().then(i.t.bind(i,50959,19)),Promise.all([i.e(68992),i.e(81643),i.e(18182),i.e(9988),i.e(10184)]).then(i.bind(i,339148))]);return{doNotCloseOnClick:!1,noInteractive:!0,jsxLabel:e.createElement(t,{active:this._linkingGroupIndex,icons:n.icons,onClick:e=>{this._setLinkingGroupIndexImpl(e)}})}}})]}}),this._setLinkingGroupIndexImpl=e=>{this._setLinkingGroupIndex(this._linkingGroupIndex.value()===e?null:e)},this._linkingGroupIndex=e.spawn(),this._setLinkingGroupIndex=t}}},521506:(e,t,i)=>{"use strict";i.d(t,{lineToolsSelectHotkeys:()=>o});i(586463);var s=i(470316);const o={LineToolFibRetracement:{hash:s.Modifiers.Alt+70,action:"setTool",description:"Draw Fib Retracement"},LineToolHorzLine:{hash:s.Modifiers.Alt+72,action:"drawRightThere",description:"Draw Horizontal Line here"},LineToolHorzRay:{hash:s.Modifiers.Alt+74,action:"drawRightThere",description:"Draw Horizontal Ray here"},LineToolRectangle:{hash:s.Modifiers.Alt+s.Modifiers.Shift+82,action:"setTool",description:"Draw Rectangle"},LineToolTrendLine:{hash:s.Modifiers.Alt+84,action:"setTool",description:"Draw Trend Line"},LineToolVertLine:{hash:s.Modifiers.Alt+86,action:"drawRightThere",description:"Draw Vertical Line here"},LineToolCrossLine:{hash:s.Modifiers.Alt+67,action:"drawRightThere",description:"Draw Cross Line here"}}},535503:(e,t,i)=>{"use strict";i.d(t,{actualBehavior:()=>a,availableValues:()=>n,navigationButtonsVisibilityKey:()=>o,property:()=>r,restoreNavigationButtonsVisibilitySettingsValue:()=>l});var s=i(87053);const o="NavigationButtons.visibility",{property:r,availableValues:n,actualBehavior:a,restoreDefaultValue:l}=(0,s.createVisibilityController)(o)},939702:(e,t,i)=>{"use strict";i.d(t,{actualBehavior:()=>a,availableValues:()=>n,property:()=>r,restorePaneButtonsVisibilitySettingsValue:()=>l});var s=i(87053),o=i(535503);const{property:r,availableValues:n,actualBehavior:a,restoreDefaultValue:l}=(0,s.createVisibilityController)("PaneButtons.visibility",o.navigationButtonsVisibilityKey)},779196:(e,t,i)=>{"use strict";i.d(t,{performanceTestMode:()=>n});var s=i(125226),o=i(638456),r=i(314802);const n=navigator.userAgent.toLowerCase().indexOf("chrome")>-1&&-1===navigator.userAgent.toLowerCase().indexOf("edge")&&!o.CheckMobile.any()&&!(0,r.isOnMobileAppPage)("any")&&!window.TVD&&!(0,o.onWidget)()&&(0,s.isFeatureEnabled)("performance_test_mode")&&!window.matchMedia("(prefers-reduced-motion)").matches},608415:(e,t,i)=>{"use strict";i.d(t,{ActionBinder:()=>s});class s{constructor(e,t,i,s,o=null){this._property=t,this._undoModel=i,this._undoText=s,this._action=e,this.setValue(t.value()),t.subscribe(this,this._propertyChanged),null!==o?e.update({onExecute:o.bind(this)}):e.update({onExecute:this._onActionCallback.bind(this)})}destroy(){this._property.unsubscribe(this,this._propertyChanged)}value(){return this._action.isChecked()}setValue(e){this._action.update({checked:Boolean(e)})}_onActionCallback(){this._undoModel.setProperty(this._property,this.value(),this._undoText)} _propertyChanged(e){this.setValue(e.value())}}},261525:(e,t,i)=>{"use strict";i.d(t,{isCustomStudy:()=>o});const s={LinearRegression:!0,PivotPointsHighLow:!0,VbPSessions:!0,VbPSessionsRoughDetailed:!0,VbPPeriodic:!0,VbPAutoAnchored:!0,ZigZag:!0,TPOPeriodic:!0,TPOSessions:!0,VbPFixed:!0,PivotPointsStandard:!0,VbPVisible:!0,VbPAnchored:!0};function o(e){return e in s}},827710:(e,t,i)=>{"use strict";i.d(t,{MetaInfoHelper:()=>u});var s=i(650151),o=i(526075),r=i(368135),n=i(389137),a=i(201089),l=i(62745);function c(e){return!e.groupId&&!e.isHidden&&e.id!==l.RangeDependentStudyInputNames.FirstBar&&e.id!==l.RangeDependentStudyInputNames.LastBar}var h=i(261525);const d=(0,a.getLogger)("Platform.GUI.PropertyDialog.Indicators.MetaInfo");class u{constructor(e){this._metaInfo=e}hasUserEditableInputs(){return this._metaInfo.inputs.some(c)}getUserEditableInputs(){return this._metaInfo.inputs.filter(c)}hasUserEditableProperties(){return o.StudyMetaInfo.isScriptStrategy(this._metaInfo)}hasUserEditableStyles(){const e=this._metaInfo;return e.plots.length>0||void 0!==e.bands||void 0!==e.filledAreas||(0,h.isCustomStudy)(e.shortId)||o.StudyMetaInfo.isScriptStrategy(this._metaInfo)||Object.values(e.graphics).some((e=>void 0!==e))}getUserEditablePlots(){const e=new Set,t=this._metaInfo;return t.plots.filter((i=>{if((0,r.isColorerPlot)(i)||(0,r.isTextColorerPlot)(i)||(0,r.isDataOffsetPlot)(i)||(0,r.isOhlcColorerPlot)(i)||(0,r.isAlertConditionPlot)(i)||(0,r.isDataPlot)(i))return!1;if((0,r.isOhlcPlot)(i)){const o=i.target;if(e.has(o))return!1;e.add(o);const r=(0,s.ensureDefined)(t.ohlcPlots);return!(0,s.ensureDefined)(r[o]).isHidden}{const e=t.styles?t.styles[i.id]:void 0;return void 0===e||!e.isHidden}}))}hasUserEditableOptions(){return this.hasUserEditableInputs()||this.hasUserEditableProperties()||this.hasUserEditableStyles()}getStrategyProperties(){const e=this._metaInfo,t=e.inputs.filter(p),i={..._};for(const s of t){const t=s.internalID;i[t]=s,_.hasOwnProperty(t)||d.logWarn(`Unknown strategy input internal id ${t} in ${e.fullId}`)}return(0,n.clone)(i)}}const _={currency:void 0,backtest_fill_limits_assumption:void 0,calc_on_every_tick:void 0,calc_on_order_fills:void 0,commission_value:void 0,commission_type:void 0,initial_capital:void 0,pyramiding:void 0,slippage:void 0,default_qty_type:void 0,default_qty_value:void 0,margin_long:void 0,margin_short:void 0,use_bar_magnifier:void 0,process_orders_on_close:void 0,fill_orders_on_standard_ohlc:void 0};function p(e){return"strategy_props"===e.groupId}},263955:(e,t,i)=>{"use strict";i.d(t,{showScriptInfoErrorNoticeDialog:()=>r});var s=i(444372),o=i(33900);function r(){(0,o.showNoticeDialog)({type:"modal",title:s.t(null,void 0,i(457898)),content:s.t(null,void 0,i(27937))})}},634447:(e,t,i)=>{"use strict";i.d(t,{showStudiesLimitGoProDialog:()=>d});var s=i(444372),o=i(405117),r=i(960337),n=i(371927),a=i(822122),l=i(427937),c=i(982217);const h=s.t(null,void 0,i(875139));function d(e,t){const i=window.user.pro_plan===a.ExpertPlans.PremiumExpert;switch(t.reason){case"child":(0, r.createGoProDialog)({feature:"studyOnStudy",actions:i?[{text:h,action:n.PredefinedAction.Close}]:void 0});break;case"fundamental":const t=e.allStudies().filter(l.isFundamentalStudy).map((e=>e.title(c.TitleDisplayTarget.StatusLine)));(0,r.createGoProDialog)({feature:"fundamentalsOnChart",actions:i?[{text:h,action:n.PredefinedAction.Close}]:void 0,customParams:t});break;default:(0,o.trackGoProFeature)("studyLimit");const s=e.listUserStudies({dontCountVolume:!0,dontCountOverlay:!0,dontCountCompare:!0});(0,r.createGoProDialog)({feature:"studyLimit",customParams:s,actions:i?[{text:h,action:n.PredefinedAction.Close}]:void 0})}}},14952:(e,t,i)=>{"use strict";i.d(t,{restoreShowMarketOpenStatusProperty:()=>l,showMarketOpenStatusProperty:()=>a});var s=i(152633),o=i(62802);const r="Chart.ShowMarketOpenStatus";function n(){return o.getBool(r,true)}const a=(0,s.createPrimitiveProperty)(n());function l(){a.setValue(true),o.remove(r)}o.onSync.subscribe(null,(()=>a.setValue(n()))),a.subscribe(null,(()=>o.setValue(r,a.value())))},397245:(e,t,i)=>{"use strict";i.d(t,{marketStatusText:()=>o});var s=i(380271);function o(e){const t=e.value();if(null!==t){const e=s.titleMap.get(t);if(void 0!==e)return e}return""}},380271:(e,t,i)=>{"use strict";i.d(t,{actionMap:()=>J,classNameMap:()=>U,countdownFnMap:()=>X,iconMap:()=>z,marketStatusDescription:()=>Y,titleColorMap:()=>j,titleMap:()=>q,tooltipMap:()=>G});var s=i(790188),o=i(444372),r=i(553218),n=i(732140),a=i(262998),l=i(725230),c=i(315507),h=i(643401),d=i(85290),u=i(212462),_=i(792263),p=i(24165),m=i(421672),g=i(792845),S=i(109494),v=i(364123) ;const f=o.t(null,void 0,i(383949)),b=o.t(null,void 0,i(356042)),y=o.t(null,void 0,i(429985)),C=o.t(null,void 0,i(895814)),w=o.t(null,void 0,i(988958)),P=o.t(null,void 0,i(269419)),T=o.t(null,void 0,i(801653)),M=o.t(null,void 0,i(540519)),x=o.t(null,void 0,i(957048)),I=o.t(null,void 0,i(987202)),A=o.t(null,void 0,i(539348)),L=o.t(null,void 0,i(107827)),k=o.t(null,void 0,i(19830)),E=o.t(null,void 0,i(735701)),D=o.t(null,void 0,i(298105)),N=o.t(null,void 0,i(950634)),B=o.t(null,void 0,i(574537)),R=new Map([["market",new Map([["small",n],["medium",a],["large",a]])],["pre_market",new Map([["small",d],["medium",u],["large",u]])],["post_market",new Map([["small",c],["medium",h],["large",h]])],["out_of_session",new Map([["small",r],["medium",r],["large",r]])],["holiday",new Map([["small",l],["medium",l],["large",l]])]]),O=new Map([["market",v.marketStatusOpen],["pre_market",v.marketStatusPre],["post_market",v.marketStatusPost],["out_of_session",v.marketStatusClose],["holiday",v.marketStatusHoliday]]),V=new Map([["market",f],["pre_market",b],["post_market",y],["out_of_session",C],["holiday",w]]),W=new Map([["market",f],["pre_market",b],["post_market",y],["out_of_session",C],["holiday",w]]),F=new Map([["market",s.colorsPalette["color-market-open"]],["pre_market",s.colorsPalette["color-pre-market"]],["post_market",s.colorsPalette["color-post-market"]],["out_of_session",s.colorsPalette["color-market-closed"]],["holiday",s.colorsPalette["color-market-holiday"]]]),H=new Map([["market",P],["pre_market",T],["post_market",M],["out_of_session",x],["holiday",I]]);R.set("delisted",new Map([["small",_],["medium",p],["large",m]])),R.set("expired",new Map([["small",g],["medium",S],["large",S]])),O.set("delisted",v.marketStatusDelisted),O.set("expired",v.marketStatusExpired),V.set("delisted",o.t(null,void 0,i(389905))),V.set("expired",o.t(null,void 0,i(911235))),W.set("delisted",o.t(null,void 0,i(137432))),W.set("expired",o.t(null,void 0,i(911235))),F.set("delisted",s.colorsPalette["color-delisted-symbol"]),F.set("expired",s.colorsPalette["color-market-expired"]),H.set("delisted","This is no longer publicly trading so no new data will be added. But you can explore the historicals here."),H.set("expired",o.t(null,void 0,i(929493)));const z=R,U=O,G=V,q=W,j=F,Y=H;function K(e){return o.t(null,{plural:"{number} minutes",count:e},i(467151)).format({number:e.toString()})}function Z(e){return o.t(null,{plural:"{number} hours",count:e},i(224430)).format({number:e.toString()})}function $(e){const t=Math.floor(e/86400),s=Math.floor((e-86400*t)/3600),r=Math.floor((e-86400*t-3600*s)/60);return 0===t&&0===s&&0===r?A:t>0?L.format({days:(n=t,o.t(null,{plural:"{number} days",count:n},i(458609)).format({number:n.toString()})),hours:Z(s)}):s>0?k.format({hours:Z(s),minutes:K(r)}):K(r);var n}const X={market:e=>("post_market"===e.status?N:D).format({remainingTime:$(e.remainingSeconds)}),pre_market:e=>E.format({remainingTime:$(e.remainingSeconds)}),post_market:e=>D.format({remainingTime:$(e.remainingSeconds)}), out_of_session:e=>("pre_market"===e.status?B:E).format({remainingTime:$(e.remainingSeconds)}),holiday:e=>("pre_market"===e.status?B:E).format({remainingTime:$(e.remainingSeconds)}),delisted:e=>"",expired:e=>""},J=new Map([["market",null],["pre_market",null],["post_market",null],["out_of_session",null],["holiday",null],["delisted",null]])},826531:(e,t,i)=>{"use strict";i.d(t,{canShowSpreadActions:()=>o,globalKeypressMatches:()=>r});i(244842),i(731042),i(583912);var s=i(846540);new RegExp("^"+s.types.QUANDL,"i");function o(){let e=!1;return e="cme"!==window.TradingView.widgetCustomer&&"bovespa"!==window.TradingView.widgetCustomer,e}function r(e){if(e.ctrlKey)return!1;if(e.metaKey)return!1;if(!e.charCode)return!1;if(!e.which||e.which<=32)return!1;const t=e.target;if(t&&(/^(input|textarea)$/i.test(t.tagName)||"listbox"===t.getAttribute("role")))return!1;{const e=i.c[911595];if(e&&e.exports.isOpenedModals())return!1}return!0}},34831:(e,t,i)=>{"use strict";function s(){return Promise.all([i.e(78596),i.e(11165),i.e(93193),i.e(44335),i.e(67249),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(66639),i.e(30006),i.e(88194),i.e(38669),i.e(5145),i.e(35649),i.e(72639),i.e(89842),i.e(25190),i.e(26855),i.e(91033),i.e(58056),i.e(21625),i.e(61631),i.e(90684),i.e(40866),i.e(99916),i.e(40812),i.e(36956),i.e(77807),i.e(56388),i.e(9227),i.e(58289),i.e(77474),i.e(21895),i.e(35542),i.e(33444),i.e(50690),i.e(30979),i.e(88087),i.e(29594),i.e(111),i.e(80870),i.e(46513),i.e(32046),i.e(99144),i.e(65973),i.e(18519),i.e(21754)]).then(i.bind(i,837490))}i.d(t,{loadNewSymbolSearch:()=>s})},394905:(e,t,i)=>{"use strict";i.d(t,{ToastsFactory:()=>s});class s{constructor(e,t){this._chartToastsPromise=null,this._resizerBridge=e,this._bottomToolbarOffsetHeightProvider=t}async getChartToasts(){return null!==this._chartToastsPromise||(this._chartToastsPromise=async function(){return Promise.all([Promise.all([i.e(32109),i.e(56400),i.e(98899),i.e(50690),i.e(43447),i.e(53088)]).then(i.bind(i,814284)),Promise.all([i.e(98899),i.e(50690),i.e(43447),i.e(94291)]).then(i.bind(i,13830))]).then((e=>[e[0].ChartToasts,e[1].globalToasts]))}().then((e=>{const t=e[0],i=e[1];return new t(this._resizerBridge,this._resizerBridge.container.value(),i,this._bottomToolbarOffsetHeightProvider())}))),this._chartToastsPromise}}},406849:(e,t,i)=>{"use strict";i.d(t,{createTradeContext:()=>o});var s=i(650151);async function o(e,t){let i=NaN,o=NaN,r="";const n=e.proSymbol(),a=(e.symbolInfo()||{name:null}).name||n,l=e.priceScale();if(t){const s=e.firstValue();i=null!==s?l.coordinateToPrice(t,s):null,r=null!==i?e.formatter().format(i):""}const c=e.bars().last();null!==c&&(o=(0,s.ensure)(c.value[TradingView.CLOSE_PLOT]));return{symbol:n,displaySymbol:a,value:i,formattedValue:r,last:o,symbolInfoTradable:!!(e.symbolInfo()||{is_tradable:!1}).is_tradable}}},834075:(e,t,i)=>{"use strict";i.d(t,{isMobileTradingAvailable:()=>d,isMobileTradingAvailableInApp:()=>u});var s=i(638456),o=i(125226),r=i(314802),n=i(244842) ;const a=(0,o.isFeatureEnabled)("mobile_trading_ios")&&s.CheckMobile.iOS()&&(0,r.isOnMobileAppPage)("old"),l=(0,o.isFeatureEnabled)("mobile_trading_android")&&s.CheckMobile.Android()&&(0,r.isOnMobileAppPage)("new"),c=(0,o.isFeatureEnabled)("mobile_trading_web")&&s.CheckMobile.any()&&!s.CheckMobile.isIPad()&&(window.matchMedia("screen and (orientation: portrait) and (max-width: 567px)").matches||window.matchMedia("screen and (orientation: landscape) and (max-height: 567px)").matches)&&!(0,r.isOnMobileAppPage)("any"),h=n.enabled("mobile_trading")&&(a||l||c);function d(){return h}function u(){return a||l}},514315:(e,t,i)=>{"use strict";i.d(t,{updateThemeActions:()=>u});var s=i(444372),o=i(461794),r=i(345848),n=i(373571),a=i(167975),l=i(104436),c=i(67302);const h=["system","dark","light"],d={dark:s.t(null,void 0,i(40890)),light:s.t(null,void 0,i(950020)),system:s.t(null,void 0,i(980899))};async function u(e){const[t,u]=await Promise.all([i.e(83767).then(i.bind(i,429874)),i.e(83767).then(i.bind(i,867432))]),_=async _=>{let p=[];if((0,c.showThemeSwitcher)()){const i=t.getStdThemeNames(),s=t.getCurrentTheme().name;p=i.map((i=>{const a=new n.Action({actionId:"Chart.Theme.Apply",options:{name:"theme-switch-to-"+i,label:(0,o.clean)(t.translateStdThemeName(i)),checkable:!0,checked:s===i,onExecute:()=>{a.update({checked:!0}),t.loadTheme(e.chartWidgetCollection(),{themeName:i,standardTheme:!0}).then((()=>{e.readOnly()||window.saver.saveChartSilently(),(0,r.trackEvent)("GUI","Themes","Switch to "+i+" theme")}))}}});return a})),p.sort(((e,t)=>e.getLabel()>t.getLabel()?-1:1))}else if((0,c.showThemeAction)()&&window.TVD&&window.TVD.getThemeSetting){const e=await window.TVD.getThemeSetting();e&&(p=h.map((t=>{const i=new n.Action({actionId:"Chart.Theme.Apply",options:{name:"theme-switch-to-"+t,label:d[t],checkable:!0,checked:e===t,onExecute:()=>{i.update({checked:!0}),window.TVD&&window.TVD.setThemeSetting&&window.TVD.setThemeSetting(t)}}});return i})))}const m=[...p];if(window.is_authenticated){m.length&&m.push(new n.Separator);const t=new n.Action({actionId:"Chart.Theme.SaveAs",options:{name:"theme-save-as",label:(0,a.appendEllipsis)(s.t(null,void 0,i(309908))),onExecute:()=>u.showThemeSaveDialogAsync(e.model().model().theme())}});m.push(t)}_&&_.length&&window.is_authenticated&&(m.length&&m.push(new n.Separator),_.forEach((i=>{const s=new n.Action({actionId:"Chart.Theme.Apply.Custom",options:{label:(0,o.clean)(t.translateStdThemeName(i)),checkable:!1,onExecute:()=>{t.loadTheme(e.chartWidgetCollection(),{themeName:i,standardTheme:!1}).then((()=>{window.saver.saveChartSilently(),(0,r.trackEvent)("GUI","Switch to custom theme")}))},toolbox:{type:l.ToolboxType.Delete,action:()=>u.showRemoveThemeDialogAsync(i)},showToolboxOnHover:!0}});m.push(s)}))),e.actions().applyColorTheme.update({subItems:m})};window.is_authenticated?t.getThemeNames().then(_):_()}},360758:(e,t,i)=>{"use strict";i.d(t,{addPlusButtonProperty:()=>u,restoreAddPlusButtonSettingsValue:()=>_,showPlusButtonOnCursor:()=>h});var s=i(799786),o=(i(244842), i(62802)),r=i(152633),n=i(401580);const a="add_plus_button";function l(){const e=s.keyboardPressedKeysState.value();return void 0!==e&&(Boolean(e.modifiers&s.Modifiers.Alt&&e.modifiers&s.Modifiers.Mod)&&(void 0===e.code||e.altOrOptionCode()||e.controlOrMetaCode()))}const c=new n.WatchedValue(l());s.keyboardPressedKeysState.subscribe((()=>c.setValue(l())));const h=c.readonly();function d(){return o.getBool(a,!0)}const u=(0,r.createPrimitiveProperty)(d());function _(){u.setValue(!0),o.remove(a)}o.onSync.subscribe(null,(()=>u.setValue(d()))),u.subscribe(null,(()=>{o.setValue(a,u.value())}))},939243:(e,t,i)=>{"use strict";i.d(t,{getAlertColorLineByTheme:()=>y,getSettingsProperty:()=>f,restoreSettingsProperty:()=>b});var s=i(650151),o=i(822914),r=i(316230),n=i(852290),a=i(790188),l=i(62802),c=i(61499),h=i(190973),d=i(738232),u=i(42292);const _="alertLabels";let p;const m={visible:!0,showOnlyActive:!0,line:{color:"",visible:!0}},g=new Map([[c.StdTheme.Light,{line:{color:(0,a.getHexColorByName)("color-cold-gray-900")}}],[c.StdTheme.Dark,{line:{color:(0,a.getHexColorByName)("color-cold-gray-200")}}]]);function S(){let e=(0,l.getJSON)(_,null);if(null===e){const t=(0,u.defaults)("chartproperties");t&&t.alertsProperties&&t.alertsProperties.labels&&(e=t.alertsProperties.labels)}null===e&&(e=(0,o.default)(m));const t=(0,d.extractAllPropertiesKeys)(m),i=(0,d.extractAllPropertiesKeys)(e);if(!(0,r.default)(t,i)){const i=(0,d.extractState)(e,t);e=(0,n.default)((0,o.default)(m),i)}return e}function v(){p&&(0,l.setJSON)(_,p.state())}function f(){return p||(p=new h.default(S()),p.listeners().subscribe(null,v),l.onSync.subscribe(null,(()=>{p.mergeAndFire(S())})),p)}function b(){p&&p.mergeAndFire(m)}function y(e){const t=e.dark().value()?c.StdTheme.Dark:c.StdTheme.Light;return(0,s.ensureDefined)(g.get(t)).line.color}},346825:(e,t,i)=>{"use strict";i.d(t,{ALERT_LABEL_WIDTH:()=>ae,AlertLabel:()=>de,isAlertLabel:()=>le});var s,o=i(650151),r=i(790188),n=i(572230),a=i(996986),l=i(888929),c=i(190973),h=i(742391),d=i(223699),u=i(444331),_=i(964824),p=i(345848),m=i(939243),g=i(86441),S=i(444372),v=i(142119),f=i(315801),b=i(230058),y=i(953725),C=i(582665),w=i(678183),P=i(458963),T=i(787123),M=i(9640),x=i(43192);!function(e){e[e.ConnectorOffsetFromIcon=28]="ConnectorOffsetFromIcon",e[e.ConnectorCircleRadius=4]="ConnectorCircleRadius",e[e.IconWidth=21]="IconWidth"}(s||(s={}));class I extends x.BitmapCoordinatesPaneRenderer{constructor(e){super(),this._data=e}hitTest(e,t){const i=(0,M.interactionTolerance)().line;for(let s=0;s=a&&e.x<=l)return new f.HitTestResult(f.HitTarget.MovePoint,{activeItem:s,hideCrosshairLinesOnHover:!0,areaName:f.AreaName.Line})}const o=this._data.levels.map((e=>e.y)),r=Math.min(...o),n=Math.max(...o),a=this._data.isLeft?Math.round(s.ConnectorOffsetFromIcon+s.IconWidth):Math.round(t.cssWidth-(s.ConnectorOffsetFromIcon+s.IconWidth)) ;if(Math.abs(a-e.x)=r&&e.y<=n){const t=o.reduce(((t,i,s)=>{const o=Math.abs(t.level-e.y);return Math.abs(i-e.y){const s=Math.round(i.y*e.verticalPixelRatio),[o,r]=this._calculateLeftRight(this._data,i,e.bitmapSize.width,e.horizontalPixelRatio);(0,T.drawHorizontalLine)(t,s,o,r)})),this._data.levels.length>1){const i=this._data.isLeft?Math.round((s.ConnectorOffsetFromIcon+s.IconWidth)*e.horizontalPixelRatio)+.5:Math.round(e.bitmapSize.width-(s.ConnectorOffsetFromIcon+s.IconWidth)*e.horizontalPixelRatio)+.5,o=this._data.levels.map((e=>e.y)),r=Math.min(...o),n=Math.max(...o);t.beginPath(),t.moveTo(i,r*e.verticalPixelRatio),t.lineTo(i,n*e.verticalPixelRatio),t.stroke();const a=Math.round(s.ConnectorCircleRadius*e.horizontalPixelRatio);(0,T.setLineStyle)(t,P.LINESTYLE_SOLID),t.fillStyle=this._data.connectorsBackColor,[r,n].forEach((s=>{const o=Math.round(s*e.verticalPixelRatio);t.beginPath(),t.arc(i,o,a,0,2*Math.PI,!0),t.fill(),t.stroke()}))}}_calculateLeftRight(e,t,i,o){const r=1===e.levels.length?0:Math.floor(s.ConnectorCircleRadius*o);let n,a;return this._data.isLeft?(a=0,n="full"===t.mode?i:"toConnector"===t.mode?Math.round((s.ConnectorOffsetFromIcon+s.IconWidth-r)*o):Math.round(this._data.distanceToTooltip*o)):(n="full"===t.mode?0:"toConnector"===t.mode?Math.round(i-(s.ConnectorOffsetFromIcon+s.IconWidth-r)*o):Math.round(i-this._data.distanceToTooltip*o),a=i),[n,a]}}var A=i(934026),L=i(674981),k=i(199471),E=i(422333),D=i(167975),N=i(511131),B=i(294162);const R=(0,N.makeFont)(12,E.CHART_FONT_FAMILY),O=new Path2D("M5 3.06574L10.9014 7L5 10.9343V3.06574ZM6 9.06574L9.09861 7L6 4.93426V9.06574ZM7 13C10.3137 13 13 10.3137 13 7C13 3.68629 10.3137 1 7 1C3.68629 1 1 3.68629 1 7C1 10.3137 3.68629 13 7 13ZM7 14C10.866 14 14 10.866 14 7C14 3.13401 10.866 0 7 0C3.13401 0 0 3.13401 0 7C0 10.866 3.13401 14 7 14Z");const V=" • ";class W extends x.BitmapCoordinatesPaneRenderer{constructor(){super(),this._data=null,this._lastPaintTextWidth=null,this._lastPaintPaneWidth=null,this._widthCache=new B.TextWidthCache}setData(e){this._data=e}hitTest(e){const t=this._data;if(null===this._lastPaintTextWidth||!t||null===this._lastPaintPaneWidth)return null;const i=this._lastPaintTextWidth+16+26,s=this._calculatePoint(t,i,this._lastPaintPaneWidth);{const o=new g.Point(s.x-26+i,s.y-9.5),r=o.add(new g.Point(26,19));if((0,A.pointInBox)(e,(0,g.box)(o,r)))return new f.HitTestResult(f.HitTarget.Custom,{activeItem:t.lineIndex,hideCrosshairLinesOnHover:!0,areaName:f.AreaName.Button,clickHandler:t.buttonAction,tapHandler:t.buttonAction})}{const o=new g.Point(s.x,s.y-9.5),r=o.add(new g.Point(i,19));if((0,A.pointInBox)(e,(0, g.box)(o,r)))return new f.HitTestResult(f.HitTarget.MovePoint,{activeItem:t.lineIndex,hideCrosshairLinesOnHover:!0,areaName:f.AreaName.Tooltip})}return null}_drawImpl(e){const t=this._data;if(!t)return;const i=e.context;this._lastPaintPaneWidth=e.mediaSize.width,i.font=R;const s=t.text,r=t.additionalText;let n=!1,a=null;r&&(this._lastPaintTextWidth=this._widthCache.measureText(i,s+V+r),a=this._tooltipSizes(e),n=a.contentWidth<=a.maxWidth);let l=s;if(!n&&(this._lastPaintTextWidth=this._widthCache.measureText(i,l),a=this._tooltipSizes(e),a.contentWidth>a.maxWidth)){l=function(e,t,i){const s=(0,L.lowerboundExt)((t=>e.substring(0,t)),t,((t,s)=>i(t===e?e:(0,D.appendEllipsis)(t))this._widthCache.measureText(i,e)))}const c=(0,o.ensureNotNull)(a).maxWidth,h=Math.round(c*e.horizontalPixelRatio),d=Math.round(19*e.verticalPixelRatio),u=this._calculatePoint(t,c,this._lastPaintPaneWidth);this._drawBorderAround(t,e,u,h,d,(e=>e.fill())),this._drawButton(t,e,u,h,d),this._drawText(t,e,u,l),n&&this._drawAdditionalText(t,e,u),this._drawBorderAround(t,e,u,h,d,(e=>e.stroke()))}_drawButton(e,t,i,s,o){const r=t.context;i=i.add(new g.Point(s/t.horizontalPixelRatio,0));{const s=Math.round((i.x-26)*t.horizontalPixelRatio)+.5,n=Math.round(i.y*t.verticalPixelRatio-.5*o)+.5;r.fillStyle=e.buttonBackColor,r.fillRect(s,n,26*t.horizontalPixelRatio,o),r.strokeStyle=e.buttonBorderColor,r.lineWidth=Math.max(1,Math.floor(t.verticalPixelRatio)),r.beginPath(),r.moveTo(s,n),r.lineTo(s,n+o),r.stroke()}0===e.buttonType?this._drawCloseButton(e,t,i):1===e.buttonType&&this._drawRestartButton(e,t,i)}_drawCloseButton(e,t,i){const s=t.context;s.strokeStyle=e.lineColor,s.beginPath();const o=Math.round((i.x-13-4+.5)*t.horizontalPixelRatio),r=Math.round((i.y-4+.5)*t.verticalPixelRatio),n=Math.round(8*t.horizontalPixelRatio),a=Math.round(8*t.verticalPixelRatio);s.moveTo(o,r),s.lineTo(o+n,r+a),s.moveTo(o,r+a),s.lineTo(o+n,r),s.stroke()}_drawRestartButton(e,t,i){const s=t.context,r=Math.round((i.x-26+6+.5)*t.horizontalPixelRatio),n=Math.round((i.y-7+.5)*t.verticalPixelRatio);s.save(),s.translate(r,n),s.scale(t.horizontalPixelRatio,t.verticalPixelRatio),s.fillStyle=(0,o.ensureDefined)(e.restartIconColor),s.fill(O,"evenodd"),s.restore()}_tooltipSizes(e){const t=(0,o.ensureNotNull)(this._lastPaintTextWidth)+16+26,i=Math.max(20,.9*(e.mediaSize.width-80));return{contentWidth:t,maxWidth:Math.min(t,i)}}_drawText(e,t,i,s){const o=t.context,r=Math.round((i.x+8)*t.horizontalPixelRatio),n=Math.round((i.y+5)*t.verticalPixelRatio);o.save(),o.translate(r,n),(0,k.drawScaled)(o,t.horizontalPixelRatio,t.verticalPixelRatio,(()=>{o.fillStyle=e.textColor,o.fillText(s,0,0)})),o.restore()}_drawAdditionalText(e,t,i){const s=t.context,r=Math.round(this._widthCache.measureText(s,e.text)*t.horizontalPixelRatio),n=Math.round(this._widthCache.measureText(s,V)*t.horizontalPixelRatio),a=Math.round((i.x+8)*t.horizontalPixelRatio)+r,l=Math.round((i.y+5)*t.verticalPixelRatio);s.save(),s.fillStyle=(0, o.ensureDefined)(e.additionalTextColor),s.translate(a,l),(0,k.drawScaled)(s,t.horizontalPixelRatio,t.verticalPixelRatio,(()=>{s.fillStyle=(0,o.ensureDefined)(e.textColor),s.fillText(V,0,0)})),s.translate(n,0),(0,k.drawScaled)(s,t.horizontalPixelRatio,t.verticalPixelRatio,(()=>{s.fillStyle=(0,o.ensureDefined)(e.additionalTextColor),s.fillText((0,o.ensureDefined)(e.additionalText),0,0)})),s.restore()}_drawBorderAround(e,t,i,s,o,r){const n=t.context,a=Math.round(i.x*t.horizontalPixelRatio)+.5,l=Math.round(i.y*t.verticalPixelRatio-o/2)+.5;n.strokeStyle=e.lineColor,n.lineWidth=Math.max(1,Math.floor(t.verticalPixelRatio));const c=Math.round(4*t.horizontalPixelRatio);n.fillStyle=e.backColor,n.beginPath(),(0,T.drawRoundRect)(n,a,l,s,o,c),r(n)}_calculatePoint(e,t,i){const s=e.point;if(e.center){const o=Math.max(0,.5*(i-t));return e.isLeft?ol.priceToCoordinate(e,a),h=[];if("channel"===r.type){const e=c(r.upper),t=c(r.lower);h.push(e),h.push(t)}else h.push(c(r.price));const d=i.isSelected(),u=i.isHovered(),_=this._model.lastHittestData(),p=this._model.lastSelectedHittestData();let m=0;u&&(m=null!==(e=null==_?void 0:_.activeItem)&&void 0!==e?e:0),d&&(m=null!==(t=null==p?void 0:p.activeItem)&&void 0!==t?t:0);const S=this._alertLabel.colors(),v=i.labelLineColor(),w=h.map(((e,t)=>({y:e,mode:i.drawHorzLine()?"full":t===m&&1===h.length?"toTooltip":"toConnector" }))),P=n.leftPriceScales().includes(l),T=1===h.length?F.NoLineModeOffsetSingleLine:F.NoLineModeOffsetMultipleLines,M={distanceToTooltip:T,levels:w,color:v,connectorsBackColor:S.connectorBackColor,iconBackgroundWithCorners:d||u,iconColor:S.iconColor,isLeft:P};if((i.drawHorzLine()||d||u)&&this._compositeRenderer.append(new I(M)),d){const e=n.height(),t=h.map((t=>this._model.backgroundColorAtYPercentFromTop(t/e))),i=P?F.SelectionPointOffset:n.width()-F.SelectionPointOffset,s={points:h.map((e=>new g.Point(i,e))),hittestResult:f.HitTarget.MovePoint,bgColors:t,visible:!0,barSpacing:this._model.timeScale().barSpacing()};this._compositeRenderer.append(new b.SelectionRenderer(s))}if((d||u)&&!this._alertLabel.isMoving()){const e=u&&(null==_?void 0:_.areaName)===f.AreaName.Button,t=P?T:n.width()-T,o=s.name()||(s.isBeingEdited().value()||i.isMoving()?s.defaultDescription():s.description()),r=this._alertLabel.isInactive()?S.inActiveTextBaseColor:v,a=async()=>{const e=this._alertLabel.alert().id().value();e&&(await(0,y.getAlertsActionCreators)()).deleteAlert(e,{confirmation:(0,C.selectedRemoveConfirmation)([s]),analytics:{actionLabel:"Alert label source",actionSource:"Chart",event:"restart"}}).execute()},l=async()=>{const e=this._alertLabel.alert().id().value();e&&(await(0,y.getAlertsActionCreators)()).restartAlert(e,{analytics:{actionLabel:"Alert label source",actionSource:"Chart",event:"restart"}}).execute()},c=i.stopReason(),d=void 0!==c,p={isLeft:P,point:new g.Point(t,h[m]),lineIndex:m,center:i.drawHorzLine(),text:o,textColor:r,additionalText:Y(c),additionalTextColor:K(c,S),lineColor:v,backColor:S.connectorBackColor,buttonType:d?1:0,buttonBorderColor:S.tooltipButtonBorderColor,buttonBackColor:e?S.tooltipButtonBorderColorHovered:S.connectorBackColor,buttonAction:d?l:a,restartIconColor:d?S.restartIconColor:void 0,themeName:this._model.dark().value()?"dark":"light"};this._tooltipRenderer.setData(p),this._compositeRenderer.append(this._tooltipRenderer)}}}var $=i(246733),X=i(229765);class J{constructor(e){this._renderers=null!=e?e:[]}clear(){this._renderers=[]}add(e){this._renderers.push(e)}draw(e,t,i,s,o,r,n){for(const a of this._renderers)a.draw(e,t,i,s,o,r,n)}lastDrawnBodyBox(){let e=null;for(const t of this._renderers)if(t.lastDrawnBodyBox){const i=t.lastDrawnBodyBox();if(null!==i){if(null===e){e=i;continue}e=(0,g.box)((0,g.point)(Math.min(e.min.x,i.min.x),Math.min(e.min.y,i.min.y)),(0,g.point)(Math.max(e.max.x,i.max.x),Math.max(e.max.y,i.max.y)))}}return e}hitTest(e,t,i){var s,o;let r=null;for(let n=this._renderers.length-1;n>=0;n-=1){const a=null===(o=(s=this._renderers[n]).hitTest)||void 0===o?void 0:o.call(s,e,t,i);null!=a&&(null===r||a.target()>r.target())&&(r=a)}return r}topBottomTotalHeight(e){const t={top:0,bottom:0,total:0};for(const i of this._renderers){const s=i.topBottomTotalHeight(e);t.top=Math.max(t.top,s.top),t.bottom=Math.max(t.bottom,s.bottom),t.top=t.top+t.bottom}return t}setData(e,t){for(const i of this._renderers)i.setData(e,t)}}var Q=i(601183) ;const ee=new Path2D("M6.21 5.27 1.68 1.06A1 1 0 0 0 0 1.79v8.42a1 1 0 0 0 1.68.73l4.53-4.2a1 1 0 0 0 0-1.47Z");class te{constructor(){this._data=null,this._commonData=null,this._bodyBox=null}setData(e,t){this._data=e,this._commonData=t}lastDrawnBodyBox(){return this._bodyBox}draw(e,t,i,s,o,r,n){var a;const l=this._data,c=this._commonData;if(!l||!c)return;e.save(),e.fillStyle=null!==(a=l.backgroung)&&void 0!==a?a:c.background;const h="right"===r?s*n:0;e.translate(h,Math.round((c.coordinate-6.5+1)*n)),(0,k.drawScaled)(e,"right"===r?-n:n,n,(()=>{e.fill(ee)})),e.restore();const d="right"===r?s-7:0;this._bodyBox=(0,g.box)((0,g.point)(d,c.coordinate-6.5),(0,g.point)(d+7,c.coordinate+6.5))}topBottomTotalHeight(e){return{top:0,bottom:0,total:0}}hitTest(e,t,i){return this._data?(0,Q.hittestByData)(this._data,e):null}}var ie;!function(e){e[e.IconMinWidth=23]="IconMinWidth"}(ie||(ie={}));class se extends X.PriceAxisView{constructor(e,t){super(),this._collapsedAxisRenderer=new te,this._lastDrawnAxisBox=null,this._lastDrawnPaneBox=null,this._alertLabel=e,this._levelIndex=t,this._collapsedAxisRenderer.setData(this._axisRendererData,this._commonRendererData)}renderer(){return this._updateRendererDataIfNeeded(),this._rendererImpl()}ignoreAlignment(){return!0}_updateRendererData(e,t,i){var s,o,r,n,a,l;if(e.visible=!1,t.visible=!1,!this._alertLabel.labelVisible())return;const c=this._alertLabel.priceScale();if(!c)return;const h=c.mainSource(),d=null!==h?h.firstValue():null;if(c.isEmpty()||null===d)return;const u=this._alertLabel.priceOfLevel(this._levelIndex);if(null===u)return;const _=this._alertLabel.colors(),p=this._alertLabel.labelLineColor();i.background=(0,$.resetTransparency)(p),i.textColor=_.iconColor,i.coordinate=c.priceToCoordinate(u,d);const m=this._alertLabel.animation();if(null!==m){const e=m.data(performance.now());i.globalAlpha=e.alpha}else i.globalAlpha=void 0;e.text=c.formatPrice(u,d);const g=null!==(r=null===(o=(s=this._rendererImpl()).lastDrawnBodyBox)||void 0===o?void 0:o.call(s))&&void 0!==r?r:this._lastDrawnAxisBox;this._lastDrawnAxisBox=null!=g?g:this._lastDrawnAxisBox,this._lastDrawnAxisBox&&(e.hitTestData={hoverModelFromAxis:!0,itemBox:this._lastDrawnAxisBox,activeItem:this._levelIndex});const S=null!==(l=null===(a=(n=this._paneRenderer).lastDrawnBodyBox)||void 0===a?void 0:a.call(n))&&void 0!==l?l:this._lastDrawnPaneBox;this._lastDrawnPaneBox=null!=S?S:this._lastDrawnPaneBox,this._lastDrawnPaneBox&&(t.hitTestData={hoverModelFromAxis:!0,itemBox:this._lastDrawnPaneBox,activeItem:this._levelIndex}),t.hitTarget=f.HitTarget.MovePoint,e.hitTarget=f.HitTarget.Regular,t.labelIcon=1,t.labelIconMinWidth=ie.IconMinWidth,t.visible=!0,e.visible=!0}_rendererImpl(){return null===this._alertLabel.animation()?this._alertLabel.isHovered()||this._alertLabel.isSelected()?this._axisRenderer:this._collapsedAxisRenderer:new J([this._collapsedAxisRenderer,this._axisRenderer])}}var oe=i(81979);const re=l.sortSourcesPreOrdered.AlertLabel,ne=l.sortSourcesPreOrdered.AlertLabelInactive,ae=5;function le(e){return e instanceof de} const ce={newAlertColor:(0,r.getHexColorByName)("color-cold-gray-450"),inActiveAlertColor:(0,r.getHexColorByName)("color-cold-gray-600"),inActiveTextBaseColor:(0,r.getHexColorByName)("color-cold-gray-450"),inActiveTextManualColor:(0,r.getHexColorByName)("color-cold-gray-450"),inActiveTextTriggeredColor:(0,r.getHexColorByName)("color-tan-orange-500"),inActiveTextExpiredColor:(0,r.getHexColorByName)("color-ripe-red-500"),connectorBackColor:(0,r.getHexColorByName)("color-cold-gray-900"),iconColor:(0,r.getHexColorByName)("color-cold-gray-900"),restartIconColor:(0,r.getHexColorByName)("color-cold-gray-200"),tooltipButtonBorderColor:(0,r.getHexColorByName)("color-cold-gray-800"),tooltipButtonBorderColorHovered:(0,r.getHexColorByName)("color-cold-gray-800")},he={newAlertColor:(0,r.getHexColorByName)("color-cold-gray-450"),inActiveAlertColor:(0,r.getHexColorByName)("color-cold-gray-300"),inActiveTextBaseColor:(0,r.getHexColorByName)("color-cold-gray-550"),inActiveTextManualColor:(0,r.getHexColorByName)("color-cold-gray-550"),inActiveTextTriggeredColor:(0,r.getHexColorByName)("color-tan-orange-500"),inActiveTextExpiredColor:(0,r.getHexColorByName)("color-ripe-red-500"),connectorBackColor:(0,r.getHexColorByName)("color-white"),iconColor:(0,r.getHexColorByName)("color-white"),restartIconColor:(0,r.getHexColorByName)("color-cold-gray-900"),tooltipButtonBorderColor:(0,r.getHexColorByName)("color-cold-gray-100"),tooltipButtonBorderColorHovered:(0,r.getHexColorByName)("color-cold-gray-100")};class de extends a.DataSource{constructor(e,t,i,s){super(),this._priceAxisViews=[],this._paneLabelsPaneViews=[],this._propertyMock=new c.default,this._startMovingPoint=null,this._currentMovingPoint=null,this._animation=null,this._onConditionChanged=()=>{const e=this.alert().condition(),t=e?"channel"===e.type?2:1:0;if(this._priceAxisViews.length!==t){for(let e=this._priceAxisViews.length;ee.lightUpdate())),t.onConditionChanged().subscribe(this,this._onConditionChanged),this._onConditionChanged(),this._isBeingEdited=t.isBeingEdited().spawn(),this._isBeingEdited.subscribe(this._resetUserEditEnabled.bind(this)),this._selected=t.selected().spawn(),this._selected.subscribe(this._onAlertSelectedChanged.bind(this)),this._selected.value()&&this.canDrawLabelForAlert()&&this._selectAlertLabel(), this._localFireTime=t.localFireTime().spawn(),this._localFireTime.subscribe(this._onAlertFireTimeChanged.bind(this),{callWithLast:!0}),(0,m.getSettingsProperty)().subscribe(this,(()=>e.updateSource(this))),this._active=t.active().spawn(),this._active.subscribe((()=>e.updateSource(this)))}destroy(){this._alertId.destroy(),this._isBeingEdited.destroy(),this._localFireTime.destroy(),this._active.destroy(),this._selected.destroy(),(0,m.getSettingsProperty)().unsubscribeAll(this),this._alert.extraUpdated().unsubscribeAll(this),super.destroy()}model(){return this._model}zorder(){return this.isInactive()?ne:re}colors(){return{...this._themedColors(),lineColor:this.labelLineColor()}}alertOwnerSource(){return this._alertOwnerSource}alertSeriesId(){return this._alertSeriesId}alignCrossHairToMovePoint(){return!0}name(){return"AlertLabel"}isSpeciallyZOrderedSource(){return!0}stop(){this._alert.id().unsubscribe(this._resetUserEditEnabled),this._alert.extraUpdated().unsubscribeAll(this),this._alert.isBeingEdited().unsubscribe(this._resetUserEditEnabled),this._alert.selected().unsubscribe(this._onAlertSelectedChanged)}alert(){return this._alert}isMoving(){return null!==this._startMovingPoint}isHovered(){return this===this._model.hoveredSource()}isSelected(){return this._model.selection().isSelected(this)}alertId(){return this.alert().id().value()}getAlert(){return Promise.resolve(this._alert)}getAlertSync(){return this._alert}priceOfLevel(e){const t=this.alert().condition();return t?"channel"===t.type?[t.upper,t.lower][e]:t.price:null}convertYCoordinateToPriceForMoving(e,t){const i=this.priceScale();if(!t||!i||i.isEmpty())return null;const s=t.firstValue();return null===s?null:i.coordinateToPrice(e,s)}isSynchronizable(){return!1}state(){const e=this.alert().condition(),t=[];return null!==e&&("channel"===e.type?(t.push({price:e.upper}),t.push({price:e.lower})):t.push({price:e.price})),{id:this._id,type:"AlertLabel",zorder:this.zorder(),points:t}}restorePoints(e){}createServerPoints(){}properties(){return this._propertyMock}paneViews(){return window.TradingView.printing||!this.labelVisible()?null:[this._paneView]}topPaneViews(){const e=performance.now();return null!==this._animation&&this._continueOrFinishAnimation(e),!window.TradingView.printing&&this.labelVisible()&&this._animationActive(e)?(this.updateAllViews((0,_.sourceChangeEvent)(this.id())),this._paneLabelsPaneViews):null}dataWindowView(){return null}priceAxisViews(e,t){return this.labelVisible()&&this.priceScale()===t&&!this._animationActive()&&this.canDrawLabelForAlert()?this._priceAxisViews:[]}topPriceAxisViews(e,t){const i=performance.now();return null!==this._animation&&this._continueOrFinishAnimation(i),this.priceScale()===t&&this._animationActive(i)&&this.canDrawLabelForAlert()?(this.updateAllViews((0,_.sourceChangeEvent)(this.id())),this._priceAxisViews):[]}updateAllViews(e){this._paneView.update(),this._priceAxisViews.forEach((t=>t.update(e))),this._paneLabelsPaneViews.forEach((t=>t.update(e)))}pointsCount(){return 0}title(){return this.alert().title()}movable(){ return!this._alert.isBeingEdited().value()&&!this._alert.isNew()}startMoving(e,t,i,s){this._userEditEnabled=!1,this._startMovingPoint=e,this.alert().saveState(),this.alert().startEditing()}move(e,t,i,s){if(!e.logical||null===t)return;const r=e.logical.price,n=this.alert(),a=(0,o.ensureNotNull)(n.condition());if(this._currentMovingPoint={...e},"channel"===a.type){let{upper:e,lower:i}=a;const s=this._alertOwnerSource.base()||100;0===t?(0,o.ensureDefined)(this._currentMovingPoint.logical).price=e=Math.max(r,i+1/s):1===t&&((0,o.ensureDefined)(this._currentMovingPoint.logical).price=i=Math.min(r,e-1/s)),n.setCondition({...a,lower:i,upper:e})}else n.setCondition({type:"price",price:r})}endMoving(){const e=this._startMovingPoint,t=this._currentMovingPoint;if(this._userEditEnabled=!0,this._startMovingPoint=null,this._currentMovingPoint=null,!e||!t||e===t)return;(0,p.trackEvent)("chart_alert","edit","move"),this._invokeAlertEditor({dataSourceHub:this._model,alert:this.alert(),type:"edit_alert",onEditCancel:()=>{setTimeout((async()=>{if(this.isInactive()){const e=this.alert().id().value();void 0!==e&&(await(0,y.getAlertsActionCreators)()).restartAlert(e,{analytics:{actionLabel:"Alert label source",actionSource:"Chart",event:"restart"}}).execute()}else this.alert().restoreState(),this.alert().abortEditing();this._model.lightUpdate()}),0)},silent:!0,actionSource:"alert_label_move"})}currentMovingPoint(){return this._currentMovingPoint}showInObjectTree(){return!1}isRemovedByStudyTemplates(){return!1}isUserDeletable(){return!1}doesMovingAffectsUndo(){return!1}drawHorzLine(){return this.labelLineVisible()}canDrawLabelForAlert(){const e=this.alert(),t=e.mainSeriesState(),i=t&&t.style,s=this._model.mainSeries(),o=s&&s.properties().childs(),r=o&&o.style&&o.style.value(),n=e.crossInterval()||d.Interval.isEqual(e.resolution(),s.interval()),a=i===r||!e.isRangeBasedStyle()&&!(0,u.isRangeBasedStyle)(s.style());return e.isPrice()&&n&&a}labelVisible(){const e=this._alertOwnerSource.symbolSource();if(e&&(e.isConvertedToOtherCurrency()||e.isConvertedToOtherUnit()))return!1;if(this._model.isInReplay())return!1;if(!this.isInactive())return(0,m.getSettingsProperty)().childs().visible.value();return void 0!==this.stopReason()&&(this._animationActive()||!this.showOnlyActive())}labelLineColor(){const e=(0,m.getSettingsProperty)().childs().line.childs().color.value(),t=e||(0,m.getAlertColorLineByTheme)(this.model());if(null!==this._animation)return(0,o.ensureDefined)(t);const i=this._themedColors();return this._alert.isNew()?(0,o.ensureDefined)(i.newAlertColor):this._alert.active().value()?t:(0,o.ensureDefined)(i.inActiveAlertColor)}labelLineVisible(){return(0,m.getSettingsProperty)().childs().line.childs().visible.value()}showOnlyActive(){return(0,m.getSettingsProperty)().childs().showOnlyActive.value()}stopReason(){return this.isInactive()?this._alert.stopReason():void 0}animation(){return this._animation}isInactive(){return!this._alert.active().value()&&!this._alert.isNew()}_themedColors(){return this._model.dark().value()?ce:he} _resetUserEditEnabled(){const e=this._alert;this._userEditEnabled=!(e.isBeingEdited().value()||e.isNew()||!e.isPrice()||null===e.condition())}_onAlertSelectedChanged(e){this.canDrawLabelForAlert()&&(e?this._selectAlertLabel():this._unselectAlertLabel())}_selectAlertLabel(){this._model.selectionMacro((e=>{e.selection().isSelected(this)||(e.clearSelection(),e.addSourceToSelection(this))}))}_unselectAlertLabel(){this._model.selectionMacro((e=>{e.selection().isSelected(this)&&e.removeSourceFromSelection(this)}))}_onAlertFireTimeChanged(e){var t,i;null!==e&&(this._animation=(t=e,i=this.isHovered()||this.isSelected()?1:0,{finished:e=>e-t>=2400,data:e=>{const s=Math.min(e-t,2400)%1200,o=s%600,r=Math.round(s/1200),n=(0,oe.easingFunc.linear)(o/600);return{alpha:0===r==(0===i)?n:1-n}}}),this._model.updateSource(this))}_continueOrFinishAnimation(e){(0,o.ensureNotNull)(this._animation).finished(e)?(this._animation=null,this._model.updateSource(this)):this._model.invalidate(n.InvalidationMask.cursor())}_animationActive(e=performance.now()){return null!==this._animation&&!this._animation.finished(e)}}},108039:(e,t,i)=>{"use strict";i.d(t,{AppliedTimeFrame:()=>o});var s=i(938550);class o{constructor(e){this._appliedTimeFrame=new s.WatchedObject(null),this._appliedTimeFrameInfo=null,this._appliedTimeFrameChangedBound=this._appliedTimeFrameChanged.bind(this),this._model=e,e.mainSeries().dataEvents().seriesTimeFrame().subscribe(this,this._onSeriesTimeFrame),this._appliedTimeFrame.subscribe(this._appliedTimeFrameChangedBound)}destroy(){this._appliedTimeFrame.unsubscribe(this._appliedTimeFrameChangedBound),this._model.timeScale().logicalRangeChanged().unsubscribeAll(this),this._model.mainSeries().dataEvents().seriesTimeFrame().unsubscribeAll(this)}appliedTimeFrame(){return this._appliedTimeFrame}_appliedTimeFrameChanged(){this._model.timeScale().logicalRangeChanged().unsubscribe(this,this._invalidateAppliedTimeFrame)}_onSeriesTimeFrame(e,t,i,s){if(s){const e=this._model.timeScale();this._appliedTimeFrameInfo={logicalRange:e.logicalRange(),baseIndex:e.baseIndex()},e.logicalRangeChanged().subscribe(this,this._invalidateAppliedTimeFrame)}}_invalidateAppliedTimeFrame(){if(null===this._appliedTimeFrameInfo)return;const e=this._model.timeScale(),t=e.logicalRange(),i=e.baseIndex(),s=this._appliedTimeFrameInfo.logicalRange,o=this._appliedTimeFrameInfo.baseIndex;(null===t||null===s||Math.abs(i-t.left()-(o-s.left()))>=.01||Math.abs(i-t.right()-(o-s.right()))>=.01)&&this._appliedTimeFrame.setValue(null)}}},155964:(e,t,i)=>{"use strict";i.d(t,{defaultsPreferencesByWhiteList:()=>E,preferencesByWhiteList:()=>k});var s=i(389137),o=i(507795),r=i(488530),n=i(201089),a=i(909598),l=i(42292),c=i(530239),h=i(329806),d=i(792795),u=i(790188);const _={visible:!1,lineStyle:i(458963).LINESTYLE_DOTTED,lineWidth:1,bidLineColor:u.colorsPalette["color-tv-blue-500"],askLineColor:u.colorsPalette["color-ripe-red-400"]};var p=i(993171),m=i(138839),g=i(490515);const S={...r.candleStylePreferencesDefault,deltaAdjust:!0,showSummary:!0, type:m.VolumeFootprintTypeValues.BuyAndSell,pointOfControl:!0,bgColors:(0,g.getBgColorsDefaults)(),imbalanceHighlight:{buyColor:(0,u.getHexColorByName)("color-minty-green-500"),sellColor:(0,u.getHexColorByName)("color-ripe-red-500"),visible:!0},inputs:{rowSize:"Auto",atrLength:14,imbalancePercent:300,ticksPerRow:100,showVA:!0,vaPercent:70,calcStackedImbalance:!1,stackedImbalanceCount:3}};var v=i(70843);const f=(0,n.getLogger)("Chart.ApplyPreferencesToAllCharts"),b={color:"",style:0},y={autoScale:!1,autoScaleDisabled:!1,lockScale:!1,percentage:!1,percentageDisabled:!1,log:!1,logDisabled:!1,alignLabels:!1,isInverted:!1,indexedTo100:!1},C={backgroundType:d.ColorType.Solid,background:"",backgroundGradientStartColor:"",backgroundGradientEndColor:"",topMargin:0,bottomMargin:0,rightOffset:0,gridLinesMode:"both",horzGridProperties:(0,h.deepExtend)({},b),vertGridProperties:(0,h.deepExtend)({},b),crossHairProperties:(0,h.deepExtend)({},{color:"",style:0,transparency:0,width:0}),legendProperties:(0,h.deepExtend)({},{showStudyArguments:!1,showStudyTitles:!1,showStudyValues:!1,showSeriesTitle:!1,showSeriesOHLC:!1,showLegend:!1,showLastDayChange:!1,showBarChange:!0,showVolume:!1,showPriceSource:!1,showBackground:!0,backgroundTransparency:0,showLogo:!0}),axisProperties:(0,h.deepExtend)({},y),separatorColor:""},w={lineColor:"",textColor:"",fontSize:0,scaleSeriesOnly:!1,showSeriesLastValue:!1,seriesLastValueMode:a.PriceAxisLastValueMode.LastValueAccordingToScale,showSeriesPrevCloseValue:!1,showStudyLastValue:!1,showSymbolLabels:!1,showStudyPlotLabels:!1,showBidAskLabels:!1,showPrePostMarketPriceLabel:!0,showFundamentalLastValue:!1,showFundamentalNameLabel:!1,showPriceScaleCrosshairLabel:!0,showTimeScaleCrosshairLabel:!0},P={...w},T={visible:!1,futureOnly:!1,breaks:(0,h.deepExtend)({},{color:"",visible:!1,style:0,width:0})},M={style:0,minTick:"",showPriceLine:!1,priceLineWidth:0,priceLineColor:"",baseLineColor:"",showPrevClosePriceLine:!1,showCountdown:!0,prevClosePriceLineWidth:0,sessionId:"regular",prevClosePriceLineColor:"",esdShowDividends:!1,esdShowSplits:!1,esdShowEarnings:!1,esdShowBreaks:!1,showContinuousContractSwitches:!1,showContinuousContractSwitchesBreaks:!1,showFuturesContractExpiration:!1,showLastNews:!1,dividendsAdjustment:!1,backAdjustment:!1,settlementAsClose:!0,statusViewStyle:(0,h.deepExtend)({},{fontSize:16,showExchange:!0,showInterval:!0,symbolTextSource:"description"}),priceAxisProperties:(0,h.deepExtend)({},y),bidAsk:(0,h.deepExtend)({},_),prePostMarket:(0,h.deepExtend)({},p.defaultPrePostMarketPreferences),volFootprintStyle:(0,h.deepExtend)({},S),tpoStyle:(0,h.deepExtend)({},v.tpoStylePreferencesDefault),volCandlesStyle:(0,h.deepExtend)({},r.candleStylePreferencesDefault),highLowAvgPrice:(0,h.deepExtend)({},{highLowPriceLinesVisible:!1,highLowPriceLabelsVisible:!1,averageClosePriceLabelVisible:!1,averageClosePriceLineVisible:!1,highLowPriceLinesColor:"",highLowPriceLinesWidth:0,averagePriceLineColor:"",averagePriceLineWidth:0}),candleStyle:(0,h.deepExtend)({},r.candleStylePreferencesDefault), hollowCandleStyle:(0,h.deepExtend)({},r.hollowCandlePreferencesStyleDefault),barStyle:(0,h.deepExtend)({},r.barStylePreferencesDefault),lineStyle:(0,h.deepExtend)({},r.lineStyleDefault),lineWithMarkersStyle:(0,h.deepExtend)({},r.lineStyleDefault),steplineStyle:(0,h.deepExtend)({},r.lineStyleDefault),areaStyle:(0,h.deepExtend)({},r.areaStylePreferencesDefault),hlcAreaStyle:(0,h.deepExtend)({},r.hlcAreaStylePreferencesDefault),baselineStyle:(0,h.deepExtend)({},r.baselineStylePreferencesDefault),hiloStyle:(0,h.deepExtend)({},r.hiloStylePreferencesDefault),haStyle:(0,h.deepExtend)({},r.haStylePreferencesDefault),renkoStyle:(0,h.deepExtend)({},r.renkoStylePreferencesDefault),pbStyle:(0,h.deepExtend)({},r.pbStylePreferencesDefault),kagiStyle:(0,h.deepExtend)({},r.kagiStylePreferencesDefault),pnfStyle:(0,h.deepExtend)({},r.pnfStylePreferencesDefault),rangeStyle:(0,h.deepExtend)({},r.rangeStylePreferencesDefault),columnStyle:(0,h.deepExtend)({},r.columnStylePreferencesDefault)},x={priceScaleSelectionStrategyName:"auto",timeScale:(0,h.deepExtend)({},{defaultRightOffset:0,defaultRightOffsetPercentage:5,usePercentageRightOffset:!1}),mainSeries:(0,h.deepExtend)({},M),sessions:(0,h.deepExtend)({},c.sessionsPreferencesDefault),paneProperties:(0,h.deepExtend)({},C),chartEventsSourceProperties:(0,h.deepExtend)({},T),tradingProperties:(0,h.deepExtend)({},o.tradingPreferencesDefault)},I={timezone:"",scalesProperties:(0,h.deepExtend)({},P),...x},A={scalesProperties:(0,h.deepExtend)({},w),...x};function L(e,t,i,o,r=!0){if(void 0===t[e])return f.logDebug(`We haven't had this property ${o}.${e} yet, please, remove it from whiteList`),null;if((0,s.isObject)(i[e])){const s=Object.keys(i[e]);let n="";return s.map((s=>({[s]:L(s,t[e],i[e],`${o}.${e}`,r)}))).reduce(((e,t)=>(n=Object.keys(t)[0],e[n]=t[n],e)),{})}return r?t[e].value():t[e]}function k(e,t,i=I){const s={timezone:"",priceScaleSelectionStrategyName:"auto",timeScale:{defaultRightOffset:e.timeScale().defaultRightOffset().value(),defaultRightOffsetPercentage:e.timeScale().defaultRightOffsetPercentage().value(),usePercentageRightOffset:e.timeScale().usePercentageRightOffset().value()},mainSeries:{},sessions:{},paneProperties:{},scalesProperties:{},chartEventsSourceProperties:{},tradingProperties:{}},o=["timeScale","mainSeries","sessions"],r=i.mainSeries,n=Object.keys(i),a=Object.keys(r),l=t.properties(),c=e.properties(),h=i.sessions,d=Object.keys(h),u=e.sessions().properties();return a.forEach((e=>{s.mainSeries[e]=L(e,l,r,"mainSeries")})),d.forEach((e=>{s.sessions[e]=L(e,u,h,"sessions")})),n.forEach((e=>{o.includes(e)||(s[e]=L(e,c,i,"preferences"))})),s}function E(e,t,i=A,s=!0){const o={timeScale:{defaultRightOffset:e.timeScale().rightOffsetDefaultValue(),defaultRightOffsetPercentage:e.timeScale().defaultRightOffsetPercentage().value(),usePercentageRightOffset:e.timeScale().usePercentageRightOffset().value()},mainSeries:{},sessions:(0,h.deepExtend)({},c.sessionsPreferencesDefault),paneProperties:{},scalesProperties:{},chartEventsSourceProperties:{},tradingProperties:{}, priceScaleSelectionStrategyName:"auto"},r=["timeScale","mainSeries","sessions"],n=i.mainSeries,a=Object.keys(i),d=Object.keys(n),u=(0,l.factoryDefaults)("chartproperties.mainSeriesProperties"),_=(0,l.factoryDefaults)("chartproperties");return d.forEach((e=>{s&&"style"===e||(o.mainSeries[e]=L(e,u,n,"mainSeries",!1))})),a.forEach((e=>{r.includes(e)||(o[e]=L(e,_,i,"preferences",!1))})),o}},480059:(e,t,i)=>{"use strict";i.d(t,{autoLogButtonsVisibilityOptions:()=>r,autoLogButtonsVisibilityProperty:()=>o,restoreAutoLogButtonsVisibilitySettingsValue:()=>n});var s=i(87053);const{property:o,availableValues:r,restoreDefaultValue:n}=(0,s.createVisibilityController)("PriceAxisAutoLogButtons.visibility")},838042:(e,t,i)=>{"use strict";i.d(t,{BarsMarksContainer:()=>m});var s=i(650151),o=i(201089),r=i(62802),n=i.n(r),a=i(244842),l=i(223699),c=i(389137),h=i(444331),d=i(996986),u=i(964824);const _=(0,o.getLogger)("Chart.BarsMarksContainer"),p=Math.round(new Date(2037,0,1).getTime()/1e3);class m extends d.DataSource{constructor(e,t,i){const o=e.onWidget();let r;r=o?!e.hideIdeas():!!a.enabled("bars_marks")&&n().getBool("BarsMarksContainer.visibile",!1),t.merge({visible:r}),t.childs().visible.subscribe(null,(t=>{o||e.isSnapshot()||!a.enabled("bars_marks")||n().setValue("BarsMarksContainer.visibile",!!t.value())})),super(i),this._paneViews=[],this._model=e,this._properties=t,this._requests=[],this._marks={},this._loadedRange=null,this._getDataTimeout=null,this._collectedRange=null,this._lastRange=null;const l=this._model.mainSeries();l.onSymbolIntervalChanged().subscribe(this,this.clearMarks),l.dataEvents().symbolResolved().subscribe(this,this.clearMarks),l.dataEvents().completed().subscribe(this,(()=>{var e,t;const i=l.data();if(0===i.size())return;const o=(0,s.ensureNotNull)(i.first()).index,r=(0,s.ensureNotNull)(i.last()).index,n=this.timeScale();this.getData({start:null!==(e=n.indexToTimePoint(o))&&void 0!==e?e:1/0,end:null!==(t=n.indexToTimePoint(r))&&void 0!==t?t:-1/0})})),this._initialize(),this._pinnedTooltips={}}destroy(){const e=this._model.mainSeries();e.onSymbolIntervalChanged().unsubscribeAll(this),e.dataEvents().symbolResolved().unsubscribeAll(this),e.dataEvents().completed().unsubscribeAll(this),super.destroy()}properties(){return this._properties}marks(){return this._marks}pinTooltip(e,t){this._pinnedTooltips[e]=t}timeScale(){return this._model.timeScale()}getIntervalInTicks(){const e=this._model.mainSeries().properties().childs().interval.value(),t=l.Interval.parse(e);if(!t.isValid())throw new TypeError("Unexpected interval");return t.isRange()?60:t.inMilliseconds()/1e3}getVisibleTickMarksRange(){var e,t;if(this.timeScale().isEmpty())return{start:0,end:0};const i=(0,s.ensureNotNull)(this.timeScale().visibleBarsStrictRange()),{firstIndex:o,lastIndex:r}=(0,s.ensureNotNull)(this.timeScale().points().range().value());if(!(i.lastBar()>o&&i.firstBar(){var o,r;const n=this._marks[s],a=n.tickmark;a>=(null!==(o=t.start)&&void 0!==o?o:1/0)&&a<=(null!==(r=t.end)&&void 0!==r?r:-1/0)+i&&e.push(n)})),e}getPublishedPlates(){const e={};return window.is_authenticated?(this.getVisibleRangePlates().forEach((t=>{t.is_public&&(this._pinnedTooltips[t.id]||t.user__id===window.user.id)&&(e[t.id]=t)})),e):e}filterDisplayedPlates(e){const t=e.reduce(((e,t)=>{const i=this._getIndex(t.tickmark);return null!==i&&(e[i]=e[i]||[],e[i].push(t)),e}),{});return Object.keys(t).reduce(((e,i)=>{let s=t[i];return s=s.sort(((e,t)=>t.views_count-e.views_count)),s=s.slice(0,10),e.concat(s)}),[])}getPlatesViewData(){var e,t,i;const o=this._model.mainSeries();if(o.data().isEmpty())return[];const r=(0,h.isPriceSourceStyle)(o.style())?o.barFunction():null,n=this.filterDisplayedPlates(this.getVisibleRangePlates()),a={},l=null!==(e=this._model.lastHittestData())&&void 0!==e?e:this._model.lastSelectedHittestData();let c=null;null!==l&&this._model.hoveredSource()===this&&(c=null!==(t=l.activeItem)&&void 0!==t?t:null);const d=[];for(const e of n){const t=(0,s.ensureNotNull)(this._getIndex(e.tickmark)),i=this._getBar(t);if(null===i)continue;const o=this._layout(e.direction),n=this._theme(e.direction),l=c===e.id,h=this.timeScale().indexToCoordinate(t),u=this._offset(o,i,r),_=(0,s.ensureNotNull)(this.priceScale()).isInverted();let p=0;t in a||(a[t]={up:0,down:0}),p=a[t][o]++,d.push({id:e.id,x:h,y:u,yInverted:_,order:p,direction:o,theme:n,hovered:l,pinned:!0===this._pinnedTooltips[e.id],user__id:e.user__id,label:e.label,labelFontColor:e.labelFontColor||"#444",minSize:e.minSize||5,...this._plateViewData(e)})}const u=d.filter((e=>!0===e.hovered));for(let e=0;ee.hovered&&!t.hovered?1:0)),d}priceAxisViews(){return null}updateAllViews(e){for(const t of this._paneViews)t.update(e)}updateAllViewsAndRepaint(){this.updateAllViews((0,u.sourceChangeEvent)(this.id())),this._model.updateSource(this)}roundRange(e){return{start:Math.round(e.start),end:Math.round(e.end)}}refreshData(){null!==this._lastRange&&this.getData(this._lastRange)}getData(e){(0,c.isNumber)(e.start)&&(0,c.isNumber)(e.end)?(this._lastRange=e,e.end=p,this._pushGetDataStack(Object.assign({},e))):_.logError("Wrong range")}clearMarks(){this._abortAllRequests(),this._marks={},this._loadedRange=null}isUserDeletable(){return!1}isSavedInChart(e){return!1}isSpeciallyZOrderedSource(){return!0}showInObjectTree(){return!1}_plateViewData(e){return{}}_layout(e){switch(e){default:case 0:case 2:case 3:case 4:case 5:case 6:return"up";case 1:return"down"}}_theme(e){switch(e){default:case 0:return"neutral";case 1:case 5:return"green";case 2:case 6:return"red";case 3:return"yellow";case 4:return"blue"}}_offset(e,t,i){ let o;switch(e){default:case"up":o=null===i?t[2]:i(t);break;case"down":o=null===i?t[3]:i(t)}return(0,s.ensureNotNull)(this.priceScale()).priceToCoordinate(o,(0,s.ensureNotNull)((0,s.ensureNotNull)(this.ownerSource()).firstValue()))}_getIndex(e){return this.timeScale().timePointToIndex(e)}_getBar(e){return this._model.mainSeries().data().valueAt(e)}_rangeDifference(e){return e=Object.assign({start:1/0,end:-1/0},e),this._loadedRange&&(e.startthis._loadedRange.end&&(e.start=this._loadedRange.end)),e}_rangeUnion(e,t){return e=Object.assign({start:1/0,end:-1/0},e),t&&(e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end)),e}_pushGetDataStack(e){(0,c.isNumber)(e.start)&&(0,c.isNumber)(e.end)?(this._getDataTimeout&&clearTimeout(this._getDataTimeout),this._collectedRange=this._rangeUnion(e,this._collectedRange),this._getDataTimeout=setTimeout((()=>{this._getData(this._collectedRange),this._getDataTimeout=this._collectedRange=null}),300)):_.logError("Wrong tickmark range")}_abortAllRequests(){this._requests.forEach((e=>{e.cancel()})),this._requests=[],this._getDataTimeout&&clearTimeout(this._getDataTimeout),this._getDataTimeout=this._collectedRange=null}}},384874:(e,t,i)=>{"use strict";i.d(t,{BarsRange:()=>o});var s=i(650151);class o{constructor(e,t){(0,s.assert)(e<=t,"The last bar in the bars range should be greater than or equal to the first bar"),this._firstBar=e,this._lastBar=t}firstBar(){return this._firstBar}lastBar(){return this._lastBar}count(){return this._lastBar-this._firstBar+1}contains(e){return this._firstBar<=e&&e<=this._lastBar}equals(e){return this._firstBar===e.firstBar()&&this._lastBar===e.lastBar()}static compare(e,t){return null===e||null===t?e===t:e.equals(t)}}},447285:(e,t,i)=>{"use strict";var s;i.d(t,{ChartEventsSourceId:()=>s}),function(e){e.Value="ChartEventsSource"}(s||(s={}))},23612:(e,t,i)=>{"use strict";i.d(t,{ChartModelBase:()=>Qs});var s=i(12481),o=i(343370),r=i(822914),n=i(650151),a=i(86441),l=i(724377),c=i(790188),h=i(444372),d=i(331633),u=i(429874),_=i(345848),p=i(268222),m=i(251954),g=i(49437),S=i(623551),v=i(507795),f=i(913984),b=i(674981),y=i(346825),C=i(713473);function w(e){return(0,C.isLineTool)(e)&&e.boundToSymbol()||(0,y.isAlertLabel)(e)}class P{constructor(){this._items=[],this._set=new Set,this._dataSourcesCache=null,this._customSourcesCache=null,this._lineSourcesCache=null}isEmpty(){return 0===this._items.length}add(e){if(this._items.length>0&&!w(this._items[0])&&this.clear(),w(e)){const t=(0,b.lowerbound)(this._items,e,((e,t)=>e.zorder()!(0,f.isDataSource)(e)))),this._customSourcesCache}checkLineToolSelection(){this._items.forEach((e=>(0,C.isLineTool)(e)&&e.calcIsActualSymbol())),this._items=this._items.filter((e=>!(0,C.isLineTool)(e)||e.isActualSymbol())),this._invalidateCache()}remove(e){this._items=this._items.filter((t=>t!==e)),this._set.delete(e),this._invalidateCache()}clear(){this._items=[],this._set.clear(),this._invalidateCache()}_invalidateCache(){this._customSourcesCache=null,this._dataSourcesCache=null,this._lineSourcesCache=null}}var T=i(388545),M=i(62745),x=i(306682),I=i(807218),A=i(223699),L=i(853965),k=i(190973),E=i(511131),D=i(422333);class N{constructor(e){this._rendererOptions={borderSize:1,additionalPaddingInner:0,fontSize:NaN,font:"",color:"",paneBackgroundColor:"",paddingBottom:0,paddingInner:0,paddingOuter:0,paddingTop:0,lineSpacing:0},this._chartModel=e}options(){const e=this._rendererOptions,t=this._chartModel.properties().childs(),i=t.scalesProperties.childs().fontSize.value();return e.fontSize!==i&&(e.fontSize=i,e.font=(0,E.makeFont)(i,D.CHART_FONT_FAMILY,""),e.paddingTop=i/12*2.5,e.paddingBottom=i/12*2.5,e.paddingInner=i/12*4,e.additionalPaddingInner=i/12*4,e.paddingOuter=i/12*4,e.lineSpacing=i/12*2),e.color=t.scalesProperties.childs().textColor.value(),e.paneBackgroundColor=t.paneProperties.childs().background.value(),this._rendererOptions}}var B=i(347710),R=i(405721),O=i(484812),V=i(624444),W=i(42292),F=i(949529),H=i(244842),z=i(444331),U=i(530239),G=i(964824);const q=new V.PriceFormatter,j="sessions";class Y extends F.CustomSourceBase{constructor(e,t,i){super(e,t),this._studySource=null,this._paneViews=[],this._metaInfo=null,this._destroyed=!1,this._isStarted=!1,this._loadedGraphics=null,this._doubleClickHandler=i,this._properties=new L.DefaultProperty("sessions"),(0,W.applyDefaultsOverrides)(this._properties.childs().graphics,void 0,!1,j),this._removeDuplicateProperties(),this._properties.subscribe(this,this._onPropertiesChanged),this._requestAndProcessMetaInfo(),t.timeScale().onReset().subscribe(this,this._clearData),t.timeScale().logicalRangeChanged().subscribe(this,this.updateAllViews.bind(this,(0,G.viewportChangeEvent)())),t.mainSeries().sessionIdProxyProperty().subscribe(this,this._updateVisibleOfPreAndPostMarketBackground),t.mainSeries().properties().childs().interval.subscribe(this,this._processHibernate),this._updateVisibleOfPreAndPostMarketBackground(t.mainSeries().properties().childs().sessionId)}applyOverrides(e){(0,W.applyPropertiesOverrides)(this._properties.childs().graphics,void 0,!1,e,j),this._model.updateSource(this)}start(){this._isStarted=!0,this._processHibernate()}restart(){this._clearData(),H.enabled("stop_study_on_restart")&&this.stop(),this.start()}isStarted(){return this._isStarted}stop(){this._isStarted=!1,null!==this._studySource&&this._studySource.stop()} isHoveredEnabled(){return!1}paneViews(e){return this._paneViews}updateAllViews(e){this._paneViews.forEach((t=>t.update(e)))}updateViewsForPane(e,t){this.updateAllViews(t)}destroy(){this._destroyed=!0,null!==this._studySource&&(this._studySource.dataCleared().unsubscribeAll(this),this._studySource.dataUpdated().unsubscribeAll(this),this._studySource.destroy(),this._studySource=null),this._model.timeScale().logicalRangeChanged().unsubscribeAll(this),this._model.timeScale().onReset().unsubscribeAll(this),this._model.mainSeries().sessionIdProxyProperty().unsubscribeAll(this),this._model.mainSeries().properties().childs().interval.unsubscribeAll(this),this._properties.unsubscribeAll(this)}series(){return this._model.mainSeries()}priceScale(){return this.series().priceScale()}graphics(){return this._loadedGraphics||(0,n.ensureNotNull)(this._studySource).graphics()}valueAt(e,t){return null}properties(){return this._properties}graphicsInfo(){return(0,n.ensureNotNull)(this._metaInfo).graphics}firstValue(e){return this._model.mainSeries().firstValue()}formatter(){return q}state(e){const t={properties:this._properties.state()};return e&&null!==this._metaInfo&&(t.data={graphics:(0,O.saveStudyGraphics)(this.graphics(),this._model.timeScale().visibleBarsStrictRange()),metaInfo:this._metaInfo}),t}restoreState(e,t){const i=e.properties;this._migrateOutOfSessionProperty(i),this._properties.mergeAndFire(i),this._removeDuplicateProperties(),this._updateVisibleOfPreAndPostMarketBackground(this._model.mainSeries().properties().childs().sessionId),void 0!==e.data&&t&&(this._loadStudyGraphics(e.data.graphics),this._setMetaInfo(e.data.metaInfo),this._createPaneViews())}restoreOldState(e,t){const i={properties:{graphics:e.state.graphics}};void 0!==e.data&&void 0!==e.metaInfo&&t&&(i.data={metaInfo:e.metaInfo,graphics:e.data.graphics}),this.restoreState(i,t)}applyPreferences(e){this._properties.mergePreferences(e)}metaInfo(){return(0,n.ensureNotNull)(this._metaInfo)}async _requestAndProcessMetaInfo(){if(this._model.isSnapshot())return;const e=await(0,B.studyMetaInfoRepository)().findById({type:"java",studyId:"Sessions@tv-basicstudies"});this._destroyed||null===this._loadedGraphics&&(this._setMetaInfo(e),null!==this._metaInfo&&(this._studySource=new R.StudyDataSource(this._model.chartApi(),this._model.mainSeries().seriesSource(),"sessions_",this._metaInfo),this._createPaneViews(),this._studySource.dataCleared().subscribe(this,this.updateAllViews.bind(this,(0,G.sourceChangeEvent)(this.id()))),this._studySource.dataUpdated().subscribe(this,this.updateAllViews.bind(this,(0,G.sourceChangeEvent)(this.id()))),this._studySource.setInputs({}),this._processHibernate()))}_loadStudyGraphics(e){const t=e.backgrounds;if(void 0!==t){const e=t.findIndex((e=>"inSession"===e.styleId));-1!==e&&t.splice(e,1)}this._loadedGraphics=(0,O.loadStudyGraphics)(e)}_setMetaInfo(e){const t=e.graphics.backgrounds;void 0!==t&&void 0!==t.inSession&&delete t.inSession,this._metaInfo=e}_updateVisibleOfPreAndPostMarketBackground(e){const t=!(0,z.isRegularSessionId)(e.value()) ;this._outOfSessionVisibilityProperty().setValue(t),this._preMarketVisibilityProperty().setValue(t),this._postMarketVisibilityProperty().setValue(t)}_clearData(){null!==this._studySource&&this._studySource.clearData()}_createPaneViews(){const e={doubleClickHandler:this._doubleClickHandler};(0,O.createGraphicsPaneViews)(this,this._model,e).then((e=>{this._paneViews=e,this._model.lightUpdate()}))}_onPropertiesChanged(){this._processHibernate(),this.updateAllViews((0,G.sourceChangeEvent)(this.id()))}_processHibernate(){if(null!==this._studySource){const e=this._canBeHibernated(),t=this._isHibernated(),i=this._studySource.isStarted();!t&&e&&i?this._studySource.stop():!t||e||i||this._studySource.start()}}_canBeHibernated(){const e=this._model.mainSeries(),t=this._preMarketVisibilityProperty().value()&&this._postMarketVisibilityProperty().value()&&this._outOfSessionVisibilityProperty().value();return e.isDWM()||!t&&!this._vertLinesVisibleProperty().value()}_isHibernated(){return this._isStarted&&(null===this._studySource||!this._studySource.isStarted())}_outOfSessionVisibilityProperty(){return this._properties.childs().graphics.childs().backgrounds.childs().outOfSession.childs().visible}_preMarketVisibilityProperty(){return this._properties.childs().graphics.childs().backgrounds.childs().preMarket.childs().visible}_postMarketVisibilityProperty(){return this._properties.childs().graphics.childs().backgrounds.childs().postMarket.childs().visible}_vertLinesVisibleProperty(){return this._properties.childs().graphics.childs().vertlines.childs().sessBreaks.childs().visible}_removeDuplicateProperties(){this._properties.hasChild("properties")&&(this._properties.removeProperty("properties"),(0,L.saveDefaultProperties)(!0),this._properties.childChanged(null,""),(0,L.saveDefaultProperties)(!1))}_migrateOutOfSessionProperty(e){const t=e.graphics.backgrounds;if(void 0!==t){const i=t.outOfSession;i.color===(0,n.ensureDefined)(U.sessionsPreferencesDefault.graphics.backgrounds).outOfSession.color||"postMarket"in t||(e.graphics.backgrounds={...t,postMarket:{color:i.color,transparency:i.transparency,visible:i.visible},preMarket:{color:i.color,transparency:i.transparency,visible:i.visible}})}}}var K=i(427937),Z=i(707957),$=i(401580),X=i(938550),J=i(572230),Q=i(261066),ee=i(480059),te=i(201089),ie=i(541558),se=i(234271),oe=i(944876),re=i(526075),ne=i(389137),ae=i(14802),le=i(627817),ce=i(459711),he=i(924788),de=i(811630),ue=i(974655),_e=i(888929);const pe=new Map([["price",e=>(0,ue.isPriceDataSource)(e)],["trading",e=>(0,C.isTrading)(e)],["drawing",e=>(0,C.isLineTool)(e)&&!(0,C.isTrading)(e)&&!e.isPhantom()],["drawingsForAllSymbols",e=>(0,C.isLineTool)(e)&&!(0,C.isTrading)(e)&&!e.isPhantom()],["phantom",e=>(0,C.isLineTool)(e)&&e.isPhantom()],["restRowSources",e=>!(0,C.isLineTool)(e)&&!(0,C.isTrading)(e)],["legendViewSources",e=>(0,ue.isPriceDataSource)(e)||(0, C.isStudyLineTool)(e)],["leftPriceScale",(e,t)=>"left"===ge(e,t)],["rightPriceScale",(e,t)=>"right"===ge(e,t)],["overlayPriceScale",(e,t)=>"overlay"===ge(e,t)]]),me=new Map([["price","visibleSorted"],["trading","visibleSorted"],["drawing","visibleSorted"],["drawingsForAllSymbols","allSorted"],["phantom","visibleSorted"],["restRowSources","visibleSorted"],["legendViewSources","visibleSorted"],["leftPriceScale","visibleSorted"],["rightPriceScale","visibleSorted"],["overlayPriceScale","visibleSorted"]]);function ge(e,t){const i=e.priceScale();return null===i?"overlay":t.priceScalePosition(i)}class Se{constructor(e){this._groupedSources=new Map,this._sources=null,this._pane=e}clear(){this._groupedSources.clear(),this._sources=null}destroy(){this.clear()}all(){return this._groupedSources.has("visibleSorted")||this._sortSources(),(0,n.ensureDefined)(this._groupedSources.get("visibleSorted"))}allIncludingHidden(){return this._groupedSources.has("allSorted")||this._sortSources(),(0,n.ensureDefined)(this._groupedSources.get("allSorted"))}allExceptSpecialSources(){if(!this._groupedSources.has("exceptSpecial")){const e=this.allIncludingHidden().filter((e=>!e.isSpeciallyZOrderedSource()));this._groupedSources.set("exceptSpecial",e)}return(0,n.ensureDefined)(this._groupedSources.get("exceptSpecial"))}tradingSources(){return this._getSourcesByGroupType("trading")}priceSources(){return this._getSourcesByGroupType("price")}lineSources(){return this._getSourcesByGroupType("drawing")}lineSourcesForAllSymbols(){return this._getSourcesByGroupType("drawingsForAllSymbols")}phantomSources(){return this._getSourcesByGroupType("phantom")}allExceptLineAndTradingSources(){return this._getSourcesByGroupType("restRowSources")}hitTestSources(){if(!this._groupedSources.has("hitTest")){const e=this.allExceptLineAndTradingSources().concat(this.lineSources());this._groupedSources.set("hitTest",e)}return(0,n.ensureDefined)(this._groupedSources.get("hitTest"))}generalSources(){if(!this._groupedSources.has("general")){const e=this.allExceptLineAndTradingSources().concat(this.lineSources());this._groupedSources.set("general",(0,_e.sortSources)(e))}return(0,n.ensureDefined)(this._groupedSources.get("general"))}leftPriceScalesSources(){return this._getSourcesByGroupType("leftPriceScale")}rightPriceScalesSources(){return this._getSourcesByGroupType("rightPriceScale")}overlayPriceScaleSources(){return this._getSourcesByGroupType("overlayPriceScale")}legendViewSources(){return this._getSourcesByGroupType("legendViewSources")}_getSourcesByGroupType(e){const t=(0,n.ensureDefined)(me.get(e));return this._groupedSources.has(t)?this._groupedSources.has(e)||this._groupSources(e):(this._sortSources(),this._groupSources(e)),(0,n.ensureDefined)(this._groupedSources.get(e))}_sortSources(){null===this._sources&&(this._sources=this._pane.dataSources());const e=(0,_e.sortSources)(this._sources),t=e.filter((e=>!(0,C.isLineTool)(e)||e.isActualSymbol()&&e.isActualCurrency()&&e.isActualUnit()));this._groupedSources.set("allSorted",e), this._groupedSources.set("visibleSorted",t)}_groupSources(e){const t=(0,n.ensureDefined)(me.get(e)),i=pe.get(e);if(void 0!==i){const s=(0,n.ensureDefined)(this._groupedSources.get(t)).filter((e=>i(e,this._pane)));this._groupedSources.set(e,s)}}}var ve=i(616117),fe=i(291784),be=i(740086),ye=i(440617),Ce=i(981107),we=i(438907),Pe=i(960521),Te=i(678515);function Me(e,t,i){const s=e.div(t).toNumber();return Math.abs(Math.round(s)-s)100)throw new Error("something wrong with base")}}}tickSpan(e,t,i){const s=0===this._base?0:1/this._base,o=Math.min(1e-14,(e-t)/1e3);let r=Math.pow(10,Math.max(0,Math.ceil((0,Te.log10)(e-t))));if(!isFinite(r))return 1e305;let n=0,a=this._integralDividers[0];for(;;){const e=(0,Te.greaterOrEqual)(r,s,o)&&r>s+o,t=(0,Te.greaterOrEqual)(r,i*a,o),l=(0,Te.greaterOrEqual)(r,1,o),c=new Pe.Big(r).div(a),h=0===s||Me(c,s,o);if(!(e&&t&&l&&h))break;r=c.toNumber(),a=this._integralDividers[++n%this._integralDividers.length]}if(r<=s+o&&(r=s),r=Math.max(1,r),this._fractionalDividers.length>0&&(0,Te.equal)(r,1,o))for(n=0,a=this._fractionalDividers[0];;){const e=(0,Te.greaterOrEqual)(r,i*a,o)&&r>s+o,t=new Pe.Big(r).div(a),l=0===s||Me(t,s,o);if(!e||!l)break;r=t.toNumber(),a=this._fractionalDividers[++n%this._fractionalDividers.length]}return r}}class Le{constructor(e,t,i,s){this._marks=null,this._priceScale=e,this._base=t,this._coordinateToLogicalFunc=i,this._logicalToCoordinateFunc=s}base(){return this._base}setBase(e){if(e<0)throw new Error("base < 0");this._base=e}tickSpan(e,t,i=0){if(e{const n=o.tickSpan(e,t,r);return n>i?Math.min(n,s):s}),1/0);return n>0&&isFinite(n)?n:e-t}rebuildTickMarks(){this._marks=null}marks(){return null===this._marks&&(this._marks=this._rebuildTickMarksImpl()),this._marks}_fontHeight(){return this._priceScale.fontSize()}_tickMarkHeight(){return Math.ceil(2.5*this._fontHeight())}_rebuildTickMarksImpl(){const e=this._priceScale,t=[],i=e.mainSource();if(e.isEmpty()||null===i)return t;let s=i.firstValue();null===s&&(s=0);const o=e.height(),r=this._coordinateToLogicalFunc(o-1,s),n=this._coordinateToLogicalFunc(0,s),a=Math.max(r,n),l=Math.min(r,n);if(a===l)return t;let c=this.tickSpan(a,l),h=a%c;h+=h<0?c:0;const d=a>=l?1:-1;let u=null;const _=e.formatter();let p=NaN;for(let i=a-h;i>l;i-=c){i===p&&(c=this.tickSpan(a,l,c)),p=i;const o=this._logicalToCoordinateFunc(i,s) ;null!==u&&Math.abs(o-u){const e=this.mainSource();if(e&&e.model()){const t=e.model().paneForSource(e);t&&e.model().updatePane(t)}})),this._scalesProperties.subscribe(this,(()=>{this._marksCache=null})),this._properties.childs().lockScale.subscribe(this,this._updateResetAvailableValue),this._properties.childs().autoScale.subscribe(this,this._updateResetAvailableValue),this._updateResetAvailableValue(),this.setId((0,ie.randomHash)())}id(){return this._id}setId(e){this._id=e}isLog(){return this._properties.childs().log.value()}isPercentage(){return this._properties.childs().percentage.value()}isInverted(){return this._properties.childs().isInverted.value()}isIndexedTo100(){return this._properties.childs().indexedTo100.value()}isAutoScale(){return this._properties.childs().autoScale.value()&&!this.isLockScale()}isLockScale(){return this._properties.childs().lockScale.value()}isRegular(){return!this.isPercentage()&&!this.isLog()&&!this.isIndexedTo100()}properties(){ return this._properties}height(){return this.m_height}setHeight(e){this.m_height!==e&&(this.m_height=e,this._invalidateInternalHeightCache(),this._marksCache=null)}internalHeight(){if(this._internalHeightCache)return this._internalHeightCache;const e=this.height()-this.topPixelMargin()-this.bottomPixelMargin();return this._internalHeightCache=e,e}fontSize(){return this._scalesProperties.childs().fontSize.value()}priceRange(){return this._makeSureItIsValid(),this.m_priceRange}setPriceRange(e,t,i){if(!(e instanceof fe.PriceRange))throw new TypeError("incorrect price range");const s=this.m_priceRange;if(!t&&fe.PriceRange.compare(s,e))return;const o=null!==this._maxPriceRange&&this._maxPriceRange.containsStrictly(e),r=null!==this._minPriceRange&&e.containsStrictly(this._minPriceRange);this.isLockScale()&&!t&&(o||r)||(this._marksCache=null,this.m_priceRange=e,i||this._priceRangeChanged.fire(s,e))}setMinPriceRange(e){this._minPriceRange=e}setMaxPriceRange(e){this._maxPriceRange=e}recalculatePriceRangeOnce(){this._recalculatePriceRangeOnce=!0}priceRangeShouldBeRecalculatedOnce(){if(!this._recalculatePriceRangeOnce||this.isLockScale())return!1;const e=this.mainSource();return null!==e&&e.priceRangeReady()}priceRangeChanged(){return this._priceRangeChanged}mode(){const e=this._properties.childs();return{autoScale:e.autoScale.value(),lockScale:e.lockScale.value(),percentage:e.percentage.value(),indexedTo100:e.indexedTo100.value(),log:e.log.value()}}setMode(e){const t={},i=this.mode(),s=this._properties.state();let o=null;void 0!==e.autoScale&&e.autoScale!==s.autoScale&&(t.autoScale=e.autoScale,this._setAutoScaleValueWithDependentProperties(e.autoScale)),void 0!==e.lockScale&&e.lockScale!==s.lockScale&&(t.lockScale=e.lockScale,this._setLockScaleValueWithDependentProperties(e.lockScale)),void 0!==e.percentage&&e.percentage!==s.percentage&&(t.percentage=e.percentage,this._setPercentageValueWithDependentProperties(e.percentage),this._invalidatedForRange.isValid=!1),void 0!==e.indexedTo100&&e.indexedTo100!==s.indexedTo100&&(t.indexedTo100=e.indexedTo100,this._setIndexedTo100ValueWithDependentProperties(e.indexedTo100),this._invalidatedForRange.isValid=!1),void 0!==e.log&&e.log!==s.log&&(t.log=e.log,this._setLogValueWithDependentProperties(e.log));const r=this._properties.childs();s.log&&!r.log.value()&&(this._canConvertPriceRangeFromLog(this.m_priceRange)?(o=this._convertPriceRangeFromLog(this.m_priceRange),null!==o&&this.setPriceRange(o)):r.autoScale.setValue(!0)),!s.log&&r.log.value()&&(o=this._convertPriceRangeToLog(this.m_priceRange),null!==o&&this.setPriceRange(o)),s.autoScale!==r.autoScale.value()&&r.autoScale.listeners().fire(r.autoScale,""),s.autoScaleDisabled!==r.autoScaleDisabled.value()&&r.autoScaleDisabled.listeners().fire(r.autoScaleDisabled,""),s.lockScale!==r.lockScale.value()&&r.lockScale.listeners().fire(r.lockScale,""),s.percentage!==r.percentage.value()&&(r.percentage.listeners().fire(r.percentage,""),this.updateFormatter()), s.indexedTo100!==r.indexedTo100.value()&&(r.indexedTo100.listeners().fire(r.indexedTo100,""),this.updateFormatter()),s.percentageDisabled!==r.percentageDisabled.value()&&r.percentageDisabled.listeners().fire(r.percentageDisabled,""),s.log!==r.log.value()&&r.log.listeners().fire(r.log,""),s.logDisabled!==r.logDisabled.value()&&r.logDisabled.listeners().fire(r.logDisabled,""),void 0===t.log&&void 0===t.percentage&&void 0===t.lockScale&&void 0===t.autoScale&&void 0===t.indexedTo100||this._modeChanged.fire(i,this.mode())}modeChanged(){return this._modeChanged}isEmpty(){return this._makeSureItIsValid(),0===this.m_height||!this.m_priceRange||this.m_priceRange.isEmpty()}canDetachSource(e){return this.m_dataSources.some((t=>t!==e&&!(0,he.isLollipopDataSource)(t)&&(0,ue.isPriceDataSource)(t)&&!((0,K.isStudy)(t)&&t.isLinkedToSeries())))}updateAllViews(e){const t=this._getSourcesToUpdateViews();for(const i of t)i.updateAllViews(e)}logFormula(){return this._logFormula}state(){var e;const t=this._properties.childs();return{id:this._id,m_priceRange:this.isAutoScale()?null:(null===(e=this.priceRange())||void 0===e?void 0:e.serialize())||null,m_isAutoScale:this.isAutoScale(),m_isPercentage:t.percentage.value(),m_isIndexedTo100:t.indexedTo100.value(),m_isLog:t.log.value(),m_isLockScale:this.isLockScale(),m_isInverted:this.isInverted(),m_topMargin:this._margins.top,m_bottomMargin:this._margins.bottom,alignLabels:t.alignLabels.value(),logFormula:(0,ne.clone)(this._logFormula)}}restoreState(e){let t=e.m_priceRange;if(void 0===t)throw new TypeError("invalid state");if(void 0===e.m_isAutoScale)throw new TypeError("invalid state");void 0!==e.id&&(this._id=e.id);const i={autoScale:e.m_isAutoScale};void 0!==e.m_isPercentage&&(i.percentage=e.m_isPercentage),void 0!==e.m_isIndexedTo100&&(i.indexedTo100=e.m_isIndexedTo100),void 0!==e.m_isLog&&(i.log=e.m_isLog),void 0!==e.m_isLockScale&&(i.lockScale=e.m_isLockScale),void 0!==e.m_isInverted&&this._properties.childs().isInverted.setValue(e.m_isInverted),this.setMode(i),t?(t instanceof fe.PriceRange||(t=new fe.PriceRange(t)),this.setPriceRange(t,!0)):this.clearPriceRange(),e.logFormula&&(this._logFormula=e.logFormula),void 0!==e.m_topMargin&&(this._margins.top=e.m_topMargin),void 0!==e.m_bottomMargin&&(this._margins.bottom=e.m_bottomMargin),void 0!==e.alignLabels&&this._properties.childs().alignLabels.setValue(e.alignLabels),this._mainSource=null,this._scaleSeriesOnly=!1}priceToLogical(e){return this.isLog()&&e?(0,be.toLog)(e,this._logFormula):e}logicalToPrice(e){return this.isLog()?(0,be.fromLog)(e,this._logFormula):e}priceToCoordinate(e,t){const i=this._priceToPercentOrIndexedTo100IfNeeded(e,t);return this._logicalToCoordinate(i)}coordinateToPrice(e,t){let i=this._coordinateToLogical(e);return this.isPercentage()?i=(0,be.fromPercent)(i,t):this.isIndexedTo100()&&(i=(0,be.fromIndexedTo100)(i,t)),i}mainSource(){if(null!==this._mainSource)return this._mainSource;let e;for(const t of this._priceDataSources){if(t instanceof ye.Series){e=t;break}e||(e=t)}return this._mainSource=e||null, this._correctedMarginsCache=null,this._mainSource}priceToCoordinateFn(e){this._makeSureItIsValid();const t=this.bottomPixelMargin(),i=(0,n.ensureNotNull)(this.priceRange()),s=i.minValue(),o=i.maxValue(),r=this.internalHeight()-1,a=this.isInverted(),l=r/(o-s),c=this.m_height,h=e=>{const i=t+l*(e-s);return a?i:c-1-i};return this.isPercentage()?t=>h((0,be.toPercent)(t,e)):this.isIndexedTo100()?t=>h((0,be.toIndexedTo100)(t,e)):this.isLog()?e=>h((0,be.toLog)(e,this._logFormula)):e=>h(e)}pricesArrayToCoordinates(e,t,i){this._makeSureItIsValid();const s=this.bottomPixelMargin(),o=(0,n.ensureNotNull)(this.priceRange()),r=o.minValue(),a=o.maxValue(),l=this.internalHeight()-1,c=this.isInverted(),h=l/(a-r);void 0===i&&(i=e.length);const d=this.isPercentage(),u=this.isIndexedTo100(),_=this.isLog(),p=this.m_height;let m,g;for(let o=0;oe?(0,be.toLog)(e,this._logFormula):e),0===s.length)return;const h="open"in s[0],d="close"in s[0];if(null!==c)for(let e=0;e0){const t=(0,we.unitConvertibleGroups)(d,_,e);l=(0,b.intersect)(l,new Set(t))}h+=1}if(null!==t)for(const i of this._priceDataSources){if(u.includes(i))continue;const c=i;if(!c.isUnitSource()||!c.isVisible())continue;const h=c.unit();if(null===h){t=null;break}s.add(h),d+=1;const _=(0,n.ensureNotNull)(c.symbolSource()),p=_.symbolInfo();if(null===p){t=null;break}if(l.size>0){const t=(0,we.unitConvertibleGroups)(p,h,e);l=(0,b.intersect)(l,new Set(t))}if(o.set(h,e.name(h)),r.set(h,e.description(h)),u.includes(_)||(l=new Set),void 0===a)a=h;else if(null!==a&&a!==h){a=null;break}}if(void 0===t)if(0===h&&0===d)t=null;else{t={availableGroups:l,selectedUnit:a||null,units:s,originalUnits:i,symbolSourceCount:h,allUnitsAreOriginal:c,names:o, descriptions:r}}return this._unitCache={value:t,availableUnitsCount:e.size()},t}measureUnitId(e){if(null!==this._measureUnitIdCache&&e.size()===this._measureUnitIdCache.availableUnitsCount)return this._measureUnitIdCache.value;let t,i;const s=new Map,o=new Map,r=new Set;let n=0;const a=this._seriesLikeSources.filter(Ce.isActingAsSymbolSource);for(const l of a){if(!l.isVisible())continue;const a=l.measureUnitId();if(null===a){t=null;break}r.add(a),s.set(a,e.name(a)),o.set(a,e.description(a)),void 0===i?i=a:null!==i&&i!==a&&(i=null),n+=1}return void 0===t&&(t=0===n?null:{selectedMeasureUnitId:i||null,measureUnitIds:r,names:s,descriptions:o,symbolSourceCount:n}),this._measureUnitIdCache={value:t,availableUnitsCount:e.size()},t}setMargins(e){if(!(0,ne.isNumber)(e.top)||!(0,ne.isNumber)(e.bottom))throw new TypeError("invalid margin");if(e.top<0||e.top>30||e.bottom<0||e.bottom>30)throw new RangeError("invalid margin");this._margins.top===e.top&&this._margins.bottom===e.bottom||(this._margins=e,this._correctedMarginsCache=null,this._invalidateInternalHeightCache(),this._marksCache=null)}topMargin(){return this._correctedMargins().top}bottomMargin(){return this._correctedMargins().bottom}invalidateMargins(){this._correctedMarginsCache=null}topPixelMargin(){return this.isInverted()?this.bottomMargin()*this.height()+this._bottomPixelMargin:this.topMargin()*this.height()+this._topPixelMargin}bottomPixelMargin(){return this.isInverted()?this.topMargin()*this.height()+this._topPixelMargin:this.bottomMargin()*this.height()+this._bottomPixelMargin}marks(){return this.isEmpty()?(this._marksCache=null,[]):(null===this._marksCache&&(this._markBuilder.rebuildTickMarks(),this._marksCache=this._markBuilder.marks(),this._onMarksChanged.fire()),this._marksCache)}onMarksChanged(){return this._onMarksChanged}priceRangeInPrice(){if(this.isEmpty())return null;const e=this.mainSource();if(null===e)return null;const t=(0,n.ensureNotNull)(e.firstValue()),i=this.height();return{from:this.coordinateToPrice(i-1,t),to:this.coordinateToPrice(0,t)}}setPriceRangeInPrice(e){if(this.isPercentage()||this.isIndexedTo100())return;const t=this.isInverted(),i=t?this.bottomMargin():this.topMargin(),s=t?this.topMargin():this.bottomMargin(),o=this.isLog();let r=o?(0,be.toLog)(e.from,this._logFormula):e.from,n=o?(0,be.toLog)(e.to,this._logFormula):e.to;const a=n-r;r+=s*a,n-=i*a,this.setMode({autoScale:!1}),this.setPriceRange(new fe.PriceRange(r,n)),this._marksCache=null,this._onMarksChanged.fire()}hasMainSeries(){return this._hasSeries}getStudies(){return this.dataSources().filter(K.isStudy)}lastSourceRemoved(){return this._lastSourceRemoved}sourcesForAutoscale(){return this._mainSource&&this._scaleSeriesOnly!==this._scalesProperties.childs().scaleSeriesOnly.value()&&(this._sourcesForAutoscale=null),this._sourcesForAutoscale||(this._sourcesForAutoscale=this._recalculateSourcesForAutoscale()),this._sourcesForAutoscale}recalculatePriceRange(e){this._invalidatedForRange={visibleBars:e,isValid:!1}}internalHeightChanged(){return this._internalHeightChanged} orderedSources(){if(this._cachedOrderedSoruces)return this._cachedOrderedSoruces;let e=this.m_dataSources.slice();return e=e.filter((e=>!(0,he.isLollipopDataSource)(e))),e=(0,_e.sortSources)(e),this._cachedOrderedSoruces=e,this._cachedOrderedSoruces}invalidateSourcesCache(){this._cachedOrderedSoruces=null,this._sourcesToUpdateViews=null}startScale(e){var t,i;this.isEmpty()||this.isPercentage()||this.isIndexedTo100()||null!==this._scaleStartPoint||null!==this._priceRangeSnapshot||(this._scaleStartPoint=this.m_height-e,this._priceRangeSnapshot=null!==(i=null===(t=this.priceRange())||void 0===t?void 0:t.clone())&&void 0!==i?i:null)}scaleTo(e){if(this.isPercentage()||this.isIndexedTo100()||null===this._scaleStartPoint)return;this.setMode({autoScale:!1}),(e=this.m_height-e)<0&&(e=0);let t=(this._scaleStartPoint+.2*(this.m_height-1))/(e+.2*(this.m_height-1));const i=(0,n.ensureNotNull)(this._priceRangeSnapshot).clone();t=Math.max(t,.1),i.scaleAroundCenter(t),this.setPriceRange(i)}endScale(){this.isPercentage()||this.isIndexedTo100()||null!==this._scaleStartPoint&&(this._scaleStartPoint=null,this._priceRangeSnapshot=null)}startTwoPointsScale(e,t){if(this.isEmpty()||this.isPercentage()||this.isIndexedTo100()||null!==this._twoPointsScaleStartPosition)return;const i=Math.min(e,t),s=Math.max(e,t);this._twoPointsScaleStartPosition={topLogical:this._coordinateToLogical(i),bottomLogical:this._coordinateToLogical(s)}}twoPointsScale(e,t){if(this.isPercentage()||this.isIndexedTo100()||null===this._twoPointsScaleStartPosition)return;this.setMode({autoScale:!1});const i=Math.min(e,t),s=Math.max(e,t),{topLogical:o,bottomLogical:r}=this._twoPointsScaleStartPosition,n=this.bottomPixelMargin(),a=this.internalHeight()-1,l=(this._invertedCoordinate(i)-n)/a,c=(r-o)/((this._invertedCoordinate(s)-n)/a-l);if(!Number.isFinite(c))return;const h=o-c*l,d=h+c;this.setPriceRange(new fe.PriceRange(this.priceToLogical(h),this.priceToLogical(d)))}endTwoPointsScale(){this._twoPointsScaleStartPosition=null}startScroll(e){var t,i;this.isAutoScale()||null===this._scrollStartPoint&&null===this._priceRangeSnapshot&&(this.isEmpty()||(this._scrollStartPoint=e,this._priceRangeSnapshot=null!==(i=null===(t=this.priceRange())||void 0===t?void 0:t.clone())&&void 0!==i?i:null))}scrollTo(e){if(this.isAutoScale())return;if(null===this._scrollStartPoint||null===this._priceRangeSnapshot)return;const t=this.priceRange();if(null===t)return;let i=e-this._scrollStartPoint;this.isInverted()&&(i*=-1);const s=i*(t.length()/(this.internalHeight()-1)),o=this._priceRangeSnapshot.clone();o.shift(s),this.setPriceRange(o,!0),this._marksCache=null}endScroll(){this.isAutoScale()||null!==this._scrollStartPoint&&(this._scrollStartPoint=null,this._priceRangeSnapshot=null)}clearPriceRange(){this.m_priceRange=null,this.recalculatePriceRangeOnce()}isVisible(){return this._isVisible}_addDataSourceImpl(e,t,i){if(t||-1===this.m_dataSources.indexOf(e)){if((0,ue.isPriceDataSource)(e)){if(void 0===i?this._priceDataSources.push(e):this._priceDataSources.splice(i,0,e), e.currencyChanged().subscribe(this,(()=>this._currencyCache=null)),e.unitChanged().subscribe(this,(()=>this._unitCache=null)),(0,Ce.isSymbolSource)(e)&&(this._seriesLikeSources.push(e),e.symbolResolved().subscribe(this,(()=>{this._currencyCache=null,this._unitCache=null,this._measureUnitIdCache=null})),e.isActingAsSymbolSource().subscribe(this._boundOnSourceIsActingAsSymbolSourceChanged),e instanceof ye.Series)){const t=e.properties();this._hasSeries||(t.childs().lockScale&&(this.setMode({lockScale:t.childs().lockScale.value()}),t.removeProperty("lockScale")),t.childs().pnfStyle.child("lockScale")&&t.childs().pnfStyle.removeProperty("lockScale")),this._hasSeries=!0}e.isSpeciallyZOrderedSource()||(this._sourcesThatAffectVisibility.push(e),e.properties().childs().visible.listeners().subscribe(this,this._onSourceVisibilityChanged))}(0,K.isStudy)(e)&&(e.onIsActualIntervalChange().subscribe(this,this._dropScaleCache),e.onHibernationStateChange().subscribe(this,this._dropScaleCache),0===this._studiesCount&&(0,ke.hideAllIndicators)().subscribe(this,this._dropScaleCache),this._studiesCount++),(0,C.isLineTool)(e)&&(0===this._drawingCount&&(0,ke.hideAllDrawings)().subscribe(this,this._dropScaleCache),this._drawingCount++),this.m_dataSources.push(e),this._mainSource=null,this.mainSource()===e&&(this._correctedMarginsCache=null,this._internalHeightCache=null,this._marksCache=null),this._dropScaleCache(),this.updateFormatter(),this._initScaleProperties(),this.invalidateSourcesCache(),this._updateIsVisible()}}_recalculateSourcesForAutoscale(){this._mainSource&&(this._scaleSeriesOnly=this._scalesProperties.childs().scaleSeriesOnly.value());const e=this._scaleSeriesOnly&&this._hasSeries;return this.m_dataSources.filter((t=>!!(t.properties().visible.value()||t instanceof ye.Series)&&(e?t instanceof ye.Series:(0,K.isStudy)(t)?!t.isSourceHidden()&&t.isIncludedInAutoScale():t.isIncludedInAutoScale())))}_updateAutoScaleDisabledProperty(e){const t=this._properties.childs(),i=t.indexedTo100.value()||t.percentage.value()||t.lockScale.value();e?t.autoScaleDisabled.setValueSilently(i):t.autoScaleDisabled.setValue(i)}_setAutoScaleValueWithDependentProperties(e){const t=this._properties.childs();t.autoScale.setValueSilently(e),e&&(t.percentage.setValueSilently(!1),t.indexedTo100.setValueSilently(!1),t.lockScale.setValueSilently(!1),t.logDisabled.setValueSilently(!1)),this._updateAutoScaleDisabledProperty(!0)}_setLockScaleValueWithDependentProperties(e){const t=this._properties.childs();t.lockScale.setValueSilently(e),e&&(t.autoScale.setValueSilently(!1),t.percentage.setValueSilently(!1),t.indexedTo100.setValueSilently(!1),t.log.setValueSilently(!1)),t.percentageDisabled.setValueSilently(e),t.logDisabled.setValueSilently(e),this._updateAutoScaleDisabledProperty(!0)}_setPercentageValueWithDependentProperties(e){const t=this._properties.childs();t.percentage.setValueSilently(e),e&&(t.autoScale.setValueSilently(!0),t.log.setValueSilently(!1),t.lockScale.setValueSilently(!1),t.indexedTo100.setValueSilently(!1)), this._updateAutoScaleDisabledProperty(!0)}_setIndexedTo100ValueWithDependentProperties(e){const t=this._properties.childs();t.indexedTo100.setValueSilently(e),e&&(t.autoScale.setValueSilently(!0),t.log.setValueSilently(!1),t.lockScale.setValueSilently(!1),t.percentage.setValueSilently(!1)),this._updateAutoScaleDisabledProperty(!0)}_setLogValueWithDependentProperties(e){const t=this._properties.childs();t.log.setValueSilently(e),e&&(t.lockScale.setValueSilently(!1),t.percentage.setValueSilently(!1),t.indexedTo100.setValueSilently(!1)),this._updateAutoScaleDisabledProperty(!0)}_recalculatePriceRangeImpl(){const e=this._invalidatedForRange.visibleBars;if(null===e)return;let t=null;const i=this.sourcesForAutoscale(),s=this.isPercentage(),o=this.isIndexedTo100();let r=0,n=0;for(const a of i){if(!a.properties().visible.value())continue;const i=a.firstValue();if(null===i||s&&0===i)continue;const l=e.firstBar(),c=e.lastBar(),h=a.autoScaleInfo(l,c);let d=h.range;d&&(s?d=(0,be.toPercentRange)(d,i):o&&(d=(0,be.toIndexedTo100Range)(d,i)),t=null===t?d:t.merge(d)),void 0!==h.topPixelMargin&&(r=Math.max(r,h.topPixelMargin)),void 0!==h.bottomPixelMargin&&(n=Math.max(n,h.bottomPixelMargin))}if((Math.abs(r-this._topPixelMargin)>0||Math.abs(n-this._bottomPixelMargin)>0)&&(this._bottomPixelMargin=n,this._topPixelMargin=r,this._marksCache=null,this._invalidateInternalHeightCache()),t){if(t.minValue()===t.maxValue()&&(t=new fe.PriceRange(t.minValue()-.5,t.maxValue()+.5)),this.isLog()){const e=this._convertPriceRangeFromLog(t),i=(0,be.logFormulaForPriceRange)(e);if(!(0,be.logFormulasAreSame)(i,this._logFormula)){const s=this._priceRangeSnapshot?this._convertPriceRangeFromLog(this._priceRangeSnapshot):null;this._logFormula=i,t=this._convertPriceRangeToLog(e),s&&(this._priceRangeSnapshot=this._convertPriceRangeToLog(s))}}this.setPriceRange(t)}else this.m_priceRange||(this.setPriceRange(new fe.PriceRange(-.5,.5)),this._logFormula=(0,be.logFormulaForPriceRange)(null));this._invalidatedForRange.isValid=!0;const a=this.mainSource();null!==a&&this._recalculatePriceRangeOnce&&(this._recalculatePriceRangeOnce=!a.priceRangeReady())}_makeSureItIsValid(){this._invalidatedForRange.isValid||(this._invalidatedForRange.isValid=!0,this._recalculatePriceRangeImpl())}_invalidateInternalHeightCache(){this._internalHeightCache=null,this._internalHeightChanged.fire()}_coordinateToLogical(e){if(this._makeSureItIsValid(),this.isEmpty())return 0;const t=this._invertedCoordinate(e),i=(0,n.ensureNotNull)(this.priceRange()),s=i.minValue()+(i.maxValue()-i.minValue())*((t-this.bottomPixelMargin())/(this.internalHeight()-1));return this.logicalToPrice(s)}_logicalToCoordinate(e){if(this._makeSureItIsValid(),this.isEmpty())return 0;e=this.priceToLogical(e);const t=(0,n.ensureNotNull)(this.priceRange()),i=this.bottomPixelMargin()+(this.internalHeight()-1)*(e-t.minValue())/(t.maxValue()-t.minValue());return this._invertedCoordinate(i)}_convertPriceRangeFromLog(e){if(null===e)return null;const t=(0,be.fromLog)(e.minValue(),this._logFormula),i=(0, be.fromLog)(e.maxValue(),this._logFormula);return new fe.PriceRange(t,i)}_convertPriceRangeToLog(e){if(null===e)return null;const t=(0,be.toLog)(e.minValue(),this._logFormula),i=(0,be.toLog)(e.maxValue(),this._logFormula);return new fe.PriceRange(t,i)}_canConvertPriceRangeFromLog(e){if(null===e)return!1;const t=(0,be.fromLog)(e.minValue(),this._logFormula),i=(0,be.fromLog)(e.maxValue(),this._logFormula);return isFinite(t)&&isFinite(i)}_onSourceVisibilityChanged(){this._dropScaleCache(),this._updateIsVisible()}_dropScaleCache(){this._sourcesForAutoscale=null,this._currencyCache=null,this._unitCache=null,this._measureUnitIdCache=null}_updateIsVisible(){this._isVisible.setValue(!0)}_invertedCoordinate(e){return this.isInverted()?e:this.height()-1-e}_initScaleProperties(){const e=this.isLockScale(),t=this.properties().childs();e&&(t.percentage.setValue(!1),t.indexedTo100.setValue(!1),t.log.setValue(!1),t.autoScale.setValue(!1)),t.percentageDisabled.setValue(e),t.logDisabled.setValue(e),this._updateAutoScaleDisabledProperty(!1),t.percentage.value()&&(t.log.setValue(!1),t.indexedTo100.setValue(!1)),t.indexedTo100.value()&&(t.log.setValue(!1),t.percentage.setValue(!1))}_correctedMargins(){if(null===this._correctedMarginsCache){const e=this.mainSource();this._correctedMarginsCache=null!==e?e.correctScaleMargins(this._margins):this._margins}return this._correctedMarginsCache}_getSourcesToUpdateViews(){return this._sourcesToUpdateViews||(this._sourcesToUpdateViews=this.m_dataSources.filter((e=>!(0,C.isLineTool)(e)||e.isActualSymbol()&&e.isActualCurrency()))),this._sourcesToUpdateViews}_mainSourceFormatter(){const e=this.mainSource();return(null==e?void 0:e.formatter())||Ne}_priceToPercentOrIndexedTo100IfNeeded(e,t){return this.isPercentage()?(0,be.toPercent)(e,t):this.isIndexedTo100()?(0,be.toIndexedTo100)(e,t):e}_onSourceIsActingAsSymbolSourceChanged(){this._dropScaleCache()}_onIsInvertedChanged(){this._marksCache=null,this._markBuilder.rebuildTickMarks()}_updateResetAvailableValue(){this._resetScaleAvailable.setValue(!this.isLockScale()&&!this.isAutoScale())}}var Oe=i(915179),Ve=i(46955),We=i(790524),Fe=i(339315),He=i(7288);const ze=[],Ue=[];class Ge{constructor(e){this._studies={},this._deferreds={},this._container=e,ze.push(e),Ue.push(this)}add(e,t){this._deferreds[e]&&(this._deferreds[e].resolve(t),delete this._deferreds[e]),this._studies[e]=t}get(e){return this._studies[e]?Promise.resolve(this._studies[e]):(this._deferreds[e]||(this._deferreds[e]=(0,p.createDeferredPromise)()),this._deferreds[e].promise)}reset(){const e=ze.indexOf(this._container);~e&&(ze.splice(e,1),Ue.splice(e,1))}static instance(e){const t=ze.indexOf(e);return~t?Ue[t]:new Ge(e)}}var qe=i(960690);var je=i(395098),Ye=i(180148),Ke=i(844295),Ze=i(167723),$e=i(711755),Xe=i(247035),Je=i(707621);const Qe=(0,te.getLogger)("Chart.Pane");function et(e,t,i){e.setMargins({top:t,bottom:i})}const tt="chart.pane";class it{constructor(e,t,i,s){this.m_dataSources=[],this._sourceWatchedValuesSubscriptions=new Map,this.m_mainDataSource=null, this._cachedOrderedSources=new Se(this),this._sourcesById=new Map,this._priceSourcesById=new Map,this._sourcePropertiesChanged=new Z.Delegate,this._sourcesZOrderChanged=new Z.Delegate,this._tagsChanged=new Z.Delegate,this._stretchFactor=1e3,this._isInInsertManyDataSourcesState=!1,this._lastLineDataSourceZOrder=null,this._rightPriceScales=[],this._leftPriceScales=[],this._lockedPriceScale=null,this._currentPriceScaleRatio=null,this._onPriceScalesChanged=new Z.Delegate,this._isRecalculatingScales=!1,this._priceDataSources=[],this._symbolSources=[],this._lollipopDataSources=[],this._symbolSourceResolved=new Z.Delegate,this._symbolSourceResolvingActive=new $.WatchedValue(!1),this._bulkActions={activeCounter:0},this._height=0,this._width=0,this._sizeChanged=new Z.Delegate,this._dataSourcesCollectionChanged=new Z.Delegate,this._symbolSourceCollectionChanged=new Z.Delegate,this._priceSourcesCollectionChanged=new Z.Delegate,this._maximized=new $.WatchedValue(!1),this._collapsed=new $.WatchedValue(!1),this._resetPriceScalesAvailable=new $.WatchedValue(!1),this._destroyed=new Z.Delegate,this._executionsPositionController=null,this._seriesDisplayError=null,this._onPriceScaleIsVisibleChanged=()=>{this._model.fullUpdate()},this._recalcSymbolSourceResolvingActive=()=>{for(const e of this._symbolSources)if(e.symbolResolvingActive().value())return void this._symbolSourceResolvingActive.setValue(!0);this._symbolSourceResolvingActive.setValue(!1)},this._onSymbolSourceCollectionChanged=()=>{0===this._bulkActions.activeCounter?this._symbolSourceCollectionChanged.fire():this._bulkActions.symbolSourceCollectionChanged=!0},this._onSeriesDisplayError=e=>{},this._updateResetPriceScalesAvailableValue=()=>{const e=e=>e.resetScaleAvailable().value(),t=this._leftPriceScales.some(e)||this._rightPriceScales.some(e);this._resetPriceScalesAvailable.setValue(t)},this._priceScaleSelectionStrategy=(0,oe.createPriceScaleSelectionStrategy)(i.properties().childs().priceScaleSelectionStrategyName.value()),this._id=null!=s?s:(0,ie.randomHashN)(6),this._timeScale=e,this.m_mainDataSource=null,this._properties=t,this._model=i,i.properties().childs().priceScaleSelectionStrategyName.subscribe(null,(e=>{this._priceScaleSelectionStrategy=(0,oe.createPriceScaleSelectionStrategy)(e.value()),this._priceScaleSelectionStrategy.apply(this)})),this._timeScale.barSpacingChanged().subscribe(this,(()=>{this.m_mainDataSource===this._model.mainSeries()&&this._recalculatePriceScaleByScaleRatio(this.m_mainDataSource.priceScale())})),t.childs().topMargin.subscribe(this,this._updateMargins),t.childs().bottomMargin.subscribe(this,this._updateMargins),this._updateMargins()}destroy(){var e;this._properties.childs().topMargin.unsubscribeAll(this),this._properties.childs().bottomMargin.unsubscribeAll(this),this._model.properties().childs().priceScaleSelectionStrategyName.unsubscribeAll(this),this._timeScale.barSpacingChanged().unsubscribeAll(this),this._leftPriceScales.concat(this._rightPriceScales).forEach((e=>{e.modeChanged().unsubscribeAll(this), e.priceRangeChanged().unsubscribeAll(this),e.internalHeightChanged().unsubscribeAll(this),e.isVisible().unsubscribe(this._onPriceScaleIsVisibleChanged),e.resetScaleAvailable().unsubscribe(this._updateResetPriceScalesAvailableValue)}));for(const e of this.m_dataSources)this.removeSourceFromPriceScale(e),e.destroy&&e.destroy();null===(e=this._seriesDisplayError)||void 0===e||e.destroy(),this._destroyed.fire()}id(){return this._id}bulkActionMacro(e){const t=this._bulkActions;t.activeCounter+=1,e(),t.activeCounter-=1,0===t.activeCounter&&(this._dataSourcesCollectionChanged.fire(),t.symbolSourceCollectionChanged&&(this._symbolSourceCollectionChanged.fire(),t.symbolSourceCollectionChanged=!1),t.priceSourcesCollectionChanged&&(this._priceSourcesCollectionChanged.fire(),t.priceSourcesCollectionChanged=!1))}defaultPriceScale(){var e,t;const i=null!==(t=null===(e=this.m_mainDataSource)||void 0===e?void 0:e.priceScale())&&void 0!==t?t:null;if(null!==i)return i;const s=this.properties().childs().axisProperties.state();return s.autoScale=!0,new Re(this._model.properties().childs().scalesProperties,s)}leftPriceScales(){return this._leftPriceScales}rightPriceScales(){return this._rightPriceScales}visibleLeftPriceScales(){var e;const t=this._model.priceScaleSlotsCount(),i=this._leftPriceScales.filter((e=>e.isVisible().value())),s=null===(e=this.mainDataSource())||void 0===e?void 0:e.priceScale();if(i.length>t.left&&(null==s?void 0:s.isVisible().value())){const e=(0,b.moveToHead)(i,s);return e.splice(t.left),e}return i}visibleRightPriceScales(){var e;const t=this._model.priceScaleSlotsCount(),i=this._rightPriceScales.filter((e=>e.isVisible().value())),s=null===(e=this.mainDataSource())||void 0===e?void 0:e.priceScale();if(i.length>t.right&&(null==s?void 0:s.isVisible().value())){const e=(0,b.moveToHead)(i,s);return e.splice(t.right),e}return i}clearSeries(e){const t=this._model.mainSeries();for(let i=this.m_dataSources.length-1;i>=0;i--)this.m_dataSources[i]===t&&this._removeSourceFromCollections(i,e)}sourcesByGroup(){return this._cachedOrderedSources}dataSourceForId(e){return this._sourcesById.get(e)||null}changeSourceId(e,t){var i;e===this._model.mainSeries()&&(null===(i=(0,se.getPersistentLogger)())||void 0===i||i.addPersistentLogEntry(`changeSourceId for series from ${e.id()} to ${t}`,te.LOGLEVEL.INFO,tt)),(0,n.assert)(this.hasDataSource(e));const s=e.id();e.setId(t),this._sourcesById.delete(s),this._sourcesById.set(t,e),(0,ue.isPriceDataSource)(e)&&(this._priceSourcesById.delete(s),this._priceSourcesById.set(t,e))}movePriceScale(e,t,i){const s=this.priceScalePosition(e);if(s!==t)this.removePriceScale(e),this._placePriceScale(e,t,i),e.invalidateMargins(),this._invalidateSourcesCache();else if(void 0!==i&&"overlay"!==s){const t="left"===s?this._leftPriceScales:this._rightPriceScales,o=t.indexOf(e);t.splice(o,1),t.splice(i,0,e)}}mainDataSource(){return this.m_mainDataSource}isEmpty(){return null===this.m_mainDataSource}recalculatePriceScale(e,t){if(!e)return;const i=e.sourcesForAutoscale() ;if((e.isAutoScale()||e.priceRangeShouldBeRecalculatedOnce())&&i&&i.length>0&&!this.timeScale().isEmpty()){const t=this.timeScale().visibleBarsStrictRange();e.recalculatePriceRange(t)}e.updateAllViews(t)}onSourceTagsChanged(){this._tagsChanged.fire()}insertDataSource(e,t,i,s){e.setZorder(i),t||(s=!1,t=this.findSuitableScale(e)),this._addSourceToCollections(e);let o=!1;e===this.model().mainSeries()?(this.m_mainDataSource=this.model().mainSeries(),o=!0):null===this.m_mainDataSource&&(0,ue.isPriceDataSource)(e)&&(this.m_mainDataSource=e,o=!0),s||t.addDataSource(e,this._isInInsertManyDataSourcesState),e.setPriceScale(t),t.invalidateMargins(),e.onTagsChanged&&e.onTagsChanged().subscribe(this,this.onSourceTagsChanged),o&&this._processMainSourceChange(),this._tagsChanged.fire(),(0,ue.isPriceDataSource)(e)&&this.recalculatePriceScale(t,(0,G.sourceChangeEvent)(e.id())),this._invalidateSourcesCache(),this._isInInsertManyDataSourcesState||(0,n.ensureNotNull)(this.model().alertsWatcher()).syncSourceAlertLabels(e)}addDataSource(e,t,i){let s=e.zorder();i||((0,C.isLineTool)(e)&&!e.isSpeciallyZOrderedSource()?(s=null!==this._lastLineDataSourceZOrder?this._lastLineDataSourceZOrder+1:this.newLineToolZOrder(),this._isInInsertManyDataSourcesState&&(this._lastLineDataSourceZOrder=s)):(0,K.isStudy)(e)&&!e.isSpeciallyZOrderedSource()&&(s=this.newStudyZOrder())),this.insertDataSource(e,t,s)}removeDataSource(e,t,i,s){const o=this.m_dataSources.indexOf(e);if(-1===o)return void Qe.logDebug("removeDataSource: invalid data source");(0,n.ensureNotNull)(this.model().alertsWatcher()).detachSourceAlertLabels(e),this._removeSourceFromCollections(o,!!i),e!==this.m_mainDataSource||t||(this.m_mainDataSource=null);const r=e.priceScale();s||this.removeSourceFromPriceScale(e),e.onTagsChanged&&e.onTagsChanged().unsubscribe(this,this.onSourceTagsChanged),(0,ue.isPriceDataSource)(e)&&!t&&this._processMainSourceChange(),this._tagsChanged.fire(),r&&(0,ue.isPriceDataSource)(e)&&this.recalculatePriceScale(r,(0,G.sourceChangeEvent)(e.id())),this._invalidateSourcesCache()}hasDataSource(e){return this._sourcesById.has(e.id())}hasPriceDataSource(e){return this._priceSourcesById.has(e.id())}dataSources(){return this.m_dataSources}priceDataSources(){return this._priceDataSources}lollipopDataSources(){return this._lollipopDataSources}symbolSources(){return this._symbolSources}replaceSource(e,t,i){const s=this.m_mainDataSource===e,o=e.zorder(),r=null==i?void 0:i.replaceSource(e,t);this.insertDataSource(t,i,o,r),this.removeDataSource(e,s,void 0,r),this._sourcesById.set(t.id(),t),(0,ue.isPriceDataSource)(t)&&this._priceSourcesById.set(t.id(),t),s&&(this.m_mainDataSource=t,this._processMainSourceChange())}findSuitableScale(e,t,i){return this._priceScaleSelectionStrategy.findSuitableScale(this,e,t,i)}createNewPriceScaleIfPossible(){return this._priceScaleSelectionStrategy.createNewPriceScaleIfPossible(this)}canCreateNewPriceScale(){return this._priceScaleSelectionStrategy.canCreateNewPriceScale(this)}isOverlay(e){const t=e.priceScale() ;return null===t||"overlay"===this.priceScalePosition(t)}recalculate(e){this._leftPriceScales.forEach((t=>this.recalculatePriceScale(t,e))),this._rightPriceScales.forEach((t=>this.recalculatePriceScale(t,e)));for(const t of this.m_dataSources)this.isOverlay(t)&&!(0,C.isLineTool)(t)&&this.recalculatePriceScale(t.priceScale(),e);this.updateAllViews(e),this._model.updatePane(this)}updateAllViews(e){for(const t of this.m_dataSources)t.updateAllViews(e);for(const t of this.model().customSources())t.updateViewsForPane(this,e)}updateLollipopViews(e){for(const t of this._lollipopDataSources)t.updateAllViews(e)}priceScalePosition(e){return this._leftPriceScales.includes(e)?"left":this._rightPriceScales.includes(e)?"right":"overlay"}createPriceScaleAtPosition(e,t){const i=this.properties().childs().axisProperties.state();i.autoScale=!0;const s=new Re(this.model().properties().childs().scalesProperties,i);return s.setHeight(this.height()),et(s,this._defaultTopMargin(),this._defaultBottomMargin()),this._placePriceScale(s,e,t),s}removePriceScale(e){e.modeChanged().unsubscribeAll(this),e.priceRangeChanged().unsubscribeAll(this),e.internalHeightChanged().unsubscribeAll(this),e.isVisible().unsubscribe(this._onPriceScaleIsVisibleChanged),e.resetScaleAvailable().unsubscribe(this._updateResetPriceScalesAvailableValue),e===this._lockedPriceScale&&(this._lockedPriceScale=null,this._currentPriceScaleRatio=null);const t=this._leftPriceScales.indexOf(e);-1!==t&&(this._leftPriceScales[t].invalidateMargins(),this._leftPriceScales.splice(t,1));const i=this._rightPriceScales.indexOf(e);if(-1!==i&&(this._rightPriceScales[i].invalidateMargins(),this._rightPriceScales.splice(i,1)),null===e.mainSource()){const t=e.dataSources().length;0!==t&&Qe.logError("Invalid priceScale state: empty mainSource but non-empty data sources="+t)}this._onPriceScalesChanged.fire(),this._updateResetPriceScalesAvailableValue()}priceScaleIndex(e,t){switch(t){case"left":return this.leftPriceScales().indexOf(e);case"right":return this.rightPriceScales().indexOf(e)}}move(e,t,i){const s=e.priceScale();this.removeSourceFromPriceScale(e),t.addDataSource(e),e.setPriceScale(t),t.invalidateMargins(),this._processMainSourceChange(),this._invalidateSourcesCache(),e.isIncludedInAutoScale()&&(null!==s&&this.recalculatePriceScale(s,(0,G.sourceChangeEvent)(e.id())),this.recalculatePriceScale(t,(0,G.sourceChangeEvent)(e.id()))),this._onPriceScalesChanged.fire()}setZOrders(e){e.forEach(((e,t)=>{t.setZorder(e)})),this._invalidateSourcesCache(),0===this._bulkActions.activeCounter&&this._dataSourcesCollectionChanged.fire(),this.model().lightUpdate()}isMainPane(){return this.hasDataSource(this.model().mainSeries())}isLast(){const e=this.model().panes();return e[e.length-1]===this}newStudyZOrder(){return(0,Ve.newStudyZOrder)(this._priceDataSources)}newLineToolZOrder(e){return(0,Ve.newLineToolZOrder)(this.m_dataSources,e)}model(){return this._model}containsMainSeries(){return this._sourcesById.has(this.model().mainSeries().id())}applyPriceScaleRatio(e,t){var i ;null!==this._lockedPriceScale&&this._lockedPriceScale!==e||this._currentPriceScaleRatio===t||!this.isMainPane()||null===this._lockedPriceScale&&e!==(null===(i=this.mainDataSource())||void 0===i?void 0:i.priceScale())||(this._setNewPriceRangeByScaleRatio(e,t,this._mainSourceVisiblePriceRange(e),!0,!0),null!==this._lockedPriceScale?this._tryToApplyNewPriceScaleRatio():e.isLog()||this.model().mainSeriesScaleRatioPropertyOnChanged())}sendToBack(e){const t=this.sourcesByGroup().allExceptSpecialSources();this._batchReorder(e,t[0],Ve.moveBeforeSource)}bringToFront(e){const t=this.sourcesByGroup().allExceptSpecialSources();this._batchReorder(e,t[t.length-1],Ve.moveAfterSource)}sendBackward(e){const t=this.sourcesByGroup().allIncludingHidden(),i=t.indexOf(e[0]);if(0===i)this.bringToFront(e);else{const s=t[i-1];this.insertBefore(e,s)}}bringForward(e){const t=this.sourcesByGroup().allExceptSpecialSources(),i=t.indexOf(e[e.length-1]);if(i===t.length-1)this.sendToBack(e);else{const s=t[i+1];this.insertAfter(e,s)}}insertAfter(e,t){this._batchReorder(e,t,Ve.moveAfterSource)}insertBefore(e,t){this._batchReorder(e,t,Ve.moveBeforeSource)}maximized(){return this._maximized}collapsed(){return this._collapsed}getPriceScaleById(e){const t=this.m_dataSources.find((t=>{var i;return(null===(i=t.priceScale())||void 0===i?void 0:i.id())===e}));return void 0===t?null:t.priceScale()}priceScaleSelectionStrategy(){return this._priceScaleSelectionStrategy}setPriceScaleSelectionStrategy(e){this._priceScaleSelectionStrategy=e,e.apply(this)}findTargetPriceAxisViews(e,t,i,s){if((0,f.isDataSource)(e)&&this.model().paneForSource(e)!==this)return[];const o=e.priceScale();if(t===o)return i;if(null===o)return[];if("overlay"===this.priceScalePosition(o))return t===this.defaultPriceScale()?i:[];const r=this.priceScalePosition(t);if(r!==this.priceScalePosition(o))return[];const n="left"===r?this.leftPriceScales():this.rightPriceScales();return n.indexOf(t)1}properties(){return this._properties}setPriceAutoScale(e,t){e.setMode({autoScale:t}),this.timeScale().isEmpty()||this.recalculatePriceScale(e,(0,G.viewportChangeEvent)())}state(e,t,i,s,o,r){var n,a;const l={sources:[],mainSourceId:null===(n=this.m_mainDataSource)||void 0===n?void 0:n.id(),stretchFactor:this._stretchFactor,leftAxisesState:[],rightAxisesState:[],overlayPriceScales:{},priceScaleRatio:this._currentPriceScaleRatio,isCollapsed:this._collapsed.value()},c=new Map,h=e=>{if(c.has(e))return c.get(e);let n=null;const a=i&&!e.isSavedInStudyTemplates()||(0,y.isAlertLabel)(e)||!e.state||(0,C.isLineTool)(e)&&r||!e.isSavedInChart(Boolean(t))||!(n=e.state(t,o))||s&&(0,C.isLineTool)(e)&&e.isActualSymbol&&!e.isActualSymbol()||e.isPhantom()?null:n;return c.set(e,a),a};if(e){l.sources=[];for(let e=0;enull!==c.get(e),u=e=>!r||!(0,C.isLineTool)(e) ;l.leftAxisesState=this._leftPriceScales.map((e=>({state:e.state(),sources:e.dataSources().filter(d).filter(u).map((e=>e.id()))}))),l.rightAxisesState=this._rightPriceScales.map((e=>({state:e.state(),sources:e.dataSources().filter(d).filter(u).map((e=>e.id()))}))),l.overlayPriceScales={};for(const e of this.m_dataSources)if(this.isOverlay(e)&&e.isSavedInChart(Boolean(t))){const t=e.priceScale();l.overlayPriceScales[e.id()]=null!==(a=null==t?void 0:t.state())&&void 0!==a?a:null}return l}restoreState(e){var t;const{state:i,withData:s,version:o,seriesId:r=this._model.mainSeries().id(),settingsMigration:a={},contentOverrides:l,restoreSilently:c,reason:h=0}=e;null===(t=(0,se.getPersistentLogger)())||void 0===t||t.addPersistentLogEntry(`Restoring pane with seriesId ${r}`,te.LOGLEVEL.INFO,tt),i.stretchFactor&&(this._stretchFactor=i.stretchFactor);const d={};if(i.sources){const e=i.sources.filter((e=>{var t;return!!e&&("MainSeries"===e.type||(!(null===(t=e.points)||void 0===t?void 0:t.some((e=>null===e.time_t||!isFinite(e.time_t))))||(Qe.logNormal("Dropped invalid "+e.type+". Reason: non-numeric point time"),!1)))})),t=e.findIndex(We.isMainSeriesState);-1!==t&&this.model().mainSeries().setObsoleteZOrder(e[t].zorder),o<3&&(0,Ve.reorderDataSourcesStateZOrder)(e);const n=-1!==this.m_dataSources.indexOf(this._model.mainSeries());this.clearSeries(Boolean(c)),this.m_mainDataSource=null,n&&this._addSourceToCollections(this._model.mainSeries(),c),(()=>{const t=e.find((e=>e.id===i.mainSourceId));if(void 0===t)return void Qe.logWarn("There is no main source with id "+i.mainSourceId+", total sources="+e.length);if(!window.TradingView[t.type]||!(0,ve.isLineToolName)(t.type))return void Qe.logNormal("The type of main source is not line tool - fix is unnecessary");let s=null;for(const i of e)if(!window.TradingView[t.type]||!(0,ve.isLineToolName)(i.type)){if(null!==s)return void Qe.logWarn("Pane contains more than 1 possibly main sources - auto fix cannot be applied");s=i}if(null===s)return void Qe.logWarn("Pane contains only line tools - possible we need to remove this pane?");const o=i.mainSourceId;let r=0;i.mainSourceId=s.id,e.forEach((e=>{e.ownerSource===o&&(e.ownerSource=null==s?void 0:s.id,r+=1)})),Qe.logNormal("Auto fix broken pane is applied, changed line tools="+r+", changed from="+o+" to="+s.id)})();for(const t of e)if("study_Sessions"===t.type){this.model().sessions().restoreOldState(t,s);break}for(const t of e)"study_Sessions"!==t.type&&(null===this._model.dataSourceForId(t.id)||"MainSeries"===t.type?(d[t.id]=t.ownerSource,(0,We.isMainSeriesState)(t)?this._restoreMainSeries(t,s,n,a,l,c):(0,We.isStudyState)(t)?this.restoreStudy(t,s,r,a,c,h):(0,We.isLineToolState)(t)?(t.state&&(t.state.zOrderVersion=2),this.restoreLineTool(t,s,void 0,c)):"ChartEventsSource"===t.type&&this._restoreSpecialSource(t,s,c)):Qe.logError("Duplicate id while restoring pane: "+t.type+","+t.id))}const u=new Set,_=(e,t)=>{e.priceScale()!==t&&(this.removeSourceFromPriceScale(e),e.setPriceScale(t),t.addDataSource(e))},p=(e,t,i)=>{if(u.has(e))return;u.add(e) ;const s=i.m_showSymbolLabels;void 0!==s&&e===this.model().mainSeries()&&this.model().properties().childs().scalesProperties.childs().showSymbolLabels.setValue(s),this._model.children(e,!0).forEach((e=>p(e,t,i))),_(e,t)},m=e=>{const t=(0,W.defaults)("chartproperties").paneProperties.axisProperties,i=new Re(this.model().properties().childs().scalesProperties,t);return i.restoreState(e.state),i.setHeight(this._height),e.sources.forEach((e=>{const s=this.dataSourceForId(e);s&&p(s,i,t)})),0===i.dataSources().length?null:i},g=e=>e.map(m).filter((e=>null!==e));let S;if(i.leftAxisesState)S=g(i.leftAxisesState);else{const e=m({state:i.leftAxisState,sources:i.leftAxisSources});S=null!==e?[e]:[]}let v;if(this._leftPriceScales.slice().forEach((e=>this.removePriceScale(e))),this._leftPriceScales=[],S.forEach((e=>this._placePriceScale(e,"left"))),i.rightAxisesState)v=g(i.rightAxisesState);else{const e=m({state:i.rightAxisState,sources:i.rightAxisSources});v=null!==e?[e]:[]}this._rightPriceScales.slice().forEach((e=>this.removePriceScale(e))),this._rightPriceScales=[],v.forEach((e=>this._placePriceScale(e,"right"))),this._currentPriceScaleRatio=i.priceScaleRatio||i.leftPriceScaleRatio||i.rightPriceScaleRatio||null;const f=new Map;for(const e of this.m_dataSources){if(u.has(e))continue;let t;if(i.overlayPriceScales&&i.overlayPriceScales[e.id()]){let s=i.overlayPriceScales[e.id()];f.has(null==s?void 0:s.id)?t=f.get(null==s?void 0:s.id):(s=(0,n.ensure)(s),t=new Re(this._model.properties().childs().scalesProperties),t.setHeight(this._height),s.m_isAutoScale=!0,s.m_isLog=!1,s.m_isPercentage=!1,s.m_isLockScale=!1,t.restoreState(s),f.set(s.id,t))}else t=new Re(this._model.properties().childs().scalesProperties),t.setHeight(this._height);_(e,t)}for(const e of Object.keys(d)){const t=d[e],i=this.dataSourceForId(e);t&&i&&null===i.ownerSource()&&i.setOwnerSource(this.dataSourceForId(t))}if(i.mainSourceId&&!this.containsMainSeries()&&(this.m_mainDataSource=this.dataSourceForId(i.mainSourceId)),!this.m_mainDataSource)for(const e of this.m_dataSources)if((0,ue.isPriceDataSource)(e)){this.m_mainDataSource=e;break}for(const e of this.m_dataSources)(0,C.isLineTool)(e)?(e.ownerSource()||e.setOwnerSource(this.mainDataSource()),e.isFixed()&&e.restoreFixedPoint()):(0,K.isStudy)(e)&&!e.ownerSource()&&e.isLinkedToSeries()&&e.setOwnerSource(this.model().mainSeries());this._updateMargins(),this._cachedOrderedSources.clear()}onPriceScalesChanged(){return this._onPriceScalesChanged}setPaneSize(e){let t;switch(e){case"large":t=1;break;case"medium":t=.6;break;case"small":t=.3;break;case"tiny":t=.15;break;default:throw new Error("Unknown size enum value: "+e)}this._stretchFactor=1e3*t}stretchFactor(){return this._stretchFactor}setStretchFactor(e){this._stretchFactor=e}customSources(e){return this.model().customSources(e)}createDrawingsCaches(){0}clearDrawingCaches(){0}executionsPositionController(){return null}width(){return this._width}height(){return this._height}setHeight(e){if(this._height!==e){this._height=e, this._leftPriceScales.forEach((t=>t.setHeight(e))),this._rightPriceScales.forEach((t=>t.setHeight(e)));for(let t=0;t(e.paneViews(this)||[]).some((e=>{const s=e.renderer(t);return s&&s.doesIntersectWithBox&&s.doesIntersectWithBox(i)}))))}logicalRectToPixels(e){const t=this.defaultPriceScale(),i=this.timeScale(),s=(0,n.ensureNotNull)((0,n.ensureNotNull)(t.mainSource()).firstValue()),o=t.priceToCoordinate(e.p1.price,s),r=i.indexToCoordinate(e.p1.index),l=t.priceToCoordinate(e.p2.price,s),c=i.indexToCoordinate(e.p2.index),h=new a.Point(Math.min(r,c),Math.min(o,l)),d=new a.Point(Math.max(r,c),Math.max(o,l));return(0,a.box)(h,d)}timeScale(){return this._timeScale}restoreLineTool(e,t,s,o,r){var a,l,c,d,u,_,p,m,g,S,v,f;delete e.state.lastUpdateTime,e.state.intervalsVisibilities=(0,je.mergeIntervalVisibilitiesDefaults)(e.state.intervalsVisibilities),s=void 0===s||s,qe.LineToolElliott.migrateState(e),"LineToolGannComplex"!==(f=e).type||void 0!==f.version&&1!==f.version||(f.type="LineToolGannFixed"),Array.isArray(e.positionPercents)&&(e.positionPercents=e.positionPercents[0]);const b=e.type,y=e.id,w=e.state,P=s?e.zorder:this.newLineToolZOrder();(0,n.assert)((0,ve.isLineToolName)(b),"invalid data source type:"+b+" (expected to be a Line Tool)");let T,M,x=null;if((0,We.isStudyLineToolState)(e)){x=this._model.studyVersioning();const s=x.patchPointsBasedStudyState(e);e=s;const r=s.metaInfo;if(Object.assign(r,re.StudyMetaInfo.parseIdString(null==r?void 0:r.fullId)),!t&&r){const t=r.productId;if(!(null===(a=window.pro)||void 0===a?void 0:a.hasPackage(t))){const t=new ce.StudyLineToolStub(this._model,e,r.shortDescription);return t.setId(y),this._addSourceToCollections(t,o),void 0!==P&&t.setZorder(P),t.setFailed(h.t(null,void 0,i(994125))),null}}const n=x.updateMetaInfo(r)||r;M=(0,C.createStudyLineToolProperties)(b,r,n,w,x),T=(0,C.createLineTool)(b,this._model,M,n,!0)}else M=(0,C.createLineToolProperties)(b,w,this._model,!1), t?null===(l=M.child("fixedSize"))||void 0===l||l.setValue(!1):null===(c=M.child("fixedSize"))||void 0===c||c.setValue(!0),T=(0,C.createLineTool)(b,this._model,M,null,!0);T.setId(y),T.linkKey().setValue(e.linkKey||null);const I=e.alertId;I&&T.canHasAlert()&&de.alertsAvailable&&!this._model.readOnly()&&!this._model.isJustClonedChart()&&T.setAlert(+I);let A=null!==(d=e.indexes)&&void 0!==d?d:[];if(A=A.slice(0,null!==(_=null===(u=e.points)||void 0===u?void 0:u.length)&&void 0!==_?_:A.length),T.isFixed()?void 0!==e.positionPercents?T.restorePositionPercents(e.positionPercents):T.restorePositionPercents({x:.5,y:.5}):e.points&&T.restorePoints(e.points,A,t),T instanceof Ye.LineToolBarsPattern||T instanceof Ke.LineToolCallout||T instanceof Ze.LineToolTrendAngle||T instanceof $e.LineToolGhostFeed||T instanceof Xe.LineToolParallelChannel||T instanceof ae.LineToolTweet||T instanceof le.LineToolIdea)null===(m=(p=T).restoreData)||void 0===m||m.call(p,e);else if(t&&(0,We.isStudyLineToolState)(e)&&T.restoreData){const t=e;x&&(t.graphics=x.patchPointsBasedStudyData(t.metaInfo,t.graphics)),null===(g=T.restoreData)||void 0===g||g.call(T,t)}const L=null==e.version?1:e.version,k=null==T.version?1:T.version;if(L!==k&&(null===(v=(S=T).migrateVersion)||void 0===v||v.call(S,L,k,{pane:this,model:this._model,properties:M})),void 0!==P&&T.setZorder(P),r)(0,C.prepareLineToolPropertiesByOwnerSource)(T.properties(),r),T.setOwnerSource(r);else{const t=e.ownerSource?this.dataSourceForId(e.ownerSource):null;T.setOwnerSource(t)}return T.isFixed()&&T.restoreFixedPoint(),void 0!==e.sharingMode&&T.share(e.sharingMode),this._addSourceToCollections(T,o),this._cachedOrderedSources.clear(),T}restoreStudy(e,t,s,o,r,n){var a;if(t&&void 0===e.data&&void 0===e.nonSeriesData&&void 0===e.indexes)return Qe.logError("Cannot restore (skipping) study without data "+e.id+", "+e.metaInfo.id),null;const l=e.id,c=e.state,d=e.zorder;s=null!=s?s:this._model.mainSeries().id();const u=(null!==(a=e.parentSources)&&void 0!==a?a:e.ownerSource?[e.ownerSource]:[]).filter((e=>e!==s));let _=(0,ne.clone)(e.metaInfo);if(Object.assign(_,re.StudyMetaInfo.parseIdString(_.id)),function(e){return"Script$TV_EARNINGS@tv-scripting"===e||"Script$TV_DIVIDENDS@tv-scripting"===e||"Script$TV_SPLITS@tv-scripting"===e||"ESD$TV_EARNINGS@tv-scripting"===e||"ESD$TV_DIVIDENDS@tv-scripting"===e||"ESD$TV_SPLITS@tv-scripting"===e||"Earnings@tv-basicstudies"===e||"Dividends@tv-basicstudies"===e||"Splits@tv-basicstudies"===e||"BarSetContinuousRollDates@tv-corestudies"===e}(_.id)&&!t)return Qe.logNormal("Skipping study "+_.id),null;let p=c;const g=this._model.studyVersioning(),S=g.patchPropsStateAndMetaInfo(p,_,{oldShowStudyLastValueProperty:t&&!(null==o?void 0:o.showStudyLastValueProperty)});p=S.propsState,_=S.metaInfo;const v=new x.StudyStub(this._model,e,_.shortDescription);let f;v.setId(l),v.setZorder(d);let b=!1;const y=i=>{if(b&&this._model.dataSourceForId(l)!==v)return;v.setStatus({type:He.StudyStatusType.Undefined});const s=i||new re.StudyMetaInfo(_),o=Ge.instance(this._model),r=r=>{var a;const c=(0, I.prepareStudyPropertiesForLoadChart)(_,i,p,g),h=(0,K.createStudy)(this._model,c,r,s,void 0,n);if(h.setId(l),h.setOwnFirstValue(null!==(a=e.ownFirstValue)&&void 0!==a?a:null),e.customFields&&h.restoreStateCustomFields(e.customFields),t){const t=e,{data:i,nsData:s,indexes:o}=g.patchStudyData(_,t.data,t.nonSeriesData,t.indexes);h.restoreData(i,s,o)}this._model.replaceStudyStub(v,h)||(f=h),o.add(l,h)};if(u.length>0){const e=u.map((e=>o.get(e)));Promise.all(e).then(r)}else r([])};if(t)y(null);else{let e=null;this._model.isSnapshot()||(e=i.e(37819).then(i.bind(i,532338)).then((e=>{const{pineIdForJavaId:t,migrateJavaStateToPine:i}=e,s=t(_.id);return s?(0,B.studyMetaInfoRepository)().findById({pineId:s,pineVersion:"last",type:"pine"}).then((e=>(i(c,_,e),_=e,m.emit("chart_migrated"),e))):_})));const t=e=>{const t=g.updateMetaInfoAsync(e);t.sync?y(t.result):t.result.then(y).catch((e=>v.setFailed("error: "+e)))};e?e.then(t).catch((()=>v.setFailed(h.t(null,void 0,i(328523))))):t(_)}const C=null!=f?f:v;if(C){C.setZorder(d);const t=e.metaInfo.linkedToSeries?this._model.mainSeries():u.length?this.dataSourceForId(u[0]):null;C.setOwnerSource(t),this._addSourceToCollections(C,r),this._processMainSourceChange(),b=C===v}return this._cachedOrderedSources.clear(),C}clipboardLineToolOwnerSource(e){const t=this.dataSourceForId(e);if(null!==t){const e=t.ownerSource();if(null!==e&&null!==e.firstValue())return e}const i=this.mainDataSource();if(null!==i&&null!==i.firstValue())return i;for(const e of this.dataSources())if((0,ue.isPriceDataSource)(e)&&null!==e.firstValue())return e;return null}realignLineTools(e){var t;let i=!1;for(const s of this.m_dataSources)!(0,C.isLineTool)(s)||void 0!==e&&(null===(t=null==s?void 0:s.ownerSource())||void 0===t?void 0:t.symbolSource())!==e&&(0,Ce.isActingAsSymbolSource)(e)||(s.realign(),s.updateAllViews((0,G.sourceChangeEvent)(s.id())),i=!0);return i&&this._invalidateSourcesCache(),i}startScalePrice(e,t){e.startScale(t)}scalePriceTo(e,t){e.scaleTo(t),this.updateAllViews((0,G.viewportChangeEvent)())}endScalePrice(e){e.endScale()}startScrollPrice(e,t){e.startScroll(t)}scrollPriceTo(e,t){e.scrollTo(t),this.updateAllViews((0,G.viewportChangeEvent)())}endScrollPrice(e){e.endScroll()}resetPriceScale(e){const t=this.timeScale().visibleBarsStrictRange();e.resetScaleAvailable().value()&&e.resetScale(),e.recalculatePriceRange(t),this.updateAllViews((0,G.viewportChangeEvent)())}resetPriceScalesAvailable(){return this._resetPriceScalesAvailable.readonly()}restorePriceScaleState(e,t){e.restoreState(t),this.updateAllViews((0,G.viewportChangeEvent)())}beginInsertManyLineDataSources(){this._isInInsertManyDataSourcesState=!0,this._lastLineDataSourceZOrder=null}endInsertManyLineDataSources(){this._isInInsertManyDataSourcesState=!1,this._lastLineDataSourceZOrder=null;{const e=(0,n.ensureNotNull)(this.model().alertsWatcher());for(const t of this.m_dataSources)e.syncSourceAlertLabels(t)}}removeSourceFromPriceScale(e){const t=e.priceScale();if(null!==t){const i=t.dataSources();i.indexOf(e)>=0&&t.removeDataSource(e), 0===i.length&&this.removePriceScale(t)}}_invalidateSourcesCache(){this._cachedOrderedSources.clear(),this._leftPriceScales.forEach((e=>e.invalidateSourcesCache())),this._rightPriceScales.forEach((e=>e.invalidateSourcesCache()))}_processMainSourceChange(){let e=!1;if(null===this.m_mainDataSource)for(const t of this.m_dataSources)if((0,ue.isPriceDataSource)(t)&&!this.isOverlay(t)&&(!(0,K.isStudy)(t)||!t.isLinkedToSeries())){this.m_mainDataSource=t,e=!0;break}if(this.m_mainDataSource&&e){let e=this.m_dataSources.filter(C.isLineTool);e=(0,_e.sortSources)(e);for(const t of e)this.move(t,(0,n.ensureNotNull)(this.m_mainDataSource.priceScale()),!0)}else if(!this.m_mainDataSource||this.isOverlay(this.m_mainDataSource)&&0===this._nonOverlayPricesSourcesCount()){let e=null;if(this.m_dataSources.includes(this._model.mainSeries()))e=this._model.mainSeries();else for(const t of this.m_dataSources)if((0,ue.isPriceDataSource)(t)&&this.isOverlay(t)&&t.showInObjectTree()){e=t;break}if(null!==e){const t=this.m_mainDataSource===e;this.m_mainDataSource=e;const i=this.createNewPriceScaleIfPossible();if(t&&e===this._model.mainSeries()){const t=(0,n.ensureNotNull)(e.priceScale());this._model.children(e,!0).forEach((e=>{this.removeSourceFromPriceScale(e),i.addDataSource(e),e.setPriceScale(i)})),this.removePriceScale(t)}this.move(e,i,!0),this.recalculatePriceScale(e.priceScale(),(0,G.globalChangeEvent)())}}}_addSourceToCollections(e,t){this.m_dataSources.push(e),this._sourcesById.set(e.id(),e),this._invalidateSourcesCache();const i=()=>{this._sourcePropertiesChanged.fire(e)};e.properties().subscribe(this,i),e.zOrderChanged().subscribe(this,(t=>this._sourcesZOrderChanged.fire(e,t))),(0,C.isLineTool)(e)&&(e.normalizedPointsChanged().subscribe(this,i),e.fixedPointChanged().subscribe(this,i),e.hasAlert().subscribe(i),e.sharingMode().subscribe(i),e.linkKey().subscribe(i),this._sourceWatchedValuesSubscriptions.set(e.id(),i));const s=(0,Ce.isSymbolSource)(e)?e:null;(0,ue.isPriceDataSource)(e)&&(this._priceSourcesById.set(e.id(),e),e.currencyChanged().subscribe(this,(()=>this._invalidateSourcesCache())),e.unitChanged().subscribe(this,(()=>this._invalidateSourcesCache())),this._priceDataSources.push(e),this._onPriceSourcesCollectionChanged(),null!==s&&(this._symbolSources.push(s),s.symbolResolved().subscribe(this,(()=>this._symbolSourceResolved.fire(e))),s.symbolResolvingActive().subscribe(this._recalcSymbolSourceResolvingActive),s.symbolHibernated().subscribe(this._onSymbolSourceCollectionChanged),this._recalcSymbolSourceResolvingActive(),this._onSymbolSourceCollectionChanged())),e.isMultiPaneAvailable()&&this.model().addMultiPaneSource(e),(0,he.isLollipopDataSource)(e)&&(this._lollipopDataSources.push(e),this.updateLollipopViews((0,G.sourceChangeEvent)(e.id()))),t||0!==this._bulkActions.activeCounter||this._dataSourcesCollectionChanged.fire()}_removeSourceFromCollections(e,t){const i=this.m_dataSources[e];i.properties().unsubscribeAll(this),i.zOrderChanged().unsubscribeAll(this),this.m_dataSources.splice(e,1),this._sourcesById.delete(i.id()) ;const s=i.id();if((0,C.isLineTool)(i)&&(i.normalizedPointsChanged().unsubscribeAll(this),i.fixedPointChanged().unsubscribeAll(this),this._sourceWatchedValuesSubscriptions.has(s))){const e=this._sourceWatchedValuesSubscriptions.get(s);i.hasAlert().unsubscribe(e),i.linkKey().unsubscribe(e)}this._invalidateSourcesCache();const o=(0,Ce.isSymbolSource)(i)?i:null;(0,ue.isPriceDataSource)(i)&&(this._priceSourcesById.delete(i.id()),i.currencyChanged().unsubscribeAll(this),i.unitChanged().unsubscribeAll(this),(0,b.removeItemFromArray)(this._priceDataSources,i),this._onPriceSourcesCollectionChanged(),null!==o&&((0,b.removeItemFromArray)(this._symbolSources,o),o.symbolResolved().unsubscribeAll(this),o.symbolResolvingActive().unsubscribe(this._recalcSymbolSourceResolvingActive),o.symbolHibernated().unsubscribe(this._onSymbolSourceCollectionChanged),this._recalcSymbolSourceResolvingActive(),this._onSymbolSourceCollectionChanged())),i.isMultiPaneAvailable()&&this.model().removeMultiPaneSource(i),(0,he.isLollipopDataSource)(i)&&((0,b.removeItemFromArray)(this._lollipopDataSources,i),this.updateLollipopViews((0,G.sourceChangeEvent)(i.id()))),t||0!==this._bulkActions.activeCounter||this._dataSourcesCollectionChanged.fire()}_recalculatePriceScaleByScaleRatio(e){this.isMainPane()&&e===this._lockedPriceScale&&(null!==this._currentPriceScaleRatio?this._applyOldScaleRatioToPriceScale():this._tryToApplyNewPriceScaleRatio())}_defaultBottomMargin(){return.01*this.properties().childs().bottomMargin.value()}_defaultTopMargin(){return.01*this.properties().childs().topMargin.value()}_updateMargins(){const e=this._defaultTopMargin(),t=this._defaultBottomMargin();for(const i of this._leftPriceScales)et(i,e,t);for(const i of this._rightPriceScales)et(i,e,t);for(const i of this.m_dataSources)if(this.isOverlay(i)){const s=i.priceScale();null!==s&&(et(s,e,t),this.recalculatePriceScale(s,(0,G.viewportChangeEvent)()))}for(const e of this._leftPriceScales)this.recalculatePriceScale(e,(0,G.viewportChangeEvent)());for(const e of this._rightPriceScales)this.recalculatePriceScale(e,(0,G.viewportChangeEvent)());this.updateAllViews((0,G.viewportChangeEvent)())}_batchReorder(e,t,i){i(this.sourcesByGroup().allExceptSpecialSources(),e,t),this._invalidateSourcesCache(),this._dataSourcesCollectionChanged.fire(),this.model().fullUpdate()}_placePriceScale(e,t,i){if("overlay"===t)return void e.invalidateMargins();const s="left"===t?this._leftPriceScales:this._rightPriceScales,o=void 0===i?s.length:i;s.splice(o,0,e),e.modeChanged().subscribe(this,this._onPriceScaleModeChanged.bind(this,e)),e.internalHeightChanged().subscribe(this,this._recalculatePriceScaleByScaleRatio.bind(this,e)),e.priceRangeChanged().subscribe(this,this._recalculateTimeScaleByScaleRatio.bind(this,e)),e.priceRangeChanged().subscribe(this,this._onPriceScaleSetMinMaxPriceRange.bind(this,e)),e.isVisible().subscribe(this._onPriceScaleIsVisibleChanged),e.resetScaleAvailable().subscribe(this._updateResetPriceScalesAvailableValue),e.isLockScale()&&((0,n.assert)(null===this._lockedPriceScale), this._lockedPriceScale=e,this._currentPriceScaleRatio=null),e.invalidateMargins(),this._onPriceScalesChanged.fire(),this._updateResetPriceScalesAvailableValue()}_onPriceScaleModeChanged(e,t,i){if(i.lockScale&&(this._lockedPriceScale!==e&&null!==this._lockedPriceScale&&this._lockedPriceScale.setMode({lockScale:!1}),this._lockedPriceScale=e,this._currentPriceScaleRatio=(0,Oe.scaleRatio)(this.timeScale(),e)),t.lockScale&&!i.lockScale&&(this._lockedPriceScale=null,this._currentPriceScaleRatio=null),t.percentage===i.percentage&&t.indexedTo100===i.indexedTo100)return;const s=this.timeScale().visibleBarsStrictRange();null!==s&&(e.recalculatePriceRange(s),e.updateAllViews((0,G.viewportChangeEvent)()))}_applyOldScaleRatioToPriceScale(){this._isRecalculatingScales||null===this._currentPriceScaleRatio||null===this._lockedPriceScale||(this._isRecalculatingScales=!0,this._setNewPriceRangeByScaleRatio(this._lockedPriceScale,this._currentPriceScaleRatio,this._mainSourceVisiblePriceRange(this._lockedPriceScale)),this._isRecalculatingScales=!1)}_setNewPriceRangeByScaleRatio(e,t,i,s,o){const r=(0,Oe.priceRangeByScaleRatio)(e,this.timeScale().barSpacing(),t);e.setPriceRange(null!==r?r:i,s,o)}_applyOldScaleRatioToTimeScale(){this._isRecalculatingScales||null===this._currentPriceScaleRatio||(this._isRecalculatingScales=!0,this._setNewBarSpacingByScaleRatio(),this._isRecalculatingScales=!1)}_tryToApplyNewPriceScaleRatio(){const e=(0,n.ensureNotNull)(this._lockedPriceScale),t=(0,Oe.scaleRatio)(this.timeScale(),e);this._currentPriceScaleRatio===t||e.isLog()||(this._currentPriceScaleRatio=t,this.model().mainSeriesScaleRatioPropertyOnChanged())}_recalculateTimeScaleByScaleRatio(e){e===this._lockedPriceScale&&(null!==this._currentPriceScaleRatio?this._applyOldScaleRatioToTimeScale():this._tryToApplyNewPriceScaleRatio())}_setNewBarSpacingByScaleRatio(){const e=this.timeScale().getValidBarSpacing((0,Oe.barSpacingByScaleRatio)((0,n.ensureNotNull)(this._lockedPriceScale),this._currentPriceScaleRatio));this.timeScale().isValidBarSpacing(e)&&this.timeScale().setBarSpacing(e)}_mainSourceVisiblePriceRange(e){const t=this.timeScale().visibleBarsStrictRange();return null!==t?(0,n.ensureNotNull)((0,n.ensureNotNull)(e.mainSource()).priceRange(t.firstBar(),t.lastBar())):new fe.PriceRange(-.5,.5)}_setMinMaxPriceRange(){const e=(0,n.ensureNotNull)(this._lockedPriceScale),t=(0,Oe.priceRangeByScaleRatio)(e,this.timeScale().maxBarSpacing(),this._currentPriceScaleRatio),i=(0,Oe.priceRangeByScaleRatio)(e,this.timeScale().minBarSpacing(),this._currentPriceScaleRatio);null!==t&&e.setMaxPriceRange(t),null!==i&&e.setMinPriceRange(i)}_onPriceScaleSetMinMaxPriceRange(e){e===this._lockedPriceScale&&this._setMinMaxPriceRange()}_onPriceSourcesCollectionChanged(){0===this._bulkActions.activeCounter?this._priceSourcesCollectionChanged.fire():this._bulkActions.priceSourcesCollectionChanged=!0}_nonOverlayPricesSourcesCount(){return this.m_dataSources.filter((e=>(!(0,K.isStudy)(e)||!e.isLinkedToSeries())&&((0, ue.isPriceDataSource)(e)&&e.showInObjectTree()&&!this.isOverlay(e)))).length}_restoreMainSeries(e,t,i,s,o,r){var n,a,l;const c=e.id,h=e.state;if(h&&o&&(h.style=null!==(n=o.style)&&void 0!==n?n:h.style,h.interval=o.interval||h.interval,o.symbol&&o.symbol!==h.symbol&&(h.symbol=o.symbol,delete h.currencyId,delete h.unitId)),h&&["candleStyle","hollowCandleStyle","haStyle"].forEach((e=>{h[e]&&(h[e].wickUpColor=h[e].wickUpColor||h[e].wickColor,h[e].wickDownColor=h[e].wickDownColor||h[e].wickColor)})),h&&(h.statusViewStyle=h.statusViewStyle||{},!h.statusViewStyle.symbolTextSource)){const e=!!h.statusViewStyle.showSymbolAsDescription;h.statusViewStyle.symbolTextSource=e?"ticker":"description"}if(h){h.extendedHours?h.sessionId="extended":h.sessionId||(h.sessionId="regular"),delete h.extendedHours,(0,Je.allChartStyles)().includes(h.style)||(h.style=2);const e=h.lineStyle.styleType;let t;delete h.lineStyle.styleType,0===e&&(t=14,h.lineWithMarkersStyle=(0,ne.clone)(h.lineStyle)),1===e&&(t=15,h.steplineStyle=(0,ne.clone)(h.lineStyle)),void 0!==t&&2===h.style&&(h.style=t)}if(!i){const e=this._model.mainSeries();this._model.mainPane().removeDataSource(e,!1,r),this._addSourceToCollections(e,r)}const d=this.model().mainSeries(),u=d.properties().childs();this.m_mainDataSource=d;const _=h&&h.style?h.style:void 0;if(6===_&&"ATR"===u.pnfStyle.childs().inputs.childs().style.value()?u.pnfStyle.childs().inputs.childs().style.setValueSilently("Traditional"):4===_&&"ATR"===u.renkoStyle.childs().inputs.childs().style.value()&&u.renkoStyle.childs().inputs.childs().style.setValueSilently("Traditional"),h&&!h.hasOwnProperty("showSessions")&&(h.showSessions=!1),h&&void 0===h.settlementAsClose&&(h.settlementAsClose=!1),h&&t&&(h.showCountdown=!1),h&&(t&&!("showSeriesLastValueProperty"in s)&&"showLastValue"in h&&this._model.properties().childs().scalesProperties.childs().showSeriesLastValue.setValue(h.showLastValue),delete h.showLastValue),h){const t={haStyle:(0,z.chartStyleStudyId)(8,!0),renkoStyle:(0,z.chartStyleStudyId)(4,!0),pbStyle:(0,z.chartStyleStudyId)(7,!0),kagiStyle:(0,z.chartStyleStudyId)(5,!0),pnfStyle:(0,z.chartStyleStudyId)(6,!0),rangeStyle:(0,z.chartStyleStudyId)(11,!0),volFootprintStyle:(0,z.chartStyleStudyId)(17,!0),tpoStyle:(0,z.chartStyleStudyId)(18,!0)},i=this._model.studyVersioning(),s=d.styleStudyInfos(),o=Object.keys(Fe.SYMBOL_STRING_DATA);for(let r=0;rthis._items[this._items.length-1])return t?this._validOffsetToIndex(this._items.length-1):null;for(let i=0;in){const i=e-n;if(i<500&&null!=t)return t(l,i);return l+i*c}return null}roughIndex(e,t=null){const i=this._items;if(!i.length||i.length<2)return null;const s=i.length-1,o=this._validOffsetToIndex(0),r=this._validOffsetToIndex(s),n=i[0],a=i[s];if(e>=n&&e<=a)return this.closestIndexLeft(e);const l=(a-n)/(r-o);if(ea){const i=e-a;let s=Math.trunc(i/l);if(s<500&&null!==t){const i=t(a,e);i.success&&(s=i.result)}return r+s}return null}closestIndexLeft(e){const t=this._items;if(!t.length)return null;if(Number.isNaN(e))return null;let i=t.length-1;if(e>=t[i])return this._validOffsetToIndex(i);let s=0;const o=t[s];if(es+1;){const o=s+i>>1,r=t[o];if(r>e)i=o;else{if(!(rthis._zoffset&&e+t>0)return at.logError("merge: when the first time point index is updated, we should fill the time points starting from the first one"),[];if(0===this._items.length)return this._items=i.slice(),this._zoffset=t,[{change:"rebuild",index:this._validOffsetToIndex(0)}];const s=e+this._zoffset;if(s<0){const o=Math.abs(s);if(i.lengththis._items.length){const e=n-this._items.length;for(let t=r;t{this._usePercentageRightOffset.setValue(!1),this._defaultRightOffsetOptionsUpdated()})),this._defaultRightOffsetPercentage.subscribe((e=>{if(e>=100||e<0){const t=Math.max(0,Math.min(e,99));this._defaultRightOffsetPercentage.setValue(t)}else this._usePercentageRightOffset.setValue(!0),this._defaultRightOffsetOptionsUpdated()})),this._usePercentageRightOffset.subscribe((()=>{this._defaultRightOffsetOptionsUpdated()})),this._options.preserveBarSpacing&&(this._barSpacing=this._scalesProperties.childs().barSpacing.value()||6),this._barSpacingChanged.subscribe(this,this._maxRightOffsetOnChanged),this._barSpacingChanged.subscribe(this,this._updateResetAvailableValue),this._rightOffsetChanged.subscribe(this,this._updateResetAvailableValue),this._widthChanged.subscribe(this,this._maxRightOffsetOnChanged),this._updateResetAvailableValue()}destroy(){this._barSpacingChanged.unsubscribeAll(this),this._barSpacingChanged.destroy(),this._widthChanged.unsubscribeAll(this),this._widthChanged.destroy()}isEmpty(){return 0===this._width||!this.canNormalize()}canNormalize(){return this._points.size()>0}update(e,t,i,s){this._visibleBarsInvalidated=!0,i.length>0&&this._points.merge(e,t,i),this._tickMarks.merge(s),this.correctOffset()}addTail(e,t,i){this._tickMarks.removeTail(t);const s=e.params,o=(0, n.ensureDefined)(this._tickMarks.maxIndex)+(i?0:1);for(let e=0;e0&&(i*=this._width/e.width)),this._tryToUpdateBarSpacing(this._barSpacing,i),this.correctOffset(),this._usePercentageRightOffset.value()&&(this._rightOffset=this.percentsToBarIndexLength(this._defaultRightOffsetPercentage.value())),this._rightOffsetChanged.fire(this._rightOffset)}marks(){if(this.isEmpty())return null;const e=this._barSpacing,t=5*((this._scalesProperties.childs().fontSize.value()||0)+4),i=Math.round(t/e),s=(0,n.ensureNotNull)(this.visibleBarsStrictRange()),o=Math.max(s.firstBar(),s.firstBar()-i),r=Math.max(s.lastBar(),s.lastBar()-i),a=this._tickMarks.build(e,t),l=[];for(const e of a){if(!(o<=e.index&&e.index<=r))continue;const t=this._tickMarks.indexToTime(e.index);null!==t&&l.push({coord:this.indexToCoordinate(e.index),label:this.formatLabel(t,e.span),span:e.span,major:e.label>=pt.DAY_SPAN})}return l}visibleBarsStrictRange(){return this._visibleBarsInvalidated&&(this._visibleBarsInvalidated=!1,this._updateVisibleBars()),this._visibleBars.strictRange()}visibleBarsStrictRangeChanged(){return this._visibleBarsChanged}visibleStrictDataRange(e){const t=this.visibleBarsStrictRange();if(null===t)return null;const i=e.search(t.firstBar(),yt.PlotRowSearchMode.NearestRight),s=e.search(t.lastBar(),yt.PlotRowSearchMode.NearestLeft);return null===i||null===s?null:new rt.BarsRange(i.index,s.index)}visibleExtendedDataRange(e,t){const i=this.visibleBarsStrictRange();if(null===i)return null;let s=1===t?null:e.search(i.firstBar()-1,yt.PlotRowSearchMode.NearestLeft),o=0===t?null:e.search(i.lastBar()+1,yt.PlotRowSearchMode.NearestRight) ;return null===s&&(s=e.search(i.firstBar(),yt.PlotRowSearchMode.NearestRight)),null===o&&(o=e.search(i.lastBar(),yt.PlotRowSearchMode.NearestLeft)),null===s||null===o?null:new rt.BarsRange(s.index,o.index)}logicalRangeChanged(){return this._logicalRangeChanged}tickMarks(){return this._tickMarks}points(){return this._points}width(){return this._width}setWidth(e,t){if(!Number.isFinite(e)||e<=0)return void xt.logWarn(`setWidth: invalid argument: ${e}`);if(this._width===e)return;const i=this._usePercentageRightOffset.value()&&this._rightOffset>0?this.barIndexLengthToPercents(this._rightOffset):-1;if(this._visibleBarsInvalidated=!0,(t||this._options.lockVisibleTimeRangeOnResize)&&this._width){const t=this._barSpacing*e/this._width;this._tryToUpdateBarSpacing(this._barSpacing,t)}else this._width&&this.setBarSpacing(this._barSpacing);if(null!==this._leftEdgeIndex){if((0,n.ensureNotNull)(this.visibleBarsStrictRange()).firstBar()<=this._leftEdgeIndex){const t=this._width-e;this._rightOffset-=Math.round(t/this._barSpacing)+1}}this._width=e,this._widthChanged.fire(e);const s=this._rightOffset;i>0?this._rightOffset=this.percentsToBarIndexLength(i):this.correctOffset(),this._rightOffset!==s&&this._rightOffsetChanged.fire(this._rightOffset),this._requestMoreData()}setLeftEdgeFix(e){this._leftEdgeIndex=e;const t=this.visibleBarsStrictRange();if(null===t)return;const i=t.firstBar()-e;if(i<0){const e=this._rightOffset-i-1;this.scrollToOffsetAnimated(e,500)}}indexToCoordinate(e){if(this.isEmpty())return 0;const t=this.baseIndex(),i=this._pointWeights.indexToTotalWeight(t+this._rightOffset+.5)-this._pointWeights.indexToTotalWeight(e);return this._width-i*this._barSpacing}indexToUserTime(e){return this._tickMarks.indexToTime(e)}timePointToIndex(e,t){switch(t){case 0:return this._points.indexOf(e,!1);case 1:return this._points.closestIndexLeft(e);default:return this._points.indexOf(e,!0)}}indexToTimePoint(e){return this._points.valueAt(e)}timeToCoordinate(e){const t=this._points.closestIndexLeft(e);if(null===t)return null;const i=(0,n.ensureNotNull)(this._points.valueAt(t)),s=this.indexToCoordinate(t);if(s<=0||s>=this._width)return null;const o=this.barSpacing(),r=this.baseIndex(),a=s+(e-i)/((0,n.ensureNotNull)(this._points.valueAt(r))-(0,n.ensureNotNull)(this._points.valueAt(r-1)))*o+1;return a<=0||a>=this._width?null:a}barBorders(e){const t={timePointIndex:e,left:NaN,center:NaN,right:NaN};return this.fillBarBorders([t]),t}fillBarBorders(e,t,i){var s,o;if(0===e.length)return;let r=null!==(s=null==t?void 0:t.startItemIndex)&&void 0!==s?s:0;const a=(null!==(o=null==t?void 0:t.endItemIndex)&&void 0!==o?o:e.length)-1;if(!0===i&&(r=(0,b.upperbound)(e,ht.UNPLOTTABLE_TIME_POINT_INDEX,((e,t)=>ea)return;const l=this._pointWeights.indexToTotalWeight(this.baseIndex()+this._rightOffset+.5),c=this._pointWeights.indexRangeToWeights(e[r].timePointIndex,e[a].timePointIndex,this._weightedPointsCache);let h=0,d=c[h];const u=d,_=c[c.length-1];let p=NaN,m=NaN,g=NaN,S=!0;for(let t=r;t<=a;t+=1){const i=e[t] ;if(i.timePointIndex_.timePointIndex)g=_.right+(i.timePointIndex-_.timePointIndex),m=g-.5,p=g-1;else for(S&&(p=d.left,m=d.center,g=d.right,S=!1);d.timePointIndexe{void 0!==t&&t(),this._requestMoreData()};if(e){const e=this.logicalRange(),t=this._model.mainSeries().bars().lastIndex();if(null===e||null===t)return;const i=this.indexToCoordinate(e.right()),o=this.indexToCoordinate(t+this._defaultRightOffset.value());return this._model.stopTimeScaleAnimation(),void this._model.setTimeScaleAnimation(new Ct.Animation({from:0,to:i-o,duration:1e3,easing:st.easingFunc.easeInOutQuint,onFinish:s}))}this._visibleBarsInvalidated=!0,this._updateRightOffset(i),this._onScroll.fire(),s()}scrollToFirstBar(e=(()=>{})){this._model.gotoTime(new Date("1800-01-01").getTime()).then(e),this._onScroll.fire()}scrollToOffsetAnimated(e,t){if(!isFinite(e))throw new RangeError("offset is required and must be finite number");const i=void 0===t?400:t;if(!isFinite(i)||i<=0)throw new RangeError("animationDuration (optional) must be finite positive number");const s=this._rightOffset,o=Date.now(),r=()=>{this._visibleBarsInvalidated=!0;const t=(Date.now()-o)/i;if(t>=1)return this._updateRightOffset(e),this._visibleBarsInvalidated=!0,this._model.recalculateAllPanes((0,G.viewportChangeEvent)()),void this._model.lightUpdate();const n=s+(e-s)*t;this._updateRightOffset(n),this._model.recalculateAllPanes((0,G.viewportChangeEvent)()),setTimeout(r,20)};r()}defaultRightOffset(){return this._defaultRightOffset}rightOffsetDefaultValue(){return 10}defaultRightOffsetPercentage(){return this._defaultRightOffsetPercentage}usePercentageRightOffset(){return this._usePercentageRightOffset}barSpacing(){return this._barSpacing}setBarSpacing(e){Number.isFinite(e)?(e=this.getValidBarSpacing(e),this._tryToUpdateBarSpacing(this._barSpacing,e)&&(this.correctOffset(),this._options.preserveBarSpacing&&((0,L.saveDefaultProperties)(!0), this._scalesProperties.childs().barSpacing.setValue(this._barSpacing),(0,L.saveDefaultProperties)(!1)),this._model.recalculateAllPanes((0,G.viewportChangeEvent)()),this._model.lightUpdate())):xt.logWarn(`setBarSpacing: invalid argument: ${e}`)}barSpacingChanged(){return this._barSpacingChanged}getValidBarSpacing(e){return null==e&&(e=this.barSpacing()),ethis.maxBarSpacing()?this.maxBarSpacing():e}isValidBarSpacing(e){return e>=this.minBarSpacing()&&e<=this.maxBarSpacing()}preserveBarSpacing(){return this._options.preserveBarSpacing}normalizeBarIndex(e){let t=0,i=0;const s=this.baseIndex(),o=(0,n.ensureNotNull)(this._points.range().value()).firstIndex;return es?(t=(0,n.ensureNotNull)(this._points.valueAt(s)),i=e-s):(t=(0,n.ensureNotNull)(this._points.valueAt(e)),i=0),{time_t:t,offset:i}}denormalizeTimePoint(e){const t=this._points.indexOf(e.time_t,!1);if(null!==t)return t+e.offset}rightOffset(){return this._rightOffset}rightOffsetChanged(){return this._rightOffsetChanged}minRightOffset(){var e;const t=null===(e=this.points().range().value())||void 0===e?void 0:e.firstIndex,i=this._baseIndex;if(void 0===t||null===i)return null;if(null!==this._leftEdgeIndex){const e=this.width()/this._barSpacing;return this._leftEdgeIndex-i+e-1}return t-i-1+Mt}maxRightOffset(){return this.width()/this._barSpacing-Mt}maxRightOffsetChanged(){return this._maxRightOffsetChanged}onReset(){return this._resetDelegate}baseIndex(){return this._baseIndex||0}zoom(e,t,i){if(!Number.isFinite(e)||!Number.isFinite(t))return void xt.logWarn(`zoom: invalid arguments: ${e}, ${t}, ${i}`);const s=this.rightOffset(),o=void 0!==i?!i:this._options.rightBarStaysOnScroll,r=o&&this.usePercentageRightOffset().value()&&s>=0,n=r?this.barIndexLengthToPercents(s):void 0,a=this.coordinateToIndex(e),l=this.barSpacing(),c=l+t*(l/10);this.setBarSpacing(c),o||(this.startScroll(this.indexToCoordinate(a)),this.scrollTo(e),this.endScroll()),r&&void 0!==n&&this.setRightOffset(this.percentsToBarIndexLength(n)),this._requestMoreData()}zoomToBarsRange(e,t){if(null!==this._leftEdgeIndex&&(e=Math.max(e,this._leftEdgeIndex)),t<=e)return;const i=this.baseIndex(),s=this._rightOffset;this._rightOffset=t-i;const o=e-.5,r=t+.5,n=Math.max(this._pointWeights.indexToTotalWeight(r)-this._pointWeights.indexToTotalWeight(o),Mt);this.setBarSpacing(this.width()/n),this._visibleBarsInvalidated=!0,this.correctOffset(),this._rightOffset!==s&&this._rightOffsetChanged.fire(this._rightOffset),this._requestMoreData()}coordinateToIndex(e){return Math.round(this.coordinateToFloatIndex(e))}coordinateToFloatIndex(e){const t=(e-this._baseIndexBarCenterCoordinate())/this._barSpacing,i=this._pointWeights.totalWeightToIndex(t);return Math.round(1e6*i)/1e6}coordinateToVisibleIndex(e){let t=this.coordinateToIndex(e);const i=this.visibleBarsStrictRange();return null===i||i.contains(t)||(t=Math.min(Math.max(i.firstBar(),t),i.lastBar())),t}canZoomIn(){return this.barSpacing()this._options.minBarSpacing}minBarSpacing(){return this._options.minBarSpacing}maxBarSpacing(){const e=this.width();return Tt?e:e/Mt}minVisibleBarCount(){return Mt}resetRightOffset(){this.setRightOffset(this.targetDefaultRightOffset())}reset(){this._visibleBarsInvalidated=!0,this._points.clear(),this._scrollData=null,this._scaleStartPoint=null,this._clearCommonTransitionsStartState(),this._tickMarks.reset(),this._leftEdgeIndex=null,this._resetDelegate.fire(),this.disconnect()}resetAvailable(){return this._resetAvailable.readonly()}disconnect(){this._requestingMoreData=!1,this._requestedTickmarksCount=0,this._endOfData=!1}setBaseIndex(e){Number.isFinite(e)?(this._visibleBarsInvalidated=!0,this._baseIndex=e,this._pointWeights.setBaseIndex(this._baseIndex),this.correctOffset()):xt.logDebug(`setBaseIndex: invalid argument: ${e}`)}resetBaseIndex(){this._visibleBarsInvalidated=!0,this._baseIndex=null}setRightOffset(e){Number.isFinite(e)?(this._visibleBarsInvalidated=!0,this._updateRightOffset(e)):xt.logWarn(`setRightOffset: invalid argument: ${e}`)}correctBarSpacing(){this.isEmpty()||this.points().size()e&&(this._rightOffset=e,this._visibleBarsInvalidated=!0);const t=this.minRightOffset();null!==t&&this._rightOffset=0&&this.setRightOffset(this.percentsToBarIndexLength(s))}endScale(){null!==this._scaleStartPoint&&(this._scaleStartPoint=null,this._clearCommonTransitionsStartState(),this._requestMoreData())}startScroll(e){null===this._scrollData&&null===this._commonTransitionStartState&&(this.isEmpty()||(this._scrollData={ startCoordinate:e,startRightEdgeLogical:this.baseIndex()+this._rightOffset+.5,startBaseIndex:this.baseIndex()},this._saveCommonTransitionsStartState()))}scrollTo(e){if(this._visibleBarsInvalidated=!0,null===this._scrollData)return;const{startCoordinate:t,startRightEdgeLogical:i,startBaseIndex:s}=this._scrollData,o=e-t,r=i+(this.baseIndex()-s),n=this.indexToCoordinate(r),a=this.coordinateToFloatIndex(n-o)-.5-this.baseIndex();this._updateRightOffset(a),this._onScroll.fire()}endScroll(){if(null===this._scrollData)return clearInterval(this._timeout),void(this._prevRO=void 0);this._scrollData=null,this._clearCommonTransitionsStartState(),this._requestMoreData(),this._timeout=setInterval((()=>{this._prevRO!==this.rightOffset()&&(this._prevRO=this.rightOffset(),this._requestMoreData())}),100)}formatLabel(e,t){const i="24-hours"===vt.timeHoursFormatProperty.value()?t.toString():`${t}_ampm`;let s=this._formattedBySpan.get(i);return void 0===s&&(s=new mt((e=>this.formatLabelImpl(e,t))),this._formattedBySpan.set(i,s)),s.format(new Date(e))}formatLabelImpl(e,t){if(!(e&&e instanceof Date))return"incorrect time";const s=function(e,t){if(e===pt.MILLISECOND_SPAN&&t)return"TimeWithMilliseconds";if(e{e.onChanged().subscribe(null,(t=>this._onChanged.fire(e.id,t)))}))}groups(){ return this._groups.filter((e=>e.isActualSymbol()))}groupsForAllSymbols(){return this._groups}createGroup(e,t,i){t=t||this._generateNextName();const s=new Et.LineToolsGroup(e,t,i);this._groups.push(s),s.onChanged().subscribe(null,(e=>this._onChanged.fire(s.id,e)));const o={visibilityChanged:!1,lockedChanged:!1,isActualIntervalChanged:!1,affectedLineTools:e.map((e=>e.id()))};return this._onChanged.fire(s.id,o),s}addGroup(e){this._groups.push(e),e.onChanged().subscribe(null,(t=>this._onChanged.fire(e.id,t))),this._onChanged.fire(e.id)}removeGroup(e){const t=this._groups.findIndex((t=>t.id===e.id));this._groups.splice(t,1),this._onChanged.fire(e.id)}groupForId(e){return this._groups.find((t=>t.id===e))||null}groupForLineTool(e){return this._groups.find((t=>t.containsLineTool(e)))||null}removeLineTools(e){const t=new Set;this._groups.forEach((i=>{const s=e.filter(i.containsLineTool.bind(i));s.length&&(i.excludeLineTools(s),t.add(i.id))}));return this._groups.filter((e=>0===e.lineTools().length)).forEach((e=>this.removeGroup(e))),Array.from(t)}state(e){return{groups:(e?this._groups.filter((e=>e.isActualSymbol())):this._groups).map((e=>e.state()))}}onChanged(){return this._onChanged}fireChangedAll(){this._groups.forEach((e=>{this._onChanged.fire(e.id)}))}static fromState(e,t){const i=[];for(const s of t.groups){const t=Et.LineToolsGroup.fromState(e,s);null!==t&&i.push(t)}return new Dt(i)}_generateNextName(){const e=new Set(this.groups().map((e=>e.name().value())));for(let t=1;;t++){const i=`Group ${t}`,s=`Group_${t}`;if(!e.has(i)&&!e.has(s))return i}}}var Nt=i(74439),Bt=i(988124),Rt=i.n(Bt),Ot=i(547944);let Vt=null;function Wt(e){return Boolean(e.symbolInfo.timezone)&&Boolean(e.symbolInfo.session)}class Ft{constructor(e,t){var i,s;this._sourceTargetBarBuilder=null,this._cache=new Map,this._source=e,this._sourceSession=Ot.SessionInfo.fromState(e.session),this._target=t,this._targetSession=Ot.SessionInfo.fromState(t.session),this._isResolutionTheSame=A.Interval.isEqual(e.resolution,t.resolution)||A.Interval.isTicks(e.resolution)&&A.Interval.isTicks(t.resolution),this._isSessionTheSame=(i=e.symbolInfo,s=t.symbolInfo,i.timezone===s.timezone&&i.session===s.session&&i.session_holidays===s.session_holidays&&i.corrections===s.corrections),this._shouldCorrectTradingDay=A.Interval.isDWM(e.resolution)&&!this._isSessionTheSame}sourceTimeToTargetTime(e){if(this._isSessionTheSame&&this._isResolutionTheSame)return e;if(!Wt(this._source)||!Wt(this._target))return e;let t=this._cache.get(e);if(void 0===t){let i=1e3*e;if(this._shouldCorrectTradingDay){let e=Rt().utc_to_cal(this._sourceSession.timezone,i);e=this._sourceSession.spec.correctTradingDay(e);const t=new Date(e);Rt().set_hms(t,0,0,0,0,this._sourceSession.timezone),i=t.valueOf()}const s=this._sourceTargetBuilder();s.moveTo(i);const o=s.indexOfBar(i);t=s.startOfBar(Math.max(0,o))/1e3,this._cache.set(e,t)}return t}_sourceTargetBuilder(){if(null===this._sourceTargetBarBuilder){const e=this._isSessionTheSame?this._targetSession:(null===Vt&&(Vt=new Ot.SessionInfo("Etc/UTC","24x7")),Vt) ;this._sourceTargetBarBuilder=(0,Ot.newBarBuilder)(this._target.resolution,this._targetSession,e)}return this._sourceTargetBarBuilder}}var Ht=i(638456),zt=i(314802),Ut=i(86746);const Gt="#000000";var qt=i(558793);async function jt(e){(await(0,qt.getChartAlertsFacade)()).invokeAlertEditor(e)}class Yt{constructor(e){this._alertLabelsBySource=new Map,this._alertsByAlertSeriesId=new Map,this._alertSeriesIdByAlert=new Map,this._alertLabelsOwnerSourcesByAlert=new Map,this._chartModel=e}destroy(){this.removeAllAlertLabels()}removeAllAlertLabels(){const e=this._alertLabelsBySource;this._alertLabelsBySource=new Map,this._alertsByAlertSeriesId.clear(),this._alertSeriesIdByAlert.clear(),this._alertLabelsOwnerSourcesByAlert.clear(),e.forEach((e=>{e.forEach((e=>this._chartModel.removeSource(e)))}))}removeSourceAlertLabels(e){for(const t of this._getAlertLabelsBySource(e))this.removeAlertLabel(t)}syncSourceAlertLabels(e){if(!(0,ue.isPriceDataSource)(e)||!e.hasStateForAlert())return;for(const t of this._getAlertLabelsBySource(e))t.alertOwnerSource().idForAlert()===t.alertSeriesId()||t.alert().isOHLC()||this.removeAlertLabel(t);const t=this._alertsByAlertSeriesId.get(e.idForAlert()),i=this._getAlertLabelsBySource(e);void 0!==t&&t.forEach((e=>{i.some((t=>t.alert()===e))||this._updateAlertLabelsByAlert(e,(0,n.ensureDefined)(this._alertSeriesIdByAlert.get(e)))}));const s=(0,n.ensureNotNull)(this._chartModel.paneForSource(e));for(const t of this._getAlertLabelsBySource(e)){const i=this._chartModel.paneForSource(t);i!==s?(null!==i&&i.removeDataSource(t),s.addDataSource(t,(0,n.ensureNotNull)(e.priceScale()),!1)):e.priceScale()!==t.priceScale()&&s.move(t,(0,n.ensureNotNull)(e.priceScale()))}}detachSourceAlertLabels(e){for(const t of this._getAlertLabelsBySource(e))this._chartModel.detachSource(t)}removeAlertLabel(e){const t=e.alertOwnerSource(),i=this._alertLabelsBySource.get(t);void 0!==i&&(i.delete(e),0===i.size&&this._alertLabelsBySource.delete(t));const s=e.alert(),o=this._alertLabelsOwnerSourcesByAlert.get(s);void 0!==o&&(o.delete(t),0===o.size&&this._alertLabelsOwnerSourcesByAlert.delete(s)),this._chartModel.removeSource(e)}addAlert(e,t){(0,n.assert)(!this._alertSeriesIdByAlert.has(e),"Alert is already added on the chart"),this._alertSeriesIdByAlert.set(e,t);let i=this._alertsByAlertSeriesId.get(t);void 0===i&&(i=new Set,this._alertsByAlertSeriesId.set(t,i)),i.add(e),this._updateAlertLabelsByAlert(e,t)}removeAlert(e){const t=this._alertLabelsOwnerSourcesByAlert.get(e);void 0!==t&&t.forEach((t=>{const i=this._alertLabelsBySource.get(t);void 0!==i&&i.forEach((t=>{t.alert()===e&&this.removeAlertLabel(t)}))}));const i=this._alertSeriesIdByAlert.get(e);if(!i)return;this._alertSeriesIdByAlert.delete(e);const s=this._alertsByAlertSeriesId.get(i);void 0!==s&&s.delete(e)}_findPanes(e){const t=[];for(const i of this._chartModel.panes()){const s=i.priceDataSources(),o=new Set;for(const t of s)t.hasStateForAlert()&&t.idForAlert()===e&&o.add(t);o.size>0&&t.push({pane:i,sources:o})}return t}_addLabelToPane(e,t,i,s){ const o=new y.AlertLabel(this._chartModel,e,s,jt);i.addDataSource(o,s.priceScale(),!1);let r=this._alertLabelsBySource.get(s);void 0===r&&(r=new Set,this._alertLabelsBySource.set(s,r)),r.add(o);let n=this._alertLabelsOwnerSourcesByAlert.get(e);void 0===n&&(n=new Set,this._alertLabelsOwnerSourcesByAlert.set(e,n)),n.add(s)}_updateAlertLabelsByAlert(e,t){const i=this._findPanes(t);if(i.length)for(const s of i)s.sources.forEach((i=>this._addLabelToPane(e,t,s.pane,i)));else if(e.isOHLC()){const i=this._chartModel.mainSeries();this._addLabelToPane(e,t,(0,n.ensureNotNull)(this._chartModel.paneForSource(i)),i)}this._chartModel.lightUpdate()}_getAlertLabelsBySource(e){const t=this._alertLabelsBySource.get(e);return void 0===t?[]:Array.from(t)}}var Kt=i(993171),Zt=i(960337),$t=i(778016),Xt=i(833813),Jt=i(690142),Qt=i(922850),ei=i(822122),ti=i(371927),ii=i(125226),si=i(315801),oi=i(458963),ri=i(246733),ni=i(838042),ai=i(792795);function li(e,t){return e.codet.code?1:0}class ci{constructor(e){this._convertibleItems=e,this._idsToItems=new Map;for(const t of e)this._idsToItems.set(t.id,t)}convertible(e){return void 0!==this._idsToItems.get(e)}item(e){var t;return null!==(t=this._idsToItems.get(e))&&void 0!==t?t:null}size(){return this._convertibleItems.length}filterConvertible(e,t){const i=this._convertibleItems.filter(function(e,t){return i=>!e.has(i.id)&&t(i.id)}(e,t));return i.sort(li),i}getItems(){return this._convertibleItems.map((e=>e.id))}}class hi{constructor(e){this._allGroups=new Set,this._idToName=new Map,this._idToDescription=new Map,this._groupedUnitIds=new Map,this._groupedUnits=new Map,this._groupById=new Map,this._size=0,this._units=e;for(const t in e)if(e.hasOwnProperty(t)){this._allGroups.add(t),this._groupedUnitIds.set(t,new Set(e[t].map((e=>e.id)))),this._groupedUnits.set(t,e[t]);for(const i of e[t])this._size++,this._idToName.set(i.id,i.name),this._idToDescription.set(i.id,i.description),this._groupById.set(i.id,t)}}unitsChanged(e){return this._units!==e}size(){return this._size}name(e){return this._idToName.get(e)||e}description(e){return this._idToDescription.get(e)||e}unitGroupById(e){return this._groupById.get(e)||null}allGroups(){return new Set(this._allGroups)}unitsByGroups(e){const t=[];return e.forEach((e=>{const i=this._groupedUnits.get(e);void 0!==i&&t.push({name:e,units:i})})),t}convertible(e,t){for(const i of t){const t=this._groupedUnitIds.get(i);if(void 0!==t&&t.has(e))return!0}return!1}}var di=i(150335);class ui{constructor(e){this._source=null,this._sourcePane=null,this._currentToolSupportsPhantomMode=!1,this._model=e}destroy(){this._source=null,this._sourcePane=null}source(){return this._source}onToolChanged(){this._removeSource();const e=this._model.currentTool();this._currentToolSupportsPhantomMode=(0,ve.isLineToolName)(e)&&(0,C.supportsPhantomMode)(e)}onCursorPositionUpdated(){if(!this._currentToolSupportsPhantomMode)return;const e=this._model.crossHairSource();if(this._sourcePane!==e.pane&&this._removeSource(),null===e.pane||!(0,di.isNumber)(e.index)||!(0, di.isNumber)(e.price))return void this._removeSource();const t={index:e.index,price:e.price};null!==this._source?this._source.setPoint(0,t):(this._source=this._model.createLineTool(e.pane,t,this._model.currentTool(),void 0,null,0),this._sourcePane=e.pane)}_removeSource(){null!==this._source&&(this._model.removeSource(this._source),this._source=null,this._sourcePane=null)}}var _i=i(315347),pi=i(80646),mi=i(451798);class gi{constructor(){this._lastValue=null}align(e,t,i){this._lastValue=null;let s=e;if(!(0,mi.magnetEnabled)().value())return s;const o=i.mainDataSource();if(null===o)return s;const r=o.model().mainSeries();if(o!==r)return s;const a=r.priceScale();if(a.isEmpty())return s;const l=function(e,t){const i=e.bars().valueAt(t);if(null===i)return;let s;if(null!==e.priceSource())s=[e.barFunction()(i)];else switch(e.style()){case 12:s=[i[2],i[3]];break;case 16:s=[i[2],i[4],i[3]];break;default:s=[i[1],i[2],i[3],i[4]]}return s}(r,t);if(!l)return s;const c=(0,n.ensure)(r.firstValue()),h=l.map((e=>({y:a.priceToCoordinate(e,c),price:e}))),d=a.priceToCoordinate(e,c);h.sort(((e,t)=>Math.abs(e.y-d)-Math.abs(t.y-d)));const u=h[0];return((0,mi.magnetMode)().value()===pi.MagnetMode.StrongMagnet||Math.abs(u.y-d)<50)&&(s=u.price,this._lastValue=s),s}lastValue(){return this._lastValue}resetLastValue(){this._lastValue=null}}var Si=i(242558),vi=i(996986),fi=i(787123),bi=i(43192);class yi extends bi.BitmapCoordinatesPaneRenderer{constructor(){super(...arguments),this._data=null}setData(e){this._data=e}hitTest(e){return null}_drawImpl(e){if(null===this._data)return;const{context:t,verticalPixelRatio:i,horizontalPixelRatio:s,bitmapSize:o}=e,r=Math.max(1,Math.floor(s));t.lineWidth=r;const n=Math.ceil(o.height*i),a=Math.ceil(o.width*s);if(t.lineCap="butt",this._data.vertLinesVisible){t.strokeStyle=this._data.vertLinesColor,(0,fi.setLineStyle)(t,this._data.vertLineStyle);for(const e of this._data.timeMarks){const i=Math.round(e.coord*s);(0,fi.drawVerticalLine)(t,i,0,n)}}if(this._data.horzLinesVisible){t.strokeStyle=this._data.horzLinesColor,(0,fi.setLineStyle)(t,this._data.horzLineStyle);for(const e of this._data.priceMarks){const s=Math.round(e.coord*i);(0,fi.drawHorizontalLine)(t,s,0,a)}}}}class Ci{constructor(e){this._renderer=new yi,this._pane=e}update(){}renderer(){const e=this._pane.defaultPriceScale(),t=this._pane.model().timeScale();if(e.isEmpty()||t.isEmpty())return null;const i=this._pane.model().properties().childs().paneProperties.childs(),s=t.marks(),o=i.gridLinesMode.value(),r={horzLinesVisible:"both"===o||"horz"===o,vertLinesVisible:"both"===o||"vert"===o,horzLinesColor:i.horzGridProperties.childs().color.value(),vertLinesColor:i.vertGridProperties.childs().color.value(),horzLineStyle:i.horzGridProperties.childs().style.value(),vertLineStyle:i.vertGridProperties.childs().style.value(),priceMarks:e.marks(),timeMarks:null!==s?s:[]};return this._renderer.setData(r),this._renderer}}class wi extends vi.DataSource{id(){return"grid"}paneViews(e){return[new Ci(e)]}name(){return"Grid"}}var Pi=i(229765) ;class Ti extends Pi.PriceAxisView{constructor(e,t,i,s){super(),this._source=e,this._pane=t,this._priceScale=i,this._priceProvider=s,this._properties=e.model().properties().childs().scalesProperties}setHitTestData(e){this._hitTestData=e}setXCoord(e){this._xCoord=e}additionalPadding(e){return 0}_updateRendererData(e,t,i){e.visible=!1,t.visible=!1;const s=this._priceScale,o=s.mainSource(),r=null!==o?o.firstValue():null;if(!this._isVisible()||s.isEmpty()||null===r)return;const n=this._currentPrice(s);if(null===n)return;i.background=(0,ri.resetTransparency)(this._bgColor()),i.textColor=this.generateTextColor(i.background);const a=this.additionalPadding(s.fontSize());i.additionalPaddingTop=a,i.additionalPaddingBottom=a,i.coordinate=s.priceToCoordinate(n,r),e.text=s.formatPrice(n,r),e.visible=!0,t.visible=!0,t.hitTestData=this._hitTestData,t.xCoord=this._xCoord}_currentPrice(e){return this._priceProvider(e)}}class Mi extends Ti{additionalPadding(e){return 2/12*e}_isVisible(){const e=this._source.lockedPane();return this._properties.childs().showPriceScaleCrosshairLabel.value()&&(this._source.visible||null!==e)&&(null!=e?e:this._source.pane)===this._pane}_currentPrice(e){const t=ke.crosshairLock.value();return null!==t&&1===t.type?this._pane===this._source.lockedPane()?t.price:null:super._currentPrice(e)}_bgColor(){const e=this._properties.childs();return this._source.model().dark().value()?e.crosshairLabelBgColorDark.value():e.crosshairLabelBgColorLight.value()}_updateRendererData(e,t,i){const s=t.visible;super._updateRendererData(e,t,i),this._source.isHovered()?t.backgroung=this._source.model().dark().value()?c.colorsPalette["color-cold-gray-600"]:c.colorsPalette["color-cold-gray-650"]:t.backgroung=void 0,s||(t.visible=s)}}class xi extends Ti{_isVisible(){return null!==this._source.measurePane().value()}_bgColor(){return this._properties.childs().axisLineToolLabelBackgroundColorCommon.value()}}var Ii=i(742391),Ai=i(439016),Li=i(406849),ki=i(373571),Ei=i(461794),Di=i(167222),Ni=i(703089),Bi=i(862297),Ri=i(726778),Oi=i(19039),Vi=i(783375),Wi=i(982217),Fi=i(360758),Hi=i(747971);function zi(e){const t=e.priceScale();return null===t?0:t.isPercentage()||t.isIndexedTo100()?2:1}class Ui extends Ii.PanePriceAxisView{constructor(e,t,i,s,o){super(e,t,s),this._crossHairMenuCachedState=null,this._hasActions=!1,this._gaOrigin="CH menu",this._crosshairPriceAxisView=e,e.setPaneRendererLabelIcon(0),this._crosshair=t,this._scale=i,this._options=o,this._updateGaOrigin(),(0,Ai.waitTradingService)().then((()=>{this._crossHairMenuCachedState=null}))}_updateImpl(e){const t=this._crosshair.y,i=this._chartModel.properties().childs().scalesProperties.childs().fontSize.value(),s=this._chartModel.timeScale().width(),o=this._crosshair.model().priceAxisRendererOptions(),r=i+2*this._crosshairPriceAxisView.additionalPadding(i)+o.paddingTop+o.paddingBottom,n=r,l=t-r/2,c=this._crosshair.pane,h=this._mainDataSourceOnPane(),d=h&&h.symbolSource(),u=!!d&&(d.isConvertedToOtherCurrency()||d.isConvertedToOtherUnit());if(this._updateGaOrigin(),null!==h){ const e=zi(h),t=h.idForAlert(),i=this._chartModel.isInReplay(),s=this._crossHairMenuCachedState,o=H.enabled("chart_crosshair_menu");null!==s&&s.id===t&&s.priceScale===e&&s.isCurrencyOrUnitConverted===u&&s.isInReplay===i&&s.isMenuEnabled===o||(this._updateTooltipAndActionsAvailability(h,e,u),this._crossHairMenuCachedState={id:t,priceScale:e,isCurrencyOrUnitConverted:u,isInReplay:i,isMenuEnabled:o})}null!==h&&(0,Ce.isActingAsSymbolSource)(h)&&h.symbol();const _=null!==c&&(c.maximized().value()||!c.collapsed().value())&&this._hasActions;this._crosshairPriceAxisView.setPaneLabelVisible(_);const p=this._position();if(null!==p){const e=0,t=s-n,i=Boolean(Fi.showPlusButtonOnCursor.value()),o=i?this._crosshair.x:void 0,c=void 0!==o?o-n/2:"left"===p?e:t,h=void 0!==o?o+n/2:"left"===p?e+n:t+n,d=(0,a.box)(new a.Point(c,l),new a.Point(h,l+r));this._data={itemBox:d,clickHandler:this._handleClick.bind(this,p,i,d)},this._crosshairPriceAxisView.setHitTestData(this._data),this._crosshairPriceAxisView.setXCoord(o)}super._updateImpl(e)}_priceScale(){return this._scale}_updateGaOrigin(){this._gaOrigin=Boolean(Fi.showPlusButtonOnCursor.value())?"CH menu cursor":"CH menu"}_updateTooltipAndActionsAvailability(e,t,i){this._hasActions=!1;if(!(1===t))return;const s=!this._chartModel.isInReplay(),o=!i&&e.alertCreationAvailable().value()&&s,r=!this._options.disableDrawHorizLineMenuAction,n=!i&&e===this._chartModel.mainSeries()&&Boolean((0,Ai.tradingService)())&&s;this._hasActions=n||o||r}_handleClick(e,t,i,s,o){if(H.enabled("widget")&&H.enabled("referral_program_for_widget_owners"))return void(0,Ni.showGoToTradingViewReferralDialog)({feature:"plusMenu"});(0,_.trackEvent)(this._gaOrigin,"click");const r=this._mainDataSourceOnPane(),n=null!==r&&(0,Ce.isActingAsSymbolSource)(r)?r.symbol():null,a={pageX:o.pageX,pageY:o.pageY,clientX:o.clientX,clientY:o.clientY,screenX:o.screenX,screenY:o.screenY,price:this._crosshair.price,symbol:n};m.emit("onPlusClick",a),this._getMenuItems(e).then((s=>{s.length>0&&this._showContextMenu(s,t,i,o,e)}))}_getMenuItems(e){const t=this._options.disableTradingMenuActions?null:(0,Ai.tradingService)(),i=(0,n.ensureNotNull)(this._crosshair.pane).mainDataSource(),s=!this._chartModel.isInReplay(),o=s,r=i===this._chartModel.mainSeries()&&Boolean(t)&&s,a=o?this._createAlertMenuItems(e):Promise.resolve([]),l=r?this._createTradingMenuItems():Promise.resolve([]);return Promise.all([a,l]).then((([e,i])=>{i.length>0&&(0,n.ensureNotNull)(t).trackEvent(this._gaOrigin,"click");const s=this._createAddHorizontalLineMenuItem(),o=e.length>0&&i.length>0;return[...e,o?new ki.Separator:null,...i,(e.length>0||i.length>0)&&s.length>0?new ki.Separator:null,...s].filter((e=>null!==e))}))}_createAlertMenuItems(e){if(null===this._crosshair.pane)return Promise.resolve([]);const t=this._crosshair.pane.mainDataSource();if(null===t)return Promise.resolve([]);const i=t.symbolSource();if(!!i&&(i.isConvertedToOtherCurrency()||i.isConvertedToOtherUnit()))return Promise.resolve([]);const s=this._crosshair.y;if(this._options.menuForMainSourceOnly){ if(t.alertCreationAvailable().value()&&t.isVisible()){const e=this._getActionAddAlert({source:t,y:s,isDisabled:!1});return Promise.resolve(null===e?[]:[e])}return Promise.resolve([])}const o=(0,n.ensureNotNull)(this._crosshair.pane).sourcesByGroup();let r=("left"===e?o.leftPriceScalesSources():o.rightPriceScalesSources()).filter((e=>(0,ue.isPriceDataSource)(e)&&e.alertCreationAvailable().value()&&e.isVisible()));return r.reverse(),r=(0,b.moveToHead)(r,this._chartModel.mainSeries()),(0,Ri.filterAccessibleDataSources)(r).then((e=>{const t=new Set(e),i=[];for(const e of r){const o=this._getActionAddAlert({source:e,y:s,isDisabled:!t.has(e)});null!==o&&i.push(o)}return i}))}_createTradingMenuItems(){const e=this._crosshair.y,t=(0,Ai.tradingService)();if(null===t||null===this._crosshair.pane)return Promise.resolve([]);const i=this._crosshair.pane.mainDataSource();if(null===i)return Promise.resolve([]);const s=i.symbolSource(),o=!!s&&(s.isConvertedToOtherCurrency()||s.isConvertedToOtherUnit()),r=zi(i);return o||1!==r?Promise.resolve([]):(0,Li.createTradeContext)(i,e).then((e=>t.chartContextMenuActions(e,{onlyMainActions:!0,hideNotExecutableAction:!0,gaOrigin:this._gaOrigin})))}_createAddHorizontalLineMenuItem(){if(null===this._crosshair.pane)return[];const e=this._crosshair.pane.mainDataSource();if(null===e)return[];const t=this._crosshair.y,i=this._getActionAddHorizontalLine({source:e,y:t,pane:this._crosshair.pane});return null===i?[]:[i]}_getActionAddAlert(e){const{source:t,y:s,isDisabled:o}=e,r=this._getValue(t,s),n=this._chartModel.mainSeries().interval();if(null===r||A.Interval.isTicks(n))return null;const a=this._formatValue(r,t),l=function(e){return(0,Ce.isActingAsSymbolSource)(e)?e.symbolTitle(Wi.TitleDisplayTarget.StatusLine,!0,!0):(0,Ei.clean)(e.title(Wi.TitleDisplayTarget.StatusLine,!0,{},!0),!0)}(t),c={label:(0,Oi.hasUsualAlertPlots)(t)?h.t(null,{replace:{title:l,price:a}},i(107005)):h.t(null,{replace:{title:l}},i(764615)),iconId:"Alert.Add"};return o?c.disabled=!0:c.onExecute=()=>this._addAlert(r,t),new Hi.ActionWithStandardIcon({actionId:"Alert.Add",options:c})}_getActionAddHorizontalLine(e){if(this._options.disableDrawHorizLineMenuAction)return null;const{source:t,y:s,pane:o}=e,r=this._getValue(t,s);if(null===r)return null;const n=this._formatValue(r,t),a={label:h.t(null,void 0,i(508338))+` ${n}`,iconId:"Chart.AddHorzLine"};return a.onExecute=()=>this._addHorizontalLineTool(o,r),new Hi.ActionWithStandardIcon({actionId:"Chart.Crosshair.PlusButton.DrawHorizontalLine",options:a})}_getValue(e,t){const i=e.priceScale(),s=e.firstValue();if(null===i||null===s)return null;return i.isPercentage()||i.isIndexedTo100()?null:i.coordinateToPrice(t,s)}_formatValue(e,t){return t.formatter().format(e)}async _addAlert(e,t){const{invokeAlertEditorWithOnlineSeries:s,createAlertSilently:o,getAlertEditorSource:r,getEditableAlertState:n}=await async function(){ const[{invokeAlertEditorWithOnlineSeries:e},{createAlertSilently:t},{getAlertEditorSource:s},{getEditableAlertState:o}]=await Promise.all([Promise.all([i.e(32327),i.e(94949),i.e(54253),i.e(22172)]).then(i.bind(i,429589)),Promise.all([i.e(92282),i.e(41723),i.e(29525),i.e(17344)]).then(i.bind(i,845980)),Promise.all([i.e(92282),i.e(41723),i.e(29525),i.e(17344)]).then(i.bind(i,19039)),Promise.all([i.e(92282),i.e(41723),i.e(29525),i.e(17344)]).then(i.bind(i,603061))]);return{invokeAlertEditorWithOnlineSeries:e,createAlertSilently:t,getAlertEditorSource:s,getEditableAlertState:o}}(),a=async()=>{const i=this._chartModel.mainSeries();if(!(0,ii.isFeatureEnabled)("alerts-editor-use-facade")||!(0,ii.isFeatureEnabled)("alerts-crosshair-plus-use-facade")){await(0,Bi.ensureSeriesIsNotOffline)(i),await(0,Bi.ensureResolvedSymbolInfo)(i);const s=r(t),a=s&&n(s,e);if(a)return o(a,s),void(0,_.trackEvent)(this._gaOrigin,"alert")}const a={dataSourceHub:this._chartModel,silent:!0,actionSource:"crosshair_menu"};(0,C.isLineTool)(t)?a.drawing=t:(a.series=t,a.value=e),s(a),(0,_.trackEvent)(this._gaOrigin,"alert")};(0,Di.runOrSigninWithFeature)((()=>a()),{feature:"alert",source:this._gaOrigin})}_addHorizontalLineTool(e,t){this._chartModel.undoModel().createLineTool({pane:e,point:{price:t,index:0},linetool:"LineToolHorzLine"})}_showContextMenu(e,t,i,s,o){const r="left"===o;setTimeout((()=>{const o=s.clientX-s.localX,a=s.clientY-s.localY,l=i.min.x+o,c=i.max.x+o,h=i.min.y+a,d=c-l,u=i.max.y+a-h,_=t?ke.crosshairLock.value():void 0;if(void 0!==_){const e=(0,n.ensureNotNull)(this._chartModel.timeScale().points().roughTime(this._crosshair.index));ke.crosshairLock.setValue({type:1,price:this._crosshair.price,time:e,modelId:this._chartModel.id(),paneId:(0,n.ensureNotNull)(this._crosshair.pane).id()})}Vi.ContextMenuManager.showMenu(e,{clientX:s.clientX,clientY:s.clientY,box:{x:l,w:d,y:h,h:u},attachToXBy:t?"auto":r?"left":"right",attachToYBy:"auto-strict",marginX:t?0:-d},void 0,{menuName:"CrosshairMenuView"},(()=>{void 0!==_&&ke.crosshairLock.setValue(_)}))}))}_mainDataSourceOnPane(){const e=this._crosshair.pane;return null!==e?e.mainDataSource():null}}var Gi=i(86121);class qi extends bi.BitmapCoordinatesPaneRenderer{constructor(e){super(),this._data=e}hitTest(e){return void 0===this._data.clickHandler?null:new si.HitTestResult(si.HitTarget.Custom,{clickHandler:this._data.clickHandler,tapHandler:this._data.clickHandler})}_drawImpl(e){const t=this._data.vertLinesVisible,i=this._data.horzLinesVisible;if(!t&&!i)return;const{context:s,horizontalPixelRatio:o,verticalPixelRatio:r,bitmapSize:n}=e;s.lineWidth=Math.max(1,Math.floor(this._data.lineWidth*o)),s.strokeStyle=this._data.color,s.fillStyle=this._data.color,s.lineCap="butt",(0,fi.setLineStyle)(s,this._data.lineStyle);const a=Math.round(this._data.x*o),l=Math.round(this._data.y*r),c=Math.ceil(n.width*o),h=Math.ceil(n.height*r);t&&a>=0&&(0,fi.drawVerticalLine)(s,a,0,h),i&&l>=0&&(0,fi.drawHorizontalLine)(s,l,0,c),this._data.drawCenter&&(s.beginPath(),s.arc(a,l,Math.round(3*o),0,2*Math.PI,!0), s.fillStyle=this._data.color,s.fill()),this._data.scissors&&function(e,t,i){const{context:s,bitmapSize:o,horizontalPixelRatio:r,verticalPixelRatio:n}=e,a=24*r,l=Math.round(t-a/2);let c=Math.round(i-a/2);if(c<0)c=0;else{const e=o.height-a;c>e&&(c=e)}s.translate(l,c),s.scale(r,n),s.fillStyle="#131722",s.fill(ji),s.strokeStyle="#fff",s.lineWidth=1,s.stroke(ji)}(e,a,l)}}const ji=new Path2D("m15.68 3.72-3.82 5.52-3.83-5.52-.28-.42-.42.3a2.84 2.84 0 0 0-.68 3.92l3.27 4.73-1.16 1.68a3.34 3.34 0 0 0-4.26 3.22 3.34 3.34 0 0 0 3.32 3.35 3.34 3.34 0 0 0 3.08-4.6l1-1.44 1.13 1.62a3.34 3.34 0 0 0 3.15 4.42c1.84 0 3.32-1.5 3.32-3.35a3.34 3.34 0 0 0-4.42-3.17l-1.23-1.78 3.22-4.65a2.86 2.86 0 0 0-.69-3.96l-.41-.29-.29.42ZM7.82 16.27c.47 0 .86.39.86.88 0 .48-.39.87-.86.87a.87.87 0 0 1-.86-.87c0-.5.4-.88.86-.88Zm8.36 0c.47 0 .86.39.86.88 0 .48-.4.87-.86.87a.87.87 0 0 1-.86-.87c0-.5.39-.88.86-.88Z");const Yi=c.colorsPalette["color-tv-blue-500"];class Ki{constructor(e,t){this._rendererData={},this._renderer=new qi(this._rendererData),this._source=e,this._pane=t}update(){}renderer(){var e,t;const i=this._source.selectPointMode().value()!==ke.SelectPointMode.None,s=this._source.lockedPane(),o=(this._source.visible||null!==s)&&(this._source.areLinesVisible||i)&&!this._source.linesShouldBeHidden(),r=this._rendererData;if(!o||null===this._pane)return null;const a=this._source.paneForPointSelect(),l=this._source.isReplaySelection(),c=null!=s?s:this._source.pane,h=this._pane===c,d=l||(null!==a?c===a&&this._pane===a:h);if(r.scissors=!1,i&&(l||this._source.isOnHoveredChartWidget())&&d){const e=(0,n.ensureNotNull)(this._source.pointToSelect());r.color=this._source.lineColor()||Yi,l?(r.lineWidth=2,r.scissors=h):r.lineWidth=1,r.lineStyle=oi.LINESTYLE_SOLID,r.horzLinesVisible=!0,r.vertLinesVisible=!0,r.drawCenter=!1,"time"===e?r.horzLinesVisible=!1:"price"===e&&(r.vertLinesVisible=!1)}else{const e=this._source.properties(),t=this._source.model().currentTool(),i=(0,Gi.lastMouseOrTouchEventInfo)(),s=i.isTouch&&!i.stylus&&((0,ve.isLineToolName)(t)||(0,ke.toolIsMeasure)(t));let o;o=s?Yi:e.childs().color.value();const n=e.childs().transparency.value();!s&&n>0&&(o=(0,ri.generateColor)(o,n)),r.color=o,r.horzLinesVisible=this._pane===c&&(this._pane.maximized().value()||!this._pane.collapsed().value()),r.vertLinesVisible=!0,r.lineWidth=e.childs().width.value(),r.lineStyle=e.childs().style.value(),r.drawCenter=s&&this._pane===c}return r.x=null!==(e=this._source.lockedX())&&void 0!==e?e:this._source.x,r.y=null!==(t=this._source.lockedY())&&void 0!==t?t:this._source.y,this._renderer}}var Zi=i(189767);const $i={backgroundColor:(0,ri.generateColor)(c.colorsPalette["color-tv-blue-500"],70),borderColor:(0,ri.generateColor)(c.colorsPalette["color-tv-blue-500"],20)};class Xi{constructor(e){this._renderer=new Zi.RectangleRenderer,this._rectangle=null,this._crosshair=e}update(){const e=this._crosshair.selection();null!==e&&null!==this._crosshair.pane?this._rectangle=this._crosshair.pane.logicalRectToPixels(e):this._rectangle=null}renderer(){ if(!this._rectangle)return null;const e={backcolor:$i.backgroundColor,color:$i.borderColor,fillBackground:!0,linewidth:1,points:[this._rectangle.min,this._rectangle.max],extendLeft:!1,extendRight:!1};return this._renderer.setData(e),this._renderer}}var Ji=i(31341),Qi=i(639958),es=i(754480),ts=i(943994),is=i(541801),ss=i(535698),os=i(142119),rs=i(855152);const ns=h.t(null,void 0,i(33355)),as=h.t(null,{context:"study"},i(32819)),ls=new Ee.PercentageFormatter,cs=new es.TimeSpanFormatter,hs=new ts.VolumeFormatter,ds=(0,c.getHexColorByName)("color-tv-blue-500"),us=(0,c.getHexColorByName)("color-ripe-red-400"),_s={bgColorPositive:(0,ri.generateColor)(ds,80),bgColorNegative:(0,ri.generateColor)(us,80),colorPositive:(0,c.getHexColorByName)("color-tv-blue-600"),colorNegative:(0,c.getHexColorByName)("color-ripe-red-400"),labelBgColorPositive:ds,labelBgColorNegative:us};class ps{constructor(e,t){this._pipFormatter=null,this._lastSymbolInfo=null,this._horzTrenRenderer=new is.TrendLineRenderer,this._vertTrenRenderer=new is.TrendLineRenderer,this._bgRenderer=new Zi.RectangleRenderer,this._labelRenderer=new ss.TextRenderer,this._p1=null,this._p2=null,this._label=null,this._source=e,this._pane=t}update(e){var t,i;const[s,o]=this._source.measurePoints();if(void 0===o)return this._p1=null,void(this._p2=null);const r=(0,n.ensureNotNull)(this._source.measurePane().value()),l=s.price,c=o.price,h=o.index-s.index,d=(0,Ji.forceLTRStr)(""+h),u=(0,n.ensureNotNull)(r.mainDataSource()),_=(0,n.ensureNotNull)(u.formatter()),p=o.price-l;let m=null!==(i=null===(t=_.formatChange)||void 0===t?void 0:t.call(_,o.price,l))&&void 0!==i?i:_.format(p);if(Math.abs(l)>1e-8){const e=p/Math.abs(l);m+=" ("+ls.format(100*e)+")"}const g=(0,Ji.forceLTRStr)(m);this._label=g+"\n"+ns.format({count:d});const S=(0,n.ensureNotNull)(u.firstValue()),v=this._source.model().timeScale().indexToCoordinate(s.index),f=this._source.model().timeScale().indexToCoordinate(o.index),b=r.defaultPriceScale().priceToCoordinate(l,S),y=r.defaultPriceScale().priceToCoordinate(c,S);this._p1=new a.Point(v,b),this._p2=new a.Point(f,y);const C=this._source.model().timeScale().indexToUserTime(s.index),w=this._source.model().timeScale().indexToUserTime(o.index);let P=null;if(null!==C&&null!==w){const e=this._pane.model().mainSeries().symbolInfo();null!==e&&e!==this._lastSymbolInfo&&(this._pipFormatter=new Qi.PipFormatter(e.pricescale,e.minmov,e.type,e.minmove2,e.typespecs),this._lastSymbolInfo=e),P=(w.valueOf()-C.valueOf())/1e3}const T=this._pipFormatter?this._pipFormatter.format(p):null,M=null!==T?" , "+T:"",x=null!==P?cs.format(P):null,I=null!==x?", "+(0,Ji.startWithLTR)(x):"";this._label=(0,Ji.forceLTRStr)(g+M)+"\n"+ns.format({count:d})+I;const A=this._source.measureVolume();Number.isNaN(A)||(this._label+=`\n${as} ${hs.format(A)}`);const L=c=50?rs.LineEnd.Arrow:rs.LineEnd.Normal};this._horzTrenRenderer.setData(s)}{const e=Math.round(B.x),t=new a.Point(e,this._p1.y),i=new a.Point(e,this._p2.y),s={points:[t,i],color:k,linewidth:1,linestyle:oi.LINESTYLE_SOLID,extendleft:!1,extendright:!1,leftend:rs.LineEnd.Normal,rightend:Math.abs(t.y-i.y)>=50?rs.LineEnd.Arrow:rs.LineEnd.Normal};this._vertTrenRenderer.setData(s)}const R={x:0,y:10},O=.5*(this._p1.x+this._p2.x),V=this._p2.y,W=new a.Point(O,V),F=(H=(0,n.ensureNotNull)(this._label),{points:[W],text:H,color:"#FFFFFF",horzAlign:"center",vertAlign:"middle",font:D.CHART_FONT_FAMILY,offsetX:R.x,offsetY:R.y,bold:!1,italic:!1,fontsize:12,padding:8,highlightBorder:!1,backgroundColor:E,backgroundTransparency:10,backgroundVertInflate:5,backgroundHorzInflate:5,backgroundRoundRect:4});var H;this._labelRenderer.setData(F);const z=this._labelRenderer.measure(),U=(0,ss.calculateLabelPosition)(z,this._p1,this._p2,R,this._pane.height());this._labelRenderer.setPoints([U])}renderer(){if(null===this._p1||null===this._p2)return null;const e=new os.CompositeRenderer;return e.append(this._bgRenderer),e.append(this._horzTrenRenderer),e.append(this._vertTrenRenderer),e.append(this._labelRenderer),e}}var ms=i(710455);class gs extends ms.MediaCoordinatesPaneRenderer{constructor(e){super(),this._data=e}hitTest(e){return null}_drawImpl(e){const t=e.context;t.translate(this._data.x-this._data.width/2,this._data.y-this._data.height/2),t.strokeStyle="rgba(153,153,153,.3)",t.lineWidth=2,t.beginPath(),this._drawShackle(t),t.stroke(),t.closePath(),t.strokeStyle="rgba(153,153,153,.7)",t.lineWidth=1,t.beginPath(),t.rect(0,this._data.height-this._data.bodyHeight+.5,this._data.width,this._data.bodyHeight),t.closePath(),t.stroke(),t.translate(0,-1),t.strokeStyle="#777",t.beginPath(),this._drawShackle(t),t.stroke(),t.closePath(),t.fillStyle="rgba(255,255,255,.7)",t.beginPath(),t.rect(1,this._data.height-this._data.bodyHeight+1.5,this._data.width-2,this._data.bodyHeight-2),t.fill(),t.beginPath(),t.rect(.5,this._data.height-this._data.bodyHeight+1,this._data.width-1,this._data.bodyHeight-1),t.stroke(),t.closePath(),t.fillStyle="#777",t.fillRect(this._data.width/2-.5,this._data.height-this._data.bodyHeight/2,1,2)}_drawShackle(e){const t=(this._data.width-3)/2,i=this._data.height-this._data.bodyHeight;e.moveTo(1.5,t),e.arc(this._data.width/2,t,t,Math.PI,2*Math.PI),i>t&&(e.moveTo(1.5,t),e.lineTo(1.5,i),e.moveTo(this._data.width-1.5,t),e.lineTo(this._data.width-1.5,i))}}class Ss{constructor(e,t,i){this._horzVisible=!1,this._source=e,this._pane=t,this._axis=i||"x"}update(){}renderer(){var e;const t=this._source.visible&&this._source.areLinesVisible,i=0===(null===(e=ke.crosshairLock.value())||void 0===e?void 0:e.type),s=t&&this._horzVisible,o=t||i ;if("y"===this._axis&&!s||!o)return null;const r="y"===this._axis?this._pane.width()-4.5:(0,n.ensureNotNull)(this._source.lockedX())+1,a="y"===this._axis?this._source.y:this._pane.height()-5.5-1;return new gs({x:r,y:a,width:9,height:11,bodyHeight:7})}}const vs=30;class fs{constructor(e,t,i){this._renderer=new Zi.RectangleRenderer,this._invalidated=!0,this._source=e,this._pane=t,this._model=i}update(){this._invalidated=!0}renderer(){return this._invalidated&&(this._updateImpl(),this._invalidated=!1),this._renderer}_updateImpl(){var e;if(this._renderer.setData(null),!this._pane||!this._source.visible)return;if(!this._source.model().mainSeries().lastValueData(void 0,!0,!0).index)return;const t=new a.Point(null!==(e=this._source.lockedX())&&void 0!==e?e:this._source.x,0),i=new a.Point(this._pane.width(),this._pane.height()),s={backcolor:(0,ri.applyTransparency)(this._model.backgroundColorAtYPercentFromTop(.5),vs),color:(0,ri.applyTransparency)(this._model.backgroundColorAtYPercentFromTop(.5),vs),fillBackground:!0,linewidth:0,points:[t,i],nohittest:!0,extendLeft:!1,extendRight:!1};this._renderer.setData(s)}}var bs=i(154765),ys=i(782086),Cs=i(60897);class ws extends ys.DataWindowView{constructor(e){super(),this._invalidated=!0,this._dateItem=new ys.DataWindowItem("",h.t(null,void 0,i(676912)),""),this._timeItem=new ys.DataWindowItem("",h.t(null,void 0,i(631976)),""),this._model=e,this._items.push(this._dateItem),this._items.push(this._timeItem)}update(){this._invalidated=!0}items(){return this._invalidated&&(this._updateImpl(),this._invalidated=!1),this._items}_updateImpl(){const e=this._model.mainSeries().isDWM();if(this._timeItem.setVisible(!e),this._timeItem.setValue(Cs.notAvailable),this._dateItem.setValue(Cs.notAvailable),this._model.timeScale().isEmpty())return;let t=this._model.crossHairSource().appliedIndex();if(!(0,di.isNumber)(t)){const e=this._model.mainSeries().data().last();if(null===e)return;t=e.index}const i=this._model.timeScale().indexToUserTime(t);null!==i&&(this._dateItem.setValue(this._model.dateFormatter().format(i)),e||this._timeItem.setValue(this._model.timeFormatter().format(i)))}}var Ps=i(161164);const Ts=c.colorsPalette["color-tv-blue-500"],Ms=h.t(null,{context:"Replay"},i(420747));class xs extends Ps.TimeAxisView{constructor(e,t,i,s=!1){super(e),this._indexProvider=i,this._highlighted=s,this._source=t,this._properties=e.properties().childs().scalesProperties}_getText(e){if(this._source.isReplaySelection()){const t=this._model.timeScale().indexToUserTime(e);return null!==t?`${Ms}: ${this._model.dateTimeFormatter().format(t)}`:""}return super._getText(e)}_getBgColor(){if(this._source.isReplaySelection())return Ts;const e=this._properties.childs();return this._highlighted?e.axisLineToolLabelBackgroundColorCommon.value():this._model.dark().value()?e.crosshairLabelBgColorDark.value():e.crosshairLabelBgColorLight.value()}_getIndex(){return this._model.crossHairSource().visible||null!==this._source.lockedPane()?this._indexProvider():null}_isVisible(){ return this._properties.childs().showTimeScaleCrosshairLabel.value()}}var Is=i(3140),As=i(731042);const Ls={menuEnabled:!1,menuForMainSourceOnly:!1,disableTradingMenuActions:!1,disableDrawHorizLineMenuAction:!1};let ks=0;const Es=(0,te.getLogger)("Chart.Crosshair");class Ds extends vi.DataSource{constructor(e,t,i){super(),this.pane=null,this.price=NaN,this.index=NaN,this.visible=!0,this.areLinesVisible=!0,this.x=NaN,this.y=NaN,this._lockData=null,this._measurePane=new $.WatchedValue(null),this._measurePaneViewCache=new WeakMap,this._startMeasurePoint=null,this._endMeasurePoint=null,this._lastValidMeasurePoint=null,this._isOnHoveredChartWidget=!1,this._crossHairSelectPointMode=new $.WatchedValue(ke.SelectPointMode.None),this._selectionPane=null,this._selectionView=new Xi(this),this._selectionStartPoint=null,this._timeLockPaneView=null,this._crosshairPaneViewCache=new WeakMap,this._pointSelectionPaneViewCache=new WeakMap,this._priceAxisViews=new Map,this._panePriceAxisViews=new Map,this._startMeasurePriceAxisViews=new Map,this._endMeasurePriceAxisViews=new Map,this._originX=NaN,this._originY=NaN,this._subscribed=!1,this._movedDelegate=new Z.Delegate,this._pointSelectedDelegate=new Z.Delegate,this._requestedPoint=null,this._paneForRequestedPoint=null,this._selectLineColor=null,this._volumeCalculator=null,this._selectFromAllChartsIfOutOfData=null,this._currentMeasurePointsetAndSymbolId=null,this._model=e,this._options=Object.assign({},Ls,i||{}),this._linesShouldBeHidden=this._model.readOnly(),this._dataWindowView=new ws(e),this.setSelectionEnabled(!1);const s=e=>t=>t===(0,n.ensureNotNull)(this._measurePane.value()).defaultPriceScale()?e():null;this._currentPosPriceProvider=e=>{const t=(0,n.ensureNotNull)(this.pane);if(e===t.defaultPriceScale())return this.price;const i=(0,n.ensureNotNull)(t.defaultPriceScale().mainSource()).firstValue();if(null===i)return null;const s=t.defaultPriceScale().priceToCoordinate(this.price,i),o=(0,n.ensureNotNull)(e.mainSource()).firstValue();return null===o?null:e.coordinateToPrice(s,o)},this._startMeasurePriceProvider=s((()=>(0,n.ensureNotNull)(this._startMeasurePoint).price)),this._endMeasurePriceProvider=s((()=>(0,n.ensureNotNull)(this._lastMeasurePoint()).price)),this._properties=t;this._timeAxisView=new xs(e,this,(()=>this.appliedIndex()),!1),this._startMeasureTimeAxisView=new xs(e,this,(()=>(0,n.ensureNotNull)(this._startMeasurePoint).index),!0),this._endMeasureTimeAxisView=new xs(e,this,(()=>(0,n.ensureNotNull)(this._lastMeasurePoint()).index),!0),e.readOnly()||ke.cursorTool.subscribe((e=>this.areLinesVisible="arrow"!==e),{callWithLast:!0}),this._crosshairLock=ke.crosshairLock.spawn(),this._showPlusButtonOnCursor=Fi.showPlusButtonOnCursor.spawn();const o=()=>{this.updateAllViews((0,G.sourceChangeEvent)(this.id())),this._model.lightUpdate()};this._crosshairLock.subscribe(o),this._showPlusButtonOnCursor.subscribe(o)}destroy(){null!==this._volumeCalculator&&this._volumeCalculator.destroy(),this._measurePane.setValue(null),this._crosshairLock.destroy(), this._showPlusButtonOnCursor.destroy(),this._removeMeasurePointset(),super.destroy()}name(){return"Crosshair"}moved(){return this._movedDelegate}originX(){return this._originX}originY(){return this._originY}saveOriginCoords(e,t){this._originX=e,this._originY=t}clearOriginCoords(){this._originX=NaN,this._originY=NaN}currentPoint(){return new a.Point(this.x,this.y)}model(){return this._model}appliedIndex(){var e;return null!==(e=this._getLockData().index)&&void 0!==e?e:this.index}lockedX(){var e;return null!==(e=this._getLockData().xCoord)&&void 0!==e?e:null}lockedY(){var e;return null!==(e=this._getLockData().yCoord)&&void 0!==e?e:null}lockedPane(){const e=ke.crosshairLock.value();return null===e||1!==e.type?null:this._model.id()===e.modelId?this._model.paneForId(e.paneId):this._model.mainPane()}invalidateLockPosition(){this._lockData=null}startMeasurePoint(){return this._startMeasurePoint||null}endMeasurePoint(){return this._endMeasurePoint||null}measureVolume(){if(null===this._volumeCalculator)return NaN;const[e,t]=this.measurePoints();return void 0===t?NaN:this._volumeCalculator.volume(e.index,t.index)}measurePane(){return this._measurePane.readonly()}startMeasuring(e,t){this._startMeasurePoint=e,this._measurePane.setValue(t),t.containsMainSeries()&&((0,n.assert)(null===this._volumeCalculator),this._volumeCalculator=new Is.SeriesTimeRangeVolumeCalculator(this.model().mainSeries())),this._model.updatePane(t)}finishMeasure(e){this._endMeasurePoint=e,this._createMeasurePointset((0,n.ensureNotNull)(this._startMeasurePoint),this._endMeasurePoint)}clearMeasure(){this._removeMeasurePointset(),this._measurePane.setValue(null),delete this._startMeasurePoint,delete this._endMeasurePoint,delete this._lastValidMeasurePoint,this._model.lightUpdate(),null!==this._volumeCalculator&&(this._volumeCalculator.destroy(),this._volumeCalculator=null)}measurePoints(){const e=[(0,n.ensureNotNull)(this._startMeasurePoint)],t=this._lastMeasurePoint();return null!==t&&e.push(t),e}startSelection(e){this._selectionStartPoint=this.currentLogicalPoint(),this._selectionPane=e}clearSelection(){this._selectionStartPoint=null,this._selectionPane=null}selection(){return this._selectionStartPoint?{p1:this._selectionStartPoint,p2:this.currentLogicalPoint()}:null}currentLogicalPoint(){return{index:this.appliedIndex(),price:this.price}}selectPointMode(){return this._crossHairSelectPointMode}lineColor(){return this._selectLineColor}cancelRequestSelectPoint(){this._crossHairSelectPointMode.value()!==ke.SelectPointMode.None&&this._setSelectPointModeState(ke.SelectPointMode.None),this._selectFromAllChartsIfOutOfData=null}requestSelectPoint(e){(0,n.assert)(this._crossHairSelectPointMode.value()===ke.SelectPointMode.None,"Point already requested");const{pointType:t,pane:i,lineColor:s=null,selectFromAllChartsIfOutOfData:o,selectPointMode:r=ke.SelectPointMode.Study}=e;i&&((0,n.assert)(-1!==this._model.panes().indexOf(i),"Chartmodel doesn't contains specified pane"),this._paneForRequestedPoint=i, this._model.panesCollectionChanged().subscribe(this,this._paneCollectionChanged)),this._selectLineColor=s,this._requestedPoint=t,this._selectFromAllChartsIfOutOfData=null!=o?o:null,this._setSelectPointModeState(r)}onPointSelected(){return this._pointSelectedDelegate}trySelectCurrentPoint(){var e;const t=(0,n.ensureNotNull)(this._requestedPoint);let i=null;if(!this._model.mainSeries().bars().search(this.index,yt.PlotRowSearchMode.Exact)&&"price"!==t&&(this._selectFromAllChartsIfOutOfData&&(i=null!==(e=Math.min(...Array.from(ke.barTimesUnderCursor.values())))&&void 0!==e?e:null),null===i))return;const s=(0,n.ensureNotNull)(this.pane);if(this._paneForRequestedPoint&&this._paneForRequestedPoint!==s)return;let o,r=i;if("price"===t||null!==i||(r=this._model.timeScale().indexToTimePoint(this.index),null!==r)){if("time"!==t){const e=s.mainDataSource();if(null===e)return;const t=e.firstValue(),i=e.priceScale();if(null===t||null===i)return;o=i.coordinateToPrice(this.y,t)}this._setSelectPointModeState(ke.SelectPointMode.None),this._pointSelectedDelegate.fire({time:null!=r?r:void 0,price:o},s)}}isOnHoveredChartWidget(){return this._isOnHoveredChartWidget}setOnHoveredChartWidget(e){this._isOnHoveredChartWidget=e}isReplaySelection(){return("AllCharts"===bs.replayModeProperty.value()||this._isOnHoveredChartWidget)&&this._crossHairSelectPointMode.value()===ke.SelectPointMode.Replay}clearPosition(){this.visible=!1,this.index=NaN,this.price=NaN,this.x=NaN,this.y=NaN,this.pane=null,this.clearOriginCoords(),this._updateVisibilityDependentPaneViews()}setPosition(e,t,i){this._subscribed||(this._model.mainSeries().onRestarted().subscribe(this,this.clearMeasure),this._subscribed=!0),this.visible=!0;const s=this._model.id(),o=this._model.mainSeries().bars().search(this.index,yt.PlotRowSearchMode.NearestRight);return o&&ke.barTimesUnderCursor.set(s,o.value[0]),this._tryToUpdateViews(e,t,i)}setLinesShouldBeHidden(e){this._linesShouldBeHidden=e}linesShouldBeHidden(){return this._linesShouldBeHidden}handleContextMenuEvent(e){this._crossHairSelectPointMode.value()!==ke.SelectPointMode.None&&this._setSelectPointModeState(ke.SelectPointMode.None)}properties(){return this._properties}priceAxisViews(e,t){var i;const s=null===this._requestedPoint||"time"!==this._requestedPoint||!this._isOnHoveredChartWidget,o=[];return(null!==(i=this.lockedPane())&&void 0!==i?i:this.pane)===e&&s&&o.push(this._createPriceAxisViewOnDemand(this._priceAxisViews,this._panePriceAxisViews,e,t,this._currentPosPriceProvider,Mi,!0)[0]),this._startMeasurePoint&&o.push(this._createPriceAxisViewOnDemand(this._startMeasurePriceAxisViews,null,e,t,this._startMeasurePriceProvider,xi)[0]),this._lastMeasurePoint()&&o.push(this._createPriceAxisViewOnDemand(this._endMeasurePriceAxisViews,null,e,t,this._endMeasurePriceProvider,xi)[0]),o}timeAxisViews(){const e=[],t=null===this._requestedPoint||"price"!==this._requestedPoint||!this._isOnHoveredChartWidget;return this._linesShouldBeHidden||!this.visible&&null===ke.crosshairLock.value()||!t||e.push(this._timeAxisView), this._startMeasurePoint&&e.push(this._startMeasureTimeAxisView),this._lastMeasurePoint()&&e.push(this._endMeasureTimeAxisView),e}paneViews(e){var t,i;if(void 0===e)return null;const s=[];if(this.isReplaySelection()){let t=this._pointSelectionPaneViewCache.get(e);t||(t=new fs(this,e,this._model),this._pointSelectionPaneViewCache.set(e,t)),s.push(t)}let o=this._crosshairPaneViewCache.get(e);if(o||(o=new Ki(this,e),this._crosshairPaneViewCache.set(e,o)),s.push(o),e===this._selectionPane&&s.push(this._selectionView),e===this._measurePane.value()){let t=this._measurePaneViewCache.get(e);t||(t=new ps(this,e),this._measurePaneViewCache.set(e,t)),t.update((0,G.sourceChangeEvent)(this.id())),s.push(t)}if((Fi.addPlusButtonProperty.value()||this._showPlusButtonOnCursor.value())&&1!==(null===(t=ke.crosshairLock.value())||void 0===t?void 0:t.type)){const t=e===this.pane,i=!Ht.CheckMobile.any()||window.screen.width>=320,o=ke.tool.value(),r=(0,ve.isLineToolName)(o),n=null!==this._model.lineBeingEdited()||null!==this._model.lineBeingCreated()||this._model.sourcesBeingMoved().length>0||null!==this._model.customSourceBeingMoved()||(0,ke.toolIsMeasure)(o);if(t&&this._isOnHoveredChartWidget&&this._crossHairSelectPointMode.value()===ke.SelectPointMode.None&&i&&!r&&!n){const t=e.mainDataSource();if(null!==t){const i=t.priceScale();if(null!==i){const t=this._createPriceAxisViewOnDemand(this._priceAxisViews,this._panePriceAxisViews,e,i,this._currentPosPriceProvider,Mi,!0)[1];null!==t&&s.push(t)}}}}return 0===(null===(i=ke.crosshairLock.value())||void 0===i?void 0:i.type)&&(null===this._timeLockPaneView&&(this._timeLockPaneView=new Ss(this,e)),s.push(this._timeLockPaneView)),s}dataWindowView(){return this._dataWindowView}updateAllViews(e){this._priceAxisViews.forEach((t=>{t.forEach((t=>t.update(e)))})),this._panePriceAxisViews.forEach((t=>{t.forEach((t=>t.update(e)))})),this._startMeasurePoint&&(this._startMeasurePriceAxisViews.forEach((t=>{t.forEach((t=>t.update(e)))})),this._startMeasureTimeAxisView.update(e)),this._lastMeasurePoint()&&(this._endMeasurePriceAxisViews.forEach((t=>{t.forEach((t=>t.update(e)))})),this._endMeasureTimeAxisView.update(e)),this._timeAxisView.update(e),this._selectionView.update(),this._dataWindowView.update(),this._updateVisibilityDependentPaneViews()}isMenuEnabled(){return this._options.menuEnabled}isHoveredEnabled(){return Fi.addPlusButtonProperty.value()||this._showPlusButtonOnCursor.value()}isHovered(){return this._model.hoveredSource()===this}pointToSelect(){return this._requestedPoint}paneForPointSelect(){return this._paneForRequestedPoint}_lastMeasurePoint(){return this._endMeasurePoint?this._endMeasurePoint:(null!==this.pane&&this._measurePane.value()===this.pane&&(this._lastValidMeasurePoint={price:this._model.magnet().align(this.price,this.index,this.pane),index:this.index}),this._lastValidMeasurePoint||null)}_createPriceAxisViewOnDemand(e,t,i,s,o,r,a=!1){let l=e.get(i),c=null!==t?t.get(i):void 0;void 0===l&&(l=new Map,e.set(i,l),this.isMenuEnabled()&&null!==t&&(c=new Map,t.set(i,c)), a&&i.onDestroyed().subscribe(this,(()=>this._onPaneDestroyed(i))));let h=l.get(s);if(void 0===h){if(h=new r(this,i,s,o),l.set(s,h),void 0!==c){const e=new Ui(h,this,s,this._model,this._options);c.set(s,e)}a&&s.lastSourceRemoved().subscribe(this,(()=>this._onPriceScaleCleared(s)))}let d=null;return void 0!==c&&(d=(0,n.ensureDefined)(c.get(s))),[h,d]}_onPaneDestroyed(e){e.onDestroyed().unsubscribeAll(this),this._priceAxisViews.delete(e),this._panePriceAxisViews.delete(e),this._startMeasurePriceAxisViews.delete(e),this._endMeasurePriceAxisViews.delete(e)}_onPriceScaleCleared(e){e.lastSourceRemoved().unsubscribeAll(this),this._priceAxisViews.forEach((t=>t.delete(e))),this._panePriceAxisViews.forEach((t=>t.delete(e))),this._startMeasurePriceAxisViews.forEach((t=>t.delete(e))),this._endMeasurePriceAxisViews.forEach((t=>t.delete(e)))}_tryToUpdateViews(e,t,i){return!!this._tryToUpdateData(e,t,i)&&(this.updateAllViews((0,G.sourceChangeEvent)(this.id())),this._movedDelegate.fire({index:this.index,price:this.price}),!0)}_tryToUpdateData(e,t,i){const s=this.x,o=this.y,r=this.price,a=this.index,l=this.pane,c=this._priceScaleByPane(i);if(this.index=e,this.x=isNaN(e)?NaN:this._model.timeScale().indexToCoordinate(e),null!==c&&null!==i){this.pane=i,this.price=t;const e=(0,n.ensureNotNull)(i.mainDataSource()).firstValue();this.y=null===e?NaN:c.priceToCoordinate(t,e)}else this.pane=null,this.price=NaN,this.y=NaN;return s!==this.x||o!==this.y||a!==this.index||r!==this.price||l!==this.pane}_priceScaleByPane(e){return e&&!e.defaultPriceScale().isEmpty()?e.defaultPriceScale():null}_setSelectPointModeState(e){e===ke.SelectPointMode.None&&(this._requestedPoint=null,this._selectLineColor=null,this._paneForRequestedPoint&&(this._paneForRequestedPoint=null,this._model.panesCollectionChanged().unsubscribe(this,this._paneCollectionChanged))),ke.activePointSelectionMode.setValue(e),this._crossHairSelectPointMode.setValue(e),this._model.lightUpdate()}_paneCollectionChanged(e){const t=this._paneForRequestedPoint;null!==t&&-1===e.indexOf(t)&&this.cancelRequestSelectPoint()}_updateVisibilityDependentPaneViews(){var e;for(const t of this.model().panes())null===(e=this._pointSelectionPaneViewCache.get(t))||void 0===e||e.update()}_getLockData(){var e;if(null===this._lockData){const t=ke.crosshairLock.value();if(null===t)this._lockData={};else{const i=this._model.timeScale(),s=null!==(e=i.points().roughIndex(t.time))&&void 0!==e?e:void 0,o=void 0===s?void 0:i.indexToCoordinate(s);switch(t.type){case 0:this._lockData={index:s,xCoord:o};break;case 1:{let e;const i=this.lockedPane();if(null!==i){const s=i.mainDataSource();if(null!==s){const i=s.firstValue(),o=s.priceScale();null!==o&&null!==i&&(e=o.priceToCoordinate(t.price,i))}}this._lockData={index:s,xCoord:o,yCoord:e}}}}}return this._lockData}_createMeasurePointset(e,t){const i=this._normalizePoint(e),s=this._normalizePoint(t),o=[[i.time_t,i.offset],[s.time_t,s.offset]];this._removeMeasurePointset(),++ks,this._currentMeasurePointsetAndSymbolId={measurePointsetId:ks,symbolId:(0, n.ensureNotNull)(this._model.mainSeries().seriesSource().symbolInstanceId())};const r=(0,As.getServerInterval)(this._model.mainSeries().interval());this._model.chartApi().createPointset(this._currentMeasurePointsetIdWithPrefix(),"turnaround",this._currentMeasurePointsetAndSymbolId.symbolId,r,o,this._onPointsetResponse.bind(this))}_removeMeasurePointset(){null!==this._currentMeasurePointsetAndSymbolId&&this._model.chartApi().isConnected().value()&&this._model.chartApi().removePointset(this._currentMeasurePointsetIdWithPrefix()),this._currentMeasurePointsetAndSymbolId=null}_currentMeasurePointsetIdWithPrefix(){return"pointsetMeasure_"+(0,n.ensureNotNull)(this._currentMeasurePointsetAndSymbolId).measurePointsetId}_normalizePoint(e){return{...this._model.timeScale().normalizeBarIndex(e.index),price:e.price}}_onPointsetResponse(e){if("pointset_error"===e.method)return void Es.logError(`Error getting pointset: ${e.params[0]} ${e.params[1]}`);if(e.params.customId!==this._currentMeasurePointsetIdWithPrefix())return;if(null===this._startMeasurePoint||null===this._endMeasurePoint)return;const t=e.params.plots;if(2!==t.length)return;const i=t[0].value[0],s=t[1].value[0];this._startMeasurePoint.index=i,this._endMeasurePoint.index=s,this.updateAllViews((0,G.sourceChangeEvent)(this.id())),this._model.updateSource(this)}}var Ns=i(983898),Bs=i(155964),Rs=i(808068),Os=i(809796),Vs=i(677305),Ws=i(772466),Fs=i(62802);class Hs{constructor(e){this._priceSourceNamesById=new Map,e.forEach((e=>this._priceSourceNamesById.set(e.id,e.name)))}name(e){var t;return null!==(t=this._priceSourceNamesById.get(e))&&void 0!==t?t:null}priceSourcesChanged(e){return e.length!==this._priceSourceNamesById.size}}var zs=i(66732);const Us=new Os.TranslatedString("remove deselected empty line tools",h.t(null,void 0,i(59211))),Gs=H.enabled("auto_enable_symbol_labels"),qs=(0,ii.isFeatureEnabled)("save_shared_line_tools"),js=(0,te.getLogger)("Chart.ChartModel");function Ys(e,t){const i=e.indexOf(t);return-1!==i&&(e.splice(i,1),!0)}function Ks(e){var t,i;for(let s=e.length;s--;){const o=e[s].dataSources();for(let e=o.length;e--;)null===(t=o[e].dataWindowView())||void 0===t||t.update();const r=e[s].priceDataSources();for(let e=r.length;e--;)null===(i=r[e].legendView())||void 0===i||i.update()}}const Zs={isSnapshot:!1,readOnly:!1,watermarkEnabled:!0,shiftVisibleRangeOnNewBar:!0,currencyConversionEnabled:!1,unitConversionEnabled:!1,countdownEnabled:!0,lastPriceAnimationEnabled:!0,onWidget:!1,hideIdeas:!1},$s={throttle:o.default,debounce:s.default},Xs=new Map([[v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction,{timeout:2e3,adapter:"debounce"}],[v.RecalcVisibleRangeStudiesReason.DataUpdate,{timeout:5e3,adapter:"throttle"}],[v.RecalcVisibleRangeStudiesReason.SeriesRestart,{timeout:2e3,adapter:"debounce"}],[v.RecalcVisibleRangeStudiesReason.SeriesCompleted,{timeout:2e3,adapter:"debounce"}],[v.RecalcVisibleRangeStudiesReason.StudyCreation,{timeout:2e3,adapter:"debounce"}]]),Js=Array.from(Xs.values());class Qs{constructor(e,t,i,o,r,n,a,l,c,h){ this._onRearrangePanes=new Z.Delegate,this._lineToolsGroupModel=new Dt,this._sourcesBeingMoved=[],this._activeItemBeingMoved=null,this._lineBeingEdited=null,this._linePointBeingEdited=null,this._linePointBeingChanged=null,this._customSourceBeingMovedHitTestData=null,this._customSourceBeingMoved=null,this._dataSourceCollectionChanged=new Z.Delegate,this._sourceProperitesChanged=new Z.Delegate,this._sourceZOrderChanged=new Z.Delegate,this._symbolSourceResolved=new Z.Delegate,this._symbolSourceResolvingActive=new $.WatchedValue(!1),this._adjustForDividendsAvailability=new $.WatchedValue(0),this._adjustForDividendsEnabled=new $.WatchedValue(!1),this._sessions=null,this._currentTool="",this._lineBeingCreated=null,this._paneBeingCreatedLineOn=null,this._lineCancelled=new Z.Delegate,this._phantomSourceContainer=new ui(this),this._destroyed=!1,this._isSettingsExternalPosition=!1,this._isTimeScrolling=!1,this._magnet=new gi,this._scrollingState=null,this._modelIntervals=[],this._rendererOptionsProvider=new N(this),this._studyInserted=new Z.Delegate,this._cachedStudiesMaxOffset=0,this._replayStatus=new $.WatchedValue(Nt.ReplayStatus.Undefined),this._panes=[],this._tagsChanged=new Z.Delegate,this._strategySources=[],this._strategySourcesChange=new Z.Delegate,this._activeStrategySource=new $.WatchedValue(null),this._paneCollapsingAvailable=new $.WatchedValue(!1),this._panesCollectionChanged=new Z.Delegate,this._scrollEnabled=H.enabled("chart_scroll"),this._zoomEnabled=H.enabled("chart_zoom"),this._lollipopSourcesWatcher=null,this._alertsWatcher=null,this._hoveredSource=null,this._hoveredSourceChanged=new Z.Delegate,this._lastHoveredHittestData=null,this._lastSelectedHittestData=null,this._topmostCustomSources=[],this._fgCustomSources=[],this._bgCustomSources=[],this._allCustomSources=[],this._customSourcesMap=new Map,this._multiPaneSources=[],this._showLegendProperty=new k.default,this._id=(0,ie.guid)(),this._chartSaveTime=null,this._availableCurrenciesList=null,this._availableCurrencies=new ci([]),this._availablePriceSources=new Hs([]),this._availableUnitsObject=null,this._availableUnits=new hi({}),this._availablePriceSourcesBySymbol=new Map,this._shouldBeSavedEvenIfHidden=!1,this._watchedThemeSpawn=d.watchedTheme.spawn(),this._gradientColorsCache=null,this._studiesWV=new X.WatchedObject([],b.compareTwoCollectionsByIds),this._studiesExcludeInternalWV=new X.WatchedObject([],b.compareTwoCollectionsByIds),this._resetScalesAvailable=new $.WatchedValue(!1),this._recalcVRStudiesParams={reasons:new Set},this._recalcColorStudiesParams={},this._recalcVisibleRangeStudiesImplDebouncedByAdapter=new Map(Object.keys($s).map((e=>[e,new Map(Js.filter((t=>t.adapter===e)).map((e=>[e.timeout,$s[e.adapter](this._recalcVisibleRangeStudiesImpl.bind(this,this._recalcVRStudiesParams),e.timeout)])))]))),this._recalcColorStudiesImplDebounced=(0,s.default)(this._recalcColorStudiesImpl.bind(this,this._recalcColorStudiesParams),250),this._width=0,this._resetScales=new Z.Delegate,this._chartThemeLoaded=new Z.Delegate,this._selection=new P, this._selectedSourceChanged=new Z.Delegate,this._symbolSourceCollectionChanged=new Z.Delegate,this._gridSource=new wi,this._visibleRangeStudiesInputs=new X.WatchedObject(null),this._syncPointCache=new Map,this._lastAppliedGotoTimeRange=null,this._lastGotoTimeRange=null,this._lollipopSourcesWatcherLoader=null,this._clearSelection=()=>{this._lastSelectedHittestData=null,this._selection.clear()},this._removeSourceFromSelection=e=>{this._selection.remove(e)},this._addSourceToSelection=(e,t)=>{const i=this._selection.isSelected(e);i&&this._lastSelectedHittestData===t||e&&!e.isSelectionEnabled()||(this._lastSelectedHittestData=t||null,i||this._selection.add(e))},this._recalcSymbolResolvingActive=()=>{for(const e of this._panes)if(e.symbolSourceResolvingActive().value())return void this._symbolSourceResolvingActive.setValue(!0);this._symbolSourceResolvingActive.setValue(!1)},this._recalcAdjustForDividendsAvailability=()=>{var e,t,i,s;if(this._symbolSourceResolvingActive.value())return;const o=this.mainSeries();switch(null!==(t=null===(e=o.symbolInfo())||void 0===e?void 0:e.allowed_adjustment)&&void 0!==t?t:"none"){case"dividends":return void this._adjustForDividendsAvailability.setValue(2);case"splits":return void this._adjustForDividendsAvailability.setValue(1);case"any":return void this._adjustForDividendsAvailability.setValue(3)}for(const e of this.symbolSources().filter(Ce.isActingAsSymbolSource)){if(e.symbolHibernated().value()||e===o)continue;if("any"===(null!==(s=null===(i=e.symbolInfo())||void 0===i?void 0:i.allowed_adjustment)&&void 0!==s?s:"none"))return void this._adjustForDividendsAvailability.setValue(3)}this._adjustForDividendsAvailability.setValue(0)},this._recalcAdjustForDividendsEnabled=()=>{switch(this._adjustForDividendsAvailability.value()){case 2:return void this._adjustForDividendsEnabled.setValue(!0);case 0:case 1:return void this._adjustForDividendsEnabled.setValue(!1)}this._adjustForDividendsEnabled.setValue(this.mainSeries().properties().childs().dividendsAdjustment.value())},this._recalcPaneCollapsingAvailable=e=>{let t=this._panes.filter((e=>!e.collapsed().value())).length;0===t&&e&&this._panes.length>0&&(this._panes[0].collapsed().setValue(!1),t=1),this._paneCollapsingAvailable.setValue(t>1)},this._updateResetScalesAvailableValue=()=>{const e=this._timeScale.resetAvailable().value()||this._panes.some((e=>e.resetPriceScalesAvailable().value()));this._resetScalesAvailable.setValue(e)},this._chartApi=e,this._invalidateHandler=t,this._undoModel=r,this._properties=i,this._options=(0,ne.merge)((0,ne.clone)(Zs),a),this._hibernateWV=l,this._linkingGroupIndex=c,this._isAutoSaveEnabled=h,this._readOnly=this._options.readOnly,this._isSnapshot=this._options.isSnapshot,this._alertsWatcher=new Yt(this),this.onWidget()||Jt.withWeekdayProperty.subscribe(this,(()=>this._updateDateTimeFormatter())),this._chartSaveTime=(new Date).valueOf(),this._backgroundColor=new $.WatchedValue(this._getBackgroundColor()),this._backgroundTopColor=new $.WatchedValue(this._getBackgroundColor(!0)), this._properties.childs().paneProperties.childs().background.subscribe(this,this._updateBackgroundColor),this._properties.childs().paneProperties.childs().backgroundType.subscribe(this,this._updateBackgroundColor),this._properties.childs().paneProperties.childs().backgroundGradientStartColor.subscribe(this,this._updateBackgroundColor),this._properties.childs().paneProperties.childs().backgroundGradientEndColor.subscribe(this,this._updateBackgroundColor),this._backgroundColor.subscribe(this.recalcColorStudies.bind(this,!1)),this._backgroundTopColor.subscribe(this.recalcColorStudies.bind(this,!1)),this._backgroundCounterColor=new $.WatchedValue(this._getBackgroundCounterColor()),this._backgroundColor.subscribe((()=>this._backgroundCounterColor.setValue(this._getBackgroundCounterColor()))),this._isDark=(0,zs.combine)((e=>"white"===e),this._backgroundCounterColor.weakReference()),this._watchedThemeSpawn.subscribe(this._updateBackgroundColor.bind(this)),this._symbolSourceResolvingActive.subscribe(this._recalcAdjustForDividendsAvailability),this.setStudiesMetaData((0,B.studyMetaInfoRepository)().getInternalMetaInfoArray(),(0,B.studyMetaInfoRepository)().getMigrations()),(0,ke.init)();const u=this._readOnly?new k.default((0,W.defaults)("chartproperties.paneProperties.crossHairProperties")):this._properties.childs().paneProperties.childs().crossHairProperties;this.m_crossHairSource=new Ds(this,u,this._options.crossHair),this._crossHairSelectPointMode=this.m_crossHairSource.selectPointMode().spawn(),this._crossHairSelectPointMode.subscribe((e=>{if(e!==ke.SelectPointMode.None&&this.lineBeingCreated()){const e=ke.tool.value();this.cancelCreatingLine(),ke.tool.setValue(e)}})),this._tagsChanged=new Z.Delegate;const _=new L.DefaultProperty("chartproperties.mainSeriesProperties");_.addExclusion("priceAxisProperties.lockScale"),_.addExclusion("priceAxisProperties.percentage"),_.addExclusion("priceAxisProperties.indexedTo100"),_.addExclusion("priceAxisProperties.isInverted"),_.addExclusion("priceAxisProperties.log"),_.addExclusion("priceAxisProperties.logDisabled"),_.addExclusion("priceAxisProperties.percentageDisabled"),_.addExclusion("priceAxisProperties.autoScaleDisabled"),_.merge(i.childs().mainSeriesProperties.state()),this._timeScale=new It(this,this._options.timeScale),this._timeScale.resetAvailable().subscribe(this._updateResetScalesAvailableValue);const p={countdownEnabled:this._options.countdownEnabled,lastPriceAnimationEnabled:this._options.lastPriceAnimationEnabled};this.m_mainSeries=new ye.Series(this,_,p,o),this.m_mainSeries.onStyleChanged().subscribe(this._timeScale,this._timeScale.invalidateVisibleBars);const m=()=>this.fullUpdate();this.m_mainSeries.properties().childs().showCountdown.subscribe(this,(()=>{this.m_mainSeries.updateAllViews((0,G.sourceChangeEvent)(this.m_mainSeries.id())),m()})),(0,Q.currencyUnitVisibilityProperty)().subscribe(this,m),(0,ee.autoLogButtonsVisibilityProperty)().subscribe(this,m), this._timeScale.visibleBarsStrictRangeChanged().subscribe(this.m_mainSeries,this.m_mainSeries.clearHighLowPriceCache),this._timeScale.visibleBarsStrictRangeChanged().subscribe(this.m_mainSeries,this.m_mainSeries.clearAveragePriceCache),this.createPane(void 0,{axisProperties:_.childs().priceAxisProperties.state(["autoScale"])}),this._adjustForDividendsAvailability.subscribe(this._recalcAdjustForDividendsEnabled),this.mainSeries().properties().childs().dividendsAdjustment.subscribe(this,this._recalcAdjustForDividendsEnabled),this._recalcAdjustForDividendsEnabled(),this._boundUpdateStudiesMaxOffset=this._updateStudiesMaxOffset.bind(this),this.mainSeries().dataEvents().seriesTimeFrame().subscribe(this,((e,t,i,s)=>{if(null!==this._lastAppliedGotoTimeRange&&null!==i&&s&&(0,_i.areEqualTimeFrames)(this._lastAppliedGotoTimeRange.range,i)){const e=this.appliedTimeFrame().value();null!==e&&!this._lastAppliedGotoTimeRange.actual&&(0,_i.areEqualTimeFrames)(this._lastAppliedGotoTimeRange.range,e.val)&&this.appliedTimeFrame().setValue(null),this._lastAppliedGotoTimeRange=null}})),this.mainSeries().dataEvents().completed().subscribe(this,(e=>{null===this._lastAppliedGotoTimeRange&&null!==this._lastGotoTimeRange&&(this.gotoTimeRange(this._lastGotoTimeRange.from,this._lastGotoTimeRange.to),this._lastGotoTimeRange=null)}));const g=this._panes[0];g.setStretchFactor(2*g.stretchFactor()),this._properties.listeners().subscribe(this,this.lightUpdate),this._properties.childs().timezone.subscribe(null,(()=>{this._chartApi&&this._chartApi.isConnected().value()&&this._chartApi.switchTimezone(this.timezone())})),g.addDataSource(this.m_mainSeries,g.findSuitableScale(this.m_mainSeries),!1),this._barsMarksSources=n(this);for(const e of this._barsMarksSources)e.setOwnerSource(this.m_mainSeries),g.addDataSource(e,this.m_mainSeries.priceScale(),!0);this.m_mainSeries.symbolResolved().subscribe(this,this._clearAvailablePriceSources),this._createLollipopSourcesWatcher()}setStudiesMetaData(e,t){this._studiesMetaData=e,this._studyVersioning=new T.StudyVersioning(this._studiesMetaData,t)}restart(){this._chartApi.switchTimezone(this.timezone()),this._timeScale.reset(),this.m_mainSeries.restart();for(const e of this.dataSources())e.restart&&e!==this.m_mainSeries&&e.restart();this.sessions().restart()}version(){return 3}collapsed(){return this._hibernateWV}visibleRangeStudiesInputs(){return this._visibleRangeStudiesInputs.readonly()}chartSaveTime(){return this._chartSaveTime}setChartSaveTime(e){this._chartSaveTime=e}destroy(){var e;this._phantomSourceContainer.destroy(),this._hoveredSourceChanged.destroy(),null!==this._watermarkSource&&(this._watermarkSource.destroy(),this._watermarkSource=null),Array.from(this._customSourcesMap.keys()).forEach(this._removeCustomSource,this),(0,n.assert)(0===this._topmostCustomSources.length),(0,n.assert)(0===this._fgCustomSources.length),(0,n.assert)(0===this._bgCustomSources.length),(0,n.assert)(0===this._allCustomSources.length),(0,n.assert)(0===this._customSourcesMap.size), null!==this._lollipopSourcesWatcher&&(this._lollipopSourcesWatcher.destroy(),this._lollipopSourcesWatcher=null),null!==this._alertsWatcher&&this._alertsWatcher.destroy(),this.onWidget()||Jt.withWeekdayProperty.unsubscribeAll(this),this._properties.childs().paneProperties.childs().background.unsubscribeAll(this),this._properties.childs().paneProperties.childs().backgroundType.unsubscribeAll(this),this._properties.childs().paneProperties.childs().backgroundGradientEndColor.unsubscribeAll(this),this._properties.childs().paneProperties.childs().backgroundGradientStartColor.unsubscribeAll(this),this._watchedThemeSpawn.destroy(),this._lastHoveredHittestData=null,this._lastSelectedHittestData=null,(0,Q.currencyUnitVisibilityProperty)().unsubscribeAll(this),(0,ee.autoLogButtonsVisibilityProperty)().unsubscribeAll(this),this._alertsList&&(this._alertsList.destroy(),this._alertsList=void 0),window.loginStateChange.unsubscribeAll(this),this._crossHairSelectPointMode.destroy(),this.m_mainSeries.symbolResolved().unsubscribe(this,this._clearAvailablePriceSources),null===(e=this._lollipopSourcesWatcherLoader)||void 0===e||e.destroy(),this._destroyed=!0}undoModel(){return this._undoModel}onData(e){switch(e.method){case"timescale_update":{const t=e.params;this._updateTimeScale({index:t.index,zoffset:t.zoffset,values:t.changes,indexDiffs:t.index_diff,baseIndex:t.baseIndex,marks:t.marks,clearFlag:t.clear});break}case"timescale_completed":{const t=Boolean(e.params[0]);this._timeScale.onTimeScaleCompleted(t);break}}}addStrategySource(e,t){1!==t&&-1===this._strategySources.indexOf(e)&&(this._strategySources.push(e),this._strategySourcesChange.fire(t),this.setActiveStrategySource(e))}removeStrategySource(e,t){if(1===t)return;const i=this._strategySources.indexOf(e);if(-1!==i){if(this._strategySources.splice(i,1)[0]===this._activeStrategySource.value()&&this.unsetActiveStrategySource(),this._strategySources.length>0){const e=this._strategySources[this._strategySources.length-1];this.setActiveStrategySource(e)}this._strategySourcesChange.fire(t)}}setActiveStrategySource(e){-1!==this._strategySources.indexOf(e)&&this._activeStrategySource.setValue(e)}unsetActiveStrategySource(){this._activeStrategySource.setValue(null)}activeStrategySource(){return this._activeStrategySource}strategySources(){return this._strategySources}strategySourcesChange(){return this._strategySourcesChange}setScrollEnabled(e){this._scrollEnabled=e}scrollEnabled(){return this._scrollEnabled}setZoomEnabled(e){this._zoomEnabled=e}zoomEnabled(){return this._zoomEnabled}zoomToViewport(e,t,i,s,o){this.setTimeViewport(e,t);let r=Math.min(i,s),n=Math.max(i,s);const a=o.defaultPriceScale();a.isPercentage()||a.setMode({autoScale:!1}),a.isLog()&&(r=a.priceToLogical(r),n=a.priceToLogical(n)),a.setPriceRange(new fe.PriceRange(r,n)),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.invalidate(this._paneInvalidationMask(o,J.InvalidationLevel.Light))}setTimeViewport(e,t){const i=this.appliedTimeFrame().value();null!==this._lastAppliedGotoTimeRange&&null!==i&&(0, _i.areEqualTimeFrames)(this._lastAppliedGotoTimeRange.range,i.val)&&!this._lastAppliedGotoTimeRange.actual||(this.timeScale().zoomToBarsRange(e,t),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction),this.lightUpdate())}onTagsChanged(){return this._tagsChanged}canZoomIn(){return this._timeScale.canZoomIn()&&this._zoomEnabled}canZoomOut(){return this._timeScale.canZoomOut()&&this._zoomEnabled}onPaneTagsChanged(){this._tagsChanged.fire()}panesCollectionChanged(){return this._panesCollectionChanged}dataSourceCollectionChanged(){return this._dataSourceCollectionChanged}symbolSourceCollectionChanged(){return this._symbolSourceCollectionChanged}symbolSourceResolved(){return this._symbolSourceResolved}symbolSourceResolvingActive(){return this._symbolSourceResolvingActive}adjustForDividendsAvailability(){return this._adjustForDividendsAvailability}adjustForDividendsEnabled(){return this._adjustForDividendsEnabled}paneCollapsingAvailable(){return this._paneCollapsingAvailable}sourcePropertiesChanged(){return this._sourceProperitesChanged}sourceZOrderChanged(){return this._sourceZOrderChanged}zoomTime(e,t,i){if(!this._zoomEnabled)return;const s=this.timeScale();if(s.isEmpty()||0===t)return;const o=s.width();e=Math.max(1,Math.min(e,o-2)),s.zoom(e,t,i),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.lightUpdate(),this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction)}lineBeingEdited(){return this._lineBeingEdited}linePointBeingEdited(){return this._linePointBeingEdited}activeItemBeingMoved(){return this._activeItemBeingMoved}linePointBeingChanged(){return this._linePointBeingChanged}updateAllPaneViews(e){for(const t of this._panes)t.updateAllViews(e)}dataSources(){const e=[this.crossHairSource()];for(const t of this._panes)for(const i of t.dataSources())e.push(i);return e}priceDataSources(){const e=[];for(const t of this._panes)for(const i of t.priceDataSources())e.push(i);return e}symbolSources(){const e=[];for(const t of this._panes)for(const i of t.symbolSources())e.push(i);return e}selection(){return this._selection}selectionMacro(e,t=!1){const i=this.selection().allSources();e({removeSourceFromSelection:this._removeSourceFromSelection,addSourceToSelection:this._addSourceToSelection,clearSelection:this._clearSelection,selection:this.selection.bind(this)});const s=(0,b.subtract)(i,this.selection().allSources()),o=(0,b.subtract)(this.selection().allSources(),i);o.concat(i).forEach((e=>e.updateAllViews((0,G.selectionChangeEvent)())));let r=[];s.forEach((e=>{if((0,C.isLineTool)(e)){const i=e.hasAlert().value()&&e.getAlertSync();i&&!i.isPrice()&&i.setSelected(!1),!t&&e.shouldBeRemovedOnDeselect()&&r.push(e)}})),o.forEach((e=>{const t=(0,C.isLineTool)(e)&&e.hasAlert&&e.hasAlert().value()&&e.getAlertSync();t&&t.setSelected(!0)})),r=r.filter((e=>null!==this.dataSourceForId(e.id()))),r.length>0&&this._undoModel.removeSources(r,!1,Us),this.lightUpdate(), (s.length>0||o.length>0)&&this._selectedSourceChanged.fire()}onSelectedSourceChanged(){return this._selectedSourceChanged}checkLineToolSelection(){const e=this.selection().allSources();this._selection.checkLineToolSelection(),e.length!==this.selection().allSources().length&&this._selectedSourceChanged.fire()}lineToolsGroupModel(){return this._lineToolsGroupModel}restoreLineToolsGroups(e){this._lineToolsGroupModel=Dt.fromState(this,e)}realignLineTools(e){for(const t of this._panes)(void 0===e||t.hasDataSource(e))&&t.realignLineTools(e)&&this._dataSourceCollectionChanged.fire(t)}copyToOtherCharts(e,t){const i=this.mainSeries(),s=i.syncModel(),o=this.timeScale();if(s)for(const r of e){if(!r.isSynchronizable())continue;const e=r.linkKey().value()||(0,ie.randomHash)();r.linkKey().setValue(e);const a=r.state(!1),l=r.normalizedPoints(),c=r.properties().interval.value(),h=i.interval();let d;if(A.Interval.isEqual(c,h))d=l.map((e=>{const t=(0,n.ensureNotNull)(o.timePointToIndex(e.time_t))+e.offset;return{price:e.price,timeStamp:(0,n.ensureNotNull)(this.externalTimeStamp(t))}}));else{const e=s.createNewModelWithResolution(c);d=l.map((t=>({price:t.price,timeStamp:0===t.offset?t.time_t:e.projectTime(t.time_t,t.offset)})))}const u={...a,id:r.id(),linkKey:e,points:d,linetool:r.toolname,model:this,symbol:i.symbol(),withUndo:t,zOrder:r.zorder(),finalState:{points:l,interval:c},pointPositionPercents:r.isFixed()?r.calcPositionPercents():void 0,sharingMode:r.sharingMode().value()};(0,ke.copyLineTool)(u)}}isSnapshot(){return this._isSnapshot}onWidget(){return this._options.onWidget}hideIdeas(){return this._options.hideIdeas}updateSource(e){const t=this._invalidationMaskForSource(e);null!==t&&this.invalidate(t)}updateSourcePriceScale(e){const t=this._invalidationMaskForSourcePriceScale(e);null!==t&&this.invalidate(t)}updatePane(e){this.invalidate(this._paneInvalidationMask(e))}updateTimeScaleBaseIndex(e){const t=this.mainSeries().bars();t.isEmpty()||this._updateBaseIndex((0,n.ensureNotNull)(t.lastIndex()),!!(e&&e.index>0))}setInterval(e,t){const i=setInterval(e,t);return this._modelIntervals.push(i),i}clearInterval(e){clearInterval(e);const t=this._modelIntervals.indexOf(e);t>-1&&this._modelIntervals.splice(t,1)}clearIntervals(){for(let e=0;e{i.ownerSource()===e&&i.setOwnerSource(t)})),this._invalidateBarColorerCaches(),t.start(),this.recalculatePane(i,(0,G.sourceChangeEvent)(t.id())),this.fullUpdate(),!0}insertStudyStub(e,t){const i=void 0!==t,s=new x.StudyStub(this,null,e,i);let o;if(t||!i){o=this.mainPane();const e=o.createPriceScaleAtPosition("overlay");o.addDataSource(s,e,!1)}else o=this.createPane(),o.addDataSource(s,null,!1);return this.recalculatePane(o,(0,G.sourceChangeEvent)(s.id())),this.fullUpdate(),s}removeStudyStub(e){const t=this.dataSourceForId(e);return null===t?(js.logNormal("StudyStub id="+e+" is not found in chart model"),!1):(this.removeSource(t),!0)}allLineTools(){return this._getAllSources(C.isLineTool)}setHoveredSource(e,t=null){const i=this._hoveredSource!==e;if(!i&&(0,si.hitTestResultDataAreEqual)(this._lastHoveredHittestData,t))return;this._lastHoveredHittestData=t;let s=null;if(this._hoveredSource){this._hoveredSource.updateAllViews((0,G.selectionChangeEvent)()),s=new J.InvalidationMask(J.InvalidationLevel.Cursor);const e=this._invalidationMaskForSource(this._hoveredSource,J.InvalidationLevel.Light);null!==e&&s.merge(e)}if(this._hoveredSource=e,e){e.updateAllViews((0,G.selectionChangeEvent)()),s||(s=new J.InvalidationMask(J.InvalidationLevel.Cursor)) ;const t=this._invalidationMaskForSource(e,J.InvalidationLevel.Light);null!==t&&s.merge(t)}s&&this.invalidate(s),i&&this._hoveredSourceChanged.fire(e)}properties(){return this._properties}chartApi(){return this._chartApi}disconnect(){this.sessions().stop();for(const e of this.dataSources())e.disconnect&&e.disconnect();this._timeScale.disconnect()}crossHairSource(){return this.m_crossHairSource}gridSource(){return this._gridSource}publishedChartsTimelineSource(){for(const e of this._barsMarksSources)if(e instanceof Qt.PublishedChartsTimeline)return e;return null}hoveredSource(){return this._hoveredSource}hoveredSourceChanged(){return this._hoveredSourceChanged}lastHittestData(){return this._lastHoveredHittestData}lastSelectedHittestData(){return this._lastSelectedHittestData}lightUpdate(){this.invalidate(J.InvalidationMask.light())}fullUpdate(){this.invalidate(J.InvalidationMask.full())}syncTimeWithModel(e,t){const i=this.mainSeries().syncModel();if(null===i)return;const s=1e3*this.createSyncPoint(e,i.syncSourceTarget()).sourceTimeToTargetTime(t/1e3),o=(0,Bt.get_timezone)(this.timezone());let r=(0,Bt.utc_to_cal)(o,s);this.mainSeries().isDWM()&&(r=i.getSession().spec.correctTradingDay(r),(0,Bt.set_hms)(r,0,0,0,0,(0,Bt.get_timezone)("Etc/UTC"))),this._gotoTimeImpl(r.getTime(),{centerIfVisible:!1})}gotoTime(e){return this._gotoTimeImpl(e,{centerIfVisible:!0})}recalculatePane(e,t){null==e||e.recalculate(t)}recalculateAllPanes(e){this._panes.forEach((t=>t.recalculate(e))),this.updateAllPaneViews(e),this.crossHairSource().updateAllViews(e)}gotoTimeRange(e,t){const i=this.timeScale(),s=i.tickMarks(),o=this.mainSeries();if(void 0===s.minIndex)return void(this._lastGotoTimeRange={from:e,to:t});let r=e,a=t;const l=o.symbolInfo();if(null!==l){let i=this.properties().childs().timezone.value();"exchange"===i&&(i=l.timezone);const s=(0,Bt.get_timezone)(i),n=(0,Bt.utc_to_cal)(s,e),c=(0,Bt.utc_to_cal)(s,t);if(o.isDWM()){const e=(0,Bt.get_timezone)("Etc/UTC");(0,Bt.set_hms)(n,0,0,0,0,e),(0,Bt.set_hms)(c,0,0,0,0,e)}r=n.getTime(),a=c.getTime()}const c=(0,n.ensureDefined)(s.maxIndex),h=(0,n.ensureDefined)(s.minIndex);if(r>=(0,n.ensureNotNull)(s.indexToTime(h)).valueOf()||o.endOfData()){const e=(e,t)=>e(0,n.ensureNotNull)(s.indexToTime(e)).valueOf(),l=(0,b.lowerboundExt)(t,r,e,s.nearestIndex(r),c);let d=r===a?l:(0,b.lowerboundExt)(t,a,e,s.nearestIndex(a),c);this._lastGotoTimeRange=null,null!==this._lastAppliedGotoTimeRange&&(this._lastAppliedGotoTimeRange.actual=!1);const u=i.baseIndex();if(l+Math.max(d-l+1,i.minVisibleBarCount())>u){const e=i.targetDefaultRightOffset();d-u=0;t--)if(this._panes[t].hasDataSource(e))return this._panes[t];return e instanceof ni.BarsMarksContainer?this.paneForSource(this.mainSeries()):null}mainPane(){for(const e of this._panes)if(e.isMainPane())return e;throw new Error("Main pane is not found")}lastPane(){return this._panes[this._panes.length-1]}removeSource(e,t){this.selectionMacro((t=>t.removeSourceFromSelection(e)),!0),this._hoveredSource===e&&(this._hoveredSource=null,this._lastHoveredHittestData=null),this._sourcesBeingMoved.includes(e)&&(this._sourcesBeingMoved=this._sourcesBeingMoved.filter((t=>t!==e)),this._sourcesBeingMoved.length||(this._activeItemBeingMoved=null)),e===this._lineBeingEdited&&(this._lineBeingEdited=null,ke.isToolEditingNow.setValue(!1)),e===this._lineBeingCreated&&(this._lineBeingCreated=null,ke.isToolCreatingNow.setValue(!1)),!t&&e.stop&&e.stop();(0,n.ensureNotNull)(this.alertsWatcher()).removeSourceAlertLabels(e);const i=this.detachSource(e),s=this.mainSeries().priceScale();return(0,K.isStudy)(e)&&(0,Ce.isActingAsSymbolSource)(e)&&e.priceScale()===s&&s.isPercentage()&&1===s.seriesLikeSources().filter(Ce.isActingAsSymbolSource).length&&s.setMode({percentage:!1}),this.fullUpdate(),this._invalidateBarColorerCaches(),(0,K.isStudy)(e)&&((0,m.emit)("study_event",e.id(),"remove"),e.isChildStudy()&&e.parentSources().forEach((t=>t.unsetChild(e))),e.maxOffset().unsubscribe(this._boundUpdateStudiesMaxOffset)),!t&&e.destroy&&e.destroy(),(0,C.isLineTool)(e)&&(e.removeAlert(),(0,m.emit)("drawing_event",e.id(),"remove")),i}allStudies(e){const t=e?e=>(0,K.isStudy)(e)&&!(0,he.isLollipopDataSource)(e):K.isStudy;return this._getAllSources(t)}studiesWV(e){return e?this._studiesExcludeInternalWV.readonly():this._studiesWV.readonly()}listUserStudies(e){const t=[];for(const i of this._panes)for(const s of i.priceDataSources())if((0,K.isStudy)(s)&&!(0,K.isFundamentalStudy)(s)&&s.showInObjectTree()){const{id:i,shortDescription:o}=s.metaInfo();if(e.dontCountVolume&&"Volume@tv-basicstudies"===i||e.dontCountCompare&&"Compare@tv-basicstudies"===i||e.dontCountOverlay&&"Overlay@tv-basicstudies"===i)continue;t.push(o)}return t}findNonOverlayStudyWithGroupingKey(e,t){const i=void 0!==t?[t]:this._panes;for(const t of i){const i=t.dataSources().find((i=>(0,K.isStudy)(i)&&i.metaInfo().groupingKey===e&&!t.isOverlay(i)));if(void 0!==i)return{pane:t,study:i}}return null}movePaneUp(e){this.movePane(e,e-1)}movePaneDown(e){this.movePane(e,e+1)}movePane(e,t){const i=this._panes[e];this._panes.splice(e,1),this._panes.splice(t,0,i),this._panesCollectionChanged.fire(this._panes),this._onRearrangePanes.fire(),this.invalidate(J.InvalidationMask.panesOrder())}toggleCollapsedPane(e){const t=this._panes[e];t.collapsed().setValue(!t.collapsed().value()),this.fullUpdate()}backgroundColor(){ return this._backgroundColor}backgroundTopColor(){return this._backgroundTopColor}backgroundColorAtYPercentFromTop(e){const t=this.backgroundColor().value(),i=this.backgroundTopColor().value();if(t===i)return t;if(e=Math.max(0,Math.min(100,Math.round(100*e))),null===this._gradientColorsCache||this._gradientColorsCache.topColor!==i||this._gradientColorsCache.bottomColor!==t)this._gradientColorsCache={topColor:i,bottomColor:t,colors:new Map};else{const t=this._gradientColorsCache.colors.get(e);if(void 0!==t)return t}const s=(0,ri.gradientColorAtPercent)(i,t,e/100);return this._gradientColorsCache.colors.set(e,s),s}backgroundCounterColor(){return this._backgroundCounterColor.readonly()}dark(){return this._isDark}defaultResolutions(){return this.chartApi().defaultResolutions()}availableCurrencies(){const e=this._getAvailableCurrencies();return e.length!==this._availableCurrencies.size()&&(this._availableCurrencies=new ci(e)),this._availableCurrencies}currencyConversionEnabled(){return this._options.currencyConversionEnabled}availableUnits(){const e=this._getAvailableUnits();return this._availableUnits.unitsChanged(e)&&(this._availableUnits=new hi(e)),this._availableUnits}unitConversionEnabled(){return this._options.unitConversionEnabled}availablePriceSources(e){const t=this._getAvailablePriceSources(e);return null!==t&&this._availablePriceSources.priceSourcesChanged(t)&&(this._availablePriceSources=new Hs(t)),this._availablePriceSources}resetDeferredStudies(){Ge.instance(this).reset()}isJustClonedChart(){return this._undoModel.isJustClonedChart()}studyTemplate(e,t,i){const s={panes:[],version:this.version()};for(const e of this.panes())s.panes.push(e.state(!0,!1,!0));const o=this.mainSeries();return e&&(s.symbol=o.symbol(),this.currencyConversionEnabled()&&i&&(s.currency=o.currency()),this.unitConversionEnabled()&&i&&(s.unit=o.unit())),t&&(s.interval=o.interval()),s}getStudyById(e){const t=this.dataSourceForId(e);return null!==t&&(0,K.isStudy)(t)?t:null}getLineToolById(e){const t=this.dataSourceForId(e);return null!==t&&(0,C.isLineTool)(t)?t:null}restoreLineToolState(e,t,i){var s;e.restorePoints(t.points,t.indexes||[]),t.state.intervalsVisibilities=(0,je.mergeIntervalVisibilitiesDefaults)(t.state.intervalsVisibilities),e.properties().merge(t.state),e.restoreData&&e.restoreData(t),e.linkKey().setValue(t.linkKey||null),e.createServerPoints(),e.setZorder(null!==(s=t.zorder)&&void 0!==s?s:e.zorder()),this.fullUpdate();const o=e.linkKey().value();null!==o&&i&&(0,ke.restoreLineToolState)({model:this,linkKey:o,state:t})}restoreFactoryDefaults(e){e.restoreFactoryDefaults(),this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction)}preferences(){return(0,Bs.preferencesByWhiteList)(this,this.mainSeries())}restoreTheme(e,t,i){e.mainSourceProperties.hollowCandleStyle||(e.mainSourceProperties.hollowCandleStyle=e.mainSourceProperties.candleStyle),this._undoModel.chartLoadTheme(e,t,i)}onResetScales(){return this._resetScales}startMovingSources(e,t,i,s,o,r){this._sourcesBeingMoved=e, this._activeItemBeingMoved=i;let a=!1;if(this._sourcesBeingMoved.forEach((e=>{!a&&(0,K.isStudy)(e)&&(a=!0);const l=(0,n.ensureNotNull)(this.paneForSource(e)),c=(0,C.isLineTool)(e),h=c&&e.linkKey().value();if(!1!==h&&null!==h&&s.has(h)&&c&&e.isFixed()){const t=(0,n.ensureDefined)(s.get(h)),a={screen:this._percentPositionToPoint(t,l)};e.startMoving(a,i,o,r)}else e.startMoving(t,i,o,r);const d=this._paneInvalidationMask(l,J.InvalidationLevel.Light);this.invalidate(d)})),!r){const s=e.filter(C.isLineTool).filter((e=>e.linkKey().value()&&e.isSynchronizable())).map((e=>e.linkKey().value()));if(s.length&&t.logical){const r=this.externalTimeStamp(t.logical.index),a={linkKeys:s,model:this,symbol:this.mainSeries().symbol(),point:{price:t.logical.price,timeStamp:r},activeItem:null!==i?i:void 0,envState:o,pointPositionPercents:new Map};e.forEach((e=>{if((0,C.isLineTool)(e)){const i=e.linkKey().value();if(i&&e.isSynchronizable()&&e.isFixed()){const s=(0,n.ensureNotNull)(this.paneForSource(e));a.pointPositionPercents.set(i,this._pointToPercentPosition((0,n.ensureDefined)(t.screen),s))}}})),(0,ke.startMovingLineTool)(a)}}ke.isToolMovingNow.setValue(!0),a&&ke.isStudyEditingNow.setValue(!0)}moveSources(e,t,i,s){if(this._sourcesBeingMoved.filter((e=>!e.isLocked||!e.isLocked())).forEach((o=>{const r=(0,C.isLineTool)(o)?o.linkKey().value():null;if(null!==r&&t.has(r)){const e=(0,n.ensureNotNull)(this.paneForSource(o)),a=(0,n.ensureDefined)(t.get(r)),l={screen:this._percentPositionToPoint(a,e)};o.move(l,this._activeItemBeingMoved,i,s)}else o.move(e,this._activeItemBeingMoved,i,s)})),this.lightUpdate(),!s&&e.logical){const t=this._sourcesBeingMoved.filter(C.isLineTool).filter((e=>e.isSynchronizable()&&!!e.linkKey().value())).map((e=>e.linkKey().value())),s=this.externalTimeStamp(e.logical.index),o={linkKeys:t,model:this,point:{price:e.logical.price,timeStamp:s},envState:i,pointPositionPercents:new Map};this._sourcesBeingMoved.filter(C.isLineTool).forEach((t=>{if(t.linkKey().value()&&t.isSynchronizable()&&t.isFixed()){const i=(0,n.ensureNotNull)(this.paneForSource(t));o.pointPositionPercents.set(t.linkKey().value(),this._pointToPercentPosition((0,n.ensureDefined)(e.screen),i))}})),(0,ke.moveLineTool)(o)}}endMovingSources(e,t,i){const s=this._sourcesBeingMoved.map((s=>{const o=(0,n.ensureNotNull)(this.paneForSource(s)),r=s.endMoving(e,t,i),a=this._paneInvalidationMask(o,J.InvalidationLevel.Light);return a.invalidateAll(J.InvalidationLevel.Light),this.invalidate(a),r})),o=this._sourcesBeingMoved.filter(C.isLineTool).filter((e=>e.isSynchronizable()&&!!e.linkKey().value())).map((e=>e.linkKey().value())),r=this._sourcesBeingMoved.filter(C.isLineTool).filter((e=>e.isSynchronizable()&&!!e.linkKey)).map((e=>{const t={points:e.normalizedPoints(),interval:this.mainSeries().interval()};return e.isFixed()&&(t.pointPositionPercents=e.calcPositionPercents()),t}));o.length&&(0,ke.finishMovingLineTool)({linkKeys:o,model:this,finalStates:r,changes:s}),this._sourcesBeingMoved=[],this._activeItemBeingMoved=null,ke.isToolMovingNow.setValue(!1), ke.isStudyEditingNow.setValue(!1)}sourcesBeingMoved(){return this._sourcesBeingMoved}setMovingCustomSource(e,t){this._customSourceBeingMoved=e,this._customSourceBeingMovedHitTestData=null!==t?{beingMoved:!1,cancelled:!1,...t}:null}processingCustomSourceMove(){null!==this._customSourceBeingMovedHitTestData&&(this._customSourceBeingMovedHitTestData.beingMoved=!0)}customSourceMovingHitTestData(){return this._customSourceBeingMovedHitTestData}customSourceBeingMoved(){return null!==this._customSourceBeingMovedHitTestData&&this._customSourceBeingMovedHitTestData.beingMoved?this._customSourceBeingMoved:null}lineToolsSynchronizer(){return this._lineToolsSynchronizer}setLineToolsSynchronizer(e){this._lineToolsSynchronizer=e}width(){return this._width}setWidth(e,t){(this._panes.reduce(((t,i)=>i.setWidth(e)||t),!1)||this._width!==e)&&(this._width=e,this._timeScale.setWidth(e,t),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction))}setPaneHeight(e,t){e.setHeight(t),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.lightUpdate()}resetScalesAvailable(){return this._resetScalesAvailable.readonly()}panes(){return this._panes}paneForId(e){return this._panes.find((t=>t.id()===e))||null}createPane(e,t,i){const s=this._undoModel.chartWidget();s.isMaximizedPane()&&s.toggleMaximizePane(null);const o=this._properties.childs().paneProperties;t&&o.merge(t);const r=new it(this._timeScale,o,this,i);return void 0!==e?this._panes.splice(e,0,r):this._panes.push(r),r.onTagsChanged().subscribe(this,Qs.prototype.onPaneTagsChanged),r.dataSourcesCollectionChanged().subscribe(this,(()=>this._dataSourceCollectionChanged.fire(r))),r.symbolSourceCollectionChanged().subscribe(this,(()=>this._onSymbolSourceCollectionChanged(r))),r.priceSourcesCollectionChanged().subscribe(this,(()=>this._onPriceSourcesCollectionChanged(r))),r.sourcePropertiesChanged().subscribe(this,(e=>this._sourceProperitesChanged.fire(r,e))),r.sourceZOrderChanged().subscribe(this,(e=>this._sourceZOrderChanged.fire(r,e))),r.symbolSourceResolved().subscribe(this,(e=>this._symbolSourceResolved.fire(r,e))),r.symbolSourceResolvingActive().subscribe(this._recalcSymbolResolvingActive),r.collapsed().subscribe(this._recalcPaneCollapsingAvailable),r.resetPriceScalesAvailable().subscribe(this._updateResetScalesAvailableValue,{callWithLast:!0}),this._recalcPaneCollapsingAvailable(),this._panesCollectionChanged.fire(this._panes),this.invalidate(J.InvalidationMask.panesOrder()),r}removePane(e){const t=this._undoModel.chartWidget();t.isMaximizedPane()&&t.toggleMaximizePane(null);const i=e;i.destroy();const s=this._panes.indexOf(i);-1!==s&&(this._panes.splice(s,1),e.dataSourcesCollectionChanged().unsubscribeAll(this),e.symbolSourceCollectionChanged().unsubscribeAll(this),e.priceSourcesCollectionChanged().unsubscribeAll(this),e.sourcePropertiesChanged().unsubscribeAll(this),e.onTagsChanged().unsubscribeAll(this),e.symbolSourceResolved().unsubscribeAll(this), i.symbolSourceResolvingActive().unsubscribe(this._recalcSymbolResolvingActive),e.collapsed().unsubscribe(this._recalcPaneCollapsingAvailable),e.resetPriceScalesAvailable().unsubscribe(this._updateResetScalesAvailableValue),this._recalcPaneCollapsingAvailable(!0)),this._updateResetScalesAvailableValue();this.crossHairSource().pane===e&&this.clearCurrentPosition(),this._panesCollectionChanged.fire(this._panes),this.invalidate(J.InvalidationMask.panesOrder())}changePanesHeight(e,t){if(this._panes.length<2)return;(0,n.assert)(e>=0&&ee+t.stretchFactor()),0),o=this._panes.reduce(((e,t)=>e+t.height()),0),r=o-30*(this._panes.length-1);t=Math.min(r,Math.max(30,t));const a=s/o,l=i.height();i.setStretchFactor(t*a);let c=t-l,h=this._panes.length-1;for(const e of this._panes)if(e!==i){const t=Math.min(r,Math.max(30,e.height()-c/h));c-=e.height()-t,h-=1;const i=t*a;e.setStretchFactor(i)}this.fullUpdate()}clearCurrentPosition(){const e=this.crossHairSource();e.clearPosition(),(0,n.ensureNotNull)(e.dataWindowView()).update(),Ks(this._panes),this.invalidate(J.InvalidationMask.cursor());const t=this._undoModel.chartWidget();t.chartWidgetCollection().syncCrosshair(null,t.id()),this._phantomSourceContainer.onCursorPositionUpdated()}setAndSaveCurrentPosition(e,t,i,s){this.crossHairSource().saveOriginCoords(e,t),this.setCurrentPosition(e,t,i,s)}setCurrentPosition(e,t,i,s){var o,r,a,l,c,h;let d=NaN;const u=this._timeScale.coordinateToVisibleIndex(e),_=null!==(a=null===(r=null!==(o=this._lineBeingEdited)&&void 0!==o?o:this._lineBeingCreated)||void 0===r?void 0:r.priceScale())&&void 0!==a?a:i.defaultPriceScale();let p=null;!_.isEmpty()&&Number.isFinite(t)&&(p=(0,n.ensureNotNull)(i.mainDataSource()).firstValue(),null!==p&&(d=_.coordinateToPrice(t,p)));const m=this._crossHairSelectPointMode.value()!==ke.SelectPointMode.None,g=this.currentTool(),S=this.mainSeries(),v=this.crossHairSource(),f=v.index,b=v.price,y=m||ke.isStudyEditingNow.value(),C=_===this.m_mainSeries.priceScale()&&(this._lineBeingCreated||this._lineBeingEdited||(0,ve.isLineToolName)(g)||(0,ke.toolIsMeasure)(g)||y);!this._isSettingsExternalPosition&&C?(d=this._magnet.align(d,u,i),null!==p&&this._setCorrectedPositionToCrosshair(u,d,i)):this._magnet.resetLastValue();let w=null;if(isNaN(d)||(w=i),this._isTimeScrolling){if(!this._isSettingsExternalPosition&&m){const e=S.bars().firstIndex(),t=S.bars().lastIndex();if(null!==e&&null!==t){const s=Math.min(Math.max(u,e),t);s!==u&&this._setCorrectedPositionToCrosshair(s,d,i)}}else v.setPosition(v.index,d,w);return}v.setOnHoveredChartWidget(!0),v.setPosition(u,d,w),(0,n.ensureNotNull)(v.dataWindowView()).update(),Ks(this._panes);const P=S.syncModel();if(this.crossHairSource().startMeasurePoint()||this._lineBeingCreated?this.lightUpdate():this.invalidate(J.InvalidationMask.cursor()),this._lineBeingCreated){const e=this._lineBeingCreated.linkKey().value();if(!this._isSettingsExternalPosition){const t=this._lineBeingCreated.setLastPoint({index:u, price:d},s);if(this._lineBeingCreated.updateAllViews((0,G.sourceChangeEvent)(this._lineBeingCreated.id())),t.price===d&&t.index===u||this._setCorrectedPositionToCrosshair(t.index,t.price,i),P&&e){const i=this._timeScale.points().roughTime(t.index,P.projectTime.bind(P));(0,ke.setLineToolLastPoint)({model:this,linkKey:e,point:{timeStamp:(0,n.ensureNotNull)(i),price:t.price}})}}}if(!this._isSettingsExternalPosition&&null!==this._lineBeingEdited&&null!==this._linePointBeingEdited){const e={index:u,price:d};if(null===(l=this._linePointBeingChanged)||void 0===l?void 0:l.nonDiscreteIndex){const t=this.crossHairSource().originX();Number.isFinite(t)&&(e.index=this._timeScale.coordinateToFloatIndex(t))}this.changeLinePoint(e,s);const t=this._lineBeingEdited.alignCrossHairToAnchor(this._linePointBeingEdited)?this._lineBeingEdited.getPoint(this._linePointBeingEdited):e;null!==t&&this._setCorrectedPositionToCrosshair(t.index,t.price,i)}if(!this._isSettingsExternalPosition&&1===this._sourcesBeingMoved.length){const e=this._sourcesBeingMoved[0];if(null===(c=e.alignCrossHairToMovePoint)||void 0===c?void 0:c.call(e)){const t=null===(h=e.currentMovingPoint)||void 0===h?void 0:h.call(e);t&&t.logical&&this._setCorrectedPositionToCrosshair(t.logical.index,t.logical.price,i)}}if(!this._isSettingsExternalPosition&&y){const e=S.bars().firstIndex(),t=S.bars().lastIndex();if(null!==e&&null!==t){const s=Math.min(Math.max(u,e),t);s!==u&&this._setCorrectedPositionToCrosshair(s,d,i)}}(f!==u||b!==d)&&this._syncCrosshair(s)}setExternalPosition(e,t){let i;const s=this.crossHairSource();if(s.setOnHoveredChartWidget(!1),null!==e&&(0,ne.isNumber)(e.timeStamp)){const t=this.mainSeries().syncModel();if(t){const s=this.createSyncPoint(e.syncSourceTarget,t.syncSourceTarget()).sourceTimeToTargetTime(e.timeStamp);i=this._timeScale.points().roughIndex(s,t.distance.bind(t))}}if(null!==e&&null!=i&&Number.isFinite(i)){this._isSettingsExternalPosition=!0;const o=(0,n.ensureNotNull)(this.paneForSource(this.mainSeries())),r=this._timeScale.indexToCoordinate(i),a=(0,n.ensureNotNull)(o.mainDataSource()).firstValue();if(null!==a){let i=NaN;void 0!==e.price&&Number.isFinite(e.price)&&(i=this.mainSeries().priceScale().priceToCoordinate(e.price,a)),s.clearOriginCoords(),this.setCurrentPosition(r,i,o,t)}return s.setOnHoveredChartWidget(!1),void(this._isSettingsExternalPosition=!1)}s.clearPosition(),(0,n.ensureNotNull)(s.dataWindowView()).update(),Ks(this._panes),this.invalidate(J.InvalidationMask.cursor())}startScaleTime(e){this._timeScale.startScale(e)}scaleTimeTo(e){this._timeScale.scaleTo(e),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.lightUpdate()}endScaleTime(){this._timeScale.endScale(),this.lightUpdate(),this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction)}resetTimeScale(){this._timeScale.restoreDefault(),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction),this.lightUpdate(),this._resetScales.fire()} startScalePrice(e,t,i){e.startScalePrice(t,i)}scalePriceTo(e,t,i){e.scalePriceTo(t,i),this.mainSeries().priceScale().isLockScale()?this.lightUpdate():this.invalidate(this._paneInvalidationMask(e,J.InvalidationLevel.Light))}endScalePrice(e,t){e.endScalePrice(t),this.invalidate(this._paneInvalidationMask(e,J.InvalidationLevel.Light))}startTwoPointsScalePrice(e,t,i,s){t.startTwoPointsScale(i,s)}twoPointsScalePriceTo(e,t,i,s){t.twoPointsScale(i,s),this.invalidate(this._paneInvalidationMask(e))}endTwoPointsScalePrice(e,t){t.endTwoPointsScale(),this.invalidate(this._paneInvalidationMask(e))}resetPriceScale(e,t){e.resetPriceScale(t),this.invalidate(this._paneInvalidationMask(e,J.InvalidationLevel.Light))}restorePriceScaleState(e,t,i){e.restorePriceScaleState(t,i),this.invalidate(this._paneInvalidationMask(e,J.InvalidationLevel.Light))}currentTool(){return this._currentTool}setCurrentTool(e){this._currentTool!==e&&((0,ve.isLineToolName)(e)&&this.selectionMacro((e=>{e.clearSelection()})),this._currentTool=e,this._phantomSourceContainer.onToolChanged())}detachSource(e){const t=this.paneForSource(e);return!!t&&(t.removeDataSource(e),t.isEmpty()?(this._lineBeingCreated&&t===this._paneBeingCreatedLineOn&&this.cancelCreatingLine(),this.removePane(t),!0):(this.fullUpdate(),!1))}children(e,t){return this.dataSources().filter((i=>(0,K.isStudy)(i)&&!(0,he.isLollipopDataSource)(i)?!t&&i.parentSources().includes(e):i.ownerSource()===e))}onRearrangePanes(){return this._onRearrangePanes}finishLineTool(e){const t=e.linkKey().value();(0,ke.drawOnAllCharts)().value()&&null!==t&&e.isSynchronizable()&&(0,ke.finishLineTool)({linkKey:t,model:this})}startChangingLinetool(e,t,i,s,o){this._lineBeingEdited=e,this._linePointBeingChanged=t||null,this._linePointBeingEdited=void 0===i?null:i,this._lineBeingEdited.startChanging(i,t,o),ke.isToolEditingNow.setValue(!0);const r=(0,n.ensureNotNull)(this.paneForSource(e));this._lineBeingEdited.startDragPoint&&void 0!==i&&void 0!==t&&this._lineBeingEdited.startDragPoint(i,t),o||void 0===i||void 0===t||this._lineBeingEdited.setPoint(i,t,s,o),this._lineBeingEdited.updateAllViews((0,G.sourceChangeEvent)(this._lineBeingEdited.id()));const a=this._paneInvalidationMask(r,J.InvalidationLevel.Light);this.invalidate(a);const l=e.linkKey().value();if(l&&e.isSynchronizable()&&void 0!==i&&void 0!==t){const e=(0,n.ensureNotNull)(this.externalTimeStamp(t.index));(0,ke.startChangingLineTool)({linkKey:l,model:this,symbol:this.mainSeries().symbol(),point:{price:t.price,timeStamp:e},pointIndex:i,envState:s||null})}}createLineTool(e,t,i,s,o,r,l,c){if((0,n.assert)((0,ve.isLineToolName)(i),`Cannot create unknown line tool: ${i}`),s){const e={...Rs.intervalsVisibilitiesDefaults},t=s.childs().intervalsVisibilities.state();(0,ne.merge)(e,null!=t?t:{});const o=s.state();o.intervalsVisibilities=e,s=(0,C.createLineToolProperties)(i,o,this)}const h=(0,C.createLineTool)(i,this,s,null,void 0,c);if("LineToolExecution"!==i){let e;switch(i){case"LineToolIcon":e=h.properties().childs().icon.value().toString(16).toUpperCase();break ;case"LineToolEmoji":e=h.properties().childs().emoji.value();break;case"LineToolSticker":e=h.properties().childs().sticker.value()}(0,_.trackEvent)("drawings","Study_Drawing_"+i,e)}(0,C.isStudyLineTool)(h)&&(0,_.trackEvent)("studies",`Study_${h.metaInfo().id}`);const d=!h.linkKey().value()&&!o;l=(0,n.ensureDefined)(l||(0,n.ensureNotNull)(e.mainDataSource())),s||(0,C.prepareLineToolPropertiesByOwnerSource)(h.properties(),l),h.setOwnerSource(l);const u=l.priceScale();if(h.setPriceScale(u),qs&&l===this.mainSeries()&&h.share(r),e.addDataSource(h,u,!1),null!==h.preferredZOrder()&&e.insertAfter([h],this.mainSeries()),(0,ke.drawOnAllCharts)().value()){const e=h.isSynchronizable()?o||(0,ie.randomHash)():null;h.linkKey().setValue(e)}else h.linkKey().setValue(o);let p;if(h.isFixed()){const i=(0,n.ensureNotNull)((0,n.ensureNotNull)(e.mainDataSource()).firstValue()),s=this._timeScale.indexToCoordinate(t.index),o=(0,n.ensureNotNull)(u).priceToCoordinate(t.price,i);p=h.addFixedPoint(new a.Point(s,o))}else p=h.addPoint(t);return p||(this._lineBeingCreated=h,this._paneBeingCreatedLineOn=e,ke.isToolCreatingNow.setValue(!0)),d&&h.enableCurrentIntervalVisibility(),this.fullUpdate(),h}endChangingLinetool(e,t){const i=(0,n.ensureNotNull)(this._lineBeingEdited),s=i.endChanging(!1,e,t);this._lineBeingEdited=null,ke.isToolEditingNow.setValue(!1),this._linePointBeingEdited=null,this._linePointBeingChanged=null,this.lightUpdate();const o={points:i.normalizedPoints(),interval:this.mainSeries().interval()},r=i.linkKey().value();null!==r&&i.isSynchronizable()&&!t&&(0,ke.finishChangingLineTool)({model:this,linkKey:r,symbol:this.mainSeries().symbol(),finalState:o,changes:s})}continueCreatingLine(e,t,i,s){const o=(0,n.ensureNotNull)(this._lineBeingCreated),r=o.addPoint(e,t,i);o.updateAllViews((0,G.sourceChangeEvent)(o.id()));const a=new J.InvalidationMask(J.InvalidationLevel.Light);return r&&(this._paneBeingCreatedLineOn=null,this._lineBeingCreated=null,ke.isToolCreatingNow.setValue(!1)),this.invalidate(a),r}cancelCreatingLine(){if(!this._lineBeingCreated)return;const e=this._lineBeingCreated;this.removeSource(this._lineBeingCreated),this._lineBeingCreated=null,this._lineCancelled.fire(),ke.isToolCreatingNow.setValue(!1),(0,ke.drawOnAllCharts)().value()&&e.isSynchronizable()&&(0,ke.cancelLineTool)({model:this})}lineBeingCreated(){return this._lineBeingCreated}paneBeingCreatedLineOn(){return this._paneBeingCreatedLineOn}lineCancelled(){return this._lineCancelled}isPhantomLine(e){return this._phantomSourceContainer.source()===e}changeLinePoint(e,t,i){const s=(0,n.ensureNotNull)(this._lineBeingEdited),o=(0,n.ensureNotNull)(this._linePointBeingEdited);let r=e.price,a=e.index;if(s.setPoint(o,e,t,i),!i){const t=s.alignCrossHairToAnchor(o)?s.getPoint(o):e;null!==t&&(a=t.index,r=t.price)}s.updateAllViews((0,G.sourceChangeEvent)(s.id())),this.lightUpdate();const l=s.linkKey().value();if(!i&&null!==l&&s.isSynchronizable()){const e=(0,n.ensureNotNull)(this._linePointBeingChanged),i={indexesChanged:a!==e.index,pricesChanged:r!==e.price },c=s.getChangePointForSync(o);if(null!==c){const e=this.externalTimeStamp(a);null!==e&&(r=c.price,(0,ke.changeLineTool)({linkKey:l,model:this,symbol:this.mainSeries().symbol(),point:{price:r,timeStamp:e},envState:t,changes:i}))}}}changeLinePoints(e,t,i){const s=e.points(),o=e.linkKey().value();!i&&o&&e.isSynchronizable()&&t.forEach(((t,i)=>{const r=s[i],a=r.price!==t.price,l=r.index!==t.index;if(e.getChangePointForSync(i)){const e=(0,n.ensureNotNull)(this.externalTimeStamp(t.index));(0,ke.changeLineTool)({linkKey:o,model:this,symbol:this.mainSeries().symbol(),point:{price:t.price,timeStamp:e},changes:{pricesChanged:a,indexesChanged:l}})}})),e.setPoints(t),e.updateAllViews((0,G.sourceChangeEvent)(e.id())),this.lightUpdate()}startScrollTime(e){this._timeScale.startScroll(e),this._isTimeScrolling=!0,this.mainSeries().clearGotoDateResult()}scrollTimeTo(e){this._timeScale.scrollTo(e),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.lightUpdate()}endScrollTime(){this._timeScale.endScroll(),this.lightUpdate(),this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction),this._isTimeScrolling=!1}startScrollPrice(e,t,i){e.startScrollPrice(t,i)}scrollPriceTo(e,t,i){e.scrollPriceTo(t,i),this.invalidate(this._paneInvalidationMask(e,J.InvalidationLevel.Light))}endScrollPrice(e,t){e.endScrollPrice(t),this.invalidate(this._paneInvalidationMask(e,J.InvalidationLevel.Light))}addCustomSource(e,t,i=v.CustomSourceLayer.Foreground){this._customSourcesMap.has(e)&&js.logWarn(`Attempt to add the same custom source multiple time "${e}"`),js.logNormal(`Adding custom source "${e}"`);const s=t(e,this);switch(i){case v.CustomSourceLayer.Background:this._bgCustomSources.push(s);break;case v.CustomSourceLayer.Foreground:this._fgCustomSources.push(s);break;case v.CustomSourceLayer.Topmost:this._topmostCustomSources.push(s);break;default:throw new Error(`Unknown custom sources layer ${i}`)}this._allCustomSources.push(s),this._customSourcesMap.set(e,s),this.lightUpdate()}removeCustomSource(e){this._removeCustomSource(e),this.lightUpdate()}hasCustomSource(e){return this._customSourcesMap.has(e)}customSourceForName(e){return this._customSourcesMap.get(e)||null}customSourceName(e){let t=null;return this._customSourcesMap.forEach(((i,s)=>{i===e&&(t=s)})),t}customSources(e){switch(e){case v.CustomSourceLayer.Background:return this._bgCustomSources;case v.CustomSourceLayer.Foreground:return this._fgCustomSources;case v.CustomSourceLayer.Topmost:return this._topmostCustomSources;default:return this._allCustomSources}}addMultiPaneSource(e){this._multiPaneSources.push(e),this.lightUpdate()}removeMultiPaneSource(e){const t=this._multiPaneSources.indexOf(e);-1===t?js.logWarn("Attempt to remove multi-pane source which does not exist in the model"):this._multiPaneSources.splice(t,1),this.lightUpdate()}multiPaneSources(e){return this._multiPaneSources.filter((t=>!e.hasDataSource(t)))}magnet(){return this._magnet}dateTimeFormatter(){return this._dateTimeFormatter}dateFormatter(){return this._dateFormatter}timeFormatter(){ return this._timeFormatter}isUnmergeAvailableForSource(e){if(!this._unmergeAvailable(e))return!1;return(0,n.ensureNotNull)(this.paneForSource(e)).dataSources().filter(this._unmergeAvailable,this).length>1}isMergeDownAvailableForSource(e){if(!this._unmergeAvailable(e))return!1;const t=this.paneForSource(e),i=this.panes();return t!==i[i.length-1]}isMergeUpAvailableForSource(e){if(!this._unmergeAvailable(e))return!1;return this.paneForSource(e)!==this.panes()[0]}sessions(){return(0,n.ensureNotNull)(this._sessions)}createSessions(e){(0,n.assert)(null===this._sessions,"Sessions are already created"),this.addCustomSource("sessions",((t,i)=>(this._sessions=new Y(t,i,e),this._sessions.start(),this._sessions)),v.CustomSourceLayer.Background)}createPrePostMarket(e){this.addCustomSource("prePostMarket",((t,i)=>new Kt.PrePostMarket(t,i,e)))}watermarkContentProvider(){return null}replayStatus(){return this._replayStatus}setReplayStatus(e){this._replayStatus.setValue(e)}isInReplay(){return this.m_mainSeries.isInReplay()}getSymbolString(){return this.m_mainSeries.getSymbolString()}interval(){return this.m_mainSeries.interval()}switchToReplay(e,t){this.m_mainSeries.switchToReplay(e,t)}switchToRealtime(){this.m_mainSeries.switchToRealtime(),this._timeScale.resetRightOffset(),this.setReplayStatus(Nt.ReplayStatus.Undefined),this._scrollingState&&(this._scrollingState.deferred.reject(),this._scrollingState=null)}async canChangeResolution(e){return this.m_mainSeries.canChangeResolution(e)}theme(){const e=this.properties().childs().paneProperties.state(["horzGridProperties.style","vertGridProperties.style"]);delete e.topMargin,delete e.bottomMargin;const t=this.mainSeries().state().state;t&&(delete t.symbol,delete t.interval,delete t.currencyId,delete t.unitId);const i={mainSourceProperties:t,sessions:this.sessions().properties().state(),chartProperties:{paneProperties:e,scalesProperties:this.properties().childs().scalesProperties.state()},version:this.version()};return i.version=this.version(),i}onChartThemeLoaded(){return this._chartThemeLoaded}chartThemeLoaded(){this._chartThemeLoaded.fire()}async colorStudiesPropertiesReady(){this._recalcColorStudiesImpl(this._recalcVRStudiesParams);const e=this.allStudies(!0).filter((e=>e.metaInfo().inputs.filter(M.isStudyInputDependsOnChartColors).length>0));await Promise.all(e.map((e=>e.propertiesPatched())))}state(e,t,i,s){var o;const r=this.publishedChartsTimelineSource(),n=this.properties().childs(),a=n.tradingProperties.state(),l={panes:this._panes.map((o=>o.state(!0,e,!1,t,i,s))),timeScale:this._timeScale.state(e),chartProperties:{paneProperties:n.paneProperties.state(["horzGridProperties.style","vertGridProperties.style"]),scalesProperties:n.scalesProperties.state(),publishedChartsTimelineProperties:r?r.state(e):void 0,chartEventsSourceProperties:null===(o=n.chartEventsSourceProperties)||void 0===o?void 0:o.state(),tradingProperties:a,priceScaleSelectionStrategyName:n.priceScaleSelectionStrategyName.value()},sessions:this.sessions().state(e),version:this.version(),timezone:this.timezone(), shouldBeSavedEvenIfHidden:this._shouldBeSavedEvenIfHidden,linkingGroup:this._linkingGroupIndex.value()};return s||(l.lineToolsGroups=this.lineToolsGroupModel().state(t)),l}restoreState(e,t,s){var o;Ge.instance(this).reset();const r={};if(!e.panes)return void js.logDebug("ChartModel.restoreState: invalid state");if(!Array.isArray(e.panes))return void js.logDebug("ChartModel.restoreState: invalid state");if(e.panes.length<1)return void js.logDebug("ChartModel.restoreState: invalid state");for(const e of this._barsMarksSources)this.detachSource(e);if(this._shouldBeSavedEvenIfHidden=void 0===e.shouldBeSavedEvenIfHidden||e.shouldBeSavedEvenIfHidden,e.chartProperties&&!e.chartProperties.timezone&&(e.chartProperties.timezone=e.timezone),e.chartProperties){const i=(0,W.factoryDefaults)("chartproperties").scalesProperties;(0,ne.merge)(i,e.chartProperties.scalesProperties),!("showLastValue"in i)||"showSeriesLastValue"in i||"showStudyLastValue"in i||(i.showSeriesLastValueProperty=i.showLastValue,i.showStudyLastValueProperty=i.showLastValue),"showSeriesLastValue"in i&&(r.showSeriesLastValueProperty=!0),"showStudyLastValue"in i&&(r.showStudyLastValueProperty=!0),(!this.isSnapshot()&&!this.readOnly()&&"showCurrency"in i||"showUnit"in i)&&((0,Q.migrateShowCurrencyAndShowUnitProperties)(i.showCurrency,i.showUnit),delete i.showCurrency,delete i.showUnit);{const{paneProperties:t}=e.chartProperties;t.vertGridProperties=t.vertGridProperties||(0,ne.clone)(t.gridProperties),t.horzGridProperties=t.horzGridProperties||(0,ne.clone)(t.gridProperties),t.horzGridProperties.style=t.vertGridProperties.style=oi.LINESTYLE_SOLID,"backgroundType"in t||(t.backgroundType=ai.ColorType.Solid),"separatorColor"in t||(t.separatorColor=(0,u.getThemedColor)("color-chart-page-bg")),this._properties.childs().paneProperties.mergeAndFire(t)}this._properties.childs().scalesProperties.mergeAndFire(i),e.chartProperties.timezone&&this._properties.childs().timezone.setValue(e.chartProperties.timezone),e.chartProperties.chartEventsSourceProperties&&this._properties.hasChild("chartEventsSourceProperties")&&this._properties.childs().chartEventsSourceProperties.mergeAndFire(e.chartProperties.chartEventsSourceProperties),e.chartProperties.tradingProperties&&this._properties.hasChild("tradingProperties")&&(void 0===e.chartProperties.tradingProperties.horizontalAlignment&&(e.chartProperties.tradingProperties.horizontalAlignment=(n=e.chartProperties.tradingProperties.lineLength)<=40?v.TradedGroupHorizontalAlignment.Right:n>=60?v.TradedGroupHorizontalAlignment.Left:v.TradedGroupHorizontalAlignment.Center),this._properties.childs().tradingProperties.mergeAndFire(e.chartProperties.tradingProperties)),this._timeScale.restoreState(e.timeScale,t),this._updateDateTimeFormatter()}var n;if(e.timeScale&&this._timeScale.restoreState(e.timeScale,t),!this.readOnly()){const t=this._getExceedingChildStudies(e.panes);if(t.length){for(let i=e.panes.length-1;i>=0;--i){const s=e.panes[i];for(let e=s.sources.length-1;e>=0;--e){const i=s.sources[e];~t.indexOf(i)&&s.sources.splice(e,1)} s.sources.length||e.panes.splice(i,1)}{const e=window.user.pro_plan;setTimeout((()=>(0,Zt.createGoProDialog)({feature:"studyOnStudy",actions:e&&e===ei.ExpertPlans.PremiumExpert?[{text:h.t(null,void 0,i(875139)),action:ti.PredefinedAction.Close}]:void 0})),500)}}}const a=e.version||0,l=e.panes;let c="_seriesId";for(const e of l){const t=e.sources.find((e=>"MainSeries"===e.type));if(t){c=t.id;break}}this.panes()[0].restoreState({state:l[0],withData:t,version:a,seriesId:c,settingsMigration:r,contentOverrides:s,restoreSilently:true,reason:2});let d=1;for(let i=1;iS&&p%100==0?{lines_limit_exceeded:!0,line_tools_count:p}:(this.panes().forEach((e=>this._dataSourceCollectionChanged.fire(e))),this._lineToolsGroupModel.fireChangedAll(),this._linkingGroupIndex.setValue(null!==(o=e.linkingGroup)&&void 0!==o?o:null),{})}shouldBeSavedEvenIfHidden(){return this._shouldBeSavedEvenIfHidden}setShouldBeSavedEvenIfHidden(e){this._shouldBeSavedEvenIfHidden=e}externalTimeStamp(e){const t=this.mainSeries().syncModel();return this.timeScale().points().roughTime(e,t&&t.projectTime.bind(t))}syncLollipopSources(){var e;null===(e=this._lollipopSourcesWatcherLoader)||void 0===e||e.callFunction((()=>{null!==this._lollipopSourcesWatcher&&this._lollipopSourcesWatcher.syncSources()}))}restoreChartEvents(e){var t;null===(t=this._lollipopSourcesWatcherLoader)||void 0===t||t.callFunction((()=>{null!==this._lollipopSourcesWatcher&&this._options.chartEventsEnabled&&this._lollipopSourcesWatcher.restoreChartEvents(e)}))}recalcVisibleRangeStudies(e){var t;if(this._recalcVRStudiesParams.reasons.add(e), this.m_mainSeries.isStarted()&&this.m_mainSeries.isCompleted()){const i=(0,n.ensureDefined)(Xs.get(e)).adapter,s=Math.min(...Array.from(this._recalcVRStudiesParams.reasons).map((e=>(0,n.ensureDefined)(Xs.get(e)))).filter((e=>e.adapter===i)).map((e=>e.timeout)));(0,n.ensureDefined)(null===(t=this._recalcVisibleRangeStudiesImplDebouncedByAdapter.get(i))||void 0===t?void 0:t.get(s))()}else this._recalcVisibleRangeStudiesImpl(this._recalcVRStudiesParams)}recalcColorStudies(e){this._recalcColorStudiesParams.force=this._recalcColorStudiesParams.force||Boolean(e),this._recalcColorStudiesImplDebounced()}recalcStudyBasedLineTools(){this.dataSources().forEach((e=>{(0,C.isStudyLineTool)(e)&&e.recalcStudyIfNeeded()}))}alertsWatcher(){return this._alertsWatcher}showLegend(){return this._showLegendProperty}id(){return this._id}selectPointMode(){return this._crossHairSelectPointMode}cancelRequestSelectPoint(){this.m_crossHairSource.cancelRequestSelectPoint()}requestSelectPoint(e){return this.m_crossHairSource.requestSelectPoint(e)}onPointSelected(){return this.m_crossHairSource.onPointSelected()}recalculatePriceRangeOnce(){const e=this.mainSeries();for(const t of this._panes)for(const i of t.priceDataSources())i.symbolSource()===e&&i.disablePriceRangeReady()}invalidate(e){var t;null===(t=this._invalidateHandler)||void 0===t||t.call(this,e)}appliedTimeFrame(){return this._appliedTimeFrame.appliedTimeFrame()}barsMarksSources(){return this._barsMarksSources}createSyncPoint(e,t){return(0,Ns.getDefault2Lazy)(this._syncPointCache,e.uniqueId,t.uniqueId,(()=>new Ft(e,t)))}isAutoSaveEnabled(){return this._isAutoSaveEnabled}linkingGroupIndex(){return this._linkingGroupIndex}studyAwareDefaultRightOffset(){return this._timeScale.usePercentageRightOffset().value()?this._timeScale.percentsToBarIndexLength(this.studyAwareDefaultRightOffsetPercentage()):Math.max(this._timeScale.defaultRightOffset().value(),this._cachedStudiesMaxOffset)}studyAwareDefaultRightOffsetPercentage(){return this._timeScale.usePercentageRightOffset().value()?Math.max(this._timeScale.defaultRightOffsetPercentage().value(),this._timeScale.barIndexLengthToPercents(this._cachedStudiesMaxOffset)):this._timeScale.barIndexLengthToPercents(this.studyAwareDefaultRightOffset())}clearAllStudies(){this.dataSources().forEach((e=>{var t;return null===(t=e.clearData)||void 0===t?void 0:t.call(e)}))}setTimeScaleAnimation(e){const t=J.InvalidationMask.light();t.setTimeScaleAnimation(e),this.invalidate(t)}stopTimeScaleAnimation(){this._timeScale.endScroll();const e=J.InvalidationMask.light();e.stopTimeScaleAnimation(),this.invalidate(e)}lollipopSourcesOptions(){const e=this._options;return{chartEventsEnabled:!this._options.isSnapshot&&this._options.chartEventsEnabled,esdEnabled:e.esdEnabled,newsNotificationsEnabled:e.newsNotificationsEnabled,continuousContractSwitchesEnabled:e.continuousContractSwitchesEnabled,futuresContractExpirationEnabled:e.futuresContractExpirationEnabled,latestUpdatesEnabled:e.latestUpdatesEnabled}}_initAlertsList(){ return this._alertsListPromise||(this._alertsListPromise=(0,qt.getChartAlertsFacade)().then((e=>{this._alertsList=e.createCollection((()=>this.mainSeries().interval()),(()=>this.mainSeries().actualSymbol())),this._alertsList.alertAdded().subscribe(this,this._addAlertLabelToChart.bind(this)),this._alertsList.alertRemoved().subscribe(this,this._removeAlertLabelFromChart.bind(this)),this._alertsList.collectionReset().subscribe(this,(()=>{if(this._alertsList){const e=this._alertsList.alerts();this._removeAllAlertLabelsFromChart();for(let t=e.length-1;t>=0;t--)this._addAlertLabelToChart(e[t])}})),this._alertsList.alertChanged().subscribe(this,(e=>{this._removeAlertLabelFromChart(e),this._addAlertLabelToChart(e)})),this._alertsList.sync();const t=e=>{this.mainSeries().dataEvents().symbolResolved()[e](this,i),this.mainSeries().dataEvents().symbolError()[e](this,this._removeAllAlertLabelsFromChart),this.mainSeries().properties().childs().interval[e](this,i)},i=()=>{var t;(null===(t=this._alertsList)||void 0===t?void 0:t.isFacade())?this._alertsList.sync():e.ensureFullAlertsList({success:()=>{var e;return null===(e=this._alertsList)||void 0===e?void 0:e.sync()},error:()=>{var e;return null===(e=this._alertsList)||void 0===e?void 0:e.reset()}})};return window.loginStateChange.subscribe(this,(()=>{t(window.is_authenticated?"subscribe":"unsubscribe")})),window.is_authenticated&&(t("subscribe"),this._alertsList.isFacade()||i()),this._alertsList}))),this._alertsListPromise}_updateStudiesMaxOffset(){const e=Math.max(...this.allStudies().map((e=>e.maxOffset().value())));this._cachedStudiesMaxOffset=e;const t=this._timeScale.rightOffset();if(t<0)return;if(e<=t)return;const i=this._timeScale.logicalRange();i?this._timeScale.zoomToBarsRange(i.left(),this._timeScale.baseIndex()+Math.max(this._timeScale.rightOffset(),e)):this._timeScale.setRightOffset(Math.max(t,e))}_updateBaseIndex(e,t){const i=this._timeScale,s=i.baseIndex(),o=i.logicalRange();if(null!==o&&t){const t=o.contains(s),r=e-s,n=t?null:i.rightOffset()-r;if(!this._options.shiftVisibleRangeOnNewBar&&t){const e=i.width()/i.barSpacing(),t=e/(e+r),s=Math.max(i.minBarSpacing(),i.barSpacing()*t);i.setBarSpacing(s)}null!==n&&i.setRightOffset(n)}i.setBaseIndex(e)}async _createLollipopSourcesWatcher(){{const e=this.lollipopSourcesOptions(),t=[e.esdEnabled,e.continuousContractSwitchesEnabled,e.futuresContractExpirationEnabled,e.latestUpdatesEnabled.minds,e.latestUpdatesEnabled.news,e.chartEventsEnabled],s=(0,Ht.onWidget)(),o=this.isSnapshot();(t.some(Boolean)||!s||o)&&(this._lollipopSourcesWatcherLoader=new S.AsyncResourceWrapper(i.e(71745).then(i.bind(i,163662))),this._lollipopSourcesWatcherLoader.callFunction((e=>{this._lollipopSourcesWatcher=new e.LollipopSourcesWatcher(this)})))}}_updateDateTimeFormatter(){const e=kt.dateFormatProperty.value(),t=this.onWidget()?void 0:Jt.withWeekdayProperty.value();if(this._dateFormatter=new Lt.DateFormatter(e,t),this.mainSeries().isDWM())this._dateTimeFormatter=new Lt.DateFormatter(e,t),this._timeFormatter=new ft.TimeFormatter((0, bt.getHourMinuteFormat)(vt.timeHoursFormatProperty.value()));else{const i=A.Interval.parse(this.mainSeries().interval()),s=(0,bt.getTimeFormatForInterval)(i,vt.timeHoursFormatProperty.value());this._dateTimeFormatter=new At.DateTimeFormatter({dateFormat:e,withWeekday:t,timeFormat:s,dateTimeSeparator:" "}),this._timeFormatter=new ft.TimeFormatter(s)}}_invalidationMaskForSource(e,t=J.InvalidationLevel.Light){if(e===this.crossHairSource())return J.InvalidationMask.cursor();if(this._watermarkSource===e)return this._paneInvalidationMask((0,n.ensureNotNull)(this.paneForSource(this.mainSeries())),t);if(-1!==this._allCustomSources.indexOf(e)){const e=new J.InvalidationMask;return e.invalidateAll(t),e}if(!(0,f.isDataSource)(e))return null;if(e.isMultiPaneEnabled())return new J.InvalidationMask(t);const i=this.paneForSource(e);return null!==i?this._paneInvalidationMask(i,t):null}_paneInvalidationMask(e,t=J.InvalidationLevel.Light){const i=new J.InvalidationMask,s=this._panes.indexOf(e);return i.invalidateAllPane(s,t),i}_invalidationMaskForSourcePriceScale(e,t=J.InvalidationLevel.Light){if(!(0,f.isDataSource)(e))return new J.InvalidationMask(t);const i=this.paneForSource(e);if(null===i)return null;let s=e.priceScale();if(null===s)return null;const o=this._panes.indexOf(i);let r=i.priceScalePosition(s);if("overlay"===r){const e=this._panes[o].defaultPriceScale();s=e,r=i.priceScalePosition(e)}const n=i.priceScaleIndex(s,r);if(void 0===n)return null;const a=new J.InvalidationMask;return a.invalidatePriceScale(o,r,n,t),a}_removeCustomSource(e){const t=this._customSourcesMap.get(e);if(void 0===t)return void js.logWarn(`Attempt to remove custom source which does not exist in the model - "${e}"`);js.logNormal(`Removing custom source "${e}"`),this.selectionMacro((e=>{e.removeSourceFromSelection(t)})),this._hoveredSource===t&&this.setHoveredSource(null),this._customSourceBeingMoved===t&&this.setMovingCustomSource(null,null);const i=Ys(this._bgCustomSources,t),s=Ys(this._fgCustomSources,t),o=Ys(this._topmostCustomSources,t),r=Ys(this._allCustomSources,t);(0,n.assert)(i||s||o,"Source should be presented in one of the layers"),(0,n.assert)(r,"Source should be presented in the array"),this._customSourcesMap.delete(e),t.destroy()}_updateShowLegendProperty(){const e=this._properties.childs().paneProperties.childs().legendProperties.childs().showLegend,t=this._showLegendProperty;if(e.value())t.setValue(!0);else{for(const e of this._panes){let i=0;for(const s of e.priceDataSources())if(null!==s.statusView()&&(i++,i>=2))return void t.setValue(!1)}t.setValue(!0)}}_pointToPercentPosition(e,t){return{x:e.x/this._timeScale.width(),y:e.y/(0,n.ensureNotNull)((0,n.ensureNotNull)(t.mainDataSource()).priceScale()).height()}}_percentPositionToPoint(e,t){const i=e.x*this._timeScale.width(),s=e.y*(0,n.ensureNotNull)((0,n.ensureNotNull)(t.mainDataSource()).priceScale()).height();return new a.Point(i,s)}_recalcVisibleRangeStudiesImpl(e){var t,i ;if(!this.m_mainSeries.isStarted()||!this.m_mainSeries.isCompleted())return void this._visibleRangeStudiesInputs.setValue(null);if(this.timeScale().isEmpty())return;const s=this.timeScale().visibleBarsStrictRange();if(null===s)return;const o=this.m_mainSeries.bars(),r=o.search(s.firstBar(),yt.PlotRowSearchMode.NearestRight),n=o.search(s.lastBar(),yt.PlotRowSearchMode.NearestLeft),a=o.lastIndex(),l=r?r.index:void 0,c=n?n.index:void 0,h=l===e.oldStartVisibleIndex,d=c===e.oldEndVisibleIndex,u=[v.RecalcVisibleRangeStudiesReason.SeriesRestart,v.RecalcVisibleRangeStudiesReason.SeriesCompleted,v.RecalcVisibleRangeStudiesReason.StudyCreation].some((t=>e.reasons.has(t)));h&&d&&!u||(e.reasons.clear(),e.oldStartVisibleIndex=void 0!==l?l:NaN,e.oldEndVisibleIndex=void 0!==c?c:NaN,this._visibleRangeStudiesInputs.setValue({firstVisibleBarTime:1e3*(null!==(t=null==r?void 0:r.value[0])&&void 0!==t?t:0),lastVisibleBarTime:1e3*(null!==(i=null==n?void 0:n.value[0])&&void 0!==i?i:0),subscribeRealtime:(null==n?void 0:n.index)===a}))}_recalcColorStudiesImpl(e){var t;const i=this.backgroundColorAtYPercentFromTop(.5),s=this.dark().value()?c.colorsPalette["color-cold-gray-200"]:c.colorsPalette["color-cold-gray-900"],o=i===e.oldBgColor,r=s===e.oldFgColor;if(o&&r&&!e.force)return;e.force=!1,e.oldBgColor=i,e.oldFgColor=s;const n=null!==(t=e.studies)&&void 0!==t?t:this.priceDataSources();e.studies=void 0;for(const e of n)if((0,K.isStudy)(e)){const t=e.metaInfo().inputs.filter(M.isStudyInputDependsOnChartColors),o=e.properties().childs().inputs;t.forEach((e=>{const t=e.id===M.ChartColorDependentStudyInputNames.FgColor?s:i;o.childs()[e.id].setValueSilently(t)})),t.length>0&&o.listeners().fire(o,"")}}_getAllSources(e){const t=[];for(const i of this._panes){const s=i.sourcesByGroup().all();for(const i of s)e(i)&&t.push(i)}return t}_invalidateBarColorerCaches(){this.mainSeries().invalidateBarColorerCache()}_addAlertLabelToChart(e){{const t=e.seriesId();if(null===t)return;(0,n.ensureNotNull)(this.alertsWatcher()).addAlert(e,t)}}_removeAlertLabelFromChart(e){(0,n.ensureNotNull)(this.alertsWatcher()).removeAlert(e)}_removeAllAlertLabelsFromChart(){(0,n.ensureNotNull)(this.alertsWatcher()).removeAllAlertLabels()}_updateTimeScale(e){var t,i,s,o;const{index:r,zoffset:n,values:a,indexDiffs:l,baseIndex:c,marks:h,clearFlag:d}=e;if(d){this._timeScale.reset();for(const e of this.dataSources())null===(t=e.clearData)||void 0===t||t.call(e)}if(l.length>0)for(const e of this.dataSources())null===(i=e.moveData)||void 0===i||i.call(e,l);const u=this._timeScale.indexToTimePoint(this._timeScale.baseIndex()),_=this._timeScale.canNormalize();this._timeScale.update(r,n,a,h);const p=this._timeScale.points().range().value();let m="ChartModel.prototype._updateTimeScale("+r+","+n+","+a.length+","+l.length+","+h.length+","+d+")";if(m+="TimeScale: {first:"+(null!==(s=null==p?void 0:p.firstIndex)&&void 0!==s?s:null)+",last:"+(null!==(o=null==p?void 0:p.lastIndex)&&void 0!==o?o:null)+"}",null===c){this._timeScale.resetBaseIndex();const e=this._timeScale.rightOffset() ;this._timeScale.setRightOffset(Math.max(e,this._cachedStudiesMaxOffset))}else if(void 0!==c){const e=this._timeScale.indexToTimePoint(c),t=null!==u&&null!==e&&e>u;this._updateBaseIndex(c,t)}if(js.logDebug(m),!_&&_!==this._timeScale.canNormalize())for(const e of this.dataSources())!(0,C.isLineTool)(e)||e.isFixed()||e.isSourceHidden()||e.processHibernate();for(const e of this.dataSources())e.updateAllViews({type:"data-source-change",sourceId:e.id(),clearData:!0});this.recalculateAllPanes((0,G.globalChangeEvent)()),this.lightUpdate()}_getAvailableCurrencies(){return!this.currencyConversionEnabled()||this.isSnapshot()?[]:(0,ne.isArray)(this._availableCurrenciesList)?this._availableCurrenciesList:(null!==this._availableCurrenciesList||(this._availableCurrenciesList=this.chartApi().availableCurrencies(),this._availableCurrenciesList.then((e=>{this._destroyed||(this._availableCurrenciesList=e,this.fullUpdate())})).catch((e=>{js.logWarn(`An error occurred while getting currencies config: ${e}`)}))),[])}_getAvailableUnits(){return!this.unitConversionEnabled()||this.isSnapshot()?{}:this._availableUnitsObject instanceof Promise||null===this._availableUnitsObject?(null!==this._availableUnitsObject||(this._availableUnitsObject=this.chartApi().availableUnits(),this._availableUnitsObject.then((e=>{this._destroyed||(this._availableUnitsObject=e,this.fullUpdate())})).catch((e=>{js.logWarn(`An error occurred while getting units config: ${e}`)}))),{}):this._availableUnitsObject}_getAvailablePriceSources(e){const t=this._availablePriceSourcesBySymbol.get(e);if(Array.isArray(t))return t;if((0,ne.isPromise)(t))return[];const i=this.chartApi().availablePriceSources(e);return this._availablePriceSourcesBySymbol.set(e,i),i.then((t=>{this._destroyed||(this._availablePriceSourcesBySymbol.set(e,t),this.fullUpdate())})).catch((e=>{js.logWarn(`An error occurred while getting price sources config: ${e}`)})),[]}_clearAvailablePriceSources(){this._availablePriceSourcesBySymbol.clear()}_getBackgroundColor(e){const t=this._properties.childs().paneProperties.childs();if(t.backgroundType.value()===ai.ColorType.Gradient){const i=t.backgroundGradientStartColor.value(),s=t.backgroundGradientEndColor.value();return function(e,t,i){if((0,u.getCurrentTheme)().name===Ut.StdTheme.Dark&&(0,zt.isOnMobileAppPage)("any")&&(0,u.isStdThemedDefaultValue)("chartProperties.paneProperties.backgroundGradientStartColor",e,Ut.StdTheme.Dark)&&(0,u.isStdThemedDefaultValue)("chartProperties.paneProperties.backgroundGradientEndColor",t,Ut.StdTheme.Dark))return Gt;return i?e:t}(i,s,Boolean(e))}const i=t.background.value();return function(e){if((0,u.getCurrentTheme)().name===Ut.StdTheme.Dark&&(0,zt.isOnMobileAppPage)("any")&&(0,u.isStdThemedDefaultValue)("chartProperties.paneProperties.background",e,Ut.StdTheme.Dark))return Gt;return e}(i)}_getBackgroundCounterColor(){const e=this.backgroundColor().value();return"black"===(0,l.rgbToBlackWhiteString)((0,l.parseRgb)(e),150)?"white":"black"}_updateBackgroundColor(){this._backgroundColor.setValue(this._getBackgroundColor()), this._backgroundTopColor.setValue(this._getBackgroundColor(!0))}_syncCrosshair(e){if(!this._isSettingsExternalPosition){const t=this._undoModel.chartWidget(),i=this._undoModel.mainSeries(),s=i.syncModel(),o=this._undoModel.crossHairSource(),r=o.pane;if(null!==s&&null!==r){const n={timeStamp:this._timeScale.points().roughTime(o.index,s.projectTime.bind(s)),syncSourceTarget:s.syncSourceTarget()};r.mainDataSource()===i&&(n.price=o.price,n.symbol=i.symbol());let a=this._lineBeingCreated||null!==this._linePointBeingEdited||Boolean(this._sourcesBeingMoved.length);a=a&&(0,ke.drawOnAllCharts)().value(),t.chartWidgetCollection().syncCrosshair(n,t.id(),a,e)}this._phantomSourceContainer.onCursorPositionUpdated()}}_gotoTimeImpl(e,t){const i=this.timeScale(),s=this.mainSeries();let o;if(void 0!==e){if(this._scrollingState&&this._scrollingState.deferred.reject(),o=(0,p.createDeferredPromise)(),o.promise.catch((()=>{})),!s.isDWM()){const t=s.symbolInfo();if(null!==t){let i=this.properties().childs().timezone.value();"exchange"===i&&(i=t.timezone);const o=(0,Bt.cal_to_utc)((0,Bt.get_timezone)(i),new Date(e)),r=(0,Si.createTimeToBarTimeAligner)(s.interval(),t)(o);e=(0,Bt.utc_to_cal)((0,Bt.get_timezone)(i),r).getTime()}}this._scrollingState={targetDate:e,deferred:o,centerIfVisible:t.centerIfVisible}}else{if(!this._scrollingState)return js.logError("scrollTo called without an argument"),Promise.reject();e=this._scrollingState.targetDate,o=this._scrollingState.deferred}if(void 0===i.tickMarks().minIndex)return o.resolve(void 0),o.promise;this.stopTimeScaleAnimation();let r=((e,t)=>{if((e=>(0,n.ensureNotNull)(i.tickMarks().indexToTime((0,n.ensureDefined)(i.tickMarks().minIndex))).valueOf()-e)(t)<0){let o=i.tickMarks().nearestIndex(t);const r=s.bars().lastIndex();if(null===r)return null;o=Math.min(o,r);let a=(0,n.ensureNotNull)(i.tickMarks().indexToTime(o)).valueOf();for(;ar&&n.push(e)),l=(l+1)%s.length}return n}}},208697:(e,t,i)=>{"use strict";i.d(t,{ChartUndoModelBase:()=>zs});var s=i(685459),o=i.n(s),r=i(316230),n=i(650151),a=i(86441),l=i(444372),c=i(81979),h=(i(397150),i(526075)),d=i(315347),u=i(223699);function _(e,t){return!!u.Interval.isEqual(e.res,t.res)&&(0,d.areEqualTimeFrames)(e.val,t.val)}var p=i(13294),m=i(794389),g=i(356893),S=i(713473),v=i(764005),f=i(345848),b=i(677305),y=i(244842),C=i(201089),w=i(427937),P=i(142257),T=i(809796);const M=new T.TranslatedString("toggle collapsed pane state",l.t(null,void 0,i(74724)));class x extends P.UndoCommand{constructor(e,t){super(M),this._chartModel=e,this._paneIndex=t}redo(){this._chartModel.toggleCollapsedPane(this._paneIndex)}undo(){this._chartModel.toggleCollapsedPane(this._paneIndex)}}var I=i(125226),A=i(638456),L=i(703089),k=i(634447),E=i(389137);const D=new T.TranslatedString("move all scales to left",l.t(null,void 0,i(581898))),N=new T.TranslatedString("move all scales to right",l.t(null,void 0,i(622863))),B=(0,C.getLogger)("Chart.MergeAllScales");class R extends P.UndoCommand{constructor(e,t,i,s,o,r){super(r),this._model=e,this._paneIndex=e.panes().indexOf(t),this._targetPosition=s,this._targetIndex=o,this._scaleId=i.id(),this._sourcePosition=t.priceScalePosition(i),"overlay"!==this._sourcePosition&&(this._sourceIndex=t.priceScaleIndex(i,this._sourcePosition))}redo(){const e=this._model.panes()[this._paneIndex],t=(0,n.ensureNotNull)(e.getPriceScaleById(this._scaleId));e.movePriceScale(t,this._targetPosition,this._targetIndex),this._model.fullUpdate()}undo(){const e=this._model.panes()[this._paneIndex],t=(0,n.ensureNotNull)(e.getPriceScaleById(this._scaleId));e.movePriceScale(t,this._sourcePosition,this._sourceIndex),this._model.fullUpdate()}}class O extends P.UndoCommand{constructor(e,t,i,s){super(s),this._createdIds=[],this._model=e,this._withoutShift=i,this._origStates=t.map((e=>e.state(!0)));const o=e.lineToolsGroupModel();this._origGroups=t.map((e=>{const t=o.groupForLineTool(e);return t&&t.id}))}redo(){const e=this._model.lineToolsGroupModel(),t=this._origStates.map(((t,i)=>{const s=(0, n.ensureNotNull)(this._model.dataSourceForId(t.id)),o=0===this._createdIds.length?void 0:(0,n.ensureDefined)(this._createdIds[i]),r=(0,S.cloneLineTool)(this._model,s,!this._withoutShift,o);void 0!==t.sharingMode&&r.share(t.sharingMode);const a=(0,n.ensureNotNull)(s.priceScale());(0,n.ensureNotNull)(this._model.paneForSource(s)).addDataSource(r,a,!1);const l=this._origGroups[i];if(null!==l){const t=e.groupForId(l);t&&t.addLineTools([r])}return this._model.updateSource(r),r}));0===this._createdIds.length&&(this._createdIds=t.map((e=>e.id()))),this._model.selectionMacro((e=>{e.clearSelection(),t.forEach((t=>{e.addSourceToSelection(t)}))})),this._model.setShouldBeSavedEvenIfHidden(!0)}undo(){const e=this._model.lineToolsGroupModel();this._createdIds.forEach((t=>{const i=(0,n.ensureNotNull)(this._model.dataSourceForId(t)),s=e.groupForLineTool(i);null!==s&&s.excludeLineTool(i),this._model.removeSource(i)}))}newIds(){return this._createdIds}}var V=i(558105),W=i(731327);class F extends P.UndoCommand{constructor(e,t,i,s=!0){super(i,s),this._newStates=[],this._model=e,this._savedStates=t.map((e=>e.state(!1)))}redo(){this._applyState(this._newStates)}undo(){0===this._newStates.length&&this.saveNewState(),this._applyState(this._savedStates)}saveNewState(){const e=this._savedStates.filter(E.notNull).map((e=>(0,n.ensureNotNull)(this._model.dataSourceForId(e.id))));this._newStates=e.map((e=>e.state(!1)))}_applyState(e){for(const t of e)if(null!==t){const e=this._model.dataSourceForId(t.id);if(null!==e)if((0,w.isStudy)(e)){const i=t.state.inputs,s=e.properties().childs().inputs.childs();for(const e in i)s[e]&&s[e].setValue(i[e])}else this._model.restoreLineToolState(e,t,!0)}}}class H extends P.UndoCommand{constructor(e,t,i){super(i),this._chartModel=e,this._sourceId=t.id();const s=(0,n.ensureNotNull)(t.priceScale());this._initialPriceScaleId=s.id(),this._initialPriceScaleState=(0,n.ensureNotNull)(t.priceScale()).state();const o=(0,n.ensureNotNull)(e.paneForSource(t));this._initialPriceScalePosition=o.priceScalePosition(s),this._initialPriceScaleIndex=o.priceScaleIndex(s,this._initialPriceScalePosition),this._initialPaneIndex=e.panes().indexOf(o)}_newPriceScaleState(e){const t={...this._initialPriceScaleState};return delete t.m_isLockScale,delete t.id,delete t.m_topMargin,delete t.m_bottomMargin,t}_originalPriceScaleState(){return this._initialPriceScaleState}}class z extends H{constructor(e,t,i){super(e,t,i)}redo(){const e=(0,n.ensureNotNull)(this._chartModel.dataSourceForId(this._sourceId)),t=(0,n.ensureNotNull)(this._chartModel.paneForSource(e)),i=this._chartModel.children(e,!0);t.bulkActionMacro((()=>{i.forEach((e=>this._chartModel.detachSource(e))),this._chartModel.detachSource(e)}));const s=this._chartModel.createPane(this.targetPaneIndex()),o=s.findSuitableScale(e);s.bulkActionMacro((()=>{s.addDataSource(e,o,!1),i.forEach((e=>s.addDataSource(e,o,!1)))}));const r=(0,n.ensureNotNull)(e.priceScale());r.restoreState(this._newPriceScaleState(s.isOverlay(e))),r.setHeight(s.height()),this._chartModel.fullUpdate(), this._chartModel.setShouldBeSavedEvenIfHidden(!0)}undo(){const e=(0,n.ensureNotNull)(this._chartModel.dataSourceForId(this._sourceId)),t=(0,n.ensureNotNull)(this._chartModel.paneForSource(e)),i=this._chartModel.children(e,!0);t.bulkActionMacro((()=>{i.forEach((e=>this._chartModel.detachSource(e)));const t=this._chartModel.detachSource(e);(0,n.assert)(t,"Undo of detaching must remove pane")}));const s=this._chartModel.panes()[this._initialPaneIndex];let o=s.getPriceScaleById(this._initialPriceScaleId);null===o&&(o=s.createPriceScaleAtPosition(this._initialPriceScalePosition,this._initialPriceScaleIndex)),s.bulkActionMacro((()=>{s.addDataSource(e,o,!0),i.forEach((e=>s.addDataSource(e,o,!1)))}));const r=(0,n.ensureNotNull)(e.priceScale());r.restoreState(this._originalPriceScaleState()),r.setHeight(s.height()),this._chartModel.fullUpdate()}}class U extends z{constructor(e,t,i){super(e,t,i)}targetPaneIndex(){return this._initialPaneIndex+1}}class G extends z{constructor(e,t,i){super(e,t,i)}targetPaneIndex(){return this._initialPaneIndex}}class q extends z{constructor(e,t,i){super(e,t,i)}targetPaneIndex(){return this._chartModel.panes().length}}class j extends H{constructor(e,t,i,s){super(e,t,i),this._restorePane=!1,this._keepZOrder=null!=s&&s,this._initialZOrder=t.zorder()}redo(){const e=this._chartModel.panes().length,t=this._chartModel.panes()[this._targetPaneIndex()],i=(0,n.ensureNotNull)(this._chartModel.dataSourceForId(this._sourceId)),s=(0,n.ensureNotNull)(this._chartModel.paneForSource(i)),o=this._chartModel.children(i,!0);s.bulkActionMacro((()=>{o.forEach((e=>this._chartModel.detachSource(e))),this._restorePane=this._chartModel.detachSource(i)}));const r="overlay"===this._initialPriceScalePosition?this._initialPriceScalePosition:void 0,a=t.findSuitableScale(i,void 0,r),l=0===a.dataSources().length;if(t.bulkActionMacro((()=>{t.addDataSource(i,a,this._keepZOrder),o.forEach((e=>t.addDataSource(e,a,this._keepZOrder)))})),i===this._chartModel.mainSeries()){const e=t.priceScalePosition(a);t.movePriceScale(a,e,0)}if(l){const e=(0,n.ensureNotNull)(i.priceScale());e.restoreState(this._newPriceScaleState(t.isOverlay(i))),e.setHeight(t.height())}this._chartModel.fullUpdate(),e!==this._chartModel.panes().length&&this._chartModel.setShouldBeSavedEvenIfHidden(!0)}undo(){let e;e=this._restorePane?this._chartModel.createPane(this._initialPaneIndex):this._chartModel.panes()[this._initialPaneIndex];const t=(0,n.ensureNotNull)(this._chartModel.dataSourceForId(this._sourceId)),i=(0,n.ensureNotNull)(this._chartModel.paneForSource(t)),s=this._chartModel.children(t,!0);i.bulkActionMacro((()=>{s.forEach((e=>this._chartModel.detachSource(e))),this._chartModel.detachSource(t)}));let o=e.getPriceScaleById(this._initialPriceScaleId);null===o&&(o=e.createPriceScaleAtPosition(this._initialPriceScalePosition,this._initialPriceScaleIndex)),e.bulkActionMacro((()=>{t.setZorder(this._initialZOrder),e.addDataSource(t,o,!0),s.forEach((t=>e.addDataSource(t,o,!1)))}));const r=(0,n.ensureNotNull)(t.priceScale()) ;r.restoreState(this._originalPriceScaleState()),r.setHeight(e.height()),this._chartModel.fullUpdate()}}class Y extends j{constructor(e,t,i){super(e,t,i)}_targetPaneIndex(){return this._initialPaneIndex-1}}class K extends j{constructor(e,t,i){super(e,t,i)}_targetPaneIndex(){return this._initialPaneIndex+1}}class Z extends j{constructor(e,t,i,s,o){super(e,t,s,o),this._targetPane=i}_targetPaneIndex(){return this._targetPane}}var $=i(888929),X=i(996986),J=i(553582),Q=i(982217);const ee=new T.TranslatedString("bring {title} to front",l.t(null,void 0,i(178246))),te=new T.TranslatedString("send {title} to back",l.t(null,void 0,i(166781))),ie=new T.TranslatedString("insert {title} after {targetTitle}",l.t(null,void 0,i(53146))),se=new T.TranslatedString("insert {title} before {targetTitle}",l.t(null,void 0,i(667176))),oe=new T.TranslatedString("send {title} backward",l.t(null,void 0,i(216259))),re=new T.TranslatedString("bring {title} forward",l.t(null,void 0,i(356763))),ne=new T.TranslatedString("send group {title} backward",l.t(null,void 0,i(404998))),ae=new T.TranslatedString("bring group {title} forward",l.t(null,void 0,i(27195)));function le(e){return new T.TranslatedString(e.name(),e.title(Q.TitleDisplayTarget.StatusLine))}class ce extends P.UndoCommand{constructor(e,t,i){super(i),this._sourcesByPanes=new Map,this._originalState=new Map,this._model=e,t.forEach((t=>{const i=(0,n.ensureNotNull)(e.paneForSource(t)),s=e.panes().indexOf(i),o=this._sourcesByPanes.get(s)||[];o.push(t.id()),this._sourcesByPanes.set(s,o)})),Array.from(this._sourcesByPanes.keys()).forEach((t=>{const i=e.panes()[t],s=new Map;i.sourcesByGroup().allIncludingHidden().forEach((e=>{s.set(e.id(),e.zorder())})),this._originalState.set(t,s)}))}undo(){this._originalState.forEach(((e,t)=>{const i=this._model.panes()[t],s=new Map;e.forEach(((e,t)=>{const o=(0,n.ensureNotNull)(i.dataSourceForId(t));s.set(o,e)})),i.setZOrders(s)}))}redo(){this._sourcesByPanes.forEach(((e,t)=>{const i=this._model.panes()[t],s=e.map((e=>(0,n.ensureNotNull)(i.dataSourceForId(e))));this._paneOperation(i,s)}))}}class he extends ce{constructor(e,t){super(e,t,ee.format({title:le(t[0])}))}_paneOperation(e,t){e.bringToFront(t)}}class de extends ce{constructor(e,t){super(e,t,te.format({title:le(t[0])}))}_paneOperation(e,t){e.sendToBack(t)}}class ue extends ce{constructor(e,t,i,s){super(e,t,s),this._targetSource=i}_paneOperation(e,t){e.insertAfter(t,this._targetSource)}}class _e extends ue{constructor(e,t,i){super(e,t,i,ie.format({title:le(t[0]),targetTitle:le(i)}))}}class pe extends ce{constructor(e,t,i,s){super(e,t,s),this._targetSource=i}_paneOperation(e,t){e.insertBefore(t,this._targetSource)}}class me extends pe{constructor(e,t,i){super(e,t,i,se.format({title:le(t[0]),targetTitle:le(i)}))}}function ge(e,t){const i=t[0],s=e.sourcesByGroup().all().filter((e=>e.zorder()e.zorder()>i.zorder()));if(0===s.length)throw new Error("Cannot bring forward source that alreadt on back");let o=s[0];if((0,S.isLineTool)(o)){const t=e.model().lineToolsGroupModel().groupForLineTool(o);if(null!==t){const e=t.lineTools();o=e[e.length-1]}}return o}class fe extends ue{constructor(e,t,i){super(e,i,ve(t,i),re.format({title:le(i[0])}))}}function be(e,t){return(0,n.ensureNotNull)(e.paneForSource(t.lineTools()[0]))}class ye extends pe{constructor(e,t){super(e,t.lineTools(),ge(be(e,t),t.lineTools()),ne.format({title:t.name().value()}))}}class Ce extends ue{constructor(e,t){super(e,t.lineTools(),ve(be(e,t),t.lineTools()),ae.format({title:t.name().value()}))}}const we=new T.TranslatedString("rearrange panes",l.t(null,void 0,i(233348)));class Pe extends P.UndoCommand{constructor(e,t,i){super(we),this._chartModel=e,this._index=t,(0,E.isNumber)(i)?this._dstIndex=i:this._dstIndex="up"===i?t-1:t+1}redo(){this._checkIndices()&&this._chartModel.movePane(this._index,this._dstIndex)}undo(){this._checkIndices()&&this._chartModel.movePane(this._dstIndex,this._index)}_checkIndices(){const e=this._chartModel.panes().length;return this._index>=0&&this._index=0&&this._dstIndex{var s,o;e.setValue(t[i].val),(null!==(o=null===(s=e.dependents)||void 0===s?void 0:s.call(e))&&void 0!==o?o:[]).forEach((e=>Ne(e,t[i].dependenValues)))}))}class Be extends P.UndoCommand{constructor(e,t,i,s,o){super(i),this._targetObj=e,this._newValue=t,this._oldValue=this._targetObj.value(),this._dependentValues=De(this._targetObj),this._model=s,o&&this.setCustomFlag("doesnt_affect_save",!0)}redo(){(0,xe.saveDefaultProperties)(!0),this._targetObj.setValue(this._newValue),(0,xe.saveDefaultProperties)(!1),this._model.recalculateAllPanes((0,ke.globalChangeEvent)()),this._model.lightUpdate()}undo(){(0,xe.saveDefaultProperties)(!0),this._targetObj.setValue(this._oldValue),Ne(this._targetObj,this._dependentValues),(0,xe.saveDefaultProperties)(!1),this._model.recalculateAllPanes((0,ke.globalChangeEvent)()),this._model.lightUpdate()}}class Re extends P.UndoCommand{constructor(e,t,i,s,o,r){super(s),this._prevPriceAxisProps={},this._dependentValues=[],this._property=e,this._mainSeries=i,this._value=t,this._model=o,this._chartWidget=r}redo(){const e=this._mainSeries,t=e.properties().childs();this._dependentValues=De(this._property), this._prevResolution=t.interval.value(),this._prevValue=this._property.value(),this._storePriceAxisProps(),(0,xe.saveDefaultProperties)(!0);const i=t.interval.value(),s=this._model.defaultResolutions(),o=(0,Le.getResolutionByChartStyle)(this._value,i,s);Ae.linking.interval.setValue(o),e.setChartStyleWithIntervalIfNeeded(this._value,o),(0,Ie.setLastUsedStyle)(this._value,e.symbolInfo()),(0,Ie.preparePriceAxisProperties)(t),(0,xe.saveDefaultProperties)(!1),this._invalidateModel(),this._chartWidget.screen.show(!0)}undo(){const e=this._mainSeries;(0,xe.saveDefaultProperties)(!0),e.setChartStyleWithIntervalIfNeeded(this._prevValue,this._prevResolution),this._restorePriceAxisProps(),Ae.linking.interval.setValue(this._prevResolution),Ne(this._property,this._dependentValues),(0,xe.saveDefaultProperties)(!1),this._invalidateModel(),this._chartWidget.screen.show(!0)}_storePriceAxisProps(){const e=this._mainSeries.priceScale();this._prevPriceAxisProps=e.mode()}_restorePriceAxisProps(){this._mainSeries.priceScale().setMode(this._prevPriceAxisProps)}_invalidateModel(){this._model&&(this._model.recalculateAllPanes((0,ke.sourceChangeEvent)(this._model.mainSeries().id())),this._model.lightUpdate())}}const Oe=new T.TranslatedString("change date range",l.t(null,void 0,i(207151)));class Ve extends P.UndoCommand{constructor(e,t){super(Oe),this._modelsData=[],this._rangeOptions=t,this._modelsData.push({model:e,prevResolution:e.mainSeries().properties().childs().interval.value(),barSpacing:e.timeScale().barSpacing(),rightOffset:e.timeScale().rightOffset(),rangeOptions:e.appliedTimeFrame().value()})}redo(){for(const e of this._modelsData){const t=e.model.mainSeries(),i=t.properties().childs().interval;u.Interval.isEqual(this._rangeOptions.res,i.value())?t.loadDataTo(this._rangeOptions.val):(t.setDefaultTimeframe(this._rangeOptions.val),t.setSymbolParams({interval:this._rangeOptions.res}))}}undo(){for(const e of this._modelsData){const t=e.model.mainSeries(),i=t.properties().childs().interval;e.prevResolution!==i.value()?(null!==e.rangeOptions&&t.setDefaultTimeframe(e.rangeOptions.val),t.setSymbolParams({interval:e.prevResolution})):null!==e.rangeOptions&&t.loadDataTo(e.rangeOptions.val);const s=e.model.timeScale();s.setBarSpacing(e.barSpacing),s.setRightOffset(e.rightOffset)}}canMerge(e){return e instanceof Ve&&_(e._rangeOptions,this._rangeOptions)}merge(e){if(!(e instanceof Ve))throw new Error("Invalid command to merge");this._modelsData=this._modelsData.concat(e._modelsData)}}var We=i(391534);i(586463);class Fe extends P.UndoCommand{constructor(e,t,i){super(i),this._model=e,this._groupId=t.id,this._groupName=t.name().value(),this._lineToolsIds=t.lineTools().map((e=>e.id()))}redo(){const e=(0,n.ensureNotNull)(this._model.lineToolsGroupModel().groupForId(this._groupId));this._model.lineToolsGroupModel().removeGroup(e)}undo(){const e=this._lineToolsIds.map((e=>this._model.dataSourceForId(e))),t=new We.LineToolsGroup(e,this._groupName,this._groupId);this._model.lineToolsGroupModel().addGroup(t)}} const He=new T.TranslatedString("create line tools group",l.t(null,void 0,i(3195)));class ze extends P.UndoCommand{constructor(e,t){super(He),this._groupId=null,this._model=e,this._sourcesIds=t.map((e=>e.id()))}redo(){const e=this._sourcesIds.map((e=>this._model.dataSourceForId(e))),t=null===this._groupId?void 0:this._groupId;this._groupId=this._model.lineToolsGroupModel().createGroup(e,this._title,t).id}undo(){const e=(0,n.ensureNotNull)(this._model.lineToolsGroupModel().groupForId((0,n.ensureNotNull)(this._groupId)));this._model.lineToolsGroupModel().removeGroup(e)}createdGroupId(){return this._groupId}}const Ue=new T.TranslatedString("add line tool(s) to group {group}",l.t(null,void 0,i(240242)));class Ge extends P.UndoCommand{constructor(e,t,i){super(Ue.format({group:t.name().value()})),this._model=e,this._groupId=t.id,this._lineToolsIds=i.map((e=>e.id()))}redo(){const e=(0,n.ensureNotNull)(this._model.lineToolsGroupModel().groupForId(this._groupId)),t=this._lineToolsIds.map((e=>this._model.dataSourceForId(e)));e.addLineTools(t)}undo(){const e=this._lineToolsIds.map((e=>this._model.dataSourceForId(e)));(0,n.ensureNotNull)(this._model.lineToolsGroupModel().groupForId(this._groupId)).excludeLineTools(e)}}var qe=i(440941);class je extends P.UndoCommand{constructor(e,t,i,s){super(s),this._chartModel=e,this._groupId=t.id,this._oldName=t.name().value(),this._newName=i}redo(){(0,n.ensureNotNull)(this._chartModel.lineToolsGroupModel().groupForId(this._groupId)).setName(this._newName)}undo(){(0,n.ensureNotNull)(this._chartModel.lineToolsGroupModel().groupForId(this._groupId)).setName(this._oldName)}}var Ye=i(885482),Ke=i(541558);class Ze extends P.UndoCommand{constructor(e,t,i,s){super(s),this._model=i,this._id=e.id(),this._targetSharingMode=t,this._originSharingMode=e.sharingMode().value()}redo(){const e=this._model.dataSourceForId(this._id);e&&(e.share(this._targetSharingMode),0!==this._targetSharingMode&&0===this._originSharingMode&&(e.linkKey().setValue((0,Ke.randomHash)()),this._model.copyToOtherCharts([e],!1)))}undo(){const e=this._model.dataSourceForId(this._id);e&&(e.share(this._originSharingMode),0===this._originSharingMode&&((0,Ye.removeLineTool)({withUndo:!1,model:this._model,symbol:e.symbol(),linkKey:(0,n.ensureNotNull)(e.linkKey().value()),sourceTitle:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,e),lineToolState:e.state(!1),unlink:!0}),e.linkKey().setValue(null)))}} const $e=new T.TranslatedString("create line tools group from selection",l.t(null,void 0,i(192659))),Xe=new T.TranslatedString("removing line tools group {name}",l.t(null,void 0,i(578811))),Je=new T.TranslatedString("add line tool {lineTool} to group {name}",l.t(null,void 0,i(799113))),Qe=new T.TranslatedString("make group {group} visible",l.t(null,void 0,i(587927))),et=new T.TranslatedString("make group {group} invisible",l.t(null,void 0,i(445223))),tt=new T.TranslatedString("lock group {group}",l.t(null,void 0,i(304963))),it=new T.TranslatedString("unlock group {group}",l.t(null,void 0,i(551114))),st=new T.TranslatedString("rename group {group} to {newName}",l.t(null,void 0,i(916338)));class ot{constructor(e){this._environment=e}createGroupFromSelection(){const e=this._environment.model();(0,n.assert)(!e.selection().isEmpty(),"Cannot create group from empty selection");const t=(0,$.sortSources)(e.selection().lineDataSources());(0,n.assert)(t.length===e.selection().allSources().length,"A group could contain line tools only");const i=t.length>1||null!==this._environment.model().lineToolsGroupModel().groupForLineTool(t[0]),s=t.reduce(((e,t)=>e.zorder()>t.zorder()?e:t),t[0]);let o=s;const r=e.lineToolsGroupModel().groupForLineTool(s);if(null!==r){const e=r.lineTools();o=e[e.length-1]}this._environment.beginUndoMacro($e,qe.lineToolsDoNotAffectChartInvalidation);const a=new Map,l=new Set;t.forEach((t=>{const i=this._groupForLineTool(t);if(null===i)return;const s=a.get(i)||[];s.push(t),a.set(i,s);const o=(0,n.ensureNotNull)(e.paneForSource(t));l.add(o)})),(0,n.assert)(l.size<=1,"All selected sources should be on the same pane"),a.forEach(((t,i)=>{const s=new W.ExcludeLineToolsFromGroupUndoCommand(e,i,t);this._environment.pushUndoCommand(s)}));const c=new ze(e,(0,$.sortSources)(t));if(this._environment.pushUndoCommand(c),i){const i=new _e(e,t,o);this._environment.pushUndoCommand(i)}this._environment.endUndoMacro();const h=(0,n.ensureNotNull)(c.createdGroupId());return(0,n.ensureNotNull)(e.lineToolsGroupModel().groupForId(h))}removeGroup(e){const t=this._environment.model(),i=e.lineTools();this._environment.beginUndoMacro(Xe.format({name:e.name().value()}),qe.lineToolsDoNotAffectChartInvalidation);const s=new Fe(t,e,null);this._environment.pushUndoCommand(s);const o=new V.RemoveSourcesUndoCommand(t,i,null);this._environment.pushUndoCommand(o);const r=t.mainSeries().symbol();i.forEach((e=>{null!==e.linkKey().value()&&(0,Ye.removeLineTool)({withUndo:!0,model:t,symbol:r,sourceTitle:new T.TranslatedString(e.name(),e.title(Q.TitleDisplayTarget.DataWindow)),lineToolState:e.state(!1),linkKey:(0,n.ensureNotNull)(e.linkKey().value())})})),this._environment.endUndoMacro()}groups(){return this._environment.model().lineToolsGroupModel().groups()}excludeLineToolFromGroup(e,t){const i=this._environment.model(),s=new W.ExcludeLineToolsFromGroupUndoCommand(i,e,[t]);s.setCustomFlag("doesnt_affect_save",qe.lineToolsDoNotAffectChartInvalidation),this._environment.pushUndoCommand(s)}addLineToolToGroup(e,t){ const i=this._environment.model(),s=i.lineToolsGroupModel().groupForLineTool(t);if(s===e)return;const o=Je.format({lineTool:new T.TranslatedString(t.name(),t.title(Q.TitleDisplayTarget.StatusLine)),name:e.name().value()});this._environment.beginUndoMacro(o,qe.lineToolsDoNotAffectChartInvalidation),null!==s&&this._environment.pushUndoCommand(new W.ExcludeLineToolsFromGroupUndoCommand(i,s,[t]));if((0,I.isFeatureEnabled)("save_shared_line_tools")){const s=e.sharingMode().value();t.sharingMode().value()!==s&&this._environment.pushUndoCommand(new Ze(t,s,i,null))}this._environment.pushUndoCommand(new Ge(i,e,[t])),this._environment.endUndoMacro()}bringToFront(e){const t=this._environment.model(),i=new he(t,e.lineTools());i.setCustomFlag("doesnt_affect_save",qe.lineToolsDoNotAffectChartInvalidation),this._environment.pushUndoCommand(i),this._environment.emitEvent("changeZOrder",[e.lineTools()])}sendToBack(e){const t=this._environment.model(),i=new de(t,e.lineTools());i.setCustomFlag("doesnt_affect_save",qe.lineToolsDoNotAffectChartInvalidation),this._environment.pushUndoCommand(i),this._environment.emitEvent("changeZOrder",[e.lineTools()])}bringForward(e){const t=this._environment.model(),i=new Ce(t,e);i.setCustomFlag("doesnt_affect_save",qe.lineToolsDoNotAffectChartInvalidation),this._environment.pushUndoCommand(i),this._environment.emitEvent("changeZOrder",[e.lineTools()])}sendBackward(e){const t=this._environment.model(),i=new ye(t,e);i.setCustomFlag("doesnt_affect_save",qe.lineToolsDoNotAffectChartInvalidation),this._environment.pushUndoCommand(i),this._environment.emitEvent("changeZOrder",[e.lineTools()])}insertAfter(e,t){const i=this._environment.model();let s;if(t instanceof We.LineToolsGroup){const e=t.lineTools();s=e[e.length-1]}else s=t;const o=new _e(i,e.lineTools(),s);this._environment.pushUndoCommand(o),this._environment.emitEvent("changeZOrder",[e.lineTools()])}insertBefore(e,t){const i=this._environment.model();let s;if(t instanceof We.LineToolsGroup){s=t.lineTools()[0]}else s=t;const o=new me(i,e.lineTools(),s);this._environment.pushUndoCommand(o),this._environment.emitEvent("changeZOrder",[e.lineTools()])}availableZOrderOperations(e){const t=this._environment.model(),i=e.lineTools(),s=i[0],o=i[i.length-1],r=(0,n.ensureNotNull)(t.paneForSource(i[0])).sourcesByGroup().allExceptSpecialSources(),a=r[0],l=r[r.length-1];return{bringForwardEnabled:o!==l,bringToFrontEnabled:o!==l,sendBackwardEnabled:s!==a,sendToBackEnabled:s!==a}}setGroupVisibility(e,t){const i=(t?Qe:et).format({group:e.name().value()}),s=this._environment.model();this._environment.beginUndoMacro(i,qe.lineToolsDoNotAffectChartInvalidation),e.lineTools().forEach((e=>{const i=e.properties().visible,o=new Be(i,t,null,s);this._environment.pushUndoCommand(o)})),this._environment.endUndoMacro()}setGroupLock(e,t){const i=(t?tt:it).format({group:e.name().value()}),s=this._environment.model();this._environment.beginUndoMacro(i,qe.lineToolsDoNotAffectChartInvalidation),e.lineTools().forEach((e=>{const i=e.properties().frozen,o=new Be(i,t,null,s) ;this._environment.pushUndoCommand(o)})),this._environment.endUndoMacro()}setGroupName(e,t){const i=this._environment.model(),s=st.format({group:e.name().value(),newName:t}),o=new je(i,e,t,s);o.setCustomFlag("doesnt_affect_save",qe.lineToolsDoNotAffectChartInvalidation),this._environment.pushUndoCommand(o)}canBeGroupped(e){const t=this._environment.model();return new Set(e.map((e=>t.paneForSource(e)))).size<=1}_groupForLineTool(e){return this._environment.model().lineToolsGroupModel().groups().find((t=>t.containsLineTool(e)))||null}}var rt=i(852290),nt=i(507795),at=i(569010),lt=i(790524),ct=i(46955);const ht=new T.TranslatedString("apply study template {template}",l.t(null,void 0,i(526065)));function dt(e){for(const t of e.panes)for(const e of t.sources)if((0,lt.isMainSeriesState)(e))return e.id;return null}class ut extends P.UndoCommand{constructor(e,t,i){var s,o;super(ht.format({template:i})),this._newSymbolParams={},this._model=e,this._templateContent=function(e,t){const i=(0,rt.default)({},e),s=(0,n.ensureNotNull)(dt(i));for(const e of i.panes){e.mainSourceId===s&&(e.mainSourceId=t);for(const i of e.sources)if(i.id===s){i.id=t;const o=e=>{const i=e.indexOf(s);-1!==i&&e.splice(i,1,t)};if(e.leftAxisesState&&e.rightAxisesState?(e.leftAxisesState.forEach((e=>o(e.sources))),e.rightAxisesState.forEach((e=>o(e.sources)))):(o(e.leftAxisSources),o(e.rightAxisSources)),e.overlayPriceScales){const i=e.overlayPriceScales[s];i&&(delete e.overlayPriceScales[s],e.overlayPriceScales[t]=i)}}else i.ownerSource===s&&(i.ownerSource=t)}return i}(t,e.mainSeries().id()),this._initialState=e.studyTemplate(!0,!0,!0);const r=e.mainSeries();t.symbol&&(this._newSymbolParams={symbol:t.symbol,currency:null!==(s=t.currency)&&void 0!==s?s:null,unit:null!==(o=t.unit)&&void 0!==o?o:null}),t.interval&&(this._newSymbolParams.interval=t.interval,this._newSymbolParams.style=(0,Ie.getChartStyleByResolution)(t.interval,r.style())),this._initialSymbolParams={symbol:r.symbol(),currency:r.currency(),unit:r.unit(),interval:r.interval(),style:r.style()},this._initialState=e.studyTemplate(),this._initialGroupsState=e.lineToolsGroupModel().state()}redo(){this._model.mainSeries().setSymbolParams(this._newSymbolParams);const e=this._merge(this._templateContent).filter(S.isLineTool);this._model.lineToolsGroupModel().removeLineTools(e);const t=this._model.mainSeries().properties();(0,Ie.preparePriceAxisProperties)(t),this._model.recalcVisibleRangeStudies(nt.RecalcVisibleRangeStudiesReason.StudyCreation),this._model.setShouldBeSavedEvenIfHidden(!0)}undo(){this._model.mainSeries().setSymbolParams(this._initialSymbolParams),this._merge(this._initialState)}_merge(e){const t=e.version||0,i=this._model,s=i.mainSeries();(0,n.assert)(s.id()===dt(e)),s.priceScale().properties().childs().lockScale.setValue(!1);const o=i.panes(),r=[];for(let e=o.length;e--;){const t=o[e],i=t.containsMainSeries(),s=t.dataSources();for(let e=s.length;e--;){const t=s[e];(!i||((0,w.isStudy)(t)||(0,w.isStudyStub)(t))&&t.isRemovedByStudyTemplates())&&r.push(t)}}i.resetDeferredStudies() ;const a=(0,at.closeSourcesSet)(i,r);for(let e=0;ee.zorder-t.zorder));for(let e=0;e-1,c=a?o[e]:i.createPane(e);if(a&&t<3&&(0,ct.reorderDataSourcesStateZOrder)(r.sources),c.restoreState({state:r,withData:!1,version:t}),null!==c.mainDataSource()){const e=(0,n.ensureNotNull)(this._model.alertsWatcher());for(const t of c.dataSources())e.syncSourceAlertLabels(t)}else i.removePane(c)}return i.syncLollipopSources(),s.priceScale().setMode({autoScale:!0}),i.startNotStartedStudies(),i.recalculateAllPanes((0,ke.globalChangeEvent)()),i.fullUpdate(),a}}var _t=i(981107);const pt=(0,C.getLogger)("Chart.ChartUndoModel"),mt=new T.TranslatedString("paste drawing",l.t(null,void 0,i(896916)));class gt extends P.UndoCommand{constructor(e,t,i,s,o){super(mt),this._needCopyToOtherCharts=!1,this._sourceState=null,this._model=e,this._clipboardData=t,this._paneIndex=this._model.panes().indexOf(i||(0,n.ensureNotNull)(this._model.paneForSource(this._model.mainSeries()))),this._pasteWithData=!!s,this._keepZIndex=!!o}redo(){const e=this._model.panes()[this._paneIndex],t=(0,n.ensureNotNull)(e.clipboardLineToolOwnerSource(this._clipboardData.source.id)),i=t===this._model.mainSeries();null===this._sourceState&&(this._sourceState=this._getSourceState(t,i));const s=(0,n.ensureNotNull)(e.restoreLineTool(this._sourceState,this._pasteWithData,this._keepZIndex,void 0,t));(0,n.ensureNotNull)(t.priceScale()).addDataSource(s),this._clipboardData.centeredOnChart&&s.centerPosition&&s.centerPosition(),s.restoreFixedPoint(),s.createServerPoints(),this._needCopyToOtherCharts=Boolean(i&&s.isSynchronizable()&&0!==s.sharingMode().value()),this._model.setShouldBeSavedEvenIfHidden(!0)}undo(){if(!this._sourceState)return void pt.logError("This command was never executed - nothing to undo");const e=this.source();this._clipboardData.centeredOnChart&&(this._clipboardData.centeredOnChart=!1,this._sourceState.points=e.normalizedPoints()),this._model.removeSource(e)}source(){return(0,n.ensureNotNull)(this._model.dataSourceForId((0,n.ensureNotNull)(this._sourceState).id))}needCopyToOtherCharts(){return this._needCopyToOtherCharts}_getSourceState(e,t){const i=(0,E.clone)(this._clipboardData.source);delete i.state.symbol,t?(null!=i.linkKey||void 0!==i.sharingMode&&0!==i.sharingMode)&&(i.linkKey=(0,Ke.randomHash)()):(i.linkKey=null,i.sharingMode=0);const s=(0,n.ensureNotNull)(e.priceScale()),o=this._model,{symbol:r,currencyId:l,unitId:c}=this._clipboardData.source.state,h=(0,n.ensureNotNull)(e.symbolSource());let d=!1;!h.symbolSameAsCurrent(r)||(null!==l?l!==(0,Ie.symbolCurrency)(h.symbolInfo(),void 0,!0):h.isConvertedToOtherCurrency())||(null!==c?c!==(0,Ie.symbolUnit)(h.symbolInfo(),this._model.unitConversionEnabled()):h.isConvertedToOtherUnit())||((0,_t.isActingAsSymbolSource)(e)?d=!0:(0, w.isStudy)(e)&&(d=Boolean(e.metaInfo().is_price_study)));const u=e=>{const t=e.x*o.timeScale().width(),i=e.y*s.height()-40;return new a.Point(t,i)},_=(0,n.ensureNotNull)(e.firstValue());if(this._model.id()===this._clipboardData.modelId||!d){for(let e=0;e{(0,n.ensureNotNull)(t.dataSourceForId(i)).setCurrency(e)})),this._chartWidget.model().selectionMacro((e=>{e.clearSelection()})),this._showFade&&this._chartWidget.screen.show(!0)}}class vt extends P.UndoCommand{constructor(e,t,i,s){super(s),this._newSourcesUnits=new Map,this._oldSourcesUnits=new Map,this._showFade=!1,this._chartWidget=i;const o=i.model().mainSeries();for(const i of e.seriesLikeSources()){if(!i.isVisible()||!i.isActingAsSymbolSource().value())continue;const e=t||(0,Ie.symbolOriginalUnit)((0,n.ensureNotNull)(i.symbolInfo()),this._chartWidget.model().model().unitConversionEnabled());this._newSourcesUnits.set(i.id(),e),this._oldSourcesUnits.set(i.id(),i.unit()),this._showFade=this._showFade||i===o&&i.unit()!==e}}redo(){this._applyUnits(this._newSourcesUnits)}undo(){this._applyUnits(this._oldSourcesUnits)}_applyUnits(e){const t=this._chartWidget.model().model();e.forEach(((e,i)=>{(0,n.ensureNotNull)(t.dataSourceForId(i)).setUnit(e)})),this._chartWidget.model().selectionMacro((e=>{e.clearSelection()})),this._showFade&&this._chartWidget.screen.show(!0)}}class ft extends H{constructor(e,t,i,s){super(e,t,s),this._sourcePaneRemoved=!1,this._targetPaneIndex=e.panes().indexOf(i)}redo(){const e=this._chartModel.panes()[this._initialPaneIndex],t=this._chartModel.panes()[this._targetPaneIndex],i=e!==t,s=this._targetPriceScale(t),o=(0,n.ensureNotNull)(this._chartModel.dataSourceForId(this._sourceId)),r=this._chartModel.children(o,!0);for(const e of r)i?(this._chartModel.detachSource(e),t.addDataSource(e,s,!1)):t.move(e,s);i?(this._sourcePaneRemoved=this._chartModel.detachSource(o),t.addDataSource(o,s,!1)):t.move(o,s);const a=t.priceScalePosition(s) ;t.movePriceScale(s,a,this._targetPriceScaleIndex(o)),this._chartModel.fullUpdate()}undo(){this._sourcePaneRemoved&&this._chartModel.createPane(this._initialPaneIndex);const e=this._chartModel.panes()[this._initialPaneIndex],t=e!==this._chartModel.panes()[this._targetPaneIndex],i=(0,n.ensureNotNull)(this._chartModel.dataSourceForId(this._sourceId));let s=e.getPriceScaleById(this._initialPriceScaleId);null===s&&(s=e.createPriceScaleAtPosition(this._initialPriceScalePosition,this._initialPriceScaleIndex));const o=this._chartModel.children(i,!0);for(const i of o)t?(this._chartModel.detachSource(i),e.addDataSource(i,s,!1)):e.move(i,s);t?(this._chartModel.detachSource(i),e.addDataSource(i,s,!1)):e.move(i,s);const r=(0,n.ensureNotNull)(i.priceScale());r.restoreState(this._originalPriceScaleState()),r.setHeight(e.height()),this._chartModel.fullUpdate()}}class bt extends ft{constructor(e,t,i,s,o){super(e,t,i,o),this._targetPriceScalePosition=s}_targetPriceScale(e){const t=e.createPriceScaleAtPosition(this._targetPriceScalePosition);return t.restoreState(this._newPriceScaleState("overlay"===this._targetPriceScalePosition)),t.setHeight(e.height()),t}_targetPriceScaleIndex(e){return e===this._chartModel.mainSeries()?0:void 0}}class yt extends ft{constructor(e,t,i,s,o){super(e,t,i,o),this._targetPriceScaleId=s.id()}_targetPriceScale(e){return(0,n.ensureNotNull)(e.getPriceScaleById(this._targetPriceScaleId))}_targetPriceScaleIndex(e){}}var Ct=i(912445);class wt extends P.UndoCommand{constructor(e,t,i,s){super(e),this._charts=new Map,this._firstRedo=!0,this._creationTime=performance.now(),this._linkingGroupIndex=s.linkingGroupIndex().value(),this._charts.set(s,{sourceId:t.id(),newSymbolParams:i,prevSymbolParams:t.symbolParams(),showFade:this._showFade(t,s),chartWidget:s})}redo(){this._firstRedo||(0,Ct.muteLinkingGroup)(this._linkingGroupIndex,!0),this._charts.forEach((e=>{this._symbolSource(e).setSymbolParams(e.newSymbolParams),e.showFade&&e.chartWidget.screen.show(!0)})),this._firstRedo||(0,Ct.muteLinkingGroup)(this._linkingGroupIndex,!1),this._firstRedo=!1}undo(){(0,Ct.muteLinkingGroup)(this._linkingGroupIndex,!0),this._charts.forEach((e=>{this._symbolSource(e).setSymbolParams(e.prevSymbolParams),e.showFade&&e.chartWidget.screen.show(!0)})),(0,Ct.muteLinkingGroup)(this._linkingGroupIndex,!1)}canMerge(e){if(!(e instanceof wt)||e._linkingGroupIndex!==this._linkingGroupIndex||!this._containsMainSeriesOnly()||!e._containsMainSeriesOnly()||e._creationTime-this._creationTime>500)return!1;for(const[t]of e._charts)if(this._charts.has(t))return!1;return!0}merge(e){if(e instanceof wt)for(const[t,i]of e._charts)this._charts.set(t,i)}_showFade(e,t){return e===t.model().mainSeries()}_symbolSource(e){return(0,n.ensureNotNull)(e.chartWidget.model().model().dataSourceForId(e.sourceId))}_containsMainSeriesOnly(){for(const[e,t]of this._charts)if(t.sourceId!==e.model().mainSeries().id())return!1;return!0}}const Pt=new T.TranslatedString("change symbol",l.t(null,void 0,i(600526)));class Tt extends wt{constructor(e,t,i){super(Pt,e,{symbol:t, currency:null,unit:null},i),this._symbol=t}canMerge(e){return e instanceof Tt&&e._symbol===this._symbol&&super.canMerge(e)}}const Mt=(0,C.getLogger)("Chart.ChartUndoModel"),xt=new T.TranslatedString("paste indicator",l.t(null,void 0,i(780611)));class It extends P.UndoCommand{constructor(e,t,i){super(xt),this._sourceState=null,this._model=e,this._clipboardData=t,this._paneId=i}redo(){if(!this._sourceState){const e=(0,E.clone)(this._clipboardData.source);e.id=(0,Ke.randomHashN)(6),this._sourceState=e}let e,t;e=this._paneId?(0,n.ensureNotNull)(this._model.paneForId(this._paneId)):this._sourceState.metaInfo.is_price_study?(0,n.ensureNotNull)(this._model.paneForSource(this._model.mainSeries())):this._model.createPane();const i=!e.mainDataSource();this._sourceState.zorder=e.newStudyZOrder();const s=(0,n.ensureNotNull)(e.restoreStudy(this._sourceState,!1));i||(t=this._sourceState.metaInfo.is_price_study?t=this._model.mainSeries().priceScale():this._paneId?e.findSuitableScale(s):e.defaultPriceScale(),t!==s.priceScale()&&e.move(s,t)),(0,w.isStudy)(s)&&s.start()}undo(){if(null===this._sourceState)return void Mt.logError("This command was never executed - nothing to undo");const e=(0,n.ensureNotNull)(this._model.dataSourceForId(this._sourceState.id));this._model.removeSource(e)}state(){return this._sourceState}}class At extends P.UndoCommand{constructor(e,t,i,s,o){super(null,!1),this._model=e,this._paneA=t,this._paneB=i,this._prevStretchA=s,this._currStretchA=o}redo(){const e=this._paneA.stretchFactor()+this._paneB.stretchFactor();this._paneA.setStretchFactor(this._currStretchA),this._paneB.setStretchFactor(e-this._currStretchA),this._model.fullUpdate()}undo(){const e=this._paneA.stretchFactor()+this._paneB.stretchFactor();this._paneA.setStretchFactor(this._prevStretchA),this._paneB.setStretchFactor(e-this._prevStretchA),this._model.fullUpdate()}}var Lt=i(950740);const kt=new T.TranslatedString("move",l.t(null,void 0,i(647107)));class Et extends P.UndoCommand{constructor(e,t,i,s){super(kt,!1),this._endEvent=null,this._model=e,this._sourceId=t.id(),this._itemIndex=i,this._startEvent=s}move(e){this._endEvent=e,this._move(e)}hasChanges(){return null!==this._endEvent}undo(){this._move(this._startEvent)}redo(){this._move((0,n.ensureNotNull)(this._endEvent))}_move(e){const t=(0,n.ensureNotNull)(this._model.dataSourceForId(this._sourceId));(0,n.assert)(void 0!==t.moveItem,'The method "moveItem" is not defined'),t.moveItem&&t.moveItem(new a.Point(e.localX,e.localY),this._itemIndex,new Lt.EnvironmentState(e))}}var Dt=i(247001),Nt=i(181728),Bt=i(778016),Rt=i(833813);class Ot extends P.UndoCommand{constructor(e,t,i,s,o,r,n,a,l,c,h,d,u){super(u),this._paneState=null,this._lastInsertionStartPromise=null,this._additionalStudiesIds=[],this._chartModel=e,this._studyMetaInfo=t,this._props=s,this._addAsOverlay=o,this._parentIds=r.map((e=>e.id())),this._inputs=i,this._targetZOrder=h,this._preferredPriceScale=n,this._allowChangeCurrency=a,this._allowChangeUnit=l,this._paneSize=c,this._studyId=null!=d?d:null}redo(){ const e=this._parentIds.map((e=>this._chartModel.dataSourceForId(e))),t=this._chartModel.insertStudyWithParams(this._studyMetaInfo,this._inputs,this._targetZOrder,this._props,this._addAsOverlay,e,this._preferredPriceScale,this._allowChangeCurrency,this._allowChangeUnit,this._paneSize,null===this._studyId?void 0:this._studyId),i=t.study;if((0,w.isFundamentalStudy)(i))this._createCopiesOfNewFundamentalForAllStocks(i);else if((0,_t.isSymbolSource)(i)){null!==i.symbolInfo()?this._createCopiesOfExistingFundamentalsForNewStock(i):i.symbolResolved().subscribe(this,(()=>this._createCopiesOfExistingFundamentalsForNewStock(i)),!0)}if(this._lastInsertionStartPromise=t.startPromise,this._studyId=i.id(),i.childStudyByRebind().subscribe(null,(()=>(0,f.trackEvent)("SOS","Apply SOS","Rebind SOS"))),(0,Dt.trackStudies)(i,"add"),this._chartModel.setShouldBeSavedEvenIfHidden(!0),null!==this._paneState){(0,n.ensureNotNull)(this._chartModel.paneForSource(i)).restoreState({state:this._paneState,withData:!1,version:this._chartModel.version()}),this._paneState=null}}undo(){const e=(0,n.ensureNotNull)(this._chartModel.dataSourceForId((0,n.ensureNotNull)(this._studyId)));(0,_t.isSymbolSource)(e)&&e.symbolResolved().unsubscribeAll(this);const t=(0,n.ensureNotNull)(this._chartModel.paneForSource(e)).state();this._additionalStudiesIds.forEach((e=>{const t=(0,n.ensureNotNull)(this._chartModel.dataSourceForId(e));this._chartModel.removeSource(t)})),this._additionalStudiesIds=[],this._chartModel.removeSource(e)&&(this._paneState=t)}insertedStudy(){return this._chartModel.dataSourceForId((0,n.ensureNotNull)(this._studyId))}lastInsertionStartPromise(){var e;return null!==(e=this._lastInsertionStartPromise)&&void 0!==e?e:Promise.resolve()}_createCopiesOfNewFundamentalForAllStocks(e){let t=(0,n.ensureNotNull)((0,Bt.getConfig)(Rt.ProductFeatures.FUNDAMENTALS_ON_CHART)).limit-this._chartModel.chartApi().getFundamentalCounter();e.isStarted()||(t-=1);const i=this._studyMetaInfo.symbolInputId(),s=this._chartModel.symbolSources();for(const o of s){if(t<=0)break;if(!o.isVisible()||o===e.symbolSource())continue;const s=o.symbolInfo();if(null!==s&&(0,Nt.isStockSymbol)(s.type,s.typespecs)){const e={};e[(0,n.ensureNotNull)(i)]=o.symbol();const s=this._chartModel.insertStudyWithParams(this._studyMetaInfo,e,null,this._props,!1);this._additionalStudiesIds.push(s.study.id()),t-=1}}}_createCopiesOfExistingFundamentalsForNewStock(e){let t=(0,n.ensureNotNull)((0,Bt.getConfig)(Rt.ProductFeatures.FUNDAMENTALS_ON_CHART)).limit-this._chartModel.chartApi().getFundamentalCounter();const i=e.symbolInfo();if(null!==i&&(0,Nt.isStockSymbol)(i.type,i.typespecs)){const i=new Set,s=this._chartModel.allStudies(!0).filter((e=>(0,w.isFundamentalStudy)(e)&&e.isVisible()));for(const o of s){if(t<=0)break;const s=o.metaInfo();if(!i.has(s.fullId)){const o={};o[(0,n.ensureNotNull)(s.symbolInputId())]=e.symbol();const r=this._chartModel.insertStudyWithParams(s,o,null,this._props,!1);this._additionalStudiesIds.push(r.study.id()),t-=1,i.add(s.fullId)}}}}} var Vt=i(209800),Wt=i(607113),Ft=i.n(Wt),Ht=i(918208),zt=i(438907),Ut=i(371764),Gt=i(972375),qt=i(62802),jt=i(520259);var Yt=i(606097),Kt=i(744084);class Zt extends P.UndoCommand{constructor(e){const{undoText:t,chartModel:i,linkKey:s,symbol:o,state:r,unlink:n}=e;super(t),this._chartModel=i,this._linkKey=s,this._symbol=o,this._state=r,this._unlink=n}redo(){const e=(0,S.lineToolByLinkKey)(this._chartModel,this._linkKey);e?(this._unlink&&e.detachAlert(),new Kt.RemoveLineDataSourcesUndoCommand({chartModel:this._chartModel,lineDataSourceIds:[e.id()],title:null}).redo()):this._chartModel.lineToolsSynchronizer().markSyncedLineToolAsDeleted(this._linkKey,this._symbol).then((e=>{if(null!==e){this._state.id=e;const t=(0,S.lineToolByLinkKey)(this._chartModel,this._linkKey);null!==t&&t.setId(e)}}))}undo(){}}var $t=i(953639),Xt=i(470130),Jt=i(100161),Qt=i(31214);const ei=new T.TranslatedString("zoom",l.t(null,void 0,i(659833)));class ti extends P.UndoCommand{constructor(e,t,i,s,o,r){super(ei),this._barSpacing=null,this._rightBarsOffset=null,this._leftBarsOffset=null,this._priceMode=null,this._model=e,this._startBar=t,this._endBar=i,this._startPrice=s,this._endPrice=o,this._pane=r}redo(){const e=(0,n.ensureNotNull)(this._model.timeScale().visibleBarsStrictRange());this._leftBarsOffset=e.firstBar()-this._startBar,this._rightBarsOffset=e.lastBar()-this._endBar,this._barSpacing=this._model.timeScale().barSpacing(),this._priceMode=this._pane.defaultPriceScale().mode(),this._model.zoomToViewport(this._startBar,this._endBar,this._startPrice,this._endPrice,this._pane)}undo(){const e=this._model.timeScale(),t=this._pane.defaultPriceScale(),i=(0,n.ensureNotNull)(e.visibleBarsStrictRange());e.setBarSpacing((0,n.ensureNotNull)(this._barSpacing)),e.zoomToBarsRange(i.firstBar()+(0,n.ensureNotNull)(this._leftBarsOffset),i.lastBar()+(0,n.ensureNotNull)(this._rightBarsOffset)),t.setMode((0,n.ensureNotNull)(this._priceMode)),t.recalculatePriceRange((0,n.ensureNotNull)(e.visibleBarsStrictRange())),this._model.recalculateAllPanes((0,ke.viewportChangeEvent)()),this._model.lightUpdate()}}const ii=(0,C.getLogger)("Chart.ChartUndoModel"),si=new T.TranslatedString("zoom",l.t(null,void 0,i(659833)));class oi extends P.UndoCommand{constructor(e,t,i){super(si),this._baseCmd=e,this._zoomStack=t,this._inOut=i}undo(){if(this._inOut){if(this._baseCmd!==this._zoomStack.head())return void ii.logDebug("zoom stack inconsistency");this._baseCmd.undo(),this._zoomStack.pop()}else this._baseCmd.redo(),this._zoomStack.push(this._baseCmd)}redo(){if(this._inOut)this._baseCmd.redo(),this._zoomStack.push(this._baseCmd);else{if(this._baseCmd!==this._zoomStack.head())return void ii.logDebug("zoom stack inconsistency");this._baseCmd.undo(),this._zoomStack.pop()}}}const ri=new T.TranslatedString("stop syncing drawing",l.t(null,void 0,i(598784)));class ni extends P.UndoCommand{constructor(e,t){super(ri),this._model=e,this._sourceId=t.id(),this._linkKey=t.linkKey().value()}redo(){(0,n.ensureNotNull)(this._model.dataSourceForId(this._sourceId)).linkKey().setValue(null)}undo(){(0, n.ensureNotNull)(this._model.dataSourceForId(this._sourceId)).linkKey().setValue(this._linkKey)}}const ai=new T.TranslatedString("restore defaults",l.t(null,void 0,i(209608)));class li extends P.UndoCommand{constructor(e,t,i=ai){super(i),this._chartModel=e,this._defaultProperty=t,this._state=t.state()}redo(){this._chartModel.restoreFactoryDefaults(this._defaultProperty)}undo(){this._defaultProperty.mergeAndFire(this._state),this._chartModel.mainSeries().onChartStyleChanged()}}var ci=i(808068);class hi extends li{redo(){this._defaultProperty.hasChild("intervalsVisibilities")&&this._defaultProperty.childs().intervalsVisibilities.mergeAndFire(ci.intervalsVisibilitiesDefaults),super.redo()}}var di=i(662080),ui=i(62745);const _i=new T.TranslatedString("restore study defaults",l.t(null,void 0,i(730107)));class pi extends hi{constructor(e,t,i=_i){super(e,t.properties(),i),this._study=t}redo(){super.redo(),this._chartModel.recalcColorStudies(!0),this._patchProperties()}undo(){super.undo(),this._chartModel.recalcColorStudies(!0),this._patchProperties()}_patchProperties(){{const e=this._study.inputs();Object.keys(e).some((e=>(0,ui.isStudyInputDependsOnChart)({id:e})))&&(0,di.patchPropertiesAsync)(this._study.properties(),this._study.metaInfo(),e)}}}var mi=i(395098),gi=i(329806),Si=i(42292);function vi(e){const{visible:t,...i}=e;return i}function fi(e){const{visible:t,...i}=e;return i}function bi(e){const{drawWick:t,drawBorder:i,drawBody:s,barColorsOnPrevClose:o,...r}=e;return r}function yi(e){const{drawWick:t,drawBorder:i,drawBody:s,...o}=e;return o}function Ci(e){const{drawWick:t,drawBorder:i,drawBody:s,showRealLastPrice:o,inputs:r,...n}=e;return n}function wi(e){const{barColorsOnPrevClose:t,dontDrawOpen:i,thinBars:s,...o}=e;return o}function Pi(e){const{showBorders:t,showLabels:i,drawBody:s,...o}=e;return o}function Ti(e){const{linestyle:t,linewidth:i,priceSource:s,...o}=e;return o}function Mi(e){const{linestyle:t,linewidth:i,priceSource:s,...o}=e;return o}function xi(e){const{inputs:t,...i}=e;return i}function Ii(e){const{inputs:t,...i}=e;return i}function Ai(e){const{inputs:t,...i}=e;return i}function Li(e){const{inputs:t,...i}=e;return i}function ki(e){const{topLineWidth:t,bottomLineWidth:i,baseLevelPercentage:s,priceSource:o,...r}=e;return r}function Ei(e){const{thinBars:t,inputs:i,...s}=e;return s}function Di(e){return{bgColors:e.bgColors}}function Ni(e){return{color:e.color,tpo:{colors:e.tpo.colors},volumeProfile:{valuesColor:e.volumeProfile.valuesColor,volumeColor:e.volumeProfile.volumeColor,valueAreaColor:e.volumeProfile.valueAreaColor,vah:{color:e.volumeProfile.vah.color},val:{color:e.volumeProfile.val.color},poc:{color:e.volumeProfile.poc.color}}}}function Bi(e){ const{visible:t,style:i,symbol:s,interval:o,sessionId:r,highLowAvgPrice:n,showCountdown:a,bidAsk:l,prePostMarket:c,priceAxisProperties:h,candleStyle:d,volCandlesStyle:u,hollowCandleStyle:_,haStyle:p,barStyle:m,hiloStyle:g,lineStyle:S,lineWithMarkersStyle:v,steplineStyle:f,areaStyle:b,renkoStyle:y,pbStyle:C,kagiStyle:w,pnfStyle:P,baselineStyle:T,rangeStyle:M,volFootprintStyle:x,tpoStyle:I,esdShowDividends:A,esdShowSplits:L,esdShowEarnings:k,esdShowBreaks:E,showContinuousContractSwitches:D,showContinuousContractSwitchesBreaks:N,showFuturesContractExpiration:B,showLastNews:R,...O}=e;return{bidAsk:vi(l),prePostMarket:fi(c),candleStyle:bi(d),hollowCandleStyle:yi(_),haStyle:Ci(p),barStyle:wi(m),hiloStyle:Pi(g),lineStyle:Ti(S),lineWithMarkersStyle:Ti(v),steplineStyle:Ti(f),areaStyle:Mi(b),renkoStyle:xi(y),pbStyle:Ii(C),kagiStyle:Ai(w),pnfStyle:Li(P),baselineStyle:ki(T),rangeStyle:Ei(M),volFootprintStyle:Di(x),tpoStyle:Ni(I),volCandlesStyle:bi(u),...O}}function Ri(e){const{scaleSeriesOnly:t,showSeriesLastValue:i,showStudyLastValue:s,showSymbolLabels:o,showBidAskLabels:r,showPrePostMarketPriceLabel:n,showStudyPlotLabels:a,showFundamentalNameLabel:l,showFundamentalLastValue:c,seriesLastValueMode:h,...d}=e;return d}function Oi(e){const{topMargin:t,bottomMargin:i,...s}=e;return s}const Vi=new T.TranslatedString("apply chart theme",l.t(null,void 0,i(766568)));class Wi extends P.UndoCommand{constructor(e,t,i){var s,o,r;super(Vi),this._model=e,this._newSessionProps=t.sessions||(0,Si.factoryDefaults)("sessions"),["candleStyle","hollowCandleStyle","haStyle"].forEach((e=>{t.mainSourceProperties[e].wickUpColor=t.mainSourceProperties[e].wickUpColor||t.mainSourceProperties[e].wickColor,t.mainSourceProperties[e].wickDownColor=t.mainSourceProperties[e].wickDownColor||t.mainSourceProperties[e].wickColor})),t.chartProperties=null!==(s=t.chartProperties)&&void 0!==s?s:{paneProperties:{},scalesProperties:void 0},t.chartProperties.paneProperties.vertGridProperties=null!==(o=t.chartProperties.paneProperties.vertGridProperties)&&void 0!==o?o:t.chartProperties.paneProperties.gridProperties,t.chartProperties.paneProperties.horzGridProperties=null!==(r=t.chartProperties.paneProperties.horzGridProperties)&&void 0!==r?r:t.chartProperties.paneProperties.gridProperties;const n=this._model.properties().state().paneProperties.legendProperties;delete n.backgroundTransparency,t.chartProperties.paneProperties.legendProperties={...t.chartProperties.paneProperties.legendProperties,...n};const a=(0,Si.factoryDefaults)("chartproperties"),l=(0,gi.deepExtend)({},a,t.chartProperties);this._newChartProps={paneProperties:Oi(l.paneProperties),scalesProperties:Ri(l.scalesProperties)},e.timeScale().preserveBarSpacing()&&delete this._newChartProps.scalesProperties.barSpacing;const c=(0,Si.factoryDefaults)("chartproperties.mainSeriesProperties"),h=(0,gi.deepExtend)({},c,t.mainSourceProperties);this._newSeriesProps=i?h:Bi(h);const d=e.properties().state();this._oldChartProps={paneProperties:Oi(d.paneProperties),scalesProperties:Ri(d.scalesProperties)} ;const u=e.mainSeries().properties().state();this._oldSeriesProps=i?u:Bi(u),this._oldSessionProps=this._model.sessions().properties().state()}undo(){this._merge(this._oldChartProps,this._oldSeriesProps,this._oldSessionProps),this._model.mainSeries().onChartStyleChanged(),this._model.updateScales(),this._model.chartThemeLoaded()}redo(){this._merge(this._newChartProps,this._newSeriesProps,this._newSessionProps),this._model.mainSeries().onChartStyleChanged(),this._model.updateScales(),this._model.chartThemeLoaded()}_merge(e,t,i){var s,o,r,n;const a=this._model;(0,xe.saveDefaultProperties)(!0),e&&(a.properties().childs().paneProperties.mergeAndFire(e.paneProperties),a.properties().childs().scalesProperties.mergeAndFire(e.scalesProperties)),"priceAxisProperties"in t&&a.mainSeries().priceScale().setMode({autoScale:null===(s=t.priceAxisProperties)||void 0===s?void 0:s.autoScale,percentage:null===(o=t.priceAxisProperties)||void 0===o?void 0:o.percentage,log:null===(r=t.priceAxisProperties)||void 0===r?void 0:r.log,lockScale:null===(n=t.priceAxisProperties)||void 0===n?void 0:n.lockScale}),a.mainSeries().properties().mergeAndFire(t),a.mainSeries().properties().saveDefaults(),a.mainSeries().createPaneView(),a.mainSeries().invalidateBarStylesCache(),a.recalculateAllPanes((0,ke.globalChangeEvent)()),a.fullUpdate(),a.properties().saveDefaults(),a.sessions().restoreState({properties:i},!1),(0,xe.saveDefaultProperties)(!1)}}const Fi=new T.TranslatedString("change resolution",l.t(null,void 0,i(932303)));class Hi extends wt{constructor(e,t,i){super(Fi,e,function(e,t){let i;const s=(0,Ie.isRangeStyle)(e.style()),o=u.Interval.isRange(t);return!s&&o?i=11:s&&!o&&(i=(0,Ie.getLastUsedStyle)()),{interval:t,style:i}}(e,t),i),this._resolution=t}canMerge(e){return e instanceof Hi&&e._resolution===this._resolution&&super.canMerge(e)}_showFade(e,t){return!0}}var zi=i(993713);class Ui extends zi.SetWatchedValueCommand{constructor(){super(...arguments),this._firstRedo=!0}redo(){this._firstRedo||(0,Ct.muteLinkingGroup)(this._newValue,!0),(0,Ct.muteLinkingGroup)(this._oldValue,!0),super.redo(),this._firstRedo||(0,Ct.muteLinkingGroup)(this._newValue,!1),(0,Ct.muteLinkingGroup)(this._oldValue,!1),this._firstRedo=!1}undo(){(0,Ct.muteLinkingGroup)(this._newValue,!0),(0,Ct.muteLinkingGroup)(this._oldValue,!0),super.undo(),(0,Ct.muteLinkingGroup)(this._newValue,!1),(0,Ct.muteLinkingGroup)(this._oldValue,!1)}}var Gi=i(849245),qi=i(251954),ji=i(832733),Yi=i(616117) ;const Ki=new T.TranslatedString("send {title} backward",l.t(null,void 0,i(216259))),Zi=new T.TranslatedString("bring {title} forward",l.t(null,void 0,i(356763))),$i=new T.TranslatedString("insert {title} after {target}",l.t(null,void 0,i(974055))),Xi=new T.TranslatedString("insert {title} before {target}",l.t(null,void 0,i(411231))),Ji=new T.TranslatedString("cut {title}",l.t(null,void 0,i(78755))),Qi=new T.TranslatedString("cut sources",l.t(null,void 0,i(63649))),es=new T.TranslatedString("remove {title}",l.t(null,void 0,i(839859))),ts=new T.TranslatedString("remove drawings group",l.t(null,void 0,i(570653))),is=new T.TranslatedString("move scale",l.t(null,void 0,i(804184))),ss=new T.TranslatedString("stop syncing line tool(s)",l.t(null,void 0,i(157011))),os=new T.TranslatedString("zoom out",l.t(null,void 0,i(809645))),rs=new T.TranslatedString("zoom in",l.t(null,void 0,i(119813))),ns=new T.TranslatedString("move drawing(s)",l.t(null,void 0,i(145356))),as=new T.TranslatedString("load default drawing template",l.t(null,void 0,i(354597))),ls=new T.TranslatedString("apply factory defaults to selected sources",l.t(null,void 0,i(796996))),cs=new T.TranslatedString("change currency",l.t(null,void 0,i(222641))),hs=new T.TranslatedString("change unit",l.t(null,void 0,i(239028))),ds=new T.TranslatedString("clone line tools",l.t(null,void 0,i(205179))),us=new T.TranslatedString("merge up",l.t(null,void 0,i(266143))),_s=new T.TranslatedString("merge down",l.t(null,void 0,i(162153))),ps=new T.TranslatedString("merge to pane",l.t(null,void 0,i(170746))),ms=new T.TranslatedString("unmerge up",l.t(null,void 0,i(52540))),gs=new T.TranslatedString("unmerge down",l.t(null,void 0,i(786949))),Ss=new T.TranslatedString("unmerge to new bottom pane",l.t(null,void 0,i(220057))),vs=new T.TranslatedString("move {title} to new right scale",l.t(null,void 0,i(545544))),fs=new T.TranslatedString("move {title} to new left scale",l.t(null,void 0,i(411303))),bs=new T.TranslatedString("make {title} no scale (Full screen)",l.t(null,void 0,i(774642))),ys=new T.TranslatedString("scroll time",l.t(null,void 0,i(170009))),Cs=new T.TranslatedString("scale time",l.t(null,void 0,i(235962))),ws=new T.TranslatedString("reset time scale",l.t(null,void 0,i(855064))),Ps=new T.TranslatedString("reset scales",l.t(null,void 0,i(721948))),Ts=new T.TranslatedString("create {tool}",l.t(null,void 0,i(581791))),Ms=new T.TranslatedString("change {pointIndex} point",l.t(null,void 0,i(572032))),xs=new T.TranslatedString("paste {title}",l.t(null,void 0,i(441601))),Is=new T.TranslatedString("insert {title}",l.t(null,void 0,i(90743))),As=new T.TranslatedString("remove all studies",l.t(null,void 0,i(415516))),Ls=new T.TranslatedString("remove drawings",l.t(null,void 0,i(644656))),ks=new T.TranslatedString("remove all studies and drawing tools",l.t(null,void 0,i(580171))),Es=new T.TranslatedString("turn line tools sharing off",l.t(null,void 0,i(128068))),Ds=new T.TranslatedString("share line tools in layout",l.t(null,void 0,i(977554))),Ns=new T.TranslatedString("share line tools globally",l.t(null,void 0,i(64704))),Bs=new T.TranslatedString("change linking group",l.t(null,void 0,i(323783))),Rs=(0, C.getLogger)("Chart.ChartUndoModel"),Os=(0,I.isFeatureEnabled)("hide_tweet_drawingtool");function Vs(e,t){return{bringForwardEnabled:e.bringForwardEnabled||t.bringForwardEnabled,bringToFrontEnabled:e.bringToFrontEnabled||t.bringToFrontEnabled,sendBackwardEnabled:e.sendBackwardEnabled||t.sendBackwardEnabled,sendToBackEnabled:e.sendToBackEnabled||t.sendToBackEnabled}}const Ws=(0,I.isFeatureEnabled)("save_shared_line_tools");function Fs(){return Ws?(0,Ye.drawOnAllCharts)().value()?1===(0,Ye.drawOnAllChartsMode)().value()?1:2:0:(0,Ye.drawOnAllCharts)().value()?1:0}function Hs(e,t){(0,A.onWidget)()?(0,L.showGoToTradingViewReferralDialog)({feature:"indicators"}):(0,k.showStudiesLimitGoProDialog)(e,t)}class zs extends(o()){constructor(e,t,i,s,o,r,n,a,l,c,h){super(),this._createLineCommand=null,this._initialTimeScrollState=null,this._initialTimeScrollPos=null,this._scalePriceInfo=null,this._currentSourceMoveCommand=null,this._currentLineChangeCommand=null,this._currentCustomMoveCommand=null,this._zoomStack=new p.UndoStack,this._chartWidget=o,this.m_model=new(Ft())(e,t,i,s,this,n,a,l,c,h),this._undoHistory=r,this._lineToolsGroupController=new ot({model:this._model.bind(this),pushUndoCommand:this._pushUndoCommand.bind(this),beginUndoMacro:(e,t)=>{this._undoHistory.beginUndoMacro(e).setCustomFlag("doesnt_affect_save",!!t)},endUndoMacro:this._undoHistory.endUndoMacro.bind(this._undoHistory),emitEvent:this.emitEvent.bind(this)})}id(){return this._model().id()}undoHistory(){return this._undoHistory}setWatchedValue(e,t,i){this._undoHistory.setWatchedValue(e,t,i)}lineToolsGroupController(){return this._lineToolsGroupController}mergeAllScales(e){!function(e,t){e.beginUndoMacro("left"===t?D:N),e.model().panes().forEach((i=>{const s="left"===t?i.rightPriceScales():i.leftPriceScales(),o=("left"===t?i.leftPriceScales():i.rightPriceScales()).concat(s),r="overlay"===i.priceScalePosition(i.defaultPriceScale())?o[0]:i.defaultPriceScale();e.movePriceScale(i,r,t,0),o.forEach((t=>{if(t===r)return;let s=t.mainSource();for(;null!==s;){e.moveToScale(s,i,r,null,!0);const o=t.mainSource();if(o===s){B.logError("Loop detected while trying to merge scales");break}s=o}}))})),e.endUndoMacro(),e.model().fullUpdate()}(this,e)}movePriceScale(e,t,i,s){const o=new R(this._model(),e,t,i,s,is);this._pushUndoCommand(o)}createLineTool({pane:e,point:t,linetool:i,properties:s,linkKey:o,ownerSource:r,disableSynchronization:a,sharingMode:l=Fs(),id:c}){const h=ji.lineToolsStudyIds[i];if((0,n.assert)(!(0,Yi.isStudyLineToolName)(h)||!!h),h){const e=this.canCreateStudy({id:h});if(!e.success)return Hs(this.model(),e),(0,Yi.isStudyLineToolName)(Ye.tool.value())&&(0,Ye.resetToCursor)(),null}const d=Ts.format({tool:new T.TranslatedString(i,Ht.lineToolsLocalizedNames[i])});this.beginUndoMacro(d,qe.lineToolsDoNotAffectChartInvalidation);const u=!a;this._createLineCommand=new J.CreateLineToolUndoCommand({model:this._model(),pane:e,lineTool:i,ownerSource:r||(0,n.ensureNotNull)(e.mainDataSource()),drawOnAllChartsMode:l,id:c}) ;const _=this._createLineCommand.startCreatingLine(t,s,o||null,l),p=(0,n.ensureNotNull)(this._createLineCommand.line());let m=null;if(_&&(u&&this.finishLineTool(p),this._pushUndoCommand(this._createLineCommand),this._createLineCommand=null,m={points:p.normalizedPoints(),interval:this.mainSeries().interval()}),u&&void 0===o&&(0,Ye.drawOnAllCharts)().value()&&p.isSynchronizable()){const e=(0,n.ensureNotNull)(this.model().externalTimeStamp(t.index)),s={point:{price:t.price,timeStamp:e},linetool:i,properties:p.properties(),symbol:this.mainSeries().symbol(),model:this.model(),linkKey:(0,n.ensureNotNull)(p.linkKey().value()),finalState:m,id:p.id(),sharingMode:p.sharingMode().value()};p.isFixed()&&(s.pointPositionPercents=p.calcPositionPercents()),(0,Ye.createLineTool)(s)}return this.endUndoMacro(),p}continueCreatingLine(e,t,i,s){const o=(0,n.ensureNotNull)(this._createLineCommand);this.beginUndoMacro(o.text(),qe.lineToolsDoNotAffectChartInvalidation);const r=(0,n.ensureNotNull)(this._model().lineBeingCreated()),a=o.continueCreatingLine(e,t,i,s);let l=null;if(a&&(this.finishLineTool(r),this._pushUndoCommand(o),this._createLineCommand=null,l={points:r.normalizedPoints(),interval:this.mainSeries().interval()}),o.drawOnAllCharts()&&r.isSynchronizable()){const i=(0,n.ensureNotNull)(this._model().externalTimeStamp(e.index));(0,Ye.continueLineTool)({point:{price:e.price,timeStamp:i},envState:t,finalState:l,model:this._model()})}return this.endUndoMacro(),a}continueExternalLine(e,t,i){const s=(0,n.ensureNotNull)(this._createLineCommand),o=s.continueCreatingLine(e,t,i);return o&&(this._pushUndoCommand(s),this._createLineCommand=null),o}finishLineTool(e){this._model().finishLineTool(e)}pasteImageAsLineTool(e,t,i,s){const o=this._model().timeScale(),r=o.width(),a=i.height(),l=i.defaultPriceScale(),c=(0,n.ensureNotNull)((0,n.ensureNotNull)(l.mainSource()).firstValue()),h={price:l.coordinateToPrice(a/2,c),index:o.coordinateToIndex(r/2)},d=(0,S.createLineToolProperties)("LineToolImage",void 0,this.model());void 0!==s&&d.childs().transparency.setValue(s);const u=(0,n.ensureNotNull)(l.mainSource());(0,S.prepareLineToolPropertiesByOwnerSource)(d,u);const _=this.createLineTool({pane:i,point:h,linetool:"LineToolImage",properties:d});return _&&(_.setBlobImageUrl(t),this.selectionMacro((e=>{e.clearSelection(),e.addSourceToSelection(_,null)})),e.then((e=>{_.properties().childs().url.setValue(e)})).catch((e=>{const t=_.linkKey().value(),i=this.model();null!==t&&(0,Ye.removeLineTool)({withUndo:!1,model:i,linkKey:t,symbol:_.symbol(),sourceTitle:new T.TranslatedString(_.name(),_.translatedType()),lineToolState:_.state(!1)}),i.removeSource(_)}))),_}loadRange(e){const t=this._model(),i=t.mainSeries().getSupportedResolution(e.res),s={val:e.val,res:i},o=t.appliedTimeFrame().value();return(null===o||!_(o,s))&&(this._pushUndoCommand(new Ve(t,s)),!0)}unlinkLines(e){const t=this.model();this.beginUndoMacro(ss,qe.lineToolsDoNotAffectChartInvalidation);for(const i of e)null!==i.linkKey().value()&&(0,Ye.removeLineTool)({withUndo:!0,model:this.model(), symbol:i.symbol(),linkKey:(0,n.ensureNotNull)(i.linkKey().value()),sourceTitle:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,i),lineToolState:i.state(!1),unlink:!0}),this._pushUndoCommand(new ni(t,i));this.endUndoMacro()}zoomFromViewport(){const e=new oi((0,n.ensureDefined)(this._zoomStack.head()),this._zoomStack,!1);this._pushUndoCommand(e)}zoomToViewport(e,t,i,s,o){const r=new ti(this.m_model,e,t,i,s,o),n=new oi(r,this._zoomStack,!0);this._pushUndoCommand(n)}zoomStack(){return this._zoomStack}hoveredSource(){return this.m_model.hoveredSource()}setProperty(e,t,i,s){if(e&&e.value()!==t){this.beginUndoMacro(i);const o=new Be(e,t,i,this.m_model,s);this._pushUndoCommand(o),this.endUndoMacro(),this.emitEvent("setProperty")}}withMacro(e,t,i){const s=this.beginUndoMacro(e,i);try{t()}finally{this.endUndoMacro()}return s}barsMarksSources(){return this.m_model.barsMarksSources()}removeAllDrawingTools(){this.beginUndoMacro(Ls,!0),this._removeAllDrawingToolsImpl(),this.endUndoMacro()}removeAllStudiesAndDrawingTools(){this.beginUndoMacro(ks),this._removeAllDrawingToolsImpl(),this._removeAllStudiesImpl(),this.endUndoMacro()}removeAllStudies(){this.beginUndoMacro(As),this._removeAllStudiesImpl(),this.endUndoMacro()}scrollChartByBar(e){if(!this.m_model.scrollEnabled())return;const t=e*this.m_model.timeScale().barSpacing();this.startScrollTime(0),this.scrollTimeTo(t),this.endScrollTime()}canZoomIn(){return this.model().canZoomIn()}canZoomOut(){return this.model().canZoomOut()}zoomOut(){const e=this.timeScale().width();if(this.canZoomOut()){try{this.beginUndoMacro(os)}catch(e){return}(0,v.doAnimate)({to:e/5,onStep:e=>{this.startScaleTime(0),this.scaleTimeTo(e),this.endScaleTime()},onComplete:()=>this.endUndoMacro()})}}zoomIn(){const e=this.timeScale().width();if(this.canZoomIn()){try{this.beginUndoMacro(rs)}catch(e){return}(0,v.doAnimate)({to:e/5,onStep:e=>{this.startScaleTime(e),this.scaleTimeTo(0),this.endScaleTime()},onComplete:()=>this.endUndoMacro()})}}startMovingSources(e,t,i,s){e.filter((e=>e.doesMovingAffectsUndo())).length&&(this._currentSourceMoveCommand=new F(this.model(),e,ns,!1),e.every(S.isLineTool)&&this._currentSourceMoveCommand.setCustomFlag("doesnt_affect_save",qe.lineToolsDoNotAffectChartInvalidation)),this.model().startMovingSources(e,t,i,new Map,s)}moveSources(e,t){this.model().moveSources(e,new Map,t)}endMovingSource(e,t){this.model().endMovingSources(e,void 0,t),null!==this._currentSourceMoveCommand&&(this._currentSourceMoveCommand.saveNewState(),this._pushUndoCommand(this._currentSourceMoveCommand)),this._currentSourceMoveCommand=null}startChangingLinetool(e,t,i,s,o){this._currentLineChangeCommand=new F(this.model(),[e],Ms.format({pointIndex:i}),!1),this._currentLineChangeCommand.setCustomFlag("doesnt_affect_save",qe.lineToolsDoNotAffectChartInvalidation),this.model().startChangingLinetool(e,t,i,s,o)}changeLinePoint(e,t){this.model().changeLinePoint(e,t)}endChangingLinetool(e){this.model().endChangingLinetool(e), null!==this._currentLineChangeCommand&&(this._currentLineChangeCommand.saveNewState(),this._pushUndoCommand(this._currentLineChangeCommand)),this._currentLineChangeCommand=null}setChartStyleProperty(e,t,i){if(e.value()!==t){const s=Jt.chartStylePermissions.get(t),o=()=>{this.beginUndoMacro(i);const s=new Re(e,t,this.mainSeries(),i,this.model(),this.chartWidget());this._pushUndoCommand(s),this.emitEvent("setChartStyleProperty"),(0,Me.trackChartStyleChanged)(e.value()),this.endUndoMacro()};s?(0,Qt.runOrGoPro)(o,s.feature,{feature:s.featureName}):o()}}restorePropertiesForSource(e){(0,S.isLineTool)(e)?this._restoreLineToolFactoryDefaults(e):this._restoreStudyFactoryDefaults(e)}restoreLineToolsFactoryDefaults(e){1===e.length?this._restoreLineToolFactoryDefaults(e[0]):(this.beginUndoMacro(ls),e.forEach((e=>this._restoreLineToolFactoryDefaults(e))),this.endUndoMacro())}restoreState(e,t,i){return this.m_model.restoreState(e,t,i)}async clipboardCopy(e,t=this.selection().dataSources()){if(!(0,y.enabled)("datasource_copypaste"))return;const i=t.filter((e=>e.copiable()));if(0===i.length)return;for(const e of i)if((0,w.isStudy)(e)&&e.isChildStudy())throw new Error("Can not copy child study");const s=(0,g.clipboardDataForSources)(this._model().id(),i);return null!==s?e.write({app:JSON.stringify(s),text:s.title}):void 0}async clipboardCut(e,t=this.selection().dataSources()){if(!(0,y.enabled)("datasource_copypaste"))return;const i=t.filter((e=>e.copiable()));if(0===i.length)return;await this.clipboardCopy(e,i);const s=i.filter((e=>e.isUserDeletable()));if(0===s.length)return;const o=(1===s.length?Ji:Qi).format({title:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,s[0])});this.beginUndoMacro(o),this.m_model.selectionMacro((()=>this.removeSources(s,!1,o)),!0),this.endUndoMacro()}async clipboardPaste(e,t){let i=null;if((0,y.enabled)("datasource_copypaste")&&(i=i||await e.read(),i.app)){const e=JSON.parse(i.app);if(null!==await this.pasteSourceFromClip(t,e))return}await this._processSpecialLineToolsContents(e,i,t)}applyStudyTemplate(e,t){const i=new ut(this._model(),e,t);this._pushUndoCommand(i),(0,qi.emit)("load_study_template")}createStudyInserter(e,t,i={}){const{stubTitle:s,isOverlay:o}=i,r={createStudy:(e,t,i,s,o,r,n,a,l,c,h)=>this.checkIfFeatureAvailable(e,r)?((0,f.trackEvent)("studies","Study_"+e.id),"Compare@tv-basicstudies"===e.id&&(0,f.trackEvent)("compare","symbol:"+t.symbol),this._insertStudy(e,t,s,o,r,n,a,l,c,null,h)):(Rs.logNormal("Cannot insert study "+e.id),null)};void 0!==s&&(r.createStub=()=>this.m_model.insertStudyStub(s,o).id(),r.removeStub=e=>this.m_model.removeStudyStub(e));const n=new Gi.StudyInserter(e,r);return n.setParentSources(t),n}replayStatus(){return this.m_model.replayStatus()}setReplayStatus(e){return this.m_model.setReplayStatus(e)}getSymbolString(){return this.m_model.getSymbolString()}interval(){return this.m_model.interval()}async canChangeResolution(e){return this.model().canChangeResolution(e)}startCustomMoving(e,t,i){this._currentCustomMoveCommand=new Et(this.model(),e,t,i)} customMoveBeingProcessed(){return null!==this._currentCustomMoveCommand}processCustomMove(e){(0,n.ensureNotNull)(this._currentCustomMoveCommand).move(e)}endCustomMoving(){null!==this._currentCustomMoveCommand&&this._currentCustomMoveCommand.hasChanges()&&(this._pushUndoCommand(this._currentCustomMoveCommand),this._currentCustomMoveCommand=null)}panes(){return this.m_model.panes()}cloneLineTools(e,t){for(let t=0;t(0,n.ensureNotNull)(this.model().dataSourceForId(e)))).filter((e=>0!==e.sharingMode().value()));return s.length&&this._model().copyToOtherCharts(s,!0),this.endUndoMacro(),this.emitEvent("cloneLineTools"),i.newIds()}removeSource(e,t,i){this.lineBeingCreated()!==e?this.removeSources([e],t,es.format({title:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,e)}),i):this.cancelCreatingLine()}removeSelectedSources(){const e=this._model().selection().dataSources();if(!e.length)return;const t=(e.length>1?ts:es).format({title:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,e[0])});this.removeSources(e,!1,t)}removeSources(e,t,i,s){s||(e=e.filter((e=>e.isUserDeletable())));const o=this._model(),r=o.lineToolsGroupModel(),a=e.every(S.isLineTool)&&qe.lineToolsDoNotAffectChartInvalidation;this.beginUndoMacro(i,a),o.selectionMacro((s=>{const a=new Map;e.forEach((e=>{if((0,S.isLineTool)(e)){const t=r.groupForLineTool(e);if(null!==t){const i=a.get(t)||[];i.push(e),a.set(t,i)}null!==e.linkKey().value()&&(0,Ye.removeLineTool)({withUndo:!0,model:this.model(),linkKey:(0,n.ensureNotNull)(e.linkKey().value()),symbol:this.model().mainSeries().symbol(),lineToolState:e.state(!1),sourceTitle:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,e)})}}));const l=new V.RemoveSourcesUndoCommand(o,e,i),c=l.removedIds();this._pushUndoCommand(l),!t&&c.length>0&&(1===c.length?this.emitEvent("removeSource",[c[0]]):this.emitEvent("removeSources",[c]))}),!0),this.endUndoMacro()}removeUnloadedLineTool({sourceTitle:e,linkKey:t,symbol:i,state:s,withUndo:o,unlink:r}){const n=new Zt({undoText:es.format({title:e}),chartModel:this._model(),linkKey:t,symbol:i,state:s,unlink:r});o?this._pushUndoCommand(n):n.redo()}async scrollToLineTool(e){const t=this.timeScale().logicalRange();if(null===t)return;const i=e.points().map((e=>e.index)),s=this.timeScale().points().range().value();if(null===s)return;let o=s.firstIndex;const r=s.lastIndex,a=t.length()/2;if(0===i.length||i.some((e=>t.contains(e))))return;const l=()=>{const t=e.points().map((e=>e.index)),i=t.filter((e=>e<=r)).reduce(((e,t)=>null===e?t:Math.max(e,t)),null);return null!==i?i:t.reduce(((e,t)=>Math.min(e,t)))};let h=l();if(o-a>h){const t=e.points().map((e=>e.time)).filter(E.notUndefined).map((e=>e.valueOf()));if(0===t.length)return;const i=t.reduce(((e,t)=>Math.min(e,t)),t[0]);await this.model().gotoTime(i),h=l();if((0, n.ensureNotNull)(this.timeScale().logicalRange()).contains(h))return;o=(0,n.ensureNotNull)(this.timeScale().points().range().value()).firstIndex}o-a>h&&this.mainSeries().setGotoDateResult({timestamp:(0,n.ensureNotNull)(this.timeScale().points().valueAt(o)),eod:!0});const d=this.timeScale().width()/2,u=this.timeScale().indexToCoordinate(h);this.model().stopTimeScaleAnimation(),this.model().setTimeScaleAnimation(new m.Animation({from:0,to:d-u,duration:c.dur,easing:c.easingFunc.easeInOutCubic}))}mergeSourceUp(e){const t=new Y(this._model(),e,us);this._mergeUnmergeSource(e,t)}mergeSourceDown(e){const t=new K(this._model(),e,_s);this._mergeUnmergeSource(e,t)}mergeToPane(e,t,i){const s=this._model().panes().indexOf(t),o=new Z(this._model(),e,s,ps,i);this._mergeUnmergeSource(e,o)}unmergeSourceUp(e){const t=new G(this._model(),e,ms);this._mergeUnmergeSource(e,t)}unmergeSourceDown(e){const t=new U(this._model(),e,gs);this._mergeUnmergeSource(e,t)}unmergeToNewBottomPane(e){const t=new q(this._model(),e,Ss);this._mergeUnmergeSource(e,t)}availableZOrderOperations(e){const t=this._model().lineToolsGroupModel(),i=e.filter(S.isLineTool),s=i.map((e=>t.groupForLineTool(e)));(0,n.assert)(new Set(s).size<=1,"Cannot move line tools from different group");const o=0===s.length?null:s[0];let r={bringForwardEnabled:!1,bringToFrontEnabled:!1,sendBackwardEnabled:!1,sendToBackEnabled:!1};const a=new Set(i);for(const t of(0,$.sortSources)(e)){if((0,S.isLineTool)(t)&&null!==o){const e=(0,$.sortSources)(o.lineTools().filter((e=>!a.has(e)||e===t)));r=Vs(r,{bringForwardEnabled:t!==e[e.length-1],bringToFrontEnabled:t!==e[e.length-1],sendBackwardEnabled:t!==e[0],sendToBackEnabled:t!==e[0]});continue}const e=(0,n.ensureNotNull)(this._model().paneForSource(t)).sourcesByGroup().allExceptSpecialSources();if(0===e.length)continue;const i=t.zorder(),s=e[0].zorder(),l=e[e.length-1].zorder();r=Vs(r,{bringForwardEnabled:i!==l,bringToFrontEnabled:i!==l,sendBackwardEnabled:i!==s,sendToBackEnabled:i!==s})}return r}sendToBack(e){if(!this.availableZOrderOperations(e).sendToBackEnabled)throw new Error("Send to back operation is unavailable");let t=null;const i=e[0];if((0,S.isLineTool)(i)){const s=this._model().lineToolsGroupModel().groupForLineTool(i);if(null!==s){const i=s.lineTools();t=new me(this.model(),(0,$.sortSources)(e),i[0])}}null===t&&(t=new de(this.model(),(0,$.sortSources)(e))),this._pushUndoCommand(t),this.emitEvent("changeZOrder",[e])}bringToFront(e){if(!this.availableZOrderOperations(e).bringToFrontEnabled)throw new Error("Bring to front operation is unavailable");let t=null;const i=e[0];if((0,S.isLineTool)(i)){const s=this._model().lineToolsGroupModel().groupForLineTool(i);if(null!==s){const i=s.lineTools();t=new _e(this.model(),(0,$.sortSources)(e),i[i.length-1])}}null===t&&(t=new he(this.model(),(0,$.sortSources)(e))),this._pushUndoCommand(t),this.emitEvent("changeZOrder",[e])}sendBackward(e){if(!this.availableZOrderOperations(e).sendBackwardEnabled)throw new Error("Send backward operation is unavailable");const t=Ki.format({title:(0, X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,e[0])});this._sendBackOrBringForward(t,(0,$.sortSources)(e),((e,t)=>new Se(this.model(),e,t)))}bringForward(e){if(!this.availableZOrderOperations(e).bringForwardEnabled)throw new Error("Bring forward operation is unavailable");const t=Zi.format({title:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,e[0])});this._sendBackOrBringForward(t,(0,$.sortSources)(e),((e,t)=>new fe(this.model(),e,t)))}insertAfter(e,t){e=(0,$.sortSources)(e);const i=$i.format({title:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,e[0]),target:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,t)});this._insertAfterOrBefore(i,e,t,(()=>new _e(this.model(),e,t)))}insertBefore(e,t){e=(0,$.sortSources)(e);const i=Xi.format({title:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,e[0]),target:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,t)});this._insertAfterOrBefore(i,e,t,(()=>new me(this.model(),e,t)))}detachToRight(e,t){(0,f.trackEvent)("Chart","Move to new right scale");const i=vs.format({title:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,e)}),s=new bt(this.model(),e,t,"right",i);this._pushUndoCommand(s),this.emitEvent("moveSource",[e])}detachToLeft(e,t){(0,f.trackEvent)("Chart","Move to new left scale");const i=fs.format({title:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,e)}),s=new bt(this.model(),e,t,"left",i);this._pushUndoCommand(s),this.emitEvent("moveSource",[e])}detachNoScale(e,t){(0,f.trackEvent)("Chart","Make source no scale");const i=bs.format({title:(0,X.getTranslatedStringForSource)(Q.TitleDisplayTarget.StatusLine,e)}),s=new bt(this.model(),e,t,"overlay",i);this._pushUndoCommand(s),this.emitEvent("moveSource",[e])}moveToScale(e,t,i,s,o){(0,f.trackEvent)("Chart","Move source to target scale"),this.beginUndoMacro(s);const r=new yt(this.model(),e,t,i,s),n=o?null:(0,b.sourceNewCurrencyOnPinningToPriceScale)(e,i,this._model()),a=o?null:(0,zt.sourceNewUnitOnPinningToPriceScale)(e,i,this._model());this._pushUndoCommand(r),null!==n&&this.setPriceScaleCurrency(i,n),null!==a&&this.setPriceScaleUnit(i,a),this.endUndoMacro(),this.emitEvent("moveSource",[e])}setLinkingGroupIndex(e){this._undoHistory.beginUndoMacro(Bs),this._pushUndoCommand(new Ui(this.model().linkingGroupIndex(),e,Bs)),this._model().setShouldBeSavedEvenIfHidden(!0),this._undoHistory.endUndoMacro()}startScrollTime(e){const t=this.timeScale();this._initialTimeScrollState={rightOffset:t.rightOffset(),barSpacing:t.barSpacing()},this._initialTimeScrollPos=e,this.model().startScrollTime(e)}scrollTimeTo(e){null!==this._initialTimeScrollPos&&null!==this._initialTimeScrollState&&Math.abs(e-this._initialTimeScrollPos)>20&&(this._pushUndoCommand(new Te.TimeScaleChangeUndoCommand(this.model(),this._initialTimeScrollState,ys)),this._initialTimeScrollPos=null,this._initialTimeScrollState=null),this.model().scrollTimeTo(e)}endScrollTime(){this.model().endScrollTime(), this._initialTimeScrollPos=null,this._initialTimeScrollState=null}startScaleTime(e){this.changeTimeScale(Cs),this.model().startScaleTime(e)}scaleTimeTo(e){this.model().scaleTimeTo(e)}endScaleTime(){this.model().endScaleTime()}resetTimeScale(){this.changeTimeScale(ws),this.model().resetTimeScale()}changeTimeScale(e){const t=this.timeScale(),i={rightOffset:t.rightOffset(),barSpacing:t.barSpacing()};this._pushUndoCommand(new Te.TimeScaleChangeUndoCommand(this.model(),i,e))}startScalePrice(e,t,i,s){this._scalePriceInfo={priceScaleState:t.state(),tryMergeConsecutiveScales:s},this.model().startScalePrice(e,t,i)}scalePriceTo(e,t,i){this.model().scalePriceTo(e,t,i)}endScalePrice(e,t){this.model().endScalePrice(e,t);const i=(0,n.ensureNotNull)(this._scalePriceInfo);(0,r.default)(i.priceScaleState,t.state())||this._pushUndoCommand(new Ut.PriceScaleChangeUndoCommand(this.model(),e,t,i.priceScaleState,i.tryMergeConsecutiveScales)),this._scalePriceInfo=null}startTwoPointsScalePrice(e,t,i,s,o){this._scalePriceInfo={priceScaleState:t.state(),tryMergeConsecutiveScales:o},this.model().startTwoPointsScalePrice(e,t,i,s)}twoPointsScalePriceTo(e,t,i,s){this.model().twoPointsScalePriceTo(e,t,i,s)}endTwoPointsScalePrice(e,t){this.model().endTwoPointsScalePrice(e,t);const i=(0,n.ensureNotNull)(this._scalePriceInfo);(0,r.default)(i.priceScaleState,t.state())||this._pushUndoCommand(new Ut.PriceScaleChangeUndoCommand(this.model(),e,t,i.priceScaleState,i.tryMergeConsecutiveScales)),this._scalePriceInfo=null}resetPriceScale(e,t){const i=t.state();this.model().resetPriceScale(e,t),(0,r.default)(i,t.state())||this._pushUndoCommand(new Ut.PriceScaleChangeUndoCommand(this.m_model,e,t,i))}rearrangePanes(e,t){const i=new Pe(this._model(),e,t);this._pushUndoCommand(i)}movePane(e,t){const i=new Pe(this._model(),e,t);this._pushUndoCommand(i)}toggleCollapsedPane(e){const t=this.panes().findIndex((t=>t===e));t<0||this._pushUndoCommand(new x(this._model(),t))}readOnly(){return this.m_model.readOnly()}checkIfFeatureAvailable(e,t){const i=t.length>0,s=(0,Xt.isFundamentalStudyMetaInfo)(e),o=this.canCreateStudy({id:e.id,child:i,fundamental:s});return!!o.success||(Hs(this.model(),o),!1)}async pasteSourceFromClip(e,t,i){const s=t;if(!s||0===s.sources.length)return null;const o=e||(0,n.ensureNotNull)(this.model().paneForSource(this.mainSeries()));if(!s.sources.some((e=>"drawing"!==e.type||null!==o.clipboardLineToolOwnerSource(e.source.id))))return null;const r=Array.from(new Set(s.sources.filter(g.isLineToolClipboardData).map((e=>e.source.type))));await Promise.all(r.map((e=>(0,S.initLineTool)(e)))),this.beginUndoMacro(xs.format({title:s.title}));let a=0;const l=[],c=[];for(const t of s.sources)if("drawing"===t.type&&null!==o.clipboardLineToolOwnerSource(t.source.id)){const e=this.pasteLineTool(o,t);a<5&&((0,Me.trackDrawingPasted)(e),a+=1),c.push(e),l.push(e)}else"study"===t.type&&t.source&&t.source.metaInfo&&this.checkIfFeatureAvailable(new h.StudyMetaInfo(t.source.metaInfo),[])&&l.push(this.pasteStudy(t,i?e:void 0));return c.length&&this.selectionMacro((e=>{ e.clearSelection(),c.forEach((t=>{e.addSourceToSelection(t,null)}))})),this.endUndoMacro(),l}pasteLineTool(e,t,i,s){t.source.state.intervalsVisibilities=(0,mi.mergeIntervalVisibilitiesDefaults)(t.source.state.intervalsVisibilities),(0,mi.makeIntervalsVisibilitiesVisibleAtInterval)(t.source.state.intervalsVisibilities,u.Interval.parse(this.model().mainSeries().interval()));const o=new gt(this.model(),t,e,i,s);this._pushUndoCommand(o);const r=o.source();return o.needCopyToOtherCharts()&&this._model().copyToOtherCharts([r],!0),this.selectionMacro((e=>{e.clearSelection(),e.addSourceToSelection(r,null)})),r}pasteStudy(e,t){const i=new It(this.model(),e,null==t?void 0:t.id());this._pushUndoCommand(i);const s=(0,n.ensureNotNull)(i.state()).id;return(0,qi.emit)("study_event",s,"paste_study"),(0,n.ensureNotNull)(this._model().dataSourceForId(s))}setPriceScaleCurrency(e,t){const i=new St(e,t,this.chartWidget(),cs);this._pushUndoCommand(i)}setPriceScaleUnit(e,t){const i=new vt(e,t,this.chartWidget(),hs);this._pushUndoCommand(i)}setSymbol(e,t){e.symbolSameAsResolved(t)||this._pushUndoCommand(new Tt(e,t,this.chartWidget()))}setResolution(e,t){e===this.mainSeries()&&(t=e.getSupportedResolution(t)),u.Interval.isEqual(e.interval(),t)||this._pushUndoCommand(new Hi(e,t,this.chartWidget()))}chartLoadTheme(e,t,i){const s=new Wi(this.model(),e,t);i?s.redo():this._pushUndoCommand(s)}isJustClonedChart(){return this._chartWidget.isJustClonedChart()}isMultipleLayout(){return this._chartWidget.isMultipleLayout()}addPaneStretchFactorUndoCommand(e,t,i,s){const o=new At(this.model(),e,t,i,s);this._pushUndoCommand(o)}paneForSource(e){return this.m_model.paneForSource(e)}destroy(){this.m_model.destroy()}moveSelectedToolsLeft(){return this._moveSelectedTools(2)}moveSelectedToolsUp(){return this._moveSelectedTools(0)}moveSelectedToolsRight(){return this._moveSelectedTools(3)}moveSelectedToolsDown(){return this._moveSelectedTools(1)}insertStudyWithoutCheck(e,t,i,s){return this._insertStudy(e,t,{},!1,[],void 0,void 0,void 0,void 0,null!=i?i:null,void 0,s)}saveLineToolState(e,t){this._pushUndoCommand(new F(this.m_model,[e],t))}resetScales(){this._model().stopTimeScaleAnimation(),this.beginUndoMacro(Ps),this.resetTimeScale();for(const e of this.m_model.panes()){for(const t of e.leftPriceScales())this.resetPriceScale(e,t);for(const t of e.rightPriceScales())this.resetPriceScale(e,t)}this.endUndoMacro(),this.m_model.recalculateAllPanes((0,ke.viewportChangeEvent)())}shareLineTools(e,t){const i=0===t?Es:1===t?Ds:Ns;this.withMacro(i,(()=>{0===t&&this.unlinkLines(e),e.forEach((i=>{const s=this.model().lineToolsGroupModel().groupForLineTool(i);if(s){s.lineTools().every((t=>e.includes(t)))||this.lineToolsGroupController().excludeLineToolFromGroup(s,i)}this.undoHistory().pushUndoCommand(new Ze(i,t,this.model(),null))}))}),!0)}canCreateStudy(e,t){return this.model().chartApi().canCreateStudy(e,t)}studiesMetaData(){return this.m_model.studiesMetaData()}chartWidgetCollectionLock(){return this._chartWidget.chartWidgetCollection().lock}_mergeUnmergeSource(e,t){ this.beginUndoMacro(t.text());const i=(0,n.ensureNotNull)(this._model().paneForSource(e)),s=new Set(i.sourcesByGroup().lineSources().filter((t=>t.ownerSource()===e)));this._model().lineToolsGroupModel().groups().filter((e=>{const t=e.lineTools().some((e=>s.has(e))),i=e.lineTools().some((e=>!s.has(e)));return t&&i})).forEach((e=>{this._pushUndoCommand(new W.ExcludeLineToolsFromGroupUndoCommand(this._model(),e,e.lineTools()))})),this._pushUndoCommand(t),this.endUndoMacro()}_insertStudy(e,t,i,s,o,r,a,l,c,h,d,u){const _=Is.format({title:e.description});this.beginUndoMacro(_);const p=new Ot(this.model(),e,t,i,s,o,r,a,l,c,h||null,u,_);this._pushUndoCommand(p);const m=p.insertedStudy();if(void 0!==d){const e=new Vt.SetPriceScaleModeCommand(d,(0,n.ensureNotNull)(m.priceScale()),null,this.model());this._pushUndoCommand(e)}return this.endUndoMacro(),{study:m,startPromise:p.lastInsertionStartPromise()}}async _processSpecialLineToolsContents(e,t,i){if(t=t||await e.read(),window.user.id&&t.files){const e=Array.from(t.files).find(Yt.blobImageFilter);if(e){const t=URL.createObjectURL(e),s=(0,Yt.uploadImage)(e);return void 0===i&&(i=(0,n.ensureNotNull)(this._model().paneForSource(this.mainSeries()))),this.pasteImageAsLineTool(s,t,i),void await s}}t.text&&(window.user.id&&!Os&&(0,Gt.isTwitterUrl)(t.text)?(0,Gt.createTweetLineToolByUrl)(t.text,this,!0):window.user.id&&(0,$t.isIdeaUrl)(t.text)?(0,$t.createIdeaLineToolByUrl)(t.text,this,!0):function(e,t){if(null===t.timeScale().logicalRange())return null;const i=t.mainSeries(),s=i.priceScale(),o=t.timeScale(),r=(0,n.ensureNotNull)(t.model().paneForSource(i)),a=(0,n.ensureNotNull)((0,n.ensureNotNull)(s.mainSource()).firstValue()),l=o.coordinateToIndex(t.timeScale().width()/2),c=r.height()/2,h={price:s.coordinateToPrice(c,a),time_t:(0,n.ensureNotNull)(o.indexToTimePoint(l)),offset:0},d=r.newLineToolZOrder(!0),u=jt.LineToolText.createProperties().state();u.text=e,u.interval=i.interval();const _={type:"drawing",source:{id:(0,Ke.randomHashN)(6),zorder:d,type:"LineToolText",state:u,symbol:i.symbol(),ownerSource:i.id(),points:[h]},geometry:[],modelId:t.model().id(),centeredOnChart:!0},p=t.pasteLineTool(r,_,!1,!1);qt.setValue("hint.pasteText",!0,{forceFlush:!0})}(t.text,this))}_insertAfterOrBefore(e,t,i,s){const o=(0,n.ensureNotNull)(this._model().paneForSource(i));if(t.some((e=>(0,S.isLineTool)(e)&&this._model().paneForSource(e)!==o)))throw new Error("Cannot insert line tool after target on another pane");this.beginUndoMacro(e),t.forEach((e=>{(0,n.ensureNotNull)(this.model().paneForSource(e))!==o&&this.mergeToPane(e,o)}));const r=s();this._pushUndoCommand(r),this.emitEvent("changeZOrder",[t]),this.endUndoMacro()}_sendBackOrBringForward(e,t,i){const s=new Map;t.forEach((e=>{const t=(0,n.ensureNotNull)(this._model().paneForSource(e)),i=s.get(t)||[];i.push(e),s.set(t,i)})),this.beginUndoMacro(e),s.forEach(((e,t)=>{this._pushUndoCommand(i(t,e))})),this.endUndoMacro(),this.emitEvent("changeZOrder",[t])}_moveSelectedTools(e){const t=this.model().selection().lineDataSources();if(0===t.length)return!1 ;if((0,Ye.lockDrawings)().value())return!0;const i=this.timeScale().visibleBarsStrictRange();if(null===i)return!1;const s=function(e){const t=new Map;for(const i of e){const e=i.ownerSource();if(null===e)continue;let s=t.get(e);if(void 0===s){const o=e.priceScale(),r=e.priceStep(),n=e.firstValue();if(null===o||null===r||null===n)continue;if(null===o.priceRange())continue;s={sources:[],priceScale:o,priceStep:r,startPrice:i.points()[0].price,firstValue:n},t.set(e,s)}s.sources.push(i)}return t}(t);if(0===s.size)return!1;this.beginUndoMacro(ns,qe.lineToolsDoNotAffectChartInvalidation);const o=i.firstBar(),r=this.timeScale().indexToCoordinate(o),n=o+(3===e?1:2===e?-1:0),l=this.timeScale().indexToCoordinate(n);return Ye.isDirectionalMovementActive.setValue(!0),s.forEach((t=>{const{startPrice:i,priceStep:s,priceScale:c,firstValue:h}=t,d=i+(0===e?s:1===e?-s:0),u=c.priceToCoordinate(i,h),_=c.priceToCoordinate(d,h),p={logical:{index:o,price:i},screen:new a.Point(r,u)},m={logical:{index:n,price:d},screen:new a.Point(l,_)};this.startMovingSources(t.sources,p,null),this.moveSources(m),this.endMovingSource(!1,!0)})),Ye.isDirectionalMovementActive.setValue(!1),this.endUndoMacro(),!0}_restoreStudyFactoryDefaults(e){const t=new pi(this.m_model,e);this._pushUndoCommand(t)}_restoreLineToolFactoryDefaults(e){this.beginUndoMacro(as,qe.lineToolsDoNotAffectChartInvalidation),this.saveLineToolState(e,as);const t=new hi(this.m_model,e.properties(),as);this._pushUndoCommand(t),this.saveLineToolState(e,as),this.endUndoMacro(),this.model().updateSource(e)}_removeAllDrawingToolsImpl(e){this.selectionMacro((()=>{this.lineBeingCreated()&&this.cancelCreatingLine();this.dataSources().filter(S.isLineTool).filter((e=>e.isActualSymbol()&&e.isUserDeletable())).filter((t=>!e||e===t.toolname)).forEach((e=>this.removeSource(e,!1)))}),!0)}_removeAllStudiesImpl(){const e=this.dataSources(),t=e.filter(w.isStudy).filter((e=>!e.isChildStudy()&&e.removeByRemoveAllStudies())),i=e.filter(w.isStudyStub);t.concat(i).forEach((e=>this.removeSource(e,!1)))}}},607113:(e,t,i)=>{"use strict";var s=i(650151).assert,o=i(23612).ChartModelBase,r=i(713473).isLineTool,n=i(767359).Watermark,a=i(638456).CheckMobile,l=i(572230).InvalidationLevel;i(707957).Delegate;const{globalChangeEvent:c,sourceChangeEvent:h}=i(964824);var d=i(427937).isStudy,u=i(885482),_=i(220843).MainSeriesScaleRatioProperty,p=i(915179).scaleRatio,m=i(849245).StudyInserter,g=i(992543).dateFormatProperty,S=i(827023).timeHoursFormatProperty,v=i(251954),f=i(65541).StudyColorRotatorFactory,b=i(244842),y=i(108039).AppliedTimeFrame,C=b.enabled("fix_left_edge");class w extends o{constructor(e,t,i,s,o,r,a,l,c,h){super(e,t,i,s,o,r,a,l,c,h);var d=this;this._mainSeriesScaleRatioProperty=new _(this),this.m_mainSeries.dataEvents().completed().subscribe(this,function(){if(this._scrollingState&&this.gotoTime(),C&&!this.m_mainSeries.requestMoreDataAvailable()){var e=this.m_mainSeries.bars().first();null!==e&&this._timeScale.setLeftEdgeFix(e.index)}}.bind(this)),this.m_mainSeries.onIntervalChanged().subscribe(this,(function(){ this._recalcVRStudiesParams.oldStartVisibleIndex=NaN,this._recalcVRStudiesParams.oldEndVisibleIndex=NaN})),this.m_mainSeries.dataEvents().barReceived().subscribe(this,w.prototype.updateTimeScaleBaseIndex),this._readOnly||(this.m_mainSeries.properties().addChild("priceAxisProperties",this.m_mainSeries.priceScale().properties()),this._properties.paneProperties.legendProperties.showStudyTitles.listeners().subscribe(this,(function(e){e.value()||d._properties.paneProperties.legendProperties.showStudyArguments.setValue(!1)}))),this._watermarkSource=this._options.watermarkEnabled?new n(this,this.m_mainSeries):null,u.hideAllDrawings().subscribe(this,this._onDrawingsVisibilityChanged),u.hideAllIndicators().subscribe(this,this._onIndicatorsVisibilityChanged),this._properties.scalesProperties.listeners().subscribe(this,w.prototype.fullUpdate),this._studyShiftColorStartOffset=void 0,g.subscribe(this,this._updateDateTimeFormatter),S.subscribe(this,this._updateDateTimeFormatter),this.mainSeries().properties().interval.subscribe(this,this._updateDateTimeFormatter),this._updateDateTimeFormatter(),this._studyColorRotatorFactory=new f(this),this._undoModel._chartWidget.onWidget()||this._initAlertsList(),this._dataSourceCollectionChanged.subscribe(this,this._updateShowLegendProperty.bind(this)),this._properties.paneProperties.legendProperties.showLegend.subscribe(this,this._updateShowLegendProperty),this._appliedTimeFrame=new y(this),this.mainSeries().onTimeFrameApplied().subscribe(this,(function(e){var t=null!==e?{res:this.mainSeries().interval(),val:e}:null;this.appliedTimeFrame().setValue(t)}))}applyPreferences(e){for(var t in e)void 0!==this._properties[t]&&"m_mainSeries"!==this._properties[t]&&this._properties[t].mergeAndFire(e[t]);void 0!==e.timeScale&&(this._timeScale.defaultRightOffset().setValue(e.timeScale.defaultRightOffset),this._timeScale.defaultRightOffsetPercentage().setValue(e.timeScale.defaultRightOffsetPercentage),this._timeScale.usePercentageRightOffset().setValue(e.timeScale.usePercentageRightOffset)),this._properties.saveDefaults(),this.m_mainSeries.applyPreferences(e.mainSeries),this.sessions().applyPreferences(e.sessions),this.recalculateAllPanes(c()),this.fullUpdate()}timezone(){return this._properties.timezone.value()}initConnection(){this._chartApi.switchTimezone(this.timezone())}updatePane(e){var t=this._paneInvalidationMask(e);this.invalidate(t)}studiesMetaData(){return this._studiesMetaData}studyVersioning(){return this._studyVersioning}startNotStartedStudies(){if(!this.m_mainSeries.isStarted())throw new Error("Cannot start studies: main series is not started");for(var e=this.dataSources(),t=0;t0),r?{left:0,right:1,totallySlots:i}:{left:1,right:0,totallySlots:i}}return{left:e,right:t,totallySlots:e+t}}setPriceAutoScale(e,t,i){e.setPriceAutoScale(t,i),this.invalidate(this._paneInvalidationMask(e,l.Light))}updateScales(e,t){this._undoModel._chartWidget._updateScalesActions()}mainSeriesScaleRatioProperty(){return this._mainSeriesScaleRatioProperty}mainSeriesScaleRatioPropertyOnChanged(){this._mainSeriesScaleRatioProperty.listeners().fire(this._mainSeriesScaleRatioProperty)}mainSeriesScaleRatio(){return p(this._timeScale,this.m_mainSeries.priceScale())}setMainSeriesScaleRatio(e){this.paneForSource(this.m_mainSeries).applyPriceScaleRatio(this.m_mainSeries.priceScale(),e)}orderedDataSources(e){var t=[];t.push(this.m_crossHairSource);for(var i=0;ithis.removeSource(e))),Array.from(this._customSourcesMap.keys()).forEach(this._removeCustomSource,this),s(0===this._topmostCustomSources.length),s(0===this._fgCustomSources.length),s(0===this._bgCustomSources.length),s(0===this._allCustomSources.length),s(0===this._customSourcesMap.size);for(var e=0;e{"use strict";var s=i(809796).TranslatedString,o=i(764005).doAnimate,r=i(208697).ChartUndoModelBase,n=i(853965).saveDefaultProperties,a=i(142257).UndoCommand,l=i(376163).ApplyLineToolTemplateUndoCommand,c=i(796517).SetPriceScaleSelectionStrategyCommand,h=i(519231).SetScaleRatioPropertiesCommand,d=i(345848).trackEvent,u=i(727803).RestoreDefaultsPreferencesUndoCommand,_=i(209800).SetPriceScaleModeCommand,p=i(371764).PriceScaleChangeUndoCommand,m=i(155964).preferencesByWhiteList,g=new s("move left",i.tf(null,void 0,i(415086))),S=new s("move right",i.tf(null,void 0,i(461711))),v=new s("toggle auto scale",i.tf(null,void 0,i(863060))),f=new s("toggle lock scale",i.tf(null,void 0,i(121203))),b=new s("toggle regular scale",i.tf(null,void 0,i(733714))),y=new s("toggle indexed to 100 scale",i.tf(null,void 0,i(98860))),C=new s("toggle percentage scale",i.tf(null,void 0,i(568642))),w=new s("toggle log scale",i.tf(null,void 0,i(160166))),P=new s("invert scale",i.tf(null,void 0,i(794245))),T=new s("remove pane",i.tf(null,void 0,i(847637))),M=new s("apply all chart properties",i.tf(null,void 0,i(64034))),x=new s("set price scale selection strategy to {title}",i.tf(null,void 0,i(669485)));class I extends a{constructor(e,t){super(M),this._model=e,this._undoModel=e.undoModel(),this._newProperties=t,function(e,t){var i={hollowCandle:{related:"candle"}};for(var s in["candleStyle","hollowCandleStyle","haStyle"].forEach((function(t){e[t].wickUpColor=e[t].wickUpColor||e[t].wickColor,e[t].wickDownColor=e[t].wickDownColor||e[t].wickColor})),t.vertGridProperties=t.vertGridProperties||t.gridProperties,t.horzGridProperties=t.horzGridProperties||t.gridProperties,i)if(!e[s+"Style"]){var o=e[i[s].related+"Style"];e[s+"Style"]=TradingView.clone(o)}}(this._newProperties.mainSeries,this._newProperties.paneProperties),this._oldProperties=m(e,e.mainSeries())}_merge(e){n(!0),this._model.applyPreferences(e),n(!1)}redo(){this._merge(this._newProperties),this._model.mainSeries().onChartStyleChanged(),this._model.updateScales()}undo(){this._merge(this._oldProperties),this._model.mainSeries().onChartStyleChanged(),this._model.updateScales()}}t.ChartUndoModel=class extends r{constructor(e,t,i,s,o,r,n,a,l,c,h){super(e,t,i,s,o,r,n,a,l,c,h),this.beginUndoMacro=(e,t)=>{var i=r.beginUndoMacro(e);return i.setCustomFlag("doesnt_affect_save",t),i},this.endUndoMacro=r.endUndoMacro.bind(r),this.createUndoCheckpoint=r.createUndoCheckpoint.bind(r),this.undoToCheckpoint=r.undoToCheckpoint.bind(r)}version(){return this.m_model.version()}createPane(e){return this.m_model.createPane(e)}restart(){this.m_model.restart()}disconnect(){this.m_model.disconnect()}studyVersioning(){return this.m_model.studyVersioning()}chartModel(){return this._model()}_model(){return this.m_model}pushUndoCommand(e){this._pushUndoCommand(e)}_pushUndoCommand(e){this._undoHistory.pushUndoCommand(e)}startScrollPrice(e,t,i){t.isAutoScale()||(this._initialPriceScrollState=t.state(),this._initialPriceScrollPos=i, this.chartModel().startScrollPrice(e,t,i))}scrollPriceTo(e,t,i){t.isAutoScale()||(this._initialPriceScrollPos&&Math.abs(this._initialPriceScrollPos-i)>20&&(this.pushUndoCommand(new p(this.m_model,e,t,this._initialPriceScrollState)),delete this._initialPriceScrollState,delete this._initialPriceScrollPos),this.chartModel().scrollPriceTo(e,t,i))}endScrollPrice(e,t){t.isAutoScale()||(delete this._initialPriceScrollState,delete this._initialPriceScrollPos,this.chartModel().endScrollPrice(e,t))}setPriceAutoScale(e,t,i){this.pushUndoCommand(new p(this.m_model,e,t,t.state())),this.chartModel().setPriceAutoScale(e,t,i)}setWidth(e){this.m_model.setWidth(e)}setPaneHeight(e,t){this.m_model.setPaneHeight(e,t)}gridSource(){return this.m_model.gridSource()}watermarkSource(){return this.m_model.watermarkSource()}publishedChartsTimelineSource(){return this.m_model.publishedChartsTimelineSource()}crossHairSource(){return this.m_model.crossHairSource()}model(){return this.m_model}chartWidget(){return this._chartWidget}mainSeries(){return this.m_model.m_mainSeries}mainSeriesScaleRatioProperty(){return this.m_model.mainSeriesScaleRatioProperty()}timeScale(){return this.m_model.timeScale()}selectionMacro(e,t){return this.m_model.selectionMacro(e,t)}setHoveredSource(e,t){this.m_model.setHoveredSource(e,t)}selection(){return this.m_model.selection()}onSelectedSourceChanged(){return this.m_model.onSelectedSourceChanged()}activeStrategySource(){return this.m_model.activeStrategySource()}invalidate(e){this.m_model.invalidate(e)}setCurrentPosition(e,t,i,s){this.m_model.setCurrentPosition(e,t,i,s)}setAndSaveCurrentPosition(e,t,i,s){this.m_model.setAndSaveCurrentPosition(e,t,i,s)}setProperties(e,t,i){var s=this;this.beginUndoMacro(i),this.m_model.selectionMacro((function(){for(var o=0;o{"use strict";i.d(t,{sourceNewCurrencyOnPinningToPriceScale:()=>o});var s=i(981107);function o(e,t,i,o){let r=null;if(i.currencyConversionEnabled()&&(0,s.isActingAsSymbolSource)(e)){const s=i.availableCurrencies(),n=t.currency(s),a=e.currency();null!==n&&null!==n.selectedCurrency&&!n.allCurrenciesAreOriginal&&n.selectedCurrency!==a&&(o&&null===a||null!==a&&s.convertible(a))&&(r=n.selectedCurrency)}return r}},949529:(e,t,i)=>{"use strict";i.d(t,{CustomSourceBase:()=>s});class s{constructor(e,t){this._id=e,this._model=t}id(){return this._id}isHoveredEnabled(){return!0}isSelectionEnabled(){return!1}priceScale(){return null}paneViews(e){return[]}labelPaneViews(e){return[]}priceAxisViews(e,t){return[]}updateViewsForPane(e,t){e.containsMainSeries()&&this.updateAllViews(t)}}},950740:(e,t,i)=>{"use strict";i.d(t,{EnvironmentState:()=>o});var s=i(638456);class o{constructor(e,t=!1){this._shift=!1,this._mod=!1,this._alt=!1,void 0!==e&&(this._shift=Boolean(e.shiftKey),this._mod=Boolean((0,s.isMac)()?e.metaKey:e.ctrlKey), this._alt=Boolean(e.altKey)),this._isApiEvent=t}shift(){return this._shift}mod(){return this._mod}alt(){return this._alt}shiftOnly(){return this._shift&&!this._mod&&!this._alt}modOnly(){return this._mod&&!this._shift&&!this._alt}altOnly(){return this._alt&&!this._shift&&!this._mod}modShift(){return this._shift&&this._mod&&!this._alt}isApiEvent(){return this._isApiEvent}static create(e=!1,t=!1,i=!1){return new o({shiftKey:e,ctrlKey:t,metaKey:t,altKey:i})}}},743354:(e,t,i)=>{"use strict";i.d(t,{DateTimeWithTzFormatter:()=>c});var s=i(245302),o=i(988124),r=i(716714),n=i(714688),a=i(157954);const l={dateFormat:"MMM dd",timeFormat:r.hourMinuteFormat};class c{constructor(e={}){const{dateFormat:t,timeFormat:i,timezone:s}={...l,...e};t&&i?this._dateFormatter=new n.DateTimeFormatter({dateFormat:t,timeFormat:i}):t?this._dateFormatter=new a.DateFormatter(t):i&&(this._dateFormatter=new r.TimeFormatter(i)),this._timezone=(0,o.get_timezone)(null!=s?s:"Etc/UTC")}format(e){const t=1e3*e,i=(0,s.parseTzOffset)(this._timezone.name(),t).string;return void 0===this._dateFormatter?i:`${this._dateFormatter.format((0,o.utc_to_cal)(this._timezone,t))} ${i}`}setTimezone(e){this._timezone=(0,o.get_timezone)(e)}}},921692:(e,t,i)=>{"use strict";i.d(t,{FuturesContractExpiration:()=>O,isFuturesContractExpiration:()=>B});var s=i(650151),o=i(996986),r=i(888929),n=i(822914),a=i(790188),l=i(86441),c=i(444372),h=i(246733),d=i(511131),u=i(528474),_=i(458963),p=i(422333),m=i(986837),g=i(315801),S=i(787123),v=i(382778);const f=new Path2D("M.18.24a4.78 4.78 0 0 0 .9 4.36c.15.18.32.34.51.5l.52.4-.52.4a3.8 3.8 0 0 0-.52.5 4.78 4.78 0 0 0-.89 4.36c.04.14.16.24.29.24h6.06c.13 0 .25-.1.29-.24a4.78 4.78 0 0 0-.9-4.36 3.8 3.8 0 0 0-.51-.5l-.52-.4.52-.4c.19-.16.36-.32.52-.5A4.78 4.78 0 0 0 6.82.24C6.78.1 6.66 0 6.53 0H.47C.34 0 .22.1.18.24ZM3.5 4.88l1.23-.97a3 3 0 0 0 1.05-2.48H1.22a3 3 0 0 0 1.05 2.48l1.23.97Z");class b extends v.LollipopRenderer{_drawLollipop(e,t,i){const s=i.pixelRatio,o=this._data.style;e.save(),e.translate(t.x,t.y),e.scale(s,s),e.beginPath(),e.strokeStyle=o.outerBorderColor,e.lineWidth=1,e.arc(0,0,11,0,2*Math.PI),e.stroke(),e.fillStyle=o.backgroundColor,e.beginPath(),e.arc(0,0,10.5,0,2*Math.PI),e.fill(),e.translate(-3.5,-5.5),e.fillStyle=o.iconColor,e.fill(f,"evenodd"),e.translate(3.5,5.5),o.borderColor&&(e.strokeStyle=o.borderColor,e.lineWidth=1.5,(0,S.setLineStyle)(e,_.LINESTYLE_SOLID),e.beginPath(),e.arc(0,0,9.75,0,2*Math.PI),e.stroke()),e.restore()}}var y=i(760823);const C=c.t(null,void 0,i(401256)),w=c.t(null,void 0,i(911235)),P={dark:{background:(0,a.getHexColorByName)("color-cold-gray-900"),foreground:(0,a.getHexColorByName)("color-cold-gray-450"),foregroundExpired:(0,a.getHexColorByName)("color-ripe-red-500")},light:{background:(0,a.getHexColorByName)("color-white"),foreground:(0,a.getHexColorByName)("color-cold-gray-550"),foregroundExpired:(0,a.getHexColorByName)("color-ripe-red-500")}},T={barLine:{lineStyle:_.LINESTYLE_DASHED,lineWidth:1,strokeStyle:""},lollipop:{width:21,height:21,bottom:2,lineWidth:1.5,strokeStyle:"", backgroundColor:"",fillCircle:!0,fillStyle:"",text:{label:"",strokeStyle:"",font:(0,d.makeFont)(12,p.CHART_FONT_FAMILY,"bold")}},iconColor:"",backgroundColor:"",outerBorderColor:""};class M extends m.LollipopPaneView{constructor(){super(...arguments),this._style=(0,n.default)(T)}renderer(e){return this._invalidated&&(this._createLollipops(e),this._invalidated=!1),this._renderer}getStyle(e){const t=this._model.dark().value()?P.dark:P.light,i=e.expired?t.foregroundExpired:t.foreground,s=t.background,o=this._style;return e.active?(o.backgroundColor=i,o.iconColor=s,o.borderColor=void 0):(o.iconColor=i,o.borderColor=i,o.backgroundColor=e.hovered?(0,u.blendColors)(s,(0,h.applyAlpha)(i,.15)):s),o.outerBorderColor=s,o.barLine.strokeStyle=i,o}_createTooltipContent(e){const t=this._model.dark().value()?P.dark:P.light,i=e.expired?t.foregroundExpired:t.foreground;return[{type:"common",title:e.expired?w:C,subTitle:e.expiration,tooltipIcon:y.replace(/currentColor/g,i),style:{color:i}}]}_createRendererForLollipop(e,t){return new b(e,new g.HitTestResult(g.HitTarget.Custom,t),this._textWidthCache)}_createLollipops(e){const t=this._source.data();if(null===t||void 0===t.index)return;const i=this._model.timeScale(),s=super._getY(),o=this._model.hoveredSource()===this._source,r=null!==this.getLastClickedLollipopId(),n={id:0,itemIndex:0,basePoint:(0,l.point)(i.indexToCoordinate(t.index),s),hovered:o,active:r,expiration:t.formattedDate,expired:t.expired,visible:!0};this._lollipops[0]=n,super._createRenderers(e)}}var x=i(988124),I=i(731042),A=i(201089),L=i(190973),k=i(65455);const E=(0,A.getLogger)("FutureContractExpiration");let D=0;let N=0;function B(e){return e instanceof O}const R={visible:!0};class O extends o.DataSource{constructor(e){super("futures_contract_expiration"),this._data=null,this._pointsetId=(D+=1,`future_expiration_${D}`),this._pointsetTurnaround=null,this._properties=new L.default(R),this._onConnectionStateChanged=e=>{e?this._updateData():this._removePointset()},this.setOwnerSource(e.mainSeries()),this._model=e,this._paneView=new M(e,this,this._showTooltip.bind(this));const t=(0,s.ensureNotNull)(e.mainSeries().marketStatusModel().futuresContractExpirationTime());this._expirationUTCTime=t.utcTime().spawn(),this._expired=t.expired().spawn(),this._sessionSpec=t.sessionSpec().spawn(),this._formattedExpirationDate=()=>e.dateFormatter().format(t.utcDayStart()),this._expirationUTCTime.subscribe((()=>{this._removePointset(),this._updateData(),this._paneView.update(),this._model.updateSource(this)})),this._expired.subscribe((()=>{null!==this._data&&(this._data.expired=this._expired.value(),this._paneView.update(),this._model.updateSource(this))}));const i=()=>{this._removePointset(),this._createPointset()};this._destroyPropertyBinder=(0,k.bindProperties)(e.mainSeries().properties().childs().showFuturesContractExpiration,this._properties.childs().visible),e.mainSeries().onIntervalChanged().subscribe(this,i),this._sessionSpec.subscribe(i),e.chartApi().isConnected().subscribe(this._onConnectionStateChanged),this._updateData()} destroy(){this._removePointset(),this._model.mainSeries().onIntervalChanged().unsubscribeAll(this),this._model.chartApi().isConnected().unsubscribe(this._onConnectionStateChanged),this._paneView.destroy(),this._expirationUTCTime.destroy(),this._expired.destroy(),this._sessionSpec.destroy(),this._destroyPropertyBinder(),super.destroy()}lollipopsAtIndex(e){return null===this._data||this._data.index!==e?0:1}name(){return"FuturesContractExpiration"}properties(){return this._properties}state(e){return null}paneViews(e){return[this._paneView]}updateAllViews(e){this._paneView.update()}data(){return this._data}zorder(){return r.sortSourcesPreOrdered.FutureContractExpiration}onClickOutside(){this._paneView.processClickOutside()}preferNoScale(){return!0}showInObjectTree(){return!1}isSavedInStudyTemplates(){return!1}isRemovedByStudyTemplates(){return!1}copiable(){return!1}hasStateForAlert(){return!1}isSavedInChart(e){return!1}isSpeciallyZOrderedSource(){return!0}isUserDeletable(){return!1}canHaveChildren(){return!1}isIncludedInAutoScale(){return!1}async _showTooltip(e,t){const o=this._model,r=this._model.timeScale(),n=[r.onScroll(),r.barSpacingChanged(),o.mainSeries().onSymbolIntervalChanged(),(0,s.ensureNotNull)(o.paneForSource(this)).onSizeChanged()],a=this._paneView.processClickOutside.bind(this._paneView),l=this._paneView.clearLastClicked.bind(this._paneView),c=t();if(null===c)return;const{showLollipopTooltip:h}=await Promise.all([i.e(22666),i.e(5993),i.e(92191),i.e(4015),i.e(53842),i.e(35649),i.e(72639),i.e(89842),i.e(88548),i.e(48986),i.e(36747),i.e(13821),i.e(6744),i.e(27620),i.e(42244),i.e(57215),i.e(94345),i.e(58666),i.e(54234),i.e(84372),i.e(91895),i.e(56943),i.e(2807),i.e(63823),i.e(50690),i.e(59255),i.e(45366),i.e(25827),i.e(18657),i.e(69226),i.e(49039)]).then(i.bind(i,722832));h({items:c,position:e,customCloseSubscriptions:n,onClickOutside:a,onCustomClose:l,showScrollFades:!0})}_updateData(){const e=this._expirationUTCTime.value();if(null===e)return this._data=null,void this._removePointset();this._data={time:e,expired:this._expired.value(),formattedDate:this._formattedExpirationDate()},this._createPointset()}_removePointset(){if(null!==this._pointsetTurnaround){const e=this._model.chartApi();e.isConnected().value()&&e.removePointset(this._pointsetId),this._pointsetTurnaround=null}}_createPointset(){if(null!==this._pointsetTurnaround)return;const e=this._model,t=e.chartApi(),i=this._sessionSpec.value();if(null===this._data||null===i||!t.isConnected().value())return;const o=e.mainSeries(),r=o.symbolInfo();if(null===r)return;let n=e.properties().childs().timezone.value();"exchange"===n&&(n=r.timezone);const a=x.get_timezone(n);this._pointsetTurnaround=(N+=1,`t${N}`);const l=(0,s.ensureNotNull)(o.seriesSource().symbolInstanceId()),c=(0,I.getServerInterval)(o.interval());let h;const d=this._data.time;if(o.isDWM()){const e=new Date(d);i.alignToSessionStart(e),h=[[x.cal_to_utc(a,e)/1e3,0]]}else h=[[d/1e3,0]];t.createPointset(this._pointsetId,this._pointsetTurnaround,l,c,h,this._onPointsetResponse.bind(this))} _onPointsetResponse(e){if("pointset_error"===e.method){const[t,i]=e.params;return void(t===this._pointsetId&&i===this._pointsetTurnaround&&E.logError("Pointset error"))}const t=e.params;t.customId===this._pointsetId&&null!==this._data&&(this._data.index=0===t.plots.length?void 0:t.plots[0].value[0],this._paneView.update(),this._model.updateSource(this))}}},924788:(e,t,i)=>{"use strict";function s(e){return e&&e.lollipopsAtIndex}i.d(t,{isLollipopDataSource:()=>s})},74439:(e,t,i)=>{"use strict";var s;i.d(t,{ReplayStatus:()=>s}),function(e){e[e.Undefined=0]="Undefined",e[e.PointSelect=1]="PointSelect",e[e.AutoPlay=2]="AutoPlay",e[e.Pause=3]="Pause",e[e.Finish=4]="Finish"}(s||(s={}))},913984:(e,t,i)=>{"use strict";function s(e){return Boolean(e.showInObjectTree)}i.d(t,{isDataSource:()=>s})},184586:(e,t,i)=>{"use strict";i.d(t,{LatestUpdatesSource:()=>G,isLatestUpdatesSource:()=>z});var s=i(650151),o=i(201089),r=i(996986),n=i(888929),a=i(190973),l=i(65455),c=i(784547),h=i(822914),d=i(790188),u=i(86441),_=i(444372),p=i(887357),m=i(207678),g=i(528474),S=i(638456),v=i(396231),f=i(246733),b=i(511131),y=i(458963),C=i(422333),w=i(986837),P=i(315801),T=i(787123),M=i(382778);const x=new Path2D("m7.06 0 .87.77-3.4 4.17H9L1.94 11l-.87-.77 3.4-4.17H0L7.06 0Z");class I extends M.LollipopRenderer{_drawLollipop(e,t,i){const s=i.pixelRatio,o=this._data.style;e.save(),e.translate(t.x,t.y),e.scale(s,s),e.beginPath(),e.strokeStyle=o.outerBorderColor,e.lineWidth=1,e.arc(0,0,11,0,2*Math.PI),e.stroke(),e.fillStyle=o.backgroundColor,e.beginPath(),e.arc(0,0,10.5,0,2*Math.PI),e.fill(),e.translate(-4.5,-5.5),e.fillStyle=o.iconColor,e.fill(x,"evenodd"),e.translate(4.5,5.5),o.borderColor&&(e.strokeStyle=o.borderColor,e.lineWidth=1.5,(0,T.setLineStyle)(e,y.LINESTYLE_SOLID),e.beginPath(),e.arc(0,0,9.75,0,2*Math.PI),e.stroke()),o.hasUpdatesCircle&&(e.fillStyle=o.hasUpdatesCircle.color,e.strokeStyle=o.hasUpdatesCircle.borderColor,e.lineWidth=2,e.beginPath(),e.arc(9.75*Math.cos(Math.PI/4),9.75*-Math.sin(Math.PI/4),3.5,0,2*Math.PI),e.closePath(),e.fill(),e.stroke()),e.restore()}}var A=i(244230);const L=(0,o.getLogger)("LatestUpdatesProvider"),k={dark:{background:(0,d.getHexColorByName)("color-cold-gray-900"),foreground:(0,d.getHexColorByName)("color-grapes-purple-400"),hasUpdatesCircle:(0,d.getHexColorByName)("color-ripe-red-500")},light:{background:(0,d.getHexColorByName)("color-white"),foreground:(0,d.getHexColorByName)("color-grapes-purple-500"),hasUpdatesCircle:(0,d.getHexColorByName)("color-ripe-red-500")}},E={barLine:{lineStyle:y.LINESTYLE_DASHED,lineWidth:1,strokeStyle:""},lollipop:{width:21,height:21,bottom:2,lineWidth:1.5,strokeStyle:"",backgroundColor:"",fillCircle:!0,fillStyle:"",text:{label:"",strokeStyle:"",font:(0,b.makeFont)(12,C.CHART_FONT_FAMILY,"bold")}},iconColor:"",backgroundColor:"",outerBorderColor:""};async function D(e,t,s){const{openMindsPage:o}=await i.e(20603).then(i.bind(i,337860));o(e,t,s)} const N=_.t(null,void 0,i(857154)),B=_.t(null,void 0,i(923278)),R=_.t(null,void 0,i(998431)),O=_.t(null,void 0,i(413070)),V=_.t(null,void 0,i(620107));class W extends w.LollipopPaneView{constructor(){super(...arguments),this._style=(0,h.default)(E)}renderer(e){return this._source.hideLollipop()?null:(this._invalidated&&(this._createLollipops(e),this._invalidated=!1),this._renderer)}getStyle(e){const t=this._model.dark().value()?k.dark:k.light,i=t.foreground,s=t.background,o=this._style;return e.active?(o.backgroundColor=i,o.iconColor=s,o.borderColor=void 0):(o.iconColor=i,o.borderColor=i,o.backgroundColor=e.hovered?(0,g.blendColors)(s,(0,f.applyAlpha)(i,.15)):s),o.outerBorderColor=s,o.barLine.strokeStyle=i,o.lollipop.incHeight=void 0===e.stack?void 0:25*e.stack,o.hasUpdatesCircle=e.data.hasNewItems?{color:t.hasUpdatesCircle,borderColor:s}:void 0,o}_createTooltipContent(e){var t,s,o,r,n;const a=this._model.mainSeries().symbol(),l=(this._model.dark().value()?k.dark:k.light).foreground,c=e.data.newsData,h=e.data.mindsData,d=c&&c.items.length>0,u=h&&h.items.length>0;if(!d&&!u)return null;const g=null!==(t=a.split(":")[1])&&void 0!==t?t:a,f={title:d&&u?N:d&&_.t(null,{replace:{symbol:g}},i(588103))||u&&_.t(null,{replace:{symbol:g}},i(883274))||"",tabs:[],tooltipIcon:A.replace(/currentColor/g,l),style:{color:l}};return d&&f.tabs.push({id:"news",name:B,content:{type:"news",items:c.items,clickHandler:(e,t)=>{S.CheckMobile.any()&&this._source.hideTooltip(),async function(e,t,s){e.isExternal||s.preventDefault();try{const o={...e,analyticsData:t.analyticsData},[{TradingViewNewsProviderFetcher:r},{onNewsCardAction:n}]=await Promise.all([Promise.all([i.e(32109),i.e(4015),i.e(88548),i.e(56400),i.e(58666),i.e(54234),i.e(80345),i.e(96821),i.e(80926),i.e(66446),i.e(56370)]).then(i.bind(i,619008)),Promise.all([i.e(32109),i.e(4015),i.e(88548),i.e(56400),i.e(58666),i.e(54234),i.e(80345),i.e(96821),i.e(80926),i.e(66446),i.e(56370)]).then(i.bind(i,253018))]);n({newsItem:o,newsItems:(await r.instance().fetch({...t.requestProps,client:"web"},3e5)).items,placement:p.NewsWidgetPlacement.Chart})(s)}catch(s){L.logWarn(`An error ocurred while loading news: ${s}`)}}(e,c,t)}},anchor:(null===(o=null===(s=window.widgetbar)||void 0===s?void 0:s.layout)||void 0===o?void 0:o.canOpen())?{text:O,onClick:()=>{var e;this._source.hideTooltip(),null===(e=window.widgetbar)||void 0===e||e.setPage("base"),(0,v.showSymbolNews)(a)},hideInMobileMode:!0}:void 0}),u&&f.tabs.push({id:"minds",name:R,content:{type:"minds",symbol:a,items:h.items,clickHandler:(e,t,i)=>{this._source.hideTooltip(),function(e,t,i,s){var o;window.innerWidth{this._source.hideTooltip(),function(e){var t ;window.innerWidthn&&e.isVisible()&&(a+=e.lollipopsAtIndex(t.index));const l={id:0,itemIndex:0,basePoint:(0,u.point)(i.indexToCoordinate(t.index),s),hovered:o,active:r,visible:!0,stack:a,data:t};this._lollipops[0]=l,super._createRenderers(e)}}const F=(0,o.getLogger)("Chart.LatestUpdate"),H={visible:!0};function z(e){return e instanceof G}function U(e){return!e.isSeconds()&&!e.isTicks()}class G extends r.DataSource{constructor(e,t){super("latestUpdates"),this._properties=new a.default(H),this._items={},this._hasNewItems=!1,this._newsThread=null,this._mindsThread=null,this._hideLollipopTooltipFn=null,this._onMindsHistoryReady=this._onMindsItems.bind(this,void 0),this._onNewsHistoryReady=this._onNewsItems.bind(this,void 0),this.setOwnerSource(e.mainSeries()),this._latestUpdatesDataEnabled=t,this._model=e,this._series=e.mainSeries(),this._paneView=new W(e,this,this._showTooltip.bind(this)),this._series.symbolResolved().subscribe(this,this._onSymbolResolved);const i=this._series.intervalObj();this._isAvailableOnCurrentInterval=U(i),this._series.onIntervalChanged().subscribe(this,this._recalculateAvailabilityOnCurrentInterval),this._destroyPropertyBinder=(0,l.bindProperties)(e.mainSeries().properties().childs().showLastNews,this._properties.childs().visible),this._initializeNewsAndMindsThreads(),this._hideLollipop=(0,c.createWVFromGetterAndSubscriptions)((()=>this._model.isInReplay()||!U(this._series.intervalObj())),[this._model.onInReplayStateChanged(),this._series.onIntervalChanged()]),this._hideLollipop.subscribe((()=>this._model.updateSource(this)))}destroy(){this._destroyNewsThread(),this._destroyMindsThread(),this._paneView.destroy(),this._series.symbolResolved().unsubscribeAll(this),this._series.onIntervalChanged().unsubscribeAll(this),this._destroyPropertyBinder(),this._hideLollipop.destroy(),super.destroy()}hideLollipop(){return this._hideLollipop.value()}lollipopsAtIndex(e){var t;return Object.keys(this._items).length>0&&e===(null===(t=this._series.data().last())||void 0===t?void 0:t.index)?1:0}name(){return"LatestUpdatesSource"}data(){const e=this._series.data().last();if(null===e||void 0===Object.keys(this._items).length)return null;const t={index:e.index,hasNewItems:this._hasNewItems};return this._items[0]&&void 0!==this._requestNewsProps&&void 0!==this._newsAnalyticsData&&(t.newsData={items:this._items[0], requestProps:this._requestNewsProps,analyticsData:this._newsAnalyticsData}),this._items[1]&&(t.mindsData={items:this._items[1]}),t}properties(){return this._properties}state(e){return null}paneViews(e){return[this._paneView]}updateAllViews(e){this._paneView.update()}zorder(){return n.sortSourcesPreOrdered.LatestUpdates}onClickOutside(){this._paneView.processClickOutside()}preferNoScale(){return!0}showInObjectTree(){return!1}isSavedInStudyTemplates(){return!1}isRemovedByStudyTemplates(){return!1}copiable(){return!1}hasStateForAlert(){return!1}isSavedInChart(e){return!1}isSpeciallyZOrderedSource(){return!0}isUserDeletable(){return!1}canHaveChildren(){return!1}isIncludedInAutoScale(){return!1}hideTooltip(){var e;null===(e=this._hideLollipopTooltipFn)||void 0===e||e.call(this),this._hideLollipopTooltipFn=null}async _showTooltip(e,t){const o=this._model.timeScale(),r=[o.onScroll(),o.barSpacingChanged(),this._series.onSymbolIntervalChanged(),(0,s.ensureNotNull)(this._model.paneForSource(this)).onSizeChanged()],n=this._paneView.processClickOutside.bind(this._paneView),a=this._paneView.clearLastClicked.bind(this._paneView),l=t();if(null===l)return;this._hasNewItems=!1;const{showLollipopTooltipWithTabs:c}=await Promise.all([i.e(22666),i.e(5993),i.e(92191),i.e(4015),i.e(53842),i.e(35649),i.e(72639),i.e(89842),i.e(88548),i.e(48986),i.e(36747),i.e(13821),i.e(6744),i.e(27620),i.e(42244),i.e(57215),i.e(94345),i.e(58666),i.e(54234),i.e(84372),i.e(91895),i.e(56943),i.e(2807),i.e(63823),i.e(50690),i.e(59255),i.e(45366),i.e(25827),i.e(18657),i.e(69226),i.e(49039)]).then(i.bind(i,480079));this._hideLollipopTooltipFn=c({content:l,position:e,customCloseSubscriptions:r,onClickOutside:n,doNotCloseOn:()=>[document.querySelector('[data-name="news-dialog"]'),document.querySelector('[data-dialog-name="image-dialog"]')].filter((e=>null!==e)),onCustomClose:a,showScrollFades:!0})}async _initializeNewsAndMindsThreads(){if(!this._isAvailableOnCurrentInterval)return void(this._items={});null!==this._series.symbolInfo()&&(this._initializeNewsThread(),this._initializeMindsThread())}async _initializeMindsThread(){if(!this._latestUpdatesDataEnabled.minds)return;const e=(0,s.ensureNotNull)(this._series.symbolInfo());try{const{popularMindsThread:t}=await i.e(12127).then(i.bind(i,121362));this._mindsThread=t({symbol:e.pro_name,limit:3},3e5,3e5),this._mindsThread.newItems().subscribe(this,this._onMindsItems.bind(this,!0)),this._mindsThread.historyReady().value()?this._onMindsItems():this._mindsThread.historyReady().subscribe(this._onMindsHistoryReady,{once:!0})}catch(e){F.logWarn(`An error ocurred while loading minds: ${e}`)}}async _initializeNewsThread(){if(!this._latestUpdatesDataEnabled.news)return;const e=(0,s.ensureNotNull)(this._series.symbolInfo());try{ const[{getIsoLanguageCodeFromLanguage:t},{getCardsAnalyticsData:s},{handleNewsProName:o},{newsThread:r}]=await Promise.all([Promise.all([i.e(32109),i.e(4015),i.e(88548),i.e(56400),i.e(58666),i.e(54234),i.e(80345),i.e(96821),i.e(80926),i.e(66446),i.e(56370)]).then(i.bind(i,39654)),Promise.all([i.e(32109),i.e(4015),i.e(88548),i.e(56400),i.e(58666),i.e(54234),i.e(80345),i.e(96821),i.e(80926),i.e(66446),i.e(56370)]).then(i.bind(i,859409)),Promise.all([i.e(32109),i.e(4015),i.e(88548),i.e(56400),i.e(58666),i.e(54234),i.e(80345),i.e(96821),i.e(80926),i.e(66446),i.e(56370)]).then(i.bind(i,470598)),Promise.all([i.e(32109),i.e(4015),i.e(88548),i.e(56400),i.e(58666),i.e(54234),i.e(80345),i.e(96821),i.e(80926),i.e(66446),i.e(56370)]).then(i.bind(i,603326))]);this._requestNewsProps={lang:t(window.language),symbol:o(e.pro_name,e.type),client:"chart"},this._newsAnalyticsData=s(this._requestNewsProps),this._newsThread=r(this._requestNewsProps,3e5,3e5),this._newsThread.newItems().subscribe(this,this._onNewsItems.bind(this,!0)),this._newsThread.historyReady().value()?this._onNewsItems():this._newsThread.historyReady().subscribe(this._onNewsHistoryReady,{once:!0})}catch(e){F.logWarn(`An error ocurred while loading news: ${e}`)}}_onNewsItems(e){const t=this._series.symbolInfo();if(this._isDestroyed||null===t)return;let i=(0,s.ensureNotNull)(this._newsThread).history().slice();i.length>0&&Date.now()-i[0].published>=26784e5&&(i=[]),this._items[0]=i,e&&(this._hasNewItems=!0),Object.keys(this._items).length&&(this._paneView.update(),this._model.updateSource(this))}_onMindsItems(e){const t=this._series.symbolInfo();if(this._isDestroyed||null===t)return;const i=(0,s.ensureNotNull)(this._mindsThread).history().slice();this._items[1]=i,e&&(this._hasNewItems=!0),Object.keys(this._items).length&&(this._paneView.update(),this._model.updateSource(this))}_destroyNewsThread(){this._newsThread&&(this._newsThread.historyReady().unsubscribe(this._onNewsHistoryReady),this._newsThread.newItems().unsubscribeAll(this),this._newsThread.destroy(),this._newsThread=null)}_destroyMindsThread(){this._mindsThread&&(this._mindsThread.historyReady().unsubscribe(this._onMindsHistoryReady),this._mindsThread.newItems().unsubscribeAll(this),this._mindsThread.destroy(),this._mindsThread=null)}_onSymbolResolved(){this._items={},this._destroyNewsThread(),this._destroyMindsThread(),this._initializeNewsAndMindsThreads()}_recalculateAvailabilityOnCurrentInterval(){const e=U(this._series.intervalObj());e!==this._isAvailableOnCurrentInterval&&(this._isAvailableOnCurrentInterval=e,e?this._initializeNewsAndMindsThreads():(this._destroyNewsThread(),this._destroyMindsThread(),this._paneView.update(),this._model.updateSource(this)))}}},440941:(e,t,i)=>{"use strict";i.d(t,{lineToolsDoNotAffectChartInvalidation:()=>s});const s=!0},391534:(e,t,i)=>{"use strict";i.d(t,{LineToolsGroup:()=>l});var s=i(707957),o=i(401580),r=i(541558);function n(e){return e.properties().visible.value()}function a(e){return!n(e)}class l{constructor(e,t,i){this._instanceId=(0,r.randomHashN)(6), this._onChanged=new s.Delegate,this._lineToolsSet=new Set,this._lineTools=[...e],this._lineToolsSet=new Set(this._lineTools),this._name=new o.WatchedValue(t),this.id=i||(0,r.randomHashN)(6)}instanceId(){return this._instanceId}lineTools(){return this._lineTools}name(){return this._name}setName(e){this._doAndFireOnChange((()=>{this._name.setValue(e)}))}isActualSymbol(){return this._lineTools.length>0&&this._lineTools[0].isActualSymbol()&&this._lineTools[0].isActualCurrency()&&this._lineTools[0].isActualUnit()}symbol(){return this._lineTools[0].symbol()}currencyId(){var e;return null!==(e=this._lineTools[0].properties().childs().currencyId.value())&&void 0!==e?e:null}unitId(){var e;return null!==(e=this._lineTools[0].properties().childs().unitId.value())&&void 0!==e?e:null}sharingMode(){return this._lineTools[0].sharingMode()}share(e){this._lineTools.forEach((t=>t.share(e)))}containsLineTool(e){return this._lineToolsSet.has(e)}addLineTools(e){this._doAndFireOnChange((t=>{e.forEach((e=>this._lineToolsSet.add(e))),this._lineTools.push(...e),t.push(...e.map((e=>e.id())))}))}excludeLineTool(e){this._doAndFireOnChange((t=>{this._lineToolsSet.delete(e);const i=this._lineTools.indexOf(e);this._lineTools.splice(i,1),t.push(e.id())}))}excludeLineTools(e){this._doAndFireOnChange((t=>{const i=new Set(e);e.forEach((e=>this._lineToolsSet.delete(e))),this._lineTools=this._lineTools.filter((e=>!i.has(e))),t.push(...e.map((e=>e.id())))}))}state(){return{id:this.id,name:this._name.value(),tools:this._lineTools.map((e=>e.id()))}}visibility(){const e=this._lineTools.some(n),t=this._lineTools.some(a);return e&&!t?"Visible":t&&!e?"Invisible":"Partial"}locked(){const e=this._lineTools.some((e=>e.properties().frozen.value())),t=this._lineTools.some((e=>!e.properties().frozen.value()));return e&&!t?"Locked":t&&!e?"Unlocked":"Partial"}isActualInterval(){const e=this._lineTools.some((e=>e.isActualInterval())),t=this._lineTools.some((e=>!e.isActualInterval()));return e&&!t?"IsActualInterval":t&&!e?"IsNotActualInterval":"Partial"}onChanged(){return this._onChanged}static fromState(e,t){const i=[];for(const s of t.tools){const t=e.dataSourceForId(s);null!==t&&i.push(t)}return i.length>0?new l(i,t.name,t.id):null}_doAndFireOnChange(e){const t=[],i=this.visibility(),s=this.locked(),o=this.isActualInterval();e(t),this._onChanged.fire({affectedLineTools:t,visibilityChanged:i!==this.visibility(),lockedChanged:s!==this.locked(),isActualIntervalChanged:o!==this.isActualInterval()})}}},549621:(e,t,i)=>{"use strict";i.d(t,{LogicalRange:()=>o});var s=i(650151);class o{constructor(e,t){(0,s.assert)(e<=t,"The left value should be greater than or equal to the right value"),this._left=e,this._right=t}left(){return this._left}right(){return this._right}length(){return this._right-this._left+1}contains(e,t){return ethis._right+.5?!0===t&&2:!0!==t||0}before(e){return ethis._right+.5}intersects(e){return!(this.after(e.left())||this.before(e.right()))}equals(e){ return this._left===e.left()&&this._right===e.right()}static compare(e,t){return null===e||null===t?e===t:e.equals(t)}}},220843:(e,t,i)=>{"use strict";i.d(t,{MainSeriesScaleRatioProperty:()=>r});var s=i(707957),o=i(428123);class r{constructor(e){this._changed=new s.Delegate,this._model=e}destroy(){this._changed.destroy()}getStepChangeValue(){return.1}getMinValue(){return 1e-7}getMaxValue(){return 99999999}value(){return this._model.mainSeriesScaleRatio()}setValue(e,t){(e!==this.value()||t)&&(this._model.setMainSeriesScaleRatio(e),this._onChanged())}state(){return null}clone(){return new r(this._model)}listeners(){return this._changed}subscribe(e,t){this._changed.subscribe(e,t)}unsubscribe(e,t){this._changed.unsubscribe(e,t)}unsubscribeAll(e){this._changed.unsubscribeAll(e)}storeStateIfUndefined(){return!0}weakReference(){return(0,o.weakReference)(this)}ownership(){return(0,o.ownership)(this)}_onChanged(){this._changed.fire(this,"")}}},993171:(e,t,i)=>{"use strict";i.d(t,{PrePostMarket:()=>v,defaultPrePostMarketPreferences:()=>S});var s=i(790188),o=i(458963),r=i(742391),n=i(949529),a=i(506387);class l extends a.PriceLineAxisView{constructor(e,t){super(),this._model=e,this._source=t}_value(){const e=this._model.mainSeries(),t=e.priceScale(),i=e.firstValue();if(null===i)return{noData:!0};const s=this._source.price(),o=this._source.currentSession();if(null===s||"pre_market"!==o&&"post_market"!==o)return{noData:!0};const r=t.priceToCoordinate(s,i);return{noData:!1,floatCoordinate:r,coordinate:r,color:"",formattedPricePercentage:"",formattedPriceAbsolute:"",formattedPriceIndexedTo100:"",text:"",index:0}}_priceLineColor(e){const t=this._source.properties().childs();return"pre_market"===this._source.currentSession()?t.preMarketColor.value():t.postMarketColor.value()}_lineWidth(){return this._source.properties().childs().lineWidth.value()}_lineStyle(){return this._source.properties().childs().lineStyle.value()}_isVisible(){if(!this._source.canBeVisibleOnSymbolAndInterval()||!this._model.properties().childs().scalesProperties.childs().showPrePostMarketPriceLabel.value())return!1;const e=this._source.price(),t=this._source.currentSession();return null!==e&&("pre_market"===t||"post_market"===t)}}var c=i(444372),h=i(229765),d=i(246733);class u extends h.PriceAxisView{constructor(e,t){super(),this._model=e,this._source=t}_updateRendererData(e,t,s){if(e.visible=!1,t.visible=!1,!this._model.properties().childs().scalesProperties.childs().showPrePostMarketPriceLabel.value())return;const o=this._model.mainSeries(),r=o.priceScale(),n=o.firstValue();if(null===n)return;if(!this._source.canBeVisibleOnSymbolAndInterval())return;const a=this._source.price(),l=this._source.currentSession();if(null==a||"pre_market"!==l&&"post_market"!==l)return;const h=this._source.properties().childs(),u="pre_market"===l?(0,d.resetTransparency)(h.preMarketColor.value()):(0,d.resetTransparency)(h.postMarketColor.value());e.visible=!0,t.visible=!0,e.text=r.formatPriceAbsolute(a),t.text="pre_market"===l?c.t(null,void 0,i(138429)):c.t(null,void 0,i(306930)), s.coordinate=r.priceToCoordinate(a,n),s.background=u,s.textColor=this.generateTextColor(u)}}var _=i(955831),p=i(315801);class m extends _.HorizontalLinePaneView{constructor(e,t,i){super(),this._model=e,this._source=t;const s={doubleClickHandler:i,doubleTapHandler:i};this._lineRenderer.setHitTest(new p.HitTestResult(p.HitTarget.Regular,s))}_updateImpl(){const e=this._lineRendererData;e.visible=!1;const t=this._model.mainSeries(),i=this._source.properties().childs();if(!i.visible.value()||!t.isVisible())return;const s=t.priceScale(),o=t.firstValue();if(null===o)return;if(!this._source.canBeVisibleOnSymbolAndInterval())return;const r=this._source.price(),n=this._source.currentSession();null===r||"pre_market"!==n&&"post_market"!==n||(e.visible=!0,e.y=s.priceToCoordinate(r,o),e.linestyle=i.lineStyle.value(),e.linewidth=i.lineWidth.value(),e.color="pre_market"===n?i.preMarketColor.value():i.postMarketColor.value())}}var g=i(964824);const S={visible:!0,lineStyle:o.LINESTYLE_DOTTED,lineWidth:1,preMarketColor:"#fb8c00",postMarketColor:s.colorsPalette["color-tv-blue-500"]};class v extends n.CustomSourceBase{constructor(e,t,i){super(e,t),this._extraHoursPrice=null,this._currentSession="holiday",this._quotesProvider=t.mainSeries().quotesProvider(),this._prePostMarketLinePaneView=new m(t,this,i),this._prePostPriceAxisView=new u(t,this),this._prePostLabelPaneView=new r.PanePriceAxisView(this._prePostPriceAxisView,t.mainSeries(),t),this._prePostPriceLineAxisView=new l(t,this),this._quotesProvider.quotesUpdate().subscribe(this,this._updateQuotes),this._updateQuotes()}destroy(){this._quotesProvider.quotesUpdate().unsubscribeAll(this)}paneViews(e){return this._isMainSourcePane(e)?[this._prePostMarketLinePaneView]:[]}labelPaneViews(e){return this._isMainSourcePane(e)?[this._prePostLabelPaneView]:[]}priceAxisViews(e,t){return this._isMainSourcePane(e)?e.findTargetPriceAxisViews(this,t,[this._prePostPriceAxisView],[this._prePostPriceLineAxisView]):[]}priceScale(){return this._model.mainSeries().priceScale()}updateAllViews(e){this._prePostMarketLinePaneView.update(e),this._prePostPriceAxisView.update(e),this._prePostPriceLineAxisView.update(e),this._prePostLabelPaneView.update(e)}price(){return this._extraHoursPrice}currentSession(){return this._currentSession}canBeVisibleOnSymbolAndInterval(){return this._model.mainSeries().isPrePostMarketPricesAvailableProperty().value()}properties(){return this._model.mainSeries().properties().childs().prePostMarket}_updateQuotes(){const e=this._quotesProvider.quotes();null===e?this._extraHoursPrice=null:(this._extraHoursPrice=e.rtc,void 0!==e.current_session&&(this._currentSession=e.current_session));const t=this._model.mainSeries().properties().childs().prePostMarket.childs().visible.value(),i=this._model.properties().childs().scalesProperties.childs().showPrePostMarketPriceLabel.value();this.canBeVisibleOnSymbolAndInterval()&&(t||i)&&(this.updateAllViews((0,g.sourceChangeEvent)(this.id())),this._model.updateSource(this))}_isMainSourcePane(e){ return this._model.paneForSource(this._model.mainSeries())===e}}},985139:(e,t,i)=>{"use strict";var s;i.d(t,{PublishedChartsFilter:()=>s}),function(e){e.None="all",e.Following="following",e.Private="private"}(s||(s={}))},922850:(e,t,i)=>{"use strict";i.d(t,{PublishedChartsTimeline:()=>N});var s=i(444372),o=i(62802),r=i.n(o),n=i(838042),a=i(405069),l=i(985139),c=i(201089),h=i(345848),d=i(638456),u=i(337779),_=i(120780),p=i(223124),m=i(853965),g=i(650151),S=i(790188),v=i(934026),f=i(86441),b=i(315801),y=i(199471);function C(e,t){const i=Math.max(1,Math.floor(t)),s=Math.round(e.x*t)+i%2/2;let o=Math.round(e.size*t);(s+o/2)%1!=0&&(o+=1);const r=Math.min(Math.max(1,Math.round(t*e.borderWidth)),o/2);let n;const a=("up"===e.direction?-1:1)*(e.yInverted?-1:1),l=a*(Math.round(e.size*t/2)+i%2);if(void 0!==e.fixedSpaceYPosition){const i=Math.round(e.fixedSpaceYPosition.itemSpacing*t),s=e.fixedSpaceYPosition.order,r=a*(o*s+i*(s+1));n=Math.round(e.fixedSpaceYPosition.basePosition*t)+r+l}else n=Math.round(e.y*t)+l;return{x:s,y:n,size:o,borderWidth:r,tickSize:i}}function w(e,t,i,s){var o;if(e.save(),i&&!s.highlightByAuthor&&(e.globalAlpha=.4),s.mine)!function(e,t,i){const{borderColor:s,backgroundColor:o,doNotFill:r,direction:n,yInverted:a}=i,{x:l,y:c,borderWidth:h,size:d,tickSize:u}=C(i,t.pixelRatio);e.strokeStyle=s,e.fillStyle=o,e.lineWidth=h;const _="up"===n!==a?-1:1;let p=Math.round(d/2/Math.tan(Math.PI/6))+u%2/2;(l+p/2)%1!=0&&(p-=1);e.translate(l,c+p/2*_),e.beginPath();const m=h/2;e.moveTo(0,-_*(p-m)),e.lineTo(d/2-m,h/2),e.lineTo(-d/2+m,h/2),e.lineTo(0,-_*(p-h/2)),e.closePath(),r||e.fill();e.stroke()}(e,t,s);else{0,function(e,t,i,s,o){const{borderColor:r,backgroundColor:n,label:a}=i,l=t.pixelRatio,{x:c,y:h,borderWidth:d,size:u}=C(i,l);e.strokeStyle=r,e.fillStyle=n,e.lineWidth=d,e.beginPath();const _=u/2-d/2;e.arc(c,h,_,0,2*Math.PI,!0),e.closePath(),e.fill(),!1;e.stroke(),!s&&a&&u/2>=7&&(e.textAlign="center",e.textBaseline="middle",e.font=a.font,e.fillStyle=a.fontColor,(0,y.drawScaled)(e,l,l,(()=>{e.fillText(a.text,c/l,h/l)})))}(e,t,s,!1,null===(o=s.image)||void 0===o?void 0:o.imageElement)}e.restore()}class P{constructor(e,t,i,s){this._canvas=null,this._clickHandler=e,this._enterHandler=t,this._leaveHandler=i,this._data=null!=s?s:null}setData(e){this._data=e}hitTest(e,t){if(null===this._data)return null;for(let i=this._data.items.length-1;i>=0;--i){const s=this._hitTestDot(this._data.items[i],e,t.pixelRatio);if(s)return s}return null}draw(e,t){this._canvas=e.canvas,null!==this._data&&this._data.items.forEach(w.bind(null,e,t,this._data.highlightByAuthor))}_hitTestDot(e,t,i){const s=new f.Point(e.x,C(e,i).y/i);if((0,v.pointInCircle)(t,s,Math.max(e.size/2,8))){const t=this._canvas,i=null===t?void 0:{mouseEnterHandler:()=>this._enterHandler(e,s.y,t),mouseLeaveHandler:()=>this._leaveHandler(),clickHandler:i=>this._clickHandler(e,s.y,t,i),tapHandler:i=>this._clickHandler(e,s.y,t,i)};return new b.HitTestResult(b.HitTarget.Regular,{activeItem:e.originalItem.id,...i})}return null}}var T=i(511131),M=i(422333);const x={green:{border:(0, S.getHexColorByName)("color-minty-green-700"),background:(0,S.getHexColorByName)("color-minty-green-a600")},red:{border:(0,S.getHexColorByName)("color-ripe-red-700"),background:(0,S.getHexColorByName)("color-ripe-red-500")},neutral:{border:(0,S.getHexColorByName)("color-tan-orange-700"),background:(0,S.getHexColorByName)("color-tan-orange-500")},yellow:{border:"#EAC300",background:"#FFD400"},blue:{border:"#047ACE",background:"#0496FF"}};function I(e){var t,i,s,o;return e.hovered||e.highlightByAuthor?null!==(i=null===(t=e.overrideBorderWidth)||void 0===t?void 0:t.hoveredWidth)&&void 0!==i?i:4:null!==(o=null===(s=e.overrideBorderWidth)||void 0===s?void 0:s.width)&&void 0!==o?o:2}const A=(0,c.getLogger)("Chart.PublishedChartsTimeline");class L extends class{constructor(e,t){this._tooltip=null,this._hoveredBarsMarkData=null,this._destroyed=!1,this._invalidated=!0,this._originalData=[],this._source=e,this._model=t,this._renderer=new P(this._onItemClicked.bind(this),this._showItem.bind(this),this._hideItem.bind(this)),this._createTooltipRenderer().then((e=>{this._destroyed?null==e||e.destroy():this._tooltip=e})),e.properties().childs().visible.subscribe(null,(()=>{var e;null===(e=this._tooltip)||void 0===e||e.hide(!0)}))}destroy(){var e;this._destroyed=!0,null===(e=this._tooltip)||void 0===e||e.destroy()}source(){return this._source}update(){this._invalidated=!0}renderer(){return this._invalidated&&(this._updateImpl(),this._invalidated=!1),this._renderer}onClickOutside(e){e.isTouch&&null!==this._tooltip&&!this._tooltip.contains(e.target)&&this._tooltip.hide(!0)}_extractBarMarksRendererItemData(e,t){var i,s;const o=null!==(i=t.overridedTheme)&&void 0!==i?i:x[t.theme],r=this._calculateSize(e,t),n=this._calculateY(e,r,t);return null===this._hoveredBarsMarkData||this._hoveredBarsMarkData.id!==t.id||this._hoveredBarsMarkData.x===t.x&&this._hoveredBarsMarkData.y===Math.round(n)||(null===(s=this._tooltip)||void 0===s||s.hide(!0),this._hoveredBarsMarkData=null),{x:t.x,y:this._calculateY(e,r,t),direction:t.direction,borderColor:o.border,borderWidth:I(t),backgroundColor:o.background,size:r,doNotFill:!t.public,yInverted:t.yInverted,label:void 0===t.label?void 0:{text:t.label,fontColor:t.labelFontColor,font:(0,T.makeFont)(Math.ceil(Math.max(10,Math.min(r/2,20))),M.CHART_FONT_FAMILY,"bold")},originalItem:t}}_onItemClicked(e,t,i,s){s.isTouch&&this._showItem(e,t,i)}async _showItem(e,t,i){var s;const o=await this._tooltipProps(e);if(null===o)return;const r=this._model.timeScale().barSpacing(),n=this._calculateSize(r,e.originalItem);this._hoveredBarsMarkData={x:e.x,y:Math.round(this._calculateY(r,n,e.originalItem)),id:e.originalItem.id},null===(s=this._tooltip)||void 0===s||s.show({itemSize:n,container:(0,g.ensureNotNull)(i.parentElement),x:e.x,y:t,factoryProps:o,onClickOutside:()=>{var e;return null===(e=this._tooltip)||void 0===e?void 0:e.hide(!0)}})}_hideItem(){var e;null===(e=this._tooltip)||void 0===e||e.hide()}_calculateSize(e,t){return Math.min(553,Math.max(7,t.minSize,.8*e))}_updateImpl(){ this._originalData=this._source.getPlatesViewData();const e=this._model.timeScale().barSpacing(),t=this._originalData.map(this._extractBarMarksRendererItemData.bind(this,e));this._renderer.setData({items:t,barSpacing:e,highlightByAuthor:!1})}}{constructor(){super(...arguments),this._profileDataCache=new Map}_extractBarMarksRendererItemData(e,t){const i=super._extractBarMarksRendererItemData(e,t);return{...i,fixedSpaceYPosition:{basePosition:t.y,order:t.order,itemSpacing:.2857142857142857*e},mine:t.mine,borderWidth:t.hovered?i.borderWidth:t.public?1:2,doNotFill:!t.public,direction:t.direction}}async _createTooltipRenderer(){const[{TooltipRenderer:e},{PublishedChartsTimelineTooltip:t}]=await Promise.all([Promise.all([i.e(88548),i.e(6744),i.e(43487),i.e(50690),i.e(70354)]).then(i.bind(i,159217)),Promise.all([i.e(88548),i.e(6744),i.e(43487),i.e(50690),i.e(70354)]).then(i.bind(i,286676))]);return new e(t)}_calculateY(e,t,i){const s=("up"===i.direction?-1:1)*(i.yInverted?-1:1),o=s*(t*i.order+.2857142857142857*t*(i.order+1));return i.y+t/2*s+o}_onItemClicked(e,t,i,s){super._onItemClicked(e,t,i,s),s.isTouch||this.source().showIdea(e.originalItem.id,!1)}async _tooltipProps(e){var t;const i=(0,g.ensureDefined)(e.originalItem.username);let s=this._profileDataCache.get(i);if(void 0===s){try{s=await function(e){return fetch(`/api/v1/user/profile/${e}/?avatars_fallback=true&by=username`).then((e=>e.json()))}(i)}catch(e){return A.logWarn(`An error ocurred while loading profile data: ${e}`),null}this._profileDataCache.set(i,s)}return Promise.resolve({avatarUrl:null===(t=s.avatars)||void 0===t?void 0:t.mid,badges:s.badges,title:(0,g.ensureDefined)(e.originalItem.title),username:i,onTitleClicked:()=>this.source().showIdea(e.originalItem.id,!1)})}}var k=i(888929),E=i(314802);const D=(0,c.getLogger)("Chart.PublishedChartsTimeLine");class N extends n.BarsMarksContainer{constructor(e,t){let i=r().getValue("PublishedChartsTimeline.filter",l.PublishedChartsFilter.None);window.is_authenticated||(i=l.PublishedChartsFilter.None);const s=new m.DefaultProperty("publishedchartstimeline",{filter:i});super(e,s),this.setId("PublishedChartsTimeline"),this._paneView=new L(this,e),this._paneViews=[this._paneView],this._currentRange=null,this._properties.childs().visible.subscribe(this,(()=>{this._getData(this._currentRange)})),s.childs().filter.subscribe(this,(e=>{r().setValue("PublishedChartsTimeline.filter",e.value()),this.clearMarks(),this._getData(this._currentRange)})),this._containsData=e.isSnapshot(),this._containsData&&this._properties.childs().visible.setValue(!0),this.setUserEditEnabled(!1),this._onIdeaClickedHandler=t}destroy(){this._onIdeaClickedHandler=null,this._boundOnMessage&&(a.pushStreamMultiplexer.off("ideas",this._boundOnMessage),a.pushStreamMultiplexer.off("ideas.post",this._boundOnMessage),this._boundOnMessage=null),this._paneView.destroy(),super.destroy()}name(){return"Ideas on chart"}title(){return s.t(null,void 0,i(5400))}zorder(){return k.sortSourcesPreOrdered.BarMarks}paneViews(){ return this._model.isInReplay()||!this._properties.childs().visible.value()?[]:this._paneViews}showIdea(e,t){var i;const s=this._marks[e];s?((0,h.trackEvent)("GUI","View published idea"),t&&(0,h.trackEvent)("GUI","Ideas navigation arrow"),(0,d.onWidget)()||this._containsData||(0,E.isOnMobileAppPage)("any")?window.open(`${this._getBaseUrl()}${s.published_chart_url||"/v/"+s.image_url+"/"}`):null===(i=this._onIdeaClickedHandler)||void 0===i||i.call(this,{chartId:s.image_url,chartName:s.name,publishedUrl:s.published_chart_url,shortSymbol:s.short_name})):D.logDebug("PublishedChartsTimeline.showIdea: unexpected published chart id")}state(e){const t={type:"BarsMarksContainer",id:this.id(),zorder:this.zorder(),pinnedTooltips:this._pinnedTooltips};return e&&this._properties.childs().visible.value()&&(t.marks=this.getPublishedPlates()),t}restoreData(e,t){null!=e.pinnedTooltips&&(this._pinnedTooltips=e.pinnedTooltips),t&&void 0!==e.marks&&(this._marks=e.marks)}onClickOutside(e){this._paneView.onClickOutside(e)}_getIndex(e){return this.timeScale().timePointToIndex(e,1)}_initialize(){a.pushStreamMultiplexer&&(this._boundOnMessage=this._onMessage.bind(this),a.pushStreamMultiplexer.on("ideas",this._boundOnMessage),a.pushStreamMultiplexer.on("ideas.post",this._boundOnMessage))}_plateViewData(e){return{title:e.title,user_id:e.user__id,username:e.username,suggested:e.is_hot,mine:e.user__id===window.user.id,public:e.is_public}}_getData(e,t){const i=this._model.mainSeries().properties().childs(),s=this._model.mainSeries().symbolInfo();if(this._currentRange=e,!s||!this._properties.childs().visible.value()&&!t)return Promise.resolve([]);let o=s.base_name.length>1?s.base_name:[s.pro_name];const r=this.roundRange(this._rangeDifference(e));o=(0,u.uniq)(o),o=o.sort();const n=new FormData;n.append("interval",i.interval.value()),n.append("legs",JSON.stringify(o)),n.append("startTickmark",r.start.toString()),n.append("endTickmark",r.end.toString()),n.append("filter",this.properties().childs().filter.value());const a=(0,p.makeCancelable)(new Promise(((e,t)=>{(0,_.fetch)("/charttimeline/",{method:"POST",body:n,headers:new Headers({acccept:"application/json","X-Requested-With":"XMLHttpRequest"})}).then((i=>{i.ok?i.json().then(e):t()})).catch(t)})));return a.promise.then((t=>{t.forEach((e=>{this._marks[e.id]=e})),this._loadedRange=this._rangeUnion(e,this._loadedRange);const i=this._requests.indexOf(a);~i&&this._requests.splice(i,1),this.updateAllViewsAndRepaint()})),this._requests.push(a),a.promise}_onMessage(e,t,i,s){if(this._containsData)return;const o=this._model.mainSeries(),r=o.symbolInfo(),n=r&&r.base_name;if(!n)return;const a=o.properties().childs();e.interval===a.interval.value()&&~n.indexOf(e.pro_symbol)&&(this._marks[e.id]=e,this.updateAllViewsAndRepaint())}_getBaseUrl(){if((0,d.onWidget)()&&window.locale_domains){const e=window.locale||"en",t=window.locale_domains[e]?window.locale_domains[e]:window.locale_domains.en;return t?document.location.protocol+"//"+t:""}return""}}},154765:(e,t,i)=>{"use strict";i.d(t,{replayModeProperty:()=>c}) ;var s=i(62802),o=i(638456),r=i(125226),n=i(152633);const a="replay_mode";function l(){return(0,r.isFeatureEnabled)("multichart_replay")&&!o.CheckMobile.any()?s.getValue(a,"ActiveChart"):"ActiveChart"}const c=(0,n.createPrimitiveProperty)(l());s.onSync.subscribe(null,(()=>c.setValue(l()))),(0,r.isFeatureEnabled)("multichart_replay")&&c.subscribe(null,(()=>s.setValue(a,c.value())))},944876:(e,t,i)=>{"use strict";i.d(t,{allPriceScaleSelectionStrategyInfo:()=>c,createPriceScaleSelectionStrategy:()=>l});var s=i(650151),o=i(444372),r=i(427937);class n{constructor(e){this._priceScalesLimit=8,this._metaInfo=e}metaInfo(){return this._metaInfo}findSuitableScale(e,t,i,s){if(void 0!==s)return this._tryToGetDesiredPriceScale(e,t,s,i);if((0,r.isStudy)(t)){const s=t.metaInfo();if("Volume"===s.shortId&&e.containsMainSeries())return e.createPriceScaleAtPosition("overlay");const o=t.desiredPriceScalePosition();if(null!==o)return this._tryToGetDesiredPriceScale(e,t,o,i);if(void 0!==i&&((0,r.isStudy)(i)||e.isMainPane())&&s.is_price_study)return this._getPriceScaleTheSameAsForSource(i,e)}let o=!1;if((0,r.isStudy)(t)){const i=t.metaInfo().groupingKey;if(void 0!==i){const t=e.model().findNonOverlayStudyWithGroupingKey(i,e);if(null!==t)return this._getPriceScaleTheSameAsForSource(t.study,t.pane)}o=Boolean(t.metaInfo().is_price_study)}else t===e.model().mainSeries()&&(o=!0);if(o){const t=this._findFirstScaleForPriceStudy(e);if(null!==t)return t}return this.createNewPriceScaleIfPossible(e)}canCreateNewPriceScale(e){return e.leftPriceScales().length+e.rightPriceScales().lengthi&&this._priceScaleIsPrice(e.rightPriceScales()[i],t))return e.rightPriceScales()[i];if(e.leftPriceScales().length>i&&this._priceScaleIsPrice(e.leftPriceScales()[i],t))return e.leftPriceScales()[i]}return null}_targetPriceScaleIndex(e,t){if(e.mainSource()===t.mainSeries())return 0}_tryToGetDesiredPriceScale(e,t,i,o){switch(i){case"left":return this.canCreateNewPriceScale(e)?e.createPriceScaleAtPosition("left"):e.createPriceScaleAtPosition("overlay");case"right":return this.canCreateNewPriceScale(e)?e.createPriceScaleAtPosition("right"):e.createPriceScaleAtPosition("overlay");case"as-series":return void 0!==o?(0,s.ensureNotNull)(o.priceScale()):e.isMainPane()?(0,s.ensureNotNull)((0,s.ensureNotNull)(e.mainDataSource()).priceScale()):this.createNewPriceScaleIfPossible(e);case"overlay":return e.createPriceScaleAtPosition("overlay")}}}const a=[{name:"left",title:o.t(null,void 0,i(665323)),ctor:class extends n{constructor(e){super(e)}apply(e){const t=e.model();e.rightPriceScales().slice(0).forEach((i=>e.movePriceScale(i,"left",this._targetPriceScaleIndex(i,t))))} createNewPriceScaleIfPossible(e){return this.canCreateNewPriceScale(e)?e.createPriceScaleAtPosition("left"):e.createPriceScaleAtPosition("overlay")}}},{name:"right",title:o.t(null,void 0,i(214113)),ctor:class extends n{constructor(e){super(e)}apply(e){const t=e.model();e.leftPriceScales().slice(0).forEach((i=>e.movePriceScale(i,"right",this._targetPriceScaleIndex(i,t))))}createNewPriceScaleIfPossible(e){return this.canCreateNewPriceScale(e)?e.createPriceScaleAtPosition("right"):e.createPriceScaleAtPosition("overlay")}}},{name:"auto",title:o.t(null,void 0,i(86951)),ctor:class extends n{constructor(e){super(e)}apply(e){if(e.containsMainSeries()){const t=(0,s.ensureNotNull)((0,s.ensureNotNull)(e.mainDataSource()).priceScale());e.movePriceScale(t,"right",0)}const t=e.model();for(;e.leftPriceScales().length>e.rightPriceScales().length;){const i=e.leftPriceScales()[e.leftPriceScales().length-1];e.movePriceScale(i,"right",this._targetPriceScaleIndex(i,t))}for(;e.rightPriceScales().length-e.leftPriceScales().length>1;){const i=e.rightPriceScales()[e.rightPriceScales().length-1];e.movePriceScale(i,"left",this._targetPriceScaleIndex(i,t))}}createNewPriceScaleIfPossible(e){if(!this.canCreateNewPriceScale(e))return e.createPriceScaleAtPosition("overlay");const t=e.leftPriceScales().lengtht.name===e)));return new t.ctor(t)}function c(){return a}},287790:(e,t,i)=>{"use strict";i.d(t,{restoreShowNewsNotificationSettingsValue:()=>l,showNewsNotificationsProperty:()=>a});var s=i(62802),o=i(152633);const r="show_news_upd_notif";function n(){return s.getBool(r,!1)}const a=(0,o.createPrimitiveProperty)(n());function l(){a.setValue(!1),s.remove(r)}a.subscribe(null,(()=>s.setValue(r,a.value()))),s.onSync.subscribe(null,(()=>a.setValue(n())))},506312:(e,t,i)=>{"use strict";i.d(t,{getFundamentalIdFromScriptIdPart:()=>o});const s=/^STD;Fund_(.*?)(?:_(?:fy|fq|fh|ttm))?$/;function o(e){const t=e.match(s);return t?t[1]:t}},370552:(e,t,i)=>{"use strict";var s;i.d(t,{InsertionErrorCode:()=>s}),function(e){e.StudyCannotBeChild="cannot_be_child",e.StubWasRemoved="stub_was_removed",e.CannotGetMetainfo="cannot_get_metainfo",e.CannotCompilePub="cannot_compile_pub",e.Cancelled="cancelled",e.Unknown="unknown"}(s||(s={}))},65541:(e,t,i)=>{"use strict";i.d(t,{StudyColorRotatorFactory:()=>h});var s=i(790188),o=i(724377),r=i(246733),n=i(427937) ;const a=["color-sky-blue-400","color-banana-yellow-700","color-deep-blue-500","color-grapes-purple-a700","color-iguana-green-500","color-minty-green-a600","color-ripe-red-a200","color-berry-pink-200","color-tv-blue-a100","color-tan-orange-a200","color-sky-blue-a400","color-deep-blue-a100","color-grapes-purple-400","color-iguana-green-a700","color-minty-green-200","color-ripe-red-200","color-berry-pink-a200","color-ripe-red-500","color-grapes-purple-500","color-deep-blue-400","color-tv-blue-a200","color-sky-blue-500","color-iguana-green-400","color-minty-green-400","color-banana-yellow-600","color-tan-orange-500","color-berry-pink-400","color-ripe-red-300","color-grapes-purple-300","color-deep-blue-300","color-tv-blue-300","color-sky-blue-300","color-iguana-green-300","color-minty-green-300","color-banana-yellow-400","color-tan-orange-300","color-berry-pink-300","color-tan-orange-a700"];class l{constructor(e){this._offset=0,this._offset=e}getColor(e){if(0===this._offset)return e;const t=a[(this._offset-1)%a.length],i=s.colorsPalette[t],n=(0,r.isHexColor)(e)?1:(0,o.parseRgba)(e)[3];return(0,r.generateColor)(i,(0,r.alphaToTransparency)(n))}}class c{constructor(e,t){this._offset=e,this._modelStartOffset=t}getColor(e){if((0,r.isHexColor)(e)){const t=(0,o.parseRgb)(e);return(0,o.rgbToHexString)((0,o.shiftRgb)(t,this._offset,this._modelStartOffset))}{const t=(0,o.parseRgba)(e);return(0,o.rgbaToString)((0,o.shiftRgba)(t,this._offset,this._modelStartOffset))}}}class h{constructor(e){this._chartModel=e}getColorRotator(e){const t=(0,n.studyColorRotationMode)(e);if(null===t)return null;const i=this._calcDefaultColorsOffset(e);switch(t){case"loop":return new l(i);case"shift":{const e=this._chartModel.getStudyShiftColorStartOffset();return new c(i,e)}}}_calcDefaultColorsOffset(e){let t=0;const i=(0,n.useSameColorRotationComparator)(e);return this._chartModel.dataSources().filter(n.isStudy).forEach((s=>{i(e,s.metaInfo())&&t++})),t}}},849245:(e,t,i)=>{"use strict";i.d(t,{StudyInserter:()=>h});var s=i(526075),o=i(389137),r=i(347710),n=i(42292),a=i(370552);const l=(0,i(201089).getLogger)("Chart.Studies.StudyInserter"),c=/^PUB;.*/;class h{constructor(e,t){this._parentSources=[],this._propsState=void 0,this._preferredPriceScale=void 0,this._allowChangeCurrency=!1,this._allowChangeUnit=!1,this._paneSize=void 0,this._forceOverlay=!1,this._inserterImpl=t,this._studyDescriptor=e}setParentSources(e){this._parentSources=e}setPaneSize(e){this._paneSize=e}setPreferredPriceScale(e){this._preferredPriceScale=e}setAllowChangeCurrency(e){this._allowChangeCurrency=e}setAllowChangeUnit(e){this._allowChangeUnit=e}setForceOverlay(e){this._forceOverlay=e}setPropertiesState(e){this._propsState=e}setTargetPriceScaleMode(e){this._targetPriceScaleMode=e}async insert(e,t){var i,h;const d=void 0!==(u=this._inserterImpl).createStub&&void 0!==u.removeStub?this._inserterImpl.createStub():null;var u;let _,p=!0;try{_=await(0,r.studyMetaInfoRepository)().findById(this._studyDescriptor)}catch(e){l.logWarn(`Cannot get study ${JSON.stringify(this._studyDescriptor)}`) ;const t=this._studyDescriptor.pineId,s=c.test(t),o=!!(null===(i=null==e?void 0:e.errors)||void 0===i?void 0:i.length);return s&&o?Promise.reject(a.InsertionErrorCode.CannotCompilePub):Promise.reject(a.InsertionErrorCode.CannotGetMetainfo)}finally{null!==d&&(p=this._inserterImpl.removeStub(d))}if(!p)return Promise.reject(a.InsertionErrorCode.StubWasRemoved);if(void 0!==t&&t.cancelled)return Promise.reject(a.InsertionErrorCode.Cancelled);if(!this._canApplyStudyToParent(_))return Promise.reject(a.InsertionErrorCode.StudyCannotBeChild);const m={..._.defaults.inputs};let g={};if(void 0!==e){const t=s.StudyMetaInfo.getStudyPropertyRootName(_),i=(0,o.clone)((0,n.defaults)(t));(0,o.merge)(m,i.inputs);const r=await e(m,_.inputs,_);g=r.inputs,this._parentSources=null!==(h=r.parentSources)&&void 0!==h?h:[]}if(void 0!==t&&t.cancelled)return Promise.reject(a.InsertionErrorCode.Cancelled);const S=this._insertStudy(_,g);return null===S?Promise.reject(a.InsertionErrorCode.Unknown):(await S.startPromise,S.study)}_insertStudy(e,t){return this._inserterImpl.createStudy(e,t,null,this._propsState,this._forceOverlay,this._parentSources,this._preferredPriceScale,this._allowChangeCurrency,this._allowChangeUnit,this._paneSize,this._targetPriceScaleMode)}_canApplyStudyToParent(e){return 0===this._parentSources.length||s.StudyMetaInfo.canBeChild(e)}}},459711:(e,t,i)=>{"use strict";i.d(t,{StudyLineToolStub:()=>n,isStudyLineToolStub:()=>r});var s=i(401580),o=i(306682);function r(e){return e instanceof n}class n extends o.StudyStub{constructor(e,t,i){var o;super(e,{...t,ownFirstValue:null},i),this._linkKey=new s.WatchedValue(null!==(o=t.linkKey)&&void 0!==o?o:null)}linkKey(){return this._linkKey}}},167258:(e,t,i)=>{"use strict";var s=i(707957).Delegate;function o(){this._marksByIndex=new Map,this._marksBySpan=[],this.changed=new s,this.minIndex=void 0,this.maxIndex=void 0}o.prototype.reset=function(){this._resetImpl(),this.changed.fire()},o.prototype._resetImpl=function(){this._marksByIndex=new Map,this._marksBySpan=[],this.minIndex=void 0,this.maxIndex=void 0,this._cache=void 0},o.prototype.merge=function(e){if(0!==e.length){var t=e[0].index,i=e[e.length-1].index;t<=this.minIndex&&i>=this.maxIndex&&this._resetImpl();for(var s=this._marksBySpan,o=new Set,r=0;r=this.maxIndex&&this.maxIndex--,this.maxIndex2;){if(1e3*this._marksByIndex.get(t).time===e)return t;if(1e3*this._marksByIndex.get(i).time===e)return i;var s=Math.round((t+i)/2);1e3*this._marksByIndex.get(s).time>e?i=s:t=s}return t},o.prototype.build=function(e,t){var i=Math.ceil(t/e);if(this._maxbar===i&&this._cache)return this._cache;this._maxbar=i;for(var s=[],o=this._marksBySpan.length;o--;)if(this._marksBySpan[o]){var r=s;s=[];for(var n=r.length,a=0,l=this._marksBySpan[o],c=l.length,h=1/0,d=-1/0,u=0;u=i&&p-d>=i&&(s.push(_),d=p)}for(;ae.index>=i&&e.index<=s))}return{marks:t=t.map((function(e){return[e.span,e.time,e.index]})),version:2}},o.prototype.restoreState=function(e){if(this._marksByIndex=new Map,this._marksBySpan=[],this.maxIndex=void 0,this.minIndex=void 0,e&&e.marks&&e.marks.length)if(2===e.version){var t=e.marks.map((function(e){return{span:e[0],time:e[1],index:e[2]}}));this.merge(t)}else this.merge(e.marks)},e.exports.Tickmarks=o},458527:(e,t,i)=>{"use strict";i.d(t,{trackChartStyleChanged:()=>h,trackDrawingCloned:()=>c,trackDrawingCreated:()=>a,trackDrawingPasted:()=>l});var s=i(776734),o=i(650151),r=i(339315);function n(e,t){(0,s.getTracker)().then((i=>{if(null!==i){const s=(0,o.ensureNotNull)(e.model().mainSeries().symbolInfo()),r=s.pro_name||s.name;i.trackDrawingsAnalytics(r,e.name(),t)}}))}function a(e){n(e,"create")}function l(e){n(e,"paste")}function c(e){n(e,"clone")}function h(e){(0,s.getTracker)().then((t=>{if(null!==t){const i=r.STYLE_SHORT_NAMES[e];t.trackChartStyle(i)}}))}},440058:(e,t,i)=>{"use strict";i.d(t,{forceTradingObjVisibilityOnScreenshot:()=>h,restoreShowOnScreenshotSettingsValue:()=>c, showOnScreenshotProperty:()=>l});var s=i(62802),o=i(401580),r=i(152633);const n="trading_drawings_on_screenshot";function a(){return s.getBool(n,!1)}const l=(0,r.createPrimitiveProperty)(a());function c(){l.setValue(!1),s.remove(n)}s.onSync.subscribe(null,(()=>l.setValue(a()))),l.subscribe(null,(()=>s.setValue(n,l.value())));const h=new o.WatchedValue(null)},376163:(e,t,i)=>{"use strict";i.d(t,{ApplyLineToolTemplateUndoCommand:()=>o});var s=i(142257);class o extends s.UndoCommand{constructor(e,t,i){super(i),this._source=e,this._newState=t,this._oldState=e.properties().state()}redo(){this._source.applyTemplate(this._newState)}undo(){this._source.applyTemplate(this._oldState)}}},553582:(e,t,i)=>{"use strict";i.d(t,{CreateLineToolUndoCommand:()=>c});var s=i(650151),o=i(444372),r=i(809796),n=i(750860),a=i(918208);const l=new r.TranslatedString("create {tool}",o.t(null,void 0,i(581791)));class c extends n.LineToolSynchronizeUndoCommand{constructor({model:e,pane:t,lineTool:i,ownerSource:s,drawOnAllChartsMode:o=0,id:n}){super(e,l.format({tool:new r.TranslatedString(i,a.lineToolsLocalizedNames[i])}),!1),this._lineId=null,this._lineState=null,this._paneIndex=e.panes().indexOf(t),this._lineTool=i,this._ownerSourceId=s.id(),this._lineId=null!=n?n:null,this._drawOnAllChartsMode=o}startCreatingLine(e,t,i,s){var o;const r=this._chartModel.panes()[this._paneIndex],n=this._chartModel.dataSourceForId(this._ownerSourceId),a=this._chartModel.createLineTool(r,e,this._lineTool,t,i,s,n||void 0,null!==(o=this._lineId)&&void 0!==o?o:void 0);return this._lineId=a.id(),!this._chartModel.lineBeingCreated()}continueCreatingLine(e,t,i,s){const o=this._chartModel.continueCreatingLine(e,t,i,s);return o&&this._chartModel.setShouldBeSavedEvenIfHidden(!0),o}line(){return null===this._lineId?null:this._chartModel.dataSourceForId(this._lineId)}drawOnAllCharts(){return 0!==this._drawOnAllChartsMode}_redo(){if(null===this._lineState)return;const e=this._chartModel.restoreSource(!1,this._paneIndex,null,(0,s.ensureNotNull)(this._lineState),null);null!==e&&(this._lineId=e.id(),this._lineState=null,e.share(this._drawOnAllChartsMode))}_undo(){const e=this.line();null!==e&&(this._lineState=e.state(!1),this._chartModel.removeSource(e),this._lineId=null)}}},731327:(e,t,i)=>{"use strict";i.d(t,{ExcludeLineToolsFromGroupUndoCommand:()=>c});var s=i(650151),o=(i(586463),i(444372)),r=i(809796),n=i(389137),a=i(142257);const l=new r.TranslatedString("exclude line tools from group {group}",o.t(null,void 0,i(363391)));class c extends a.UndoCommand{constructor(e,t,i){super(l.format({group:t.name().value()})),this._model=e,this._groupId=t.id,this._groupName=t.name().value(),this._lineToolsIds=i.map((e=>e.id()))}redo(){const e=(0,s.ensureNotNull)(this._model.lineToolsGroupModel().groupForId(this._groupId)),t=this._lineToolsIds.map((e=>this._model.dataSourceForId(e))).filter(n.notNull);e.excludeLineTools(t),0===e.lineTools().length&&this._model.lineToolsGroupModel().removeGroup(e)}undo(){ const e=this._lineToolsIds.map((e=>this._model.dataSourceForId(e))),t=this._model.lineToolsGroupModel().groupForId(this._groupId);null!==t?t.addLineTools(e):this._model.lineToolsGroupModel().createGroup(e,this._groupName,this._groupId)}}},750860:(e,t,i)=>{"use strict";i.d(t,{LineToolSynchronizeUndoCommand:()=>o});var s=i(142257);class o extends s.UndoCommand{constructor(e,t,i){super(t,i),this._invalidateViaSync=!1,this._chartModel=e,this._invalidateViaSync=e.lineToolsSynchronizer().invalidateViaSync()}redo(){this._invalidateViaSync?this._chartModel.lineToolsSynchronizer().executeSyncedAction((()=>this._redo())):this._redo()}undo(){this._invalidateViaSync?this._chartModel.lineToolsSynchronizer().executeSyncedAction((()=>this._undo())):this._undo()}}},371764:(e,t,i)=>{"use strict";i.d(t,{PriceScaleChangeUndoCommand:()=>h});var s=i(650151),o=i(444372),r=i(809796),n=i(201089),a=i(142257);const l=(0,n.getLogger)("Chart.ChartUndoModel"),c=new r.TranslatedString("scale price",o.t(null,void 0,i(347222)));class h extends a.UndoCommand{constructor(e,t,i,s,o){super(c,!1),this._newPriceScaleState=null,this._model=e,this._paneIndex=e.panes().indexOf(t),this._priceScaleId=i.id(),this._state=s,this._timestamp=o?performance.now():null}undo(){if(null!==this._newPriceScaleState)return void l.logDebug("PriceScaleChangeUndoCommand.undo: Command is already undone");const[e,t]=this._paneAndScale();this._newPriceScaleState=t.state(),this._model.restorePriceScaleState(e,t,this._state)}redo(){if(null===this._newPriceScaleState)return void l.logDebug("PriceScaleChangeUndoCommand.redo: Command is not undone");const[e,t]=this._paneAndScale();this._model.restorePriceScaleState(e,t,this._newPriceScaleState),this._newPriceScaleState=null}canMerge(e){return e instanceof h&&null!==this._timestamp&&null!==e._timestamp&&null===this._newPriceScaleState&&e._model===this._model&&e._paneIndex===this._paneIndex&&e._priceScaleId===this._priceScaleId&&Math.abs(e._timestamp-this._timestamp)<1e3}merge(e){this._timestamp=e._timestamp}_paneAndScale(){const e=this._model.panes()[this._paneIndex],t=(0,s.ensureNotNull)(e.getPriceScaleById(this._priceScaleId));return[e,t]}}},744084:(e,t,i)=>{"use strict";i.d(t,{RemoveLineDataSourcesUndoCommand:()=>n});var s=i(650151),o=i(750860),r=i(731327);class n extends o.LineToolSynchronizeUndoCommand{constructor({chartModel:e,title:t,lineDataSourceIds:i}){super(e,t),this._excludeLineToolsFromGroupUndoCommands=[],this._undoState=[],this._lineDataSourceIds=i}_redo(){const e=this._lineDataSourceIds.map((e=>(0,s.ensureNotNull)(this._chartModel.dataSourceForId(e))));this._groupLineToolsByGroups(e).forEach(((e,t)=>{const i=new r.ExcludeLineToolsFromGroupUndoCommand(this._chartModel,t,e);i.redo(),this._excludeLineToolsFromGroupUndoCommands.push(i)})),e.forEach((e=>{this._undoState.push({state:e.state(!1),paneIndex:this._chartModel.panes().indexOf((0,s.ensureNotNull)(this._chartModel.paneForSource(e))),sharingMode:e.sharingMode().value()}),this._chartModel.removeSource(e)}))}_undo(){var e ;for(let t=this._undoState.shift();t;t=this._undoState.shift())null===(e=this._chartModel.restoreSource(!1,t.paneIndex,null,t.state,null))||void 0===e||e.share(t.sharingMode);this._excludeLineToolsFromGroupUndoCommands.forEach((e=>e.undo()))}_groupLineToolsByGroups(e){const t=this._chartModel.lineToolsGroupModel();return e.reduce(((e,i)=>{const s=t.groupForLineTool(i);if(null!==s){const t=e.get(s)||[];t.push(i),e.set(s,t)}return e}),new Map)}}},558105:(e,t,i)=>{"use strict";i.d(t,{RemoveSourcesUndoCommand:()=>m});var s=i(650151),o=i(444372),r=i(809796),n=i(247001),a=i(750860),l=i(713473),c=i(201089),h=i(569010),d=i(427937),u=i(744084);const _=(0,c.getLogger)("Chart.RemoveSourcesUndoCommand"),p=new r.TranslatedString("remove line data sources",o.t(null,void 0,i(66414)));class m extends a.LineToolSynchronizeUndoCommand{constructor(e,t,i){super(e,i),this._removeLineDataSourcesUndoCommand=null,this._initialPriceScaleMode=null;const[o,r]=(0,h.closeSourcesSet)(e,t).reduce(((e,t)=>((0,l.isLineTool)(t)?e[1].push(t.id()):e[0].push(t.id()),e)),[[],[]]);this._sourceIds=o,this._lineDataSourceIds=r,this._sourceStates=[],this._paneIndexes=[],this._priceScalePositionIds=[],this._paneStates=[],this._restorePanes=[];const n=t[0];1===t.length&&(0,d.isStudy)(n)&&(this._initialPriceScaleMode=(0,s.ensureNotNull)(n.priceScale()).mode())}removedIds(){return[...this._sourceIds,...this._lineDataSourceIds]}_redo(){const e=this._chartModel.panes().length,t=this._sourceIds.map((e=>(0,s.ensureNotNull)(this._chartModel.dataSourceForId(e))));this._sourceStates=t.map((e=>(0,s.ensureNotNull)(e.state(!1))));const i=t.map((e=>(0,s.ensureNotNull)(this._chartModel.paneForSource(e))));this._paneIndexes=i.map((e=>this._chartModel.panes().indexOf(e))),this._lineDataSourceIds.length>0&&(this._removeLineDataSourcesUndoCommand=new u.RemoveLineDataSourcesUndoCommand({title:p,chartModel:this._chartModel,lineDataSourceIds:this._lineDataSourceIds}),this._removeLineDataSourcesUndoCommand.redo()),this._priceScalePositionIds=t.map(((e,t)=>{const s=e.priceScale();if(null===s)return null;const o=i[t].priceScalePosition(s);return{id:s.id(),position:o,priceScaleIndex:i[t].priceScaleIndex(s,o)}}));const o=new Set;t.forEach(((e,t)=>{o.add(this._paneIndexes[t])})),this._paneStates=t.map(((e,t)=>{const s=this._paneIndexes[t];return o.has(s)?i[t].state(!1,!0):null})),this._restorePanes=t.map((e=>this._chartModel.removeSource(e))),t.forEach((e=>{(0,d.isStudy)(e)&&(0,n.trackStudies)(e,"remove")})),e!==this._chartModel.panes().length&&this._chartModel.setShouldBeSavedEvenIfHidden(!0)}_undo(){const e=[];for(let t=this._sourceStates.length-1;t>=0;t--){const i=this._chartModel.restoreSource(this._restorePanes[t],this._paneIndexes[t],this._paneStates[t],this._sourceStates[t],this._priceScalePositionIds[t]);i&&e.push(i)}e.some(((t,i)=>t.id()!==this._sourceIds[e.length-i-1]))&&_.logError("Source was restored improperly - source ids does not match"),null!==this._initialPriceScaleMode&&(0,s.ensureNotNull)(e[0].priceScale()).setMode(this._initialPriceScaleMode), this._removeLineDataSourcesUndoCommand&&this._removeLineDataSourcesUndoCommand.undo()}}},727803:(e,t,i)=>{"use strict";i.d(t,{RestoreDefaultsPreferencesUndoCommand:()=>w});var s=i(650151),o=i(444372),r=i(809796),n=i(142257),a=i(155964),l=i(992543),c=i(827023),h=i(14952),d=i(261066),u=i(480059),_=i(535503),p=i(939702),m=i(287790),g=i(690142),S=i(440058),v=i(490515),f=i(939243),b=i(439016),y=i(360758);const C=new r.TranslatedString("apply all chart properties",o.t(null,void 0,i(64034)));class w extends n.UndoCommand{constructor(e){super(C),this._trading=null,this._oldShowSellBuyButtons=null,this._oldNoConfirmEnabled=null,this._oldShowOnlyRejectionNotifications=null,this._oldShowPricesWithZeroVolume=null,this._oldShowPricesWithSpread=null,this._oldOrderExecutedSoundEnabled=null,this._prevWatermarkPreferences=null,this._prevAlertPreferences=null,this._model=e,this._trading=(0,b.tradingService)(),null!==this._trading&&(this._oldShowSellBuyButtons=this._trading.showSellBuyButtons.value(),this._oldNoConfirmEnabled=this._trading.noConfirmEnabled.value(),this._oldShowOnlyRejectionNotifications=this._trading.showOnlyRejectionNotifications.value(),this._oldShowPricesWithZeroVolume=this._trading.showPricesWith().zeroVolume.value(),this._oldShowPricesWithSpread=this._trading.showPricesWith().spread.value(),this._oldOrderExecutedSoundEnabled=this._trading.orderExecutedSoundParams.enabled.value()),this._defaultsPreferences=(0,a.defaultsPreferencesByWhiteList)(this._model,this._model.mainSeries()),this._oldPreferences=e.preferences(),this._prevDateFormat=l.dateFormatProperty.value(),this._prevAlertPreferences=(0,f.getSettingsProperty)().state(),this._model.onWidget()||(this._prevWithWeekday=g.withWeekdayProperty.value()),this._prevTimeHoursFormat=c.timeHoursFormatProperty.value(),this._prevAddPlusButton=y.addPlusButtonProperty.value(),this._prevShowOpenMarkerStatus=h.showMarketOpenStatusProperty.value(),this._prevCurrencyUnitVisibility=(0,d.currencyUnitVisibilityProperty)().value(),this._prevAutoLogButtonsVisibility=(0,u.autoLogButtonsVisibilityProperty)().value(),this._prevNavigationButtonsVisibility=(0,_.property)().value(),this._prevPaneButtonsVisibility=(0,p.property)().value();const t=this._model.watermarkSource();null!==t&&(this._prevWatermarkPreferences=t.properties().state())}redo(){null!==this._trading&&(this._trading.showSellBuyButtons.setValue(!0),this._trading.noConfirmEnabled.setValue(!1),this._trading.showOnlyRejectionNotifications.setValue(!1),this._trading.showPricesWith().zeroVolume.setValue(!0),this._trading.showPricesWith().spread.setValue(!0),this._trading.orderExecutedSoundParams.enabled.setValue(!1)),this._defaultsPreferences.mainSeries.volFootprintStyle.bgColors=(0,v.getBgColorsDefaults)(),this._model.applyPreferences(this._defaultsPreferences),this._model.updateScales(),(0,l.restoreDateFormatSettingsValue)(),(0,c.restoreTimeHoursFormatSettingsValue)(),(0,y.restoreAddPlusButtonSettingsValue)(),(0,h.restoreShowMarketOpenStatusProperty)(),(0,d.restoreCurrencyUnitVisibilitySettingsValue)(),(0, u.restoreAutoLogButtonsVisibilitySettingsValue)(),(0,_.restoreNavigationButtonsVisibilitySettingsValue)(),(0,p.restorePaneButtonsVisibilitySettingsValue)(),(0,g.restoreWithWeekdaySettingsValue)(),(0,S.restoreShowOnScreenshotSettingsValue)(),(0,m.restoreShowNewsNotificationSettingsValue)(),(0,f.restoreSettingsProperty)();const e=this._model.watermarkSource();null!==e&&e.restorePropertiesDefaults()}undo(){null!==this._trading&&(this._trading.showSellBuyButtons.setValue((0,s.ensureNotNull)(this._oldShowSellBuyButtons)),this._trading.noConfirmEnabled.setValue((0,s.ensureNotNull)(this._oldNoConfirmEnabled)),this._trading.showOnlyRejectionNotifications.setValue((0,s.ensureNotNull)(this._oldShowOnlyRejectionNotifications)),this._trading.showPricesWith().zeroVolume.setValue((0,s.ensureNotNull)(this._oldShowPricesWithZeroVolume)),this._trading.showPricesWith().spread.setValue((0,s.ensureNotNull)(this._oldShowPricesWithSpread)),this._trading.orderExecutedSoundParams.enabled.setValue((0,s.ensureNotNull)(this._oldOrderExecutedSoundEnabled))),this._model.applyPreferences(this._oldPreferences),this._model.updateScales(),l.dateFormatProperty.setValue(this._prevDateFormat),c.timeHoursFormatProperty.setValue(this._prevTimeHoursFormat),h.showMarketOpenStatusProperty.setValue(this._prevShowOpenMarkerStatus),y.addPlusButtonProperty.setValue(this._prevAddPlusButton),(0,d.currencyUnitVisibilityProperty)().setValue(this._prevCurrencyUnitVisibility),(0,u.autoLogButtonsVisibilityProperty)().setValue(this._prevAutoLogButtonsVisibility),(0,_.property)().setValue(this._prevNavigationButtonsVisibility),(0,p.property)().setValue(this._prevPaneButtonsVisibility),null!==this._prevAlertPreferences&&(0,f.getSettingsProperty)().mergeAndFire(this._prevAlertPreferences),this._model.onWidget()||g.withWeekdayProperty.setValue(this._prevWithWeekday);const e=this._model.watermarkSource();null!==e&&null!==this._prevWatermarkPreferences&&e.properties().mergeAndFire(this._prevWatermarkPreferences)}}},209800:(e,t,i)=>{"use strict";i.d(t,{SetPriceScaleModeCommand:()=>n});var s=i(853965),o=i(142257),r=i(964824);class n extends o.UndoCommand{constructor(e,t,i,s){super(i),this._newMode=e,this._priceScaleId=t.id(),this._model=s,this._oldMode=t.mode()}redo(){this._applyMode(this._newMode)}undo(){this._applyMode(this._oldMode)}_applyMode(e){const t=this._findPriceScaleById();null!==t&&((0,s.saveDefaultProperties)(!0),t.setMode(e),(0,s.saveDefaultProperties)(!1),this._model&&(this._model.recalculateAllPanes((0,r.viewportChangeEvent)()),this._model.lightUpdate()))}_findPriceScaleById(){const e=this._model.panes();for(let t=0;t{"use strict";i.d(t,{SetPriceScaleSelectionStrategyCommand:()=>a});var s=i(650151),o=i(142257),r=i(944876);class n{constructor(e){this._leftScales=e.leftPriceScales().map((e=>e.id())),this._rightScales=e.rightPriceScales().map((e=>e.id()))}restorePane(e){this._leftScales.reverse().map((t=>(0, s.ensureNotNull)(e.getPriceScaleById(t)))).forEach((t=>e.movePriceScale(t,"left"))),this._rightScales.reverse().map((t=>(0,s.ensureNotNull)(e.getPriceScaleById(t)))).forEach((t=>e.movePriceScale(t,"right")))}}class a extends o.UndoCommand{constructor(e,t,i){super(i),this._chartModel=e,this._targetStrategy=(0,r.createPriceScaleSelectionStrategy)(t),this._initialState=e.panes().map((e=>new n(e)))}redo(){this._chartModel.panes().forEach((e=>e.setPriceScaleSelectionStrategy(this._targetStrategy))),this._chartModel.fullUpdate()}undo(){const e=this._chartModel.panes();for(let t=0;t{"use strict";i.d(t,{SetScaleRatioPropertiesCommand:()=>n});var s=i(142257),o=i(853965),r=i(964824);class n extends s.UndoCommand{constructor(e,t,i,s){super(i),this._property=e,this._newValue=t,this._model=s,this._priceScale=this._model.mainSeries().priceScale(),this._oldValue=this._property.value(),this._oldMode=this._priceScale.mode()}redo(){this._oldValue=this._property.value(),this._oldMode=this._priceScale.mode(),(0,o.saveDefaultProperties)(!0),this._priceScale.setMode({autoScale:!1,percentage:!1,log:!1}),this._property.setValue(this._newValue),(0,o.saveDefaultProperties)(!1),this._model.recalculateAllPanes((0,r.viewportChangeEvent)()),this._model.lightUpdate()}undo(){(0,o.saveDefaultProperties)(!0),this._property.setValue(this._oldValue),this._priceScale.setMode(this._oldMode),(0,o.saveDefaultProperties)(!1),this._model.recalculateAllPanes((0,r.viewportChangeEvent)()),this._model.lightUpdate()}}},993713:(e,t,i)=>{"use strict";i.d(t,{SetWatchedValueCommand:()=>o});var s=i(142257);class o extends s.UndoCommand{constructor(e,t,i){super(i),this._wv=e,this._newValue=t,this._oldValue=e.value()}redo(){this._wv.setValue(this._newValue)}undo(){this._wv.setValue(this._oldValue)}}},569010:(e,t,i)=>{"use strict";function s(e,t){let i=[];const o=e.children(t,!1);for(let t=0;t{e.children(t,!1).forEach((e=>{i.has(e)||(i.add(e),o(e))}))};return t.forEach(o),t.filter((e=>!i.has(e))).map((t=>s(e,t))).reduce(((e,t)=>e.concat(t)),[])}i.d(t,{closeSourcesSet:()=>o})},744728:(e,t,i)=>{"use strict";i.d(t,{SwapChartsUndoCommand:()=>a});var s=i(444372),o=i(809796),r=i(142257);const n=new o.TranslatedString("swap charts in the Layout",s.t(null,void 0,i(665818)));class a extends r.UndoCommand{constructor(e,t,i){super(n),this._swapper=e,this._from=t,this._to=i}redo(){this._swapper(this._from,this._to)}undo(){this._swapper(this._from,this._to)}}},89820:(e,t,i)=>{"use strict";i.d(t,{TimeScaleChangeUndoCommand:()=>n});var s=i(201089),o=i(142257);const r=(0,s.getLogger)("Chart.ChartUndoModel");class n extends o.UndoCommand{constructor(e,t,i){super(i,!1),this._newRightOffsetAndBarSpacing=null,this.setCustomFlag("doesnt_affect_save",!0),this._model=e,this._rightOffsetAndBarSpacing=t}undo(){ if(null!==this._newRightOffsetAndBarSpacing)return void r.logDebug("TimeScaleChangeUndoCommand.undo: Command is already undone");const e=this._model.timeScale();this._newRightOffsetAndBarSpacing={barSpacing:e.barSpacing(),rightOffset:e.rightOffset()},e.setBarSpacing(this._rightOffsetAndBarSpacing.barSpacing),e.setRightOffset(this._rightOffsetAndBarSpacing.rightOffset),this._model.lightUpdate()}redo(){if(null===this._newRightOffsetAndBarSpacing)return void r.logDebug("TimeScaleChangeUndoCommand.redo: Command is not undone");const e=this._model.timeScale();e.setBarSpacing(this._newRightOffsetAndBarSpacing.barSpacing),e.setRightOffset(this._newRightOffsetAndBarSpacing.rightOffset),this._model.lightUpdate(),this._newRightOffsetAndBarSpacing=null}}},142257:(e,t,i)=>{"use strict";i.d(t,{UndoCommand:()=>o});var s=i(809796);class o{constructor(e,t=!0){this._customFlags={},this._text=e||new s.TranslatedString("",""),this._executeOnPush=t}text(){return this._text}executeOnPush(){return this._executeOnPush}customFlag(e){return this._customFlags[e]}setCustomFlag(e,t){this._customFlags[e]=t}canMerge(e){return!1}merge(e){throw new Error("Should be re-implemented in child classes")}}},176019:(e,t,i)=>{"use strict";i.d(t,{createUndoHistory:()=>h});var s=i(650151),o=i(13294),r=i(345297),n=i(993713),a=i(201089),l=i(707957);const c=(0,a.getLogger)("Common.UndoHistory");function h(){const e=[],t=new o.UndoStack,i=new o.UndoStack,a=new l.Delegate;function h(s){if(e.length>0)e[e.length-1].addCommand(s);else{i.clear();const e=t.head(),o=e&&e.text().originalText();e&&e.canMerge(s)?e.merge(s):t.push(s);const r=s.text().originalText();""!==r&&r!==o&&c.logNormal("DO: "+r)}s.executeOnPush()&&s.redo(),e.length||a.fire(d())}function d(){const e=t.head(),s=i.head(),o=void 0===e?void 0:e.text(),r=void 0===s?void 0:s.text();return{enableUndo:!t.isEmpty(),undoCommandCount:t.size(),undoText:void 0!==o?o.translatedText():o,enableRedo:!i.isEmpty(),redoCommandCount:i.size(),redoText:void 0!==r?r.translatedText():r,originalUndoText:void 0!==o?o.originalText():void 0,originalRedoText:void 0!==r?r.originalText():void 0}}return{beginUndoMacro:function(t){const i=new r.UndoMacroCommand(t);return e.push(i),i},clearStack:function(){t.clear(),i.clear(),a.fire(d())},createUndoCheckpoint:function(){return{lastActualCommand:t.isEmpty()?null:t.head()}},endUndoMacro:function(){const t=(0,s.ensureDefined)(e.pop());t.isEmpty()||h(t)},pushUndoCommand:h,redo:function(){if(i.isEmpty())return!1;const e=i.pop();return!!e&&(e.redo(),t.push(e),c.logNormal("REDO: "+e.text().originalText()),a.fire(d()),!0)},redoStack:function(){return i},setWatchedValue:function(e,t,i,s){if(e.value()!==t){const o=new n.SetWatchedValueCommand(e,t,i);o.setCustomFlag("doesnt_affect_save",!!s),h(o),o.redo()}},undo:function(){if(t.isEmpty())return!1;const e=t.pop();return!!e&&(e.undo(),i.push(e),c.logNormal("UNDO: "+e.text().originalText()),a.fire(d()),!0)},undoStack:function(){return t},undoToCheckpoint:function(e){for(;!t.isEmpty()&&e.lastActualCommand!==t.head();)t.pop().undo();i.clear(), a.fire(d())},state:d,onChange:function(){return a}}}},345297:(e,t,i)=>{"use strict";i.d(t,{UndoMacroCommand:()=>o});var s=i(142257);class o extends s.UndoCommand{constructor(e){super(e,!1),this._subcommands=[]}addCommand(e){this._subcommands.push(e)}isEmpty(){return 0===this._subcommands.length}redo(){for(let e=0;e=0;e--)this._subcommands[e].undo()}commands(){return this._subcommands}}},13294:(e,t,i)=>{"use strict";i.d(t,{UndoStack:()=>n});var s=i(142257),o=i(707957);const r=(0,i(201089).getLogger)("Common.UndoStack");class n{constructor(){this._commands=[],this._onChange=new o.Delegate}onChange(){return this._onChange}isEmpty(){return 0===this._commands.length}size(){return this._commands.length}clear(){this.isEmpty()||(this._commands.length=0,this._onChange.fire())}push(e){if(!(e instanceof s.UndoCommand))throw new TypeError("argument must be an instance of UndoCommand");this._commands.push(e),this._onChange.fire(e)}pop(){if(this.isEmpty())return void r.logDebug("pop: undo stack is empty");const e=this._commands.pop();return this._onChange.fire(e),e}head(){if(!this.isEmpty())return this._commands[this._commands.length-1]}}},438907:(e,t,i)=>{"use strict";i.d(t,{sourceNewUnitOnPinningToPriceScale:()=>n,unitConvertibleGroups:()=>r});var s=i(981107),o=i(444331);function r(e,t,i){const s=(0,o.symbolUnitConvertibleGroupsIfExist)(e,!0);if(null!==s)return s;const r=i.unitGroupById(t);return null===r?[]:[r]}function n(e,t,i,o){let n=null;if(i.unitConversionEnabled()&&(0,s.isSymbolSource)(e)){const s=i.availableUnits(),a=t.unit(s),l=e.unit(),c=null===l?[]:r(e.symbolInfo(),l,s);null!==a&&null!==a.selectedUnit&&!a.allUnitsAreOriginal&&a.selectedUnit!==l&&(o&&null===l||null!==l&&s.convertible(l,c))&&(n=a.selectedUnit)}return n}},347900:(e,t,i)=>{"use strict";i.r(t),i.d(t,{restoreWatermarkPropertyDefaults:()=>h,watermarkProperty:()=>c});var s=i(62802),o=i(190973);const r="symbolWatermark",n={visibility:!1,color:"rgba(80, 83, 94, 0.25)"};function a(){const e=s.getJSON(r);return Object.assign({},n,e)}let l=null;function c(){return null===l&&(l=new o.default(a()),s.onSync.subscribe(null,(()=>{null!==l&&l.mergeAndFire(a())})),l.listeners().subscribe(null,(()=>{null!==l&&s.setJSON(r,l.state())}))),l}function h(){null!==l&&l.mergeAndFire(n)}},767359:(e,t,i)=>{"use strict";var s=i(168883).translatedIntervalString,o=i(665570).getTranslatedSymbolDescription,r=i(422333).CHART_FONT_FAMILY,n=i(347900),a=n.watermarkProperty,l=n.restoreWatermarkPropertyDefaults,c=i(199471).drawScaled,h=i(42292).applyDefaultsOverrides,d=i(42292).applyPropertiesOverrides;const u="symbolWatermark";t.Watermark=function(e,t){var i={},n=a();function _(e,t){var s=e.font;return i.hasOwnProperty(s)||(i[s]={}),i[s].hasOwnProperty(t)||(i[s][t]=e.measureText(t).width),i[s][t]}h(n,void 0,!1,u),n.listeners().subscribe(this,(function(){e.updateSource(this)})),this.destroy=function(){n.listeners().unsubscribeAll(this)},this.properties=function(){return n}, this.restorePropertiesDefaults=function(){l()},this.applyOverrides=function(e){d(n,void 0,!1,e,u)};var p={renderer:function(i){const{cssHeight:a,cssWidth:l}=i;return{draw:function(i,h){c(i,h.pixelRatio,h.pixelRatio,(function(){var c=t.symbolInfo();i.fillStyle=n.color.value();var h,d=c.name;/QUANDL/.test(c.exchange)&&((h=d.split(/\//)).length&&(d=h[h.length-1]));var u={description:c.description,short_description:c.short_description,pro_name:c.pro_name,short_name:c.name,local_description:c.local_description,language:c.language};const p=e.watermarkContentProvider(),m=p?p({symbolInfo:c,interval:t.interval()}):null;for(var g=(m?m.map((e=>({text:e.text,font:`${e.fontSize}px ${r}`,lineHeight:e.lineHeight,vertOffset:e.vertOffset}))):null)||[{text:d?d+", "+s(t.interval()):"",font:"96px "+r,lineHeight:117,vertOffset:0},{text:o(u)||"",font:"48px "+r,lineHeight:58,vertOffset:5}],S=0,v=0;vl?l/f:1,S+=y.lineHeight*y.zoom}}var b=Math.max((a-S)/2,0);for(v=0;v{"use strict";i.d(t,{restoreWithWeekdaySettingsValue:()=>l,withWeekdayProperty:()=>a});var s=i(62802),o=i(152633);const r="date_format_with_weekday";function n(){return s.getBool(r,!0)}const a=(0,o.createPrimitiveProperty)(n());function l(){a.setValue(!0),s.remove(r)}a.subscribe(null,(()=>s.setValue(r,a.value()))),s.onSync.subscribe(null,(()=>a.setValue(n())))},46955:(e,t,i)=>{"use strict";i.d(t,{moveAfterSource:()=>k,moveBeforeSource:()=>E,newLineToolZOrder:()=>C,newStudyZOrder:()=>w,reorderDataSourcesStateZOrder:()=>f});var s=i(713473),o=i(427937),r=i(440617),n=i(790524),a=i(674981);function l(e){return(0,s.isLineTool)(e)&&!e.isSpeciallyZOrderedSource()}function c(e){return(0,o.isStudy)(e)&&!e.isSpeciallyZOrderedSource()}function h(e,t){return e.zorder-t.zorder}function d(e,t){(0,n.isMainSeriesState)(e)?e.zorder=0:e.zorder=t}function u(e,t){e.setZorder(t)}function _(e){return e.zorder()}function p(e){return Math.round(1e3*e)/1e3}function m(e,t){const i=Math.max(e,t),s=Math.min(e,t);return Math.max(0,Math.ceil(i)-Math.floor(s)-1)}function g(e,t,i){let s=0;const o=function(e,t){const i=1e3;return Math.abs(t*i-e*i)/i}(t,e);var r;return o>i?(e=Math.trunc(e),s=Math.floor(o/(i+1))):(r=o/(i+1),s=Math.floor(1e3*r)/1e3),{startZOrder:e,zOrderStep:s}}function S(e,t,i,s){let o=e.length,r=t;for(let t=e.length-1;t>=-1;t--)if(-1===t||s(e[t])){const s=t;let n=T(r);if(o-1===s)s>=0&&i(e[s],n);else{const t=m(o,s);let a=0;for(;0===a;){const e=g(r,n,t);r=e.startZOrder,a=e.zOrderStep,0===a&&(n-=1e4,0===n&&(n-=1e4))}let l=o-1;for(;l>s;){const t=p(r-a);i(e[l],t),r=t,l--}s>=0&&i(e[s],n)}r=n,o=s}}function v(e,t,i,s){let o=-1,r=t;for(let t=0;t<=e.length;t++)if(t===e.length||s(e[t])){const s=t ;let n=P(r);if(o+1===s)s<=e.length-1&&i(e[s],n);else{const t=m(o,s);let a=0;for(;0===a;){const e=g(r,n,t);r=e.startZOrder,a=e.zOrderStep,0===a&&(n+=1e4,0===n&&(n+=1e4))}let l=o+1;for(;l<=s-1;){const t=p(r+a);i(e[l],t),r=t,l++}s<=e.length-1&&i(e[s],n)}r=n,o=s}}function f(e){!function(e,t,i,s,o,r){let n=null;const a=[];for(const o of e)t(o)?(a.push(o),n=o):(i(o)||s(o))&&a.push(o);a.sort(r),null!==n&&o(n,0);const l=null===n?-1:a.indexOf(n);-1!==l?(S(a.slice(0,l),0,o,i),v(a.slice(l+1),0,o,i)):v(a,0,o,i)}(e,n.isMainSeriesState,n.isStudyState,n.isLineToolState,d,h)}function b(e,t){const i=Math.floor(e/1e4);let s=t.get(i);return void 0===s&&(s=[],t.set(i,s)),s}function y(e,t,i,s,o,r){let n=-1/0,a=1/0,l=-1/0,c=0;const h=new Map;for(let s=0;so(e)-o(t)));let _=T(o(u[0]));const m=P(_),S=g(_,m,u.length+1).zOrderStep;return 0!==S?(u.forEach((e=>{const t=p(_+S);s(e,t),_=t})),p(_+S)):p(m+5e3)}function C(e,t){return y(e,l,c,u,_,t)}function w(e){let t=-1e4;for(const i of e)c(i)&&(t=Math.min(t,i.zorder()-1e4));return 0===t?-1e4:t}function P(e){const t=1e4*Math.ceil(e/1e4);return t===e?t+1e4:t}function T(e){const t=1e4*Math.floor(e/1e4);return t===e?t-1e4:t}function M(e,t,i,s,o,r,n){const l=t.length,{newItems:c,movedItemsStartIndex:h}=i>0?(0,a.moveAfter)(e,t,i-1):(0,a.moveBefore)(e,t,0);let d=!1;for(let t=h;to(e)))?function(e,t,i,s,o,r){let n,a,l=-1,c=-1;0===i?(c=x(e,i+t,s),a=r(e[c])):i+t===e.length?(l=I(e,i-1,s),n=r(e[l])):(l=I(e,i-1,s),n=r(e[l]),c=x(e,i+t,s),a=r(e[c]));if((void 0===n||n<0)&&void 0!==a&&a<=0)S(e.slice(0,c),a,o,s);else if((void 0===a||a>0)&&void 0!==n&&n>=0)v(e.slice(l+1),n,o,s);else{i+t0)&&void 0!==a&&a>=0){c=a;const e=g(c,void 0!==l?l:P(a),t);c=e.startZOrder,_=e.zOrderStep,d=i,u=d+t,h=1}if(0!==_)for(;d!==u;){const t=p(c+h*_);r(e[d],t),c=t,d+=h}else{const t=e.findIndex((e=>o(e)));-1!==t?(S(e.slice(0,t),0,r,s),v(e.slice(t+1),0,r,s)):v(e,0,r,s)}}(c,l,h,o,s,r,n)}function x(e,t,i){for(;t=0&&i(e[t]);)t--;return Math.max(0,t)}function A(e,t,i,s,o,r,n){const a=e.indexOf(i)+1;M(e,t,a,s,o,r,n)}function L(e,t,i,s,o,r,n){const a=e.indexOf(i) ;M(e,t,a,s,o,r,n)}function k(e,t,i){A(e,t,i,r.isSeries,c,u,_)}function E(e,t,i){L(e,t,i,r.isSeries,c,u,_)}},537133:(e,t,i)=>{"use strict";i.d(t,{alertEditorInvocationHandler:()=>a});var s=i(650151),o=i(401580),r=i(862297);class n{constructor(){this._state=new o.WatchedValue(!1)}subscribe(e){this._state.subscribe(e)}unsubscribe(e){this._state.unsubscribe(e)}value(){return this._state.value()}abort(){this._state.setValue(!0)}}const a=new class{constructor(){this._dialogInvocations=new o.WatchedValue(new Map)}getDialogInvocations(){return this._dialogInvocations}isAllowedToInvoke(e){return e.silent||!this._dialogInvocations.value().has(l(e))}lockInvocation(e){if(e.silent)return{unlockInvocation:()=>{}};const t=l(e),i=new n,s=new Map(this._dialogInvocations.value());return s.set(t,i),this._dialogInvocations.setValue(s),{abortSignal:i,unlockInvocation:()=>{const e=new Map(this._dialogInvocations.value());e.delete(t),this._dialogInvocations.setValue(e)}}}};function l(e){var t,i;return"create_alert"===(0,r.getAlertDialogType)(e)?-1:(0,s.ensureDefined)((null===(t=e.alert)||void 0===t?void 0:t.id)||(null===(i=e.facadeAlert)||void 0===i?void 0:i.alertId))}},937994:(e,t,i)=>{"use strict";function s(e=0){return e<1e3?e:e/1e3}function o(e,t){if(e.length>t){const i=/[\W]+$/g,s=e.substring(0,t),o=s.replace(i,"");return`${o.length?o:s.substring(0,t-1)}…`}return e}i.d(t,{cutString:()=>o,ensureDurationInSeconds:()=>s})},547871:(e,t,i)=>{"use strict";i.d(t,{getAlertsChartActionCreators:()=>s});const s=(0,i(895171).default)((async()=>{const{getCreateAlertAction:e}=await i.e(43853).then(i.bind(i,966238)),{getEditAlertOnLineDataSourceAction:t}=await i.e(43853).then(i.bind(i,330359));return{createAlert:e,editAlertOnLineDataSource:t}}))},19039:(e,t,i)=>{"use strict";i.r(t),i.d(t,{getAlertEditorSource:()=>c,hasUsualAlertPlots:()=>m,isFirstAlertPlotUsual:()=>p});var s=i(624444),o=i(440617),r=i(427937),n=i(982217),a=i(62745),l=i(223284);function c(e){return e?(0,o.isSeries)(e)?h(e):(0,r.isStudyStrategy)(e)?{type:2,..._(e)}:(0,r.isStudy)(e)?d(e):null:null}function h(e){return{type:0,...u(e),isLogScale:()=>e.priceScale().isLog(),symbolInfo:()=>e.symbolInfo()}}function d(e){return{type:1,..._(e),isPine:()=>e.isPine()}}function u(e){return{getSymbolString:()=>e.getSymbolString(),interval:()=>e.interval(),isSpread:()=>e.isSpread(),isCryptoCap:()=>{var t;return"CRYPTOCAP"===(null===(t=e.symbolInfo())||void 0===t?void 0:t.exchange)},formatter:()=>function(e){if(!(e instanceof s.PriceFormatter))throw new Error(`Unsupported formatter type: ${e.constructor.name}`);if(e.isFractional())throw new Error(`Unsupported format of ${e.constructor.name}: fractional`);return e}(e.formatter()),title:()=>e.title(n.TitleDisplayTarget.StatusLine)}}function _(e){return{...u(e.series()),title:()=>e.title(n.TitleDisplayTarget.StatusLine),series:()=>h(e.series()),plotStyles:()=>e.metaInfo().styles,hasAlertFunction:()=>{var t;return null!==(t=e.metaInfo().hasAlertFunction)&&void 0!==t&&t},historyCalculationMayChange:()=>{var t ;return null!==(t=e.metaInfo().historyCalculationMayChange)&&void 0!==t&&t},inputs:()=>function(e){const t=["pineId","pineVersion","text"],i=["price","time","bar_time","color","text_area"],s={};for(const[o,r]of Object.entries(e)){if((0,a.isExtendedInput)(r)&&i.includes(r.t))throw new Error(`Unsupported input type ${r.t}`);t.includes(o)||(s[o]=r)}return s}(e.inputs()),plots:()=>(0,l.plotsForAlert)(e.metaInfo(),e.offset.bind(e)),resolvedSymbolInfoBySymbol:t=>e.resolvedSymbolInfoBySymbol(t),isChildStudy:()=>e.isChildStudy(),ownerSource:()=>c(e.ownerSource()),parentSources:()=>e.parentSources().map(d)}}function p(e){if((0,o.isSeries)(e))return!0;if((0,r.isStudy)(e)&&!(0,r.isStudyStrategy)(e)){const t=(0,l.plotsForAlert)(e.metaInfo(),e.offset.bind(e));return!e.metaInfo().hasAlertFunction&&t.every((e=>"alertcondition"!==e.type))}return!1}function m(e){if((0,o.isSeries)(e))return!0;if((0,r.isStudy)(e)&&!(0,r.isStudyStrategy)(e)){return(0,l.plotsForAlert)(e.metaInfo(),e.offset.bind(e)).some((e=>"alertcondition"!==e.type))}return!1}},678183:(e,t,i)=>{"use strict";var s;i.d(t,{AlertStopReason:()=>s}),function(e){e[e.Auto=0]="Auto",e[e.Manual=1]="Manual",e[e.Expired=2]="Expired"}(s||(s={}))},193149:(e,t,i)=>{"use strict";i.d(t,{formatAppendingResolutionString:()=>r});var s=i(731042),o=i(31341);function r(e){const t=(0,s.getTranslatedResolution)(e);return(0,o.isRtl)()?" "+(0,o.forceRTLStr)(" ,"+t):", "+t}},126290:(e,t,i)=>{"use strict";i.d(t,{formatSymbolAndResolution:()=>a});var s=i(59171),o=i.n(s),r=i(919892),n=i(193149);function a(e,t){const i=function(e,t){let i=(0,r.unwrapSimpleSymbol)(e);t||(i=o().shortName(i));return i}(e.symbol,t);if(e.crossInterval)return i;return i+(0,n.formatAppendingResolutionString)(e.resolution)}},992393:(e,t,i)=>{"use strict";i.d(t,{confirmDatasourceRemoving:()=>r});var s=i(444372),o=i(779923);function r(){return new Promise((e=>(0,o.showConfirm)({text:s.t(null,void 0,i(784019)),onConfirm:({dialogClose:t})=>{e(!0),t()},onClose:()=>e(!1)})))}},726778:(e,t,i)=>{"use strict";function s(e){return r().then((t=>t.hasUserAccessToDataSource(e)))}function o(e){return r().then((t=>t.filterAccessibleDataSources(e)))}i.d(t,{filterAccessibleDataSources:()=>o,hasUserAccessToDataSource:()=>s});const r=()=>Promise.all([i.e(68716),i.e(5209),i.e(24028),i.e(59156),i.e(83433),i.e(32679),i.e(95011),i.e(42700),i.e(84266),i.e(11386),i.e(83441)]).then(i.bind(i,827019))},582665:(e,t,i)=>{"use strict";i.d(t,{bulkRemoveConfirmation:()=>l,bulkRemoveInactiveConfirmation:()=>c,bulkRestartConfirmation:()=>a,bulkStopConfirmation:()=>n,selectedRemoveConfirmation:()=>h});var s=i(444372),o=i(591427),r=i(937994);const n=e=>e?{title:s.t(null,void 0,i(742692)),text:s.t(null,void 0,i(528183))}:{title:s.t(null,void 0,i(73016)),text:s.t(null,void 0,i(343860))},a=e=>e?{title:s.t(null,void 0,i(733946)),text:s.t(null,void 0,i(548111))}:{title:s.t(null,void 0,i(639901)),text:s.t(null,void 0,i(530147))},l=e=>e?{title:s.t(null,void 0,i(830930)),text:s.t(null,void 0,i(764123))}:{title:s.t(null,void 0,i(879698)),text:s.t(null,void 0,i(597411)) },c=()=>({title:s.t(null,void 0,i(447537)),text:s.t(null,void 0,i(669387))}),h=e=>{if(1!==e.length)return{title:s.t(null,void 0,i(558519)),text:s.t(null,void 0,i(260920))};const t=e[0],n=(0,o.getAlertDescription)(t);return{title:s.t(null,void 0,i(588511)),text:s.t(null,void 0,i(974834)).format({alert:(0,r.cutString)(n,100)})}}},623551:(e,t,i)=>{"use strict";i.d(t,{AsyncResourceWrapper:()=>s});class s{constructor(e){this._destroyed=!1,this._callbacks=[],this._resource={pendingResource:e},e.then((e=>{for(const t of this._callbacks)t(e);this._resource.resource=e})).finally((()=>{this._callbacks=[]}))}destroy(){this._callbacks=[],this._destroyed=!0}callFunction(e){this._destroyed||(this._resource.resource?e(this._resource.resource):this._callbacks.push(e))}get(){return this._destroyed||!this._resource.resource?null:this._resource.resource}promise(){return this._destroyed?Promise.reject("Resource is destroyed"):this._resource.pendingResource}}},454984:(e,t,i)=>{"use strict";function s(e,t,i="promise rejected by time-out"){return new Promise(((s,o)=>{const r=setTimeout((()=>o(i)),t);e.then((e=>{clearTimeout(r),s(e)})),e.catch((e=>{clearTimeout(r),o(e)}))}))}i.d(t,{makeTimeLimited:()=>s})},868683:(e,t,i)=>{"use strict";function s(){return Promise.all([i.e(62253),i.e(22666),i.e(92108),i.e(9817),i.e(34465),i.e(69121),i.e(88194),i.e(99138),i.e(50690),i.e(62526),i.e(32077)]).then(i.bind(i,880880))}i.d(t,{loadChangeIntervalDialog:()=>s})},230296:(e,t,i)=>{"use strict";i.d(t,{showChangeIntervalDialogAsync:()=>r});var s=i(868683);let o=null;function r(e){const t=o=(0,s.loadChangeIntervalDialog)().then((i=>{t===o&&i.showChangeIntervalDialog(e)}));return t}},277774:(e,t,i)=>{"use strict";function s(e){return Promise.all([i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(92191),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(34465),i.e(69121),i.e(88194),i.e(38669),i.e(5145),i.e(72639),i.e(25190),i.e(10990),i.e(22486),i.e(89434),i.e(24215),i.e(18511),i.e(17301),i.e(43159),i.e(50690),i.e(59255),i.e(62526),i.e(49829),i.e(59703),i.e(57727),i.e(91859)]).then(i.bind(i,533919)).then((t=>t.showGoToDateDialog(e)))}i.d(t,{showGoToDateDialog:()=>s})},703089:(e,t,i)=>{"use strict";async function s(e){(await Promise.all([i.e(29303),i.e(82564),i.e(62253),i.e(92191),i.e(68992),i.e(81643),i.e(33199),i.e(92483),i.e(61298),i.e(967),i.e(36953),i.e(27781),i.e(73151),i.e(61633),i.e(5201),i.e(50690),i.e(23127),i.e(57982),i.e(53490),i.e(32605),i.e(72736),i.e(74785),i.e(26066)]).then(i.bind(i,492418))).renderGoToTradingViewReferralDialog(e)}i.d(t,{showGoToTradingViewReferralDialog:()=>s})},663554:(e,t,i)=>{"use strict";i.d(t,{showDeleteStudyTreeConfirm:()=>r});var s=i(444372),o=i(779923);function r(e){(0,o.showConfirm)({title:s.t(null,void 0,i(638154)),text:s.t(null,void 0,i(452003)),onConfirm:({dialogClose:t})=>{e(),t()}})}},568247:(e,t,i)=>{"use strict";function s(e){ Promise.all([i.e(22309),i.e(62253),i.e(22666),i.e(92108),i.e(5993),i.e(32109),i.e(9817),i.e(4015),i.e(53842),i.e(30006),i.e(38669),i.e(5145),i.e(35649),i.e(25190),i.e(48986),i.e(58056),i.e(67080),i.e(77807),i.e(48450),i.e(4745),i.e(50690),i.e(62526),i.e(44246),i.e(9022),i.e(9374)]).then(i.bind(i,493443)).then((({SymbolInfoDialogImpl:t})=>{t.getInstance().show(e)}))}i.d(t,{showSymbolInfoDialog:()=>s})},625923:e=>{e.exports=''},270068:e=>{e.exports=''},634369:e=>{e.exports=''},748040:e=>{e.exports=''},861814:e=>{e.exports=''},324020:e=>{e.exports=''},421672:e=>{ e.exports=''},553218:e=>{e.exports=''},24165:e=>{e.exports=''},792263:e=>{e.exports=''},262998:e=>{e.exports=''},732140:e=>{e.exports=''},109494:e=>{e.exports=''},792845:e=>{e.exports=''},725230:e=>{e.exports=''},643401:e=>{e.exports=''},212462:e=>{ e.exports=''},845437:e=>{e.exports=''},527409:e=>{e.exports=''},855824:e=>{e.exports=''},539706:e=>{e.exports=''},760823:e=>{e.exports=''},244230:e=>{e.exports=''},428026:e=>{e.exports=''},437924:e=>{ e.exports=''},902872:e=>{e.exports=''},507983:e=>{e.exports=''},139267:e=>{e.exports=''},416911:e=>{e.exports=''},198083:e=>{e.exports=''},472382:e=>{ e.exports=''},706862:e=>{e.exports=''},854190:e=>{e.exports=''},225191:e=>{e.exports=''},593379:e=>{e.exports=''},535149:e=>{e.exports=''},484959:e=>{ e.exports=''},397874:e=>{e.exports=''},677067:e=>{e.exports=''},776351:e=>{e.exports=''},439970:e=>{e.exports=''},789795:e=>{e.exports=''},786559:e=>{ e.exports=''},80465:e=>{e.exports=''}}]);